hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e0a7276db322163764aaf177f470eac5fee77a8
3,152
java
Java
classpath-0.98/java/util/logging/LoggingMXBean.java
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
2
2015-09-08T15:40:04.000Z
2017-02-09T15:19:33.000Z
classpath-0.98/java/util/logging/LoggingMXBean.java
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
null
null
null
classpath-0.98/java/util/logging/LoggingMXBean.java
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
null
null
null
36.651163
75
0.752538
4,420
/* LoggingMxBean.java -- Management interface for logging Copyright (C) 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.util.logging; import java.util.List; /** * This interface represents the management interface for logging. * There is a single logging bean per VM instance, which can be * retrieved via {@link LogManager#getLoggingMXBean()}. * * @since 1.5 */ public interface LoggingMXBean { /** * Return the name of the logging level given the name of * a logger. Returns null if no such logger exists. * @param logger the logger's name * @return the logging level's name, or null */ String getLoggerLevel(String logger); /** * Return a list of all logger names. */ List<String> getLoggerNames(); /** * Return the name of the parent of the indicated logger. * If no such logger exists, returns null. If the logger * is the root logger, returns the empty string. * @param logger the logger's name * @return the name of the logger's parent, or null */ String getParentLoggerName(String logger); /** * Sets the logging level for a particular logger. * * @param logger the name of the logger * @param level the name of the new logging level, or null * @throws IllegalArgumentException if the level is not * recognized, or if the logger does not exist * @throws SecurityException if access is denied; * see {@link Logger#setLevel(Level)} */ void setLoggerLevel(String logger, String level); }
3e0a72f3a338635d05480f89a26e2b43c338c083
4,582
java
Java
aai-service/provider/src/test/java/org/onap/ccsdk/sli/adaptors/aai/EchoRequestTest.java
onap/archive-ccsdk-sli-adaptors
cb066c294b8bc988441d25a222e08d0af4673ac5
[ "Apache-2.0" ]
null
null
null
aai-service/provider/src/test/java/org/onap/ccsdk/sli/adaptors/aai/EchoRequestTest.java
onap/archive-ccsdk-sli-adaptors
cb066c294b8bc988441d25a222e08d0af4673ac5
[ "Apache-2.0" ]
null
null
null
aai-service/provider/src/test/java/org/onap/ccsdk/sli/adaptors/aai/EchoRequestTest.java
onap/archive-ccsdk-sli-adaptors
cb066c294b8bc988441d25a222e08d0af4673ac5
[ "Apache-2.0" ]
null
null
null
33.445255
139
0.56591
4,421
/*- * ============LICENSE_START======================================================= * openECOMP : SDN-C * ================================================================================ * 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.onap.ccsdk.sli.adaptors.aai; import static org.junit.Assert.assertNotNull; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class EchoRequestTest { private static final Logger LOG = LoggerFactory.getLogger(EchoRequestTest.class); private static EchoRequest request; private static AAIService aaiService; @BeforeClass public static void setUp() throws Exception { aaiService = new AAIService( AAIService.class.getResource(AAIService.AAICLIENT_PROPERTIES)); request = new EchoRequest(); LOG.info("\nEchoRequestTest.setUp\n"); } @AfterClass public static void tearDown() throws Exception { request = null; LOG.info("----------------------- EchoRequestTest.tearDown -----------------------"); } @Test public void runGetRequestUrlTest() { LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); URL url; try { url = request.getRequestUrl("GET", null); assertNotNull(url); } catch (UnsupportedEncodingException | MalformedURLException exc) { LOG.error("Failed test", exc); } } @Test public void runToJSONStringTest() { LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); try { String json = request.toJSONString(); assertNotNull(json); } catch (Exception exc) { LOG.error("Failed test", exc); } } @Test public void runGetArgsListTest() { LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); try { String[] args = request.getArgsList(); assertNotNull(args); } catch (Exception exc) { LOG.error("Failed test", exc); } } @Test public void runGetModelTest() { LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); try { Class<? extends AAIDatum> clazz = request.getModelClass(); assertNotNull(clazz); } catch (Exception exc) { LOG.error("Failed test", exc); } } // @Test public void EchoTest() { LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); try { SvcLogicContext ctx = new SvcLogicContext(); QueryStatus resp = null; // (String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) resp = aaiService.query("echo", false, null, "", "aaidata", null, ctx); assert(resp == QueryStatus.SUCCESS); } catch (Throwable e) { LOG.error("Caught exception", e); // fail("Caught exception"); } } }
3e0a732047412937fb19d0530f29fef318c0c700
5,430
java
Java
src/main/java/com/glaf/matrix/combination/web/springmvc/CombinationHistoryController.java
gitee2008/crowd
dde77987c8045a7b819d2917a8f9ff08fcdb5d73
[ "Apache-2.0" ]
2
2017-10-20T12:29:56.000Z
2018-03-04T02:20:38.000Z
src/main/java/com/glaf/matrix/combination/web/springmvc/CombinationHistoryController.java
gitee2008/crowd
dde77987c8045a7b819d2917a8f9ff08fcdb5d73
[ "Apache-2.0" ]
14
2019-11-13T03:15:50.000Z
2022-03-31T18:46:48.000Z
src/main/java/com/glaf/matrix/combination/web/springmvc/CombinationHistoryController.java
gitee2008/crowd
dde77987c8045a7b819d2917a8f9ff08fcdb5d73
[ "Apache-2.0" ]
4
2018-08-14T04:40:43.000Z
2022-03-27T04:43:01.000Z
30.852273
127
0.747145
4,422
package com.glaf.matrix.combination.web.springmvc; import java.io.IOException; import java.util.*; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.bind.annotation.*; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import com.alibaba.fastjson.*; import com.glaf.core.config.ViewProperties; import com.glaf.core.security.*; import com.glaf.core.util.*; import com.glaf.matrix.combination.domain.*; import com.glaf.matrix.combination.query.*; import com.glaf.matrix.combination.service.*; /** * * SpringMVC控制器 * */ @Controller("/sys/combinationHistory") @RequestMapping("/sys/combinationHistory") public class CombinationHistoryController { protected static final Log logger = LogFactory.getLog(CombinationHistoryController.class); protected CombinationHistoryService combinationHistoryService; public CombinationHistoryController() { } @RequestMapping("/edit") public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); CombinationHistory combinationHistory = combinationHistoryService.getCombinationHistory(RequestUtils.getLong(request, "id")); if (combinationHistory != null) { request.setAttribute("combinationHistory", combinationHistory); } String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } String x_view = ViewProperties.getString("combinationHistory.edit"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } return new ModelAndView("/matrix/combinationHistory/edit", modelMap); } @RequestMapping("/json") @ResponseBody public byte[] json(HttpServletRequest request, ModelMap modelMap) throws IOException { LoginContext loginContext = RequestUtils.getLoginContext(request); Map<String, Object> params = RequestUtils.getParameterMap(request); CombinationHistoryQuery query = new CombinationHistoryQuery(); Tools.populate(query, params); query.deleteFlag(0); query.setActorId(loginContext.getActorId()); query.setLoginContext(loginContext); /** * 此处业务逻辑需自行调整 */ if (!loginContext.isSystemAdministrator()) { String actorId = loginContext.getActorId(); query.createBy(actorId); } int start = 0; int limit = 10; String orderName = null; String order = null; int pageNo = ParamUtils.getInt(params, "page"); limit = ParamUtils.getInt(params, "rows"); start = (pageNo - 1) * limit; orderName = ParamUtils.getString(params, "sortName"); order = ParamUtils.getString(params, "sortOrder"); if (start < 0) { start = 0; } if (limit <= 0) { limit = Paging.DEFAULT_PAGE_SIZE; } JSONObject result = new JSONObject(); int total = combinationHistoryService.getCombinationHistoryCountByQueryCriteria(query); if (total > 0) { result.put("total", total); result.put("totalCount", total); result.put("totalRecords", total); result.put("start", start); result.put("startIndex", start); result.put("limit", limit); result.put("pageSize", limit); if (StringUtils.isNotEmpty(orderName)) { query.setSortOrder(orderName); if (StringUtils.equals(order, "desc")) { query.setSortOrder(" desc "); } } List<CombinationHistory> list = combinationHistoryService.getCombinationHistorysByQueryCriteria(start, limit, query); if (list != null && !list.isEmpty()) { JSONArray rowsJSON = new JSONArray(); result.put("rows", rowsJSON); for (CombinationHistory combinationHistory : list) { JSONObject rowJSON = combinationHistory.toJsonObject(); rowJSON.put("id", combinationHistory.getId()); rowJSON.put("rowId", combinationHistory.getId()); rowJSON.put("combinationHistoryId", combinationHistory.getId()); rowJSON.put("startIndex", ++start); rowsJSON.add(rowJSON); } } } else { JSONArray rowsJSON = new JSONArray(); result.put("rows", rowsJSON); result.put("total", total); } return result.toJSONString().getBytes("UTF-8"); } @RequestMapping public ModelAndView list(HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } return new ModelAndView("/matrix/combinationHistory/list", modelMap); } @RequestMapping("/query") public ModelAndView query(HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } String x_view = ViewProperties.getString("combinationHistory.query"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } return new ModelAndView("/matrix/combinationHistory/query", modelMap); } @javax.annotation.Resource(name = "com.glaf.matrix.combination.service.combinationHistoryService") public void setCombinationHistoryService(CombinationHistoryService combinationHistoryService) { this.combinationHistoryService = combinationHistoryService; } }
3e0a7393181221db0be8e726468b98601552f636
448
java
Java
Scratchpad_J/src/common/interfaces/Serverable.java
kasmaslrn/MCOMP_Team_Project_2017-2018
5e20c49c0d7a30083944ddc71ed9d595783a12a5
[ "MIT" ]
1
2019-03-18T14:27:46.000Z
2019-03-18T14:27:46.000Z
Scratchpad_J/src/common/interfaces/Serverable.java
kasmaslrn/MCOMP_Team_Project_2017-2018
5e20c49c0d7a30083944ddc71ed9d595783a12a5
[ "MIT" ]
null
null
null
Scratchpad_J/src/common/interfaces/Serverable.java
kasmaslrn/MCOMP_Team_Project_2017-2018
5e20c49c0d7a30083944ddc71ed9d595783a12a5
[ "MIT" ]
null
null
null
17.92
57
0.660714
4,423
package common.interfaces; import java.rmi.Remote; import java.rmi.RemoteException; /** * * @author Ryan Shoobert (15812407) * */ public interface Serverable extends Remote { /** * * Example method * * @param a The first Addend * @param b The last Addend (number to be added to 'a') * @return the result of adding the two numbers * @throws RemoteException */ int add(int a, int b) throws RemoteException; }
3e0a73ddc60c2dbb9880f4fc144bb3ebe5abcc52
1,738
java
Java
implementations/src/main/java/ru/ifmo/orthant/domCount/NaiveImplementation.java
scala-steward/orthant-search
f0173837d4e3b8277c9da33f2fcb85c22db95a52
[ "MIT" ]
null
null
null
implementations/src/main/java/ru/ifmo/orthant/domCount/NaiveImplementation.java
scala-steward/orthant-search
f0173837d4e3b8277c9da33f2fcb85c22db95a52
[ "MIT" ]
null
null
null
implementations/src/main/java/ru/ifmo/orthant/domCount/NaiveImplementation.java
scala-steward/orthant-search
f0173837d4e3b8277c9da33f2fcb85c22db95a52
[ "MIT" ]
null
null
null
28.966667
98
0.551784
4,424
package ru.ifmo.orthant.domCount; import java.util.Arrays; import ru.ifmo.orthant.util.DominanceHelper; import ru.ifmo.orthant.util.PointWrapper; public final class NaiveImplementation extends DominanceCount { private final PointWrapper[] wrappers; private final int maxDimension; public NaiveImplementation(int maxPoints, int maxDimension) { this.maxDimension = maxDimension; wrappers = new PointWrapper[maxPoints]; for (int i = 0; i < maxPoints; ++i) { wrappers[i] = new PointWrapper(); } } @Override public int getMaximumPoints() { return wrappers.length; } @Override public int getMaximumDimension() { return maxDimension; } @Override public void evaluate(double[][] points, int[] dominanceCounts) { int n = points.length; if (n == 0) { return; } int dimension = points[0].length; for (int i = 0; i < n; ++i) { wrappers[i].point = points[i]; wrappers[i].index = i; wrappers[i].value = 0; wrappers[i].dimension = dimension; } Arrays.sort(wrappers, 0, n); Arrays.fill(dominanceCounts, 0, n, 0); for (int i = 0; i < n; ++i) { PointWrapper good = wrappers[i]; for (int j = i + 1; j < n; ++j) { if (DominanceHelper.strictlyDominates(good.point, wrappers[j].point, dimension)) { ++good.value; } } } for (int i = 0; i < n; ++i) { PointWrapper wrapper = wrappers[i]; dominanceCounts[wrapper.index] = wrapper.value; wrapper.point = null; } } }
3e0a7635fbf6782387eeacfee2bfac00f1eae2ad
2,660
java
Java
cloudata-blocks/src/main/java/com/cloudata/blockstore/iscsi/ScsiServiceActionRequest.java
justinsb/cloudata
076735914b479642f660fd7e56383667316fefde
[ "Apache-2.0" ]
16
2015-04-10T20:29:46.000Z
2021-09-16T06:33:30.000Z
cloudata-blocks/src/main/java/com/cloudata/blockstore/iscsi/ScsiServiceActionRequest.java
justinsb/cloudata
076735914b479642f660fd7e56383667316fefde
[ "Apache-2.0" ]
null
null
null
cloudata-blocks/src/main/java/com/cloudata/blockstore/iscsi/ScsiServiceActionRequest.java
justinsb/cloudata
076735914b479642f660fd7e56383667316fefde
[ "Apache-2.0" ]
5
2015-10-11T11:44:42.000Z
2021-08-12T07:19:46.000Z
24.40367
94
0.630827
4,425
package com.cloudata.blockstore.iscsi; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ListenableFuture; public class ScsiServiceActionRequest extends ScsiCommandRequest { private static final Logger log = LoggerFactory.getLogger(ScsiServiceActionRequest.class); public static final byte SCSI_CODE = (byte) 0x9e; private static final byte READ_CAPACITY_16 = 0x10; final Action action; enum Action { READ_CAPACITY; } public ScsiServiceActionRequest(IscsiSession session, ByteBuf buf) { super(session, buf); assert getByte(CDB_START) == SCSI_CODE; byte actionCode = getByte(CDB_START + 1); switch (actionCode) { case READ_CAPACITY_16: action = Action.READ_CAPACITY; break; default: log.warn("Action code unknown: {}", actionCode); throw new UnsupportedOperationException(); } } @Override public ListenableFuture<Void> start() { ScsiDataInResponse response = new ScsiDataInResponse(); populateResponseFields(session, response); int allocationLength = getInt(CDB_START + 10); switch (action) { case READ_CAPACITY: sendCapacity(session, response); break; default: throw new UnsupportedOperationException(); } int dataLength = response.getDataLength(); response.setResiduals(allocationLength, dataLength); return sendFinal(response); } private void sendCapacity(IscsiSession session, ScsiDataInResponse response) { response.setStatus((byte) 0); int length = 32; ByteBuf data = Unpooled.buffer(length); int blockSize = session.getBlockSize(); long volumeSize = volume.getLength(); long blocks = volumeSize / blockSize; data.writeLong(blocks); data.writeInt(blockSize); // Reserved // P_TYPE PROT_EN data.writeByte(0); // P_I_EXPONENT // LOGICAL BLOCKS PER PHYSICAL BLOCK EXPONENT data.writeByte(0); // TPE // TPRZ // LOWEST ALIGNED LOGICAL BLOCK ADDRESS data.writeByte(0); data.writeByte(0); // Reserved (16) data.writeZero(16); assert data.writerIndex() == length; assert data.refCnt() == 1; response.setData(data, false); } @Override public String toString() { return "ScsiServiceActionRequest [action=" + action + "]"; } }
3e0a76c1fb8b3bf842302ce01dbc12bf10729f86
1,038
java
Java
src/main/java/cn/ccsn/api/SignItem.java
lkkccsncom/lkk-java-sdk
5c06fc96589134e420782043cf3ddb07cea3ef7a
[ "Apache-2.0" ]
1
2019-12-02T08:06:26.000Z
2019-12-02T08:06:26.000Z
src/main/java/cn/ccsn/api/SignItem.java
lkkccsncom/lkk-java-sdk
5c06fc96589134e420782043cf3ddb07cea3ef7a
[ "Apache-2.0" ]
1
2019-12-02T03:36:57.000Z
2019-12-02T03:36:57.000Z
src/main/java/cn/ccsn/api/SignItem.java
lkkccsncom/lkk-java-sdk
5c06fc96589134e420782043cf3ddb07cea3ef7a
[ "Apache-2.0" ]
null
null
null
20.352941
76
0.563584
4,426
package cn.ccsn.api; public class SignItem { /** * 签名源串 */ private String signSourceDate; /** * 签名 */ private String sign; /** * Getter method for property <tt>signSourceDate</tt>. * * @return property value of signSourceDate */ public String getSignSourceDate() { return signSourceDate; } /** * Setter method for property <tt>signSourceDate</tt>. * * @param signSourceDate value to be assigned to property signSourceDate */ public void setSignSourceDate(String signSourceDate) { this.signSourceDate = signSourceDate; } /** * Getter method for property <tt>sign</tt>. * * @return property value of sign */ public String getSign() { return sign; } /** * Setter method for property <tt>sign</tt>. * * @param sign value to be assigned to property sign */ public void setSign(String sign) { this.sign = sign; } }
3e0a76ece389d30a37e1279f25c938d05fa6ba9f
9,128
java
Java
bione-plugin/src/main/java/com/yusys/bione/plugin/rptvalid/web/RptValidLogicController.java
JamesLoveCurry/bione_input
6cb302439369bb364d4bb1de45d70b2b54d94a23
[ "Apache-2.0" ]
null
null
null
bione-plugin/src/main/java/com/yusys/bione/plugin/rptvalid/web/RptValidLogicController.java
JamesLoveCurry/bione_input
6cb302439369bb364d4bb1de45d70b2b54d94a23
[ "Apache-2.0" ]
null
null
null
bione-plugin/src/main/java/com/yusys/bione/plugin/rptvalid/web/RptValidLogicController.java
JamesLoveCurry/bione_input
6cb302439369bb364d4bb1de45d70b2b54d94a23
[ "Apache-2.0" ]
null
null
null
33.218182
113
0.747017
4,427
package com.yusys.bione.plugin.rptvalid.web; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.yusys.bione.comp.common.CommonTreeNode; import com.yusys.bione.comp.entity.page.Pager; import com.yusys.bione.comp.utils.StringUtils2; import com.yusys.bione.frame.base.common.GlobalConstants4frame; import com.yusys.bione.frame.base.web.BaseController; import com.yusys.bione.plugin.rptdim.entity.RptDimTypeInfo; import com.yusys.bione.plugin.rptidx.entity.RptIdxFormulaFunc; import com.yusys.bione.plugin.rptidx.entity.RptIdxFormulaSymbol; import com.yusys.bione.plugin.rptmgr.service.RptMgrBS; import com.yusys.bione.plugin.rptvalid.service.RptValidLogicBS; import com.yusys.bione.plugin.valid.entitiy.RptValidCfgextLogic; import com.yusys.bione.plugin.valid.web.vo.CfgextLogicVO; /** * * <pre> * Title: * Description: * </pre> * * @author efpyi@example.com * @version 1.00.00 * * <pre> * 修改记录 * 修改后版本: 修改人: 修改日期: 修改内容: * </pre> */ @Controller @RequestMapping("/report/frame/rptvalid/logic") public class RptValidLogicController extends BaseController { @Autowired private RptValidLogicBS logicBs; @Autowired public RptMgrBS rptMgrBS; /** * 首页 * * @return */ //显示首页 @RequestMapping(method = RequestMethod.GET) public ModelAndView index(){ ModelMap mm = new ModelMap(); mm.put("treeRootNo", GlobalConstants4frame.TREE_ROOT_NO); mm.put("rootIcon", GlobalConstants4frame.DATA_TREE_NODE_ICON_ROOT); return new ModelAndView("/plugin/rptvalid/rpt-valid-cfg-index", mm); } /** * 跳转到某个报表下的逻辑校验grid * * @param rptId * @return */ //展示右侧grid内容--转向 @RequestMapping(value = "/tab", method = RequestMethod.GET) public ModelAndView logicTab(String indexCatalogNo, String indexNo, String indexVerId, String defSrc) { ModelMap mm = new ModelMap(); if(null==indexCatalogNo){ indexCatalogNo=""; } try { indexCatalogNo=URLDecoder.decode(indexCatalogNo,"UTF-8"); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } if(StringUtils.isNotEmpty(indexCatalogNo)){ mm.put("indexCatalogNo", StringUtils2.javaScriptEncode(indexCatalogNo)); } if(StringUtils.isNotEmpty(indexNo)){ mm.put("indexNo", StringUtils2.javaScriptEncode(indexNo)); } if(StringUtils.isNotEmpty(indexVerId)){ mm.put("indexVerId", StringUtils2.javaScriptEncode(indexVerId)); } if (StringUtils.isNotEmpty(defSrc)) { mm.put("defSrc", StringUtils2.javaScriptEncode(defSrc)); } return new ModelAndView("/plugin/rptvalid/rpt-valid-logic-index", mm); } @RequestMapping(value = "/new", method = RequestMethod.GET) public ModelAndView newEdit(String indexCatalogNo,String indexNo,String indexNm, String defSrc,String checkId) { Map<String, String> map = new HashMap<String, String>(); map.put("indexCatalogNo", StringUtils2.javaScriptEncode(indexCatalogNo)); map.put("indexNo", StringUtils2.javaScriptEncode(indexNo)); map.put("indexNm", StringUtils2.javaScriptEncode(indexNm)); map.put("defSrc", StringUtils2.javaScriptEncode(defSrc)); map.put("checkId", StringUtils2.javaScriptEncode(checkId)); return new ModelAndView("/plugin/rptvalid/rpt-valid-logic-infoFrame", map); } @RequestMapping(value = "/newLogic", method = RequestMethod.GET) public ModelAndView newLogic(String indexCatalogNo,String indexNo,String indexNm,String defSrc,String checkId) { Map<String, String> map = new HashMap<String, String>(); //map = this.logicBs.getRptAndLine(templateId, rptId); map.put("indexCatalogNo", StringUtils2.javaScriptEncode(indexCatalogNo)); map.put("indexNo", StringUtils2.javaScriptEncode(indexNo)); map.put("indexNm", StringUtils2.javaScriptEncode(indexNm)); map.put("defSrc", StringUtils2.javaScriptEncode(defSrc)); map.put("checkId", StringUtils2.javaScriptEncode(checkId)); map.put("treeRootNo", GlobalConstants4frame.TREE_ROOT_NO); map.put("rootIcon", GlobalConstants4frame.DATA_TREE_NODE_ICON_ROOT); return new ModelAndView("/plugin/rptvalid/rpt-valid-cfgext-logic-edit-new",map); } @RequestMapping(value = "/basicInfo", method = RequestMethod.GET) public ModelAndView basicInfo(String checkId) { checkId = StringUtils2.javaScriptEncode(checkId); return new ModelAndView("/plugin/rptvalid/rpt-valid-cfgext-basic-info", "checkId", checkId); } //修改跳转 @RequestMapping(value = "/editDim", method = RequestMethod.GET) public ModelAndView editDim(String checkId,String indexNos) { ModelMap mm = new ModelMap(); mm.put("checkId", StringUtils2.javaScriptEncode(checkId)); mm.put("indexNos", StringUtils2.javaScriptEncode(indexNos)); return new ModelAndView("/plugin/rptvalid/rpt-valid-logic-dim", mm); } //获取维度树 @RequestMapping(value = "/listDimTree.*") @ResponseBody public List<CommonTreeNode> listDimTree(String indexNos,String checkId) { List<RptDimTypeInfo> types = new ArrayList<RptDimTypeInfo>(); if (!StringUtils.isEmpty(indexNos)) { List<String> nos = new ArrayList<String>(); String[] noStrs = StringUtils.split(indexNos, ','); for (String noStrTmp : noStrs) { if(noStrTmp.contains(".")){ noStrTmp = noStrTmp + "."; String compNo[] = StringUtils.split(noStrTmp, "."); noStrTmp = compNo[0]; } if (!nos.contains(noStrTmp)) { nos.add(noStrTmp); } } types = this.logicBs.getDimTypesByNos(nos); } return this.logicBs.listDimTree(types,indexNos,checkId); } //保存选择维度信息 @RequestMapping(value = "/selectDim") @ResponseBody public void selectDim(String checkId,String ids,String dimTypes) { this.logicBs.saveDimInfo(checkId,ids,dimTypes); } @RequestMapping(value = "/list.*", method = RequestMethod.POST) @ResponseBody public Map<String, Object> list(Pager pager, String indexCatalogNo, String indexNo, String indexVerId, String defSrc) { return this.logicBs.list(pager, indexCatalogNo,indexNo,defSrc); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CfgextLogicVO getInfo(@PathVariable("id") String checkId) { return this.logicBs.getInfo(checkId); } @RequestMapping(value = "/{ids}", method = RequestMethod.POST) @ResponseBody public void delete(@PathVariable("ids") String checkIds) { this.logicBs.delete(checkIds); } @RequestMapping(value = "/getFuncAll.*", method = RequestMethod.POST) @ResponseBody public List<RptIdxFormulaFunc> getFuncAll() { return this.logicBs.getFuncAll(); } @RequestMapping(value = "/getFuncTree.*", method = RequestMethod.POST) @ResponseBody public List<CommonTreeNode> getFuncTree() { return this.logicBs.getFuncTree(); } @RequestMapping(value = "/getSymbolAll.*", method = RequestMethod.POST) @ResponseBody public List<RptIdxFormulaSymbol> getSymbolAll() { return this.logicBs.getSymbolAll(); } @RequestMapping(value = "/getSymbolTree.*", method = RequestMethod.POST) @ResponseBody public List<CommonTreeNode> getSymbolTree() { return this.logicBs.getSymbolTree(); } @RequestMapping(method = RequestMethod.POST) public void save(RptValidCfgextLogic logic,String leftFormulaIndex, String rightFormulaIndex) { this.logicBs.saveLogic(logic, leftFormulaIndex, rightFormulaIndex); } @RequestMapping(value = "/replaceExpression", method = RequestMethod.POST) @ResponseBody public Map<String, Object> replaceExpression(String leftExpression, String rightExpression, String expression) { Map<String, Object> map = this.logicBs.replaceExpression( leftExpression, rightExpression, expression); if (map.get("message") == null && map.get("formulaIndx") != null && !StringUtils.isEmpty(map.get("formulaIndex").toString())) { Map<String, Object> result = this.logicBs.checkCycleRef(map.get( "formulaIndex").toString()); if (result == null) { return map; } return result; } return map; } @RequestMapping(value = "/checkCycleRef") @ResponseBody public Map<String, Object> checkCycleRef(String formulaIndex) { return this.logicBs.checkCycleRef(formulaIndex); } @RequestMapping(value = "/validExpression", method = RequestMethod.POST) @ResponseBody public Map<String, String> validExpression(String expression, String expressionDesc) { return this.logicBs.validExpression(expression, expressionDesc); } /** * 判断校验公式名称是否重复 * * @return */ @RequestMapping(value = "/testSameCheckNm", method = RequestMethod.POST) @ResponseBody public Boolean testSameCheckNm(String checkNm,String checkId) { return this.logicBs.testSameCheckNm(checkNm,checkId); } }
3e0a77abfee7b5a4dae96ead2db62051a2fd02d8
345
java
Java
Reversi-JavaFx-Application/reversi-service/src/test/java/hu/unideb/inf/reversi/service/test/suite/ReversiGameBoardSuiteTest.java
gabichelsea/Reversi-JavaFx
af2dfa7fa38a24cb7b0d505e46c7b4e6357de495
[ "MIT" ]
null
null
null
Reversi-JavaFx-Application/reversi-service/src/test/java/hu/unideb/inf/reversi/service/test/suite/ReversiGameBoardSuiteTest.java
gabichelsea/Reversi-JavaFx
af2dfa7fa38a24cb7b0d505e46c7b4e6357de495
[ "MIT" ]
null
null
null
Reversi-JavaFx-Application/reversi-service/src/test/java/hu/unideb/inf/reversi/service/test/suite/ReversiGameBoardSuiteTest.java
gabichelsea/Reversi-JavaFx
af2dfa7fa38a24cb7b0d505e46c7b4e6357de495
[ "MIT" ]
null
null
null
24.642857
69
0.817391
4,428
package hu.unideb.inf.reversi.service.test.suite; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import hu.unideb.inf.reversi.service.test.board.ReversiGameBoardTest; @RunWith(Suite.class) @SuiteClasses({ ReversiGameBoardTest.class }) public class ReversiGameBoardSuiteTest { }
3e0a7a09807599617836fa7b6e347a9e3ada5d22
3,582
java
Java
src/main/java/com/kmv/Converter.java
khosroMakari1989/json-xml-integration
066cc5ecd6e8029ef6d74907aa3522042c93f2a0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/kmv/Converter.java
khosroMakari1989/json-xml-integration
066cc5ecd6e8029ef6d74907aa3522042c93f2a0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/kmv/Converter.java
khosroMakari1989/json-xml-integration
066cc5ecd6e8029ef6d74907aa3522042c93f2a0
[ "Apache-2.0" ]
null
null
null
39
146
0.630156
4,429
package com.kmv; import com.kmv.domain.coah.Content; import com.kmv.domain.coah.Hotel; import com.kmv.domain.giata.Giata; import com.kmv.util.file.FileType; import com.kmv.util.file.FileUtil; import java.net.URL; /** * * This class converts and integreates json&xml files into one JSON file, and * will download the images via URLs which have been put inside the files. * * Coah and Giata are two type of data to be read from files and write them back * as one integrated json file * * @author ychag@example.com */ public class Converter { public static final String BASE_PATH; //The path will be a "data" folder beside the project. static { URL url = Converter.class.getProtectionDomain().getCodeSource().getLocation(); String path = url.getFile(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } path = path.substring(0, path.lastIndexOf("/")); path = path.substring(0, path.lastIndexOf("/")); BASE_PATH = path.concat("/data/"); } public static void main(String[] args) { System.out.println("Please wait..."); convert(); System.out.println("Done!"); } /** * reads data from 6 files of XML and JSON which should be exist in the * folder 'data', then integrates them as one JSON file with the name * 'output.json' */ public static void convert() { Content content = FileUtil.readXmlOrJsonFile(Content.class, "3956-coah.xml", FileType.XML); Content coah2 = FileUtil.readXmlOrJsonFile(Content.class, "162838-coah.xml", FileType.XML); Content coah3 = FileUtil.readXmlOrJsonFile(Content.class, "594608-coah.json", FileType.JSON); Giata giata = FileUtil.readXmlOrJsonFile(Giata.class, "3956-giata.xml", FileType.XML); Giata giata2 = FileUtil.readXmlOrJsonFile(Giata.class, "162838-giata.xml", FileType.XML); Giata giata3 = FileUtil.readXmlOrJsonFile(Giata.class, "411144-giata.xml", FileType.XML); content.getHotels().get(0).setGiata(giata.getGiataData()); coah2.getHotels().get(0).setGiata(giata2.getGiataData()); content.getHotels().add(coah2.getHotels().get(0)); content.getHotels().add(coah3.getHotels().get(0)); Hotel hotel = new Hotel(); hotel.setGiata(giata3.getGiataData()); content.getHotels().add(hotel); uploadContentImages(content); FileUtil.writeObjectToJsonFile(Content.class, content, "output.json"); } /** * downloads images of content asynchronously, using Java 8 parallel streams * * @param content the object which contains data along with image URLs */ private static void uploadContentImages(Content content) { content.getHotels().forEach(hotel -> { if (hotel.getImages() != null) { hotel.getImages().parallelStream().forEach(image -> { FileUtil.downloadImage(image.getUrl(), image.getUrl().substring( image.getUrl().lastIndexOf("=") + 1, image.getUrl().length() - 1), hotel.getGiata_id().toString().concat("-coah")); }); } if (hotel.getGiata() != null && hotel.getGiata().getBildfiles() != null) { hotel.getGiata().getBildfiles().parallelStream().forEach(image -> { FileUtil.downloadImage(image.getUrl(), image.getId(), hotel.getGiata().getGeoData().getGiataID().toString().concat("-giata")); }); } }); } }
3e0a7a43aa7030ac45c195bda50deeaa472818b4
2,947
java
Java
gsl/src/gen/java/org/bytedeco/gsl/gsl_function_fdf.java
viditsethi13/org
e24e8c953db82b269ccc0707b70180535e8454e7
[ "Apache-2.0" ]
2
2019-05-08T18:56:11.000Z
2019-12-05T13:17:42.000Z
gsl/src/gen/java/org/bytedeco/gsl/gsl_function_fdf.java
viditsethi13/org
e24e8c953db82b269ccc0707b70180535e8454e7
[ "Apache-2.0" ]
null
null
null
gsl/src/gen/java/org/bytedeco/gsl/gsl_function_fdf.java
viditsethi13/org
e24e8c953db82b269ccc0707b70180535e8454e7
[ "Apache-2.0" ]
null
null
null
48.311475
160
0.735324
4,430
// Targeted by JavaCPP version 1.5: DO NOT EDIT THIS FILE package org.bytedeco.gsl; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.openblas.global.openblas_nolapack.*; import static org.bytedeco.openblas.global.openblas.*; import static org.bytedeco.gsl.global.gsl.*; /* Definition of an arbitrary function returning two values, r1, r2 */ @Name("gsl_function_fdf_struct") @Properties(inherit = org.bytedeco.gsl.presets.gsl.class) public class gsl_function_fdf extends Pointer { static { Loader.load(); } /** Default native constructor. */ public gsl_function_fdf() { super((Pointer)null); allocate(); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public gsl_function_fdf(long size) { super((Pointer)null); allocateArray(size); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public gsl_function_fdf(Pointer p) { super(p); } private native void allocate(); private native void allocateArray(long size); @Override public gsl_function_fdf position(long position) { return (gsl_function_fdf)super.position(position); } public static class F_double_Pointer extends FunctionPointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public F_double_Pointer(Pointer p) { super(p); } protected F_double_Pointer() { allocate(); } private native void allocate(); public native double call(double x, Pointer params); } public native F_double_Pointer f(); public native gsl_function_fdf f(F_double_Pointer setter); public static class Df_double_Pointer extends FunctionPointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public Df_double_Pointer(Pointer p) { super(p); } protected Df_double_Pointer() { allocate(); } private native void allocate(); public native double call(double x, Pointer params); } public native Df_double_Pointer df(); public native gsl_function_fdf df(Df_double_Pointer setter); public static class Fdf_double_Pointer_DoublePointer_DoublePointer extends FunctionPointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public Fdf_double_Pointer_DoublePointer_DoublePointer(Pointer p) { super(p); } protected Fdf_double_Pointer_DoublePointer_DoublePointer() { allocate(); } private native void allocate(); public native void call(double x, Pointer params, DoublePointer f, DoublePointer df); } public native Fdf_double_Pointer_DoublePointer_DoublePointer fdf(); public native gsl_function_fdf fdf(Fdf_double_Pointer_DoublePointer_DoublePointer setter); public native Pointer params(); public native gsl_function_fdf params(Pointer setter); }
3e0a7a6319ef1f25e63049bbd04e32873b44052d
1,264
java
Java
java/src/uk/co/n3tw0rk/websocketregistration/wrappers/AbstractionThread.java
willitscale/simplejavawebsocket
f02ac845da235cbf553c4484bf5f3932a0e0944d
[ "Apache-2.0" ]
null
null
null
java/src/uk/co/n3tw0rk/websocketregistration/wrappers/AbstractionThread.java
willitscale/simplejavawebsocket
f02ac845da235cbf553c4484bf5f3932a0e0944d
[ "Apache-2.0" ]
null
null
null
java/src/uk/co/n3tw0rk/websocketregistration/wrappers/AbstractionThread.java
willitscale/simplejavawebsocket
f02ac845da235cbf553c4484bf5f3932a0e0944d
[ "Apache-2.0" ]
null
null
null
19.446154
89
0.674842
4,431
package uk.co.n3tw0rk.websocketregistration.wrappers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import uk.co.n3tw0rk.websocketregistration.config.Config; public class AbstractionThread extends Thread { public static DateFormat dateFormat = new SimpleDateFormat("[yyyy/MM/dd HH:mm:ss] :: "); public static String objectName = null; public static Date date = null; public void console( String message ) { if( Config.DEBUGGING_VERBOSE ) { objectName = this.getClass().getName(); date = new Date(); System.out.println( dateFormat.format(date) + objectName + " :: " + message ); } } public void console( short message ) { this.console( "" + message ); } public void console( byte message ) { this.console( "" + message ); } public void console( float message ) { this.console( "" + message ); } public void console( double message ) { this.console( "" + message ); } public void console( long message ) { this.console( "" + message ); } public void console( int message ) { this.console( "" + message ); } public void console( char message ) { this.console( "" + message ); } public void console( boolean message ) { this.console( "" + message ); } }
3e0a7a770f59ea783f71d114241defeccc1e8a29
2,073
java
Java
app/src/main/java/com/example/instagramclone/PostsAdapter.java
Carlosv1232/InstagramClone
6a25549c554392a8c29d9f4ad8f485ef406c3b6f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/instagramclone/PostsAdapter.java
Carlosv1232/InstagramClone
6a25549c554392a8c29d9f4ad8f485ef406c3b6f
[ "Apache-2.0" ]
2
2021-03-01T10:52:20.000Z
2021-03-08T09:22:23.000Z
app/src/main/java/com/example/instagramclone/PostsAdapter.java
Carlosv1232/InstagramClone
6a25549c554392a8c29d9f4ad8f485ef406c3b6f
[ "Apache-2.0" ]
null
null
null
26.576923
92
0.677279
4,432
package com.example.instagramclone; import android.content.Context; import android.text.Layout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.parse.ParseFile; import org.w3c.dom.Text; import java.time.chrono.ThaiBuddhistEra; import java.util.List; public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> { private Context context; private List<Post> posts; public PostsAdapter(Context context, List<Post> posts) { this.posts = posts; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Post post = posts.get(position); holder.bind(post); } @Override public int getItemCount() { return posts.size(); } class ViewHolder extends RecyclerView.ViewHolder{ private TextView tvUsername; private ImageView ivImage; private TextView tvDescription; public ViewHolder(@NonNull View itemView) { super(itemView); tvUsername = itemView.findViewById(R.id.tvUsername); ivImage = itemView.findViewById(R.id.ivImage); tvDescription = itemView.findViewById(R.id.tvDescription); } public void bind(Post post) { tvDescription.setText(post.getDescription()); tvUsername.setText(post.getUser().getUsername()); ParseFile image = post.getImage(); if(image != null){ Glide.with(context).load(post.getImage().getUrl()).into(ivImage); } } } }
3e0a7c34fd300fde5d8691db3b2abb55ad47d811
9,117
java
Java
src/main/java/com/hwq/fundament/JavaDataStructure/avl/AVLTreeDemo.java
Evil-king/Fundament
e3b423a5ea90dec3b0ad4ecc5622c2b0d21aa939
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hwq/fundament/JavaDataStructure/avl/AVLTreeDemo.java
Evil-king/Fundament
e3b423a5ea90dec3b0ad4ecc5622c2b0d21aa939
[ "Apache-2.0" ]
1
2022-01-08T14:50:43.000Z
2022-01-08T14:50:43.000Z
src/main/java/com/hwq/fundament/JavaDataStructure/avl/AVLTreeDemo.java
Evil-king/Fundament
e3b423a5ea90dec3b0ad4ecc5622c2b0d21aa939
[ "Apache-2.0" ]
null
null
null
27.378378
98
0.468246
4,433
package com.hwq.fundament.JavaDataStructure.avl; public class AVLTreeDemo { public static void main(String[] args) { // int[] arr = {4, 3, 6, 5, 7, 8}; int[] arr = {10, 12, 8, 9, 7, 6}; //创建一个AVLTree对象 AVLTree avlTree = new AVLTree(); //添加结点 for (int i = 0; i < arr.length; i++) { avlTree.add(new Node(arr[i])); } //遍历 System.out.println("中序遍历"); avlTree.infixOrder(); System.out.println("在平衡处理~~"); System.out.println("树的高度=" + avlTree.getRoot().height()); System.out.println("树的左子树的高度=" + avlTree.getRoot().leftHeight()); System.out.println("树的右子树的高度=" + avlTree.getRoot().rightHeight()); System.out.println("当前的根节点=" + avlTree.getRoot()); System.out.println("根的节点左子结点=" + avlTree.getRoot().left); System.out.println("根的节点右子结点=" + avlTree.getRoot().right); } } //创建AVL树 class AVLTree { private Node root; public Node getRoot() { return root; } //查找要删除的结点 public Node search(int value) { if (root == null) { return null; } else { return root.search(value); } } //查找父节点 public Node searchParent(int value) { if (root == null) { return null; } else { return root.searchParent(value); } } // //1、返回的以node 为根结点的二叉排序树的最小结点 //2、删除node 为根结点的二叉排序树的最小结点 /** * @param node 传入的结点(当做二叉排序树的根结点) * @return 返回的是 以Node 为根结点的二叉排序树的最小结点的值 */ public int delRightTreeMin(Node node) { Node target = node; //循环的查找左子节点,就会找到最小值 while (target.left != null) { target = target.left; } //这时 target就指向了最小结点 delNode(target.value); //删除最小结点 return target.value; } //删除结点 public void delNode(int value) { if (root == null) { return; } else { //1、需要先找到要删除的结点 targetNode Node targetNode = search(value); //如果没有找到要删除的结点 if (targetNode == null) { return; } //如果我们发现当前这颗二叉排序树只有一个结点 if (root.left == null && root.right == null) { root = null; return; } //去查找targetNode的父节点 Node parent = searchParent(value); //如果要删除的结点是叶子结点 if (targetNode.left == null && targetNode.right == null) { //判断targetNode是父节点的左子结点还是右子结点 if (parent.left != null && parent.left.value == value) { parent.left = null; } else if (parent.right != null && parent.right.value == value) { parent.right = null; } } else if (targetNode.left != null && targetNode.right != null) { //删除有两颗子树的节点 int minValue = delRightTreeMin(targetNode.right); targetNode.value = minValue; } else { //删除只有一颗子树的节点 //如果要删除的结点有左子结点 if (targetNode.left != null) { //如果targetNode是parent的左子结点 if (parent != null) { if (parent.left.value == value) { parent.left = targetNode.left; } else { //targetNode 是parent的右子结点 parent.right = targetNode.left; } } else { root = targetNode.left; } } else { //如果要删除的结点有右子结点 //如果targetNode是parent的右子结点 if (parent != null) { if (parent.left.value == value) { parent.left = targetNode.right; } else {//targetNode 是parent的左子结点 parent.right = targetNode.right; } } else { root = targetNode.right; } } } } } //添加结点的方法 public void add(Node node) { if (root == null) { root = node;//如果node为空则直接让root指向node } else { root.add(node); } } //中序遍历 public void infixOrder() { if (root != null) { root.infixOrder(); } else { System.out.println("二叉排序树为空。不能遍历"); } } } //创建Node结点 class Node { int value; Node left; Node right; public Node(int value) { this.value = value; } //返回左子树的高度 public int leftHeight() { if (left == null) { return 0; } return left.height(); } //返回右子树的高度 public int rightHeight() { if (right == null) { return 0; } return right.height(); } //返回以该结点为根结点的树的高度 public int height() { return Math.max(left == null ? 0 : left.height(), right == null ? 0 : right.height()) + 1; } //左旋转方法 private void leftRotate() { //创建新的结点,以当前根结点的值 Node newNode = new Node(value); //把新节点的左子树设置为当前节点的左子树 newNode.left = left; //把新节点的右子树设置为当前节点的右子树的左子树 newNode.right = right.left; //把当前节点的值换为右子节点的值 value = right.value; //把当前节点的右子树设置成右子树的右子树 right = right.right; //把当前节点的左子树设置为新节点 left = newNode; } //右旋转 private void rightRotate() { //创建新的结点,以当前根结点的值 Node newNode = new Node(value); //把新节点的右子树设置了当前节点的右子树 newNode.right = right; //把新节点的左子树设置为当前节点的左子树的右子树 newNode.left = left.right; //把当前节点的值换成左子节点的值 value = left.value; //把当前节点的左子树设置成左子树的左子树 left = left.left; //把当前节点的右子树设置为新节点 right = newNode; } //查找要删除的结点 /** * @param value 希望删除的结点的值 * @return 如果找到返回该结点,否则返回null */ public Node search(int value) { if (value == this.value) { //说明找到就是该结点 return this; } else if (value < this.value) { //如果查找的值小于当前结点,向左子树递归查找 //如果左子结点为空 if (this.left == null) { return null; } return this.left.search(value); } else { //如果查找的值大于等于当前结点,向左子树递归查找 //如果左子结点为空 if (this.right == null) { return null; } return this.right.search(value); } } //查找要删除结点的父结点 /** * @param value 要找到的结点的值 * @return 返回的是要删除的结点的父节点,如果没有就返回null */ public Node searchParent(int value) { //如果当前结点就是要删除的结点的父节点,就返回 if ((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)) { return this; } else { //如果查找的值小于当前结点的值,并且当前结点的左子结点不为空 if (value < this.value && this.left != null) { return this.left.searchParent(value);//向左子树递归查找 } else if (value >= this.value && this.right != null) { return this.right.searchParent(value);//向右子树递归查找 } else { return null;//没有父节点 } } } @Override public String toString() { return "Node{" + "value=" + value + '}'; } //添加结点的方法 //递归的形式添加结点,注意需要满足二叉排序树的要求 public void add(Node node) { if (node == null) { return; } //判断传入的结点的值,和当前子树的根结点的值关系 if (node.value < this.value) { //如果当前结点左子结点为null if (this.left == null) { this.left = node; } else { //递归的向左子树添加 this.left.add(node); } } else { //添加的结点的值大于 当前结点的值 if (this.right == null) { this.right = node; } else { //递归的向右子树添加 this.right.add(node); } } //当添加完一个结点后,如果:(右子树的高度-左子树的高度的) > 1 左旋转 if (rightHeight() - leftHeight() > 1) { //如果它的右子树的左子树的高度大于它的右子树的右子树的高度 if(right != null && right.leftHeight() > right.rightHeight()) { //先对右子节点进行右旋转 right.rightRotate(); //然后在对当前结点的进行左旋转 leftRotate(); } else { //直接进行左旋转 leftRotate(); } return; } //如果:(左子树的高度-右子树的高度的) > 1 右旋转 if(leftHeight() - rightHeight() > 1){ //如果它的左子树的右子树高度大于它的左子树的高度 if(left != null && left.rightHeight() > left.leftHeight()){ //先对当前结点的左结点(左子树) -> 左旋转 left.leftRotate(); //再对当前结点进行右旋转 rightRotate(); } else { rightRotate(); } } } //中序遍历 public void infixOrder() { if (this.left != null) { this.left.infixOrder(); } System.out.println(this); if (this.right != null) { this.right.infixOrder(); } } }
3e0a7c5f4cc0cde2efc70964166d5b1333dd1d4b
2,575
java
Java
yoko-util/src/test/java/testify/jupiter/annotation/iiop/ConfigureOrb.java
joe-chacko/yoko
72c6fe5e43aaa50de34aaa94f344f593248f96c4
[ "Apache-2.0" ]
null
null
null
yoko-util/src/test/java/testify/jupiter/annotation/iiop/ConfigureOrb.java
joe-chacko/yoko
72c6fe5e43aaa50de34aaa94f344f593248f96c4
[ "Apache-2.0" ]
null
null
null
yoko-util/src/test/java/testify/jupiter/annotation/iiop/ConfigureOrb.java
joe-chacko/yoko
72c6fe5e43aaa50de34aaa94f344f593248f96c4
[ "Apache-2.0" ]
null
null
null
36.785714
107
0.725825
4,434
/* * 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 testify.jupiter.annotation.iiop; import org.apache.yoko.orb.spi.naming.NameServiceInitializer; import org.junit.jupiter.api.extension.ExtendWith; import org.omg.PortableInterceptor.ORBInitializer; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Optional; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static testify.jupiter.annotation.iiop.ConfigureOrb.NameService.NONE; @ExtendWith(OrbExtension.class) @Target({ANNOTATION_TYPE, TYPE}) @Retention(RUNTIME) public @interface ConfigureOrb { enum NameService { NONE, READ_ONLY(NameServiceInitializer.class, NameServiceInitializer.NS_REMOTE_ACCESS_ARG, "readOnly"), READ_WRITE(NameServiceInitializer.class, NameServiceInitializer.NS_REMOTE_ACCESS_ARG, "readWrite"); final String[] args; private final Class<? extends ORBInitializer> initializerClass; NameService() { this.args = new String[0]; this.initializerClass = null; } NameService(Class<? extends ORBInitializer> initializerClass, String...args) { this.args = args; this.initializerClass = initializerClass; } Optional<Class<? extends ORBInitializer>> getInitializerClass() { return Optional.ofNullable(initializerClass); } } String value() default "orb"; String[] args() default ""; String[] props() default ""; NameService nameService() default NONE; @Target({ANNOTATION_TYPE, TYPE}) @Retention(RUNTIME) @interface UseWithOrb { String value() default ".*"; } }
3e0a7e13fc0b6a4050653f32bb58a0534fd2b861
557
java
Java
training_program_2019/core_java/hello-spring/src/main/java/com/trendmicro/ets/hellospring/HelloSpringApplication.java
jeffrey-zhang/learn
7d9d53f955f0424ad4c68f69d5538867e5b7fa98
[ "Apache-2.0" ]
1
2020-10-12T01:23:51.000Z
2020-10-12T01:23:51.000Z
training_program_2019/core_java/hello-spring/src/main/java/com/trendmicro/ets/hellospring/HelloSpringApplication.java
jeffrey-zhang/learn
7d9d53f955f0424ad4c68f69d5538867e5b7fa98
[ "Apache-2.0" ]
1
2020-10-11T10:38:21.000Z
2020-10-11T10:38:21.000Z
training_program_2019/core_java/hello-spring/src/main/java/com/trendmicro/ets/hellospring/HelloSpringApplication.java
jeffrey-zhang/learn
7d9d53f955f0424ad4c68f69d5538867e5b7fa98
[ "Apache-2.0" ]
1
2020-09-07T07:22:54.000Z
2020-09-07T07:22:54.000Z
25.318182
68
0.813285
4,435
package com.trendmicro.ets.hellospring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class HelloSpringApplication { public static void main(String[] args) { SpringApplication.run(HelloSpringApplication.class, args); } @RequestMapping("/hello") public String hello() { return "hello spring!"; } }
3e0a7eba31d5ec3fe86c34e2db8a7bfc9928b035
1,245
java
Java
app/src/main/java/io/agora/openlive/activities/RoleActivity.java
d-samoilov-nlt/OpenLive-Android
dca69b4b92b6f56e89431079825a7412f1634c55
[ "MIT" ]
null
null
null
app/src/main/java/io/agora/openlive/activities/RoleActivity.java
d-samoilov-nlt/OpenLive-Android
dca69b4b92b6f56e89431079825a7412f1634c55
[ "MIT" ]
null
null
null
app/src/main/java/io/agora/openlive/activities/RoleActivity.java
d-samoilov-nlt/OpenLive-Android
dca69b4b92b6f56e89431079825a7412f1634c55
[ "MIT" ]
null
null
null
29.642857
82
0.718072
4,436
package io.agora.openlive.activities; import android.content.Intent; import android.os.Bundle; import android.view.View; import io.agora.openlive.R; import io.agora.rtc.Constants; import static io.agora.rtc.Constants.CLIENT_ROLE_BROADCASTER; import static io.agora.rtc.IRtcEngineEventHandler.ClientRole.CLIENT_ROLE_AUDIENCE; public class RoleActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_role); } public void onJoinAsBroadcaster(View view) { gotoLiveActivity(CLIENT_ROLE_BROADCASTER); } public void onJoinAsAudience(View view) { gotoLiveActivity(Constants.CLIENT_ROLE_AUDIENCE); } private void gotoLiveActivity(int role) { Intent intent = new Intent(getIntent()); if (role == CLIENT_ROLE_AUDIENCE) { intent.setClass(getApplicationContext(), LiveActivity.class); } else if (role == CLIENT_ROLE_BROADCASTER) { intent.setClass(getApplicationContext(), CoachLiveTypeActivity.class); } startActivity(intent); } public void onBackArrowPressed(View view) { finish(); } }
3e0a7f79a4ec99da8abdb4f95519d46d2fdde314
3,407
java
Java
app/src/main/java/com/example/smallweb/FetchUrlMimeType.java
mcshengInworking/SmallWeb
f52e1bfc4e0d4a536b8b641989ca320a5f7d0c23
[ "Apache-2.0" ]
1
2017-10-15T16:27:33.000Z
2017-10-15T16:27:33.000Z
app/src/main/java/com/example/smallweb/FetchUrlMimeType.java
mcshengInworking/SmallWeb
f52e1bfc4e0d4a536b8b641989ca320a5f7d0c23
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/smallweb/FetchUrlMimeType.java
mcshengInworking/SmallWeb
f52e1bfc4e0d4a536b8b641989ca320a5f7d0c23
[ "Apache-2.0" ]
null
null
null
29.626087
80
0.726446
4,437
/* * Copyright 2014 A.C.R. Development */ //取自android源码 package com.example.smallweb; import android.app.DownloadManager; import android.content.Context; import android.net.http.AndroidHttpClient; import android.os.Environment; import android.webkit.MimeTypeMap; import android.webkit.URLUtil; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpHead; import java.io.IOException; /** * This class is used to pull down the http headers of a given URL so that we * can analyse the mimetype and make any correction needed before we give the * URL to the download manager. This operation is needed when the user * long-clicks on a link or image and we don't know the mimetype. If the user * just clicks on the link, we will do the same steps of correcting the mimetype * down in android.os.webkit.LoadListener rather than handling it here. */ public class FetchUrlMimeType extends Thread { private Context mContext; private DownloadManager.Request mRequest; private String mUri; private String mCookies; private String mUserAgent; public FetchUrlMimeType(Context context, DownloadManager.Request request, String uri, String cookies, String userAgent) { mContext = context.getApplicationContext(); mRequest = request; mUri = uri; mCookies = cookies; mUserAgent = userAgent; } @Override public void run() { // User agent is likely to be null, though the AndroidHttpClient // seems ok with that. AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent); HttpHead request = new HttpHead(mUri); if (mCookies != null && mCookies.length() > 0) { request.addHeader("Cookie", mCookies); } HttpResponse response; String mimeType = null; String contentDisposition = null; try { response = client.execute(request); // We could get a redirect here, but if we do lets let // the download manager take care of it, and thus trust that // the server sends the right mimetype if (response.getStatusLine().getStatusCode() == 200) { Header header = response.getFirstHeader("Content-Type"); if (header != null) { mimeType = header.getValue(); final int semicolonIndex = mimeType.indexOf(';'); if (semicolonIndex != -1) { mimeType = mimeType.substring(0, semicolonIndex); } } Header contentDispositionHeader = response .getFirstHeader("Content-Disposition"); if (contentDispositionHeader != null) { contentDisposition = contentDispositionHeader.getValue(); } } } catch (IllegalArgumentException ex) { request.abort(); } catch (IOException ex) { request.abort(); } finally { client.close(); } if (mimeType != null) { if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) { String newMimeType = MimeTypeMap.getSingleton() .getMimeTypeFromExtension( MimeTypeMap.getFileExtensionFromUrl(mUri)); if (newMimeType != null) { mRequest.setMimeType(newMimeType); } } String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType); mRequest.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, filename); } // Start the download DownloadManager manager = (DownloadManager) mContext .getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(mRequest); } }
3e0a7f80dfb96be9d9dbbd0e927a37ed051318ea
717
java
Java
hsweb-web-dao/hsweb-web-dao-api/src/main/java/org/hsweb/web/dao/template/TemplateMapper.java
liaominghua/hsweb
7b0be195a7539f6ca34cba0b4cec8b02e81176d9
[ "Apache-2.0" ]
1
2017-08-16T09:39:18.000Z
2017-08-16T09:39:18.000Z
hsweb-web-dao/hsweb-web-dao-api/src/main/java/org/hsweb/web/dao/template/TemplateMapper.java
liaominghua/hsweb
7b0be195a7539f6ca34cba0b4cec8b02e81176d9
[ "Apache-2.0" ]
null
null
null
hsweb-web-dao/hsweb-web-dao-api/src/main/java/org/hsweb/web/dao/template/TemplateMapper.java
liaominghua/hsweb
7b0be195a7539f6ca34cba0b4cec8b02e81176d9
[ "Apache-2.0" ]
1
2021-03-28T13:07:16.000Z
2021-03-28T13:07:16.000Z
18.868421
73
0.630404
4,438
package org.hsweb.web.dao.template; import org.hsweb.ezorm.core.param.QueryParam; import org.hsweb.web.bean.po.template.Template; import org.hsweb.web.dao.GenericMapper; import java.util.List; /** * Created by zhouhao on 16-5-20. */ public interface TemplateMapper extends GenericMapper<Template, String> { /** * 查看当前正在使用的模板 * * @param name 模板名字 * @return 模板对象 */ Template selectUsing(String name) ; /** * 查询最新版本的模板列表 * * @param param 查询参数 * @return 模板列表 */ List<Template> selectLatestList(QueryParam param) ; /** * 查询最新版本的模板数量 * * @param param 查询参数 * @return 模板数量 */ int countLatestList(QueryParam param) ; }
3e0a7f9db3e2ff041a10ef22bb5e0345a9e00052
5,437
java
Java
app/controllers/LayoutrevisionApplication.java
mdelapenya/generated-crud-play
49b3ad2fdc7c3f2c6da607b4317329c527dc59ba
[ "Apache-2.0" ]
1
2015-03-02T23:18:55.000Z
2015-03-02T23:18:55.000Z
app/controllers/LayoutrevisionApplication.java
mdelapenya/generated-crud-play
49b3ad2fdc7c3f2c6da607b4317329c527dc59ba
[ "Apache-2.0" ]
null
null
null
app/controllers/LayoutrevisionApplication.java
mdelapenya/generated-crud-play
49b3ad2fdc7c3f2c6da607b4317329c527dc59ba
[ "Apache-2.0" ]
null
null
null
32.951515
106
0.780026
4,439
package controllers; import com.avaje.ebean.Ebean; import controllers.layoutrevision.LayoutrevisionFormData; import models.layoutrevision.Layoutrevision; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.html.layoutrevision.layoutrevision; import views.html.layoutrevision.layoutrevisions; import java.util.Date; import java.util.List; /** * @author Manuel de la Peña * @generated */ public class LayoutrevisionApplication extends Controller { public static Result addLayoutrevision() { Form<LayoutrevisionFormData> form = Form.form( LayoutrevisionFormData.class).fill(new Layoutrevision().toFormData()); return ok(layoutrevision.render(form)); } public static Result get(Long id) { Layoutrevision dbLayoutrevision = Layoutrevision.find.byId(id); Form<LayoutrevisionFormData> form = Form.form( LayoutrevisionFormData.class).fill(dbLayoutrevision.toFormData()); return ok(layoutrevision.render(form)); } public static Result all() { List<Layoutrevision> layoutrevisionList = Layoutrevision.find.all(); return ok(layoutrevisions.render(layoutrevisionList)); } public static Result submit() { Form<LayoutrevisionFormData> formData = Form.form( LayoutrevisionFormData.class).bindFromRequest(); String[] postSubmit = request().body().asFormUrlEncoded().get("submit"); if (postSubmit == null || postSubmit.length == 0) { return badRequest("You must provide a valid action"); } else { String action = postSubmit[0]; if ("edit".equals(action)) { return edit(formData); } else if ("delete".equals(action)) { return delete(formData); } else { return badRequest("This action is not allowed"); } } } public static Result edit(Form<LayoutrevisionFormData> formData) { if (formData.hasErrors()) { flash("error", "Please correct errors above."); return addLayoutrevision(); } else { LayoutrevisionFormData layoutrevisionFormData = formData.get(); String id = layoutrevisionFormData.layoutRevisionId; long layoutrevisionId = 0; if (id != null) { layoutrevisionId = Long.valueOf(id); } Layoutrevision layoutrevision; if (layoutrevisionId > 0) { layoutrevision = Layoutrevision.find.byId(layoutrevisionId); layoutrevision.setMvccVersion(Long.valueOf(layoutrevisionFormData.mvccVersion)); layoutrevision.setLayoutRevisionId(Long.valueOf(layoutrevisionFormData.layoutRevisionId)); layoutrevision.setGroupId(Long.valueOf(layoutrevisionFormData.groupId)); layoutrevision.setCompanyId(Long.valueOf(layoutrevisionFormData.companyId)); layoutrevision.setUserId(Long.valueOf(layoutrevisionFormData.userId)); layoutrevision.setUserName(layoutrevisionFormData.userName); layoutrevision.setCreateDate(new Date(layoutrevisionFormData.createDate)); layoutrevision.setModifiedDate(new Date(layoutrevisionFormData.modifiedDate)); layoutrevision.setLayoutSetBranchId(Long.valueOf(layoutrevisionFormData.layoutSetBranchId)); layoutrevision.setLayoutBranchId(Long.valueOf(layoutrevisionFormData.layoutBranchId)); layoutrevision.setParentLayoutRevisionId(Long.valueOf(layoutrevisionFormData.parentLayoutRevisionId)); layoutrevision.setHead(Boolean.valueOf(layoutrevisionFormData.head)); layoutrevision.setMajor(Boolean.valueOf(layoutrevisionFormData.major)); layoutrevision.setPlid(Long.valueOf(layoutrevisionFormData.plid)); layoutrevision.setPrivateLayout(Boolean.valueOf(layoutrevisionFormData.privateLayout)); layoutrevision.setName(layoutrevisionFormData.name); layoutrevision.setTitle(layoutrevisionFormData.title); layoutrevision.setDescription(layoutrevisionFormData.description); layoutrevision.setKeywords(layoutrevisionFormData.keywords); layoutrevision.setRobots(layoutrevisionFormData.robots); layoutrevision.setTypeSettings(layoutrevisionFormData.typeSettings); layoutrevision.setIconImageId(Long.valueOf(layoutrevisionFormData.iconImageId)); layoutrevision.setThemeId(layoutrevisionFormData.themeId); layoutrevision.setColorSchemeId(layoutrevisionFormData.colorSchemeId); layoutrevision.setWapThemeId(layoutrevisionFormData.wapThemeId); layoutrevision.setWapColorSchemeId(layoutrevisionFormData.wapColorSchemeId); layoutrevision.setCss(layoutrevisionFormData.css); layoutrevision.setStatus(Integer.valueOf(layoutrevisionFormData.status)); layoutrevision.setStatusByUserId(Long.valueOf(layoutrevisionFormData.statusByUserId)); layoutrevision.setStatusByUserName(layoutrevisionFormData.statusByUserName); layoutrevision.setStatusDate(new Date(layoutrevisionFormData.statusDate)); } else { layoutrevision = new Layoutrevision(layoutrevisionFormData); } Ebean.save(layoutrevision); flash("success", "Layoutrevision instance created/edited: " + layoutrevision); return all(); } } public static Result delete(Form<LayoutrevisionFormData> formData) { LayoutrevisionFormData layoutrevisionFormData = formData.get(); String id = layoutrevisionFormData.layoutRevisionId; long layoutrevisionId = 0; if (id != null) { layoutrevisionId = Long.valueOf(id); } Layoutrevision layoutrevision; if (layoutrevisionId > 0) { layoutrevision = Layoutrevision.find.byId(layoutrevisionId); Ebean.delete(layoutrevision); } else { flash("error", "Cannot delete Layoutrevision"); } return all(); } }
3e0a7fd9cf8a3402597e483a9c6d6c7944b153c3
3,306
java
Java
cwsfe_website/src/main/java/eu/com/cwsfe/portfolio/PortfolioController.java
RadoslawOsinski/cwsfe_website_1
5e025fcdc68fba7a7b8a7b9f499ca4aa4968bc13
[ "Apache-2.0" ]
null
null
null
cwsfe_website/src/main/java/eu/com/cwsfe/portfolio/PortfolioController.java
RadoslawOsinski/cwsfe_website_1
5e025fcdc68fba7a7b8a7b9f499ca4aa4968bc13
[ "Apache-2.0" ]
null
null
null
cwsfe_website/src/main/java/eu/com/cwsfe/portfolio/PortfolioController.java
RadoslawOsinski/cwsfe_website_1
5e025fcdc68fba7a7b8a7b9f499ca4aa4968bc13
[ "Apache-2.0" ]
null
null
null
45.287671
181
0.709316
4,440
package eu.com.cwsfe.portfolio; import eu.com.cwsfe.GenericController; import eu.com.cwsfe.model.Keyword; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; /** * @author Radoslaw Osinski */ @Controller class PortfolioController extends GenericController { private void setPageMetadata(ModelMap model, Locale locale, String title) { model.addAttribute("headerPageTitle", ResourceBundle.getBundle(CWSFE_RESOURCE_BUNDLE, locale).getString("Portfolio") + " " + title); model.addAttribute("keywords", setPageKeywords(locale, title)); model.addAttribute("additionalCssCode", setAdditionalCss()); } public List<Keyword> setPageKeywords(Locale locale, String title) { List<Keyword> keywords = new ArrayList<>(5); keywords.add(new Keyword(ResourceBundle.getBundle(CWSFE_RESOURCE_BUNDLE, locale).getString("CWSFEPortfolio"))); keywords.add(new Keyword(ResourceBundle.getBundle(CWSFE_RESOURCE_BUNDLE, locale).getString("CWSFEProjects"))); keywords.add(new Keyword(title)); return keywords; } private List<String> setAdditionalCss() { List<String> cssUrl = new ArrayList<>(3); cssUrl.add("/resources-cwsfe/css/tipsy/tipsy-min.css"); cssUrl.add("/resources-cwsfe/css/prettyPhoto/prettyPhoto-min.css"); cssUrl.add("/resources-cwsfe/img/layout/css/pages-min.css"); cssUrl.add("/resources-cwsfe/css/Portfolio-min.css"); return cssUrl; } @RequestMapping(value = "/portfolio", method = RequestMethod.GET) public String listPortfolio(ModelMap model, Locale locale, @RequestParam(value = "currentPage", required = false) Integer currentPage, @RequestParam(value = "newsFolder", required = false) String newsFolder ) { setPageMetadata(model, locale, ""); model.addAttribute("additionalJavaScriptCode", "/resources-cwsfe/js/Portfolio.js"); if (currentPage == null) { currentPage = 0; } model.addAttribute("localeLanguage", locale.getLanguage()); model.addAttribute("currentPage", currentPage); model.addAttribute("newsFolder", newsFolder); return "portfolio/Portfolio"; } @RequestMapping(value = "/portfolio/singleNews/{cmsNewsId}/{cmsNewsI18nContentsId}", method = RequestMethod.GET) public String singleNewsView(ModelMap model, Locale locale, @PathVariable("cmsNewsId") Integer cmsNewsId, @PathVariable("cmsNewsI18nContentsId") Integer cmsNewsI18nContentsId) { setPageMetadata(model, locale, ""); model.addAttribute("additionalJavaScriptCode", "/resources-cwsfe/js/SinglePortfolioEntry.js"); model.addAttribute("cmsNewsId", cmsNewsId); model.addAttribute("cmsNewsI18nContentsId", cmsNewsI18nContentsId); return "portfolio/PortfolioSingleView"; } }
3e0a80950809493956132783bd6a59efbc3b7798
1,005
java
Java
src/main/java/com/turreta/springevent/ComTurretaSpringeventApplication.java
Turreta/Spring-Boot-Publish-and-Consume-Custom-Application-Events
13c678ff16b28ae01490230712bc8feb0eb3bcc7
[ "Apache-2.0" ]
1
2019-11-04T09:19:16.000Z
2019-11-04T09:19:16.000Z
src/main/java/com/turreta/springevent/ComTurretaSpringeventApplication.java
Turreta/Spring-Boot-Publish-and-Consume-Custom-Application-Events
13c678ff16b28ae01490230712bc8feb0eb3bcc7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/turreta/springevent/ComTurretaSpringeventApplication.java
Turreta/Spring-Boot-Publish-and-Consume-Custom-Application-Events
13c678ff16b28ae01490230712bc8feb0eb3bcc7
[ "Apache-2.0" ]
null
null
null
32.419355
99
0.797015
4,441
package com.turreta.springevent; import com.turreta.springevent.events.AppEventA; import com.turreta.springevent.events.AppEventAPublisher; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.concurrent.TimeUnit; @SpringBootApplication public class ComTurretaSpringeventApplication { public static void main(String[] args) throws Exception{ ApplicationContext context = SpringApplication.run(ComTurretaSpringeventApplication.class, args); /** * Alternatively, you can used @Autowired but we are using static main method. */ AppEventAPublisher eventAPublisher = (AppEventAPublisher)context.getBean("appEventAPublisher"); eventAPublisher.publish(new AppEventA(new EventSource())); /** * We wait for a minutes before the application terminates. * For web application, you won't need this at all. */ TimeUnit.MINUTES.sleep(1); } }
3e0a8261ea6a466f2e1925eadb88e754cec9d96b
2,855
java
Java
Exareme-Docker/src/exareme/exareme-master/src/main/java/madgik/exareme/master/engine/executor/remote/operator/OptiqueStreamQueryEndPoint/HttpResponses.java
tchamabe1979/exareme
462983e4feec7808e1fd447d02901502588a8879
[ "MIT" ]
null
null
null
Exareme-Docker/src/exareme/exareme-master/src/main/java/madgik/exareme/master/engine/executor/remote/operator/OptiqueStreamQueryEndPoint/HttpResponses.java
tchamabe1979/exareme
462983e4feec7808e1fd447d02901502588a8879
[ "MIT" ]
null
null
null
Exareme-Docker/src/exareme/exareme-master/src/main/java/madgik/exareme/master/engine/executor/remote/operator/OptiqueStreamQueryEndPoint/HttpResponses.java
tchamabe1979/exareme
462983e4feec7808e1fd447d02901502588a8879
[ "MIT" ]
null
null
null
34.39759
95
0.635377
4,442
package madgik.exareme.master.engine.executor.remote.operator.OptiqueStreamQueryEndPoint; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; /** * @author Christoforos Svingos */ public class HttpResponses { public static void badRequest(final HttpResponse response, String message) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); if (message != null) { StringEntity entity = new StringEntity(message, ContentType.create("text/plain", "UTF-8")); response.setEntity(entity); } } public static void internalServerError(final HttpResponse response, String message) { response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); if (message != null) { StringEntity entity = new StringEntity(message, ContentType.create("text/plain", "UTF-8")); response.setEntity(entity); } } public static void notFound(final HttpResponse response, String message) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); if (message != null) { StringEntity entity = new StringEntity(message, ContentType.create("text/plain", "UTF-8")); response.setEntity(entity); } } public static void conflict(final HttpResponse response, String message) { response.setStatusCode(HttpStatus.SC_CONFLICT); if (message != null) { StringEntity entity = new StringEntity(message, ContentType.create("text/plain", "UTF-8")); response.setEntity(entity); } } public static void toManyRequests(final HttpResponse response, String message) { response.setStatusCode(429); response.setReasonPhrase("Too Many Requests"); if (message != null) { StringEntity entity = new StringEntity(message, ContentType.create("text/plain", "UTF-8")); response.setEntity(entity); } } public static void quickResponse(final HttpResponse response, String message) { response.setStatusCode(HttpStatus.SC_OK); if (message != null) { StringEntity entity = new StringEntity(message, ContentType.create("application/json", "UTF-8")); response.setEntity(entity); } } public static void serviceUnavailable(final HttpResponse response, String message) { response.setStatusCode(HttpStatus.SC_SERVICE_UNAVAILABLE); if (message != null) { StringEntity entity = new StringEntity(message, ContentType.create("text/plain", "UTF-8")); response.setEntity(entity); } } }
3e0a830d357a56562d47ae987d687e3c2b9d5437
22,152
java
Java
hbase-common/src/main/java/org/apache/hadoop/hbase/nio/ByteBuff.java
dasanjan1296/hbase
643548f5f5d6dfd44beb95185eba682979473995
[ "Apache-2.0" ]
4,857
2015-01-02T11:45:14.000Z
2022-03-31T14:00:55.000Z
hbase-common/src/main/java/org/apache/hadoop/hbase/nio/ByteBuff.java
dasanjan1296/hbase
643548f5f5d6dfd44beb95185eba682979473995
[ "Apache-2.0" ]
4,070
2015-05-01T02:52:57.000Z
2022-03-31T23:54:50.000Z
hbase-common/src/main/java/org/apache/hadoop/hbase/nio/ByteBuff.java
dasanjan1296/hbase
643548f5f5d6dfd44beb95185eba682979473995
[ "Apache-2.0" ]
3,611
2015-01-02T11:33:55.000Z
2022-03-31T11:12:19.000Z
35.386581
100
0.689373
4,443
/** * 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.hadoop.hbase.nio; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.util.List; import org.apache.hadoop.hbase.io.ByteBuffAllocator.Recycler; import org.apache.hadoop.hbase.util.ByteBufferUtils; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ObjectIntPair; import org.apache.yetus.audience.InterfaceAudience; import org.apache.hbase.thirdparty.io.netty.util.internal.ObjectUtil; /** * An abstract class that abstracts out as to how the byte buffers are used, either single or * multiple. We have this interface because the java's ByteBuffers cannot be sub-classed. This class * provides APIs similar to the ones provided in java's nio ByteBuffers and allows you to do * positional reads/writes and relative reads and writes on the underlying BB. In addition to it, we * have some additional APIs which helps us in the read path. <br/> * The ByteBuff implement {@link HBaseReferenceCounted} interface which mean need to maintains a * {@link RefCnt} inside, if ensure that the ByteBuff won't be used any more, we must do a * {@link ByteBuff#release()} to recycle its NIO ByteBuffers. when considering the * {@link ByteBuff#duplicate()} or {@link ByteBuff#slice()}, releasing either the duplicated one or * the original one will free its memory, because they share the same NIO ByteBuffers. when you want * to retain the NIO ByteBuffers even if the origin one called {@link ByteBuff#release()}, you can * do like this: * * <pre> * ByteBuff original = ...; * ByteBuff dup = original.duplicate(); * dup.retain(); * original.release(); * // The NIO buffers can still be accessed unless you release the duplicated one * dup.get(...); * dup.release(); * // Both the original and dup can not access the NIO buffers any more. * </pre> */ @InterfaceAudience.Private public abstract class ByteBuff implements HBaseReferenceCounted { private static final String REFERENCE_COUNT_NAME = "ReferenceCount"; private static final int NIO_BUFFER_LIMIT = 64 * 1024; // should not be more than 64KB. protected RefCnt refCnt; /*************************** Methods for reference count **********************************/ protected void checkRefCount() { ObjectUtil.checkPositive(refCnt(), REFERENCE_COUNT_NAME); } public int refCnt() { return refCnt.refCnt(); } @Override public boolean release() { return refCnt.release(); } /******************************* Methods for ByteBuff **************************************/ /** * @return this ByteBuff's current position */ public abstract int position(); /** * Sets this ByteBuff's position to the given value. * @param position * @return this object */ public abstract ByteBuff position(int position); /** * Jumps the current position of this ByteBuff by specified length. * @param len the length to be skipped */ public abstract ByteBuff skip(int len); /** * Jumps back the current position of this ByteBuff by specified length. * @param len the length to move back */ public abstract ByteBuff moveBack(int len); /** * @return the total capacity of this ByteBuff. */ public abstract int capacity(); /** * Returns the limit of this ByteBuff * @return limit of the ByteBuff */ public abstract int limit(); /** * Marks the limit of this ByteBuff. * @param limit * @return This ByteBuff */ public abstract ByteBuff limit(int limit); /** * Rewinds this ByteBuff and the position is set to 0 * @return this object */ public abstract ByteBuff rewind(); /** * Marks the current position of the ByteBuff * @return this object */ public abstract ByteBuff mark(); /** * Returns bytes from current position till length specified, as a single ByteBuffer. When all * these bytes happen to be in a single ByteBuffer, which this object wraps, that ByteBuffer item * as such will be returned. So users are warned not to change the position or limit of this * returned ByteBuffer. The position of the returned byte buffer is at the begin of the required * bytes. When the required bytes happen to span across multiple ByteBuffers, this API will copy * the bytes to a newly created ByteBuffer of required size and return that. * * @param length number of bytes required. * @return bytes from current position till length specified, as a single ByteButter. */ public abstract ByteBuffer asSubByteBuffer(int length); /** * Returns bytes from given offset till length specified, as a single ByteBuffer. When all these * bytes happen to be in a single ByteBuffer, which this object wraps, that ByteBuffer item as * such will be returned (with offset in this ByteBuffer where the bytes starts). So users are * warned not to change the position or limit of this returned ByteBuffer. When the required bytes * happen to span across multiple ByteBuffers, this API will copy the bytes to a newly created * ByteBuffer of required size and return that. * * @param offset the offset in this ByteBuff from where the subBuffer should be created * @param length the length of the subBuffer * @param pair a pair that will have the bytes from the current position till length specified, * as a single ByteBuffer and offset in that Buffer where the bytes starts. * Since this API gets called in a loop we are passing a pair to it which could be created * outside the loop and the method would set the values on the pair that is passed in by * the caller. Thus it avoids more object creations that would happen if the pair that is * returned is created by this method every time. */ public abstract void asSubByteBuffer(int offset, int length, ObjectIntPair<ByteBuffer> pair); /** * Returns the number of elements between the current position and the * limit. * @return the remaining elements in this ByteBuff */ public abstract int remaining(); /** * Returns true if there are elements between the current position and the limt * @return true if there are elements, false otherwise */ public abstract boolean hasRemaining(); /** * Similar to {@link ByteBuffer}.reset(), ensures that this ByteBuff * is reset back to last marked position. * @return This ByteBuff */ public abstract ByteBuff reset(); /** * Returns an ByteBuff which is a sliced version of this ByteBuff. The position, limit and mark * of the new ByteBuff will be independent than that of the original ByteBuff. * The content of the new ByteBuff will start at this ByteBuff's current position * @return a sliced ByteBuff */ public abstract ByteBuff slice(); /** * Returns an ByteBuff which is a duplicate version of this ByteBuff. The * position, limit and mark of the new ByteBuff will be independent than that * of the original ByteBuff. The content of the new ByteBuff will start at * this ByteBuff's current position The position, limit and mark of the new * ByteBuff would be identical to this ByteBuff in terms of values. * * @return a sliced ByteBuff */ public abstract ByteBuff duplicate(); /** * A relative method that returns byte at the current position. Increments the * current position by the size of a byte. * @return the byte at the current position */ public abstract byte get(); /** * Fetches the byte at the given index. Does not change position of the underlying ByteBuffers * @param index * @return the byte at the given index */ public abstract byte get(int index); /** * Fetches the byte at the given offset from current position. Does not change position * of the underlying ByteBuffers. * * @param offset * @return the byte value at the given index. */ public abstract byte getByteAfterPosition(int offset); /** * Writes a byte to this ByteBuff at the current position and increments the position * @param b * @return this object */ public abstract ByteBuff put(byte b); /** * Writes a byte to this ByteBuff at the given index * @param index * @param b * @return this object */ public abstract ByteBuff put(int index, byte b); /** * Copies the specified number of bytes from this ByteBuff's current position to * the byte[]'s offset. Also advances the position of the ByteBuff by the given length. * @param dst * @param offset within the current array * @param length upto which the bytes to be copied */ public abstract void get(byte[] dst, int offset, int length); /** * Copies the specified number of bytes from this ByteBuff's given position to * the byte[]'s offset. The position of the ByteBuff remains in the current position only * @param sourceOffset the offset in this ByteBuff from where the copy should happen * @param dst the byte[] to which the ByteBuff's content is to be copied * @param offset within the current array * @param length upto which the bytes to be copied */ public abstract void get(int sourceOffset, byte[] dst, int offset, int length); /** * Copies the content from this ByteBuff's current position to the byte array and fills it. Also * advances the position of the ByteBuff by the length of the byte[]. * @param dst */ public abstract void get(byte[] dst); /** * Copies from the given byte[] to this ByteBuff * @param src * @param offset the position in the byte array from which the copy should be done * @param length the length upto which the copy should happen * @return this ByteBuff */ public abstract ByteBuff put(byte[] src, int offset, int length); /** * Copies from the given byte[] to this ByteBuff * @param src * @return this ByteBuff */ public abstract ByteBuff put(byte[] src); /** * @return true or false if the underlying BB support hasArray */ public abstract boolean hasArray(); /** * @return the byte[] if the underlying BB has single BB and hasArray true */ public abstract byte[] array(); /** * @return the arrayOffset of the byte[] incase of a single BB backed ByteBuff */ public abstract int arrayOffset(); /** * Returns the short value at the current position. Also advances the position by the size * of short * * @return the short value at the current position */ public abstract short getShort(); /** * Fetches the short value at the given index. Does not change position of the * underlying ByteBuffers. The caller is sure that the index will be after * the current position of this ByteBuff. So even if the current short does not fit in the * current item we can safely move to the next item and fetch the remaining bytes forming * the short * * @param index * @return the short value at the given index */ public abstract short getShort(int index); /** * Fetches the short value at the given offset from current position. Does not change position * of the underlying ByteBuffers. * * @param offset * @return the short value at the given index. */ public abstract short getShortAfterPosition(int offset); /** * Returns the int value at the current position. Also advances the position by the size of int * * @return the int value at the current position */ public abstract int getInt(); /** * Writes an int to this ByteBuff at its current position. Also advances the position * by size of int * @param value Int value to write * @return this object */ public abstract ByteBuff putInt(int value); /** * Fetches the int at the given index. Does not change position of the underlying ByteBuffers. * Even if the current int does not fit in the * current item we can safely move to the next item and fetch the remaining bytes forming * the int * * @param index * @return the int value at the given index */ public abstract int getInt(int index); /** * Fetches the int value at the given offset from current position. Does not change position * of the underlying ByteBuffers. * * @param offset * @return the int value at the given index. */ public abstract int getIntAfterPosition(int offset); /** * Returns the long value at the current position. Also advances the position by the size of long * * @return the long value at the current position */ public abstract long getLong(); /** * Writes a long to this ByteBuff at its current position. * Also advances the position by size of long * @param value Long value to write * @return this object */ public abstract ByteBuff putLong(long value); /** * Fetches the long at the given index. Does not change position of the * underlying ByteBuffers. The caller is sure that the index will be after * the current position of this ByteBuff. So even if the current long does not fit in the * current item we can safely move to the next item and fetch the remaining bytes forming * the long * * @param index * @return the long value at the given index */ public abstract long getLong(int index); /** * Fetches the long value at the given offset from current position. Does not change position * of the underlying ByteBuffers. * * @param offset * @return the long value at the given index. */ public abstract long getLongAfterPosition(int offset); /** * Copy the content from this ByteBuff to a byte[]. * @return byte[] with the copied contents from this ByteBuff. */ public byte[] toBytes() { return toBytes(0, this.limit()); } /** * Copy the content from this ByteBuff to a byte[] based on the given offset and * length * * @param offset * the position from where the copy should start * @param length * the length upto which the copy has to be done * @return byte[] with the copied contents from this ByteBuff. */ public abstract byte[] toBytes(int offset, int length); /** * Copies the content from this ByteBuff to a ByteBuffer * Note : This will advance the position marker of {@code out} but not change the position maker * for this ByteBuff * @param out the ByteBuffer to which the copy has to happen * @param sourceOffset the offset in the ByteBuff from which the elements has * to be copied * @param length the length in this ByteBuff upto which the elements has to be copied */ public abstract void get(ByteBuffer out, int sourceOffset, int length); /** * Copies the contents from the src ByteBuff to this ByteBuff. This will be * absolute positional copying and * won't affect the position of any of the buffers. * @param offset the position in this ByteBuff to which the copy should happen * @param src the src ByteBuff * @param srcOffset the offset in the src ByteBuff from where the elements should be read * @param length the length up to which the copy should happen */ public abstract ByteBuff put(int offset, ByteBuff src, int srcOffset, int length); /** * Reads bytes from the given channel into this ByteBuff * @param channel * @return The number of bytes read from the channel * @throws IOException */ public abstract int read(ReadableByteChannel channel) throws IOException; /** * Reads bytes from FileChannel into this ByteBuff */ public abstract int read(FileChannel channel, long offset) throws IOException; /** * Write this ByteBuff's data into target file */ public abstract int write(FileChannel channel, long offset) throws IOException; /** * function interface for Channel read */ @FunctionalInterface interface ChannelReader { int read(ReadableByteChannel channel, ByteBuffer buf, long offset) throws IOException; } static final ChannelReader CHANNEL_READER = (channel, buf, offset) -> { return channel.read(buf); }; static final ChannelReader FILE_READER = (channel, buf, offset) -> { return ((FileChannel)channel).read(buf, offset); }; // static helper methods public static int read(ReadableByteChannel channel, ByteBuffer buf, long offset, ChannelReader reader) throws IOException { if (buf.remaining() <= NIO_BUFFER_LIMIT) { return reader.read(channel, buf, offset); } int originalLimit = buf.limit(); int initialRemaining = buf.remaining(); int ret = 0; while (buf.remaining() > 0) { try { int ioSize = Math.min(buf.remaining(), NIO_BUFFER_LIMIT); buf.limit(buf.position() + ioSize); offset += ret; ret = reader.read(channel, buf, offset); if (ret < ioSize) { break; } } finally { buf.limit(originalLimit); } } int nBytes = initialRemaining - buf.remaining(); return (nBytes > 0) ? nBytes : ret; } /** * Read integer from ByteBuff coded in 7 bits and increment position. * @return Read integer. */ public static int readCompressedInt(ByteBuff buf) { byte b = buf.get(); if ((b & ByteBufferUtils.NEXT_BIT_MASK) != 0) { return (b & ByteBufferUtils.VALUE_MASK) + (readCompressedInt(buf) << ByteBufferUtils.NEXT_BIT_SHIFT); } return b & ByteBufferUtils.VALUE_MASK; } /** * Compares two ByteBuffs * * @param buf1 the first ByteBuff * @param o1 the offset in the first ByteBuff from where the compare has to happen * @param len1 the length in the first ByteBuff upto which the compare has to happen * @param buf2 the second ByteBuff * @param o2 the offset in the second ByteBuff from where the compare has to happen * @param len2 the length in the second ByteBuff upto which the compare has to happen * @return Positive if buf1 is bigger than buf2, 0 if they are equal, and negative if buf1 is * smaller than buf2. */ public static int compareTo(ByteBuff buf1, int o1, int len1, ByteBuff buf2, int o2, int len2) { if (buf1.hasArray() && buf2.hasArray()) { return Bytes.compareTo(buf1.array(), buf1.arrayOffset() + o1, len1, buf2.array(), buf2.arrayOffset() + o2, len2); } int end1 = o1 + len1; int end2 = o2 + len2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return len1 - len2; } /** * Read long which was written to fitInBytes bytes and increment position. * @param fitInBytes In how many bytes given long is stored. * @return The value of parsed long. */ public static long readLong(ByteBuff in, final int fitInBytes) { long tmpLength = 0; for (int i = 0; i < fitInBytes; ++i) { tmpLength |= (in.get() & 0xffl) << (8l * i); } return tmpLength; } public abstract ByteBuffer[] nioByteBuffers(); @Override public String toString() { return this.getClass().getSimpleName() + "[pos=" + position() + ", lim=" + limit() + ", cap= " + capacity() + "]"; } /********************************* ByteBuff wrapper methods ***********************************/ /** * In theory, the upstream should never construct an ByteBuff by passing an given refCnt, so * please don't use this public method in other place. Make the method public here because the * BucketEntry#wrapAsCacheable in hbase-server module will use its own refCnt and ByteBuffers from * IOEngine to composite an HFileBlock's ByteBuff, we didn't find a better way so keep the public * way here. */ public static ByteBuff wrap(ByteBuffer[] buffers, RefCnt refCnt) { if (buffers == null || buffers.length == 0) { throw new IllegalArgumentException("buffers shouldn't be null or empty"); } return buffers.length == 1 ? new SingleByteBuff(refCnt, buffers[0]) : new MultiByteBuff(refCnt, buffers); } public static ByteBuff wrap(ByteBuffer[] buffers, Recycler recycler) { return wrap(buffers, RefCnt.create(recycler)); } public static ByteBuff wrap(ByteBuffer[] buffers) { return wrap(buffers, RefCnt.create()); } public static ByteBuff wrap(List<ByteBuffer> buffers, Recycler recycler) { return wrap(buffers, RefCnt.create(recycler)); } public static ByteBuff wrap(List<ByteBuffer> buffers) { return wrap(buffers, RefCnt.create()); } public static ByteBuff wrap(ByteBuffer buffer) { return wrap(buffer, RefCnt.create()); } /** * Make this private because we don't want to expose the refCnt related wrap method to upstream. */ private static ByteBuff wrap(List<ByteBuffer> buffers, RefCnt refCnt) { if (buffers == null || buffers.size() == 0) { throw new IllegalArgumentException("buffers shouldn't be null or empty"); } return buffers.size() == 1 ? new SingleByteBuff(refCnt, buffers.get(0)) : new MultiByteBuff(refCnt, buffers.toArray(new ByteBuffer[0])); } /** * Make this private because we don't want to expose the refCnt related wrap method to upstream. */ private static ByteBuff wrap(ByteBuffer buffer, RefCnt refCnt) { return new SingleByteBuff(refCnt, buffer); } }
3e0a833c3f65ff1cd003d6f4256f0d31076d99fc
204
java
Java
references/bcb_chosen_clones/selected#39789#183#187.java
cragkhit/elasticsearch
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
23
2018-10-03T15:02:53.000Z
2021-09-16T11:07:36.000Z
references/bcb_chosen_clones/selected#39789#183#187.java
cragkhit/elasticsearch
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
18
2019-02-10T04:52:54.000Z
2022-01-25T02:14:40.000Z
references/bcb_chosen_clones/selected#39789#183#187.java
cragkhit/Siamese
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
19
2018-11-16T13:39:05.000Z
2021-09-05T23:59:30.000Z
34
66
0.651961
4,444
private Object createInstance() throws Exception { final Constructor c = getConstructor(); final Object newInstance = c.newInstance(new Object[] {}); return newInstance; }
3e0a837044bb6f3fa024b566cc38d56281a72972
10,371
java
Java
main/ejml-ddense/test/org/ejml/dense/row/decomposition/svd/StandardSvdChecks_DDRM.java
BluSteve/ejml
06d7d82d6867c18c5ad769e36edc581a1362af9b
[ "Apache-2.0" ]
429
2015-01-08T20:17:15.000Z
2022-03-15T21:37:37.000Z
main/ejml-ddense/test/org/ejml/dense/row/decomposition/svd/StandardSvdChecks_DDRM.java
BluSteve/ejml
06d7d82d6867c18c5ad769e36edc581a1362af9b
[ "Apache-2.0" ]
126
2015-01-08T14:42:58.000Z
2022-03-11T16:24:21.000Z
main/ejml-ddense/test/org/ejml/dense/row/decomposition/svd/StandardSvdChecks_DDRM.java
BluSteve/ejml
06d7d82d6867c18c5ad769e36edc581a1362af9b
[ "Apache-2.0" ]
114
2015-02-22T05:38:33.000Z
2022-01-22T12:46:26.000Z
32.92381
101
0.645068
4,445
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of Efficient Java Matrix Library (EJML). * * 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.ejml.dense.row.decomposition.svd; import org.ejml.EjmlStandardJUnit; import org.ejml.UtilEjml; import org.ejml.data.DMatrixRMaj; import org.ejml.data.UtilTestMatrix; import org.ejml.dense.row.CommonOps_DDRM; import org.ejml.dense.row.MatrixFeatures_DDRM; import org.ejml.dense.row.RandomMatrices_DDRM; import org.ejml.dense.row.SingularOps_DDRM; import org.ejml.interfaces.decomposition.SingularValueDecomposition; import org.ejml.interfaces.decomposition.SingularValueDecomposition_F64; import org.ejml.simple.SimpleMatrix; import static org.junit.jupiter.api.Assertions.*; public abstract class StandardSvdChecks_DDRM extends EjmlStandardJUnit { public abstract SingularValueDecomposition_F64<DMatrixRMaj> createSvd(); boolean omitVerySmallValues = false; public void allTests() { testSizeZero(); testDecompositionOfTrivial(); testWide(); testTall(); checkGetU_Transpose(); checkGetU_Storage(); checkGetV_Transpose(); checkGetV_Storage(); if( !omitVerySmallValues ) testVerySmallValue(); testZero(); testLargeToSmall(); testIdentity(); testLarger(); testLots(); } public void testSizeZero() { SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertFalse(alg.decompose(new DMatrixRMaj(0, 0))); assertFalse(alg.decompose(new DMatrixRMaj(0,2))); assertFalse(alg.decompose(new DMatrixRMaj(2,0))); } public void testDecompositionOfTrivial() { DMatrixRMaj A = new DMatrixRMaj(3,3, true, 5, 2, 3, 1.5, -2, 8, -3, 4.7, -0.5); SingularValueDecomposition_F64<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); assertEquals(3, SingularOps_DDRM.rank(alg, UtilEjml.EPS)); assertEquals(0, SingularOps_DDRM.nullity(alg, UtilEjml.EPS)); double []w = alg.getSingularValues(); UtilTestMatrix.checkNumFound(1,UtilEjml.TEST_F64_SQ,9.59186,w); UtilTestMatrix.checkNumFound(1,UtilEjml.TEST_F64_SQ,5.18005,w); UtilTestMatrix.checkNumFound(1,UtilEjml.TEST_F64_SQ,4.55558,w); checkComponents(alg,A); } public void testWide() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(5,20,-1,1,rand); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); checkComponents(alg,A); } public void testTall() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(21,5,-1,1,rand); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); checkComponents(alg,A); } public void testZero() { for( int i = 1; i <= 16; i += 5 ) { for( int j = 1; j <= 16; j += 5 ) { DMatrixRMaj A = new DMatrixRMaj(i,j); SingularValueDecomposition_F64<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); int min = Math.min(i,j); assertEquals(min,checkOccurrence(0,alg.getSingularValues(),min),UtilEjml.EPS); checkComponents(alg,A); } } } public void testIdentity() { DMatrixRMaj A = CommonOps_DDRM.identity(6,6); SingularValueDecomposition_F64<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); assertEquals(6,checkOccurrence(1,alg.getSingularValues(),6),UtilEjml.TEST_F64_SQ); checkComponents(alg,A); } public void testLarger() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(200,200,-1,1,rand); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); checkComponents(alg,A); } /** * See if it can handle very small values and not blow up. This can some times * cause a zero to appear unexpectedly and thus a divided by zero. */ public void testVerySmallValue() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(5,5,-1,1,rand); CommonOps_DDRM.scale( Math.pow(UtilEjml.EPS, 12) ,A); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); checkComponents(alg,A); } public void testLots() { SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); for( int i = 1; i < 10; i++ ) { for( int j = 1; j < 10; j++ ) { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(i,j,-1,1,rand); assertTrue(alg.decompose(A)); checkComponents(alg,A); } } } /** * Makes sure transposed flag is correctly handled. */ public void checkGetU_Transpose() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(5, 7, -1, 1, rand); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); DMatrixRMaj U = alg.getU(null,false); DMatrixRMaj Ut = alg.getU(null,true); DMatrixRMaj found = new DMatrixRMaj(U.numCols,U.numRows); CommonOps_DDRM.transpose(U,found); assertTrue( MatrixFeatures_DDRM.isEquals(Ut,found)); } /** * Makes sure the optional storage parameter is handled correctly */ public void checkGetU_Storage() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(5,7,-1,1,rand); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); // test positive cases DMatrixRMaj U = alg.getU(null,false); DMatrixRMaj storage = alg.getU(new DMatrixRMaj(U.numRows,U.numCols),false); assertTrue( MatrixFeatures_DDRM.isEquals(U,storage)); storage = alg.getU(new DMatrixRMaj(10,20),false); assertTrue( MatrixFeatures_DDRM.isEquals(U,storage)); U = alg.getU(null,true); storage = alg.getU(new DMatrixRMaj(U.numRows,U.numCols),true); assertTrue( MatrixFeatures_DDRM.isEquals(U,storage)); storage = alg.getU(new DMatrixRMaj(10,20),true); assertTrue( MatrixFeatures_DDRM.isEquals(U,storage)); } /** * Makes sure transposed flag is correctly handled. */ public void checkGetV_Transpose() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(5,7,-1,1,rand); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); DMatrixRMaj V = alg.getV(null,false); DMatrixRMaj Vt = alg.getV(null,true); DMatrixRMaj found = new DMatrixRMaj(V.numCols,V.numRows); CommonOps_DDRM.transpose(V,found); assertTrue( MatrixFeatures_DDRM.isEquals(Vt,found)); } /** * Makes sure the optional storage parameter is handled correctly */ public void checkGetV_Storage() { DMatrixRMaj A = RandomMatrices_DDRM.rectangle(5,7,-1,1,rand); SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); assertTrue(alg.decompose(A)); // test positive cases DMatrixRMaj V = alg.getV(null, false); DMatrixRMaj storage = alg.getV(new DMatrixRMaj(V.numRows,V.numCols), false); assertTrue(MatrixFeatures_DDRM.isEquals(V, storage)); storage = alg.getV(new DMatrixRMaj(10,20), false); assertTrue(MatrixFeatures_DDRM.isEquals(V, storage)); V = alg.getV(null, true); storage = alg.getV(new DMatrixRMaj(V.numRows,V.numCols), true); assertTrue(MatrixFeatures_DDRM.isEquals(V, storage)); storage = alg.getV(new DMatrixRMaj(10,20), true); assertTrue(MatrixFeatures_DDRM.isEquals(V, storage)); } /** * Makes sure arrays are correctly set when it first computers a larger matrix * then a smaller one. When going from small to large its often forces to declare * new memory, this way it actually uses memory. */ public void testLargeToSmall() { SingularValueDecomposition<DMatrixRMaj> alg = createSvd(); // first the larger one DMatrixRMaj A = RandomMatrices_DDRM.rectangle(10,10,-1,1,rand); assertTrue(alg.decompose(A)); checkComponents(alg,A); // then the smaller one A = RandomMatrices_DDRM.rectangle(5,5,-1,1,rand); assertTrue(alg.decompose(A)); checkComponents(alg,A); } private int checkOccurrence( double check , double[]values , int numSingular ) { int num = 0; for( int i = 0; i < numSingular; i++ ) { if( Math.abs(values[i]-check)<UtilEjml.TEST_F64) num++; } return num; } private void checkComponents(SingularValueDecomposition<DMatrixRMaj> svd , DMatrixRMaj expected ) { SimpleMatrix U = SimpleMatrix.wrap(svd.getU(null,false)); SimpleMatrix Vt = SimpleMatrix.wrap(svd.getV(null,true)); SimpleMatrix W = SimpleMatrix.wrap(svd.getW(null)); assertTrue( !U.hasUncountable() ); assertTrue( !Vt.hasUncountable() ); assertTrue( !W.hasUncountable() ); if( svd.isCompact() ) { assertEquals(W.numCols(),W.numRows()); assertEquals(U.numCols(),W.numRows()); assertEquals(Vt.numRows(),W.numCols()); } else { assertEquals(U.numCols(),W.numRows()); assertEquals(W.numCols(),Vt.numRows()); assertEquals(U.numCols(),U.numRows()); assertEquals(Vt.numCols(),Vt.numRows()); } DMatrixRMaj found = U.mult(W).mult(Vt).getMatrix(); // found.print(); // expected.print(); assertTrue(MatrixFeatures_DDRM.isIdentical(expected,found,UtilEjml.TEST_F64)); } }
3e0a83d3fc129b21968fad5fd5346c2f7aff09aa
2,412
java
Java
springdata/src/main/java/jdblender/sdata/Config.java
rumatoest/db-shaker
616ecf08a12e9800b797db8b788d97b9c7ce452f
[ "MIT" ]
null
null
null
springdata/src/main/java/jdblender/sdata/Config.java
rumatoest/db-shaker
616ecf08a12e9800b797db8b788d97b9c7ce452f
[ "MIT" ]
null
null
null
springdata/src/main/java/jdblender/sdata/Config.java
rumatoest/db-shaker
616ecf08a12e9800b797db8b788d97b9c7ce452f
[ "MIT" ]
null
null
null
38.285714
102
0.753317
4,446
package jdblender.sdata; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.Map; import javax.sql.DataSource; @Configuration @ComponentScan("jdblender.sdata") @EnableJpaRepositories(basePackages = "jdblender.sdata.dao") @EnableTransactionManagement public class Config { @Bean DataSource dataSourceH2() { return H2DS.get(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(false); vendorAdapter.setDatabase(Database.H2); vendorAdapter.setShowSql(false); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("jdblender.sdata.model"); factory.setDataSource(dataSourceH2()); Map<String, Object> props = factory.getJpaPropertyMap(); props.put("hibernate.cache.use_query_cache", "false"); props.put("hibernate.cache.use_second_level_cache", "false"); props.put("hibernate.hbm2ddl.auto", "validate"); //props.put("hibernate.jdbc.batch_size", "100"); //props.put("hibernate.cache.use_second_level_cache", "false"); //props.put("hibernate.order_inserts", "1"); //props.put("hibernate.order_updates", "1"); factory.setJpaPropertyMap(props); return factory; } @Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setDataSource(dataSourceH2()); txManager.setEntityManagerFactory(entityManagerFactory().getObject()); return txManager; } }
3e0a8434ef997b99395d0cce303fae24448e555a
606
java
Java
nl.naturalis.oaipmh.api/src/main/java/nl/naturalis/oaipmh/api/jaxb/ggbn/package-info.java
naturalis/nl.naturalis.oaipmh
2d50ee01ee5e78c7ef65b0ccd1eccadcabfbed53
[ "Apache-2.0" ]
1
2015-12-22T14:08:45.000Z
2015-12-22T14:08:45.000Z
nl.naturalis.oaipmh.api/src/main/java/nl/naturalis/oaipmh/api/jaxb/ggbn/package-info.java
naturalis/nl.naturalis.oaipmh
2d50ee01ee5e78c7ef65b0ccd1eccadcabfbed53
[ "Apache-2.0" ]
null
null
null
nl.naturalis.oaipmh.api/src/main/java/nl/naturalis/oaipmh/api/jaxb/ggbn/package-info.java
naturalis/nl.naturalis.oaipmh
2d50ee01ee5e78c7ef65b0ccd1eccadcabfbed53
[ "Apache-2.0" ]
null
null
null
37.875
91
0.737624
4,447
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) // Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source // schema. // Generated on: 2015.12.16 at 11:48:39 AM CET // /** * JAXB classes for GGBN. Generated by xjc. */ @javax.xml.bind.annotation.XmlSchema(namespace = "http://data.ggbn.org/schemas/ggbn/terms", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package nl.naturalis.oaipmh.api.jaxb.ggbn;
3e0a8450bde6e8a9a13def052086460cb6c2ff40
2,275
java
Java
chapter_001/src/test/java/ru/job4j/map/ProfilesTest.java
Spirka/shustovakv
c0cb61adfc5422c0c1ad8c32da554a95fe4bf7a3
[ "Apache-2.0" ]
null
null
null
chapter_001/src/test/java/ru/job4j/map/ProfilesTest.java
Spirka/shustovakv
c0cb61adfc5422c0c1ad8c32da554a95fe4bf7a3
[ "Apache-2.0" ]
4
2021-12-10T01:10:45.000Z
2022-02-16T00:59:11.000Z
chapter_001/src/test/java/ru/job4j/map/ProfilesTest.java
Spirka/shustovakv
c0cb61adfc5422c0c1ad8c32da554a95fe4bf7a3
[ "Apache-2.0" ]
null
null
null
40.625
83
0.601758
4,448
package ru.job4j.map; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class ProfilesTest { @Test public void whenProfileListConvertedToAddressList() { List<Profile> profiles = Arrays.asList( new Profile(new Address("Saint Petersburg", "Decabristov", 15, 1)), new Profile(new Address("Moskow", "Lenina", 25, 15)), new Profile(new Address("Tihvin", "Lesnaya", 10, 205))); List<Address> expected = Arrays.asList( new Address("Moskow", "Lenina", 25, 15), new Address("Saint Petersburg", "Decabristov", 15, 1), new Address("Tihvin", "Lesnaya", 10, 205)); testProfiles(profiles, expected); } @Test public void whenAddressListOfContainsDuplicates() { List<Profile> profiles = Arrays.asList( new Profile(new Address("Saint Petersburg", "Decabristov", 15, 1)), new Profile(new Address("Moskow", "Lenina", 25, 15)), new Profile(new Address("Moskow", "Lenina", 25, 15))); List<Address> expected = Arrays.asList( new Address("Moskow", "Lenina", 25, 15), new Address("Saint Petersburg", "Decabristov", 15, 1)); testProfiles(profiles, expected); } @Test public void whenAddressListIsSortedByCity() { List<Profile> profiles = Arrays.asList( new Profile(new Address("Saint Petersburg", "Decabristov", 15, 1)), new Profile(new Address("Arkhangelsk", "Lenina", 25, 15)), new Profile(new Address("Novosibirsk", "Popova", 25, 15))); List<Address> expected = Arrays.asList( new Address("Arkhangelsk", "Lenina", 25, 15), new Address("Novosibirsk", "Popova", 25, 15), new Address("Saint Petersburg", "Decabristov", 15, 1)); testProfiles(profiles, expected); } public void testProfiles(List<Profile> profiles, List<Address> expected) { Profiles addressBook = new Profiles(); List<Address> addressList = addressBook.collect(profiles); assertThat(addressList, is(expected)); } }
3e0a85119ee63a4666d1db44cde4b9b733e6528b
2,630
java
Java
conjure-java-jaxrs-client/src/main/java/com/palantir/conjure/java/client/jaxrs/feignimpl/InputStreamDelegateEncoder.java
palantir/http-remoting
c51d041bfb63f80f1389064bfdd7f33cf5525779
[ "Apache-2.0" ]
51
2015-12-26T22:18:18.000Z
2018-09-05T18:14:17.000Z
conjure-java-jaxrs-client/src/main/java/com/palantir/conjure/java/client/jaxrs/feignimpl/InputStreamDelegateEncoder.java
palantir/http-remoting
c51d041bfb63f80f1389064bfdd7f33cf5525779
[ "Apache-2.0" ]
553
2015-12-03T21:52:28.000Z
2018-09-10T14:01:59.000Z
conjure-java-jaxrs-client/src/main/java/com/palantir/conjure/java/client/jaxrs/feignimpl/InputStreamDelegateEncoder.java
palantir/http-remoting
c51d041bfb63f80f1389064bfdd7f33cf5525779
[ "Apache-2.0" ]
87
2015-12-03T21:33:10.000Z
2018-08-30T09:30:12.000Z
39.848485
105
0.71749
4,449
/* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.conjure.java.client.jaxrs.feignimpl; import com.codahale.metrics.Meter; import com.palantir.conjure.java.client.jaxrs.feignimpl.FeignClientMetrics.DangerousBuffering_Direction; import com.palantir.logsafe.Safe; import com.palantir.tritium.metrics.registry.SharedTaggedMetricRegistries; import feign.RequestTemplate; import feign.Util; import feign.codec.EncodeException; import feign.codec.Encoder; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; /** If the body type is an InputStream, write it into the body, otherwise pass to delegate. */ public final class InputStreamDelegateEncoder implements Encoder { private final Encoder delegate; private final Meter dangerousBufferingMeter; public InputStreamDelegateEncoder(Encoder delegate) { this("unknown", delegate); } @SuppressWarnings("deprecation") // No access to a TaggedMetricRegistry without breaking API public InputStreamDelegateEncoder(@Safe String clientNameForLogging, Encoder delegate) { this.delegate = delegate; this.dangerousBufferingMeter = FeignClientMetrics.of(SharedTaggedMetricRegistries.getSingleton()) .dangerousBuffering() .client(clientNameForLogging) .direction(DangerousBuffering_Direction.REQUEST) .build(); } @Override public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { if (bodyType.equals(InputStream.class)) { try { byte[] bytes = Util.toByteArray((InputStream) object); dangerousBufferingMeter.mark(Math.max(1, bytes.length)); template.body(bytes, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } else { delegate.encode(object, bodyType, template); } } }
3e0a85ad1b611d4f1aa864702a3159d389a54f39
1,945
java
Java
hopsworks-api/src/main/java/io/hops/hopsworks/api/admin/dto/ProjectDeletionLog.java
cbotsikas/hopsworks
77e5f0f374dd073ba1ea7a2ff34177b17c15f183
[ "MIT" ]
120
2015-08-31T10:28:19.000Z
2019-11-05T05:31:45.000Z
hopsworks-api/src/main/java/io/hops/hopsworks/api/admin/dto/ProjectDeletionLog.java
cbotsikas/hopsworks
77e5f0f374dd073ba1ea7a2ff34177b17c15f183
[ "MIT" ]
278
2015-04-01T10:03:33.000Z
2019-03-18T09:48:08.000Z
hopsworks-api/src/main/java/io/hops/hopsworks/api/admin/dto/ProjectDeletionLog.java
cbotsikas/hopsworks
77e5f0f374dd073ba1ea7a2ff34177b17c15f183
[ "MIT" ]
54
2015-09-23T14:05:06.000Z
2019-03-31T00:06:33.000Z
34.122807
98
0.748072
4,450
/* * Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved * * 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 io.hops.hopsworks.api.admin.dto; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @XmlRootElement public class ProjectDeletionLog implements Serializable { private static final long serialVersionUID = 1L; private String successLog; private String errorLog; public ProjectDeletionLog() { } public ProjectDeletionLog(String successLog, String errorLog) { this.successLog = successLog; this.errorLog = errorLog; } public String getSuccessLog() { return successLog; } public void setSuccessLog(String successLog) { this.successLog = successLog; } public String getErrorLog() { return errorLog; } public void setErrorLog(String errorLog) { this.errorLog = errorLog; } }
3e0a85d95434902a04113b5ece45e049fe711d37
7,305
java
Java
demo/src/main/java/me/yokeyword/sample/demo_flow/MainActivity.java
Lz-abc/Fragmention
669afe804347e8dade1f012f5432b2b82f7d057b
[ "Apache-2.0" ]
10,723
2016-02-24T01:19:21.000Z
2022-03-31T02:39:30.000Z
demo/src/main/java/me/yokeyword/sample/demo_flow/MainActivity.java
MargaretLHP/Fragmentation
32e75a23550ee4cb2c0d73762f6ed7035c51c923
[ "Apache-2.0" ]
1,246
2016-04-18T14:14:55.000Z
2021-12-20T04:07:09.000Z
demo/src/main/java/me/yokeyword/sample/demo_flow/MainActivity.java
MargaretLHP/Fragmentation
32e75a23550ee4cb2c0d73762f6ed7035c51c923
[ "Apache-2.0" ]
2,483
2016-03-06T16:19:16.000Z
2022-03-31T09:06:57.000Z
37.849741
113
0.629158
4,451
package me.yokeyword.sample.demo_flow; import android.content.Intent; import android.os.Bundle; import com.google.android.material.navigation.NavigationView; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.ActionBarDrawerToggle; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import me.yokeyword.fragmentation.ISupportFragment; import me.yokeyword.fragmentation.SupportFragment; import me.yokeyword.fragmentation.anim.FragmentAnimator; import me.yokeyword.sample.R; import me.yokeyword.sample.demo_flow.base.BaseMainFragment; import me.yokeyword.sample.demo_flow.base.MySupportActivity; import me.yokeyword.sample.demo_flow.base.MySupportFragment; import me.yokeyword.sample.demo_flow.ui.fragment.account.LoginFragment; import me.yokeyword.sample.demo_flow.ui.fragment.discover.DiscoverFragment; import me.yokeyword.sample.demo_flow.ui.fragment.home.HomeFragment; import me.yokeyword.sample.demo_flow.ui.fragment.shop.ShopFragment; /** * 流程式demo tip: 多使用右上角的"查看栈视图" * Created by YoKeyword on 16/1/29. */ public class MainActivity extends MySupportActivity implements NavigationView.OnNavigationItemSelectedListener, BaseMainFragment.OnFragmentOpenDrawerListener , LoginFragment.OnLoginSuccessListener { public static final String TAG = MainActivity.class.getSimpleName(); // 再点一次退出程序时间设置 private static final long WAIT_TIME = 2000L; private long TOUCH_TIME = 0; private DrawerLayout mDrawer; private NavigationView mNavigationView; private TextView mTvName; // NavigationView上的名字 private ImageView mImgNav; // NavigationView上的头像 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MySupportFragment fragment = findFragment(HomeFragment.class); if (fragment == null) { loadRootFragment(R.id.fl_container, HomeFragment.newInstance()); } initView(); } /** * 设置动画,也可以使用setFragmentAnimator()设置 */ @Override public FragmentAnimator onCreateFragmentAnimator() { // 设置默认Fragment动画 默认竖向(和安卓5.0以上的动画相同) return super.onCreateFragmentAnimator(); // 设置横向(和安卓4.x动画相同) // return new DefaultHorizontalAnimator(); // 设置自定义动画 // return new FragmentAnimator(enter,exit,popEnter,popExit); } private void initView() { mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, mDrawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close); // mDrawer.setDrawerListener(toggle); toggle.syncState(); mNavigationView = (NavigationView) findViewById(R.id.nav_view); mNavigationView.setNavigationItemSelectedListener(this); mNavigationView.setCheckedItem(R.id.nav_home); LinearLayout llNavHeader = (LinearLayout) mNavigationView.getHeaderView(0); mTvName = (TextView) llNavHeader.findViewById(R.id.tv_name); mImgNav = (ImageView) llNavHeader.findViewById(R.id.img_nav); llNavHeader.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDrawer.closeDrawer(GravityCompat.START); mDrawer.postDelayed(new Runnable() { @Override public void run() { goLogin(); } }, 250); } }); } @Override public void onBackPressedSupport() { if (mDrawer.isDrawerOpen(GravityCompat.START)) { mDrawer.closeDrawer(GravityCompat.START); } else { ISupportFragment topFragment = getTopFragment(); // 主页的Fragment if (topFragment instanceof BaseMainFragment) { mNavigationView.setCheckedItem(R.id.nav_home); } if (getSupportFragmentManager().getBackStackEntryCount() > 1) { pop(); } else { if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) { finish(); } else { TOUCH_TIME = System.currentTimeMillis(); Toast.makeText(this, R.string.press_again_exit, Toast.LENGTH_SHORT).show(); } } } } /** * 打开抽屉 */ @Override public void onOpenDrawer() { if (!mDrawer.isDrawerOpen(GravityCompat.START)) { mDrawer.openDrawer(GravityCompat.START); } } @Override public boolean onNavigationItemSelected(final MenuItem item) { mDrawer.closeDrawer(GravityCompat.START); mDrawer.postDelayed(new Runnable() { @Override public void run() { int id = item.getItemId(); final ISupportFragment topFragment = getTopFragment(); MySupportFragment myHome = (MySupportFragment) topFragment; if (id == R.id.nav_home) { HomeFragment fragment = findFragment(HomeFragment.class); Bundle newBundle = new Bundle(); newBundle.putString("from", "From:" + topFragment.getClass().getSimpleName()); fragment.putNewBundle(newBundle); myHome.start(fragment, SupportFragment.SINGLETASK); } else if (id == R.id.nav_discover) { DiscoverFragment fragment = findFragment(DiscoverFragment.class); if (fragment == null) { myHome.startWithPopTo(DiscoverFragment.newInstance(), HomeFragment.class, false); } else { // 如果已经在栈内,则以SingleTask模式start myHome.start(fragment, SupportFragment.SINGLETASK); } } else if (id == R.id.nav_shop) { ShopFragment fragment = findFragment(ShopFragment.class); if (fragment == null) { myHome.startWithPopTo(ShopFragment.newInstance(), HomeFragment.class, false); } else { // 如果已经在栈内,则以SingleTask模式start,也可以用popTo // start(fragment, SupportFragment.SINGLETASK); myHome.popTo(ShopFragment.class, false); } } else if (id == R.id.nav_login) { goLogin(); } else if (id == R.id.nav_swipe_back) { startActivity(new Intent(MainActivity.this, SwipeBackSampleActivity.class)); } } }, 300); return true; } private void goLogin() { start(LoginFragment.newInstance()); } @Override public void onLoginSuccess(String account) { mTvName.setText(account); mImgNav.setImageResource(R.drawable.ic_account_circle_white_48dp); Toast.makeText(this, R.string.sign_in_success, Toast.LENGTH_SHORT).show(); } }
3e0a8659be4189d68b483c9106144ef169c814f1
9,333
java
Java
Flat_Earth_UI_Skin/example/core/src/com/ray3k/flatearth/Main.java
raeleus/Ray3K-Skins
d36a5160d369d2894553184fc39bca715321ccc3
[ "MIT" ]
2
2019-09-14T08:23:57.000Z
2020-04-15T08:03:05.000Z
Flat_Earth_UI_Skin/example/core/src/com/ray3k/flatearth/Main.java
raeleus/Ray3K-Skins
d36a5160d369d2894553184fc39bca715321ccc3
[ "MIT" ]
null
null
null
Flat_Earth_UI_Skin/example/core/src/com/ray3k/flatearth/Main.java
raeleus/Ray3K-Skins
d36a5160d369d2894553184fc39bca715321ccc3
[ "MIT" ]
null
null
null
39.379747
164
0.630987
4,452
package com.ray3k.flatearth; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.ButtonGroup; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Slider; import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle; import com.badlogic.gdx.scenes.scene2d.ui.SplitPane; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.Touchpad; import com.badlogic.gdx.scenes.scene2d.ui.Tree; import com.badlogic.gdx.scenes.scene2d.ui.Tree.Node; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Scaling; import com.badlogic.gdx.utils.viewport.ScreenViewport; public class Main extends ApplicationAdapter { private Skin skin; private Stage stage; private final static String longText = "The tale of Flatland tells a story\n" + "about a square living in a two dimensional world. He attempts to\n" + "convince the world of Lineland, a one dimensional world, that there\n" + "is indeed more than just one dimension. He was sadly repudiated.\n" + "He is then visited by Sphere who shows Square the three dimensional\n" + "world of Spaceland. Having his mind blown by this notion, Square\n" + "attempts and fails to convince the people of Flatland that there\n" + "are more than two dimensions. An important takeaway is that Sphere,\n" + "so sure of his three dimensions, denounced any possibility of a\n" + "fourth or fifth dimension. There is more to the world than what\n" + "you can see, people."; @Override public void create() { stage = new Stage(new ScreenViewport()); Gdx.input.setInputProcessor(stage); skin = new Skin(Gdx.files.internal("flat-earth-ui.json")); ProgressBarStyle progressBarStyle = skin.get("fancy", ProgressBarStyle.class); TiledDrawable tiledDrawable = skin.getTiledDrawable("slider-fancy-knob").tint(skin.getColor("selection")); tiledDrawable.setMinWidth(0); progressBarStyle.knobBefore = tiledDrawable; SliderStyle sliderStyle = skin.get("fancy", SliderStyle.class); sliderStyle.knobBefore = tiledDrawable; Window window = new Window("Flat Earth UI", skin); window.setSize(700.0f, 700.0f); window.setPosition(Gdx.graphics.getWidth() / 2.0f, Gdx.graphics.getHeight() / 2.0f, Align.center); window.getTitleTable().getCells().first().padLeft(15.0f); stage.addActor(window); Button button = new Button(skin, "close"); window.getTitleTable().add(button).padRight(15.0f); Label label = new Label("Flat Earth UI", skin, "title"); window.add(label).colspan(2).padBottom(10.0f).expandX(); window.row(); Table rowTable = new Table(); window.add(rowTable).growX().colspan(2); Table table = new Table(); table.defaults().growX(); rowTable.add(table).width(200.0f).right(); TextButton textButton = new TextButton("Start", skin); table.add(textButton); table.row(); textButton = new TextButton("Config", skin); table.add(textButton).padTop(10.0f); table.row(); textButton = new TextButton("Quit", skin); table.add(textButton).padTop(10.0f); Image image = new Image(skin, "earth"); image.setScaling(Scaling.none); rowTable.add(image).left().padLeft(15.0f); window.row(); table = new Table(); window.add(table).colspan(2).padTop(20.0f); label = new Label("Volume:", skin); table.add(label); final Slider slider = new Slider(0, 100, 1, false, skin, "fancy"); slider.setValue(50.0f); table.add(slider).width(261); table.row(); label = new Label("Progress:", skin); table.add(label); final ProgressBar progressBar = new ProgressBar(0, 100, 1, false, skin, "fancy"); progressBar.setValue(50.0f); table.add(progressBar).width(261); slider.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { progressBar.setValue(slider.getValue()); } }); window.row(); table = new Table(); table.defaults().expandX().left(); window.add(table).colspan(2).padTop(20.0f); ButtonGroup buttonGroup = new ButtonGroup(); ImageTextButton imageTextButton = new ImageTextButton("Flat", skin, "radio"); buttonGroup.add(imageTextButton); table.add(imageTextButton); imageTextButton = new ImageTextButton("Horizon", skin, "check"); imageTextButton.setChecked(true); table.add(imageTextButton).padLeft(20.0f); table.row(); imageTextButton = new ImageTextButton("Round", skin, "radio"); buttonGroup.add(imageTextButton); table.add(imageTextButton); imageTextButton = new ImageTextButton("Satellites", skin, "check"); imageTextButton.setChecked(true); table.add(imageTextButton).padLeft(20.0f); table.row(); imageTextButton = new ImageTextButton("Cuboid", skin, "radio"); buttonGroup.add(imageTextButton); table.add(imageTextButton); imageTextButton = new ImageTextButton("Planes", skin, "check"); imageTextButton.setChecked(true); table.add(imageTextButton).padLeft(20.0f); window.row(); rowTable = new Table(); window.add(rowTable).colspan(2); SelectBox selectBox = new SelectBox(skin); selectBox.setItems("Rhetoric", "Hyperbole", "Colorful Prose", "Banality", "Celebrity", "Contrarianism", "Arrogance", "Ignorance", "Denialism", "Solipsism"); selectBox.setMaxListCount(4); rowTable.add(selectBox).padTop(20.0f); table = new Table(); table.add(new Label(longText, skin)); ScrollPane scrollPane = new ScrollPane(table, skin); scrollPane.setFadeScrollBars(false); table = new Table(); Touchpad touchpad = new Touchpad(0, skin); table.add(touchpad); SplitPane splitPane = new SplitPane(table, scrollPane, false, skin); splitPane.setSplitAmount(.45f); rowTable.add(splitPane).padTop(20.0f).width(250.0f).padLeft(50.0f); window.row(); rowTable = new Table(); window.add(rowTable).colspan(2).growY(); Tree tree = new Tree(skin); Node parent = new Tree.Node(new Label("Global", skin)); tree.add(parent); rowTable.add(tree).padTop(20.0f); Node child = new Tree.Node(new Label("Conspiracy", skin)); parent.add(child); parent = child; child = new Tree.Node(new Label("Spanning", skin)); parent.add(child); child = new Tree.Node(new Label("Thousands of Years", skin)); parent.add(child); child = new Tree.Node(new Label("Yet no whistleblowers?", skin)); parent.add(child); tree.expandAll(); table = new Table(); rowTable.add(table).padTop(20.0f).padLeft(50.0f); table.add(new Label("User", skin)); TextField textField = new TextField("", skin); table.add(textField).padLeft(10.0f); table.row(); table.add(new Label("Pass", skin)); textField = new TextField("", skin); textField.setPasswordCharacter('•'); textField.setPasswordMode(true); table.add(textField).padLeft(10.0f).padTop(5.0f); } @Override public void render() { Gdx.gl.glClearColor(128.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getRawDeltaTime()); stage.draw(); } @Override public void resize(int width, int height) { super.resize(width, height); stage.getViewport().update(width, height, true); } @Override public void dispose() { stage.dispose(); skin.dispose(); } }
3e0a86629ad73e6a633deb35a9fec5c0b0e3bf1c
106
java
Java
src/main/java/dev/xethh/libs/toolkits/commons/OSDetecting/OS.java
O7UNp/libs-toolkit-commons
02f6363f2a0fdf31160f118ba5b2c038be6b928d
[ "Apache-2.0" ]
null
null
null
src/main/java/dev/xethh/libs/toolkits/commons/OSDetecting/OS.java
O7UNp/libs-toolkit-commons
02f6363f2a0fdf31160f118ba5b2c038be6b928d
[ "Apache-2.0" ]
null
null
null
src/main/java/dev/xethh/libs/toolkits/commons/OSDetecting/OS.java
O7UNp/libs-toolkit-commons
02f6363f2a0fdf31160f118ba5b2c038be6b928d
[ "Apache-2.0" ]
null
null
null
17.666667
52
0.745283
4,453
package dev.xethh.libs.toolkits.commons.OSDetecting; public enum OS{ Windows, Linux, Mac, Solaris }
3e0a870d0085f7b0dc997e12d1ae4cdd3ac49f49
907
java
Java
test/org/traccar/protocol/MeitrackProtocolEncoderTest.java
e-green/gpssystem
46bef508e7a85b13bf5ae8cc40af1cb8e11c9a7d
[ "Apache-2.0" ]
1
2019-10-09T09:14:09.000Z
2019-10-09T09:14:09.000Z
test/org/traccar/protocol/MeitrackProtocolEncoderTest.java
e-green/gpssystem
46bef508e7a85b13bf5ae8cc40af1cb8e11c9a7d
[ "Apache-2.0" ]
null
null
null
test/org/traccar/protocol/MeitrackProtocolEncoderTest.java
e-green/gpssystem
46bef508e7a85b13bf5ae8cc40af1cb8e11c9a7d
[ "Apache-2.0" ]
1
2021-01-16T08:07:26.000Z
2021-01-16T08:07:26.000Z
29.258065
119
0.714443
4,454
package org.traccar.protocol; import org.junit.Assert; import org.junit.Test; import org.traccar.ProtocolTest; import org.traccar.model.Command; public class MeitrackProtocolEncoderTest extends ProtocolTest { @Test public void testEncode() throws Exception { MeitrackProtocolEncoder encoder = new MeitrackProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_POSITION_SINGLE); Assert.assertEquals("@@Q25,123456789012345,A10*68\r\n", encoder.encodeCommand(command)); command.setDeviceId(1); command.setType(Command.TYPE_SEND_SMS); command.set(Command.KEY_PHONE_NUMBER, "15360853789"); command.set(Command.KEY_MESSAGE, "Meitrack"); Assert.assertEquals("@@f48,123456789012345,C02,0,15360853789,Meitrack*B0\r\n", encoder.encodeCommand(command)); } }
3e0a879888e2e6d13be25e1eccb5f361fcc23709
376
java
Java
mobile_app1/module1183/src/main/java/module1183packageJava0/Foo661.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module1183/src/main/java/module1183packageJava0/Foo661.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module1183/src/main/java/module1183packageJava0/Foo661.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
11.75
47
0.577128
4,455
package module1183packageJava0; import java.lang.Integer; public class Foo661 { Integer int0; public void foo0() { new module1183packageJava0.Foo660().foo5(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } }
3e0a88069c411e02832ef82c96bb886c4738cb7c
5,583
java
Java
app/src/main/java/me/littlecheesecake/cropimagelayout/crop.java
mseslami/facedetection
de1b9ed9a28b76e56268576a79cd133559d22182
[ "MIT" ]
null
null
null
app/src/main/java/me/littlecheesecake/cropimagelayout/crop.java
mseslami/facedetection
de1b9ed9a28b76e56268576a79cd133559d22182
[ "MIT" ]
null
null
null
app/src/main/java/me/littlecheesecake/cropimagelayout/crop.java
mseslami/facedetection
de1b9ed9a28b76e56268576a79cd133559d22182
[ "MIT" ]
null
null
null
31.721591
226
0.612037
4,456
package me.littlecheesecake.cropimagelayout; import android.app.Activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import me.littlecheesecake.croplayout.EditPhotoView; import me.littlecheesecake.croplayout.EditableImage; import me.littlecheesecake.croplayout.handler.OnBoxChangedListener; import me.littlecheesecake.croplayout.model.ScalableBox; import static me.littlecheesecake.cropimagelayout.Mainfragment.responsephoto; import static me.littlecheesecake.cropimagelayout.Mainfragment.bmp32; //import static me.littlecheesecake.cropimagelayout.MainActivity.responsephoto; //import static me.littlecheesecake.cropimagelayout.MainActivity.bmp32; /** * A simple {@link Fragment} subclass. */ public class crop extends Fragment { boolean nextfaceb; static public int x1, x2, y1, y2; static ScalableBox box1, box2, box3; static List<ScalableBox> boxes; static EditableImage image; int facecount; EditPhotoView imageView; public crop() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_crop, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); imageView = (EditPhotoView) getView().findViewById(R.id.editable_image); final TextView boxText = (TextView) getView().findViewById(R.id.box_text); final TextView boxText2 = (TextView) getView().findViewById(R.id.box_text2); boxText2.setVisibility(View.INVISIBLE); // ImageView nextface = (ImageView) getView().findViewById(R.id.nextface); boxText2.setText(responsephoto.size() + " FACES ARE FOUND"); // final EditableImage image = new EditableImage(getActivity(), R.drawable.photo2); for (int i = 0; i < responsephoto.size(); i++) { Log.d("see response as a:", "onResponse: crop crop responsephoto is : +" + responsephoto.get(i).get(0) + +responsephoto.get(i).get(1) + responsephoto.get(i).get(2) + responsephoto.get(i).get(3) + " b type is : "); } image = new EditableImage(bmp32); // ScalableBox box1 = new ScalableBox(25, 10, 640, 80); // ScalableBox box2 = new ScalableBox(2, 18, 680, 80); // ScalableBox box3 = new ScalableBox(250, 80, 400, 80); facecount = responsephoto.size(); nextfaceb = true; // boxText3.setText("cropint " + (responsephoto.size() - facecount + 1) + "th face"); // String strtext = getArguments().getString("edttext"); try { // y1 = responsephoto.get(facecount - 1).get(0).intValue(); // x2 = responsephoto.get(facecount - 1).get(1).intValue(); // y2 = responsephoto.get(facecount - 1).get(2).intValue(); // x1 = responsephoto.get(facecount - 1).get(3).intValue(); y1 = getArguments().getInt("y1"); x2 = getArguments().getInt("x2"); y2 = getArguments().getInt("y2"); x1 = getArguments().getInt("x1"); // y1 = 19; // x2 = 220; // y2 = 90; // x1 = 10; box1 = new ScalableBox(x1, y1, x2, y2); box2 = new ScalableBox(0, 0, 0, 0); box3 = new ScalableBox(0, 0, 0, 0); boxes = new ArrayList<>(); boxes.add(box1); boxes.add(box2); boxes.add(box3); image.setBoxes(boxes); imageView.initView(getActivity(), image); boxText.setText("box: [" + x1 + " " + y1 + " " + x2 + " " + y2 + " ]"); // doit(); imageView.setOnBoxChangedListener(new OnBoxChangedListener() { @Override public void onChanged(int x1, int y1, int x2, int y2) { boxText.setText("box: [" + x1 + "," + y1 + "],[" + x2 + "," + y2 + "]"); someMethod(x1, y1, x2, y2); } }); } catch (Exception e) { // Toast.makeText(getActivity(), " error :(", Toast.LENGTH_SHORT).show(); } } TextClicked mCallback; public interface TextClicked { public void sendText(int x1, int y1, int x2, int y2); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (TextClicked) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement TextClicked"); } } public void someMethod(int x1, int y1, int x2, int y2) { mCallback.sendText(x1, y1, x2, y2); } @Override public void onDetach() { // someMethod(); mCallback = null; // => avoid leaking, thanks @Deepscorn super.onDetach(); } }
3e0a8848451ff442402602beace257edf3c0f231
4,198
java
Java
modules/main/src/test/java/deepboof/impl/forward/standard/ChecksSpatialWindow.java
lessthanoptimal/DeepBoof
bb690ec8bc9fe99d05511900617531f51843c952
[ "Apache-2.0" ]
19
2016-10-15T02:04:18.000Z
2021-07-15T17:36:08.000Z
modules/main/src/test/java/deepboof/impl/forward/standard/ChecksSpatialWindow.java
lessthanoptimal/DeepBoof
bb690ec8bc9fe99d05511900617531f51843c952
[ "Apache-2.0" ]
1
2022-03-01T13:20:21.000Z
2022-03-01T13:20:21.000Z
modules/main/src/test/java/deepboof/impl/forward/standard/ChecksSpatialWindow.java
lessthanoptimal/DeepBoof
bb690ec8bc9fe99d05511900617531f51843c952
[ "Apache-2.0" ]
5
2016-10-07T14:21:09.000Z
2019-08-14T04:56:41.000Z
26.074534
99
0.686994
4,457
/* * Copyright (c) 2016, Peter Abeles. All Rights Reserved. * * This file is part of DeepBoof * * 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 deepboof.impl.forward.standard; import deepboof.DeepBoofConstants; import deepboof.forward.ConfigSpatial; import deepboof.misc.TensorFactory_F64; import deepboof.tensors.Tensor_F64; import org.junit.jupiter.api.Test; import java.util.Random; import static deepboof.misc.TensorOps.WI; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Peter Abeles */ public abstract class ChecksSpatialWindow { protected Random rand = new Random(234); protected final int pad = 2; protected int N = 3; protected int C = 4; ConfigSpatial configSpatial; public abstract BaseSpatialWindow<Tensor_F64,ConstantPadding2D_F64> create(ConfigSpatial config ); @Test public void entirelyInside() { for( boolean sub : new boolean[]{false,true}) { Tensor_F64 original = TensorFactory_F64.random(rand, sub,N,C,2,2); configSpatial = new ConfigSpatial(); configSpatial.WW = 3; configSpatial.HH = 3; BaseSpatialWindow<Tensor_F64,ConstantPadding2D_F64> helper = create(configSpatial); helper.initialize(C,2,2); Tensor_F64 found = new Tensor_F64(WI(N,C,4,4)); helper.forward(original, found); compareToBruteForce(original, found); } } @Test public void insideAndOutside() { for( boolean sub : new boolean[]{false,true}) { Tensor_F64 original = TensorFactory_F64.random(rand, sub,N,C,8,9); configSpatial = new ConfigSpatial(); configSpatial.HH = 3; configSpatial.WW = 3; BaseSpatialWindow<Tensor_F64,ConstantPadding2D_F64> helper = create(configSpatial); helper.initialize(C,8,9); Tensor_F64 found = new Tensor_F64(WI(N,C,10,11)); helper.forward(original,found); compareToBruteForce(original,found); } } /** * Adjust the period settings and see if it responds correctly */ @Test public void period() { for( boolean sub : new boolean[]{false,true}) { Tensor_F64 original = TensorFactory_F64.random(rand, sub,N,C,8,9); configSpatial = new ConfigSpatial(); configSpatial.periodY=3; configSpatial.periodX=2; configSpatial.HH = 3; configSpatial.WW = 3; BaseSpatialWindow<Tensor_F64,ConstantPadding2D_F64> helper = create(configSpatial); helper.initialize(C,8,9); Tensor_F64 found = new Tensor_F64(WI(N,C,4,6)); helper.forward(original, found); compareToBruteForce(original,found); } } protected void compareToBruteForce(Tensor_F64 input , Tensor_F64 found ) { int periodY = configSpatial.periodY; int periodX = configSpatial.periodX; int HH = configSpatial.HH; int WW = configSpatial.WW; int H = input.length(2)+pad*2; int W = input.length(3)+pad*2; for (int batch = 0; batch < N; batch++) { for (int channel = 0; channel < C; channel++) { int outY = 0; for (int y = 0; y <= H-HH; y += periodY, outY++) { int outX = 0; for (int x = 0; x <= W-WW; x += periodX, outX++) { double expected = sumWindow(input,batch,channel, y, x, HH, WW); double foundValue = found.get(batch,channel,outY,outX); assertEquals(expected,foundValue, DeepBoofConstants.TEST_TOL_F64,y+" "+x); } } } } } private double sumWindow(Tensor_F64 input, int b, int c, int y0, int x0, int HH, int WW) { int H = input.length(2)+pad*2; int W = input.length(3)+pad*2; double sum = 0; for (int y = 0; y < HH; y++) { int yy = y+y0; for (int x = 0; x < WW; x++) { int xx = x+x0; // border is all zero if( xx >= pad && xx < W-pad && yy >= pad && yy < H-pad ) { sum += input.get(b,c,yy-pad,xx-pad); } } } return sum; } }
3e0a88585a2fbe88bc8203e55d4889f26b109c97
248
java
Java
MineTweaker3-API/src/main/java/minetweaker/api/recipes/IBrewingRecipe.java
GTNewHorizons/NewHorizonsTweaker
7507ce5638c28d84d4acacae60f7d27f9ac80599
[ "MIT" ]
null
null
null
MineTweaker3-API/src/main/java/minetweaker/api/recipes/IBrewingRecipe.java
GTNewHorizons/NewHorizonsTweaker
7507ce5638c28d84d4acacae60f7d27f9ac80599
[ "MIT" ]
null
null
null
MineTweaker3-API/src/main/java/minetweaker/api/recipes/IBrewingRecipe.java
GTNewHorizons/NewHorizonsTweaker
7507ce5638c28d84d4acacae60f7d27f9ac80599
[ "MIT" ]
null
null
null
19.076923
49
0.766129
4,458
package minetweaker.api.recipes; import stanhebben.zenscript.annotations.ZenClass; /** * Created by Jared on 6/2/2016. */ @ZenClass("minetweaker.recipes.IBrewingRecipe") public interface IBrewingRecipe { public String toCommandString(); }
3e0a885e37a02dbfd64a6a678fd8cde3a1c41b5a
765
java
Java
extensions/resteasy-classic/rest-client-jsonb/deployment/src/main/java/io/quarkus/restclient/jsonb/deployment/RestClientJsonbProcessor.java
BarDweller/quarkus
8421eb9f1bc1e0e5f3486575fcec76e500c53d62
[ "Apache-2.0" ]
6
2021-05-12T07:04:59.000Z
2022-03-03T21:22:09.000Z
extensions/resteasy-classic/rest-client-jsonb/deployment/src/main/java/io/quarkus/restclient/jsonb/deployment/RestClientJsonbProcessor.java
BarDweller/quarkus
8421eb9f1bc1e0e5f3486575fcec76e500c53d62
[ "Apache-2.0" ]
149
2020-07-21T06:24:49.000Z
2022-03-17T20:02:09.000Z
extensions/rest-client-jsonb/deployment/src/main/java/io/quarkus/restclient/jsonb/deployment/RestClientJsonbProcessor.java
jamesnetherton/quarkus
e86f7c5392bd14f2a1afdff215aa00025ebe1859
[ "Apache-2.0" ]
4
2019-10-14T18:35:26.000Z
2020-05-15T16:25:42.000Z
36.428571
78
0.802614
4,459
package io.quarkus.restclient.jsonb.deployment; import io.quarkus.deployment.Capability; import io.quarkus.deployment.Feature; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.CapabilityBuildItem; import io.quarkus.deployment.builditem.FeatureBuildItem; public class RestClientJsonbProcessor { @BuildStep void build(BuildProducer<FeatureBuildItem> feature, BuildProducer<CapabilityBuildItem> capability) { feature.produce(new FeatureBuildItem(Feature.REST_CLIENT_JSONB)); capability.produce(new CapabilityBuildItem(Capability.REST_JSONB)); capability.produce(new CapabilityBuildItem(Capability.RESTEASY_JSON)); } }
3e0a887964cfd77861e7e2f796f50805ed0abd2b
784
java
Java
src/main/java/com/arkesel/IPhoneVerification.java
ArkeselDev/arkesel-java-library
98daa87f994e9b6830fe2c94660775200866fab7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/arkesel/IPhoneVerification.java
ArkeselDev/arkesel-java-library
98daa87f994e9b6830fe2c94660775200866fab7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/arkesel/IPhoneVerification.java
ArkeselDev/arkesel-java-library
98daa87f994e9b6830fe2c94660775200866fab7
[ "Apache-2.0" ]
null
null
null
39.2
114
0.776786
4,460
package com.arkesel; import com.arkesel.model.OTPMedium; import com.arkesel.model.OTPObject; import com.arkesel.model.OTPType; import java.io.IOException; import java.net.http.HttpResponse; public interface IPhoneVerification { public HttpResponse<String> sendOTPCode(OTPObject otpObject) throws IOException, InterruptedException; public HttpResponse<String> sendOTPCode(int length, OTPType type, int expiry, String message, String number, OTPMedium medium) throws IOException, InterruptedException; public HttpResponse<String> verifyOTPCode(OTPObject otpObject) throws IOException, InterruptedException; public HttpResponse<String> verifyOTPCode(String number,String code) throws IOException, InterruptedException; }
3e0a89b2bea182acae27e764f0df5c5ac2aeca8c
2,321
java
Java
Online-Education-Platform/edu_parent/service/service_edu/src/main/java/com/tsuiraku/eduservice/controller/CourseFrontController.java
tsuirak/Web
b72df2d027a593230972536dbe1e9a9726cb6e54
[ "MIT" ]
63
2021-01-24T05:16:01.000Z
2022-03-31T03:41:02.000Z
Online-Education-Platform/edu_parent/service/service_edu/src/main/java/com/tsuiraku/eduservice/controller/CourseFrontController.java
tsuirak/Web
b72df2d027a593230972536dbe1e9a9726cb6e54
[ "MIT" ]
2
2021-04-20T08:41:01.000Z
2022-02-16T11:00:16.000Z
Online-Education-Platform/edu_parent/service/service_edu/src/main/java/com/tsuiraku/eduservice/controller/CourseFrontController.java
tsuirak/Web
b72df2d027a593230972536dbe1e9a9726cb6e54
[ "MIT" ]
27
2021-02-01T06:59:59.000Z
2022-03-29T09:41:02.000Z
35.707692
103
0.735459
4,461
package com.tsuiraku.eduservice.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.tsuiraku.eduservice.entity.EduCourse; import com.tsuiraku.eduservice.entity.chapter.ChapterVo; import com.tsuiraku.eduservice.entity.frontvo.CourseFrontVo; import com.tsuiraku.eduservice.entity.frontvo.CourseWebVo; import com.tsuiraku.eduservice.service.EduChapterService; import com.tsuiraku.eduservice.service.EduCourseService; import com.tsuiraku.utils.R; import com.tsuiraku.utils.vo.CourseVo; import io.swagger.annotations.ApiOperation; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @RestController @RequestMapping("/eduservice/coursefront") @CrossOrigin public class CourseFrontController { @Autowired private EduCourseService courseService; @Autowired private EduChapterService chapterService; @ApiOperation("查询课程分页") @PostMapping("getFrontCourseList/{page}/{limit}") public R getFrontCourseList(@PathVariable long page, @PathVariable long limit, @RequestBody(required = false) CourseFrontVo courseFrontVo) { Page<EduCourse> pageCourse = new Page<>(page, limit); Map<String, Object> map = courseService.getCourseFrontList(pageCourse, courseFrontVo); return R.success().data(map); } @ApiOperation("查询课程信息") @GetMapping("getFrontCourseInfo/{id}") public R getFrontCourseInfo(@PathVariable String id) { CourseWebVo courseWebVo = courseService.getBaseCourseInfo(id); List<ChapterVo> chapterVideoList = chapterService.getChapterVideoByCourseId(id); return R.success().data("courseWebVo", courseWebVo).data("chapterVideoList", chapterVideoList); } /** * @Author: tsuiraku * @Date: 2021/11/29 下午1:55 * @Description: 根据课程id查询课程信息 */ @PostMapping("getCourseInfoOrder/{id}") public CourseVo getCourseInfoOrder(@PathVariable String id) { CourseWebVo courseInfo = courseService.getBaseCourseInfo(id); CourseVo courseVo = new CourseVo(); BeanUtils.copyProperties(courseInfo, courseVo); return courseVo; } }
3e0a89c5b39c55cef54e2ecaea4ec796f212be40
1,927
java
Java
campaignsdk/src/main/java/com/loyagram/android/campaignsdk/models/npssettings/RequestReasonSettings.java
Loyagram/campaign-sdk
fc1cf05f8839f9f16fae26113eed2fea279b708d
[ "Apache-2.0" ]
null
null
null
campaignsdk/src/main/java/com/loyagram/android/campaignsdk/models/npssettings/RequestReasonSettings.java
Loyagram/campaign-sdk
fc1cf05f8839f9f16fae26113eed2fea279b708d
[ "Apache-2.0" ]
null
null
null
campaignsdk/src/main/java/com/loyagram/android/campaignsdk/models/npssettings/RequestReasonSettings.java
Loyagram/campaign-sdk
fc1cf05f8839f9f16fae26113eed2fea279b708d
[ "Apache-2.0" ]
null
null
null
25.355263
125
0.662688
4,462
package com.loyagram.android.campaignsdk.models.npssettings; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; /** * Created by renju on 18/10/16. */ public class RequestReasonSettings implements Parcelable { @SerializedName("type") private String type = null; @SerializedName("all") private ReasonSetting all = null; @SerializedName("custom") private CustomReasonSettings custom = null; public String getType() { return type; } public void setType(String type) { this.type = type; } public ReasonSetting getAll() { return all; } public void setAll(ReasonSetting all) { this.all = all; } public CustomReasonSettings getCustom() { return custom; } public void setCustom(CustomReasonSettings custom) { this.custom = custom; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.type); dest.writeParcelable(this.all, flags); dest.writeParcelable(this.custom, flags); } public RequestReasonSettings() { } protected RequestReasonSettings(Parcel in) { this.type = in.readString(); this.all = in.readParcelable(ReasonSetting.class.getClassLoader()); this.custom = in.readParcelable(CustomReasonSettings.class.getClassLoader()); } public static final Parcelable.Creator<RequestReasonSettings> CREATOR = new Parcelable.Creator<RequestReasonSettings>() { @Override public RequestReasonSettings createFromParcel(Parcel source) { return new RequestReasonSettings(source); } @Override public RequestReasonSettings[] newArray(int size) { return new RequestReasonSettings[size]; } }; }
3e0a8a47c793c244c2a6d347ab9047e69d1e343a
1,256
java
Java
orca-core/src/main/java/com/netflix/spinnaker/orca/events/BeforeInitialExecutionPersist.java
plumpy/orca
370ce376707a2112c0bbf9adc6aaad2245440ddc
[ "Apache-2.0" ]
230
2015-11-16T17:54:37.000Z
2022-03-31T07:45:19.000Z
orca-core/src/main/java/com/netflix/spinnaker/orca/events/BeforeInitialExecutionPersist.java
plumpy/orca
370ce376707a2112c0bbf9adc6aaad2245440ddc
[ "Apache-2.0" ]
1,528
2015-11-17T14:55:07.000Z
2022-03-31T03:44:59.000Z
orca-core/src/main/java/com/netflix/spinnaker/orca/events/BeforeInitialExecutionPersist.java
plumpy/orca
370ce376707a2112c0bbf9adc6aaad2245440ddc
[ "Apache-2.0" ]
957
2015-11-16T19:32:54.000Z
2022-03-28T18:32:15.000Z
33.945946
79
0.765924
4,463
/* * Copyright 2018 Netflix, 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.netflix.spinnaker.orca.events; import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution; import javax.annotation.Nonnull; import org.springframework.context.ApplicationEvent; /** An event emitted immediately before the initial persist of an execution. */ public final class BeforeInitialExecutionPersist extends ApplicationEvent { private final PipelineExecution execution; public BeforeInitialExecutionPersist( @Nonnull Object source, @Nonnull PipelineExecution execution) { super(source); this.execution = execution; } public final @Nonnull PipelineExecution getExecution() { return execution; } }
3e0a8b57a8cc1a47dfc4177908ad36a503ba73f9
5,228
java
Java
hw09-ORM/src/main/java/ru/otus/StartORM.java
Lallora/2020-06-otus-java-Arefulin
d0dc913a773aee8ab8e272a3532baf504f70bccc
[ "MIT" ]
1
2022-03-26T13:31:17.000Z
2022-03-26T13:31:17.000Z
hw09-ORM/src/main/java/ru/otus/StartORM.java
Lallora/2020-06-otus-java-Arefulin
d0dc913a773aee8ab8e272a3532baf504f70bccc
[ "MIT" ]
null
null
null
hw09-ORM/src/main/java/ru/otus/StartORM.java
Lallora/2020-06-otus-java-Arefulin
d0dc913a773aee8ab8e272a3532baf504f70bccc
[ "MIT" ]
null
null
null
48.859813
116
0.687643
4,464
package ru.otus; import org.flywaydb.core.Flyway; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.otus.core.models.Account; import ru.otus.core.models.User; import ru.otus.core.service.DbServiceAccountImpl; import ru.otus.core.service.DbServiceUserImpl; import ru.otus.h2.DataSourceH2; import ru.otus.jdbc.DbExecutor; import ru.otus.jdbc.DbExecutorImpl; import ru.otus.jdbc.dao.DaoAccountJDBC; import ru.otus.jdbc.dao.DaoUserJDBC; import ru.otus.jdbc.mapper.EntityClassMetaDataImpl; import ru.otus.jdbc.mapper.EntitySQLMetaDataImpl; import ru.otus.jdbc.mapper.JdbcMapperImpl; import ru.otus.jdbc.sessionmanager.SessionManager; import ru.otus.jdbc.sessionmanager.SessionManagerImpl; import javax.sql.DataSource; import java.util.Optional; public class StartORM { private static final Logger logger = LoggerFactory.getLogger(StartORM.class); public static void main(String[] args) { // Общая часть var dataSource = new DataSourceH2(); flywayMigrations(dataSource); SessionManager sessionManager = new SessionManagerImpl(dataSource); // Users DbExecutor<User> dbExecutorUser = new DbExecutorImpl<>(); var classMetaDataUser = new EntityClassMetaDataImpl(User.class); var sqlMetaDataUser = new EntitySQLMetaDataImpl(classMetaDataUser); var jdbcMapperUser = new JdbcMapperImpl(sessionManager, dbExecutorUser, classMetaDataUser, sqlMetaDataUser); var userDao = new DaoUserJDBC(sessionManager, jdbcMapperUser); var dbServiceUser = new DbServiceUserImpl(userDao); // Insert dbServiceUser.saveUser(new User(0, "Petrova", 24)); dbServiceUser.saveUser(new User(0, "Ivanov", 37)); Optional<User> user1 = dbServiceUser.getUser(1); Optional<User> user2 = dbServiceUser.getUser(2); user1.ifPresentOrElse(crUser -> logger.info("created user1, name:{}", crUser.getName()), () -> logger.info("user1 was not created")); user2.ifPresentOrElse(crUser -> logger.info("created user2, name:{}", crUser.getName()), () -> logger.info("user2 was not created")); dbServiceUser.saveUser(new User(0, "Sidorov", 50)); Optional<User> user3 = dbServiceUser.getUser(3); user3.ifPresentOrElse(crUser -> logger.info("created user3, name:{}", crUser.getName()), () -> logger.info("user3 was not created")); // Update or insert dbServiceUser.saveUser(new User(125, "Kuznecova", 55)); Optional<User> user4 = dbServiceUser.getUser(4); user4.ifPresentOrElse(crUser -> logger.info("created user4, name:{}", crUser.getName()), () -> logger.info("user4 was not created")); // Update dbServiceUser.getUser(1); dbServiceUser.saveUser(new User(1, "Ivanova", 25)); dbServiceUser.getUser(1); // Accounts DbExecutor<Account> dbExecutorAccount = new DbExecutorImpl<>(); var classAccountMetaDataAccount = new EntityClassMetaDataImpl(Account.class); var sqlAccountMetaDataAccount = new EntitySQLMetaDataImpl(classAccountMetaDataAccount); var jdbcMapperAccount = new JdbcMapperImpl(sessionManager, dbExecutorAccount, classAccountMetaDataAccount, sqlAccountMetaDataAccount); var accountDao = new DaoAccountJDBC(sessionManager, jdbcMapperAccount); var dbServiceAccount = new DbServiceAccountImpl(accountDao); // Insert dbServiceAccount.saveAccount(new Account(0, "acc001", 1)); dbServiceAccount.saveAccount(new Account(0, "acc002", 2)); Optional<Account> account1 = dbServiceAccount.getAccount(1); Optional<Account> account2 = dbServiceAccount.getAccount(2); account1.ifPresentOrElse(crAccount -> logger.info("created Account1, name:{}", crAccount.getType()), () -> logger.info("Account1 was not created")); account2.ifPresentOrElse(crAccount -> logger.info("created Account2, name:{}", crAccount.getType()), () -> logger.info("Account2 was not created")); dbServiceAccount.saveAccount(new Account(0, "acc003", 3)); Optional<Account> account3 = dbServiceAccount.getAccount(3); account3.ifPresentOrElse(crAccount -> logger.info("created Account3, name:{}", crAccount.getType()), () -> logger.info("Account3 was not created")); // Update or insert dbServiceAccount.saveAccount(new Account(125, "acc004", 4)); Optional<Account> account4 = dbServiceAccount.getAccount(4); account4.ifPresentOrElse(crAccount -> logger.info("created Account4, name:{}", crAccount.getType()), () -> logger.info("Account4 was not created")); // Update dbServiceAccount.getAccount(1); dbServiceAccount.saveAccount(new Account(1, "acc005", 5)); dbServiceAccount.getAccount(1); } private static void flywayMigrations(DataSource dataSource) { logger.info("db migration started..."); var flyway = Flyway.configure() .dataSource(dataSource) .locations("classpath:/db/migration") .load(); flyway.migrate(); logger.info("db migration finished."); logger.info("***"); } }
3e0a8c84ad7dc9048b0bd2fc41ccc8903f9cadd6
8,079
java
Java
src/test/java/com/thebuzzmedia/exiftool/ExifTool_getImageMeta_Test.java
wiecklabs/exiftool
0f14e97c69a614b19fa14c9b72540420d1a57ed4
[ "Apache-2.0" ]
null
null
null
src/test/java/com/thebuzzmedia/exiftool/ExifTool_getImageMeta_Test.java
wiecklabs/exiftool
0f14e97c69a614b19fa14c9b72540420d1a57ed4
[ "Apache-2.0" ]
null
null
null
src/test/java/com/thebuzzmedia/exiftool/ExifTool_getImageMeta_Test.java
wiecklabs/exiftool
0f14e97c69a614b19fa14c9b72540420d1a57ed4
[ "Apache-2.0" ]
null
null
null
32.873984
188
0.754297
4,465
/** * Copyright 2011 The Buzz Media, LLC * Copyright 2015 Mickael Jeanroy <dycjh@example.com> * * 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.thebuzzmedia.exiftool; import com.thebuzzmedia.exiftool.core.StandardFormat; import com.thebuzzmedia.exiftool.core.StandardTag; import com.thebuzzmedia.exiftool.exceptions.UnreadableFileException; import com.thebuzzmedia.exiftool.process.Command; import com.thebuzzmedia.exiftool.process.CommandExecutor; import com.thebuzzmedia.exiftool.process.CommandResult; import com.thebuzzmedia.exiftool.process.OutputHandler; import com.thebuzzmedia.exiftool.tests.builders.CommandResultBuilder; import com.thebuzzmedia.exiftool.tests.builders.FileBuilder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.rules.ExpectedException.none; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ExifTool_getImageMeta_Test { @Rule public ExpectedException thrown = none(); private String path; @Mock private CommandExecutor executor; @Mock private ExecutionStrategy strategy; @Captor private ArgumentCaptor<List<String>> argsCaptor; private ExifTool exifTool; @Before public void setUp() throws Exception { path = "exiftool"; CommandResult cmd = new CommandResultBuilder() .output("9.36") .build(); when(executor.execute(any(Command.class))).thenReturn(cmd); when(strategy.isSupported(any(Version.class))).thenReturn(true); exifTool = new ExifTool(path, executor, strategy); reset(executor); } @Test public void it_should_fail_if_image_is_null() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("Image cannot be null and must be a valid stream of image data."); exifTool.getImageMeta(null, StandardFormat.HUMAN_READABLE, asList((Tag[]) StandardTag.values())); } @Test public void it_should_fail_if_format_is_null() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("Format cannot be null."); exifTool.getImageMeta(mock(File.class), null, asList((Tag[]) StandardTag.values())); } @Test public void it_should_fail_if_tags_is_null() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("Tags cannot be null and must contain 1 or more Tag to query the image for."); exifTool.getImageMeta(mock(File.class), StandardFormat.HUMAN_READABLE, null); } @Test public void it_should_fail_if_tags_is_empty() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Tags cannot be null and must contain 1 or more Tag to query the image for."); exifTool.getImageMeta(mock(File.class), StandardFormat.HUMAN_READABLE, Collections.<Tag>emptyList()); } @Test public void it_should_fail_with_unknown_file() throws Exception { thrown.expect(UnreadableFileException.class); thrown.expectMessage("Unable to read the given image [/tmp/foo.png], ensure that the image exists at the given withPath and that the executing Java process has permissions to read it."); File image = new FileBuilder("foo.png") .exists(false) .build(); exifTool.getImageMeta(image, StandardFormat.HUMAN_READABLE, asList((Tag[]) StandardTag.values())); } @Test public void it_should_fail_with_non_readable_file() throws Exception { thrown.expect(UnreadableFileException.class); thrown.expectMessage("Unable to read the given image [/tmp/foo.png], ensure that the image exists at the given withPath and that the executing Java process has permissions to read it."); File image = new FileBuilder("foo.png") .canRead(false) .build(); exifTool.getImageMeta(image, StandardFormat.HUMAN_READABLE, asList((Tag[]) StandardTag.values())); } @Test public void it_should_get_image_metadata() throws Exception { // Given final Format format = StandardFormat.HUMAN_READABLE; final File image = new FileBuilder("foo.png").build(); final Map<Tag, String> tags = new HashMap<Tag, String>(); tags.put(StandardTag.ARTIST, "bar"); tags.put(StandardTag.COMMENT, "foo"); doAnswer(new ReadTagsAnswer(tags, "{ready}")) .when(strategy).execute(same(executor), same(path), anyListOf(String.class), any(OutputHandler.class)); // When Map<Tag, String> results = exifTool.getImageMeta(image, format, tags.keySet()); // Then verify(strategy).execute(same(executor), same(path), argsCaptor.capture(), any(OutputHandler.class)); assertThat(results) .isNotNull() .isNotEmpty() .hasSize(tags.size()) .isEqualTo(tags); } @Test public void it_should_get_image_metadata_in_numeric_format() throws Exception { // Given final Format format = StandardFormat.NUMERIC; final File image = new FileBuilder("foo.png").build(); final Map<Tag, String> tags = new HashMap<Tag, String>(); tags.put(StandardTag.ARTIST, "foo"); tags.put(StandardTag.COMMENT, "bar"); doAnswer(new ReadTagsAnswer(tags, "{ready}")) .when(strategy).execute(same(executor), same(path), anyListOf(String.class), any(OutputHandler.class)); // When Map<Tag, String> results = exifTool.getImageMeta(image, format, tags.keySet()); // Then verify(strategy).execute(same(executor), same(path), argsCaptor.capture(), any(OutputHandler.class)); assertThat(results) .isNotNull() .isNotEmpty() .hasSize(tags.size()) .isEqualTo(tags); } @Test public void it_should_get_image_metadata_in_numeric_format_by_default() throws Exception { // Given final File image = new FileBuilder("foo.png").build(); final Map<Tag, String> tags = new HashMap<Tag, String>(); tags.put(StandardTag.ARTIST, "foo"); tags.put(StandardTag.COMMENT, "bar"); doAnswer(new ReadTagsAnswer(tags, "{ready}")) .when(strategy).execute(same(executor), same(path), anyListOf(String.class), any(OutputHandler.class)); // When Map<Tag, String> results = exifTool.getImageMeta(image, tags.keySet()); // Then verify(strategy).execute(same(executor), same(path), argsCaptor.capture(), any(OutputHandler.class)); assertThat(results) .isNotNull() .isNotEmpty() .hasSize(tags.size()) .isEqualTo(tags); } private static class ReadTagsAnswer implements Answer<Void> { private final Map<Tag, String> tags; private final String end; public ReadTagsAnswer(Map<Tag, String> tags, String end) { this.tags = tags; this.end = end; } @Override public Void answer(InvocationOnMock invocation) throws Throwable { OutputHandler handler = (OutputHandler) invocation.getArguments()[3]; // Read tags for (Map.Entry<Tag, String> entry : tags.entrySet()) { handler.readLine(entry.getKey().getName() + ": " + entry.getValue()); } // Read last line handler.readLine(end); return null; } } }
3e0a8d15c3cce15a3b3f63bd55b8ed8648c5a087
651
java
Java
src/test/groovy/ru/vyarus/dropwizard/guice/debug/renderer/guice/support/OverrideModule.java
gb/dropwizard-guicey
810e1183db77c838ac54b7e6dfed40f0ce43cb53
[ "MIT" ]
219
2015-01-14T13:14:13.000Z
2022-03-24T03:09:59.000Z
src/test/groovy/ru/vyarus/dropwizard/guice/debug/renderer/guice/support/OverrideModule.java
JKomoroski/dropwizard-guicey
111dc14da011c92f98955bca3c99728351cb1b9e
[ "MIT" ]
194
2015-01-02T11:22:59.000Z
2022-03-17T23:53:12.000Z
src/test/groovy/ru/vyarus/dropwizard/guice/debug/renderer/guice/support/OverrideModule.java
JKomoroski/dropwizard-guicey
111dc14da011c92f98955bca3c99728351cb1b9e
[ "MIT" ]
54
2015-04-17T19:00:50.000Z
2021-11-20T02:12:17.000Z
32.55
84
0.771121
4,466
package ru.vyarus.dropwizard.guice.debug.renderer.guice.support; import com.google.inject.AbstractModule; import ru.vyarus.dropwizard.guice.debug.renderer.guice.support.exts.BindService; import ru.vyarus.dropwizard.guice.debug.renderer.guice.support.exts.BindService2; import ru.vyarus.dropwizard.guice.debug.renderer.guice.support.exts.OverrideService; /** * @author Vyacheslav Rusakov * @since 20.08.2019 */ public class OverrideModule extends AbstractModule { @Override protected void configure() { bind(BindService.class).to(OverrideService.class); bind(BindService2.class).toInstance(new BindService2() {}); } }
3e0a8fc5fe05b3c69db35672fc04305adc3f846c
2,803
java
Java
src/main/java/io/objects/tl/api/request/TLRequestMessagesEditChatPhoto.java
shahrivari/tlobjects
154f77c4cbe3ac8a64043ec6688f9e33077aa191
[ "MIT" ]
1
2019-07-23T11:00:47.000Z
2019-07-23T11:00:47.000Z
src/main/java/io/objects/tl/api/request/TLRequestMessagesEditChatPhoto.java
shahrivari/tlobjects
154f77c4cbe3ac8a64043ec6688f9e33077aa191
[ "MIT" ]
2
2020-03-04T23:25:48.000Z
2021-01-21T00:16:40.000Z
src/main/java/io/objects/tl/api/request/TLRequestMessagesEditChatPhoto.java
shahrivari/tlobjects
154f77c4cbe3ac8a64043ec6688f9e33077aa191
[ "MIT" ]
8
2019-07-30T15:51:32.000Z
2021-01-15T17:03:26.000Z
28.313131
158
0.688905
4,467
package io.objects.tl.api.request; import static io.objects.tl.StreamUtils.*; import static io.objects.tl.TLObjectUtils.*; import io.objects.tl.TLContext; import io.objects.tl.api.TLAbsInputChatPhoto; import io.objects.tl.api.TLAbsUpdates; import io.objects.tl.core.TLMethod; import io.objects.tl.core.TLObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.Override; import java.lang.String; import java.lang.SuppressWarnings; /** * This class is generated by Mono's TL class generator */ public class TLRequestMessagesEditChatPhoto extends TLMethod<TLAbsUpdates> { public static final int CONSTRUCTOR_ID = 0xca4c79d8; protected int chatId; protected TLAbsInputChatPhoto photo; private final String _constructor = "messages.editChatPhoto#ca4c79d8"; public TLRequestMessagesEditChatPhoto() { } public TLRequestMessagesEditChatPhoto(int chatId, TLAbsInputChatPhoto photo) { this.chatId = chatId; this.photo = photo; } @Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public TLAbsUpdates deserializeResponse(InputStream stream, TLContext context) throws IOException { final TLObject response = readTLObject(stream, context); if (response == null) { throw new IOException("Unable to parse response"); } if (!(response instanceof TLAbsUpdates)) { throw new IOException("Incorrect response type, expected " + getClass().getCanonicalName() + ", found " + response.getClass().getCanonicalName()); } return (TLAbsUpdates) response; } @Override public void serializeBody(OutputStream stream) throws IOException { writeInt(chatId, stream); writeTLObject(photo, stream); } @Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public void deserializeBody(InputStream stream, TLContext context) throws IOException { chatId = readInt(stream); photo = readTLObject(stream, context, TLAbsInputChatPhoto.class, -1); } @Override public int computeSerializedSize() { int size = SIZE_CONSTRUCTOR_ID; size += SIZE_INT32; size += photo.computeSerializedSize(); return size; } @Override public String toString() { return _constructor; } @Override public int getConstructorId() { return CONSTRUCTOR_ID; } public int getChatId() { return chatId; } public void setChatId(int chatId) { this.chatId = chatId; } public TLAbsInputChatPhoto getPhoto() { return photo; } public void setPhoto(TLAbsInputChatPhoto photo) { this.photo = photo; } }
3e0a8fc652c84abc7a7fa7fc818290103f1dc419
14,437
java
Java
pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/buffer/TransactionLowWaterMarkTest.java
abhilashmandaliya/pulsar
2e4bada632af2f15a2882e9684c6376a4d8ba2a5
[ "Apache-2.0" ]
7
2021-01-28T14:52:31.000Z
2021-12-04T08:16:20.000Z
pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/buffer/TransactionLowWaterMarkTest.java
abhilashmandaliya/pulsar
2e4bada632af2f15a2882e9684c6376a4d8ba2a5
[ "Apache-2.0" ]
24
2021-06-09T15:46:51.000Z
2022-03-31T12:54:59.000Z
pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/buffer/TransactionLowWaterMarkTest.java
abhilashmandaliya/pulsar
2e4bada632af2f15a2882e9684c6376a4d8ba2a5
[ "Apache-2.0" ]
3
2021-04-27T13:24:08.000Z
2022-03-16T21:20:19.000Z
45.542587
133
0.662742
4,468
/** * 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.pulsar.broker.transaction.buffer; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.google.common.collect.Sets; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.mledger.impl.PositionImpl; import org.apache.commons.collections4.map.LinkedMap; import org.apache.pulsar.broker.service.BrokerService; import org.apache.pulsar.broker.service.Topic; import org.apache.pulsar.broker.service.persistent.PersistentSubscription; import org.apache.pulsar.broker.transaction.TransactionTestBase; import org.apache.pulsar.broker.transaction.pendingack.impl.PendingAckHandleImpl; import org.apache.pulsar.client.api.Consumer; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.SubscriptionInitialPosition; import org.apache.pulsar.client.api.SubscriptionType; import org.apache.pulsar.client.api.transaction.Transaction; import org.apache.pulsar.client.api.transaction.TxnID; import org.apache.pulsar.client.impl.PulsarClientImpl; import org.apache.pulsar.client.impl.transaction.TransactionImpl; import org.apache.pulsar.common.naming.NamespaceName; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.partition.PartitionedTopicMetadata; import org.apache.pulsar.common.policies.data.ClusterData; import org.apache.pulsar.common.policies.data.ClusterDataImpl; import org.apache.pulsar.common.policies.data.TenantInfoImpl; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; import org.apache.pulsar.transaction.coordinator.TransactionCoordinatorID; import org.apache.pulsar.transaction.coordinator.TransactionMetadataStore; import org.apache.pulsar.transaction.coordinator.TransactionMetadataStoreState; import org.apache.pulsar.transaction.coordinator.impl.MLTransactionMetadataStore; import org.awaitility.Awaitility; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Pulsar client transaction test. */ @Slf4j @Test(groups = "broker") public class TransactionLowWaterMarkTest extends TransactionTestBase { private static final String TENANT = "tnx"; private static final String NAMESPACE1 = TENANT + "/ns1"; private static final String TOPIC = NAMESPACE1 + "/test-topic"; @BeforeMethod(alwaysRun = true) protected void setup() throws Exception { setBrokerCount(1); internalSetup(); String[] brokerServiceUrlArr = getPulsarServiceList().get(0).getBrokerServiceUrl().split(":"); String webServicePort = brokerServiceUrlArr[brokerServiceUrlArr.length -1]; admin.clusters().createCluster(CLUSTER_NAME, ClusterData.builder().serviceUrl("http://localhost:" + webServicePort).build()); admin.tenants().createTenant(TENANT, new TenantInfoImpl(Sets.newHashSet("appid1"), Sets.newHashSet(CLUSTER_NAME))); admin.namespaces().createNamespace(NAMESPACE1); admin.topics().createNonPartitionedTopic(TOPIC); admin.tenants().createTenant(NamespaceName.SYSTEM_NAMESPACE.getTenant(), new TenantInfoImpl(Sets.newHashSet("appid1"), Sets.newHashSet(CLUSTER_NAME))); admin.namespaces().createNamespace(NamespaceName.SYSTEM_NAMESPACE.toString()); admin.topics().createPartitionedTopic(TopicName.TRANSACTION_COORDINATOR_ASSIGN.toString(), 16); if (pulsarClient != null) { pulsarClient.shutdown(); } pulsarClient = PulsarClient.builder() .serviceUrl(getPulsarServiceList().get(0).getBrokerServiceUrl()) .statsInterval(0, TimeUnit.SECONDS) .enableTransaction(true) .build(); Map<TransactionCoordinatorID, TransactionMetadataStore> stores = getPulsarServiceList().get(0).getTransactionMetadataStoreService().getStores(); Awaitility.await().until(() -> { if (stores.size() == 16) { for (TransactionCoordinatorID transactionCoordinatorID : stores.keySet()) { if (((MLTransactionMetadataStore) stores.get(transactionCoordinatorID)).getState() != TransactionMetadataStoreState.State.Ready) { return false; } } return true; } else { return false; } }); } @AfterMethod(alwaysRun = true) protected void cleanup() throws Exception { super.internalCleanup(); } @Test public void testTransactionBufferLowWaterMark() throws Exception { Transaction txn = pulsarClient.newTransaction() .withTransactionTimeout(5, TimeUnit.SECONDS) .build().get(); Producer<byte[]> producer = pulsarClient .newProducer() .topic(TOPIC) .sendTimeout(0, TimeUnit.SECONDS) .enableBatching(false) .create(); Consumer<byte[]> consumer = pulsarClient.newConsumer() .topic(TOPIC) .subscriptionName("test") .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest) .enableBatchIndexAcknowledgment(true) .subscriptionType(SubscriptionType.Failover) .subscribe(); final String TEST1 = "test1"; final String TEST2 = "test2"; final String TEST3 = "test3"; producer.newMessage(txn).value(TEST1.getBytes()).send(); txn.commit().get(); Message<byte[]> message = consumer.receive(2, TimeUnit.SECONDS); assertEquals(new String(message.getData()), TEST1); message = consumer.receive(2, TimeUnit.SECONDS); assertNull(message); Field field = TransactionImpl.class.getDeclaredField("state"); field.setAccessible(true); field.set(txn, TransactionImpl.State.OPEN); producer.newMessage(txn).value(TEST2.getBytes()).send(); message = consumer.receive(2, TimeUnit.SECONDS); assertNull(message); PartitionedTopicMetadata partitionedTopicMetadata = ((PulsarClientImpl) pulsarClient).getLookup() .getPartitionedTopicMetadata(TopicName.TRANSACTION_COORDINATOR_ASSIGN).get(); Transaction lowWaterMarkTxn = null; for (int i = 0; i < partitionedTopicMetadata.partitions; i++) { lowWaterMarkTxn = pulsarClient.newTransaction() .withTransactionTimeout(5, TimeUnit.SECONDS) .build().get(); if (((TransactionImpl) lowWaterMarkTxn).getTxnIdMostBits() == ((TransactionImpl) txn).getTxnIdMostBits()) { break; } } if (lowWaterMarkTxn != null && ((TransactionImpl) lowWaterMarkTxn).getTxnIdMostBits() == ((TransactionImpl) txn).getTxnIdMostBits()) { producer.newMessage(lowWaterMarkTxn).value(TEST3.getBytes()).send(); message = consumer.receive(2, TimeUnit.SECONDS); assertNull(message); lowWaterMarkTxn.commit().get(); message = consumer.receive(); assertEquals(new String(message.getData()), TEST3); } else { fail(); } } @Test public void testPendingAckLowWaterMark() throws Exception { String subName = "test"; Transaction txn = pulsarClient.newTransaction() .withTransactionTimeout(5, TimeUnit.SECONDS) .build().get(); @Cleanup Producer<byte[]> producer = pulsarClient .newProducer() .topic(TOPIC) .sendTimeout(0, TimeUnit.SECONDS) .enableBatching(false) .create(); @Cleanup Consumer<byte[]> consumer = pulsarClient.newConsumer() .topic(TOPIC) .subscriptionName(subName) .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest) .enableBatchIndexAcknowledgment(true) .subscriptionType(SubscriptionType.Failover) .subscribe(); final String TEST1 = "test1"; final String TEST2 = "test2"; final String TEST3 = "test3"; producer.send(TEST1.getBytes()); producer.send(TEST2.getBytes()); producer.send(TEST3.getBytes()); Message<byte[]> message = consumer.receive(2, TimeUnit.SECONDS); assertEquals(new String(message.getData()), TEST1); consumer.acknowledgeAsync(message.getMessageId(), txn).get(); LinkedMap<TxnID, HashMap<PositionImpl, PositionImpl>> individualAckOfTransaction = null; for (int i = 0; i < getPulsarServiceList().size(); i++) { Field field = BrokerService.class.getDeclaredField("topics"); field.setAccessible(true); ConcurrentOpenHashMap<String, CompletableFuture<Optional<Topic>>> topics = (ConcurrentOpenHashMap<String, CompletableFuture<Optional<Topic>>>) field .get(getPulsarServiceList().get(i).getBrokerService()); CompletableFuture<Optional<Topic>> completableFuture = topics.get("persistent://" + TOPIC); if (completableFuture != null) { Optional<Topic> topic = completableFuture.get(); if (topic.isPresent()) { PersistentSubscription persistentSubscription = (PersistentSubscription) topic.get() .getSubscription(subName); field = PersistentSubscription.class.getDeclaredField("pendingAckHandle"); field.setAccessible(true); PendingAckHandleImpl pendingAckHandle = (PendingAckHandleImpl) field.get(persistentSubscription); field = PendingAckHandleImpl.class.getDeclaredField("individualAckOfTransaction"); field.setAccessible(true); individualAckOfTransaction = (LinkedMap<TxnID, HashMap<PositionImpl, PositionImpl>>) field.get(pendingAckHandle); } } } assertTrue(individualAckOfTransaction.containsKey(new TxnID(((TransactionImpl) txn).getTxnIdMostBits(), ((TransactionImpl) txn).getTxnIdLeastBits()))); txn.commit().get(); Field field = TransactionImpl.class.getDeclaredField("state"); field.setAccessible(true); field.set(txn, TransactionImpl.State.OPEN); assertFalse(individualAckOfTransaction.containsKey(new TxnID(((TransactionImpl) txn).getTxnIdMostBits(), ((TransactionImpl) txn).getTxnIdLeastBits()))); message = consumer.receive(); assertEquals(new String(message.getData()), TEST2); consumer.acknowledgeAsync(message.getMessageId(), txn).get(); assertTrue(individualAckOfTransaction.containsKey(new TxnID(((TransactionImpl) txn).getTxnIdMostBits(), ((TransactionImpl) txn).getTxnIdLeastBits()))); PartitionedTopicMetadata partitionedTopicMetadata = ((PulsarClientImpl) pulsarClient).getLookup() .getPartitionedTopicMetadata(TopicName.TRANSACTION_COORDINATOR_ASSIGN).get(); Transaction lowWaterMarkTxn = null; for (int i = 0; i < partitionedTopicMetadata.partitions; i++) { lowWaterMarkTxn = pulsarClient.newTransaction() .withTransactionTimeout(5, TimeUnit.SECONDS) .build().get(); if (((TransactionImpl) lowWaterMarkTxn).getTxnIdMostBits() == ((TransactionImpl) txn).getTxnIdMostBits()) { break; } } if (lowWaterMarkTxn != null && ((TransactionImpl) lowWaterMarkTxn).getTxnIdMostBits() == ((TransactionImpl) txn).getTxnIdMostBits()) { producer.newMessage(lowWaterMarkTxn).value(TEST3.getBytes()).send(); message = consumer.receive(2, TimeUnit.SECONDS); assertEquals(new String(message.getData()), TEST3); consumer.acknowledgeAsync(message.getMessageId(), lowWaterMarkTxn).get(); assertTrue(individualAckOfTransaction.containsKey(new TxnID(((TransactionImpl) txn).getTxnIdMostBits(), ((TransactionImpl) txn).getTxnIdLeastBits()))); assertTrue(individualAckOfTransaction .containsKey(new TxnID(((TransactionImpl) lowWaterMarkTxn).getTxnIdMostBits(), ((TransactionImpl) lowWaterMarkTxn).getTxnIdLeastBits()))); lowWaterMarkTxn.commit().get(); assertFalse(individualAckOfTransaction.containsKey(new TxnID(((TransactionImpl) txn).getTxnIdMostBits(), ((TransactionImpl) txn).getTxnIdLeastBits()))); assertFalse(individualAckOfTransaction .containsKey(new TxnID(((TransactionImpl) lowWaterMarkTxn).getTxnIdMostBits(), ((TransactionImpl) lowWaterMarkTxn).getTxnIdLeastBits()))); } else { fail(); } } }
3e0a8fc91a83f76d9c12af0392530bcd416601bb
5,373
java
Java
tools/closure-compiler/trunk/src/com/google/debugging/sourcemap/Util.java
rlugojr/jsrepl
abf72e7a221e12acea344e5ea53579a502236f15
[ "MIT" ]
36
2018-07-03T13:05:00.000Z
2022-03-11T11:10:54.000Z
src/com/google/debugging/sourcemap/Util.java
pietrobraione/sushi-experiments-closure72
3f687f25787d319a9d77e75b14dfff14731ff67e
[ "Apache-2.0" ]
null
null
null
src/com/google/debugging/sourcemap/Util.java
pietrobraione/sushi-experiments-closure72
3f687f25787d319a9d77e75b14dfff14731ff67e
[ "Apache-2.0" ]
19
2018-06-24T15:41:33.000Z
2022-03-13T10:41:39.000Z
35.833333
80
0.563535
4,469
/* * Copyright 2011 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.debugging.sourcemap; import java.io.IOException; import java.nio.charset.CharsetEncoder; /** * @author hzdkv@example.com (John Lenz) */ class Util { private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * Escapes the given string to a double quoted (") JavaScript/JSON string */ static String escapeString(String s) { return escapeString(s, '"', "\\\"", "\'", "\\\\", null); } /** Helper to escape javascript string as well as regular expression */ static String escapeString(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': // Break --> into --\> or ]]> into ]]\> if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': // Break </script into <\/script final String END_SCRIPT = "/script"; // Break <!-- into <\!-- final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: // If we're given an outputCharsetEncoder, then check if the // character can be represented in this character set. if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { // Unicode-escape the character. appendCharAsHex(sb, c); } } else { // No charsetEncoder provided - pass straight latin characters // through, and escape the rest. Doing the explicit character // check is measurably faster than using the CharsetEncoder. if (c > 0x1f && c <= 0x7f) { sb.append(c); } else { // Other characters can be misinterpreted by some js parsers, // or perhaps mangled by proxies along the way, // so we play it safe and unicode escape them. appendCharAsHex(sb, c); } } } } sb.append(quote); return sb.toString(); } /** * @see #appendHexJavaScriptRepresentation(Appendable, int) */ @SuppressWarnings("cast") private static void appendCharAsHex( StringBuilder sb, char c) { try { appendHexJavaScriptRepresentation(sb, (int)c); } catch (IOException ex) { // StringBuilder does not throw IOException. throw new RuntimeException(ex); } } /** * Returns a javascript representation of the character in a hex escaped * format. * @param out The buffer to which the hex representation should be appended. * @param codePoint The codepoint to append. */ private static void appendHexJavaScriptRepresentation( Appendable out, int codePoint) throws IOException { if (Character.isSupplementaryCodePoint(codePoint)) { // Handle supplementary unicode values which are not representable in // javascript. We deal with these by escaping them as two 4B sequences // so that they will round-trip properly when sent from java to javascript // and back. char[] surrogates = Character.toChars(codePoint); appendHexJavaScriptRepresentation(out, surrogates[0]); appendHexJavaScriptRepresentation(out, surrogates[1]); return; } out.append("\\u") .append(HEX_CHARS[(codePoint >>> 12) & 0xf]) .append(HEX_CHARS[(codePoint >>> 8) & 0xf]) .append(HEX_CHARS[(codePoint >>> 4) & 0xf]) .append(HEX_CHARS[codePoint & 0xf]); } }
3e0a8fcda62fd4b66fd01c98bf7706abc2ba6b67
2,068
java
Java
Molap/Molap-Core/src/com/huawei/unibi/molap/csvreader/checkpoint/CheckPointInterface.java
foryou2030/carbondata
ca60c4270f65c17ae233fc313cb32cd0909af5a5
[ "Apache-2.0" ]
null
null
null
Molap/Molap-Core/src/com/huawei/unibi/molap/csvreader/checkpoint/CheckPointInterface.java
foryou2030/carbondata
ca60c4270f65c17ae233fc313cb32cd0909af5a5
[ "Apache-2.0" ]
null
null
null
Molap/Molap-Core/src/com/huawei/unibi/molap/csvreader/checkpoint/CheckPointInterface.java
foryou2030/carbondata
ca60c4270f65c17ae233fc313cb32cd0909af5a5
[ "Apache-2.0" ]
null
null
null
35.050847
101
0.697776
4,470
/* * 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 com.huawei.unibi.molap.csvreader.checkpoint; import java.util.Map; import com.huawei.unibi.molap.csvreader.checkpoint.exception.CheckPointException; public interface CheckPointInterface { /** * Below method will be used to get the checkpoint cache * * @return check point cache * @throws CheckPointException will throw exception in case of any error while getting the cache */ Map<String, Long> getCheckPointCache() throws CheckPointException; /** * Below method will be used to store the check point cache * * @param checkPointCache check point cache * @throws CheckPointException problem while storing the checkpoint cache */ void saveCheckPointCache(Map<String, Long> checkPointCache) throws CheckPointException; /** * Below method will be used to get the check point info field count * * @return */ int getCheckPointInfoFieldCount(); /** * This methods implementation will update the output row and add the Filepath and offset for * next step. * * @param inputRow * @param outputRow */ void updateInfoFields(Object[] inputRow, Object[] outputRow); }
3e0a901266ac1e39c519385612af6b7c51f830fe
2,072
java
Java
pinot-core/src/main/java/com/linkedin/pinot/core/query/aggregation/function/MinAggregationNoDictionaryFunction.java
bforevdr/pinot_
83b9a8f4f1be795619b3778fe4a37285534179c1
[ "Apache-2.0" ]
17
2015-11-27T15:56:18.000Z
2020-11-17T12:38:17.000Z
pinot-core/src/main/java/com/linkedin/pinot/core/query/aggregation/function/MinAggregationNoDictionaryFunction.java
bforevdr/pinot_
83b9a8f4f1be795619b3778fe4a37285534179c1
[ "Apache-2.0" ]
null
null
null
pinot-core/src/main/java/com/linkedin/pinot/core/query/aggregation/function/MinAggregationNoDictionaryFunction.java
bforevdr/pinot_
83b9a8f4f1be795619b3778fe4a37285534179c1
[ "Apache-2.0" ]
10
2015-12-30T07:50:16.000Z
2019-10-31T03:13:23.000Z
34.065574
110
0.712705
4,471
/** * Copyright (C) 2014-2015 LinkedIn Corp. (envkt@example.com) * * 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.linkedin.pinot.core.query.aggregation.function; import com.linkedin.pinot.core.common.Block; import com.linkedin.pinot.core.common.BlockDocIdIterator; import com.linkedin.pinot.core.common.BlockSingleValIterator; import com.linkedin.pinot.core.common.Constants; public class MinAggregationNoDictionaryFunction extends MinAggregationFunction { @Override public Double aggregate(Block docIdSetBlock, Block[] block) { double ret = Double.POSITIVE_INFINITY; double tmp = 0; int docId = 0; BlockDocIdIterator docIdIterator = docIdSetBlock.getBlockDocIdSet().iterator(); BlockSingleValIterator blockValIterator = (BlockSingleValIterator) block[0].getBlockValueSet().iterator(); while ((docId = docIdIterator.next()) != Constants.EOF) { if (blockValIterator.skipTo(docId)) { tmp = blockValIterator.nextDoubleVal(); if (tmp < ret) { ret = tmp; } } } return ret; } @Override public Double aggregate(Double mergedResult, int docId, Block[] block) { BlockSingleValIterator blockValIterator = (BlockSingleValIterator) block[0].getBlockValueSet().iterator(); if (blockValIterator.skipTo(docId)) { if (mergedResult == null) { return blockValIterator.nextDoubleVal(); } double tmp = blockValIterator.nextDoubleVal(); if (tmp < mergedResult) { return tmp; } } return mergedResult; } }
3e0a90922febf2463ee6099a58a0da1d8a017be8
1,865
java
Java
src/main/java/edu/vanderbilt/imagecrawler/utils/ImageUtils.java
americanstone/image-crawler
2ac7bf09376a9fa6104963c67ece65e7f2b9912e
[ "MIT" ]
null
null
null
src/main/java/edu/vanderbilt/imagecrawler/utils/ImageUtils.java
americanstone/image-crawler
2ac7bf09376a9fa6104963c67ece65e7f2b9912e
[ "MIT" ]
null
null
null
src/main/java/edu/vanderbilt/imagecrawler/utils/ImageUtils.java
americanstone/image-crawler
2ac7bf09376a9fa6104963c67ece65e7f2b9912e
[ "MIT" ]
null
null
null
31.610169
107
0.633244
4,472
package edu.vanderbilt.imagecrawler.utils; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import edu.vanderbilt.imagecrawler.web.TransformedImage; public class ImageUtils { /** * Converts a BufferedImage to a formatted byte array. * * @param bi Buffered image input * @param format Format (typically "jpg" or "png"). * @return image byte array */ public static byte[] toByteArray(BufferedImage bi, String format) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, format, baos); return baos.toByteArray(); } catch (IOException e) { throw ExceptionUtils.unchecked(e); } } /** * Converts image byte[] to a BufferedImage. * * @param bytes bytes to convert. * @return BufferedImage */ public static BufferedImage toBufferedImage(byte[] bytes) { try { return ImageIO.read(new ByteArrayInputStream(bytes)); } catch (IOException e) { throw ExceptionUtils.unchecked(e); } } public static File toFile(TransformedImage transformedImage) { try { byte[] bytes = transformedImage.getBytes(); InputStream inputStream = new ByteArrayInputStream(bytes); BufferedImage bi = ImageIO.read(inputStream); String fileName = transformedImage.getTransformName() + "-" + transformedImage.getSourceName(); File file = new File(fileName); ImageIO.write(bi, "png", file); return file; } catch (IOException e) { throw ExceptionUtils.unchecked(e); } } }
3e0a92ad6528891b9255c5c4e646de896c0ed480
5,745
java
Java
app/src/main/java/org/sil/bloom/reader/ShelfActivity.java
silexcorp/BloomReader
9dc87155e9803469ae2c0540cf574ce305a75a8d
[ "MIT" ]
1
2021-03-22T19:08:31.000Z
2021-03-22T19:08:31.000Z
app/src/main/java/org/sil/bloom/reader/ShelfActivity.java
silexcorp/BloomReader
9dc87155e9803469ae2c0540cf574ce305a75a8d
[ "MIT" ]
null
null
null
app/src/main/java/org/sil/bloom/reader/ShelfActivity.java
silexcorp/BloomReader
9dc87155e9803469ae2c0540cf574ce305a75a8d
[ "MIT" ]
null
null
null
47.479339
142
0.68738
4,473
package org.sil.bloom.reader; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Bundle; import androidx.appcompat.app.ActionBarDrawerToggle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import org.sil.bloom.reader.models.BookCollection; import org.sil.bloom.reader.models.ExtStorageUnavailableException; /** * Created by Thomson on 10/20/2017. * Showing a bookshelf is much like our main activity, which also shows a list of books (and shelves-- * something that just might come to this activity one day). For now we are using the same layout, * with the action bar changed to show the shelf icon, title and background and a back button instead * of the menu. * There are just a few things we need to do differently. * It may at some point be worth refactoring to extract a common base class, but for now, I prefer * to see all the logic in the class that primarily uses it and for which it was originally written, * MainActivity itself. This will also tend to facilitate git comparisons. */ public class ShelfActivity extends MainActivity { private String filter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // This is one half of configuring the action bar to have an up (back) arrow instead of // the usual hamburger menu. The other half is the override of configureActionBar(). // I would like to put this line in that method but for some unknown reason that doesn't // work...we get no control at all in the hamburger position. getSupportActionBar().setDisplayHomeAsUpEnabled(true); filter = getIntent().getStringExtra("filter"); // Initialize the bookshelf label (empty in MainActivity) with the data // passed through our intent. View toolbar = findViewById(R.id.toolbar); final int background = Color.parseColor("#" + getIntent().getStringExtra("background")); toolbar.setBackgroundColor(background); TextView labelText = findViewById(R.id.shelfName); labelText.setText(getIntent().getStringExtra("label")); ImageView bloomIcon = findViewById(R.id.bloom_icon); // replace the main bloom icon with the bookshelf one. bloomIcon.setImageResource(R.drawable.bookshelf); bloomIcon.setPadding(0,0, 10,0); // The color chosen for the bookshelf may not contrast well with the default white // color of text and the back arrow and the default black color of the bookshelf icon. // Change them all to black or white, whichever gives better contrast. int forecolor = pickTextColorBasedOnBgColor(background, Color.WHITE, Color.BLACK); labelText.setTextColor(forecolor); // This bit of magic from https://stackoverflow.com/questions/26788464/how-to-change-color-of-the-back-arrow-in-the-new-material-theme // makes the the back arrow use the contrasting foreground color Drawable upArrow = ((androidx.appcompat.widget.Toolbar)toolbar).getNavigationIcon(); upArrow.setColorFilter(forecolor, PorterDuff.Mode.SRC_ATOP); // And this bit, from https://stackoverflow.com/questions/1309629/how-to-change-colors-of-a-drawable-in-android, // switches the color of the bookshelf icon. bloomIcon.setColorFilter(forecolor); } // official W3C recommendation for deciding whether a light or dark color will contrast best // with the given background color. The right one to use is returned. // Based on https://stackoverflow.com/questions/3942878/how-to-decide-font-color-in-white-or-black-depending-on-background-color int pickTextColorBasedOnBgColor(int bgColor, int lightColor, int darkColor) { int r = (bgColor >> 16) & 0xff; int g = (bgColor >> 8) & 0xff; int b = bgColor & 0xff; double[] uicolors = new double[] {r / 255, g / 255, b / 255}; double[] c = new double[3]; for (int i = 0; i < 3; i++) { double col = uicolors[i]; if (col < 0.03928) c[i] = col/12.92; else c[i] = Math.pow((col + 0.055)/1.055, 2.4); } double luminance = (0.2126 * c[0]) + (0.7152 * c[1]) + (0.0722 * c[2]); return (luminance > 0.179) ? darkColor : lightColor; } // In the shelf view the action bar's menu is replaced with a back button. // It's possible we could achieve this in another way, for example, by initializing the // shelf view with a layout that doesn't have a navigation bar at all. But as the views // are so similar, I like having them share the same layout. @Override protected void configureActionBar(ActionBarDrawerToggle toggle) { toggle.setDrawerIndicatorEnabled(false); toggle.setToolbarNavigationClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } @Override protected void updateFilter() { _bookCollection.setFilter(filter); } @Override protected BookCollection setupBookCollection() throws ExtStorageUnavailableException { if (BloomReaderApplication.theOneBookCollection == null) { // Presume the OS threw away and re-created the BloomReaderApplication while we // weren't looking. We need to do the full job of making one. return super.setupBookCollection(); } // normally we just want to use the one the main activity made. return BloomReaderApplication.theOneBookCollection; } }
3e0a92c38c15be00859dce0c26b76663f4cb5f6c
2,256
java
Java
snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/request/rf2/validation/Rf2ValidationIssueReporter.java
fossabot/snow-owl
238f4e481d6ba762eeaa5c7185fbd9bedd81918a
[ "Apache-2.0" ]
null
null
null
snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/request/rf2/validation/Rf2ValidationIssueReporter.java
fossabot/snow-owl
238f4e481d6ba762eeaa5c7185fbd9bedd81918a
[ "Apache-2.0" ]
null
null
null
snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/request/rf2/validation/Rf2ValidationIssueReporter.java
fossabot/snow-owl
238f4e481d6ba762eeaa5c7185fbd9bedd81918a
[ "Apache-2.0" ]
null
null
null
29.684211
129
0.757979
4,474
/* * Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.datastore.request.rf2.validation; import java.util.Collection; import org.slf4j.Logger; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; /** * @since 7.0 */ public final class Rf2ValidationIssueReporter { private static final int MAX_NUMBER_OF_VALIDATION_PROBLEMS = 100; private Multimap<Rf2ValidationType, String> validationProblems = ArrayListMultimap.create(2, MAX_NUMBER_OF_VALIDATION_PROBLEMS); public void error(String message, Object...args) { if (getNumberOfErrors() < MAX_NUMBER_OF_VALIDATION_PROBLEMS) { validationProblems.put(Rf2ValidationType.ERROR, String.format(message, args)); } } public void warning(String message, Object...args) { if (getNumberOfWarnings() < MAX_NUMBER_OF_VALIDATION_PROBLEMS) { validationProblems.put(Rf2ValidationType.WARNING, String.format(message, args)); } } public int getNumberOfErrors() { return getErrors().size(); } public int getNumberOfWarnings() { return getWarnings().size(); } public Collection<String> getErrors() { return ImmutableList.copyOf(validationProblems.get(Rf2ValidationType.ERROR)); } public Collection<String> getWarnings() { return ImmutableList.copyOf(validationProblems.get(Rf2ValidationType.WARNING)); } public Collection<String> getIssues() { return ImmutableList.copyOf(validationProblems.values()); } public void logWarnings(Logger log) { getWarnings().forEach(log::warn); } public void logErrors(Logger log) { getErrors().forEach(log::error); } }
3e0a92cba91bccfb7eb178fa6e476b7d0de37ee1
8,278
java
Java
myFrame/src/com/vission/mf/base/sellms/smscompinfo/service/SmsCompInfoService.java
vission18/test
d77bc4ba1f56d9544285ffb90f430978bdcec473
[ "Apache-2.0" ]
null
null
null
myFrame/src/com/vission/mf/base/sellms/smscompinfo/service/SmsCompInfoService.java
vission18/test
d77bc4ba1f56d9544285ffb90f430978bdcec473
[ "Apache-2.0" ]
null
null
null
myFrame/src/com/vission/mf/base/sellms/smscompinfo/service/SmsCompInfoService.java
vission18/test
d77bc4ba1f56d9544285ffb90f430978bdcec473
[ "Apache-2.0" ]
null
null
null
28.743056
86
0.634574
4,475
package com.vission.mf.base.sellms.smscompinfo.service; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.vission.mf.base.exception.ServiceException; import com.vission.mf.base.hibernate.CriteriaSetup; import com.vission.mf.base.model.bo.DataGrid; import com.vission.mf.base.sellms.smscompinfo.dao.SmsCompInfoDao; import com.vission.mf.base.sellms.smscompinfo.po.SmsCompInfo; import com.vission.mf.base.service.BaseService; import com.vission.mf.base.util.POIUtil; /** * 作者:acf * 描述:SmsCompInfoService 业务逻辑处理 * 日期:2019-6-21 9:29:04 * 类型:SERVICE文件 */ @Service("smscompinfoService") @Transactional public class SmsCompInfoService extends BaseService { @Autowired private SmsCompInfoDao smscompinfoDao; /** * 分页数据列表 */ @Transactional(readOnly = true) public DataGrid dataGrid(SmsCompInfo po, int pageNo, int pageSize) { DataGrid dataGrid = new DataGrid(); dataGrid.setStartRow((pageNo - 1) * pageSize); Map<String, Object> filterMap = new HashMap<String, Object>(); setupFilterMap(po, filterMap); // 将查询条件对象拆分成 将对象型查询条件拆分成集合型查询条件 Map<String, String> orderMap = new HashMap<String, String>(1); orderMap.put("busiType", CriteriaSetup.ASC); dataGrid = smscompinfoDao.findByCriteria(dataGrid, pageSize, filterMap, orderMap); return dataGrid;// 空对象 页尺寸 map类型的查询条件 查询条件 } /** * 新增查询条件 */ private void setupFilterMap(SmsCompInfo po, Map<String, Object> filterMap) { if (po.getPkId() != null && !po.getPkId().trim().equals("") && !po.getPkId().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "pkId", po.getPkId()); } if (po.getBusiType() != null && !po.getBusiType().trim().equals("") && !po.getBusiType().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "busiType", po.getBusiType()); } if (po.getCompName() != null && !po.getCompName().trim().equals("") && !po.getCompName().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "compName", po.getCompName()); } if (po.getCompLegal() != null && !po.getCompLegal().trim().equals("") && !po.getCompLegal().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "compLegal", po.getCompLegal()); } if (po.getCompMoney() != null && !po.getCompMoney().trim().equals("") && !po.getCompMoney().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "compMoney", po.getCompMoney()); } if (po.getCompDate() != null && !po.getCompDate().trim().equals("") && !po.getCompDate().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "compDate", po.getCompDate()); } if (po.getTelNumber() != null && !po.getTelNumber().trim().equals("") && !po.getTelNumber().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "telNumber", po.getTelNumber()); } if (po.getMobile() != null && !po.getMobile().trim().equals("") && !po.getMobile().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "mobile", po.getMobile()); } if (po.getCompAdd() != null && !po.getCompAdd().trim().equals("") && !po.getCompAdd().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "compAdd", po.getCompAdd()); } if (po.getCompWeb() != null && !po.getCompWeb().trim().equals("") && !po.getCompWeb().trim().equals("null")) { filterMap.put(CriteriaSetup.LIKE_ALL + "compWeb", po.getCompWeb()); } } @Transactional(readOnly = true) public SmsCompInfo getSmsCompInfoById(String pkId) { return smscompinfoDao.get(pkId); } /** * 删除 */ public void deleteSmsCompInfoById(String pkId) throws ServiceException { this.smscompinfoDao.delete(this.getSmsCompInfoById(pkId)); } /** * 保存 */ public void saveSmsCompInfo(SmsCompInfo po) throws ServiceException { this.smscompinfoDao.save(po); } /** * 批量上传 * @param in * @param request * @return * @throws ServiceException */ public List<SmsCompInfo> saveBacthCompInfo(InputStream in,HttpServletRequest request) throws ServiceException { List<SmsCompInfo> list0 = new ArrayList<SmsCompInfo>();//存在重复的公司名称 List<SmsCompInfo> list1 = new ArrayList<SmsCompInfo>();//存储Excel的公司名称 try { List<List<String>> result = new ArrayList<List<String>>(); result = POIUtil.readExcel07(in, 0, 1, 0, 10); in.close(); for (int i = 0; i < result.size(); i++) { List<String> row = result.get(i); SmsCompInfo compInfo = new SmsCompInfo(); compInfo.setBusiType("99"); /* if (row.get(0) != null) { compInfo.setBusiType(row.get(0)); }*/ if (row.get(0) != null) { compInfo.setCompName(row.get(0)); } if (row.get(1) != null) { compInfo.setCompLegal(row.get(1)); } if (row.get(2) != null) { compInfo.setCompMoney(row.get(2)); } if (row.get(3) != null) { compInfo.setCompDate(row.get(3)); } if (row.get(4) != null) { String[] phoneArr = row.get(4).split(";"); if(phoneArr.length>1){ for(int p=0;p<phoneArr.length;p++){ String phoneStr = phoneArr[p].trim(); phoneStr = phoneStr.replaceAll(" ", ""); phoneStr = phoneStr.replaceAll(";", ""); if(phoneArr[p].startsWith("0")){ compInfo.setTelNumber(phoneArr[p].trim()); break; } } }else{ compInfo.setTelNumber(row.get(4)); } } if (row.get(5) != null) { String[] phoneArr = row.get(5).split(";"); if(phoneArr.length>1){ for(int p=0;p<phoneArr.length;p++){ String phoneStr = phoneArr[p].trim(); phoneStr = phoneStr.replaceAll(" ", ""); phoneStr = phoneStr.replaceAll(";", ""); if(phoneArr[p].startsWith("1")){ compInfo.setMobile(phoneStr); break; } } }else{ compInfo.setMobile(row.get(5)); } } if (row.get(6) != null) { compInfo.setCompAdd(row.get(6).trim()); } if (row.get(7) != null) { String[] webArr = row.get(7).split(";"); if(webArr.length>1){ compInfo.setCompWeb(webArr[0].trim()); }else{ compInfo.setCompWeb(row.get(7)); } } if (row.get(8) != null) { String[] emailArr = row.get(8).trim().split(";"); if(emailArr.length>1){ compInfo.setCompEmail(emailArr[0].trim()); }else{ compInfo.setCompEmail(row.get(8)); } } if (row.get(9) != null) { compInfo.setBusiScope(row.get(9).trim()); } if(compInfo.getMobile() == null || !compInfo.getMobile().startsWith("1")){ continue; } list1.add(compInfo); } }catch (Exception e) { if("Cannot get a text value from a numeric cell".equals(e.getMessage())){ throw new ServiceException("[请将所有单元格设置成文本格式]"); }else{ throw new ServiceException(e.getMessage()); } } list0 = uniqCompInfoList(list1)[0]; if (list0.size() <= 0) { //批量保存 List<SmsCompInfo> list = uniqCompInfoList(list1)[1]; for (int j = 0; j < list.size(); j++) { System.out.println("-------------------------"+list.get(j).getCompName()); this.smscompinfoDao.onlySave(list.get(j)); if (j % 50 == 0) { this.smscompinfoDao.getSession().flush(); this.smscompinfoDao.getSession().clear(); } } } return list0; } /** * 批量保存辅助 * @param list * @return * @throws ServiceException */ public List[] uniqCompInfoList(List<SmsCompInfo> list) throws ServiceException { List[] lists = new List[2]; Map<String, SmsCompInfo> map1 = new HashMap<String, SmsCompInfo>(); List<SmsCompInfo> repeatList = new ArrayList<SmsCompInfo>();//重复用户的集合 List<SmsCompInfo> result = new ArrayList<SmsCompInfo>();//排重后结果 for (int i = 0, j = list.size(); i < j; i++) { SmsCompInfo compInfo = list.get(i); //先判断是该指标是否已存在 if(map1.containsKey(compInfo.getCompName())){ repeatList.add(compInfo); }else{ //自动生成ID map1.put(compInfo.getCompName(), compInfo); result.add(compInfo); } } lists[0] = repeatList; lists[1] = result; return lists; } }
3e0a943ee5f20ac27ead10e642269c124ab39291
5,112
java
Java
src/main/java/com/pixelmed/scpecg/Section2.java
anniyanvr/nifi-dicom
f8616408bda79b3f18845fa156d2f623b6e8bcfc
[ "MIT" ]
8
2018-10-29T21:05:27.000Z
2022-01-10T04:48:17.000Z
src/main/java/com/pixelmed/scpecg/Section2.java
anniyanvr/nifi-dicom
f8616408bda79b3f18845fa156d2f623b6e8bcfc
[ "MIT" ]
null
null
null
src/main/java/com/pixelmed/scpecg/Section2.java
anniyanvr/nifi-dicom
f8616408bda79b3f18845fa156d2f623b6e8bcfc
[ "MIT" ]
10
2018-10-04T15:56:04.000Z
2021-05-14T12:17:25.000Z
37.588235
165
0.736111
4,476
/* Copyright (c) 2001-2017, David A. Clunie DBA Pixelmed Publishing. All rights reserved. */ package com.pixelmed.scpecg; import java.io.IOException; import java.util.ArrayList; import java.util.ListIterator; import java.util.TreeMap; import com.pixelmed.dicom.BinaryInputStream; /** * <p>A class to encapsulate the SCP-ECG Huffman Tables section.</p> * * @author dclunie */ public class Section2 extends Section { private static final String identString = "@(#) $Header: /userland/cvs/pixelmed/imgbook/com/pixelmed/scpecg/Section2.java,v 1.12 2017/01/24 10:50:47 dclunie Exp $"; /** * <p>Get a string name for this section.</p> * * @return a string name for this section */ public String getSectionName() { return "Huffman Tables"; } private int numberOfHuffmanTables; private ArrayList huffmanTablesList; // of class HuffmanTable public int getNumberOfHuffmanTables() { return numberOfHuffmanTables; } static public boolean useDefaultTable(int numberOfHuffmanTables) { return numberOfHuffmanTables == 19999; } public boolean useDefaultTable() { return useDefaultTable(numberOfHuffmanTables); } public boolean useNoTable() { return numberOfHuffmanTables == 0; } // Hmmm ... should really be indicate by absence of this section public int getNumberOfEncodedHuffmanTables() { return huffmanTablesList == null ? 0 : huffmanTablesList.size(); } public ArrayList getHuffmanTables() { return huffmanTablesList; } public Section2(SectionHeader header) { super(header); } public long read(BinaryInputStream i) throws IOException { numberOfHuffmanTables=i.readUnsigned16(); bytesRead+=2; sectionBytesRemaining-=2; // /Users/dclunie/Documents/Medical/stuff/ECG/OpenECG/Data/Files/101.scp has bytes after 19999 // /Users/dclunie/Documents/Medical/stuff/ECG/OpenECG/Data/Files/112.scp actually has a huffman table if ((useDefaultTable() || useNoTable()) && sectionBytesRemaining != 0) { System.err.println("Section 2 Number Of Huffman Tables ="+numberOfHuffmanTables+" dec, but " +sectionBytesRemaining+" more bytes(code structures) in section are present - ignoring them"); skipToEndOfSectionIfNotAlreadyThere(i); } while (sectionBytesRemaining > 0) { int numberOfCodeStructures = i.readUnsigned16(); bytesRead+=2; sectionBytesRemaining-=2; int[] numberOfBitsInPrefix = new int[numberOfCodeStructures]; int[] numberOfBitsInEntireCode = new int[numberOfCodeStructures]; int[] tableModeSwitch = new int[numberOfCodeStructures]; int[] baseValueRepresentedByBaseCode = new int[numberOfCodeStructures]; long[] baseCode = new long[numberOfCodeStructures]; for (int codeStructure=0; codeStructure<numberOfCodeStructures; ++codeStructure) { numberOfBitsInPrefix[codeStructure] = i.readUnsigned8(); bytesRead++; sectionBytesRemaining--; numberOfBitsInEntireCode[codeStructure] = i.readUnsigned8(); bytesRead++; sectionBytesRemaining--; tableModeSwitch[codeStructure] = i.readUnsigned8(); bytesRead++; sectionBytesRemaining--; baseValueRepresentedByBaseCode[codeStructure] = i.readUnsigned16(); bytesRead+=2; sectionBytesRemaining-=2; baseCode[codeStructure] = i.readUnsigned32(); bytesRead+=4; sectionBytesRemaining-=4; } if (huffmanTablesList == null) { huffmanTablesList = new ArrayList(); } huffmanTablesList.add(new HuffmanTable(numberOfCodeStructures,numberOfBitsInPrefix,numberOfBitsInEntireCode, tableModeSwitch,baseValueRepresentedByBaseCode,baseCode)); } if (!useDefaultTable() && numberOfHuffmanTables != getNumberOfEncodedHuffmanTables()) { System.err.println("Section 2 Number Of Huffman Tables specified as " +numberOfHuffmanTables+" but encountered "+getNumberOfEncodedHuffmanTables()); } skipToEndOfSectionIfNotAlreadyThere(i); return bytesRead; } public String toString() { StringBuffer strbuf = new StringBuffer(); strbuf.append("Number of Huffman Tables = "+numberOfHuffmanTables+" dec (0x"+Integer.toHexString(numberOfHuffmanTables)+")"); strbuf.append((useDefaultTable() ? " DEFAULT" : "")+"\n"); if (huffmanTablesList != null) { ListIterator i = huffmanTablesList.listIterator(); while (i.hasNext()) { strbuf.append("Table Number = "+i.nextIndex()+"\n"); HuffmanTable t = (HuffmanTable)(i.next()); strbuf.append(t); } } return strbuf.toString(); } public String validate() { return ""; } /** * <p>Get the contents of the section as a tree for display, constructing it if not already done.</p> * * @param parent the node to which this section is to be added if it needs to be created de novo * @return the section as a tree */ public SCPTreeRecord getTree(SCPTreeRecord parent) { if (tree == null) { SCPTreeRecord tree = new SCPTreeRecord(parent,"Section",getValueForSectionNodeInTree()); addSectionHeaderToTree(tree); new SCPTreeRecord(tree,"Number of Huffman Tables",Long.toString(numberOfHuffmanTables)+" dec (0x"+Long.toHexString(numberOfHuffmanTables)+")"+ (useDefaultTable() ? " DEFAULT" : "")); } return tree; } }
3e0a944a80392228708ffa63c538030a7df0202f
962
java
Java
StudentManagementSystem/src/main/java/com/netizenbd/springbootApp/controller/ClassRoutineController.java
msekh/NetizenIT
75fa5318f5bdbedee4b71608401184e41ffb2960
[ "MIT" ]
null
null
null
StudentManagementSystem/src/main/java/com/netizenbd/springbootApp/controller/ClassRoutineController.java
msekh/NetizenIT
75fa5318f5bdbedee4b71608401184e41ffb2960
[ "MIT" ]
null
null
null
StudentManagementSystem/src/main/java/com/netizenbd/springbootApp/controller/ClassRoutineController.java
msekh/NetizenIT
75fa5318f5bdbedee4b71608401184e41ffb2960
[ "MIT" ]
null
null
null
34.357143
70
0.821206
4,477
package com.netizenbd.springbootApp.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.netizenbd.springbootApp.entity.ClassRoutine; import com.netizenbd.springbootApp.repository.ClassRoutineRepository; import com.netizenbd.springbootApp.service.ClassRoutineServiceImpl; @RestController @RequestMapping("/class_routine") public class ClassRoutineController { @Autowired private ClassRoutineRepository repo; @Autowired private ClassRoutineServiceImpl service; @GetMapping("/all_class_routine_list") public ResponseEntity<List<ClassRoutine>> getAllClassRoutine() { return ResponseEntity.ok().body(this.service.getAllRoutines()); } }
3e0a94fe06f0a6edbddb11e5f7fcbffc5d2d64d8
2,373
java
Java
tools/closure-compiler/trunk/src/com/google/javascript/jscomp/JoinOp.java
rlugojr/jsrepl
abf72e7a221e12acea344e5ea53579a502236f15
[ "MIT" ]
36
2018-07-03T13:05:00.000Z
2022-03-11T11:10:54.000Z
src/com/google/javascript/jscomp/JoinOp.java
pietrobraione/sushi-experiments-closure72
3f687f25787d319a9d77e75b14dfff14731ff67e
[ "Apache-2.0" ]
null
null
null
src/com/google/javascript/jscomp/JoinOp.java
pietrobraione/sushi-experiments-closure72
3f687f25787d319a9d77e75b14dfff14731ff67e
[ "Apache-2.0" ]
19
2018-06-24T15:41:33.000Z
2022-03-13T10:41:39.000Z
31.223684
75
0.646439
4,478
/* * Copyright 2010 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Function; import com.google.common.base.Preconditions; import java.util.List; /** * Defines a way join a list of LatticeElements. */ interface JoinOp<L extends LatticeElement> extends Function<List<L>, L> { /** * An implementation of {@code JoinOp} that makes it easy to join to * lattice elements at a time. */ static abstract class BinaryJoinOp<L extends LatticeElement> implements JoinOp<L> { @Override public final L apply(List<L> values) { Preconditions.checkArgument(!values.isEmpty()); int size = values.size(); if (size == 1) { return values.get(0); } else if (size == 2) { return apply(values.get(0), values.get(1)); } else { int mid = computeMidPoint(size); return apply( apply(values.subList(0, mid)), apply(values.subList(mid, size))); } } /** * Creates a new lattice that will be the join of two input lattices. * * @return The join of {@code latticeA} and {@code latticeB}. */ abstract L apply(L latticeA, L latticeB); /** * Finds the midpoint of a list. The function will favor two lists of * even length instead of two lists of the same odd length. The list * must be at least length two. * * @param size Size of the list. */ static int computeMidPoint(int size) { int midpoint = size >>> 1; if (size > 4) { /* Any list longer than 4 should prefer an even split point * over the true midpoint, so that [0,6] splits at 2, not 3. */ midpoint &= -2; // (0xfffffffe) clears low bit so midpoint is even } return midpoint; } } }
3e0a9529e8276866d527dc31e893108a0f816f27
1,421
java
Java
src/test/java/org/oakgp/function/coll/CountTest.java
s-webber/oakgp
269b325ca6d457310f65ccdca3839f203df02f52
[ "Apache-2.0" ]
5
2016-05-22T19:55:27.000Z
2022-02-09T05:36:13.000Z
src/test/java/org/oakgp/function/coll/CountTest.java
webber-s/oakgp
269b325ca6d457310f65ccdca3839f203df02f52
[ "Apache-2.0" ]
8
2015-11-14T10:10:49.000Z
2018-08-19T14:26:39.000Z
src/test/java/org/oakgp/function/coll/CountTest.java
webber-s/oakgp
269b325ca6d457310f65ccdca3839f203df02f52
[ "Apache-2.0" ]
1
2021-01-13T08:43:35.000Z
2021-01-13T08:43:35.000Z
29
108
0.701619
4,479
/* * Copyright 2015 S. Webber * * 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.oakgp.function.coll; import static org.oakgp.Type.integerType; import java.util.Collections; import org.oakgp.Type; import org.oakgp.function.AbstractFunctionTest; import org.oakgp.node.ConstantNode; public class CountTest extends AbstractFunctionTest { @Override protected Count getFunction() { return new Count(integerType()); } @Override public void testEvaluate() { ConstantNode emptyList = new ConstantNode(Collections.emptyList(), Type.listType(Type.integerType())); evaluate("(count v0)").assigned(emptyList).to(0); evaluate("(count [2 -12 8])").to(3); evaluate("(count [2 -12 8 -3 -7])").to(5); } @Override public void testCanSimplify() { simplify("(count [2 -12 8])").to("3"); } @Override public void testCannotSimplify() { } }
3e0a95970bffbab9d465c8badc0405c432101cf5
7,634
java
Java
app/src/main/java/com/example/distancemeasurement/methods/WifiAware.java
haswell4u/android-D2D-DistanceMeasurement
d4cbf3f45716360f603ba8a46efb3eee2f093999
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/distancemeasurement/methods/WifiAware.java
haswell4u/android-D2D-DistanceMeasurement
d4cbf3f45716360f603ba8a46efb3eee2f093999
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/distancemeasurement/methods/WifiAware.java
haswell4u/android-D2D-DistanceMeasurement
d4cbf3f45716360f603ba8a46efb3eee2f093999
[ "Apache-2.0" ]
null
null
null
40.823529
100
0.635578
4,480
package com.example.distancemeasurement.methods; import android.content.Context; import android.content.SharedPreferences; import android.net.wifi.aware.AttachCallback; import android.net.wifi.aware.DiscoverySessionCallback; import android.net.wifi.aware.PeerHandle; import android.net.wifi.aware.PublishConfig; import android.net.wifi.aware.PublishDiscoverySession; import android.net.wifi.aware.SubscribeConfig; import android.net.wifi.aware.SubscribeDiscoverySession; import android.net.wifi.aware.WifiAwareManager; import android.net.wifi.aware.WifiAwareSession; import android.util.Log; import androidx.preference.PreferenceManager; import com.example.distancemeasurement.Constants; import com.example.distancemeasurement.Device; import com.example.distancemeasurement.MeasurementService; import com.example.distancemeasurement.R; import com.example.distancemeasurement.Utils; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class WifiAware { private MeasurementService mMeasurementService; private SharedPreferences mSharedPreferences; private WifiAwareManager mWifiAwareManager; private WifiAwareSession mWifiAwareSession; private PublishDiscoverySession mPublishDiscoverySession; private SubscribeDiscoverySession mSubscribeDiscoverySession; private Timer mTimer; public WifiAware(MeasurementService service) { mMeasurementService = service; mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mMeasurementService); mWifiAwareManager = (WifiAwareManager) mMeasurementService .getSystemService(Context.WIFI_AWARE_SERVICE); mTimer = new Timer(); obtainSession(); } private void obtainSession() { if (mWifiAwareManager.isAvailable()) mWifiAwareManager.attach(new AttachCallback() { @Override public void onAttached(WifiAwareSession session) { super.onAttached(session); mWifiAwareSession = session; mMeasurementService.sendMessage(mMeasurementService .getString(R.string.message_wifi_aware_obtain_session)); publishService(); subscribeService(); } }, null); else mMeasurementService.sendError(mMeasurementService .getString(R.string.message_wifi_aware_state_changed)); } private void publishService() { PublishConfig config = new PublishConfig.Builder() .setServiceSpecificInfo(Utils.dataEncoding(mSharedPreferences .getString(Constants.PREFERENCES_NAME_DEVICE_ID, Constants.PREFERENCES_DEFAULT_STRING))) .setServiceName(Constants.WIFI_AWARE_SERVICE_NAME) .build(); mWifiAwareSession.publish(config, new DiscoverySessionCallback() { @Override public void onPublishStarted(PublishDiscoverySession session) { mPublishDiscoverySession = session; mMeasurementService.sendMessage(mMeasurementService .getString(R.string.message_wifi_aware_publish_service)); } @Override public void onMessageReceived(PeerHandle peerHandle, byte[] message) { super.onMessageReceived(peerHandle, message); mPublishDiscoverySession.sendMessage(peerHandle, Constants.WIFI_AWARE_CHECK_ALIVE_ID, Utils.dataEncoding(mSharedPreferences .getString(Constants.PREFERENCES_NAME_DEVICE_ID, Constants.PREFERENCES_DEFAULT_STRING))); } }, null); } private void subscribeService() { SubscribeConfig config = new SubscribeConfig.Builder() .setServiceName(Constants.WIFI_AWARE_SERVICE_NAME) .build(); mWifiAwareSession.subscribe(config, new DiscoverySessionCallback() { @Override public void onSubscribeStarted(SubscribeDiscoverySession session) { mSubscribeDiscoverySession = session; mMeasurementService.sendMessage(mMeasurementService .getString(R.string.message_wifi_aware_subscribe_service)); } @Override public void onServiceDiscovered(PeerHandle peerHandle, byte[] serviceSpecificInfo, List<byte[]> matchFilter) { String id = Utils.dataDecoding(serviceSpecificInfo); synchronized (mMeasurementService.mPeerHandleList) { if (!mMeasurementService.mPeerHandleList.containsKey(id)) { mMeasurementService.mPeerHandleList.put(id, peerHandle); mMeasurementService.sendMessage(createFindUserMessage(id)); } else mMeasurementService.mPeerHandleList.replace(id, peerHandle); } } @Override public void onMessageReceived(PeerHandle peerHandle, byte[] message) { super.onMessageReceived(peerHandle, message); ArrayList<Device> list = new ArrayList<Device>(); list.add(createDevice(Utils.dataDecoding(message))); mMeasurementService.sendMessage(createFindUserMessage(Utils.dataDecoding(message))); mMeasurementService.sendDevice(list); } }, null); } public void checkAlive() { long interval = Long.parseLong(mSharedPreferences .getString(Constants.PREFERENCES_NAME_REFRESH, Constants.PREFERENCES_DEFAULT_STRING)); mTimer.schedule(new TimerTask() { @Override public void run() { synchronized (mMeasurementService.mPeerHandleList) { for (String id : mMeasurementService.mPeerHandleList.keySet()) mSubscribeDiscoverySession.sendMessage( mMeasurementService.mPeerHandleList.get(id), Constants.WIFI_AWARE_CHECK_ALIVE_ID, Utils.dataEncoding(mSharedPreferences .getString(Constants.PREFERENCES_NAME_DEVICE_ID, Constants.PREFERENCES_DEFAULT_STRING))); } } }, interval, interval); } public Device createDevice(String id) { long time = System.currentTimeMillis(); return new Device(id, time); } private String createFindUserMessage(String id) { StringBuffer str = new StringBuffer(mMeasurementService .getString(R.string.message_device_find)); str.insert(Constants.OFFSET_MESSAGE_DEVICE_FOUND_REMOVED, id); str.append(" (WiFi Aware)"); return str.toString(); } public void close() { mTimer.cancel(); if (mSubscribeDiscoverySession != null) mSubscribeDiscoverySession.close(); if (mPublishDiscoverySession != null) mPublishDiscoverySession.close(); if (mWifiAwareSession != null) { mWifiAwareSession.close(); mMeasurementService.sendMessage(mMeasurementService .getString(R.string.message_wifi_aware_close_session)); } } }
3e0a96022c97407512c618dcfe0e09acf288a206
1,090
java
Java
subsystems/MotorTest.java
team751/core751
fcecd2243dd046502e7374a51bc5fb738bd03749
[ "MIT" ]
null
null
null
subsystems/MotorTest.java
team751/core751
fcecd2243dd046502e7374a51bc5fb738bd03749
[ "MIT" ]
3
2020-01-12T10:26:42.000Z
2020-02-12T23:33:58.000Z
subsystems/MotorTest.java
team751/core751
fcecd2243dd046502e7374a51bc5fb738bd03749
[ "MIT" ]
null
null
null
24.772727
69
0.611009
4,481
package frc.robot.core751.subsystems; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.TalonFXControlMode; import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class MotorTest extends SubsystemBase{ public enum motType { Falcon500, Neo, CIM; } int id; motType mType; public MotorTest(motType mType,int id){ this.mType = mType; this.id = id; } public void set(double speed){ switch(mType){ case Falcon500: WPI_TalonFX talon = new WPI_TalonFX(id); talon.configFactoryDefault(); talon.stopMotor(); talon.set(ControlMode.PercentOutput, speed); break; case Neo: new CANSparkMax(id, MotorType.kBrushless).set(speed); break; case CIM: break; } } }
3e0a96987e6fe6b17947de99484b8819dab2ccd3
7,137
java
Java
main/test/mockit/FakingTest.java
Godin/jmockit1
15ad16b1d6aaf738014f36bcc748b7a16c6b835e
[ "MIT" ]
463
2015-01-04T11:23:49.000Z
2022-03-25T08:31:04.000Z
main/test/mockit/FakingTest.java
Godin/jmockit1
15ad16b1d6aaf738014f36bcc748b7a16c6b835e
[ "MIT" ]
609
2015-01-02T14:13:16.000Z
2022-03-31T15:12:20.000Z
main/test/mockit/FakingTest.java
Godin/jmockit1
15ad16b1d6aaf738014f36bcc748b7a16c6b835e
[ "MIT" ]
267
2015-01-02T15:46:50.000Z
2022-03-18T10:29:27.000Z
26.932075
139
0.606277
4,482
package mockit; import java.awt.*; import java.lang.reflect.*; import java.rmi.*; import java.util.concurrent.atomic.*; import javax.accessibility.AccessibleContext; import javax.sound.midi.*; import javax.swing.*; import javax.swing.plaf.basic.*; import org.junit.*; import org.junit.rules.*; import static org.junit.Assert.*; public final class FakingTest { @Rule public final ExpectedException thrown = ExpectedException.none(); @Test public void attemptToApplyFakeWithoutTheTargetType() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("No target type"); new MockUp() {}; } // Fakes for classes /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Test public void fakeAClass() { new MockUp<Panel>() { @Mock int getComponentCount() { return 123; } }; assertEquals(123, new Panel().getComponentCount()); } static final class Main { static final AtomicIntegerFieldUpdater<Main> atomicCount = AtomicIntegerFieldUpdater.newUpdater(Main.class, "count"); volatile int count; int max = 2; boolean increment() { while (true) { int currentCount = count; if (currentCount >= max) { return false; } if (atomicCount.compareAndSet(this, currentCount, currentCount + 1)) { return true; } } } } @Test public void fakeAGivenClass() { final Main main = new Main(); new MockUp<AtomicIntegerFieldUpdater<?>>(Main.atomicCount.getClass()) { boolean second; @Mock public boolean compareAndSet(Object obj, int expect, int update) { assertSame(main, obj); assertEquals(0, expect); assertEquals(1, update); if (second) { return true; } second = true; return false; } }; assertTrue(main.increment()); } @Test public void attemptToFakeGivenClassButPassNull() { thrown.expect(NullPointerException.class); new MockUp<Panel>(null) {}; } @SuppressWarnings("rawtypes") static class FakeForGivenClass extends MockUp { @SuppressWarnings("unchecked") FakeForGivenClass() { super(Panel.class); } @Mock String getName() { return "mock"; } } @Test public void fakeGivenClassUsingNamedFake() { new FakeForGivenClass(); String s = new Panel().getName(); assertEquals("mock", s); } // Fakes for other situations ////////////////////////////////////////////////////////////////////////////////////////////////////////// @Test public <M extends Panel & Runnable> void attemptToFakeClassAndInterfaceAtOnce() { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("Unable to capture"); new MockUp<M>() { @Mock String getName() { return ""; } @Mock void run() {} }; } @Test public void fakeUsingInvocationParameters() { new MockUp<Panel>() { @Mock void $init(Invocation inv) { Panel it = inv.getInvokedInstance(); assertNotNull(it); } @Mock int getBaseline(Invocation inv, int w, int h) { return inv.proceed(); } }; int i = new Panel().getBaseline(20, 15); assertEquals(-1, i); } public static class PublicNamedFakeWithNoInvocationParameters extends MockUp<Panel> { boolean executed; @Mock public void $init() { executed = true; } @Mock public String getName() { return "test"; } } @Test public void publicNamedFakeWithNoInvocationParameter() { PublicNamedFakeWithNoInvocationParameters fake = new PublicNamedFakeWithNoInvocationParameters(); Panel applet = new Panel(); assertTrue(fake.executed); String name = applet.getName(); assertEquals("test", name); } @Test @SuppressWarnings("deprecation") public void fakingOfAnnotatedClass() throws Exception { new MockUp<RMISecurityException>() { @Mock void $init(String s) { assertNotNull(s); } }; assertTrue(RMISecurityException.class.isAnnotationPresent(Deprecated.class)); Constructor<RMISecurityException> aConstructor = RMISecurityException.class.getDeclaredConstructor(String.class); assertTrue(aConstructor.isAnnotationPresent(Deprecated.class)); Deprecated deprecated = aConstructor.getAnnotation(Deprecated.class); assertNotNull(deprecated); } @Test public void fakeSameClassTwiceUsingSeparateFakes() { Panel a = new Panel(); class Fake1 extends MockUp<Panel> { @Mock void addNotify() {} } new Fake1(); a.addNotify(); new MockUp<Panel>() { @Mock AccessibleContext getAccessibleContext() { return null; } }; a.addNotify(); // still faked a.getAccessibleContext(); } @Test public void fakeConstructorOfInnerClass() { final BasicColorChooserUI outer = new BasicColorChooserUI(); final boolean[] constructed = {false}; new MockUp<BasicColorChooserUI.PropertyHandler>() { @Mock void $init(BasicColorChooserUI o) { assertSame(outer, o); constructed[0] = true; } }; outer.new PropertyHandler(); assertTrue(constructed[0]); } @Test public void callFakeMethodFromAWTEventDispatchingThread() throws Exception { new MockUp<Panel>() { @Mock int getComponentCount() { return 10; } }; SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int i = new Panel().getComponentCount(); assertEquals(10, i); } }); } static final class JRESubclass extends Patch { JRESubclass(int i, int j) { super(i, j); } } @Test public void anonymousFakeForJRESubclassHavingFakeMethodForJREMethod() { new MockUp<JRESubclass>() { @Mock int getBank() { return 123; } }; Patch t = new JRESubclass(1, 2); int i = t.getBank(); assertEquals(123, i); } static Boolean fakeTornDown; static final class FakeWithActionOnTearDown extends MockUp<Panel> { @Override protected void onTearDown() { fakeTornDown = true; } } @Test public void performActionOnFakeTearDown() { fakeTornDown = false; new FakeWithActionOnTearDown(); assertFalse(fakeTornDown); } @AfterClass public static void verifyFakeAppliedInTestWasTornDown() { assertTrue(fakeTornDown == null || fakeTornDown); } @Test public void fakeVarargsMethodWithProceedingFakeMethodWhichPassesReplacementArguments() { new MockUp<ProcessBuilder>() { @Mock ProcessBuilder command(Invocation inv, String... command) { String[] newArgs = {"replaced"}; return inv.proceed((Object) newArgs); } }; new ProcessBuilder().command("test", "something"); } }
3e0a9705203acb9d6a2ce0cdb1662defc5b16b0f
6,248
java
Java
src/main/java/com/bric/io/FileTreeIterator.java
javagraphics/main
582aada63bfe936e0b49a9d105099401c06d6225
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
src/main/java/com/bric/io/FileTreeIterator.java
javagraphics/main
582aada63bfe936e0b49a9d105099401c06d6225
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
src/main/java/com/bric/io/FileTreeIterator.java
javagraphics/main
582aada63bfe936e0b49a9d105099401c06d6225
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
30.930693
87
0.68822
4,483
/* * @(#)FileTreeIterator.java * * $Date: 2015-11-03 14:51:57 +0100 (Di, 03 Nov 2015) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * https://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package com.bric.io; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Vector; import com.bric.util.TreeIterator; /** This iterates through a file tree structure. */ public class FileTreeIterator extends TreeIterator<File> { /** This finds the first file in the directory that matches * the name provided. * @param dir * @param fileName * @return a file nested inside dir that matches the file name provided, * or null if no such file is found. */ public static File find(File dir,String fileName) { if(dir==null) throw new NullPointerException(); FileTreeIterator iter = new FileTreeIterator(dir); while(iter.hasNext()) { File f = iter.next(); if(f.getName().equals(fileName)) return f; } return null; } /** This finds all files in the directory that match * the exact name provided. * @param dir the directories to search in. Null elements * in this array are skipped, but if the array itself is null then * a <code>NullPointerException</code> is thrown. * @param fileName the exact file name to search for. * @return files nested inside dir that satisfy this search. * This may return an empty array but will not return null. */ public static File[] findAll(File[] dir,String fileName) { if(dir==null) throw new NullPointerException(); if(fileName==null) throw new NullPointerException(); Vector<File> results = new Vector<File>(); for(File d : dir) { if(d!=null) { FileTreeIterator iter = new FileTreeIterator(d); while(iter.hasNext()) { File f = iter.next(); if(f.getName().equals(fileName)) { results.add(f); } } } } return results.toArray(new File[results.size()]); } /** This finds all files in the directory that match * the name provided. * @param dir the directories to search in. Null elements * in this array are skipped, but if the array itself is null then * a <code>NullPointerException</code> is thrown. * @param fileBaseName the name of the file without the file extension * @param fileExtensions the file extensions search check against. * @return files nested inside dir that satisfy this search. * This may return an empty array but will not return null. */ public static File[] findAll(File[] dir,String fileBaseName,String[] fileExtensions) { if(dir==null) throw new NullPointerException(); Vector<File> results = new Vector<File>(); for(File d : dir) { if(d!=null) { FileTreeIterator iter = new FileTreeIterator(d, fileExtensions); while(iter.hasNext()) { File f = iter.next(); String name = f.getName(); int i = name.lastIndexOf('.'); if(i!=-1) { name = name.substring(0, i); } if(name.equals(fileBaseName)) { results.add(f); } } } } return results.toArray(new File[results.size()]); } public final FileFilter fileFilter; /** Creates a new <code>FileTreeIterator</code> * * @param parent the root file to begin searching in. * For best results this should be parent.getCanonicalFile(). Otherwise * case sensitivity might accidentally result in some files being flagged * as aliases. (That is: if the user inputs a file path in a case insensitive * manner, and then we call isAlias(myFile), it may return a false positive.) * @param filter the filter determining what files to list. */ public FileTreeIterator(File parent,FileFilter filter) { super(parent, true); this.fileFilter = filter; } /** Creates a new <code>FileTreeIterator</code>. * * @param parent the root file to begin searching in. * For best results this should be parent.getCanonicalFile(). Otherwise * case sensitivity might accidentally result in some files being flagged * as aliases. (That is: if the user inputs a file path in a case insensitive * manner, and then we call isAlias(myFile), it may return a false positive.) * @param extensions the file name extensions to search for. */ public FileTreeIterator(File parent,String... extensions) { this(parent,new SuffixFilenameFilter(extensions)); } /** Creates a new <code>FileTreeIterator</code> that * iterates over every non-directory file in this tree. * * @param parent the root file to begin searching in. */ public FileTreeIterator(File parent) { this(parent,(FileFilter)null); } @Override protected File[] listChildren(File parent) { File[] f = parent==null ? null : parent.listFiles(); if(f==null) return null; for(int a = 0; a<f.length; a++) { if(isAlias(f[a])) f[a] = null; } return f; } @Override protected boolean isReturnValue(File node) { if(fileFilter==null) return true; return fileFilter.accept(node); } /** This checks to see if a <code>File</code> is * a symlink/alias. Unfortunately this is not * officially supported in the <code>File</code> method * signatures, so this uses a potentially awkward approach. */ public static boolean isAlias(File file) { try { if (!file.exists()) return false; else { String cnnpath = file.getCanonicalPath(); String abspath = file.getAbsolutePath(); if(cnnpath.startsWith("/private") && (!abspath.startsWith("/private"))) { cnnpath = cnnpath.substring("/private".length()); } //this is just a verbose path, but it's probably not an alias: if(abspath.endsWith(cnnpath) && abspath.startsWith("/Volumes/")) return false; boolean returnValue = !abspath.equals(cnnpath); return returnValue; } } catch(IOException ex) { return false; } } }
3e0a975e1b361978aa6e82edc2e696012a84f1e5
483
java
Java
src/main/java/com/piotrblachnio/reddit/dto/request/RefreshTokenRequest.java
PiotrBlachnio/Reddit-API
54b7e8261fd91fc02360f5325edeeb4d5a6a9fbe
[ "MIT" ]
null
null
null
src/main/java/com/piotrblachnio/reddit/dto/request/RefreshTokenRequest.java
PiotrBlachnio/Reddit-API
54b7e8261fd91fc02360f5325edeeb4d5a6a9fbe
[ "MIT" ]
null
null
null
src/main/java/com/piotrblachnio/reddit/dto/request/RefreshTokenRequest.java
PiotrBlachnio/Reddit-API
54b7e8261fd91fc02360f5325edeeb4d5a6a9fbe
[ "MIT" ]
null
null
null
28.411765
85
0.732919
4,484
package com.piotrblachnio.reddit.dto.request; import lombok.*; import javax.validation.constraints.*; @Data @AllArgsConstructor @NoArgsConstructor public class RefreshTokenRequest { @NotEmpty(message = "Refresh token cannot be empty") private String refreshToken; @Email(message = "Email should be valid") @Size(min = 5, max = 64, message = "Email should be between 5 and 64 characters") @NotEmpty(message = "Email cannot be empty") private String email; }
3e0a97c1e1b50d03260d8d3cce3521fddf58a0fe
1,338
java
Java
app/src/main/java/com/galtashma/lazyparse/MainActivity.java
cyb3rko/LazyParse
92881c0638f6353f8d3c5b5a633c7fa1d25562ec
[ "MIT" ]
2
2019-05-04T22:00:17.000Z
2019-05-05T10:44:07.000Z
app/src/main/java/com/galtashma/lazyparse/MainActivity.java
cyb3rko/LazyParse
92881c0638f6353f8d3c5b5a633c7fa1d25562ec
[ "MIT" ]
null
null
null
app/src/main/java/com/galtashma/lazyparse/MainActivity.java
cyb3rko/LazyParse
92881c0638f6353f8d3c5b5a633c7fa1d25562ec
[ "MIT" ]
1
2021-11-01T09:11:31.000Z
2021-11-01T09:11:31.000Z
33.45
143
0.715994
4,485
package com.galtashma.lazyparse; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ListView; import android.widget.Toast; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ParseQuery<WordLazy> query = new ParseQuery<WordLazy>(WordLazy.class); query.orderByAscending("value"); LazyList<WordLazy> list = new LazyList<>(query); WordListInfiniteAdapter adapter = new WordListInfiniteAdapter(this, list); ListView listView = findViewById(R.id.list_view); listView.setAdapter(adapter); listView.setOnScrollListener(new ScrollInfiniteListener(adapter)); adapter.setOnClickListener(new ScrollInfiniteAdapter.OnClickListener<WordLazy>() { @Override public void onClick(WordLazy object) { Toast.makeText(getApplicationContext(), "Clicked " + object.getObjectId() + " " + object.getWord(), Toast.LENGTH_SHORT).show(); } }); } }
3e0a97f40f2065b425b657ecc63cb3ddc9672341
4,452
java
Java
tagsync/src/main/java/org/apache/ranger/tagsync/source/atlas/AtlasHiveResourceMapper.java
philipjung164/ranger
07b293187838c00073a34ba63b50bbeff7069e89
[ "Apache-2.0" ]
555
2017-02-07T06:40:37.000Z
2022-03-30T12:02:27.000Z
tagsync/src/main/java/org/apache/ranger/tagsync/source/atlas/AtlasHiveResourceMapper.java
philipjung164/ranger
07b293187838c00073a34ba63b50bbeff7069e89
[ "Apache-2.0" ]
260
2021-03-23T19:15:32.000Z
2022-03-31T17:02:27.000Z
tagsync/src/main/java/org/apache/ranger/tagsync/source/atlas/AtlasHiveResourceMapper.java
philipjung164/ranger
07b293187838c00073a34ba63b50bbeff7069e89
[ "Apache-2.0" ]
605
2017-01-26T17:39:50.000Z
2022-03-30T12:02:33.000Z
44.52
129
0.768868
4,486
/* * 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.ranger.tagsync.source.atlas; import java.util.Map; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.model.RangerServiceResource; import org.apache.ranger.tagsync.source.atlasrest.RangerAtlasEntity; public class AtlasHiveResourceMapper extends AtlasResourceMapper { public static final String ENTITY_TYPE_HIVE_DB = "hive_db"; public static final String ENTITY_TYPE_HIVE_TABLE = "hive_table"; public static final String ENTITY_TYPE_HIVE_COLUMN = "hive_column"; public static final String RANGER_TYPE_HIVE_DB = "database"; public static final String RANGER_TYPE_HIVE_TABLE = "table"; public static final String RANGER_TYPE_HIVE_COLUMN = "column"; public static final String[] SUPPORTED_ENTITY_TYPES = { ENTITY_TYPE_HIVE_DB, ENTITY_TYPE_HIVE_TABLE, ENTITY_TYPE_HIVE_COLUMN }; public AtlasHiveResourceMapper() { super("hive", SUPPORTED_ENTITY_TYPES); } @Override public RangerServiceResource buildResource(final RangerAtlasEntity entity) throws Exception { String qualifiedName = (String)entity.getAttributes().get(AtlasResourceMapper.ENTITY_ATTRIBUTE_QUALIFIED_NAME); if (StringUtils.isEmpty(qualifiedName)) { throw new Exception("attribute '" + ENTITY_ATTRIBUTE_QUALIFIED_NAME + "' not found in entity"); } String resourceStr = getResourceNameFromQualifiedName(qualifiedName); if (StringUtils.isEmpty(resourceStr)) { throwExceptionWithMessage("resource not found in attribute '" + ENTITY_ATTRIBUTE_QUALIFIED_NAME + "': " + qualifiedName); } String clusterName = getClusterNameFromQualifiedName(qualifiedName); if (StringUtils.isEmpty(clusterName)) { throwExceptionWithMessage("cluster-name not found in attribute '" + ENTITY_ATTRIBUTE_QUALIFIED_NAME + "': " + qualifiedName); } String entityType = entity.getTypeName(); String entityGuid = entity.getGuid(); String serviceName = getRangerServiceName(clusterName); String[] resources = resourceStr.split(QUALIFIED_NAME_DELIMITER); String dbName = resources.length > 0 ? resources[0] : null; String tblName = resources.length > 1 ? resources[1] : null; String colName = resources.length > 2 ? resources[2] : null; Map<String, RangerPolicyResource> elements = new HashMap<String, RangerPolicyResource>(); if (StringUtils.equals(entityType, ENTITY_TYPE_HIVE_DB)) { if (StringUtils.isNotEmpty(dbName)) { elements.put(RANGER_TYPE_HIVE_DB, new RangerPolicyResource(dbName)); } } else if (StringUtils.equals(entityType, ENTITY_TYPE_HIVE_TABLE)) { if (StringUtils.isNotEmpty(dbName) && StringUtils.isNotEmpty(tblName)) { elements.put(RANGER_TYPE_HIVE_DB, new RangerPolicyResource(dbName)); elements.put(RANGER_TYPE_HIVE_TABLE, new RangerPolicyResource(tblName)); } } else if (StringUtils.equals(entityType, ENTITY_TYPE_HIVE_COLUMN)) { if (StringUtils.isNotEmpty(dbName) && StringUtils.isNotEmpty(tblName) && StringUtils.isNotEmpty(colName)) { elements.put(RANGER_TYPE_HIVE_DB, new RangerPolicyResource(dbName)); elements.put(RANGER_TYPE_HIVE_TABLE, new RangerPolicyResource(tblName)); elements.put(RANGER_TYPE_HIVE_COLUMN, new RangerPolicyResource(colName)); } } else { throwExceptionWithMessage("unrecognized entity-type: " + entityType); } if(elements.isEmpty()) { throwExceptionWithMessage("invalid qualifiedName for entity-type '" + entityType + "': " + qualifiedName); } RangerServiceResource ret = new RangerServiceResource(entityGuid, serviceName, elements); return ret; } }
3e0a98c46dfaa46321dea551a20b9e830a700916
1,223
java
Java
src/main/java/uk/gov/justice/digital/ndh/api/delius/response/Event.java
ministryofjustice/oasys-ndh-delius-replacement
74379431731b21b39c6dffb8cc3430521091428d
[ "MIT" ]
null
null
null
src/main/java/uk/gov/justice/digital/ndh/api/delius/response/Event.java
ministryofjustice/oasys-ndh-delius-replacement
74379431731b21b39c6dffb8cc3430521091428d
[ "MIT" ]
1
2022-01-25T10:20:44.000Z
2022-01-25T10:20:44.000Z
src/main/java/uk/gov/justice/digital/ndh/api/delius/response/Event.java
noms-digital-studio/oasys-ndh-delius-replacement
74379431731b21b39c6dffb8cc3430521091428d
[ "MIT" ]
1
2021-04-11T06:32:50.000Z
2021-04-11T06:32:50.000Z
29.119048
80
0.753884
4,487
package uk.gov.justice.digital.ndh.api.delius.response; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import lombok.Builder; import lombok.Value; import java.util.List; @Value @Builder public class Event { @JsonProperty("EventNumber") private String eventNumber; @JsonProperty("OffenceCode") private String offenceCode; @JsonProperty("OffenceDate") private String offenceDate; @JsonProperty("CommencementDate") private String commencementDate; @JsonProperty("OrderType") private String orderType; @JsonProperty("OrderLength") private String orderLength; @JsonProperty("Court") private String court; @JsonProperty("CourtType") private String courtType; @JsonProperty("UWHours") private String uwHours; @JsonProperty("Requirements") @JacksonXmlElementWrapper(localName = "Requirements") private List<Category> requirements; @JsonProperty("AdditionalRequirements") @JacksonXmlElementWrapper(localName = "AdditionalRequirements") private List<Category> additionalRequirements; @JsonProperty("Custody") private Custody custody; }
3e0a99f4f73e42c592708c276bb1c1bd23109a52
1,917
java
Java
grok/Java/buildingJava/javaWithMake/IsPrime.java
grscheller/scheller-linux-environment
3eb706ea5e39ae4f1119c83c0b4e7d10dbaac8a3
[ "BSD-3-Clause" ]
4
2017-04-16T19:54:09.000Z
2020-05-21T22:51:04.000Z
grok/Java/buildingJava/javaWithMake/IsPrime.java
grscheller/scheller-linux-environment
3eb706ea5e39ae4f1119c83c0b4e7d10dbaac8a3
[ "BSD-3-Clause" ]
1
2017-03-07T19:25:01.000Z
2020-06-06T05:08:45.000Z
grok/Java/buildingJava/javaWithMake/IsPrime.java
grscheller/scheller-linux-environment
3eb706ea5e39ae4f1119c83c0b4e7d10dbaac8a3
[ "BSD-3-Clause" ]
1
2020-11-25T03:05:55.000Z
2020-11-25T03:05:55.000Z
27.385714
77
0.527908
4,488
/* * Program to determine if input arguments, * parsed as unsigned longs, are prime. * * The purpose of this program is to * 1. Get a lambda to work * 2. Get parallism to work in Java * 3. Test different build schemes * * Note: Java does not seem to implement unsigned types. * * Note: Streams can only be run once, sort of the monster * child of a lazy list and a future. * * @author Geoffrey Scheller * */ import java.util.stream.LongStream; public class IsPrime { public static void main(String[] args) { final int argCnt = args.length; long[] potPrimes = new long[argCnt]; if (argCnt > 0) { try { for (int ii = 0; ii < argCnt; ii++) { long potPrime = Long.parseUnsignedLong(args[ii]); if (potPrime < 0L || args[ii] == "9223372036854775808") { throw new NumberFormatException( args[ii] + " parsed unsigned input as signed long <= 0" ); } else { potPrimes[ii] = potPrime; } } } catch (Exception e) { System.err.println(e); return; } } else { System.err.println("No arguments given"); return; } for (int jj = 0; jj < argCnt; jj++) { long potPrime = potPrimes[jj]; System.out.print(potPrime); if (potPrime == 0L || potPrime == 1L) { System.out.println(" is not prime"); } else if (isPrime(potPrimes[jj])){ System.out.println(" is prime"); } else { System.out.println(" is not prime"); } } } private static boolean isPrime(final Long num) { final long upto = (long)java.lang.Math.sqrt(num) + 1L; return LongStream.range(2, upto) .parallel() .noneMatch(e -> num % e == 0); } }
3e0a9a625375b5fdebdac1d5ecb6e20ba79c1ca2
7,652
java
Java
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveProject.java
TencentEMapReduce/EMR131-Hive
70d741709a3af706b5ca764268c37ab8ca9da5d5
[ "Apache-2.0" ]
30
2016-05-14T06:44:39.000Z
2021-02-25T06:40:12.000Z
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveProject.java
TencentEMapReduce/EMR131-Hive
70d741709a3af706b5ca764268c37ab8ca9da5d5
[ "Apache-2.0" ]
2
2021-02-03T19:20:12.000Z
2022-01-27T16:17:09.000Z
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveProject.java
TencentEMapReduce/EMR131-Hive
70d741709a3af706b5ca764268c37ab8ca9da5d5
[ "Apache-2.0" ]
49
2016-09-05T03:09:53.000Z
2022-03-18T08:10:38.000Z
38.26
127
0.723079
4,489
/** * 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.hadoop.hive.ql.optimizer.calcite.reloperators; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptCost; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelCollation; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexUtil; import org.apache.calcite.util.Util; import org.apache.calcite.util.mapping.Mapping; import org.apache.calcite.util.mapping.MappingType; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException.UnsupportedFeature; import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil; import org.apache.hadoop.hive.ql.optimizer.calcite.TraitsUtil; import com.google.common.collect.ImmutableList; public class HiveProject extends Project implements HiveRelNode { private final List<Integer> virtualCols; private boolean isSysnthetic; /** * Creates a HiveProject. * * @param cluster * Cluster this relational expression belongs to * @param child * input relational expression * @param exps * List of expressions for the input columns * @param rowType * output row type * @param flags * values as in {@link Project.Flags} */ public HiveProject(RelOptCluster cluster, RelTraitSet traitSet, RelNode child, List<? extends RexNode> exps, RelDataType rowType, int flags) { super(cluster, traitSet, child, exps, rowType, flags); assert traitSet.containsIfApplicable(HiveRelNode.CONVENTION); virtualCols = ImmutableList.copyOf(HiveCalciteUtil.getVirtualCols(exps)); } /** * Creates a HiveProject with no sort keys. * * @param child * input relational expression * @param exps * set of expressions for the input columns * @param fieldNames * aliases of the expressions */ public static HiveProject create(RelNode child, List<? extends RexNode> exps, List<String> fieldNames) throws CalciteSemanticException{ RelOptCluster cluster = child.getCluster(); // 1 Ensure columnNames are unique - CALCITE-411 if (fieldNames != null && !Util.isDistinct(fieldNames)) { String msg = "Select list contains multiple expressions with the same name." + fieldNames; throw new CalciteSemanticException(msg, UnsupportedFeature.Same_name_in_multiple_expressions); } RelDataType rowType = RexUtil.createStructType(cluster.getTypeFactory(), exps, fieldNames); return create(cluster, child, exps, rowType, Collections.<RelCollation> emptyList()); } /** * Creates a HiveProject. */ public static HiveProject create(RelOptCluster cluster, RelNode child, List<? extends RexNode> exps, RelDataType rowType, final List<RelCollation> collationList) { RelTraitSet traitSet = TraitsUtil.getDefaultTraitSet(cluster); return new HiveProject(cluster, traitSet, child, exps, rowType, Flags.BOXED); } /** * Creates a HiveProject. */ public static HiveProject create(RelOptCluster cluster, RelNode child, List<? extends RexNode> exps, RelDataType rowType, RelTraitSet traitSet, final List<RelCollation> collationList) { return new HiveProject(cluster, traitSet, child, exps, rowType, Flags.BOXED); } /** * Creates a relational expression which projects the output fields of a * relational expression according to a partial mapping. * * <p> * A partial mapping is weaker than a permutation: every target has one * source, but a source may have 0, 1 or more than one targets. Usually the * result will have fewer fields than the source, unless some source fields * are projected multiple times. * * <p> * This method could optimize the result as {@link #permute} does, but does * not at present. * * @param rel * Relational expression * @param mapping * Mapping from source fields to target fields. The mapping type must * obey the constraints {@link MappingType#isMandatorySource()} and * {@link MappingType#isSingleSource()}, as does * {@link MappingType#INVERSE_FUNCTION}. * @param fieldNames * Field names; if null, or if a particular entry is null, the name * of the permuted field is used * @return relational expression which projects a subset of the input fields * @throws CalciteSemanticException */ public static RelNode projectMapping(RelNode rel, Mapping mapping, List<String> fieldNames) throws CalciteSemanticException { assert mapping.getMappingType().isSingleSource(); assert mapping.getMappingType().isMandatorySource(); if (mapping.isIdentity()) { return rel; } final List<String> outputNameList = new ArrayList<String>(); final List<RexNode> outputProjList = new ArrayList<RexNode>(); final List<RelDataTypeField> fields = rel.getRowType().getFieldList(); final RexBuilder rexBuilder = rel.getCluster().getRexBuilder(); for (int i = 0; i < mapping.getTargetCount(); i++) { int source = mapping.getSource(i); final RelDataTypeField sourceField = fields.get(source); outputNameList .add(((fieldNames == null) || (fieldNames.size() <= i) || (fieldNames.get(i) == null)) ? sourceField .getName() : fieldNames.get(i)); outputProjList.add(rexBuilder.makeInputRef(rel, source)); } return create(rel, outputProjList, outputNameList); } @Override public Project copy(RelTraitSet traitSet, RelNode input, List<RexNode> exps, RelDataType rowType) { assert traitSet.containsIfApplicable(HiveRelNode.CONVENTION); HiveProject hp = new HiveProject(getCluster(), traitSet, input, exps, rowType, getFlags()); if (this.isSynthetic()) { hp.setSynthetic(); } return hp; } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { return mq.getNonCumulativeCost(this); } @Override public void implement(Implementor implementor) { } public List<Integer> getVirtualCols() { return virtualCols; } // TODO: this should come through RelBuilder to the constructor as opposed to // set method. This requires calcite change public void setSynthetic() { this.isSysnthetic = true; } public boolean isSynthetic() { return isSysnthetic; } }
3e0a9a8dc770fa91a8b4910cf8dd4d86f2a2f30d
375
java
Java
src/com/leetcode/struct/RandomListNode.java
Hitooooo/OnlineJudge
540ecfd6dcaa4516d42a86e2889b1db270778bf2
[ "MIT" ]
1
2019-03-05T11:05:32.000Z
2019-03-05T11:05:32.000Z
src/com/leetcode/struct/RandomListNode.java
Hitooooo/OnlineJudge
540ecfd6dcaa4516d42a86e2889b1db270778bf2
[ "MIT" ]
1
2019-09-19T14:58:24.000Z
2019-09-19T14:58:24.000Z
src/com/leetcode/struct/RandomListNode.java
Hitooooo/OnlineJudge
540ecfd6dcaa4516d42a86e2889b1db270778bf2
[ "MIT" ]
null
null
null
19.736842
45
0.677333
4,490
package com.leetcode.struct; /** * 每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点 * * @author hitomeng * @date 2020-04-12 11:04:43 */ public class RandomListNode { public int label; public RandomListNode next = null; public RandomListNode random = null; public RandomListNode(){} public RandomListNode(int label) { this.label = label; } }
3e0a9a99911f9426fc1396f92bc33c9be29ca56c
9,419
java
Java
nd4j/nd4j-common/src/main/java/org/nd4j/common/config/ND4JSystemProperties.java
taotesea/EclipseDeeplearning4j
a119da98b5fdf0181fa6f9ae93f1bfff45772495
[ "Apache-2.0" ]
13,006
2015-02-13T18:35:31.000Z
2022-03-18T12:11:44.000Z
nd4j/nd4j-common/src/main/java/org/nd4j/common/config/ND4JSystemProperties.java
taotesea/EclipseDeeplearning4j
a119da98b5fdf0181fa6f9ae93f1bfff45772495
[ "Apache-2.0" ]
5,319
2015-02-13T08:21:46.000Z
2019-06-12T14:56:50.000Z
nd4j/nd4j-common/src/main/java/org/nd4j/common/config/ND4JSystemProperties.java
taotesea/EclipseDeeplearning4j
a119da98b5fdf0181fa6f9ae93f1bfff45772495
[ "Apache-2.0" ]
4,719
2015-02-13T22:48:55.000Z
2022-03-22T07:25:36.000Z
58.503106
200
0.718017
4,491
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.common.config; import org.nd4j.common.resources.Resources; import org.nd4j.common.resources.strumpf.ResourceFile; import org.nd4j.common.resources.strumpf.StrumpfResolver; import java.io.File; import java.net.URL; public class ND4JSystemProperties { /** * Applicability: Always<br> * Description: Sets the default datatype for ND4J - should be one of "float", "double", "half". * ND4J is set to float (32-bit floating point values) by default. */ public static final String DTYPE = "dtype"; /** * Applicability: Always<br> * Description: By default, ND4J will log some information when the library has completed initialization, such as the * backend (CPU or CUDA), CPU/Devices, memory etc. This system property can be used to disable the logging of this * initialization information */ public static final String LOG_INITIALIZATION = "org.nd4j.log.initialization"; /** * Applicability: nd4j-native when running non-AVX binary on an AVX compatible CPU<br> * Description: Set to true to avoid logging AVX warnings (i.e., running generic x86 binaries on an AVX2 system) */ public static final String ND4J_IGNORE_AVX = "org.nd4j.avx.ignore"; /** * Applicability: Always<br> * Description: This system property defines the maximum amount of off-heap memory that can be used. * ND4J uses off-heap memory for storage of all INDArray data. This off-heap memory is a different * pool of memory to the on-heap JVM memory (configured using standard Java Xms/Xmx options). * Default: 2x Java XMX setting * * @see #JAVACPP_MEMORY_MAX_PHYSICAL_BYTES */ public static final String JAVACPP_MEMORY_MAX_BYTES = "org.bytedeco.javacpp.maxbytes"; /** * Applicability: Always<br> * Description: This system property defines the maximum total amount of memory that the process can use - it is * the sum of both off-heap and on-heap memory. This can be used to provide an upper bound on the maximum amount * of memory (of all types) that ND4J will use * * @see #JAVACPP_MEMORY_MAX_BYTES */ public static final String JAVACPP_MEMORY_MAX_PHYSICAL_BYTES = "org.bytedeco.javacpp.maxphysicalbytes"; /** * Applicability: ND4J Temporary file creation/extraction for ClassPathResource, memory mapped workspaces, and <br> * Description: Specify the local directory where temporary files will be written. If not specified, the default * Java temporary directory (java.io.tmpdir system property) will generally be used. */ public static final String ND4J_TEMP_DIR_PROPERTY = "org.nd4j.tempdir"; /** * Applicability: always - but only if an ND4J backend cannot be found/loaded via standard ServiceLoader mechanisms<br> * Description: Set this property to a set fully qualified JAR files to attempt to load before failing on * not loading a backend. JAR files should be semi-colon delimited; i.e., "/some/file.jar;/other/path.jar". * This should rarely be required in practice - for example, only in dynamic class loading/dynamic classpath scenarios<br> * For equivalent system property, see {@link ND4JEnvironmentVars#BACKEND_DYNAMIC_LOAD_CLASSPATH} for the equivalent * system property (the system property will take precidence if both are set) */ public static final String DYNAMIC_LOAD_CLASSPATH_PROPERTY = "org.nd4j.backend.dynamicbackend"; /** * Applicability: Always<br> * Description Setting the system property to false will stop ND4J from performing the version check, and logging any * warnings/errors. By default, the version check is enabled.<br> * Note: the version check is there for a reason! Using incompatible versions of ND4J/DL4J etc is likely to cause * issues, and should be avoided. */ public static final String VERSION_CHECK_PROPERTY = "org.nd4j.versioncheck"; /** * Applicability: always<br> * Description: Used to specify the maximum number of elements (numbers) to print when using DataBuffer.toString(). * Use -1 to print all elements (i.e., no limit). This is usually to avoid expensive toString() calls on buffers * which may have millions of elements - for example, in a debugger<br> * Default: 1000 */ public static final String DATABUFFER_TO_STRING_MAX_ELEMENTS = "org.nd4j.databuffer.tostring.maxelements"; /** * Applicability: nd4j-native backend, when multiple BLAS libraries are available<br> * Description: This system property can be used to control which BLAS library is loaded and used by ND4J. * For example, {@code org.bytedeco.javacpp.openblas.load=mkl_rt} can be used to load a default installation of MKL. * However, MKL is liked with by default (when available) so setting this option explicitly is not usually required. * For more details, see <a href="https://github.com/bytedeco/javacpp-presets/tree/master/openblas#documentation">https://github.com/bytedeco/javacpp-presets/tree/master/openblas#documentation</a> */ public static final String ND4J_CPU_LOAD_OPENBLAS = "org.bytedeco.openblas.load"; /** * Applicability: nd4j-native backend, when multiple BLAS libraries are available<br> * Description: This system property can be used to control which BLAS library is loaded and used by ND4J. * Similar to {@link #ND4J_CPU_LOAD_OPENBLAS} but when this is set, LAPACK will not be loaded */ public static final String ND4J_CPU_LOAD_OPENBLAS_NOLAPACK = "org.bytedeco.openblas_nolapack.load"; /** * Applicability: nd4j-parameter-server, dl4j-spark (gradient sharing training master)<br> * Description: Aeros in a high-performance communication library used in distributed computing contexts in some * places in ND4J and DL4J. This term buffer length determines the maximum message length that can be sent via Aeron * in a single message. It can be increased to avoid exceptions such as {@code Encoded message exceeds maxMessageLength of 2097152}, * at the expense of increased memory consumption (memory consumption is a multiple of this). It is specified in bytes * with no unit suffix. Default value: 33554432 (32MB). * <b>IMPORTANT</b>: This value must be an exact power of 2.<br> * Note also the maximum effective size is 128MB (134217728) (due to Aeron internal limits - beyond which increasing * the buffer size will have no effect) */ public static final String AERON_TERM_BUFFER_PROP = "aeron.term.buffer.length"; /** * Applicability: nd4j-common {@link Resources} class (and hence {@link StrumpfResolver})<br> * Description: When resolving resources from a Strumpf resource file (Example: {@code Resources.asFile("myFile.txt")} * where should the remote files be downloaded to?<br> * This is generally used for resolving test resources, but can be used for Strumpf resource files generally. */ public static final String RESOURCES_CACHE_DIR = "org.nd4j.test.resources.cache.dir"; /** * Applicability: nd4j-common {@link Resources} class (and hence {@link StrumpfResolver})<br> * Description: When resolving resources from a Strumpf resource file (Example: {@code Resources.asFile("myFile.txt")} * what should be the connection timeout, as used by {@link org.apache.commons.io.FileUtils#copyURLToFile(URL, File, int, int)}<br> * Default: {@link ResourceFile#DEFAULT_CONNECTION_TIMEOUT} */ public static final String RESOURCES_CONNECTION_TIMEOUT = "org.nd4j.resources.download.connectiontimeout"; /** * Applicability: nd4j-common {@link Resources} class (and hence {@link StrumpfResolver})<br> * Description: When resolving resources from a Strumpf resource file (Example: {@code Resources.asFile("myFile.txt")} * what should be the connection timeout, as used by {@link org.apache.commons.io.FileUtils#copyURLToFile(URL, File, int, int)}<br> * Default: {@link ResourceFile#DEFAULT_READ_TIMEOUT} */ public static final String RESOURCES_READ_TIMEOUT = "org.nd4j.resources.download.readtimeout"; /** * Applicability: nd4j-common {@link Resources} class (and hence {@link StrumpfResolver})<br> * Description: When resolving resources, what local directories should be checked (in addition to the classpath) for files? * This is optional. Multiple directories may be specified, using comma-separated paths */ public static final String RESOURCES_LOCAL_DIRS = "org.nd4j.strumpf.resource.dirs"; private ND4JSystemProperties() { } }
3e0a9ae45c0b3f3476c5788408257e319502ba72
717
java
Java
platform/commons/src/test/java/com/peregrine/commons/TextUtilsTest.java
gaohangdy/uxhub-sling12
cc0152b45ef3e41342970c62febe3f1b00908057
[ "Apache-2.0" ]
54
2017-09-13T21:14:34.000Z
2021-11-30T08:36:46.000Z
platform/commons/src/test/java/com/peregrine/commons/TextUtilsTest.java
gaohangdy/uxhub-sling12
cc0152b45ef3e41342970c62febe3f1b00908057
[ "Apache-2.0" ]
751
2018-09-22T15:38:00.000Z
2022-03-21T00:36:45.000Z
platform/commons/src/test/java/com/peregrine/commons/TextUtilsTest.java
gaohangdy/uxhub-sling12
cc0152b45ef3e41342970c62febe3f1b00908057
[ "Apache-2.0" ]
44
2017-10-11T00:01:26.000Z
2022-03-07T09:14:35.000Z
34.142857
122
0.74198
4,492
package com.peregrine.commons; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class TextUtilsTest { @Test public void createsStaticReplicationPath(){ String dir = System.getProperty("user.dir"); System.getProperties().setProperty("sling.home", dir); String staticReplicationPath = TextUtils.replacePlaceholders("${sling.home}/staticreplication", (String) -> null); assertNotNull(staticReplicationPath); assertTrue(staticReplicationPath.endsWith("/staticreplication")); assertEquals(dir+"/staticreplication", staticReplicationPath); } }
3e0a9b01ea347de264aee001716be00acecdf068
6,330
java
Java
app/models/entity/game/Map.java
ssachtleben/herowar
b82dfb4f22f6d0c1f8d5dfa27b07766d8598e838
[ "Apache-2.0" ]
1
2015-11-30T22:18:34.000Z
2015-11-30T22:18:34.000Z
app/models/entity/game/Map.java
ssachtleben/herowar
b82dfb4f22f6d0c1f8d5dfa27b07766d8598e838
[ "Apache-2.0" ]
null
null
null
app/models/entity/game/Map.java
ssachtleben/herowar
b82dfb4f22f6d0c1f8d5dfa27b07766d8598e838
[ "Apache-2.0" ]
null
null
null
24.440154
140
0.635387
4,493
package models.entity.game; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import models.entity.BaseModel; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Sebastian Sachtleben */ @Entity @SuppressWarnings("serial") @JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" }) public class Map extends BaseModel implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String description; private String skybox; private Integer teamSize; private Integer prepareTime; private Integer lives; private Integer goldStart; private Integer goldPerTick; @OneToOne(cascade = CascadeType.ALL) private Terrain terrain; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name = "map_towers") private Set<Tower> towers = new HashSet<Tower>(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "map", orphanRemoval = true) private Set<Wave> waves = new HashSet<Wave>(); @OneToMany(cascade = CascadeType.ALL, mappedBy = "map", orphanRemoval = true) private Set<Mesh> objects = new HashSet<Mesh>(); @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name = "map_materials") @JsonIgnore private Set<Material> allMaterials = new HashSet<Material>(); @OneToMany(cascade = CascadeType.ALL, mappedBy = "map", orphanRemoval = true) private Set<Path> paths = new HashSet<Path>(); @Transient private List<Material> materials; @Transient private List<Geometry> staticGeometries; public Map() { this.name = "Default Map"; this.description = ""; this.skybox = "default"; this.teamSize = 1; this.prepareTime = 500; this.lives = 20; this.goldStart = 2000; this.goldPerTick = 5; this.allMaterials = new HashSet<>(); this.terrain = new Terrain(); this.getTerrain().setGeometry(new Geometry()); this.getTerrain().getGeometry().setTerrain(this.getTerrain()); this.getTerrain().getGeometry().setMetadata(new GeoMetaData()); this.getTerrain().getGeometry().getMetadata().setGeometry(this.getTerrain().getGeometry()); } // GETTER & SETTER // public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSkybox() { return skybox; } public void setSkybox(String skybox) { this.skybox = skybox; } public Integer getTeamSize() { return teamSize; } public void setTeamSize(Integer teamSize) { this.teamSize = teamSize; } public Integer getPrepareTime() { return prepareTime; } public void setPrepareTime(Integer prepareTime) { this.prepareTime = prepareTime; } public Integer getLives() { return lives; } public void setLives(Integer lives) { this.lives = lives; } public Integer getGoldStart() { return goldStart; } public void setGoldStart(Integer goldStart) { this.goldStart = goldStart; } public Integer getGoldPerTick() { return goldPerTick; } public void setGoldPerTick(Integer goldPerTick) { this.goldPerTick = goldPerTick; } public Terrain getTerrain() { return terrain; } public void setTerrain(Terrain terrain) { this.terrain = terrain; } public Set<Tower> getTowers() { return towers; } public void setTowers(Set<Tower> towers) { this.towers = towers; } public Set<Wave> getWaves() { return waves; } public void setWaves(Set<Wave> waves) { this.waves = waves; } public Set<Material> getAllMaterials() { return allMaterials; } public void setAllMaterials(Set<Material> allMaterials) { this.allMaterials = allMaterials; } public Set<Mesh> getObjects() { return objects; } public void setObjects(Set<Mesh> objects) { this.objects = objects; } public List<Material> getMaterials() { return materials; } public void setMaterials(List<Material> materials) { this.materials = materials; } public List<Geometry> getStaticGeometries() { return staticGeometries; } public void setStaticGeometries(List<Geometry> staticGeometries) { this.staticGeometries = staticGeometries; } public Set<Path> getPaths() { return paths; } public void setPaths(Set<Path> paths) { this.paths = paths; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Map other = (Map) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Map [id=" + id + ", name=" + name + ", description=" + description + ", teamSize=" + teamSize + ", prepareTime=" + prepareTime + ", lives=" + lives + ", goldStart=" + goldStart + ", goldPerTick=" + goldPerTick + "]"; } }
3e0a9bb17e6b2309326e636a164dc782c7c11950
10,368
java
Java
app/src/main/java/kr/ac/gachon/sw/gbro/map/MapFragment.java
Taehyuny/G-Bro
06a9f521bfd6dba5ba6eb44514e37eddcf2c6303
[ "Apache-2.0" ]
null
null
null
app/src/main/java/kr/ac/gachon/sw/gbro/map/MapFragment.java
Taehyuny/G-Bro
06a9f521bfd6dba5ba6eb44514e37eddcf2c6303
[ "Apache-2.0" ]
null
null
null
app/src/main/java/kr/ac/gachon/sw/gbro/map/MapFragment.java
Taehyuny/G-Bro
06a9f521bfd6dba5ba6eb44514e37eddcf2c6303
[ "Apache-2.0" ]
null
null
null
39.124528
154
0.563272
4,494
package kr.ac.gachon.sw.gbro.map; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.FragmentManager; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import com.naver.maps.geometry.LatLng; import com.naver.maps.geometry.LatLngBounds; import com.naver.maps.map.CameraPosition; import com.naver.maps.map.NaverMap; import com.naver.maps.map.NaverMapOptions; import com.naver.maps.map.OnMapReadyCallback; import com.naver.maps.map.overlay.InfoWindow; import com.naver.maps.map.overlay.Marker; import com.naver.maps.map.overlay.OverlayImage; import com.naver.maps.map.overlay.PathOverlay; import java.util.ArrayList; import java.util.HashMap; import kr.ac.gachon.sw.gbro.R; import kr.ac.gachon.sw.gbro.base.BaseFragment; import kr.ac.gachon.sw.gbro.databinding.FragmentMapBinding; import kr.ac.gachon.sw.gbro.util.Firestore; import kr.ac.gachon.sw.gbro.util.model.Post; public class MapFragment extends BaseFragment<FragmentMapBinding> implements OnMapReadyCallback { private ArrayList<Marker> markers = null; private com.naver.maps.map.MapFragment mapFragment; private ArrayList<Integer> path = null; private boolean isMain = false; @Override protected FragmentMapBinding getBinding() { return FragmentMapBinding.inflate(getLayoutInflater()); } public static MapFragment getPathInstance(ArrayList<Integer> path){ MapFragment mapFragment = new MapFragment(); Bundle args = new Bundle(); args.putIntegerArrayList("path", path); mapFragment.setArguments(args); return mapFragment; } public static MapFragment getMainInstance() { MapFragment mapFragment = new MapFragment(); Bundle args = new Bundle(); args.putBoolean("isMain", true); mapFragment.setArguments(args); return mapFragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { path = getArguments().getIntegerArrayList("path"); isMain = getArguments().getBoolean("isMain"); } } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { setMap(); return getBinding().getRoot(); } @Override public void onResume() { super.onResume(); mapFragment.getMapAsync(naverMap -> { if (path != null && !path.isEmpty()) { Log.d("MapFragment", "Path Map"); String firstPos = getResources().getStringArray(R.array.gachon_globalcampus_coordinate)[path.get(0)]; String[] posArray = firstPos.split(","); naverMap.setCameraPosition(new CameraPosition(new LatLng(Double.parseDouble(posArray[0]), Double.parseDouble(posArray[1])), 14.5)); drawPath(naverMap, path); } }); } private void setMap() { FragmentManager fragmentManager = getChildFragmentManager(); mapFragment = (com.naver.maps.map.MapFragment) fragmentManager.findFragmentById(binding.map.getId()); if(mapFragment == null) { NaverMapOptions options = new NaverMapOptions() .camera(new CameraPosition(new LatLng(37.45199894842855, 127.13179114165393), 14)) .locationButtonEnabled(true) .logoGravity(Gravity.START | Gravity.TOP) .logoMargin(8, 8, 8, 8) .locationButtonEnabled(false) .compassEnabled(false) .zoomControlEnabled(false); mapFragment = com.naver.maps.map.MapFragment.newInstance(options); fragmentManager.beginTransaction().add(binding.map.getId(), mapFragment).commit(); mapFragment.getMapAsync(naverMap -> { naverMap.setExtent(new LatLngBounds(new LatLng(37.44792028734633, 127.12628356183701), new LatLng(37.4570968690434, 127.13723061921826))); naverMap.setMinZoom(14.0); naverMap.setMaxZoom(0.0); if(isMain) { Log.d("MapFragment", "Main Map"); drawMarker(naverMap); } }); } } /** * 지도에 Marker를 표시한다 * @author Subin Kim, Minjae Seon * @param naverMap NaverMap Object */ public void drawMarker(NaverMap naverMap) { markers = new ArrayList<>(); String[] buildingCoordinate = getResources().getStringArray(R.array.gachon_globalcampus_coordinate); Firestore.getUnfinishedPost(0) .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { HashMap<Integer, Integer> lostNumList = new HashMap<>(); HashMap<Integer, Integer> foundNumList = new HashMap<>(); for(DocumentSnapshot doc : task.getResult().getDocuments()) { Post post = doc.toObject(Post.class); if(post.getType() == 1) { if(lostNumList.get(post.getSummaryBuildingType()) != null) { lostNumList.put(post.getSummaryBuildingType(), lostNumList.get(post.getSummaryBuildingType()) + 1); } else { lostNumList.put(post.getSummaryBuildingType(), 1); } } else if(post.getType() == 2) { if(foundNumList.get(post.getSummaryBuildingType()) != null) { foundNumList.put(post.getSummaryBuildingType(), foundNumList.get(post.getSummaryBuildingType()) + 1); } else { foundNumList.put(post.getSummaryBuildingType(), 1); } } } for(int i = 0; i < buildingCoordinate.length - 1; i++) { String[] posArray = buildingCoordinate[i].split(","); Marker marker = new Marker(); marker.setPosition(new LatLng(Double.parseDouble(posArray[0]), Double.parseDouble(posArray[1]))); marker.setMap(naverMap); marker.setWidth(40); marker.setHeight(60); marker.setIcon(OverlayImage.fromResource(R.drawable.marker)); setInfoWindow(marker, i, lostNumList.get(i) == null ? 0 : lostNumList.get(i), foundNumList.get(i) == null ? 0 : foundNumList.get(i)); markers.add(marker); } } else { Log.e("MapFragment", "Get Unfinished Post Error!", task.getException()); } } }); } /** * 지도에 Path를 표시한다 * @author Suyeon Jung, Minjae Seon * @param naverMap NaverMap Object * @param pathArr 건물 번호 ArrayList */ public void drawPath(NaverMap naverMap, ArrayList<Integer> pathArr){ // Exception if(pathArr.size() > 5) { return; } String [] str_coordinate = getResources().getStringArray(R.array.gachon_globalcampus_coordinate); ArrayList<LatLng> coordinates = new ArrayList<>(); for (int i : pathArr){ String [] arr = str_coordinate[i].split(","); coordinates.add(new LatLng(Double.parseDouble(arr[0]), Double.parseDouble(arr[1]))); } PathOverlay path = new PathOverlay(); path.setCoords(coordinates); path.setMap(naverMap); } @Override public void onMapReady(@NonNull NaverMap naverMap) { } /** * Marker의 InfoWindow 설정 * @author Subin Kim, Minjae Seon * @param marker Marker * @param buildingNum 건물 번호 */ private void setInfoWindow(Marker marker, int buildingNum, int lost, int found) { String[] buildingName = getResources().getStringArray(R.array.gachon_globalcampus_building); InfoWindow infoWindow = new InfoWindow(); marker.setOnClickListener(overlay -> { if (marker.getInfoWindow() == null) { // 마커를 클릭할 때 정보창을 엶 // 다른 열린 마커 닫기 closeOpenMarkers(); infoWindow.open(marker); } else { // 이미 현재 마커에 정보 창이 열려있을 경우 닫음 infoWindow.close(); } return true; }); infoWindow.setAdapter(new InfoWindow.DefaultTextAdapter(getContext()) { @NonNull @Override public CharSequence getText(@NonNull InfoWindow infoWindow) { return getString(R.string.Info_building_name, buildingName[buildingNum]) +"\n" +getString(R.string.Info_lost_cnt,lost) +"\n" +getString(R.string.Info_get_cnt,found); } }); } /** * 모든 열린 마커들을 닫음 * @author Minjae Seon */ private void closeOpenMarkers() { for (Marker marker : markers) { InfoWindow infoWindow = marker.getInfoWindow(); if (infoWindow != null) { infoWindow.close(); } } } }
3e0a9c76ce45ec48c17fdc1a3d4147748f99af8b
835
java
Java
src/com/modofo/util/DbUtils.java
zhangv/moder
a1df5ab8cabcbc5ef45141cd5b0525a62ede81f7
[ "MIT" ]
null
null
null
src/com/modofo/util/DbUtils.java
zhangv/moder
a1df5ab8cabcbc5ef45141cd5b0525a62ede81f7
[ "MIT" ]
null
null
null
src/com/modofo/util/DbUtils.java
zhangv/moder
a1df5ab8cabcbc5ef45141cd5b0525a62ede81f7
[ "MIT" ]
null
null
null
27.833333
159
0.756886
4,495
package com.modofo.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DbUtils { public static void createDerbyDatabase(String path,String dbname) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{ String driver = "org.apache.derby.jdbc.EmbeddedDriver"; String protocol = "jdbc:derby:"; Class.forName(driver).newInstance(); System.out.println("Loaded the appropriate driver."); Connection conn = null; Properties props = new Properties(); props.put("user", "mocar"); props.put("password", "mocar"); conn = DriverManager.getConnection(protocol + dbname+";create=true", props); System.out.println("Connected to and created database derbyDB"); conn.setAutoCommit(false); } }
3e0a9eb7954c4fd3c3cce2a4545f8c0733e7948a
604
java
Java
validation/src/main/java/net/sf/mmm/util/validation/api/Validatable.java
m-m-m/util
0b6d40b1976f9fa2f32b1a7ff03821eef939b301
[ "Apache-2.0" ]
2
2016-07-07T05:05:00.000Z
2016-12-07T11:25:43.000Z
validation/src/main/java/net/sf/mmm/util/validation/api/Validatable.java
m-m-m/util
0b6d40b1976f9fa2f32b1a7ff03821eef939b301
[ "Apache-2.0" ]
143
2015-05-02T20:55:20.000Z
2021-03-01T16:41:47.000Z
validation/src/main/java/net/sf/mmm/util/validation/api/Validatable.java
m-m-m/util
0b6d40b1976f9fa2f32b1a7ff03821eef939b301
[ "Apache-2.0" ]
2
2016-05-17T14:21:15.000Z
2021-01-26T03:30:21.000Z
26.26087
91
0.69702
4,496
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.util.validation.api; /** * This is the abstract interface for an object, that can be {@link #validate() validated}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 7.4.0 */ public abstract interface Validatable { /** * This method performs the actual validation. * * @see ValueValidator#validate(Object) * * @return {@link ValidationFailure} the validation failure. */ ValidationFailure validate(); }
3e0a9f0136dcbb0bee10604e40ee60121e3fb805
391
java
Java
evaluation/github_authmreloaded_unsafe/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
32
2019-02-21T21:10:05.000Z
2022-02-03T20:04:11.000Z
evaluation/github_authmreloaded_unsafe/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
null
null
null
evaluation/github_authmreloaded_unsafe/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
6
2019-02-17T07:02:43.000Z
2021-08-24T09:02:31.000Z
21.722222
78
0.70844
4,497
package fr.xephi.authme.permission; /** * Test for {@link DebugSectionPermissions}. */ public class DebugSectionPermissionsTest extends AbstractPermissionsEnumTest { @Override protected PermissionNode[] getPermissionNodes() { return DebugSectionPermissions.values(); } @Override protected String getRequiredPrefix() { return "authme.debug."; } }
3e0a9f29f0709807107709ef181b39d03a0747a7
46,074
java
Java
src/com/lilithsthrone/game/character/body/coverings/BodyCoveringType.java
gas-public-wooden-clean/liliths-throne-public
81a1fc0b147c557baf890e25224da14fb2f487c1
[ "Linux-OpenIB" ]
261
2017-07-29T01:00:40.000Z
2022-03-30T06:15:41.000Z
src/com/lilithsthrone/game/character/body/coverings/BodyCoveringType.java
gas-public-wooden-clean/liliths-throne-public
81a1fc0b147c557baf890e25224da14fb2f487c1
[ "Linux-OpenIB" ]
1,452
2017-07-29T20:33:05.000Z
2022-03-04T22:15:20.000Z
src/com/lilithsthrone/game/character/body/coverings/BodyCoveringType.java
gas-public-wooden-clean/liliths-throne-public
81a1fc0b147c557baf890e25224da14fb2f487c1
[ "Linux-OpenIB" ]
562
2017-07-29T01:47:15.000Z
2022-03-21T21:16:16.000Z
34.984055
165
0.758041
4,498
package com.lilithsthrone.game.character.body.coverings; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.lilithsthrone.game.character.body.valueEnums.BodyMaterial; import com.lilithsthrone.game.character.body.valueEnums.CoveringModifier; import com.lilithsthrone.game.character.body.valueEnums.CoveringPattern; import com.lilithsthrone.utils.Util; import com.lilithsthrone.utils.Util.Value; import com.lilithsthrone.utils.colours.Colour; import com.lilithsthrone.utils.colours.ColourListPresets; import com.lilithsthrone.utils.colours.PresetColour; /** * @since 0.1.0 * @version 0.4.0 * @author Innoxia */ public class BodyCoveringType { public static AbstractBodyCoveringType HUMAN = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, BodyCoveringTemplateFactory.createSkin( Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 30), new Value<>(CoveringPattern.FRECKLED_FACE, 2), new Value<>(CoveringPattern.FRECKLED, 1)), PresetColour.humanSkinColours, PresetColour.humanSkinColours, PresetColour.allSkinColours)) { }; public static AbstractBodyCoveringType FOX_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, "a layer of", false, "fur", "fur", Util.newArrayListOfValues( CoveringModifier.FLUFFY, CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.MARKED, 1)), // Foxes always have white markings on their undersides CoveringPattern.allHairCoveringPatterns, Util.newArrayListOfValues( PresetColour.COVERING_ORANGE, PresetColour.COVERING_TAN, PresetColour.COVERING_GREY, PresetColour.COVERING_BLACK), PresetColour.allCoveringColours, Util.newArrayListOfValues( PresetColour.COVERING_WHITE), // Fox markings are always naturally white PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType ANGEL = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, BodyCoveringTemplateFactory.createTopSkin( Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), PresetColour.humanSkinColours)) { }; public static AbstractBodyCoveringType ANGEL_FEATHER = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FEATHER, "a layer of", true, "feathers", "feather", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allHairCoveringPatterns, Util.newArrayListOfValues(PresetColour.COVERING_WHITE), Util.mergeLists(PresetColour.dyeFeatherColours, PresetColour.naturalFeatherColours), Util.newArrayListOfValues(PresetColour.COVERING_WHITE), Util.mergeLists(PresetColour.dyeFeatherColours, PresetColour.naturalFeatherColours)) { }; public static AbstractBodyCoveringType DEMON_COMMON = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, BodyCoveringTemplateFactory.createTopSkin( Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), PresetColour.demonSkinColours)) { }; public static AbstractBodyCoveringType DEMON_FEATHER = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FEATHER, "a layer of", true, "feathers", "feather", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allHairCoveringPatterns, Util.newArrayListOfValues(PresetColour.COVERING_BLACK), Util.mergeLists(PresetColour.dyeFeatherColours, PresetColour.naturalFeatherColours), Util.newArrayListOfValues(PresetColour.COVERING_BLACK), Util.mergeLists(PresetColour.dyeFeatherColours, PresetColour.naturalFeatherColours)) { }; // public static AbstractBodyCoveringType DEMON_HORSE_HAIR = new AbstractBodyCoveringType( // BodyCoveringCategory.MAIN_HAIR, // "a layer of", // false, // "hair", // "hair", // Util.newArrayListOfValues(CoveringModifier.SHORT), // null, // Util.newHashMapOfValues( // new Value<>(CoveringPattern.NONE, 30), // new Value<>(CoveringPattern.MOTTLED, 5), // new Value<>(CoveringPattern.SPOTTED, 5), // new Value<>(CoveringPattern.MARKED, 5)), // CoveringPattern.allHairCoveringPatterns, // PresetColour.naturalFurColours, // PresetColour.allCoveringColours, // PresetColour.naturalFurColours, // PresetColour.allCoveringColours) { // }; public static AbstractBodyCoveringType BAT_SKIN = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, BodyCoveringTemplateFactory.createBottomSkin(PresetColour.humanSkinColours)) { }; public static AbstractBodyCoveringType BAT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin( Util.newArrayListOfValues(CoveringModifier.SHORT), Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)))) { }; public static AbstractBodyCoveringType CANINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin( Util.newArrayListOfValues( CoveringModifier.FLUFFY, CoveringModifier.SHORT, CoveringModifier.SHAGGY), Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 30), new Value<>(CoveringPattern.SPOTTED, 5), new Value<>(CoveringPattern.MARKED, 5)))) { }; public static AbstractBodyCoveringType LYCAN_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin(Util.newArrayListOfValues(CoveringModifier.SHAGGY), null)) { }; public static AbstractBodyCoveringType FELINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin( Util.newArrayListOfValues( CoveringModifier.SMOOTH, CoveringModifier.SHORT, CoveringModifier.FLUFFY), Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 50), new Value<>(CoveringPattern.MOTTLED, 5), new Value<>(CoveringPattern.SPOTTED, 5), new Value<>(CoveringPattern.MARKED, 5), new Value<>(CoveringPattern.STRIPED, 5), new Value<>(CoveringPattern.HIGHLIGHTS, 5)))) { }; public static AbstractBodyCoveringType SQUIRREL_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin(Util.newArrayListOfValues(CoveringModifier.SMOOTH), null)) { }; public static AbstractBodyCoveringType RAT_SKIN = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, BodyCoveringTemplateFactory.createBottomSkin(PresetColour.ratSkinColours)) { }; public static AbstractBodyCoveringType RAT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin(Util.newArrayListOfValues(CoveringModifier.SMOOTH), null)) { }; public static AbstractBodyCoveringType RABBIT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin(Util.newArrayListOfValues(CoveringModifier.SMOOTH), null)) { }; public static AbstractBodyCoveringType HORSE_HAIR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_HAIR, "a layer of", false, "hair", "hair", Util.newArrayListOfValues(CoveringModifier.SHORT), null, Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 30), new Value<>(CoveringPattern.MOTTLED, 5), new Value<>(CoveringPattern.SPOTTED, 5), new Value<>(CoveringPattern.MARKED, 5)), CoveringPattern.allHairCoveringPatterns, PresetColour.naturalFurColours, PresetColour.allCoveringColours, PresetColour.naturalFurColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType REINDEER_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin( Util.newArrayListOfValues(CoveringModifier.SMOOTH), Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)))) { }; public static AbstractBodyCoveringType BOVINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FUR, BodyCoveringTemplateFactory.createFurSkin( Util.newArrayListOfValues( CoveringModifier.SHORT, CoveringModifier.SMOOTH), Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 10), new Value<>(CoveringPattern.SPOTTED, 5), new Value<>(CoveringPattern.MOTTLED, 1), new Value<>(CoveringPattern.MARKED, 1)))) { }; /** Used for their leg covering */ public static AbstractBodyCoveringType HARPY_SKIN = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, "a layer of", // This colour is set in GameCharacter's getCovering method, based on the colour of the dildo equipped. false, "skin", "skin", Util.newArrayListOfValues(CoveringModifier.LEATHERY), null, null, null, Util.newArrayListOfValues( PresetColour.SKIN_EBONY, PresetColour.SKIN_GREY, PresetColour.SKIN_AMBER, PresetColour.SKIN_YELLOW, PresetColour.SKIN_ORANGE), ColourListPresets.ALL, ColourListPresets.ALL, null) { }; public static AbstractBodyCoveringType DILDO = new AbstractBodyCoveringType( BodyCoveringCategory.ARTIFICIAL, "a layer of", // This colour is set in GameCharacter's getCovering method, based on the colour of the dildo equipped. false, "silicone", "silicone", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, null, null, ColourListPresets.ALL, null, ColourListPresets.ALL, null) { }; public static AbstractBodyCoveringType PENIS = new AbstractBodyCoveringType( BodyCoveringCategory.PENIS, BodyCoveringTemplateFactory.createPenisSkin()) { }; public static AbstractBodyCoveringType ANUS = new AbstractBodyCoveringType( BodyCoveringCategory.ANUS, BodyCoveringTemplateFactory.createOrificeSkin(CoveringPattern.ORIFICE_ANUS)) { }; public static AbstractBodyCoveringType MOUTH = new AbstractBodyCoveringType( BodyCoveringCategory.MOUTH, BodyCoveringTemplateFactory.createOrificeSkin(CoveringPattern.ORIFICE_MOUTH)) { }; public static AbstractBodyCoveringType NIPPLES = new AbstractBodyCoveringType( BodyCoveringCategory.NIPPLE, BodyCoveringTemplateFactory.createOrificeSkin(CoveringPattern.ORIFICE_NIPPLE)) { }; public static AbstractBodyCoveringType NIPPLES_CROTCH = new AbstractBodyCoveringType( BodyCoveringCategory.NIPPLE_CROTCH, BodyCoveringTemplateFactory.createOrificeSkin(CoveringPattern.ORIFICE_NIPPLE_CROTCH)) { }; public static AbstractBodyCoveringType VAGINA = new AbstractBodyCoveringType( BodyCoveringCategory.VAGINA, BodyCoveringTemplateFactory.createOrificeSkin(CoveringPattern.ORIFICE_VAGINA)) { }; public static AbstractBodyCoveringType SPINNERET = new AbstractBodyCoveringType( BodyCoveringCategory.SPINNERET, BodyCoveringTemplateFactory.createOrificeSkin(CoveringPattern.ORIFICE_SPINNERET)) { }; public static AbstractBodyCoveringType ALLIGATOR_SCALES = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SCALES, "a layer of", true, "scales", "scale", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allScalesCoveringPatterns, PresetColour.naturalScaleColours, PresetColour.allCoveringColours, PresetColour.naturalScaleColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType SNAKE_SCALES = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SCALES, "a layer of", true, "scales", "scale", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allScalesCoveringPatterns, PresetColour.naturalScaleColours, PresetColour.allCoveringColours, PresetColour.naturalScaleColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType SPIDER_CHITIN = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_CHITIN, "a layer of", false, "chitin", "chitin", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allScalesCoveringPatterns, PresetColour.naturalScaleColours, PresetColour.allCoveringColours, PresetColour.naturalScaleColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType OCTOPUS_SKIN = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, "a layer of", false, "skin", "skin", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 5), new Value<>(CoveringPattern.SPOTTED, 1)), PresetColour.allSkinColours, PresetColour.allCoveringColours, PresetColour.allSkinColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType FISH_SCALES = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SCALES, "a layer of", true, "scales", "scale", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allScalesCoveringPatterns, PresetColour.naturalScaleColours, PresetColour.allCoveringColours, PresetColour.naturalScaleColours, PresetColour.allCoveringColours) { }; // MISC: public static AbstractBodyCoveringType ANTENNA = new AbstractBodyCoveringType( BodyCoveringCategory.ANTENNAE, "a layer of", false, "chitin", "chitin", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, null, CoveringPattern.allScalesCoveringPatterns, PresetColour.naturalScaleColours, PresetColour.allCoveringColours, PresetColour.naturalScaleColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType HORN = new AbstractBodyCoveringType( BodyCoveringCategory.HORN, "a layer of", false, "keratin", "keratin", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, null, CoveringPattern.allScalesCoveringPatterns, PresetColour.hornColours, PresetColour.allCoveringColours, PresetColour.hornColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType ANTLER = new AbstractBodyCoveringType( BodyCoveringCategory.ANTLER, "a layer of", false, "velvet", "velvet", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, null, CoveringPattern.allScalesCoveringPatterns, PresetColour.antlerColours, PresetColour.allCoveringColours, PresetColour.antlerColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType TONGUE = new AbstractBodyCoveringType( BodyCoveringCategory.TONGUE, "a layer of", false, "skin", "skin", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, null, Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 1), new Value<>(CoveringPattern.HIGHLIGHTS, 1), new Value<>(CoveringPattern.STRIPED, 1), new Value<>(CoveringPattern.SPOTTED, 1), new Value<>(CoveringPattern.MOTTLED, 1), new Value<>(CoveringPattern.MARKED, 1)), Util.newArrayListOfValues(PresetColour.ORIFICE_INTERIOR), PresetColour.allSkinColours, Util.newArrayListOfValues(PresetColour.ORIFICE_INTERIOR), PresetColour.allSkinColours) { }; public static AbstractBodyCoveringType FEATHERS = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_FEATHER, "a layer of", true, "feathers", "feather", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues( new Value<>(CoveringPattern.NONE, 10), new Value<>(CoveringPattern.MARKED, 10), new Value<>(CoveringPattern.SPOTTED, 5), new Value<>(CoveringPattern.MOTTLED, 2), new Value<>(CoveringPattern.STRIPED, 1)), CoveringPattern.allHairCoveringPatterns, PresetColour.naturalFeatherColours, PresetColour.dyeFeatherColours, PresetColour.naturalFeatherColours, PresetColour.dyeFeatherColours) { }; public static AbstractBodyCoveringType WING_LEATHER = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_SKIN, "a layer of", false, "skin", "skin", Util.newArrayListOfValues(CoveringModifier.LEATHERY), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allStandardCoveringPatterns, Util.newArrayListOfValues(PresetColour.COVERING_BLACK), PresetColour.allCoveringColours, Util.newArrayListOfValues(PresetColour.COVERING_BLACK), PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType WING_CHITIN = new AbstractBodyCoveringType( BodyCoveringCategory.MAIN_CHITIN, "a layer of", false, "chitin", "chitin", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allScalesCoveringPatterns, Util.newArrayListOfValues(PresetColour.COVERING_CLEAR), PresetColour.allCoveringColours, Util.newArrayListOfValues(PresetColour.COVERING_CLEAR), PresetColour.allCoveringColours) { }; // HAIR: public static AbstractBodyCoveringType HAIR_HUMAN = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createHeadHair(CoveringModifier.SMOOTH)) {}; public static AbstractBodyCoveringType HAIR_ANGEL = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createHeadHair(CoveringModifier.SILKEN)) {}; public static AbstractBodyCoveringType HAIR_FOX_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, "a layer of", false, "hair", "hair", Util.newArrayListOfValues( CoveringModifier.FURRY), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), CoveringPattern.allHairCoveringPatterns, PresetColour.naturalHairColours, PresetColour.allCoveringColours, PresetColour.naturalHairColours, PresetColour.allCoveringColours) { }; public static AbstractBodyCoveringType HAIR_DEMON = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createHeadHair(CoveringModifier.SILKEN)) {}; public static AbstractBodyCoveringType HAIR_CANINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType HAIR_LYCAN_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType HAIR_FELINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType HAIR_HORSE_HAIR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.COARSE)) {}; public static AbstractBodyCoveringType HAIR_REINDEER_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.COARSE)) {}; public static AbstractBodyCoveringType HAIR_BOVINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.COARSE)) {}; public static AbstractBodyCoveringType HAIR_SQUIRREL_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType HAIR_RAT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType HAIR_RABBIT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType HAIR_BAT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType HAIR_HARPY = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, "a plume of", true, "feathers", "feather", Util.newArrayListOfValues(CoveringModifier.SMOOTH), null, CoveringPattern.allHairCoveringPatterns, null, PresetColour.naturalFeatherColours, PresetColour.dyeFeatherColours, PresetColour.naturalFeatherColours, PresetColour.dyeFeatherColours) { }; public static AbstractBodyCoveringType HAIR_SCALES_ALLIGATOR = new AbstractBodyCoveringType( BodyCoveringCategory.HAIR, BodyCoveringTemplateFactory.createFurHeadHair(CoveringModifier.COARSE)) {}; // BODY HAIR: public static AbstractBodyCoveringType BODY_HAIR_HUMAN = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.COARSE)) {}; public static AbstractBodyCoveringType BODY_HAIR_ANGEL = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.SILKEN)) {}; public static AbstractBodyCoveringType BODY_HAIR_DEMON = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.SILKEN)) {}; public static AbstractBodyCoveringType BODY_HAIR_CANINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_LYCAN_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_FOX_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_FELINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_HORSE_HAIR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.COARSE)) {}; public static AbstractBodyCoveringType BODY_HAIR_REINDEER_HAIR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.COARSE)) {}; public static AbstractBodyCoveringType BODY_HAIR_BOVINE_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.COARSE)) {}; public static AbstractBodyCoveringType BODY_HAIR_SQUIRREL_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_RAT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_RABBIT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_BAT_FUR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.FURRY)) {}; public static AbstractBodyCoveringType BODY_HAIR_HARPY = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, "a patch of", true, "feathers", "feather", Util.newArrayListOfValues(CoveringModifier.FLUFFY), null, null, CoveringPattern.allHairCoveringPatterns, PresetColour.naturalFeatherColours, PresetColour.dyeFeatherColours, PresetColour.naturalFeatherColours, PresetColour.dyeFeatherColours) { }; public static AbstractBodyCoveringType BODY_HAIR_SCALES_ALLIGATOR = new AbstractBodyCoveringType( BodyCoveringCategory.BODY_HAIR, BodyCoveringTemplateFactory.createBodyHair(CoveringModifier.COARSE)) {}; // EYES: public static AbstractBodyCoveringType EYE_HUMAN = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrisesHeterochromiaNaturallyOccurring()) {}; public static AbstractBodyCoveringType EYE_ANGEL = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_DEMON_COMMON = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrisesWithCustomColors( PresetColour.naturalDemonIrisColours, PresetColour.dyeDemonIrisColours, true)) { }; public static AbstractBodyCoveringType EYE_DOG_MORPH = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrisesHeterochromiaNaturallyOccurring()) {}; public static AbstractBodyCoveringType EYE_LYCAN = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrisesWithCustomColors( PresetColour.naturalPredatorIrisColours, PresetColour.dyePredatorIrisColours, true)) { }; public static AbstractBodyCoveringType EYE_FOX_MORPH = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, "a pair of", true, "eyes", "eye", Util.newArrayListOfValues( CoveringModifier.EYE), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_IRISES, 1)), Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_IRISES_HETEROCHROMATIC, 1)), PresetColour.naturalPredatorIrisColours, PresetColour.dyePredatorIrisColours, PresetColour.naturalPredatorIrisColours, PresetColour.dyePredatorIrisColours) { }; public static AbstractBodyCoveringType EYE_FELINE = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrisesWithCustomColors( PresetColour.naturalPredatorIrisColours, PresetColour.dyePredatorIrisColours, true)) { }; public static AbstractBodyCoveringType EYE_SQUIRREL = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_RAT = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_RABBIT = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_BAT = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_ALLIGATOR_MORPH = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_HORSE_MORPH = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrisesHeterochromiaNaturallyOccurring()) {}; public static AbstractBodyCoveringType EYE_REINDEER_MORPH = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_COW_MORPH = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrisesHeterochromiaNaturallyOccurring()) {}; public static AbstractBodyCoveringType EYE_HARPY = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_IRIS, BodyCoveringTemplateFactory.createEyeIrises()) {}; public static AbstractBodyCoveringType EYE_PUPILS = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_PUPIL, "a pair of", true, "pupils", "pupil", Util.newArrayListOfValues(CoveringModifier.EYE), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_PUPILS, 1)), Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_PUPILS_HETEROCHROMATIC, 1)), PresetColour.naturalPupilColours, PresetColour.dyePupilColours, PresetColour.naturalPupilColours, PresetColour.dyePupilColours) { }; public static AbstractBodyCoveringType EYE_SCLERA = new AbstractBodyCoveringType( BodyCoveringCategory.EYE_SCLERA, "a pair of", true, "sclerae", "sclera", Util.newArrayListOfValues(CoveringModifier.EYE), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_SCLERA, 1)), Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_SCLERA_HETEROCHROMATIC, 1)), PresetColour.naturalScleraColours, PresetColour.dyeScleraColours, PresetColour.naturalScleraColours, PresetColour.dyeScleraColours) { }; // Fluids: public static AbstractBodyCoveringType CUM = new AbstractBodyCoveringType( BodyCoveringCategory.FLUID, "", false, "cum", "cum", Util.newArrayListOfValues(CoveringModifier.FLUID), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.FLUID, 1)), null, Util.newArrayListOfValues(PresetColour.COVERING_WHITE), PresetColour.allCoveringColours, null, null) { }; public static AbstractBodyCoveringType GIRL_CUM = new AbstractBodyCoveringType( BodyCoveringCategory.FLUID, "", false, "girlcum", "girlcum", Util.newArrayListOfValues(CoveringModifier.FLUID), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.FLUID, 1)), null, Util.newArrayListOfValues(PresetColour.COVERING_CLEAR), PresetColour.allCoveringColours, null, null) { }; public static AbstractBodyCoveringType MILK = new AbstractBodyCoveringType( BodyCoveringCategory.FLUID, "", false, "milk", "milk", Util.newArrayListOfValues(CoveringModifier.FLUID), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.FLUID, 1)), null, Util.newArrayListOfValues(PresetColour.COVERING_WHITE), PresetColour.allCoveringColours, null, null) { }; // Makeup: public static AbstractBodyCoveringType MAKEUP_BLUSHER = new AbstractBodyCoveringType( BodyCoveringCategory.MAKEUP, "a layer of", false, "blusher", "blusher", Util.newArrayListOfValues(CoveringModifier.MAKEUP), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), null, Util.newArrayListOfValues(PresetColour.COVERING_NONE), PresetColour.allMakeupColours, null, null) { }; public static AbstractBodyCoveringType MAKEUP_EYE_LINER = new AbstractBodyCoveringType( BodyCoveringCategory.MAKEUP, "a layer of", false, "eye liner", "eye liner", Util.newArrayListOfValues(CoveringModifier.MAKEUP), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), null, Util.newArrayListOfValues(PresetColour.COVERING_NONE), PresetColour.allMakeupColours, null, null) { }; public static AbstractBodyCoveringType MAKEUP_EYE_SHADOW = new AbstractBodyCoveringType( BodyCoveringCategory.MAKEUP, "a layer of", false, "eye shadow", "eye shadow", Util.newArrayListOfValues( CoveringModifier.MATTE, CoveringModifier.SPARKLY, CoveringModifier.METALLIC), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), null, Util.newArrayListOfValues(PresetColour.COVERING_NONE), PresetColour.allMakeupColours, null, null) { }; public static AbstractBodyCoveringType MAKEUP_LIPSTICK = new AbstractBodyCoveringType( BodyCoveringCategory.MAKEUP, "a layer of", false, "lipstick", "lipstick", Util.newArrayListOfValues( CoveringModifier.GLOSSY, CoveringModifier.MATTE, CoveringModifier.SPARKLY, CoveringModifier.METALLIC), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), Util.newHashMapOfValues( new Value<>(CoveringPattern.SPOTTED, 1), new Value<>(CoveringPattern.STRIPED, 1)), Util.newArrayListOfValues(PresetColour.COVERING_NONE), PresetColour.allMakeupColours, null, PresetColour.allMakeupColours) { }; public static AbstractBodyCoveringType MAKEUP_NAIL_POLISH_HANDS = new AbstractBodyCoveringType( BodyCoveringCategory.MAKEUP, "a layer of", false, "nail polish", "nail polish", Util.newArrayListOfValues( CoveringModifier.SMOOTH, CoveringModifier.SPARKLY, CoveringModifier.METALLIC), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), Util.newHashMapOfValues( new Value<>(CoveringPattern.SPOTTED, 1), new Value<>(CoveringPattern.STRIPED, 1)), Util.newArrayListOfValues(PresetColour.COVERING_NONE), PresetColour.allMakeupColours, null, PresetColour.allMakeupColours) { }; public static AbstractBodyCoveringType MAKEUP_NAIL_POLISH_FEET = new AbstractBodyCoveringType( BodyCoveringCategory.MAKEUP, "a layer of", false, "nail polish", "nail polish", Util.newArrayListOfValues( CoveringModifier.SMOOTH, CoveringModifier.SPARKLY, CoveringModifier.METALLIC), null, Util.newHashMapOfValues(new Value<>(CoveringPattern.NONE, 1)), Util.newHashMapOfValues( new Value<>(CoveringPattern.SPOTTED, 1), new Value<>(CoveringPattern.STRIPED, 1)), Util.newArrayListOfValues(PresetColour.COVERING_NONE), PresetColour.allMakeupColours, null, PresetColour.allMakeupColours) { }; public static List<AbstractBodyCoveringType> allBodyCoveringTypes; public static Map<AbstractBodyCoveringType, String> bodyCoveringTypesToIdMap = new HashMap<>(); public static Map<String, AbstractBodyCoveringType> idToBodyCoveringTypesMap = new HashMap<>(); public static List<AbstractBodyCoveringType> allMakeupTypes; public static List<AbstractBodyCoveringType> allSlimeTypes; public static AbstractBodyCoveringType getBodyCoveringTypeFromId(String id) { // Imp changes: if(id.equals("IMP")) { id = "DEMON_COMMON"; } else if(id.equals("HAIR_IMP")) { id = "HAIR_DEMON"; } else if(id.equals("BODY_HAIR_IMP")) { id = "BODY_HAIR_DEMON"; } else if(id.equals("EYE_IMP")) { id = "EYE_DEMON_COMMON"; } // Material updates in v0.4: if(id.equals("SLIME")) { id = "SLIME_MAIN_SKIN"; } else if(id.equals("SLIME_EYE")) { id = "SLIME_EYE_IRIS"; } else if(id.equals("SLIME_PUPILS")) { id = "SLIME_EYE_PUPIL"; } else if(id.equals("SLIME_SCLERA")) { id = "SLIME_EYE_SCLERA"; } else if(id.equals("SLIME_NIPPLES")) { id = "SLIME_NIPPLE"; } else if(id.equals("SLIME_NIPPLES_CROTCH")) { id = "SLIME_NIPPLE_CROTCH"; } else if(id.equals("FIRE")) { id = "FIRE_MAIN_SKIN"; } else if(id.equals("WATER")) { id = "WATER_MAIN_SKIN"; } else if(id.equals("ICE")) { id = "ICE_MAIN_SKIN"; } else if(id.equals("AIR")) { id = "AIR_MAIN_SKIN"; } else if(id.equals("STONE")) { id = "STONE_MAIN_SKIN"; } else if(id.equals("RUBBER")) { id = "RUBBER_MAIN_SKIN"; } else if(id.equals("ARCANE")) { id = "ARCANE_MAIN_SKIN"; } // Other changes: if(id.equals("DEMON_HORSE_HAIR")) { id = "HORSE_HAIR"; } else if(id.equals("ANTLER_REINDEER")) { id = "ANTLER"; } id = Util.getClosestStringMatch(id, idToBodyCoveringTypesMap.keySet()); return idToBodyCoveringTypesMap.get(id); } public static String getIdFromBodyCoveringType(AbstractBodyCoveringType bct) { return bodyCoveringTypesToIdMap.get(bct); } /** * @param material The BodyMaterial which the body is made up of. * @param category The BodyCoveringCategory which you want to find the AbstractBodyCoveringType of. * @return The AbstractBodyCoveringType which corresponds to the supplied material and category. */ public static AbstractBodyCoveringType getMaterialBodyCoveringType(BodyMaterial material, BodyCoveringCategory category) { return getBodyCoveringTypeFromId(material.toString()+"_"+category.toString()); } static { allBodyCoveringTypes = new ArrayList<>(); allMakeupTypes = new ArrayList<>(); // Modded covering types: Map<String, Map<String, File>> moddedFilesMap = Util.getExternalModFilesById("/race", "coveringTypes", null); for(Entry<String, Map<String, File>> entry : moddedFilesMap.entrySet()) { for(Entry<String, File> innerEntry : entry.getValue().entrySet()) { try { AbstractBodyCoveringType coveringType = new AbstractBodyCoveringType(innerEntry.getValue(), entry.getKey(), true) {}; String id = innerEntry.getKey().replaceAll("coveringTypes_", ""); allBodyCoveringTypes.add(coveringType); bodyCoveringTypesToIdMap.put(coveringType, id); idToBodyCoveringTypesMap.put(id, coveringType); } catch(Exception ex) { System.err.println("Loading modded bodyCoveringType failed at 'BodyCoveringType'. File path: "+innerEntry.getValue().getAbsolutePath()); System.err.println("Actual exception: "); ex.printStackTrace(System.err); } } } // External res covering types: Map<String, Map<String, File>> filesMap = Util.getExternalFilesById("res/race", "coveringTypes", null); for(Entry<String, Map<String, File>> entry : filesMap.entrySet()) { for(Entry<String, File> innerEntry : entry.getValue().entrySet()) { try { AbstractBodyCoveringType coveringType = new AbstractBodyCoveringType(innerEntry.getValue(), entry.getKey(), false) {}; String id = innerEntry.getKey().replaceAll("coveringTypes_", ""); allBodyCoveringTypes.add(coveringType); bodyCoveringTypesToIdMap.put(coveringType, id); idToBodyCoveringTypesMap.put(id, coveringType); } catch(Exception ex) { System.err.println("Loading bodyCoveringType failed at 'BodyCoveringType'. File path: "+innerEntry.getValue().getAbsolutePath()); System.err.println("Actual exception: "); ex.printStackTrace(System.err); } } } Field[] fields = BodyCoveringType.class.getFields(); for(Field f : fields){ if(AbstractBodyCoveringType.class.isAssignableFrom(f.getType())) { AbstractBodyCoveringType bct; try { bct = ((AbstractBodyCoveringType) f.get(null)); if(bct.getCategory()==BodyCoveringCategory.MAKEUP) { allMakeupTypes.add(bct); } bodyCoveringTypesToIdMap.put(bct, f.getName()); idToBodyCoveringTypesMap.put(f.getName(), bct); allBodyCoveringTypes.add(bct); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } } // Automatically add AbstractBodyCoveringTypes for all non-flesh materials: for(BodyMaterial mat : BodyMaterial.values()) { if(mat!=BodyMaterial.FLESH) { if(mat==BodyMaterial.SLIME) { allSlimeTypes = new ArrayList<>(); for(BodyCoveringCategory cat : BodyCoveringCategory.values()) { AbstractBodyCoveringType bct = null; switch(cat) { case ANTENNAE: case ANTLER: case HORN: case BODY_HAIR: case HAIR: case MAIN_FEATHER: case MAIN_FUR: case MAIN_HAIR: case MAIN_SCALES: case MAIN_CHITIN: case MAIN_SKIN: case PENIS: case TONGUE: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.NONE, CoveringPattern.allSlimeCoveringPatterns)) {}; break; case EYE_IRIS: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.EYE_IRISES, Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_IRISES_HETEROCHROMATIC, 1)))) { }; break; case EYE_PUPIL: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.EYE_PUPILS, Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_IRISES_HETEROCHROMATIC, 1)))) { }; break; case EYE_SCLERA: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.EYE_SCLERA, Util.newHashMapOfValues(new Value<>(CoveringPattern.EYE_IRISES_HETEROCHROMATIC, 1)))) { }; break; case ANUS: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.ORIFICE_ANUS, null)) {}; break; case MOUTH: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.ORIFICE_MOUTH, null)) {}; break; case NIPPLE: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.ORIFICE_NIPPLE, null)) {}; break; case NIPPLE_CROTCH: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.ORIFICE_NIPPLE_CROTCH, null)) {}; break; case VAGINA: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.ORIFICE_VAGINA, null)) {}; break; case SPINNERET: bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createSlime(CoveringPattern.ORIFICE_SPINNERET, null)) {}; break; case ARTIFICIAL: case FLUID: case MAKEUP: break; } if(bct!=null) { String id = mat.toString()+"_"+cat.toString(); bodyCoveringTypesToIdMap.put(bct,id); idToBodyCoveringTypesMap.put(id, bct); allBodyCoveringTypes.add(bct); allSlimeTypes.add(bct); } } } else { String name = ""; CoveringModifier modifier = CoveringModifier.SMOOTH; List<Colour> naturalColours = new ArrayList<>(); switch(mat) { case FLESH: case SLIME: break; case AIR: name = "vapours"; modifier = CoveringModifier.SWIRLING; naturalColours.add(PresetColour.COVERING_BLUE_LIGHT); naturalColours.add(PresetColour.COVERING_GREY); naturalColours.add(PresetColour.COVERING_WHITE); break; case ARCANE: name = "energy"; modifier = CoveringModifier.SWIRLING; naturalColours.add(PresetColour.COVERING_PINK); naturalColours.add(PresetColour.COVERING_PINK_DARK); naturalColours.add(PresetColour.COVERING_PINK_LIGHT); break; case FIRE: name = "flames"; modifier = CoveringModifier.BLAZING; naturalColours.add(PresetColour.COVERING_RED); naturalColours.add(PresetColour.COVERING_ORANGE); naturalColours.add(PresetColour.COVERING_YELLOW); naturalColours.add(PresetColour.COVERING_BLUE_LIGHT); break; case ICE: name = "ice"; modifier = CoveringModifier.GLITTERING; naturalColours.add(PresetColour.COVERING_BLUE_LIGHT); naturalColours.add(PresetColour.COVERING_WHITE); break; case RUBBER: name = "rubber"; modifier = CoveringModifier.GLOSSY; naturalColours.add(PresetColour.COVERING_BLACK); break; case STONE: name = "stone"; modifier = CoveringModifier.MATTE; naturalColours.add(PresetColour.COVERING_GREY); naturalColours.add(PresetColour.COVERING_BLACK); break; case WATER: name = "water"; modifier = CoveringModifier.SHIMMERING; naturalColours.add(PresetColour.COVERING_BLUE); naturalColours.add(PresetColour.COVERING_BLUE_LIGHT); naturalColours.add(PresetColour.COVERING_BLUE_DARK); break; } for(BodyCoveringCategory cat : BodyCoveringCategory.values()) { if(cat.isInfluencedByMaterialType()) { CoveringPattern pattern = CoveringPattern.NONE; switch(cat) { case ANTENNAE: case ANTLER: case HORN: case BODY_HAIR: case HAIR: case MAIN_FEATHER: case MAIN_FUR: case MAIN_HAIR: case MAIN_SCALES: case MAIN_CHITIN: case MAIN_SKIN: case PENIS: case TONGUE: break; case EYE_IRIS: pattern = CoveringPattern.EYE_IRISES; break; case EYE_PUPIL: pattern = CoveringPattern.EYE_PUPILS; break; case EYE_SCLERA: pattern = CoveringPattern.EYE_SCLERA; break; case ANUS: pattern = CoveringPattern.ORIFICE_ANUS; break; case MOUTH: pattern = CoveringPattern.ORIFICE_MOUTH; break; case NIPPLE: pattern = CoveringPattern.ORIFICE_NIPPLE; break; case NIPPLE_CROTCH: pattern = CoveringPattern.ORIFICE_NIPPLE_CROTCH; break; case VAGINA: pattern = CoveringPattern.ORIFICE_VAGINA; break; case SPINNERET: pattern = CoveringPattern.ORIFICE_SPINNERET; break; case ARTIFICIAL: case FLUID: case MAKEUP: break; } AbstractBodyCoveringType bct = new AbstractBodyCoveringType(cat, BodyCoveringTemplateFactory.createElemental(name, modifier, pattern, naturalColours)) {}; String id = mat.toString()+"_"+cat.toString(); bodyCoveringTypesToIdMap.put(bct, id); idToBodyCoveringTypesMap.put(id, bct); allBodyCoveringTypes.add(bct); } } } } } } public static List<AbstractBodyCoveringType> getAllBodyCoveringTypes() { return allBodyCoveringTypes; } public static List<AbstractBodyCoveringType> getAllMakeupTypes() { return allMakeupTypes; } public static List<AbstractBodyCoveringType> getAllSlimeTypes() { return allSlimeTypes; } }
3e0a9f6361e414cb5685c140123e2f0bd77ec5bf
898
java
Java
DataBaseDev/SQLAdvanced/MultitableQueryPractice/train8.java
tewentong/JavaHub
021e9a2366f0f8a842d7af970c1432e9099bbc1c
[ "MIT" ]
null
null
null
DataBaseDev/SQLAdvanced/MultitableQueryPractice/train8.java
tewentong/JavaHub
021e9a2366f0f8a842d7af970c1432e9099bbc1c
[ "MIT" ]
null
null
null
DataBaseDev/SQLAdvanced/MultitableQueryPractice/train8.java
tewentong/JavaHub
021e9a2366f0f8a842d7af970c1432e9099bbc1c
[ "MIT" ]
null
null
null
40.818182
96
0.328508
4,499
/* 列出与FORD从事相同工作的所有员工及部门名称 列:e.*, d.dname 表:EMP e, DEPT d 条件:job=(查询出庞统的工作) 答案: SELECT e.*, d.dname FROM EMP e, DEPT d WHERE e.deptno=d.deptno AND job=(SELECT job from EMP WHERE ename='FORD'); 程序输出: +-------+-------+---------+------+------------+---------+------+--------+----------+ | EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO | dname | +-------+-------+---------+------+------------+---------+------+--------+----------+ | 7788 | SCOTT | ANALYST | 7566 | 1987-04-19 | 3000.00 | NULL | 20 | RESEARCH | | 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | RESEARCH | +-------+-------+---------+------+------------+---------+------+--------+----------+ */ public class train8 { }
3e0a9f90c83af553fc663a9657de19ee03ea8529
4,831
java
Java
adpharma/adpharma.client/src/main/java/org/adorsys/adpharma/client/jpa/article/ArticleSectionController.java
francis-pouatcha/forgelab
fdcbbded852a985f3bd437b639a2284d92703e33
[ "Apache-2.0" ]
null
null
null
adpharma/adpharma.client/src/main/java/org/adorsys/adpharma/client/jpa/article/ArticleSectionController.java
francis-pouatcha/forgelab
fdcbbded852a985f3bd437b639a2284d92703e33
[ "Apache-2.0" ]
null
null
null
adpharma/adpharma.client/src/main/java/org/adorsys/adpharma/client/jpa/article/ArticleSectionController.java
francis-pouatcha/forgelab
fdcbbded852a985f3bd437b639a2284d92703e33
[ "Apache-2.0" ]
null
null
null
32.863946
99
0.673774
4,500
package org.adorsys.adpharma.client.jpa.article; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.ResourceBundle; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.WorkerStateEvent; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javax.inject.Inject; import org.adorsys.adpharma.client.jpa.section.Section; import org.adorsys.adpharma.client.jpa.section.SectionSearchInput; import org.adorsys.adpharma.client.jpa.section.SectionSearchResult; import org.adorsys.adpharma.client.jpa.section.SectionSearchService; import org.adorsys.javafx.crud.extensions.locale.Bundle; import org.adorsys.javafx.crud.extensions.locale.CrudKeys; import org.adorsys.javafx.crud.extensions.login.ErrorDisplay; import org.adorsys.javafx.crud.extensions.login.ServiceCallFailedEventHandler; import org.adorsys.javafx.crud.extensions.view.ErrorMessageDialog; import org.apache.commons.lang3.StringUtils; public abstract class ArticleSectionController { @Inject private SectionSearchService searchService; @Inject private ServiceCallFailedEventHandler searchServiceCallFailedEventHandler; private SectionSearchResult targetSearchResult; @Inject @Bundle({ CrudKeys.class, Section.class, Article.class }) private ResourceBundle resourceBundle; @Inject private ErrorMessageDialog errorMessageDialog; protected Article sourceEntity; protected void disableButton(final ArticleSectionSelection selection) { selection.getSection().setDisable(true); } protected void activateButton(final ArticleSectionSelection selection) { } protected void bind(final ArticleSectionSelection selection, final ArticleSectionForm form) { // selection.getSection().valueProperty().bindBidirectional(sourceEntity.sectionProperty()); // send search result event. searchService.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent event) { SectionSearchService s = (SectionSearchService) event .getSource(); targetSearchResult = s.getValue(); event.consume(); s.reset(); List<Section> entities = targetSearchResult.getResultList(); selection.getSection().getItems().clear(); selection.getSection().getItems().add(new ArticleSection()); entities.sort(new Comparator<Section>() { @Override public int compare(Section o1, Section o2) { // TODO Auto-generated method stub return o1.getName().compareToIgnoreCase(o2.getName()); } }); ArrayList<ArticleSection> arrayList = new ArrayList<ArticleSection>(); for (Section entity : entities) { arrayList.add(new ArticleSection(entity)); } selection.getSection().getItems().addAll(arrayList); } }); searchServiceCallFailedEventHandler.setErrorDisplay(new ErrorDisplay() { @Override protected void showError(Throwable exception) { String message = exception.getMessage(); errorMessageDialog.getTitleText().setText( resourceBundle.getString("Entity_search_error.title")); if (!StringUtils.isBlank(message)) errorMessageDialog.getDetailText().setText(message); errorMessageDialog.display(); } }); searchService.setOnFailed(searchServiceCallFailedEventHandler); errorMessageDialog.getOkButton().setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { errorMessageDialog.closeDialog(); } }); selection.getSection().valueProperty().addListener(new ChangeListener<ArticleSection>() { @Override public void changed(ObservableValue<? extends ArticleSection> ov, ArticleSection oldValue, ArticleSection newValue) { if (sourceEntity != null) form.update(newValue); // sourceEntity.setSection(newValue); } }); selection.getSection().armedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observableValue, Boolean oldValue, Boolean newValue) { if (newValue) load(); } }); } public void load() { // if(searchService.isRunning()) return; searchService.setSearchInputs(new SectionSearchInput()).start(); } }
3e0a9fc0d4e3d9fdb59c9262ec100fab37ddefb6
2,632
java
Java
backend/src/main/java/me/steffenjacobs/supersocial/domain/entity/Post.java
steffenjacobs/supersocial
d6fda66e95d21a09e2c6c4e32b89a29b4dc7b051
[ "MIT" ]
6
2020-04-26T12:23:02.000Z
2021-08-02T18:52:43.000Z
backend/src/main/java/me/steffenjacobs/supersocial/domain/entity/Post.java
steffenjacobs/supersocial
d6fda66e95d21a09e2c6c4e32b89a29b4dc7b051
[ "MIT" ]
null
null
null
backend/src/main/java/me/steffenjacobs/supersocial/domain/entity/Post.java
steffenjacobs/supersocial
d6fda66e95d21a09e2c6c4e32b89a29b4dc7b051
[ "MIT" ]
null
null
null
20.724409
95
0.778116
4,501
package me.steffenjacobs.supersocial.domain.entity; import java.util.Date; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.GenericGenerator; /** @author Steffen Jacobs */ @Entity public class Post implements Secured { @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") @Column(name = "id", updatable = false, nullable = false) private UUID id; @Column private String text; @Column private String externalId; @Column @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) private Date created; @Column @Temporal(TemporalType.TIMESTAMP) private Date published; @ManyToOne private SupersocialUser creator; @Column(length = 512) private String errorMessage; @OneToOne private AccessControlList accessControlList; @ManyToOne(fetch = FetchType.EAGER) private SocialMediaAccount socialMediaAccountToPostWith; public String getText() { return text; } public void setText(String text) { this.text = text; } public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } public UUID getId() { return id; } public Date getCreated() { return created; } public void setCreator(SupersocialUser creator) { this.creator = creator; } public SupersocialUser getCreator() { return creator; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getErrorMessage() { return errorMessage; } public Date getPublished() { return published; } public void setPublished(Date published) { this.published = published; } @Override public SecuredType getSecuredType() { return SecuredType.POST; } @Override public AccessControlList getAccessControlList() { return accessControlList; } @Override public void setAccessControlList(AccessControlList accessControlList) { this.accessControlList = accessControlList; } public SocialMediaAccount getSocialMediaAccountToPostWith() { return socialMediaAccountToPostWith; } public void setSocialMediaAccountToPostWith(SocialMediaAccount socialMediaAccountToPostWith) { this.socialMediaAccountToPostWith = socialMediaAccountToPostWith; } }
3e0a9ff90de24af1520e9d7c1decba3640cd0ae2
3,634
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ServoTestSwing.java
ftcshortcircuits/Artemis6
ac42b647320f2c58180937e87a7d425ade5ff28e
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ServoTestSwing.java
ftcshortcircuits/Artemis6
ac42b647320f2c58180937e87a7d425ade5ff28e
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ServoTestSwing.java
ftcshortcircuits/Artemis6
ac42b647320f2c58180937e87a7d425ade5ff28e
[ "MIT" ]
null
null
null
37.854167
103
0.679417
4,502
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.Servo; /** * Tests a single servo. Name is hard-coded, and will have to be edited to match configuration. Servo * will move to zero at "Run", then respond with movement on each button press: "Y" to increase servo * position, "A" to reduce it. */ @TeleOp(name="ServoTestSwing", group="Linear Opmode") @Disabled public class ServoTestSwing extends LinearOpMode { private Servo testServo; private boolean yUp, aUp; private double testPos = 0.50; private double step = 0.01; @Override public void runOpMode() { testServo = hardwareMap.get(Servo.class, "swingServo"); // Hardcoded configuration name telemetry.addData("Status", "Initialized"); telemetry.addData("Initial position will be ", testPos); telemetry.addData("Button 'Y' increases, 'A' decreases, in steps of ", step); telemetry.update(); waitForStart(); testServo.setPosition(testPos); // Initial position aUp = true; yUp = true; while (opModeIsActive()){ if(!gamepad2.a) aUp = true; if(!gamepad2.y) yUp = true; if(gamepad2.a && aUp){ aUp = false; testPos -= step; testServo.setPosition(testPos); telemetry.addData("Servo position: ","%.03f", testPos); telemetry.update(); } if(gamepad2.y && yUp){ yUp = false; testPos += step; testServo.setPosition(testPos); telemetry.addData("Servo position: ","%.03f", testPos); telemetry.update(); } } } }
3e0a9ffafb7c4ef0c31ccce2912c488c8dc7aec1
1,900
java
Java
projects/OG-Language/Client/src/com/opengamma/language/invoke/TypeConverter.java
gsteri1/OG-Platform
e682c31e69cadde06dd3776544913dde17fe41ba
[ "Apache-2.0" ]
1
2021-02-27T21:05:05.000Z
2021-02-27T21:05:05.000Z
projects/OG-Language/Client/src/com/opengamma/language/invoke/TypeConverter.java
gsteri1/OG-Platform
e682c31e69cadde06dd3776544913dde17fe41ba
[ "Apache-2.0" ]
null
null
null
projects/OG-Language/Client/src/com/opengamma/language/invoke/TypeConverter.java
gsteri1/OG-Platform
e682c31e69cadde06dd3776544913dde17fe41ba
[ "Apache-2.0" ]
null
null
null
33.333333
132
0.72
4,503
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.language.invoke; import java.util.Map; import com.opengamma.language.convert.ValueConversionContext; import com.opengamma.language.definition.JavaTypeInfo; /** * Rule for converting data to a specific type. */ public interface TypeConverter { /** * Tests whether the type converter will attempt to produce a value of the given type. * * @param targetType the desired type, not null * @return true if the type can be produced, false if it can never be produced */ boolean canConvertTo(JavaTypeInfo<?> targetType); /** * Returns the set of types the converter will attempt to convert directly into the given type. * * @param targetType the desired type, not null. This will only be invoked for types that return true from {@link #canConvertTo}. * @return the types it can convert to the target type with the conversion cost, not empty, not null */ Map<JavaTypeInfo<?>, Integer> getConversionsTo(JavaTypeInfo<?> targetType); /** * Converts a value to a specified type if possible. * <p> * If the conversion is not possible indicates the failure within the {@code conversionContext}. * * @param conversionContext the value conversion context * @param value the value to convert from * @param type the type to convert to for the type */ void convertValue(ValueConversionContext conversionContext, Object value, JavaTypeInfo<?> type); /** * Returns a "key" to identify the converter. * <p> * Only one converter with any given key is allowed in a chain. This is enforced by the * aggregator so that a language binding can override conversions already provided. * * @return the converter key, not null */ String getTypeConverterKey(); }
3e0aa047d46a37ef98d7aa9b966b3a4521358cee
5,148
java
Java
src/main/java/io/github/pulsebeat02/nativelibraryloader/utils/NativeUtils.java
PulseBeat02/native-library-loader
26e9ef93d96015f920fdea3aff014f0f76adb751
[ "MIT" ]
1
2021-12-25T22:51:26.000Z
2021-12-25T22:51:26.000Z
src/main/java/io/github/pulsebeat02/nativelibraryloader/utils/NativeUtils.java
PulseBeat02/native-library-loader
26e9ef93d96015f920fdea3aff014f0f76adb751
[ "MIT" ]
1
2021-12-28T22:47:26.000Z
2021-12-28T22:47:26.000Z
src/main/java/io/github/pulsebeat02/nativelibraryloader/utils/NativeUtils.java
PulseBeat02/native-library-loader
26e9ef93d96015f920fdea3aff014f0f76adb751
[ "MIT" ]
null
null
null
32.582278
100
0.706099
4,504
/** * MIT License * * <p>Copyright (c) 2021 Brandon Li * * <p>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: * * <p>The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * <p>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 io.github.pulsebeat02.nativelibraryloader.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; public final class NativeUtils { private static final Path TEMPORARY_DIRECTORY; private static final String JNA_LIBRARY_PATH; static { try { TEMPORARY_DIRECTORY = FileUtils.createTempDirectory("native-library-loader"); FileUtils.deleteOnExit(TEMPORARY_DIRECTORY); JNA_LIBRARY_PATH = "jna.library.path"; } catch (final IOException e) { throw new AssertionError(e); } } private NativeUtils() {} public static void loadLibraryFromUrl(final String url) throws IOException { if (!isValidUrl(url)) { throw new IllegalArgumentException("The url must be valid!"); } final String filename = FileUtils.getFileNameFromUrl(url); if (!isValidName(filename)) { throw new IllegalArgumentException("The filename has to be at least 3 characters long."); } final Path downloaded = FileUtils.downloadFile(url, TEMPORARY_DIRECTORY); System.load(downloaded.toString()); addSearchPath(downloaded.getParent()); } private static boolean isValidUrl(final String url) { try { new URL(url).toURI(); return true; } catch (final MalformedURLException | URISyntaxException e) { return false; } } public static void loadLibraryFromJar(final String path) throws IOException { if (!isAbsolute(path)) { throw new IllegalArgumentException("The path has to be absolute (start with '/')."); } final String[] parts = path.split("/"); final String filename = (parts.length > 1) ? parts[parts.length - 1] : null; if (!isValidName(filename)) { throw new IllegalArgumentException("The filename has to be at least 3 characters long."); } loadNativeBinary(copyNativeLibrary(path, filename)); } private static boolean isAbsolute(final String path) { return path != null && path.startsWith("/"); } private static boolean isValidName(final String name) { return name != null && name.length() >= 3; } private static void loadNativeBinary(final Path temp) throws IOException { try { System.load(temp.toString()); addSearchPath(temp.getParent()); } finally { deleteNativeBinary(temp); } } private static void deleteNativeBinary(final Path temp) throws IOException { if (FileUtils.isPosixCompliant()) { Files.deleteIfExists(temp); } else { FileUtils.deleteOnExit(temp); } } private static Path copyNativeLibrary(final String path, final String filename) throws IOException { final Path temp = TEMPORARY_DIRECTORY.resolve(filename); try (final InputStream is = NativeUtils.class.getResourceAsStream(path)) { validateStream(is); Files.copy(is, temp, StandardCopyOption.REPLACE_EXISTING); } return temp; } private static void validateStream(final InputStream stream) { if (stream == null) { throw new IllegalArgumentException("Native library stream cannot be null!"); } } /** * Adds a search directory for JNA to the search path. * * @param directory the directory */ public static void addSearchPath(final Path directory) { final String dir = directory.toString(); final String property = System.getProperty(JNA_LIBRARY_PATH); // only single path if (property == null || property.equals("null")) { System.setProperty(JNA_LIBRARY_PATH, dir); return; } final String[] paths = System.getProperty(JNA_LIBRARY_PATH).split(";"); for (final String path : paths) { if (path.equals(dir)) { return; // already included } } System.setProperty( JNA_LIBRARY_PATH, String.format("%s%s%s", property, File.pathSeparator, dir)); } }
3e0aa04b8fa83eec25bd13cf5ae79dba3448b02e
6,853
java
Java
src/test/org/apache/hcatalog/mapreduce/TestHCatHiveCompatibility.java
kidaak/hcatalog
f18216c56eb571445912044b0b6502843d4a2488
[ "ECL-2.0", "Apache-2.0" ]
2
2018-11-02T06:36:51.000Z
2021-06-14T22:26:28.000Z
src/test/org/apache/hcatalog/mapreduce/TestHCatHiveCompatibility.java
kidaak/hcatalog
f18216c56eb571445912044b0b6502843d4a2488
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/test/org/apache/hcatalog/mapreduce/TestHCatHiveCompatibility.java
kidaak/hcatalog
f18216c56eb571445912044b0b6502843d4a2488
[ "ECL-2.0", "Apache-2.0" ]
4
2021-02-25T17:50:30.000Z
2021-11-23T15:35:45.000Z
39.16
120
0.732088
4,505
/** * 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.hcatalog.mapreduce; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Properties; import junit.framework.TestCase; import org.apache.hadoop.hive.cli.CliSessionState; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.ql.Driver; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hcatalog.MiniCluster; import org.apache.hcatalog.common.HCatConstants; import org.apache.hcatalog.pig.HCatLoader; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.data.Tuple; import org.apache.pig.impl.util.UDFContext; public class TestHCatHiveCompatibility extends TestCase { MiniCluster cluster = MiniCluster.buildCluster(); private Driver driver; Properties props; private HiveMetaStoreClient client; String fileName = "/tmp/input.data"; String fullFileName; @Override protected void setUp() throws Exception { HiveConf hiveConf = new HiveConf(this.getClass()); hiveConf.set(HiveConf.ConfVars.PREEXECHOOKS.varname, ""); hiveConf.set(HiveConf.ConfVars.POSTEXECHOOKS.varname, ""); hiveConf.set(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname, "false"); driver = new Driver(hiveConf); client = new HiveMetaStoreClient(hiveConf); SessionState.start(new CliSessionState(hiveConf)); props = new Properties(); props.setProperty("fs.default.name", cluster.getProperties().getProperty("fs.default.name")); fullFileName = cluster.getProperties().getProperty("fs.default.name") + fileName; MiniCluster.deleteFile(cluster, fileName); int LOOP_SIZE = 11; String[] input = new String[LOOP_SIZE]; for(int i = 0; i < LOOP_SIZE; i++) { input[i] = i + "\t1"; } MiniCluster.createInputFile(cluster, fileName, input); } @Override protected void tearDown() throws Exception { MiniCluster.deleteFile(cluster, fileName); } public void testUnpartedReadWrite() throws Exception{ driver.run("drop table junit_unparted_noisd"); String createTable = "create table junit_unparted_noisd(a int) stored as RCFILE"; int retCode = driver.run(createTable).getResponseCode(); if(retCode != 0) { throw new IOException("Failed to create table."); } // assert that the table created has no howl instrumentation, and that we're still able to read it. Table table = client.getTable("default", "junit_unparted_noisd"); assertFalse(table.getParameters().containsKey(HCatConstants.HCAT_ISD_CLASS)); assertTrue(table.getSd().getInputFormat().equals(HCatConstants.HIVE_RCFILE_IF_CLASS)); PigServer server = new PigServer(ExecType.LOCAL, props); UDFContext.getUDFContext().setClientSystemProps(); server.registerQuery("A = load '"+fullFileName+"' as (a:int);"); server.registerQuery("store A into 'default.junit_unparted_noisd' using org.apache.hcatalog.pig.HCatStorer();"); server.registerQuery("B = load 'default.junit_unparted_noisd' using "+HCatLoader.class.getName()+"();"); Iterator<Tuple> itr= server.openIterator("B"); int i = 0; while(itr.hasNext()){ Tuple t = itr.next(); assertEquals(1, t.size()); assertEquals(t.get(0), i); i++; } assertFalse(itr.hasNext()); assertEquals(11, i); // assert that the table created still has no howl instrumentation Table table2 = client.getTable("default", "junit_unparted_noisd"); assertFalse(table2.getParameters().containsKey(HCatConstants.HCAT_ISD_CLASS)); assertTrue(table2.getSd().getInputFormat().equals(HCatConstants.HIVE_RCFILE_IF_CLASS)); driver.run("drop table junit_unparted_noisd"); } public void testPartedRead() throws Exception{ driver.run("drop table junit_parted_noisd"); String createTable = "create table junit_parted_noisd(a int) partitioned by (b string) stored as RCFILE"; int retCode = driver.run(createTable).getResponseCode(); if(retCode != 0) { throw new IOException("Failed to create table."); } // assert that the table created has no howl instrumentation, and that we're still able to read it. Table table = client.getTable("default", "junit_parted_noisd"); assertFalse(table.getParameters().containsKey(HCatConstants.HCAT_ISD_CLASS)); assertTrue(table.getSd().getInputFormat().equals(HCatConstants.HIVE_RCFILE_IF_CLASS)); PigServer server = new PigServer(ExecType.LOCAL, props); UDFContext.getUDFContext().setClientSystemProps(); server.registerQuery("A = load '"+fullFileName+"' as (a:int);"); server.registerQuery("store A into 'default.junit_parted_noisd' using org.apache.hcatalog.pig.HCatStorer('b=42');"); server.registerQuery("B = load 'default.junit_parted_noisd' using "+HCatLoader.class.getName()+"();"); Iterator<Tuple> itr= server.openIterator("B"); int i = 0; while(itr.hasNext()){ Tuple t = itr.next(); assertEquals(2, t.size()); assertEquals(t.get(0), i); assertEquals(t.get(1), "42"); i++; } assertFalse(itr.hasNext()); assertEquals(11, i); // assert that the table created still has no howl instrumentation Table table2 = client.getTable("default", "junit_parted_noisd"); assertFalse(table2.getParameters().containsKey(HCatConstants.HCAT_ISD_CLASS)); assertTrue(table2.getSd().getInputFormat().equals(HCatConstants.HIVE_RCFILE_IF_CLASS)); // assert that there is one partition present, and it had howl instrumentation inserted when it was created. Partition ptn = client.getPartition("default", "junit_parted_noisd", Arrays.asList("42")); assertNotNull(ptn); assertTrue(ptn.getParameters().containsKey(HCatConstants.HCAT_ISD_CLASS)); assertTrue(ptn.getSd().getInputFormat().equals(HCatConstants.HIVE_RCFILE_IF_CLASS)); driver.run("drop table junit_unparted_noisd"); } }
3e0aa376a4bb1ada179eb05940627f78f216cc8e
449
java
Java
even odd diff/EvenOddDiff.java
Jajabenit250/java-exercises
64382b49713fccf98362cfd68fb4d6a9149c2b9c
[ "Apache-2.0" ]
1
2021-05-19T04:27:26.000Z
2021-05-19T04:27:26.000Z
even odd diff/EvenOddDiff.java
Jajabenit250/java-exercises
64382b49713fccf98362cfd68fb4d6a9149c2b9c
[ "Apache-2.0" ]
null
null
null
even odd diff/EvenOddDiff.java
Jajabenit250/java-exercises
64382b49713fccf98362cfd68fb4d6a9149c2b9c
[ "Apache-2.0" ]
null
null
null
17.96
44
0.360802
4,506
/** * EvenOddDiff */ public class EvenOddDiff { public static void main(String[] args) { int a[] = {5,6,1, 9,3,8}; System.out.println(diff(a)); } static int diff(int a[]) { int x = 0; int y = 0; for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { x += a[i]; } else { y += a[i]; } } return x-y; } }
3e0aa41399f6c25744a529495194bbd27017cb36
1,159
java
Java
src/main/java/com/handicraft/client/mixin/client/FluidRenderer_MatchWaters.java
TheShinyBunny/HandiClient
95b657e46d9730b83ae5fa15ed5e34cb8a7ff873
[ "MIT" ]
null
null
null
src/main/java/com/handicraft/client/mixin/client/FluidRenderer_MatchWaters.java
TheShinyBunny/HandiClient
95b657e46d9730b83ae5fa15ed5e34cb8a7ff873
[ "MIT" ]
null
null
null
src/main/java/com/handicraft/client/mixin/client/FluidRenderer_MatchWaters.java
TheShinyBunny/HandiClient
95b657e46d9730b83ae5fa15ed5e34cb8a7ff873
[ "MIT" ]
null
null
null
38.633333
162
0.74547
4,507
/* * Copyright (c) 2020. Yaniv - TheShinyBunny */ package com.handicraft.client.mixin.client; import net.minecraft.client.render.block.FluidRenderer; import net.minecraft.fluid.Fluid; import net.minecraft.tag.FluidTags; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(FluidRenderer.class) public class FluidRenderer_MatchWaters { @Redirect(method = "isSameFluid",at = @At(value = "INVOKE",target = "Lnet/minecraft/fluid/Fluid;matchesType(Lnet/minecraft/fluid/Fluid;)Z")) private static boolean matchesWater(Fluid fluid1, Fluid fluid2) { if (fluid1.isIn(FluidTags.WATER) && fluid2.isIn(FluidTags.WATER)) return true; return fluid1.matchesType(fluid2); } @Redirect(method = "getNorthWestCornerFluidHeight",at = @At(value = "INVOKE",target = "Lnet/minecraft/fluid/Fluid;matchesType(Lnet/minecraft/fluid/Fluid;)Z")) private boolean matchesWater2(Fluid fluid1, Fluid fluid2) { if (fluid1.isIn(FluidTags.WATER) && fluid2.isIn(FluidTags.WATER)) return true; return fluid1.matchesType(fluid2); } }
3e0aa43cc111ce81b0f656c8ef5e21a5f3d2b8b1
8,059
java
Java
src/main/java/io/github/xiaohua/support/commons/base/util/ParameterUtil.java
z-xiaohua/support-commons-base
d64f1c5f102488a2be16293dff436a049e9d967a
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/xiaohua/support/commons/base/util/ParameterUtil.java
z-xiaohua/support-commons-base
d64f1c5f102488a2be16293dff436a049e9d967a
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/xiaohua/support/commons/base/util/ParameterUtil.java
z-xiaohua/support-commons-base
d64f1c5f102488a2be16293dff436a049e9d967a
[ "Apache-2.0" ]
null
null
null
27.982639
88
0.606651
4,508
package io.github.xiaohua.support.commons.base.util; import io.github.xiaohua.support.commons.base.exception.BaseException; import io.github.xiaohua.support.commons.base.exception.ServerCode; import java.util.Collection; import java.util.Date; import org.apache.commons.lang3.StringUtils; /** * 参数判断的工具类 * * @author zhongxiaohua */ public class ParameterUtil { /** * 限定参数不能为空(null,""),也不可以全部字符是空格,否则抛出BaseException * * @param s 字符串 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertNotBlank(String s, String errorMessage) { if (StringUtils.isBlank(s)) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定参数必须为true,否则抛出BaseException * * @param b 布尔值 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertTrue(boolean b, String errorMessage) { if (!b) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定参数必须为false,否则抛出BaseException * * @param b 布尔值 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertFalse(boolean b, String errorMessage) { if (b) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定参数的长度不能超过指定值,否则抛出异常。 当 s 不等于null,并且长度超出maxLength才抛出异常。 * * @param s 要判断的字符串 * @param maxLength 指定长度 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertMaxLength(String s, int maxLength, String errorMessage) { if (s != null && s.length() > maxLength) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定一个整数不能是负数,否则抛出BaseException * * @param n 要判断的整数 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertNonNegativeInt(int n, String errorMessage) { if (n < 0) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定a必须大于等于b,否则抛出BaseException * * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertGreaterThanOrEqual(int a, int b, String errorMessage) { if (a < b) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定a必须大于等于b,否则抛出BaseException * * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertGreaterThanOrEqual(short a, short b, String errorMessage) { if (a < b) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定a必须等于b,否则抛出BaseException * * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertEqual(int a, int b, String errorMessage) { if (a != b) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定a必须大于等于b,否则抛出BaseException * * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertGreaterThanOrEqual(long a, long b, String errorMessage) { if (a < b) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 限定输入值必须是指定列表的其中之一,否则抛出BaseException * * @param a 输入值 * @param errorMessage 出错时的异常错误信息 * @param values 指定列表 * @throws BaseException 出错时抛出异常 */ public static void assertOneOfThem(short a, String errorMessage, short... values) { boolean pass = false; if (values != null) { for (short n : values) { if (a == n) { pass = true; break; } } } else { throw new IllegalArgumentException("values为空"); } if (!pass) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断参数必须大于 0,否则抛出异常 * * @param n 要判断的数字 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertGreaterThanZero(Integer n, String errorMessage) { if (n == null || n < 1) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断参数必须大于 0,否则抛出异常 * * @param n 要判断的数字 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertGreaterThanZero(Short n, String errorMessage) { if (n == null || n < 1) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断参数必须大于 0,否则抛出异常 * * @param n 要判断的数字 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertGreaterThanZero(Long n, String errorMessage) { if (n == null || n < 1L) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断参数列表里必须有一个大于0 * * @param values 要判断的数字组合 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertOneOfThemThanZero(String errorMessage, int... values) { boolean exception = true; if (values != null) { for (int n : values) { if (n >= 0) { exception = false; break; } } } if (exception) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断参数不能为null,否则抛出异常 * * @param o 要判断的参数 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertNotNull(Object o, String errorMessage) { if (o == null) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断参数是否为null,不为null否则抛出异常 * * @param o 要判断的参数 * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertNull(Object o, String errorMessage) { if (o != null) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断时间范围的合法性,end>=start,否则抛出异常 * * @param start 开始时间,不能为null * @param end 结束时间,不能为null * @param errorMessage 出错时的异常错误信息 * @throws BaseException 出错时抛出异常 */ public static void assertTimeRange(Date start, Date end, String errorMessage) { if (start == null || end == null) { throw new IllegalArgumentException("start或end为空"); } if (start.after(end)) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 判断集合不能为空, 否则抛出异常 * * @param collection 集合 * @param errorMessage 错误信息 */ @SuppressWarnings("rawtypes") public static void assertNotEmpty(Collection collection, String errorMessage) { if (collection == null || collection.isEmpty()) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } /** * 集合不为空, 抛出异常 * * @param collection 集合 * @param errorMessage 错误信息 */ @SuppressWarnings("rawtypes") public static void assertEmpty(Collection collection, String errorMessage) { if (collection != null && !collection.isEmpty()) { throw new BaseException(ServerCode.INVALID_PARAMS_CONVERSION, errorMessage); } } }
3e0aa443112b96a489349c1a2f30d49f4e134a15
439
java
Java
spring-kafka-serp/src/main/java/com/baeldung/spring/kafka/dto/document/full/ReassignmentRequestAcceptTaskFull.java
pyramidon/tutorials
c6cd380b118e7a2a1b7a6cbf3e88eed9f72d5a6f
[ "MIT" ]
null
null
null
spring-kafka-serp/src/main/java/com/baeldung/spring/kafka/dto/document/full/ReassignmentRequestAcceptTaskFull.java
pyramidon/tutorials
c6cd380b118e7a2a1b7a6cbf3e88eed9f72d5a6f
[ "MIT" ]
null
null
null
spring-kafka-serp/src/main/java/com/baeldung/spring/kafka/dto/document/full/ReassignmentRequestAcceptTaskFull.java
pyramidon/tutorials
c6cd380b118e7a2a1b7a6cbf3e88eed9f72d5a6f
[ "MIT" ]
null
null
null
36.583333
86
0.867882
4,509
package com.baeldung.spring.kafka.dto.document.full; import com.baeldung.spring.kafka.dto.document.dal.ReassignmentRequest; import com.baeldung.spring.kafka.dto.document.dal.ReassignmentRequestAcceptTask; import lombok.Data; @Data public class ReassignmentRequestAcceptTaskFull extends ReassignmentRequestAcceptTask { private ReassignmentRequest initialReassignmentRequest; private ReassignmentRequest acceptedReassignmentRequest; }
3e0aa49c9bd9b6ce21b368c346c9d7f46b42e122
457
java
Java
core/common/src/main/java/mb/common/util/ADT.java
pmisteliac/spoofax-pie
38eaa6e4a7446c782fa10d863e58bd6430a2c105
[ "Apache-2.0" ]
1
2021-09-27T22:35:06.000Z
2021-09-27T22:35:06.000Z
core/common/src/main/java/mb/common/util/ADT.java
pmisteliac/spoofax-pie
38eaa6e4a7446c782fa10d863e58bd6430a2c105
[ "Apache-2.0" ]
null
null
null
core/common/src/main/java/mb/common/util/ADT.java
pmisteliac/spoofax-pie
38eaa6e4a7446c782fa10d863e58bd6430a2c105
[ "Apache-2.0" ]
3
2021-08-11T11:53:53.000Z
2021-09-27T22:35:09.000Z
26.882353
92
0.80744
4,510
package mb.common.util; import org.derive4j.Data; import org.derive4j.Derive; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static org.derive4j.Make.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Data(@Derive(make = {lambdaVisitor, constructors, getters, casesMatching, caseOfMatching})) public @interface ADT {}
3e0aa5689c75d9be176f680d55c731ab7700b8d6
1,887
java
Java
NewShare/app/src/main/java/com/melvin/share/ui/activity/selfcenter/ScanHistoryActivity.java
MelvinWang/NewShare
4b992335f12bb009d0c8b2ae72ec66db696aa22d
[ "Apache-2.0" ]
1
2016-12-17T09:54:15.000Z
2016-12-17T09:54:15.000Z
NewShare/app/src/main/java/com/melvin/share/ui/activity/selfcenter/ScanHistoryActivity.java
MelvinWang/NewShare
4b992335f12bb009d0c8b2ae72ec66db696aa22d
[ "Apache-2.0" ]
null
null
null
NewShare/app/src/main/java/com/melvin/share/ui/activity/selfcenter/ScanHistoryActivity.java
MelvinWang/NewShare
4b992335f12bb009d0c8b2ae72ec66db696aa22d
[ "Apache-2.0" ]
null
null
null
26.957143
123
0.713831
4,511
package com.melvin.share.ui.activity.selfcenter; import android.content.Context; import android.databinding.DataBindingUtil; import android.widget.LinearLayout; import com.jcodecraeer.xrecyclerview.ProgressStyle; import com.melvin.share.R; import com.melvin.share.databinding.ActivityScanHistoryBinding; import com.melvin.share.modelview.acti.ScanHistoryViewModel; import com.melvin.share.ui.activity.common.BaseActivity; import com.melvin.share.view.MyRecyclerView; import java.util.HashMap; import java.util.Map; /** * Author: Melvin * <p> * Data: 2016/8/4 * <p> * 描述: 浏览记录页面 */ public class ScanHistoryActivity extends BaseActivity implements MyRecyclerView.LoadingListener { private ActivityScanHistoryBinding binding; private Context mContext = null; private MyRecyclerView mRecyclerView; private ScanHistoryViewModel scanHistoryViewModel; private Map map; @Override protected void initView() { binding = DataBindingUtil.setContentView(this, R.layout.activity_scan_history); mContext = this; initWindow(); initToolbar(binding.toolbar); ininData(); } private void ininData() { map=new HashMap(); map.put("customer.id", "1"); mRecyclerView = binding.recyclerView; mRecyclerView.setLaodingMoreProgressStyle(ProgressStyle.BallRotate); mRecyclerView.setLoadingListener(this); scanHistoryViewModel = new ScanHistoryViewModel(this, mRecyclerView, binding.edit, binding.cancel, binding.delete); binding.setViewModel(scanHistoryViewModel); scanHistoryViewModel.requestData(map); } /** * 下拉刷新 */ @Override public void onRefresh() { scanHistoryViewModel.requestData(map); mRecyclerView.refreshComplete(); } /** * 上拉加载更多 */ @Override public void onLoadMore() { } }
3e0aa695fe73201b646952853ec7cedf15510ce3
3,289
java
Java
spring-cloud-aws-jdbc/src/test/java/org/springframework/cloud/aws/jdbc/retry/SqlRetryPolicyTest.java
valli-dr/spring-cloud-aws
8d1675bd900071094ed92e638e8ff2ca093a6633
[ "Apache-2.0" ]
613
2015-02-04T01:14:22.000Z
2022-01-06T13:07:17.000Z
spring-cloud-aws-jdbc/src/test/java/org/springframework/cloud/aws/jdbc/retry/SqlRetryPolicyTest.java
valli-dr/spring-cloud-aws
8d1675bd900071094ed92e638e8ff2ca093a6633
[ "Apache-2.0" ]
664
2015-01-02T03:56:29.000Z
2022-01-16T08:47:41.000Z
spring-cloud-aws-jdbc/src/test/java/org/springframework/cloud/aws/jdbc/retry/SqlRetryPolicyTest.java
valli-dr/spring-cloud-aws
8d1675bd900071094ed92e638e8ff2ca093a6633
[ "Apache-2.0" ]
461
2015-01-12T08:20:08.000Z
2022-01-17T06:06:02.000Z
37.375
107
0.798723
4,512
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.aws.jdbc.retry; import java.sql.SQLException; import java.sql.SQLTransientException; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.retry.context.RetryContextSupport; import org.springframework.transaction.TransactionSystemException; import static org.assertj.core.api.Assertions.assertThat; /** * Unit test class for the {@link SqlRetryPolicy}. * * @author Agim Emruli */ class SqlRetryPolicyTest { @Test void testRetryTransientExceptions() throws Exception { SqlRetryPolicy sqlRetryPolicy = new SqlRetryPolicy(); RetryContextSupport retryContext = new RetryContextSupport(null); retryContext.registerThrowable(new SQLTransientException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isTrue(); retryContext.registerThrowable(new TransientDataAccessResourceException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isTrue(); } @Test void testNoRetryPersistentExceptions() throws Exception { SqlRetryPolicy sqlRetryPolicy = new SqlRetryPolicy(); RetryContextSupport retryContext = new RetryContextSupport(null); retryContext.registerThrowable(new SQLException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isFalse(); retryContext.registerThrowable(new DataAccessResourceFailureException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isFalse(); } @Test void testWithNestedException() throws Exception { SqlRetryPolicy sqlRetryPolicy = new SqlRetryPolicy(); RetryContextSupport retryContext = new RetryContextSupport(null); retryContext.registerThrowable( new TransactionSystemException("Could not commit JDBC transaction", new SQLTransientException("foo"))); assertThat(sqlRetryPolicy.canRetry(retryContext)).isTrue(); } @Test void testMaxRetriesReached() throws Exception { SqlRetryPolicy sqlRetryPolicy = new SqlRetryPolicy(); sqlRetryPolicy.setMaxNumberOfRetries(3); RetryContextSupport retryContext = new RetryContextSupport(null); retryContext.registerThrowable(new SQLTransientException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isTrue(); retryContext.registerThrowable(new SQLTransientException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isTrue(); retryContext.registerThrowable(new SQLTransientException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isTrue(); retryContext.registerThrowable(new SQLTransientException("foo")); assertThat(sqlRetryPolicy.canRetry(retryContext)).isFalse(); } }
3e0aa789532145bb9a0206b3df7d7455b89f603f
6,442
java
Java
app/src/androidTest/java/cmput301/team19/lendz/AcceptRequestTest.java
CMPUT301F20T19/lendz
d39a93356ab71b6dc1730f778a8edd52a5ab87bc
[ "MIT" ]
null
null
null
app/src/androidTest/java/cmput301/team19/lendz/AcceptRequestTest.java
CMPUT301F20T19/lendz
d39a93356ab71b6dc1730f778a8edd52a5ab87bc
[ "MIT" ]
42
2020-10-07T02:27:46.000Z
2020-11-30T01:55:45.000Z
app/src/androidTest/java/cmput301/team19/lendz/AcceptRequestTest.java
CMPUT301F20T19/lendz
d39a93356ab71b6dc1730f778a8edd52a5ab87bc
[ "MIT" ]
2
2020-10-01T04:14:54.000Z
2020-11-06T23:15:26.000Z
40.791139
146
0.690303
4,513
package cmput301.team19.lendz; import android.util.Log; import androidx.annotation.NonNull; import androidx.test.espresso.NoMatchingViewException; import androidx.test.espresso.action.ViewActions; import androidx.test.espresso.contrib.RecyclerViewActions; import androidx.test.ext.junit.rules.ActivityScenarioRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.gms.tasks.OnFailureListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.functions.FirebaseFunctions; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static androidx.test.espresso.Espresso.onData; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.clearText; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.scrollTo; import static androidx.test.espresso.action.ViewActions.typeText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.anything; import static org.junit.Assert.fail; @RunWith(AndroidJUnit4.class) public class AcceptRequestTest { private final String QUERY_STRING = "2536732323232"; private final DocumentReference testBookRef = FirebaseFirestore.getInstance() .document("books/acceptRequestTestBook"); @Rule public ActivityScenarioRule<LoginActivity> rule = new ActivityScenarioRule<>(LoginActivity.class); @Before public void initialize() { // Ensure started logged out FirebaseAuth.getInstance().signOut(); FirebaseFirestore db = FirebaseFirestore.getInstance(); // Create the required book Map<String, Object> bookData = new HashMap<>(); Map<String, Object> descriptionMap = new HashMap<>(); descriptionMap.put("author", "boyonda"); descriptionMap.put("description", "the witcher"); descriptionMap.put("isbn", "2536732323232"); descriptionMap.put("title", "Chelsea Book"); bookData.put("description", descriptionMap); List<String> keywordsArray = new ArrayList<>(); keywordsArray.add("2536732323232"); bookData.put("keywords", keywordsArray); bookData.put("owner", db.document("users/dwpqY6Wnr4MTavg9pJkvfjFadJ73")); bookData.put("ownerUsername", "WoodieFrank101"); bookData.put("photo", null); bookData.put("status", BookStatus.REQUESTED.ordinal()); List<DocumentReference> pendingRequestsArray = new ArrayList<>(); pendingRequestsArray.add(db.document("requests/acceptRequestTestRequest")); bookData.put("pendingRequests", pendingRequestsArray); List<DocumentReference> pendingRequestersArray = new ArrayList<>(); pendingRequestersArray.add(db.document("users/dqdzdaUMthZxuyo43LLpeCfkvjb2")); bookData.put("pendingRequesters", pendingRequestersArray); testBookRef.set(bookData); // Create the required request Map<String, Object> requestData = new HashMap<>(); requestData.put("book", testBookRef); requestData.put("bookPhotoUrl", null); requestData.put("bookTitle", "Chelsea book"); requestData.put("location", null); requestData.put("ownerUsername", "WoodieFrank101"); requestData.put("requester", db.document("users/dqdzdaUMthZxuyo43LLpeCfkvjb2")); requestData.put("requesterFullName", "James Harden"); requestData.put("requesterUsername", "jamesHarden"); requestData.put("status", RequestStatus.SENT.ordinal()); requestData.put("timestamp", 1606715798873L); db.document("requests/acceptRequestTestRequest") .set(requestData); // Log in onView(withId(R.id.editText_login_email)) .perform(clearText()) .perform(typeText("lyhxr@example.com"), ViewActions.closeSoftKeyboard()); onView(withId(R.id.editText_login_password)) .perform(clearText()) .perform(typeText("1234567"), ViewActions.closeSoftKeyboard()); onView(withId(R.id.login_button)) .perform(click()); } /** * Begins the activity for the search * Makes a search and awaits the results * */ @Test public void acceptRequest() throws InterruptedException { Thread.sleep(8000); onView(withId(R.id.search_item)).perform(click()); Thread.sleep(2000); onView(withId(R.id.search_edit)).perform(typeText(QUERY_STRING),ViewActions.closeSoftKeyboard()); Thread.sleep(2000); onView(withId(R.id.search_button)).perform(click()); Thread.sleep(2000); onView(withId(R.id.search_recyclerview)). perform(RecyclerViewActions.actionOnItemAtPosition(0, click())); Thread.sleep(2000); //check if view requests button is in view try { onView(withId(R.id.view_requests_button)) .check(matches(withText("VIEW REQUESTS"))); onView(withId(R.id.view_requests_button)).perform(scrollTo(), click()); //navigate to list view onData(anything()).inAdapterView(withId(R.id.requestListView)).onChildView(withId(R.id.acceptRequest)).atPosition(0).perform(click()); Thread.sleep(2000); onView(withText("Accept Request")).check(matches(isDisplayed())); Thread.sleep(2000); onView(withId(android.R.id.button1)).perform(click()); Thread.sleep(2000); //open map activity onView(withText("Pickup Location")).check(matches(isDisplayed())); Thread.sleep(2000); onView(withId(android.R.id.button1)).perform(click()); }catch (NoMatchingViewException ignore) { //no matching view exception } } }
3e0aa99165483baff0afd889d07339380937e311
5,249
java
Java
pay-service/src/test/java/com/aaden/pay/service/resouce/lianlian/LianlianPayUtil.java
xwt-benchmarks/aaden-pay
13ccbf0c40333e80cd7c4d904374fbec21453ba7
[ "Apache-2.0" ]
50
2017-12-13T02:37:34.000Z
2021-11-22T22:40:36.000Z
pay-service/src/test/java/com/aaden/pay/service/resouce/lianlian/LianlianPayUtil.java
xwt-benchmarks/aaden-pay
13ccbf0c40333e80cd7c4d904374fbec21453ba7
[ "Apache-2.0" ]
null
null
null
pay-service/src/test/java/com/aaden/pay/service/resouce/lianlian/LianlianPayUtil.java
xwt-benchmarks/aaden-pay
13ccbf0c40333e80cd7c4d904374fbec21453ba7
[ "Apache-2.0" ]
32
2017-12-18T08:06:54.000Z
2021-05-28T03:52:50.000Z
22.241525
96
0.607925
4,514
package com.aaden.pay.service.resouce.lianlian; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.aaden.pay.core.logger.SimpleLogger; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; /** * @Description 连连工具类 * @author aaden * @date 2017年12月5日 */ public class LianlianPayUtil { private static SimpleLogger logger = SimpleLogger.getLogger(LianlianPayUtil.class); /** * str空判断 * * @param str * @return * @author guoyx */ public static boolean isnull(String str) { if (null == str || str.equalsIgnoreCase("null") || str.equals("")) { return true; } else return false; } /** * 生成待签名串 * * @param paramMap * @return * @author guoyx */ public static String genSignData(JSONObject jsonObject) { StringBuffer content = new StringBuffer(); // 按照key做首字母升序排列 List<String> keys = new ArrayList<String>(jsonObject.keySet()); Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); for (int i = 0; i < keys.size(); i++) { String key = (String) keys.get(i); if ("sign".equals(key)) { continue; } String value = jsonObject.getString(key); // 空串不参与签名 if (isnull(value)) { continue; } content.append((i == 0 ? "" : "&") + key + "=" + value); } String signSrc = content.toString(); if (signSrc.startsWith("&")) { signSrc = signSrc.replaceFirst("&", ""); } System.out.println(signSrc); return signSrc; } /** * 加签 * * @param reqObj * @param rsa_private * @param md5_key * @return * @author guoyx */ public static String addSign(JSONObject reqObj, String rsa_private, String md5_key) { if (reqObj == null) { return ""; } String sign_type = reqObj.getString("sign_type"); if (LianlianSignTypeEnum.MD5.getCode().equals(sign_type)) { return addSignMD5(reqObj, md5_key); } else { return addSignRSA(reqObj, rsa_private); } } /** * 签名验证 * * @param reqStr * @return */ public static boolean checkSign(String reqStr, String rsa_public, String md5_key) { JSONObject reqObj = JSON.parseObject(reqStr); if (reqObj == null) { return false; } String sign_type = reqObj.getString("sign_type"); if (LianlianSignTypeEnum.MD5.getCode().equals(sign_type)) { return checkSignMD5(reqObj, md5_key); } else { return checkSignRSA(reqObj, rsa_public); } } /** * RSA签名验证 * * @param reqObj * @return * @author guoyx */ private static boolean checkSignRSA(JSONObject reqObj, String rsa_public) { if (reqObj == null) { return false; } String sign = reqObj.getString("sign"); // 生成待签名串 String sign_src = genSignData(reqObj); try { if (LianlianTraderRSAUtil.checksign(rsa_public, sign_src, sign)) { return true; } else { return false; } } catch (Exception e) { return false; } } /** * MD5签名验证 * * @param signSrc * @param sign * @return * @author guoyx */ private static boolean checkSignMD5(JSONObject reqObj, String md5_key) { if (reqObj == null) { return false; } String sign = reqObj.getString("sign"); // 生成待签名串 String sign_src = genSignData(reqObj); sign_src += "&key=" + md5_key; try { if (sign.equals(LianlianMd5Algorithm.getInstance().md5Digest(sign_src.getBytes("utf-8")))) { return true; } else { return false; } } catch (UnsupportedEncodingException e) { return false; } } /** * RSA加签名 * * @param reqObj * @param rsa_private * @return * @author guoyx */ private static String addSignRSA(JSONObject reqObj, String rsa_private) { if (reqObj == null) { return ""; } // 生成待签名串 String sign_src = genSignData(reqObj); logger.info("连连RSA签名原串数据:"+sign_src); try { return LianlianTraderRSAUtil.sign(rsa_private, sign_src); } catch (Exception e) { return ""; } } /** * MD5加签名 * * @param reqObj * @param md5_key * @return * @author guoyx */ private static String addSignMD5(JSONObject reqObj, String md5_key) { if (reqObj == null) { return ""; } // 生成待签名串 String sign_src = genSignData(reqObj); sign_src += "&key=" + md5_key; logger.info("连连MD5签名原串数据:"+sign_src); try { return LianlianMd5Algorithm.getInstance().md5Digest(sign_src.getBytes("utf-8")); } catch (Exception e) { return ""; } } // // /** // * 读取request流 // * // * @param req // * @return // * @author guoyx // */ // public static String readReqStr(HttpServletRequest request) { // BufferedReader reader = null; // StringBuilder sb = new StringBuilder(); // try { // reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8")); // String line = null; // // while ((line = reader.readLine()) != null) { // sb.append(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (null != reader) { // reader.close(); // } // } catch (IOException e) { // // } // } // return sb.toString(); // } }
3e0aaada5c4e51b1ea7dc877d923b5176479744d
411
java
Java
src/main/java/id/ac/tazkia/payment/cimb/dto/CIMB3RdPartyPaymentRs.java
idtazkia/cimb-ws
cc943f493ddf99ce1f8613014e136bf10f90d29e
[ "Apache-2.0" ]
1
2019-02-12T06:01:01.000Z
2019-02-12T06:01:01.000Z
src/main/java/id/ac/tazkia/payment/cimb/dto/CIMB3RdPartyPaymentRs.java
idtazkia/cimb-ws
cc943f493ddf99ce1f8613014e136bf10f90d29e
[ "Apache-2.0" ]
null
null
null
src/main/java/id/ac/tazkia/payment/cimb/dto/CIMB3RdPartyPaymentRs.java
idtazkia/cimb-ws
cc943f493ddf99ce1f8613014e136bf10f90d29e
[ "Apache-2.0" ]
1
2019-11-14T00:58:11.000Z
2019-11-14T00:58:11.000Z
21.631579
55
0.746959
4,515
package id.ac.tazkia.payment.cimb.dto; import lombok.Data; import javax.xml.bind.annotation.*; @Data @XmlRootElement(name = "CIMB3rdParty_PaymentRs") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CIMB3rdParty_PaymentRs", propOrder = { "paymentRs" }) public class CIMB3RdPartyPaymentRs { @XmlElement(name = "PaymentRs", required = true) private PaymentRs paymentRs = new PaymentRs(); }
3e0aab2f5d9d65e569e6d25b8dcee9ad594f0f92
237
java
Java
src/main/java/com/mayreh/toyka/ChannelStateMachine.java
ocadaruma/kkaaf
c2e8d76d35a5b2988259c8a77986c373090035f5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mayreh/toyka/ChannelStateMachine.java
ocadaruma/kkaaf
c2e8d76d35a5b2988259c8a77986c373090035f5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mayreh/toyka/ChannelStateMachine.java
ocadaruma/kkaaf
c2e8d76d35a5b2988259c8a77986c373090035f5
[ "Apache-2.0" ]
null
null
null
18.230769
65
0.64135
4,516
//package com.mayreh.zerokafka; // //public class ChannelStateMachine { // // public interface ChannelState { // ChannelState become() // } // // public static class ReadingHeader implements ChannelState { // // } //}
3e0aab89cb28c7063d50aed4136ab206f391356d
4,492
java
Java
onnx/src/gen/java/org/bytedeco/onnx/TensorProto_Segment.java
viditsethi13/org
e24e8c953db82b269ccc0707b70180535e8454e7
[ "Apache-2.0" ]
2
2019-05-08T18:56:11.000Z
2019-12-05T13:17:42.000Z
onnx/src/gen/java/org/bytedeco/onnx/TensorProto_Segment.java
viditsethi13/org
e24e8c953db82b269ccc0707b70180535e8454e7
[ "Apache-2.0" ]
null
null
null
onnx/src/gen/java/org/bytedeco/onnx/TensorProto_Segment.java
viditsethi13/org
e24e8c953db82b269ccc0707b70180535e8454e7
[ "Apache-2.0" ]
null
null
null
47.284211
110
0.711487
4,517
// Targeted by JavaCPP version 1.5: DO NOT EDIT THIS FILE package org.bytedeco.onnx; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.onnx.global.onnx.*; // ------------------------------------------------------------------- @Namespace("onnx") @NoOffset @Properties(inherit = org.bytedeco.onnx.presets.onnx.class) public class TensorProto_Segment extends MessageLite { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public TensorProto_Segment(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public TensorProto_Segment(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public TensorProto_Segment position(long position) { return (TensorProto_Segment)super.position(position); } public TensorProto_Segment() { super((Pointer)null); allocate(); } private native void allocate(); public TensorProto_Segment(@Const @ByRef TensorProto_Segment from) { super((Pointer)null); allocate(from); } private native void allocate(@Const @ByRef TensorProto_Segment from); public native @ByRef @Name("operator =") TensorProto_Segment put(@Const @ByRef TensorProto_Segment from); // #if LANG_CXX11 // #endif public native @Const @ByRef UnknownFieldSet unknown_fields(); public native UnknownFieldSet mutable_unknown_fields(); public static native @Cast("const google::protobuf::Descriptor*") Pointer descriptor(); public static native @Const @ByRef TensorProto_Segment default_instance(); public static native void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY public static native @Const TensorProto_Segment internal_default_instance(); @MemberGetter public static native int kIndexInFileMessages(); public static final int kIndexInFileMessages = kIndexInFileMessages(); public native void Swap(TensorProto_Segment other); // implements Message ---------------------------------------------- public native TensorProto_Segment New(); public native TensorProto_Segment New(Arena arena); public native void CopyFrom(@Cast("const google::protobuf::Message*") @ByRef MessageLite from); public native void MergeFrom(@Cast("const google::protobuf::Message*") @ByRef MessageLite from); public native void CopyFrom(@Const @ByRef TensorProto_Segment from); public native void MergeFrom(@Const @ByRef TensorProto_Segment from); public native void Clear(); public native @Cast("bool") boolean IsInitialized(); public native @Cast("size_t") long ByteSizeLong(); public native @Cast("bool") boolean MergePartialFromCodedStream( CodedInputStream input); public native void SerializeWithCachedSizes( CodedOutputStream output); public native @Cast("google::protobuf::uint8*") BytePointer InternalSerializeWithCachedSizesToArray( @Cast("bool") boolean deterministic, @Cast("google::protobuf::uint8*") BytePointer target); public native @Cast("google::protobuf::uint8*") ByteBuffer InternalSerializeWithCachedSizesToArray( @Cast("bool") boolean deterministic, @Cast("google::protobuf::uint8*") ByteBuffer target); public native @Cast("google::protobuf::uint8*") byte[] InternalSerializeWithCachedSizesToArray( @Cast("bool") boolean deterministic, @Cast("google::protobuf::uint8*") byte[] target); public native int GetCachedSize(); public native @ByVal @Cast("google::protobuf::Metadata*") Pointer GetMetadata(); // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional int64 begin = 1; public native @Cast("bool") boolean has_begin(); public native void clear_begin(); @MemberGetter public static native int kBeginFieldNumber(); public static final int kBeginFieldNumber = kBeginFieldNumber(); public native @Cast("google::protobuf::int64") long begin(); public native void set_begin(@Cast("google::protobuf::int64") long value); // optional int64 end = 2; public native @Cast("bool") boolean has_end(); public native void clear_end(); @MemberGetter public static native int kEndFieldNumber(); public static final int kEndFieldNumber = kEndFieldNumber(); public native @Cast("google::protobuf::int64") long end(); public native void set_end(@Cast("google::protobuf::int64") long value); }
3e0aabd6f92940d7420a303c9e0578ee1706841d
15,773
java
Java
feihua-utils/src/main/java/com/feihua/utils/graphic/ImageUtils.java
revolvernn/feihua-framework
0a6fc6e283799fef18fcb97ebe080a2f19a6db0d
[ "MIT" ]
1
2018-08-25T08:05:05.000Z
2018-08-25T08:05:05.000Z
feihua-utils/src/main/java/com/feihua/utils/graphic/ImageUtils.java
revolvernn/feihua-framework
0a6fc6e283799fef18fcb97ebe080a2f19a6db0d
[ "MIT" ]
null
null
null
feihua-utils/src/main/java/com/feihua/utils/graphic/ImageUtils.java
revolvernn/feihua-framework
0a6fc6e283799fef18fcb97ebe080a2f19a6db0d
[ "MIT" ]
null
null
null
30.101145
233
0.707665
4,518
package com.feihua.utils.graphic; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.ColorModel; import java.io.*; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import javax.imageio.*; import com.feihua.utils.string.StringUtils; import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import org.apache.commons.lang3.RandomUtils; public class ImageUtils { public static String IMAGE_TYPE_GIF = "gif"; // 图形交换格式 public static String IMAGE_TYPE_JPG = "jpg"; // 联合照片专家组 public static String IMAGE_TYPE_JPEG = "jpeg"; // 联合照片专家组 public static String IMAGE_TYPE_BMP = "bmp"; // 英文Bitmap(位图)的简写,它是Windows操作系统中的标准图像文件格式 public static String IMAGE_TYPE_PNG = "png"; // 可移植网络图形 /** * 创建图片 * @return */ public final static BufferedImage createImage(int width,int height){ BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); return image; } /** * 创建带背景颜色图片 * @return */ public final static BufferedImage createImage(int width,int height,Color bgColor){ BufferedImage image = createImage(width,height); Graphics2D g = image.createGraphics(); g.setColor(bgColor); //g.drawRect(0, 0, image.getWidth(), image.getHeight()); g.fillRect(0, 0, image.getWidth(), image.getHeight()); g.dispose(); return image; } /** * 根据图片路径读取图片 * @param imagePath * @return * @throws IOException */ public final static BufferedImage createImage(String imagePath) throws IOException{ return createImage (new File(imagePath)); // 读入文件 } /** * 根据文件读取图片 * @param imageFile * @return * @throws IOException */ public final static BufferedImage createImage(File imageFile) throws IOException{ BufferedImage image = ImageIO.read(imageFile); // 读入文件 return image; } /** * 缓冲图片对象转像对象 * @param image * @return */ public final static Image BufferedImageToImage(BufferedImage image){ return image.getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_DEFAULT); } /** * 按比例缩放 * @param image 图像 * @param scale 比例,如果缩小请用小数 */ public final static BufferedImage zoomImage(BufferedImage image,double scale) { int width = (int) (image.getWidth() * scale); // 得到源图宽 int height = (int) (image.getHeight() * scale); // 得到源图长 //缩放后的图像 Image scaleImage = image.getScaledInstance(width, height, Image.SCALE_DEFAULT); //创建一个新图像 BufferedImage resultImage = createImage(width, height); Graphics g = resultImage.getGraphics(); g.drawImage(scaleImage, 0, 0, null); // 绘制缩放后的图 g.dispose(); return resultImage; } /** * 按高度和宽度缩放 * @param image * @param width * @return */ public final static BufferedImage zoomEqualRatioImageByWidth(BufferedImage image, int width) { double ratio = (new Integer(width)).doubleValue()/image.getWidth(); return zoomImage(image,ratio); } /** * 按高度和宽度缩放 * @param image * @param height * @return */ public final static BufferedImage zoomEqualRatioImageByHeight(BufferedImage image,int height) { double ratio = (new Integer(height)).doubleValue()/ image.getHeight(); return zoomImage(image,ratio); } /** * 旋转图像 * @param bufferedimage * @param degree * @return */ public static BufferedImage rotateImage(BufferedImage bufferedimage,int degree) { // 得到图片宽度。 int w = bufferedimage.getWidth(); // 得到图片高度。 int h = bufferedimage.getHeight(); // 空的图片。 BufferedImage img = createImage(w, h); // 空的画笔。 Graphics2D graphics2d = img.createGraphics(); // 旋转,degree是整型,度数,比如垂直90度。 graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2); // 从bufferedimagecopy图片至img,0,0是img的坐标。 graphics2d.drawImage(bufferedimage, 0, 0, null); graphics2d.dispose(); // 返回复制好的图片,原图片依然没有变,没有旋转,下次还可以使用。 return img; } /** * 水平翻转 * @param bufferedimage * @return */ public static BufferedImage flipImageH(BufferedImage bufferedimage) { // 得到宽度。 int w = bufferedimage.getWidth(); // 得到高度。 int h = bufferedimage.getHeight(); return cutImage(bufferedimage,w, 0, 0, h); } /** * 垂直翻转 * @param bufferedimage * @return */ public static BufferedImage flipImageV(BufferedImage bufferedimage) { // 得到宽度。 int w = bufferedimage.getWidth(); // 得到高度。 int h = bufferedimage.getHeight(); return cutImage(bufferedimage,0, h, w, 0); } /** * 按指定起点坐标和宽高切割 * @param bufferedimage * @param dx * @param dy * @param width * @param height */ public final static BufferedImage cutImage(BufferedImage bufferedimage, int dx, int dy, int width, int height) { int srcWidth = bufferedimage.getWidth(); // 源图宽度 int srcHeight = bufferedimage.getHeight(); // 源图高度 BufferedImage resultImage = null; int dwidth = Math.abs(width-dx); int dheight = Math.abs(height-dy); if (srcWidth > 0 && srcHeight > 0) { resultImage = createImage(width, height); Graphics g = resultImage.getGraphics(); g.drawImage(bufferedimage, 0, 0, width,height ,dx,dy,width,height, null); // 绘制切割后的图 g.dispose(); } return resultImage; } /** * 指定切片的行数和列数 * @param bufferedimage * @param rows * @param cols */ public final static BufferedImage[][] cutImageByRC(BufferedImage bufferedimage, int rows, int cols) { BufferedImage[][] result = new BufferedImage[rows][cols]; // 读取源图像 int srcWidth = bufferedimage.getWidth(); // 源图宽度 int srcHeight = bufferedimage.getHeight(); // 源图高度 if (srcWidth > 0 && srcHeight > 0) { int destWidth = srcWidth; // 每张切片的宽度 int destHeight = srcHeight; // 每张切片的高度 // 计算切片的宽度和高度 if (srcWidth % cols == 0) { destWidth = srcWidth / cols; } else { destWidth = (int) Math.floor(srcWidth / cols) + 1; } if (srcHeight % rows == 0) { destHeight = srcHeight / rows; } else { destHeight = (int) Math.floor(srcHeight / rows) + 1; } // 循环建立切片 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int sx = j * destWidth; int sy = i* destHeight; BufferedImage resultImage = cutImage(bufferedimage,sx, sy,sx + destWidth,sy + destHeight); result[i][j] = resultImage; } } } return result; } /** * 指定切片的宽度和高度 * @param bufferedimage * @param width * @param height */ public final static BufferedImage[][] cutImageByHW(BufferedImage bufferedimage, int width, int height) { // 读取源图像 int srcWidth = bufferedimage.getWidth(); // 源图宽度 int srcHeight = bufferedimage.getHeight(); // 源图高度 int cols = 0; // 切片横向数量 int rows = 0; // 切片纵向数量 if (srcWidth > width && srcHeight > height) { // 计算切片的横向和纵向数量 if (srcWidth % width == 0) { cols = srcWidth / width; } else { cols = (int) Math.floor(srcWidth / width) + 1; } if (srcHeight % height == 0) { rows = srcHeight / height; } else { rows = (int) Math.floor(srcHeight / height) + 1; } } return cutImageByRC(bufferedimage,rows,cols); } /** * 变黑白 * @param bufferedimage */ public final static BufferedImage gray(BufferedImage bufferedimage) { BufferedImage src = bufferedimage; ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); ColorConvertOp op = new ColorConvertOp(cs, null); src = op.filter(src, null); return src; } /** * 给图片添加文字水印 * @param bufferedimage * @param pressText * @param fontName * @param fontStyle * @param color * @param fontSize * @param x * @param y * @param alpha * @return */ public final static BufferedImage pressText(BufferedImage bufferedimage,String pressText, String fontName, int fontStyle, Color color, int fontSize, int x, int y, float alpha) { BufferedImage image = bufferedimage; Graphics2D g = image.createGraphics(); g.setColor(color); g.setFont(new Font(fontName, fontStyle, fontSize)); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 在指定坐标绘制水印文字 g.drawString(pressText, x, y); g.dispose(); return image; } /** * 给图片添加图片水印 * @param bufferedimage * @param pressImg * @param x * @param y * @param alpha * @return */ public final static BufferedImage pressImage(BufferedImage bufferedimage,Image pressImg, int x, int y, float alpha) { int width = bufferedimage.getWidth(); int height = bufferedimage.getHeight(); Graphics2D g = bufferedimage.createGraphics(); // 水印文件 int width_biao = pressImg.getWidth(null); int height_biao = pressImg.getHeight(null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); g.drawImage(pressImg, x,y,null); // 水印文件结束 g.dispose(); return bufferedimage; } /** * 输出图像文件 * @param bufferedimage * @param targetPath * @throws IOException */ public final static void outPutImage(BufferedImage bufferedimage ,String formatName,String targetPath) throws IOException{ String _formatName = formatName; if(_formatName == null) { _formatName = IMAGE_TYPE_JPEG; } ImageIO.write(bufferedimage, _formatName, new File(targetPath)); } /** * * @param byteArrayInputStream * @return * @throws IOException */ public final static BufferedImage inputStreamToBufferedImage(ByteArrayInputStream byteArrayInputStream) throws IOException { return ImageIO.read(byteArrayInputStream); } /** * * @param bufferedImage * @return * @throws IOException */ public final static InputStream bufferedImageToInputStream(BufferedImage bufferedImage,String formatName) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, formatName, os); InputStream is = new ByteArrayInputStream(os.toByteArray()); return is; } /** * 图片质量压缩 * @param bufferedImage * @param quality * @param formatName 注意这个参数现在不支持png * @return */ public final static ByteArrayInputStream compressImage(BufferedImage bufferedImage, String formatName, float quality) throws IOException { String _formatName = formatName; if(_formatName == null) { _formatName = IMAGE_TYPE_JPEG; } // 得到指定Format图片的writer Iterator<ImageWriter> iter = ImageIO .getImageWritersByFormatName(_formatName);// 得到迭代器 ImageWriter writer = iter.next(); // 得到writer // 得到指定writer的输出参数设置(ImageWriteParam ) ImageWriteParam imageWriteParam = writer.getDefaultWriteParam(); if(imageWriteParam.canWriteCompressed()){ imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 设置可否压缩 imageWriteParam.setCompressionQuality(quality); // 设置压缩质量参数 } imageWriteParam.setProgressiveMode(ImageWriteParam.MODE_DISABLED); ColorModel colorModel = ColorModel.getRGBdefault(); // 指定压缩时使用的色彩模式 imageWriteParam.setDestinationType(new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16))); IIOImage iIamge = new IIOImage(bufferedImage, null, null); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 取得内存输出流 writer.setOutput(ImageIO .createImageOutputStream(byteArrayOutputStream)); writer.write(null, iIamge, imageWriteParam); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); return byteArrayInputStream; } /** * 生成验证码 * @param width 宽 * @param height 高 * @param bgColor 背景色 * @param fontSize 字体大小 * @param text 内容 * @param randomLineNum 混淆画线次数 * @return */ public final static BufferedImage createSimpleCaptchaImage(int width,int height,Color bgColor,int fontSize,String text[],int randomLineNum){ int padding = 2; BufferedImage imag = createImage(width,height,bgColor); Graphics g = imag.createGraphics(); Color lineColor = null; for (int i = 0; i < randomLineNum; i++) { lineColor = new Color(RandomUtils.nextInt(0,256), RandomUtils.nextInt(0,256), RandomUtils.nextInt(0,256)); g.setColor(lineColor); int x1 = RandomUtils.nextInt(0,width + 1); int y1 = RandomUtils.nextInt(0,height + 1); int x2 = RandomUtils.nextInt(0,width + 1); int y2 = RandomUtils.nextInt(0,height + 1); g.drawLine(x1, y1, x2, y2); } Color textColor = null; // 添加水印 for (int i = 0; i < text.length; i++) { textColor = new Color(RandomUtils.nextInt(0,256), RandomUtils.nextInt(0,256), RandomUtils.nextInt(0,256)); int x = padding + i * width/text.length; int y = RandomUtils.nextInt(padding,height-fontSize-padding); System.out.println(y); pressText(imag,text[i],"宋体",Font.BOLD,textColor,fontSize,x,y+fontSize,0.9f); } g.dispose(); return imag; } /** * 生成二维码 * @param qrCodeSize 大小像素单位 * @param content 内容 * @param character_set 编码 utf-8等 * @param margin 白边边距 * @param bgColor 背景色 * @param frontColor 前景色 * @return * @throws WriterException */ public static final BufferedImage createQrCode(int qrCodeSize, String content,String character_set,int margin, Color bgColor, final Color frontColor) throws WriterException { return createQrCode(qrCodeSize, content,character_set,margin,ErrorCorrectionLevel.L,bgColor, new QrcodeColorGenerator() { @Override public Color generate(int i, int j) { return frontColor; } }); } /** * 生成二维码 * @param qrCodeSize 大小像素单位 * @param content 内容 * @param character_set 编码 utf-8等 * @param margin 白边边距 * @param errorCorrectionLevel 容错率,越高点数越多 * @param bgColor 背景色 * @param qrcodeColorGenerator 前景色生成器 * @return * @throws WriterException */ public static final BufferedImage createQrCode(int qrCodeSize,String content,String character_set,int margin,ErrorCorrectionLevel errorCorrectionLevel,Color bgColor,QrcodeColorGenerator qrcodeColorGenerator) throws WriterException { //设置二维码纠错级别MAP Hashtable<EncodeHintType, Object> hintMap = new Hashtable<EncodeHintType, Object>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel); // 矫错级别 hintMap.put(EncodeHintType.CHARACTER_SET, character_set); hintMap.put(EncodeHintType.MARGIN, margin); MultiFormatWriter qrCodeWriter = new MultiFormatWriter(); //创建比特矩阵(位矩阵)的QR码编码的字符串 BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap); // 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点) int matrixWidth = byteMatrix.getWidth(); int matrixHeight = byteMatrix.getWidth(); BufferedImage imag = createImage(matrixWidth,matrixHeight,bgColor); Graphics g = imag.createGraphics(); Color _frontColor = null; for (int i = 0; i < matrixWidth; i++) { for (int j = 0; j < matrixWidth; j++) { if (byteMatrix.get(i, j)) { _frontColor = qrcodeColorGenerator.generate(i,j); g.setColor(_frontColor); g.fillRect(i, j, 1, 1); } } } g.dispose(); return imag; } /** * 读取二维码内容 * @param image * @param character_set * @return * @throws IOException * @throws NotFoundException */ public static final String readQrCode(BufferedImage image,String character_set) throws IOException, NotFoundException { MultiFormatReader formatReader = new MultiFormatReader(); LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, character_set); Result result = formatReader.decode(binaryBitmap, hints); return result.getText(); } }
3e0aac8bb7646921eba73b9c754ff8e5d68a907f
3,569
java
Java
src/main/java/com/wizzardo/jrt/M3UHandler.java
wizzardo/jrtorrent
9bfe9f8da950c00b6d5b172c84f5677aa598e6b9
[ "MIT" ]
14
2016-01-14T17:31:59.000Z
2021-11-08T13:18:04.000Z
src/main/java/com/wizzardo/jrt/M3UHandler.java
wizzardo/jrtorrent
9bfe9f8da950c00b6d5b172c84f5677aa598e6b9
[ "MIT" ]
null
null
null
src/main/java/com/wizzardo/jrt/M3UHandler.java
wizzardo/jrtorrent
9bfe9f8da950c00b6d5b172c84f5677aa598e6b9
[ "MIT" ]
1
2017-05-23T20:39:11.000Z
2017-05-23T20:39:11.000Z
34.317308
109
0.628748
4,519
package com.wizzardo.jrt; import com.wizzardo.http.TokenizedFileTreeHandler; import com.wizzardo.http.filter.TokenFilter; import com.wizzardo.http.framework.ControllerUrlMapping; import com.wizzardo.http.framework.Holders; import com.wizzardo.http.request.Header; import com.wizzardo.http.request.Request; import com.wizzardo.http.response.Response; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Created by wizzardo on 03/12/16. */ public class M3UHandler<T extends M3UHandler.HandlerContextWithRequest> extends TokenizedFileTreeHandler<T> { protected Set<String> extensions = new HashSet<>(Arrays.asList( "mkv", "avi", "mp4", "mp3", "aac", "flac", "ape", "wav", "ts" )); protected FileFilter fileFilter = pathname -> { if(pathname.isDirectory()) return true; String name = pathname.getName(); int i = name.lastIndexOf('.'); if (i == -1 || i == name.length() - 1) return false; String extension = name.substring(i + 1); return extensions.contains(extension.toLowerCase()); }; public M3UHandler(String workDir, String prefix, TokenFilter tokenFilter, String name) { super(workDir, prefix, tokenFilter, name); } @Override protected Response handleDirectory(Request request, Response response, String path, File file) { StringBuilder sb = new StringBuilder(); T handlerContext = createHandlerContext(path, request); return response.setBody(addFileRecursively(file, sb, handlerContext).toString()) .header(Header.KEY_CONTENT_TYPE, "audio/x-mpegurl") .header("Content-Disposition", "attachment; filename=\"" + file.getName() + ".m3u\"") ; } protected StringBuilder getPath(StringBuilder sb, File file) { if (!file.equals(workDir)) { getPath(sb, file.getParentFile()); sb.append("/").append(encodeName(file.getName())); } return sb; } @Override protected String generateUrl(File file, T handlerContext) { ControllerUrlMapping mapping = Holders.getApplication().getUrlMapping(); StringBuilder sb = new StringBuilder("https://" + handlerContext.request.header(Header.KEY_HOST)); sb.append(mapping.getUrlTemplate("downloads").getRelativeUrl()); getPath(sb, file.getParentFile()).append("/").append(super.generateUrl(file, handlerContext)); return sb.toString(); } protected StringBuilder addFileRecursively(File file, StringBuilder sb, T context) { if (file.isDirectory()) { File[] files = file.listFiles(fileFilter); if (files != null) { Arrays.sort(files); for (File f : files) { addFileRecursively(f, sb, context); } } } else { sb.append(generateUrl(file, context)).append("\n"); } return sb; } @Override protected T createHandlerContext(String path, Request request) { return (T) new HandlerContextWithRequest(path, request); } protected class HandlerContextWithRequest extends HandlerContextWithToken { protected final Request request; public HandlerContextWithRequest(String path, Request request) { super(path, request); this.request = request; } } }