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
3e0632ca1abd28c35331d7a047adcd75fbeb9d8c
5,390
java
Java
tools/fits/0.5.0/src/edu/harvard/hul/ois/fits/tools/mediainfo/MediaInfo.java
opf-attic/ref
a489c09ffc4dccf6e484b21cb2a2655872df9c93
[ "Apache-2.0" ]
null
null
null
tools/fits/0.5.0/src/edu/harvard/hul/ois/fits/tools/mediainfo/MediaInfo.java
opf-attic/ref
a489c09ffc4dccf6e484b21cb2a2655872df9c93
[ "Apache-2.0" ]
null
null
null
tools/fits/0.5.0/src/edu/harvard/hul/ois/fits/tools/mediainfo/MediaInfo.java
opf-attic/ref
a489c09ffc4dccf6e484b21cb2a2655872df9c93
[ "Apache-2.0" ]
null
null
null
32.083333
128
0.7282
2,616
/* * Copyright 2009 Harvard University Library * * This file is part of FITS (File Information Tool Set). * * FITS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FITS 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FITS. If not, see <http://www.gnu.org/licenses/>. */ package edu.harvard.hul.ois.fits.tools.mediainfo; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jdom.Document; import edu.harvard.hul.ois.fits.Fits; import edu.harvard.hul.ois.fits.exceptions.FitsException; import edu.harvard.hul.ois.fits.exceptions.FitsToolCLIException; import edu.harvard.hul.ois.fits.exceptions.FitsToolException; import edu.harvard.hul.ois.fits.tools.ToolBase; import edu.harvard.hul.ois.fits.tools.ToolInfo; import edu.harvard.hul.ois.fits.tools.ToolOutput; import edu.harvard.hul.ois.fits.tools.utils.CommandLine; import edu.harvard.hul.ois.fits.tools.utils.XsltTransformMap; public class MediaInfo extends ToolBase { private boolean osIsWindows = false; private boolean osHasMediaInfo = false; private List<String> winCommand = new ArrayList<String>(Arrays.asList(Fits.FITS_TOOLS+"exiftool/windows/exiftool.exe")); //TODO private List<String> unixCommand = new ArrayList<String>(Arrays.asList("mediainfo")); private List<String> testCommand = Arrays.asList("which", "mediainfo"); private final static String TOOL_NAME = "MediaInfo"; private boolean enabled = true; public final static String mediaInfoFitsConfig = Fits.FITS_XML+"mediainfo"+File.separator; public final static String genericTransform = "mediainfo_generic_to_fits.xslt"; public MediaInfo() throws FitsException { String osName = System.getProperty("os.name"); info = new ToolInfo(); info.setName(TOOL_NAME); String versionOutput = null; List<String> infoCommand = new ArrayList<String>(); if (osName.startsWith("Windows")) { //TODO make it work with windows //use provided Windows exiftool.exe osIsWindows = true; infoCommand.addAll(winCommand); info.setNote("mediainfo for windows"); } else if (testForMediaInfo()){ osHasMediaInfo = true; //use OS version of perl and the provided perl version of exiftool infoCommand.addAll(unixCommand); info.setNote("mediainfo for unix"); } else { throw new FitsToolException("MediaInfo was not found on this system"); } infoCommand.add("--Version"); versionOutput = CommandLine.exec(infoCommand,null); info.setVersion(versionOutput.trim()); transformMap = XsltTransformMap.getMap(mediaInfoFitsConfig+"mediainfo_xslt_map.xml"); } public ToolOutput extractInfo(File file) throws FitsToolException { List execCommand = new ArrayList(); //determine if the file can be used on the current platform if (osIsWindows) { //use provided Windows File Utility execCommand.addAll(winCommand); execCommand.add(file.getPath()); } else if(osHasMediaInfo) { //use file command in operating system execCommand.addAll(unixCommand); execCommand.add(file.getPath()); } else { //Tool cannot be used on this file on this system return null; } //Output in tabbed format with tag names instead of descriptive names execCommand.add("-t"); execCommand.add("-s"); String execOut = CommandLine.exec(execCommand,null); String[] outParts = execOut.split("\n"); String format = null; for(String s : outParts) { s = s.toLowerCase(); String[] lineParts = s.split("\t"); if(lineParts[0].equalsIgnoreCase("filetype")) { format = lineParts[1].trim(); break; } } Document rawOut = null; /* Document exifDoc = null; try { exifDoc = saxBuilder.build(new StringReader(execOut)); } catch (Exception e) { throw new FitsToolException("Error parsing ffident XML Output",e); } String format = XmlUtils.getDomValue(exifDoc.getDocument(),"File:FileType"); exifDoc.getRootElement().getChild("rdf:Description/File:FileType"); Namespace ns = Namespace.getNamespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); String test = exifDoc.getRootElement().getChildText("rdf:Description",ns); */ String xsltTransform = null; if(format != null) { xsltTransform = (String)transformMap.get(format.toUpperCase()); } Document fitsXml = null; if(xsltTransform != null) { fitsXml = transform(mediaInfoFitsConfig+xsltTransform,rawOut); } else { //use generic transform fitsXml = transform(mediaInfoFitsConfig+genericTransform,rawOut); } output = new ToolOutput(this,fitsXml,rawOut); //} return output; } public boolean testForMediaInfo() throws FitsToolCLIException { String output = CommandLine.exec(testCommand,null); if(output == null || output.length() == 0) { return false; } else { return true; } } public boolean isEnabled() { return enabled; } public void setEnabled(boolean value) { enabled = value; } }
3e063354f48b3d113c88d214ba0e26953940f16b
1,057
java
Java
officefloor/server/officeserver/src/main/java/net/officefloor/server/http/HttpRequestCookie.java
officefloor/OfficeFloor
16c73ac87019d27de6df16c54c976a295db184ea
[ "Apache-2.0" ]
17
2019-09-30T08:23:01.000Z
2021-12-20T04:51:03.000Z
officefloor/server/officeserver/src/main/java/net/officefloor/server/http/HttpRequestCookie.java
officefloor/OfficeFloor
16c73ac87019d27de6df16c54c976a295db184ea
[ "Apache-2.0" ]
880
2019-07-08T04:31:14.000Z
2022-03-16T20:16:03.000Z
officefloor/server/officeserver/src/main/java/net/officefloor/server/http/HttpRequestCookie.java
officefloor/OfficeFloor
16c73ac87019d27de6df16c54c976a295db184ea
[ "Apache-2.0" ]
3
2019-09-30T08:22:37.000Z
2021-10-13T10:05:24.000Z
22.020833
75
0.667928
2,617
/*- * #%L * HTTP Server * %% * Copyright (C) 2005 - 2020 Daniel Sagenschneider * %% * 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. * #L% */ package net.officefloor.server.http; /** * <p> * Cookie on the {@link HttpRequest}. * <p> * As per <a href="https://tools.ietf.org/html/rfc6265">RFC-6265</a>. * * @author Daniel Sagenschneider */ public interface HttpRequestCookie { /** * Obtains the name. * * @return Name. */ String getName(); /** * Obtains the value. * * @return Value. */ String getValue(); }
3e0633c9462b9d3cc930fae221136e905776e830
2,399
java
Java
gulimall-order/src/main/java/com/criminal/gulimall/order/controller/OrderReturnReasonController.java
criminal016/gulimall
da50a19336a68c75e392329b70616b2f1feac7c5
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/criminal/gulimall/order/controller/OrderReturnReasonController.java
criminal016/gulimall
da50a19336a68c75e392329b70616b2f1feac7c5
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/criminal/gulimall/order/controller/OrderReturnReasonController.java
criminal016/gulimall
da50a19336a68c75e392329b70616b2f1feac7c5
[ "Apache-2.0" ]
null
null
null
26.622222
83
0.717446
2,618
package com.criminal.gulimall.order.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.criminal.gulimall.order.entity.OrderReturnReasonEntity; import com.criminal.gulimall.order.service.OrderReturnReasonService; import com.criminal.common.utils.PageUtils; import com.criminal.common.utils.R; /** * 退货原因 * * @author lifg * @email [email protected] * @date 2021-05-05 14:59:32 */ @RestController @RequestMapping("order/orderreturnreason") public class OrderReturnReasonController { @Autowired private OrderReturnReasonService orderReturnReasonService; /** * 列表 */ @RequestMapping("/list") // @RequiresPermissions("order:orderreturnreason:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = orderReturnReasonService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") // @RequiresPermissions("order:orderreturnreason:info") public R info(@PathVariable("id") Long id){ OrderReturnReasonEntity orderReturnReason = orderReturnReasonService.getById(id); return R.ok().put("orderReturnReason", orderReturnReason); } /** * 保存 */ @RequestMapping("/save") // @RequiresPermissions("order:orderreturnreason:save") public R save(@RequestBody OrderReturnReasonEntity orderReturnReason){ orderReturnReasonService.save(orderReturnReason); return R.ok(); } /** * 修改 */ @RequestMapping("/update") // @RequiresPermissions("order:orderreturnreason:update") public R update(@RequestBody OrderReturnReasonEntity orderReturnReason){ orderReturnReasonService.updateById(orderReturnReason); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") // @RequiresPermissions("order:orderreturnreason:delete") public R delete(@RequestBody Long[] ids){ orderReturnReasonService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
3e063440a075ad4d11b98d1aadc627000d48a7d9
4,202
java
Java
project/src/fw/jbiz/logic/ZLogic.java
xuedapeng/jbiz
792d449a093db8baad5868295fb514ed005a7dac
[ "Apache-2.0" ]
1
2019-08-16T03:06:15.000Z
2019-08-16T03:06:15.000Z
project/src/fw/jbiz/logic/ZLogic.java
xuedapeng/jbiz
792d449a093db8baad5868295fb514ed005a7dac
[ "Apache-2.0" ]
1
2018-05-11T12:00:38.000Z
2018-05-11T12:00:38.000Z
project/src/fw/jbiz/logic/ZLogic.java
xuedapeng/jbiz-core
792d449a093db8baad5868295fb514ed005a7dac
[ "Apache-2.0" ]
null
null
null
26.935897
121
0.680628
2,619
package fw.jbiz.logic; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.apache.log4j.Logger; import fw.jbiz.ext.json.ZGsonObject; import fw.jbiz.ext.json.ZSimpleJsonObject; import fw.jbiz.jpa.ZJpaHelper; import fw.jbiz.logic.interfaces.IResponseObject; public abstract class ZLogic extends ZLogicTop { static Logger logger = Logger.getLogger(ZLogic.class); // start add 2015.7.23 by xuedp [过滤器] private List<ZLogicFilter> logicFilterList = new ArrayList<ZLogicFilter>(); // end add @Override protected ZSimpleJsonObject res() { return new ZGsonObject(); } protected final EntityManager getEntityManager() { return ZJpaHelper.getEntityManager(getPersistenceUnitName()); } @Override protected String processLogic(ZLogicParam logicParam, IResponseObject res) { logger.info("processLogic 1"); EntityManager em = getEntityManager(); logger.info("processLogic 2"); try { logger.info("processLogic 3"); ZJpaHelper.beginTransaction(em); logger.info("processLogic 4"); // 执行前置过滤器 if (!doLogicFilterChainsBefore(logicParam, (ZSimpleJsonObject)res, em)) { return breakProcess(logicParam, (ZSimpleJsonObject)res, em); } logger.info("processLogic 5"); if (!validate(logicParam, (ZSimpleJsonObject)res, em)) { return breakProcess(logicParam, (ZSimpleJsonObject)res, em); } logger.info("processLogic 6"); // 身份认证 if (!auth(logicParam, (ZSimpleJsonObject)res, em)) { return breakProcess(logicParam, (ZSimpleJsonObject)res, em); } logger.info("processLogic 7"); // 执行主逻辑 boolean result = execute(logicParam, (ZSimpleJsonObject)res, em); String resStr = res.toString(); logger.info("processLogic 8"); // 执行后置过滤器 doLogicFilterChainsAfter(logicParam, (ZSimpleJsonObject)res, em); logger.info("processLogic 9"); if (result) { logger.info("processLogic 10"); ZJpaHelper.commit(em); } else { logger.info("processLogic 11"); ZJpaHelper.rollback(em); } logger.info("processLogic 12"); return resStr; } catch (Exception e) { logger.error(trace(e)); logger.info("processLogic 13"); try { ZJpaHelper.rollback(em); // 可能em事物没有启动成功 } catch (Exception e2) { logger.error(trace(e2)); } setErrorMessage(res, e); return res.toString(); } finally { logger.info("processLogic 14"); ZJpaHelper.closeEntityManager(em); } } // start add 2015.7.23 by xuedp [过滤器] protected void addFilter(ZLogicFilter filter) { this.logicFilterList.add(filter); } private boolean doLogicFilterChainsBefore(ZLogicParam logicParam, ZSimpleJsonObject res, EntityManager em) { for (ZLogicFilter filter: this.logicFilterList) { if (!filter.doFilterBefore(logicParam, res, em)) { return false; } } return true; } private boolean doLogicFilterChainsAfter(ZLogicParam logicParam, ZSimpleJsonObject res, EntityManager em) { for (ZLogicFilter filter: this.logicFilterList) { if (!filter.doFilterAfter(logicParam, res, em)) { return false; } } return true; } private String breakProcess(ZLogicParam logicParam, ZSimpleJsonObject res, EntityManager em) { try { logger.info("processLogic 21"); // 执行后置过滤器 doLogicFilterChainsAfter(logicParam, res, em); logger.info("processLogic 22"); ZJpaHelper.rollback(em); } catch(Exception e) { logger.error(trace(e)); } finally { // ZJpaHelper.closeEntityManager(em); process 中close } return res.toString(); } // end add // 身份认证 protected abstract boolean auth(ZLogicParam logicParam, ZSimpleJsonObject res, EntityManager em) throws Exception; protected abstract boolean execute(ZLogicParam logicParam, ZSimpleJsonObject res, EntityManager em) throws Exception; protected abstract boolean validate(ZLogicParam logicParam, ZSimpleJsonObject res, EntityManager em) throws Exception; protected abstract String getPersistenceUnitName(); }
3e063468f946a894f2204e28279f0e3626fc232d
826
java
Java
app-data/src/main/java/io/github/tkaczenko/model/enumeration/OrderType.java
tkaczenko/shop
c10966b2c20abcd67ac3593005e57b216b7c07a4
[ "MIT" ]
1
2018-09-19T15:15:00.000Z
2018-09-19T15:15:00.000Z
app-data/src/main/java/io/github/tkaczenko/model/enumeration/OrderType.java
tkaczenko/shop
c10966b2c20abcd67ac3593005e57b216b7c07a4
[ "MIT" ]
null
null
null
app-data/src/main/java/io/github/tkaczenko/model/enumeration/OrderType.java
tkaczenko/shop
c10966b2c20abcd67ac3593005e57b216b7c07a4
[ "MIT" ]
1
2018-10-14T01:56:24.000Z
2018-10-14T01:56:24.000Z
21.736842
107
0.625908
2,620
package io.github.tkaczenko.model.enumeration; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Created by tkaczenko on 11.03.17. */ public enum OrderType { IN_PROGRESS(0), SUBMITTED(1), DELIVERED(2); private static final Map<Integer, OrderType> lookup = Collections.unmodifiableMap(initializeMapping()); private int code; OrderType(int code) { this.code = code; } private static Map<Integer, OrderType> initializeMapping() { Map<Integer, OrderType> map = new HashMap<>(); for (OrderType v : OrderType.values()) { map.put(v.getCode(), v); } return map; } public static OrderType get(int code) { return lookup.get(code); } public int getCode() { return code; } }
3e0634f714cc23c8b4e4ee672664452e74efd952
3,977
java
Java
src/test/java/com/faforever/client/notification/NotificationServiceTest.java
Evgene-Kopylov/downlords-faf-client
96c933143d439acce2fb21bb1fe89e46f3ed72eb
[ "MIT" ]
161
2016-06-06T16:00:33.000Z
2022-03-19T20:11:05.000Z
src/test/java/com/faforever/client/notification/NotificationServiceTest.java
Evgene-Kopylov/downlords-faf-client
96c933143d439acce2fb21bb1fe89e46f3ed72eb
[ "MIT" ]
2,217
2016-05-27T18:21:49.000Z
2022-03-31T12:08:14.000Z
src/test/java/com/faforever/client/notification/NotificationServiceTest.java
Evgene-Kopylov/downlords-faf-client
96c933143d439acce2fb21bb1fe89e46f3ed72eb
[ "MIT" ]
127
2016-06-13T22:52:19.000Z
2022-03-02T17:47:25.000Z
33.420168
91
0.796077
2,621
package com.faforever.client.notification; import com.faforever.client.i18n.I18n; import com.faforever.client.reporting.ReportingService; import com.faforever.client.test.ServiceTest; import javafx.collections.SetChangeListener; import javafx.collections.SetChangeListener.Change; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class NotificationServiceTest extends ServiceTest { private NotificationService instance; @Mock private ReportingService reportingService; @Mock private I18n i18n; @BeforeEach public void setUp() throws Exception { instance = new NotificationService(reportingService, i18n); } @Test public void testAddNotificationPersistent() throws Exception { instance.addNotification(new PersistentNotification("text", Severity.INFO)); } @Test public void testAddNotificationImmediate() throws Exception { instance.addNotification(new ImmediateNotification("title", "text", Severity.INFO)); } @Test public void testAddNotificationTransient() throws Exception { instance.addNotification(new TransientNotification("title", "text")); } @Test @SuppressWarnings("unchecked") public void testAddPersistentNotificationListener() throws Exception { SetChangeListener<PersistentNotification> listener = mock(SetChangeListener.class); instance.addPersistentNotificationListener(listener); instance.addNotification(mock(PersistentNotification.class)); verify(listener).onChanged(any(Change.class)); } @Test @SuppressWarnings("unchecked") public void testAddTransientNotificationListener() throws Exception { OnTransientNotificationListener listener = mock(OnTransientNotificationListener.class); instance.addTransientNotificationListener(listener); TransientNotification notification = mock(TransientNotification.class); instance.addNotification(notification); verify(listener).onTransientNotification(notification); } @Test @SuppressWarnings("unchecked") public void testAddImmediateNotificationListener() throws Exception { OnImmediateNotificationListener listener = mock(OnImmediateNotificationListener.class); instance.addImmediateNotificationListener(listener); ImmediateNotification notification = mock(ImmediateNotification.class); instance.addNotification(notification); verify(listener).onImmediateNotification(notification); } @Test public void testGetPersistentNotifications() throws Exception { assertThat(instance.getPersistentNotifications(), empty()); PersistentNotification notification = mock(PersistentNotification.class); instance.addNotification(notification); assertThat(instance.getPersistentNotifications(), hasSize(1)); assertSame(notification, instance.getPersistentNotifications().iterator().next()); } @Test public void testRemoveNotification() throws Exception { assertThat(instance.getPersistentNotifications(), empty()); PersistentNotification notification1 = mock(PersistentNotification.class); PersistentNotification notification2 = mock(PersistentNotification.class); instance.addNotification(notification1); instance.addNotification(notification2); assertThat(instance.getPersistentNotifications(), hasSize(2)); instance.removeNotification(notification2); assertThat(instance.getPersistentNotifications(), hasSize(1)); assertSame(notification1, instance.getPersistentNotifications().iterator().next()); instance.removeNotification(notification1); assertThat(instance.getPersistentNotifications(), empty()); } }
3e06362bbe98d6d069fc3ca5b2e0c9c8fa76e09a
786
java
Java
src/main/java/br/zup/criacao/proposta/rodrigo/criacaoproposta/apiexterna/ConsultClient.java
rodrigoananiaszup/orange-talents-05-template-proposta
0211fc9099b018a27ac54dbb53572a1417353e54
[ "Apache-2.0" ]
null
null
null
src/main/java/br/zup/criacao/proposta/rodrigo/criacaoproposta/apiexterna/ConsultClient.java
rodrigoananiaszup/orange-talents-05-template-proposta
0211fc9099b018a27ac54dbb53572a1417353e54
[ "Apache-2.0" ]
null
null
null
src/main/java/br/zup/criacao/proposta/rodrigo/criacaoproposta/apiexterna/ConsultClient.java
rodrigoananiaszup/orange-talents-05-template-proposta
0211fc9099b018a27ac54dbb53572a1417353e54
[ "Apache-2.0" ]
null
null
null
39.3
108
0.838422
2,622
package br.zup.criacao.proposta.rodrigo.criacaoproposta.apiexterna; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import br.zup.criacao.proposta.rodrigo.criacaoproposta.proposta.consultadadosdosolicitante.ConsultaRequest; import br.zup.criacao.proposta.rodrigo.criacaoproposta.proposta.consultadadosdosolicitante.ConsultaResponse; @FeignClient(value = "ConsultaClient", url = "${consulta.uri}") public interface ConsultClient { @PostMapping("/api/solicitacao") ResponseEntity<ConsultaResponse> consultar(ConsultaRequest request); @GetMapping("/actuator/health") ResponseEntity<Void> healthCheck(); }
3e06366873bbedd135f1f4248bb4f946222c8632
2,163
java
Java
app/src/main/java/com/wzl/wzl_vanda/vandaimlibforhub/LoginActivity.java
10045125/VandaIMLibForHub
6442392700762f0d30fef590eb004a5ce5604f9a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/wzl/wzl_vanda/vandaimlibforhub/LoginActivity.java
10045125/VandaIMLibForHub
6442392700762f0d30fef590eb004a5ce5604f9a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/wzl/wzl_vanda/vandaimlibforhub/LoginActivity.java
10045125/VandaIMLibForHub
6442392700762f0d30fef590eb004a5ce5604f9a
[ "Apache-2.0" ]
null
null
null
32.772727
136
0.661119
2,623
package com.wzl.wzl_vanda.vandaimlibforhub; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.avos.avoscloud.AVException; import com.avos.avoscloud.AVUser; import com.avos.avoscloud.LogInCallback; import com.wzl.wzl_vanda.vandaimlibforhub.controller.ChatManager; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by wzl_vanda on 15/7/31. */ public class LoginActivity extends AppCompatActivity { @Bind(R.id.id_username) EditText idUsername; @Bind(R.id.id_userpassword) EditText idUserpassword; @Bind(R.id.id_btn_login) Button idBtnLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_mina); ButterKnife.bind(this); if (AVUser.getCurrentUser() != null) { startActivity(new Intent(this, MainBaseActivity.class)); finish(); } } @OnClick(R.id.id_btn_login) public void IdButtonLogin(View view) { if (!idUsername.getText().toString().equals("") && !idUserpassword.getText().toString().equals("")) { AVUser.logInInBackground(idUsername.getText().toString(), idUserpassword.getText().toString(), new LogInCallback<AVUser>() { @Override public void done(AVUser avUser, AVException e) { if (AVUser.getCurrentUser() != null) { ChatManager.getInstance().setupDatabaseWithSelfId(AVUser.getCurrentUser().getObjectId()); ChatManager.getInstance().openClientWithSelfId(AVUser.getCurrentUser().getObjectId(), null); } startActivity(new Intent(LoginActivity.this, MainBaseActivity.class)); finish(); } }); } else { Toast.makeText(this, "error", Toast.LENGTH_SHORT).show(); } } }
3e0637cc95e14cdbc3a162c593e839ffb4ef7300
2,169
java
Java
app/src/main/java/gq/altafchaudhari/cowatch/utilities/ExceptionHandler.java
altafc22/CoronaTracker
d983111f953a211e8e1493d1c3a1c14cc01129ee
[ "MIT" ]
null
null
null
app/src/main/java/gq/altafchaudhari/cowatch/utilities/ExceptionHandler.java
altafc22/CoronaTracker
d983111f953a211e8e1493d1c3a1c14cc01129ee
[ "MIT" ]
null
null
null
app/src/main/java/gq/altafchaudhari/cowatch/utilities/ExceptionHandler.java
altafc22/CoronaTracker
d983111f953a211e8e1493d1c3a1c14cc01129ee
[ "MIT" ]
null
null
null
30.985714
72
0.723836
2,624
package gq.altafchaudhari.cowatch.utilities; import android.app.Activity; import android.content.Intent; import android.os.Build; import java.io.PrintWriter; import java.io.StringWriter; public class ExceptionHandler implements Thread.UncaughtExceptionHandler { private final Activity myContext; private final String LINE_SEPARATOR = "\n"; private Class<?> activity; public ExceptionHandler(Activity context, Class<?> activity) { myContext = context; this.activity = activity; } public void uncaughtException(Thread thread, Throwable exception) { StringWriter stackTrace = new StringWriter(); exception.printStackTrace(new PrintWriter(stackTrace)); StringBuilder errorReport = new StringBuilder(); errorReport.append("************ CAUSE OF ERROR ************\n\n"); errorReport.append(stackTrace.toString()); errorReport.append("\n************ DEVICE INFORMATION ***********\n"); errorReport.append("Brand: "); errorReport.append(Build.BRAND); errorReport.append(LINE_SEPARATOR); errorReport.append("Device: "); errorReport.append(Build.DEVICE); errorReport.append(LINE_SEPARATOR); errorReport.append("Model: "); errorReport.append(Build.MODEL); errorReport.append(LINE_SEPARATOR); errorReport.append("Id: "); errorReport.append(Build.ID); errorReport.append(LINE_SEPARATOR); errorReport.append("Product: "); errorReport.append(Build.PRODUCT); errorReport.append(LINE_SEPARATOR); errorReport.append("\n************ FIRMWARE ************\n"); errorReport.append("SDK: "); errorReport.append(Build.VERSION.SDK); errorReport.append(LINE_SEPARATOR); errorReport.append("Release: "); errorReport.append(Build.VERSION.RELEASE); errorReport.append(LINE_SEPARATOR); errorReport.append("Incremental: "); errorReport.append(Build.VERSION.INCREMENTAL); errorReport.append(LINE_SEPARATOR); Intent intent = new Intent(myContext, activity); intent.putExtra("error", errorReport.toString()); myContext.startActivity(intent); exitReport(); } private void exitReport(){ android.os.Process.killProcess(android.os.Process.myPid()); System.exit(10); } }
3e0638015ef2c6b686fdeadecea01b197195ea3e
6,656
java
Java
app/src/main/java/com/example/startit/ToDoItem.java
mdechdee/CS350_Start-It
e3f351b5aaba17f9a12614fea460ca5114118596
[ "MIT" ]
1
2019-09-19T05:54:24.000Z
2019-09-19T05:54:24.000Z
app/src/main/java/com/example/startit/ToDoItem.java
mdechdee/CS350_Start-It
e3f351b5aaba17f9a12614fea460ca5114118596
[ "MIT" ]
null
null
null
app/src/main/java/com/example/startit/ToDoItem.java
mdechdee/CS350_Start-It
e3f351b5aaba17f9a12614fea460ca5114118596
[ "MIT" ]
null
null
null
29.192982
228
0.631761
2,625
package com.example.startit; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; public class ToDoItem { /* * ::::::::::::::::::::::::ToDoItem class index:::::::::::::::::::::::: * * ::::::::::::::::::::::::Default Properties Of Classes:::::::::::::::::::::::: * * attributes line = 45 * * constructors line = 65 * * setters line = 95 * getters line = 121 * * isEqual(object) line = 199 * * @Override * toString() line = 214 * * ::::::::::::::::::::::::Methods:::::::::::::::::::::::: * * markAsDone() ; mark the item as done. * isDone() ; checks weather this item is done or not. * addTagName(tag) ; add a new tag to the item. * isTagged(tag) ; checks weather this item has the specified tag * deleteTagName(tag) ; delete a specific tag from the item's tag list and returns that deleted item. * updateTimeTaken(extraTime) ; add an extra time to ( timeTaken ) to record any progress. * timeSpare(date) ; checks the remaining time until the due date. * isPassDue() ; check weather it is passed due or not. * * * ::::::::::::::::::::::::Requirements:::::::::::::::::::::::: * * Android version 8.0 or later. * * */ //identity of an item. private String title; private String note; private ArrayList<String> tags; private final int TAGS_CAP = 10; //time constraints private LocalDateTime dateAdded; private LocalDateTime dueDate; private Duration estimatedTime; private Duration timeTaken; //score system private int difficulatyScore; private int scoreAchieved; //achievement status ( is it done ? ) private boolean isDone; //constructors public ToDoItem(){ this("","",new ArrayList<String>(),LocalDateTime.now(),LocalDateTime.MAX, Duration.ofMinutes(0),Duration.ofSeconds(0),0,0,false); } public ToDoItem(String title , String note, ArrayList<String> tags , LocalDateTime dateAdded , LocalDateTime dueDate , Duration timeTaken , Duration estimatedTime , int difficulatyScore , int scoreAchieved , boolean isDone){ this.title = title; this.note = note; this.tags = tags; this.dateAdded = dateAdded; this.dueDate = dueDate; this.timeTaken = timeTaken; this.estimatedTime = estimatedTime; this.difficulatyScore = difficulatyScore; this.scoreAchieved = scoreAchieved; this.isDone = isDone; } public ToDoItem(String title , String note, ArrayList<String> tags , LocalDateTime dateAdded , LocalDateTime dueDate , Duration estimatedTime , int difficulatyScore ){ this(title,note,tags,dateAdded,dueDate,Duration.ofMinutes(0),estimatedTime,difficulatyScore,0,false); } public ToDoItem(String title , String note, LocalDateTime dateAdded , LocalDateTime dueDate , Duration estimatedTime , int difficulatyScore ){ this(title,note,new ArrayList<String>(),dateAdded,dueDate,Duration.ofMinutes(0),estimatedTime,difficulatyScore,0,false); } public ToDoItem(String title , LocalDateTime dateAdded , LocalDateTime dueDate , Duration estimatedTime , int difficulatyScore ){ this(title,"",dateAdded,dueDate,estimatedTime,difficulatyScore); } //Setters public void setTitle(String title){ this.title = title; } public void setNote(String note){ this.note = note; } public void setTags(ArrayList<String> tags){ this.tags = tags; } public void setDateAdded(LocalDateTime dateAdded){ this.dateAdded = dateAdded; } public void setDueDate(LocalDateTime dueDate){ this.dueDate = dueDate; } public void setEstimatedTime(Duration estimatedTime){ this.estimatedTime = estimatedTime; } public void setDifficulatyScore(int difficulatyScore){ this.difficulatyScore = difficulatyScore; } public void setTimeTaken(Duration timeTaken){ this.timeTaken = timeTaken; } //getters public String getTitle(){ return title; } public String getNote(){ return note; } public LocalDateTime getDateAdded(){ return dateAdded; } public LocalDateTime getDueDate(){ return dueDate; } public Duration getEstimatedTime(){ return estimatedTime; } public Duration getTimeTaken() { return timeTaken; } public int getDifficulatyScore(){ return difficulatyScore; } public int getScoreAchieved(){ return scoreAchieved; } //methods public void markAsDone(){ isDone = true; } public boolean isDone(){ return isDone; } public void addTagName(String newTag){ if(newTag instanceof String){ newTag = newTag.toLowerCase(); //potential exception (duplicate tag && full array) if( !(tags.contains(newTag)) && tags.size() <= TAGS_CAP )//checks existence & not exceeding the capacity tags.add(newTag); } } public boolean isTagged(String tag){ return tags.contains(tag);//returns true if the tag is found in the list } public String deleteTagName(String deletedTag){ //potential exception ( notFoundTag && remove from empty list ) if(tags.remove(deletedTag))//returns true if deleted successfully return deletedTag; return ""; } public void updateTimeTaken(Duration extraTime){ timeTaken = timeTaken.plus(extraTime);//update the time taken on this item with passed argument added } public Duration timeSpare(LocalDateTime date){ //potential exception ( passDue exception ) if(dueDate.isBefore(date)){//if it is passed due then return 0 seconds spare time; return Duration.of(0,ChronoUnit.SECONDS); } return Duration.between(date,dueDate);//else it returns the spare time until due date } public boolean isPassDue(){ return dueDate.isBefore(LocalDateTime.now());//checks if due date comes before the date of calling this function. } //this function compares to Items by title. It returns true if equal and false otherwise. public boolean isEqual(Object o) { if(this.getClass() != o.getClass()){ return false; }else{ if(this.title != ((ToDoItem)o).title ) return false; } return true; } @Override public String toString(){ return""; } }
3e06387639eded55547020119529bcfe5625987a
1,128
java
Java
src/main/java/io/quarkuscoffeeshop/homeoffice/infrastructure/MockerService.java
quarkuscoffeeshop/homeoffice-backend
4db393cfa338346aefb2672e295c987fc91e5d77
[ "Apache-2.0" ]
null
null
null
src/main/java/io/quarkuscoffeeshop/homeoffice/infrastructure/MockerService.java
quarkuscoffeeshop/homeoffice-backend
4db393cfa338346aefb2672e295c987fc91e5d77
[ "Apache-2.0" ]
null
null
null
src/main/java/io/quarkuscoffeeshop/homeoffice/infrastructure/MockerService.java
quarkuscoffeeshop/homeoffice-backend
4db393cfa338346aefb2672e295c987fc91e5d77
[ "Apache-2.0" ]
null
null
null
24.521739
71
0.621454
2,626
package io.quarkuscoffeeshop.homeoffice.infrastructure; import io.quarkus.runtime.QuarkusApplication; import io.quarkus.runtime.annotations.QuarkusMain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.util.Random; @QuarkusMain @Singleton public class MockerService implements QuarkusApplication { final Logger logger = LoggerFactory.getLogger(MockerService.class); @Inject OrderMocker orderMocker; private boolean running = true; public boolean pause = false; @Override public int run(String... args) throws Exception { logger.info("starting"); mock.run(); return 10; } private Runnable mock = () -> { while (running == true) { try { while (!pause){ Thread.sleep(1000); } Thread.sleep((new Random().nextInt(3)+1) * 1000); orderMocker.mockAndPersistOrder(); } catch (InterruptedException e) { e.printStackTrace(); } } }; }
3e0638bca3eb0f40ff735dd7e2036f17f198f538
4,826
java
Java
Corpus/eclipse.pde.ui/113.java
masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018
72aee638779aef7a56295c784a9bcbd902e41593
[ "MIT" ]
15
2018-07-10T09:38:31.000Z
2021-11-29T08:28:07.000Z
Corpus/eclipse.pde.ui/113.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
3
2018-11-16T02:58:59.000Z
2021-01-20T16:03:51.000Z
Corpus/eclipse.pde.ui/113.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
6
2018-06-27T20:19:00.000Z
2022-02-19T02:29:53.000Z
40.940678
146
0.569861
2,627
/******************************************************************************* * Copyright (c) 2000, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Lars Vogel <[email protected]> - Bug 487943 *******************************************************************************/ package org.eclipse.pde.internal.ui.views.dependencies; import org.eclipse.jface.viewers.*; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.pde.core.plugin.IPluginModelBase; import org.eclipse.pde.core.plugin.ModelEntry; import org.eclipse.pde.internal.core.*; public class DependenciesViewPageContentProvider implements IContentProvider, IPluginModelListener { private DependenciesView fView; private StructuredViewer fViewer; /** * Constructor. */ public DependenciesViewPageContentProvider(DependenciesView view) { this.fView = view; attachModelListener(); } public void attachModelListener() { PDECore.getDefault().getModelManager().addPluginModelListener(this); } public void removeModelListener() { PDECore.getDefault().getModelManager().removePluginModelListener(this); } @Override public void dispose() { removeModelListener(); } private void handleModifiedModels(ModelEntry[] modified) { Object input = fViewer.getInput(); if (input instanceof IPluginModelBase) { BundleDescription desc = ((IPluginModelBase) input).getBundleDescription(); String inputID = (desc != null) ? desc.getSymbolicName() : ((IPluginModelBase) input).getPluginBase().getId(); for (int i = 0; i < modified.length; i++) { ModelEntry entry = modified[i]; if (entry.getId().equals(inputID)) { // if we find a matching id to our current input, check to see if the input still exists if (modelExists(entry, (IPluginModelBase) input)) fView.updateTitle(input); else // if input model does not exist, clear view fView.openTo(null); return; } } } } private boolean modelExists(ModelEntry entry, IPluginModelBase input) { IPluginModelBase[][] entries = new IPluginModelBase[][] { entry.getExternalModels(), entry.getWorkspaceModels() }; for (int i = 0; i < 2; i++) { for (int j = 0; j < entries[i].length; j++) { if (entries[i][j].equals(input)) return true; } } return false; } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { fView.updateTitle(newInput); this.fViewer = (StructuredViewer) viewer; } @Override public void modelsChanged(final PluginModelDelta delta) { if (fViewer == null || fViewer.getControl().isDisposed()) return; fViewer.getControl().getDisplay().asyncExec(new Runnable() { @Override public void run() { int kind = delta.getKind(); if (fViewer.getControl().isDisposed()) return; try { if ((kind & PluginModelDelta.REMOVED) != 0) { // called when all instances of a Bundle-SymbolicName are all removed handleModifiedModels(delta.getRemovedEntries()); } if ((kind & PluginModelDelta.CHANGED) != 0) { // called when a plug-in is changed (possibly the input) // AND when the model for the ModelEntry changes (new bundle with existing id/remove bundle with 2 instances with same id) handleModifiedModels(delta.getChangedEntries()); } if ((kind & PluginModelDelta.ADDED) != 0) { // when user modifies Bundle-SymbolicName, a ModelEntry is created for the new name. In this case, if the input matches // the modified model, we need to update the title. handleModifiedModels(delta.getAddedEntries()); } } finally { // no matter what, refresh the viewer since bundles might un/resolve with changes fViewer.refresh(); } } }); } }
3e0638d942ed3b5a1937aec5f7111469e0827255
157
java
Java
app/src/main/java/hackmaster/persistence/DBComponentInterface.java
drFruitFace/HackMaster
cd963f0d5b764d7b717b64459c0b9cd000cab82d
[ "BSD-3-Clause" ]
2
2018-10-13T19:29:33.000Z
2019-01-03T21:58:32.000Z
app/src/main/java/hackmaster/persistence/DBComponentInterface.java
drFruitFace/HackMaster
cd963f0d5b764d7b717b64459c0b9cd000cab82d
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/hackmaster/persistence/DBComponentInterface.java
drFruitFace/HackMaster
cd963f0d5b764d7b717b64459c0b9cd000cab82d
[ "BSD-3-Clause" ]
null
null
null
17.444444
39
0.764331
2,628
package hackmaster.persistence; import java.sql.Statement; public interface DBComponentInterface { void open(Statement statement); void close(); }
3e06392b1715189395c963461f25566f57f54538
1,984
java
Java
coeus-code/src/main/java/org/kuali/coeus/common/budget/framework/core/category/BudgetCategoryMapping.java
sasipolus/kc
6bf957db29c17162853c41710f5898631fb4a111
[ "ECL-2.0" ]
null
null
null
coeus-code/src/main/java/org/kuali/coeus/common/budget/framework/core/category/BudgetCategoryMapping.java
sasipolus/kc
6bf957db29c17162853c41710f5898631fb4a111
[ "ECL-2.0" ]
null
null
null
coeus-code/src/main/java/org/kuali/coeus/common/budget/framework/core/category/BudgetCategoryMapping.java
sasipolus/kc
6bf957db29c17162853c41710f5898631fb4a111
[ "ECL-2.0" ]
null
null
null
29.61194
117
0.743448
2,629
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-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.kuali.coeus.common.budget.framework.core.category; import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase; import org.kuali.coeus.common.budget.api.core.category.BudgetCategoryMappingContract; public class BudgetCategoryMapping extends KcPersistableBusinessObjectBase implements BudgetCategoryMappingContract { private String budgetCategoryCode; private String mappingName; private String targetCategoryCode; private BudgetCategory budgetCategory; @Override public String getBudgetCategoryCode() { return budgetCategoryCode; } public void setBudgetCategoryCode(String budgetCategoryCode) { this.budgetCategoryCode = budgetCategoryCode; } @Override public String getMappingName() { return mappingName; } public void setMappingName(String mappingName) { this.mappingName = mappingName; } @Override public String getTargetCategoryCode() { return targetCategoryCode; } public void setTargetCategoryCode(String targetCategoryCode) { this.targetCategoryCode = targetCategoryCode; } @Override public BudgetCategory getBudgetCategory() { return budgetCategory; } public void setBudgetCategory(BudgetCategory budgetCategory) { this.budgetCategory = budgetCategory; } }
3e06397679867dcd639f8d6f3498ed838504a783
1,159
java
Java
src/main/java/org/omg/hw/flowDomain_cmcc/ConnectivityRequirement_T.java
dong706/CorbaDemo
bcf0826ae8934f91b5e68085605127c2a671ffe3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/omg/hw/flowDomain_cmcc/ConnectivityRequirement_T.java
dong706/CorbaDemo
bcf0826ae8934f91b5e68085605127c2a671ffe3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/omg/hw/flowDomain_cmcc/ConnectivityRequirement_T.java
dong706/CorbaDemo
bcf0826ae8934f91b5e68085605127c2a671ffe3
[ "Apache-2.0" ]
null
null
null
25.755556
101
0.752373
2,630
package org.omg.hw.flowDomain_cmcc; /** * Generated from IDL definition of enum "ConnectivityRequirement_T" * @author JacORB IDL compiler */ public final class ConnectivityRequirement_T implements org.omg.CORBA.portable.IDLEntity { private int value = -1; public static final int _CR_IGNORE = 0; public static final ConnectivityRequirement_T CR_IGNORE = new ConnectivityRequirement_T(_CR_IGNORE); public static final int _CR_REJECT = 1; public static final ConnectivityRequirement_T CR_REJECT = new ConnectivityRequirement_T(_CR_REJECT); public int value() { return value; } public static ConnectivityRequirement_T from_int(int value) { switch (value) { case _CR_IGNORE: return CR_IGNORE; case _CR_REJECT: return CR_REJECT; default: throw new org.omg.CORBA.BAD_PARAM(); } } public String toString() { switch (value) { case _CR_IGNORE: return "CR_IGNORE"; case _CR_REJECT: return "CR_REJECT"; default: throw new org.omg.CORBA.BAD_PARAM(); } } protected ConnectivityRequirement_T(int i) { value = i; } java.lang.Object readResolve() throws java.io.ObjectStreamException { return from_int(value()); } }
3e063a4852b83713af1d870c40d3eada768a8afe
1,361
java
Java
src/main/java/com/mychaldea/api/banner/info/entity/BannerInfoSave.java
sir-nutty/myChaldea-API
4583462b594bf11f970ed022a8c403047c5850ba
[ "MIT" ]
null
null
null
src/main/java/com/mychaldea/api/banner/info/entity/BannerInfoSave.java
sir-nutty/myChaldea-API
4583462b594bf11f970ed022a8c403047c5850ba
[ "MIT" ]
4
2021-07-21T15:19:47.000Z
2021-07-21T15:29:21.000Z
src/main/java/com/mychaldea/api/banner/info/entity/BannerInfoSave.java
sir-nutty/myChaldea-API
4583462b594bf11f970ed022a8c403047c5850ba
[ "MIT" ]
null
null
null
43.903226
102
0.767818
2,631
package com.mychaldea.api.banner.info.entity; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedStoredProcedureQuery; import javax.persistence.ParameterMode; import javax.persistence.StoredProcedureParameter; @Entity @NamedStoredProcedureQuery(name = "saveBannerInfo", procedureName = "saveBannerInfo", parameters = { @StoredProcedureParameter(mode = ParameterMode.IN, name = "user_uid", type = String.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "banner_ID", type = Integer.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "bannerRegion_ID", type = Integer.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "bannerName", type = String.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "region", type = String.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "startDate", type = Date.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "endDate", type = Date.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "image", type = String.class) }, resultClasses = BannerInfoSave.class) public class BannerInfoSave { @Id @GeneratedValue @Column(name = "ID") private int id; }
3e063a57aaa3e99501652c13eceae3d3a05a1a02
1,725
java
Java
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/CustomTargetingKeyType.java
admariner/googleads-java-lib
31a159d6bae4f98a97ac1210e6cf6d18ef0cb68c
[ "Apache-2.0" ]
215
2015-01-03T08:17:03.000Z
2022-01-20T09:48:18.000Z
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/CustomTargetingKeyType.java
googleads/googleads-java-lib
cc5b2fc8ef76082b72f021c11ff9b7e4d9326aca
[ "Apache-2.0" ]
189
2015-01-06T15:16:41.000Z
2021-12-16T14:13:12.000Z
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/CustomTargetingKeyType.java
admariner/googleads-java-lib
31a159d6bae4f98a97ac1210e6cf6d18ef0cb68c
[ "Apache-2.0" ]
382
2015-01-07T04:42:40.000Z
2022-03-03T12:15:10.000Z
25.746269
95
0.654493
2,632
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.api.ads.admanager.jaxws.v202105; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CustomTargetingKey.Type. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="CustomTargetingKey.Type"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="PREDEFINED"/> * &lt;enumeration value="FREEFORM"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "CustomTargetingKey.Type") @XmlEnum public enum CustomTargetingKeyType { /** * * Target audiences by criteria values that are defined in advance. * * */ PREDEFINED, /** * * Target audiences by adding criteria values when creating line items. * * */ FREEFORM; public String value() { return name(); } public static CustomTargetingKeyType fromValue(String v) { return valueOf(v); } }
3e063acda75e839c733e1f27e8912635ba3f0267
4,721
java
Java
integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/extender/ExtenderTest.java
cit-consulting/gemini.blueprint
d671a74fe8aa631e8f006aad5e43d3b3f1be6359
[ "Apache-2.0" ]
26
2015-02-13T10:07:12.000Z
2022-02-18T04:31:58.000Z
integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/extender/ExtenderTest.java
cit-consulting/gemini.blueprint
d671a74fe8aa631e8f006aad5e43d3b3f1be6359
[ "Apache-2.0" ]
8
2015-06-21T12:17:01.000Z
2018-04-16T05:31:20.000Z
integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/extender/ExtenderTest.java
cit-consulting/gemini.blueprint
d671a74fe8aa631e8f006aad5e43d3b3f1be6359
[ "Apache-2.0" ]
28
2015-05-04T08:36:14.000Z
2021-08-19T10:36:52.000Z
38.382114
115
0.705994
2,633
/****************************************************************************** * Copyright (c) 2006, 2010 VMware Inc., Oracle Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0 * is available at http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * * Contributors: * VMware Inc. * Oracle Inc. *****************************************************************************/ package org.eclipse.gemini.blueprint.iandt.extender; import java.io.FilePermission; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.gemini.blueprint.iandt.BaseIntegrationTest; import org.osgi.framework.AdminPermission; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.util.tracker.ServiceTracker; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.springframework.util.CollectionUtils; /** * @author Hal Hildebrand Date: May 21, 2007 Time: 4:43:52 PM */ public class ExtenderTest extends BaseIntegrationTest { protected String getManifestLocation() { return null; } // Overridden to remove the spring extender bundle! protected String[] getTestFrameworkBundlesNames() { String[] bundles = super.getTestFrameworkBundlesNames(); List list = new ArrayList(bundles.length); // remove extender CollectionUtils.mergeArrayIntoCollection(bundles, list); // additionally remove the annotation bundle as well (if included) int bundlesFound = 0; for (Iterator iter = list.iterator(); (iter.hasNext() && (bundlesFound < 2));) { String element = (String) iter.next(); if (element.indexOf("extender") >= 0 || element.indexOf("osgi-annotation") >= 0) { iter.remove(); bundlesFound++; } } return (String[]) list.toArray(new String[list.size()]); } // Specifically cannot wait - test scenario has bundles which are spring // powered, but will not be started. protected boolean shouldWaitForSpringBundlesContextCreation() { return false; } protected String[] getTestBundlesNames() { return new String[] { "org.eclipse.gemini.blueprint.iandt, lifecycle," + getSpringDMVersion() }; } public void testLifecycle() throws Exception { assertNull("Guinea pig has already been started", System .getProperty("org.eclipse.gemini.blueprint.iandt.lifecycle.GuineaPig.close")); StringBuilder filter = new StringBuilder(); filter.append("(&"); filter.append("(").append(Constants.OBJECTCLASS).append("=").append(ApplicationContext.class.getName()).append( ")"); filter.append("(").append("org.springframework.context.service.name"); filter.append("=").append("org.eclipse.gemini.blueprint.iandt.lifecycle").append(")"); filter.append(")"); ServiceTracker tracker = new ServiceTracker(bundleContext, bundleContext.createFilter(filter.toString()), null); tracker.open(); ApplicationContext appContext = (ApplicationContext) tracker.waitForService(1); assertNull("lifecycle application context does not exist", appContext); Resource extenderResource = getLocator().locateArtifact("org.eclipse.gemini.blueprint", "gemini-blueprint-extender", getSpringDMVersion()); assertNotNull("Extender bundle resource", extenderResource); Bundle extenderBundle = bundleContext.installBundle(extenderResource.getURL().toExternalForm()); assertNotNull("Extender bundle", extenderBundle); extenderBundle.start(); tracker.open(); appContext = (ApplicationContext) tracker.waitForService(60000); assertNotNull("lifecycle application context exists", appContext); assertNotSame("Guinea pig hasn't already been shutdown", "true", System .getProperty("org.eclipse.gemini.blueprint.iandt.lifecycle.GuineaPig.close")); assertEquals("Guinea pig started up", "true", System .getProperty("org.eclipse.gemini.blueprint.iandt.lifecycle.GuineaPig.startUp")); } protected List getTestPermissions() { List perms = super.getTestPermissions(); // export package perms.add(new AdminPermission("*", AdminPermission.EXECUTE)); perms.add(new AdminPermission("*", AdminPermission.LIFECYCLE)); perms.add(new AdminPermission("*", AdminPermission.RESOLVE)); perms.add(new FilePermission("<<ALL FILES>>", "read")); return perms; } }
3e063c14513d9f03a7ad5d4f4059939246e91f9a
1,984
java
Java
src/com/reason/lang/ModuleHelper.java
samdfonseca/reasonml-idea-plugin
a3cb65f2b60aaeacb307b458d1838dad185458d3
[ "MIT" ]
null
null
null
src/com/reason/lang/ModuleHelper.java
samdfonseca/reasonml-idea-plugin
a3cb65f2b60aaeacb307b458d1838dad185458d3
[ "MIT" ]
null
null
null
src/com/reason/lang/ModuleHelper.java
samdfonseca/reasonml-idea-plugin
a3cb65f2b60aaeacb307b458d1838dad185458d3
[ "MIT" ]
null
null
null
32.52459
112
0.610887
2,634
package com.reason.lang; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.reason.lang.core.psi.PsiAnnotation; import com.reason.lang.core.psi.PsiExternal; import com.reason.lang.core.psi.PsiLet; import org.jetbrains.annotations.Nullable; import java.util.List; public class ModuleHelper { private ModuleHelper() { } public static boolean isComponent(@Nullable PsiElement element) { if (element == null) { return false; } PsiElement componentDef = null; PsiLet makeDef = null; // JSX 3 // Try to find a react.component attribute List<PsiAnnotation> annotations = PsiTreeUtil.getStubChildrenOfTypeAsList(element, PsiAnnotation.class); for (PsiAnnotation annotation : annotations) { if ("@react.component".equals(annotation.getName())) { return true; } } // JSX 2 // Try to find if it's a proxy to a React class List<PsiExternal> externals = PsiTreeUtil.getStubChildrenOfTypeAsList(element, PsiExternal.class); for (PsiExternal external : externals) { if ("ReasonReact.reactClass".equals(external.getORSignature().asString(element.getLanguage()))) { componentDef = external; break; } } // Try to find a make function and a component (if not a proxy) functions List<PsiLet> expressions = PsiTreeUtil.getStubChildrenOfTypeAsList(element, PsiLet.class); for (PsiLet let : expressions) { if (componentDef == null && "component".equals(let.getName())) { componentDef = let; } else if (makeDef == null && "make".equals(let.getName())) { makeDef = let; } else if (componentDef != null && makeDef != null) { break; } } return componentDef != null && makeDef != null; } }
3e063c5bbe54f60344b6f1c3928bb68eb32c1d5f
395
java
Java
java/Visitor/src/Boss.java
harkhuang/designpatterns
dfd6623976410882753913498158dcb0ea70c1d2
[ "Apache-2.0" ]
null
null
null
java/Visitor/src/Boss.java
harkhuang/designpatterns
dfd6623976410882753913498158dcb0ea70c1d2
[ "Apache-2.0" ]
null
null
null
java/Visitor/src/Boss.java
harkhuang/designpatterns
dfd6623976410882753913498158dcb0ea70c1d2
[ "Apache-2.0" ]
null
null
null
17.954545
68
0.620253
2,635
public class Boss extends Employee { private int bonusDays; public Boss(String name, float salary, int vacdays, int sickdays) { super(name, salary, vacdays, sickdays); } public void setBonusDays(int bonus) { bonusDays = bonus; } public int getBonusDays() { return bonusDays; } public void accept(Visitor v) { v.visit(this); } }
3e063ca94eeb5f27ed79b9bf1d88bbfb6c455284
857
java
Java
jadx-core/src/test/java/jadx/tests/integration/trycatch/TestTryCatchFinally11.java
warifp/jadx
63f7ce20a412bac4abb665207ec1682761186f74
[ "Apache-2.0" ]
30,785
2015-01-01T08:27:01.000Z
2022-03-31T19:45:36.000Z
jadx-core/src/test/java/jadx/tests/integration/trycatch/TestTryCatchFinally11.java
warifp/jadx
63f7ce20a412bac4abb665207ec1682761186f74
[ "Apache-2.0" ]
1,263
2015-01-06T19:10:02.000Z
2022-03-31T16:30:21.000Z
jadx-core/src/test/java/jadx/tests/integration/trycatch/TestTryCatchFinally11.java
warifp/jadx
63f7ce20a412bac4abb665207ec1682761186f74
[ "Apache-2.0" ]
4,097
2015-01-04T05:58:26.000Z
2022-03-31T07:26:09.000Z
17.489796
69
0.660443
2,636
package jadx.tests.integration.trycatch; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import jadx.tests.api.IntegrationTest; import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat; public class TestTryCatchFinally11 extends IntegrationTest { public static class TestCls { private int count = 0; public void test(List<Object> list) { try { call1(); } finally { for (Object item : list) { call2(item); } } } private void call1() { count += 100; } private void call2(Object item) { count++; } public void check() { TestCls t = new TestCls(); t.test(Arrays.asList("1", "2")); assertThat(t.count).isEqualTo(102); } } @Test public void test() { assertThat(getClassNode(TestCls.class)) .code() .containsOne("} finally {"); } }
3e063df60d57ae6a7825e18b331a380b160515f9
1,276
java
Java
jeecg-cloud-module/jeecg-cloud-system-eval/src/main/java/org/jeecg/modules/running/uut/service/impl/RunningUutListServiceImpl.java
zhanglailong/stcp
2209f2f7c81a01da948e5c6c050d215d656a77de
[ "MIT" ]
null
null
null
jeecg-cloud-module/jeecg-cloud-system-eval/src/main/java/org/jeecg/modules/running/uut/service/impl/RunningUutListServiceImpl.java
zhanglailong/stcp
2209f2f7c81a01da948e5c6c050d215d656a77de
[ "MIT" ]
null
null
null
jeecg-cloud-module/jeecg-cloud-system-eval/src/main/java/org/jeecg/modules/running/uut/service/impl/RunningUutListServiceImpl.java
zhanglailong/stcp
2209f2f7c81a01da948e5c6c050d215d656a77de
[ "MIT" ]
null
null
null
33.578947
132
0.806426
2,637
package org.jeecg.modules.running.uut.service.impl; import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.jeecg.modules.running.uut.entity.RunningUutList; import org.jeecg.modules.running.uut.mapper.RunningUutListMapper; import org.jeecg.modules.running.uut.service.IRunningUutListService; import org.jeecg.modules.running.uut.vo.RunningUutListVo; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @Description: 被测对象列表 * @Author: jeecg-boot * @Date: 2020-12-23 * @Version: V1.0 */ @Service @DS("uutDatabase") public class RunningUutListServiceImpl extends ServiceImpl<RunningUutListMapper, RunningUutList> implements IRunningUutListService { @Override @Transactional(rollbackFor = Exception.class) public RunningUutList findUniqueBy(String fieldname, String value) { return this.getBaseMapper().findUniqueBy(fieldname, value); } @Override public RunningUutListVo findUniqueVoBy(String fieldname, String value) { return this.getBaseMapper().findUniqueVoBy(fieldname, value); } @Override public void changeSystem(String uutId, String systemId) { this.getBaseMapper().changeSystem(uutId, systemId); } }
3e063f237a8a8efcabec8071fcbc3a21bfb4bda9
1,083
java
Java
org.eniware.edge/src/org/eniware/edge/backup/SimpleBackupResourceInfo.java
eniware-org/org.eniware.edge
67ef441bd72515147824c3e4fbb73264c52ae7e3
[ "Apache-2.0" ]
null
null
null
org.eniware.edge/src/org/eniware/edge/backup/SimpleBackupResourceInfo.java
eniware-org/org.eniware.edge
67ef441bd72515147824c3e4fbb73264c52ae7e3
[ "Apache-2.0" ]
null
null
null
org.eniware.edge/src/org/eniware/edge/backup/SimpleBackupResourceInfo.java
eniware-org/org.eniware.edge
67ef441bd72515147824c3e4fbb73264c52ae7e3
[ "Apache-2.0" ]
1
2018-03-20T17:44:28.000Z
2018-03-20T17:44:28.000Z
20.433962
87
0.602955
2,638
/* ================================================================== * Eniware Open Source:Nikolai Manchev * Apache License 2.0 * ================================================================== */ package org.eniware.edge.backup; /** * Basic implementation of {@link BackupResourceInfo}. * * @version 1.0 * @since 1.46 */ public class SimpleBackupResourceInfo implements BackupResourceInfo { private final String providerKey; private final String name; private final String description; /** * Construct with values. * * @param providerKey * The provider key. * @param name * The name. * @param description * The description. */ public SimpleBackupResourceInfo(String providerKey, String name, String description) { super(); this.providerKey = providerKey; this.name = name; this.description = description; } @Override public String getProviderKey() { return providerKey; } @Override public String getName() { return name; } @Override public String getDescription() { return description; } }
3e063f7119299e41832c81121e6a83ba39a6fac6
2,626
java
Java
engine/src/main/java/com/arcadedb/compression/LZ4Compression.java
elegoff/arcadedb
7de1f4b1088ff4ea0680148126da6d2594bf57d0
[ "Apache-2.0" ]
null
null
null
engine/src/main/java/com/arcadedb/compression/LZ4Compression.java
elegoff/arcadedb
7de1f4b1088ff4ea0680148126da6d2594bf57d0
[ "Apache-2.0" ]
31
2021-11-29T04:18:59.000Z
2022-03-28T05:14:55.000Z
engine/src/main/java/com/arcadedb/compression/LZ4Compression.java
elegoff/arcadedb
7de1f4b1088ff4ea0680148126da6d2594bf57d0
[ "Apache-2.0" ]
null
null
null
37.514286
103
0.733054
2,639
/* * Copyright 2021 Arcade Data Ltd * * 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.arcadedb.compression; import com.arcadedb.database.Binary; import net.jpountz.lz4.LZ4Compressor; import net.jpountz.lz4.LZ4Factory; import net.jpountz.lz4.LZ4FastDecompressor; /** * Compression implementation that uses the popular LZ4 algorithm. */ public class LZ4Compression implements Compression { private static final byte[] EMPTY_BYTES = new byte[0]; private static final Binary EMPTY_BINARY = new Binary(EMPTY_BYTES); private final LZ4Factory factory; private final LZ4Compressor compressor; private final LZ4FastDecompressor decompressor; public LZ4Compression() { this.factory = LZ4Factory.fastestInstance(); this.compressor = factory.fastCompressor(); this.decompressor = factory.fastDecompressor(); } @Override public Binary compress(final Binary data) { final int decompressedLength = data.size() - data.position(); final int maxCompressedLength = compressor.maxCompressedLength(decompressedLength); final byte[] compressed = new byte[maxCompressedLength]; final int compressedLength = compressor .compress(data.getContent(), data.position(), data.size(), compressed, 0, maxCompressedLength); return new Binary(compressed, compressedLength); } @Override public Binary decompress(final Binary data, final int decompressedLength) { if (decompressedLength == 0) return EMPTY_BINARY; final int compressedLength = data.size() - data.position(); if (compressedLength == 0) return EMPTY_BINARY; final byte[] decompressed = new byte[decompressedLength]; decompressor.decompress(data.getContent(), data.position(), decompressed, 0, decompressedLength); return new Binary(decompressed); } }
3e064025094a2436ec7514e985ff5651c9436210
2,425
java
Java
org.openbel.editor.core/src/org/openbel/editor/core/record/LongColumn.java
OpenBEL/bel-editor
31ee70668cea6820b657e397d15c7f472d97e31b
[ "Apache-2.0" ]
1
2021-02-03T12:51:48.000Z
2021-02-03T12:51:48.000Z
org.openbel.editor.core/src/org/openbel/editor/core/record/LongColumn.java
OpenBEL/bel-editor
31ee70668cea6820b657e397d15c7f472d97e31b
[ "Apache-2.0" ]
null
null
null
org.openbel.editor.core/src/org/openbel/editor/core/record/LongColumn.java
OpenBEL/bel-editor
31ee70668cea6820b657e397d15c7f472d97e31b
[ "Apache-2.0" ]
1
2018-11-30T07:37:41.000Z
2018-11-30T07:37:41.000Z
26.075269
72
0.629278
2,640
/** * Copyright (c) 2012 Selventa. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributors: * Selventa - initial API and implementation */ package org.openbel.editor.core.record; import static java.lang.System.arraycopy; import static java.nio.ByteBuffer.allocate; import java.nio.ByteBuffer; /** * Represents a {@link Column} of type {@link Long} sized to 8 bytes. */ public class LongColumn extends Column<Long> { private static final LongColumn selfNonNull; private static final LongColumn selfNull; private static final byte space = 8; private static final byte[] nullValue; static { selfNonNull = new LongColumn(false); selfNull = new LongColumn(true); final ByteBuffer buffer = allocate(space); buffer.putLong(0); nullValue = buffer.array(); } /** * Creates a long column with a size of {@code 8} bytes. */ private LongColumn(boolean nullable) { super(space, nullable); } /** * Returns the {@link LongColumn non-null long column} singleton. * * @return {@link LongColumn non-null long column} */ public static LongColumn nonNullLongColumn() { return selfNonNull; } /** * Returns the {@link LongColumn nullable long column} singleton. * * @return {@link LongColumn nullable long column} */ public static LongColumn nullLongColumn() { return selfNull; } /** * {@inheritDoc} */ @Override protected Long decodeData(byte[] buffer) { final ByteBuffer bytebuf = allocate(size); // buffer is guaranteed non-null and proper length bytebuf.put(buffer); bytebuf.rewind(); return bytebuf.getLong(); } /** * {@inheritDoc} */ @Override protected byte[] encodeType(Long t) { final ByteBuffer buffer = allocate(size); // t is guaranteed non-null by superclass buffer.putLong(t); return buffer.array(); } /** * {@inheritDoc} */ @Override protected byte[] getNullValue() { final byte[] ret = new byte[size]; arraycopy(nullValue, 0, ret, 0, size); return ret; } }
3e06411eab05fba8fb4da83a9df7de9675ff6fb1
25,167
java
Java
src/main/java/com/sjhy/plugin/ui/MainSetting.java
gejun123456/EasyCode
d3b4d90e34e594fd27f1e882317f9242b0ca3917
[ "MIT" ]
null
null
null
src/main/java/com/sjhy/plugin/ui/MainSetting.java
gejun123456/EasyCode
d3b4d90e34e594fd27f1e882317f9242b0ca3917
[ "MIT" ]
null
null
null
src/main/java/com/sjhy/plugin/ui/MainSetting.java
gejun123456/EasyCode
d3b4d90e34e594fd27f1e882317f9242b0ca3917
[ "MIT" ]
null
null
null
37.562687
154
0.582628
2,641
package com.sjhy.plugin.ui; import a.f.R; import cn.hutool.core.io.file.FileReader; import cn.hutool.core.io.file.FileWriter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.intellij.icons.AllIcons; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.UnnamedConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.NonEmptyInputValidator; import com.intellij.openapi.ui.ex.MultiLineLabel; import com.intellij.ui.components.JBTextField; import com.intellij.util.ExceptionUtil; import com.sjhy.plugin.config.Settings; import com.sjhy.plugin.constants.MsgValue; import com.sjhy.plugin.constants.StrState; import com.sjhy.plugin.entity.*; import com.sjhy.plugin.tool.*; import com.sjhy.plugin.ui.base.ImOrExportWayConfirmPanel; import com.sjhy.plugin.ui.base.Item; import com.sjhy.plugin.ui.base.ListCheckboxPanel; import com.sjhy.plugin.ui.base.ListRadioPanel; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.util.List; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 主设置面板 * * @author makejava * @version 1.2.5 * @since 2018/07/17 13:10 */ public class MainSetting implements Configurable, Configurable.Composite { /** * 主面板 */ private JPanel mainPanel; /** * 作者编辑框 */ private JTextField authorTextField; /** * 重置默认设置按钮 */ private JButton resetBtn; /** * 模板导入按钮 */ private JButton importBtn; /** * 模板导出按钮 */ private JButton exportBtn; /** * 当前版本号 */ private JLabel versionLabel; /** * 同步地址,默认 */ private JTextField syncHost; /** * 重置列表 */ private List<Configurable> resetList; /** * 需要保存的列表 */ private List<Configurable> saveList; /** * 所有列表 */ private List<Configurable> allList; /** * 设置对象 */ private Settings settings = Settings.getInstance(); /** * 默认构造方法 */ public MainSetting() { // 获取当前项目 Project project = ProjectUtils.getCurrProject(); init(); //初始化事件 Settings settings = Settings.getInstance(); //重置配置信息 resetBtn.addActionListener(e -> { if (MessageDialogUtils.yesNo(project, MsgValue.RESET_DEFAULT_SETTING_MSG)) { if (CollectionUtil.isEmpty(resetList)) { return; } // 初始化默认配置 settings.initDefault(); // 重置 resetList.forEach(UnnamedConfigurable::reset); if (CollectionUtil.isEmpty(saveList)) { return; } // 保存 saveList.forEach(configurable -> { try { configurable.apply(); } catch (ConfigurationException e1) { e1.printStackTrace(); } }); } }); // 模板导入事件 importBtn.addActionListener(e -> { // 创建两行一列的主面板 ImOrExportWayConfirmPanel importPanel = new ImOrExportWayConfirmPanel(); // 构建dialog DialogBuilder dialogBuilder = new DialogBuilder(project); dialogBuilder.setTitle(MsgValue.TITLE_INFO); dialogBuilder.setCenterPanel(importPanel); dialogBuilder.addActionDescriptor(dialogWrapper -> new AbstractAction("OK") { @Override public void actionPerformed(ActionEvent e) { final String importWay = importPanel.getSelected(); final String importValue = importPanel.getValue(); if (importOrExportWayError(project, "导入", importWay, importValue)) { return; } // 关闭并退出 switch (importWay) { case ImOrExportWayConfirmPanel.WAY_TOKEN: tokenImport(importValue); break; case ImOrExportWayConfirmPanel.WAY_LOCAL: localImport(importValue); break; default: break; } dialogWrapper.close(DialogWrapper.OK_EXIT_CODE); } }); dialogBuilder.show(); }); // 模板导出事件 exportBtn.addActionListener(e -> { // 创建一行四列的主面板 JPanel mainPanel = new JPanel(new GridLayout(1, 4)); // Type Mapper ListCheckboxPanel typeMapperPanel = new ListCheckboxPanel("Type Mapper", settings.getTypeMapperGroupMap().keySet()); mainPanel.add(typeMapperPanel); // Template ListCheckboxPanel templatePanel = new ListCheckboxPanel("Template", settings.getTemplateGroupMap().keySet()); mainPanel.add(templatePanel); // Column Config ListCheckboxPanel columnConfigPanel = new ListCheckboxPanel("Column Config", settings.getColumnConfigGroupMap().keySet()); mainPanel.add(columnConfigPanel); // GlobalConfig ListCheckboxPanel globalConfigPanel = new ListCheckboxPanel("Global Config", settings.getGlobalConfigGroupMap().keySet()); mainPanel.add(globalConfigPanel); // 创建导出方式主面板 ImOrExportWayConfirmPanel exportPanel = new ImOrExportWayConfirmPanel(false); JPanel centerPanel = new JPanel(new BorderLayout(10, 10)); centerPanel.add(mainPanel, BorderLayout.CENTER); centerPanel.add(exportPanel, BorderLayout.SOUTH); // 构建dialog DialogBuilder dialogBuilder = new DialogBuilder(project); dialogBuilder.setTitle(MsgValue.TITLE_INFO); dialogBuilder.setNorthPanel(new MultiLineLabel("请选择要导出的配置分组:")); dialogBuilder.setCenterPanel(centerPanel); dialogBuilder.addActionDescriptor(dialogWrapper -> new AbstractAction("OK") { @Override public void actionPerformed(ActionEvent e) { if (!MainSetting.this.isSelected(typeMapperPanel, templatePanel, columnConfigPanel, globalConfigPanel)) { Messages.showWarningDialog("至少选择一个模板组!", MsgValue.TITLE_INFO); return; } final String selected = exportPanel.getSelected(); final String text = exportPanel.getValue(); if (importOrExportWayError(project, "导出", selected, text)) { return; } // 打包数据 Map<String, Object> param = new HashMap<>(4); Map<String, TypeMapperGroup> typeMapper = new LinkedHashMap<>(); for (String selectedItem : typeMapperPanel.getSelectedItems()) { typeMapper.put(selectedItem, settings.getTypeMapperGroupMap().get(selectedItem)); } param.put(StrState.TYPE_MAPPER, typeMapper); Map<String, TemplateGroup> template = new LinkedHashMap<>(); for (String selectedItem : templatePanel.getSelectedItems()) { template.put(selectedItem, settings.getTemplateGroupMap().get(selectedItem)); } param.put(StrState.TEMPLATE, template); Map<String, ColumnConfigGroup> columnConfig = new LinkedHashMap<>(); for (String selectedItem : columnConfigPanel.getSelectedItems()) { columnConfig.put(selectedItem, settings.getColumnConfigGroupMap().get(selectedItem)); } param.put(StrState.COLUMN_CONFIG, columnConfig); Map<String, GlobalConfigGroup> globalConfig = new LinkedHashMap<>(); for (String selectedItem : globalConfigPanel.getSelectedItems()) { globalConfig.put(selectedItem, settings.getGlobalConfigGroupMap().get(selectedItem)); } param.put(StrState.GLOBAL_CONFIG, globalConfig); // 关闭并退出 dialogWrapper.close(DialogWrapper.OK_EXIT_CODE); switch (selected) { case ImOrExportWayConfirmPanel.WAY_TOKEN: tokenExport(project, param); break; case ImOrExportWayConfirmPanel.WAY_LOCAL: localExport(project, param, text); break; default: break; } } }); dialogBuilder.show(); }); } private boolean importOrExportWayError(Project project, String action, String way, String value) { // 导入导出方式错误检查 if (StringUtils.isEmpty(way)) { Messages.showWarningDialog(project, String.format("请选择%s方式", action), MsgValue.TITLE_INFO); return true; } else if (way.equals(ImOrExportWayConfirmPanel.WAY_LOCAL)&&StringUtils.isEmpty(value)) { Messages.showWarningDialog(project, String.format("请填写%s", "Token".equals(way) ? "Token" : "本地路径"), MsgValue.TITLE_INFO); return true; } else if(way.equals(ImOrExportWayConfirmPanel.WAY_TOKEN)&&action.equals("导入")&& StringUtils.isEmpty(value)){ Messages.showWarningDialog(project, "请填写token", MsgValue.TITLE_INFO); return true; } return false; } /** * 网络Token导入 * * @param token */ private void tokenImport(String token) { if (token == null) { return; } String url = String.format("%s/template?token=%s", settings.getSyncHost(), token); String result = HttpUtils.get(url); if (result == null) { return; } dataImport(result); } /** * 本地导入 * * @param local */ private void localImport(String local) { File localGroup = new File(local); ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> param = new HashMap<>(); Map<String, TypeMapperGroup> typeMapper = new LinkedHashMap<>(); param.put(StrState.TYPE_MAPPER, typeMapper); final File typeMapperFile = new File(local + File.separatorChar + StrState.TYPE_MAPPER + ".json"); if (typeMapperFile.exists()) { try { String content = new FileReader(typeMapperFile).readString().replace("\r", ""); final TypeMapperGroup typeMapperGroup = objectMapper.readValue(content, TypeMapperGroup.class); typeMapper.put(typeMapperGroup.getName(), typeMapperGroup); } catch (IOException e) { e.printStackTrace(); } } Map<String, ColumnConfigGroup> columnConfig = new LinkedHashMap<>(); param.put(StrState.COLUMN_CONFIG, columnConfig); final File columnConfigFile = new File(local + File.separatorChar + StrState.COLUMN_CONFIG + ".json"); if (columnConfigFile.exists()) { try { String content = new FileReader(columnConfigFile).readString().replace("\r", ""); final ColumnConfigGroup columnConfigGroup = objectMapper.readValue(content, ColumnConfigGroup.class); columnConfig.put(columnConfigGroup.getName(), columnConfigGroup); } catch (IOException e) { e.printStackTrace(); } } Map<String, TemplateGroup> template = new LinkedHashMap<>(); param.put(StrState.TEMPLATE, template); final String templateDirectories = local + File.separatorChar + StrState.TEMPLATE; final File templateDirectoriesFile = new File(templateDirectories); if (templateDirectoriesFile.exists()) { final TemplateGroup templateGroup = (TemplateGroup) readConfig(templateDirectoriesFile, TemplateGroup.class, f -> { Template t = new Template(); final String name = f.getName(); t.setName(name.substring(0, name.indexOf(".vm"))); t.setCode(new FileReader(f).readString().replace("\r", "")); return t; }); templateGroup.setName(localGroup.getName()); if (!templateGroup.getElementList().isEmpty()) { template.put(templateGroup.getName(), templateGroup); } } Map<String, GlobalConfigGroup> globalConfig = new LinkedHashMap<>(); param.put(StrState.GLOBAL_CONFIG, globalConfig); final String globalConfigDirectories = local + File.separatorChar + StrState.GLOBAL_CONFIG; final File globalConfigDirectoriesFile = new File(globalConfigDirectories); if (globalConfigDirectoriesFile.exists()) { final GlobalConfigGroup globalConfigGroup = (GlobalConfigGroup) readConfig(globalConfigDirectoriesFile, GlobalConfigGroup.class, f -> { final GlobalConfig config = new GlobalConfig(); final String name = f.getName(); config.setName(name.substring(0, name.indexOf(".vm"))); config.setValue(new FileReader(f).readString().replace("\r", "")); return config; }); globalConfigGroup.setName(localGroup.getName()); if (!globalConfigGroup.getElementList().isEmpty()) { globalConfig.put(globalConfigGroup.getName(), globalConfigGroup); } } try { dataImport(objectMapper.writeValueAsString(param)); } catch (JsonProcessingException e) { e.printStackTrace(); } } private <T> AbstractGroup<T> readConfig(File directories, Class<? extends AbstractGroup<T>> clazz, Function<File, T> supplier) { final AbstractGroup<T> group; try { group = clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(clazz.getName() + "new instance error!"); } List<T> collect = Arrays.stream(directories.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".vm"); } })).map(supplier).collect(Collectors.toList()); group.setElementList(collect); return group; } private void dataImport(String result) { // 解析数据 ObjectMapper objectMapper = new ObjectMapper(); try { JsonNode jsonNode = objectMapper.readTree(result); if (jsonNode == null) { return; } // 配置覆盖 coverConfig(jsonNode, StrState.TYPE_MAPPER, TypeMapperGroup.class, settings.getTypeMapperGroupMap()); coverConfig(jsonNode, StrState.TEMPLATE, TemplateGroup.class, settings.getTemplateGroupMap()); coverConfig(jsonNode, StrState.COLUMN_CONFIG, ColumnConfigGroup.class, settings.getColumnConfigGroupMap()); coverConfig(jsonNode, StrState.GLOBAL_CONFIG, GlobalConfigGroup.class, settings.getGlobalConfigGroupMap()); // 重置配置 allList.forEach(UnnamedConfigurable::reset); if (CollectionUtil.isEmpty(saveList)) { return; } // 保存 allList.forEach(configurable -> { try { configurable.apply(); } catch (ConfigurationException e1) { e1.printStackTrace(); } }); // 覆盖提示 Messages.showInfoMessage("导入完成", MsgValue.TITLE_INFO); } catch (IOException e1) { ExceptionUtil.rethrow(e1); } } /** * Token导出 * * @param project * @param param */ private void tokenExport(Project project, Map<String, Object> param) { // 上传数据 String result = HttpUtils.postJson(settings.getSyncHost() + "/template", param); if (result != null) { // 提取token String token = "error"; if (result.contains("token")) { int startLocation = result.indexOf("token") + 6; token = result.substring(startLocation, result.indexOf(",", startLocation)); } // 显示token Messages.showInputDialog(project, result, MsgValue.TITLE_INFO, AllIcons.General.InformationDialog, token, new NonEmptyInputValidator()); } } /** * 本地导出 * * @param project * @param local * @param param */ private void localExport(Project project, Map<String, Object> param, String local) { // 导出文件夹结构 // local // |-- Default // |-- typeMapper.json // |-- columnConfig.json // |-- globalConfig // |-- init.vm // |-- template // |-- entity.java.vm ObjectMapper objectMapper = new ObjectMapper(); Map<String, TypeMapperGroup> typeMapper = (LinkedHashMap<String, TypeMapperGroup>) param.get(StrState.TYPE_MAPPER); for (Map.Entry<String, TypeMapperGroup> entry : typeMapper.entrySet()) { final TypeMapperGroup typeMapperGroup = entry.getValue(); final String name = typeMapperGroup.getName(); final String groupFileName = local + File.separatorChar + name + File.separatorChar + StrState.TYPE_MAPPER + ".json"; try { final String string = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(typeMapperGroup); FileWriter writer = new FileWriter(groupFileName); writer.write(string); } catch (JsonProcessingException e) { e.printStackTrace(); } } Map<String, ColumnConfigGroup> columnConfig = (LinkedHashMap<String, ColumnConfigGroup>) param.get(StrState.COLUMN_CONFIG); for (Map.Entry<String, ColumnConfigGroup> entry : columnConfig.entrySet()) { final ColumnConfigGroup columnConfigGroup = entry.getValue(); final String name = columnConfigGroup.getName(); final String groupFileName = local + File.separatorChar + name + File.separatorChar + StrState.COLUMN_CONFIG + ".json"; try { final String string = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(columnConfigGroup); FileWriter writer = new FileWriter(groupFileName); writer.write(string); } catch (JsonProcessingException e) { e.printStackTrace(); } } Map<String, TemplateGroup> template = (Map<String, TemplateGroup>) param.get(StrState.TEMPLATE); for (Map.Entry<String, TemplateGroup> entry : template.entrySet()) { final TemplateGroup templateGroup = entry.getValue(); final String name = templateGroup.getName(); final String templateGroupDirectories = local + File.separatorChar + name + File.separatorChar + StrState.TEMPLATE; for (Template t : templateGroup.getElementList()) { final String fileName = templateGroupDirectories + File.separatorChar + t.getName() + ".vm"; FileWriter writer = new FileWriter(fileName); writer.write(t.getCode()); } } Map<String, GlobalConfigGroup> globalConfig = (Map<String, GlobalConfigGroup>) param.get(StrState.GLOBAL_CONFIG); for (Map.Entry<String, GlobalConfigGroup> entry : globalConfig.entrySet()) { final GlobalConfigGroup globalConfigGroup = entry.getValue(); final String name = globalConfigGroup.getName(); final String globalConfigGroupDirectories = local + File.separatorChar + name + File.separatorChar + StrState.GLOBAL_CONFIG; for (GlobalConfig config : globalConfigGroup.getElementList()) { final String fileName = globalConfigGroupDirectories + File.separatorChar + config.getName() + ".vm"; FileWriter writer = new FileWriter(fileName); writer.write(config.getValue()); } } Messages.showInfoMessage("导出完成,请到选定的本地文件夹中查看!", MsgValue.TITLE_INFO); } /** * 判断是否选中 * * @param checkboxPanels 复选框面板 * @return 是否选中 */ private boolean isSelected(@NotNull ListCheckboxPanel... checkboxPanels) { for (ListCheckboxPanel checkboxPanel : checkboxPanels) { if (!CollectionUtil.isEmpty(checkboxPanel.getSelectedItems())) { return true; } } return false; } /** * 覆盖配置 * * @param jsonNode json节点对象 * @param name 配置组名称 * @param cls 配置组类 * @param srcGroup 源分组 */ private <T extends AbstractGroup> void coverConfig(@NotNull JsonNode jsonNode, @NotNull String name, Class<T> cls, @NotNull Map<String, T> srcGroup) { ObjectMapper objectMapper = new ObjectMapper(); if (!jsonNode.has(name)) { return; } try { JsonNode node = jsonNode.get(name); if (node.size() == 0) { return; } // 覆盖配置 Iterator<String> names = node.fieldNames(); while (names.hasNext()) { String key = names.next(); String value = node.get(key).toString(); T group = objectMapper.readValue(value, cls); if (srcGroup.containsKey(key)) { if (!MessageDialogUtils.yesNo(String.format("是否覆盖%s配置中的%s分组?", name, key))) { continue; } } srcGroup.put(key, group); } } catch (IOException e) { Messages.showWarningDialog("JSON解析错误!", MsgValue.TITLE_INFO); ExceptionUtil.rethrow(e); } } /** * 初始化方法 */ private void init() { //初始化数据 versionLabel.setText(settings.getVersion()); authorTextField.setText(settings.getAuthor()); syncHost.setText(settings.getSyncHost()); } /** * 设置显示名称 * * @return 显示名称 */ @Nls @Override public String getDisplayName() { return "Easy Code"; } /** * Returns the topic in the help file which is shown when help for the configurable is requested. * * @return the help topic, or {@code null} if no help is available */ @Nullable @Override public String getHelpTopic() { return getDisplayName(); } /** * 更多配置 * * @return 配置选项 */ @NotNull @Override public Configurable[] getConfigurables() { Configurable[] result = new Configurable[4]; result[0] = new TypeMapperSetting(settings); result[1] = new TemplateSettingPanel(); result[2] = new TableSettingPanel(); result[3] = new GlobalConfigSettingPanel(); // 所有列表 allList = new ArrayList<>(); allList.add(result[0]); allList.add(result[1]); allList.add(result[2]); allList.add(result[3]); // 需要重置的列表 resetList = new ArrayList<>(); resetList.add(result[0]); resetList.add(result[1]); resetList.add(result[3]); // 不需要重置的列表 saveList = new ArrayList<>(); saveList.add(this); saveList.add(result[2]); return result; } /** * 获取主面板信息 * * @return 主面板 */ @Nullable @Override public JComponent createComponent() { return mainPanel; } /** * 判断是否修改 * * @return 是否修改 */ @Override public boolean isModified() { return !settings.getAuthor().equals(authorTextField.getText()) || !settings.getSyncHost().equals(syncHost.getText()); } /** * 应用修改 */ @Override public void apply() { //保存数据 settings.setAuthor(authorTextField.getText()); settings.setSyncHost(syncHost.getText()); } /** * 重置 */ @Override public void reset() { init(); } }
3e06419801d331406847686f4a6d1a714b6ea67b
244
java
Java
cc-execute-e2e/src/main/java/edu/cmu/cs/mvelezce/e2e/execute/time/gt/package-info.java
miguelvelezmj25/comprx
0bde9a45f1cc5d72d2661f00033d1538b043aa71
[ "MIT" ]
null
null
null
cc-execute-e2e/src/main/java/edu/cmu/cs/mvelezce/e2e/execute/time/gt/package-info.java
miguelvelezmj25/comprx
0bde9a45f1cc5d72d2661f00033d1538b043aa71
[ "MIT" ]
null
null
null
cc-execute-e2e/src/main/java/edu/cmu/cs/mvelezce/e2e/execute/time/gt/package-info.java
miguelvelezmj25/comprx
0bde9a45f1cc5d72d2661f00033d1538b043aa71
[ "MIT" ]
null
null
null
30.5
74
0.881148
2,642
@ParametersAreNonnullByDefault @ReturnTypesAreNonNullByDefault package edu.cmu.cs.mvelezce.e2e.execute.time.gt; import com.mijecu25.meme.utils.annotations.ReturnTypesAreNonNullByDefault; import javax.annotation.ParametersAreNonnullByDefault;
3e0641d93ba6959b32cc99e932429c154bd40def
1,202
java
Java
zhq-websocket-deploy/src/test/java/cn/zhuhongqing/websocket/WebSocketServer.java
legend0702/zhq
dd8706069cd65ae554d26fc782d8e3199aa1d44b
[ "Apache-2.0" ]
3
2016-05-28T10:52:28.000Z
2017-12-22T07:31:24.000Z
zhq-websocket-deploy/src/test/java/cn/zhuhongqing/websocket/WebSocketServer.java
legend0702/zhq
dd8706069cd65ae554d26fc782d8e3199aa1d44b
[ "Apache-2.0" ]
null
null
null
zhq-websocket-deploy/src/test/java/cn/zhuhongqing/websocket/WebSocketServer.java
legend0702/zhq
dd8706069cd65ae554d26fc782d8e3199aa1d44b
[ "Apache-2.0" ]
1
2017-12-22T07:31:41.000Z
2017-12-22T07:31:41.000Z
30.05
75
0.735441
2,643
package cn.zhuhongqing.websocket; import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.SendHandler; import javax.websocket.SendResult; import javax.websocket.Session; public class WebSocketServer extends Endpoint { public void onClose(Session session, CloseReason closeReason) { System.out.println("Connection closed: " + session.getId() + " CloseReason:" + closeReason.getReasonPhrase()); } public void onError(Session session, Throwable throwable) { System.out.println("Connection error: " + session.getId()); throwable.printStackTrace(); } public void onOpen(final Session session, EndpointConfig endpointConfig) { session.getAsyncRemote().sendText( "Client Success!Your id is: " + session.getId()); session.addMessageHandler(new MessageHandler.Whole<String>() { @Override public void onMessage(String message) { session.getAsyncRemote().sendObject(message, new SendHandler() { @Override public void onResult(SendResult result) { System.out.println(session.getId() + ":" + result.isOK()); } }); } }); } }
3e0641f7537f76d06867c233ce9095ce07590933
11,245
java
Java
phpunit-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/PharIo/namespaces/Manifest/classes/ManifestDocument.java
RuntimeConverter/PHPUnit-Java-Converted
0a036307ab56c8b787860ad25a74a17584218fda
[ "BSD-3-Clause" ]
1
2018-06-26T13:56:48.000Z
2018-06-26T13:56:48.000Z
phpunit-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/PharIo/namespaces/Manifest/classes/ManifestDocument.java
RuntimeConverter/PHPUnit-Java-Converted
0a036307ab56c8b787860ad25a74a17584218fda
[ "BSD-3-Clause" ]
null
null
null
phpunit-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/PharIo/namespaces/Manifest/classes/ManifestDocument.java
RuntimeConverter/PHPUnit-Java-Converted
0a036307ab56c8b787860ad25a74a17584218fda
[ "BSD-3-Clause" ]
null
null
null
43.585271
128
0.565407
2,644
package com.project.convertedCode.globalNamespace.namespaces.PharIo.namespaces.Manifest.classes; import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs; import com.runtimeconverter.runtime.classes.StaticBaseClass; import com.runtimeconverter.runtime.modules.standard.CRArrayF; import com.runtimeconverter.runtime.nativeClasses.dom.DOMDocument; import com.runtimeconverter.runtime.classes.RuntimeClassBase; import com.project.convertedCode.globalNamespace.namespaces.PharIo.namespaces.Manifest.classes.ContainsElement; import com.runtimeconverter.runtime.RuntimeEnv; import com.runtimeconverter.runtime.nativeClasses.dom.DOMElement; import com.runtimeconverter.runtime.ZVal; import com.runtimeconverter.runtime.reflection.ReflectionClassData; import com.runtimeconverter.runtime.annotations.ConvertedParameter; import com.runtimeconverter.runtime.arrays.ZPair; import com.project.convertedCode.globalNamespace.namespaces.PharIo.namespaces.Manifest.classes.BundlesElement; import com.project.convertedCode.globalNamespace.namespaces.PharIo.namespaces.Manifest.classes.CopyrightElement; import com.project.convertedCode.globalNamespace.NamespaceGlobal; import com.runtimeconverter.runtime.annotations.ConvertedMethod; import com.project.convertedCode.globalNamespace.namespaces.PharIo.namespaces.Manifest.classes.ManifestDocumentLoadingException; import com.project.convertedCode.globalNamespace.namespaces.PharIo.namespaces.Manifest.classes.RequiresElement; import com.runtimeconverter.runtime.modules.standard.other.function_file_get_contents; import com.project.convertedCode.globalNamespace.namespaces.PharIo.namespaces.Manifest.classes.ManifestDocumentException; import static com.runtimeconverter.runtime.ZVal.toObjectR; import static com.runtimeconverter.runtime.ZVal.assignParameter; /* Converted with The Runtime Converter (runtimeconverter.com) vendor/phar-io/manifest/src/xml/ManifestDocument.php */ public class ManifestDocument extends RuntimeClassBase { public Object dom = null; public ManifestDocument(RuntimeEnv env, Object... args) { super(env); if (this.getClass() == ManifestDocument.class) { this.__construct(env, args); } } @ConvertedMethod @ConvertedParameter(index = 0, name = "dom", typeHint = "DOMDocument") private Object __construct(RuntimeEnv env, Object... args) { Object dom = assignParameter(args, 0, null); env.callMethod(this, "ensureCorrectDocumentType", ManifestDocument.class, dom); toObjectR(this).accessProp(this, env).name("dom").set(dom); return null; } @ConvertedMethod public Object getContainsElement(RuntimeEnv env, Object... args) { return ZVal.assign( new ContainsElement( env, env.callMethod( this, "fetchElementByName", ManifestDocument.class, "contains"))); } @ConvertedMethod public Object getCopyrightElement(RuntimeEnv env, Object... args) { return ZVal.assign( new CopyrightElement( env, env.callMethod( this, "fetchElementByName", ManifestDocument.class, "copyright"))); } @ConvertedMethod public Object getRequiresElement(RuntimeEnv env, Object... args) { return ZVal.assign( new RequiresElement( env, env.callMethod( this, "fetchElementByName", ManifestDocument.class, "requires"))); } @ConvertedMethod public Object hasBundlesElement(RuntimeEnv env, Object... args) { return ZVal.assign( ZVal.strictEqualityCheck( toObjectR( env.callMethod( toObjectR(this) .accessProp(this, env) .name("dom") .value(), "getElementsByTagNameNS", ManifestDocument.class, CONST_XMLNS, "bundles")) .accessProp(this, env) .name("length") .value(), "===", 1)); } @ConvertedMethod public Object getBundlesElement(RuntimeEnv env, Object... args) { return ZVal.assign( new BundlesElement( env, env.callMethod( this, "fetchElementByName", ManifestDocument.class, "bundles"))); } @ConvertedMethod @ConvertedParameter(index = 0, name = "dom", typeHint = "DOMDocument") private Object ensureCorrectDocumentType(RuntimeEnv env, Object... args) { Object dom = assignParameter(args, 0, null); Object root = null; root = ZVal.assign(toObjectR(dom).accessProp(this, env).name("documentElement").value()); if (ZVal.toBool( ZVal.strictNotEqualityCheck( toObjectR(root).accessProp(this, env).name("localName").value(), "!==", "phar")) || ZVal.toBool( ZVal.strictNotEqualityCheck( toObjectR(root).accessProp(this, env).name("namespaceURI").value(), "!==", CONST_XMLNS))) { throw ZVal.getException( env, new ManifestDocumentException(env, "Not a phar.io manifest document")); } return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "elementName") private Object fetchElementByName(RuntimeEnv env, Object... args) { Object elementName = assignParameter(args, 0, null); Object element = null; element = env.callMethod( env.callMethod( toObjectR(this).accessProp(this, env).name("dom").value(), "getElementsByTagNameNS", ManifestDocument.class, CONST_XMLNS, elementName), "item", ManifestDocument.class, 0); if (!ZVal.isTrue(ZVal.checkInstanceType(element, DOMElement.class, "DOMElement"))) { throw ZVal.getException( env, new ManifestDocumentException( env, NamespaceGlobal.sprintf .env(env) .call("Element %s missing", elementName) .value())); } return ZVal.assign(element); } public static final Object CONST_XMLNS = "https://phar.io/xml/manifest/1.0"; public static final Object CONST_class = "PharIo\\Manifest\\ManifestDocument"; // Runtime Converter Internals // RuntimeStaticCompanion contains static methods // RequestStaticProperties contains static (per-request) properties // ReflectionClassData contains php reflection data used by the runtime library public static class RuntimeStaticCompanion extends StaticBaseClass { @ConvertedMethod @ConvertedParameter(index = 0, name = "filename") public Object fromFile(RuntimeEnv env, Object... args) { Object filename = assignParameter(args, 0, null); if (!NamespaceGlobal.file_exists.env(env).call(filename).getBool()) { throw ZVal.getException( env, new ManifestDocumentException( env, NamespaceGlobal.sprintf .env(env) .call("File \"%s\" not found", filename) .value())); } return ZVal.assign( runtimeStaticObject.fromString( env, function_file_get_contents.f.env(env).call(filename).value())); } @ConvertedMethod @ConvertedParameter(index = 0, name = "xmlString") public Object fromString(RuntimeEnv env, Object... args) { Object xmlString = assignParameter(args, 0, null); Object dom = null; Object prev = null; Object errors = null; prev = NamespaceGlobal.libxml_use_internal_errors.env(env).call(true).value(); NamespaceGlobal.libxml_clear_errors.env(env).call(); dom = new DOMDocument(env); env.callMethod(dom, "loadXML", ManifestDocument.class, xmlString); errors = NamespaceGlobal.libxml_get_errors.env(env).call().value(); NamespaceGlobal.libxml_use_internal_errors.env(env).call(prev); if (ZVal.strictNotEqualityCheck( CRArrayF.count.env(env).call(errors).value(), "!==", 0)) { throw ZVal.getException(env, new ManifestDocumentLoadingException(env, errors)); } return ZVal.assign( new com.project .convertedCode .globalNamespace .namespaces .PharIo .namespaces .Manifest .classes .ManifestDocument(env, dom)); } } public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion(); private static final ReflectionClassData runtimeConverterReflectionData = ReflectionClassData.builder() .setName("PharIo\\Manifest\\ManifestDocument") .setLookup(ManifestDocument.class, java.lang.invoke.MethodHandles.lookup()) .setLocalProperties("dom") .setFilename("vendor/phar-io/manifest/src/xml/ManifestDocument.php") .get(); @Override public ReflectionClassData getRuntimeConverterReflectionData() { return runtimeConverterReflectionData; } @Override public Object converterRuntimeCallExtended( RuntimeEnv env, String method, Class<?> caller, PassByReferenceArgs passByReferenceArgs, Object... args) { return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic( this, runtimeConverterReflectionData, env, method, caller, passByReferenceArgs, args); } }
3e0642f25c1973c9b5a0c47ee05a98ef4d872e04
734
java
Java
src/main/java/org/rdtif/zaxslackbot/userinterface/Extent.java
RDT-IF/zax-slack-bot
d644c25498a0b914b47b439b0f7cf36ac1969c36
[ "MIT" ]
null
null
null
src/main/java/org/rdtif/zaxslackbot/userinterface/Extent.java
RDT-IF/zax-slack-bot
d644c25498a0b914b47b439b0f7cf36ac1969c36
[ "MIT" ]
null
null
null
src/main/java/org/rdtif/zaxslackbot/userinterface/Extent.java
RDT-IF/zax-slack-bot
d644c25498a0b914b47b439b0f7cf36ac1969c36
[ "MIT" ]
null
null
null
19.837838
78
0.594005
2,645
package org.rdtif.zaxslackbot.userinterface; import java.util.Objects; public class Extent { private final int rows; private final int columns; public Extent(int rows, int columns) { this.rows = rows; this.columns = columns; } int getRows() { return rows; } int getColumns() { return columns; } @Override public final boolean equals(Object other) { if (other instanceof Extent) { Extent otherExtent = (Extent) other; return rows == otherExtent.rows && columns == otherExtent.columns; } return false; } @Override public final int hashCode() { return Objects.hash(rows, columns); } }
3e06431c86b121c150ca9dc225b3857c1f81b018
16,119
java
Java
angel-ps/core/src/main/java/com/tencent/angel/ps/impl/ParameterServer.java
ericzhang-cn/angel
d40f64e33c43411ae40eed71a58cb369889c6f44
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-08-25T02:17:39.000Z
2020-08-25T02:17:39.000Z
angel-ps/core/src/main/java/com/tencent/angel/ps/impl/ParameterServer.java
hashiot/angel
88c8d27dd7b6509c3042f8ea31be864ab3b63ee5
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
angel-ps/core/src/main/java/com/tencent/angel/ps/impl/ParameterServer.java
hashiot/angel
88c8d27dd7b6509c3042f8ea31be864ab3b63ee5
[ "Apache-2.0", "BSD-3-Clause" ]
1
2019-12-16T09:34:15.000Z
2019-12-16T09:34:15.000Z
30.93858
130
0.688442
2,646
/* * Tencent is pleased to support the open source community by making Angel available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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.tencent.angel.ps.impl; import com.google.protobuf.ServiceException; import com.tencent.angel.AngelDeployMode; import com.tencent.angel.RunningMode; import com.tencent.angel.common.AngelEnvironment; import com.tencent.angel.common.Location; import com.tencent.angel.conf.AngelConf; import com.tencent.angel.ipc.TConnection; import com.tencent.angel.ipc.TConnectionManager; import com.tencent.angel.master.MasterProtocol; import com.tencent.angel.protobuf.ProtobufUtil; import com.tencent.angel.protobuf.generated.MLProtos.MatrixStatus; import com.tencent.angel.protobuf.generated.MLProtos.PSAttemptIdProto; import com.tencent.angel.protobuf.generated.MLProtos.Pair; import com.tencent.angel.protobuf.generated.PSMasterServiceProtos.*; import com.tencent.angel.ps.PSAttemptId; import com.tencent.angel.ps.ParameterServerId; import com.tencent.angel.ps.impl.matrix.ServerMatrix; import com.tencent.angel.ps.matrix.transport.MatrixTransportServer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Parameter server,hold and manage individual parameters that divided by {@link com.tencent.angel.master.AngelApplicationMaster}. * * @see ServerMatrix * @see MatrixTransportServer * */ public class ParameterServer { private static final Log LOG = LogFactory.getLog(ParameterServer.class); private final Location masterLocation; private final Configuration conf; private volatile MasterProtocol masterProxy; private ParameterServerService psServerService; private MatrixTransportServer matrixTransportServer; private SnapshotManager snapshotManager; private final PSAttemptId attemptId; private final PSAttemptIdProto attemptIdProto; private final AtomicBoolean stopped; private final int attemptIndex; private ParameterServerState state; private Thread heartbeatThread; private MatrixPartitionManager matrixPartitionManager; private MatrixCommitter committer; private static final AtomicInteger runningWorkerGroupNum = new AtomicInteger(0); private static final AtomicInteger runningWorkerNum = new AtomicInteger(0); private static final AtomicInteger runningTaskNum = new AtomicInteger(0); public static int getRunningWorkerGroupNum() { return runningWorkerGroupNum.get(); } public static int getRunningWorkerNum() { return runningWorkerNum.get(); } public static int getRunningTaskNum() { return runningTaskNum.get(); } public static void setRunningWorkerGroupNum(int num) { runningWorkerGroupNum.set(num); } public static void setRunningWorkerNum(int num) { runningWorkerNum.set(num); } public static void setRunningTaskNum(int num) { runningTaskNum.set(num); } /** * Create a new Parameter server. * * @param serverIndex the server index * @param attemptIndex the attempt index * @param appMasterHost the app master host * @param appMasterPort the app master port * @param conf the conf */ public ParameterServer(int serverIndex, int attemptIndex, String appMasterHost, int appMasterPort, Configuration conf) { this.attemptId = new PSAttemptId(new ParameterServerId(serverIndex), attemptIndex); this.attemptIdProto = ProtobufUtil.convertToIdProto(attemptId); this.attemptIndex = attemptIndex; this.masterLocation = new Location(appMasterHost, appMasterPort); this.conf = conf; this.stopped = new AtomicBoolean(false); } /** * Gets matrix partition manager. * * @return the matrix partition manager */ public MatrixPartitionManager getMatrixPartitionManager() { return matrixPartitionManager; } public SnapshotManager getSnapshotManager() { return snapshotManager; } /** * Stop parameter server. * * @param exitCode the exit code */ public void stop(int exitCode) { LOG.info("stop ps rpcServer!"); if (psServerService != null) { psServerService.stop(); psServerService = null; } LOG.info("stop heartbeat thread!"); if (!stopped.getAndSet(true)) { if (heartbeatThread != null) { heartbeatThread.interrupt(); try { heartbeatThread.join(); } catch (InterruptedException ie) { LOG.warn("InterruptedException while stopping heartbeatThread."); } heartbeatThread = null; } if(matrixTransportServer != null) { try { matrixTransportServer.stop(); } catch (InterruptedException e) { LOG.warn("stop matrixTransportServer interrupted."); } matrixTransportServer = null; } if(snapshotManager != null) { snapshotManager.stop(); } exit(exitCode); } } private void exit(int code) { AngelDeployMode deployMode = PSContext.get().getDeployMode(); if(deployMode == AngelDeployMode.YARN) { System.exit(code); } } public static void main(String[] argv) { LOG.info("Starting Parameter Server"); int serverIndex = Integer.valueOf(System.getenv(AngelEnvironment.PARAMETERSERVER_ID.name())); String appMasterHost = System.getenv(AngelEnvironment.LISTEN_ADDR.name()); int appMasterPort = Integer.valueOf(System.getenv(AngelEnvironment.LISTEN_PORT.name())); int attemptIndex = Integer.valueOf(System.getenv(AngelEnvironment.PS_ATTEMPT_ID.name())); Configuration conf = new Configuration(); conf.addResource(AngelConf.ANGEL_JOB_CONF_FILE); String user = System.getenv(ApplicationConstants.Environment.USER.name()); UserGroupInformation.setConfiguration(conf); String runningMode = conf.get(AngelConf.ANGEL_RUNNING_MODE, AngelConf.DEFAULT_ANGEL_RUNNING_MODE); if(runningMode.equals(RunningMode.ANGEL_PS_WORKER.toString())){ LOG.debug("AngelEnvironment.TASK_NUMBER.name()=" + AngelEnvironment.TASK_NUMBER.name()); conf.set(AngelConf.ANGEL_TASK_ACTUAL_NUM, System.getenv(AngelEnvironment.TASK_NUMBER.name())); } final ParameterServer psServer = new ParameterServer(serverIndex, attemptIndex, appMasterHost, appMasterPort, conf); PSContext.get().setPs(psServer); try{ Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); UserGroupInformation psUGI = UserGroupInformation.createRemoteUser(System .getenv(ApplicationConstants.Environment.USER.toString())); // Add tokens to new user so that it may execute its task correctly. psUGI.addCredentials(credentials); psUGI.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { psServer.initialize(); psServer.start(); return null; } }); } catch (Throwable x) { LOG.fatal("Start PS failed ", x); psServer.failed(x.getMessage()); } LOG.info("Starting Parameter Server successfully."); } /** * Gets host address. * * @return the host address * @throws UnknownHostException */ public String getHostAddress() throws UnknownHostException { return psServerService.getHostAddress(); } /** * Gets port. * * @return the port */ public int getPort() { return psServerService.getPort(); } /** * Gets server id. * * @return the server id */ public ParameterServerId getServerId() { return attemptId.getParameterServerId(); } /** * Gets ps attempt id. * * @return the ps attempt id */ public PSAttemptId getPSAttemptId() { return attemptId; } /** * Gets master location. * * @return the master location */ public Location getMasterLocation() { return masterLocation; } /** * Gets conf. * * @return the conf */ public Configuration getConf() { return conf; } /** * Initialize. * * @throws IOException * @throws InstantiationException * @throws IllegalAccessException */ public void initialize() throws IOException, InstantiationException, IllegalAccessException { LOG.info("Initialize a parameter server"); matrixPartitionManager = new MatrixPartitionManager(); matrixPartitionManager.init(); committer = new MatrixCommitter(this); TConnection connection = TConnectionManager.getConnection(conf); try { masterProxy = connection.getMasterService(masterLocation.getIp(), masterLocation.getPort()); } catch (IOException e) { LOG.error("Connect to master failed! PS is to exit now!", e); stop(-1); } psServerService = new ParameterServerService(); psServerService.start(); matrixTransportServer = new MatrixTransportServer(getPort() + 1); snapshotManager = new SnapshotManager(attemptId); snapshotManager.init(); } private void startHeartbeat() { final int heartbeatInterval = conf.getInt(AngelConf.ANGEL_PS_HEARTBEAT_INTERVAL_MS, AngelConf.DEFAULT_ANGEL_PS_HEARTBEAT_INTERVAL_MS); LOG.info("Starting HeartbeatThread, interval is " + heartbeatInterval + " ms"); heartbeatThread = new Thread(new Runnable() { @Override public void run() { while (!stopped.get() && !Thread.currentThread().isInterrupted()) { try { Thread.sleep(heartbeatInterval); } catch (InterruptedException e) { if (!stopped.get()) { LOG.warn("Allocated thread interrupted. Returning."); } return; } try { if(!stopped.get()) { heartbeat(); } } catch (YarnRuntimeException e) { LOG.error("Error communicating with AM: " + e.getMessage(), e); return; } catch (Exception e) { LOG.error("ERROR IN CONTACTING RM. ", e); } } } }); heartbeatThread.setName("heartbeatThread"); heartbeatThread.start(); } private void register() throws IOException { LOG.info("Registering to AppMaster " + masterLocation); PSRegisterRequest.Builder regBuilder = PSRegisterRequest.newBuilder(); regBuilder.setPsAttemptId(attemptIdProto); try { Location location = new Location(InetAddress.getLocalHost().getHostAddress(), psServerService.getPort()); regBuilder.setLocation(ProtobufUtil.convertLocation(location)); } catch (UnknownHostException eop) { LOG.error("UnknownHostException: " + eop); throw new IOException(eop); } try { masterProxy.psRegister(null, regBuilder.build()); LOG.info("Register to AppMaster successfully"); } catch (ServiceException e) { // to exit LOG.error("ps register to AppMaster failed: ", e); stop(-1); } } private List<MatrixReport> buildMatrixReports() { MatrixReport.Builder builder = MatrixReport.newBuilder(); List<MatrixReport> ret = new ArrayList<MatrixReport>(); ConcurrentHashMap<Integer, ServerMatrix> matrixIdMap = matrixPartitionManager.getMatrixIdMap(); for (Entry<Integer, ServerMatrix> matrixEntry : matrixIdMap.entrySet()) { ret.add(builder.setMatrixId(matrixEntry.getKey()) .setMatrixName(matrixEntry.getValue().getName()).setStatus(MatrixStatus.M_OK).build()); } return ret; } private void heartbeat() { PSReportRequest.Builder builder = PSReportRequest.newBuilder(); builder.setPsAttemptId(attemptIdProto); Pair.Builder pairBuilder = Pair.newBuilder(); pairBuilder.setKey("key"); pairBuilder.setValue("value"); builder.addMetrics(pairBuilder.build()); builder.addAllMatrixReports(buildMatrixReports()); PSReportResponse ret = null; try { ret = masterProxy.psReport(null, builder.build()); LOG.debug("heartbeat response " + ret); switch (ret.getPsCommand()) { case PSCOMMAND_REGISTER: try { register(); } catch (Exception x) { LOG.error("register failed: ", x); stop(-1); } break; case PSCOMMAND_SHUTDOWN: LOG.error("shutdown command come from appmaster, exit now!!"); stop(-1); break; case PSCOMMAND_COMMIT: LOG.info("received ps commit command, ps is committing now!"); LOG.info("to stop taskSnapshotsThread."); snapshotManager.stop(); committer.commit(ret.getNeedCommitMatrixIdsList()); break; default: break; } syncMatrixInfo(ret.getNeedCreateMatrixIdsList(), ret.getNeedReleaseMatrixIdsList()); } catch (ServiceException e) { LOG.error("send heartbeat to appmaster failed ", e); stop(-1); } } private void syncMatrixInfo(List<MatrixPartition> needCreateMatrixesList, List<Integer> needReleaseMatrixesList) { try { matrixPartitionManager.addMatrixPartitions(needCreateMatrixesList); } catch (IOException e) { LOG.fatal("init matrix failed, exit now ", e); stop(-1); } PSContext.get().getSnapshotManager().processRecovery(); matrixPartitionManager.removeMatrices(needReleaseMatrixesList); } /** * Start parameter server services. * * @throws IOException the io exception */ public void start() throws IOException { matrixTransportServer.start(); register(); startHeartbeat(); snapshotManager.start(); } /** * Done, will notify master and exit */ public void done() { try { masterProxy.psDone(null, PSDoneRequest.newBuilder().setPsAttemptId(attemptIdProto).build()); LOG.info("send done message to master success"); } catch (ServiceException e) { LOG.error("send done message to master failed ", e); } finally { stop(0); } } /** * Failed, will notify master and exit * * @param errorLog the error log */ public void failed(String errorLog) { try { masterProxy.psError(null, PSErrorRequest.newBuilder().setPsAttemptId(attemptIdProto).setMsg(errorLog).build()); LOG.info("send failed message to master success"); } catch (ServiceException e) { LOG.error("send failed message to master failed ", e); } finally { stop(-1); } } /** * Gets state. * * @return the state */ public ParameterServerState getState() { return state; } /** * Gets parameter server service. * * @return the ps server service */ public ParameterServerService getPsService() { return psServerService; } /** * Gets rpc client to master * @return MasterProtocol rpc client to master */ public MasterProtocol getMaster() { return masterProxy; } public int getAttemptIndex() { return attemptIndex; } }
3e06434b33c0b8fe887f837e33203515737944d1
800
java
Java
src/main/java/com/modesteam/urutau/service/persistence/Persistence.java
ProjectUrutau/urutau
0938c7a564976f78777e3a3d302589e9b6f83deb
[ "Apache-2.0" ]
1
2017-02-16T01:21:10.000Z
2017-02-16T01:21:10.000Z
src/main/java/com/modesteam/urutau/service/persistence/Persistence.java
ProjectUrutau/urutau
0938c7a564976f78777e3a3d302589e9b6f83deb
[ "Apache-2.0" ]
21
2016-09-23T00:56:17.000Z
2017-07-01T01:28:37.000Z
src/main/java/com/modesteam/urutau/service/persistence/Persistence.java
ProjectUrutau/urutau
0938c7a564976f78777e3a3d302589e9b6f83deb
[ "Apache-2.0" ]
null
null
null
19.512195
61
0.64375
2,647
package com.modesteam.urutau.service.persistence; /** * All services of persistence should implement this contract * * @param <Entity> * related entity to service */ public interface Persistence<Entity> { /** * Persist an entity instance */ public void save(Entity entity); /** * Gets your instance of database to synchronize with it * * @param entity * edited, unmanaged bean */ public void reload(Entity entity); /** * Merge alterations for a database instance * * @param entity * should be a managed bean in JPA * @return managed entity */ public Entity update(Entity entity); /** * Delete database instance * * @param entity * Managed bean to be deleted */ public void delete(Entity entity); }
3e0643b5c5678fbf7d4109e1cacc5b48411e8466
3,000
java
Java
CBP/plugin/sub_app_module/fermat-cbp-plugin-sub-app-module-crypto-broker-community-bitdubai/src/main/java/com/bitdubai/fermat_cbp_plugin/layer/sub_app_module/crypto_broker_community/developer/bitdubai/version_1/structure/SelectableIdentity.java
guillermo20/fermat
f0a912adb66a439023ec4e70b821ba397e0f7760
[ "MIT" ]
3
2016-03-23T05:26:51.000Z
2016-03-24T14:33:05.000Z
CBP/plugin/sub_app_module/fermat-cbp-plugin-sub-app-module-crypto-broker-community-bitdubai/src/main/java/com/bitdubai/fermat_cbp_plugin/layer/sub_app_module/crypto_broker_community/developer/bitdubai/version_1/structure/SelectableIdentity.java
yalayn/fermat
f0a912adb66a439023ec4e70b821ba397e0f7760
[ "MIT" ]
17
2015-11-20T20:43:17.000Z
2016-07-25T20:35:49.000Z
CBP/plugin/sub_app_module/fermat-cbp-plugin-sub-app-module-crypto-broker-community-bitdubai/src/main/java/com/bitdubai/fermat_cbp_plugin/layer/sub_app_module/crypto_broker_community/developer/bitdubai/version_1/structure/SelectableIdentity.java
yalayn/fermat
f0a912adb66a439023ec4e70b821ba397e0f7760
[ "MIT" ]
26
2015-11-20T13:20:23.000Z
2022-03-11T07:50:06.000Z
34.918605
159
0.667333
2,648
package com.bitdubai.fermat_cbp_plugin.layer.sub_app_module.crypto_broker_community.developer.bitdubai.version_1.structure; import com.bitdubai.fermat_api.layer.all_definition.enums.Actors; import com.bitdubai.fermat_cbp_api.layer.identity.crypto_broker.interfaces.CryptoBrokerIdentity; import com.bitdubai.fermat_cbp_api.layer.identity.crypto_customer.interfaces.CryptoCustomerIdentity; import com.bitdubai.fermat_cbp_api.layer.sub_app_module.crypto_broker_community.exceptions.CantSelectIdentityException; import com.bitdubai.fermat_cbp_api.layer.sub_app_module.crypto_broker_community.interfaces.CryptoBrokerCommunitySelectableIdentity; import java.util.Arrays; /** * The class <code>com.bitdubai.fermat_cbp_plugin.layer.sub_app_module.crypto_broker_community.developer.bitdubai.version_1.structure.SelectableIdentity</code> * bla bla bla. * <p/> * Created by Leon Acosta - ([email protected]) on 21/12/2015. */ public final class SelectableIdentity implements CryptoBrokerCommunitySelectableIdentity { private final String alias ; private final String publicKey; private final Actors actorType; private final byte[] image ; public SelectableIdentity(final String alias , final String publicKey, final Actors actorType, final byte[] image ) { this.alias = alias ; this.publicKey = publicKey; this.actorType = actorType; this.image = image ; } public SelectableIdentity(final CryptoBrokerIdentity cryptoBrokerIdentity) { this.alias = cryptoBrokerIdentity.getAlias() ; this.publicKey = cryptoBrokerIdentity.getPublicKey() ; this.actorType = Actors.CBP_CRYPTO_BROKER ; this.image = cryptoBrokerIdentity.getProfileImage(); } public SelectableIdentity(final CryptoCustomerIdentity cryptoCustomerIdentity) { this.alias = cryptoCustomerIdentity.getAlias() ; this.publicKey = cryptoCustomerIdentity.getPublicKey() ; this.actorType = Actors.CBP_CRYPTO_CUSTOMER ; this.image = cryptoCustomerIdentity.getProfileImage(); } @Override public final String getAlias() { return alias; } @Override public final String getPublicKey() { return publicKey; } @Override public final byte[] getImage() { return image; } @Override public final Actors getActorType() { return actorType; } @Override public String toString() { return "SelectableIdentity{" + "alias='" + alias + '\'' + ", publicKey='" + publicKey + '\'' + ", actorType=" + actorType + ", profileImage=" + Arrays.toString(image) + '}'; } @Override public void select() throws CantSelectIdentityException { // TODO implement } }
3e0644debd267f8426a2acb3d1954416dc4e1048
145
java
Java
demoproj/src/main/java/com/ngtech/AbstractFactPattern/Tea.java
NeelamGhawate/Junit-mavenDemo
08dc705fe9418dea5dd3843f0b61d7afad902a46
[ "Apache-2.0" ]
null
null
null
demoproj/src/main/java/com/ngtech/AbstractFactPattern/Tea.java
NeelamGhawate/Junit-mavenDemo
08dc705fe9418dea5dd3843f0b61d7afad902a46
[ "Apache-2.0" ]
null
null
null
demoproj/src/main/java/com/ngtech/AbstractFactPattern/Tea.java
NeelamGhawate/Junit-mavenDemo
08dc705fe9418dea5dd3843f0b61d7afad902a46
[ "Apache-2.0" ]
null
null
null
14.5
39
0.737931
2,649
package com.ngtech.AbstractFactPattern; public class Tea extends HotDrinks{ public void drink() { System.out.println("drinking Tea"); } }
3e06454fca3373f991c19d187738bc29d31536bd
1,899
java
Java
src/main/java/com/pepipost/api/models/SortEnum.java
kanhaiya2012/sample-java
802601102db268bc0a596e712567f9c1aa7bd4a3
[ "MIT" ]
3
2018-09-22T14:57:24.000Z
2020-08-31T03:15:53.000Z
src/main/java/com/pepipost/api/models/SortEnum.java
kanhaiya2012/sample-java
802601102db268bc0a596e712567f9c1aa7bd4a3
[ "MIT" ]
10
2017-10-16T13:20:16.000Z
2022-01-25T08:50:26.000Z
src/main/java/com/pepipost/api/models/SortEnum.java
pepipost/pepipost-sdk-java
7806cb453cc9932c45bfaa7a4e060d1c24f45b46
[ "MIT" ]
9
2017-10-18T03:48:50.000Z
2020-11-22T22:26:48.000Z
29.671875
89
0.626119
2,650
/* * PepipostLib * * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). */ package com.pepipost.api.models; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; public enum SortEnum { ASC, //TODO: Write general description for this element DESC; //TODO: Write general description for this element private static TreeMap<String, SortEnum> valueMap = new TreeMap<String, SortEnum>(); private String value; static { ASC.value = "asc"; DESC.value = "desc"; valueMap.put("asc", ASC); valueMap.put("desc", DESC); } /** * Returns the enum member associated with the given string value * @return The enum member against the given string value */ @com.fasterxml.jackson.annotation.JsonCreator public static SortEnum fromString(String toConvert) { return valueMap.get(toConvert); } /** * Returns the string value associated with the enum member * @return The string value against enum member */ @com.fasterxml.jackson.annotation.JsonValue public String value() { return value; } /** * Get string representation of this enum */ @Override public String toString() { return value.toString(); } /** * Convert list of SortEnum values to list of string values * @param toConvert The list of SortEnum values to convert * @return List of representative string values */ public static List<String> toValue(List<SortEnum> toConvert) { if(toConvert == null) return null; List<String> convertedValues = new ArrayList<String>(); for (SortEnum enumValue : toConvert) { convertedValues.add(enumValue.value); } return convertedValues; } }
3e0645be94906ef031252e72c25933e59faa3244
253
java
Java
springboot-swagger/src/main/java/com/stone/swagger/entity/JsonResult.java
bravestonezou/Spring-Boot-Learn
7fb74c7c48973b165fb359c26ac6d298aebd9807
[ "Apache-2.0" ]
null
null
null
springboot-swagger/src/main/java/com/stone/swagger/entity/JsonResult.java
bravestonezou/Spring-Boot-Learn
7fb74c7c48973b165fb359c26ac6d298aebd9807
[ "Apache-2.0" ]
null
null
null
springboot-swagger/src/main/java/com/stone/swagger/entity/JsonResult.java
bravestonezou/Spring-Boot-Learn
7fb74c7c48973b165fb359c26ac6d298aebd9807
[ "Apache-2.0" ]
null
null
null
15.352941
35
0.689655
2,651
package com.stone.swagger.entity; import lombok.Data; /** * @author zou.shiyong * @Description * @date 2018/11/1 * @Email [email protected] */ @Data public class JsonResult { private String status = null; private Object result = null; }
3e064689fc2b68b95368b227dac8eb50f954881e
368
java
Java
auth-back/src/main/java/jp/bootware/authesample/infrastructure/auth/dto/Token.java
Xenuzever/authentication-sample
a1d4877b3034a3b26281226f8e7d29a80c8604af
[ "Apache-2.0" ]
null
null
null
auth-back/src/main/java/jp/bootware/authesample/infrastructure/auth/dto/Token.java
Xenuzever/authentication-sample
a1d4877b3034a3b26281226f8e7d29a80c8604af
[ "Apache-2.0" ]
null
null
null
auth-back/src/main/java/jp/bootware/authesample/infrastructure/auth/dto/Token.java
Xenuzever/authentication-sample
a1d4877b3034a3b26281226f8e7d29a80c8604af
[ "Apache-2.0" ]
1
2021-08-07T18:10:03.000Z
2021-08-07T18:10:03.000Z
17.52381
56
0.785326
2,652
package jp.bootware.authesample.infrastructure.auth.dto; import lombok.AllArgsConstructor; import lombok.Data; import java.time.LocalDateTime; @Data @AllArgsConstructor public class Token { private TokenType tokenType; private String tokenValue; private Long duration; private LocalDateTime expiryDate; public enum TokenType { ACCESS, REFRESH } }
3e06469c7208e4221015fdc4ddfeac02c6e8e720
415
java
Java
0.5.1.1/JFP-Framework-Core/src/main/java/org/zmsoft/jfp/framework/support/ISSMSGatewaySupport.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
null
null
null
0.5.1.1/JFP-Framework-Core/src/main/java/org/zmsoft/jfp/framework/support/ISSMSGatewaySupport.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
null
null
null
0.5.1.1/JFP-Framework-Core/src/main/java/org/zmsoft/jfp/framework/support/ISSMSGatewaySupport.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
1
2022-03-16T01:57:07.000Z
2022-03-16T01:57:07.000Z
18.043478
60
0.701205
2,653
package org.zmsoft.jfp.framework.support; import org.zmsoft.jfp.framework.beans.common.RESTResultBean; import org.zmsoft.jfp.framework.beans.pub.SMSBean; /** * 短信发送网关 * @author zmsoft * @version 2.4.1 2015/9/9 * @version 2.1.3 2015/4/23 * @since 2.1.3 * */ public interface ISSMSGatewaySupport { /** * 短信发送 * @param message * @return */ public RESTResultBean<SMSBean> doSend(SMSBean message); }
3e0646ea5ee79379dcf139c3616c6472f11d0e22
289
java
Java
src/main/java/net/glowstone/net/message/play/player/TabCompleteMessage.java
Johni0702/Glowstone
c061facfed82710dff442f96e35138a41048b4c0
[ "MIT" ]
15
2016-07-10T10:24:39.000Z
2021-08-20T13:15:13.000Z
src/main/java/net/glowstone/net/message/play/player/TabCompleteMessage.java
Johni0702/Glowstone
c061facfed82710dff442f96e35138a41048b4c0
[ "MIT" ]
15
2016-06-27T21:07:09.000Z
2017-06-16T14:48:20.000Z
src/main/java/net/glowstone/net/message/play/player/TabCompleteMessage.java
Johni0702/Glowstone
c061facfed82710dff442f96e35138a41048b4c0
[ "MIT" ]
7
2017-02-22T21:12:31.000Z
2021-08-18T08:59:41.000Z
19.266667
58
0.795848
2,654
package net.glowstone.net.message.play.player; import com.flowpowered.networking.Message; import lombok.Data; import org.bukkit.util.BlockVector; @Data public final class TabCompleteMessage implements Message { private final String text; private final BlockVector location; }
3e064706b724cdadf557629da2888b30442ed4dd
1,954
java
Java
libBase/src/main/java/com/effective/android/base/intent/IntentData.java
hongqinghe/AndroidModularArchiteture
6fbf34ade359e1300c5beb6a1aa7fa7fc1a8b557
[ "MIT" ]
179
2018-01-22T13:08:34.000Z
2022-03-28T07:40:51.000Z
libBase/src/main/java/com/effective/android/base/intent/IntentData.java
hongqinghe/AndroidModularArchiteture
6fbf34ade359e1300c5beb6a1aa7fa7fc1a8b557
[ "MIT" ]
9
2019-10-21T02:58:19.000Z
2020-12-04T08:05:08.000Z
libBase/src/main/java/com/effective/android/base/intent/IntentData.java
hongqinghe/AndroidModularArchiteture
6fbf34ade359e1300c5beb6a1aa7fa7fc1a8b557
[ "MIT" ]
33
2019-01-09T10:12:31.000Z
2022-03-14T17:10:47.000Z
27.138889
83
0.587001
2,655
package com.effective.android.base.intent; import android.content.Intent; import android.os.Parcelable; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; public class IntentData { public static final String KEY = "IntentDataKey"; private Map<String, Parcelable> data; private Map<String, Parcelable[]> arrayData; private Map<String, ArrayList<Parcelable>> arrayListData; public long value; public IntentData() { data = new HashMap<>(); arrayData = new HashMap<>(); arrayListData = new HashMap<>(); value = System.currentTimeMillis(); } public void put(String key, Parcelable value) { data.put(key, value); } public void put(String key, Parcelable[] value) { arrayData.put(key, value); } public void put(String key, ArrayList<Parcelable> value) { arrayListData.put(key, value); } public boolean isContainParcelableData() { return !data.isEmpty() || !arrayData.isEmpty() || !arrayListData.isEmpty(); } public Intent make(Intent intent) { if (isContainParcelableData()) { intent.putExtra(KEY, value); } return intent; } public Intent reset(Intent intent) { if (!data.isEmpty()) { Set<String> keys = data.keySet(); for (String key : keys) { intent.putExtra(key, data.get(key)); } } if (!arrayData.isEmpty()) { Set<String> keys = arrayData.keySet(); for (String key : keys) { intent.putExtra(key, arrayData.get(key)); } } if (!arrayListData.isEmpty()) { Set<String> keys = arrayListData.keySet(); for (String key : keys) { intent.putParcelableArrayListExtra(key, arrayListData.get(key)); } } return intent; } }
3e0647e37da5a39e3fe400ebe13d81eb0bb3b9a6
551
java
Java
sandbox/src/main/java/ru/stqa/pft/sandbox/MyFirstProgram.java
IrinaTik/java_training
09d71c0bdbe718c2403a089bd0883ff801e995b3
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/ru/stqa/pft/sandbox/MyFirstProgram.java
IrinaTik/java_training
09d71c0bdbe718c2403a089bd0883ff801e995b3
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/ru/stqa/pft/sandbox/MyFirstProgram.java
IrinaTik/java_training
09d71c0bdbe718c2403a089bd0883ff801e995b3
[ "Apache-2.0" ]
null
null
null
22.958333
104
0.586207
2,656
package ru.stqa.pft.sandbox; public class MyFirstProgram { public static void main (String[] args) { hello("world"); hello("user"); hello("Akumo"); Square s = new Square(5); System.out.println("Площадь квадрата со стороной " + s.length + " = " + s.area()); Rectangle r = new Rectangle(4, 6); System.out.println("Площадь прямоугольника со сторонами " + r.a + " и " + r.b + " = " + r.area()); } public static void hello(String somebody) { System.out.println("Hello, " + somebody + "!"); } }
3e06484b6f082a6c7a53755d3e86270cd28bb1ce
1,226
java
Java
ast/ConstructorNode.java
Maldus512/FOOLCompiler
da1fbde841d48601182d820f00155b3936b1c8f3
[ "MIT" ]
2
2017-06-15T09:31:12.000Z
2019-02-25T10:49:51.000Z
ast/ConstructorNode.java
Maldus512/FOOLCompiler
da1fbde841d48601182d820f00155b3936b1c8f3
[ "MIT" ]
null
null
null
ast/ConstructorNode.java
Maldus512/FOOLCompiler
da1fbde841d48601182d820f00155b3936b1c8f3
[ "MIT" ]
null
null
null
18.861538
96
0.682708
2,657
package ast; import java.util.ArrayList; import util.Environment; import util.SemanticError; import util.STentry; import ast.types.*; public class ConstructorNode extends CallNode { public ConstructorNode(String i, ArrayList<Node> p) { super(i, p); } public ConstructorNode(String i, STentry e, ArrayList<Node> p, int nl) { super(i, e, p, nl); } public String getId() { return id; } // public ClassNode getClassRef() { // return classRef; // } @Override public String toPrint(String s) { String parstr = ""; for (Node par : parList) { parstr += par.toPrint(s + " "); } return s + "New:" + id + "\n" + parstr; } @Override public ArrayList<SemanticError> checkSemantics(Environment env) { ArrayList<SemanticError> res = new ArrayList<SemanticError>(); if (env.classTypeEnvGet(id) == null) { res.add(new SemanticError("Class " + id + " has not been defined; cannot be instantiated.")); return res; } res.addAll(super.checkSemantics(env)); return res; } //valore di ritorno non utilizzato @Override public TypeNode typeCheck(Environment env) { return super.typeCheck(env); } @Override public String codeGeneration() { return super.codeGeneration(); } }
3e06490f25923daa8af31fc6df23d866bac6f8fd
1,299
java
Java
src/main/java/net/kigawa/plugin/kyosaba/system/bingosystem/create/CreateCommand.java
kigawa8390/bingosystem
73ad058813ff38aace177fb138063b5ca4bb5210
[ "MIT" ]
null
null
null
src/main/java/net/kigawa/plugin/kyosaba/system/bingosystem/create/CreateCommand.java
kigawa8390/bingosystem
73ad058813ff38aace177fb138063b5ca4bb5210
[ "MIT" ]
null
null
null
src/main/java/net/kigawa/plugin/kyosaba/system/bingosystem/create/CreateCommand.java
kigawa8390/bingosystem
73ad058813ff38aace177fb138063b5ca4bb5210
[ "MIT" ]
null
null
null
39.363636
108
0.749038
2,658
package net.kigawa.plugin.kyosaba.system.bingosystem.create; import net.kigawa.plugin.kigawautillib.Command.SubCommand; import net.kigawa.plugin.kyosaba.system.bingosystem.BingoSystem; import net.kigawa.plugin.kyosaba.system.bingosystem.data.GameTemplate; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.List; public class CreateCommand extends net.kigawa.plugin.kigawautillib.Command.Command { BingoSystem plugin; GameTemplate template=new GameTemplate(); public CreateCommand(BingoSystem bingoSystem){ super(bingoSystem); plugin=bingoSystem; List<SubCommand> subCommands=super.getSubCommands(); subCommands.add(new CreateGate(plugin)); subCommands.add(new CreateGame(plugin,template)); subCommands.add(new AddStartLoc(plugin,template)); subCommands.add(new AddLotteryButton(plugin,template)); subCommands.add(new AddLotteryLoc(plugin,template)); subCommands.add(new AddPig(plugin,template)); subCommands.add(new AddSlot(plugin,template)); subCommands.add(new AddSlotList(plugin,template)); } @Override public boolean onMainCommand(CommandSender commandSender, Command command, String s, String[] strings) { return true; } }
3e0649563a531beb13e7b460eb828009a7c6fbae
4,047
java
Java
src/main/java/org/nebulae2us/stardust/db/domain/ColumnBuilder.java
nebulae2us/stardust
c54872fdc2c6e5257ea0da7d9884ea1f12aee889
[ "Apache-2.0" ]
null
null
null
src/main/java/org/nebulae2us/stardust/db/domain/ColumnBuilder.java
nebulae2us/stardust
c54872fdc2c6e5257ea0da7d9884ea1f12aee889
[ "Apache-2.0" ]
1
2022-01-21T23:08:59.000Z
2022-01-21T23:08:59.000Z
src/main/java/org/nebulae2us/stardust/db/domain/ColumnBuilder.java
nebulae2us/stardust
c54872fdc2c6e5257ea0da7d9884ea1f12aee889
[ "Apache-2.0" ]
null
null
null
27.161074
176
0.667161
2,659
package org.nebulae2us.stardust.db.domain; import java.util.*; import org.nebulae2us.electron.*; import org.nebulae2us.electron.util.*; import org.nebulae2us.stardust.internal.util.*; @Builder(destination=Column.class) public class ColumnBuilder<P> implements Wrappable<Column> { protected final Column $$$wrapped; protected final P $$$parentBuilder; public ColumnBuilder() { this.$$$wrapped = null; this.$$$parentBuilder = null; } public ColumnBuilder(P parentBuilder) { this.$$$wrapped = null; this.$$$parentBuilder = parentBuilder; } protected ColumnBuilder(Column wrapped) { if (wrapped == null) { throw new NullPointerException(); } this.$$$wrapped = wrapped; this.$$$parentBuilder = null; } public ColumnBuilder<P> storeTo(BuilderRepository repo, Object builderId) { repo.put(builderId, this); return this; } public Column getWrappedObject() { return this.$$$wrapped; } protected void verifyMutable() { if (this.$$$wrapped != null) { throw new IllegalStateException("Cannot mutate fields of immutable objects"); } } public P end() { return this.$$$parentBuilder; } public Column toColumn() { return new Converter(new DestinationClassResolverByAnnotation(), true, Builders.IGNORED_TYPES).convert(this).to(Column.class); } private String name; public String getName() { if (this.$$$wrapped != null && WrapHelper.valueNotSet(this.name, String.class)) { Object o = WrapHelper.getValue(this.$$$wrapped, Column.class, "name"); this.name = new WrapConverter(Builders.DESTINATION_CLASS_RESOLVER, Builders.IGNORED_TYPES).convert(o).to(String.class); } return name; } public void setName(String name) { verifyMutable(); this.name = name; } public ColumnBuilder<P> name(String name) { verifyMutable(); this.name = name; return this; } private TableBuilder<?> table; public TableBuilder<?> getTable() { if (this.$$$wrapped != null && WrapHelper.valueNotSet(this.table, TableBuilder.class)) { Object o = WrapHelper.getValue(this.$$$wrapped, Column.class, "table"); this.table = new WrapConverter(Builders.DESTINATION_CLASS_RESOLVER, Builders.IGNORED_TYPES).convert(o).to(TableBuilder.class); } return table; } public void setTable(TableBuilder<?> table) { verifyMutable(); this.table = table; } public ColumnBuilder<P> table(TableBuilder<?> table) { verifyMutable(); this.table = table; return this; } public ColumnBuilder<P> table$wrap(Table table) { verifyMutable(); this.table = new WrapConverter(Builders.DESTINATION_CLASS_RESOLVER, Builders.IGNORED_TYPES).convert(table).to(TableBuilder.class); return this; } public ColumnBuilder<P> table$restoreFrom(BuilderRepository repo, Object builderId) { verifyMutable(); Object restoredObject = repo.get(builderId); if (restoredObject == null) { if (repo.isSupportLazy()) { repo.addObjectStoredListener(builderId, new Procedure() { public void execute(Object... arguments) { ColumnBuilder.this.table = (TableBuilder<?>)arguments[0]; } }); } else { throw new IllegalStateException("Object does not exist with id " + builderId); } } else if (!(restoredObject instanceof TableBuilder)) { throw new IllegalStateException("Type mismatch for id: " + builderId + ". " + TableBuilder.class.getSimpleName() + " vs " + restoredObject.getClass().getSimpleName()); } else { this.table = (TableBuilder<?>)restoredObject; } return this; } public TableBuilder<? extends ColumnBuilder<P>> table$begin() { verifyMutable(); TableBuilder<ColumnBuilder<P>> result = new TableBuilder<ColumnBuilder<P>>(this); this.table = result; return result; } /* CUSTOM CODE ********************************* * * Put your own custom code below. These codes won't be discarded during generation. * */ }
3e0649c7a0807d822b482dfdf070457ef31e7b23
2,448
java
Java
openjdk11/test/hotspot/jtreg/vmTestbase/nsk/jdi/ExceptionRequest/_bounds_/filters001/TestDescription.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
test/hotspot/jtreg/vmTestbase/nsk/jdi/ExceptionRequest/_bounds_/filters001/TestDescription.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
test/hotspot/jtreg/vmTestbase/nsk/jdi/ExceptionRequest/_bounds_/filters001/TestDescription.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
40.8
84
0.727124
2,660
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * * @summary converted from VM Testbase nsk/jdi/ExceptionRequest/_bounds_/filters001. * VM Testbase keywords: [jpda, jdi] * VM Testbase readme: * DESCRIPTION: * The test for the boundary value of the parameters. * The test checks up that the methods * com.sun.jdi.request.ExceptionRequest.addThreadFilter(ThreadReference) * com.sun.jdi.request.ExceptionRequest.addInstanceFilter(ObjectReference) * com.sun.jdi.request.ExceptionRequest.addClassFilter(ReferenceType) * com.sun.jdi.request.ExceptionRequest.addClassFilter(String) * com.sun.jdi.request.ExceptionRequest.addClassExclusionFilter(String) * correctly work for the boundary value of parameter and throw described * exceptions. * The test check up this methods with <null> argument value. In any cases * NullPointerException is expected. * COMMENTS: * * @library /vmTestbase * /test/lib * @run driver jdk.test.lib.FileInstaller . . * @build nsk.jdi.ExceptionRequest._bounds_.filters001 * nsk.jdi.ExceptionRequest._bounds_.filters001a * @run main/othervm PropertyResolvingWrapper * nsk.jdi.ExceptionRequest._bounds_.filters001 * -verbose * -arch=${os.family}-${os.simpleArch} * -waittime=5 * -debugee.vmkind=java * -transport.address=dynamic * "-debugee.vmkeys=${test.vm.opts} ${test.java.opts}" */
3e064a8e98d101e4d4ac6b86b0813435b3d6c2c0
17,528
java
Java
enterprise/payara.eecommon/test/unit/src/org/netbeans/modules/payara/eecommon/api/config/PayaraConfigurationTest.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
enterprise/payara.eecommon/test/unit/src/org/netbeans/modules/payara/eecommon/api/config/PayaraConfigurationTest.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
enterprise/payara.eecommon/test/unit/src/org/netbeans/modules/payara/eecommon/api/config/PayaraConfigurationTest.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
53.932308
135
0.670755
2,661
/* * 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.netbeans.modules.payara.eecommon.api.config; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.netbeans.api.j2ee.core.Profile; import org.netbeans.junit.NbTestCase; import org.netbeans.modules.payara.tooling.data.PayaraPlatformVersionAPI; import org.netbeans.modules.payara.tooling.utils.OsUtils; import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule; import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleFactory; import org.netbeans.modules.payara.tooling.data.PayaraPlatformVersion; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Pair; /** * Payara Java EE server configuration API support tests. * <p/> * @author Tomas Kraus */ public class PayaraConfigurationTest extends NbTestCase { private GFTestEEModuleImpl moduleImplCar; private J2eeModule moduleCar; private GFTestEEModuleImpl moduleImplEjb; private J2eeModule moduleEjb; private GFTestEEModuleImpl moduleImplEar; private J2eeModule moduleEar; private GFTestEEModuleImpl moduleImplWar; private J2eeModule moduleWar; private GFTestEEModuleImpl moduleImplRar; private J2eeModule moduleRar; public PayaraConfigurationTest(final String testName) { super(testName); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before @Override public void setUp() throws Exception { final File dataDir = getDataDir(); final File rootFolder = new File(dataDir, "gfsample"); rootFolder.mkdirs(); final FileObject rootFolderFO = FileUtil.toFileObject(rootFolder); moduleImplCar = new GFTestEEModuleImpl( rootFolderFO, J2eeModule.Type.CAR, Profile.JAVA_EE_7_FULL.toPropertiesString()); moduleCar = J2eeModuleFactory.createJ2eeModule(moduleImplCar); moduleImplEjb = new GFTestEEModuleImpl( rootFolderFO, J2eeModule.Type.EJB, Profile.JAVA_EE_7_FULL.toPropertiesString()); moduleEjb = J2eeModuleFactory.createJ2eeModule(moduleImplEjb); moduleImplEar = new GFTestEEModuleImpl( rootFolderFO, J2eeModule.Type.EAR, Profile.JAVA_EE_7_FULL.toPropertiesString()); moduleEar = J2eeModuleFactory.createJ2eeModule(moduleImplEar); moduleImplRar = new GFTestEEModuleImpl( rootFolderFO, J2eeModule.Type.RAR, Profile.JAVA_EE_7_FULL.toPropertiesString()); moduleRar = J2eeModuleFactory.createJ2eeModule(moduleImplRar); moduleImplWar = new GFTestEEModuleImpl( rootFolderFO, J2eeModule.Type.WAR, Profile.JAVA_EE_7_WEB.toPropertiesString()); moduleWar = J2eeModuleFactory.createJ2eeModule(moduleImplWar); } @After @Override public void tearDown() { // Pass everything to GC. moduleImplCar = null; moduleCar = null; moduleImplEjb = null; moduleEjb = null; moduleImplEar = null; moduleEar = null; moduleImplRar = null; moduleRar = null; moduleImplWar = null; moduleWar = null; } /** * Test Java EE module directory structure for resource file. * @throws NoSuchMethodException when there is a problem with reflection. * @throws IllegalAccessException when there is a problem with reflection. * @throws IllegalArgumentException when there is a problem with reflection. * @throws InvocationTargetException when there is a problem with reflection. */ @Test public void testResourceFilePath() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final Method resourceFilePath = PayaraConfiguration.class.getDeclaredMethod( "resourceFilePath", J2eeModule.class, String.class); resourceFilePath.setAccessible(true); final String pathFragment = "myDirectory"; final String verifyConfigDirCar = OsUtils.joinPaths(JavaEEModule.META_INF, pathFragment); final String verifyConfigDirEjb = OsUtils.joinPaths(JavaEEModule.META_INF, pathFragment); final String verifyConfigDirEar = OsUtils.joinPaths(JavaEEModule.META_INF, pathFragment); final String verifyConfigDirRar = OsUtils.joinPaths(JavaEEModule.META_INF, pathFragment); final String verifyConfigDirWar = OsUtils.joinPaths(JavaEEModule.WEB_INF, pathFragment); final String configDirCar = (String)resourceFilePath.invoke(null, moduleCar, pathFragment); final String configDirEjb = (String)resourceFilePath.invoke(null, moduleEjb, pathFragment); final String configDirEar = (String)resourceFilePath.invoke(null, moduleEar, pathFragment); final String configDirRar = (String)resourceFilePath.invoke(null, moduleRar, pathFragment); final String configDirWar = (String)resourceFilePath.invoke(null, moduleWar, pathFragment); assertEquals("Expected resource file path for CAR is: " + verifyConfigDirCar, verifyConfigDirCar, configDirCar); assertEquals("Expected resource file path for EJB is: " + verifyConfigDirEjb, verifyConfigDirEjb, configDirEjb); assertEquals("Expected resource file path for EAR is: " + verifyConfigDirEar, verifyConfigDirEar, configDirEar); assertEquals("Expected resource file path for RAR is: " + verifyConfigDirRar, verifyConfigDirRar, configDirRar); assertEquals("Expected resource file path for WAR is: " + verifyConfigDirWar, verifyConfigDirWar, configDirWar); } /** * Test new Payara resources file name generation depending on passed {@link PayaraPlatformVersionAPI}. * Expected values are:<ul> * <li>PREFIX/src/conf/META_INF/sun-resources.xml for CAR, EAR, EJB and RAR * on Payara older than 3.1</li\> * <li>PREFIX/src/conf/META_INF/sun-resources.xml for CAR, EAR, EJB and RAR * on Payara 3.1 and later</li\> * <li>PREFIX/src/conf/WEB_INF/sun-resources.xml for WAR on Payara older than 3.1</li\> * <li>PREFIX/src/conf/WEB_INF/sun-resources.xml for WAR on Payara 3.1 and later</li\></ul> */ @Test public void testGetNewResourceFile() { for (PayaraPlatformVersionAPI version : PayaraPlatformVersion.getVersions()) { final Pair<File, Boolean> pairCar = PayaraConfiguration.getNewResourceFile(moduleCar, version); final Pair<File, Boolean> pairEar = PayaraConfiguration.getNewResourceFile(moduleEar, version); final Pair<File, Boolean> pairEjb = PayaraConfiguration.getNewResourceFile(moduleEjb, version); final Pair<File, Boolean> pairRar = PayaraConfiguration.getNewResourceFile(moduleRar, version); final Pair<File, Boolean> pairWar = PayaraConfiguration.getNewResourceFile(moduleWar, version); final File resourceFileCar = pairCar.first(); final File resourceFileEar = pairEar.first(); final File resourceFileEjb = pairEjb.first(); final File resourceFileRar = pairRar.first(); final File resourceFileWar = pairWar.first(); File verifyPrefixCar; File verifyPrefixEar; File verifyPrefixEjb; File verifyPrefixRar; File verifyPrefixWar; if (!version.isMinimumSupportedVersion()) { verifyPrefixCar = moduleCar.getResourceDirectory(); verifyPrefixEar = moduleEar.getResourceDirectory(); verifyPrefixEjb = moduleEjb.getResourceDirectory(); verifyPrefixRar = moduleRar.getResourceDirectory(); verifyPrefixWar = moduleWar.getResourceDirectory(); } else { verifyPrefixCar = moduleCar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleCar.getType())); verifyPrefixEar = moduleEar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleEar.getType())); verifyPrefixEjb = moduleEjb.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleEjb.getType())); verifyPrefixRar = moduleRar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleRar.getType())); verifyPrefixWar = moduleWar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleWar.getType())); } final String fileName = !version.isMinimumSupportedVersion() ? "sun-resources.xml" : "glassfish-resources.xml"; final File verifyFileCar = new File(verifyPrefixCar, fileName); final File verifyFileEar = new File(verifyPrefixEar, fileName); final File verifyFileEjb = new File(verifyPrefixEjb, fileName); final File verifyFileRar = new File(verifyPrefixRar, fileName); final File verifyFileWar = new File(verifyPrefixWar, fileName); assertTrue("New resource file for " + version.toString() + " CAR: " + verifyFileCar.toString() + " was " + resourceFileCar, verifyFileCar.equals(resourceFileCar)); assertTrue("New resource file for " + version.toString() + " EAR: " + verifyFileEar.toString() + " was " + resourceFileEar, verifyFileEar.equals(resourceFileEar)); assertTrue("New resource file for " + version.toString() + " EJB: " + verifyFileEjb.toString() + " was " + resourceFileEjb, verifyFileEjb.equals(resourceFileEjb)); assertTrue("New resource file for " + version.toString() + " RAR: " + verifyFileRar.toString() + " was " + resourceFileRar, verifyFileRar.equals(resourceFileRar)); assertTrue("New resource file for " + version.toString() + " WAR: " + verifyFileWar.toString() + " was " + resourceFileWar, verifyFileWar.equals(resourceFileWar)); } } /** * Verify that proper resource file from Java EE module is returned. * Both {@code sun-resources.xml} and {@code glassfish-resources.xml} are available * in Java EE module configuration directory on the disk. * Expected values are:<ul> * <li>PREFIX/src/conf/META_INF/sun-resources.xml for CAR, EAR, EJB and RAR * on Payara older than 3.1</li\> * <li>PREFIX/src/conf/META_INF/sun-resources.xml for CAR, EAR, EJB and RAR * on Payara 3.1 and later</li\> * <li>PREFIX/src/conf/WEB_INF/sun-resources.xml for WAR on Payara older than 3.1</li\> * <li>PREFIX/src/conf/WEB_INF/sun-resources.xml for WAR on Payara 3.1 and later</li\></ul> */ @Test public void testGetExistingResourceFile() throws IOException { final File prefixCar = moduleCar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleCar.getType())); final File prefixEar = moduleEar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleEar.getType())); final File prefixEjb = moduleEjb.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleEjb.getType())); final File prefixRar = moduleRar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleRar.getType())); final File prefixWar = moduleWar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleWar.getType())); final Set<File> prefixes = new HashSet<File>(5); prefixes.add(prefixCar); prefixes.add(prefixEar); prefixes.add(prefixEjb); prefixes.add(prefixRar); prefixes.add(prefixWar); // Create all resource files (they are empty but it's enough for this test). for (File prefix : prefixes) { final File sunResource = new File(prefix, "sun-resources.xml"); final File gfResource = new File(prefix, "glassfish-resources.xml"); prefix.mkdirs(); sunResource.createNewFile(); gfResource.createNewFile(); } for (PayaraPlatformVersionAPI version : PayaraPlatformVersion.getVersions()) { final Pair<File, Boolean> pairCar = PayaraConfiguration.getNewResourceFile(moduleCar, version); final Pair<File, Boolean> pairEar = PayaraConfiguration.getNewResourceFile(moduleEar, version); final Pair<File, Boolean> pairEjb = PayaraConfiguration.getNewResourceFile(moduleEjb, version); final Pair<File, Boolean> pairRar = PayaraConfiguration.getNewResourceFile(moduleRar, version); final Pair<File, Boolean> pairWar = PayaraConfiguration.getNewResourceFile(moduleWar, version); final File resourcesCar = pairCar.first(); final File resourcesEar = pairEar.first(); final File resourcesEjb = pairEjb.first(); final File resourcesRar = pairRar.first(); final File resourcesWar = pairWar.first(); File verifyPrefixCar; File verifyPrefixEar; File verifyPrefixEjb; File verifyPrefixRar; File verifyPrefixWar; if (!version.isMinimumSupportedVersion()) { verifyPrefixCar = moduleCar.getResourceDirectory(); verifyPrefixEar = moduleEar.getResourceDirectory(); verifyPrefixEjb = moduleEjb.getResourceDirectory(); verifyPrefixRar = moduleRar.getResourceDirectory(); verifyPrefixWar = moduleWar.getResourceDirectory(); } else { verifyPrefixCar = moduleCar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleCar.getType())); verifyPrefixEar = moduleEar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleEar.getType())); verifyPrefixEjb = moduleEjb.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleEjb.getType())); verifyPrefixRar = moduleRar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleRar.getType())); verifyPrefixWar = moduleWar.getDeploymentConfigurationFile( JavaEEModule.getConfigDir(moduleWar.getType())); } final String fileName = !version.isMinimumSupportedVersion() ? "sun-resources.xml" : "glassfish-resources.xml"; final File verifyFileCar = new File(verifyPrefixCar, fileName); final File verifyFileEar = new File(verifyPrefixEar, fileName); final File verifyFileEjb = new File(verifyPrefixEjb, fileName); final File verifyFileRar = new File(verifyPrefixRar, fileName); final File verifyFileWar = new File(verifyPrefixWar, fileName); assertTrue("Existing resource file for " + version.toString() + " CAR: " + verifyFileCar.toString() + " was " + resourcesCar, verifyFileCar.equals(resourcesCar)); assertTrue("Existing resource file for " + version.toString() + " EAR: " + verifyFileEar.toString() + " was " + resourcesEar, verifyFileEar.equals(resourcesEar)); assertTrue("Existing resource file for " + version.toString() + " EJB: " + verifyFileEjb.toString() + " was " + resourcesEjb, verifyFileEjb.equals(resourcesEjb)); assertTrue("Existing resource file for " + version.toString() + " RAR: " + verifyFileRar.toString() + " was " + resourcesRar, verifyFileRar.equals(resourcesRar)); assertTrue("Existing resource file for " + version.toString() + " WAR: " + verifyFileWar.toString() + " was " + resourcesWar, verifyFileWar.equals(resourcesWar)); } // Delete all resource files. for (File prefix : prefixes) { final File sunResource = new File(prefix, "sun-resources.xml"); final File gfResource = new File(prefix, "glassfish-resources.xml"); sunResource.delete(); gfResource.delete(); } } }
3e064aa80b55433afe7a2a703cc74bdee8b2ca29
966
java
Java
src/main/java/dev/cosgy/JMusicBot/commands/general/InviteCommand.java
TeamFelnull/JMusicBot-FelNull
873fad5c3e636f15e13cbde7899f810f798f0a42
[ "Apache-2.0" ]
null
null
null
src/main/java/dev/cosgy/JMusicBot/commands/general/InviteCommand.java
TeamFelnull/JMusicBot-FelNull
873fad5c3e636f15e13cbde7899f810f798f0a42
[ "Apache-2.0" ]
null
null
null
src/main/java/dev/cosgy/JMusicBot/commands/general/InviteCommand.java
TeamFelnull/JMusicBot-FelNull
873fad5c3e636f15e13cbde7899f810f798f0a42
[ "Apache-2.0" ]
null
null
null
40.25
316
0.755694
2,662
package dev.cosgy.JMusicBot.commands.general; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; import net.dv8tion.jda.api.Permission; public class InviteCommand extends Command { public InviteCommand() { this.name = "invite"; this.help = "Botの招待用URLを表示します。"; this.guildOnly = false; } @Override protected void execute(CommandEvent event) { long botId = event.getSelfUser().getIdLong(); Permission[] permissions = new Permission[] {Permission.MANAGE_CHANNEL, Permission.MANAGE_ROLES, Permission.MESSAGE_MANAGE, Permission.NICKNAME_CHANGE, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.VOICE_CONNECT, Permission.VOICE_SPEAK, Permission.VIEW_CHANNEL, Permission.MESSAGE_EXT_EMOJI}; event.replyFormatted("https://discord.com/oauth2/authorize?client_id=%s&scope=bot&permissions=%s", botId, Permission.getRaw(permissions)); } }
3e064c86068e0835b8a187e1b6404204a77235ab
1,509
java
Java
src/main/java/net/kiberion/swampmachine/scripting/jython/PythonScript.java
kibertoad/swampmachine-scripting
166a744f120f7935d3872b9ac023ef1d67b8728b
[ "MIT" ]
null
null
null
src/main/java/net/kiberion/swampmachine/scripting/jython/PythonScript.java
kibertoad/swampmachine-scripting
166a744f120f7935d3872b9ac023ef1d67b8728b
[ "MIT" ]
null
null
null
src/main/java/net/kiberion/swampmachine/scripting/jython/PythonScript.java
kibertoad/swampmachine-scripting
166a744f120f7935d3872b9ac023ef1d67b8728b
[ "MIT" ]
null
null
null
30.795918
99
0.708416
2,663
package net.kiberion.swampmachine.scripting.jython; import java.util.Map.Entry; import net.kiberion.swampmachine.scripting.api.SwampBinding; import net.kiberion.swampmachine.scripting.api.SwampScript; import net.kiberion.swampmachine.scripting.api.SwampScriptInvokationResult; import org.python.core.Py; import org.python.core.PyCode; import org.python.core.PyObject; import org.python.core.PyStringMap; import org.python.util.PythonInterpreter; /** * This class is thread-safe * @author kibertoad * */ public class PythonScript implements SwampScript { private final PyCode compiledScript; public PythonScript(String scriptBody) { try (PythonInterpreter interp = new PythonInterpreter()) { this.compiledScript = interp.compile(scriptBody); } } public PythonScript(PyCode script) { this.compiledScript = script; } @Override public SwampScriptInvokationResult apply(SwampBinding params) { try (PythonInterpreter interpreter = new PythonInterpreter()) { for (Entry<String, Object> entry : params.getVariableEntries()) { interpreter.set(entry.getKey(), entry.getValue()); } final PyStringMap localVars = (PyStringMap) interpreter.getLocals(); PyObject resultObject = Py.runCode(compiledScript, localVars, interpreter.getLocals()); localVars.getMap().put(SCRIPT_RESULT, resultObject); return new PyMapWrapper(localVars); } } }
3e064cfa7ac187b5ffe1bc8ac9050d9cbffd58c3
4,341
java
Java
src/main/java/com/binance/client/model/trade/MyTrade.java
xingyu4j/Binance_Futures_Java
ff70e66d9bebc9c99108bec1bf96b9391291abb3
[ "Apache-2.0" ]
1
2020-12-15T07:59:37.000Z
2020-12-15T07:59:37.000Z
src/main/java/com/binance/client/model/trade/MyTrade.java
xingyu4j/Binance_Futures_Java
ff70e66d9bebc9c99108bec1bf96b9391291abb3
[ "Apache-2.0" ]
1
2020-12-28T04:31:43.000Z
2020-12-28T06:35:41.000Z
src/main/java/com/binance/client/model/trade/MyTrade.java
xingyu4j/Binance_Futures_Java
ff70e66d9bebc9c99108bec1bf96b9391291abb3
[ "Apache-2.0" ]
1
2020-12-28T05:43:33.000Z
2020-12-28T05:43:33.000Z
19.379464
114
0.580742
2,664
package com.binance.client.model.trade; import com.binance.client.constant.BinanceApiConstants; import org.apache.commons.lang3.builder.ToStringBuilder; import java.math.BigDecimal; /** * 账户成交历史 * * @author xingyu */ public class MyTrade { /** * 是否是买方 */ private Boolean isBuyer; /** * 手续费 */ private BigDecimal commission; /** * 手续费计价单位 */ private String commissionAsset; /** * 是否是挂单方 */ private Boolean isMaker; /** * 交易ID */ private Long id; /** * 订单编号 */ private Long orderId; /** * 成交价 */ private BigDecimal price; /** * 成交量 */ private BigDecimal qty; /** * 成交额 */ private BigDecimal quoteQty; /** * 是否是买方 */ private Long counterPartyId; /** * 实现盈亏 */ private BigDecimal realizedPnl; /** * 买卖方向 */ private String side; /** * 持仓方向 */ private String positionSide; /** * 交易对 */ private String symbol; /** * 时间 */ private Long time; public Boolean getBuyer() { return isBuyer; } public void setBuyer(Boolean buyer) { isBuyer = buyer; } public Boolean getMaker() { return isMaker; } public void setMaker(Boolean maker) { isMaker = maker; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Boolean getIsBuyer() { return isBuyer; } public void setIsBuyer(Boolean isBuyer) { this.isBuyer = isBuyer; } public BigDecimal getCommission() { return commission; } public void setCommission(BigDecimal commission) { this.commission = commission; } public String getCommissionAsset() { return commissionAsset; } public void setCommissionAsset(String commissionAsset) { this.commissionAsset = commissionAsset; } public Long getCounterPartyId() { return counterPartyId; } public void setCounterPartyId(Long counterPartyId) { this.counterPartyId = counterPartyId; } public Boolean getIsMaker() { return isMaker; } public void setIsMaker(Boolean isMaker) { this.isMaker = isMaker; } public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getQty() { return qty; } public void setQty(BigDecimal qty) { this.qty = qty; } public BigDecimal getQuoteQty() { return quoteQty; } public void setQuoteQty(BigDecimal quoteQty) { this.quoteQty = quoteQty; } public BigDecimal getRealizedPnl() { return realizedPnl; } public void setRealizedPnl(BigDecimal realizedPnl) { this.realizedPnl = realizedPnl; } public String getSide() { return side; } public void setSide(String side) { this.side = side; } public String getPositionSide() { return positionSide; } public void setPositionSide(String positionSide) { this.positionSide = positionSide; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public Long getTime() { return time; } public void setTime(Long time) { this.time = time; } @Override public String toString() { return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE).append("isBuyer", isBuyer) .append("commission", commission).append("commissionAsset", commissionAsset) .append("counterPartyId", counterPartyId).append("isMaker", isMaker) .append("orderId", orderId).append("price", price).append("qty", qty).append("quoteQty", quoteQty) .append("realizedPnl", realizedPnl).append("side", side).append("positionSide", positionSide) .append("symbol", symbol).append("time", time).toString(); } }
3e064df0099e04f25b892738491a2de47626dcc8
748
java
Java
src/main/java/br/ufsc/cultivar/security/AuthResponseDTO.java
LuizMaestri/cultivar
9325008230cd47cb14d6b3da50f537132d3c1f56
[ "MIT" ]
null
null
null
src/main/java/br/ufsc/cultivar/security/AuthResponseDTO.java
LuizMaestri/cultivar
9325008230cd47cb14d6b3da50f537132d3c1f56
[ "MIT" ]
null
null
null
src/main/java/br/ufsc/cultivar/security/AuthResponseDTO.java
LuizMaestri/cultivar
9325008230cd47cb14d6b3da50f537132d3c1f56
[ "MIT" ]
null
null
null
28.769231
65
0.807487
2,665
package br.ufsc.cultivar.security; import br.ufsc.cultivar.model.User; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import lombok.AccessLevel; import lombok.Builder; import lombok.Value; import lombok.experimental.FieldDefaults; import lombok.experimental.Wither; @Value @Wither @Builder(builderClassName = "Builder") @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) @JsonDeserialize(builder = AuthResponseDTO.Builder.class) @JsonInclude(JsonInclude.Include.NON_NULL) class AuthResponseDTO { User user; String token; @JsonPOJOBuilder(withPrefix = "") static class Builder{} }
3e064e17a9bc5983259c8a44d0dd3a54697e9c80
34,743
java
Java
src/test/java/org/s1ck/gdl/GDLLoaderTest.java
p-f/gdl
d96ed0ddbbf38881137cdaad9d914c0a45ff9229
[ "Apache-2.0" ]
24
2015-11-19T10:15:43.000Z
2021-10-30T00:23:21.000Z
src/test/java/org/s1ck/gdl/GDLLoaderTest.java
p-f/gdl
d96ed0ddbbf38881137cdaad9d914c0a45ff9229
[ "Apache-2.0" ]
42
2016-02-04T14:31:14.000Z
2021-03-06T10:12:40.000Z
src/test/java/org/s1ck/gdl/GDLLoaderTest.java
p-f/gdl
d96ed0ddbbf38881137cdaad9d914c0a45ff9229
[ "Apache-2.0" ]
15
2015-11-19T07:21:31.000Z
2020-11-30T13:46:41.000Z
38.517738
129
0.633336
2,666
package org.s1ck.gdl; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.junit.Test; import org.s1ck.gdl.exceptions.DuplicateDeclarationException; import org.s1ck.gdl.exceptions.InvalidReferenceException; import org.s1ck.gdl.model.Edge; import org.s1ck.gdl.model.Element; import org.s1ck.gdl.model.Graph; import org.s1ck.gdl.model.GraphElement; import org.s1ck.gdl.model.Vertex; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import static org.junit.Assert.*; @SuppressWarnings("OptionalGetWithoutIsPresent") public class GDLLoaderTest { // -------------------------------------------------------------------------------------------- // Vertex only tests // -------------------------------------------------------------------------------------------- @Test public void readVertexTest() { GDLLoader loader = getLoaderFromGDLString("()"); validateCollectionSizes(loader, 0, 1, 0); validateCacheSizes(loader, 0, 0, 0, 0, 1, 0); Optional<Vertex> vertex = loader.getVertices().stream().findFirst(); assertTrue(vertex.isPresent()); assertEquals(1, vertex.get().getLabels().size()); assertEquals(loader.getDefaultVertexLabel(), vertex.get().getLabels().get(0)); } @Test public void readVertexWithVariableTest() { GDLLoader loader = getLoaderFromGDLString("(var)"); validateCollectionSizes(loader, 0, 1, 0); validateCacheSizes(loader, 0, 1, 0, 0, 0, 0); assertTrue("vertex not cached", loader.getVertexCache().containsKey("var")); assertNotNull("vertex was null", loader.getVertexCache().get("var")); } @Test public void readVertexWithLabelTest() { GDLLoader loader = getLoaderFromGDLString("(var:Label)"); Vertex v = loader.getVertexCache().get("var"); assertEquals("vertex has wrong label", "Label", v.getLabels().get(0)); } @Test public void readVertexWithMultipleLabelsTest() { GDLLoader loader = getLoaderFromGDLString("(var:Label1:Label2:Label3)"); Vertex v = loader.getVertexCache().get("var"); assertEquals( "vertex has wrong label", Arrays.asList("Label1", "Label2", "Label3"), v .getLabels() ); } @Test public void readVertexWithCamelCaseLabelTest() { GDLLoader loader = getLoaderFromGDLString("(var:BlogPost)"); Vertex v = loader.getVertexCache().get("var"); assertEquals("vertex has wrong label", "BlogPost", v.getLabel()); } @Test public void readVertexWithSnakeCaseLabelTest() { GDLLoader loader = getLoaderFromGDLString("(var:Blog_Post)"); Vertex v = loader.getVertexCache().get("var"); assertEquals("vertex has wrong label", "Blog_Post", v.getLabel()); } @Test public void readVertexWithPropertiesTest() { GDLLoader loader = getLoaderFromGDLString(String.format("(var %s)", PROPERTIES_STRING)); validateProperties(loader.getVertexCache().get("var")); } @Test public void readVertexWithVariablesTest() { GDLLoader loader = getLoaderFromGDLString("(var)"); Vertex v = loader.getVertices().iterator().next(); assertEquals("vertex has wrong variable", "var", v.getVariable()); } @Test public void readVertexWithDifferentStringRepresentations() { GDLLoader loader = getLoaderFromGDLString("" + "({" + " foo: \"foo\"," + " bar: 'bar'," + " baz: \"\\\"baz\\\"\"," + " foobar: '\\'foobar\\''" + "})" ); Vertex v = loader.getVertices().iterator().next(); Map<String, Object> properties = v.getProperties(); assertEquals("foo", properties.get("foo")); assertEquals("bar", properties.get("bar")); assertEquals("\"baz\"", properties.get("baz")); assertEquals("'foobar'", properties.get("foobar")); } @Test public void failOnDuplicateVertexPropertyAssignment() { DuplicateDeclarationException exc = assertThrows( DuplicateDeclarationException.class, () -> getLoaderFromGDLString("(v1 {prop: 1}), (v1 {prop: 1})") ); assertEquals("Vertex `v1` is declared multiple times. " + "Declaring properties or labels while referencing a variable is not allowed. " + "Use `(v1)` to refer to the element instead.", exc.getMessage() ); } // -------------------------------------------------------------------------------------------- // Edge only tests // -------------------------------------------------------------------------------------------- @Test public void readEdgeTest() { GDLLoader loader = getLoaderFromGDLString("()-->()"); validateCollectionSizes(loader, 0, 2, 1); validateCacheSizes(loader, 0, 0, 0, 0, 2, 1); Optional<Edge> edge = loader.getEdges().stream().findFirst(); assertTrue(edge.isPresent()); assertFalse("edge should not have variable length", edge.get().hasVariableLength()); assertEquals("edge has wrong label", loader.getDefaultEdgeLabel(), edge.get().getLabel()); } @Test public void readOutgoingEdgeWithVariablesTest() { GDLLoader loader = getLoaderFromGDLString("(v1)-[e1]->(v2)"); validateCollectionSizes(loader, 0, 2, 1); validateCacheSizes(loader, 0, 2, 1, 0, 0, 0); assertTrue("edge not cached", loader.getEdgeCache().containsKey("e1")); Edge e1 = loader.getEdgeCache().get("e1"); assertNotNull("e was null", e1); assertFalse("edge should not have variable length", e1.hasVariableLength()); assertEquals(loader.getDefaultEdgeLabel(), e1.getLabel()); Vertex v1 = loader.getVertexCache().get("v1"); Vertex v2 = loader.getVertexCache().get("v2"); assertEquals("wrong source vertex identifier", (Long) v1.getId(), e1.getSourceVertexId()); assertEquals("wrong target vertex identifier", (Long) v2.getId(), e1.getTargetVertexId()); } @Test public void readIncomingEdgeWithVariablesTest() { GDLLoader loader = getLoaderFromGDLString("(v1)<-[e1]-(v2)"); assertEquals("wrong number of edges", 1, loader.getEdges().size()); assertEquals("wrong number of cached edges", 1, loader.getEdgeCache().size()); assertTrue("edge not cached", loader.getEdgeCache().containsKey("e1")); Edge e1 = loader.getEdgeCache().get("e1"); assertNotNull("e was null", e1); assertFalse("edge should not have variable length", e1.hasVariableLength()); Vertex v1 = loader.getVertexCache().get("v1"); Vertex v2 = loader.getVertexCache().get("v2"); assertEquals("wrong source vertex identifier", (Long) v1.getId(), e1.getTargetVertexId()); assertEquals("wrong target vertex identifier", (Long) v2.getId(), e1.getSourceVertexId()); } @Test public void readEdgeWithNoLabelTest() throws Exception { GDLLoader loader = getLoaderFromGDLString("()-[e]->()"); Edge e = loader.getEdgeCache().get("e"); assertEquals("edge has wrong label", loader.getDefaultEdgeLabel(), e.getLabel()); } @Test public void readEdgeWithLabelTest() { GDLLoader loader = getLoaderFromGDLString("()-[e:knows]->()"); Edge e = loader.getEdgeCache().get("e"); assertFalse("edge should not have variable length", e.hasVariableLength()); assertEquals("edge has the wrong number of labels", 1, e.getLabels().size()); assertEquals("edge has wrong label", "knows", e.getLabel()); } @Test public void readEdgeWithCamelCaseLabelTest() { GDLLoader loader = getLoaderFromGDLString("()-[e:hasInterest]->()"); Edge e = loader.getEdgeCache().get("e"); assertEquals("edge has wrong label", "hasInterest", e.getLabel()); } @Test public void readEdgeWithSnakeCaseLabelTest() { GDLLoader loader = getLoaderFromGDLString("()-[e:HAS_INTEREST]->()"); Edge e = loader.getEdgeCache().get("e"); assertEquals("edge has wrong label", "HAS_INTEREST", e.getLabel()); } @Test public void readEdgeWithMultipleLabelsTest() { GDLLoader loader = getLoaderFromGDLString("()-[e:hasInterest:foobar]->()"); Edge e = loader.getEdgeCache().get("e"); assertEquals( "edge has wrong label", Arrays.asList("hasInterest", "foobar"), e.getLabels() ); assertEquals("hasInterest", e.getLabel()); } @Test public void readEdgeWithPropertiesTest() { GDLLoader loader = getLoaderFromGDLString(String.format("()-[e %s]->()", PROPERTIES_STRING)); validateProperties(loader.getEdgeCache().get("e")); } @Test public void readEdgeWithVariablesTest() { GDLLoader loader = getLoaderFromGDLString("()-[e]->()"); Edge e = loader.getEdges().iterator().next(); assertEquals("edge has wrong variable", "e", e.getVariable()); } @Test public void readEdgeWithNoRangeExpression() { GDLLoader loader = getLoaderFromGDLString("()-[e]->()"); Edge e = loader.getEdgeCache().get("e"); assertFalse("edge should not have variable length", e.hasVariableLength()); assertEquals("wrong lower bound", 1, e.getLowerBound()); assertEquals("wrong upper bound", 1, e.getUpperBound()); } @Test public void readEdgeWithLowerBoundTest() { GDLLoader loader = getLoaderFromGDLString("()-[e*2]->()"); Edge e = loader.getEdgeCache().get("e"); assertTrue("edge should have variable length", e.hasVariableLength()); assertEquals("wrong lower bound", 2, e.getLowerBound()); assertEquals("wrong lower bound", 0, e.getUpperBound()); } @Test public void readEdgeWithUpperBoundTest() { GDLLoader loader = getLoaderFromGDLString("()-[e*..5]->()"); Edge e = loader.getEdgeCache().get("e"); assertTrue("edge should have variable length", e.hasVariableLength()); assertEquals("wrong lower bound", 0, e.getLowerBound()); assertEquals("wrong lower bound", 5, e.getUpperBound()); } @Test public void readEdgeWithLowerAndUpperBoundTest() { GDLLoader loader = getLoaderFromGDLString("()-[e*3..5]->()"); Edge e = loader.getEdgeCache().get("e"); assertTrue("edge should have variable length", e.hasVariableLength()); assertEquals("wrong lower bound", 3, e.getLowerBound()); assertEquals("wrong lower bound", 5, e.getUpperBound()); } @Test public void readEdgeWithUnboundLengthTest() { GDLLoader loader = getLoaderFromGDLString("()-[e*]->()"); Edge e = loader.getEdgeCache().get("e"); assertTrue("edge should have variable length", e.hasVariableLength()); assertEquals("wrong lower bound", 0, e.getLowerBound()); assertEquals("wrong lower bound", 0, e.getUpperBound()); } @Test public void failOnDuplicateEdgePropertyAssignment() { DuplicateDeclarationException exc = assertThrows( DuplicateDeclarationException.class, () -> getLoaderFromGDLString("g[(a)-[f {prop: 1}]->(b)],h[(a)-[f {prop: 1}]->(b)]") ); assertEquals("Edge `f` is declared multiple times. " + "Declaring properties or labels while referencing a variable is not allowed. " + "Use `[f]` to refer to the element instead.", exc.getMessage() ); } // -------------------------------------------------------------------------------------------- // Graph only tests // -------------------------------------------------------------------------------------------- @Test public void readEmptyGraphTest() { GDLLoader loader = getLoaderFromGDLString("[]"); validateCollectionSizes(loader, 1, 0, 0); validateCacheSizes(loader, 0, 0, 0, 1, 0, 0); Optional<Graph> graph = loader.getGraphs().stream().findFirst(); assertTrue(graph.isPresent()); assertEquals(1, graph.get().getLabels().size()); assertEquals(loader.getDefaultGraphLabel(), graph.get().getLabels().get(0)); } @Test public void readSimpleGraphTest() { GDLLoader loader = getLoaderFromGDLString("[()]"); validateCollectionSizes(loader, 1, 1, 0); validateCacheSizes(loader, 0, 0, 0, 1, 1, 0); } @Test public void readGraphWithVariableTest() { GDLLoader loader = getLoaderFromGDLString("g[()]"); validateCollectionSizes(loader, 1, 1, 0); validateCacheSizes(loader, 1, 0, 0, 0, 1, 0); assertTrue("graph not cached", loader.getGraphCache().containsKey("g")); Graph g = loader.getGraphCache().get("g"); assertNotNull("graph was null", g); assertEquals(loader.getDefaultGraphLabel(), g.getLabel()); } @Test public void readGraphWithLabelTest() { GDLLoader loader = getLoaderFromGDLString("g:Label[()]"); validateCollectionSizes(loader, 1, 1, 0); validateCacheSizes(loader, 1, 0, 0, 0, 1, 0); Graph g = loader.getGraphCache().get("g"); assertEquals("graph has the wrong number of labels", 1, g.getLabels().size()); assertEquals("graph has wrong label", "Label", g.getLabel()); } @Test public void readGraphWithCamelCaseLabelTest() { GDLLoader loader = getLoaderFromGDLString("g:LabelParty[()]"); Graph g = loader.getGraphCache().get("g"); assertEquals("graph has wrong label", "LabelParty", g.getLabel()); } @Test public void readGraphWithMultipleLabelsTest() { GDLLoader loader = getLoaderFromGDLString("g:Label1:Label2[()]"); Graph g = loader.getGraphCache().get("g"); assertEquals( "graph has wrong label", Arrays.asList("Label1", "Label2"), g.getLabels() ); } @Test public void readGraphWithPropertiesTest() { GDLLoader loader = getLoaderFromGDLString(String.format("g%s[()]", PROPERTIES_STRING)); validateCollectionSizes(loader, 1, 1, 0); validateCacheSizes(loader, 1, 0, 0, 0, 1, 0); validateProperties(loader.getGraphCache().get("g")); } @Test public void readGraphWithPropertiesOnly() { GDLLoader loader = getLoaderFromGDLString(String.format("%s[()]", PROPERTIES_STRING)); validateCollectionSizes(loader, 1, 1, 0); validateCacheSizes(loader, 0, 0, 0, 1, 1, 0); validateProperties(loader.getGraphs().iterator().next()); } @Test public void readGraphWithVariablesTest() { GDLLoader loader = getLoaderFromGDLString("g[()]"); Graph g = loader.getGraphs().iterator().next(); assertEquals("edge has wrong variable", "g", g.getVariable()); } @Test public void readFragmentedGraphTest() { GDLLoader loader = getLoaderFromGDLString("g[()],g[()]"); validateCollectionSizes(loader, 1, 2, 0); validateCacheSizes(loader, 1, 0, 0, 0, 2, 0); } @Test public void failOnDuplicateGraphPropertyAssignment() { DuplicateDeclarationException exc = assertThrows( DuplicateDeclarationException.class, () -> getLoaderFromGDLString("g:Community{memberCount:23}[(a)] g:{memberCount:23}[(a)]") ); assertEquals("Graph `g` is declared multiple times. " + "Declaring properties or labels while referencing a variable is not allowed. " + "Use `g` to refer to the element instead.", exc.getMessage() ); } // -------------------------------------------------------------------------------------------- // Path cases // -------------------------------------------------------------------------------------------- @Test public void pathTest() { GDLLoader loader = getLoaderFromGDLString("(v1)-[e1]->(v2)<-[e2]-(v3)"); validateCollectionSizes(loader, 0, 3, 2); validateCacheSizes(loader, 0, 3, 2, 0, 0, 0); Vertex v1 = loader.getVertexCache().get("v1"); Vertex v2 = loader.getVertexCache().get("v2"); Vertex v3 = loader.getVertexCache().get("v3"); Edge e1 = loader.getEdgeCache().get("e1"); Edge e2 = loader.getEdgeCache().get("e2"); assertEquals("edge e1 has wrong source vertex identifier", (Long) v1.getId(), e1.getSourceVertexId()); assertEquals("edge e1 has wrong target vertex identifier", (Long) v2.getId(), e1.getTargetVertexId()); assertEquals("edge e2 has wrong source vertex identifier", (Long) v3.getId(), e2.getSourceVertexId()); assertEquals("edge e2 has wrong target vertex identifier", (Long) v2.getId(), e2.getTargetVertexId()); } // -------------------------------------------------------------------------------------------- // Optional CREATE statement // -------------------------------------------------------------------------------------------- @Test public void testWithCreateStatement() { GDLLoader loader = getLoaderFromGDLString("CREATE ()-->()"); validateCollectionSizes(loader, 0, 2, 1); validateCacheSizes(loader, 0, 0, 0, 0, 2, 1); } // -------------------------------------------------------------------------------------------- // MATCH ... WHERE ... tests // -------------------------------------------------------------------------------------------- @Test public void testNonPredicateMatch() throws Exception { String query = "MATCH (n)-[e]->(m)"; GDLLoader loader = getLoaderFromGDLString(query); validateCollectionSizes(loader, 0, 2, 1); assertFalse(loader.getPredicates().isPresent()); } @Test public void testSimpleWhereClause() { String query = "MATCH (alice)-[r]->(bob)" + "WHERE alice.age > 50"; GDLLoader loader = getLoaderFromGDLString(query); validateCollectionSizes(loader, 0, 2, 1); assertEquals("alice.age > 50", loader.getPredicates().get().toString()); } @Test public void testNotClause() { String query = "MATCH (alice)-[r]->(bob)" + "WHERE NOT alice.age > 50"; GDLLoader loader = getLoaderFromGDLString(query); validateCollectionSizes(loader, 0, 2, 1); assertEquals("(NOT alice.age > 50)", loader.getPredicates().get().toString()); } @Test public void testComplexWhereClause() { String query = "MATCH (alice)-[r]->(bob)" + "WHERE (alice.age > bob.age OR (alice.age < 30 AND bob.name = \"Bob\")) AND alice.id != bob.id"; GDLLoader loader = getLoaderFromGDLString(query); validateCollectionSizes(loader, 0, 2, 1); assertEquals("((alice.age > bob.age OR (alice.age < 30 AND bob.name = Bob)) AND alice.id != bob.id)", loader.getPredicates().get().toString()); } @Test public void testEmbeddedWhereClause() { String query = "MATCH (alice {age : 50})-[r:knows]->(bob:User)"; GDLLoader loader = getLoaderFromGDLString(query); validateCollectionSizes(loader, 0, 2, 1); assertEquals("((alice.age = 50 AND bob.__label__ = User) AND r.__label__ = knows)", loader.getPredicates().get().toString()); } @Test public void testEmbeddedAndExplicitWhereClause() { GDLLoader loader = getLoaderFromGDLString( "MATCH (p:Person)-[e1:likes {love: TRUE}]->(other:Person) " + "WHERE p.age >= other.age"); validateCollectionSizes(loader, 0, 2, 1); Vertex p = loader.getVertexCache().get("p"); assertEquals("((((p.age >= other.age" + " AND p.__label__ = Person)" + " AND other.__label__ = Person)" + " AND e1.__label__ = likes)" + " AND e1.love = true)", loader.getPredicates().get().toString()); assertEquals("vertex p has wrong label","Person", p.getLabel()); } @Test(expected=InvalidReferenceException.class) public void testThrowExceptionOnInvalidVariableReference() { getLoaderFromGDLString("MATCH (a) where b.age = 42"); } // -------------------------------------------------------------------------------------------- // Combined tests // -------------------------------------------------------------------------------------------- @Test public void testGraphWithContentTest() { GDLLoader loader = getLoaderFromGDLString("g[(alice)-[r]->(bob),(alice)-[s]->(eve)]"); validateCollectionSizes(loader, 1, 3, 2); validateCacheSizes(loader, 1, 3, 2, 0, 0 ,0); Graph g = loader.getGraphCache().get("g"); List<GraphElement> graphElements = Arrays.asList( loader.getVertexCache().get("alice"), loader.getVertexCache().get("bob"), loader.getVertexCache().get("eve"), loader.getEdgeCache().get("r"), loader.getEdgeCache().get("s") ); for (GraphElement graphElement : graphElements) { assertEquals("element has wrong graphs size", 1, graphElement.getGraphs().size()); assertTrue("element was not in graph", graphElement.getGraphs().contains(g.getId())); } } @Test public void testGraphsWithOverlappingContent() { GDLLoader loader = getLoaderFromGDLString("g1[(alice)-[r]->(bob)],g2[(alice)-[s]->(bob)]"); validateCollectionSizes(loader, 2, 2, 2); validateCacheSizes(loader, 2, 2, 2, 0, 0 , 0); Graph g1 = loader.getGraphCache().get("g1"); Graph g2 = loader.getGraphCache().get("g2"); List<Vertex> overlapElements = Arrays.asList( loader.getVertexCache().get("alice"), loader.getVertexCache().get("bob") ); for (Vertex vertex : overlapElements) { assertEquals("vertex has wrong graph size", 2, vertex.getGraphs().size()); assertTrue("vertex was not in graph g1", vertex.getGraphs().contains(g1.getId())); assertTrue("vertex was not in graph g2", vertex.getGraphs().contains(g2.getId())); } assertEquals("edge r has wrong graph size", 1, loader.getEdgeCache().get("r").getGraphs().size()); assertTrue("edge r was not in graph g1", loader.getEdgeCache().get("r").getGraphs().contains(g1.getId())); assertEquals("edge s has wrong graph size", 1, loader.getEdgeCache().get("s").getGraphs().size()); assertTrue("edge s was not in graph g2", loader.getEdgeCache().get("s").getGraphs().contains(g2.getId())); } @Test public void testFragmentedGraphWithVariables() { GDLLoader loader = getLoaderFromGDLString( "g[(a)-->(b)],g[(a)-[e]->(b)],g[(a)-[f]->(b)],h[(a)-[f]->(b)]"); validateCollectionSizes(loader, 2, 2, 3); validateCacheSizes(loader, 2, 2, 2, 0, 0, 1); Graph g = loader.getGraphCache().get("g"); Graph h = loader.getGraphCache().get("h"); Vertex a = loader.getVertexCache().get("a"); Vertex b = loader.getVertexCache().get("b"); Edge e = loader.getEdgeCache().get("e"); Edge f = loader.getEdgeCache().get("f"); assertEquals("vertex a has wrong graph size", 2, a.getGraphs().size()); assertEquals("vertex b has wrong graph size", 2, b.getGraphs().size()); assertTrue("vertex a was not in g", a.getGraphs().contains(g.getId())); assertTrue("vertex a was not in h", a.getGraphs().contains(h.getId())); assertTrue("vertex b was not in g", b.getGraphs().contains(g.getId())); assertTrue("vertex b was not in h", b.getGraphs().contains(h.getId())); assertEquals("edge e has wrong graph size", 1, e.getGraphs().size()); assertEquals("edge f has wrong graph size", 2, f.getGraphs().size()); assertTrue("edge e was not in g", e.getGraphs().contains(g.getId())); assertTrue("edge f was not in g", f.getGraphs().contains(g.getId())); assertTrue("edge f was not in h", f.getGraphs().contains(h.getId())); } // -------------------------------------------------------------------------------------------- // Special cases // -------------------------------------------------------------------------------------------- @Test public void readNullValueTest() { GDLLoader loader = getLoaderFromGDLString("(v{name:NULL})"); validateCollectionSizes(loader, 0, 1, 0); validateCacheSizes(loader, 0, 1, 0, 0, 0, 0); Vertex a = loader.getVertexCache().get("v"); assertTrue("missing property at vertex", a.getProperties().containsKey("name")); assertNull("property value was not null", a.getProperties().get("name")); } @Test public void readEmptyGDLTest() { GDLLoader loader = getLoaderFromGDLString(""); validateCollectionSizes(loader, 0, 0, 0); validateCacheSizes(loader, 0, 0, 0, 0, 0, 0); } @Test public void loopTest() { GDLLoader loader = getLoaderFromGDLString("(v)-[e]->(v)"); validateCollectionSizes(loader, 0, 1, 1); validateCacheSizes(loader, 0, 1, 1, 0, 0, 0); Vertex v = loader.getVertexCache().get("v"); Edge e = loader.getEdgeCache().get("e"); assertEquals("wrong source vertex identifier", (Long) v.getId(), e.getSourceVertexId()); assertEquals("wrong target vertex identifier", (Long) v.getId(), e.getTargetVertexId()); } @Test public void cycleTest() { GDLLoader loader = getLoaderFromGDLString("(v1)-[e1]->(v2)<-[e2]-(v1)"); validateCollectionSizes(loader, 0, 2, 2); validateCacheSizes(loader, 0, 2, 2, 0, 0, 0); Vertex v1 = loader.getVertexCache().get("v1"); Vertex v2 = loader.getVertexCache().get("v2"); Edge e1 = loader.getEdgeCache().get("e1"); Edge e2 = loader.getEdgeCache().get("e2"); assertEquals("edge e1 has wrong source vertex identifier", (Long) v1.getId(), e1.getSourceVertexId()); assertEquals("edge e1 has wrong target vertex identifier", (Long) v2.getId(), e1.getTargetVertexId()); assertEquals("edge e2 has wrong source vertex identifier", (Long) v1.getId(), e2.getSourceVertexId()); assertEquals("edge e2 has wrong target vertex identifier", (Long) v2.getId(), e2.getTargetVertexId()); } // -------------------------------------------------------------------------------------------- // Test helpers // -------------------------------------------------------------------------------------------- private static final String DEFAULT_GRAPH_LABEL = "DefaultGraph"; private static final String DEFAULT_VERTEX_LABEL = "DefaultVertex"; private static final String DEFAULT_EDGE_LABEL = "DefaultEdge"; private GDLLoader getLoaderFromGDLString(String gdlString) { GDLLexer lexer = new GDLLexer(new ANTLRInputStream(gdlString)); GDLParser parser = new GDLParser(new CommonTokenStream(lexer)); ParseTreeWalker walker = new ParseTreeWalker(); GDLLoader loader = new GDLLoader(DEFAULT_GRAPH_LABEL, DEFAULT_VERTEX_LABEL, DEFAULT_EDGE_LABEL); walker.walk(loader, parser.database()); return loader; } private GDLLoader getLoaderFromFile(String fileName) throws IOException { InputStream inputStream = getClass().getResourceAsStream(fileName); GDLLexer lexer = new GDLLexer(new ANTLRInputStream(inputStream)); GDLParser parser = new GDLParser(new CommonTokenStream(lexer)); ParseTreeWalker walker = new ParseTreeWalker(); GDLLoader loader = new GDLLoader(DEFAULT_GRAPH_LABEL, DEFAULT_VERTEX_LABEL, DEFAULT_EDGE_LABEL); walker.walk(loader, parser.database()); return loader; } // string representation of all valid properties private static String PROPERTIES_STRING; // contains all valid properties private static final List<PropertyTriple<?>> PROPERTIES_LIST = new ArrayList<>(); /** * Represents a property for testing. * * @param <T> */ private static class PropertyTriple<T> { private String key; private String value; private T expected; public PropertyTriple(String key, String value, T expected) { this.key = key; this.value = value; this.expected = expected; } public String getKey() { return key; } public String getValue() { return value; } public T getExpected() { return expected; } @Override public String toString() { return String.format("%s:%s", getKey(), getValue()); } } static { PROPERTIES_LIST.add(new PropertyTriple<>("_", "true", true)); PROPERTIES_LIST.add(new PropertyTriple<>("_k1", "true", true)); PROPERTIES_LIST.add(new PropertyTriple<>("__k1", "true", true)); PROPERTIES_LIST.add(new PropertyTriple<>("_k_1", "true", true)); PROPERTIES_LIST.add(new PropertyTriple<>("k1", "\"value\"", "value")); PROPERTIES_LIST.add(new PropertyTriple<>("k2", "true", true)); PROPERTIES_LIST.add(new PropertyTriple<>("k3", "false", false)); PROPERTIES_LIST.add(new PropertyTriple<>("k4", "TRUE", true)); PROPERTIES_LIST.add(new PropertyTriple<>("k5", "FALSE", false)); PROPERTIES_LIST.add(new PropertyTriple<>("k6", "0", 0)); PROPERTIES_LIST.add(new PropertyTriple<>("k7", "0L", 0L)); PROPERTIES_LIST.add(new PropertyTriple<>("k8", "0l", 0L)); PROPERTIES_LIST.add(new PropertyTriple<>("k9", "42", 42)); PROPERTIES_LIST.add(new PropertyTriple<>("k10", "42L", 42L)); PROPERTIES_LIST.add(new PropertyTriple<>("k11", "42l", 42L)); PROPERTIES_LIST.add(new PropertyTriple<>("k12", "-42", -42)); PROPERTIES_LIST.add(new PropertyTriple<>("k13", "-42L", -42L)); PROPERTIES_LIST.add(new PropertyTriple<>("k14", "-42l", -42L)); PROPERTIES_LIST.add(new PropertyTriple<>("k15", "0.0", 0.0f)); PROPERTIES_LIST.add(new PropertyTriple<>("k16", "0.0f", 0.0f)); PROPERTIES_LIST.add(new PropertyTriple<>("k17", "0.0F", 0.0f)); PROPERTIES_LIST.add(new PropertyTriple<>("k18", "0.0d", 0.0d)); PROPERTIES_LIST.add(new PropertyTriple<>("k19", "0.0D", 0.0D)); PROPERTIES_LIST.add(new PropertyTriple<>("k20", "-0.0", -0.0f)); PROPERTIES_LIST.add(new PropertyTriple<>("k21", "-0.0f", -0.0f)); PROPERTIES_LIST.add(new PropertyTriple<>("k22", "-0.0F", -0.0F)); PROPERTIES_LIST.add(new PropertyTriple<>("k23", "-0.0d", -0.0d)); PROPERTIES_LIST.add(new PropertyTriple<>("k24", "-0.0D", -0.0D)); PROPERTIES_LIST.add(new PropertyTriple<>("k25", ".0", .0f)); PROPERTIES_LIST.add(new PropertyTriple<>("k26", ".0f", .0f)); PROPERTIES_LIST.add(new PropertyTriple<>("k27", ".0F", .0F)); PROPERTIES_LIST.add(new PropertyTriple<>("k28", ".0d", .0d)); PROPERTIES_LIST.add(new PropertyTriple<>("k29", ".0D", .0D)); PROPERTIES_LIST.add(new PropertyTriple<>("k30", "3.14", 3.14f)); PROPERTIES_LIST.add(new PropertyTriple<>("k31", "3.14f", 3.14f)); PROPERTIES_LIST.add(new PropertyTriple<>("k32", "3.14F", 3.14F)); PROPERTIES_LIST.add(new PropertyTriple<>("k33", "3.14d", 3.14d)); PROPERTIES_LIST.add(new PropertyTriple<>("k34", "3.14D", 3.14D)); PROPERTIES_LIST.add(new PropertyTriple<>("k35", "-3.14", -3.14f)); PROPERTIES_LIST.add(new PropertyTriple<>("k36", "-3.14f", -3.14f)); PROPERTIES_LIST.add(new PropertyTriple<>("k37", "-3.14F", -3.14F)); PROPERTIES_LIST.add(new PropertyTriple<>("k38", "-3.14d", -3.14d)); PROPERTIES_LIST.add(new PropertyTriple<>("k39", "-3.14D", -3.14D)); PROPERTIES_LIST.add(new PropertyTriple<>("k40", "NaN", Double.NaN)); PROPERTIES_LIST.add(new PropertyTriple<>("k41", "[1, 3, 3, 7]", new ArrayList<>(Arrays.asList(1, 3, 3, 7)))); PROPERTIES_LIST.add(new PropertyTriple<>("k42", "[1L, 3L, 3L, 7L]", new ArrayList<>(Arrays.asList(1L, 3L, 3L, 7L)))); PROPERTIES_LIST.add(new PropertyTriple<>("k43", "[1.0F, 3.0f, 3.0F, 7.0f]", new ArrayList<>(Arrays.asList(1f, 3f, 3f, 7f)))); PROPERTIES_LIST.add(new PropertyTriple<>("k44", "[1.0D, 3.0d, 3.0D, 7.0d]", new ArrayList<>(Arrays.asList(1d, 3d, 3d, 7d)))); PROPERTIES_LIST.add(new PropertyTriple<>("k45", "[1.0, 3.0, 3, 7L]", new ArrayList<>(Arrays.asList(1.0f, 3.0f, 3, 7L)))); PROPERTIES_LIST.add(new PropertyTriple<>("k46", "[]", new ArrayList<>())); PROPERTIES_LIST.add(new PropertyTriple<>("k47", "[ ]", new ArrayList<>())); PROPERTIES_LIST.add(new PropertyTriple<>("k48", "[NaN, NULL]", new ArrayList<>(Arrays.asList(Double.NaN, null)))); Iterator<PropertyTriple<?>> iterator = PROPERTIES_LIST.iterator(); StringBuilder sb = new StringBuilder(); sb.append("{"); while (iterator.hasNext()) { sb.append(iterator.next().toString()); if (iterator.hasNext()) { sb.append(","); } } sb.append("}"); PROPERTIES_STRING = sb.toString(); } private void validateProperties(Element element) { assertEquals("wrong number of properties", PROPERTIES_LIST.size(), element.getProperties().size()); for (PropertyTriple<?> expectedProperty : PROPERTIES_LIST) { assertEquals("wrong property for key: " + expectedProperty.getKey(), expectedProperty.getExpected(), element.getProperties().get(expectedProperty.getKey())); } } private void validateCollectionSizes(GDLLoader loader, int expectedGraphCount, int expectedVertexCount, int expectedEdgeCount) { assertEquals("wrong number of graphs", expectedGraphCount, loader.getGraphs().size()); assertEquals("wrong number of vertices", expectedVertexCount, loader.getVertices().size()); assertEquals("wrong number of edges", expectedEdgeCount, loader.getEdges().size()); } private void validateCacheSizes(GDLLoader loader, int expectedUserGraphCacheSize, int expectedUserVertexCacheSize, int expectedUserEdgeCacheSize, int expectedAutoGraphCacheSize, int expectedAutoVertexCacheSize, int expectedAutoEdgeCacheSize) { // default (user-defined) assertEquals("wrong number of cached user-defined graphs", expectedUserGraphCacheSize, loader.getGraphCache().size()); assertEquals("wrong number of cached user-defined vertices", expectedUserVertexCacheSize, loader.getVertexCache().size()); assertEquals("wrong number of cached user-defined edges", expectedUserEdgeCacheSize, loader.getEdgeCache().size()); // user-defined assertEquals("wrong number of cached user-defined graphs", expectedUserGraphCacheSize, loader.getGraphCache(true, false).size()); assertEquals("wrong number of cached user-defined vertices", expectedUserVertexCacheSize, loader.getVertexCache(true, false).size()); assertEquals("wrong number of cached user-defined edges", expectedUserEdgeCacheSize, loader.getEdgeCache(true, false).size()); // auto-generated assertEquals("wrong number of cached auto-defined graphs", expectedAutoGraphCacheSize, loader.getGraphCache(false, true).size()); assertEquals("wrong number of cached auto-defined vertices", expectedAutoVertexCacheSize, loader.getVertexCache(false, true).size()); assertEquals("wrong number of cached auto-defined edges", expectedAutoEdgeCacheSize, loader.getEdgeCache(false, true).size()); // all assertEquals("wrong number of cached auto-defined graphs", expectedUserGraphCacheSize + expectedAutoGraphCacheSize, loader.getGraphCache(true, true).size()); assertEquals("wrong number of cached auto-defined vertices", expectedUserVertexCacheSize + expectedAutoVertexCacheSize, loader.getVertexCache(true, true).size()); assertEquals("wrong number of cached auto-defined edges", expectedUserEdgeCacheSize + expectedAutoEdgeCacheSize, loader.getEdgeCache(true, true).size()); } }
3e064e8724048af3d7d29d5de453f522b3dcaf1c
2,713
java
Java
algorithm/src/com/caleb/algorithm/leetcode/CanFinish207.java
CalebLogin/JavaDemo
95f4ef8d041e02f6f59bdcf00c2c356127b1c95a
[ "Apache-2.0" ]
null
null
null
algorithm/src/com/caleb/algorithm/leetcode/CanFinish207.java
CalebLogin/JavaDemo
95f4ef8d041e02f6f59bdcf00c2c356127b1c95a
[ "Apache-2.0" ]
null
null
null
algorithm/src/com/caleb/algorithm/leetcode/CanFinish207.java
CalebLogin/JavaDemo
95f4ef8d041e02f6f59bdcf00c2c356127b1c95a
[ "Apache-2.0" ]
null
null
null
23.798246
70
0.44895
2,667
package com.caleb.algorithm.leetcode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * * @author:hanzhigang * @Date : 2021/5/16 9:31 PM * * 课程表 * * 你这个学期必须选修 numCourses 门课程,记为0到numCourses - 1 。 * * 在选修某些课程之前需要一些先修课程。 先修课程按数组prerequisites给出, * * 其中prerequisites[i] = [ai, bi] ,表示如果要学习课程ai 则 必须 先学习课程 bi 。 * * 例如,先修课程对[0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1 。 * * 请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false */ public class CanFinish207 { /** * 拓扑问题 如果存在环问题,则说明不可以!! 队列就可以解决 * * 深度优先遍历 * * @param numCourses * @param prerequisites * @return */ List<List<Integer>> edges = new ArrayList<>(); int[] visited; boolean valid = true; public boolean canFinish(int numCourses, int[][] prerequisites) { for (int i = 0; i < numCourses; i++) { edges.set(i, new ArrayList<>()); } for (int[] i : prerequisites) { edges.get(i[0]).add(i[1]); } visited = new int[numCourses]; for (int i = 0; i < numCourses && valid; i++) { if (visited[i] == 0) { dfs(i); } } return valid; } private void dfs(int v) { // 重点 visited[v] = 1; for (int nv : edges.get(v)) { if (visited[nv] == 0) { dfs(nv); if (!valid) { return; } } else if (visited[nv] == 1) { valid = false; return; } } // 重点 visited[v] = 2; } /** * 广度优先遍历 * * @param numCourses * @param prerequisites * @return */ public boolean canFinish1(int numCourses, int[][] prerequisites) { Queue<Integer> q = new LinkedList<>(); List<List<Integer>> edges = new ArrayList<>(); // 节点入度 int[] indeg = new int[numCourses]; for (int i = 0; i < numCourses; i++) { edges.add(new ArrayList<>()); } for (int[] i : prerequisites) { edges.get(i[1]).add(i[0]); ++indeg[i[0]]; } for (int i = 0; i < numCourses; i++) { if (indeg[i] == 0) { q.offer(i); } } int visitedCount = 0; while (!q.isEmpty()) { visitedCount++; int u = q.poll(); for (int v : edges.get(u)) { --indeg[v]; if (indeg[v] == 0) { q.offer(v); } } } return numCourses == visitedCount; } }
3e064ecc19244f444ca875a65b73da0d3a2e2f21
520
java
Java
src/main/java/com/tcfritchman/pojo/ReleaseLabel.java
tcfritchman/MusicGraph
c374fb09af455228b8a85e7186127398731e53ea
[ "MIT" ]
null
null
null
src/main/java/com/tcfritchman/pojo/ReleaseLabel.java
tcfritchman/MusicGraph
c374fb09af455228b8a85e7186127398731e53ea
[ "MIT" ]
null
null
null
src/main/java/com/tcfritchman/pojo/ReleaseLabel.java
tcfritchman/MusicGraph
c374fb09af455228b8a85e7186127398731e53ea
[ "MIT" ]
null
null
null
19.259259
49
0.763462
2,668
package com.tcfritchman.pojo; import lombok.Data; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; /** * @author Thomas Fritchman */ @Data @XmlRootElement(name = "label") @XmlAccessorType(XmlAccessType.FIELD) public class ReleaseLabel { @XmlAttribute private String id; @XmlAttribute private String catno; @XmlAttribute private String name; }
3e06500dfb29133db7dba460c7978ee3097fe8e7
1,223
java
Java
Cinefilia/src/main/java/model/factory/Factory.java
jass2125/cinefilia
406a29c6e50dca7abcd510563b50803b20496712
[ "Apache-2.0" ]
null
null
null
Cinefilia/src/main/java/model/factory/Factory.java
jass2125/cinefilia
406a29c6e50dca7abcd510563b50803b20496712
[ "Apache-2.0" ]
null
null
null
Cinefilia/src/main/java/model/factory/Factory.java
jass2125/cinefilia
406a29c6e50dca7abcd510563b50803b20496712
[ "Apache-2.0" ]
null
null
null
23.075472
79
0.721995
2,669
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model.factory; import model.abstractfactory.AbstractFactory; import model.dao.AmizadeDao; import model.dao.FilmeDao; import model.dao.GrupoDao; import model.dao.ParticipaGrupoDao; import model.dao.UsuarioDao; import model.interfacesdaoifs.AmizadeDaoIF; import model.interfacesdaoifs.FilmeDaoIF; import model.interfacesdaoifs.GrupoDaoIF; import model.interfacesdaoifs.ParticipaGrupoDaoIF; import model.interfacesdaoifs.UsuarioDaoIF; /** * * @author Anderson Souza */ public class Factory extends AbstractFactory{ @Override public UsuarioDaoIF createDaoUsuario() { return new UsuarioDao(); } @Override public FilmeDaoIF createDaoFilme() { return new FilmeDao(); } public GrupoDaoIF createDaoGrupo(){ return new GrupoDao(); } @Override public AmizadeDaoIF createDaoAmizade() { return new AmizadeDao(); } @Override public ParticipaGrupoDaoIF createDaoParticipaGrupo(){ return new ParticipaGrupoDao(); } }
3e0650c9970d2abe7cd82a947b3dcee747bf5ab9
9,024
java
Java
persistit-core/src/main/java/com/persistit/mxbeans/JournalManagerMXBean.java
OpenIdentityPlatform/forgerock-persistit
08a77ac1f78924c547c87ed96f4f7eddc1d63df3
[ "Apache-2.0" ]
3
2017-03-15T07:27:40.000Z
2019-04-29T22:45:00.000Z
persistit-core/src/main/java/com/persistit/mxbeans/JournalManagerMXBean.java
OpenIdentityPlatform/forgerock-persistit
08a77ac1f78924c547c87ed96f4f7eddc1d63df3
[ "Apache-2.0" ]
3
2019-02-21T05:02:47.000Z
2019-12-03T00:34:58.000Z
src/main/java/com/persistit/mxbeans/JournalManagerMXBean.java
SonarSource/sonar-persistit
2eb91b68ac6e5ba9edbfe917fd35bb6a717d94a8
[ "Apache-2.0" ]
4
2015-01-19T08:23:26.000Z
2019-03-14T10:21:20.000Z
35.667984
114
0.730829
2,670
/** * Copyright 2011-2012 Akiban Technologies, 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.persistit.mxbeans; import javax.management.MXBean; import com.persistit.exception.PersistitException; /** * Management interface to the <code>JournalManager</code>, including journal * file names and file positions. Of particular interest are * {@link #getCurrentAddress()} and {@link #getBaseAddress()}. The difference * between these represents the degree to which JOURNAL_COPIER has fallen behind * recent updates. * * @author peter * */ @MXBean public interface JournalManagerMXBean { public final static String MXBEAN_NAME = "com.persistit:type=Persistit,class=JournalManager"; /** * Version number for the journal file format defined in this edition. Will * change if the journal file format changes. */ final static int VERSION = 2; /** * Default size of one journal file (10E9). */ final static long DEFAULT_BLOCK_SIZE = 1000000000L; /** * Minimum permitted journal file size. */ final static long MINIMUM_BLOCK_SIZE = 10000000L; /** * Maximum permitted journal file size. */ final static long MAXIMUM_BLOCK_SIZE = 100000000000L; /** * Size at which a completely obsolete journal file can be eliminated. */ final static long ROLLOVER_THRESHOLD = 4 * 1024 * 1024; /** * Default, minimum and maximum size of journal write buffer. */ final static int DEFAULT_BUFFER_SIZE = 16 * 1024 * 1024; final static int MINIMUM_BUFFER_SIZE = 65536; final static int MAXIMUM_BUFFER_SIZE = DEFAULT_BUFFER_SIZE * 10; /** * Default size of journal read buffer. */ final static int DEFAULT_COPY_BUFFER_SIZE = 16 * 1024 * 1024; /** * Default time interval (in milliseconds) between calls to the * FileChannel.force() method. */ final static long DEFAULT_FLUSH_INTERVAL_MS = 100; /** * Default time interval (in milliseconds) between calls to the journal * copier method. */ final static long DEFAULT_COPIER_INTERVAL_MS = 10000; /** * Default journal file count at which transactions are throttled to allow * copier to catch up. */ final static int DEFAULT_URGENT_FILE_COUNT_THRESHOLD = 15; final static int MINIMUM_URGENT_FILE_COUNT_THRESHOLD = 5; final static int MAXIMUM_URGENT_FILE_COUNT_THRESHOLD = 100; /** * Default value for maximum pages to be copied per cycle. */ final static int DEFAULT_COPIES_PER_CYCLE = 1000; /** * Default time interval (in milliseconds) for logging repetitive I/O * exceptions on attempts to write to the journal. Prevents excessively * verbose log on repeated failures. */ final static long DEFAULT_LOG_REPEAT_INTERVAL_MS = 60000L; final static long MINIMUM_LOG_REPEAT_INTERVAL_MS = 1000L; final static long MAXIMUM_LOG_REPEAT_INTERVAL_MS = Long.MAX_VALUE; /** * Default threshold time in milliseconds for JournalManager flush * operations. If a flush operation takes longer than this time, a WARNING * message is written to the log. */ final static long DEFAULT_SLOW_IO_ALERT_THRESHOLD_MS = 2000L; final static long MINIMUM_SLOW_ALERT_THRESHOLD_MS = 100L; final static long MAXIMUM_SLOW_ALERT_THRESHOLD_MS = Long.MAX_VALUE; /** * File name appended when journal path specifies only a directory */ final static String DEFAULT_JOURNAL_FILE_NAME = "persistit_journal"; /** * Format expression defining the name of a journal file. */ final static String PATH_FORMAT = "%s.%012d"; final static int MAXIMUM_CONCURRENT_TRANSACTIONS = 10000; @Description("Number of transaction map items in the live map") int getLiveTransactionMapSize(); @Description("Number of unique pages currently stored in the journal") int getPageMapSize(); @Description("Number of unique page versions currently stored in the journal") int getPageListSize(); @Description("Address of first record in the journal required for recovery") long getBaseAddress(); @Description("Address of next record to be written") long getCurrentAddress(); @Description("Maximum size of one journal file") long getBlockSize(); @Description("True if copying of pages from the journal to their destination volumes is disabled") boolean isAppendOnly(); @Description("True to allow journal to lose pages from missing volumes") boolean isIgnoreMissingVolumes(); @Description("True if copy-fast mode has been enabled") boolean isCopyingFast(); @Description("True if copying of pages from the journal to their destination volumes is disabled") void setAppendOnly(boolean appendOnly); @Description("True to allow journal to lose pages from missing volumes") void setIgnoreMissingVolumes(boolean ignore); @Description("True if copy-fast mode has been enabled") void setCopyingFast(boolean fast); @Description("Interval between data flush cycles in milliseconds") long getFlushInterval(); @Description("Interval between data flush cycles in milliseconds") void setFlushInterval(long flushInterval); @Description("Interval between page copying cycles") long getCopierInterval(); @Description("Interval between page copying cycles") void setCopierInterval(long copierInterval); @Description("True if the journal has been closed") boolean isClosed(); @Description("True if the JOURNAL_COPIER thread is currently active") boolean isCopying(); @Description("File path where journal files are written") String getJournalFilePath(); @Description("Total number of page images read from the journal") long getReadPageCount(); @Description("Total number of page images written to the journal") long getJournaledPageCount(); @Description("Total number of page images copied from the journal to their destination volumes") long getCopiedPageCount(); @Description("Total number of page images pages dropped from the journal due the existence of newer versions") long getDroppedPageCount(); @Description("System time when journal was first created") long getJournalCreatedTime(); @Description("Timestamp value when the most recently valid checkpoint was created") long getLastValidCheckpointTimestamp(); @Description("Current timestamp value") long getCurrentTimestamp(); @Description("True to enable pruning of rolled-back transactions") void setRollbackPruningEnabled(boolean rollbackPruning); @Description("True to enable pruning of rolled-back transactions") boolean isRollbackPruningEnabled(); @Description("True to enable pruning when writing pages to journal") void setWritePagePruningEnabled(boolean rollbackPruning); @Description("True to enable pruning when writing pages to journal") boolean isWritePagePruningEnabled(); @Description("Degree of urgency for copying pages: 0-10") int urgency(); @Description("Flush all pending journal records to durable storage") void force() throws PersistitException; @Description("Perform accelerated page copying") void copyBack() throws Exception; @Description("String value of last Exception encountered by the JOURNAL_COPIER thread") String getLastCopierException(); @Description("String value of last Exception encountered by the JOURNAL_FLUSHER thread") String getLastFlusherException(); @Description("System time when the most recently valid checkpoint was created") long getLastValidCheckpointTimeMillis(); @Description("Total number of transaction commit records written to the journal") long getTotalCompletedCommits(); @Description("Total aggregate time spent waiting for durable commits in milliseconds") long getCommitCompletionWaitTime(); @Description("Threshold in milliseconds for warnings of long duration flush cycles") long getSlowIoAlertThreshold(); @Description("Threshold in milliseconds for warnings of long duration flush cycles") void setSlowIoAlertThreshold(long slowIoAlertThreshold); @Description("Journal file count threshold for throttling transactions") int getUrgentFileCountThreshold(); @Description("Journal file count threshold for throttling transactions") void setUrgentFileCountThreshold(int threshold); }
3e06514b2eb3128baf4bd69ec78f01245cac02cf
3,473
java
Java
components/governance/org.wso2.carbon.governance.custom.lifecycles.checklist.ui/src/main/java/org/wso2/carbon/governance/custom/lifecycles/checklist/ui/processors/InvokeAspectProcessor.java
jranabahu/carbon-governance
96dc772013cdd4e85bc5d8976c1c396d44653432
[ "Apache-2.0" ]
8
2015-04-01T07:28:02.000Z
2022-02-17T14:07:07.000Z
components/governance/org.wso2.carbon.governance.custom.lifecycles.checklist.ui/src/main/java/org/wso2/carbon/governance/custom/lifecycles/checklist/ui/processors/InvokeAspectProcessor.java
jranabahu/carbon-governance
96dc772013cdd4e85bc5d8976c1c396d44653432
[ "Apache-2.0" ]
53
2015-01-06T09:56:21.000Z
2022-01-27T16:16:37.000Z
components/governance/org.wso2.carbon.governance.custom.lifecycles.checklist.ui/src/main/java/org/wso2/carbon/governance/custom/lifecycles/checklist/ui/processors/InvokeAspectProcessor.java
jranabahu/carbon-governance
96dc772013cdd4e85bc5d8976c1c396d44653432
[ "Apache-2.0" ]
127
2015-01-16T11:52:06.000Z
2022-03-23T06:47:05.000Z
44.525641
114
0.686438
2,671
/* * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.governance.custom.lifecycles.checklist.ui.processors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.governance.custom.lifecycles.checklist.ui.clients.LifecycleServiceClient; import org.wso2.carbon.registry.core.RegistryConstants; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; public class InvokeAspectProcessor { private static final Log log = LogFactory.getLog(InvokeAspectProcessor.class); public static void invokeAspect(HttpServletRequest request, ServletConfig config) throws Exception { LifecycleServiceClient lifecycleServiceClient = new LifecycleServiceClient(config, request.getSession()); String path = request.getParameter("path"); String aspect = request.getParameter("aspect"); String action = request.getParameter("action"); String[] items = request.getParameterValues("items"); /* "true, false, true, false"*/ String versionString = request.getParameter("parameterString"); if (!versionString.trim().equals("")) { String[] keySetWithValues = versionString.split("\\^\\|\\^"); String[][] resourceVersionArray = new String[keySetWithValues.length][2]; for (int i = 0; i < keySetWithValues.length; i++) { String keySetWithValue = keySetWithValues[i]; String[] keyAndValue = keySetWithValue.split("\\^\\^"); resourceVersionArray[i][0] = keyAndValue[0]; resourceVersionArray[i][1] = keyAndValue[1]; } lifecycleServiceClient.invokeAspectWithParams(path, aspect, action, items,resourceVersionArray); } else{ lifecycleServiceClient.invokeAspect(path, aspect, action, items); } } public static String[] getAllDependencies(HttpServletRequest request, ServletConfig config) throws Exception { String path = request.getParameter("path"); LifecycleServiceClient lifecycleServiceClient = new LifecycleServiceClient(config,request.getSession()); String[] dependencies = lifecycleServiceClient.getAllDependencies(path); List<String> filteredDependencies = new ArrayList<String>(); for (String dependency : dependencies) { if (dependency.startsWith("/")) { filteredDependencies.add(dependency); } else { log.warn("Dependency " + dependency + " of " + path.substring( path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1) + " ignored when promoting"); } } return filteredDependencies.toArray(new String[filteredDependencies.size()]); } }
3e0651a29b131876656bced508988bab1e3523aa
657
java
Java
src/main/java/word/WordReducer.java
Meruem117/mapreduce_count_text
408dd322d5a59272347e79bb5c221548d1eaac98
[ "MIT" ]
1
2021-07-13T10:19:19.000Z
2021-07-13T10:19:19.000Z
src/main/java/word/WordReducer.java
Meruem117/mapreduce_count_text
408dd322d5a59272347e79bb5c221548d1eaac98
[ "MIT" ]
null
null
null
src/main/java/word/WordReducer.java
Meruem117/mapreduce_count_text
408dd322d5a59272347e79bb5c221548d1eaac98
[ "MIT" ]
null
null
null
27.375
82
0.672755
2,672
package word; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; public class WordReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } //for循环遍历,将得到的values值累加 result.set(sum); context.write(key, result); } }
3e0651add2fff444c3fa500b73147506cd8f7930
2,055
java
Java
src/test/java/uk/ac/ebi/embl/flatfile/writer/embl/ASWriterTest.java
enasequence/sequence-validator
773ae2a2331ea4dc84c312bbde34bbfd784d857c
[ "Apache-2.0" ]
9
2016-08-10T14:05:14.000Z
2021-02-11T23:38:00.000Z
src/test/java/uk/ac/ebi/embl/flatfile/writer/embl/ASWriterTest.java
enasequence/sequence-validator
773ae2a2331ea4dc84c312bbde34bbfd784d857c
[ "Apache-2.0" ]
52
2016-08-10T13:51:00.000Z
2021-09-15T07:23:23.000Z
src/test/java/uk/ac/ebi/embl/flatfile/writer/embl/ASWriterTest.java
enasequence/sequence-validator
773ae2a2331ea4dc84c312bbde34bbfd784d857c
[ "Apache-2.0" ]
5
2016-08-11T08:36:54.000Z
2019-03-16T21:24:53.000Z
39.519231
81
0.615572
2,673
/******************************************************************************* * Copyright 2012 EMBL-EBI, Hinxton outstation * * 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 uk.ac.ebi.embl.flatfile.writer.embl; import java.io.IOException; import java.io.StringWriter; import uk.ac.ebi.embl.api.entry.EntryFactory; public class ASWriterTest extends EmblWriterTest { public void testWrite_Assembly() throws IOException { EntryFactory entryFactory = new EntryFactory(); entry.addAssembly(entryFactory.createAssembly("AC004528", 1, 18665l, 19090l, true, 1l, 426l)); entry.addAssembly(entryFactory.createAssembly("AC004529", 6, 45665l, 98790l, true, 6l, 546l)); StringWriter writer = new StringWriter(); assertTrue(new ASWriter(entry).write(writer)); //System.out.print(writer.toString()); assertEquals( "AH LOCAL_SPAN PRIMARY_IDENTIFIER PRIMARY_SPAN COMP\n" + "AS 1-426 AC004528.1 18665-19090 c\n" + "AS 6-546 AC004529.6 45665-98790 c\n", writer.toString()); } public void testWrite_NoAssembly() throws IOException { entry.removeAssemblies(); StringWriter writer = new StringWriter(); assertFalse(new ASWriter(entry).write(writer)); // System.out.print(writer.toString()); assertEquals( "", writer.toString()); } }
3e0652b369b9f4e6fb28c50421f5cd3af33ddbe8
493
java
Java
app/src/main/java/com/example/logapptest/MainActivity.java
IsmaProject/LibraryLog-Android
bb1c9811a0ed13f2a6427c01c7d6a86068de725b
[ "MIT" ]
null
null
null
app/src/main/java/com/example/logapptest/MainActivity.java
IsmaProject/LibraryLog-Android
bb1c9811a0ed13f2a6427c01c7d6a86068de725b
[ "MIT" ]
null
null
null
app/src/main/java/com/example/logapptest/MainActivity.java
IsmaProject/LibraryLog-Android
bb1c9811a0ed13f2a6427c01c7d6a86068de725b
[ "MIT" ]
null
null
null
23.47619
56
0.705882
2,674
package com.example.logapptest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.example.librarytest.LogDebug; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LogDebug.d("jcb"); LogDebug.add(2,9); LogDebug.rem(1,1); LogDebug.tell("chdjsbc"); } }
3e06536462cef43938b4e6a41844cce2d6fdc164
2,948
java
Java
CognitoBjs/app/libs/aws-android-sdk-core/src/main/java/com/amazonaws/auth/AWSEnhancedCognitoIdentityProvider.java
xfsnow/android
6d8fa6505066293ef2f2588e8374cc417a58b305
[ "Apache-2.0" ]
7
2017-11-07T04:10:06.000Z
2020-04-01T04:53:40.000Z
CognitoBjs/app/libs/aws-android-sdk-core/src/main/java/com/amazonaws/auth/AWSEnhancedCognitoIdentityProvider.java
xfsnow/android
6d8fa6505066293ef2f2588e8374cc417a58b305
[ "Apache-2.0" ]
2
2018-09-10T17:47:23.000Z
2018-09-25T04:10:02.000Z
CognitoBjs/app/libs/aws-android-sdk-core/src/main/java/com/amazonaws/auth/AWSEnhancedCognitoIdentityProvider.java
xfsnow/android
6d8fa6505066293ef2f2588e8374cc417a58b305
[ "Apache-2.0" ]
4
2020-02-22T02:23:18.000Z
2020-12-11T02:55:48.000Z
35.95122
98
0.714722
2,675
/** * Copyright 2011-2015 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.0 * * This file 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.amazonaws.auth; import com.amazonaws.ClientConfiguration; import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentity; import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient; /** * An extension of the AbstractCognitoProvider that is used to communicate with * Cognito when using the enhanced authentication flow. All other functionality * is the same as that of AbstractCognitoIdentityProvider. */ public final class AWSEnhancedCognitoIdentityProvider extends AWSAbstractCognitoIdentityProvider { /** * An extension of the AbstractCognitoProvider that is used to communicate * with Cognito. * * @param accountId the account id of the developer * @param identityPoolId the identity pool id of the app/user in question */ public AWSEnhancedCognitoIdentityProvider(String accountId, String identityPoolId) { this(accountId, identityPoolId, new ClientConfiguration()); } /** * An extension of the AbstractCognitoProvider that is used to communicate * with Cognito. * * @param accountId the account id of the developer * @param identityPoolId the identity pool id of the app/user in question * @param clientConfiguration the configuration to apply to service clients * created */ public AWSEnhancedCognitoIdentityProvider(String accountId, String identityPoolId, ClientConfiguration clientConfiguration) { this(accountId, identityPoolId, new AmazonCognitoIdentityClient (new AnonymousAWSCredentials(), clientConfiguration)); } /** * An extension of the AbstractCognitoProvider that is used to communicate * with Cognito. * * @param accountId the account id of the developer * @param identityPoolId the identity pool id of the app/user in question * @param cibClient the cib client which will be used to contact the cib * back end */ public AWSEnhancedCognitoIdentityProvider(String accountId, String identityPoolId, AmazonCognitoIdentity cibClient) { super(accountId, identityPoolId, cibClient); } @Override public String getProviderName() { return "Cognito"; } @Override public String refresh() { getIdentityId(); // This flow doesn't request a token return null; } }
3e06537b69dac33efba034e57f263b71acbfc7a0
4,149
java
Java
services/meeting/src/main/java/com/huaweicloud/sdk/meeting/v1/model/UpdateDepartmentRequest.java
huaweicloud/huaweicloud-sdk-java-v3
a01cd21a3d03f6dffc807bea7c522e34adfa368d
[ "Apache-2.0" ]
50
2020-05-18T11:35:20.000Z
2022-03-15T02:07:05.000Z
services/meeting/src/main/java/com/huaweicloud/sdk/meeting/v1/model/UpdateDepartmentRequest.java
huaweicloud/huaweicloud-sdk-java-v3
a01cd21a3d03f6dffc807bea7c522e34adfa368d
[ "Apache-2.0" ]
45
2020-07-06T03:34:12.000Z
2022-03-31T09:41:54.000Z
services/meeting/src/main/java/com/huaweicloud/sdk/meeting/v1/model/UpdateDepartmentRequest.java
huaweicloud/huaweicloud-sdk-java-v3
a01cd21a3d03f6dffc807bea7c522e34adfa368d
[ "Apache-2.0" ]
27
2020-05-28T11:08:44.000Z
2022-03-30T03:30:37.000Z
28.033784
106
0.640636
2,676
package com.huaweicloud.sdk.meeting.v1.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; import java.util.function.Consumer; /** Request Object */ public class UpdateDepartmentRequest { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "X-Request-Id") private String xRequestId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "Accept-Language") private String acceptLanguage; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "dept_code") private String deptCode; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "body") private ModDeptDTO body; public UpdateDepartmentRequest withXRequestId(String xRequestId) { this.xRequestId = xRequestId; return this; } /** 请求requestId,用来标识一路请求,用于问题跟踪定位,建议使用uuId,若不携带,则后台自动生成 * * @return xRequestId */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "X-Request-Id") public String getXRequestId() { return xRequestId; } public void setXRequestId(String xRequestId) { this.xRequestId = xRequestId; } public UpdateDepartmentRequest withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** 语言参数,默认为中文zh_CN, 英文为en_US * * @return acceptLanguage */ public String getAcceptLanguage() { return acceptLanguage; } public void setAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; } public UpdateDepartmentRequest withDeptCode(String deptCode) { this.deptCode = deptCode; return this; } /** 部门编码。 长度: 0-32位。 * * @return deptCode */ public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode; } public UpdateDepartmentRequest withBody(ModDeptDTO body) { this.body = body; return this; } public UpdateDepartmentRequest withBody(Consumer<ModDeptDTO> bodySetter) { if (this.body == null) { this.body = new ModDeptDTO(); bodySetter.accept(this.body); } return this; } /** Get body * * @return body */ public ModDeptDTO getBody() { return body; } public void setBody(ModDeptDTO body) { this.body = body; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateDepartmentRequest updateDepartmentRequest = (UpdateDepartmentRequest) o; return Objects.equals(this.xRequestId, updateDepartmentRequest.xRequestId) && Objects.equals(this.acceptLanguage, updateDepartmentRequest.acceptLanguage) && Objects.equals(this.deptCode, updateDepartmentRequest.deptCode) && Objects.equals(this.body, updateDepartmentRequest.body); } @Override public int hashCode() { return Objects.hash(xRequestId, acceptLanguage, deptCode, body); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UpdateDepartmentRequest {\n"); sb.append(" xRequestId: ").append(toIndentedString(xRequestId)).append("\n"); sb.append(" acceptLanguage: ").append(toIndentedString(acceptLanguage)).append("\n"); sb.append(" deptCode: ").append(toIndentedString(deptCode)).append("\n"); sb.append(" body: ").append(toIndentedString(body)).append("\n"); sb.append("}"); return sb.toString(); } /** Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0653a0c3773ef674d8e1e43c7eb2aaff120e1a
212
java
Java
src/BehavioralPattern/CommandPattern/Barbecuer.java
abelzyp/DesignPatterns
485f5a50e8918317595ae52afc947890f9c18bba
[ "Apache-2.0" ]
6
2018-07-17T10:48:50.000Z
2019-12-06T03:33:51.000Z
src/BehavioralPattern/CommandPattern/Barbecuer.java
abelzyp/DesignPatterns
485f5a50e8918317595ae52afc947890f9c18bba
[ "Apache-2.0" ]
null
null
null
src/BehavioralPattern/CommandPattern/Barbecuer.java
abelzyp/DesignPatterns
485f5a50e8918317595ae52afc947890f9c18bba
[ "Apache-2.0" ]
1
2018-07-17T10:49:05.000Z
2018-07-17T10:49:05.000Z
14.133333
41
0.688679
2,677
package BehavioralPattern.CommandPattern; /* * 烤肉串者 */ public class Barbecuer { public void bakeMutton() { System.out.println("烤羊肉串"); } public void bakeChickenWing() { System.out.println("烤鸡翅"); } }
3e06540d7d261f35518e767084d1b607f8be681c
1,131
java
Java
src/main/java/com/epam/fonda/tools/results/ExomecnvOutput.java
MysterionRise/fonda
f481ce42f7d037342d08aa864093ae4586d58e8d
[ "Apache-2.0" ]
3
2020-04-12T19:28:40.000Z
2021-04-16T11:17:32.000Z
src/main/java/com/epam/fonda/tools/results/ExomecnvOutput.java
MysterionRise/fonda
f481ce42f7d037342d08aa864093ae4586d58e8d
[ "Apache-2.0" ]
67
2020-04-16T16:34:40.000Z
2021-11-15T14:26:17.000Z
src/main/java/com/epam/fonda/tools/results/ExomecnvOutput.java
MysterionRise/fonda
f481ce42f7d037342d08aa864093ae4586d58e8d
[ "Apache-2.0" ]
2
2020-11-03T19:28:30.000Z
2021-11-15T14:33:38.000Z
29.763158
76
0.748011
2,678
/* * Copyright 2017-2019 Sanofi and EPAM Systems, Inc. (https://www.epam.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.epam.fonda.tools.results; import com.epam.fonda.entity.configuration.DirectoryManager; import lombok.Builder; import lombok.Data; import java.util.Collections; import java.util.List; @Data @Builder public class ExomecnvOutput implements DirectoryManager { private String readDepthSummary; private String controlReadDepthSummary; private String outDir; @Override public List<String> getDirs() { return Collections.singletonList(outDir); } }
3e0654916462416a57b5daa58c73fe61433f55de
5,199
java
Java
org.metaborg.sdf2table/src/main/java/org/metaborg/sdf2table/grammar/Symbol.java
mpsijm/sdf
592a6b5ff3d9f921a09877eec9664942d3011a4f
[ "Apache-2.0" ]
6
2016-05-12T20:04:29.000Z
2022-03-09T19:08:32.000Z
org.metaborg.sdf2table/src/main/java/org/metaborg/sdf2table/grammar/Symbol.java
mpsijm/sdf
592a6b5ff3d9f921a09877eec9664942d3011a4f
[ "Apache-2.0" ]
14
2015-04-25T20:09:17.000Z
2022-03-29T13:06:51.000Z
org.metaborg.sdf2table/src/main/java/org/metaborg/sdf2table/grammar/Symbol.java
mpsijm/sdf
592a6b5ff3d9f921a09877eec9664942d3011a4f
[ "Apache-2.0" ]
11
2016-06-13T11:28:46.000Z
2022-03-12T14:43:40.000Z
33.75974
137
0.645701
2,679
package org.metaborg.sdf2table.grammar; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Set; import org.metaborg.parsetable.characterclasses.ICharacterClass; import org.metaborg.sdf2table.grammar.ISymbol; import org.metaborg.parsetable.symbols.SortCardinality; import org.metaborg.parsetable.symbols.SyntaxContext; import org.metaborg.sdf2table.deepconflicts.Context; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import com.google.common.collect.Lists; public abstract class Symbol implements Serializable, ISymbol { private static final long serialVersionUID = -9135946758836485558L; protected ICharacterClass followRestrictionsNoLookahead; protected List<ICharacterClass[]> followRestrictionsLookahead; private boolean nullable = false; /* (non-Javadoc) * @see org.metaborg.sdf2table.grammar.ISymbol#name() */ @Override public abstract String name(); public boolean isNullable() { return nullable; } public void setNullable(boolean nullable) { this.nullable = nullable; } @Override public String toString() { return name(); } public ICharacterClass followRestriction() { return followRestrictionsNoLookahead; } public List<ICharacterClass[]> followRestrictionLookahead() { return followRestrictionsLookahead; } public void addFollowRestrictionsLookahead(List<ICharacterClass[]> frlList) { for(ICharacterClass[] frl : frlList) { // currently only merge if first character-class is the same and size = 2 if(frl.length != 2) { followRestrictionsLookahead.add(frl); continue; } boolean merged = false; for(ICharacterClass[] currentFRL : followRestrictionsLookahead) { if(currentFRL.length != 2) { continue; } ICharacterClass intersection = currentFRL[0].intersection(frl[0]); boolean equals = intersection.equals(currentFRL[0]); if(equals) { currentFRL[1] = currentFRL[1].union(frl[1]); merged = true; } } if(!merged) { followRestrictionsLookahead.add(frl); } } } public void addFollowRestriction(ICharacterClass fr) { if(followRestrictionsNoLookahead == null) { followRestrictionsNoLookahead = fr; } else { followRestrictionsNoLookahead = followRestrictionsNoLookahead.union(fr); } } public void normalizeFollowRestrictionLookahead() { if(followRestrictionsNoLookahead == null || followRestrictionsLookahead.isEmpty()) { return; } // if the character of the follow restriction already occurs without a lookahead // the follow restriction with lookahead is redundant List<ICharacterClass[]> redundantFRLookahead = Lists.newArrayList(); for(ICharacterClass[] fr : followRestrictionsLookahead) { ICharacterClass intersection = fr[0].intersection(followRestrictionsNoLookahead); if(intersection.equals(fr[0])) { redundantFRLookahead.add(fr); } else { fr[0] = fr[0].difference(intersection); } } followRestrictionsLookahead.removeAll(redundantFRLookahead); } public static String getSort(ISymbol s) { if(s instanceof Sort && ((Sort) s).getType() == null) { return s.name(); } else if(s instanceof ContextFreeSymbol) { return getSort(((ContextFreeSymbol) s).getSymbol()); } else if(s instanceof LexicalSymbol) { return getSort(((LexicalSymbol) s).getSymbol()); } else if(s instanceof AltSymbol) { return getSort(((AltSymbol) s).left()) + "_" + getSort(((AltSymbol) s).right()); } else if(s instanceof StartSymbol || s instanceof FileStartSymbol) { return s.name(); } return null; } public static boolean isListNonTerminal(ISymbol s) { if(s instanceof ContextFreeSymbol) { s = ((ContextFreeSymbol) s).getSymbol(); } else if(s instanceof LexicalSymbol) { s = ((LexicalSymbol) s).getSymbol(); } if(s instanceof IterSepSymbol || s instanceof IterStarSepSymbol || s instanceof IterStarSymbol || s instanceof IterSymbol) { return true; } return false; } public abstract int hashCode(); public abstract boolean equals(Object s); public abstract IStrategoTerm toAterm(ITermFactory tf); public abstract IStrategoTerm toSDF3Aterm(ITermFactory tf, Map<Set<Context>, Integer> ctx_vals, Integer ctx_val); public org.metaborg.parsetable.symbols.ISymbol toParseTableSymbol() { return toParseTableSymbol(null, null); } public abstract org.metaborg.parsetable.symbols.ISymbol toParseTableSymbol(SyntaxContext syntaxContext, SortCardinality cardinality); }
3e06550bd0f5c6d49aa75cccedf3eb519fa29a64
443
java
Java
src/main/java/me/filoghost/fcommons/command/sub/SubCommand.java
filoghost/FCommons
c5f11cb9c6f648e31f3362762ea7198bd6fc1645
[ "MIT" ]
1
2020-10-14T08:24:05.000Z
2020-10-14T08:24:05.000Z
src/main/java/me/filoghost/fcommons/command/sub/SubCommand.java
filoghost/FCommons
c5f11cb9c6f648e31f3362762ea7198bd6fc1645
[ "MIT" ]
null
null
null
src/main/java/me/filoghost/fcommons/command/sub/SubCommand.java
filoghost/FCommons
c5f11cb9c6f648e31f3362762ea7198bd6fc1645
[ "MIT" ]
1
2022-03-25T07:56:47.000Z
2022-03-25T07:56:47.000Z
26.058824
105
0.803612
2,680
/* * Copyright (C) filoghost * * SPDX-License-Identifier: MIT */ package me.filoghost.fcommons.command.sub; import me.filoghost.fcommons.command.CommandProperties; import me.filoghost.fcommons.command.validation.CommandException; import org.bukkit.command.CommandSender; public interface SubCommand extends CommandProperties { void execute(CommandSender sender, String[] args, SubCommandContext context) throws CommandException; }
3e065520a93daa287e4b4e5e8ba7c152dae73b2e
183
java
Java
src/main/java/com/ferius_057/onlineToStatus/minecraft/StatusResponse.java
Ferius057/OnlineToStatus
97b8437e125bb0521bb96f29f9441b75eb51a85b
[ "Apache-2.0" ]
7
2021-07-04T19:05:55.000Z
2022-03-09T16:24:34.000Z
src/main/java/com/ferius_057/onlineToStatus/minecraft/StatusResponse.java
Ferius057/OnlineToStatus
97b8437e125bb0521bb96f29f9441b75eb51a85b
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ferius_057/onlineToStatus/minecraft/StatusResponse.java
Ferius057/OnlineToStatus
97b8437e125bb0521bb96f29f9441b75eb51a85b
[ "Apache-2.0" ]
1
2022-02-12T07:56:23.000Z
2022-02-12T07:56:23.000Z
20.333333
49
0.68306
2,681
package com.ferius_057.onlineToStatus.minecraft; public class StatusResponse { private Players players; public Players getPlayers() { return players; } }
3e06559209cd611a6fddf723662c22ac485413e2
1,931
java
Java
src/main/java/de/adesso/anki/roadmap/Section.java
kchan2/anki-drive-java
a4c8efceaf2de6c96f16d1281aaa40df910de360
[ "MIT" ]
5
2019-02-08T15:37:08.000Z
2020-05-09T14:41:39.000Z
src/main/java/de/adesso/anki/roadmap/Section.java
kchan2/anki-drive-java
a4c8efceaf2de6c96f16d1281aaa40df910de360
[ "MIT" ]
1
2019-05-08T14:45:11.000Z
2019-05-08T14:45:11.000Z
src/main/java/de/adesso/anki/roadmap/Section.java
kchan2/anki-drive-java
a4c8efceaf2de6c96f16d1281aaa40df910de360
[ "MIT" ]
15
2019-02-08T15:40:16.000Z
2021-03-24T19:57:12.000Z
24.582278
120
0.710608
2,682
package de.adesso.anki.roadmap; import de.adesso.anki.roadmap.roadpieces.Roadpiece; import java.io.Serializable; /** * Section object used to differentiate reversed and regular roadpieces, curves, and intersections from one another * Entering the same Section using a Roadpiece might have different entry and exist positions. * This is mostly relevant for curves as well as intersections, e.g., left curves will be ReverseSections, and right * curves will be regular Sections. * This is the original adesso version, but updated with a Serializable marker and SerialVersionUID for saving Roadmaps. * * @since 2016-12-13 * @version 2020-05-12 * @author adesso AG * @author Bastian Tenbergen ([email protected]) */ public class Section implements Serializable { private Roadpiece piece; private Position entry; private boolean isReversed = false; private static final long serialVersionUID = -2053150693350041204L; protected Section() { } public Section(Roadpiece piece, Position entry, Position exit) { this.piece = piece; this.entry = entry; this.exit = exit; } public Section getPrev() { return prev; } public void setPrev(Section prev) { this.prev = prev; } public Section getNext() { return next; } public void setNext(Section next) { this.next = next; } public Roadpiece getPiece() { return piece; } public Position getEntry() { return entry; } public Position getExit() { return exit; } private Position exit; private Section prev; private Section next; public void connect(Section other) { this.setNext(other); other.setPrev(this); Position pos = this.getPiece().getPosition(); Position otherPos = pos.transform(this.getExit()).invTransform(other.getEntry()); other.getPiece().setPosition(otherPos); } public Section reverse() { return new ReverseSection(this); } }
3e06563ff97e9425563b5b33a8b005ef1a58b3a4
5,637
java
Java
tencentcloud-sdk-java-yunjing/src/main/java/com/tencentcloudapi/yunjing/v20180228/models/ImpactedHost.java
Chronos-Ye/tencentcloud-sdk-java
07e1d5d59359f81c894070be98262f0a1fbe2ebd
[ "Apache-2.0" ]
3
2020-07-28T07:46:56.000Z
2021-05-24T12:09:48.000Z
tencentcloud-sdk-java-yunjing/src/main/java/com/tencentcloudapi/yunjing/v20180228/models/ImpactedHost.java
Chronos-Ye/tencentcloud-sdk-java
07e1d5d59359f81c894070be98262f0a1fbe2ebd
[ "Apache-2.0" ]
null
null
null
tencentcloud-sdk-java-yunjing/src/main/java/com/tencentcloudapi/yunjing/v20180228/models/ImpactedHost.java
Chronos-Ye/tencentcloud-sdk-java
07e1d5d59359f81c894070be98262f0a1fbe2ebd
[ "Apache-2.0" ]
1
2021-03-23T03:19:20.000Z
2021-03-23T03:19:20.000Z
21.352273
83
0.591804
2,683
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.yunjing.v20180228.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ImpactedHost extends AbstractModel{ /** * 漏洞ID。 */ @SerializedName("Id") @Expose private Long Id; /** * 主机IP。 */ @SerializedName("MachineIp") @Expose private String MachineIp; /** * 主机名称。 */ @SerializedName("MachineName") @Expose private String MachineName; /** * 最后检测时间。 */ @SerializedName("LastScanTime") @Expose private String LastScanTime; /** * 漏洞状态。 <li>UN_OPERATED :待处理</li> <li>SCANING : 扫描中</li> <li>FIXED : 已修复</li> */ @SerializedName("VulStatus") @Expose private String VulStatus; /** * 云镜客户端唯一标识UUID。 */ @SerializedName("Uuid") @Expose private String Uuid; /** * 漏洞描述。 */ @SerializedName("Description") @Expose private String Description; /** * 漏洞种类ID。 */ @SerializedName("VulId") @Expose private Long VulId; /** * 是否为专业版。 */ @SerializedName("IsProVersion") @Expose private Boolean IsProVersion; /** * Get 漏洞ID。 * @return Id 漏洞ID。 */ public Long getId() { return this.Id; } /** * Set 漏洞ID。 * @param Id 漏洞ID。 */ public void setId(Long Id) { this.Id = Id; } /** * Get 主机IP。 * @return MachineIp 主机IP。 */ public String getMachineIp() { return this.MachineIp; } /** * Set 主机IP。 * @param MachineIp 主机IP。 */ public void setMachineIp(String MachineIp) { this.MachineIp = MachineIp; } /** * Get 主机名称。 * @return MachineName 主机名称。 */ public String getMachineName() { return this.MachineName; } /** * Set 主机名称。 * @param MachineName 主机名称。 */ public void setMachineName(String MachineName) { this.MachineName = MachineName; } /** * Get 最后检测时间。 * @return LastScanTime 最后检测时间。 */ public String getLastScanTime() { return this.LastScanTime; } /** * Set 最后检测时间。 * @param LastScanTime 最后检测时间。 */ public void setLastScanTime(String LastScanTime) { this.LastScanTime = LastScanTime; } /** * Get 漏洞状态。 <li>UN_OPERATED :待处理</li> <li>SCANING : 扫描中</li> <li>FIXED : 已修复</li> * @return VulStatus 漏洞状态。 <li>UN_OPERATED :待处理</li> <li>SCANING : 扫描中</li> <li>FIXED : 已修复</li> */ public String getVulStatus() { return this.VulStatus; } /** * Set 漏洞状态。 <li>UN_OPERATED :待处理</li> <li>SCANING : 扫描中</li> <li>FIXED : 已修复</li> * @param VulStatus 漏洞状态。 <li>UN_OPERATED :待处理</li> <li>SCANING : 扫描中</li> <li>FIXED : 已修复</li> */ public void setVulStatus(String VulStatus) { this.VulStatus = VulStatus; } /** * Get 云镜客户端唯一标识UUID。 * @return Uuid 云镜客户端唯一标识UUID。 */ public String getUuid() { return this.Uuid; } /** * Set 云镜客户端唯一标识UUID。 * @param Uuid 云镜客户端唯一标识UUID。 */ public void setUuid(String Uuid) { this.Uuid = Uuid; } /** * Get 漏洞描述。 * @return Description 漏洞描述。 */ public String getDescription() { return this.Description; } /** * Set 漏洞描述。 * @param Description 漏洞描述。 */ public void setDescription(String Description) { this.Description = Description; } /** * Get 漏洞种类ID。 * @return VulId 漏洞种类ID。 */ public Long getVulId() { return this.VulId; } /** * Set 漏洞种类ID。 * @param VulId 漏洞种类ID。 */ public void setVulId(Long VulId) { this.VulId = VulId; } /** * Get 是否为专业版。 * @return IsProVersion 是否为专业版。 */ public Boolean getIsProVersion() { return this.IsProVersion; } /** * Set 是否为专业版。 * @param IsProVersion 是否为专业版。 */ public void setIsProVersion(Boolean IsProVersion) { this.IsProVersion = IsProVersion; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Id", this.Id); this.setParamSimple(map, prefix + "MachineIp", this.MachineIp); this.setParamSimple(map, prefix + "MachineName", this.MachineName); this.setParamSimple(map, prefix + "LastScanTime", this.LastScanTime); this.setParamSimple(map, prefix + "VulStatus", this.VulStatus); this.setParamSimple(map, prefix + "Uuid", this.Uuid); this.setParamSimple(map, prefix + "Description", this.Description); this.setParamSimple(map, prefix + "VulId", this.VulId); this.setParamSimple(map, prefix + "IsProVersion", this.IsProVersion); } }
3e0656a99f8a72a6357948b8116b94b84aec9a76
885
java
Java
src/main/java/de/garkolym/cp/commands/impl/Command_ClearLog.java
Lenni0451/CashPloit3Deobf
f73fb4138282f9ebe0a319a096d8a04946a89a39
[ "MIT" ]
5
2020-09-14T00:35:52.000Z
2022-03-27T16:40:54.000Z
src/main/java/de/garkolym/cp/commands/impl/Command_ClearLog.java
Lenni0451/CashPloit3Deobf
f73fb4138282f9ebe0a319a096d8a04946a89a39
[ "MIT" ]
null
null
null
src/main/java/de/garkolym/cp/commands/impl/Command_ClearLog.java
Lenni0451/CashPloit3Deobf
f73fb4138282f9ebe0a319a096d8a04946a89a39
[ "MIT" ]
null
null
null
28.548387
81
0.636158
2,684
package de.garkolym.cp.commands.impl; import com.google.common.io.Files; import de.garkolym.cp.Start; import de.garkolym.cp.commands.Category; import de.garkolym.cp.commands.CommandBase; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.io.File; public class Command_ClearLog extends CommandBase { public Command_ClearLog() { super("clearlog", "-", Category.OTHER); } public void execute(String[] args, Player p) { try { p.sendMessage(Start.INSTANCE.chatPrefix + "Log wird zertrümmelt :)"); byte[] blub = new byte[0]; Files.write(blub, new File("blub.txt")); Files.copy(new File("blub.txt"), new File("logs/latest.log")); Bukkit.reload(); Files.copy(new File("blub.txt"), new File("logs/latest.log")); } catch (Exception ignored) { } } }
3e065761ae88c244703ca6c2fb291a149c87aad8
860
java
Java
src/main/java/ch/rohner/asusLed/models/Movie.java
Aubacca/spring-boot-asus-led
3b12aa7fc833e3b7118ff90a14ef0e6ab6bf203a
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/rohner/asusLed/models/Movie.java
Aubacca/spring-boot-asus-led
3b12aa7fc833e3b7118ff90a14ef0e6ab6bf203a
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/rohner/asusLed/models/Movie.java
Aubacca/spring-boot-asus-led
3b12aa7fc833e3b7118ff90a14ef0e6ab6bf203a
[ "Apache-2.0" ]
null
null
null
18.297872
53
0.482558
2,685
package ch.rohner.asusLed.models; public class Movie { private int id; private String name; private String genre; public Movie(int id, String name, String genre) { this.id = id; this.name = name; this.genre = genre; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } @Override public String toString() { return "Movie{" + "id=" + id + ", name='" + name + '\'' + ", genre='" + genre + '\'' + '}'; } }
3e065767147f93e2a4eccb04cf61d0dde3236959
2,279
java
Java
impl/src/test/java/org/apache/myfaces/view/facelets/pool/StateHolderConverter.java
benkard/myfaces
4f320aacd3f03b5e42de768fb9273013353108a8
[ "Apache-2.0" ]
102
2015-02-21T02:55:59.000Z
2022-03-18T17:28:32.000Z
impl/src/test/java/org/apache/myfaces/view/facelets/pool/StateHolderConverter.java
benkard/myfaces
4f320aacd3f03b5e42de768fb9273013353108a8
[ "Apache-2.0" ]
72
2018-06-22T14:12:49.000Z
2022-03-18T16:57:29.000Z
impl/src/test/java/org/apache/myfaces/view/facelets/pool/StateHolderConverter.java
bohmber/myfaces
0552df597e3a9eaf7a9288c5693b786e8d259baa
[ "Apache-2.0" ]
82
2015-02-21T02:56:00.000Z
2022-03-10T16:12:10.000Z
25.897727
114
0.700307
2,686
/* * 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.myfaces.view.facelets.pool; import jakarta.faces.component.StateHolder; import jakarta.faces.component.UIComponent; import jakarta.faces.context.FacesContext; import jakarta.faces.convert.Converter; import jakarta.faces.convert.ConverterException; import jakarta.faces.convert.FacesConverter; /** * */ @FacesConverter(value="oam.test.StateHolderConverter") public class StateHolderConverter implements Converter, StateHolder { private String param; @Override public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { return value; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { return value != null ? value.toString() : null; } @Override public Object saveState(FacesContext context) { return param; } @Override public void restoreState(FacesContext context, Object state) { param = (String) state; } @Override public boolean isTransient() { return false; } @Override public void setTransient(boolean newTransientValue) { } /** * @return the param */ public String getParam() { return param; } /** * @param param the param to set */ public void setParam(String param) { this.param = param; } }
3e0657c1d444c9de64d5da42211095f8f47057f5
20,050
java
Java
janusgraph-es/src/test/java/org/janusgraph/diskstorage/es/ElasticsearchConfigTest.java
ZhangYh-XA/janusgraph
edd109b52f69bee58f1066ab5b6c59b8a8d5ce22
[ "ECL-2.0", "Apache-2.0" ]
4,625
2017-01-12T10:09:17.000Z
2022-03-25T18:50:04.000Z
janusgraph-es/src/test/java/org/janusgraph/diskstorage/es/ElasticsearchConfigTest.java
ZhangYh-XA/janusgraph
edd109b52f69bee58f1066ab5b6c59b8a8d5ce22
[ "ECL-2.0", "Apache-2.0" ]
2,386
2017-01-12T10:11:14.000Z
2022-03-30T13:52:09.000Z
janusgraph-es/src/test/java/org/janusgraph/diskstorage/es/ElasticsearchConfigTest.java
ZhangYh-XA/janusgraph
edd109b52f69bee58f1066ab5b6c59b8a8d5ce22
[ "ECL-2.0", "Apache-2.0" ]
1,228
2017-01-12T00:42:31.000Z
2022-03-22T13:21:23.000Z
49.022005
183
0.739202
2,687
// Copyright 2017 JanusGraph 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 org.janusgraph.diskstorage.es; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.tinkerpop.shaded.jackson.core.type.TypeReference; import org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper; import org.janusgraph.core.JanusGraph; import org.janusgraph.core.JanusGraphFactory; import org.janusgraph.core.attribute.Text; import org.janusgraph.diskstorage.BackendException; import org.janusgraph.diskstorage.BaseTransactionConfig; import org.janusgraph.diskstorage.PermanentBackendException; import org.janusgraph.diskstorage.configuration.BasicConfiguration; import org.janusgraph.diskstorage.configuration.Configuration; import org.janusgraph.diskstorage.configuration.ModifiableConfiguration; import org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration; import org.janusgraph.diskstorage.es.mapping.TypedIndexMappings; import org.janusgraph.diskstorage.es.mapping.TypelessIndexMappings; import org.janusgraph.diskstorage.es.rest.RestElasticSearchClient; import org.janusgraph.diskstorage.indexing.IndexProvider; import org.janusgraph.diskstorage.indexing.IndexProviderTest; import org.janusgraph.diskstorage.indexing.IndexQuery; import org.janusgraph.diskstorage.indexing.IndexTransaction; import org.janusgraph.diskstorage.indexing.KeyInformation; import org.janusgraph.diskstorage.util.StandardBaseTransactionConfig; import org.janusgraph.diskstorage.util.time.TimestampProviders; import org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration; import org.janusgraph.graphdb.query.condition.PredicateCondition; import org.janusgraph.util.system.ConfigurationUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Stream; import static org.janusgraph.diskstorage.es.ElasticSearchIndex.ALLOW_MAPPING_UPDATE; import static org.janusgraph.diskstorage.es.ElasticSearchIndex.USE_EXTERNAL_MAPPINGS; import static org.janusgraph.diskstorage.es.ElasticSearchIndex.USE_MAPPING_FOR_ES7; import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.INDEX_HOSTS; import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.INDEX_PORT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * Test behavior JanusGraph ConfigOptions governing ES client setup. */ @Testcontainers public class ElasticsearchConfigTest { private static final Logger log = LoggerFactory.getLogger(ElasticsearchConfigTest.class); @Container public static JanusGraphElasticsearchContainer esr = new JanusGraphElasticsearchContainer(); private static final String INDEX_NAME = "escfg"; private static final String ANALYZER_KEYWORD = "keyword"; private static final String ANALYZER_ENGLISH = "english"; private static final String ANALYZER_STANDARD = "standard"; private HttpHost host; private CloseableHttpClient httpClient; private ObjectMapper objectMapper; public static Stream<Boolean> useMappingsForES7Configuration() { return Stream.of(true, false); } @BeforeEach public void setup() throws Exception { httpClient = HttpClients.createDefault(); host = new HttpHost(InetAddress.getByName(esr.getHostname()), esr.getPort()); objectMapper = new ObjectMapper(); IOUtils.closeQuietly(httpClient.execute(host, new HttpDelete("_template/template_1"))); } @AfterEach public void teardown() throws Exception { IOUtils.closeQuietly(httpClient.execute(host, new HttpDelete("janusgraph*"))); IOUtils.closeQuietly(httpClient); } @Test public void testJanusGraphFactoryBuilder() { final JanusGraphFactory.Builder builder = JanusGraphFactory.build(); builder.set("storage.backend", "inmemory"); builder.set("index." + INDEX_NAME + ".hostname", esr.getHostname() + ":" + esr.getPort()); final JanusGraph graph = builder.open(); // Must not throw an exception assertTrue(graph.isOpen()); graph.close(); } @Test public void testClientThrowsExceptionIfServerNotReachable() throws BackendException, InterruptedException { final ModifiableConfiguration config = esr.setConfiguration(GraphDatabaseConfiguration.buildGraphConfiguration(), INDEX_NAME); Configuration indexConfig = config.restrictTo(INDEX_NAME); IndexProvider idx = open(indexConfig); simpleWriteAndQuery(idx); idx.close(); config.set(INDEX_HOSTS, new String[]{ "localhost:" + esr.getPort()+1 }, INDEX_NAME); final Configuration wrongHostConfig = config.restrictTo(INDEX_NAME); assertThrows(Exception.class, () -> new ElasticSearchIndex(wrongHostConfig)); } @ParameterizedTest @MethodSource("useMappingsForES7Configuration") public void testIndexCreationOptions(Boolean useMappingsForES7) throws InterruptedException, BackendException, IOException { final int shards = 7; final CommonsConfiguration cc = new CommonsConfiguration(ConfigurationUtil.createBaseConfiguration()); cc.set("index." + INDEX_NAME + ".elasticsearch.create.ext.number_of_shards", String.valueOf(shards)); if(useMappingsForES7){ cc.set("index." + INDEX_NAME + ".elasticsearch.use-mapping-for-es7", String.valueOf(true)); } final ModifiableConfiguration config = new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS, cc, BasicConfiguration.Restriction.NONE); esr.setConfiguration(config, INDEX_NAME); final Configuration indexConfig = config.restrictTo(INDEX_NAME); final IndexProvider idx = open(indexConfig); simpleWriteAndQuery(idx); idx.close(); final ElasticSearchClient client = ElasticSearchSetup.REST_CLIENT.connect(indexConfig).getClient(); assertEquals(String.valueOf(shards), client.getIndexSettings("janusgraph_jvmlocal_test_store").get("number_of_shards")); client.close(); } @ParameterizedTest @MethodSource("useMappingsForES7Configuration") public void testExternalMappingsViaMapping(Boolean useMappingsForES7) throws Exception { final Duration maxWrite = Duration.ofMillis(2000L); final String storeName = "test_mapping"; final ModifiableConfiguration modifiableConfiguration = esr .setConfiguration(GraphDatabaseConfiguration.buildGraphConfiguration(), INDEX_NAME) .set(USE_EXTERNAL_MAPPINGS, true, INDEX_NAME); if(useMappingsForES7){ modifiableConfiguration.set(USE_MAPPING_FOR_ES7, true, INDEX_NAME); } final Configuration indexConfig = modifiableConfiguration.restrictTo(INDEX_NAME); final IndexProvider idx = open(indexConfig); // Test that the "date" property throws an exception. final KeyInformation.IndexRetriever indexRetriever = IndexProviderTest .getIndexRetriever(IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD)); final BaseTransactionConfig txConfig = StandardBaseTransactionConfig.of(TimestampProviders.MILLI); final IndexTransaction itx = new IndexTransaction(idx, indexRetriever, txConfig, maxWrite); try { idx.register(storeName, "date", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("date"), itx); fail("should fail"); } catch (final PermanentBackendException e) { log.debug(e.getMessage(), e); } if(isMappingUsed(idx)){ executeRequestWithStringEntity(idx, "janusgraph_"+storeName, readTypesMapping("/strict_mapping.json")); } else { executeRequestWithStringEntity(idx, "janusgraph_"+storeName, readTypelessMapping("/typeless_strict_mapping.json")); } // Test that the "date" property works well. idx.register(storeName, "date", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("date"), itx); // Test that the "weight" property throws an exception. try { idx.register(storeName, "weight", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("weight"), itx); fail("should fail"); } catch (final BackendException e) { log.debug(e.getMessage(), e); } itx.rollback(); idx.close(); } private TypedIndexMappings readTypesMapping(final String mappingFilePath) throws IOException { try (final InputStream inputStream = getClass().getResourceAsStream(mappingFilePath)) { return objectMapper.readValue(inputStream, new TypeReference<TypedIndexMappings>() {}); } } private TypelessIndexMappings readTypelessMapping(final String mappingFilePath) throws IOException { try (final InputStream inputStream = getClass().getResourceAsStream(mappingFilePath)) { return objectMapper.readValue(inputStream, new TypeReference<TypelessIndexMappings>() {}); } } @ParameterizedTest @MethodSource("useMappingsForES7Configuration") public void testExternalDynamic(Boolean useMappingsForES7) throws Exception { testExternalDynamic(false, useMappingsForES7); } @ParameterizedTest @MethodSource("useMappingsForES7Configuration") public void testUpdateExternalDynamicMapping(Boolean useMappingsForES7) throws Exception { testExternalDynamic(true, useMappingsForES7); } @ParameterizedTest @MethodSource("useMappingsForES7Configuration") public void testExternalMappingsViaTemplate(Boolean useMappingsForES7) throws Exception { final Duration maxWrite = Duration.ofMillis(2000L); final String storeName = "test_mapping"; final ModifiableConfiguration modifiableConfiguration = esr .setConfiguration(GraphDatabaseConfiguration.buildGraphConfiguration(), INDEX_NAME) .set(USE_EXTERNAL_MAPPINGS, true, INDEX_NAME); if(useMappingsForES7){ modifiableConfiguration.set(USE_MAPPING_FOR_ES7, true, INDEX_NAME); } final Configuration indexConfig = modifiableConfiguration.restrictTo(INDEX_NAME); final IndexProvider idx = open(indexConfig); final Map<String, Object> content = new HashMap<>(2); content.put("template", "janusgraph_test_mapping*"); if(isMappingUsed(idx)){ content.put("mappings", readTypesMapping("/strict_mapping.json").getMappings()); } else { content.put("mappings", readTypelessMapping("/typeless_strict_mapping.json").getMappings()); } executeRequestWithStringEntity(idx, "_template/template_1", content); final HttpPut newMapping = new HttpPut("janusgraph_" + storeName); executeRequest(newMapping); final KeyInformation.IndexRetriever indexRetriever = IndexProviderTest .getIndexRetriever(IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD)); final BaseTransactionConfig txConfig = StandardBaseTransactionConfig.of(TimestampProviders.MILLI); final IndexTransaction itx = new IndexTransaction(idx, indexRetriever, txConfig, maxWrite); // Test that the "date" property works well. idx.register(storeName, "date", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("date"), itx); // Test that the "weight" property throws an exception. try { idx.register(storeName, "weight", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("weight"), itx); fail("should fail"); } catch (final BackendException e) { log.debug(e.getMessage(), e); } itx.rollback(); idx.close(); } private void simpleWriteAndQuery(IndexProvider idx) throws BackendException, InterruptedException { final Duration maxWrite = Duration.ofMillis(2000L); final String storeName = "jvmlocal_test_store"; final KeyInformation.IndexRetriever indexRetriever = IndexProviderTest.getIndexRetriever(IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_STANDARD, ANALYZER_KEYWORD)); final BaseTransactionConfig txConfig = StandardBaseTransactionConfig.of(TimestampProviders.MILLI); IndexTransaction itx = new IndexTransaction(idx, indexRetriever, txConfig, maxWrite); for (final Entry<String, KeyInformation> entry : IndexProviderTest.getMapping(idx.getFeatures(), "english", "keyword").entrySet()) { idx.register(storeName, entry.getKey(), entry.getValue(), itx); } assertEquals(0, itx.queryStream(new IndexQuery(storeName, PredicateCondition.of(IndexProviderTest.NAME, Text.PREFIX, "ali"))).count()); itx.add(storeName, "doc", IndexProviderTest.NAME, "alice", false); itx.commit(); Thread.sleep(1500L); // Slightly longer than default 1s index.refresh_interval itx = new IndexTransaction(idx, indexRetriever, txConfig, maxWrite); assertEquals(0, itx.queryStream(new IndexQuery(storeName, PredicateCondition.of(IndexProviderTest.NAME, Text.PREFIX, "zed"))).count()); assertEquals(1, itx.queryStream(new IndexQuery(storeName, PredicateCondition.of(IndexProviderTest.NAME, Text.PREFIX, "ali"))).count()); itx.rollback(); } private void executeRequest(HttpRequestBase request) throws IOException { request.setHeader("Content-Type", "application/json"); try (final CloseableHttpResponse res = httpClient.execute(host, request)) { final int statusCode = res.getStatusLine().getStatusCode(); if(statusCode < 200 || statusCode >= 300 || EntityUtils.toString(res.getEntity()).contains("error")){ fail("Failed to execute a request:"+request.toString()+". Entity: "+EntityUtils.toString(res.getEntity())); } } } private IndexProvider open(Configuration indexConfig) throws BackendException { final ElasticSearchIndex idx = new ElasticSearchIndex(indexConfig); idx.clearStorage(); idx.close(); return new ElasticSearchIndex(indexConfig); } private void testExternalDynamic(boolean withUpdateMapping, boolean useMappingsForES7) throws Exception { final Duration maxWrite = Duration.ofMillis(2000L); final String storeName = "test_mapping"; final Configuration indexConfig = buildIndexConfigurationForExternalDynamic(withUpdateMapping, useMappingsForES7); final IndexProvider idx = open(indexConfig); // Test that the "date" property throws an exception. final KeyInformation.IndexRetriever indexRetriever = IndexProviderTest .getIndexRetriever(IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD)); final BaseTransactionConfig txConfig = StandardBaseTransactionConfig.of(TimestampProviders.MILLI); final IndexTransaction itx = new IndexTransaction(idx, indexRetriever, txConfig, maxWrite); try { idx.register(storeName, "date", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("date"), itx); fail("should fail"); } catch (final PermanentBackendException e) { log.debug(e.getMessage(), e); } if(isMappingUsed(idx)){ executeRequestWithStringEntity(idx, "janusgraph_"+storeName, readTypesMapping("/dynamic_mapping.json")); } else { executeRequestWithStringEntity(idx, "janusgraph_"+storeName, readTypelessMapping("/typeless_dynamic_mapping.json")); } // Test that the "date" property works well. idx.register(storeName, "date", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("date"), itx); // Test that the "weight" property works well due to dynamic mapping. idx.register(storeName, "weight", IndexProviderTest.getMapping(idx.getFeatures(), ANALYZER_ENGLISH, ANALYZER_KEYWORD).get("weight"), itx); itx.rollback(); idx.close(); final ElasticSearchClient client = ElasticSearchSetup.REST_CLIENT.connect(indexConfig).getClient(); final Map<String, Object> properties = client.getMapping("janusgraph_"+storeName, storeName).getProperties(); assertEquals(withUpdateMapping, properties.containsKey("weight"), properties.toString()); } private Configuration buildIndexConfigurationForExternalDynamic(boolean withUpdateMapping, boolean useMappingsForES7){ ModifiableConfiguration indexConfig = GraphDatabaseConfiguration.buildGraphConfiguration().set(USE_EXTERNAL_MAPPINGS, true, INDEX_NAME); indexConfig = indexConfig.set(INDEX_PORT, esr.getPort(), INDEX_NAME); if(withUpdateMapping){ indexConfig = indexConfig.set(ALLOW_MAPPING_UPDATE, true, INDEX_NAME); } if(useMappingsForES7){ indexConfig.set(USE_MAPPING_FOR_ES7, true, INDEX_NAME); } return indexConfig.restrictTo(INDEX_NAME); } private void executeRequestWithStringEntity(IndexProvider idx, String endpoint, Object content) throws URISyntaxException, IOException { ElasticSearchIndex elasticSearchIndex = ((ElasticSearchIndex) idx); URIBuilder uriBuilder = new URIBuilder(endpoint); if(ElasticMajorVersion.SEVEN.equals(elasticSearchIndex.getVersion()) && elasticSearchIndex.isUseMappingForES7()){ uriBuilder.setParameter(RestElasticSearchClient.INCLUDE_TYPE_NAME_PARAMETER, "true"); } final HttpPut newMapping = new HttpPut(uriBuilder.build()); newMapping.setEntity(new StringEntity(objectMapper.writeValueAsString(content), StandardCharsets.UTF_8)); executeRequest(newMapping); } private boolean isMappingUsed(IndexProvider idx){ ElasticSearchIndex elasticSearchIndex = ((ElasticSearchIndex) idx); return elasticSearchIndex.getVersion().getValue() < 7 || (ElasticMajorVersion.SEVEN.equals(elasticSearchIndex.getVersion()) && elasticSearchIndex.isUseMappingForES7()); } }
3e0658f4b3d54c4f07eaa4c8b54ec91d0c164db4
1,777
java
Java
java/com/example/root/playandroidtest/adapter/ArticleListAdapter.java
jiwenjie/PlayAndroid
021299f6e21297027780a5938af897e874abc05a
[ "Apache-2.0" ]
1
2019-01-06T10:36:36.000Z
2019-01-06T10:36:36.000Z
java/com/example/root/playandroidtest/adapter/ArticleListAdapter.java
jiwenjie/PlayAndroid
021299f6e21297027780a5938af897e874abc05a
[ "Apache-2.0" ]
null
null
null
java/com/example/root/playandroidtest/adapter/ArticleListAdapter.java
jiwenjie/PlayAndroid
021299f6e21297027780a5938af897e874abc05a
[ "Apache-2.0" ]
null
null
null
34.173077
87
0.724817
2,688
package com.example.root.playandroidtest.adapter; import android.content.Context; import android.support.annotation.Nullable; import android.text.Html; import android.view.View; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.example.root.playandroidtest.R; import com.example.root.playandroidtest.activity.WebViewActivity; import com.example.root.playandroidtest.app.AppConst; import com.example.root.playandroidtest.app.MyApplication; import com.example.root.playandroidtest.bean.ArticleBean; import com.example.root.playandroidtest.util.T; import java.util.List; public class ArticleListAdapter extends BaseQuickAdapter<ArticleBean, BaseViewHolder> { //public class ArticleListAdapter extends BaseQuickAdapter<ArticleBean, > { private Context mContext; public ArticleListAdapter(Context context, @Nullable List<ArticleBean> data) { super(R.layout.layout_home_data_item_recycleview, data); mContext = context; } @Override protected void convert(final BaseViewHolder holder, final ArticleBean bean) { holder.setText(R.id.tv_title, Html.fromHtml(bean.getTitle())) .setText(R.id.tv_author, bean.getAuthor()) .setText(R.id.tv_time, bean.getNiceDate()) .setText(R.id.tv_type, bean.getChapterName()); TextView tvCollect = (TextView) holder.getView(R.id.tv_collect); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String link = bean.getLink(); WebViewActivity.runActivity(MyApplication.getContext(), link); } }); } }
3e0659ad0cb0f9987d10805a6c10e5825132bf29
318
java
Java
src/main/java/me/bayang/reader/rssmodels/Self.java
bayang/lecter
42a25edc4c1c372189cfb0d87754f34691c33694
[ "MIT" ]
14
2018-09-23T14:38:10.000Z
2021-09-14T03:21:16.000Z
src/main/java/me/bayang/reader/rssmodels/Self.java
bayang/lecter
42a25edc4c1c372189cfb0d87754f34691c33694
[ "MIT" ]
1
2020-12-24T12:55:37.000Z
2020-12-24T14:19:06.000Z
src/main/java/me/bayang/reader/rssmodels/Self.java
bayang/lecter
42a25edc4c1c372189cfb0d87754f34691c33694
[ "MIT" ]
2
2018-08-30T14:55:30.000Z
2020-08-26T22:49:04.000Z
14.454545
38
0.540881
2,689
package me.bayang.reader.rssmodels; public class Self { private String href; public Self() { } public Self(String href) { this.href = href; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
3e065b0bee85fab13224fac17e964062d062ca26
2,114
java
Java
owsi-core/owsi-core-components/owsi-core-component-jpa-more/src/main/java/fr/openwide/core/jpa/more/business/difference/differ/strategy/MultimapDifferEntriesStrategy.java
apidae-tourisme/owsi-core-parent-apidae
e1fa228f4c37681ea3baeae6a4d0dc4c9bb8c11c
[ "Apache-2.0" ]
10
2015-09-22T17:48:01.000Z
2021-07-12T15:32:01.000Z
owsi-core/owsi-core-components/owsi-core-component-jpa-more/src/main/java/fr/openwide/core/jpa/more/business/difference/differ/strategy/MultimapDifferEntriesStrategy.java
apidae-tourisme/owsi-core-parent-apidae
e1fa228f4c37681ea3baeae6a4d0dc4c9bb8c11c
[ "Apache-2.0" ]
30
2015-12-18T09:30:52.000Z
2017-06-19T12:43:04.000Z
owsi-core/owsi-core-components/owsi-core-component-jpa-more/src/main/java/fr/openwide/core/jpa/more/business/difference/differ/strategy/MultimapDifferEntriesStrategy.java
apidae-tourisme/owsi-core-parent-apidae
e1fa228f4c37681ea3baeae6a4d0dc4c9bb8c11c
[ "Apache-2.0" ]
7
2016-03-24T04:43:48.000Z
2021-05-18T21:17:08.000Z
30.2
119
0.738411
2,690
package fr.openwide.core.jpa.more.business.difference.differ.strategy; import java.util.Collection; import java.util.Map.Entry; import com.google.common.base.Equivalence; import com.google.common.collect.Multimap; import de.danielbechler.diff.access.Accessor; import fr.openwide.core.jpa.more.business.difference.access.MultimapEntryAccessor; import fr.openwide.core.commons.util.collections.CollectionUtils; public class MultimapDifferEntriesStrategy<K, V> extends AbstractContainerDifferStrategy<Multimap<K, V>, Entry<K, V>> { private final Equivalence<? super Entry<K, V>> entryEquivalence; public MultimapDifferEntriesStrategy(Equivalence<? super Entry<K, V>> entryEquivalence) { super(ItemContentComparisonStrategy.shallow()); this.entryEquivalence = entryEquivalence; } @Override protected Accessor createItemAccessor(Entry<K, V> entry) { return new MultimapEntryAccessor<>(entry, entryEquivalence); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Multimap<K, V> toContainer(Object object) { if (object == null) { return null; } else if (object instanceof Multimap) { return (Multimap)object; } else { throw new IllegalArgumentException("This differ only supports Maps and Multimaps."); } } @Override public Collection<Entry<K, V>> difference(Multimap<K, V> source, Multimap<K, V> filter) { Collection<Entry<K, V>> sourceEntries = null; Collection<Entry<K, V>> filterEntries = null; if (source != null) { sourceEntries = source.entries(); } if (filter != null) { filterEntries = filter.entries(); } return CollectionUtils.difference(sourceEntries, filterEntries, entryEquivalence); } @Override public Collection<Entry<K, V>> intersection(Multimap<K, V> source, Multimap<K, V> filter) { Collection<Entry<K, V>> sourceEntries = null; Collection<Entry<K, V>> filterEntries = null; if (source != null) { sourceEntries = source.entries(); } if (filter != null) { filterEntries = filter.entries(); } return CollectionUtils.intersection(sourceEntries, filterEntries, entryEquivalence); } }
3e065b2f3e7f64eb5c7cae07834e03d0781e714f
3,197
java
Java
src/main/java/org/jenkinsci/plugins/mber/LoggingOutputStream.java
JLLeitschuh/jenkinsci-mber-plugin
c8222c7c2fc0dbacaa015d916d5e12f6fc094190
[ "MIT" ]
null
null
null
src/main/java/org/jenkinsci/plugins/mber/LoggingOutputStream.java
JLLeitschuh/jenkinsci-mber-plugin
c8222c7c2fc0dbacaa015d916d5e12f6fc094190
[ "MIT" ]
null
null
null
src/main/java/org/jenkinsci/plugins/mber/LoggingOutputStream.java
JLLeitschuh/jenkinsci-mber-plugin
c8222c7c2fc0dbacaa015d916d5e12f6fc094190
[ "MIT" ]
null
null
null
29.063636
111
0.719112
2,691
/* The Jenkins Mber Plugin is free software distributed under the terms of the MIT license (http://opensource.org/licenses/mit-license.html) reproduced here: Copyright (c) 2013-2015 Mber 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 org.jenkinsci.plugins.mber; import hudson.model.BuildListener; import java.io.IOException; import java.io.OutputStream; import java.util.Timer; import java.util.TimerTask; public class LoggingOutputStream extends OutputStream { private final OutputStream output; private final BuildListener listener; private final Timer timer = new Timer(); private final long expectedBytes; private final String inputName; private long bytesWritten; public LoggingOutputStream(OutputStream output, BuildListener listener, long expectedBytes, String inputName) { this.output = output; this.listener = listener; this.expectedBytes = expectedBytes; this.inputName = inputName; this.bytesWritten = 0; initTimer(); } @Override public void close() throws IOException { this.timer.cancel(); this.output.close(); if (this.listener != null) { int percent = Math.round(this.bytesWritten * 100 / this.expectedBytes); this.listener.getLogger().println("Uploaded "+percent+"% of "+this.inputName); } } @Override public void flush() throws IOException { this.output.flush(); } @Override public void write(byte[] b) throws IOException { log(b.length); this.output.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { log(len); this.output.write(b, off, len); } @Override public void write(int b) throws IOException { log(1); this.output.write(b); } private void log(int length) { this.bytesWritten += length; } private void initTimer() { long timeout = 1 * 60 * 1000; this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (listener != null) { int percent = Math.round(bytesWritten * 100 / expectedBytes); listener.getLogger().println("Uploaded "+percent+"% of "+inputName); } } }, timeout, timeout); } }
3e065b4efc254a98bcf286cb015015738688fc3e
19,606
java
Java
cortado-core/cortado/src/main/java/edu/utexas/cs/utopia/cortado/lockPlacement/LockAssignmentChecker.java
utopia-group/cortado
84a782700457e0d57e48fccaa46f9c1d89fa765b
[ "MIT" ]
1
2022-03-21T21:45:02.000Z
2022-03-21T21:45:02.000Z
cortado-core/cortado/src/main/java/edu/utexas/cs/utopia/cortado/lockPlacement/LockAssignmentChecker.java
utopia-group/cortado
84a782700457e0d57e48fccaa46f9c1d89fa765b
[ "MIT" ]
1
2022-03-20T16:24:00.000Z
2022-03-21T21:28:20.000Z
cortado-core/cortado/src/main/java/edu/utexas/cs/utopia/cortado/lockPlacement/LockAssignmentChecker.java
utopia-group/cortado
84a782700457e0d57e48fccaa46f9c1d89fa765b
[ "MIT" ]
null
null
null
49.888041
176
0.561359
2,692
package edu.utexas.cs.utopia.cortado.lockPlacement; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Sets; import com.google.common.collect.Streams; import com.google.common.graph.EndpointPair; import com.google.common.graph.GraphBuilder; import com.google.common.graph.MutableGraph; import edu.utexas.cs.utopia.cortado.ccrs.CCR; import edu.utexas.cs.utopia.cortado.ccrs.Fragment; import edu.utexas.cs.utopia.cortado.ccrs.FragmentedMonitor; import edu.utexas.cs.utopia.cortado.staticanalysis.CommutativityAnalysis; import edu.utexas.cs.utopia.cortado.staticanalysis.RaceConditionAnalysis; import edu.utexas.cs.utopia.cortado.staticanalysis.rwsetanalysis.MemoryLocations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.SootMethod; import soot.Unit; import javax.annotation.Nonnull; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * Checks lock assignments for correctness. * Also can be used to build correctness constraints */ @SuppressWarnings("ALL") public class LockAssignmentChecker { private static final Logger log = LoggerFactory.getLogger(LockAssignmentChecker.class); private final FragmentedMonitor fragmentedMonitor; private final RaceConditionAnalysis raceConditionAnalysis; private final CommutativityAnalysis commutativityAnalysis; public LockAssignmentChecker(@Nonnull FragmentedMonitor fragmentedMonitor, @Nonnull RaceConditionAnalysis raceConditionAnalysis, @Nonnull CommutativityAnalysis commutativityAnalysis, Map<SootMethod, Set<Unit>> preChecks) { this.fragmentedMonitor = fragmentedMonitor; this.raceConditionAnalysis = raceConditionAnalysis; this.commutativityAnalysis = commutativityAnalysis; } /** * @return the underlying fragmented monitor */ @Nonnull public FragmentedMonitor getFragmentedMonitor() { return fragmentedMonitor; } /** * Check if lockAssignment * - prevents race conditions * - prevents atomicity violations * - obtains locks in order * - allows a consistent assignment from predicates * to the lowest lock held by that predicate * * @param lockAssignment the lock assignment * @return true iff lockAssignment satisfies the correctness check */ @SuppressWarnings("UnstableApiUsage") public boolean check(@Nonnull LockAssignment lockAssignment) { // make sure the lock assignment prohibits race conditions boolean allowsRaceConditions = !getPossibleRaces().stream() .allMatch(possibleRace -> possibleRace.mutexedUnderAssignment(lockAssignment)); if(allowsRaceConditions) return false; // make sure the lock assignment prohibits atomicity violations boolean allowsInvInterleaving = !getInvalidInterleavings().stream().allMatch(interleav -> interleav.mutexedUnderAssignment(lockAssignment)); boolean nonAtomicCCR = !getCCRFragSets().stream().allMatch(fragSet -> fragSet.mutexedUnderAssignment(lockAssignment)); if(allowsInvInterleaving || nonAtomicCCR) return false; // now make sure that the locks are always obtained in order Comparator<Integer> lockOrder = lockAssignment.getLockOrder(); boolean locksNotObtainedInOrder = fragmentedMonitor.getFragmentsCFG() .edges() .stream() .anyMatch(edge -> { Set<Integer> sourceLocks = lockAssignment.getLocksInOrder(edge.nodeU()); Set<Integer> destLocks = lockAssignment.getLocksInOrder(edge.nodeV()); Set<Integer> locksHeldOnEdge = Sets.intersection(sourceLocks, destLocks); Set<Integer> locksObtained = Sets.difference(destLocks, sourceLocks); // locks are not obtained in order if the first lock obtained // is less than the greatest lock already held return !locksHeldOnEdge.isEmpty() && !locksObtained.isEmpty() && Collections.max(locksHeldOnEdge, lockOrder) > Collections.min(locksObtained, lockOrder); }); if(locksNotObtainedInOrder) return false; // make sure that predicates are associated to the same // lowest lock ImmutableSortedSet<Integer> locks = lockAssignment.getLocks(); int noLockValue = locks.isEmpty() ? -1 : Collections.min(locks) - 1; return fragmentedMonitor.getCCRs() .stream() // group the CCRs by guard .filter(CCR::hasGuard) .collect(Collectors.groupingBy(CCR::getGuard)) .entrySet() .stream() .allMatch(entry -> { Set<Integer> lowestLocksHeld = entry.getValue() .stream() .map(CCR::getWaituntilFragment) .map(lockAssignment::getLocksInOrder) .map(locksInOrder -> locksInOrder.isEmpty() ? noLockValue : locksInOrder.first()) .collect(Collectors.toSet()); return lowestLocksHeld.size() == 1 && !lowestLocksHeld.contains(noLockValue); }); } List<CCRFragmentSet> getCCRFragSets() { return fragmentedMonitor.getCCRs() .stream() .map(ccr -> new CCRFragmentSet(ccr.getFragments().toArray(new Fragment[0]))) .collect(Collectors.toList()); } /** * @return the list of possible race conditions or predicate violations in the monitor */ @Nonnull List<PossibleRace> getPossibleRaces() { final List<Fragment> fragments = getFragmentedMonitor().getFragments(); // For each pair of fragments frag1, frag2 return getAllFragmentPais().parallelStream() .map(fragPair -> new PossibleRace(fragPair.f1, fragPair.f2, raceConditionAnalysis.getRaces(fragPair.f1, fragPair.f2))) .filter(race -> !race.memLocs.isEmpty()) .collect(Collectors.toList()); } List<FragmentPair> fragmentPairsWithoutRaces() { return getAllFragmentPais().stream() .filter(fragPair -> raceConditionAnalysis.getRaces(fragPair.f1, fragPair.f2).isEmpty()) // No need to parallelize fragments that just evaluate predicates for signalling. .filter(fragPair -> (!fragPair.f1.isSignalPredicateEvalFragment() && !fragPair.f2.isSignalPredicateEvalFragment())) // Do not parallelize fragements that do not access any monitor state. .filter(fragPair -> (fragPair.f1.accessesMonitorState() && fragPair.f2.accessesMonitorState())) .collect(Collectors.toList()); } /** * @return the list of possible atomicity violations in the monitor */ @SuppressWarnings("UnstableApiUsage") @Nonnull List<PossibleAtomicityViolation> getInvalidInterleavings() { return getFragmentedMonitor().getFragmentsCFG() .edges() .parallelStream() // Ignore self-edges .filter(e -> !(e.source().equals(e.target()))) // Ignore egdes where the target just evaluates predicates for signalling. // Losing atomicity for those edges does not affect correctness. .filter(e -> !e.target().isSignalPredicateEvalFragment()) .flatMap(edge -> getFragmentedMonitor().getFragments() .parallelStream() .filter(frag -> isNotLinearizableInterleaving(frag, edge)) .map(frag -> new PossibleAtomicityViolation(frag, edge))) .collect(Collectors.toList()); } private static class isNotLinearEdgeInterleavingQuery { private final Fragment fragi; private final EndpointPair<Fragment> edge; public isNotLinearEdgeInterleavingQuery(Fragment fragi, EndpointPair<Fragment> edge) { this.fragi = fragi; this.edge = edge; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LockAssignmentChecker.isNotLinearEdgeInterleavingQuery that = (LockAssignmentChecker.isNotLinearEdgeInterleavingQuery) o; return fragi.equals(that.fragi) && edge.equals(that.edge); } @Override public int hashCode() { return Objects.hash(fragi, edge); } } private ConcurrentHashMap<LockAssignmentChecker.isNotLinearEdgeInterleavingQuery, Boolean> isNotLinearEdgeInterleavingQuery = new ConcurrentHashMap<>(); /** * Return true iff we cannot prove fragi can interleave between * u and v along the control-flow edge u -> v * * @param fragi the interleaving fragment * @param edge the edge between fragments during * which fragi might execute * @return true iff we cannot prove fragi can safely execute between u and v */ @SuppressWarnings("UnstableApiUsage") private boolean isNotLinearizableInterleaving(@Nonnull Fragment fragi, @Nonnull EndpointPair<Fragment> edge) { return Streams.concat(Streams.stream(Collections.singleton(edge)), Streams.stream(fragmentedMonitor.getPredecessorFragments(edge.source())) .flatMap(pred -> fragmentedMonitor.getFragmentsCFG() .predecessors(pred) .stream() .map(predOfPred -> EndpointPair.ordered(predOfPred, pred)) ), Streams.stream(fragmentedMonitor.getSuccessorFragments(edge.target())) .flatMap(succ -> fragmentedMonitor.getFragmentsCFG() .successors(succ) .stream() .map(succOfSucc -> EndpointPair.ordered(succ, succOfSucc)) ) ) .parallel() // Filter out self-edges of the waituntil fragment! // REASONING: // We know the waituntil fragment only reads from monitor. // If we write to these values, it's either right before a yield() ( no problem there ) // or right after returning from a yield(), in which case we can think of // the operation commuting to before the yield .filter(e -> !(e.source().isWaitUntilFrag() && e.source().equals(e.target()))) .filter(e -> !e.target().isSignalPredicateEvalFragment()) .anyMatch(e -> isNotLinearEdgeInterleaving(fragi, e)); } /** * A fragment interleaving along an edge (u, v) is a linear edge interleaving iff * * (1) The fragment preserves the edge condition of edge (see {@link edu.utexas.cs.utopia.cortado.vcgen.CommutativityChecker#preservesEdgeCondition(Fragment, EndpointPair)} * (2) All monitor fields read by the fragment are not written by u * (3) The fragment commutes with both u and v * * @param fragi the fragment * @param edge the edge * @return true iff fragi is a linear edge interleaving along edge */ @SuppressWarnings("UnstableApiUsage") private boolean isNotLinearEdgeInterleaving(@Nonnull Fragment fragi, @Nonnull EndpointPair<Fragment> edge) { return isNotLinearEdgeInterleavingQuery.computeIfAbsent(new isNotLinearEdgeInterleavingQuery(fragi, edge), (k) -> { final Fragment u = edge.source(); final Fragment v = edge.target(); boolean fragiMustNotReadFromEdgeSourceWrite = raceConditionAnalysis.getRaces(fragi, u).isEmpty() || !MemoryLocations.mayIntersectAny(fragi.getMonitorReadSet(), u.getMonitorWriteSet()); return !(fragiMustNotReadFromEdgeSourceWrite && commutativityAnalysis.preservesEdgeCondition(fragi, edge) && (u.isWaitUntilFrag() || commutativityAnalysis.commutes(fragi, u)) && (v.isWaitUntilFrag() || commutativityAnalysis.commutes(fragi, v)) ); }); } /** * We upper bound number of locks by number of fragments. * * We also upper bound the number of locks * by the minimal number of locks required so that * - Every pair of fragments which {@link RaceConditionAnalysis#getRaces(Fragment, Fragment)} * shares no lock. * - Every pair of fragments which cannot run in parallel shares a lock. * Under this framework, the set of fragments holding each lock * is a clique in the graph G := (vertices=fragments, edges=u -> v iff u cannot run in parallel with v), * so we use upper bounds on the intersection number (https://en.wikipedia.org/wiki/Intersection_number_(graph_theory)) * of this graph. * * @return An upper bound on the number of locks */ @SuppressWarnings("UnstableApiUsage") public int getNumLocksUpperBound() { FragmentedMonitor fragmentedMonitor = getFragmentedMonitor(); if(fragmentedMonitor.numFragments() <= 0) { throw new IllegalStateException("No fragments present."); } int upperBound = fragmentedMonitor.numFragments(); // build graph of fragments // with edges between fragments which cannot run // in parallel final MutableGraph<Fragment> cannotRunInParallelGraph = GraphBuilder.undirected() .allowsSelfLoops(false) .expectedNodeCount(fragmentedMonitor.numFragments()) .build(); List<Fragment> frags = fragmentedMonitor.getFragments(); frags.forEach(cannotRunInParallelGraph::addNode); for (int i = 0; i < frags.size(); i++) { Fragment frag1 = frags.get(i); frags.stream() .skip(i + 1) .filter(frag2 -> frag2 != frag1) .filter(frag2 -> !raceConditionAnalysis.getRaces(frag1, frag2).isEmpty()) .forEach(frag2 -> cannotRunInParallelGraph.putEdge(frag1, frag2)); } // Remove isolated vertices final int numExtraLocks = (int) frags.stream() .filter(frag -> cannotRunInParallelGraph.degree(frag) <= 0) .filter(frag -> !raceConditionAnalysis.getRaces(frag, frag).isEmpty()) .count(); frags.stream() .filter(frag -> cannotRunInParallelGraph.degree(frag) <= 0) .forEach(cannotRunInParallelGraph::removeNode); // use upper bounds from // https://en.wikipedia.org/wiki/Intersection_number_(graph_theory)#Upper_bounds // // We have to add in extra locks for isolated vertices with self-loops final int nVerts = cannotRunInParallelGraph.nodes().size(), nEdges = cannotRunInParallelGraph.edges().size(); // upper bounds based on number of edges/vertices upperBound = Math.min(upperBound, nEdges + numExtraLocks); upperBound = Math.min(upperBound, nVerts * nVerts / 4 + numExtraLocks); // upper bound based on number of non-incident pairs int numPairsNotIncident = 0; for(int i = 0; i < fragmentedMonitor.numFragments() - 1; ++i) { Fragment fragi = frags.get(i); for(int j = i + 1; j < fragmentedMonitor.numFragments(); ++j) { Fragment fragj = frags.get(j); if(cannotRunInParallelGraph.hasEdgeConnecting(fragi, fragj)) { numPairsNotIncident++; } } } int t = 0; while((t-1) * t <= numPairsNotIncident) { t++; } t--; assert numPairsNotIncident < t * (t+1); upperBound = Math.min(upperBound, numPairsNotIncident + t + numExtraLocks); // get good upper bound for dense graphs final int minDegree = cannotRunInParallelGraph.nodes() .stream() .map(cannotRunInParallelGraph::degree) .reduce(Math::min) .orElse(0); int maxDegreeInComplement = nVerts - 1 - minDegree; final double complementOfSparseUpperBound = 2 * Math.exp(2) * (maxDegreeInComplement + 1) * (maxDegreeInComplement + 1) * Math.log(nVerts); upperBound = Math.min(upperBound, (int) complementOfSparseUpperBound + numExtraLocks); // sanity check assert upperBound > 0; // return our upper bound return upperBound; } private List<FragmentPair> getAllFragmentPais() { List<Fragment> fragments = getFragmentedMonitor().getFragments(); return Streams.mapWithIndex(fragments.stream(), (frag1, index) -> fragments.stream() .skip(index) .map(frag2 -> new FragmentPair(frag1, frag2)) .collect(Collectors.toList())) .flatMap(Collection::stream) .collect(Collectors.toList()); } static class FragmentPair { Fragment f1, f2; public FragmentPair(Fragment f1, Fragment f2) { this.f1 = f1; this.f2 = f2; } } }
3e065b53dab9313149fa4f412444089c0574ecd7
1,490
java
Java
src/main/java/com/bitmovin/api/sdk/model/BroadcastTsMuxingInformation.java
mcherif/bitmovinexp
d4d746794f26c8e9692c834e63d5d19503693bbf
[ "MIT" ]
7
2019-10-03T05:24:47.000Z
2022-03-04T14:46:15.000Z
src/main/java/com/bitmovin/api/sdk/model/BroadcastTsMuxingInformation.java
mcherif/bitmovinexp
d4d746794f26c8e9692c834e63d5d19503693bbf
[ "MIT" ]
3
2020-04-15T15:35:45.000Z
2020-11-09T18:53:38.000Z
src/main/java/com/bitmovin/api/sdk/model/BroadcastTsMuxingInformation.java
mcherif/bitmovinexp
d4d746794f26c8e9692c834e63d5d19503693bbf
[ "MIT" ]
2
2020-04-21T13:48:56.000Z
2022-02-14T00:58:09.000Z
26.140351
80
0.702013
2,693
package com.bitmovin.api.sdk.model; import java.util.Objects; import java.util.Arrays; import com.bitmovin.api.sdk.model.MuxingInformationAudioTrack; import com.bitmovin.api.sdk.model.MuxingInformationVideoTrack; import com.bitmovin.api.sdk.model.ProgressiveMuxingInformation; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * BroadcastTsMuxingInformation */ public class BroadcastTsMuxingInformation extends ProgressiveMuxingInformation { @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return super.equals(o); } @Override public int hashCode() { return Objects.hash(super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BroadcastTsMuxingInformation {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e065c910a5e1072ccf23151661cfe1c2cf90ab8
1,363
java
Java
restlight-jaxrs-provider/src/main/java/esa/restlight/jaxrs/spi/RequestBodyArgumentResolverProvider.java
alalag1/esa-restlight
13fd32715cf33ee0d2f826b0f28028abb1aea5af
[ "Apache-2.0" ]
140
2020-12-05T05:43:52.000Z
2022-03-31T04:01:26.000Z
restlight-jaxrs-provider/src/main/java/esa/restlight/jaxrs/spi/RequestBodyArgumentResolverProvider.java
alalag1/esa-restlight
13fd32715cf33ee0d2f826b0f28028abb1aea5af
[ "Apache-2.0" ]
43
2020-12-09T09:23:02.000Z
2022-03-01T08:42:34.000Z
restlight-jaxrs-provider/src/main/java/esa/restlight/jaxrs/spi/RequestBodyArgumentResolverProvider.java
alalag1/esa-restlight
13fd32715cf33ee0d2f826b0f28028abb1aea5af
[ "Apache-2.0" ]
35
2020-12-06T08:07:23.000Z
2022-03-07T08:53:32.000Z
40.088235
117
0.774762
2,694
/* * Copyright 2020 OPPO ESA Stack Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package esa.restlight.jaxrs.spi; import esa.restlight.core.DeployContext; import esa.restlight.core.config.RestlightOptions; import esa.restlight.core.resolver.ArgumentResolverFactory; import esa.restlight.core.spi.ArgumentResolverProvider; import esa.restlight.jaxrs.resolver.arg.RequestBodyArgumentResolver; import java.util.Optional; public class RequestBodyArgumentResolverProvider implements ArgumentResolverProvider { @Override public Optional<ArgumentResolverFactory> factoryBean(DeployContext<? extends RestlightOptions> ctx) { return Optional.of(new RequestBodyArgumentResolver(ctx.options().getSerialize().getRequest().isNegotiation(), ctx.options().getSerialize().getRequest().getNegotiationParam())); } }
3e065cb56aad8dbe5389e112cf6e220202282ca6
1,374
java
Java
opencga-analysis/src/main/java/org/opencb/opencga/analysis/beans/ExampleOption.java
roalva1/opencga
26f6fc6615d7039c9116d86171deb38bcfa7b480
[ "Apache-2.0" ]
null
null
null
opencga-analysis/src/main/java/org/opencb/opencga/analysis/beans/ExampleOption.java
roalva1/opencga
26f6fc6615d7039c9116d86171deb38bcfa7b480
[ "Apache-2.0" ]
null
null
null
opencga-analysis/src/main/java/org/opencb/opencga/analysis/beans/ExampleOption.java
roalva1/opencga
26f6fc6615d7039c9116d86171deb38bcfa7b480
[ "Apache-2.0" ]
null
null
null
24.535714
75
0.635371
2,695
/* * Copyright 2015 OpenCB * * 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.opencb.opencga.analysis.beans; public class ExampleOption { private String paramName, value; public ExampleOption() { } public ExampleOption(String executionId, String value) { this.paramName = executionId; this.value = value; } @Override public String toString() { return "ExampleOption{" + "paramName='" + paramName + '\'' + ", value='" + value + '\'' + '}'; } public String getParamName() { return paramName; } public void setParamName(String paramName) { this.paramName = paramName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
3e065d509a0174aefbf21ce2b1f709a0e271c627
681
java
Java
cowbird-flink-common/src/main/java/cowbird/flink/common/config/Topics.java
swandroid/distributed-cowbird
616db92db533422c89f452f55888b74356b5aece
[ "Apache-2.0" ]
1
2017-08-06T23:46:20.000Z
2017-08-06T23:46:20.000Z
cowbird-flink-common/src/main/java/cowbird/flink/common/config/Topics.java
swandroid/distributed-cowbird
616db92db533422c89f452f55888b74356b5aece
[ "Apache-2.0" ]
null
null
null
cowbird-flink-common/src/main/java/cowbird/flink/common/config/Topics.java
swandroid/distributed-cowbird
616db92db533422c89f452f55888b74356b5aece
[ "Apache-2.0" ]
null
null
null
37.833333
84
0.726872
2,696
package cowbird.flink.common.config; public final class Topics { public static final String SENSORS_VALUES_TOPIC = "STREAMS-SENSORS-VALUE-TOPIC"; /* Sensor Value Expression control topic. */ public static final String CONTROL_TOPIC_SVE = "STREAMS-CONTROL-TOPIC-SVE"; public static final String RESULT_TOPIC = "STREAMS-RESULT-TOPIC"; /* New topics for more complex expressions. */ public static final String CONTROL_TOPIC_CVE = "STREAMS-CONTROL-TOPIC-CVE"; public static final String CONTROL_TOPIC_CE = "STREAMS-CONTROL-TOPIC-CE"; private Topics() { throw new RuntimeException("You can't create an instance of this class"); } }
3e065da6f732c5d63a725caf341824a5e52232db
769
java
Java
nautilus-framework-plugin/src/main/java/org/nautilus/plugin/extension/algorithm/NSGAIIWithConfidenceBasedReductionAlgorithmExtension.java
nautilus-framework/nautilus-framework
88db6ae5cd717e642e9c5b1b5269325a3590992d
[ "MIT" ]
1
2022-01-27T08:06:43.000Z
2022-01-27T08:06:43.000Z
nautilus-framework-plugin/src/main/java/org/nautilus/plugin/extension/algorithm/NSGAIIWithConfidenceBasedReductionAlgorithmExtension.java
nautilus-framework/nautilus-framework
88db6ae5cd717e642e9c5b1b5269325a3590992d
[ "MIT" ]
null
null
null
nautilus-framework-plugin/src/main/java/org/nautilus/plugin/extension/algorithm/NSGAIIWithConfidenceBasedReductionAlgorithmExtension.java
nautilus-framework/nautilus-framework
88db6ae5cd717e642e9c5b1b5269325a3590992d
[ "MIT" ]
1
2022-02-24T16:47:27.000Z
2022-02-24T16:47:27.000Z
28.481481
102
0.794538
2,697
package org.nautilus.plugin.extension.algorithm; import org.nautilus.core.algorithm.Builder; import org.nautilus.core.algorithm.NSGAII; import org.nautilus.core.reduction.AbstractReduction; import org.nautilus.core.reduction.ConfidenceBasedReduction; import org.uma.jmetal.algorithm.Algorithm; import org.uma.jmetal.solution.Solution; @SuppressWarnings({"rawtypes", "unchecked"}) public class NSGAIIWithConfidenceBasedReductionAlgorithmExtension extends AbstractAlgorithmExtension { @Override public Algorithm<? extends Solution<?>> getAlgorithm(Builder builder) { return new NSGAII(builder); } @Override public String getName() { return "COR-NSGA-II"; } public AbstractReduction getReduction() { return new ConfidenceBasedReduction(); } }
3e065e24bf6dba8e3d2d555d04e6c63568f2dc07
1,156
java
Java
src/main/java/com/geekerstar/s1003/ReverseStackUsingRecursive.java
geekerstar/coding-interview
6807a21134cf9a4750dd3c0c4483e7e14dbd2f28
[ "MIT" ]
4
2019-02-26T09:14:48.000Z
2019-06-09T03:59:19.000Z
src/main/java/com/geekerstar/s1003/ReverseStackUsingRecursive.java
geekerstar/coding-interview
6807a21134cf9a4750dd3c0c4483e7e14dbd2f28
[ "MIT" ]
null
null
null
src/main/java/com/geekerstar/s1003/ReverseStackUsingRecursive.java
geekerstar/coding-interview
6807a21134cf9a4750dd3c0c4483e7e14dbd2f28
[ "MIT" ]
1
2020-10-13T09:37:41.000Z
2020-10-13T09:37:41.000Z
23.12
69
0.563149
2,698
package com.geekerstar.s1003; import java.util.Stack; /** * @author geekerstar * date: 2019/2/27 19:36 * description: * * 题目:用递归函数和栈操作逆序一个栈 * * 一个栈依次压人1,2,3,4,5,那么从栈顶到栈底分别为5,4,3,2,1。将这个站转置后, * 从栈顶到栈底为1,2,3,4,5,也就是实现栈中元素的逆序,但是只能用递归函数来实现,不能用其他数据结构。 */ public class ReverseStackUsingRecursive { public static void reverse(Stack<Integer> stack) { if (stack.isEmpty()) { return; } int i = getAndRemoveLastElement(stack); reverse(stack); stack.push(i); } public static int getAndRemoveLastElement(Stack<Integer> stack) { int result = stack.pop(); if (stack.isEmpty()) { return result; } else { int last = getAndRemoveLastElement(stack); stack.push(result); return last; } } public static void main(String[] args) { Stack<Integer> test = new Stack<Integer>(); test.push(1); test.push(2); test.push(3); test.push(4); test.push(5); reverse(test); while (!test.isEmpty()) { System.out.println(test.pop()); } } }
3e065e82cf6ba2c24039a2839c47e0b1d006a6e7
303
java
Java
oop-pattern/ch01/example/app/src/main/java/study/Button.java
appkr/pattern
8075aa34e24a19961542cf020917e087a7fd590f
[ "MIT" ]
10
2017-07-10T03:04:28.000Z
2019-07-08T09:14:44.000Z
oop-pattern/ch01/example/app/src/main/java/study/Button.java
appkr/pattern
8075aa34e24a19961542cf020917e087a7fd590f
[ "MIT" ]
null
null
null
oop-pattern/ch01/example/app/src/main/java/study/Button.java
appkr/pattern
8075aa34e24a19961542cf020917e087a7fd590f
[ "MIT" ]
2
2017-02-13T02:40:08.000Z
2017-09-17T23:57:12.000Z
12.625
60
0.643564
2,699
package study; public class Button implements Component { private String id; public Button(String id) { this.id = id; } public Button() { } @Override public String getId() { return id; } @Override public void setOnClickListener(OnClickListener listener) { // } }
3e065eb2b7d528c663ed4610f9ca424435c8c8f7
456
java
Java
src/com/mber/javarush/task/task23/task2303/Solution.java
M10beretta/java
33afd60e19d91e0c9247532ce5192e06c85b6a7e
[ "MIT" ]
null
null
null
src/com/mber/javarush/task/task23/task2303/Solution.java
M10beretta/java
33afd60e19d91e0c9247532ce5192e06c85b6a7e
[ "MIT" ]
null
null
null
src/com/mber/javarush/task/task23/task2303/Solution.java
M10beretta/java
33afd60e19d91e0c9247532ce5192e06c85b6a7e
[ "MIT" ]
null
null
null
20.727273
60
0.622807
2,700
package com.mber.javarush.task.task23.task2303; /* Запрети создание экземпляров класса */ public class Solution { public abstract static class Listener { public void onMouseDown(int x, int y) { // Do something when the mouse down event occurs } public void onMouseUp(int x, int y) { // Do something when the mouse up event occurs } } public static void main(String[] args) { } }
3e06602dbcf29e1c8ff9f2de3cadfcfa5ba9c3be
4,195
java
Java
core/cas-server-core-events/src/main/java/org/apereo/cas/support/events/config/CasCoreEventsConfiguration.java
JasonEverling/cas
9d5eb3e7dbf34a29f5f69141602b3f83b48353c8
[ "Apache-2.0" ]
1
2022-03-03T03:28:12.000Z
2022-03-03T03:28:12.000Z
core/cas-server-core-events/src/main/java/org/apereo/cas/support/events/config/CasCoreEventsConfiguration.java
Nurran/cas
43392ae8eefeb36d44a2b06fdedba589d726f4ae
[ "Apache-2.0" ]
1
2022-03-19T12:37:05.000Z
2022-03-19T12:37:05.000Z
core/cas-server-core-events/src/main/java/org/apereo/cas/support/events/config/CasCoreEventsConfiguration.java
isabella232/cas
fc570ef1f0aa6b18817a955c5158e84d35aa201d
[ "Apache-2.0" ]
null
null
null
48.77907
120
0.775685
2,701
package org.apereo.cas.support.events.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.configuration.support.CasFeatureModule; import org.apereo.cas.support.events.CasEventRepository; import org.apereo.cas.support.events.dao.NoOpCasEventRepository; import org.apereo.cas.support.events.listener.CasAuthenticationAuthenticationEventListener; import org.apereo.cas.support.events.listener.CasAuthenticationEventListener; import org.apereo.cas.support.events.web.CasEventsReportEndpoint; import org.apereo.cas.util.spring.beans.BeanCondition; import org.apereo.cas.util.spring.beans.BeanSupplier; import org.apereo.cas.util.spring.boot.ConditionalOnFeature; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ScopedProxyMode; /** * This is {@link CasCoreEventsConfiguration}. * * @author Misagh Moayyed * @since 5.0.0 */ @Configuration(value = "CasCoreEventsConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) @ConditionalOnFeature(feature = CasFeatureModule.FeatureCatalog.Events) public class CasCoreEventsConfiguration { private static final BeanCondition CONDITION = BeanCondition.on("cas.events.core.enabled").isTrue().evenIfMissing(); @Configuration(value = "CasCoreEventsListenerConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public static class CasCoreEventsListenerConfiguration { @ConditionalOnMissingBean(name = "defaultCasEventListener") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public CasAuthenticationEventListener defaultCasEventListener( final ConfigurableApplicationContext applicationContext, @Qualifier(CasEventRepository.BEAN_NAME) final CasEventRepository casEventRepository) throws Exception { return BeanSupplier.of(CasAuthenticationEventListener.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> new CasAuthenticationAuthenticationEventListener(casEventRepository)) .otherwiseProxy() .get(); } } @Configuration(value = "CasCoreEventsWebConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public static class CasCoreEventsWebConfiguration { @Bean @ConditionalOnAvailableEndpoint @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public CasEventsReportEndpoint casEventsReportEndpoint( final CasConfigurationProperties casProperties, final ConfigurableApplicationContext applicationContext) { return new CasEventsReportEndpoint(casProperties, applicationContext); } } @Configuration(value = "CasCoreEventsRepositoryConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public static class CasCoreEventsRepositoryConfiguration { @ConditionalOnMissingBean(name = CasEventRepository.BEAN_NAME) @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public CasEventRepository casEventRepository( final ConfigurableApplicationContext applicationContext) throws Exception { return BeanSupplier.of(CasEventRepository.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> NoOpCasEventRepository.INSTANCE) .otherwiseProxy() .get(); } } }
3e0660bfd1f256cb82b60529643ab38c78fed7b0
4,530
java
Java
src/com/bluegosling/redis/Redis.java
jhump/hyper-redis
069a931245d75f62c1f226e85a7e999b1904aae9
[ "Apache-2.0" ]
null
null
null
src/com/bluegosling/redis/Redis.java
jhump/hyper-redis
069a931245d75f62c1f226e85a7e999b1904aae9
[ "Apache-2.0" ]
null
null
null
src/com/bluegosling/redis/Redis.java
jhump/hyper-redis
069a931245d75f62c1f226e85a7e999b1904aae9
[ "Apache-2.0" ]
null
null
null
36.532258
102
0.664238
2,702
package com.bluegosling.redis; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.bluegosling.redis.channel.RedisChannel; import com.bluegosling.redis.concurrent.Callback; import com.bluegosling.redis.protocol.ArrayOfLongListener; import com.bluegosling.redis.protocol.RequestStreamer; import com.bluegosling.redis.values.BitFieldType; import com.bluegosling.redis.values.GeoElement; import com.bluegosling.redis.values.OverflowType; import com.bluegosling.redis.values.Response; public interface Redis<K, V> { // placeholder String MIN_VERSION = "1.0.0"; static <K, V> Redis<K, V> newInstance(RedisChannel channel, Marshaller<K> keyMarshaller, Marshaller<V> valueMarshaller) { return new RedisImpl<>(channel, keyMarshaller, valueMarshaller); } // DatabaseMetadata<K> databaseMetadata(); // FuturesRedis<K, V> withFutures(); // BlockingRedis<K, V> withBlocking(); // void validate_v2_2_0(Callback<Redis22<K, V>> callback); // RedisTransactor<K, V> transactor(); // SubscriptionController subscriptionController(); // interface RedisTransactor<K, V> { // <X extends Throwable> void runTransaction(TransactionBlock<K, V, X> block) throws X; // <T, X extends Throwable> T callInTransaction(TransactionCallable<K, V, T, X> block) throws X; // <X extends Throwable >void runTransaction(WatchingTransactionBlock<K, V, X> block) throws X; // <T, X extends Throwable> T callInTransaction(WatchingTransactionCallable<K, V, T, X> block) // throws X; // } // interface TransactionBlock<K, V, X extends Throwable> { // void run(TransactingRedis<K, V> redis) throws X; // } // interface TransactionCallable<K, V, T, X extends Throwable> { // T call(TransactingRedis<K, V> redis) throws X; // } // interface WatchingTransactionBlock<K, V, X extends Throwable> { // void run(TransactingRedis<K, V> redis, WatchingRedis<K, V> watcher) throws X; // } // interface WatchingTransactionCallable<K, V, T, X extends Throwable> { // T call(TransactingRedis<K, V> redis, WatchingRedis<K, V> watcher) throws X; // } // interface TransactingRedis<K, V> { // } // interface WatchingRedis<K, V> { // } void append(K key, V value, Callback.OfLong callback); void eval(String script, Collection<K> keys, Collection<String> args, Callback<Response> callback); void geoAdd(K key, Collection<GeoElement<V>> elements, Callback.OfInt callback); BitFieldOperation bitField(K key); final class BitFieldOperation { private final RedisChannel channel; private final List<Object> tokens = new ArrayList<>(); BitFieldOperation(RedisChannel channel, Object... tokens) { this.channel = channel; for (Object t : tokens) { this.tokens.add(requireNonNull(t)); } } // :get type=bitfieldtype offset=long public BitFieldOperation get(BitFieldType type, long offset) { tokens.add("GET"); tokens.add(requireNonNull(type)); tokens.add(Long.toString(offset)); return this; } // :set type=BitFieldType offset=long value=long public BitFieldOperation set(BitFieldType type, long offset, long value) { tokens.add("SET"); tokens.add(requireNonNull(type)); tokens.add(Long.toString(offset)); tokens.add(Long.toString(value)); return this; } // :incrementBy=incrby type=BitFieldType offset=long inc=long public BitFieldOperation incrementBy(BitFieldType type, long offset, long inc) { tokens.add("INCRBY"); tokens.add(requireNonNull(type)); tokens.add(Long.toString(offset)); tokens.add(Long.toString(inc)); return this; } // :overflow OverflowType public BitFieldOperation overflow(OverflowType overflowType) { tokens.add("OVERFLOW"); tokens.add(requireNonNull(overflowType)); return this; } public void execute(Callback<long[]> callback) { RequestStreamer cmd = channel.newCommand(new ArrayOfLongListener(callback)); for (Object t : tokens) { if (t instanceof Marshallable) { cmd.nextToken(((Marshallable) t).marshall(channel.allocator())); } else { cmd.nextToken(String.valueOf(t)); } } cmd.finish(); } } }
3e066110b523d8e9e9821cc5b74f3299a960aac0
118
java
Java
src/main/java/auxiliary/otherCryptosystems/RSACryptosystem.java
REduard/NTRU
5da434320821b4cde8f14423b0f7dbfd0fe863db
[ "MIT" ]
null
null
null
src/main/java/auxiliary/otherCryptosystems/RSACryptosystem.java
REduard/NTRU
5da434320821b4cde8f14423b0f7dbfd0fe863db
[ "MIT" ]
null
null
null
src/main/java/auxiliary/otherCryptosystems/RSACryptosystem.java
REduard/NTRU
5da434320821b4cde8f14423b0f7dbfd0fe863db
[ "MIT" ]
null
null
null
14.75
37
0.728814
2,703
package auxiliary.otherCryptosystems; /** * Created by R.Eduard on 31.10.2017. */ public class RSACryptosystem { }
3e06612b37cd3f70f4fd246b9a4afed11617f7e9
5,035
java
Java
src/Client_OpenRoad/citizen_validation.java
gitexel/Client_OpenRoad
7d8211dda1cdaaefdec9eed03fe610a7b8e59e32
[ "Apache-2.0" ]
6
2018-04-13T15:01:04.000Z
2021-11-13T07:49:17.000Z
src/Client_OpenRoad/citizen_validation.java
gitexel/Client_OpenRoad
7d8211dda1cdaaefdec9eed03fe610a7b8e59e32
[ "Apache-2.0" ]
null
null
null
src/Client_OpenRoad/citizen_validation.java
gitexel/Client_OpenRoad
7d8211dda1cdaaefdec9eed03fe610a7b8e59e32
[ "Apache-2.0" ]
2
2018-12-03T05:16:20.000Z
2019-07-14T03:04:35.000Z
31.867089
205
0.566832
2,704
package Client_OpenRoad; import org.jetbrains.annotations.NotNull; import java.sql.*; import java.time.LocalDate; /** * Created by Salem on 12/28/16 at 3:41 AM. */ public class citizen_validation extends customer_validation_time { private db_use_info db_token = new db_use_info(); public citizen_validation() { } private Connection connection() throws SQLException { try { Class.forName(db_token.getDriver()); } catch (ClassNotFoundException e) { e.printStackTrace(); } return DriverManager.getConnection(db_token.getUrl() + "user=" + db_token.getUsername() + "&password=" + db_token.getPassword()); } // check if the national id has true value public @NotNull Boolean valid_citizen(String username, String n_id, @NotNull String f_name, @NotNull String m_name, @NotNull String l_name, String country, @NotNull String gender, LocalDate birthday) { int action = 0; try { PreparedStatement pst = connection().prepareStatement("SELECT n_id from opr.citizen WHERE n_id=? and fname=? and mname=? and lname=? and country_name=? and gender=? and birthday=?" ); pst.setString(1, n_id); pst.setString(2, f_name.toLowerCase()); pst.setString(3, m_name.toLowerCase()); pst.setString(4, l_name.toLowerCase()); pst.setString(5, country); pst.setString(6, String.valueOf(gender.charAt(0))); pst.setDate(7, Date.valueOf(birthday)); ResultSet rst = pst.executeQuery(); if (rst.next()) { connection().close(); PreparedStatement pst1 = connection().prepareStatement("update opr.customer set verified=?, n_id=? WHERE username=?"); pst1.setBoolean(1, true); pst1.setString(2, n_id); pst1.setString(3, username); action = pst1.executeUpdate(); } connection().close(); } catch (SQLException e) { e.printStackTrace(); } if (action > 0) { //user have validation for 1 year if no still customer withot id and not verfied new_request(username); return true; } else return false; } // check if the customer hava been validated in the database protected boolean check_customer_citizen(String username) { boolean done = false; check_validation_time(username); // check validation time expired or not try { PreparedStatement pst1 = connection().prepareStatement("SELECT customer.verified FROM opr.customer WHERE username=? and verified=?"); pst1.setString(1, username); pst1.setInt(2, 1); ResultSet rst1 = pst1.executeQuery(); connection().close(); done = rst1.next(); } catch (SQLException e) { e.printStackTrace(); } return done; } private void check_validation_time(String username) { try { PreparedStatement pst2 = connection().prepareStatement("SELECT * from opr.valid_users WHERE username=? and valid=?"); pst2.setString(1, username); pst2.setBoolean(2, true); ResultSet rst1 = pst2.executeQuery(); connection().close(); if (rst1.next()) { Statement pst1 = connection().createStatement(); ResultSet rst4 = pst1.executeQuery("SELECT CURRENT_TIMESTAMP");//current server time if (rst4.next()) { // get current time status if (rst1.getTimestamp(4).before(rst4.getTimestamp("CURRENT_TIMESTAMP"))) { //check if expired connection().close(); PreparedStatement pst3 = connection().prepareStatement("update opr.valid_users set valid=? WHERE username=? and valid=true"); pst3.setBoolean(1, false); pst3.setString(2, username); pst3.executeUpdate(); connection().close(); PreparedStatement pst4 = connection().prepareStatement("update opr.customer set verified=? WHERE username=?"); pst4.setBoolean(1, false); pst4.setString(2, username); pst4.executeUpdate(); connection().close(); } } else { connection().close(); } } else { // if not have any valid time PreparedStatement pst5 = connection().prepareStatement("update opr.customer set verified=? WHERE username=?"); pst5.setBoolean(1, false); pst5.setString(2, username); pst5.executeUpdate(); connection().close(); } } catch (SQLException e) { e.printStackTrace(); } } }
3e0661c4ac548b69fb2868dadd6f0b987f28c2ae
2,458
java
Java
server/src/main/java/org/cloudfoundry/identity/uaa/db/BootstrapIdentityZones.java
jamelseagraves/uaa
0360c27e729e3cd036e7bd37d126382308a9f4ab
[ "Apache-2.0" ]
5
2016-11-01T19:39:38.000Z
2018-11-20T22:45:34.000Z
server/src/main/java/org/cloudfoundry/identity/uaa/db/BootstrapIdentityZones.java
jamelseagraves/uaa
0360c27e729e3cd036e7bd37d126382308a9f4ab
[ "Apache-2.0" ]
39
2019-05-24T18:41:59.000Z
2019-07-04T05:03:25.000Z
server/src/main/java/org/cloudfoundry/identity/uaa/db/BootstrapIdentityZones.java
jamelseagraves/uaa
0360c27e729e3cd036e7bd37d126382308a9f4ab
[ "Apache-2.0" ]
3
2017-01-26T00:19:30.000Z
2020-05-13T14:29:37.000Z
58.52381
276
0.738812
2,705
package org.cloudfoundry.identity.uaa.db; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.zone.IdentityZone; import org.flywaydb.core.api.migration.spring.SpringJdbcMigration; import org.springframework.jdbc.core.JdbcTemplate; import java.sql.Timestamp; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; public class BootstrapIdentityZones implements SpringJdbcMigration { @Override public void migrate(JdbcTemplate jdbcTemplate) throws Exception { IdentityZone uaa = IdentityZone.getUaa(); Timestamp t = new Timestamp(uaa.getCreated().getTime()); jdbcTemplate.update("insert into identity_zone VALUES (?,?,?,?,?,?,?)", uaa.getId(),t,t,uaa.getVersion(),uaa.getSubdomain(),uaa.getName(),uaa.getDescription()); Map<String,String> originMap = new HashMap<String, String>(); Set<String> origins = new LinkedHashSet<String>(); origins.addAll(Arrays.asList(new String[] {OriginKeys.UAA, OriginKeys.LOGIN_SERVER, OriginKeys.LDAP, OriginKeys.KEYSTONE})); origins.addAll(jdbcTemplate.queryForList("SELECT DISTINCT origin from users", String.class)); for (String origin : origins) { String identityProviderId = UUID.randomUUID().toString(); originMap.put(origin, identityProviderId); jdbcTemplate.update("insert into identity_provider VALUES (?,?,?,0,?,?,?,?,null)",identityProviderId, t, t, uaa.getId(),origin,origin,origin); } jdbcTemplate.update("update oauth_client_details set identity_zone_id = ?",uaa.getId()); List<String> clientIds = jdbcTemplate.queryForList("SELECT client_id from oauth_client_details", String.class); for (String clientId : clientIds) { jdbcTemplate.update("insert into client_idp values (?,?) ",clientId,originMap.get(OriginKeys.UAA)); } jdbcTemplate.update("update users set identity_provider_id = (select id from identity_provider where identity_provider.origin_key = users.origin), identity_zone_id = (select identity_zone_id from identity_provider where identity_provider.origin_key = users.origin);"); jdbcTemplate.update("update group_membership set identity_provider_id = (select id from identity_provider where identity_provider.origin_key = group_membership.origin);"); } }
3e0661f49e7728ce3defddba57086a9bbd0f2034
75
java
Java
src/main/java/me/modmuss50/jsonDestroyer/api/IDestroyable.java
modmuss50/JSON-Destroyer
4ba643760b8f60eb46b41080d2288cf956b18e0b
[ "MIT" ]
12
2016-01-19T17:31:51.000Z
2021-02-02T15:23:35.000Z
src/main/java/me/modmuss50/jsonDestroyer/api/IDestroyable.java
modmuss50/JSON-Destroyer
4ba643760b8f60eb46b41080d2288cf956b18e0b
[ "MIT" ]
10
2016-01-31T18:54:12.000Z
2018-06-17T16:29:22.000Z
src/main/java/me/modmuss50/jsonDestroyer/api/IDestroyable.java
modmuss50/JSON-Destroyer
4ba643760b8f60eb46b41080d2288cf956b18e0b
[ "MIT" ]
4
2016-01-31T18:52:14.000Z
2016-05-11T00:10:49.000Z
15
39
0.813333
2,706
package me.modmuss50.jsonDestroyer.api; public interface IDestroyable { }
3e06626a443ad36c30fa8667ef5277bc22652d2b
913
java
Java
src/test/java/com/sebastian_daschner/jaxrs_analyzer/analysis/results/testclasses/typeanalyzer/TestClass32.java
markrileybot/jaxrs-analyzer
46d64290d38d8c14109c26df5195742ef0ec194e
[ "Apache-2.0" ]
null
null
null
src/test/java/com/sebastian_daschner/jaxrs_analyzer/analysis/results/testclasses/typeanalyzer/TestClass32.java
markrileybot/jaxrs-analyzer
46d64290d38d8c14109c26df5195742ef0ec194e
[ "Apache-2.0" ]
null
null
null
src/test/java/com/sebastian_daschner/jaxrs_analyzer/analysis/results/testclasses/typeanalyzer/TestClass32.java
markrileybot/jaxrs-analyzer
46d64290d38d8c14109c26df5195742ef0ec194e
[ "Apache-2.0" ]
null
null
null
22.825
88
0.784228
2,707
package com.sebastian_daschner.jaxrs_analyzer.analysis.results.testclasses.typeanalyzer; import com.sebastian_daschner.jaxrs_analyzer.model.rest.TypeIdentifier; import com.sebastian_daschner.jaxrs_analyzer.model.rest.TypeRepresentation; import java.util.Collections; import java.util.Set; public class TestClass32 { private String name; private String notThisOne; public String getName() { return name; } public TestClass32 setName(String name) { this.name = name; return this; } public String getNotThisOne() { return notThisOne; } public TestClass32 setNotThisOne(String notThisOne) { this.notThisOne = notThisOne; return this; } public static Set<TypeRepresentation> expectedTypeRepresentations() { return Collections.emptySet(); // this type is swapped with a String } public static TypeIdentifier expectedIdentifier() { return TypeIdentifier.ofType(String.class); } }
3e06638e5351066783a66dea83ceaaa434c21a7f
2,401
java
Java
core-adapters/core-adapter-common/src/main/java/org/openstack/atlas/adapter/common/service/impl/HostServiceImpl.java
openstack-atlas/atlas-lb
66327a6aa1ecce959b8beb9e452f6c59f0e55664
[ "Apache-2.0" ]
1
2015-04-19T19:30:13.000Z
2015-04-19T19:30:13.000Z
core-adapters/core-adapter-common/src/main/java/org/openstack/atlas/adapter/common/service/impl/HostServiceImpl.java
openstack-atlas/atlas-lb
66327a6aa1ecce959b8beb9e452f6c59f0e55664
[ "Apache-2.0" ]
2
2020-11-16T16:49:36.000Z
2022-01-21T23:18:40.000Z
core-adapters/core-adapter-common/src/main/java/org/openstack/atlas/adapter/common/service/impl/HostServiceImpl.java
openstack-atlas/atlas-lb
66327a6aa1ecce959b8beb9e452f6c59f0e55664
[ "Apache-2.0" ]
null
null
null
32.013333
118
0.72095
2,708
package org.openstack.atlas.adapter.common.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openstack.atlas.adapter.common.entity.Host; import org.openstack.atlas.adapter.common.entity.LoadBalancerHost; import org.openstack.atlas.service.domain.exception.PersistenceServiceException; import org.openstack.atlas.adapter.common.repository.HostRepository; import org.openstack.atlas.adapter.common.service.HostService; import org.openstack.atlas.service.domain.service.impl.HealthMonitorServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class HostServiceImpl implements HostService { private final Log LOG = LogFactory.getLog(HostServiceImpl.class); @Autowired private HostRepository hostRepository; @Override @Transactional(value="adapter_transactionManager") public final LoadBalancerHost createLoadBalancerHost(LoadBalancerHost lbHost) throws PersistenceServiceException { try { LoadBalancerHost dbLoadBalancerHost = hostRepository.createLoadBalancerHost(lbHost); return dbLoadBalancerHost; } catch (Exception e) { throw new PersistenceServiceException(e); } } @Override @Transactional(value="adapter_transactionManager") public final void removeLoadBalancerHost(LoadBalancerHost lbHost) throws PersistenceServiceException { try { hostRepository.removeLoadBalancerHost(lbHost); } catch (Exception e) { throw new PersistenceServiceException(e); } } @Override @Transactional(value="adapter_transactionManager") public final LoadBalancerHost getLoadBalancerHost(Integer loadBalancerId) { return hostRepository.getLBHost(loadBalancerId); } @Override public Host getDefaultActiveHost() { List<Host> hosts = hostRepository.getHosts(); if (hosts == null || hosts.size() <= 0) { return null; } if (hosts.size() == 1) { Host host = hosts.get(0); return (host); } else { Host host = hostRepository.getHostWithMinimumLoadBalancers(hosts); return (host); } } }
3e0663f1f7f5b9fb1505e2d833d092ee03d08b75
3,357
java
Java
src/test/java/com/xvzhu/connections/apis/ConnectionManagerConfigTest.java
coregiu/pooled-connection-client
7f63dd64fff675e0d82fae2f221a76cfce22dcbf
[ "Apache-2.0" ]
1
2020-03-07T04:46:58.000Z
2020-03-07T04:46:58.000Z
src/test/java/com/xvzhu/connections/apis/ConnectionManagerConfigTest.java
coregiu/pooled-connection-client
7f63dd64fff675e0d82fae2f221a76cfce22dcbf
[ "Apache-2.0" ]
3
2021-12-18T18:14:59.000Z
2022-01-04T16:39:05.000Z
src/test/java/com/xvzhu/connections/apis/ConnectionManagerConfigTest.java
xvzhu/pooled-connection-client
7f63dd64fff675e0d82fae2f221a76cfce22dcbf
[ "Apache-2.0" ]
null
null
null
40.445783
101
0.729818
2,709
/* * Copyright (c) Xvzhu 2020. All rights reserved. */ package com.xvzhu.connections.apis; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; /** * @author : xvzhu * @version V1.0 * @since Date : 2020-02-22 12:05 */ public class ConnectionManagerConfigTest { @Test public void should_init_default_max_connection_size_value_when_default_created() { assertThat(ConnectionManagerConfig.builder().build().getMaxConnectionSize(), is(8)); } @Test public void should_init_default_borrow_time_value_when_default_created() { assertThat(ConnectionManagerConfig.builder().build().getBorrowTimeoutMS(), is(3600000)); } @Test public void should_init_default_idle_time_value_when_default_created() { assertThat(ConnectionManagerConfig.builder().build().getIdleTimeoutMS(), is(300000)); } @Test public void should_init_default_connection_timeout_value_when_default_created() { assertThat(ConnectionManagerConfig.builder().build().getConnectionTimeoutMs(), is(5000)); } @Test public void should_init_default_schedule_period_value_when_default_created() { assertThat(ConnectionManagerConfig.builder().build().getSchedulePeriodTimeMS(), is(600000L)); } @Test public void should_init_default_auto_inspect_value_when_default_created() { assertTrue(ConnectionManagerConfig.builder().build().isAutoInspect()); } @Test public void should_init_default_borrow_wait_time_value_when_default_created() { assertThat(ConnectionManagerConfig.builder().build().getBorrowMaxWaitTimeMS(), is(60000L)); } @Test public void should_equal_when_config_bean_has_same_value() { ConnectionManagerConfig connectionManagerConfig = new ConnectionManagerConfig(); ConnectionManagerConfig connectionManagerConfig1 = ConnectionManagerConfig.builder().build(); assertTrue(connectionManagerConfig.canEqual(connectionManagerConfig1)); assertNotNull(connectionManagerConfig.toString()); assertEquals(connectionManagerConfig.hashCode(), connectionManagerConfig1.hashCode()); assertEquals(connectionManagerConfig, connectionManagerConfig1); } @Test public void should_using_new_value_when_config_value_changed() { ConnectionManagerConfig connectionManagerConfig = ConnectionManagerConfig.builder() .maxConnectionSize(10) .borrowMaxWaitTimeMS(10000) .borrowTimeoutMS(5000) .connectionTimeoutMs(3000) .idleTimeoutMS(1800000) .isAutoInspect(false) .schedulePeriodTimeMS(12000L) .build(); assertNotNull(connectionManagerConfig.toString()); assertThat(connectionManagerConfig.isAutoInspect(), is(false)); assertThat(connectionManagerConfig.getSchedulePeriodTimeMS(), is(12000L)); assertThat(connectionManagerConfig.getConnectionTimeoutMs(), is(3000)); assertThat(connectionManagerConfig.getBorrowTimeoutMS(), is(5000)); assertThat(connectionManagerConfig.getMaxConnectionSize(), is(10)); assertThat(connectionManagerConfig.getIdleTimeoutMS(), is(1800000)); assertThat(connectionManagerConfig.getBorrowMaxWaitTimeMS(), is(10000L)); } }
3e0664030d5603fe2d041877a0e26cb56887f1ee
874
java
Java
src/S0312BurstBalloons.java
camelcc/leetcode
0ba37f7fd47ed3e893525988ce803ce805001ba7
[ "CECILL-B" ]
4
2021-11-30T20:28:14.000Z
2022-01-04T04:01:32.000Z
src/S0312BurstBalloons.java
camelcc/leetcode
0ba37f7fd47ed3e893525988ce803ce805001ba7
[ "CECILL-B" ]
null
null
null
src/S0312BurstBalloons.java
camelcc/leetcode
0ba37f7fd47ed3e893525988ce803ce805001ba7
[ "CECILL-B" ]
1
2021-11-30T23:33:51.000Z
2021-11-30T23:33:51.000Z
26.484848
109
0.415332
2,710
public class S0312BurstBalloons { public int maxCoins(int[] nums) { int[] d = new int[nums.length+2]; d[0] = 1; int len = 1; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { continue; } d[len++] = nums[i]; } d[len++] = 1; int[][] dp = new int[len][len]; return max(d, 0, len-1, dp); } private int max(int[] nums, int start, int end, int[][] dp) { if (start+1 == end) { return 0; } if (dp[start][end] > 0) { return dp[start][end]; } int res = 0; for (int i = start+1; i < end; i++) { res = Math.max(res, nums[start]*nums[i]*nums[end]+max(nums, start, i, dp)+max(nums, i, end, dp)); } dp[start][end] = res; return res; } }
3e066458fb75f39f1e51b0e320f9b4d6742694a7
4,556
java
Java
src/main/java/edu/ucdenver/ccp/common/collections/LegacyCollectionsUtil.java
UCDenver-ccp/common
fe36bad6110b3f006e9d787886971fa584bf768e
[ "BSD-3-Clause" ]
null
null
null
src/main/java/edu/ucdenver/ccp/common/collections/LegacyCollectionsUtil.java
UCDenver-ccp/common
fe36bad6110b3f006e9d787886971fa584bf768e
[ "BSD-3-Clause" ]
2
2021-12-18T18:21:32.000Z
2022-01-04T16:36:09.000Z
src/main/java/edu/ucdenver/ccp/common/collections/LegacyCollectionsUtil.java
UCDenver-ccp/common
fe36bad6110b3f006e9d787886971fa584bf768e
[ "BSD-3-Clause" ]
3
2015-04-24T00:54:13.000Z
2017-04-24T05:17:56.000Z
39.669565
119
0.733012
2,711
package edu.ucdenver.ccp.common.collections; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2014 Regents of the University of Colorado * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 HOLDER 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. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * This utility class is dedicated to dealing with raw type collections (used pre-Java 1.5) in such * a manner as they are safely converted to generic collections. * * @author Center for Computational Pharmacology; [email protected] * */ public class LegacyCollectionsUtil { /** * This utility method ensures the content of the input raw-type list is as expected (in terms * of the Classes being stored in the list) and returns a generified list. Type checking is done * at runtime in this case, so compiler warnings for type checking are suppressed. * * @param <T> * @param list a raw-type list * @param clazz the Class expected to comprise the contents of the input raw-type list * @return a generified List which has been verified to contain only instances off the expected Class * @throws ClassCastException if a member of the input list is not an instance of the expected class */ /* * This method deals with the raw-type List. Because of this, type checking cannot be done by * the compiler and is instead done at runtime, therefore it is safe to suppress the "unchecked" * compiler warnings. */ @SuppressWarnings("unchecked") public static <T> List<T> checkList(@SuppressWarnings("rawtypes") List list, Class<T> clazz) { List<T> checkedList = Collections.checkedList(new ArrayList<T>(), clazz); try { checkedList.addAll(list); } catch (ClassCastException cce) { for (Object item : list) if (!(clazz.isInstance(item))) throw new ClassCastException( String.format( "Raw-type List contains an unexpected class. Cannot cast from class %s to expected class %s.", item.getClass().getName(), clazz.getName())); } return checkedList; } /** * This utility method ensures the content of the input raw-type Iterator is as expected in * regards to the Classes it returns. Type checking is done at runtime in this case so compiler * warnings for unchecked types can be suppressed. * * @param <T> * @param iter a raw-type iterator * @param clazz the Class expected by the user to be returned by the input raw-type iterator * @return a generified Iterator containing only instances of the specified class * @throws ClassCastException if the input iterator returns a class that is not an instance of the expected class */ public static <T> Iterator<T> checkIterator(@SuppressWarnings("rawtypes") final Iterator iter, final Class<T> clazz) { return new Iterator<T>() { @Override public boolean hasNext() { return iter.hasNext(); } @Override public T next() { return clazz.cast(iter.next()); } @Override public void remove() { iter.remove(); } }; } }
3e06646bdf4043af25a6adcad43ccdc1c64e33d3
2,360
java
Java
test/com/isode/stroke/filetransfer/FileWriteBytestreamTest.java
senagbe/stroke
9b518dcdd98d694a4464895fce17a3c7a8caf569
[ "BSD-3-Clause" ]
9
2015-06-01T08:57:02.000Z
2021-07-01T19:33:28.000Z
test/com/isode/stroke/filetransfer/FileWriteBytestreamTest.java
senagbe/stroke
9b518dcdd98d694a4464895fce17a3c7a8caf569
[ "BSD-3-Clause" ]
7
2015-03-11T17:27:13.000Z
2019-01-06T05:30:26.000Z
test/com/isode/stroke/filetransfer/FileWriteBytestreamTest.java
senagbe/stroke
9b518dcdd98d694a4464895fce17a3c7a8caf569
[ "BSD-3-Clause" ]
12
2015-03-09T20:59:14.000Z
2021-08-13T07:06:18.000Z
28.095238
86
0.583898
2,712
/* Copyright (c) 2016, Isode Limited, London, England. * All rights reserved. * * Acquisition and use of this software and related materials for any * purpose requires a written license agreement from Isode Limited, * or a written license from an organisation licensed by Isode Limited * to grant such a license. * */ package com.isode.stroke.filetransfer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.Test; import com.isode.stroke.base.ByteArray; import com.isode.stroke.signals.Slot1; /** * Tests for {@link FileWriteBytestream} * */ public class FileWriteBytestreamTest { private boolean onWriteWasCalled = false; @Test public void testSuccessfulWrite() { File tempfile = null; String filename = null; try { try { tempfile = File.createTempFile("write_file_bytestream_test_", ".tmp"); filename = tempfile.getAbsolutePath(); } catch (IOException e) { // Unable to create file exit test return; } WriteBytestream writeBytestream = new FileWriteBytestream(filename); writeBytestream.onWrite.connect(new Slot1<ByteArray>() { @Override public void call(ByteArray data) { handleOnWrite(data); } }); assertTrue(writeBytestream.write(new ByteArray("Some data."))); assertTrue(onWriteWasCalled); } finally { if (tempfile != null && tempfile.exists()) { tempfile.delete(); } } } @Test public void testFailingWrite() { WriteBytestream writeBytestream = new FileWriteBytestream(""); writeBytestream.onWrite.connect(new Slot1<ByteArray>() { @Override public void call(ByteArray data) { handleOnWrite(data); } }); assertFalse(writeBytestream.write(new ByteArray("Some data."))); assertFalse(onWriteWasCalled); } private void handleOnWrite(ByteArray data) { onWriteWasCalled = true; } }
3e0665299fc3cd98926eae41f877d630daeadfb8
7,508
java
Java
javamesh-samples/javamesh-flowcontrol/flowcontrol-plugin/src/main/java/com/huawei/flowcontrol/core/datasource/zookeeper/ZookeeperDatasourceManager.java
scyiwei/JavaMesh
ab72caceb00022021110ad58a902f5ce9cea98b4
[ "Apache-2.0" ]
null
null
null
javamesh-samples/javamesh-flowcontrol/flowcontrol-plugin/src/main/java/com/huawei/flowcontrol/core/datasource/zookeeper/ZookeeperDatasourceManager.java
scyiwei/JavaMesh
ab72caceb00022021110ad58a902f5ce9cea98b4
[ "Apache-2.0" ]
null
null
null
javamesh-samples/javamesh-flowcontrol/flowcontrol-plugin/src/main/java/com/huawei/flowcontrol/core/datasource/zookeeper/ZookeeperDatasourceManager.java
scyiwei/JavaMesh
ab72caceb00022021110ad58a902f5ce9cea98b4
[ "Apache-2.0" ]
null
null
null
44.426036
111
0.695392
2,713
/* * Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved. */ package com.huawei.flowcontrol.core.datasource.zookeeper; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.ReadableDataSource; import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource; import com.alibaba.csp.sentinel.log.RecordLog; import com.alibaba.csp.sentinel.slots.block.AbstractRule; import com.alibaba.csp.sentinel.slots.block.SentinelRpcException; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import com.alibaba.csp.sentinel.slots.system.SystemRule; import com.alibaba.csp.sentinel.slots.system.SystemRuleManager; import com.alibaba.csp.sentinel.util.AppNameUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.huawei.flowcontrol.core.config.CommonConst; import com.huawei.flowcontrol.core.config.ConfigConst; import com.huawei.flowcontrol.core.datasource.DataSourceManager; import com.huawei.flowcontrol.core.util.PluginConfigUtil; import com.huawei.flowcontrol.core.util.RedisRuleUtil; import java.lang.reflect.Type; import java.util.List; /** * 加载流控规则 * * @author liyi * @since 2020-08-26 */ public class ZookeeperDatasourceManager implements DataSourceManager { /** * 初始化规则 */ @Override public void initRules() { try { RecordLog.info("initRules begin...."); String remoteAddress = PluginConfigUtil.getValueByKey(ConfigConst.SENTINEL_ZOOKEEPER_ADDRESS); String rootPath = fixRootPath(PluginConfigUtil.getValueByKey(ConfigConst.SENTINEL_ZOOKEEPER_PATH)); String appName = AppNameUtil.getAppName(); loadFlowRule(remoteAddress, rootPath, appName); loadDegradeRule(remoteAddress, rootPath, appName); loadSystemRule(remoteAddress, rootPath, appName); loadAuthorityRule(remoteAddress, rootPath, appName); RecordLog.info("initRules end"); } catch (SentinelRpcException e) { RecordLog.error("[BootInterceptor] initRules loading failed=" + e); } finally { if (FlowRuleManager.getRules().size() == 0) { // 判断后执行加载redis配置文件 RedisRuleUtil.loadRules(); } } } private String fixRootPath(String rootPath) { if (rootPath == null || "".equals(rootPath.trim())) { return ""; } return rootPath.startsWith(CommonConst.SLASH_SIGN) ? rootPath.substring(1) : rootPath; } private String getGroupId(String rootPath, String appName) { if ("".equals(rootPath)) { return appName; } return rootPath + CommonConst.SLASH_SIGN + appName; } private void loadAuthorityRule(String remoteAddress, String rootPath, String appName) { // 加载授权规则 String group = getGroupId(rootPath, appName); // 加载授权规则 String authorityRulePath = CommonConst.SLASH_SIGN + group + CommonConst.SLASH_SIGN + CommonConst.SENTINEL_RULE_AUTHORITY; RecordLog.info("the authorityRule path in zookeeper =" + authorityRulePath); ReadableDataSource<String, List<AuthorityRule>> authorityRuleDataSource = new ZookeeperDataSource<List<AuthorityRule>>( remoteAddress, authorityRulePath, new ZookeeperDataSourceConverter<List<AuthorityRule>>( new FlowControlTypeReference<AuthorityRule>(AuthorityRule.class))); AuthorityRuleManager.register2Property(authorityRuleDataSource.getProperty()); printlnRules("AuthorityRule", AuthorityRuleManager.getRules()); } private void loadSystemRule(String remoteAddress, String rootPath, String appName) { // 加载系统规则 String group = getGroupId(rootPath, appName); String systemRulePath = CommonConst.SLASH_SIGN + group + CommonConst.SLASH_SIGN + CommonConst.SENTINEL_RULE_SYSTEM; RecordLog.info("The systemRule path in zookeeper =" + systemRulePath); ReadableDataSource<String, List<SystemRule>> systemRuleDataSource = new ZookeeperDataSource<List<SystemRule>>( remoteAddress, systemRulePath, new ZookeeperDataSourceConverter<List<SystemRule>>( new FlowControlTypeReference<SystemRule>(SystemRule.class))); SystemRuleManager.register2Property(systemRuleDataSource.getProperty()); printlnRules("SystemRule", SystemRuleManager.getRules()); } private void loadDegradeRule(String remoteAddress, String rootPath, String appName) { // 加载降级规则 String group = getGroupId(rootPath, appName); String degradeRulePath = CommonConst.SLASH_SIGN + group + CommonConst.SLASH_SIGN + CommonConst.SENTINEL_RULE_DEGRADE; RecordLog.info("The degradeRule path in zookeeper =" + degradeRulePath); ReadableDataSource<String, List<DegradeRule>> degradeRuleDataSource = new ZookeeperDataSource<List<DegradeRule>>( remoteAddress, degradeRulePath, new ZookeeperDataSourceConverter<List<DegradeRule>>( new FlowControlTypeReference<DegradeRule>(DegradeRule.class))); DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty()); printlnRules("DegradeRule", DegradeRuleManager.getRules()); } private void loadFlowRule(String remoteAddress, String rootPath, String appName) { // 加载流控规则 String group = getGroupId(rootPath, appName); String flowRulePath = CommonConst.SLASH_SIGN + group + CommonConst.SLASH_SIGN + CommonConst.SENTINEL_RULE_FLOW; RecordLog.info("The flowRule path in zookeeper =" + flowRulePath); ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<List<FlowRule>>( remoteAddress, flowRulePath, new ZookeeperDataSourceConverter<List<FlowRule>>( new FlowControlTypeReference<FlowRule>(FlowRule.class))); FlowRuleManager.register2Property(flowRuleDataSource.getProperty()); printlnRules("FlowRule", FlowRuleManager.getRules()); } private <T extends AbstractRule> void printlnRules(String ruleTypeName, List<T> rules) { for (AbstractRule rule : rules) { RecordLog.info(String.format("%s has : %s", ruleTypeName, rule.getResource())); } } static class ZookeeperDataSourceConverter<T> implements Converter<String, T> { private final TypeReference<T> typeReference; ZookeeperDataSourceConverter(TypeReference<T> typeReference) { this.typeReference = typeReference; } @Override public T convert(String source) { return JSON.parseObject(source, typeReference); } } static class FlowControlTypeReference<T> extends TypeReference<List<T>> { public FlowControlTypeReference(Type... actualTypeArguments) { super(actualTypeArguments); } } }
3e06658e2fb4093a066146ffc5723bcb19dd0f53
3,946
java
Java
pxlab/src/main/java/de/pxlab/pxl/display/DeuteranopicConfusionColors.java
manuelgentile/pxlab
c8d29347d36c3e758bac4115999fc88143c84f87
[ "MIT", "Unlicense" ]
1
2019-03-04T11:10:59.000Z
2019-03-04T11:10:59.000Z
pxlab/src/main/java/de/pxlab/pxl/display/DeuteranopicConfusionColors.java
manuelgentile/pxlab
c8d29347d36c3e758bac4115999fc88143c84f87
[ "MIT", "Unlicense" ]
null
null
null
pxlab/src/main/java/de/pxlab/pxl/display/DeuteranopicConfusionColors.java
manuelgentile/pxlab
c8d29347d36c3e758bac4115999fc88143c84f87
[ "MIT", "Unlicense" ]
null
null
null
39.069307
81
0.647238
2,714
package de.pxlab.pxl.display; import java.awt.*; import de.pxlab.pxl.*; /** * Deuteranopic Confusion Colors. * * <P> * The hues of the three columns of this pattern are indiscriminable for * deuteranopes. They lie on the deuteranopic confusion line. * * <P> * Only the top left and top right colors are adjustable. All other fields are * computed. The center column is a mixture of the left and right column. * * <P> * Pokorny, J. & Smith, V. C. (1986). Colorimetry and color discrimination. In * K. R. Boff, L. Kaufman & J. P. Thomas (Eds.) Handbook of perception and human * performance. Vol. I. Sensory processes and perception, Chapter 8. New York: * Wiley. * * @author M. Hodapp * @version 0.1.0 */ /* * 05/15/00 */ public class DeuteranopicConfusionColors extends Display { public ExPar Color1 = new ExPar(COLOR, new ExParValue(38.11, 0.390, 0.257), "Color of the field 1"); public ExPar Color2 = new ExPar(COLOR, new ExParValue(22.90, 0.388, 0.256), "Color of the field 2"); public ExPar Color3 = new ExPar(COLOR, new ExParValue(14.06, 0.388, 0.262), "Color of the field 3"); public ExPar Color4 = new ExPar(COLOR, new ExParValue(58.25, 0.298, 0.323), "Color of the field 4"); public ExPar Color5 = new ExPar(COLOR, new ExParValue(34.70, 0.298, 0.322), "Color of the field 5"); public ExPar Color6 = new ExPar(COLOR, new ExParValue(20.53, 0.294, 0.318), "Color of the field 6"); public ExPar Color7 = new ExPar(COLOR, new ExParValue(76.48, 0.230, 0.364), "Color of the field 7"); public ExPar Color8 = new ExPar(COLOR, new ExParValue(46.05, 0.231, 0.366), "Color of the field 8"); public ExPar Color9 = new ExPar(COLOR, new ExParValue(27.28, 0.231, 0.366), "Color of the field 9"); public DeuteranopicConfusionColors() { setTitleAndTopic("Deuteranopic confusion colors", COLOR_DISCRIMINATION_DSP | DEMO); } private int s1, s2, s3, s4, s5, s6, s7, s8, s9; /** Initialize the display list of the demo. */ protected int create() { s1 = enterDisplayElement(new Bar(Color1)); s2 = enterDisplayElement(new Bar(Color2)); s3 = enterDisplayElement(new Bar(Color3)); s4 = enterDisplayElement(new Bar(Color4)); s5 = enterDisplayElement(new Bar(Color5)); s6 = enterDisplayElement(new Bar(Color6)); s7 = enterDisplayElement(new Bar(Color7)); s8 = enterDisplayElement(new Bar(Color8)); s9 = enterDisplayElement(new Bar(Color9)); defaultTiming(0); return (s2); } protected void computeGeometry() { int msize = largeSquareSize(width, height); Rectangle ms = largeSquare(width, height); Rectangle r1 = new Rectangle(ms.x, ms.y, msize / 14 * 4, msize / 14 * 4); Rectangle r2 = new Rectangle(ms.x, ms.y + msize / 14 * 5, msize / 14 * 4, msize / 14 * 4); Rectangle r3 = new Rectangle(ms.x, ms.y + msize / 14 * 10, msize / 14 * 4, msize / 14 * 4); Rectangle r4 = new Rectangle(ms.x + msize / 14 * 5, ms.y, msize / 14 * 4, msize / 14 * 4); Rectangle r5 = new Rectangle(ms.x + msize / 14 * 5, ms.y + msize / 14 * 5, msize / 14 * 4, msize / 14 * 4); Rectangle r6 = new Rectangle(ms.x + msize / 14 * 5, ms.y + msize / 14 * 10, msize / 14 * 4, msize / 14 * 4); Rectangle r7 = new Rectangle(ms.x + msize / 14 * 10, ms.y, msize / 14 * 4, msize / 14 * 4); Rectangle r8 = new Rectangle(ms.x + msize / 14 * 10, ms.y + msize / 14 * 5, msize / 14 * 4, msize / 14 * 4); Rectangle r9 = new Rectangle(ms.x + msize / 14 * 10, ms.y + msize / 14 * 10, msize / 14 * 4, msize / 14 * 4); getDisplayElement(s1).setRect(r1); getDisplayElement(s2).setRect(r2); getDisplayElement(s3).setRect(r3); getDisplayElement(s4).setRect(r4); getDisplayElement(s5).setRect(r5); getDisplayElement(s6).setRect(r6); getDisplayElement(s7).setRect(r7); getDisplayElement(s8).setRect(r8); getDisplayElement(s9).setRect(r9); } }
3e0665b300ccbfcaaa179cd3390e6b477e5bbc5a
1,032
java
Java
sharding-jdbc-core/src/test/java/com/dangdang/ddframe/rdb/sharding/parsing/parser/jaxb/Conditions.java
wangjianwen/sharding-jdbc
b554f7bcd7762dccf8eb87b5b9173bd9c488b187
[ "Apache-2.0" ]
114
2017-09-25T03:04:52.000Z
2022-03-16T15:38:44.000Z
sharding-jdbc-core/src/test/java/com/dangdang/ddframe/rdb/sharding/parsing/parser/jaxb/Conditions.java
collery/sharding-jdbc
d6ac50704f5e45beeeded09a4f0b160c7320b993
[ "Apache-2.0" ]
3
2022-01-21T23:22:16.000Z
2022-03-31T21:02:43.000Z
sharding-jdbc-core/src/test/java/com/dangdang/ddframe/rdb/sharding/parsing/parser/jaxb/Conditions.java
collery/sharding-jdbc
d6ac50704f5e45beeeded09a4f0b160c7320b993
[ "Apache-2.0" ]
110
2017-07-31T00:17:14.000Z
2022-03-16T15:38:34.000Z
29.485714
75
0.750969
2,715
/* * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package com.dangdang.ddframe.rdb.sharding.parsing.parser.jaxb; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import lombok.Getter; @Getter @XmlAccessorType(XmlAccessType.FIELD) public final class Conditions { @XmlElement(name = "condition") private List<Condition> conditions; }