hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
705ce385b09c83547c2c3ae74ab6c20c36d6e6ef
3,054
package ca.uhn.fhir.parser.i391; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.primitive.BoundCodeDt; import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.parser.CustomTypeDstu2Test; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.util.TestUtil; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * See #391 */ public class TestOutcomeTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CustomTypeDstu2Test.class); @Test public void testCustomDataTypeBugN2_UnknownElement() { CustomBlock nameDt = new CustomBlock(); nameDt.ourValue = new StringDt("testText"); CustomOperationOutcome outcome = new CustomOperationOutcome(); outcome.element2 = nameDt; IParser parser = FhirContext.forDstu2().newXmlParser(); String outcomeString = parser.setPrettyPrint(true).encodeResourceToString(outcome); ourLog.info(outcomeString); assertEquals("<OperationOutcome xmlns=\"http://hl7.org/fhir\">" + "<meta>" + "<profile value=\"http://hl7.org/fhir/profiles/custom-operation-outcome\"/>" + "</meta>" + "<extension url=\"#someElement2\">" + "<valueString value=\"testText\"/>" + "</extension>" + "</OperationOutcome>", parser.setPrettyPrint(false).encodeResourceToString(outcome)); CustomOperationOutcome parsedOutcome = parser.parseResource(CustomOperationOutcome.class, outcomeString); ourLog.info(outcomeString); // assertNotNull(parsedOutcome.element2); // assertNotNull(parsedOutcome.element2.ourValue); } @Test public void testParseBoundCodeDtJson() { IParser jsonParser = FhirContext.forDstu2().newJsonParser(); TestOutcome outcome = new TestOutcome(); outcome.setElement(new BoundCodeDt<OutcomeEnum>(new OutcomeBinder(), OutcomeEnum.ITEM1)); String xmlResource = jsonParser.encodeResourceToString(outcome); TestOutcome operationOutcome = jsonParser.parseResource(TestOutcome.class, xmlResource); assertNotNull(operationOutcome.getElement()); assertTrue(operationOutcome.getElement() instanceof BoundCodeDt); assertEquals(outcome.getElement(), operationOutcome.getElement()); } @Test public void testParseBoundCodeDtXml() { IParser xmlParser = FhirContext.forDstu2().newXmlParser(); TestOutcome outcome = new TestOutcome(); outcome.setElement(new BoundCodeDt<OutcomeEnum>(new OutcomeBinder(), OutcomeEnum.ITEM1)); String xmlResource = xmlParser.encodeResourceToString(outcome); TestOutcome operationOutcome = xmlParser.parseResource(TestOutcome.class, xmlResource); assertNotNull(operationOutcome.getElement()); assertTrue(operationOutcome.getElement() instanceof BoundCodeDt); assertEquals(outcome.getElement(), operationOutcome.getElement()); } @AfterAll public static void afterClassClearContext() { TestUtil.clearAllStaticFieldsForUnitTest(); } }
35.103448
109
0.774394
7b3dfcb3d07a7b15a29d5a36d780f431ddaa12fa
355
package cn.com.vipkid.vkdns; // _ _ _ _ //__ _(_)_ __ | | _(_) __| | //\ \ / / | '_ \| |/ / |/ _` | // \ V /| | |_) | <| | (_| | // \_/ |_| .__/|_|\_\_|\__,_| // |_| /* * *2018/11/2 */ class Constants { static final String TAG = "httpdns"; static final String HTTPDNS_RESULT_FORMAT = "result : host->%s;ip->%s"; }
19.722222
73
0.433803
417a30b9233da1bef84efeaafc3165e70bb4e042
1,128
package org.jimmutable.core.serialization; import org.jimmutable.core.exceptions.ValidationException; import org.jimmutable.core.objects.Stringable; import junit.framework.TestCase; /** * This class cannot be used across projects as it lives in the test folder of * Jimmutable core. The test folder is local to just core. In order to test a * Stringable using utilities from jimmutable you should instead use * StringableTestingUtils from jimmutable core. */ abstract public class StringableTest extends TestCase { abstract public Stringable fromString(String src); public StringableTest( String testName ) { super( testName ); } public void assertNotValid(String src_code) { try { Stringable test = fromString(src_code); fail(); // failure, should have not been valid } catch(ValidationException e) { // This is what we expect } } public void assertValid(String src_code, String expected_value) { try { Stringable test = fromString(src_code); assertEquals(test.getSimpleValue(),expected_value); } catch(Exception e) { e.printStackTrace(); fail(); } } }
22.117647
78
0.734929
e649a4576c41df887dde231f703ce781ef7242f6
509
package main.models.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** Model for newsapi.org error response */ @JsonIgnoreProperties(value={"status"}) public class NewsResponseError { private String code; private String message; public String getCode() { return code; } public String getMessage() { return message; } public void setCode(String code) { this.code = code; } public void setMessage(String message) { this.message = message; } }
18.178571
61
0.709234
d163ee82746197eb94bfdafe7e8aa0c26afc8211
6,731
package com.newegg.ec.redis.controller; import com.alibaba.fastjson.JSONObject; import com.newegg.ec.redis.aop.annotation.OperationLog; import com.newegg.ec.redis.entity.OperationObjectType; import com.newegg.ec.redis.entity.OperationType; import com.newegg.ec.redis.entity.Result; import com.newegg.ec.redis.entity.SentinelMaster; import com.newegg.ec.redis.service.IClusterService; import com.newegg.ec.redis.service.IRedisService; import com.newegg.ec.redis.service.ISentinelMastersService; import com.newegg.ec.redis.util.RedisUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Everly.J.Ju * @date 2020/2/12 */ @RequestMapping("/sentinel/*") @Controller public class SentinelMasterController { private static final Logger logger = LoggerFactory.getLogger(SentinelMasterController.class); @Autowired private IRedisService redisService; @Autowired private ISentinelMastersService sentinelMastersService; @Autowired private IClusterService clusterService; @RequestMapping(value = "/getSentinelMasterList/{clusterId}", method = RequestMethod.GET) @ResponseBody public Result getMasterInformation(@PathVariable("clusterId") Integer clusterId) { List<SentinelMaster> sentinelMaster = sentinelMastersService.getSentinelMasterByClusterId(clusterId); return Result.successResult(sentinelMaster); } @RequestMapping(value = "/getSentinelMasterByName", method = RequestMethod.POST) @ResponseBody public Result getSentinelMasterById(@RequestBody SentinelMaster sentinelMaster) { SentinelMaster sentinelMasterByName = sentinelMastersService.getSentinelMasterByMasterName(sentinelMaster.getClusterId(), sentinelMaster.getName()); return sentinelMasterByName != null ? Result.successResult(sentinelMaster) : Result.failResult(); } @RequestMapping(value = "/getSentinelMasterInfo", method = RequestMethod.POST) @ResponseBody public Result getSentinelMasterInfo(@RequestBody SentinelMaster sentinelMaster) { Map<String, String> masterMap = redisService.getSentinelMasterInfoByName(sentinelMaster); if (masterMap == null) { return Result.failResult(); } List<JSONObject> infoList = new ArrayList<>(); masterMap.forEach((key, value) -> { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", key); jsonObject.put("value", value); infoList.add(jsonObject); }); return Result.successResult(infoList); } //新增,移除 sentinel master @RequestMapping(value = "/addSentinelMaster", method = RequestMethod.POST) @ResponseBody @OperationLog(type = OperationType.UPDATE, objType = OperationObjectType.CLUSTER) public Result add(@RequestBody SentinelMaster sentinelMaster) { boolean result = sentinelMastersService.addSentinelMaster(sentinelMaster); return result ? Result.successResult() : Result.failResult(); } @RequestMapping(value = "/deleteSentinelMaster", method = RequestMethod.POST) @ResponseBody @OperationLog(type = OperationType.UPDATE, objType = OperationObjectType.CLUSTER) public Result deleteSentinelMaster(@RequestBody SentinelMaster sentinelMaster) { boolean result = redisService.sentinelRemove(sentinelMaster) && sentinelMastersService.deleteSentinelMasterByName(sentinelMaster.getClusterId(), sentinelMaster.getName()); return result ? Result.successResult() : Result.failResult(); } @RequestMapping(value = "/monitorMaster", method = RequestMethod.POST) @ResponseBody @OperationLog(type = OperationType.UPDATE, objType = OperationObjectType.CLUSTER) public Result monitorMaster(@RequestBody SentinelMaster sentinelMaster) { boolean result = redisService.monitorMaster(sentinelMaster); if (result) { boolean saveResult = sentinelMastersService.addSentinelMaster(sentinelMaster); return saveResult ? Result.successResult() : Result.failResult(); } return Result.failResult(); } @RequestMapping(value = "/updateSentinelMaster", method = RequestMethod.POST) @ResponseBody @OperationLog(type = OperationType.UPDATE, objType = OperationObjectType.CLUSTER) public Result updateSentinelMaster(@RequestBody SentinelMaster sentinelMaster) { boolean result = redisService.sentinelSet(sentinelMaster); if (result) { boolean saveResult = sentinelMastersService.updateSentinelMaster(sentinelMaster); return saveResult ? Result.successResult() : Result.failResult(); } return Result.failResult(); } @RequestMapping(value = "/failoverSentinelMaster", method = RequestMethod.POST) @ResponseBody @OperationLog(type = OperationType.UPDATE, objType = OperationObjectType.CLUSTER) public Result failoverSentinelMaster(@RequestBody SentinelMaster sentinelMaster) { boolean result = redisService.failoverMaster(sentinelMaster); if (result) { Map<String, String> sentinelMasterInfoByName = redisService.getSentinelMasterInfoByName(sentinelMaster); String ip = sentinelMasterInfoByName.get("ip"); Integer port = Integer.parseInt(sentinelMasterInfoByName.get("port")); sentinelMaster.setHost(ip); sentinelMaster.setPort(port); sentinelMaster.setLastMasterNode(RedisUtil.getNodeString(ip, port)); boolean saveResult = sentinelMastersService.updateSentinelMaster(sentinelMaster); return saveResult ? Result.successResult() : Result.failResult(); } return Result.failResult(); } @RequestMapping(value = "/getSentinelMasterSlaves", method = RequestMethod.POST) @ResponseBody public Result getSentinelMasterSlaves(@RequestBody SentinelMaster sentinelMaster) { List<Map<String, String>> slaves = redisService.sentinelSlaves(sentinelMaster); if (slaves == null) { return Result.failResult(); } List<JSONObject> infoList = new ArrayList<>(); for (Map<String, String> slave : slaves) { slave.forEach((key, value) -> { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", key); jsonObject.put("value", value); infoList.add(jsonObject); }); } return Result.successResult(infoList); } }
43.993464
156
0.718615
57f2b723519e16c894156450c6a423802c987843
2,484
package com.avides.xml.saxxomparser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.ext.DefaultHandler2; import nu.xom.Attribute; import nu.xom.Document; import nu.xom.Element; public class DocumentSaxParser extends DefaultHandler2 { private String elementTagName; private DocumentCallbackHandler callbackHandler; private Document document; private Element currentElement; public DocumentSaxParser(String elementTagName, DocumentCallbackHandler callback) { this.elementTagName = elementTagName; this.callbackHandler = callback; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (document == null && elementTagName.equals(qName)) { Element rootElement = createElement(qName, attributes); document = new Document(rootElement); } else if (document != null && currentElement == null) { currentElement = createElement(qName, attributes); document.getRootElement().appendChild(currentElement); } else if (currentElement != null) { Element element = createElement(qName, attributes); currentElement.appendChild(element); currentElement = element; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (currentElement != null && currentElement.getParent() instanceof Element) { currentElement = (Element) currentElement.getParent(); } if (elementTagName.equals(qName)) { callbackHandler.process(document); document = null; currentElement = null; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (currentElement != null) { currentElement.appendChild(new String(ch, start, length)); } } private static Element createElement(String name, Attributes attributes) { Element element = new Element(name); for (int i = 0; i < attributes.getLength(); i++) { String key = attributes.getLocalName(i); String value = attributes.getValue(i); element.addAttribute(new Attribute(key, value)); } return element; } }
29.571429
115
0.637279
4e6aa6120850469b5555bd9700ef585bd0d485c5
8,546
/* * 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.cassandra.db; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ExecutionException; import org.junit.Test; import org.apache.cassandra.CleanupHelper; import org.apache.cassandra.db.filter.IdentityQueryFilter; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.io.SSTableReader; import static junit.framework.Assert.assertEquals; import static org.apache.cassandra.db.TableTest.assertColumns; public class CompactionsPurgeTest extends CleanupHelper { public static final String TABLE1 = "Keyspace1"; public static final String TABLE2 = "Keyspace2"; @Test public void testMajorCompactionPurge() throws IOException, ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Table table = Table.open(TABLE1); String cfName = "Standard1"; ColumnFamilyStore cfs = table.getColumnFamilyStore(cfName); String key = "key1"; RowMutation rm; // inserts rm = new RowMutation(TABLE1, key); for (int i = 0; i < 10; i++) { rm.add(new QueryPath(cfName, null, String.valueOf(i).getBytes()), new byte[0], 0); } rm.apply(); cfs.forceBlockingFlush(); // deletes for (int i = 0; i < 10; i++) { rm = new RowMutation(TABLE1, key); rm.delete(new QueryPath(cfName, null, String.valueOf(i).getBytes()), 1); rm.apply(); } cfs.forceBlockingFlush(); // resurrect one column rm = new RowMutation(TABLE1, key); rm.add(new QueryPath(cfName, null, String.valueOf(5).getBytes()), new byte[0], 2); rm.apply(); cfs.forceBlockingFlush(); // major compact and test that all columns but the resurrected one is completely gone CompactionManager.instance.submitMajor(cfs, 0, Integer.MAX_VALUE).get(); cfs.invalidateCachedRow(key); ColumnFamily cf = cfs.getColumnFamily(new IdentityQueryFilter(key, new QueryPath(cfName))); assertColumns(cf, "5"); assert cf.getColumn(String.valueOf(5).getBytes()) != null; } @Test public void testMinorCompactionPurge() throws IOException, ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Table table = Table.open(TABLE2); String cfName = "Standard1"; ColumnFamilyStore cfs = table.getColumnFamilyStore(cfName); RowMutation rm; for (int k = 1; k <= 2; ++k) { String key = "key" + k; // inserts rm = new RowMutation(TABLE2, key); for (int i = 0; i < 10; i++) { rm.add(new QueryPath(cfName, null, String.valueOf(i).getBytes()), new byte[0], 0); } rm.apply(); cfs.forceBlockingFlush(); // deletes for (int i = 0; i < 10; i++) { rm = new RowMutation(TABLE2, key); rm.delete(new QueryPath(cfName, null, String.valueOf(i).getBytes()), 1); rm.apply(); } cfs.forceBlockingFlush(); } String key1 = "key1"; String key2 = "key2"; // flush, remember the current sstable and then resurrect one column // for first key. Then submit minor compaction on remembered sstables. cfs.forceBlockingFlush(); Collection<SSTableReader> sstablesIncomplete = cfs.getSSTables(); rm = new RowMutation(TABLE2, key1); rm.add(new QueryPath(cfName, null, String.valueOf(5).getBytes()), new byte[0], 2); rm.apply(); cfs.forceBlockingFlush(); CompactionManager.instance.doCompaction(cfs, sstablesIncomplete, Integer.MAX_VALUE); // verify that minor compaction does not GC when key is present // in a non-compacted sstable ColumnFamily cf = cfs.getColumnFamily(new IdentityQueryFilter(key1, new QueryPath(cfName))); assert cf.getColumnCount() == 10; // verify that minor compaction does GC when key is provably not // present in a non-compacted sstable cf = cfs.getColumnFamily(new IdentityQueryFilter(key2, new QueryPath(cfName))); assert cf == null; } @Test public void testCompactionPurgeOneFile() throws IOException, ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Table table = Table.open(TABLE1); String cfName = "Standard2"; ColumnFamilyStore store = table.getColumnFamilyStore(cfName); String key = "key1"; RowMutation rm; // inserts rm = new RowMutation(TABLE1, key); for (int i = 0; i < 5; i++) { rm.add(new QueryPath(cfName, null, String.valueOf(i).getBytes()), new byte[0], 0); } rm.apply(); // deletes for (int i = 0; i < 5; i++) { rm = new RowMutation(TABLE1, key); rm.delete(new QueryPath(cfName, null, String.valueOf(i).getBytes()), 1); rm.apply(); } store.forceBlockingFlush(); assert store.getSSTables().size() == 1 : store.getSSTables(); // inserts & deletes were in the same memtable -> only deletes in sstable // compact and test that the row is completely gone CompactionManager.instance.submitMajor(store, 0, Integer.MAX_VALUE).get(); assert store.getSSTables().isEmpty(); ColumnFamily cf = table.getColumnFamilyStore(cfName).getColumnFamily(new IdentityQueryFilter(key, new QueryPath(cfName))); assert cf == null : cf; } @Test public void testKeyCache50() throws IOException, ExecutionException, InterruptedException { testKeyCache("Standard3", 64); } @Test public void testKeyCache100() throws IOException, ExecutionException, InterruptedException { testKeyCache("Standard4", 128); } public void testKeyCache(String cfname, int expectedCacheSize) throws IOException, ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Table table = Table.open(TABLE1); String cfName = cfname; ColumnFamilyStore store = table.getColumnFamilyStore(cfName); // KeyCache should start at size 1 if we're caching X% of zero data. int keyCacheSize = store.getKeyCacheCapacity(); assert keyCacheSize == 1 : keyCacheSize; String key1 = "key1"; String key2 = "key2"; RowMutation rm; // inserts rm = new RowMutation(TABLE1, key1); rm.add(new QueryPath(cfName, null, "1".getBytes()), new byte[0], 0); rm.apply(); rm = new RowMutation(TABLE1, key2); rm.add(new QueryPath(cfName, null, "2".getBytes()), new byte[0], 0); rm.apply(); // deletes rm = new RowMutation(TABLE1, key1); rm.delete(new QueryPath(cfName, null, "1".getBytes()), 1); rm.apply(); rm = new RowMutation(TABLE1, key2); rm.delete(new QueryPath(cfName, null, "2".getBytes()), 1); rm.apply(); // After a flush, the cache should expand to be X% of indices * INDEX_INTERVAL. store.forceBlockingFlush(); keyCacheSize = store.getKeyCacheCapacity(); assert keyCacheSize == expectedCacheSize : keyCacheSize; // After a compaction, the cache should expand to be X% of zero data. CompactionManager.instance.submitMajor(store, 0, Integer.MAX_VALUE).get(); keyCacheSize = store.getKeyCacheCapacity(); assert keyCacheSize == 1 : keyCacheSize; } }
36.678112
143
0.63831
0fe75454f1d2c065ac566d66ef0a993be1f34e4d
894
import java.util.*; /** * Created by AMK on 7/30/2019. * Life is nice :) * Enjoy coding :D */ public class Main2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); for (int i = 0; i < T; i++) { int n = scanner.nextInt(); ArrayList<Integer> arrayList = new ArrayList<>(); for (int j = 0; j < n; j++) { int m = scanner.nextInt(); arrayList.add(m); } int ans = 1; int sum = 1; for (int j = 1; j < arrayList.size() - 1; j++) { if (sum + arrayList.get(j) < arrayList.get(j + 1)){ sum += arrayList.get(j); ans++; } } System.out.println(++ans); } } }
27.9375
68
0.412752
32731e7a50164497fb1ea346ef7138a2fd84c660
681
package com.moomoohk.JNotificationCenter.notifications; import com.moomoohk.JNotificationCenter.OSXSoundEffect; public class SimpleNotification extends Notification { public SimpleNotification(String title, String message, String subtitle) { super(title, message, subtitle); } public SimpleNotification(String title, String message, String subtitle, String sender, OSXSoundEffect sound) { super(title, message, subtitle, sender, sound); } @Override public void show() { show(this.title, this.message, this.subtitle, this.sender, this.sound.toString()); } private native void show(String title, String message, String subtitle, String sender, String sound); }
27.24
110
0.779736
9786992c974a71c69512bd1706b02cc66f59ca22
749
package com.example.lottery.application; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.example.lottery.service.LotteryService; import com.example.lottery.service.RandomNumberGeneratorService; public class LotteryApp { private static final String BASE_PACKAGE = "com.example.lottery"; public static void main(String[] args) { var container = new AnnotationConfigApplicationContext(BASE_PACKAGE); container.getBean(LotteryService.class) .draw(60, 6, 10) .forEach(System.out::println); var randomSrv = container.getBean("fastRandomService", RandomNumberGeneratorService.class); System.out.println(randomSrv.generate(100, 200)); container.close(); } }
29.96
81
0.76769
06e120020739cc256b68ca1ff1f8e0e48d9d9c66
1,246
package com.medical.soft.persistence.entity; import javax.persistence.*; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.List; @Entity @Table(name = "lugar") public class Lugar implements Externalizable { @Id @Column(name = "cod_lugar") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer codLugar; // Attributes private String lugar; // Relationships @OneToMany(mappedBy = "lugar") private List<Paciente> pacientes; // Methods public String getLugar() { return lugar; } public void setLugar(String lugar) { this.lugar = lugar; } public Integer getCodLugar() { return codLugar; } public void setCodLugar(Integer codLugar) { this.codLugar = codLugar; } public List<Paciente> getPacientes() { return pacientes; } public void setPacientes(List<Paciente> pacientes) { this.pacientes = pacientes; } @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } }
20.766667
89
0.675762
406618755431558e05b163d2cc6c28b326e65c8e
2,630
/* * Copyright 2021 EPAM Systems * * 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.ta.reportportal.core.launch.cluster.pipeline.data; import com.epam.ta.reportportal.core.analyzer.auto.client.AnalyzerServiceClient; import com.epam.ta.reportportal.core.analyzer.auto.impl.preparer.LaunchPreparerService; import com.epam.ta.reportportal.core.launch.GetLaunchHandler; import com.epam.ta.reportportal.core.launch.cluster.config.ClusterEntityContext; import com.epam.ta.reportportal.core.launch.cluster.config.GenerateClustersConfig; import com.epam.ta.reportportal.dao.TestItemRepository; import com.epam.ta.reportportal.entity.item.TestItem; import com.epam.ta.reportportal.entity.launch.Launch; import com.epam.ta.reportportal.ws.model.analyzer.IndexLaunch; import org.apache.commons.collections4.CollectionUtils; import java.util.List; import java.util.Optional; /** * @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a> */ public class AnalyzerItemClusterDataProvider extends AnalyzerClusterDataProvider { private final GetLaunchHandler getLaunchHandler; private final TestItemRepository testItemRepository; private final LaunchPreparerService launchPreparerService; public AnalyzerItemClusterDataProvider(AnalyzerServiceClient analyzerServiceClient, GetLaunchHandler getLaunchHandler, TestItemRepository testItemRepository, LaunchPreparerService launchPreparerService) { super(analyzerServiceClient); this.getLaunchHandler = getLaunchHandler; this.testItemRepository = testItemRepository; this.launchPreparerService = launchPreparerService; } @Override protected Optional<IndexLaunch> prepareIndexLaunch(GenerateClustersConfig config) { final ClusterEntityContext entityContext = config.getEntityContext(); if (CollectionUtils.isEmpty(entityContext.getItemIds())) { return Optional.empty(); } final Launch launch = getLaunchHandler.get(entityContext.getLaunchId()); final List<TestItem> testItems = testItemRepository.findAllById(entityContext.getItemIds()); return launchPreparerService.prepare(launch, testItems, config.getAnalyzerConfig()); } }
43.114754
119
0.814829
7a80d5358d0fa1197e8dcbf9d14c48f401d4ae9f
5,031
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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 git4idea.commands; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.util.Key; import gnu.trove.TObjectDoubleHashMap; import gnu.trove.TObjectDoubleProcedure; import org.jetbrains.annotations.NotNull; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Captures standard remote operation notifications: "counting objects", "compressing objects", "receiving objects", "resolving deltas" and returns the fraction based on the stage of the command execution. * Some operations or some progress indications may be skipped - this will be handled properly. * @author Kirill Likhodedov */ public class GitStandardProgressAnalyzer implements GitProgressAnalyzer { // progress of each operation is stored here. this is an overhead since operations go one by one, // but it looks simpler than storing current operation, checking that there was no skipped, etc. private final TObjectDoubleHashMap<Operation> myOperationsProgress = new TObjectDoubleHashMap<>(4); public static GitLineHandlerListener createListener(@NotNull final ProgressIndicator indicator) { final GitStandardProgressAnalyzer progressAnalyzer = new GitStandardProgressAnalyzer(); return new GitLineHandlerListener() { @Override public void onLineAvailable(String line, Key outputType) { final double fraction = progressAnalyzer.analyzeProgress(line); if (fraction >= 0) { indicator.setFraction(fraction); indicator.setText2(line); } } }; } /** * A long git command usually consists of the operations in this enum. * A pattern is used to match the operation from the git output. fraction is used to indicate which part of the total git command * this operation takes (these numbers are not strict, we can't predict how much it will take in reality): * counting objects - 5% * compressing objects - 10 % * receiving objects - 80 % * resolving deltas - 5 % */ private enum Operation { COUNTING_OBJECTS(".*Counting objects: +(\\d+).*", 0.05) { @Override double getProgress(int outputNumber) { // no percentage is given. +20% on each thousand objects. if (outputNumber > 5000) { return 1; } return outputNumber / 5000.0; } }, COMPRESSING_OBJECTS(".*Compressing objects: +(\\d{1,3})%.*", 0.1), RECEIVING_OR_WRITING_OBJECTS(".*(?:Receiving|Writing) objects: +(\\d{1,3})%.*", 0.8), // receiving on fetch, writing on push RESOLVING_DELTAS(".*Resolving deltas: +(\\d{1,3})%.*", 0.05); private final Pattern myPattern; private final double myFractionInTotal; Operation(String pattern, double fractionInTotal) { myPattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); myFractionInTotal = fractionInTotal; } /** * Returns the progress of the operation - the completed fraction (between 0 and 1.0) - basing on the integer given by the git * command output. This output number usually is a percent, but it may vary (see implementations of the method). */ double getProgress(int outputNumber) { return outputNumber / 100.0; } } @Override public double analyzeProgress(String output) { for (Operation operation : Operation.values()) { final Matcher matcher = operation.myPattern.matcher(output); if (matcher.matches()) { try { double operationProgress = operation.getProgress(Integer.parseInt(matcher.group(1))); // progress of this operation myOperationsProgress.put(operation, operationProgress); } catch (NumberFormatException e) { return -1; } return updateTotalProgress(operation); } } return -1; } private double updateTotalProgress(Operation currentOperation) { // marking all operations before this one as completed for (Operation op : Operation.values()) { if (currentOperation.compareTo(op) > 0) { myOperationsProgress.put(op, 1.0); } } // counting progress final double[] totalProgress = new double[1]; myOperationsProgress.forEachEntry(new TObjectDoubleProcedure<Operation>() { @Override public boolean execute(Operation operation, double progress) { totalProgress[0] += operation.myFractionInTotal * progress; return true; } }); return totalProgress[0]; } }
39
205
0.702445
a301373b797385bbd286f9228286f26ae6cafc17
2,582
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; @Autonomous(name="RedFoundation") public class RedFoundation extends LinearOpMode { HardwareBot robot = new HardwareBot(); Movement move = new Movement(robot,this); Pathways path = new Pathways(robot,move,this); ElapsedTime gyroTimer = new ElapsedTime(); @Override public void runOpMode() { robot.init(hardwareMap,telemetry,true); waitForStart(); while(opModeIsActive()) { normFound(); } } public void normFound() { move.encoderStrafe(0.4,12,1.0); move.turn(0); // move.encoderStrafe(0.4,-4,1.0); // move.turn(0); path.gap(); robot.intakeDrop(true); path.gap(); move.gyroTime(0.3,0,1800,gyroTimer); path.gap(); robot.foundationServo(false); path.gap(); robot.setZero(); path.gap(); move.gyroTime(-0.3,0,3650,gyroTimer); path.gap(); robot.foundationServo(true); sleep(1000); gyroStrafe(0.5,0,2250,gyroTimer); move.turn(0); move.driveBackward(0.4,5,0); sleep(40000); } public void pivFound() { gyroStrafe(-0.5,0,950,gyroTimer); path.gap(); robot.intakeDrop(true); path.gap(); move.gyroTime(0.3,0,2100,gyroTimer); path.gap(); robot.foundationServo(false); path.gap(); robot.setZero(); path.gap(); move.driveBackward(0.4,10,0); move.turn(-90); path.gap(); robot.foundationServo(true); move.turn(0); move.driveBackward(0.4,25,0); sleep(40000); } // used to go forwards and backwards at a certain heading and uses time public void gyroStrafe(double power, float wantedAngle, double msec, ElapsedTime timer) { double correction; timer.reset(); while (timer.milliseconds() < msec) { correction = move.checkDirection(wantedAngle); robot.leftFront.setPower(-power + correction); robot.rightFront.setPower(power - correction); robot.leftBack.setPower(power - correction); robot.rightBack.setPower(-power + correction); } robot.setZero(); } }
28.688889
91
0.566228
4f1586e9f92e6c6355a7a4a9db95ccf5452378b2
3,975
package mcjty.lib.preferences; import mcjty.lib.McJtyLib; import mcjty.lib.gui.BuffStyle; import mcjty.lib.gui.GuiStyle; import mcjty.lib.network.PacketSendPreferencesToClient; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.util.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.fml.network.NetworkDirection; import javax.annotation.Nonnull; public class PreferencesProperties { private static final int DEFAULT_BUFFX = -20; private static final int DEFAULT_BUFFY = -20; private static final GuiStyle DEFAULT_STYLE = GuiStyle.STYLE_FLAT_GRADIENT; private int buffX = DEFAULT_BUFFX; private int buffY = DEFAULT_BUFFY; private BuffStyle buffStyle = BuffStyle.BOTRIGHT; private GuiStyle style = DEFAULT_STYLE; private boolean dirty = true; public PreferencesProperties() { } public void tick(ServerPlayerEntity player) { if (dirty) { syncToClient(player); } } private void syncToClient(ServerPlayerEntity player) { McJtyLib.networkHandler.sendTo(new PacketSendPreferencesToClient(buffStyle, buffX, buffY, style), player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); dirty = false; } public void saveNBTData(CompoundNBT compound) { compound.putString("buffStyle", buffStyle.getName()); compound.putInt("buffX", buffX); compound.putInt("buffY", buffY); compound.putString("style", style.getStyle()); } public void loadNBTData(CompoundNBT compound) { buffStyle = BuffStyle.getStyle(compound.getString("buffStyle")); if (buffStyle == null) { buffStyle = BuffStyle.BOTRIGHT; buffX = DEFAULT_BUFFX; buffY = DEFAULT_BUFFY; } else { buffX = compound.getInt("buffX"); buffY = compound.getInt("buffY"); } String s = compound.getString("style"); style = GuiStyle.getStyle(s); if (style == null) { style = DEFAULT_STYLE; } dirty = true; } public void reset() { buffStyle = BuffStyle.TOPLEFT; buffX = DEFAULT_BUFFX; buffY = DEFAULT_BUFFY; style = DEFAULT_STYLE; dirty = true; } public boolean setStyle(String s) { GuiStyle st = GuiStyle.getStyle(s); if (st == null) { return false; } style = st; dirty = true; return true; } public boolean setStyle(GuiStyle st) { if (st == null) { return false; } style = st; dirty = true; return true; } @Nonnull public GuiStyle getStyle() { return style; } public void setBuffXY(BuffStyle buffStyle, int x, int y) { this.buffStyle = buffStyle; this.buffX = x; this.buffY = y; dirty = true; } public BuffStyle getBuffStyle() { return buffStyle; } public int getBuffX() { return buffX; } public int getBuffY() { return buffY; } public static void register() { CapabilityManager.INSTANCE.register(PreferencesProperties.class, new Capability.IStorage<PreferencesProperties>() { @Override public INBT writeNBT(Capability<PreferencesProperties> capability, PreferencesProperties instance, Direction side) { throw new UnsupportedOperationException(); } @Override public void readNBT(Capability<PreferencesProperties> capability, PreferencesProperties instance, Direction side, INBT nbt) { throw new UnsupportedOperationException(); } }, () -> { throw new UnsupportedOperationException(); }); } }
28.804348
169
0.636478
a7f1199c97155d959e784232a38de62401e25683
749
package id.nap.discord.model.wordnik; public class Example { private String url; private String title; private String text; private long id; public Example() { super(); } public Example(String url, String title, String text, long id) { super(); this.url = url; this.title = title; this.text = text; this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } public long getId() { return id; } public void setId(long id) { this.id = id; } }
14.132075
65
0.64753
223fe3b9376d218d05a9ef330eca5fdaae44ccc1
4,841
package com.sykomaniac.sunwidget; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.sykomaniac.sunwidget.prefs.SharedPreferenceAPIClient; import com.sykomaniac.sunwidget.util.AlwaysMarqueeTextView; import clc.sliteplugin.flowboard.AbstractPlugin; import clc.sliteplugin.flowboard.ISpringBoardHostStub; public class widget extends AbstractPlugin { // Tag for logging purposes. private final static String TAG = "SunWidget"; // Activity variables private boolean isActive = false; private Context mContext; private View mView; private TextView sunriseView; private TextView sunsetView; private AlwaysMarqueeTextView widgetTypeView; private AlwaysMarqueeTextView updatedView; // Set up the widget's layout @Override public View getView(Context paramContext) { this.mContext = paramContext; this.mView = LayoutInflater.from(paramContext).inflate(R.layout.widget, null); Log.d(widget.TAG, "Starting widget..."); this.init(); Log.d(widget.TAG, "Done..."); return this.mView; } // Initialize widget private void init() { sunriseView = this.mView.findViewById(R.id.sunrise); sunsetView = this.mView.findViewById(R.id.sunset); widgetTypeView = this.mView.findViewById(R.id.widgetType); updatedView = this.mView.findViewById(R.id.updated); } /* * Widget active/deactivate state management */ private void onShow() { // If view loaded (and was inactive) if (this.mView != null && !this.isActive) { // Get widget values from settings SharedPreferenceAPIClient apiClient = new SharedPreferenceAPIClient(this.mContext, this.mContext.getString(R.string.api_authority)); sunriseView.setText(apiClient.getString("sunUp", R.string.sunrise_time)); sunsetView.setText(apiClient.getString("sunDown", R.string.sunset_time)); widgetTypeView.setText(apiClient.getString("widgetType", R.string.widget_type)); updatedView.setText(apiClient.getString("updated", R.string.update_time)); } this.isActive = true; } private void onHide() { this.isActive = false; } // Events for widget hide @Override public void onInactive(Bundle paramBundle) { super.onInactive(paramBundle); this.onHide(); } @Override public void onPause() { super.onPause(); this.onHide(); } @Override public void onStop() { super.onStop(); this.onHide(); } // Events for widget show @Override public void onActive(Bundle paramBundle) { super.onActive(paramBundle); this.onShow(); } @Override public void onResume() { super.onResume(); this.onShow(); } /* * Below where are unchanged functions that the widget should have */ // Return the icon for this page, used when the page is disabled in the app list. In this case, the launcher icon is used @Override public Bitmap getWidgetIcon(Context paramContext) { return ((BitmapDrawable) this.mContext.getResources().getDrawable(R.mipmap.ic_launcher)).getBitmap(); } // Return the launcher intent for this page. This might be used for the launcher as well when the page is disabled? @Override public Intent getWidgetIntent() { return new Intent(); } // Return the title for this page, used when the page is disabled in the app list. In this case, the app name is used @Override public String getWidgetTitle(Context paramContext) { return this.mContext.getResources().getString(R.string.app_name); } // Save springboard host private ISpringBoardHostStub host = null; // Returns the springboard host public ISpringBoardHostStub getHost() { return this.host; } // Called when the page is loading and being bound to the host @Override public void onBindHost(ISpringBoardHostStub paramISpringBoardHostStub) { //Store host this.host = paramISpringBoardHostStub; } // Not sure what this does, can't find it being used anywhere. Best leave it alone @Override public void onReceiveDataFromProvider(int paramInt, Bundle paramBundle) { super.onReceiveDataFromProvider(paramInt, paramBundle); } // Called when the page is destroyed completely (in app mode). Same as the onDestroy method of an activity @Override public void onDestroy() { super.onDestroy(); } }
31.435065
144
0.681677
22ee92a99c47d554b7a5e1b052eee290b02c2579
977
package jdo.party.model.relationship; import javax.persistence.Entity; import jdo.party.model.roles.Customer; import jdo.party.model.roles.InternalOrganization; @Entity public class CustomerRelationship extends PartyRelationship { public CustomerRelationship(InternalOrganization relationshipFrom, Customer relationshipTo) { super(); setRelationshipFrom(relationshipFrom); setRelationshipTo(relationshipTo); } public CustomerRelationship() { super(); } /** * */ private static final long serialVersionUID = 1L; public InternalOrganization getRelationshipFrom() { return (InternalOrganization) super.getRelationshipFrom(); } public Customer getRelationshipTo() { return (Customer) super.getRelationshipTo(); } public void setRelationshipFrom(InternalOrganization relationshipFrom) { super.setRelationshipFrom(relationshipFrom); } public void setRelationshipTo(Customer relationshipTo) { super.setRelationshipTo(relationshipTo); } }
22.72093
94
0.793245
11fdcbfbe7748555bd962a39c9d8e7f2579092a6
26,022
/* * BSD 3-Clause License * * Copyright © 2020, viadee Unternehmensberatung AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder 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. */ package de.viadee.bpm.vPAV; import de.viadee.bpm.vPAV.config.model.RuleSet; import de.viadee.bpm.vPAV.constants.ConfigConstants; import de.viadee.bpm.vPAV.processing.ElementGraphBuilder; import de.viadee.bpm.vPAV.processing.JavaReaderStatic; import de.viadee.bpm.vPAV.processing.ProcessVariableReader; import de.viadee.bpm.vPAV.processing.EntryPointScanner; import de.viadee.bpm.vPAV.processing.code.flow.BasicNode; import de.viadee.bpm.vPAV.processing.code.flow.BpmnElement; import de.viadee.bpm.vPAV.processing.code.flow.ControlFlowGraph; import de.viadee.bpm.vPAV.processing.code.flow.FlowAnalysis; import de.viadee.bpm.vPAV.processing.model.data.ProcessVariableOperation; import de.viadee.bpm.vPAV.processing.model.data.VariableOperation; import de.viadee.bpm.vPAV.processing.model.graph.Graph; import org.camunda.bpm.model.bpmn.Bpmn; import org.camunda.bpm.model.bpmn.BpmnModelInstance; import org.camunda.bpm.model.bpmn.instance.BaseElement; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import soot.Scene; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; public class ScopeTest { @BeforeClass public static void setupSoot() throws MalformedURLException { final File file = new File("."); final String currentPath = file.toURI().toURL().toString(); final URL classUrl = new URL(currentPath + "src/test/java"); final URL[] classUrls = { classUrl }; ClassLoader cl = new URLClassLoader(classUrls); RuntimeConfig.getInstance().setClassLoader(cl); RuntimeConfig.getInstance().setResource("en_US"); RuntimeConfig.getInstance().setTest(true); FileScanner.setupSootClassPaths(new LinkedList<>()); JavaReaderStatic.setupSoot(); Scene.v().loadNecessaryClasses(); } @Before public void setupProperties() { Properties myProperties = new Properties(); myProperties.put("scanpath", ConfigConstants.TARGET_TEST_PATH); RuntimeConfig.getInstance().setProperties(myProperties); } @Test public void testScopeMultiInstanceTasks() { BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent(). serviceTask("MyServiceTask").multiInstance().camundaCollection("collection") .camundaElementVariable("loopElement").multiInstanceDone() .endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyServiceTask")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(2, element.getControlFlowGraph().getNodes().size()); Iterator<BasicNode> nodes = element.getControlFlowGraph().getNodes().values().iterator(); BasicNode defaultVariables = nodes.next(); BasicNode collection = nodes.next(); // Multi instance variables are only available within the task Assert.assertEquals("MyServiceTask", defaultVariables.getDefined().values().iterator().next().getScopeId()); Assert.assertEquals("loopElement", collection.getDefined().values().iterator().next().getName()); Assert.assertEquals("MyServiceTask", collection.getDefined().values().iterator().next().getScopeId()); } @Test public void testScopeExecutionListener() { BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().serviceTask("MyServiceTask") .camundaExecutionListenerExpression("start", "${execution.setVariable('var',true)}").endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyServiceTask")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(1, element.getControlFlowGraph().getNodes().size()); // Variables are normally set globally Assert.assertEquals("MyProcess", element.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values().iterator() .next() .getScopeId()); } @Test public void testScopeTaskListener() { BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent() .userTask("MyUserTask").camundaTaskListenerExpression("create", "${task.setVariable('var', true)}") .endEvent() .done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyUserTask")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(1, element.getControlFlowGraph().getNodes().size()); // Variables are normally set globally Assert.assertEquals("var", element.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values().iterator() .next() .getName()); Assert.assertEquals("MyProcess", element.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values().iterator() .next() .getScopeId()); } @Test public void testScopeDelegate() { BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().serviceTask("MyServiceTask") .camundaClass("de.viadee.bpm.vPAV.delegates.TestDelegate") .endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyServiceTask")); reader.getVariablesFromElement(element, new BasicNode[1]); // Variables are normally set globally Assert.assertEquals(1, element.getControlFlowGraph().getNodes().size()); Assert.assertEquals("MyProcess", element.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values().iterator() .next() .getScopeId()); } @Test public void testScopeIOParameter() { BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().serviceTask("MyServiceTask") .camundaInputParameter("myInputParameter", "${globalReadVariable}") .camundaOutputParameter("myOutputParameter", "myValue") .endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyServiceTask")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(3, element.getControlFlowGraph().getNodes().size()); Iterator<BasicNode> iterator = element.getControlFlowGraph().getNodes().values().iterator(); BasicNode inputNodeValue = iterator.next(); BasicNode inputNodeName = iterator.next(); BasicNode outputNode = iterator.next(); // Input parameter is only available in Service Task Assert.assertEquals("myInputParameter", inputNodeName.getDefined().values().iterator().next().getName()); Assert.assertEquals("MyServiceTask", inputNodeName.getDefined().values().iterator().next().getScopeId()); Assert.assertEquals("globalReadVariable", inputNodeValue.getUsed().values().iterator().next().getName()); Assert.assertEquals("MyProcess", inputNodeValue.getUsed().values().iterator().next().getScopeId()); // Output parameter is globally accessible Assert.assertEquals("myOutputParameter", outputNode.getDefined().values().iterator().next().getName()); Assert.assertEquals("MyProcess", outputNode.getDefined().values().iterator().next().getScopeId()); } @Test public void testScopeVariableMapping() { BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().callActivity("MyCallActivity") .camundaVariableMappingClass("de.viadee.bpm.vPAV.delegates.DelegatedVarMapping") .calledElement("MyCalledProcess").endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyCallActivity")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(2, element.getControlFlowGraph().getNodes().size()); Iterator<BasicNode> iterator = element.getControlFlowGraph().getNodes().values().iterator(); BasicNode inputVariables = iterator.next(); BasicNode outputVariables = iterator.next(); // In mapped variable is only available in called process Assert.assertEquals("inMapping", inputVariables.getDefined().values().iterator().next().getName()); Assert.assertEquals("MyCalledProcess", inputVariables.getDefined().values().iterator().next().getScopeId()); // Out mapped variable is only available in normal process Assert.assertEquals("outMapping", outputVariables.getDefined().values().iterator().next().getName()); Assert.assertEquals("MyProcess", outputVariables.getDefined().values().iterator().next().getScopeId()); } @Test public void testScopeSubprocess() { // Tested: delegate, input parameter, output parameter, listener, multi instance, task listener // Variables in Subprocesses are globally available if execution.setVariableLocal is not used (not supported yet) BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().subProcess() .embeddedSubProcess().startEvent() .serviceTask("MyFirstTask").camundaExpression("${execution.setVariable('test', true)}") .serviceTask("MySecondTask").camundaInputParameter("aNewValue", "myValue") .camundaOutputParameter("outputVar", "1234") .camundaExecutionListenerExpression("start", "${execution.setVariable('var', true)}").endEvent() .userTask("MyMultiInstanceTask").multiInstance().cardinality("5").sequential().multiInstanceDone() .userTask("MyTaskListener") .camundaTaskListenerExpression("create", "${task.setVariable('varTaskListener', true)}").endEvent() .subProcessDone() .endEvent() .done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); // Expression (Implementation) BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyFirstTask")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(1, element.getControlFlowGraph().getNodes().size()); Assert.assertEquals("test", element.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values().iterator() .next().getName()); Assert.assertEquals("MyProcess", element.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values().iterator() .next().getScopeId()); // Input/Output Parameter, Execution Listener BpmnElement element2 = getBpmnElement(modelInstance.getModelElementById("MySecondTask")); reader.getVariablesFromElement(element2, new BasicNode[1]); Iterator<ProcessVariableOperation> defined = element2.getControlFlowGraph().getOperations().values().iterator(); ProcessVariableOperation inputParameter = defined.next(); ProcessVariableOperation listener = defined.next(); ProcessVariableOperation outputParameter = defined.next(); Assert.assertEquals(3, element2.getControlFlowGraph().getNodes().size()); Assert.assertEquals("aNewValue", inputParameter.getName()); Assert.assertEquals("MySecondTask", inputParameter.getScopeId()); Assert.assertEquals("outputVar", outputParameter.getName()); Assert.assertEquals("MyProcess", outputParameter.getScopeId()); Assert.assertEquals("var", listener.getName()); Assert.assertEquals("MyProcess", listener.getScopeId()); // Multi-instance tasks BpmnElement multiInstanceTask = getBpmnElement(modelInstance.getModelElementById("MyMultiInstanceTask")); reader.getVariablesFromElement(multiInstanceTask, new BasicNode[1]); Assert.assertEquals(1, multiInstanceTask.getControlFlowGraph().getNodes().size()); Assert.assertEquals("nrOfInstances", multiInstanceTask.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values() .iterator() .next().getName()); Assert.assertEquals("MyMultiInstanceTask", multiInstanceTask.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values() .iterator() .next().getScopeId()); // Task Listener BpmnElement taskListener = getBpmnElement(modelInstance.getModelElementById("MyTaskListener")); reader.getVariablesFromElement(taskListener, new BasicNode[1]); Assert.assertEquals(1, taskListener.getControlFlowGraph().getNodes().size()); Assert.assertEquals("varTaskListener", taskListener.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values() .iterator() .next() .getName()); Assert.assertEquals("MyProcess", taskListener.getControlFlowGraph().getNodes().values().iterator().next().getDefined().values() .iterator() .next() .getScopeId()); } @Test public void testScopeCallActivity() { BpmnModelInstance modelInstance = Bpmn.createProcess().startEvent().callActivity() .calledElement("calledProcess") .endEvent().done(); final Map<String, String> processIdToPathMap = new HashMap<>(); processIdToPathMap.put("calledProcess", "ModelWithWriteExpression.bpmn"); ElementGraphBuilder graphBuilder = new ElementGraphBuilder(null, processIdToPathMap); FlowAnalysis flowAnalysis = new FlowAnalysis(); FileScanner fileScanner = new FileScanner(new RuleSet()); Collection<Graph> graphs = graphBuilder.createProcessGraph(fileScanner, modelInstance, "", new ArrayList<>(), new EntryPointScanner(null), flowAnalysis); flowAnalysis.analyze(graphs); Assert.assertEquals("test", flowAnalysis.getNodes().get("MyServiceTask__0").getDefined().values().iterator().next().getName()); Assert.assertEquals("calledProcess", flowAnalysis.getNodes().get("MyServiceTask__0").getDefined().values().iterator().next().getScopeId()); } @Test public void testScopeMessages() { // Setup bean mapping because variables cannot be directly modified in the message name // expression as it must return a string final Map<String, String> beanMapping = new HashMap<>(); beanMapping.put("msgNameDelegate", "de.viadee.bpm.vPAV.delegates.SignalMessageNameDelegate"); RuntimeConfig.getInstance().setBeanMapping(beanMapping); BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().serviceTask() .intermediateThrowEvent("MyThrowEvent").message("${msgNameDelegate.giveMeTheName(execution)}") .endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyThrowEvent")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(1, element.getControlFlowGraph().getNodes().size()); Iterator<BasicNode> iterator = element.getControlFlowGraph().getNodes().values().iterator(); BasicNode node = iterator.next(); Assert.assertEquals("variable", node.getDefined().get("variable_0").getName()); Assert.assertEquals(VariableOperation.WRITE, node.getDefined().get("variable_0").getOperation()); Assert.assertEquals("MyProcess", node.getDefined().get("variable_0").getScopeId()); } @Test public void testScopeSignals() { // Setup bean mapping because variables cannot be directly modified in the message name // expression as it must return a string final Map<String, String> beanMapping = new HashMap<>(); beanMapping.put("signalNameDelegate", "de.viadee.bpm.vPAV.delegates.SignalMessageNameDelegate"); RuntimeConfig.getInstance().setBeanMapping(beanMapping); BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().serviceTask() .intermediateThrowEvent("MyThrowEvent").signal("${signalNameDelegate.giveMeTheName(execution)}") .endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyThrowEvent")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(1, element.getControlFlowGraph().getNodes().size()); Iterator<BasicNode> iterator = element.getControlFlowGraph().getNodes().values().iterator(); BasicNode node = iterator.next(); Assert.assertEquals("variable", node.getDefined().get("variable_0").getName()); Assert.assertEquals(VariableOperation.WRITE, node.getDefined().get("variable_0").getOperation()); Assert.assertEquals("MyProcess", node.getDefined().get("variable_0").getScopeId()); } @Test public void testScopeFormData() { // Setup bean mapping because variables cannot be directly modified in the message name // expression as it must return a string final Map<String, String> beanMapping = new HashMap<>(); beanMapping.put("signalNameDelegate", "de.viadee.bpm.vPAV.delegates.SignalMessageNameDelegate"); RuntimeConfig.getInstance().setBeanMapping(beanMapping); BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent() .userTask("MyUserTask").camundaFormField().camundaId("firstname") .camundaFormFieldDone() .endEvent().done(); ProcessVariableReader reader = new ProcessVariableReader(null, null); BpmnElement element = getBpmnElement(modelInstance.getModelElementById("MyUserTask")); reader.getVariablesFromElement(element, new BasicNode[1]); Assert.assertEquals(1, element.getControlFlowGraph().getNodes().size()); Iterator<BasicNode> iterator = element.getControlFlowGraph().getNodes().values().iterator(); BasicNode formField = iterator.next(); Assert.assertEquals("firstname", formField.getDefined().get("firstname_0").getName()); Assert.assertEquals(VariableOperation.WRITE, formField.getDefined().get("firstname_0").getOperation()); Assert.assertEquals("MyProcess", formField.getDefined().get("firstname_0").getScopeId()); } @Test public void testScopeConsideredInAnalysisInputParameters() { ElementGraphBuilder graphBuilder = new ElementGraphBuilder(null, null); FlowAnalysis flowAnalysis = new FlowAnalysis(); FileScanner fileScanner = new FileScanner(new RuleSet()); // Test that input parameters are not passed beyond scope BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().serviceTask("MyServiceTask") .camundaInputParameter("myInputParameter", "${globalReadVariable}") .camundaOutputParameter("myOutputParameter", "myValue").sequenceFlowId("MySequenceFlow") .endEvent().done(); Collection<Graph> graphs = graphBuilder.createProcessGraph(fileScanner, modelInstance, "", new ArrayList<>(), new EntryPointScanner(null), flowAnalysis); flowAnalysis.analyze(graphs); // Only myOutputParameter is accessible after the service task Assert.assertEquals(1, flowAnalysis.getNodes().get("MySequenceFlow").getInUnused().size()); Assert.assertEquals("myOutputParameter", flowAnalysis.getNodes().get("MySequenceFlow").getInUnused().values().iterator().next().getName()); Assert.assertEquals(0, flowAnalysis.getNodes().get("MySequenceFlow").getInUsed().size()); } @Test public void testScopeConsideredInAnalysisSubprocess() { ElementGraphBuilder graphBuilder = new ElementGraphBuilder(null, null); FileScanner fileScanner = new FileScanner(new RuleSet()); // Test that global variables are accessible in subprocesses and that variables are accessible outside BpmnModelInstance modelInstance = Bpmn.createProcess("MyProcess").startEvent().serviceTask() .camundaExpression("${execution.setVariable('globalVar', true)}").subProcess() .embeddedSubProcess().startEvent("MyStartEvent") .serviceTask("MyServiceTask").camundaExpression("${execution.setVariable('test', true)}").endEvent() .subProcessDone() .endEvent("MyEndEvent") .done(); FlowAnalysis flowAnalysis = new FlowAnalysis(); Collection<Graph> graphs = graphBuilder.createProcessGraph(fileScanner, modelInstance, "", new ArrayList<>(), new EntryPointScanner(null), flowAnalysis); flowAnalysis.analyze(graphs); Assert.assertEquals(1, flowAnalysis.getNodes().get("MyServiceTask__0").getInUnused().size()); Assert.assertEquals("globalVar", flowAnalysis.getNodes().get("MyServiceTask__0").getInUnused().values().iterator().next().getName()); Assert.assertEquals(2, flowAnalysis.getNodes().get("MyEndEvent").getInUnused().size()); Iterator<ProcessVariableOperation> iter = flowAnalysis.getNodes().get("MyEndEvent").getInUnused().values() .iterator(); Assert.assertEquals("globalVar", iter.next().getName()); Assert.assertEquals("test", iter.next().getName()); } @Test public void testScopeConsideredInAnalysisCallActivity() { final Map<String, String> processIdToPathMap = new HashMap<>(); processIdToPathMap.put("calledProcess", "ModelWithWriteExpression.bpmn"); ElementGraphBuilder graphBuilder = new ElementGraphBuilder(null, processIdToPathMap); FlowAnalysis flowAnalysis = new FlowAnalysis(); FileScanner fileScanner = new FileScanner(new RuleSet()); // Test that variables in called processes are scoped BpmnModelInstance modelInstance = Bpmn.createProcess().startEvent().serviceTask() .camundaExpression("${execution.setVariable('globalVar',true)}").callActivity() .calledElement("calledProcess") .endEvent("MyEndEvent").done(); Collection<Graph> graphs = graphBuilder.createProcessGraph(fileScanner, modelInstance, "", new ArrayList<>(), new EntryPointScanner(null), flowAnalysis); flowAnalysis.analyze(graphs); // Variable set in caller process is not available in called process Assert.assertEquals(0, flowAnalysis.getNodes().get("MyServiceTask__0").getInUnused().size()); Assert.assertEquals(0, flowAnalysis.getNodes().get("MyServiceTask__0").getInUsed().size()); // Variable set in called process is not available in caller process Assert.assertEquals(1, flowAnalysis.getNodes().get("MyEndEvent").getInUnused().size()); Assert.assertEquals("globalVar", flowAnalysis.getNodes().get("MyEndEvent").getInUnused().values().iterator().next().getName()); } private BpmnElement getBpmnElement(BaseElement element) { return new BpmnElement(null, element, new ControlFlowGraph(), new FlowAnalysis()); } }
56.69281
122
0.688302
1f1c3c76190108193dd0cb3f8edcc7f3adcb797a
15,123
/* Copyright 2017 Zutubi Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zutubi.pulse.core.commands.core; import com.zutubi.pulse.core.PulseExecutionContext; import com.zutubi.pulse.core.RegexPatternConfiguration; import com.zutubi.pulse.core.engine.api.ExecutionContext; import com.zutubi.pulse.core.engine.api.Feature; import com.zutubi.pulse.core.marshal.FileLoadException; import com.zutubi.pulse.core.model.*; import com.zutubi.pulse.core.postprocessors.DefaultPostProcessorContext; import com.zutubi.pulse.core.test.api.PulseTestCase; import com.zutubi.util.io.IOUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.regex.Pattern; import static com.zutubi.pulse.core.engine.api.BuildProperties.NAMESPACE_INTERNAL; import static com.zutubi.pulse.core.engine.api.BuildProperties.PROPERTY_OUTPUT_DIR; /** * Tests for RegexPostProcessor. */ public class RegexPostProcessorTest extends PulseTestCase { private static final String[] LINES = {"first line", "second line", "xxx", "xxx abc", "abc xxx", "abc xxx abc"}; private StoredFileArtifact artifact; private File tempFile; private File tempDir; public void setUp() throws IOException { tempFile = File.createTempFile("regex-pp-test", null); tempDir = tempFile.getParentFile(); PrintWriter writer = null; try { writer = new PrintWriter(tempFile.getAbsolutePath()); for (String line : LINES) { writer.println(line); } } finally { IOUtils.close(writer); } artifact = new StoredFileArtifact(tempFile.getName()); } public void tearDown() { assertTrue(tempFile.delete()); } public void testMatchAll() { simpleErrors(".*", LINES); } public void testMatchXXX() { simpleErrors("^xxx$", "xxx"); } public void testStartsXXX() { simpleErrors("^xxx.*", "xxx", "xxx abc"); } public void testEndsXXX() { simpleErrors(".*xxx$", "xxx", "abc xxx"); } public void testFloatingXXX() { simpleErrors("xxx", "xxx", "xxx abc", "abc xxx", "abc xxx abc"); } public void testCustomSummary() { RegexPostProcessorConfiguration pp = new RegexPostProcessorConfiguration("test-pp"); RegexPatternConfiguration pattern = new RegexPatternConfiguration(Feature.Level.ERROR, Pattern.compile("^xxx$")); pattern.setSummary("custom"); pp.getPatterns().add(pattern); simpleErrors(pp, "custom"); } public void testCustomSummaryGroups() { RegexPostProcessorConfiguration pp = new RegexPostProcessorConfiguration("test-pp"); RegexPatternConfiguration pattern = new RegexPatternConfiguration(Feature.Level.ERROR, Pattern.compile("^x(x)x$")); pattern.setSummary("$1"); pp.getPatterns().add(pattern); simpleErrors(pp, "x"); } public void testExcludeAll() { RegexPostProcessorConfiguration pp = createExclusionProcessor("xxx", ".*"); simpleErrors(pp); } public void testExcludeSame() { RegexPostProcessorConfiguration pp = createExclusionProcessor(".*xxx$", ".*xxx$"); simpleErrors(pp); } public void testExcludeSome() { RegexPostProcessorConfiguration pp = createExclusionProcessor(".*xxx$", "^xxx$"); simpleErrors(pp, "abc xxx"); } public void testMultipleExclusions() { RegexPostProcessorConfiguration pp = createExclusionProcessor(".*", "^xxx$", "abc"); simpleErrors(pp, "first line", "second line"); } public void testFailOnError() { RegexPostProcessorConfiguration pp = createPostProcessor(".*"); CommandResult result = simpleErrors(pp, LINES); assertTrue(result.failed()); assertEquals("Error features detected", getFailureMessage(result)); } public void testNoFailOnError() { RegexPostProcessorConfiguration pp = createPostProcessor(".*"); pp.setFailOnError(false); CommandResult result = simpleErrors(pp, LINES); assertFalse(result.failed()); } public void testNoFailOnWarning() { RegexPostProcessorConfiguration pp = createPostProcessor(".*", Feature.Level.WARNING); assertFalse(pp.isFailOnWarning()); CommandResult result = simpleFeatures(pp, Feature.Level.WARNING, LINES); assertFalse(result.failed()); } public void testFailOnWarning() { RegexPostProcessorConfiguration pp = createPostProcessor(".*", Feature.Level.WARNING); pp.setFailOnWarning(true); CommandResult result = simpleFeatures(pp, Feature.Level.WARNING, LINES); assertTrue(result.failed()); assertEquals("Warning features detected", getFailureMessage(result)); } public void testLeadingContext() { contextHelper(1, 0); } public void testTrailingContext() { contextHelper(0, 1); } public void testLeadingAndTrailingContext() { contextHelper(1, 1); } public void testMultipleLeadingContext() { contextHelper(2, 0); } public void testMultipleTrailingContext() { contextHelper(0, 2); } public void testMultipleLeadingAndTrailingContext() { contextHelper(2, 2); } public void testJustUnderLeadingContext() { contextHelper(LINES.length - 1, 0); } public void testJustUnderTrailingContext() { contextHelper(0, LINES.length - 1); } public void testJustUnderLEadingAndTrailingContext() { contextHelper(LINES.length - 1, LINES.length - 1); } public void testExactLeadingContext() { contextHelper(LINES.length, 0); } public void testExactTrailingContext() { contextHelper(0, LINES.length); } public void testExactLeadingAndTrailingContext() { contextHelper(LINES.length, LINES.length); } public void testJustOverLeadingContext() { contextHelper(LINES.length + 1, 0); } public void testJustOverTrailingContext() { contextHelper(0, LINES.length + 1); } public void testJustOverLeadingAndTrailingContext() { contextHelper(LINES.length + 1, LINES.length + 1); } public void testHugeLeadingContext() { contextHelper(10000, 0); } public void testHugeTrailingContext() { contextHelper(0, 10000); } public void testHugeLeadingAndTrailingContext() { contextHelper(10000, 10000); } public void testJoinOverlapping() { RegexPostProcessorConfiguration pp = createPostProcessor("xxx"); pp.setTrailingContext(1); simpleErrors(pp, "xxx\nxxx abc\nabc xxx\nabc xxx abc"); } public void testJoinDoubleOverlapping() { RegexPostProcessorConfiguration pp = createPostProcessor("xxx"); pp.setTrailingContext(2); simpleErrors(pp, "xxx\nxxx abc\nabc xxx\nabc xxx abc"); } public void testNotJoinAdjacent() { RegexPostProcessorConfiguration pp = createPostProcessor("xxx abc"); pp.setTrailingContext(1); simpleErrors(pp, "xxx abc\nabc xxx", "abc xxx abc"); } public void testJoinSeparated() { RegexPostProcessorConfiguration pp = createPostProcessor("xxx abc"); pp.setTrailingContext(2); simpleErrors(pp, "xxx abc\nabc xxx\nabc xxx abc"); } public void testOverlappingDifferentLevels() throws FileLoadException { RegexPostProcessorConfiguration ppConfig = new RegexPostProcessorConfiguration("test"); RegexPatternConfiguration pattern = new RegexPatternConfiguration(); pattern.setCategory(Feature.Level.WARNING); pattern.setExpression("^xxx abc$"); ppConfig.setTrailingContext(1); ppConfig.getPatterns().add(pattern); pattern = new RegexPatternConfiguration(); pattern.setCategory(Feature.Level.ERROR); pattern.setExpression("^abc xxx$"); ppConfig.setLeadingContext(1); ppConfig.getPatterns().add(pattern); CommandResult result = new CommandResult("test"); ExecutionContext context = new PulseExecutionContext(); context.addString(NAMESPACE_INTERNAL, PROPERTY_OUTPUT_DIR, tempDir.getAbsolutePath()); RegexPostProcessor pp = new RegexPostProcessor(ppConfig); pp.process(tempFile, new DefaultPostProcessorContext(artifact, result, Integer.MAX_VALUE, context)); List<PersistentFeature> features = artifact.getFeatures(); assertEquals(2, features.size()); assertEquals(Feature.Level.WARNING, features.get(0).getLevel()); assertEquals(Feature.Level.ERROR, features.get(1).getLevel()); } public void testSmileFace() throws FileLoadException, FileNotFoundException { RegexPostProcessorConfiguration pp = createPostProcessor(":-\\)"); writeToArtifact("first line", ":-) blah blah blah", "last line"); simpleFeatures(pp, Feature.Level.ERROR, ":-) blah blah blah"); } private void writeToArtifact(String... lines) throws FileNotFoundException { PrintWriter writer = null; try { writer = new PrintWriter(tempFile.getAbsolutePath()); for (String line : lines) { writer.println(line); } } finally { IOUtils.close(writer); } artifact = new StoredFileArtifact(tempFile.getName()); } private void contextHelper(int leading, int trailing) { RegexPostProcessorConfiguration pp = createPostProcessor(".*"); pp.setLeadingContext(leading); pp.setTrailingContext(trailing); pp.setJoinOverlapping(false); simpleErrors(pp, joinLines(leading, trailing)); checkFeatureLines(artifact, leading, trailing); } private void checkFeatureLines(StoredFileArtifact artifact, int leading, int trailing) { int lineNumber = 1; for (PersistentFeature f : artifact.getFeatures()) { PersistentPlainFeature pf = (PersistentPlainFeature) f; assertEquals(lineNumber, pf.getLineNumber()); assertEquals(lineNumber > leading ? lineNumber - leading : 1, pf.getFirstLine()); assertEquals(lineNumber + trailing <= LINES.length ? lineNumber + trailing : LINES.length, pf.getLastLine()); lineNumber++; } } private String[] joinLines(int leading, int trailing) { String[] result = new String[LINES.length]; for (int i = 0; i < LINES.length; i++) { StringBuilder joined = new StringBuilder(); for (int j = i - leading; j < i; j++) { if (j >= 0) { joined.append(LINES[j]); joined.append('\n'); } } joined.append(LINES[i]); for (int j = i + 1; j <= i + trailing && j < LINES.length; j++) { joined.append('\n'); joined.append(LINES[j]); } result[i] = joined.toString(); } return result; } private CommandResult simpleFeatures(RegexPostProcessorConfiguration config, Feature.Level level, String... lines) { CommandResult result = new CommandResult("test"); ExecutionContext context = new PulseExecutionContext(); context.addString(NAMESPACE_INTERNAL, PROPERTY_OUTPUT_DIR, tempDir.getAbsolutePath()); RegexPostProcessor pp = new RegexPostProcessor(config); pp.process(tempFile, new DefaultPostProcessorContext(artifact, result, Integer.MAX_VALUE, context)); result.complete(); List<PersistentFeature> features = artifact.getFeatures(); assertEquals(lines.length, features.size()); for (int i = 0; i < lines.length; i++) { PersistentFeature feature = features.get(i); assertEquals(level, feature.getLevel()); assertEquals(lines[i], feature.getSummary()); } if (features.size() > 0) { if (level == Feature.Level.ERROR && config.isFailOnError()) { assertTrue(result.failed()); assertEquals("Error features detected", getFailureMessage(result)); } else if (level == Feature.Level.WARNING && config.isFailOnWarning()) { assertTrue(result.failed()); assertEquals("Warning features detected", getFailureMessage(result)); } } return result; } private String getFailureMessage(Result result) { PersistentFeature feature = result.getFeatures().get(0); assertEquals(Feature.Level.ERROR, feature.getLevel()); return feature.getSummary(); } private CommandResult simpleErrors(RegexPostProcessorConfiguration pp, String... lines) { return simpleFeatures(pp, Feature.Level.ERROR, lines); } private void simpleErrors(String expression, String... lines) { RegexPostProcessorConfiguration pp = createPostProcessor(expression); assertTrue(pp.isFailOnError()); assertFalse(pp.isFailOnWarning()); simpleErrors(pp, lines); } private RegexPostProcessorConfiguration createPostProcessor(String expression) { return createPostProcessor(expression, Feature.Level.ERROR); } private RegexPostProcessorConfiguration createPostProcessor(String expression, Feature.Level level) { RegexPostProcessorConfiguration pp = new RegexPostProcessorConfiguration("test-pp"); pp.addRegexes(level, expression); return pp; } private RegexPostProcessorConfiguration createExclusionProcessor(String expression, String... exclusions) { RegexPostProcessorConfiguration pp = new RegexPostProcessorConfiguration("test-pp"); RegexPatternConfiguration pattern = new RegexPatternConfiguration(Feature.Level.ERROR, Pattern.compile(expression)); for (String e : exclusions) { pattern.getExclusions().add(e); } pp.getPatterns().add(pattern); return pp; } }
30.737805
124
0.641077
00ef4953ad241fdeb8dc6fd91c7a91f86acb2ef3
2,940
/* * 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.sling.models.impl.via; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.resource.Resource; import org.apache.sling.models.annotations.ViaProviderType; import org.apache.sling.models.annotations.via.OriginalResourceType; import org.apache.sling.models.spi.ViaProvider; import org.osgi.service.component.annotations.Component; /** * This {@link ViaProvider} implements the counterpart of the {@link ForcedResourceTypeViaProvider} and the * {@link ResourceSuperTypeViaProvider}. It is in particular helpful in models that want to inject another model using the original * {@link Resource}'s or {@link SlingHttpServletRequest}'s resource type instead of the one forced by either of the above-mentioned * {@link ViaProvider}s * <p> * The implementation simply unwraps the {@link org.apache.sling.api.resource.ResourceWrapper} or * {@link org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper} used by the {@link ForcedResourceTypeViaProvider} and * {@link ResourceSuperTypeViaProvider}. */ @Component public class OriginalResourceTypeViaProvider implements ViaProvider { @Override public Class<? extends ViaProviderType> getType() { return OriginalResourceType.class; } @Override public Object getAdaptable(Object original, String value) { if (original instanceof SlingHttpServletRequest) { SlingHttpServletRequest originalRequest = (SlingHttpServletRequest) original; while (originalRequest instanceof ResourceTypeForcingRequestWrapper) { originalRequest = ((ResourceTypeForcingRequestWrapper) originalRequest).getSlingRequest(); } return originalRequest; } else if (original instanceof Resource) { Resource originalResource = (Resource) original; while (originalResource instanceof ResourceTypeForcingResourceWrapper) { originalResource = ((ResourceTypeForcingResourceWrapper) originalResource).getResource(); } return originalResource; } else { return null; } } }
46.666667
131
0.744218
8d31a1e5617150ef6350cc577e7a113655aa98f8
1,858
/* * 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.commons.weaver.utils; /** * Argument/Parameter-related utilities. */ public final class Args { private Args() { } /** * Compare two parameter type arrays. * * @param paramTypes1 * lhs * @param paramTypes2 * rhs * @return {@code int} as specified by {@link java.util.Comparator#compare(Object, Object)} */ @SuppressWarnings("PMD.UseVarargs") // not needed for comparing one array to another public static int compare(final Class<?>[] paramTypes1, final Class<?>[] paramTypes2) { for (int param = 0; param < paramTypes1.length; param++) { if (param >= paramTypes2.length) { return 1; } final int test = paramTypes1[param].getName().compareTo(paramTypes2[param].getName()); if (test == 0) { continue; } return test; } if (paramTypes1.length == paramTypes2.length) { return 0; } return -1; } }
33.178571
98
0.636168
9664ed3c729e56015daa14d543371d28b8577819
6,790
/* * Copyright (c) 2019 by cordalo.ch - MIT License * * 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 ch.cordalo.template.contracts; import ch.cordalo.corda.common.contracts.StateVerifier; import ch.cordalo.template.states.ChatMessageState; import net.corda.core.contracts.CommandData; import net.corda.core.contracts.Contract; import net.corda.core.transactions.LedgerTransaction; import static net.corda.core.contracts.ContractsDSL.requireThat; public class ChatMessageContract implements Contract { public static final String ID = "ch.cordalo.template.contracts.ChatMessageContract"; @Override public void verify(LedgerTransaction tx) throws IllegalArgumentException { StateVerifier verifier = StateVerifier.fromTransaction(tx, ChatMessageContract.Commands.class); ChatMessageContract.Commands commandData = (ChatMessageContract.Commands) verifier.command(); commandData.verify(tx, verifier); } public interface Commands extends CommandData { public void verify(LedgerTransaction tx, StateVerifier verifier) throws IllegalArgumentException; /* @CordaSerializable public class Reference extends ReferenceContract.Commands.Reference<ChatMessageState> implements ChatMessageContract.Commands { public Reference(ChatMessageState myState) { super(myState); } @Override public void verify(LedgerTransaction tx, StateVerifier verifier) throws IllegalArgumentException { this.verify(tx); } } */ class Send implements ChatMessageContract.Commands { @Override public void verify(LedgerTransaction tx, StateVerifier verifier) throws IllegalArgumentException { requireThat(req -> { verifier.input().empty("input must be empty"); ChatMessageState message = verifier .output() .one() .one(ChatMessageState.class) .isNotEmpty(ChatMessageState::getLinearId, "id must be provided") .isNotEmpty(ChatMessageState::getSender, "sender must be provided") .isNotEmpty(ChatMessageState::getReceiver, "receiver must be provided") .isNotEmpty(ChatMessageState::getMessage, "message cannot be empty") .isNotEqual(ChatMessageState::getSender, ChatMessageState::getReceiver, "selfie-messages are not allowed") .object(); return null; }); } } class Reply implements ChatMessageContract.Commands { @Override public void verify(LedgerTransaction tx, StateVerifier verifier) throws IllegalArgumentException { requireThat(req -> { verifier .input() .one() .one(ChatMessageState.class); verifier .output() .count(2); ChatMessageState refMessage = verifier .intersection(ChatMessageState.class) .one("1 input and 1 output the same - used as a reference") .one(ChatMessageState.class) .object(); ChatMessageState reply = verifier .output() .count(2) .newOutput(ChatMessageState.class) .one() .one(ChatMessageState.class) .isNotEmpty(ChatMessageState::getLinearId, "id must be provided") .isNotEmpty(ChatMessageState::getSender, "sender must be provided") .isNotEmpty(ChatMessageState::getReceiver, "receiver must be provided") .isNotEmpty(ChatMessageState::getMessage, "message cannot be empty") .isNotEqual(ChatMessageState::getSender, ChatMessageState::getReceiver, "selfie-messages are not allowed") .object(); req.using("receiver must be sender", reply.getReceiver().equals(refMessage.getSender())); req.using("sender must be receiver", reply.getSender().equals(refMessage.getReceiver())); req.using("reply base id must be id from input", reply.getBaseMessageId().equals(refMessage.getLinearId())); return null; }); } } class Delete implements ChatMessageContract.Commands { @Override public void verify(LedgerTransaction tx, StateVerifier verifier) throws IllegalArgumentException { requireThat(req -> { verifier.output().empty("output must be empty"); ChatMessageState message = verifier .input() .one() .one(ChatMessageState.class) .isNotEmpty(ChatMessageState::getLinearId, "id must be provided") .isNotEmpty(ChatMessageState::getSender, "sender must be provided") .isNotEmpty(ChatMessageState::getReceiver, "receiver must be provided") .isNotEmpty(ChatMessageState::getMessage, "message cannot be empty") .object(); return null; }); } } } }
52.635659
463
0.594109
ff6e7cfe9cc68385889abc99a01cbe29e1a68fca
2,100
package com.pipemaze.eggdropsoap.mod_pndc; import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.entity.Entity; import net.minecraft.entity.monster.EntitySlime; import net.minecraft.entity.monster.IMob; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.event.entity.living.LivingSpawnEvent; import net.minecraftforge.event.entity.living.LivingSpawnEvent.CheckSpawn; public class MyCheckSpawn { @SubscribeEvent public void spawnfired(CheckSpawn event) { World world = event.world; // String dimension = world.provider.getDimensionName(); // int dimensionId = world.getWorldInfo().getVanillaDimension(); int dimensionId = world.provider.dimensionId; Entity entity = event.entity; String name = entity.toString(); boolean isHostile = IMob.mobSelector.isEntityApplicable(entity); boolean isSlime = entity instanceof EntitySlime; int x = MathHelper.floor_double(event.x); int y = MathHelper.floor_double(event.y); int z = MathHelper.floor_double(event.z); Chunk chunk = world.getChunkFromBlockCoords(x, z); int skyLight = chunk.getSavedLightValue(EnumSkyBlock.Sky, x & 15, y, z & 15); // deny any normally-permitted spawn that is under direct sky // if (dimension.equals("Overworld") && isHostile && world.canBlockSeeTheSky(x, y, z) ) { // deny any normally-permitted spawn that is under or near open sky, unless it's a slime if (dimensionId == 0 && isHostile && !isSlime && skyLight > 7 ) { // System.out.println("Spawn denied: "+dimensionId+" @ ["+x+","+y+","+z+"] sl: "+skyLight+" ("+name+")"); event.setResult(Result.DENY); } // else { //// System.out.println("Spawn allowed: "+dimension+" @ ["+x+", "+y+", "+z+"] sl: "+skyLight+" ("+name+")"); // System.out.println("Dimension name: "+dimension+", ID: "+dimensionId+", ID2: "+dimensionId2); // } } }
45.652174
113
0.697619
07441699345ec1824decb64e9bd7f2e2caa83900
4,059
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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.broad.igv.ui; import org.apache.log4j.Logger; import org.broad.igv.ui.commandbar.IGVCommandBar; import org.broad.igv.ui.panel.MainPanel; import org.broad.igv.ui.panel.TrackPanel; import org.broad.igv.ui.util.ApplicationStatusBar; import javax.swing.*; import javax.swing.plaf.basic.BasicBorders; import java.awt.*; /** * The content pane for the IGV main window. */ public class IGVContentPane extends JPanel { private static Logger log = Logger.getLogger(IGVContentPane.class); private JPanel commandBarPanel; private IGVCommandBar igvCommandBar; private MainPanel mainPanel; private ApplicationStatusBar statusBar; private IGV igv; /** * Creates new form IGV */ public IGVContentPane(IGV igv) { setOpaque(true); // Required by Swing this.igv = igv; // Create components setLayout(new BorderLayout()); commandBarPanel = new JPanel(); BoxLayout layout = new BoxLayout(commandBarPanel, BoxLayout.PAGE_AXIS); commandBarPanel.setLayout(layout); add(commandBarPanel, BorderLayout.NORTH); igvCommandBar = new IGVCommandBar(); igvCommandBar.setMinimumSize(new Dimension(250, 33)); igvCommandBar.setBorder(new BasicBorders.MenuBarBorder(Color.GRAY, Color.GRAY)); igvCommandBar.setAlignmentX(Component.BOTTOM_ALIGNMENT); commandBarPanel.add(igvCommandBar); mainPanel = new MainPanel(igv); add(mainPanel, BorderLayout.CENTER); statusBar = new ApplicationStatusBar(); statusBar.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION); add(statusBar, BorderLayout.SOUTH); } public void addCommandBar(JComponent component) { component.setBorder(new BasicBorders.MenuBarBorder(Color.GRAY, Color.GRAY)); component.setAlignmentX(Component.BOTTOM_ALIGNMENT); commandBarPanel.add(component); commandBarPanel.invalidate(); } @Override public Dimension getPreferredSize() { return UIConstants.preferredSize; } public void revalidateTrackPanels() { for (TrackPanel tp : mainPanel.getTrackPanels()) { tp.getScrollPane().getDataPanel().revalidate(); } } public void validateTrackPanels() { for (TrackPanel tp : mainPanel.getTrackPanels()) { tp.getScrollPane().getDataPanel().validate(); } } /** * Reset the default status message, which is the number of tracks loaded. */ public void resetStatusMessage() { statusBar.setMessage("" + igv.getVisibleTrackCount() + " tracks loaded"); } public MainPanel getMainPanel() { return mainPanel; } public IGVCommandBar getCommandBar() { return igvCommandBar; } public ApplicationStatusBar getStatusBar() { return statusBar; } }
29.627737
88
0.700172
fc55614bfbf5079fa9b40097377c5b563e9ea21e
1,319
package examples.rmi.arithmetic; import bus.uigen.models.MainClassLaunchingUtility; // this is a distrbuted implementation of a CS 1 (UNC Comp 110) first assignment submission described below /****************************************************************** * Program or Assignment #: Assignment1 * * Programmer: Jacob * * Due Date: Tuesday, Jan. 28 * * COMP110-002, Spring 2014 Instructor: Prof. Jay Aikat * * Pledge: I have neither given nor received unauthorized aid * on this program. * * Description: Insert a brief paragraph describing the program * * Input: Insert a brief description of user inputs, or "None" if * there is no user input * * Output: Insert a brief description of the program output * ******************************************************************/ public class DemoerOfMixedTypeArithmetic { public static void main(String args[]) { demo(); } public static void demo() { // String currentDir = System.getProperty("user.dir"); // System.out.println("Current dir using System:" +currentDir); Class[] classes = { DistributedRMIRegistryStarter.class, AMixedTypeArithmeticServerLauncher.class, AMixedTypeAirthmeticClientLauncher.class }; MainClassLaunchingUtility.createInteractiveLauncher(classes); } }
28.06383
107
0.645944
eae72f04ab3c2001ef95ae53f81694b81dd22157
8,950
package com.example.thread; import com.example.util.Utility; import java.util.Date; /** * @author VanceKing * @since 2018/3/18. */ class SynchronizedSample { private interface AAA { int a = 1; void test(); } private static class MyObject { private int count = 0; private static int count2 = 0; private Object lock = new Object(); public MyObject() { synchronized (this) { } } //实例同步方法。多个线程同时访问时,只能有一个线程允许进入同步方法。 public synchronized void add(int value) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } this.count += value; } //静态同步方法。由于静态方法是属于类的,在当前类中只允许一个线程访问。 public static synchronized void add2(int value) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } count2 += value; } //必须获得对象的监视器才能访问。实例方法的同步加上代码块this的同步,仍然针对同一个实例对象 public void add3(int value) { synchronized (this) {//"this" 监视器对象是当前类的实例。 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } this.count += value; } } public void add4(int value) { synchronized (lock) {//自定义监视器对象 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } this.count += value; } } public void add5(int value) { synchronized (MyObject.class) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } this.count += value; } } } private static class MyRunnable implements Runnable { private MyObject myObject; private int method; public MyRunnable(MyObject myObject, int method) { this.myObject = myObject; this.method = method; } @Override public void run() { System.out.println(Thread.currentThread().getName() + " 开始时间: " + new Date()); if (method == 1) { myObject.add(1); } else if (method == 2) { MyObject.add2(1); } else if (method == 3) { myObject.add3(1); } else if (method == 4) { myObject.add4(1); } else if (method == 5) { myObject.add5(1); } System.out.println(Thread.currentThread().getName() + " 结束时间: " + new Date()); } } public static void main(String[] args) { test5(); } /* t2 on obj1 开始时间: Sun Mar 18 16:01:10 CST 2018 t4 on obj2 开始时间: Sun Mar 18 16:01:10 CST 2018 t3 on obj2 开始时间: Sun Mar 18 16:01:10 CST 2018 t1 on obj1 开始时间: Sun Mar 18 16:01:10 CST 2018 t4 on obj2 结束时间: Sun Mar 18 16:01:15 CST 2018 t2 on obj1 结束时间: Sun Mar 18 16:01:15 CST 2018 t1 on obj1 结束时间: Sun Mar 18 16:01:20 CST 2018 t3 on obj2 结束时间: Sun Mar 18 16:01:20 CST 2018 */ private static void test1() { MyObject myObject1 = new MyObject(); MyObject myObject2 = new MyObject(); Thread thread1 = new Thread(new MyRunnable(myObject1, 1), "t1 on obj1"); Thread thread2 = new Thread(new MyRunnable(myObject1, 1), "t2 on obj1"); Thread thread3 = new Thread(new MyRunnable(myObject2, 1), "t3 on obj2"); Thread thread4 = new Thread(new MyRunnable(myObject2, 1), "t4 on obj2"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } /* t2 on obj1 开始时间: Sun Mar 18 16:16:15 CST 2018 t4 on obj2 开始时间: Sun Mar 18 16:16:15 CST 2018 t1 on obj1 开始时间: Sun Mar 18 16:16:15 CST 2018 t3 on obj2 开始时间: Sun Mar 18 16:16:15 CST 2018 t2 on obj1 结束时间: Sun Mar 18 16:16:20 CST 2018 t3 on obj2 结束时间: Sun Mar 18 16:16:25 CST 2018 t1 on obj1 结束时间: Sun Mar 18 16:16:30 CST 2018 t4 on obj2 结束时间: Sun Mar 18 16:16:35 CST 2018 */ private static void test2() { MyObject myObject1 = new MyObject(); MyObject myObject2 = new MyObject(); Thread thread1 = new Thread(new MyRunnable(myObject1, 2), "t1 on obj1"); Thread thread2 = new Thread(new MyRunnable(myObject1, 2), "t2 on obj1"); Thread thread3 = new Thread(new MyRunnable(myObject2, 2), "t3 on obj2"); Thread thread4 = new Thread(new MyRunnable(myObject2, 2), "t4 on obj2"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } /* t3 on obj2 开始时间: Sun Mar 18 16:25:18 CST 2018 t1 on obj1 开始时间: Sun Mar 18 16:25:18 CST 2018 t4 on obj2 开始时间: Sun Mar 18 16:25:18 CST 2018 t2 on obj1 开始时间: Sun Mar 18 16:25:18 CST 2018 t3 on obj2 结束时间: Sun Mar 18 16:25:23 CST 2018 t1 on obj1 结束时间: Sun Mar 18 16:25:23 CST 2018 t4 on obj2 结束时间: Sun Mar 18 16:25:28 CST 2018 t2 on obj1 结束时间: Sun Mar 18 16:25:28 CST 2018 */ private static void test3() { MyObject myObject1 = new MyObject(); MyObject myObject2 = new MyObject(); Thread thread1 = new Thread(new MyRunnable(myObject1, 3), "t1 on obj1"); Thread thread2 = new Thread(new MyRunnable(myObject1, 3), "t2 on obj1"); Thread thread3 = new Thread(new MyRunnable(myObject2, 3), "t3 on obj2"); Thread thread4 = new Thread(new MyRunnable(myObject2, 3), "t4 on obj2"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } /* t1 on obj1 开始时间: Sun Mar 18 16:49:05 CST 2018 t4 on obj2 开始时间: Sun Mar 18 16:49:05 CST 2018 t2 on obj1 开始时间: Sun Mar 18 16:49:05 CST 2018 t3 on obj2 开始时间: Sun Mar 18 16:49:05 CST 2018 t4 on obj2 结束时间: Sun Mar 18 16:49:10 CST 2018 t1 on obj1 结束时间: Sun Mar 18 16:49:10 CST 2018 t2 on obj1 结束时间: Sun Mar 18 16:49:15 CST 2018 t3 on obj2 结束时间: Sun Mar 18 16:49:15 CST 2018 */ private static void test4() { MyObject myObject1 = new MyObject(); MyObject myObject2 = new MyObject(); Thread thread1 = new Thread(new MyRunnable(myObject1, 4), "t1 on obj1"); Thread thread2 = new Thread(new MyRunnable(myObject1, 4), "t2 on obj1"); Thread thread3 = new Thread(new MyRunnable(myObject2, 4), "t3 on obj2"); Thread thread4 = new Thread(new MyRunnable(myObject2, 4), "t4 on obj2"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } /* t4 on obj2 开始时间: Tue Mar 20 10:24:54 CST 2018 t1 on obj1 开始时间: Tue Mar 20 10:24:54 CST 2018 t2 on obj1 开始时间: Tue Mar 20 10:24:54 CST 2018 t3 on obj2 开始时间: Tue Mar 20 10:24:54 CST 2018 t4 on obj2 结束时间: Tue Mar 20 10:24:59 CST 2018 t3 on obj2 结束时间: Tue Mar 20 10:25:04 CST 2018 t2 on obj1 结束时间: Tue Mar 20 10:25:09 CST 2018 t1 on obj1 结束时间: Tue Mar 20 10:25:14 CST 2018 */ private static void test5() { MyObject myObject1 = new MyObject(); MyObject myObject2 = new MyObject(); Thread thread1 = new Thread(new MyRunnable(myObject1, 5), "t1 on obj1"); Thread thread2 = new Thread(new MyRunnable(myObject1, 5), "t2 on obj1"); Thread thread3 = new Thread(new MyRunnable(myObject2, 5), "t3 on obj2"); Thread thread4 = new Thread(new MyRunnable(myObject2, 5), "t4 on obj2"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } //类锁和同步锁可以同时执行 private static void test6() { final AClass aClass = new AClass(); final AClass aClass2 = new AClass(); Thread thread = new Thread() { @Override public void run() { super.run(); aClass.printA(); } }; thread.setPriority(Thread.MAX_PRIORITY); thread.start(); new Thread() { @Override public void run() { super.run(); aClass.printB(); } }.start(); } private static class AClass { private static final Object lock = new Object(); public void printA() { synchronized (this) { System.out.println("A方法开始"); Utility.sleep(2000); System.out.println("printA"); System.out.println("A方法结束"); } } public void printB() { synchronized (AClass.class) { System.out.println("B方法开始"); System.out.println("printB"); System.out.println("B方法结束"); } } } }
30.650685
90
0.552849
bbd11740fb75f82438659c09be9dd8258102ec81
1,549
package ng.cheo.android.inventory; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by mickey on 7/11/16. */ import ng.cheo.android.inventory.AssetContract.AssetEntry; public class AssetDbHelper extends SQLiteOpenHelper { public static final String LOG_TAG = AssetDbHelper.class.getSimpleName(); private static final String DATABASE_NAME = "inventory.db"; private static final int DATABASE_VERSION = 1; public AssetDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create a String that contains the SQL statement to create the pets table String SQL_CREATE_ASSETS_TABLE = "CREATE TABLE " + AssetEntry.TABLE_NAME + " (" + AssetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + AssetEntry.COLUMN_NAME + " TEXT NOT NULL, " + AssetEntry.COLUMN_PRICE + " DOUBLE NOT NULL DEFAULT 0.0, " + AssetEntry.COLUMN_QUANTITY + " INTEGER NOT NULL DEFAULT 0," + AssetEntry.COLUMN_QUANTITY_SOLD + " INTEGER NOT NULL DEFAULT 0," + AssetEntry.COLUMN_IMAGE + " BLOB NOT NULL);"; // Execute the SQL statement db.execSQL(SQL_CREATE_ASSETS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Still at version 1, nothing to be done here. } }
35.204545
88
0.681085
a181c2d72215ef3835e2fff226629e0cff9289dd
5,130
package com.base.springboot.utils; import com.alibaba.fastjson.JSONObject; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; /** * @Title: WebUtils * @Package: com.base.springboot.utils * @Description: TODO(添加描述) * @Author: monkjavaer * @Date: 2019/8/8 14:11 * @Version: V1.0 */ public class WebUtils { private static Logger logger = LoggerFactory.getLogger(WebUtils.class); private static final int BUFFER_SIZE = 1024; private WebUtils() { } /** * 获取客户端IP地址 * @param request * @return */ public static String getRemortIP(HttpServletRequest request) { if (request.getHeader("x-forwarded-for") == null) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); } public static JSONObject getRequest(HttpServletRequest request) { InputStream is = null; try { is = new BufferedInputStream(request.getInputStream(), BUFFER_SIZE); int contentLength = Integer.valueOf(request.getHeader("Content-Length")); byte[] bytes = new byte[contentLength]; int readCount = 0; while (readCount < contentLength) { readCount += is.read(bytes, readCount, contentLength - readCount); } String requestJson = new String(bytes, "UTF-8"); JSONObject jsonObj = JsonUtils.toJSONObject(requestJson); logger.info(String.format("--> URL={%s}, PARAMS={%s}",request.getRequestURI(), jsonObj)); return jsonObj; } catch (IOException e) { logger.error("error happens when get request, " + e.toString()); return null; } finally { IOUtils.closeQuietly(is); } } /** * * <b>方法说明:</b> * <ul> * 提取Http请求中的查询参数 * </ul> * @param request Http请求 * @param clazz 待提取的参数类型 * @return T 提取出来的参数对象 */ public static <T> T extractParams(HttpServletRequest request, Class<T> clazz) { try { T queryVO = clazz.newInstance(); for (Field field : queryVO.getClass().getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers())) { continue; //序列号不取 } String paramVal = request.getParameter(field.getName()); if (paramVal != null) { field.setAccessible(true); if (field.getGenericType().toString().equals("boolean") || field.getGenericType().toString().equals("class java.lang.Boolean")) { field.set(queryVO, Boolean.parseBoolean(paramVal)); } else if (field.getGenericType().toString().equals("char") || field.getGenericType().toString().equals("class java.lang.Character")) { field.set(queryVO, paramVal.charAt(0)); } else if (field.getGenericType().toString().equals("byte") || field.getGenericType().toString().equals("class java.lang.Byte")) { field.set(queryVO, paramVal.getBytes()[0]); } else if (field.getGenericType().toString().equals("short") || field.getGenericType().toString().equals("class java.lang.Short")) { field.set(queryVO, Short.parseShort(paramVal)); } else if (field.getGenericType().toString().equals("int") || field.getGenericType().toString().equals("class java.lang.Integer")) { field.set(queryVO, Integer.parseInt(paramVal)); } else if (field.getGenericType().toString().equals("long") || field.getGenericType().toString().equals("class java.lang.Long")) { field.set(queryVO, Long.parseLong(paramVal)); } else if (field.getGenericType().toString().equals("float") || field.getGenericType().toString().equals("class java.lang.Float")) { field.set(queryVO, Float.parseFloat(paramVal)); } else if (field.getGenericType().toString().equals("double") || field.getGenericType().toString().equals("class java.lang.Double")) { field.set(queryVO, Double.parseDouble(paramVal)); } else if (field.getGenericType().toString().equals("class java.lang.String")) { field.set(queryVO, paramVal); } else if (field.getGenericType().toString().equals("class java.util.Date")) { field.set(queryVO, DateTimeUtils.getDate(paramVal)); } } } return queryVO; } catch (Exception e) { logger.error("error happens when extractParams, " + e.toString()); throw new RuntimeException("Exception when trying to extract parameters from http redquest", e); } } }
42.75
155
0.588889
e20fc2520ba46e98a43d53d81e2a6e655fe14c83
619
package memstore.grader; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class GradescopeOutput { public int executionTime; public String stdout_visibility = "visible"; public List<GradedTestResult> tests; public List<LeaderBoardValue> leaderboard; public GradescopeOutput( int eTime, List<GradedTestResult> results, List<LeaderBoardValue> leaderboard ) { this.executionTime = eTime; this.tests = results; this.leaderboard = leaderboard; } }
26.913043
52
0.689822
d5d159b57122c808dea975058fb252060ae5033a
3,654
package kr.geun.o.config; import kr.geun.o.app.bbs.code.ArticleStatusCd; import kr.geun.o.app.bbs.model.BbsArticleEntity; import kr.geun.o.app.bbs.model.BbsCategoryEntity; import kr.geun.o.app.bbs.repository.BbsArticleRepository; import kr.geun.o.app.bbs.repository.BbsCategoryRepository; import kr.geun.o.app.user.model.UserAuthEntity; import kr.geun.o.app.user.model.UserEntity; import kr.geun.o.app.user.repository.UserAuthRepository; import kr.geun.o.app.user.repository.UserRepository; import kr.geun.o.core.constants.AuthorityCd; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author akageun */ @Slf4j @Component public class TempApplicationRunner implements CommandLineRunner { @Autowired private UserAuthRepository userAuthRepository; @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private BbsArticleRepository bbsArticleRepository; @Autowired private BbsCategoryRepository bbsCategoryRepository; @Override public void run(String... args) throws Exception { String userId = "test"; UserEntity userEntityParam = UserEntity.builder().userId(userId).passWd(passwordEncoder.encode("test")).build(); userRepository.save(userEntityParam); UserAuthEntity userAuthEntityParam = UserAuthEntity.builder().userId(userId).authorityCd(AuthorityCd.USER.roleCd()).build(); userAuthRepository.save(userAuthEntityParam); UserEntity userEntityParam2 = UserEntity.builder().userId(userId + "1").passWd(passwordEncoder.encode("test")).build(); userRepository.save(userEntityParam2); UserAuthEntity userAuthEntityParam2 = UserAuthEntity.builder().userId(userId + "1").authorityCd(AuthorityCd.ADMIN.roleCd()).build(); userAuthRepository.save(userAuthEntityParam2); UserAuthEntity userAuthEntityParam3 = UserAuthEntity.builder().userId(userId + "1").authorityCd(AuthorityCd.USER.roleCd()).build(); userAuthRepository.save(userAuthEntityParam3); List<BbsCategoryEntity> bbsCategoryEntities = IntStream.range(0, 5) .mapToObj(info -> BbsCategoryEntity.builder() .name("테스트 " + info) .type(ArticleStatusCd.NORMAL.name()) .createdUserId(userId) .updatedUserId(userId) .build() ).collect(Collectors.toList()); List<BbsCategoryEntity> bbsCategoryEntities1 = bbsCategoryRepository.saveAll(bbsCategoryEntities); List<BbsArticleEntity> article = IntStream.range(0, 30) .mapToObj(info -> BbsArticleEntity.builder() .title("테스트 " + info) .content("## 테스트 글 입니다.") .statusCd("NORMAL") .createdUserId(userId) .categoryId(bbsCategoryEntities1.get(RandomUtils.nextInt(0, 4)).getCategoryId()) .updatedUserId(userId).build() ).collect(Collectors.toList()); bbsArticleRepository.saveAll(article); } }
40.153846
140
0.670772
e0ef9e151a6aa5565dd57236dca1326a5375d326
2,023
package com.sequenceiq.flow.component.sleep.event; import java.util.ArrayList; import java.util.Objects; import com.sequenceiq.cloudbreak.common.event.AcceptResult; import com.sequenceiq.cloudbreak.common.event.IdempotentEvent; import reactor.rx.Promise; public class NestedSleepChainTriggerEvent implements IdempotentEvent<NestedSleepChainTriggerEvent> { public static final String NESTED_SLEEP_CHAIN_TRIGGER_EVENT = "NESTED_SLEEP_CHAIN_TRIGGER_EVENT"; private final Long resourceId; private final ArrayList<SleepChainTriggerEvent> sleepChainTriggerEvents; private final Promise<AcceptResult> accepted; public NestedSleepChainTriggerEvent(Long resourceId, ArrayList<SleepChainTriggerEvent> sleepChainTriggerEvents, Promise<AcceptResult> accepted) { this.resourceId = resourceId; this.sleepChainTriggerEvents = sleepChainTriggerEvents; this.accepted = accepted; } public ArrayList<SleepChainTriggerEvent> getSleepChainTriggerEvents() { return sleepChainTriggerEvents; } @Override public Long getResourceId() { return resourceId; } @Override public String selector() { return NESTED_SLEEP_CHAIN_TRIGGER_EVENT; } @Override public Promise<AcceptResult> accepted() { return accepted; } @Override public boolean equalsEvent(NestedSleepChainTriggerEvent other) { return equals(other); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !getClass().equals(o.getClass())) { return false; } NestedSleepChainTriggerEvent that = (NestedSleepChainTriggerEvent) o; return Objects.equals(resourceId, that.resourceId) && Objects.equals(sleepChainTriggerEvents, that.sleepChainTriggerEvents); } @Override public int hashCode() { return Objects.hash(resourceId, sleepChainTriggerEvents); } }
28.492958
101
0.704399
0f033e46a85316ffb14954ae2096e9637a104c2b
2,677
/* * Copyright (c) 2022 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.opengauss.mppdbide.bl.serverdatacache.groups; import org.opengauss.mppdbide.bl.serverdatacache.Database; /** * This class collects the Database objects * */ import org.opengauss.mppdbide.bl.serverdatacache.OBJECTTYPE; import org.opengauss.mppdbide.bl.serverdatacache.Server; import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; /** * * Title: class * * Description: The Class DatabaseObjectGroup. * */ public class DatabaseObjectGroup extends OLAPObjectGroup<Database> { private boolean isLoadingDatabaseGroupInProgress; /** * Instantiates a new database object group. * * @param type the type * @param server the server */ public DatabaseObjectGroup(OBJECTTYPE type, Server server) { super(type, server); } /** * Gets the server. * * @return the server */ public Server getServer() { return (Server) getParent(); } /** * Refresh. * * @throws DatabaseOperationException the database operation exception * @throws DatabaseCriticalException the database critical exception */ public void refresh() throws DatabaseOperationException, DatabaseCriticalException { Database db = this.getServer().findOneActiveDb(); this.getServer().refreshDBs(db); } /** * Checks if is loading database group in progress. * * @return true, if is loading database group in progress */ public boolean isLoadingDatabaseGroupInProgress() { return isLoadingDatabaseGroupInProgress; } /** * Sets the loading database group in progress. * * @param status the new loading database group in progress */ public void setLoadingDatabaseGroupInProgress(boolean status) { this.isLoadingDatabaseGroupInProgress = status; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } }
26.77
88
0.686589
757bed99164f23beaaf2d47378ab7a16c98ea775
936
package jedi.db.models; /** * @author thiago * @version v1.0.0 20/03/2017 * @since v1.0.0 */ public enum AutoClose { YES(true), NO(false); private final boolean value; private AutoClose(final boolean value) { this.value = value; } public static AutoClose of(boolean value) { return value == true ? YES : NO; } public static AutoClose of(String value) { if (value != null && value.matches("false|true")) { boolean value_ = Boolean.parseBoolean(value); return AutoClose.of(value_); } else { throw new IllegalArgumentException("A propriedade auto_close de jedi.properties só admite os valores false ou true!"); } } public static boolean of(AutoCommit autoClose) { return autoClose.value(); } public boolean isValue() { return value; } public boolean value() { return value; } }
20.8
127
0.604701
2cd2950164726a16eb3d31bff233d949789355dc
2,076
package datastructures; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class BinaryPTrieTest { private List<Integer> getInsertNumbers(String filepath) { try (BufferedReader reader = new BufferedReader(new FileReader(new File(filepath)))) { return reader.lines() .map(Integer::valueOf) .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); fail(); return new ArrayList<>(); } } private static final String INSERT_FILEPATH = "test/datastructures/data/test-insert.data"; private static final String NON_MEMBER_FILEPATH = "test/datastructures/data/test-is-member.data"; private Membership getFileFilledDataStructure() { BinaryTrie2 ds = new BinaryTrie2(); for (Integer number : getInsertNumbers(INSERT_FILEPATH)) { ds.insert(number); } return new BinaryPTrie(ds); } @Test public void testAllInsertedElementsArePresent() { Membership ds = getFileFilledDataStructure(); for (Integer number : getInsertNumbers(INSERT_FILEPATH)) { assertTrue(ds.isMember(number), String.format("%d should be in the data structure", number)); } } @Test public void testAllNonInsertedElementsAreNotPresent() { Membership ds = getFileFilledDataStructure(); for (Integer number : getInsertNumbers(NON_MEMBER_FILEPATH)) { assertFalse(ds.isMember(number), String.format("%d should NOT be in the data structure", number)); } } }
31.938462
101
0.675819
11af30197ba5642a6a639d4c559b474dcb0688ce
722
package pl.stqa.training.selenium.appmanager; import org.apache.commons.lang3.RandomStringUtils; import java.util.Random; /** * Created by Konrad on 26/11/2017. */ public class Generators extends HelperBase { public Generators(ApplicationManager app) throws Exception { super(app); } public static String getRandomAlphanumericString(int length){ return RandomStringUtils.randomAlphanumeric(length); } public static String getRandomAlphabeticString(int length){ return RandomStringUtils.randomAlphabetic(length); } public static int getRandomInt(int max){ return new Random().nextInt(max); } public static boolean getRandomBoolean(){ return new Random().nextBoolean(); } }
22.5625
63
0.752078
79493a68774abf0b31ba563e33686f991550b276
7,712
package com.tgithubc.kumao.message; import android.os.Looper; import android.util.Log; import android.util.Pair; import com.tgithubc.kumao.message.handler.ThreadMessageHandler; import com.tgithubc.kumao.message.message.Message; import com.tgithubc.kumao.message.message.RunThread; import com.tgithubc.kumao.message.proxy.DefaultProxyHandler; import com.tgithubc.kumao.message.proxy.StickyProxyHandler; import com.tgithubc.kumao.message.util.BusTool; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** * Bus * Created by tc :) */ public class MessageBus { private static final String TAG = "MessageBus"; private ThreadMessageHandler mMainHandler, mWorkHandler; // 观察者集合 private List<WeakReference<? extends IObserver>> mObservers; // 每一个事件接口,对应一个handler处理对象,循环处理所有相关订阅者的方法调用 private Map<Class<? extends IObserver>, DefaultProxyHandler> mProxyMap; private Map<Class<? extends IObserver>, StickyProxyHandler> mStickyProxyMap; // 这是个不太友好的数据结构,为了实现粘性消息的顺序激活,用了有序的list,多层pair为了记录方法信息 private List<Pair<Class<? extends IObserver>, Pair<Method, Object[]>>> mStickyMethodMap; private MessageBus() { mObservers = new CopyOnWriteArrayList<>(); mProxyMap = new ConcurrentHashMap<>(); mStickyMethodMap = new CopyOnWriteArrayList<>(); mStickyProxyMap = new ConcurrentHashMap<>(); mWorkHandler = new ThreadMessageHandler(); mMainHandler = new ThreadMessageHandler(Looper.getMainLooper()); } private static class SingletonHolder { private static final MessageBus BUS = new MessageBus(); } public static MessageBus instance() { return SingletonHolder.BUS; } /** * 获取接收普通消息对象的代理 * * @param clazz * @param <T> * @return */ public <T extends IObserver> T getDefault(Class<T> clazz) { return getProxy(clazz, false); } /** * 获取接收粘性消息对象的代理 * * @param clazz * @param <T> * @return */ public <T extends IObserver> T getSticky(Class<T> clazz) { return getProxy(clazz, true); } /** * 分发消息 * * @param message */ public void dispatch(Message message) { @RunThread int runThread = message.decorateInfo.runThread; long delayedTime = message.decorateInfo.delayedTime; switch (runThread) { case RunThread.MAIN: if (delayedTime > 0) { mMainHandler.postDelayed(message, delayedTime); } else { if (isMainThread()) { message.run(); } else { mMainHandler.post(message); } } break; case RunThread.BACKGROUND: if (delayedTime > 0) { mWorkHandler.postDelayed(message, delayedTime); } else { if (!isMainThread()) { message.run(); } else { mWorkHandler.post(message); } } break; default: break; } } /** * 注册 * * @param observer */ public void register(IObserver observer) { if (observer == null || hasRegistered(observer)) { Log.w(TAG, "observer == null or has been registered"); return; } mObservers.add(new WeakReference<>(observer)); Log.d(TAG, "add size :" + mObservers.size() + ",mObservers :" + mObservers); handlerStickyMessage(observer); } /** * 解注册 * * @param observer */ public void unRegister(IObserver observer) { if (observer == null) { return; } for (WeakReference<? extends IObserver> ref : mObservers) { IObserver ob = ref.get(); if (observer.equals(ob) || ob == null) { mObservers.remove(ref); } } Iterator iterator = mProxyMap.keySet().iterator(); while (iterator.hasNext()) { Class type = (Class) iterator.next(); if (type.isInstance(observer) && mProxyMap.get(type).getSameTypeObserverCount() == 0) { iterator.remove(); } } if (mObservers.size() == 0) { mMainHandler.stop(); mWorkHandler.stop(); } Log.d(TAG, "remove size :" + mObservers.size() + ",mObservers :" + mObservers); } /** * 移除指定粘性消息 * * @param stickClazz */ public void removeStickyMessage(Class<? extends IObserver> stickClazz) { mStickyProxyMap.remove(stickClazz); for (Pair<Class<? extends IObserver>, Pair<Method, Object[]>> pair : mStickyMethodMap) { if (stickClazz.equals(pair.first)) { mStickyMethodMap.remove(pair); } } } /** * 获取代理对象 * * @param clazz * @param sticky * @param <T> * @return */ @SuppressWarnings("unchecked") private <T extends IObserver> T getProxy(Class<T> clazz, boolean sticky) { DefaultProxyHandler handler; if (sticky) { handler = mStickyProxyMap.get(clazz); if (handler == null) { handler = new StickyProxyHandler(mStickyMethodMap, mObservers, clazz); mStickyProxyMap.put(clazz, (StickyProxyHandler) handler); } } else { handler = mProxyMap.get(clazz); if (handler == null) { handler = new DefaultProxyHandler(mObservers, clazz); mProxyMap.put(clazz, handler); } } return (T) handler.get(); } /** * 处理粘性消息 * * @param observer */ private void handlerStickyMessage(IObserver observer) { // ob对应的接口方法集合 List<Class<? extends IObserver>> list = BusTool.getAllMethodInterfaces(observer); for (Pair<Class<? extends IObserver>, Pair<Method, Object[]>> pair : mStickyMethodMap) { if (list.contains(pair.first)) { Pair<Method, Object[]> methodPair = pair.second; try { // 具体方法快照 Method method = methodPair.first; Object[] args = methodPair.second; // obMethod Method obMethod = observer.getClass().getMethod(method.getName(), method.getParameterTypes()); Message.DecorateInfo info = BusTool.getDecorateInfo(obMethod); // 是否粘性标示 if (info.isSticky) { // 生成message去分发 Message message = BusTool.obtainMessage(method, args, info, observer); dispatch(message); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } } } /** * 是否注册 * * @param observer * @return */ private boolean hasRegistered(IObserver observer) { for (WeakReference ref : mObservers) { IObserver o = (IObserver) ref.get(); if (observer.equals(o)) { return true; } } return false; } private boolean isMainThread() { return Thread.currentThread() == Looper.getMainLooper().getThread(); } }
30.125
114
0.55083
5ac5d15943538dccae54850e17aa34fbbd08face
3,216
//| Copyright - The University of Edinburgh 2013 | //| | //| 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.ed.epcc.webapp.jdbc.expr; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import uk.ac.ed.epcc.webapp.AppContext; import uk.ac.ed.epcc.webapp.content.Labeller; import uk.ac.ed.epcc.webapp.jdbc.exception.DataException; import uk.ac.ed.epcc.webapp.jdbc.filter.PatternArgument; import uk.ac.ed.epcc.webapp.jdbc.filter.SQLFilter; /** * @author spb * @param <T> type of nested SQLValue * @param <R> type of returned object * */ public class LabellerSQLValue<T,R> implements NestedSQLValue<R,T> { public LabellerSQLValue(AppContext c,Labeller<T,R> labeller, SQLValue<T> nested) { super(); this.conn=c; this.labeller = labeller; this.nested = nested; } private final AppContext conn; private final Labeller<T,R> labeller; private final SQLValue<T> nested; /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.Targetted#getTarget() */ public Class<R> getTarget() { return labeller.getTarget(); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.expr.SQLValue#add(java.lang.StringBuilder, boolean) */ public int add(StringBuilder sb, boolean qualify) { return nested.add(sb,qualify); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.expr.SQLValue#getParameters(java.util.List) */ public List<PatternArgument> getParameters(List<PatternArgument> list) { return nested.getParameters(list); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.expr.SQLValue#makeObject(java.sql.ResultSet, int) */ public R makeObject(ResultSet rs, int pos) throws DataException, SQLException { return labeller.getLabel(conn, nested.makeObject(rs, pos)); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.expr.SQLValue#getRequiredFilter() */ public SQLFilter getRequiredFilter() { return nested.getRequiredFilter(); } @Override public String toString() { return labeller.getClass().getSimpleName()+"("+nested.toString()+")"; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.expr.NestedSQLValue#getNested() */ @Override public SQLValue<T> getNested() { return nested; } @Override final public boolean groupingIsomorphic() { // labeller may map multiple records to the same label return false; } }
35.340659
86
0.637127
e815116889a04ca5297de0cb1fcf12927326416c
6,849
/* * Copyright (C) 2021 Not Alexa * * 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 not.alexa.netobjects.types; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Abstract type for interfaces and classes. Types based on this class are allowed to reference them self if and only if they are not * {@link TypeDefinition#isAnonymous()}. * * @author notalexa * */ public abstract class AbstractClassTypeDefinition extends TypeDefinition { private static final MethodTypeDefinition[] NO_METHODS=new MethodTypeDefinition[0]; private boolean immutable; protected int h; protected InterfaceTypeDefinition[] interfaces; protected MethodTypeDefinition[] methods=NO_METHODS; protected MethodTypeDefinition[] allMethods=NO_METHODS; protected AbstractClassTypeDefinition(Class<?> clazz) { super(clazz); } public AbstractClassTypeDefinition(ObjectType... types) { super(types); } @Override public MethodTypeDefinition[] getMethods() { return allMethods; } @Override protected boolean isImmutable() { return immutable; } @Override public synchronized TypeDefinition fix() { immutable=true; return this; } protected abstract void calculateHash(); public int hashCode() { return h; } public boolean equals(Object o) { if(o.getClass().equals(getClass())&&o.hashCode()==hashCode()) { AbstractClassTypeDefinition other=(AbstractClassTypeDefinition)o; if(isAnonymous()) { if(other.isAnonymous()) { return deepEquals(other); } else { return false; } } else if(!other.isAnonymous()) { if(check(other)==0) { return true; } } } return false; } protected boolean deepEquals(AbstractClassTypeDefinition other) { return Arrays.equals(other.methods,methods); } /** * Add interfaces to this class type declaration. This interfaces are <b>not part of the global class definition</b> but can be * defined in a <b>local execution environment</b> and are therefore non persistent. * * @param interfaces the interfaces to add * @return this type description */ public synchronized AbstractClassTypeDefinition addInterface(InterfaceTypeDefinition...interfaces) { if(this.interfaces==null) { this.interfaces=interfaces.length==0?null:interfaces; } else { InterfaceTypeDefinition[] tmp=this.interfaces; outerloop:for(InterfaceTypeDefinition i:interfaces) { if(i==null) { continue outerloop; } for(InterfaceTypeDefinition i1:this.interfaces) { if(i1.equals(i)) { continue outerloop; } } tmp=Arrays.copyOf(tmp,tmp.length+1); tmp[tmp.length-1]=i; } this.interfaces=tmp; } if(this.interfaces!=null) { allMethods=computeMethodArray(Arrays.asList(methods),this.interfaces); } return this; } private MethodTypeDefinition[] computeMethodArray(List<MethodTypeDefinition> methodTypes,InterfaceTypeDefinition[] interfaces) { Set<MethodTypeDefinition> methods=new HashSet<MethodTypeDefinition>(methodTypes); if(interfaces!=null) for(InterfaceTypeDefinition i:interfaces) { for(MethodTypeDefinition methodType:i.getMethods()) { methods.add(methodType.forClass(this)); } } return methods.toArray(new MethodTypeDefinition[methods.size()]); } protected abstract class Builder<T extends Builder<T>> { protected List<MethodTypeDefinition> methods=new ArrayList<MethodTypeDefinition>(); /** * Create a new method for this type * * @param name the name of the method. * @return a builder for additional configuration */ public MethodBuilder createMethod(String name) { return new MethodBuilder(name); } /** * After creation, the type is immutable. * * @return the type definition build from this builder. */ public AbstractClassTypeDefinition build() { synchronized (AbstractClassTypeDefinition.this) { if(!immutable) { immutable=true; allMethods=AbstractClassTypeDefinition.this.methods=computeMethodArray(methods,null); } return AbstractClassTypeDefinition.this; } } /** * Add all methods of all interfaces to this type definition. This methods become part of the global definition. * * @param interfaces the interfaces to add * @return this for additional configuration */ public T addInterface(InterfaceTypeDefinition...interfaces) { for(InterfaceTypeDefinition i:interfaces) { for(MethodTypeDefinition m:i.getMethods()) { methods.add(m); } } return self(); } /** * * @return <code>true</code> if the underlying type is already immutable */ public boolean isImmutable() { return AbstractClassTypeDefinition.this.isImmutable(); } protected abstract T self(); public class MethodBuilder { private List<ObjectType> types=new ArrayList<ObjectType>(); private MethodTypeDefinition.Builder builder; private MethodBuilder(String name) { builder=new MethodTypeDefinition(AbstractClassTypeDefinition.this,name).createBuilder(); } /** * * @return a method type definition build from the builders material */ public T build() { MethodTypeDefinition m=builder.build(); for(ObjectType t:types) { m.addTypes(t); } for(ObjectType t:getTypes()) { m.addTypes(t.getNamespace().createMethodType(m)); } methods.add(m); return self(); } public MethodBuilder setTypes(ObjectType...types) { for(ObjectType t:types) { if(t!=null) { this.types.add(t); } } return this; } /** * Modify the parameter types of this method * @param parameterTypes the new parameter types * @return <code>this</code> */ public MethodBuilder setParameterTypes(TypeDefinition...parameterTypes) { builder.setParameterTypes(parameterTypes); return this; } /** * Modify the return types of this method * @param returnTypes the new return types * @return <code>this</code> */ public MethodBuilder setReturnTypes(TypeDefinition...returnTypes) { builder.setReturnTypes(returnTypes); return this; } } } }
28.5375
133
0.691196
75f30fb0fd25fd66b97ff66eb912a6573dbc2614
2,073
// Copyright 2005 Google Inc. // All Rights Reserved. package net.jsunit; import junit.framework.TestCase; import net.jsunit.utility.XmlUtility; import org.jdom.Document; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; public class RemoteMachineRunnerHitterTest extends TestCase { String xml = "<my_document><my_node value=\"1\">my text</my_node></my_document>"; public void testAllAtOnce() throws Exception { RemoteMachineServerHitter hitter = new RemoteMachineServerHitter(); Document document = hitter.hitURL(createURL(xml, xml.length())); assertDocumentHasXml(xml, document); } public void testAPieceAtATime() throws Exception { RemoteMachineServerHitter hitter = new RemoteMachineServerHitter(); Document document = hitter.hitURL(createURL(xml, 3)); assertDocumentHasXml(xml, document); } private void assertDocumentHasXml(String expectedXML, Document document) { assertEquals(expectedXML, XmlUtility.asString(document.getRootElement())); } private URL createURL(final String xml, final int byteCount) throws MalformedURLException { return new URL("http", "www.example.com", 8080, "foo", new URLStreamHandler() { protected URLConnection openConnection(URL u) { return new URLConnection(u) { public void connect() { } public InputStream getInputStream() { return new InputStream() { private int index = 0; public int read() { if (index >= xml.length()) return -1; return xml.codePointAt(index++); } }; } }; } }); } }
34.55
96
0.575494
b974abbbebbd834c8df7a10c8e03918f45d0fef7
115
void advance() { do { position += 2; } while (position < data.length && data[position] == EMPTY); }
23
64
0.53913
879c7c238fa5658800e5e174b2e106181b9baf0b
10,667
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document package|; end_package begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|util operator|. name|Utils import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|base operator|. name|Stopwatch import|; end_import begin_import import|import static name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit operator|. name|MILLISECONDS import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|Collection operator|. name|SETTINGS import|; end_import begin_comment comment|/** * The JournalGarbageCollector can clean up JournalEntries that are older than a * particular age. *<p> * It would typically be invoked in conjunction with the VersionGarbageCollector * but must not be confused with that one - 'journal' refers to the separate * collection that contains changed paths per background writes used for * observation. */ end_comment begin_class specifier|public class|class name|JournalGarbageCollector block|{ specifier|private specifier|static specifier|final name|Logger name|log init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|JournalGarbageCollector operator|. name|class argument_list|) decl_stmt|; comment|/** * ID of the journalGC document in the settings collection. */ specifier|private specifier|static specifier|final name|String name|JOURNAL_GC_ID init|= literal|"journalGC" decl_stmt|; comment|/** * Key name of the entry that contains the timestamp of the journal tail. */ specifier|private specifier|static specifier|final name|String name|TAIL_TIMESTAMP init|= literal|"tailTimestamp" decl_stmt|; specifier|private specifier|final name|DocumentNodeStore name|ns decl_stmt|; specifier|private specifier|final name|long name|maxRevisionAgeMillis decl_stmt|; specifier|private specifier|volatile name|long name|lastTailTimestampRefresh init|= name|Long operator|. name|MIN_VALUE decl_stmt|; specifier|private name|Revision name|tailRevision decl_stmt|; specifier|public name|JournalGarbageCollector parameter_list|( name|DocumentNodeStore name|nodeStore parameter_list|, name|long name|maxRevisionAgeMillis parameter_list|) block|{ name|this operator|. name|ns operator|= name|nodeStore expr_stmt|; name|this operator|. name|maxRevisionAgeMillis operator|= name|maxRevisionAgeMillis expr_stmt|; name|this operator|. name|tailRevision operator|= operator|new name|Revision argument_list|( literal|0 argument_list|, literal|0 argument_list|, name|ns operator|. name|getClusterId argument_list|() argument_list|) expr_stmt|; block|} comment|/** * Deletes entries in the journal that are older than * {@link #getMaxRevisionAgeMillis()}. * * @return the number of entries that have been removed */ specifier|public name|int name|gc parameter_list|() block|{ name|DocumentStore name|ds init|= name|ns operator|. name|getDocumentStore argument_list|() decl_stmt|; name|Revision name|checkpointRev init|= name|ns operator|. name|getCheckpoints argument_list|() operator|. name|getOldestRevisionToKeep argument_list|() decl_stmt|; name|Long name|keep init|= literal|null decl_stmt|; if|if condition|( name|checkpointRev operator|!= literal|null condition|) block|{ comment|// keep more entries than just up to the checkpoint to account comment|// for branch commits that may be referenced by merge commits name|keep operator|= name|checkpointRev operator|. name|getTimestamp argument_list|() operator|- name|maxRevisionAgeMillis operator|/ literal|2 expr_stmt|; block|} name|long name|now init|= name|ns operator|. name|getClock argument_list|() operator|. name|getTime argument_list|() decl_stmt|; name|long name|gcOlderThan init|= name|now operator|- name|maxRevisionAgeMillis decl_stmt|; if|if condition|( name|keep operator|!= literal|null operator|&& name|keep operator|< name|gcOlderThan condition|) block|{ name|gcOlderThan operator|= name|keep expr_stmt|; name|log operator|. name|debug argument_list|( literal|"gc: Checkpoint {} is older than maxRevisionAge: {} min" argument_list|, name|keep argument_list|, name|MILLISECONDS operator|. name|toMinutes argument_list|( name|maxRevisionAgeMillis argument_list|) argument_list|) expr_stmt|; block|} if|if condition|( name|log operator|. name|isDebugEnabled argument_list|() condition|) block|{ name|log operator|. name|debug argument_list|( literal|"gc: Journal garbage collection starts with maxAge: {} min." argument_list|, name|MILLISECONDS operator|. name|toMinutes argument_list|( name|maxRevisionAgeMillis argument_list|) argument_list|) expr_stmt|; block|} name|Stopwatch name|sw init|= name|Stopwatch operator|. name|createStarted argument_list|() decl_stmt|; comment|// update the tail timestamp in the journalGC document comment|// of the settings collection name|updateTailTimestamp argument_list|( name|gcOlderThan argument_list|) expr_stmt|; name|int name|numDeleted init|= name|ds operator|. name|remove argument_list|( name|Collection operator|. name|JOURNAL argument_list|, name|JournalEntry operator|. name|MODIFIED argument_list|, literal|0 argument_list|, name|gcOlderThan argument_list|) decl_stmt|; name|sw operator|. name|stop argument_list|() expr_stmt|; if|if condition|( name|numDeleted operator|> literal|0 condition|) block|{ name|log operator|. name|info argument_list|( literal|"gc: Journal garbage collection took {}, deleted {} entries that were older than {} min." argument_list|, name|sw argument_list|, name|numDeleted argument_list|, name|MILLISECONDS operator|. name|toMinutes argument_list|( name|now operator|- name|gcOlderThan argument_list|) argument_list|) expr_stmt|; block|} return|return name|numDeleted return|; block|} specifier|private name|void name|updateTailTimestamp parameter_list|( name|long name|gcOlderThan parameter_list|) block|{ name|UpdateOp name|op init|= operator|new name|UpdateOp argument_list|( name|JOURNAL_GC_ID argument_list|, literal|true argument_list|) decl_stmt|; name|op operator|. name|max argument_list|( name|TAIL_TIMESTAMP argument_list|, name|gcOlderThan argument_list|) expr_stmt|; name|ns operator|. name|getDocumentStore argument_list|() operator|. name|createOrUpdate argument_list|( name|SETTINGS argument_list|, name|op argument_list|) expr_stmt|; block|} specifier|public name|Revision name|getTailRevision parameter_list|() block|{ name|refreshTailRevisionIfNecessary argument_list|() expr_stmt|; return|return name|tailRevision return|; block|} name|long name|getMaxRevisionAgeMillis parameter_list|() block|{ return|return name|maxRevisionAgeMillis return|; block|} specifier|private name|void name|refreshTailRevisionIfNecessary parameter_list|() block|{ comment|// refresh once a minute name|long name|now init|= name|ns operator|. name|getClock argument_list|() operator|. name|getTime argument_list|() decl_stmt|; if|if condition|( name|lastTailTimestampRefresh operator|+ name|TimeUnit operator|. name|MINUTES operator|. name|toMillis argument_list|( literal|1 argument_list|) operator|> name|now condition|) block|{ return|return; block|} name|lastTailTimestampRefresh operator|= name|now expr_stmt|; name|Document name|doc init|= name|ns operator|. name|getDocumentStore argument_list|() operator|. name|find argument_list|( name|SETTINGS argument_list|, name|JOURNAL_GC_ID argument_list|) decl_stmt|; if|if condition|( name|doc operator|== literal|null condition|) block|{ comment|// no gc yet return|return; block|} name|Long name|ts init|= name|Utils operator|. name|asLong argument_list|( operator|( name|Number operator|) name|doc operator|. name|get argument_list|( name|TAIL_TIMESTAMP argument_list|) argument_list|) decl_stmt|; if|if condition|( name|ts operator|!= literal|null condition|) block|{ name|tailRevision operator|= name|Utils operator|. name|max argument_list|( name|tailRevision argument_list|, operator|new name|Revision argument_list|( name|ts argument_list|, literal|0 argument_list|, name|ns operator|. name|getClusterId argument_list|() argument_list|) argument_list|) expr_stmt|; block|} block|} specifier|private name|List argument_list|< name|String argument_list|> name|asKeys parameter_list|( name|List argument_list|< name|JournalEntry argument_list|> name|deletionBatch parameter_list|) block|{ specifier|final name|List argument_list|< name|String argument_list|> name|keys init|= operator|new name|ArrayList argument_list|< name|String argument_list|> argument_list|( name|deletionBatch operator|. name|size argument_list|() argument_list|) decl_stmt|; for|for control|( name|JournalEntry name|e range|: name|deletionBatch control|) block|{ name|keys operator|. name|add argument_list|( name|e operator|. name|getId argument_list|() argument_list|) expr_stmt|; block|} return|return name|keys return|; block|} block|} end_class end_unit
15.733038
815
0.794881
9682a821ae27445e52dbe8233a34f52e46010dcd
88
package note.designPattern.abstractFactory; public class AudiSedan implements Sedan{ }
17.6
43
0.840909
8c784a7861287206ec29ae8b98f09bece93db0d8
8,551
/** 12.12.2011 01:16 */ package fabric.module.typegen.base; import java.util.List; import java.util.Stack; import java.util.HashMap; import org.apache.xmlbeans.SchemaType; import fabric.module.typegen.AttributeContainer; import fabric.wsdlschemaparser.schema.FSchemaRestrictions; import fabric.wsdlschemaparser.schema.FSchemaType; import fabric.wsdlschemaparser.schema.FSimpleType; /** * This helper class contains various static methods that are * being used by both the JavaTypeGen and the CppTypeGen class. * The functions that are provided are of different kind. They * were externalized to increase readability and improve the * overall maintainability of the TypeGen implementations. * * @author seidel */ public class TypeGenHelper { /** * Private constructor, because all methods of this class are static. */ private TypeGenHelper() { // Empty implementation } /** * Create an AttributeContainer.Restriction object according to * the restrictions, which are set in the provided type object. * This way we can add restrictions to a container class and * take them into account, when we do the source code write-out. * * @param type FSimpleType object (may be restricted) * * @return Restriction object for AttributeContainer */ public static AttributeContainer.Restriction createRestrictions(final FSimpleType type) { AttributeContainer.Restriction restrictions = new AttributeContainer.Restriction(); // Determine restrictions, which are currently set on the type object FSchemaRestrictions schemaRestrictions = type.getRestrictions(); List<Integer> validFacets = type.getValidFacets(); // Iterate over all possible restrictions... for (Integer facet: validFacets) { // ... and check which are set switch (facet) { // Type object is length restricted case SchemaType.FACET_LENGTH: if (schemaRestrictions.hasRestriction(facet)) { restrictions.length = schemaRestrictions.getStringValue(facet); } break; // Type object is minLength restricted case SchemaType.FACET_MIN_LENGTH: if (schemaRestrictions.hasRestriction(facet)) { restrictions.minLength = schemaRestrictions.getStringValue(facet); } break; // Type object is maxLength restricted case SchemaType.FACET_MAX_LENGTH: if (schemaRestrictions.hasRestriction(facet)) { restrictions.maxLength = schemaRestrictions.getStringValue(facet); } break; // Type object is minInclusive restricted case SchemaType.FACET_MIN_INCLUSIVE: if (schemaRestrictions.hasRestriction(facet)) { restrictions.minInclusive = schemaRestrictions.getStringValue(facet); } break; // Type object is maxInclusive restricted case SchemaType.FACET_MAX_INCLUSIVE: if (schemaRestrictions.hasRestriction(facet)) { restrictions.maxInclusive = schemaRestrictions.getStringValue(facet); } break; // Type object is minExclusive restricted case SchemaType.FACET_MIN_EXCLUSIVE: if (schemaRestrictions.hasRestriction(facet)) { restrictions.minExclusive = schemaRestrictions.getStringValue(facet); } break; // Type object is maxExclusive restricted case SchemaType.FACET_MAX_EXCLUSIVE: if (schemaRestrictions.hasRestriction(facet)) { restrictions.maxExclusive = schemaRestrictions.getStringValue(facet); } break; // Type object is pattern restricted case SchemaType.FACET_PATTERN: if (schemaRestrictions.hasRestriction(facet)) { restrictions.pattern = schemaRestrictions.getStringValue(facet); } break; // Type object is whiteSpace restricted case SchemaType.FACET_WHITE_SPACE: if (schemaRestrictions.hasRestriction(facet)) { restrictions.whiteSpace = TypeGenHelper.translateWhiteSpaceRestriction( schemaRestrictions.getStringValue(facet)); } break; // Type object is totalDigits restricted case SchemaType.FACET_TOTAL_DIGITS: if (schemaRestrictions.hasRestriction(facet)) { restrictions.totalDigits = schemaRestrictions.getStringValue(facet); } break; // Type object is fractionDigits restricted case SchemaType.FACET_FRACTION_DIGITS: if (schemaRestrictions.hasRestriction(facet)) { restrictions.fractionDigits = schemaRestrictions.getStringValue(facet); } break; // Type object is not restricted default: break; } } return restrictions; } /** * Return simple class name of the Fabric FSchemaType object. * This is used for the internal mapping of the basic XSD * data types (i.e. xs:string, xs:short, ...). * * @param type FSchemaType object * * @return Simple class name of type object */ public static String getFabricTypeName(final FSchemaType type) { return type.getClass().getSimpleName(); } /** * Helper method to check, whether there are any incomplete local * builders for the container class, which has been added to the * top-level incompleteBuilders stack last. * * The boolean expression was moved to this function to increase * code readability at the location where it is being called. * * @param incompleteBuilders Stack of incomplete builders * @param incompleteLocalBuilders Map of incomplete local builders * * @return True if incomplete local builders exist, false otherwise */ public static boolean hasIncompleteLocalBuilders(final Stack<AttributeContainer.Builder> incompleteBuilders, HashMap<String, Stack<AttributeContainer.Builder>> incompleteLocalBuilders) { return (!incompleteBuilders.empty() && !incompleteLocalBuilders.isEmpty() && // Stack and Map must not be empty null != incompleteLocalBuilders.get(incompleteBuilders.peek().getName()) && // Stack must be initialized (not null) !incompleteLocalBuilders.get(incompleteBuilders.peek().getName()).empty()); // Stack must not be empty } /** * Helper method to check, whether the stack of incomplete local * builders for a given container class is empty or not. * * The boolean expression was moved to this function to increase * code readability in the loop where it is being called. * * @param incompleteLocalBuilders Map of incomplete local builders * @param className Name of outer container class * * @return True while stack is not empty, false otherwise */ public static boolean stackIsNotEmpty( final HashMap<String, Stack<AttributeContainer.Builder>> incompleteLocalBuilders, final String className) { return (incompleteLocalBuilders.containsKey(className) && // Map must contain entry for class name null != incompleteLocalBuilders.get(className) && // Stack must be initialized (not null) !incompleteLocalBuilders.get(className).empty()); // Stack must not be empty } /** * Translate identifiers for 'whiteSpace' restriction from weird * XMLBeans values to proper textual representation. XMLBeans may * either deliver strings or numeric identifiers, when we call * schemaRestrictions.getStringValue(facet), so we need this rather * dirty hack to get a clean textual representation of the current * 'whiteSpace' value. * * @param xmlBeansConstant XMLBeans identifier for 'whiteSpace' value * * @return Proper string representation of identifier or 'null', if * 'whiteSpace' restriction is not set or has unknown value */ public static String translateWhiteSpaceRestriction(final String xmlBeansConstant) { String result = ""; if (("preserve").equals(xmlBeansConstant) || ("1").equals(xmlBeansConstant)) { result = "preserve"; } else if (("replace").equals(xmlBeansConstant) || ("2").equals(xmlBeansConstant)) { result = "replace"; } else if (("collapse").equals(xmlBeansConstant) || ("3").equals(xmlBeansConstant)) { result = "collapse"; } else { result = null; } return result; } }
34.479839
127
0.678751
9479e2d246b87aa619de273e35e03f8d679bf094
1,505
/* * Copyright (c) 1998-2021 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.grib.grib1; import static com.google.common.truth.Truth.assertThat; import java.io.IOException; import java.lang.invoke.MethodHandles; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.array.Array; import ucar.nc2.NetcdfFile; import ucar.nc2.NetcdfFiles; import ucar.nc2.Variable; public class TestSinglePointGds { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); /** * See https://github.com/Unidata/netcdf-java/issues/297 * * This tests reading a GRIB message with a GDS describing a single lat/lon point. * */ @Test public void checkLatLon() throws IOException { final String testfile = "../grib/src/test/data/single_point_gds.grib1"; final float expectedLon = 76.21f; final float expectedLat = 18.95f; final float tol = 0.001f; try (NetcdfFile nc = NetcdfFiles.open(testfile)) { checkVal(nc.findVariable("lon"), expectedLon, tol); checkVal(nc.findVariable("lat"), expectedLat, tol); } } private void checkVal(Variable variable, float expectedValue, float tol) throws IOException { Array<Float> array = (Array<Float>) variable.readArray(); assertThat(array.getSize()).isEqualTo(1); float val = array.get(0); assertThat(val).isWithin(tol).of(expectedValue); } }
32.021277
101
0.730233
cb7d8c37fef26d7fd502b41e0134f2ead4f1d57f
14,401
package at.ac.tuwien.ec.sleipnir; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.PairFlatMapFunction; import org.apache.spark.api.java.function.PairFunction; import org.apache.spark.scheduler.AllJobsCancelled; import at.ac.tuwien.ec.datamodel.DataDistributionGenerator; import at.ac.tuwien.ec.datamodel.DataEntry; import at.ac.tuwien.ec.datamodel.algorithms.placement.DataPlacementAlgorithm; import at.ac.tuwien.ec.datamodel.algorithms.placement.FFDCPUPlacement; import at.ac.tuwien.ec.datamodel.algorithms.placement.FFDPRODPlacement; import at.ac.tuwien.ec.datamodel.algorithms.placement.L2NormPlacement; import at.ac.tuwien.ec.datamodel.algorithms.placement.SteinerTreeHeuristic; import at.ac.tuwien.ec.datamodel.algorithms.selection.BestFitCPU; import at.ac.tuwien.ec.datamodel.algorithms.selection.FirstFitCPUDecreasing; import at.ac.tuwien.ec.datamodel.algorithms.selection.FirstFitCPUIncreasing; import at.ac.tuwien.ec.datamodel.algorithms.selection.FirstFitDecreasingSizeVMPlanner; import at.ac.tuwien.ec.datamodel.algorithms.selection.VMPlanner; import at.ac.tuwien.ec.datamodel.placement.DataPlacement; import at.ac.tuwien.ec.model.infrastructure.MobileBlockchainInfrastructure; import at.ac.tuwien.ec.model.infrastructure.MobileDataDistributionInfrastructure; import at.ac.tuwien.ec.model.infrastructure.planning.DefaultCloudPlanner; import at.ac.tuwien.ec.model.infrastructure.planning.DefaultIoTPlanner; import at.ac.tuwien.ec.model.infrastructure.planning.DefaultNetworkPlanner; import at.ac.tuwien.ec.model.infrastructure.planning.edge.EdgeAllCellPlanner; import at.ac.tuwien.ec.model.infrastructure.planning.edge.RandomEdgePlanner; import at.ac.tuwien.ec.model.infrastructure.planning.mobile.DefaultMobileDevicePlanner; import at.ac.tuwien.ec.model.infrastructure.planning.mobile.MobileDevicePlannerWithMobility; import at.ac.tuwien.ec.scheduling.offloading.pos.PoSNearestNodeBroker; import at.ac.tuwien.ec.scheduling.offloading.pos.PoSOffloadingAlgorithm; import at.ac.tuwien.ec.scheduling.offloading.pos.ValidationOffloadScheduling; import at.ac.tuwien.ec.scheduling.offloading.pos.Z3PoSBroker; import at.ac.tuwien.ec.scheduling.utils.blockchain.TransactionPool; import scala.Tuple2; import scala.Tuple4; import scala.Tuple5; public class UCC2019Main { public static void main(String[] arg) { Logger.getLogger("org").setLevel(Level.OFF); Logger.getLogger("akka").setLevel(Level.OFF); class FrequencyComparator implements Comparator<Tuple2<ValidationOffloadScheduling, Tuple5<Integer,Double,Double,Double,Double>>>, Serializable { /** * */ private static final long serialVersionUID = -2034500309733677393L; @Override public int compare(Tuple2<ValidationOffloadScheduling, Tuple5<Integer, Double, Double,Double, Double>> o1, Tuple2<ValidationOffloadScheduling, Tuple5<Integer, Double, Double,Double, Double>> o2) { // TODO Auto-generated method stub return o1._2()._1() - o2._2()._1(); } } processArgs(arg); switch(SimulationSetup.area) { case "HERNALS": SimulationSetup.MAP_M = 6; SimulationSetup.MAP_N = 6; SimulationSetup.iotDevicesNum = 36; //SimulationSetup.mobileNum = 24; SimulationSetup.mobileNum = 12; SimulationSetup.mobilityTraceFile = "traces/hernals.coords"; SimulationSetup.x_max = 3119; SimulationSetup.y_max = 3224; break; case "LEOPOLDSTADT": SimulationSetup.MAP_M = 10; SimulationSetup.MAP_N = 10; SimulationSetup.iotDevicesNum = 100; //SimulationSetup.mobileNum = 40; SimulationSetup.mobileNum = 20; SimulationSetup.mobilityTraceFile = "traces/leopoldstadt.coords"; SimulationSetup.x_max = 11098; SimulationSetup.y_max = 9099; break; case "SIMMERING": SimulationSetup.MAP_M = 12; SimulationSetup.MAP_N = 12; SimulationSetup.iotDevicesNum = 144; //SimulationSetup.mobileNum = 48; SimulationSetup.mobileNum = 24; SimulationSetup.mobilityTraceFile = "traces/simmering.coords"; SimulationSetup.x_max = 6720; SimulationSetup.y_max = 5623; break; } SparkConf configuration = new SparkConf(); configuration.setMaster("local"); configuration.setAppName("Sleipnir"); JavaSparkContext jscontext = new JavaSparkContext(configuration); Z3PoSBroker.loadLibrary(); ArrayList<Tuple2<TransactionPool,MobileBlockchainInfrastructure>> test = generateSamples(SimulationSetup.iterations); JavaRDD<Tuple2<TransactionPool, MobileBlockchainInfrastructure>> input = jscontext.parallelize(test); JavaPairRDD<ValidationOffloadScheduling,Tuple5<Integer,Double, Double, Double,Double>> results = input.flatMapToPair(new PairFlatMapFunction<Tuple2<TransactionPool,MobileBlockchainInfrastructure>, ValidationOffloadScheduling, Tuple5<Integer,Double, Double, Double,Double>>() { private static final long serialVersionUID = 1L; @Override public Iterator<Tuple2<ValidationOffloadScheduling, Tuple5<Integer, Double, Double, Double,Double>>> call(Tuple2<TransactionPool, MobileBlockchainInfrastructure> inputValues) throws Exception { ArrayList<Tuple2<ValidationOffloadScheduling,Tuple5<Integer,Double,Double, Double,Double>>> output = new ArrayList<Tuple2<ValidationOffloadScheduling,Tuple5<Integer,Double, Double, Double,Double>>>(); //HEFTResearch search = new HEFTResearch(inputValues); PoSOffloadingAlgorithm search = new Z3PoSBroker(inputValues); //PoSOffloadingAlgorithm search = new PoSNearestNodeBroker(inputValues); //RandomDataPlacementAlgorithm search = new RandomDataPlacementAlgorithm(new FirstFitDecreasingSizeVMPlanner(),inputValues); //SteinerTreeHeuristic search = new SteinerTreeHeuristic(currentPlanner, inputValues); ArrayList<ValidationOffloadScheduling> offloads = (ArrayList<ValidationOffloadScheduling>) search.findScheduling(); if(offloads != null) for(ValidationOffloadScheduling dp : offloads) { if(dp!=null) output.add( new Tuple2<ValidationOffloadScheduling,Tuple5<Integer,Double, Double, Double, Double>>(dp, new Tuple5<Integer,Double, Double,Double,Double>( 1, dp.getRunTime(), dp.getUserCost(), dp.getBatteryLifetime(), dp.getSimTime() ))); } return output.iterator(); } }); System.out.println(results.first()); JavaPairRDD<ValidationOffloadScheduling,Tuple5<Integer,Double, Double, Double, Double>> aggregation = results.reduceByKey( new Function2<Tuple5<Integer,Double, Double,Double,Double>, Tuple5<Integer,Double,Double,Double,Double>, Tuple5<Integer,Double,Double,Double,Double>>() { /** * */ private static final long serialVersionUID = 1L; @Override public Tuple5<Integer, Double, Double, Double, Double> call( Tuple5<Integer, Double,Double, Double, Double> off1, Tuple5<Integer, Double,Double, Double, Double> off2) throws Exception { // TODO Auto-generated method stub return new Tuple5<Integer, Double, Double, Double, Double>( off1._1() + off2._1(), off1._2() + off2._2(), off1._3() + off2._3(), off1._4() + off2._4(), off1._5() + off2._5() ); } } ); System.out.println(aggregation.first()); JavaPairRDD<ValidationOffloadScheduling,Tuple5<Integer,Double, Double, Double, Double>> histogram = aggregation.mapToPair( new PairFunction<Tuple2<ValidationOffloadScheduling,Tuple5<Integer, Double, Double, Double, Double>>, ValidationOffloadScheduling,Tuple5<Integer, Double, Double, Double,Double>>() { private static final long serialVersionUID = 1L; @Override public Tuple2<ValidationOffloadScheduling, Tuple5<Integer, Double, Double, Double, Double>> call( Tuple2<ValidationOffloadScheduling, Tuple5<Integer, Double, Double, Double, Double>> arg0) throws Exception { Tuple5<Integer, Double, Double, Double, Double> val = arg0._2(); Tuple5<Integer, Double, Double, Double, Double> tNew = new Tuple5<Integer, Double, Double, Double, Double> ( val._1(), val._2()/val._1(), val._3()/val._1(), val._4()/val._1(), val._5()/val._1() ); return new Tuple2<ValidationOffloadScheduling,Tuple5<Integer, Double, Double, Double, Double>>(arg0._1,tNew); } } ); JavaPairRDD<ValidationOffloadScheduling,Tuple5<Integer,Double,Double,Double,Double>> histogramF = histogram.filter((t -> ( !Double.isNaN(t._2()._2()) && !Double.isNaN(t._2()._3()) && !Double.isNaN(t._2()._4()) && !Double.isNaN(t._2()._5()) ))); Tuple2<ValidationOffloadScheduling, Tuple5<Integer, Double, Double, Double, Double>> mostFrequent = histogramF.max(new FrequencyComparator()); System.out.println(mostFrequent._2()); double runtimes[], profits[], energies[], simtimes[]; runtimes = new double[histogramF.collect().size()]; profits = new double[histogramF.collect().size()]; energies = new double[histogramF.collect().size()]; simtimes = new double[histogramF.collect().size()]; double runtimeAvg = 0, profitAvg = 0, energyAvg = 0, simtimeAvg = 0; int i = 0, nSamples = 0; for(Tuple2<ValidationOffloadScheduling, Tuple5<Integer, Double, Double, Double, Double>> t : histogramF.collect()) { if( !validNumber(t._2()._2()) && !validNumber(t._2()._3()) && !validNumber(t._2()._4()) && !validNumber(t._2()._5())) continue; nSamples++; runtimeAvg += t._2()._2(); profitAvg += t._2()._3(); energyAvg += t._2()._4(); simtimeAvg += t._2()._5(); runtimes[i] = t._2()._2(); profits[i] = t._2()._3(); energies[i] = t._2()._4(); simtimes[i] = t._2()._5(); } runtimeAvg = runtimeAvg/nSamples; profitAvg = profitAvg/nSamples; energyAvg = energyAvg/nSamples; simtimeAvg = simtimeAvg/nSamples; double varRt = 0.0, varProfit = 0.0, varEnergy = 0.0, varSim = 0.0; for(i = 0; i < nSamples; i++) { varRt += (runtimes[i] - runtimeAvg) * (runtimes[i] - runtimeAvg); varProfit += (profits[i] - profitAvg) * (profits[i] - profitAvg); varEnergy += (energies[i] - energyAvg) * (energies[i] - energyAvg); varSim += (simtimes[i] - simtimeAvg) * (simtimes[i] - simtimeAvg); } varRt = varRt / (nSamples - 1); varProfit = varProfit / (nSamples - 1); varEnergy = varEnergy / (nSamples - 1); varSim = varSim / (nSamples - 1); System.out.println("RT: ["+(runtimeAvg - (1.96 * Math.sqrt(varRt)))+","+(runtimeAvg + 1.96 * Math.sqrt(varRt))+"]"); System.out.println("PR: ["+(profitAvg - (1.96 * Math.sqrt(varProfit)))+","+(profitAvg + 1.96 * Math.sqrt(varProfit))+"]"); System.out.println("EC: ["+(energyAvg - (1.96 * Math.sqrt(varEnergy)))+","+(energyAvg + 1.96 * Math.sqrt(varEnergy))+"]"); System.out.println("ST: ["+(simtimeAvg - (1.96 * Math.sqrt(varSim)))+","+(simtimeAvg + 1.96 * Math.sqrt(varSim))+"]"); jscontext.close(); } private static boolean validNumber(Double num) { return Double.isFinite(num) && !Double.isNaN(num); } private static ArrayList<Tuple2<TransactionPool, MobileBlockchainInfrastructure>> generateSamples(int iterations) { ArrayList<Tuple2<TransactionPool,MobileBlockchainInfrastructure>> samples = new ArrayList<Tuple2<TransactionPool,MobileBlockchainInfrastructure>>(); TransactionPool pool = new TransactionPool(); pool.generateTransactions(); for(int i = 0; i < iterations; i++) { //ArrayList<DataEntry> globalWorkload = ddg.getGeneratedData(); //WorkloadGenerator generator = new WorkloadGenerator(); //globalWorkload = generator.setupWorkload(2, "mobile_0"); //MobileApplication app = new FacerecognizerApp(0,"mobile_0"); MobileBlockchainInfrastructure inf = new MobileBlockchainInfrastructure(); DefaultCloudPlanner.setupCloudNodes(inf, SimulationSetup.cloudNum); //RandomEdgePlanner.setupEdgeNodes(inf); EdgeAllCellPlanner.setupEdgeNodes(inf); //MobileDevicePlannerWithMobility.setupMobileDevices(inf,SimulationSetup.mobileNum); //DefaultNetworkPlanner.setupNetworkConnections(inf); Tuple2<TransactionPool,MobileBlockchainInfrastructure> singleSample = new Tuple2<TransactionPool,MobileBlockchainInfrastructure>(pool,inf); samples.add(singleSample); } return samples; } private static void processArgs(String[] args) { for(String arg: args) { if(arg.startsWith("-filename=")) { String[] pars = arg.split("="); SimulationSetup.filename = pars[1]; } if(arg.startsWith("-area=")) { String[] pars = arg.split("="); SimulationSetup.area = pars[1]; switch(pars[1]) { case "HERNALS": SimulationSetup.MAP_M = 6; SimulationSetup.MAP_N = 6; //SimulationSetup.iotDevicesNum = 36; SimulationSetup.mobileNum = 24; SimulationSetup.mobilityTraceFile = "traces/hernals.coords"; SimulationSetup.x_max = 3119; SimulationSetup.y_max = 3224; break; case "LEOPOLDSTADT": SimulationSetup.MAP_M = 10; SimulationSetup.MAP_N = 10; //SimulationSetup.iotDevicesNum = 100; SimulationSetup.mobileNum = 40; SimulationSetup.mobilityTraceFile = "traces/leopoldstadt.coords"; SimulationSetup.x_max = 11098; SimulationSetup.y_max = 9099; break; case "SIMMERING": SimulationSetup.MAP_M = 12; SimulationSetup.MAP_N = 12; SimulationSetup.iotDevicesNum = 144; SimulationSetup.mobileNum = 48; SimulationSetup.mobilityTraceFile = "traces/simmering.coords"; SimulationSetup.x_max = 6720; SimulationSetup.y_max = 5623; break; } } if(arg.startsWith("-workload=")) { String[] pars = arg.split("="); SimulationSetup.workloadType = pars[1]; } if(arg.startsWith("-iter=")) { String[] pars = arg.split("="); SimulationSetup.iterations = Integer.parseInt(pars[1]); } } } }
39.346995
182
0.715992
5a0e5bbcef0488d9bfdabff028e146390be32a80
78
/** * Ardor3D's UI extension package. */ package com.ardor3d.extension.ui;
13
34
0.692308
72f70ba98b70b42d135c7bede2bc6541b5e87b32
1,773
package com.beekeeper.model.comb.cell; import java.util.ArrayList; import com.beekeeper.model.agent.Agent; import com.beekeeper.model.agent.EmitterAgent; import com.beekeeper.model.agent.WorkingAgent; import com.beekeeper.model.comb.CombServices; public class CombCell { protected int combID = -1; public int x,y; public int number; public volatile Agent visiting = null; public volatile WorkingAgent inside = null; public CellContent content = CellContent.empty; protected ArrayList<CombCell> neighbors; private CombServices cs; public CombCell(int x, int y, int number, int combID, CombServices cs) { this.combID = combID; this.x = x; this.y = y; this.cs = cs; this.number = number; } public ArrayList<Integer> getNeighbors() { return cs.getNeighbors(x, y); } public boolean askMoveToCell(Agent who, Integer where) { return cs.askMoveToCell(who, where); } public ArrayList<WorkingAgent> getNeighborBees() { return cs.getNeighborBees(x,y); } public ArrayList<Integer> getUpCells() { return cs.getUpNeighbors(x,y); } public ArrayList<Integer> getDownCells() { return cs.getDownNeighbors(x,y); } public WorkingAgent getAgentInside() { return inside; } public int getCombID() {return combID;} /** * Frees the visiting slot of cell and notifies the Comb to remove the agent */ public void freeCell() { cs.notifyTakeOff(visiting); visiting = null; } public void notifyAgentLeft(Agent a) { cs.notifyTakeOff(a); } public void notifyLanding(EmitterAgent a) { cs.notifyLanding(a); visiting = a; } public boolean isFacingAnotherCell() { return cs.isFacingAnotherComb(); } public boolean askMoveToFacingCell(Agent who) { return cs.askMoveToFacingCell(who, number); } }
20.37931
77
0.724196
f74e5f923c2694dcde61069b7d027a2dc82e99ad
3,090
/* * Copyright 2019 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. 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.amplifyframework.datastore.syncengine; import android.annotation.SuppressLint; import androidx.annotation.NonNull; import com.amplifyframework.core.model.Model; import com.amplifyframework.datastore.appsync.ModelWithMetadata; import java.util.Objects; /** * A {@link SubscriptionEvent} notify the client of mutations that have * occurred on the backend. * @param <T> Type of data that has been mutated on the backend */ final class SubscriptionEvent<T extends Model> { private final ModelWithMetadata<T> modelWithMetadata; private final Class<T> modelClass; private final Type type; private SubscriptionEvent(ModelWithMetadata<T> modelWithMetadata, Class<T> modelClass, Type type) { this.modelWithMetadata = modelWithMetadata; this.modelClass = modelClass; this.type = type; } @NonNull ModelWithMetadata<T> modelWithMetadata() { return modelWithMetadata; } @SuppressWarnings("unused") @NonNull Class<T> modelClass() { return modelClass; } @SuppressWarnings("unused") @NonNull Type type() { return type; } @NonNull static <T extends Model> Builder<T> builder() { return new Builder<>(); } static final class Builder<T extends Model> { private ModelWithMetadata<T> modelWithMetadata; private Class<T> modelClass; private Type type; @NonNull Builder<T> modelWithMetadata(@NonNull ModelWithMetadata<T> modelWithMetadata) { this.modelWithMetadata = Objects.requireNonNull(modelWithMetadata); return this; } @NonNull Builder<T> modelClass(@NonNull Class<T> modelClass) { this.modelClass = Objects.requireNonNull(modelClass); return this; } @NonNull Builder<T> type(@NonNull Type type) { this.type = Objects.requireNonNull(type); return this; } @SuppressLint("SyntheticAccessor") @NonNull SubscriptionEvent<T> build() { return new SubscriptionEvent<>(modelWithMetadata, modelClass, type); } } /** * An enumeration of the different type of mutations that may be observed. */ public enum Type { /** * An item is created. */ CREATE, /** * An item is updated. */ UPDATE, /** * An item is deleted. */ DELETE } }
27.105263
103
0.643689
2fd45feaa7271f34a66fa45ee5715a064aee74d0
4,493
package io.keyko.monitoring.agent.core.chain.service.strategy; import io.keyko.monitoring.agent.core.chain.block.BlockListener; import io.keyko.monitoring.agent.core.chain.service.domain.Block; import io.keyko.monitoring.agent.core.model.LatestBlock; import io.keyko.monitoring.agent.core.service.AsyncTaskService; import io.keyko.monitoring.agent.core.service.EventStoreService; import io.keyko.monitoring.agent.core.utils.ExecutorNameFactory; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.UndeliverableException; import io.reactivex.plugins.RxJavaPlugins; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.web3j.protocol.Web3j; import java.io.IOException; import java.net.SocketException; import java.util.Collection; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedQueue; @Slf4j public abstract class AbstractBlockSubscriptionStrategy<T> implements BlockSubscriptionStrategy { private final Logger LOG = LoggerFactory.getLogger(AbstractBlockSubscriptionStrategy.class); protected static final String BLOCK_EXECUTOR_NAME = "BLOCK"; protected Collection<BlockListener> blockListeners = new ConcurrentLinkedQueue<>(); protected Disposable blockSubscription; protected Web3j web3j; protected EventStoreService eventStoreService; protected String nodeName; protected AsyncTaskService asyncService; public AbstractBlockSubscriptionStrategy(Web3j web3j, String nodeName, EventStoreService eventStoreService, AsyncTaskService asyncService) { this.web3j = web3j; this.nodeName = nodeName; this.eventStoreService = eventStoreService; this.asyncService = asyncService; RxJavaPlugins.setErrorHandler(e -> { if (e instanceof UndeliverableException) { e = e.getCause(); } if ((e instanceof IOException) || (e instanceof SocketException)) { // fine, irrelevant network problem or API that throws on cancellation return; } if (e instanceof InterruptedException) { // fine, some blocking code was interrupted by a dispose call return; } if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { // that's likely a bug in the application LOG.error("Error application"); return; } if (e instanceof IllegalStateException) { LOG.error("Error in RxJava or in a custom operator"); return; } LOG.warn("Undeliverable exception received, not sure what to do", e); }); } @Override public void unsubscribe() { try { if (blockSubscription != null) { blockSubscription.dispose(); } } catch (UndeliverableException ex) { } finally { blockSubscription = null; } } @Override public void addBlockListener(BlockListener blockListener) { blockListeners.add(blockListener); } @Override public void removeBlockListener(BlockListener blockListener) { blockListeners.remove(blockListener); } public boolean isSubscribed() { return blockSubscription != null && !blockSubscription.isDisposed(); } protected void triggerListeners(T blockObject) { final Block eventeumBlock = convertToEventeumBlock(blockObject); triggerListeners(eventeumBlock); } protected void triggerListeners(Block eventeumBlock) { asyncService.execute(ExecutorNameFactory.build(BLOCK_EXECUTOR_NAME, eventeumBlock.getNodeName()), () -> { blockListeners.forEach(listener -> triggerListener(listener, eventeumBlock)); }); } protected void triggerListener(BlockListener listener, Block block) { try { listener.onBlock(block); } catch(Throwable t) { log.error(String.format("An error occured when processing block with hash %s", block.getHash()), t); } } protected Optional<LatestBlock> getLatestBlock() { return eventStoreService.getLatestBlock(nodeName); } abstract Block convertToEventeumBlock(T blockObject); }
36.827869
113
0.66548
df7ee8384dc032b7f4f6e71d7b86caa355363e00
2,373
package com.trett.rss.models; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Type; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import java.time.LocalDateTime; import java.util.Objects; /** * RSS channel item */ @Entity public class FeedItem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotEmpty private String guid; private String title; @NotEmpty private String link; @JsonFormat(pattern = "yyyy-MM-dd HH:mm") private LocalDateTime pubDate; @Lob @Type(type = "org.hibernate.type.TextType") private String description; @ManyToOne(fetch = FetchType.LAZY) @JsonIgnore private Channel channel; private boolean read; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public LocalDateTime getPubDate() { return pubDate; } public void setPubDate(LocalDateTime pubDate) { this.pubDate = pubDate; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Channel getChannel() { return channel; } public void setChannel(Channel channel) { this.channel = channel; } public boolean isRead() { return read; } public void setRead(boolean read) { this.read = read; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FeedItem feedItem = (FeedItem) o; return Objects.equals(getGuid(), feedItem.getGuid()); } @Override public int hashCode() { return Objects.hash(getGuid()); } }
18.833333
61
0.606827
8d6fab40bc00e67f0b78f6eb76223fa4b3211e5c
11,107
package signpost; import ucb.gui2.Pad; import java.util.concurrent.ArrayBlockingQueue; import java.awt.Font; import java.awt.Color; import java.awt.Graphics2D; import java.awt.BasicStroke; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import static java.awt.RenderingHints.*; import static signpost.Place.pl; import signpost.Model.Sq; /** A widget that displays a Signpost puzzle. * @author Xinyu Fu */ class BoardWidget extends Pad { /* Parameters controlling sizes, speeds, colors, and fonts. */ /** Pause in milliseconds before each turn of arrows to signal solved * puzzle. */ static final long ARROW_BUMP_INTERVAL = 120; /** Colors of squares, arrows, and grid lines. */ static final Color BACKGROUND_COLOR = new Color(220, 220, 220), GRID_LINE_COLOR = Color.black, ARROW_COLOR = Color.black, NUMBERED_SQUARE_COLOR = Color.white, CONNECTED_COLOR = new Color(180, 180, 180), NUM_COLOR = Color.black, FIXED_NUM_COLOR = Color.blue; /** Basic cell background RGB color values (from Simon Tatham). */ static final int[] BG_BASE_RGB = { 0xffffff, 0xffa07a, 0x98fb98, 0x7fffd4, 0x9370db, 0xffa500, 0x87cefa, 0xffff00, }; /** Background colors used by runs of unnumbered squares. */ static final Color[] BG_COLORS = new Color[BG_BASE_RGB.length * 3]; static { int p = BG_BASE_RGB.length; for (int i = 0; i < BG_COLORS.length; i += 1) { if (i < p) { BG_COLORS[i] = new Color(BG_BASE_RGB[i]); } else { BG_COLORS[i] = new Color((BG_COLORS[i - p].getRGB() + BG_COLORS[i - p + 1].getRGB()) / 2); } } } /** Bar width separating squares and other dimensions (pixels). */ static final int CELL_SIDE = 50, GRID_LINE_WIDTH = 1, PADDING = CELL_SIDE / 2, TEXT_OFFSET = 4, OFFSET = 2, DOT_SIZE = 7; /** Separation between cell centers and half separation between cell * centers. */ static final int CELL_SEP = CELL_SIDE + GRID_LINE_WIDTH, HALF_SEP = CELL_SEP / 2; /** Strokes for ordinary grid lines and those that are parts of * boundaries. */ static final BasicStroke GRIDLINE_STROKE = new BasicStroke(GRID_LINE_WIDTH); /** Font for square numbers. */ static final Font NUM_FONT = new Font("Dejavu Serif", Font.BOLD, 18); /** Font for square group-sequence numbers (e.g., "a+1"). */ static final Font GROUP_TEXT_FONT = new Font("Dejavu Serif", Font.BOLD, 12); /** Font for dots. */ static final Font DOT_FONT = new Font("SansSerif", Font.BOLD, 36); /** Arrow vertex coordinates: x in first row, y in second. */ static final int [][] ARROW = { { 0, 7, 7, 14, 14, 21, 10, }, { 10, 10, 0, 0, 10, 10, 21, } }; /** Star vertex coordinates. */ static final int[][] STAR = { { 22, 15, 18, 11, 4, 7, 0, 8, 11, 14 }, { 8, 13, 21, 16, 21, 13, 8, 8, 0, 8 } }; /** Amount of rotation between arrow positions. */ static final double PI_4 = 0.25 * Math.PI; /** A graphical representation of a Signpost board that sends commands * derived from mouse clicks to COMMANDS. */ BoardWidget(ArrayBlockingQueue<String> commands) { _commands = commands; setMouseHandler("press", this::mousePressed); setMouseHandler("release", this::mouseReleased); } /** Set the size of the board to WIDTH x HEIGHT. */ public void setSize(int width, int height) { synchronized (me) { _width = width; _height = height; _boardWidth = width * CELL_SEP + 3 * GRID_LINE_WIDTH; _boardHeight = height * CELL_SEP + 3 * GRID_LINE_WIDTH; setPreferredSize(_boardWidth, _boardHeight); } repaint(); } /** Draw the grid lines on G. */ private void drawGrid(Graphics2D g) { g.setColor(GRID_LINE_COLOR); g.setStroke(GRIDLINE_STROKE); for (int k = 0; k <= _width; k += 1) { g.drawLine(cx(k), cy(0), cx(k), cy(_height)); } for (int k = 0; k <= _height; k += 1) { g.drawLine(cx(0), cy(k), cx(_width), cy(k)); } } /** Return the appropriate color for arrow in SQ. */ private Color arrowColor(Sq sq) { return sq.successor() == null ? ARROW_COLOR : CONNECTED_COLOR; } /** Return the appropriate color for numeral in SQ. */ private Color numberColor(Sq sq) { return sq.hasFixedNum() ? FIXED_NUM_COLOR : sq.successor() == null || sq.predecessor() == null ? NUM_COLOR : CONNECTED_COLOR; } /** Draw star in SQ on G. */ private void drawStar(Graphics2D g, Sq sq) { g.setColor(arrowColor(sq)); int px = cx(sq.x), py = cy(sq.y); int[] x = new int[STAR[0].length], y = new int[STAR[0].length]; for (int i = 0; i < x.length; i += 1) { x[i] = px + STAR[0][i] + CELL_SIDE / 2 + 2; y[i] = py + STAR[1][i] - CELL_SIDE / 2 - 2; } g.fillPolygon(x, y, x.length); } /** Draw arrow in SQ on G. */ private void drawArrow(Graphics2D g, Sq sq) { if (sq.direction() == 0) { drawStar(g, sq); return; } g.setColor(arrowColor(sq)); int px = cx(sq.x), py = cy(sq.y); int[] x = new int[ARROW[0].length], y = new int[ARROW[0].length]; for (int i = 0; i < x.length; i += 1) { x[i] = px + CELL_SIDE / 2 + 2 + ARROW[0][i]; y[i] = py - CELL_SIDE / 2 + 2 + ARROW[1][i]; } AffineTransform init = g.getTransform(); int dir = (sq.direction() + _dirBump - 1) % 8 + 1; g.rotate((dir - 4) * PI_4, px + 3 * CELL_SIDE / 4, py - CELL_SIDE / 4); g.fillPolygon(x, y, x.length); g.setTransform(init); } /** Draw SQ on G. */ private void drawSquare(Graphics2D g, Sq sq) { int px = cx(sq.x), py = cy(sq.y); if (sq.group() >= 0) { g.setColor(groupColor(sq.group())); g.fillRect(px + GRID_LINE_WIDTH, py + GRID_LINE_WIDTH - CELL_SIDE, CELL_SIDE - GRID_LINE_WIDTH, CELL_SIDE - GRID_LINE_WIDTH); } drawArrow(g, sq); if (sq.predecessor() == null && sq.sequenceNum() != 1) { g.setColor(ARROW_COLOR); g.fillOval(px + 3 * TEXT_OFFSET, py - 4 * TEXT_OFFSET, DOT_SIZE, DOT_SIZE); } if (sq.sequenceNum() != 0) { g.setColor(numberColor(sq)); g.setFont(NUM_FONT); } else if (sq.group() > 0) { g.setColor(NUM_COLOR); g.setFont(GROUP_TEXT_FONT); } else { return; } g.drawString(sq.seqText(), px + TEXT_OFFSET, py - CELL_SIDE / 2 - 2 * TEXT_OFFSET); } /** Give a visual signal that the puzzle is solved. */ private void signalSolved() { while (true) { try { Thread.sleep(ARROW_BUMP_INTERVAL); } catch (InterruptedException excp) { /* Ignore InterruptedException. */ } synchronized (this) { _dirBump = (_dirBump + 1) % 8; repaint(); if (_dirBump == 0) { break; } } } } @Override public synchronized void paintComponent(Graphics2D g) { g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); g.setColor(BACKGROUND_COLOR); g.fillRect(0, 0, _boardWidth, _boardHeight); drawGrid(g); int n = 2; for (Sq sq : _model) { drawSquare(g, sq); } } /** Handle mouse pressed event E, recording the starting square of a * connection, if appropriate. */ private synchronized void mousePressed(String unused, MouseEvent e) { int x = x(e), y = y(e); if (e.getButton() != MouseEvent.BUTTON1) { return; } if (_model.isCell(x, y)) { _connStart = pl(x, y); } else { _connStart = null; } } /** Handle mouse released event E, reporting a connection, * if appropriate. */ private synchronized void mouseReleased(String unused, MouseEvent e) { int x = x(e), y = y(e); if (e.getButton() != MouseEvent.BUTTON1) { return; } Place endPlace; if (_connStart != null) { if (_model.isCell(x, y)) { Sq sq0 = _model.get(_connStart), sq1 = _model.get(x, y); _commands.offer(String.format("CONN %d %d %d %d", sq0.x, sq0.y, x, y)); } else { _commands.offer(String.format("BRK %d %d", _connStart.x, _connStart.y)); } } _connStart = null; } /** Return the column index of the square on which EVENT occurred. */ private int x(MouseEvent event) { return (int) Math.floorDiv(event.getX() - OFFSET, CELL_SEP); } /** Return the row index of the square on which EVENT occurred. */ private int y(MouseEvent event) { return _height - 1 - (int) Math.floorDiv(event.getY() - OFFSET, CELL_SEP); } /** Return the color associated with group N. */ private Color groupColor(int n) { if (n == 0) { return NUMBERED_SQUARE_COLOR; } else { return BG_COLORS[(n - 1) % (BG_COLORS.length - 1) + 1]; } } /** Revise the displayed board according to MODEL. */ void update(Model model) { synchronized (this) { _model = new Model(model); _dirBump = 0; } repaint(); if (_model.solved()) { signalSolved(); } } /** Return pixel coordinates of vertical board coordinate Y relative * to window. */ private int cy(int y) { return OFFSET + (_height - y) * CELL_SEP; } /** Return pixel coordinates of horizontal board coordinate X relative * to window. */ private int cx(int x) { return OFFSET + x * CELL_SEP; } /** Number of height and of columns. */ private int _height, _width; /** Queue on which to post commands (from mouse clicks). */ private ArrayBlockingQueue<String> _commands; /** Current model being displayed. */ private Model _model; /** Length (in pixels) of the side of the board. */ private int _boardWidth, _boardHeight; /** Place where mouse action started. */ private Place _connStart; /** Amount to add to direction value for each displayed arrow (used for * special effect signaling completion. */ private int _dirBump; }
32.381924
80
0.544792
9e403475527fbf89b63a9d0f5be92806cd676ef0
1,821
/* * This file is subject to the terms and conditions outlined in the file 'LICENSE' (hint: it's MIT); this file is located in the root directory near the README.md which you should also read. * * This file is part of the 'Adama' project which is a programming language and document store for board games; however, it can be so much more. * * See http://www.adama-lang.org/ for more information. * * (c) 2020 - 2022 by Jeffrey M. Barber (http://jeffrey.io) */ package org.adamalang.translator.tree.expressions; import org.adamalang.translator.env.Environment; import org.adamalang.translator.parser.token.Token; import org.adamalang.translator.tree.common.DocumentPosition; import org.adamalang.translator.tree.common.StringBuilderWithTabs; import org.adamalang.translator.tree.types.TyType; import java.util.function.Consumer; public abstract class Expression extends DocumentPosition { protected TyType cachedType = null; public abstract void emit(Consumer<Token> yielder); public TyType getCachedType() { return cachedType; } public boolean passedTypeChecking() { return cachedType != null; } public TyType typing(final Environment environment, final TyType suggestion) { if (cachedType == null) { cachedType = typingInternal(environment, suggestion); } return cachedType; } protected abstract TyType typingInternal(Environment environment, TyType suggestion); public Expression withPosition(final DocumentPosition position) { ingest(position); return this; } public void writeJava(final StringBuilderWithTabs sb, final Environment environment) { final var child = new StringBuilder(); writeJava(child, environment); sb.append(child.toString()); } public abstract void writeJava(StringBuilder sb, Environment environment); }
33.109091
190
0.756727
12a4b286067324ebfd3b3697c72f404cabb76393
1,444
package at.adridi.finanzverwaltung.db; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; /** * Hibernate Utility Klasse um Session-Factory-Objekt abzurufen * */ public class HibernateUtil { private static final SessionFactory SESSION_FACTORY; private static final ServiceRegistry SERVER_REGISTRY; static { try { // Konfiguration und Mapping laden Configuration configuration = new Configuration().configure(); SERVER_REGISTRY = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); //Session Factory von der Service Registry erstellen SESSION_FACTORY = configuration.buildSessionFactory(SERVER_REGISTRY); } catch (HibernateException ex) { // Exception loggen System.err.println("creation of Initial Session Factory failed: " + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return SESSION_FACTORY; } public static void close() { if (SERVER_REGISTRY != null) { StandardServiceRegistryBuilder.destroy(SERVER_REGISTRY); } } }
32.088889
84
0.680748
89c8f6f598e4ba3fa5ee56ff5746877b4bfd5ec5
4,212
package com.swifty.fillcolor.controller.main; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.swifty.fillcolor.MyApplication; import com.swifty.fillcolor.R; import com.swifty.fillcolor.model.AsynImageLoader; import com.swifty.fillcolor.model.OnRecycleViewItemClickListener; import com.swifty.fillcolor.model.bean.ThemeBean; import java.util.List; /** * Created by Swifty.Wang on 2015/8/14. */ public class ThemeListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { Context context; FrameLayout footer; List<ThemeBean.Theme> themelist; private final int TYPE_ITEM = 1; private final int TYPE_FOOTER = 2; public void setOnRecycleViewItemClickListener(OnRecycleViewItemClickListener onRecycleViewItemClickListener) { this.onRecycleViewItemClickListener = onRecycleViewItemClickListener; } private OnRecycleViewItemClickListener onRecycleViewItemClickListener; public ThemeListAdapter(Context context, List<ThemeBean.Theme> themelist, View footer) { this.context = context; this.themelist = themelist; this.footer = (FrameLayout) footer.getParent(); } @Override public int getItemViewType(int position) { if (position == themelist.size()) { return TYPE_FOOTER; } return TYPE_ITEM; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = null; if (viewType == TYPE_ITEM) { v = LayoutInflater.from(context) .inflate(R.layout.view_list_item, parent, false); return new VHItem(v); } else if (viewType == TYPE_FOOTER) { return new VHFooter(footer); } return null; } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) { if (holder instanceof VHItem) { if (themelist.get(position) != null) { ((VHItem) holder).name.setText(themelist.get(position).getN()); if (themelist.get(position).getC() == -1) { ((VHItem) holder).image.setImageResource(R.mipmap.secretgraden); } else { AsynImageLoader.showImageAsyn(((VHItem) holder).image, String.format(MyApplication.ThemeThumbUrl, themelist.get(position).getC())); } ((VHItem) holder).parent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onRecycleViewItemClickListener != null) onRecycleViewItemClickListener.recycleViewItemClickListener(((VHItem) holder).parent, position); } }); } } else if (holder instanceof VHFooter) { ((VHFooter) holder).footer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } } @Override public int getItemCount() { return themelist.size() + 1; } public List<ThemeBean.Theme> getList() { return themelist; } class VHFooter extends RecyclerView.ViewHolder { FrameLayout footer; public VHFooter(View itemView) { super(itemView); footer = (FrameLayout) itemView; } } static class VHItem extends RecyclerView.ViewHolder { public ImageView image; public TextView name; public View parent; public VHItem(View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.image); name = (TextView) itemView.findViewById(R.id.name); parent = itemView; } } public void updateListView(List<ThemeBean.Theme> list) { this.themelist = list; notifyDataSetChanged(); } }
32.90625
160
0.650047
04b93924038dc29cf48cb14bbe0e7a59606941a7
4,147
package uk.gov.hmcts.reform.divorce.service; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.divorce.mapper.DocumentCollectionDocumentRequestMapper; import uk.gov.hmcts.reform.divorce.model.ccd.CollectionMember; import uk.gov.hmcts.reform.divorce.model.ccd.Document; import uk.gov.hmcts.reform.divorce.model.documentupdate.GeneratedDocumentInfo; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; @Service @RequiredArgsConstructor public class CoreCaseDataDocumentService { private static final String PETITION = "petition"; private static final String D8_DOCUMENTS_GENERATED_CCD_FIELD = "D8DocumentsGenerated"; private static final String GENERIC_DOCUMENT_TYPE = "other"; private final ObjectMapper objectMapper; private final DocumentCollectionDocumentRequestMapper documentCollectionDocumentRequestMapper; public Map<String, Object> removeAllPetitionDocuments(final Map<String, Object> coreCaseData) { return removeAllDocumentsByType(coreCaseData, PETITION); } public Map<String, Object> addDocuments(final Map<String, Object> coreCaseData, final List<GeneratedDocumentInfo> generatedDocumentInfos) { if (coreCaseData == null) { throw new IllegalArgumentException("Existing case data must not be null."); } if (isNotEmpty(generatedDocumentInfos)) { final List<CollectionMember<Document>> resultDocuments = new ArrayList<>(); final List<CollectionMember<Document>> newDocuments = generatedDocumentInfos.stream() .map(documentCollectionDocumentRequestMapper::map) .collect(Collectors.toList()); final Set<String> newDocumentsTypes = generatedDocumentInfos.stream() .map(GeneratedDocumentInfo::getDocumentType) .collect(Collectors.toSet()); final List<CollectionMember<Document>> documentsGenerated = objectMapper.convertValue(coreCaseData.get(D8_DOCUMENTS_GENERATED_CCD_FIELD), new TypeReference<>() { }); if (isNotEmpty(documentsGenerated)) { final List<CollectionMember<Document>> existingDocuments = documentsGenerated.stream() .filter(documentCollectionMember -> GENERIC_DOCUMENT_TYPE.equals(documentCollectionMember.getValue().getDocumentType()) || !newDocumentsTypes.contains(documentCollectionMember.getValue().getDocumentType()) ) .collect(Collectors.toList()); resultDocuments.addAll(existingDocuments); } resultDocuments.addAll(newDocuments); coreCaseData.put(D8_DOCUMENTS_GENERATED_CCD_FIELD, resultDocuments); } return coreCaseData; } public Map<String, Object> removeAllDocumentsByType(final Map<String, Object> coreCaseData, final String documentType) { if (coreCaseData == null) { throw new IllegalArgumentException("Existing case data must not be null."); } final List<CollectionMember<Document>> allDocuments = objectMapper.convertValue(coreCaseData.get(D8_DOCUMENTS_GENERATED_CCD_FIELD), new TypeReference<>() { }); if (isNotEmpty(allDocuments)) { allDocuments.removeIf(documents -> isDocumentType(documents, documentType)); coreCaseData.replace(D8_DOCUMENTS_GENERATED_CCD_FIELD, allDocuments); } return coreCaseData; } private boolean isDocumentType(final CollectionMember<Document> document, final String documentType) { return document.getValue().getDocumentType().equalsIgnoreCase(documentType); } }
41.47
124
0.694478
412953ad9f2ec974ba89e36e5e39dc47e21f5fac
673
package de.hasi.bandbash.commands; import java.util.Collection; import java.util.Map; public interface Queries { Collection<Map<String, String>> getAreaIntro(); Collection<Map<String, String>> describeArea(); Collection<Map<String, String>> getPaths(); Collection<Map<String, String>> goTo(String target); Collection<Map<String, String>> inventory(); Collection<Map<String, String>> describeItem(String itemname); Collection<Map<String, String>> take(String item); Collection<Map<String, String>> getTime(); Collection<Map<String, String>> setTime(String time); Collection<Map<String,String>> describePerson(String s); }
24.925926
66
0.719168
c09bc1a3f0c99e26ccc8816e734db47af6ffb89d
7,144
package com.fumbbl.iconcomposer.image; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.stream.Collectors; import com.fumbbl.iconcomposer.ColourTheme; import com.fumbbl.iconcomposer.controllers.Controller; import com.fumbbl.iconcomposer.model.Model; import com.fumbbl.iconcomposer.model.types.*; import com.kitfox.svg.SVGDiagram; import com.kitfox.svg.SVGException; import javafx.geometry.Point2D; public class BaseRenderer { protected int width = 480; protected int height = 480; private Model model; protected Controller controller; protected double imageScale; protected Color renderBackground = new Color(148,158,148); private Color gridColor = new Color(160,89,179); private SvgRenderer svgRenderer; private ImageRenderer imageRenderer; public BaseRenderer(Model model, Controller controller) { this.model = model; this.controller = controller; svgRenderer = new SvgRenderer(this); imageRenderer = new ImageRenderer(this); } public double getImageScale() { return imageScale; } public void renderSkin(Skin skin) { if (skin == null || skin.skeleton == null) { return; } Graphics2D g2 = controller.viewState.getGraphics2D(); g2.setColor(renderBackground); g2.fillRect(0, 0, width, height); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); try { skin.skeleton.updateTransforms(); drawIcon(g2, skin, 0, 0, 480); } catch (SVGException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void renderDiagram(Diagram diagram) { Graphics2D g2 = controller.viewState.getGraphics2D(); g2.setColor(renderBackground); g2.fillRect(0, 0, width, height); g2.setColor(gridColor); g2.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1f, new float[] {5,3}, 0f)); g2.drawLine(this.width / 2, 0, this.width / 2, this.height); g2.drawLine(0, this.height / 2, this.width, this.height / 2); g2.drawLine(this.width / 2 - 1, 0, this.width / 2 - 1, this.height); g2.drawLine(0, this.height / 2 - 1, this.width, this.height / 2 - 1); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.translate(-diagram.width/2, -diagram.height/2); applyPixelTransform(diagram, g2); try { diagram.resetColour(controller.getSvg(diagram.getImage().getName())); controller.onColourThemeChanged(diagram.getTheme()); renderDiagram(g2, diagram); } catch (SVGException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void applyPixelTransform(Diagram diagram, Graphics2D g2) { g2.scale(8.0, 8.0); double xFix = diagram.width % 2 == 0 ? 0.0 : 0.5; double yFix = diagram.height % 2 == 0 ? 0.0 : 0.5; g2.translate(30- diagram.width/2 - xFix,30- diagram.height/2 - yFix); } public void renderSkeleton(Skeleton skeleton, String currentBone) { Graphics2D g2 = controller.viewState.getGraphics2D(); g2.setColor(renderBackground); g2.fillRect(0, 0, width, height); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (skeleton == null) { return; } double scale = 8; if (skeleton.width != 0) { scale = 8; } skeleton.updateTransforms(); for (Bone b : skeleton.getBones()) { int cx = (int) (this.width/2 + scale*b.worldX/2); int cy = (int) (this.height/2 - scale*b.worldY/2); if (b.parentBone != null) { Bone parent = b.parentBone; int px = (int) (this.width/2 + scale*parent.worldX/2); int py = (int) (this.height/2 - scale*parent.worldY/2); g2.setColor(gridColor); g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1f, new float[] {1, 4}, 0)); g2.drawLine(px, py, cx, cy); } g2.setColor(Color.gray); g2.setStroke(new BasicStroke(2)); g2.drawLine(cx-10, cy, cx+10, cy); g2.drawLine(cx, cy-10, cx, cy+10); g2.setStroke(new BasicStroke(1)); g2.setColor(Color.white); g2.fillOval(cx-3, cy-3, 6, 6); g2.setColor(Color.black); g2.drawOval(cx-3, cy-3, 6, 6); if (b.name.equals(currentBone)) { g2.drawString(b.name, cx+4, cy-2); } } } public void renderCursor(double x, double y) { Graphics2D g2 = controller.viewState.getGraphics2D(); g2.setColor(Color.blue); int cx = (int) (240.0 - x*imageScale); int cy = (int) (240.0 + y*imageScale); g2.setColor(Color.black); g2.setStroke(new BasicStroke(3)); g2.drawLine(cx-8, cy-8, cx+8, cy+8); g2.drawLine(cx+8, cy-8, cx-8, cy+8); g2.setColor(Color.pink); g2.setStroke(new BasicStroke(1)); g2.drawLine(cx-8, cy-8, cx+8, cy+8); g2.drawLine(cx+8, cy-8, cx-8, cy+8); g2.drawLine(cx-9, cy-8, cx+7, cy+8); g2.drawLine(cx+7, cy-8, cx-9, cy+8); g2.drawLine(cx-8, cy-9, cx+8, cy+7); g2.drawLine(cx+8, cy-9, cx-8, cy+7); g2.drawLine(cx-9, cy-9, cx+7, cy+7); g2.drawLine(cx+7, cy-9, cx-9, cy+7); } public Point2D getImageOffset(double x, double y) { double oX = Math.round(-(x - 240) / imageScale); double oY = Math.round((y - 240) / imageScale); return new Point2D(oX, oY); } private void drawIcon(Graphics2D g2, Skin skin, double x, double y, double size) throws SVGException { AffineTransform originalTransform = g2.getTransform(); AffineTransform at = g2.getTransform(); ColourTheme theme = controller.getColourTheme(); for (Slot slot : model.getSlots().stream().sorted(Slot.ReverseComparator).collect(Collectors.toList())) { Diagram diagram = skin.getDiagram(slot); if (diagram != null) { diagram.setColour(controller.getSvg(diagram.getImage().getName()), theme); g2.translate(x, y); renderDiagram(g2, diagram, skin.skeleton, slot, size); } g2.setTransform(at); } g2.setTransform(originalTransform); } private void renderDiagram(Graphics2D g2, Diagram diagram, Skeleton skeleton, Slot slot, double size) throws SVGException { if (diagram != null) { AffineTransform at = g2.getTransform(); skeleton.getTransform(slot.getBone().name, diagram); applyPixelTransform(diagram, g2); g2.translate(-diagram.worldX, -diagram.worldY); renderDiagram(g2, diagram); g2.setTransform(at); } } private void renderDiagram(Graphics2D g2, Diagram diagram) throws SVGException { NamedImage image = diagram.getImage(); if (image instanceof NamedSVG) { svgRenderer.renderSvg(((NamedSVG) image).diagram); } else if (image instanceof NamedPng) { imageRenderer.renderImage(g2, ((NamedPng)image).image); } } public void render(NamedItem image) { if (image instanceof NamedSVG) { svgRenderer.renderSvg(((NamedSVG)image).diagram); } else if (image instanceof NamedPng) { imageRenderer.renderImage(((NamedPng)image).image); } } }
30.926407
124
0.703947
aeb4818eb454e88f738e8b4e3aea31576278f350
4,782
package com.secuconnect.demo.payment.payout; import com.secuconnect.client.Environment; import com.secuconnect.demo.Globals; import com.secuconnect.client.ApiException; import com.secuconnect.client.api.PaymentSecupayPayoutApi; import com.secuconnect.client.model.*; import java.util.ArrayList; public class createPayoutPayment { public static void main(String[] args) { try { // init env Environment.getGlobalEnv().setCredentials(Globals.O_AUTH_CLIENT_CREDENTIALS); // init request SecupayPayoutDTO transaction = new SecupayPayoutDTO(); transaction.setCurrency("EUR"); transaction.setContract("PCR_M32SCZ98Q2N3U4GW70ZAVWWE47XPAH"); transaction.setRedirectUrl(new SecupayRedirectUrl()); transaction.getRedirectUrl().setUrlPush("https://api.example.com/secuconnect/push"); transaction.setPurpose("Payout Test #1"); transaction.setOrderId("201900123"); // See src/payment/createCustomer.java if you want to know how you can create a payment customer id transaction.setCustomer(new PaymentCustomersProductModel()); transaction.getCustomer().setId("PCU_3BBSV6C702NCA4HR70ZAVCAX3R6CAW"); SecupayTransactionListItem listItem1 = new SecupayTransactionListItem(); listItem1.setReferenceId("2000.1"); listItem1.setName("Payout Purpose 1"); listItem1.setTransactionHash("andbeqalxuik3414051"); listItem1.setTotal(100); // in euro-cent SecupayTransactionListItem listItem2 = new SecupayTransactionListItem(); listItem2.setReferenceId("2000.2"); listItem2.setName("Payout Purpose 2"); listItem2.setContainerId("PCT_3RW7JJ3JC2NCA5RRN0ZAVDYF4DUKA2"); listItem2.setTotal(200); // in euro-cent SecupayTransactionListItem listItem3 = new SecupayTransactionListItem(); listItem3.setReferenceId("2000.3"); listItem3.setName("Payout Purpose 3"); listItem3.setTransactionId("PCI_WQH6C6CM2KQHBCJ5YVCX5D49P4P0NG"); listItem3.setTotal(50); // in euro-cent transaction.setTransactionList(new ArrayList<SecupayTransactionListItem>(3)); transaction.getTransactionList().add(listItem1); transaction.getTransactionList().add(listItem2); transaction.getTransactionList().add(listItem3); // calculate the amount Integer amount = 0; for (SecupayTransactionListItem item : transaction.getTransactionList()) { amount += item.getTotal(); } transaction.setAmount(amount); // in euro-cent PaymentSecupayPayoutApi apiInstance = new PaymentSecupayPayoutApi(); SecupayPayoutProductModel response = apiInstance.paymentSecupaypayoutPost(transaction); System.out.print(response); /* * Sample output: * ============== * class SecupayPayoutProductModel { * object: payment.secupaypayout * id: aoaomyekdbjf3479559 * transId: 14252853 * status: authorized * amount: 350 * currency: EUR * purpose: Payout Test #1 * orderId: 201900123 * transactionStatus: 25 * transactionList: [class SecupayTransactionListItem { * itemType: transaction_payout * referenceId: 2000.1 * name: Payout Purpose 1 * transactionHash: andbeqalxuik3414051 * total: 100 * }, class SecupayTransactionListItem { * itemType: transaction_payout * referenceId: 2000.2 * name: Payout Purpose 2 * containerId: PCT_3RW7JJ3JC2NCA5RRN0ZAVDYF4DUKA2 * total: 200 * }, class SecupayTransactionListItem { * itemType: transaction_payout * referenceId: 2000.3 * name: Payout Purpose 3 * transactionId: PCI_WQH6C6CM2KQHBCJ5YVCX5D49P4P0NG * total: 50 * }] * transferPurpose: TA 14252853 * transferAccount: class PaymentInformation { * iban: DE88300500000001747013 * bic: WELADEDDXXX * } * } */ } catch (ApiException e) { e.printStackTrace(); System.out.println("ERROR: " + e.getResponseBody()); } } }
42.318584
111
0.589084
033e0ddda084e9c441d7b235d7d4510fc22f0294
2,291
package com.structurizr.componentfinder; import com.structurizr.Workspace; import com.structurizr.model.Component; import com.structurizr.model.Container; import com.structurizr.model.Model; import com.structurizr.model.SoftwareSystem; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class TypeBasedComponentFinderStrategyTests { private Container webApplication; @Before public void setUp() { Workspace workspace = new Workspace("Name", "Description"); Model model = workspace.getModel(); SoftwareSystem softwareSystem = model.addSoftwareSystem("Name", "Description"); webApplication = softwareSystem.addContainer("Name", "Description", "Technology"); } @Test public void test_findComponents() throws Exception { ComponentFinder componentFinder = new ComponentFinder( webApplication, "com.structurizr.componentfinder.myapp", new TypeBasedComponentFinderStrategy( new NameSuffixTypeMatcher("Controller", "", "An MVC controller"), new NameSuffixTypeMatcher("Repository", "", "A data access object") ) ); componentFinder.findComponents(); assertEquals(2, webApplication.getComponents().size()); Component myController = webApplication.getComponentWithName("MyController"); assertNotNull(myController); assertEquals("MyController", myController.getName()); assertEquals("com.structurizr.componentfinder.myapp.MyController", myController.getType()); assertEquals("", myController.getDescription()); Component myRepository = webApplication.getComponentWithName("MyRepository"); assertNotNull(myRepository); assertEquals("MyRepository", myRepository.getName()); assertEquals("com.structurizr.componentfinder.myapp.MyRepository", myRepository.getType()); assertEquals("", myRepository.getDescription()); assertEquals(1, myController.getRelationships().size()); assertNotNull(myController.getRelationships().stream().filter(r -> r.getDestination() == myRepository).findFirst().get()); } }
39.5
130
0.701877
8be5d122c1903cb5f5e2e132456455a135123cd2
2,098
package org.simpleframework.demo.jmx; import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import javax.management.ObjectName; import org.springframework.jmx.export.annotation.ManagedResource; import com.sun.jdmk.comm.AuthInfo; import com.sun.jdmk.comm.CommunicatorServer; import com.sun.jdmk.comm.HtmlAdaptorServer; /** * This provides a means of management for the host service via a web * browser. All controls exposed are JMX attributes or operations which * allows various components to be manipulated for management. * * @author Niall Gallagher */ @ManagedResource(description="Web administration tool") public class WebAdministrator { private final WebConfiguration config; private final WebPageParser parser; public WebAdministrator(WebConfiguration config) { this(config, null); } public WebAdministrator(WebConfiguration config, WebObjectIntrospector introspector) { this.parser = new WebPageParser(config, introspector); this.config = config; } public void start() { try { int port = config.getPort(); String login = config.getLogin(); String password = config.getPassword(); MBeanServer platformServer = ManagementFactory.getPlatformMBeanServer(); HtmlAdaptorServer adapterServer = new HtmlAdaptorServer(); AuthInfo authInfo = new AuthInfo(login, password); ObjectName serverName = new ObjectName("com.yb.fix.manage.jmx:name=WebAdministratorServer,type=HtmlAdaptorServer"); ObjectName parserName = new ObjectName("com.yb.fix.manage.jmx:name=WebPageParser,type=WebPageParser"); platformServer.registerMBean(parser, parserName); adapterServer.setPort(port); adapterServer.addUserAuthenticationInfo(authInfo); platformServer.registerMBean(adapterServer, serverName); adapterServer.start(); adapterServer.setParser(parserName); adapterServer.waitState(CommunicatorServer.ONLINE, 1000); } catch (Exception e) { e.printStackTrace(); } } }
36.172414
124
0.732602
c960fafb5dc27037037e8a82c0463c3d1d3f2354
1,016
package com.portal.app.helper; public class SearchCriteria { private String key; private String parentKey; private String operation; private Object value; public SearchCriteria() { } public SearchCriteria(String key, String parentKey, String operation, Object value) { this.key = key; this.parentKey = parentKey; this.operation = operation; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getParentKey() { return parentKey; } public void setParentKey(String parentKey) { this.parentKey = parentKey; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } }
18.472727
89
0.608268
3f2180e4a6154f1392ab624c1bf9d46c4b918e16
5,385
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.msu.cme.rdp.framebot.stat; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * * @author wangqion */ public class IdMappingReader { /** * get the abundance for each rep sequence for each sample from the idMapping file and sampleMapping file * @param idmapping * @return * @throws IOException */ public static HashMap getIDCount(String idmapping, HashMap<String, HashSet<String>> sampleMap ) throws IOException { HashMap<String, HashMap<String, Integer>> countMap = new HashMap<String, HashMap<String, Integer>>(); if ( idmapping == null) { if ( sampleMap == null) { return countMap; } else { // if idmapping is null, we should assume seq in sampleMap have one count for ( String sample: sampleMap.keySet()){ Set<String> sample_seqset = sampleMap.get(sample); HashMap<String, Integer> tmp = countMap.get(sample); if ( tmp == null){ tmp = new HashMap<String, Integer>(); countMap.put(sample, tmp); } for ( String id: sample_seqset){ tmp.put( id, 1); } } } return countMap; } BufferedReader reader = new BufferedReader(new FileReader(new File(idmapping))); String line = null; while ( (line=reader.readLine()) != null){ if ( line.trim().equals("")) continue; String [] values = line.split("\\s+"); String[] ids = values[1].split(","); if ( sampleMap == null){ HashMap<String, Integer> tmp = countMap.get(GetFrameBotStatMain.DEFAULT_SAMPLE); if ( tmp == null){ tmp = new HashMap<String, Integer>(); countMap.put(GetFrameBotStatMain.DEFAULT_SAMPLE, tmp); } tmp.put( ids[0], ids.length); }else { HashSet<String> seqset = new HashSet<String>(); for ( String id: ids){ seqset.add(id); } int prev_size = seqset.size(); for ( String sample: sampleMap.keySet()){ Set sample_seqset = sampleMap.get(sample); if ( sample_seqset != null) seqset.removeAll(sample_seqset); HashMap<String, Integer> tmp = countMap.get(sample); if ( tmp == null){ tmp = new HashMap<String, Integer>(); countMap.put(sample, tmp); } if ( (prev_size - seqset.size() ) > 0 ){ tmp.put( ids[0], prev_size - seqset.size()); } prev_size = seqset.size(); } } } reader.close(); return countMap; } /** * get the mapping sequence IDs of the rep sequences for each sample from the idMapping and sampleMapping file * @param idmapping * @return * @throws IOException */ public static HashMap getIDMapping(String idmapping, HashMap<String, HashSet<String>> sampleMap ) throws IOException { HashMap<String, HashMap<String, Set>> countMap = new HashMap<String, HashMap<String, Set>>(); if ( idmapping == null) return countMap; BufferedReader reader = new BufferedReader(new FileReader(new File(idmapping))); String line = null; while ( (line=reader.readLine()) != null){ if ( line.trim().equals("")) continue; String [] values = line.split("\\s+"); String[] ids = values[1].split(","); HashSet<String> seqset = new HashSet<String>(); for ( String id: ids){ seqset.add(id); } if ( sampleMap == null){ HashMap<String, Set> tmp = countMap.get(GetFrameBotStatMain.DEFAULT_SAMPLE); if ( tmp == null){ tmp = new HashMap<String, Set>(); countMap.put(GetFrameBotStatMain.DEFAULT_SAMPLE, tmp); } tmp.put( ids[0], seqset); countMap.put(GetFrameBotStatMain.DEFAULT_SAMPLE, tmp); }else { for ( String sample: sampleMap.keySet()){ HashSet sample_seqset = sampleMap.get(sample); Set commonSet = new HashSet(seqset); commonSet.retainAll(sample_seqset); HashMap<String, Set> tmp = countMap.get(sample); if ( tmp == null){ tmp = new HashMap<String,Set>(); countMap.put(sample, tmp); } tmp.put(ids[0], commonSet); } } } reader.close(); return countMap; } }
37.922535
123
0.497864
efc38b9e0d55db8b8bed805a9975146771b0a118
8,051
package me.mathiasluo.widget; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Color; import android.os.Build; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import me.mathiasluo.APP; import me.mathiasluo.R; import weekselection.com.library.CheckedTextView; import weekselection.com.library.util.StringUtil; import weekselection.com.library.util.ThemeUtil; /** * Created by mathiasluo on 16-4-6. */ public class WeekPickLayout extends LinearLayout implements View.OnClickListener { private int mAnimationDuration=300;//点击后动画时长默认300毫秒 private final String SPLIT = "、"; private final String TAG = "WeekPickLayout"; private final String[] WEEKS = APP.getInstance().getResources().getStringArray(R.array.weeks); private boolean[] mIsCheckeds = new boolean[]{false, false, false, false, false, false, false}; private int[][] states = new int[][]{ new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked}, }; private int[] colors; private int mTextColor=0XFFFFFF; private int mTextSize = -1; private int mCheckedColor; private CheckedTextView mCircleCTV_1; private CheckedTextView mCircleCTV_2; private CheckedTextView mCircleCTV_3; private CheckedTextView mCircleCTV_4; private CheckedTextView mCircleCTV_5; private CheckedTextView mCircleCTV_6; private CheckedTextView mCircleCTV_7; public void setVaules(String vaule) { if (!StringUtil.isEmpty(vaule)) { String values[] = vaule.split(SPLIT); int len = values.length; for (int i = 0; i < len; i++) { int index = StringUtil.getIndex(values[i], WEEKS); mIsCheckeds[index] = true; } setChecked(); } } public String getValues() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 7; i++) { if (mIsCheckeds[i]) sb.append(WEEKS[i]).append(SPLIT); } if (sb.length() == 0) return ""; else return sb.deleteCharAt(sb.length() - 1).toString(); } public void setChecked() { mCircleCTV_1.setChecked(mIsCheckeds[0]); mCircleCTV_2.setChecked(mIsCheckeds[1]); mCircleCTV_3.setChecked(mIsCheckeds[2]); mCircleCTV_4.setChecked(mIsCheckeds[3]); mCircleCTV_5.setChecked(mIsCheckeds[4]); mCircleCTV_6.setChecked(mIsCheckeds[5]); mCircleCTV_7.setChecked(mIsCheckeds[6]); } public WeekPickLayout(Context context) { super(context); iniColor( context); init(context); } public WeekPickLayout(Context context, AttributeSet attrs) { super(context, attrs); iniColor( context); applyStyle(context,attrs,0,0); init(context); } public WeekPickLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); iniColor( context); applyStyle(context,attrs,defStyleAttr,0); init(context); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public WeekPickLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); iniColor( context); applyStyle(context,attrs,defStyleAttr,defStyleRes); init(context); } protected void init(Context context) { setOrientation(HORIZONTAL); LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); params.weight = 1; mCircleCTV_1 = new CheckedTextView(getContext()); mCircleCTV_1.setLayoutParams(params); intiStyle(mCircleCTV_1, 1); addView(mCircleCTV_1); mCircleCTV_2 = new CheckedTextView(getContext()); mCircleCTV_2.setLayoutParams(params); intiStyle(mCircleCTV_2, 2); addView(mCircleCTV_2); mCircleCTV_3 = new CheckedTextView(getContext()); mCircleCTV_3.setLayoutParams(params); intiStyle(mCircleCTV_3, 3); addView(mCircleCTV_3); mCircleCTV_4 = new CheckedTextView(getContext()); mCircleCTV_4.setLayoutParams(params); intiStyle(mCircleCTV_4, 4); addView(mCircleCTV_4); mCircleCTV_5 = new CheckedTextView(getContext()); mCircleCTV_5.setLayoutParams(params); intiStyle(mCircleCTV_5, 5); addView(mCircleCTV_5); mCircleCTV_6 = new CheckedTextView(getContext()); mCircleCTV_6.setLayoutParams(params); intiStyle(mCircleCTV_6, 6); addView(mCircleCTV_6); mCircleCTV_7 = new CheckedTextView(getContext()); mCircleCTV_7.setLayoutParams(params); intiStyle(mCircleCTV_7, 7); addView(mCircleCTV_7); setListener(); } protected void iniColor(Context context){ int mPrimaryColor = ThemeUtil.colorPrimary(context, 0xFF000000); mCheckedColor = ThemeUtil.colorControlActivated(context, 0xFF000000); colors=new int[]{mPrimaryColor, Color.WHITE}; } protected void setListener() { mCircleCTV_1.setOnClickListener(this); mCircleCTV_2.setOnClickListener(this); mCircleCTV_3.setOnClickListener(this); mCircleCTV_4.setOnClickListener(this); mCircleCTV_5.setOnClickListener(this); mCircleCTV_6.setOnClickListener(this); mCircleCTV_7.setOnClickListener(this); } protected void setClickState(View view) { int index = 0; if (view == mCircleCTV_1) { index = 0; } else if (view == mCircleCTV_2) { index = 1; } else if (view == mCircleCTV_3) { index = 2; } else if (view == mCircleCTV_4) { index = 3; } else if (view == mCircleCTV_5) { index = 4; } else if (view == mCircleCTV_6) { index = 5; } else if (view == mCircleCTV_7) { index = 6; } mIsCheckeds[index] = !mIsCheckeds[index]; ((CheckedTextView) view).setChecked(mIsCheckeds[index]); } protected void intiStyle(CheckedTextView CheckedTextView, int index) { CheckedTextView.setAnimDuration(mAnimationDuration); CheckedTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize); CheckedTextView.setTextColor(new ColorStateList(states, colors)); CheckedTextView.setBackgroundColor(mCheckedColor); CheckedTextView.setText(WEEKS[index - 1]); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { CheckedTextView.setTextAlignment(TEXT_ALIGNMENT_CENTER); } CheckedTextView.setGravity(Gravity.CENTER); } protected void applyStyle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ TypedArray a = context.obtainStyledAttributes(attrs, weekselection.com.library.R.styleable.WeekPickLayout, defStyleAttr, defStyleRes); for(int i = 0, count = a.getIndexCount(); i < count; i++){ int attr = a.getIndex(i); if(attr== weekselection.com.library.R.styleable.WeekPickLayout_wpl_TextSize){ mTextSize = a.getDimensionPixelSize(attr, 0); }else if(attr== weekselection.com.library.R.styleable.WeekPickLayout_wpl_AnimDuration){ mAnimationDuration= a.getInteger(attr, 0); }else if(attr== weekselection.com.library.R.styleable.WeekPickLayout_wpl_CheckedBgColor){ mCheckedColor=a.getColor(attr,0); }else if(attr== weekselection.com.library.R.styleable.WeekPickLayout_wpl_TextColor){ colors[0]=a.getColor(attr,0); } } } @Override public void onClick(View v) { setClickState(v); } }
36.265766
142
0.661905
8e08bc02de2cdd00e9336dd736aa9e61e0c4e774
3,696
package home.eduard.braintraininggame; public class Question { private int level; private final String[] oper = {"*", "/", "+", "-"}; private final int maximumNumber = 10; private String challenge; private int howManyNumbers; private int answer; public Question(int level) { this.level = level; challenge = "Guess:"; answer = 999999; } public void start() { switch (level) { case 0: novice(); break; case 1: easy(); break; case 2: medium(); break; default: guru(); break; } } public void novice() { howManyNumbers = 2; createChallenge(howManyNumbers); } public void easy() { double number = Math.floor(Math.random() * 2 + 2); howManyNumbers = (int) number; createChallenge(howManyNumbers); } public void medium() { double number = Math.floor(Math.random() * 3 + 2); howManyNumbers = (int) number; createChallenge(howManyNumbers); } public void guru() { double number = Math.floor(Math.random() * 3 + 4); howManyNumbers = (int) number; createChallenge(howManyNumbers); } public void createChallenge(int numbers) { int i = 1, randomNumber, sign; double number; //first random number: 0 -> maximumNumber number = Math.floor(Math.random() * maximumNumber); randomNumber = (int) number; //adding the first random number to the challenge string and answer setChallenge(randomNumber); answer = randomNumber; while (i < numbers) { //generate random operation sign number = Math.floor(Math.random() * 4); sign = (int) number; //adding the sign to the final challenge expression setChallenge(oper[sign]); //random number: 0 -> maximumNumber randomNumber = generateNumber(); if (oper[sign].equals("/")) while (randomNumber == 0) randomNumber = generateNumber(); /* * this basically means that if the sign is / (division), * then the following radom number should not be 0 */ //adding the random number to the challenge string setChallenge(randomNumber); //add the operation and number to the final good answer doAnswer(oper[sign], randomNumber); i++; } } public String getChallenge() { return challenge; } public void setChallenge(String challenge) { this.challenge += challenge; } public void setChallenge(int number) { this.challenge += Integer.toString(number); } public int generateNumber() { //generate random number double number = Math.floor(Math.random() * maximumNumber); int randomNumber = (int) number; return randomNumber; } public void doAnswer(String operation, int number) { switch (operation) { case "*": answer *= number; break; case "/": double toSet = (double) answer / number; answer = (int) Math.round(toSet); break; case "-": answer -= number; break; default: answer += number; break; } } public int getAnswer() { return answer; } }
25.666667
75
0.520292
256528d77924658485de05c81d1a21652b498be9
3,295
/*- * #%L * anchor-feature-io * %% * Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * 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. * #L% */ package org.anchoranalysis.feature.io.csv.table; import java.nio.file.Path; import java.util.List; import org.anchoranalysis.io.generator.Generator; import org.anchoranalysis.io.generator.tabular.CSVGenerator; import org.anchoranalysis.io.generator.tabular.CSVWriter; import org.anchoranalysis.io.output.bean.OutputWriteSettings; import org.anchoranalysis.io.output.error.OutputWriteFailedException; /** * Base class for a {@link Generator} that outputs a feature-table in CSV format. * * @author Owen Feehan * @param <T> type of object that describes <i>all</i> rows of feature calculations. */ public abstract class FeatureTableCSVGenerator<T> extends CSVGenerator<T> { private List<String> headerNames; /** * Creates for a particular manifest-function and headers. * * @param manifestFunction the manifest-function. * @param headerNames the headers of all columns for the CSV output. */ protected FeatureTableCSVGenerator(String manifestFunction, List<String> headerNames) { super(manifestFunction); this.headerNames = headerNames; } @Override public void writeToFile(T element, OutputWriteSettings settings, Path filePath) throws OutputWriteFailedException { try (CSVWriter writer = CSVWriter.create(filePath)) { writeFeaturesToCSV(writer, element, headerNames); } catch (OutputWriteFailedException e) { throw new OutputWriteFailedException(e); } } /** * Writes the features to the CSV-file. * * @param writer the write to use * @param allFeatureResults all rows to write * @param headerNames header-names for columns, corresponding to the data in {@code rows}. * @throws OutputWriteFailedException if the output cannot be written. */ protected abstract void writeFeaturesToCSV( CSVWriter writer, T allFeatureResults, List<String> headerNames) throws OutputWriteFailedException; }
40.679012
95
0.712291
22bb857c71d53f1d83097ce5105d58f4688e5059
3,883
package main.controller; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.CheckBox; import javafx.scene.control.TextInputControl; import main.Main; import main.db.*; import java.net.URL; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ResourceBundle; class CustomerAddInvalidFormException extends Exception { public CustomerAddInvalidFormException(String message) { super(message); Alert alert = new Alert(Alert.AlertType.ERROR, message); alert.show(); } } public class CustomerAdd implements Initializable { @FXML private TextInputControl nameInput; @FXML private TextInputControl phoneInput; @FXML private TextInputControl addressInput; @FXML private TextInputControl address2Input; @FXML private TextInputControl cityInput; @FXML private TextInputControl zipInput; @FXML private TextInputControl countryInput; @FXML private CheckBox activeCheckbox; @Override public void initialize(URL location, ResourceBundle resources) { activeCheckbox.setSelected(true); } public void add() throws Exception { String name = nameInput.getText(); String phone = phoneInput.getText(); String address = addressInput.getText(); String address2 = address2Input.getText(); String city = cityInput.getText(); String zip = zipInput.getText(); String country = countryInput.getText(); boolean active = activeCheckbox.isSelected(); try { this.validateForm(name, phone, address, city, zip, country); } catch(CustomerAddInvalidFormException e){ return; } LocalDateTime ldt = LocalDateTime.now(); ZonedDateTime locZdt = ZonedDateTime.of(ldt, ZoneId.systemDefault()); ZonedDateTime utcZdt = locZdt.withZoneSameInstant(ZoneOffset.UTC); DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String utcLocalDateTime = customFormatter.format(utcZdt); String user = Authenticate.user.getUsername(); int isActive = active ? 1 : 0; int countryId = DBCountry.create(country, utcLocalDateTime, user); int cityId = DBCity.create(city, countryId, utcLocalDateTime, user); int addressId = DBAddress.create(address, address2, cityId, zip, phone, utcLocalDateTime, user); DBCustomer.create(name, addressId, isActive, utcLocalDateTime, user); Store.refreshCustomer(); Main.goToCustomer(); } private void validateForm(String name, String phone, String address, String city, String zip, String country) throws CustomerAddInvalidFormException { if (name == null || name.trim().equals("")) { throw new CustomerAddInvalidFormException("Name is a required field"); } if (phone == null || phone.trim().equals("")) { throw new CustomerAddInvalidFormException("Phone is a required field"); } if (address == null || address.trim().equals("")) { throw new CustomerAddInvalidFormException("Address is a required field"); } if (city == null || city.trim().equals("")) { throw new CustomerAddInvalidFormException("City is a required field"); } if (zip == null || zip.trim().equals("")) { throw new CustomerAddInvalidFormException("Zip is a required field"); } if (country == null || country.trim().equals("")) { throw new CustomerAddInvalidFormException("Country is a required field"); } } public void goBack() throws Exception { Main.goToCustomer(); } }
36.28972
154
0.674994
1a07c70154661802eb6dbeab5bc0cde9275c275a
6,268
/* * Copyright 2012-2017 Canoo Engineering AG. * * 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.opendolphin.core; import groovy.lang.GString; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; /** * The value may be null as long as the BaseAttribute is used as a "placeholder". */ public abstract class BaseAttribute extends AbstractObservable implements Attribute { static final public Class[] SUPPORTED_VALUE_TYPES = {Character.class, String.class, Number.class, Boolean.class, Date.class}; static final private Logger log = Logger.getLogger(BaseAttribute.class.getName()); static private long instanceCount = 0; private final String propertyName; private Object value; private Object baseValue; private boolean dirty = false; private final Tag tag; private PresentationModel presentationModel; private String id ; private String qualifier; // application specific semantics apply public BaseAttribute(String propertyName) { this(propertyName, null); } public BaseAttribute(String propertyName, Object baseValue) { this(propertyName, baseValue, Tag.VALUE); } public BaseAttribute(String propertyName, Object baseValue, Tag tag) { this(propertyName, baseValue, null, tag); } public BaseAttribute(String propertyName, Object baseValue, String qualifier, Tag tag) { this.id = (instanceCount++) + getOrigin(); this.propertyName = propertyName; this.baseValue = baseValue; this.value = baseValue; this.qualifier = qualifier; this.tag = (null==tag) ? Tag.VALUE : tag ; } /** * @return 'C' for client or 'S' for server */ public abstract String getOrigin(); public boolean isDirty() { return dirty; } public Object getBaseValue() { return baseValue; } public void setPresentationModel(PresentationModel presentationModel) { if (this.presentationModel != null) { throw new IllegalStateException("You can not set a presentation model for an attribute that is already bound."); } this.presentationModel = presentationModel; } @Override public PresentationModel getPresentationModel() { return this.presentationModel; } public Object getValue() { return value; } public Tag getTag() { return tag; } /** Check whether value is of allowed type and convert to an allowed type if possible. */ public static Object checkValue(Object value) { if (null == value) return null; if (value instanceof Tag) return ((Tag)value).getName(); // name instead of ordinal to make decoding easier Object result = value; if (result instanceof GString) result = value.toString(); if (result instanceof BaseAttribute) { if (log.isLoggable(Level.WARNING)) log.warning("An Attribute may not itself contain an attribute as a value. Assuming you forgot to call getValue()."); result = checkValue((((BaseAttribute) value).getValue())); } boolean ok = false; for (Class type : SUPPORTED_VALUE_TYPES ) { if (type.isAssignableFrom(result.getClass())) { ok = true; break; } } if (!ok) { throw new IllegalArgumentException("Attribute values of this type are not allowed: " + result.getClass().getSimpleName()); } return result; } // todo dk: think about specific method versions for each allowed type public void setValue(Object newValue) { Object checkedValue = checkValue(newValue); setDirty(isDifferent(baseValue, checkedValue)); if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion } } private boolean isDifferent(Object oldValue, Object newValue) { return oldValue == null ? newValue != null : !oldValue.equals(newValue); } private void setDirty(boolean dirty) { firePropertyChange(DIRTY_PROPERTY, this.dirty, this.dirty = dirty); if (null != presentationModel) presentationModel.updateDirty(); } public void setBaseValue(Object baseValue) { setDirty(isDifferent(baseValue, value)); firePropertyChange(BASE_VALUE, this.baseValue, this.baseValue = baseValue); } public void rebase() { setBaseValue(getValue()); setDirty(false); } public void reset() { setValue(getBaseValue()); setDirty(false); } public String toString() { return new StringBuilder() .append(id) .append(" : ") .append(propertyName) .append(" (") .append(qualifier).append(") ") .append("[").append(tag.getName()).append("] ") .append(value).toString(); } public String getPropertyName() { return propertyName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getQualifier() { return qualifier; } public void setQualifier(String qualifier) { firePropertyChange(QUALIFIER_PROPERTY, this.qualifier, this.qualifier = qualifier); } public void syncWith(Attribute source) { if (this == source || null == source) return; //order is important setQualifier(source.getQualifier()); setBaseValue(source.getBaseValue()); setValue(source.getValue()); } }
32.816754
163
0.647735
f4bfe911c77d83cc4b56e2b30a45c310fdc86c1f
815
package com.strumski.library.util; import com.strumski.library.entities.Author; import com.strumski.library.entities.Book; import org.apache.commons.lang3.RandomStringUtils; import java.util.Random; public class BookAuthorFactory { public static Book generateRandomBook() { return Book.builder() .title(RandomStringUtils.randomAlphabetic(5)) .description(RandomStringUtils.randomAlphabetic(10)) .id(new Random().nextInt(100)) .build(); } public static Author generateRandomAuthor() { return Author.builder() .name(RandomStringUtils.randomAlphabetic(5)) .birthplace(RandomStringUtils.randomAlphabetic(10)) .id(new Random().nextInt(100)) .build(); } }
30.185185
68
0.641718
4bd91b8ea6432858275ca9e390b7e95c0f2baaed
3,898
package com.am.scheduling.presentation.screens.home.schedule.modules; import android.util.SparseArray; import com.am.scheduling.chapter5.Timetable; import com.am.scheduling.data.database.models.Group; import com.am.scheduling.presentation.abc.core.base.BasePresenterImpl; import com.am.scheduling.presentation.screens.home.schedule.modules.adapter.group_module.GroupModulesDH; import com.am.scheduling.presentation.screens.home.schedule.modules.adapter.module.ModuleDH; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import io.reactivex.Observable; public class ModulesPresenter extends BasePresenterImpl<ModulesContract.View> implements ModulesContract.Presenter { private ModulesContract.Model model; private ArrayList<GroupModulesDH> groupModules; private SparseArray<SetWrap> subjTeachersId; public ModulesPresenter(ModulesContract.View view, ModulesContract.Model model, ArrayList<Group> groups) { super(view); this.model = model; this.groupModules = new ArrayList<>(Observable.fromIterable(groups) .map(GroupModulesDH::new) .toList() .blockingGet()); subjTeachersId = new SparseArray<>(); addDisposable(model.subjectListCase.async() .flatMapObservable(Observable::fromIterable) .subscribe(subject -> subjTeachersId.put(subject.id, new SetWrap()))); } @Override public void subscribe() { getView().setTabs(groupModules); } @Override public void next(GroupModulesDH dh, int position) { if (dh.moduleDHS.isEmpty()) { getView().showMessage("Need module(s)"); } else if (position < groupModules.size() - 1) { groupModules.set(position, dh); getView().selectTab(position + 1); } else { getView().startGeneratorScreen(prepareTimetable()); } } private Timetable prepareTimetable() { Timetable timetable = new Timetable(); obtainSubjects(); for (GroupModulesDH dh : groupModules) { IntWrap moduleIds = new IntWrap(); for (ModuleDH moduleDH : dh.moduleDHS){ timetable.addProfessor(moduleDH.teacher.id, moduleDH.teacher.fullName); timetable.addModule(moduleDH.subject.id, moduleDH.subject.name, subjTeachersId.get(moduleDH.subject.id).get()); for (int i = 0; i < moduleDH.count; i++) { moduleIds.add(moduleDH.subject.id); } } timetable.addGroup(dh.group.id, dh.group.size, moduleIds.get()); } return timetable; } private void obtainSubjects() { for (GroupModulesDH dh : groupModules) { for (ModuleDH moduleDH : dh.moduleDHS) { subjTeachersId.get(moduleDH.subject.id).add(moduleDH.teacher.id); } } } class IntWrap { List<Integer> ids; IntWrap() { ids = new ArrayList<>(); } public int[] get() { int[] res = new int[ids.size()]; for (int i = 0; i < ids.size(); i++) { res[i] = ids.get(i); } return res; } public void add(int value) { ids.add(value); } } class SetWrap { Set<Integer> ids; SetWrap() { ids = new HashSet<>(); } public int[] get() { int[] res = new int[ids.size()]; Iterator<Integer> iterator = ids.iterator(); int i = 0; while (iterator.hasNext()) { res[i] = iterator.next(); ++i; } return res; } public void add(int value) { ids.add(value); } } }
30.453125
127
0.590559
c60aef0cf45814a8add2ea628b0f9e8dfd25c6bf
4,165
package com.baxi.agrohelper.view; /*- * #%L * agro-helper * %% * Copyright (C) 2017 University of Debrecen, Faculty of Informatics * %% * 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% */ import com.baxi.agrohelper.dao.VarietyDao; import com.baxi.agrohelper.dao.VarietyNameDao; import com.baxi.agrohelper.model.Variety; import com.baxi.agrohelper.service.VarietyNameService; import com.baxi.agrohelper.service.VarietyNameServiceImpl; import com.baxi.agrohelper.service.VarietyService; import com.baxi.agrohelper.service.VarietyServiceImpl; import com.baxi.agrohelper.util.EntityManagerProvider; import com.baxi.agrohelper.util.StatementUtil; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.stage.Stage; public class VarietyEditDialogController { @FXML private ChoiceBox<String> nameBox; @FXML private TextField priceTextField; @FXML private TextField yieldTextField; @FXML private TextField areaTextField; private Stage dialogStage; private Variety variety; private boolean okClicked; private VarietyService varietyService; private VarietyNameService varietyNameService; @FXML private void initialize(){ varietyService = new VarietyServiceImpl(new VarietyDao(EntityManagerProvider.provideEntityManager())); varietyNameService = new VarietyNameServiceImpl(new VarietyNameDao(EntityManagerProvider.provideEntityManager())); } public void setDialogStage(Stage dialogStage){ this.dialogStage = dialogStage; } public void setVariety(Variety variety){ this.variety = variety; nameBox.getItems().addAll(varietyNameService.getAllVarietyNames()); nameBox.setValue(this.variety.getVarietyName()); areaTextField.setText(Double.toString(this.variety.getVarietyArea())); priceTextField.setText(Integer.toString(this.variety.getVarietyPrice())); yieldTextField.setText(Double.toString(this.variety.getVarietyYield())); } public boolean isOkClicked(){ return okClicked; } @FXML public void handleOk(){ if(isInputValid()){ variety.setVarietyName(nameBox.getSelectionModel().getSelectedItem()); try{ variety.setVarietyPrice(Integer.parseInt(priceTextField.getText())); variety.setVarietyYield(Double.parseDouble(yieldTextField.getText())); variety.setVarietyArea(Double.parseDouble(areaTextField.getText())); variety.setTotalHarvest(StatementUtil.countVarietyHarvest(this.variety)); variety.setTotalIncome(StatementUtil.countVarietyIncome(this.variety)); }catch(NumberFormatException e){ } varietyService.updateVariety(variety); okClicked = true; dialogStage.close(); } } @FXML private void handleCancel(){ dialogStage.close(); } private boolean isInputValid(){ String errorMessage = ""; if(priceTextField.getText().length() != 0){ try{ Integer.parseInt(priceTextField.getText()); }catch(NumberFormatException e){ errorMessage += "Hibás ár!\n"; } } if(yieldTextField.getText().length() != 0){ try{ Double.parseDouble(yieldTextField.getText()); }catch(NumberFormatException e){ errorMessage += "Hibás hozam!\n"; } } try{ Double.parseDouble(areaTextField.getText()); }catch(NumberFormatException e){ errorMessage += "Hibás terület!\n"; } if(errorMessage.length() == 0){ return true; }else{ Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Hiba"); alert.setHeaderText("Hibás adatok."); alert.setContentText(errorMessage); alert.showAndWait(); return false; } } }
28.141892
116
0.75006
93f6db1701b78ec58fd710f8f2dacb7c6abb5ff2
3,970
package org.terasology.joml.test; import org.joml.Vector2dc; import org.joml.Vector2fc; import org.joml.Vector3dc; import org.joml.Vector3fc; import org.joml.Vector4dc; import org.joml.Vector4fc; import java.util.function.Supplier; import static org.terasology.joml.test.AssertionUtils.failNotEqual; import static org.terasology.joml.test.AssertionUtils.isValid; public class VectorAssert { private VectorAssert() { } public static void assertEquals(Vector4fc expected, Vector4fc actual, float epsilon) { if (isValid(expected, actual) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual); } } public static void assertEquals(Vector4dc expected, Vector4dc actual, float epsilon) { if (isValid(expected, actual) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual); } } public static void assertEquals(Vector3fc expected, Vector3fc actual, float epsilon) { if (isValid(expected, actual) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual); } } public static void assertEquals(Vector3fc expected, Vector3fc actual, float epsilon, String message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } public static void assertEquals(Vector3fc expected, Vector3fc actual, float epsilon, Supplier<String> message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } public static void assertEquals(Vector3dc expected, Vector3dc actual, double epsilon) { if (isValid(expected, actual) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual); } } public static void assertEquals(Vector3dc expected, Vector3dc actual, double epsilon, String message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } public static void assertEquals(Vector3dc expected, Vector3dc actual, double epsilon, Supplier<String> message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } public static void assertEquals(Vector2fc expected, Vector2fc actual, float epsilon) { if (isValid(expected, actual) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual); } } public static void assertEquals(Vector2fc expected, Vector2fc actual, float epsilon, String message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } public static void assertEquals(Vector2fc expected, Vector2fc actual, float epsilon, Supplier<String> message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } public static void assertEquals(Vector2dc expected, Vector2dc actual, double epsilon) { if (isValid(expected, actual) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual); } } public static void assertEquals(Vector2dc expected, Vector2dc actual, double epsilon, String message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } public static void assertEquals(Vector2dc expected, Vector2dc actual, double epsilon, Supplier<String> message) { if (isValid(expected, actual, message) && !expected.equals(actual, epsilon)) { failNotEqual(expected, actual, message); } } }
38.543689
117
0.672796
f103f83269707412a1340a54108ede5df17e6cf0
4,596
/* * Copyright (C) 2010-2021 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.repo.sql.data.common; import javax.persistence.*; import javax.xml.datatype.XMLGregorianCalendar; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.ForeignKey; import org.hibernate.annotations.Persister; import com.evolveum.midpoint.repo.sql.data.RepositoryContext; import com.evolveum.midpoint.repo.sql.data.common.embedded.REmbeddedReference; import com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString; import com.evolveum.midpoint.repo.sql.query.definition.JaxbName; import com.evolveum.midpoint.repo.sql.query.definition.NeverNull; import com.evolveum.midpoint.repo.sql.util.DtoTranslationException; import com.evolveum.midpoint.repo.sql.util.IdGeneratorResult; import com.evolveum.midpoint.repo.sql.util.MidPointJoinedPersister; import com.evolveum.midpoint.repo.sql.util.RUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationDefinitionType; @Entity @Table(name = RAccessCertificationDefinition.TABLE_NAME, uniqueConstraints = @UniqueConstraint(name = "uc_acc_cert_definition_name", columnNames = { "name_norm" }), indexes = { @Index(name = "iCertDefinitionNameOrig", columnList = "name_orig"), } ) @Persister(impl = MidPointJoinedPersister.class) @ForeignKey(name = "fk_acc_cert_definition") @DynamicUpdate public class RAccessCertificationDefinition extends RObject { public static final String TABLE_NAME = "m_acc_cert_definition"; private RPolyString nameCopy; private String handlerUri; private REmbeddedReference ownerRefDefinition; private XMLGregorianCalendar lastCampaignStartedTimestamp; private XMLGregorianCalendar lastCampaignClosedTimestamp; @JaxbName(localPart = "name") @AttributeOverrides({ @AttributeOverride(name = "orig", column = @Column(name = "name_orig")), @AttributeOverride(name = "norm", column = @Column(name = "name_norm")) }) @Embedded @NeverNull public RPolyString getNameCopy() { return nameCopy; } public void setNameCopy(RPolyString nameCopy) { this.nameCopy = nameCopy; } public String getHandlerUri() { return handlerUri; } @JaxbName(localPart = "ownerRef") @Embedded @AttributeOverrides({ @AttributeOverride(name = "relation", column = @Column(name = "ownerRef_relation", length = RUtil.COLUMN_LENGTH_QNAME)), @AttributeOverride(name = "targetOid", column = @Column(name = "ownerRef_targetOid", length = RUtil.COLUMN_LENGTH_OID)), @AttributeOverride(name = "targetType", column = @Column(name = "ownerRef_targetType")) }) public REmbeddedReference getOwnerRefDefinition() { return ownerRefDefinition; } public XMLGregorianCalendar getLastCampaignStartedTimestamp() { return lastCampaignStartedTimestamp; } public XMLGregorianCalendar getLastCampaignClosedTimestamp() { return lastCampaignClosedTimestamp; } public void setHandlerUri(String handlerUri) { this.handlerUri = handlerUri; } public void setOwnerRefDefinition(REmbeddedReference ownerRefDefinition) { this.ownerRefDefinition = ownerRefDefinition; } public void setLastCampaignStartedTimestamp(XMLGregorianCalendar lastCampaignStartedTimestamp) { this.lastCampaignStartedTimestamp = lastCampaignStartedTimestamp; } public void setLastCampaignClosedTimestamp(XMLGregorianCalendar lastCampaignClosedTimestamp) { this.lastCampaignClosedTimestamp = lastCampaignClosedTimestamp; } // dynamically called public static void copyFromJAXB(AccessCertificationDefinitionType jaxb, RAccessCertificationDefinition repo, RepositoryContext repositoryContext, IdGeneratorResult generatorResult) throws DtoTranslationException { copyAssignmentHolderInformationFromJAXB(jaxb, repo, repositoryContext, generatorResult); repo.setNameCopy(RPolyString.copyFromJAXB(jaxb.getName())); repo.setHandlerUri(jaxb.getHandlerUri()); repo.setOwnerRefDefinition(RUtil.jaxbRefToEmbeddedRepoRef(jaxb.getOwnerRef(), repositoryContext.relationRegistry)); repo.setLastCampaignStartedTimestamp(jaxb.getLastCampaignStartedTimestamp()); repo.setLastCampaignClosedTimestamp(jaxb.getLastCampaignClosedTimestamp()); } }
39.965217
132
0.756527
2e1f13058620c3b76b2ce38d46beddf5abfda4b1
2,060
package com.arcao.trackables; import android.app.Application; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.net.Uri; import android.widget.ImageView; import com.arcao.trackables.internal.di.component.AppComponent; import com.arcao.trackables.preference.PreferenceHelper; import com.arcao.trackables.ui.util.picasso.CropSquareTransformation; import com.mikepenz.materialdrawer.util.DrawerImageLoader; import com.squareup.picasso.Picasso; import javax.inject.Inject; import timber.log.Timber; public class App extends Application { private AppComponent component; @Inject protected PreferenceHelper preferenceHelper; @Inject protected Picasso picasso; @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } else { // TODO Crashlytics.start(this); // TODO Timber.plant(new CrashlyticsTree()); } component().inject(this); //initialize and create the image loader logic DrawerImageLoader.init(new DrawerImageLoader.IDrawerImageLoader() { @Override public void set(ImageView imageView, Uri uri, Drawable placeholder) { picasso.load(uri).placeholder(placeholder).transform(new CropSquareTransformation()).into(imageView); } @Override public void cancel(ImageView imageView) { picasso.cancelRequest(imageView); } @Override public Drawable placeholder(Context context) { return null; } }); } public AppComponent component() { if (component == null) { component = AppComponent.Initializer.init(this); } return component; } public static App get(Context context) { return (App) context.getApplicationContext(); } public String getVersion() { try { return getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { Timber.e(e, e.getMessage()); return "1.0"; } } public String getDeviceId() { return preferenceHelper.getDeviceId(); } }
23.678161
105
0.750485
ed1c7be25cf445ffe0527c97e0c268246c73000f
7,374
/* * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.sap.productconfig.frontend.controllers; import de.hybris.platform.acceleratorstorefrontcommons.constants.WebConstants; import de.hybris.platform.sap.productconfig.facades.ConfigurationData; import de.hybris.platform.sap.productconfig.facades.KBKeyData; import de.hybris.platform.sap.productconfig.frontend.UiStatus; import de.hybris.platform.sap.productconfig.frontend.constants.SapproductconfigfrontendWebConstants; import de.hybris.platform.servicelayer.exceptions.BusinessException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * Default Controller for the dynamic product configuration content page. * * @see UpdateConfigureProductController */ @Controller @RequestMapping() public class ConfigureProductController extends AbstractProductConfigController { private static final Logger LOGGER = Logger.getLogger(ConfigureProductController.class); /** * Accepts HTTP-GET requests and delegates to * {@link ConfigureProductController#configureProduct(String, Model, HttpServletRequest, RedirectAttributes)} */ @RequestMapping(value = "/**/{productCode:.*}/configuratorPage/" + SapproductconfigfrontendWebConstants.CONFIGURATOR_TYPE, method = RequestMethod.GET) public String configureProductGET(@PathVariable("productCode") final String productCodeEncoded, final Model model, final HttpServletRequest request, final RedirectAttributes redirectAttributes) throws BusinessException { return configureProduct(productCodeEncoded, model, request, redirectAttributes); } /** * Accepts HTTP-POST requests and delegates to * {@link ConfigureProductController#configureProduct(String, Model, HttpServletRequest, RedirectAttributes)} */ @RequestMapping(value = "/**/{productCode:.*}/configuratorPage/" + SapproductconfigfrontendWebConstants.CONFIGURATOR_TYPE, method = RequestMethod.POST) public String configureProductPOST(@PathVariable("productCode") final String productCodeEncoded, final Model model, final HttpServletRequest request, final RedirectAttributes redirectAttributes) throws BusinessException { return configureProduct(productCodeEncoded, model, request, redirectAttributes); } /** * Renders the dynamic product configuration content page for the given product. In case a configuration session * already exists for this product in the user session, it will be restored. Otherwise a new session is initiated, so * that the runtime configuration is populated with the default values. * * @param productCodeEncoded * coded of the configurable product * @param model * view model * @param request * HTTP-Request * @param redirectAttributes * redirect attributes * @return view name * @throws BusinessException */ protected String configureProduct(final String productCodeEncoded, final Model model, final HttpServletRequest request, final RedirectAttributes redirectAttributes) throws BusinessException { final String productCode = decodeWithScheme(productCodeEncoded, UTF_8); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Config '%s' received for '%s' - Current Session: '%s'", request.getMethod(), productCode, getSessionService().getCurrentSession().getSessionId())); } final ConfigurationData configData = populateConfigurationModel(request, model, productCode); getUiRecorder().recordUiAccess(configData, productCode); if (hasProductVariantApplied(productCode, configData)) { return SapproductconfigfrontendWebConstants.CONFIG_PAGE_VIEW_NAME; } else { model.asMap().entrySet().stream() .forEach(entry -> redirectAttributes.addFlashAttribute(entry.getKey(), entry.getValue())); return REDIRECT_PREFIX + ROOT + configData.getKbKey().getProductCode() + SapproductconfigfrontendWebConstants.CONFIG_URL; } } protected boolean hasProductVariantApplied(final String productCode, final ConfigurationData configData) { return configData.getKbKey().getProductCode().equals(productCode); } protected ConfigurationData populateConfigurationModel(final HttpServletRequest request, final Model model, final String productCode) throws BusinessException { model.addAttribute(WebConstants.BREADCRUMBS_KEY, getBreadcrumbBuilder().getBreadcrumbs(productCode, getCartEntryNumber(productCode))); populateCMSAttributes(model); if (model.containsAttribute(SapproductconfigfrontendWebConstants.CONFIG_ATTRIBUTE)) { return (ConfigurationData) model.asMap().get(SapproductconfigfrontendWebConstants.CONFIG_ATTRIBUTE); } final KBKeyData kbKey = new KBKeyData(); kbKey.setProductCode(productCode); final ConfigurationData configData; UiStatus uiStatus; if (!isConfigRemoved(productCode)) { // old ui status uiStatus = getSessionAccessFacade().getUiStatusForProduct(productCode); configData = reloadConfigurationByKBKey(kbKey, uiStatus); if (uiStatus == null) { uiStatus = getSessionAccessFacade().getUiStatusForProduct(configData.getKbKey().getProductCode()); } configData.setQuantity(uiStatus.getQuantity()); } else { final long quantity = getQuantity(request); configData = loadNewConfiguration(kbKey); configData.setQuantity(quantity); // new ui status is created by loadNewConfiguration, product code can change in case of variants uiStatus = getSessionAccessFacade().getUiStatusForProduct(configData.getKbKey().getProductCode()); uiStatus.setQuantity(quantity); } populateProductData(configData.getKbKey().getProductCode(), model, request); getUiStateHandler().compileGroupForDisplay(configData, uiStatus); setCartEntryLinks(configData); model.addAttribute(SapproductconfigfrontendWebConstants.CONFIG_ATTRIBUTE, configData); final BindingResult errors = getBindingResultForConfigAndSaveUiStatus(configData, uiStatus); model.addAttribute(BindingResult.MODEL_KEY_PREFIX + SapproductconfigfrontendWebConstants.CONFIG_ATTRIBUTE, errors); getUiStateHandler().countNumberOfUiErrorsPerGroup(configData.getGroups()); getUiStateHandler().handleConflictSolverMessage(uiStatus, getUiStatusSync().getNumberOfConflicts(configData), model); getUiStateHandler().handleProductConfigMessages(configData.getMessages(), model); logModelmetaData(configData); return configData; } protected long getQuantity(final HttpServletRequest request) { final String qtyString = request.getParameter("qty"); long qty = 1; if (StringUtils.isNotEmpty(qtyString)) { qty = Long.parseLong(qtyString); } return qty; } }
38.810526
124
0.79387
a1e1825f49143ddf2efe6aab8007839f51e6672a
785
import fi.helsinki.cs.tmc.edutestutils.Points; import org.junit.*; import static org.junit.Assert.*; @Points("02-30") public class SmallestTest { @Test public void normalCase() { test(2, 7, 2); } @Test public void oneIsNegative() { test(-5, 4, -5); } @Test public void veryLargeValues() { test(Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); } @Test public void normalCaseReversed() { test(7, 2, 2); } private void test(int num1, int num2, int expected) { assertEquals(getError(num1, num2), expected, Smallest.smallest(num1, num2)); } private String getError(int num1, int num2) { return "Wrong result when number1=" + num1 + " and nsumber2=" + num2; } }
21.216216
84
0.610191
1bd86157102dba0931bb81414c578fc246750e06
10,922
package com.zyu.wsecx.asn1.pkcs; import com.zyu.wsecx.asn1.ASN1Encodable; import com.zyu.wsecx.asn1.ASN1EncodableVector; import com.zyu.wsecx.asn1.ASN1InputStream; import com.zyu.wsecx.asn1.ASN1Sequence; import com.zyu.wsecx.asn1.DERBitString; import com.zyu.wsecx.asn1.DERInteger; import com.zyu.wsecx.asn1.DERNull; import com.zyu.wsecx.asn1.DERObject; import com.zyu.wsecx.asn1.DERObjectIdentifier; import com.zyu.wsecx.asn1.DERSequence; import com.zyu.wsecx.asn1.cryptopro.CryptoProObjectIdentifiers; import com.zyu.wsecx.asn1.nist.NISTObjectIdentifiers; import com.zyu.wsecx.asn1.oiw.OIWObjectIdentifiers; import com.zyu.wsecx.asn1.x509.AlgorithmIdentifier; import com.zyu.wsecx.asn1.x9.X9ObjectIdentifiers; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; /** * PKCS10 Certification request object. * * <pre> * CertificationRequest ::= SEQUENCE { * certificationRequestInfo CertificationRequestInfo, * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, * signature BIT STRING * } * </pre> */ public class CertificationRequest extends ASN1Encodable { protected static Hashtable algorithms = new Hashtable(); protected static Hashtable params = new Hashtable(); private static Hashtable keyAlgorithms = new Hashtable(); private static Hashtable oids = new Hashtable(); protected static Vector noParams = new Vector(); private static Hashtable sigAlgorithms = new Hashtable(); static { algorithms.put("RSA", new DERObjectIdentifier("1.2.840.113549.1.1.1")); algorithms.put("MD2WITHRSAENCRYPTION", new DERObjectIdentifier("1.2.840.113549.1.1.2")); algorithms.put("MD2WITHRSA", new DERObjectIdentifier("1.2.840.113549.1.1.2")); algorithms.put("MD5WITHRSAENCRYPTION", new DERObjectIdentifier("1.2.840.113549.1.1.4")); algorithms.put("MD5WITHRSA", new DERObjectIdentifier("1.2.840.113549.1.1.4")); algorithms.put("RSAWITHMD5", new DERObjectIdentifier("1.2.840.113549.1.1.4")); algorithms.put("SHA1WITHRSAENCRYPTION", new DERObjectIdentifier("1.2.840.113549.1.1.5")); algorithms.put("SHA1WITHRSA", new DERObjectIdentifier("1.2.840.113549.1.1.5")); algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("RSAWITHSHA1", new DERObjectIdentifier("1.2.840.113549.1.1.5")); algorithms.put("RIPEMD160WITHRSAENCRYPTION", new DERObjectIdentifier("1.3.36.3.3.1.2")); algorithms.put("RIPEMD160WITHRSA", new DERObjectIdentifier("1.3.36.3.3.1.2")); algorithms.put("SHA1WITHDSA", new DERObjectIdentifier("1.2.840.10040.4.3")); algorithms.put("DSAWITHSHA1", new DERObjectIdentifier("1.2.840.10040.4.3")); algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); algorithms.put("GOST3410WITHGOST3411", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); // For sm2 algs /* * algorithms.put("SM3WITHSM2", new DERObjectIdentifier( * "1.2.156.10197.1.501")); algorithms.put("SHA1WITHSM2", new * DERObjectIdentifier( "1.2.156.10197.1.502")); */ algorithms.put("SM3WITHSM2", new DERObjectIdentifier("1.2.840.10045.2.1")); // // reverse mappings // oids.put(new DERObjectIdentifier("1.2.156.10197.1.501"), "SM3WITHSM2"); oids.put(new DERObjectIdentifier("1.2.156.10197.1.502"), "SHA1WITHSM2"); oids.put(new DERObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); oids.put(new DERObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); oids.put(new DERObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); oids.put(new DERObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); oids.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); oids.put(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); sigAlgorithms.put("SM3WITHSM2", new DERObjectIdentifier("1.2.156.10197.1.501")); // // key types // keyAlgorithms.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); keyAlgorithms.put(X9ObjectIdentifiers.id_dsa, "DSA"); // // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or // MUST (ecdsa-with-SHA*) omit the parameters field. // The parameters field SHALL be NULL for RSA based signature // algorithms. // noParams.addElement(X9ObjectIdentifiers.ecdsa_with_SHA1); noParams.addElement(X9ObjectIdentifiers.ecdsa_with_SHA224); noParams.addElement(X9ObjectIdentifiers.ecdsa_with_SHA256); noParams.addElement(X9ObjectIdentifiers.ecdsa_with_SHA384); noParams.addElement(X9ObjectIdentifiers.ecdsa_with_SHA512); noParams.addElement(X9ObjectIdentifiers.id_dsa_with_sha1); noParams.addElement(NISTObjectIdentifiers.dsa_with_sha224); noParams.addElement(NISTObjectIdentifiers.dsa_with_sha256); // // RFC 4491 // noParams.addElement(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); noParams.addElement(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); // // explicit params // AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull()); params.put("SHA1WITHRSAANDMGF1", creatPSSParams(sha1AlgId, 20)); AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull()); params.put("SHA224WITHRSAANDMGF1", creatPSSParams(sha224AlgId, 28)); AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull()); params.put("SHA256WITHRSAANDMGF1", creatPSSParams(sha256AlgId, 32)); AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull()); params.put("SHA384WITHRSAANDMGF1", creatPSSParams(sha384AlgId, 48)); AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, new DERNull()); params.put("SHA512WITHRSAANDMGF1", creatPSSParams(sha512AlgId, 64)); params.put("SM3WITHSM2", new DERObjectIdentifier("1.2.156.10197.1.301")); } protected CertificationRequestInfo reqInfo = null; protected AlgorithmIdentifier sigAlgId = null; protected AlgorithmIdentifier pubKeyAlgId = null; protected DERBitString sigBits = null; private static RSASSAPSSparams creatPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) { return new RSASSAPSSparams(hashAlgId, new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), new DERInteger(saltSize), new DERInteger(1)); } public static CertificationRequest getInstance(Object o) { if (o instanceof CertificationRequest) { return (CertificationRequest) o; } if (o instanceof ASN1Sequence) { return new CertificationRequest((ASN1Sequence) o); } throw new IllegalArgumentException("Invalid object: " + o.getClass().getName()); } protected CertificationRequest() { } public CertificationRequest(CertificationRequestInfo requestInfo, AlgorithmIdentifier algorithm, DERBitString signature) { this.reqInfo = requestInfo; this.sigAlgId = algorithm; this.sigBits = signature; } public CertificationRequest(ASN1Sequence seq) { reqInfo = CertificationRequestInfo.getInstance(seq.getObjectAt(0)); sigAlgId = AlgorithmIdentifier.getInstance(seq.getObjectAt(1)); sigBits = (DERBitString) seq.getObjectAt(2); } public CertificationRequestInfo getCertificationRequestInfo() { return reqInfo; } public AlgorithmIdentifier getSignatureAlgorithm() { return sigAlgId; } public DERBitString getSignature() { return sigBits; } public DERObject toASN1Object() { // Construct the CertificateRequest ASN1EncodableVector v = new ASN1EncodableVector(); v.add(reqInfo); v.add(sigAlgId); v.add(sigBits); return new DERSequence(v); } protected static ASN1Sequence toDERSequence(byte[] bytes) { ASN1InputStream dIn = null; try { dIn = new ASN1InputStream(bytes); return (ASN1Sequence) dIn.readObject(); } catch (Exception e) { throw new IllegalArgumentException("badly encoded request"); } finally { try { dIn.close(); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } } }
42.498054
152
0.787493
bf012c4117640c72061e831e5effd77fce6bde1d
1,603
/* * Copyright (c) 2020, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.distort; import boofcv.struct.distort.PixelTransform; import georegression.struct.affine.Affine2D_F64; import georegression.struct.point.Point2D_F64; import georegression.transform.affine.AffinePointOps_F64; import lombok.Getter; /** * Distorts pixels using {@link Affine2D_F64}. * * @author Peter Abeles */ public class PixelTransformAffine_F64 implements PixelTransform<Point2D_F64> { @Getter protected final Affine2D_F64 model = new Affine2D_F64(); public PixelTransformAffine_F64() {} public PixelTransformAffine_F64( Affine2D_F64 affine ) { this.model.setTo(affine); } public void setTo( Affine2D_F64 affine ) { this.model.setTo(affine); } @Override public void compute( int x, int y, Point2D_F64 output ) { AffinePointOps_F64.transform(model, x, y, output); } @Override public PixelTransformAffine_F64 copyConcurrent() { return new PixelTransformAffine_F64(model); } }
28.625
78
0.75733
c21c6cf388f73772615b0f68213405389913b52e
645
package com.education.repository.projection; import java.time.LocalDate; import lombok.Getter; import lombok.Setter; @Getter @Setter public class DiaryClassroomSchoolProjection { private Long id; private LocalDate dateDiary; private Boolean active; private Long idClassroomSchool; private String nameClassroomSchool; public DiaryClassroomSchoolProjection(Long id, LocalDate dateDiary, Boolean active, Long idClassroomSchool, String nameClassroomSchool) { this.id = id; this.dateDiary = dateDiary; this.active = active; this.idClassroomSchool = idClassroomSchool; this.nameClassroomSchool = nameClassroomSchool; } }
22.241379
138
0.796899
444657ad3c4934820964cc039f9394021cbed3f6
1,131
package org.sherlockyb.leetcode.string.zigZagConversion; /** * Created by yangbing on 2017/4/3. */ public class Solution { public String convert(String s, int numRows) { if (s == null || s.length() <= 0 || numRows <= 0) { return ""; } if (numRows == 1) return s; char[] result = new char[s.length()]; int rIdx = 0; int headLetterIdx, step1, step2; for (int i = 0; i < numRows; i++) { headLetterIdx = i; step1 = numRows-i%(numRows-1)-1 + numRows-i%(numRows-1)-2 + 1; step2 = numRows-(numRows-1-i)%(numRows-1)-1 + numRows-(numRows-1-i)%(numRows-1)-2 + 1; boolean step1Flag = true; while (headLetterIdx < s.length()) { result[rIdx++] = s.charAt(headLetterIdx); if (step1Flag) { headLetterIdx += step1; step1Flag = false; } else { headLetterIdx += step2; step1Flag = true; } } } return new String(result); } }
30.567568
98
0.473033
dd8ad2240c3b6b54d24c541c9b11986cd289ed0d
674
package com.haiyu.manager.dao; import com.haiyu.manager.pojo.SettingsPayType; import com.haiyu.manager.query.PayTypeQuery; import com.haiyu.manager.vo.PayTypeVO; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import tk.mapper.MyMapper; import java.util.List; @Repository public interface SettingsPayTypeMapper extends MyMapper<SettingsPayType> { List<PayTypeVO> getPayTypeList(PayTypeQuery query); SettingsPayType findByPayTypeName(@Param("typeName") String typeName); int updatePayType(SettingsPayType pojo); int updatePayTypeStatus(@Param("id") Integer id, @Param("typeStatus") Integer typeStatus); }
28.083333
94
0.801187
9979ba5ff3a6f74026ad3252da22a1be8ea8b274
5,042
/* * Copyright (c) 2009, Rickard Öberg. 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.qi4j.spi.entitystore.helpers; import java.util.Iterator; import java.util.NoSuchElementException; import org.json.JSONArray; import org.json.JSONException; import org.qi4j.api.entity.EntityReference; import org.qi4j.spi.entity.ManyAssociationState; import org.qi4j.spi.entitystore.EntityStoreException; /** * JSON implementation of ManyAssociationState. * <p>Backed by a JSONArray.</p> */ public final class JSONManyAssociationState implements ManyAssociationState { private JSONEntityState entityState; private JSONArray references; public JSONManyAssociationState( JSONEntityState entityState, JSONArray references ) { this.entityState = entityState; this.references = references; } @Override public int count() { return references.length(); } @Override public boolean contains( EntityReference entityReference ) { return indexOfReference( entityReference.identity() ) != -1; } @Override public boolean add( int idx, EntityReference entityReference ) { try { if( indexOfReference( entityReference.identity() ) != -1 ) { return false; } entityState.cloneStateIfGlobalStateLoaded(); insertReference( idx, entityReference.identity() ); entityState.markUpdated(); return true; } catch( JSONException e ) { throw new EntityStoreException( e ); } } @Override public boolean remove( EntityReference entityReference ) { int refIndex = indexOfReference( entityReference.identity() ); if( refIndex != -1 ) { entityState.cloneStateIfGlobalStateLoaded(); references.remove( refIndex ); entityState.markUpdated(); return true; } return false; } @Override public EntityReference get( int i ) { try { return new EntityReference( references.getString( i ) ); } catch( JSONException e ) { throw new EntityStoreException( e ); } } @Override public Iterator<EntityReference> iterator() { return new Iterator<EntityReference>() { private int idx = 0; @Override public boolean hasNext() { return idx < references.length(); } @Override public EntityReference next() { try { EntityReference ref = new EntityReference( references.getString( idx ) ); idx++; return ref; } catch( JSONException e ) { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException( "remove() is not supported on ManyAssociation iterators." ); } }; } @Override public String toString() { return references.toString(); } private int indexOfReference( Object item ) { for( int idx = 0; idx < references.length(); idx++ ) { if( item.equals( references.opt( idx ) ) ) { return idx; } } return -1; } private void insertReference( int insert, Object item ) throws JSONException { if( insert < 0 || insert > references.length() ) { throw new JSONException( "JSONArray[" + insert + "] is out of bounds." ); } if( insert == references.length() ) { // append references.put( item ); } else { // insert (copy/insert/apply) JSONArray output = new JSONArray(); for( int idx = 0; idx < references.length(); idx++ ) { if( idx == insert ) { output.put( item ); } output.put( references.opt( idx ) ); } for( int idx = 0; idx < output.length(); idx++ ) { references.put( idx, output.opt( idx ) ); } } } }
27.402174
117
0.549782
a8238e35f53208a575cb07e836a79f553dde03fd
5,601
package de.max.adventofcode; import java.time.LocalDateTime; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Day04 { public static void main(String[] args) { doPart(1); System.out.println(); doPart(2); } private static void doPart(int partNumber) { System.out.println("Doing part " + partNumber); long start = System.currentTimeMillis(); System.out.println("Starting at: " + LocalDateTime.now()); List<String> passportData = Utils.getListFromFilename("input-day04.txt"); passportData.add(""); final String patternString = "(\\w+)\\:(\\#*\\w+)"; Pattern pattern = Pattern.compile(patternString); int validPassports = 0; Passport currentPassport = new Passport(); for (String line : passportData) { if (line.isEmpty()) { boolean isValid = isValidByPartNumber(currentPassport, partNumber); if (isValid) { validPassports++; // System.out.println(currentPassport); } currentPassport = new Passport(); } Matcher matcher = pattern.matcher(line); while (matcher.find()) { switch (matcher.group(1)) { case "byr": currentPassport.birthYear = Integer.valueOf(matcher.group(2)); break; case "iyr": currentPassport.issueYear = Integer.valueOf(matcher.group(2)); break; case "eyr": currentPassport.expirationYear = Integer.valueOf(matcher.group(2)); break; case "hgt": currentPassport.height = matcher.group(2); break; case "hcl": currentPassport.hairColor = matcher.group(2); break; case "ecl": currentPassport.eyeColor = matcher.group(2); break; case "pid": currentPassport.passportId = matcher.group(2); break; case "cid": currentPassport.countryId = Integer.valueOf(matcher.group(2)); break; default: System.out .println("unknown field: " + matcher.group(1) + ", content: " + matcher.group(2)); break; } } } System.out.println("valid passports: " + validPassports); long end = System.currentTimeMillis(); System.out.println("Finishing at: " + LocalDateTime.now()); System.out.println("Runtime: " + (end - start) + "ms"); } private static boolean isValidByPartNumber(Passport currentPassport, int partNumber) { if (partNumber == 1) return currentPassport.isValidPart1(); if (partNumber == 2) return currentPassport.isValidPart2(); throw new IllegalArgumentException("Invalid part number: " + partNumber); } private static class Passport { public Integer birthYear; public Integer issueYear; public Integer expirationYear; public String height; public String hairColor; public String eyeColor; public String passportId; public Integer countryId; public boolean isValidPart1() { if (this.birthYear != null && this.issueYear != null && this.expirationYear != null && this.height != null && this.hairColor != null && this.eyeColor != null && this.passportId != null) return true; return false; } public boolean isValidPart2() { if (!this.isValidPart1()) { return false; } else { if (this.birthYear < 1920 || this.birthYear > 2002) return false; if (this.issueYear < 2010 || this.issueYear > 2020) return false; if (this.expirationYear < 2020 || this.expirationYear > 2030) return false; // matching height final String patternString = "(^[0-9]{2,3})(cm$|in$)"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(this.height); if (!matcher.find()) return false; int heightNumber = Integer.parseInt(matcher.group(1)); String heightUnit = matcher.group(2); if (heightUnit.equals("cm") && (heightNumber < 150 || heightNumber > 193)) return false; if (heightUnit.equals("in") && (heightNumber < 59 || heightNumber > 76)) return false; // matching haircolor pattern = Pattern.compile("(^\\#[0-9a-f]{6}$)"); matcher = pattern.matcher(this.hairColor); if (!matcher.find()) return false; // matching eyecolor pattern = Pattern.compile("^(amb|blu|brn|gry|grn|hzl|oth)$"); matcher = pattern.matcher(this.eyeColor); if (!matcher.find()) return false; // matching passportNumber pattern = Pattern.compile("^[0-9]{9}$"); matcher = pattern.matcher(this.passportId); if (!matcher.find()) return false; return true; } } @Override public String toString() { return "Passport [birthYear=" + birthYear + ", issueYear=" + issueYear + ", expirationYear=" + expirationYear + ", height=" + height + "," + (height != null && height.length() == 4 ? " " : "") + " hairColor=" + hairColor + ", eyeColor=" + eyeColor + ", passportId=" + passportId + ", countryId=" + countryId + "]"; } } }
30.606557
99
0.560614
5c3cfb4a534bb8e16c262276e4a97b89d2c44140
369
package com.github.amatanhead.pcl.errors; /** * Error when processing user input. */ public class ProcessingError extends Exception { public ProcessingError() { super(); } public ProcessingError(String message) { super(message); } public ProcessingError(String message, Throwable cause) { super(message, cause); } }
19.421053
61
0.655827
a61d4a4ddcc73901438f97c4c11c96c035096b65
342
package com.fjx.mg.me.safe_center; public interface AuthType { int GESTURE = 2;//手势修改或者重置验证 int SECURITY_ISSUES = 3;//设置安全问题 int LOGIN_PASSWORD = 4;//扽里密码修改或者重置 int BIND_MOBILE = 5;//换绑手机 int PAY_PASSWORD = 6;//设置支付密码 int FINGERPRINT = 7;//指纹设置 int BIND_DEVICE = 8;//绑定设备 int FORGET_PASSWORD = 9;//忘记密码,重置 }
24.428571
39
0.669591
a215ff44dfcfe45cac502c7dbf0e14b41bd3c309
4,192
package com.smcpartners.shape.usecases.activate_user; import com.smcpartners.shape.crosscutting.security.RequestScopedUserId; import com.smcpartners.shape.crosscutting.security.annotations.SecureRequireActiveLogActivity; import com.smcpartners.shape.frameworks.data.dao.shape.UserDAO; import com.smcpartners.shape.shared.constants.SecurityRoleEnum; import com.smcpartners.shape.shared.dto.common.BooleanValueDTO; import com.smcpartners.shape.shared.dto.shape.UserDTO; import com.smcpartners.shape.shared.usecasecommon.IllegalAccessException; import com.smcpartners.shape.shared.usecasecommon.UseCaseException; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import java.util.logging.Level; import java.util.logging.Logger; /** * Responsible:</br> * 1.If its ADMIN then make the changes. If its ORG_ADMIN find the requesting users organization * and make sure the requesting users organization matches the target users organization</br * <p> * Created by johndestefano on 9/28/15. * </p> * <p> * Changes:<br> * 1. * </p> */ @RequestScoped public class ActivateUserServiceAdapter implements ActivateUserService, ActivateUserUCAdapter { @Inject private Logger log; @EJB private UserDAO userDAO; @Inject private RequestScopedUserId requestScopedUserId; private ActivateUserUC activateUserUC; /** * Default constructor */ public ActivateUserServiceAdapter() { } @PostConstruct protected void postConstruct() { this.activateUserUC = new ActivateUserUC(this); } /** * This method is protected so only Admin users can dao it and * it requires an active Admin user. * * @param targetUserId - The user to be activated * @throws UseCaseException * @see ActivateUserService */ @Override @SecureRequireActiveLogActivity({SecurityRoleEnum.ADMIN, SecurityRoleEnum.ORG_ADMIN}) public BooleanValueDTO activateUser(String targetUserId) throws UseCaseException { try { // Find the requesting users role SecurityRoleEnum reqUserRoleEnum = SecurityRoleEnum.valueOf(requestScopedUserId.getSecurityRole()); // If its ADMIN then make the changes // If its ORG_ADMIN find the requesting users organization // Make sure the requesting users organization matches the target users organization // Make the change if (reqUserRoleEnum == SecurityRoleEnum.ADMIN) { userDAO.activateUser(targetUserId); } else { // Its an org admin so only for there organization UserDTO targetUser = userDAO.findById(targetUserId); if (targetUser.getOrganizationId() == requestScopedUserId.getOrgId()) { userDAO.activateUser(targetUserId); } else { throw new IllegalAccessException(); } } return new BooleanValueDTO(true); } catch (Exception e) { log.logp(Level.SEVERE, this.getClass().getName(), "activateUser", e.getMessage(), e); throw new UseCaseException(e.getMessage()); } } @Override public SecurityRoleEnum getRequestingUsersRole() throws UseCaseException { try { String requestingUserId = requestScopedUserId.getRequestUserId(); UserDTO requestiongUserDTO = userDAO.findById(requestingUserId); return SecurityRoleEnum.valueOf(requestiongUserDTO.getRole()); } catch (Exception e) { log.logp(Level.SEVERE, this.getClass().getName(), "getRequestingUsersRole", e.getMessage(), e); throw new UseCaseException(e.getMessage()); } } @Override public void activateTargetUser(String targetUserId) throws UseCaseException { try { userDAO.activateUser(targetUserId); } catch (Exception e) { log.logp(Level.SEVERE, this.getClass().getName(), "activateTargetUser", e.getMessage(), e); throw new UseCaseException(e.getMessage()); } } }
36.137931
111
0.684399
35f7b9476d38d2d2b67952550a724ca01598341b
4,047
package com.laxmena.a478_editcontactapp; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Creaetd by Lakshmanan Meiyappan on 02/02/2021 */ public class MainActivity extends AppCompatActivity { private int REQUEST_CODE = 1; private final String TAG = "MainActivity"; private String userName = null; private int resultCode = RESULT_CANCELED; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); updateWelcomeText(); // Sets Welcome text in the MainActivity // First Button - Opens new activity Button fillNameBtn = (Button)findViewById(R.id.editUsername); fillNameBtn.setOnClickListener((View v) -> { openEditNameActivity(); }); //Second Button - Tries to create a new contact Button createContactBtn = (Button)findViewById(R.id.createContact); createContactBtn.setOnClickListener((View v) -> { createNewContact(); }); } private void openEditNameActivity() { // Create a new Intent to the second activity Intent intent = new Intent(this, EditName.class); startActivityForResult(intent, REQUEST_CODE); } private void createNewContact() { // Create Intent to contact with the valid username if(resultCode == RESULT_OK & isValidUserName()) { Intent contactInt = new Intent(ContactsContract.Intents.Insert.ACTION); contactInt.setType(ContactsContract.RawContacts.CONTENT_TYPE); contactInt.putExtra(ContactsContract.Intents.Insert.NAME, userName); startActivity(contactInt); resetValues(); } else if(resultCode == RESULT_CANCELED){ // Show error message as toast if no name is invalid if(isValidUserName()) Toast.makeText(getApplicationContext(), Const.TOAST_INVALID_NAME + userName, Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(), Const.TOAST_FILL_NAME, Toast.LENGTH_SHORT).show(); } } public void resetValues() { // This method is called when a new Contact is created, and the values need to be reset. userName = null; updateWelcomeText(); resultCode = RESULT_CANCELED; } private boolean isValidUserName() { // Checks if the username is valid. Returns boolean. // // FullName is fetched from EditName Activity and assigned to username // only if it passes the validation in the EditName Activity. return !(userName==null); } private void updateWelcomeText() { // Updates Welcome Text in the MainActivity // Customized Welcome text is displayed if valid username is available. TextView welcomeText = (TextView)findViewById(R.id.welcomeText); if(isValidUserName()) { welcomeText.setText(Const.WELCOME_TEXT+userName); } else { welcomeText.setText(Const.DEFAULT_WELCOME_TEXT); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(data == null) { resetValues(); return; } if(requestCode == REQUEST_CODE) { userName = data.getStringExtra(Const.FULL_NAME); this.resultCode = resultCode; if(resultCode == RESULT_CANCELED) { Toast.makeText(getApplicationContext(), Const.TOAST_INVALID_NAME + userName, Toast.LENGTH_SHORT).show(); } updateWelcomeText(); //Update welcome text } } }
36.459459
120
0.660983
314e7ddf17bc6678325dca93cf65ed9f24884a82
4,887
/* * 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.hop.pipeline.transforms.pipelineexecutor; import org.apache.hop.core.IRowSet; import org.apache.hop.core.RowMetaAndData; import org.apache.hop.core.row.IRowMeta; import org.apache.hop.core.row.IValueMeta; import org.apache.hop.pipeline.Pipeline; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.engine.IPipelineEngine; import org.apache.hop.pipeline.transform.BaseTransformData; import org.apache.hop.pipeline.transform.ITransformData; import java.util.List; /** * @author Matt * @since 18-mar-2013 */ public class PipelineExecutorData extends BaseTransformData implements ITransformData { private IPipelineEngine<PipelineMeta> executorPipeline; private PipelineMeta executorPipelineMeta; private IRowMeta inputRowMeta; private IRowMeta executorTransformOutputRowMeta; private IRowMeta resultRowsOutputRowMeta; private IRowMeta executionResultsOutputRowMeta; private IRowMeta resultFilesOutputRowMeta; public List<RowMetaAndData> groupBuffer; public int groupSize; public int groupTime; public long groupTimeStart; public String groupField; public int groupFieldIndex; public IValueMeta groupFieldMeta; public Object prevGroupFieldData; private IRowSet executorTransformOutputRowSet; private IRowSet resultRowsRowSet; private IRowSet resultFilesRowSet; private IRowSet executionResultRowSet; public PipelineExecutorData() { super(); } /** * Gets executorPipeline * * @return value of executorPipeline */ public IPipelineEngine<PipelineMeta> getExecutorPipeline() { return executorPipeline; } /** @param executorPipeline The executorPipeline to set */ public void setExecutorPipeline(IPipelineEngine<PipelineMeta> executorPipeline) { this.executorPipeline = executorPipeline; } public PipelineMeta getExecutorPipelineMeta() { return executorPipelineMeta; } public void setExecutorPipelineMeta(PipelineMeta executorPipelineMeta) { this.executorPipelineMeta = executorPipelineMeta; } public IRowMeta getInputRowMeta() { return inputRowMeta; } public void setInputRowMeta(IRowMeta inputRowMeta) { this.inputRowMeta = inputRowMeta; } public IRowMeta getExecutorTransformOutputRowMeta() { return executorTransformOutputRowMeta; } public void setExecutorTransformOutputRowMeta(IRowMeta executorTransformOutputRowMeta) { this.executorTransformOutputRowMeta = executorTransformOutputRowMeta; } public IRowMeta getResultRowsOutputRowMeta() { return resultRowsOutputRowMeta; } public void setResultRowsOutputRowMeta(IRowMeta resultRowsOutputRowMeta) { this.resultRowsOutputRowMeta = resultRowsOutputRowMeta; } public IRowMeta getExecutionResultsOutputRowMeta() { return executionResultsOutputRowMeta; } public void setExecutionResultsOutputRowMeta(IRowMeta executionResultsOutputRowMeta) { this.executionResultsOutputRowMeta = executionResultsOutputRowMeta; } public IRowMeta getResultFilesOutputRowMeta() { return resultFilesOutputRowMeta; } public void setResultFilesOutputRowMeta(IRowMeta resultFilesOutputRowMeta) { this.resultFilesOutputRowMeta = resultFilesOutputRowMeta; } public IRowSet getExecutorTransformOutputRowSet() { return executorTransformOutputRowSet; } public void setExecutorTransformOutputRowSet(IRowSet executorTransformOutputRowSet) { this.executorTransformOutputRowSet = executorTransformOutputRowSet; } public IRowSet getResultRowsRowSet() { return resultRowsRowSet; } public void setResultRowsRowSet(IRowSet resultRowsRowSet) { this.resultRowsRowSet = resultRowsRowSet; } public IRowSet getResultFilesRowSet() { return resultFilesRowSet; } public void setResultFilesRowSet(IRowSet resultFilesRowSet) { this.resultFilesRowSet = resultFilesRowSet; } public IRowSet getExecutionResultRowSet() { return executionResultRowSet; } public void setExecutionResultRowSet(IRowSet executionResultRowSet) { this.executionResultRowSet = executionResultRowSet; } }
30.54375
90
0.791692
9503b69b1ddebb3bc9d83a22d657987743633a18
373
package com.qidao.qidao.msg.msgMenu.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class MsgMenuFather { private Long id; private String name; private Long pid; private List<MsgMenuSon> sons; }
14.92
43
0.769437
17ab8716e055b9b4d9fd48be6daadd4f5fdfdce9
203
public class MyThread extends Thread{ @Override public void run() { super.run(); for (int i = 0;i <= 1000;i++){ System.out.println("分支线程-----> "+i); } } }
20.3
48
0.472906
3d43d838f33bd31a401376cd2eb9d2f6d82efe31
1,704
/* Foilen Infra Resource DNS https://github.com/foilen/foilen-infra-resource-dns Copyright (c) 2018 Foilen (http://foilen.com) The MIT License http://opensource.org/licenses/MIT */ package com.foilen.infra.resource.dns; import com.foilen.infra.plugin.v1.core.context.ChangesContext; import com.foilen.infra.plugin.v1.core.context.CommonServicesContext; import com.foilen.infra.plugin.v1.core.eventhandler.AbstractCommonMethodUpdateEventHandler; import com.foilen.infra.plugin.v1.core.eventhandler.CommonMethodUpdateEventHandlerContext; import com.foilen.infra.plugin.v1.core.exception.IllegalUpdateException; import com.foilen.infra.resource.dns.model.DnsEntryType; import com.foilen.infra.resource.machine.Machine; import com.foilen.smalltools.tools.StringTools; public class MachineUpdateHandler extends AbstractCommonMethodUpdateEventHandler<Machine> { @Override protected void commonHandlerExecute(CommonServicesContext services, ChangesContext changes, CommonMethodUpdateEventHandlerContext<Machine> context) { Machine resource = context.getResource(); if (context.getOldResource() != null && !StringTools.safeEquals(context.getOldResource().getName(), resource.getName())) { throw new IllegalUpdateException("You cannot change a Machine's name"); } context.getManagedResourceTypes().add(DnsEntry.class); if (resource.getPublicIp() != null) { // Use a DnsEntry context.getManagedResources().add(new DnsEntry(resource.getName(), DnsEntryType.A, resource.getPublicIp())); } } @Override public Class<Machine> supportedClass() { return Machine.class; } }
37.043478
153
0.748239
c751c3272b132ebd14b7627373a25b7f015d4c50
1,045
package com.lordjoe.ui.propertyeditor; import com.lordjoe.propertyeditor.*; /** * com.lordjoe.ui.propertyeditor.ICollectionEditorGenerator * factory for collection editors * @author Steve Lewis * @date Dec 15, 2007 */ public interface ICollectionEditorGenerator { public static ICollectionEditorGenerator[] EMPTY_ARRAY = {}; public static Class THIS_CLASS = ICollectionEditorGenerator.class; /** * this implementation says to nothing */ public static final ICollectionEditorGenerator NULL_GENERATOR = new NullCollectionEditorGenerator(); /** * make a suitable property edotir * @param p non-null property * @return non-null editor */ public IGenericPropertyEditor buildEditor(ICollectionWrapper p); public static class NullCollectionEditorGenerator implements ICollectionEditorGenerator { private NullCollectionEditorGenerator() {} public IGenericPropertyEditor buildEditor(ICollectionWrapper p) { return null; } } }
29.857143
92
0.717703
2e0e01167708cff51e28e735b97fdb704e4a4d1a
45
package P01_Jar_of_T; public class Main { }
9
21
0.755556
b236f83650d9688c2513ec30389d09019c5028df
628
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.logomotion.model.states.arm; /** * * @author CJ */ public class ShoulderState { public int lastPWMRight; public int lastPWMLeft; public double shoulderAngle; public String toString(){ String output = "/-----\n"; output += "Shoulder State\n"; output += "Last PWM Right: " + this.lastPWMRight + '\n'; output += "Last PWM Left: " + this.lastPWMLeft + '\n'; output += "Shoulder Angle: " + this.shoulderAngle + '\n'; return output; } }
22.428571
65
0.603503
f619b31f02608dee345b12b1fb7ce6b13f257dc3
2,059
package cn.bamboo.user.dao; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import cn.bamboo.user.domain.User; /** * 数据类 * * */ public class UserDao { private String path = "D:/users.xml";// 依赖数据文件 /** * 按用户名查询 * * @param username * @return */ public User findByUserName(String username) { /** * 1,得到Document 2,xpath查询 3,校验结果是否为null,如果为null,返回null * 4,如果不为null,需要把Elecment封装到User对象中 */ // 创建解析器 SAXReader reader = new SAXReader(); try { Document doc = reader.read(path); // 2,xpath查询得到Element Element ele = (Element) doc.selectSingleNode("//user[@username='" + username + "']"); if (ele == null) return null; // 把Element对象封装到User对象中 User user = new User(); user.setUsername(ele.attributeValue("username"));// 获取该元素名为username属性值 user.setPassword(ele.attributeValue("password"));// 该元素名为password属性 return user; } catch (DocumentException e) { throw new RuntimeException(e); } } /** * * @param user */ public void add(User user) { /** * 1,得到Document 2,通过Document得到root元素<users> 3,使用参数,转发成Element对象 * 4,把element添加到root元素中 5,保存Document */ // 创建解析器 SAXReader reader = new SAXReader(); try { Document doc = reader.read(path); // 得到根元素 Element root = doc.getRootElement(); // 通过根元素创建新元素 Element userEle = root.addElement("user"); // 设置属性 userEle.addAttribute("username", user.getUsername()); userEle.addAttribute("password", user.getPassword()); /** * 保存文档 */ OutputFormat format = new OutputFormat("\t", true);// 缩进使用\t,是否换行,是 format.setTrimText(true);// 清空原有的换行和缩进 // 创建XmlWriter XMLWriter writer = new XMLWriter(new OutputStreamWriter( new FileOutputStream(path), "utf-8"), format); writer.write(doc); writer.close(); } catch (Exception e) { throw new RuntimeException(e); } } }
22.877778
73
0.671685
9002a8d8fd40f29e4681caf1300a3a2123c1db22
6,516
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.aws.autoconfigure.cache; import java.lang.reflect.Field; import java.util.Arrays; import com.amazonaws.services.elasticache.AmazonElastiCache; import com.amazonaws.services.elasticache.model.CacheCluster; import com.amazonaws.services.elasticache.model.DescribeCacheClustersRequest; import com.amazonaws.services.elasticache.model.DescribeCacheClustersResult; import com.amazonaws.services.elasticache.model.Endpoint; import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpServer; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurer; import org.springframework.cloud.aws.autoconfigure.context.MetaDataServer; import org.springframework.cloud.aws.context.support.env.AwsCloudEnvironmentCheckUtils; import org.springframework.cloud.aws.core.env.stack.ListableStackResourceFactory; import org.springframework.cloud.aws.core.env.stack.StackResource; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; public class ElastiCacheAutoConfigurationTest { private AnnotationConfigApplicationContext context; @AfterClass public static void shutDownHttpServer() { MetaDataServer.shutdownHttpServer(); } @AfterClass public static void shutdownCacheServer() throws Exception { TestMemcacheServer.stopServer(); } @Before public void restContextInstanceDataCondition() throws IllegalAccessException { Field field = ReflectionUtils.findField(AwsCloudEnvironmentCheckUtils.class, "isCloudEnvironment"); assertThat(field).isNotNull(); ReflectionUtils.makeAccessible(field); field.set(null, null); } @After public void tearDown() throws Exception { this.context.close(); } @Test public void cacheManager_configuredMultipleCachesWithStack_configuresCacheManager() throws Exception { // Arrange HttpServer httpServer = MetaDataServer.setupHttpServer(); HttpContext instanceIdHttpContext = httpServer.createContext( "/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId")); this.context = new AnnotationConfigApplicationContext(); this.context.register(MockCacheConfigurationWithStackCaches.class); this.context.register(ElastiCacheAutoConfiguration.class); // Act this.context.refresh(); // Assert CacheManager cacheManager = this.context.getBean(CachingConfigurer.class) .cacheManager(); assertThat(cacheManager.getCacheNames().contains("sampleCacheOneLogical")) .isTrue(); assertThat(cacheManager.getCacheNames().contains("sampleCacheTwoLogical")) .isTrue(); assertThat(cacheManager.getCacheNames().size()).isEqualTo(2); httpServer.removeContext(instanceIdHttpContext); } @Test public void cacheManager_configuredNoCachesWithNoStack_configuresNoCacheManager() throws Exception { // Arrange HttpServer httpServer = MetaDataServer.setupHttpServer(); HttpContext instanceIdHttpContext = httpServer.createContext( "/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId")); this.context = new AnnotationConfigApplicationContext(); this.context.register(ElastiCacheAutoConfiguration.class); // Act this.context.refresh(); // Assert CacheManager cacheManager = this.context.getBean(CachingConfigurer.class) .cacheManager(); assertThat(cacheManager.getCacheNames().size()).isEqualTo(0); httpServer.removeContext(instanceIdHttpContext); } @Configuration public static class MockCacheConfigurationWithStackCaches { @Bean public AmazonElastiCache amazonElastiCache() { AmazonElastiCache amazonElastiCache = Mockito.mock(AmazonElastiCache.class); int port = TestMemcacheServer.startServer(); DescribeCacheClustersRequest sampleCacheOneLogical = new DescribeCacheClustersRequest() .withCacheClusterId("sampleCacheOneLogical"); sampleCacheOneLogical.setShowCacheNodeInfo(true); Mockito.when(amazonElastiCache.describeCacheClusters(sampleCacheOneLogical)) .thenReturn( new DescribeCacheClustersResult() .withCacheClusters( new CacheCluster() .withConfigurationEndpoint( new Endpoint() .withAddress( "localhost") .withPort(port)) .withEngine("memcached"))); DescribeCacheClustersRequest sampleCacheTwoLogical = new DescribeCacheClustersRequest() .withCacheClusterId("sampleCacheTwoLogical"); sampleCacheTwoLogical.setShowCacheNodeInfo(true); Mockito.when(amazonElastiCache.describeCacheClusters(sampleCacheTwoLogical)) .thenReturn( new DescribeCacheClustersResult() .withCacheClusters( new CacheCluster() .withConfigurationEndpoint( new Endpoint() .withAddress( "localhost") .withPort(port)) .withEngine("memcached"))); return amazonElastiCache; } @Bean public ListableStackResourceFactory stackResourceFactory() { ListableStackResourceFactory resourceFactory = Mockito .mock(ListableStackResourceFactory.class); Mockito.when( resourceFactory.resourcesByType("AWS::ElastiCache::CacheCluster")) .thenReturn(Arrays.asList( new StackResource("sampleCacheOneLogical", "sampleCacheOne", "AWS::ElastiCache::CacheCluster"), new StackResource("sampleCacheTwoLogical", "sampleCacheTwo", "AWS::ElastiCache::CacheCluster"))); return resourceFactory; } } }
35.221622
90
0.76903
9dd5230a5593b3c6e0b8969ec504df0c37d8bf5d
1,268
package com.hourglassapps.util; import java.io.Closeable; import java.util.Deque; import java.util.LinkedList; public class Closer implements AutoCloseable { private boolean mClosed=false; private Deque<AutoCloseable> mCloseables=new LinkedList<>(); /** * Adds an AutoCloseable instance to the end of our list of AutoCloseables. * @param pCloseable - if <code>null</code> nothing will be added. * @return this to allow chaining */ public Closer before(AutoCloseable pCloseable) { assert !closed(); if(pCloseable!=null) { mCloseables.addLast(pCloseable); } return this; } /** * Adds an AutoCloseable instance to the start of our list of AutoCloseables. * @param pCloseable - if <code>null</code> nothing will be added. * @return this to allow chaining */ public Closer after(AutoCloseable pCloseable) { assert !closed(); if(pCloseable!=null) { mCloseables.addFirst(pCloseable); } return this; } /** * Closes all AutoCloseable instance in same order that they were before'ed and */ @Override public void close() throws Exception { if(!closed()) { mClosed=true; AutoCloseable c; while((c=mCloseables.pollFirst())!=null) { c.close(); } } } public boolean closed() { return mClosed; } }
23.481481
80
0.701104
050d5d7c1f8357c1e39beed81cbc42d3ffd79a6b
243
/* * 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. */ module B { requires transitive A; exports pkgB; }
24.3
79
0.716049
83d36594acf993a5d1aaf1c0167412706584b893
2,846
package testPackage; import javax.ejb.*; /** * This is the bean class for the SalesTaxCodeTblBean enterprise bean. * Created Kdysi * @author Kdosi */ public abstract class SalesTaxCodeTblBean implements javax.ejb.EntityBean, testPackage.SalesTaxCodeTblLocalBusiness { private javax.ejb.EntityContext context; // <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click on the + sign on the left to edit the code."> // TODO Consider creating Transfer Object to encapsulate data // TODO Review finder methods /** * @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext) */ public void setEntityContext(javax.ejb.EntityContext aContext) { context = aContext; } /** * @see javax.ejb.EntityBean#ejbActivate() */ public void ejbActivate() { } /** * @see javax.ejb.EntityBean#ejbPassivate() */ public void ejbPassivate() { } /** * @see javax.ejb.EntityBean#ejbRemove() */ public void ejbRemove() { } /** * @see javax.ejb.EntityBean#unsetEntityContext() */ public void unsetEntityContext() { context = null; } /** * @see javax.ejb.EntityBean#ejbLoad() */ public void ejbLoad() { } /** * @see javax.ejb.EntityBean#ejbStore() */ public void ejbStore() { } // </editor-fold> public abstract java.lang.String getStateCode(); public abstract void setStateCode(java.lang.String stateCode); public abstract java.sql.Date getEffectDate(); public abstract void setEffectDate(java.sql.Date effectDate); public abstract java.math.BigDecimal getRate(); public abstract void setRate(java.math.BigDecimal rate); public abstract java.util.Collection getOrderTblBean(); public abstract void setOrderTblBean(java.util.Collection orderTblBean); public java.lang.String ejbCreate(java.lang.String stateCode, java.sql.Date effectDate, java.math.BigDecimal rate) throws javax.ejb.CreateException { if (stateCode == null) { throw new javax.ejb.CreateException("The field \"stateCode\" must not be null"); } if (effectDate == null) { throw new javax.ejb.CreateException("The field \"effectDate\" must not be null"); } // TODO add additional validation code, throw CreateException if data is not valid setStateCode(stateCode); setEffectDate(effectDate); setRate(rate); return null; } public void ejbPostCreate(java.lang.String stateCode, java.sql.Date effectDate, java.math.BigDecimal rate) { // TODO populate relationships here if appropriate } }
28.178218
154
0.634575
2e92ab003602cf5500c729af145f69c837cdb47c
3,791
package com.pavikumbhar.javaheart.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.pavikumbhar.javaheart.entity.UserInfo; @Controller public class ExcelFileUploadController { @Autowired ServletContext context; @RequestMapping(value = "/fileUpload", method = RequestMethod.GET) public String HelloWorld(Model model) { //model.addAttribute("lstUser", lstUser); model.addAttribute("message", "Welcome to Spring MVC"); model.addAttribute("css", "success"); return "fileUpload"; } @RequestMapping(value = "/processExcel", method = RequestMethod.POST) public String processExcel(Model model, @RequestParam("excelfile") MultipartFile excelfile) { try { List<UserInfo> lstUser = new ArrayList<>(); int i = 0; // Creates a workbook object from the uploaded excelfile HSSFWorkbook workbook = new HSSFWorkbook(excelfile.getInputStream()); // Creates a worksheet object representing the first sheet HSSFSheet worksheet = workbook.getSheetAt(0); // Reads the data in excel file until last row is encountered while (i <= worksheet.getLastRowNum()) { // Creates an object for the UserInfo Model UserInfo user = new UserInfo(); // Creates an object representing a single row in excel HSSFRow row = worksheet.getRow(i++); if(row.getRowNum() != 0){ // Sets the Read data to the model class user.setId((int) row.getCell(0).getNumericCellValue()); user.setUsername(row.getCell(1).getStringCellValue()); //user.setInputDate(row.getCell(2).getDateCellValue()); } // persist data into database in here lstUser.add(user); } workbook.close(); model.addAttribute("lstUser", lstUser); } catch (Exception e) { e.printStackTrace(); } return "fileUpload"; } @RequestMapping(value = "/fileUpload", method = RequestMethod.POST) public String processExcel2007(Model model, @RequestParam("excelfile2007") MultipartFile excelfile) { try { List<UserInfo> lstUser = new ArrayList<>(); int i = 0; // Creates a workbook object from the uploaded excelfile XSSFWorkbook workbook = new XSSFWorkbook(excelfile.getInputStream()); // Creates a worksheet object representing the first sheet XSSFSheet worksheet = workbook.getSheetAt(0); // Reads the data in excel file until last row is encountered while (i <= worksheet.getLastRowNum()) { // Creates an object for the UserInfo Model UserInfo user = new UserInfo(); // Creates an object representing a single row in excel XSSFRow row = worksheet.getRow(i++); if(row.getRowNum() != 0){ // Sets the Read data to the model class user.setId((int) row.getCell(0).getNumericCellValue()); user.setUsername(row.getCell(1).getStringCellValue()); //user.setInputDate(row.getCell(2).getDateCellValue()); }// persist data into database in here lstUser.add(user); } workbook.close(); model.addAttribute("lstUser", lstUser); } catch (Exception e) { e.printStackTrace(); } return "fileUpload"; } }
35.764151
104
0.72804