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
e338d08f75b37ce7f439d59cf6a9f75ada4c385e
3,831
/* ### * IP: GHIDRA * * 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 ghidra.feature.vt.gui.wizard; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import docking.widgets.OptionDialog; import ghidra.feature.vt.api.impl.VTSessionContentHandler; import ghidra.feature.vt.gui.task.SaveTask; import ghidra.framework.main.DataTreeDialog; import ghidra.framework.model.DomainFile; import ghidra.framework.model.DomainFileFilter; import ghidra.program.database.ProgramDB; import ghidra.util.HTMLUtilities; import ghidra.util.task.TaskLauncher; public class VTWizardUtils { private static class DomainFileBox { DomainFile df; } public static final DomainFileFilter VT_SESSION_FILTER = new DomainFileFilter() { @Override public boolean accept(DomainFile df) { if (VTSessionContentHandler.CONTENT_TYPE.equals(df.getContentType())) { return true; } return false; } }; public static final DomainFileFilter PROGRAM_FILTER = new DomainFileFilter() { @Override public boolean accept(DomainFile df) { if (ProgramDB.CONTENT_TYPE.equals(df.getContentType())) { return true; } return false; } }; static DomainFile chooseDomainFile(Component parent, String domainIdentifier, DomainFileFilter filter, DomainFile fileToSelect) { final DataTreeDialog dataTreeDialog = filter == null ? new DataTreeDialog(parent, "Choose " + domainIdentifier, DataTreeDialog.OPEN) : new DataTreeDialog(parent, "Choose " + domainIdentifier, DataTreeDialog.OPEN, filter); final DomainFileBox box = new DomainFileBox(); dataTreeDialog.addOkActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { box.df = dataTreeDialog.getDomainFile(); if (box.df == null) { return; } dataTreeDialog.close(); } }); dataTreeDialog.selectDomainFile(fileToSelect); dataTreeDialog.showComponent(); return box.df; } static public boolean askUserToSave(Component parent, DomainFile domainFile) { String filename = domainFile.getName(); int result = OptionDialog.showYesNoDialog(parent, "Save Version Tracking Changes?", "<html>Unsaved Version Tracking changes found for session: " + HTMLUtilities.escapeHTML(filename) + ". <br>" + "Would you like to save these changes?"); boolean doSave = result == OptionDialog.YES_OPTION; if (doSave) { SaveTask saveTask = new SaveTask(domainFile); new TaskLauncher(saveTask, parent); return saveTask.didSave(); } return false; } // returns false if the operation was cancelled or the user tried to save but it failed. static public boolean askUserToSaveBeforeClosing(Component parent, DomainFile domainFile) { String filename = domainFile.getName(); int result = OptionDialog.showYesNoCancelDialog(parent, "Save Version Tracking Changes?", "<html>Unsaved Version Tracking changes found for session: " + HTMLUtilities.escapeHTML(filename) + ". <br>" + "Would you like to save these changes?"); if (result == OptionDialog.CANCEL_OPTION) { return false; } boolean doSave = result == OptionDialog.YES_OPTION; if (doSave) { SaveTask saveTask = new SaveTask(domainFile); new TaskLauncher(saveTask, parent); return saveTask.didSave(); } return true; } }
32.193277
92
0.742365
5ef58b12ff296368dcfde6c9349d43e1bea18193
3,224
package com.company.payment.payment.model.repository; import java.util.List; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.company.payment.payment.model.Transaction; import com.company.payment.payment.model.TransactionStatus; import com.company.payment.payment.model.TransactionType; import com.company.payment.payment.model.dao.HibernateDao; @Repository public class TransactionRepository { @Value("${transaction.delete.interval}") private Integer transactionDeleteInterval; @Autowired private HibernateDao<Transaction> transactionDao; /** * Save or update transaction * * @param transaction */ @Transactional public void saveOrUpdate(Transaction transaction) { transactionDao.saveOrUpdate(transaction); } /** * Delete transaction * * @param transaction */ @Transactional public void delete(Transaction transaction) { transactionDao.delete(transaction); } /** * retrieve transaction by ReferenceId and merchantId * * @param referenceId * @param merchantId * @param type * @return */ @Transactional public Transaction getTransactionByReferenceId(String referenceId, Integer merchantId, TransactionType type) { Query<Transaction> query = transactionDao.getCurrentSession().createQuery( "FROM " + Transaction.class.getTypeName() + " WHERE reference_id = :reference_id " + " AND merchant_id = :merchant_id " + " AND type = :type " + " AND status = :status", Transaction.class); query.setParameter("reference_id", referenceId); query.setParameter("merchant_id", merchantId); query.setParameter("status", TransactionStatus.APPROVED); query.setParameter("type", type); List<Transaction> list = query.list(); if (list.size() > 0) { return list.get(0); } else { return null; } } /** * retrieve transaction by uuid and merchantId * * @param uuid * @param merchantId * @return */ @Transactional public Transaction getTransactionByUuid(String uuid, Integer merchantId, TransactionType type) { Query<Transaction> query = transactionDao.getCurrentSession() .createQuery( "FROM " + Transaction.class.getTypeName() + " WHERE uuid = :uuid " + " AND merchant_id = :merchant_id" + " AND type = :type " + " AND status = :status", Transaction.class); query.setParameter("uuid", uuid); query.setParameter("merchant_id", merchantId); query.setParameter("status", TransactionStatus.APPROVED); query.setParameter("type", type); List<Transaction> list = query.list(); if (list.size() > 0) { return list.get(0); } else { return null; } } /** * Delete old transactions * @return */ @Transactional public List<Transaction> getOldTransactions() { Query<Transaction> query = transactionDao.getCurrentSession().createQuery( "FROM " + Transaction.class.getTypeName() + " WHERE hour(sysdate() - create_date) >= :interval", Transaction.class); query.setParameter("interval", transactionDeleteInterval); return query.list(); } }
28.530973
111
0.728598
0ed8022afb8cf704b7941b11f0c6ccab15181af5
1,058
package 题库; import java.util.List; /** * 在经典汉诺塔问题中,有 3 根柱子及 N 个不同大小的穿孔圆盘,盘子可以滑入任意一根柱子。一开始,所有盘子自上而下按升序依次套在第一根柱子上(即每一个盘子只能放在更大的盘子上面)。移动圆盘时受到以下限制: * (1) 每次只能移动一个盘子; * (2) 盘子只能从柱子顶端滑出移到下一根柱子; * (3) 盘子只能叠在比它大的盘子上。 * * 请编写程序,用栈将所有盘子从第一根柱子移到最后一根柱子。 * * 你需要原地修改栈。 * * 示例1: * * 输入:A = [2, 1, 0], B = [], C = [] * 输出:C = [2, 1, 0] * 示例2: * * 输入:A = [1, 0], B = [], C = [] * 输出:C = [1, 0] * 提示: * * A中盘子的数目不大于14个。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/hanota-lcci * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class _面试题_08_06_汉诺塔问题 { public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) { hanoi(A.size(), A, B, C); } private void hanoi(int n, List<Integer> A, List<Integer> B, List<Integer> C) { if (n == 1) { move(A, C); return; } hanoi(n - 1, A, C, B); move(A, C); hanoi(n - 1, B, A, C); } private void move(List<Integer> from, List<Integer> to) { to.add(from.remove(from.size() - 1)); } }
20.745098
105
0.548204
df696c44ceefbb0aacb8c9b7ad930a9756149a31
3,496
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package desenho.formas; import controlador.Diagrama; import controlador.inspector.InspectorProperty; import desenho.linhas.PontoDeLinha; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Point; import java.awt.Shape; import java.util.ArrayList; /** * * @author ccandido */ public class FormaNaoRetangularDisformeBase extends FormaNaoRetangularBase { private static final long serialVersionUID = 4979116307999403371L; public FormaNaoRetangularDisformeBase(Diagrama modelo) { super(modelo); setTipo(TipoDePontos.tp4Pontos); } public FormaNaoRetangularDisformeBase(Diagrama modelo, String texto) { super(modelo, texto); setTipo(TipoDePontos.tp4Pontos); } @Override public Shape getRegiao() { return Regiao; } /** * Lados: 0 1 2 3 Default: 0,0 */ protected Point[] reposicionePonto = new Point[]{new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0)}; /** * eposicionePontoEsquerda reposicionePontoCima reposicionePontoDireita * reposicionePontoAbaixo Lados: 0 1 2 3 Default: -1 -1 -1 -1 = nenhum ponto * a ser movido. */ protected int[] ptsToMove = new int[]{-1, -1, -1, -1}; protected boolean shouldMove(int ldo) { if (ldo > 3 || ldo < 0) { return false; } return ptsToMove[ldo] > -1; } protected Point getReposicionePonto(int ldo) { //if (!shouldMove(ldo)) return new Point(0, 0); return reposicionePonto[ldo]; } @Override protected void Posicione4Pontos(PontoDeLinha ponto) { super.Posicione4Pontos(ponto); /* * +----1-----+ * | | * 0 2 * | | * +----3-----+ */ if (shouldMove(ponto.getLado())) { Point p = ponto.getCentro(); Point pM = getReposicionePonto(ponto.getLado()); ponto.setCentro(p.x + pM.x, p.y + pM.y); } } @Override protected void DoPaintDoks(Graphics2D g) { Point[] pts = getPontosColaterais(); Paint bkpP = g.getPaint(); g.setPaint(Color.yellow); for (int i = 0; i < pts.length; i++) { if (shouldMove(i)) { Point p = getReposicionePonto(i); g.fillRect(pts[i].x - 2 + p.x, pts[i].y - 2 + p.y, 4, 4); } else { g.fillRect(pts[i].x - 2, pts[i].y - 2, 4, 4); } } g.setPaint(bkpP); } private boolean mudarParaTextoLongo = true; public final void setMudarParaTextoLongo(boolean mudarParaTextoLongo) { this.mudarParaTextoLongo = mudarParaTextoLongo; } public boolean isMudarParaTextoLongo() { return mudarParaTextoLongo; } @Override public ArrayList<InspectorProperty> GenerateProperty() { ArrayList<InspectorProperty> res = super.GenerateProperty(); if (isMudarParaTextoLongo()) { InspectorProperty tmp = InspectorProperty.FindByProperty(res, "setTexto"); tmp.ReSetCaptionFromConfig("nometexto"); tmp.tipo = InspectorProperty.TipoDeProperty.tpTextoLongo; } return res; } }
28.892562
121
0.595252
25a5919ba423e2ec4d7e925858e2c500a011c8eb
4,292
package lab09.list; /** * An implementation of the List interface using a singly linked list of * Objects. * * @author Xiang Wei * @version 12/2/15 */ public class CS132SinglyLinkedList implements CS132List { private int size; private SinglyLinkedNode head; /** * Construct a new empty CS132SinglyLinkedList. */ public CS132SinglyLinkedList() { size = 0; head = null; } /* * Structure used to represent a node in the linked list. */ private static class SinglyLinkedNode { public SinglyLinkedNode next; public Object element; public SinglyLinkedNode(Object element) { this.element = element; next = null; } } @Override public int size() { return size; } @Override public void add(Object element) { SinglyLinkedNode toBeAdded = new SinglyLinkedNode(element); //there is nothing in the "list" so we just point head to the element that we are adding if(head == null) { head = toBeAdded; }// end if statement else { SinglyLinkedNode lastNode = this.getNodeAtIndex(size - 1); //set the last node's next to be the node that we want to add to the "list" lastNode.next = toBeAdded; }// end else statement //increase the size of the "list" every time we add to it size++; } @Override public Object get(int index) throws IndexOutOfBoundsException { this.checkForIndexOutOfBoundsException(index); if(index == 0) { return head.element; }// end if statement else { return this.getNodeAtIndex(index).element; }// end else statement } @Override public void set(int index, Object element) throws IndexOutOfBoundsException { this.checkForIndexOutOfBoundsException(index); if(index == 0) { head.element = element; }// if statement else { this.getNodeAtIndex(index).element = element; }//else statement } @Override public void insert(int index, Object element) throws IndexOutOfBoundsException { if (index < 0 || index > size) { throw new IndexOutOfBoundsException("Index " + index + " not a valid position"); }// end if statement SinglyLinkedNode toBeInsertedNode = new SinglyLinkedNode(element); //nothing is in the "list" so just put it there if(index == 0 && size == 0) { head = toBeInsertedNode; } //inserting at head but there's something already there else if(index == 0 && size!= 0) { toBeInsertedNode.next = head; head = toBeInsertedNode; }// end else if statement //inserting elsewhere in the of the "list" else { SinglyLinkedNode nodeBeforeIndex = this.getNodeAtIndex(index - 1); SinglyLinkedNode nodeAtIndex = this.getNodeAtIndex(index); toBeInsertedNode.next = nodeAtIndex; nodeBeforeIndex.next = toBeInsertedNode; }// end else statement //increase the size of the "list" since we've inserted a node size++; } @Override public Object remove(int index) throws IndexOutOfBoundsException { this.checkForIndexOutOfBoundsException(index); SinglyLinkedNode toBeRemovedNode = this.getNodeAtIndex(index); //removing at head if(index == 0) { head = toBeRemovedNode; }// end if statement //removing elsewhere in the "list" else { SinglyLinkedNode nodeBeforeToBeRemovedNode = this.getNodeAtIndex(index - 1); nodeBeforeToBeRemovedNode.next = toBeRemovedNode.next; }//end else statement //decrease the size since a node was removed from the "list" size--; return toBeRemovedNode.element; } /** * This helper method checks to see if the index in the Array will throw an * IndexOutOfBoundsException. * * @param index the index to check for in the Array */ private void checkForIndexOutOfBoundsException(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index " + index + " not a valid position in the Array"); }// end if statement } /** * This helper method returns the SinglyLinkedNode located at the specified index * @param index the index where the SinglyLinkedNode is located * @return the SinglyLinkednode located at index */ private SinglyLinkedNode getNodeAtIndex(int index) { SinglyLinkedNode curNode = head; // use a for loop to get to the last node in the "list" for(int i = 0; i < index; i++) { curNode = curNode.next; }// end for loop with counter return curNode; } }
25.099415
96
0.705033
b6665111960079a1cda6409b9d54373b6e04bdbd
10,248
/* * Copyright: (c) Mayo Foundation for Medical Education and * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the * triple-shield Mayo logo are trademarks and service marks of MFMER. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/lexevs-service/LICENSE.txt for details. */ package edu.mayo.cts2.framework.plugin.service.lexevs.service.resolvedvalueset; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.StringWriter; import java.util.HashSet; import java.util.Set; import javax.annotation.Resource; import javax.xml.transform.stream.StreamResult; import org.LexGrid.LexBIG.test.LexEvsTestRunner.LoadContent; import org.LexGrid.LexBIG.test.LexEvsTestRunner.LoadContents; import org.junit.Test; import edu.mayo.cts2.framework.core.xml.Cts2Marshaller; import edu.mayo.cts2.framework.model.command.Page; import edu.mayo.cts2.framework.model.command.ResolvedFilter; import edu.mayo.cts2.framework.model.core.URIAndEntityName; import edu.mayo.cts2.framework.model.core.ScopedEntityName; import edu.mayo.cts2.framework.model.directory.DirectoryResult; import edu.mayo.cts2.framework.model.entity.EntityDirectoryEntry; import edu.mayo.cts2.framework.model.service.core.EntityNameOrURI; import edu.mayo.cts2.framework.model.util.ModelUtils; import edu.mayo.cts2.framework.plugin.service.lexevs.test.AbstractTestITBase; import edu.mayo.cts2.framework.plugin.service.lexevs.utility.CommonTestUtils; import edu.mayo.cts2.framework.service.command.restriction.ResolvedValueSetResolutionEntityRestrictions; import edu.mayo.cts2.framework.service.meta.StandardMatchAlgorithmReference; import edu.mayo.cts2.framework.service.meta.StandardModelAttributeReference; import edu.mayo.cts2.framework.service.profile.resolvedvalueset.ResolvedValueSetResolutionService; import edu.mayo.cts2.framework.service.profile.resolvedvalueset.name.ResolvedValueSetReadId; import edu.mayo.cts2.framework.service.profile.valuesetdefinition.ResolvedValueSetResult; @LoadContents({ @LoadContent(contentPath = "lexevs/test-content/valueset/ResolvedAllDomesticAutosAndGM.xml"), @LoadContent(contentPath="lexevs/test-content/Automobiles.xml")}) public class LexEVSResolvedValuesetResolutionServiceTestIT extends AbstractTestITBase { @Resource private ResolvedValueSetResolutionService service; @Resource private Cts2Marshaller marshaller; // ---- Test methods ---- @Test public void testSetUp() { assertNotNull(this.service); } @Test public void testGetResolution() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); DirectoryResult<URIAndEntityName> dirResult = service.getResolution( identifier, null, new Page()); assertNotNull(dirResult); int expecting = 1; int actual = dirResult.getEntries().size(); assertEquals("Expecting " + expecting + " but got " + actual, expecting, actual); } @Test public void testGetResolutionNotFoundDefintion() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("__INVALID__")); DirectoryResult<URIAndEntityName> dirResult = service.getResolution( identifier, null, new Page()); assertNull(dirResult); } @Test public void testGetResolutionNotFoundDefintionValueSet() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("__INVALID__"), ModelUtils.nameOrUriFromName("571eb4e6")); DirectoryResult<URIAndEntityName> dirResult = service.getResolution( identifier, null, new Page()); assertNull(dirResult); } @Test public void testGetResolutionNotFoundId() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("__INVALID__", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); DirectoryResult<URIAndEntityName> dirResult = service.getResolution( identifier, null, new Page()); assertNull(dirResult); } @Test public void testGetResolutionEntitiesNoFilter() { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); DirectoryResult<EntityDirectoryEntry> dirResult = service.getEntities( identifier, null, null, new Page()); assertTrue(dirResult.getEntries().size() > 0); } @Test public void testGetResolutionEntitiesNoFilterValidXML() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); DirectoryResult<EntityDirectoryEntry> dirResult = service.getEntities( identifier, null, null, new Page()); assertTrue(dirResult.getEntries().size() > 0); for(EntityDirectoryEntry entry : dirResult.getEntries()){ StreamResult result = new StreamResult(new StringWriter()); marshaller.marshal(entry, result); } } @Test public void testGetResolutionEntitiesWithFilter() { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); Set<ResolvedFilter> filter = CommonTestUtils.createFilterSet(StandardModelAttributeReference.RESOURCE_NAME.getComponentReference(), StandardMatchAlgorithmReference.CONTAINS.getMatchAlgorithmReference(), "GM"); ResolvedValueSetResolutionQueryImpl query= new ResolvedValueSetResolutionQueryImpl(); query.setFilterComponent(filter); DirectoryResult<EntityDirectoryEntry> dirResult = service.getEntities( identifier, query, null, new Page()); assertTrue(dirResult.getEntries().size() > 0); } @Test public void testGetResolutionEntitiesWithEntityRestriction() { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); ResolvedValueSetResolutionQueryImpl query= new ResolvedValueSetResolutionQueryImpl(); ResolvedValueSetResolutionEntityRestrictions entityRestriction= new ResolvedValueSetResolutionEntityRestrictions(); EntityNameOrURI entity = new EntityNameOrURI(); ScopedEntityName scopedEntityName = new ScopedEntityName(); //scopedEntityName.setNamespace("Automobiles"); scopedEntityName.setName("GM"); entity.setEntityName(scopedEntityName); Set<EntityNameOrURI> entities= new HashSet<EntityNameOrURI>(); entities.add(entity); entityRestriction.setEntities(entities); query.setResolvedValueSetResolutionEntityRestrictions(entityRestriction); query.setResolvedValueSetResolutionEntityRestrictions(entityRestriction); DirectoryResult<EntityDirectoryEntry> dirResult = service.getEntities( identifier, query, null, new Page()); assertTrue(dirResult.getEntries().size() > 0); } @Test public void testGetResolutionValidXML() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); ResolvedValueSetResult<URIAndEntityName> dirResult = service.getResolution( identifier, null, new Page()); for (URIAndEntityName synopsis: dirResult.getEntries()) { StringWriter sw = new StringWriter(); StreamResult result= new StreamResult(sw); marshaller.marshal(synopsis, result); } } @Test public void testGetResolutionValidHasValidHeader() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); Set<ResolvedFilter> filter = CommonTestUtils.createFilterSet(StandardModelAttributeReference.RESOURCE_NAME.getComponentReference(), StandardMatchAlgorithmReference.CONTAINS.getMatchAlgorithmReference(), "GM"); ResolvedValueSetResult<URIAndEntityName> dirResult = service.getResolution( identifier, filter, new Page()); assertNotNull(dirResult.getResolvedValueSetHeader()); StreamResult result = new StreamResult(new StringWriter()); marshaller.marshal(dirResult.getResolvedValueSetHeader(), result); } @Test public void testGetResolutionHasCorrectHrefs() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); Set<ResolvedFilter> filter = CommonTestUtils.createFilterSet(StandardModelAttributeReference.RESOURCE_NAME.getComponentReference(), StandardMatchAlgorithmReference.CONTAINS.getMatchAlgorithmReference(), "GM"); ResolvedValueSetResult<URIAndEntityName> dirResult = service.getResolution( identifier, filter, new Page()); URIAndEntityName synopsis = dirResult.getEntries().get(0); String href = synopsis.getHref(); assertNotNull(href); assertEquals("http://localhost:8080/webapp/codesystem/Automobiles/version/1.0/entity/Automobiles:GM", href); } @Test public void testGetResolutionHasCorrectUri() throws Exception { ResolvedValueSetReadId identifier = new ResolvedValueSetReadId("1", ModelUtils.nameOrUriFromName("All Domestic Autos AND GM"), ModelUtils.nameOrUriFromName("571eb4e6")); Set<ResolvedFilter> filter = CommonTestUtils.createFilterSet(StandardModelAttributeReference.RESOURCE_NAME.getComponentReference(), StandardMatchAlgorithmReference.CONTAINS.getMatchAlgorithmReference(), "GM"); ResolvedValueSetResult<URIAndEntityName> dirResult = service.getResolution( identifier, filter, new Page()); URIAndEntityName synopsis = dirResult.getEntries().get(0); String uri = synopsis.getUri(); assertEquals("urn:oid:11.11.0.1:GM", uri); } }
38.965779
134
0.788154
26090765d2f01a866bb17805351c9e2bb5f0d6e2
318
package com.swayzetrain.inventory.common.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.swayzetrain.inventory.common.model.Role; public interface RoleRepository extends JpaRepository<Role, Long> { Role findByRoleid(Integer roleid); Role findByRolename(String rolename); }
24.461538
67
0.823899
ba31b253ff05d8a6a800c614d334d527e1ecc41e
2,091
package com.aimmac23.hub.videostorage; import java.io.InputStream; import com.aimmac23.hub.servlet.HubVideoInfoServlet; /** * An interface to describe a plugin which handles how we store videos. * * @author Alasdair Macmillan * */ public interface IVideoStore { /** * Store a video using this plugin. * * @param videoStream - an input stream for the video being streamed from the node. * @param contentLength - the length of the video stream, in bytes * @param mimeType - a mimetype for the video stream. * @param sessionId - the Selenium session ID which this video recorded. * @param sessionInfo - A bean representing information about the session that just ran. * @throws Exception if anything went wrong when trying to store the video. */ public void storeVideo(InputStream videoStream, long contentLength, String mimeType, String sessionId, SessionInfoBean sessionInfo) throws Exception; /** * Attempts to retrieve the video using this plugin. * * @param sessionId - The Selenium sessionId that the video recorded * @return a {@link StoredVideoDownloadContext} representing the video, even if it was not found. * @throws Exception if anything went wrong when trying to download the video. */ public StoredVideoDownloadContext retrieveVideo(String sessionId) throws Exception; /** * Retrieves abstract information about the video, which could include where the video is stored. * * @param sessionId - The Selenium sessionId that the video recorded * @return a {@link StoredVideoInfoContext} representing the video, even if it was not found. * @throws Exception if anything went wrong when trying to get information about the video. */ public StoredVideoInfoContext getVideoInformation(String sessionId) throws Exception; /** * Returns some sort of machine-readable string to help identify the storage mechanism * being used. This is used in the {@link HubVideoInfoServlet} * * @return A string identifier for the storage mechanism. Should be unique. */ public String getVideoStoreTypeIdentifier(); }
38.722222
104
0.755141
fcff9a9507b45f9e1c806a733f975fdf9dd6b503
621
package com.sparrow.bundle.framework.utils; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class IOUtil { public static String streamToString(InputStream is) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = -1; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } is.close(); return baos.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }
25.875
69
0.549114
03819251b2a69ec56fb28b38f9d6a8b029d2b829
16,312
package systemtests; import static org.junit.Assert.assertTrue; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX; import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_PARENT_COMMAND; import static seedu.address.logic.commands.person.PinCommand.MESSAGE_PIN_PERSON_SUCCESS; import static seedu.address.logic.commands.person.UnpinCommand.MESSAGE_UNPIN_PERSON_SUCCESS; import static seedu.address.testutil.TestUtil.getLastIndex; import static seedu.address.testutil.TestUtil.getUnpinPerson; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON; import static seedu.address.testutil.TypicalPersons.KEYWORD_MATCHING_MEIER; import java.util.List; import org.junit.Before; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.person.PinCommand; import seedu.address.logic.commands.person.UnpinCommand; import seedu.address.model.Model; import seedu.address.model.person.ReadOnlyPerson; import seedu.address.model.person.exceptions.PersonNotFoundException; //@@author Alim95 public class PinUnpinCommandSystemTest extends AddressBookSystemTest { private static final String MESSAGE_INVALID_PIN_COMMAND_FORMAT = String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, PinCommand.MESSAGE_USAGE); private static final String MESSAGE_INVALID_UNPIN_COMMAND_FORMAT = String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, UnpinCommand.MESSAGE_USAGE); @Before public void setParentMode() { executeParentCommand(); } @Test public void pinUnpin() { /* ----------------- Performing pin operation while an unfiltered list is being shown -------------------- */ /* Case: pin the first person in the list, command with leading spaces and trailing spaces -> pinned */ Model expectedModel = getModel(); String command = " " + PinCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + " "; ReadOnlyPerson pinnedPerson = pinPerson(expectedModel, INDEX_FIRST_PERSON); String expectedResultMessage = String.format(MESSAGE_PIN_PERSON_SUCCESS, pinnedPerson); assertPinCommandSuccess(command, expectedModel, expectedResultMessage); /* Case: pin the last person in the list -> pinned */ Model modelBeforePinningLast = getModel(); Index lastPersonIndex = getLastIndex(modelBeforePinningLast); assertPinCommandSuccess(lastPersonIndex); /* ----------------- Performing unpin operation while an unfiltered list is being shown -------------------- */ /* Case: unpin the first person in the list, command with leading spaces and trailing spaces -> unpinned */ expectedModel = getModel(); command = " " + UnpinCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + " "; ReadOnlyPerson unpinnedPerson = unpinPerson(expectedModel, INDEX_FIRST_PERSON); expectedResultMessage = String.format(MESSAGE_UNPIN_PERSON_SUCCESS, unpinnedPerson); assertUnpinCommandSuccess(command, expectedModel, expectedResultMessage); /* Case: unpin the last person in the list -> unpinned */ Model modelBeforeUnpinningLast = getModel(); lastPersonIndex = getLastIndex(modelBeforeUnpinningLast); assertUnpinCommandSuccess(lastPersonIndex); /* ------------------ Performing pin operation while a filtered list is being shown ---------------------- */ /* Case: filtered person list, pin index within bounds of address book and person list -> pinned */ showPersonsWithName(KEYWORD_MATCHING_MEIER); Index index = INDEX_FIRST_PERSON; assertTrue(index.getZeroBased() < getModel().getFilteredPersonList().size()); assertPinCommandSuccess(index); /* Case: filtered person list, pin index within bounds of address book but out of bounds of person list * -> rejected */ int invalidIndex = getModel().getAddressBook().getPersonList().size(); command = PinCommand.COMMAND_WORD + " " + invalidIndex; assertPinCommandFailure(command, MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); /* Case: filtered person list, pin person already pinned * -> rejected */ command = PinCommand.COMMAND_WORD + " 1"; assertPinCommandFailure(command, Messages.MESSAGE_PERSON_ALREADY_PINNED); /* ------------------ Performing unpin operation while a filtered list is being shown ---------------------- */ /* Case: filtered person list, pin index within bounds of address book and person list -> pinned */ showPersonsWithName(KEYWORD_MATCHING_MEIER); index = INDEX_FIRST_PERSON; assertTrue(index.getZeroBased() < getModel().getFilteredPersonList().size()); assertUnpinCommandSuccess(index); /* Case: filtered person list, pin index within bounds of address book but out of bounds of person list * -> rejected */ command = UnpinCommand.COMMAND_WORD + " " + invalidIndex; assertUnpinCommandFailure(command, MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); /* Case: filtered person list, unpin person not pinned * -> rejected */ command = UnpinCommand.COMMAND_WORD + " 1"; assertPinCommandFailure(command, Messages.MESSAGE_PERSON_ALREADY_UNPINNED); /* ---------------------------- Performing invalid pin and unpin operation ------------------------------- */ /* Case: invalid index (0) -> rejected */ command = PinCommand.COMMAND_WORD + " 0"; assertPinCommandFailure(command, MESSAGE_INVALID_PIN_COMMAND_FORMAT); command = UnpinCommand.COMMAND_WORD + " 0"; assertUnpinCommandFailure(command, MESSAGE_INVALID_UNPIN_COMMAND_FORMAT); /* Case: invalid index (-1) -> rejected */ command = PinCommand.COMMAND_WORD + " -1"; assertPinCommandFailure(command, MESSAGE_INVALID_PIN_COMMAND_FORMAT); command = UnpinCommand.COMMAND_WORD + " -1"; assertUnpinCommandFailure(command, MESSAGE_INVALID_UNPIN_COMMAND_FORMAT); /* Case: invalid index (size + 1) -> rejected */ Index outOfBoundsIndex = Index.fromOneBased( getModel().getAddressBook().getPersonList().size() + 1); command = PinCommand.COMMAND_WORD + " " + outOfBoundsIndex.getOneBased(); assertPinCommandFailure(command, MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); command = UnpinCommand.COMMAND_WORD + " " + outOfBoundsIndex.getOneBased(); assertUnpinCommandFailure(command, MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); /* Case: invalid arguments (alphabets) -> rejected */ assertPinCommandFailure(PinCommand.COMMAND_WORD + " abc", MESSAGE_INVALID_PIN_COMMAND_FORMAT); assertUnpinCommandFailure(UnpinCommand.COMMAND_WORD + " abc", MESSAGE_INVALID_UNPIN_COMMAND_FORMAT); /* Case: invalid arguments (extra argument) -> rejected */ assertPinCommandFailure(PinCommand.COMMAND_WORD + " 1 abc", MESSAGE_INVALID_PIN_COMMAND_FORMAT); assertUnpinCommandFailure(UnpinCommand.COMMAND_WORD + " 1 abc", MESSAGE_INVALID_UNPIN_COMMAND_FORMAT); /* Case: mixed case command word -> rejected */ assertPinCommandFailure("PiN 1", MESSAGE_UNKNOWN_PARENT_COMMAND); assertPinCommandFailure("uNPiN 1", MESSAGE_UNKNOWN_PARENT_COMMAND); } /** * Pins the {@code ReadOnlyPerson} at the specified {@code index} in {@code model}'s address book. * * @return the pinned person */ private ReadOnlyPerson pinPerson(Model model, Index index) { List<ReadOnlyPerson> lastShownList = model.getFilteredPersonList(); ReadOnlyPerson targetPerson = lastShownList.get(index.getZeroBased()); try { model.pinPerson(targetPerson); } catch (PersonNotFoundException pnfe) { throw new AssertionError("targetPerson is retrieved from model."); } return targetPerson; } /** * Pins the person at {@code toPin} by creating a default {@code PinCommand} using {@code toPin} and * performs the same verification as {@code assertPinCommandSuccess(String, Model, String)}. * * @see PinUnpinCommandSystemTest#assertPinCommandSuccess(String, Model, String) */ private void assertPinCommandSuccess(Index toPin) { Model expectedModel = getModel(); ReadOnlyPerson pinnedPerson = pinPerson(expectedModel, toPin); String expectedResultMessage = String.format(MESSAGE_PIN_PERSON_SUCCESS, pinnedPerson); assertPinCommandSuccess( PinCommand.COMMAND_WORD + " " + toPin.getOneBased(), expectedModel, expectedResultMessage); } /** * Executes {@code command} and in addition,<br> * 1. Asserts that the command box displays an empty string.<br> * 2. Asserts that the result display box displays {@code expectedResultMessage}.<br> * 3. Asserts that the model related components equal to {@code expectedModel}.<br> * 4. Asserts that the browser url and selected card remains unchanged.<br> * 5. Asserts that the status bar's sync status changes.<br> * 6. Asserts that the command box has the default style class.<br> * Verifications 1 to 3 are performed by * {@code AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model)}. * * @see AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model) */ private void assertPinCommandSuccess(String command, Model expectedModel, String expectedResultMessage) { assertPinCommandSuccess(command, expectedModel, expectedResultMessage, null); } /** * Performs the same verification as {@code assertPinCommandSuccess(String, Model, String)} * except that the browser url and selected card are expected to update accordingly depending * on the card at {@code expectedSelectedCardIndex}. * * @see PinUnpinCommandSystemTest#assertPinCommandSuccess(String, Model, String) * @see AddressBookSystemTest#assertSelectedCardChanged(Index) */ private void assertPinCommandSuccess(String command, Model expectedModel, String expectedResultMessage, Index expectedSelectedCardIndex) { executeCommand(command); assertApplicationDisplaysExpected("", expectedResultMessage, expectedModel); if (expectedSelectedCardIndex != null) { assertSelectedCardChanged(expectedSelectedCardIndex); } else { assertSelectedCardUnchanged(); } assertCommandBoxShowsDefaultStyle(); assertStatusBarUnchangedExceptSyncStatus(); } /** * Executes {@code command} and in addition,<br> * 1. Asserts that the command box displays {@code command}.<br> * 2. Asserts that result display box displays {@code expectedResultMessage}.<br> * 3. Asserts that the model related components equal to the current model.<br> * 4. Asserts that the browser url, selected card and status bar remain unchanged.<br> * 5. Asserts that the command box has the error style.<br> * Verifications 1 to 3 are performed by * {@code AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model)}.<br> * * @see AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model) */ private void assertPinCommandFailure(String command, String expectedResultMessage) { Model expectedModel = getModel(); executeCommand(command); assertApplicationDisplaysExpected(command, expectedResultMessage, expectedModel); assertSelectedCardUnchanged(); assertCommandBoxShowsErrorStyle(); assertStatusBarUnchanged(); } /** * Unpins the {@code ReadOnlyPerson} at the specified {@code index} in {@code model}'s address book. * * @return the unpinned person */ private ReadOnlyPerson unpinPerson(Model model, Index index) { ReadOnlyPerson targetPerson = getUnpinPerson(model, index); try { model.unpinPerson(targetPerson); } catch (PersonNotFoundException pnfe) { throw new AssertionError("targetPerson is retrieved from model."); } return targetPerson; } /** * Unpins the person at {@code toUnpin} by creating a default {@code UnpinCommand} using {@code toUnpin} and * performs the same verification as {@code assertUnpinCommandSuccess(String, Model, String)}. * * @see PinUnpinCommandSystemTest#assertUnpinCommandSuccess(String, Model, String) */ private void assertUnpinCommandSuccess(Index toUnpin) { Model expectedModel = getModel(); ReadOnlyPerson unpinnedPerson = unpinPerson(expectedModel, toUnpin); String expectedResultMessage = String.format(MESSAGE_UNPIN_PERSON_SUCCESS, unpinnedPerson); assertUnpinCommandSuccess( UnpinCommand.COMMAND_WORD + " " + toUnpin.getOneBased(), expectedModel, expectedResultMessage); } /** * Executes {@code command} and in addition,<br> * 1. Asserts that the command box displays an empty string.<br> * 2. Asserts that the result display box displays {@code expectedResultMessage}.<br> * 3. Asserts that the model related components equal to {@code expectedModel}.<br> * 4. Asserts that the browser url and selected card remains unchanged.<br> * 5. Asserts that the status bar's sync status changes.<br> * 6. Asserts that the command box has the default style class.<br> * Verifications 1 to 3 are performed by * {@code AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model)}. * * @see AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model) */ private void assertUnpinCommandSuccess(String command, Model expectedModel, String expectedResultMessage) { assertUnpinCommandSuccess(command, expectedModel, expectedResultMessage, null); } /** * Performs the same verification as {@code assertUnpinCommandSuccess(String, Model, String)} * except that the browser url and selected card are expected to update accordingly depending * on the card at {@code expectedSelectedCardIndex}. * * @see PinUnpinCommandSystemTest#assertUnpinCommandSuccess(String, Model, String) * @see AddressBookSystemTest#assertSelectedCardChanged(Index) */ private void assertUnpinCommandSuccess(String command, Model expectedModel, String expectedResultMessage, Index expectedSelectedCardIndex) { executeCommand(command); assertApplicationDisplaysExpected("", expectedResultMessage, expectedModel); if (expectedSelectedCardIndex != null) { assertSelectedCardChanged(expectedSelectedCardIndex); } else { assertSelectedCardUnchanged(); } assertCommandBoxShowsDefaultStyle(); assertStatusBarUnchangedExceptSyncStatus(); } /** * Executes {@code command} and in addition,<br> * 1. Asserts that the command box displays {@code command}.<br> * 2. Asserts that result display box displays {@code expectedResultMessage}.<br> * 3. Asserts that the model related components equal to the current model.<br> * 4. Asserts that the browser url, selected card and status bar remain unchanged.<br> * 5. Asserts that the command box has the error style.<br> * Verifications 1 to 3 are performed by * {@code AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model)}.<br> * * @see AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model) */ private void assertUnpinCommandFailure(String command, String expectedResultMessage) { Model expectedModel = getModel(); executeCommand(command); assertApplicationDisplaysExpected(command, expectedResultMessage, expectedModel); assertSelectedCardUnchanged(); assertCommandBoxShowsErrorStyle(); assertStatusBarUnchanged(); } }
49.280967
119
0.701385
73faa9284c997bc7ef027e9a9e6046e8a6ef51c7
594
package com.savethislittle.userinfo.repository.repository.springdatarepositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.savethislittle.userinfo.repository.entity.SumAmountExpensesMonthYear; import com.savethislittle.userinfo.repository.entity.SumAmountExpensesYear; @Repository public interface SumAmountExpensesYearSpringDataRepository extends JpaRepository<SumAmountExpensesYear, String>{ public List<SumAmountExpensesYear> findByEmailAndYear(String email, String year); }
33
113
0.86532
3d4b411ad472371484baf374e6f8af4962c906f2
275
package com.freedy.common.to; import lombok.Data; import java.math.BigDecimal; /** * @author Freedy * @date 2021/2/7 15:17 */ @Data public class SpuBoundTo { private Long SpuId; private BigDecimal buyBounds; private BigDecimal growBounds; }
16.176471
35
0.669091
a4d0cfa13794e2a1131c44fcec4dfadf73d1378f
6,316
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 DECL|package|org.apache.camel.component.rabbitmq package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|rabbitmq package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|Endpoint import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|EndpointInject import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|builder operator|. name|RouteBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|mock operator|. name|MockEndpoint import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class DECL|class|RabbitMQBasicIntTest specifier|public class|class name|RabbitMQBasicIntTest extends|extends name|AbstractRabbitMQIntTest block|{ comment|// Startup RabbitMQ via Docker (see readme.txt in camel-rabbitmq folder) annotation|@ name|EndpointInject argument_list|( literal|"rabbitmq:localhost:5672/foo?username=cameltest&password=cameltest" argument_list|) DECL|field|foo specifier|private name|Endpoint name|foo decl_stmt|; annotation|@ name|EndpointInject argument_list|( literal|"rabbitmq:localhost:5672/bar?username=cameltest&password=cameltest" argument_list|) DECL|field|bar specifier|private name|Endpoint name|bar decl_stmt|; annotation|@ name|EndpointInject argument_list|( literal|"mock:result" argument_list|) DECL|field|mock specifier|private name|MockEndpoint name|mock decl_stmt|; annotation|@ name|Override DECL|method|createRouteBuilder () specifier|protected name|RouteBuilder name|createRouteBuilder parameter_list|() throws|throws name|Exception block|{ return|return operator|new name|RouteBuilder argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|configure parameter_list|() throws|throws name|Exception block|{ name|from argument_list|( name|foo argument_list|) operator|. name|log argument_list|( literal|"FOO received: ${body}" argument_list|) operator|. name|to argument_list|( name|bar argument_list|) expr_stmt|; name|from argument_list|( name|bar argument_list|) operator|. name|log argument_list|( literal|"BAR received: ${body}" argument_list|) operator|. name|to argument_list|( name|mock argument_list|) operator|. name|transform argument_list|() operator|. name|simple argument_list|( literal|"Bye ${body}" argument_list|) expr_stmt|; block|} block|} return|; block|} annotation|@ name|Test DECL|method|sentBasicInOnly () specifier|public name|void name|sentBasicInOnly parameter_list|() throws|throws name|Exception block|{ name|mock operator|. name|expectedBodiesReceived argument_list|( literal|"World" argument_list|) expr_stmt|; name|log operator|. name|info argument_list|( literal|"Sending to FOO" argument_list|) expr_stmt|; name|template operator|. name|sendBody argument_list|( name|foo argument_list|, literal|"World" argument_list|) expr_stmt|; name|log operator|. name|info argument_list|( literal|"Sending to FOO done" argument_list|) expr_stmt|; name|mock operator|. name|assertIsSatisfied argument_list|() expr_stmt|; block|} annotation|@ name|Test DECL|method|sentBasicInOut () specifier|public name|void name|sentBasicInOut parameter_list|() throws|throws name|Exception block|{ name|mock operator|. name|expectedBodiesReceived argument_list|( literal|"World" argument_list|) expr_stmt|; name|log operator|. name|info argument_list|( literal|"Sending to FOO" argument_list|) expr_stmt|; name|String name|out init|= name|template operator|. name|requestBody argument_list|( name|foo argument_list|, literal|"World" argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; name|assertEquals argument_list|( literal|"Bye World" argument_list|, name|out argument_list|) expr_stmt|; name|log operator|. name|info argument_list|( literal|"Sending to FOO done" argument_list|) expr_stmt|; name|mock operator|. name|assertIsSatisfied argument_list|() expr_stmt|; block|} annotation|@ name|Test DECL|method|sentBasicInOutTwo () specifier|public name|void name|sentBasicInOutTwo parameter_list|() throws|throws name|Exception block|{ name|mock operator|. name|expectedBodiesReceived argument_list|( literal|"World" argument_list|, literal|"Camel" argument_list|) expr_stmt|; name|log operator|. name|info argument_list|( literal|"Sending to FOO" argument_list|) expr_stmt|; name|String name|out init|= name|template operator|. name|requestBody argument_list|( name|foo argument_list|, literal|"World" argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; name|assertEquals argument_list|( literal|"Bye World" argument_list|, name|out argument_list|) expr_stmt|; name|out operator|= name|template operator|. name|requestBody argument_list|( name|foo argument_list|, literal|"Camel" argument_list|, name|String operator|. name|class argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Bye Camel" argument_list|, name|out argument_list|) expr_stmt|; name|log operator|. name|info argument_list|( literal|"Sending to FOO done" argument_list|) expr_stmt|; name|mock operator|. name|assertIsSatisfied argument_list|() expr_stmt|; block|} block|} end_class end_unit
16.405195
810
0.799398
1c99a3abd4263183e149a071cb765a53807b1183
2,882
/* * File: PoissonBayesianEstimatorTest.java * Authors: Kevin R. Dixon * Company: Sandia National Laboratories * Project: Cognitive Foundry * * Copyright Dec 15, 2009, Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the U.S. Government. * Export of this program may require a license from the United States * Government. See CopyrightHistory.txt for complete details. * */ package gov.sandia.cognition.statistics.bayesian.conjugate; import gov.sandia.cognition.statistics.distribution.GammaDistribution; import gov.sandia.cognition.statistics.distribution.PoissonDistribution; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; /** * Unit tests for PoissonBayesianEstimatorTest. * * @author krdixon */ public class PoissonBayesianEstimatorTest extends ConjugatePriorBayesianEstimatorTestHarness<Number,Double,GammaDistribution> { /** * Tests for class PoissonBayesianEstimatorTest. * @param testName Name of the test. */ public PoissonBayesianEstimatorTest( String testName) { super(testName); } /** * Tests the constructors of class PoissonBayesianEstimatorTest. */ public void testConstructors() { System.out.println( "Constructors" ); PoissonBayesianEstimator f = new PoissonBayesianEstimator(); assertEquals( 1.0, f.getInitialBelief().getShape() ); assertEquals( 1.0, f.getInitialBelief().getScale() ); GammaDistribution g = new GammaDistribution( RANDOM.nextDouble() * 10.0, RANDOM.nextDouble() * 10.0 ); f = new PoissonBayesianEstimator( g ); assertSame( g, f.getInitialBelief() ); } @Override public PoissonBayesianEstimator createInstance() { double shape = RANDOM.nextDouble() * 10.0+10.0; double scale = 1.0; return new PoissonBayesianEstimator( new GammaDistribution( shape, scale ) ); } @Override public PoissonDistribution.PMF createConditionalDistribution() { double rate = RANDOM.nextDouble() * 10.0 + 10.0; return new PoissonDistribution.PMF( rate ); } @Override public void testKnownValues() { System.out.println( "Known Values" ); PoissonBayesianEstimator instance = new PoissonBayesianEstimator( new GammaDistribution( 6.25, 1.0/2.5 ) ); Collection<Number> values = new LinkedList<Number>( Arrays.asList( 3.0, 2.0, 0.0, 8.0, 2.0, 4.0, 6.0, 1.0 ) ); GammaDistribution result = instance.learn(values); System.out.println( "Gamma Mean: " + result.getMean() ); assertEquals( 32.25, result.getShape() ); assertEquals( 1.0/10.5, result.getScale() ); } }
30.659574
110
0.66898
cc52ccbc1569131998cd29f08d0683002fe8e60d
5,174
package org.egov.chat.service.valuefetch; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import org.egov.chat.config.JsonPointerNameConstants; import org.egov.chat.models.EgovChat; import org.egov.chat.models.Message; import org.egov.chat.repository.MessageRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.List; @Component public class ValueFetcher { @Autowired private ObjectMapper objectMapper; @Autowired List<ExternalValueFetcher> externalValueFetchers; @Autowired private MessageRepository messageRepository; public ArrayNode getAllValidValues(JsonNode config, JsonNode chatNode) { ArrayNode validValues = objectMapper.createArrayNode(); if (config.get("values").isArray()) { validValues = getValuesFromArrayNode(config); } else if (config.get("values").isObject()) { validValues = getValuesFromExternalSource(config, chatNode); } return validValues; } public String getCodeForValue(JsonNode config, EgovChat chatNode, String answer) { if (config.get("values").isArray()) { return answer; } else { ExternalValueFetcher externalValueFetcher = getExternalValueFetcher(config); JsonNode jsonNode = objectMapper.valueToTree(chatNode); ObjectNode params = createParamsToFetchValues(config, jsonNode); return externalValueFetcher.getCodeForValue(params, answer); } } public String getExternalLinkForParams(JsonNode config, EgovChat chatNode) { ExternalValueFetcher externalValueFetcher = getExternalValueFetcher(config); JsonNode jsonNode = objectMapper.valueToTree(chatNode); return externalValueFetcher.createExternalLinkForParams(createParamsToFetchValues(config, jsonNode)); } ArrayNode getValuesFromArrayNode(JsonNode config) { ArrayNode validValues = objectMapper.createArrayNode(); for (JsonNode jsonNode : config.get("values")) { ObjectNode value = objectMapper.createObjectNode(); value.put("value", jsonNode.asText()); validValues.add(value); } return validValues; } ArrayNode getValuesFromExternalSource(JsonNode config, JsonNode chatNode) { ExternalValueFetcher externalValueFetcher = getExternalValueFetcher(config); ObjectNode params = createParamsToFetchValues(config, chatNode); return externalValueFetcher.getValues(params); } ObjectNode createParamsToFetchValues(JsonNode config, JsonNode chatNode) { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); ObjectNode params = mapper.createObjectNode(); ObjectNode paramConfigurations = (ObjectNode) config.get("values").get("params"); Iterator<String> paramKeys = paramConfigurations.fieldNames(); while (paramKeys.hasNext()) { String key = paramKeys.next(); JsonNode paramValue; String paramConfiguration = paramConfigurations.get(key).asText(); if (paramConfiguration.substring(0, 1).equalsIgnoreCase("/")) { paramValue = chatNode.at(paramConfiguration); } else if (paramConfiguration.substring(0, 1).equalsIgnoreCase("~")) { String nodeId = paramConfiguration.substring(1); String conversationId = chatNode.at(JsonPointerNameConstants.conversationId).asText(); List<Message> messages = messageRepository.getValidMessagesOfConversation(conversationId); paramValue = TextNode.valueOf(findMessageForNode(messages, nodeId, chatNode)); } else { paramValue = TextNode.valueOf(paramConfiguration); } params.set(key, paramValue); } return params; } ExternalValueFetcher getExternalValueFetcher(JsonNode config) { String className = config.get("values").get("class").asText(); for (ExternalValueFetcher externalValueFetcher : externalValueFetchers) { if (externalValueFetcher.getClass().getName().equalsIgnoreCase(className)) return externalValueFetcher; } return null; } String findMessageForNode(List<Message> messages, String nodeId, JsonNode chatNode) { for (Message message : messages) { if (message.getNodeId().equalsIgnoreCase(nodeId)) { return message.getMessageContent(); } } //If nodeId isn't found in previously saved messages in DB //Try to find in the last received message if (chatNode.at("/message/nodeId").asText().equalsIgnoreCase(nodeId)) { return chatNode.at("/message/messageContent").asText(); } return null; } }
38.902256
109
0.691148
525b89835af89231eb06ceca98bd34fdf24ba8f2
5,057
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.test.hibernate.cache.commons.functional.cluster; import java.util.Map; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Environment; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.infinispan.test.hibernate.cache.commons.functional.AbstractFunctionalTest; import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup; import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider; import org.infinispan.test.hibernate.cache.commons.util.TxUtil; import org.junit.ClassRule; /** * @author Galder Zamarreño * @since 3.5 */ public abstract class DualNodeTest extends AbstractFunctionalTest { @ClassRule public static final InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup(); public static final String REGION_FACTORY_DELEGATE = "hibernate.cache.region.factory_delegate"; public static final String NODE_ID_PROP = "hibernate.test.cluster.node.id"; public static final String NODE_ID_FIELD = "nodeId"; public static final String LOCAL = "local"; public static final String REMOTE = "remote"; private SecondNodeEnvironment secondNodeEnvironment; protected void withTxSession(SessionFactory sessionFactory, TxUtil.ThrowingConsumer<Session, Exception> consumer) throws Exception { TxUtil.withTxSession(useJta, sessionFactory, consumer); } protected <T> T withTxSessionApply(SessionFactory sessionFactory, TxUtil.ThrowingFunction<Session, T, Exception> consumer) throws Exception { return TxUtil.withTxSessionApply(useJta, sessionFactory, consumer); } @Override protected String getBaseForMappings() { return "org/infinispan/test/"; } @Override public String[] getMappings() { return new String[] { "hibernate/cache/commons/functional/entities/Contact.hbm.xml", "hibernate/cache/commons/functional/entities/Customer.hbm.xml" }; } @Override @SuppressWarnings("unchecked") protected void addSettings(Map settings) { super.addSettings( settings ); applyStandardSettings( settings ); settings.put( NODE_ID_PROP, LOCAL ); settings.put( NODE_ID_FIELD, LOCAL ); settings.put( REGION_FACTORY_DELEGATE, TestRegionFactoryProvider.load().getRegionFactoryClass()); } @Override protected void cleanupTest() throws Exception { cleanupTransactionManagement(); } protected void cleanupTransactionManagement() { DualNodeJtaTransactionManagerImpl.cleanupTransactions(); DualNodeJtaTransactionManagerImpl.cleanupTransactionManagers(); } @Override public void startUp() { super.startUp(); // In some cases tests are multi-threaded, so they have to join the group infinispanTestIdentifier.joinContext(); secondNodeEnvironment = new SecondNodeEnvironment(); } @Override public void shutDown() { if ( secondNodeEnvironment != null ) { secondNodeEnvironment.shutDown(); } super.shutDown(); } protected SecondNodeEnvironment secondNodeEnvironment() { return secondNodeEnvironment; } protected void configureSecondNode(StandardServiceRegistryBuilder ssrb) { } @SuppressWarnings("unchecked") protected void applyStandardSettings(Map settings) { settings.put( Environment.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getClusterAwareClass().getName() ); } public class SecondNodeEnvironment { private StandardServiceRegistry serviceRegistry; private SessionFactoryImplementor sessionFactory; public SecondNodeEnvironment() { StandardServiceRegistryBuilder ssrb = constructStandardServiceRegistryBuilder(); applyStandardSettings( ssrb.getSettings() ); ssrb.applySetting( NODE_ID_PROP, REMOTE ); ssrb.applySetting( NODE_ID_FIELD, REMOTE ); configureSecondNode( ssrb ); serviceRegistry = ssrb.build(); MetadataSources metadataSources = new MetadataSources( serviceRegistry ); applyMetadataSources( metadataSources ); Metadata metadata = metadataSources.buildMetadata(); applyCacheSettings( metadata ); afterMetadataBuilt( metadata ); sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory(); } public StandardServiceRegistry getServiceRegistry() { return serviceRegistry; } public SessionFactoryImplementor getSessionFactory() { return sessionFactory; } public void shutDown() { if ( sessionFactory != null ) { try { sessionFactory.close(); } catch (Exception ignore) { } } if ( serviceRegistry != null ) { try { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } catch (Exception ignore) { } } } } }
31.02454
142
0.775756
3b89aaf88d8c9f226740418815453b93147d94e0
19,068
package com.nutiteq.advancedmap.activity; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; import org.mapsforge.map.reader.MapDatabase; import org.mapsforge.map.reader.header.FileOpenResult; import org.mapsforge.map.reader.header.MapFileInfo; import org.mapsforge.map.rendertheme.InternalRenderTheme; import org.mapsforge.map.rendertheme.XmlRenderTheme; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Path; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Toast; import android.widget.ZoomControls; import com.graphhopper.GHRequest; import com.graphhopper.GHResponse; import com.graphhopper.GraphHopper; import com.graphhopper.util.Helper; import com.graphhopper.util.Instruction; import com.graphhopper.util.InstructionList; import com.graphhopper.util.PointList; import com.graphhopper.util.StopWatch; import com.nutiteq.MapView; import com.nutiteq.advancedmap.R; import com.nutiteq.advancedmap.maplisteners.RouteMapEventListener; import com.nutiteq.components.Bounds; import com.nutiteq.components.Components; import com.nutiteq.components.MapPos; import com.nutiteq.components.Options; import com.nutiteq.filepicker.FilePickerActivity; import com.nutiteq.geometry.Geometry; import com.nutiteq.geometry.Line; import com.nutiteq.geometry.Marker; import com.nutiteq.log.Log; import com.nutiteq.projections.EPSG3857; import com.nutiteq.projections.Projection; import com.nutiteq.rasterlayers.RasterLayer; import com.nutiteq.services.routing.Route; import com.nutiteq.services.routing.RouteActivity; import com.nutiteq.style.LineStyle; import com.nutiteq.style.MarkerStyle; import com.nutiteq.style.StyleSet; import com.nutiteq.ui.DefaultLabel; import com.nutiteq.utils.UnscaledBitmapLoader; import com.nutiteq.vectorlayers.GeometryLayer; import com.nutiteq.vectorlayers.MarkerLayer; import com.nutiteq.datasources.raster.MapsforgeRasterDataSource; /** * * * Uses Graphhopper library to calculate offline routes * * Requires that user has downloaded Graphhopper data package to SDCARD. * * See https://github.com/nutiteq/hellomap3d/wiki/Offline-routing for details and downloads * * @author jaak * */ public class GraphhopperRouteActivity extends Activity implements FilePickerActivity, RouteActivity{ private MapView mapView; private GraphHopper gh; protected boolean errorLoading; protected boolean graphLoaded; protected boolean shortestPathRunning; private GeometryLayer routeLayer; private Marker startMarker; private Marker stopMarker; private MarkerStyle instructionUp; private MarkerStyle instructionLeft; private MarkerStyle instructionRight; private MarkerLayer instructionLayer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.enableAll(); Log.setTag("graphhopper"); // 1. Get the MapView from the Layout xml - mandatory mapView = (MapView) findViewById(R.id.mapView); // Optional, but very useful: restore map state during device rotation, // it is saved in onRetainNonConfigurationInstance() below Components retainObject = (Components) getLastNonConfigurationInstance(); if (retainObject != null) { // just restore configuration, skip other initializations mapView.setComponents(retainObject); // add event listener RouteMapEventListener mapListener = new RouteMapEventListener(this); mapView.getOptions().setMapListener(mapListener); return; } else { // 2. create and set MapView components - mandatory Components components = new Components(); mapView.setComponents(components); // add event listener RouteMapEventListener mapListener = new RouteMapEventListener(this); mapView.getOptions().setMapListener(mapListener); } // read filename from extras Bundle b = getIntent().getExtras(); String mapFilePath = b.getString("selectedFile"); // use mapsforge as offline base map XmlRenderTheme renderTheme = InternalRenderTheme.OSMARENDER; MapDatabase mapDatabase = new MapDatabase(); mapDatabase.closeFile(); File mapFile = new File("/" + mapFilePath); FileOpenResult fileOpenResult = mapDatabase.openFile(mapFile); if (fileOpenResult.isSuccess()) { Log.debug("MapsforgeRasterDataSource: MapDatabase opened ok: " + mapFilePath); } MapsforgeRasterDataSource dataSource = new MapsforgeRasterDataSource(new EPSG3857(), 0, 20, mapFile, mapDatabase, renderTheme, this.getApplication()); RasterLayer mapLayer = new RasterLayer(dataSource, mapFile.hashCode()); mapView.getLayers().setBaseLayer(mapLayer); // set initial map view camera from database MapFileInfo mapFileInfo = dataSource.getMapDatabase().getMapFileInfo(); if(mapFileInfo != null){ if(mapFileInfo.startPosition != null && mapFileInfo.startZoomLevel != null){ // start position is defined MapPos mapCenter = new MapPos(mapFileInfo.startPosition.longitude, mapFileInfo.startPosition.latitude,mapFileInfo.startZoomLevel); Log.debug("center: "+mapCenter); mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(mapCenter.x,mapCenter.y)); mapView.setZoom((float) mapCenter.z); }else if(mapFileInfo.boundingBox != null){ // start position not defined, but boundingbox is defined MapPos boxMin = mapView.getLayers().getBaseLayer().getProjection().fromWgs84(mapFileInfo.boundingBox.minLongitude, mapFileInfo.boundingBox.minLatitude); MapPos boxMax = mapView.getLayers().getBaseLayer().getProjection().fromWgs84(mapFileInfo.boundingBox.maxLongitude, mapFileInfo.boundingBox.maxLatitude); mapView.setBoundingBox(new Bounds(boxMin.x,boxMin.y,boxMax.x,boxMax.y), true); } } // open graph from folder. remove -gh and file name openGraph(mapFilePath.replace("-gh", "").substring(0,mapFilePath.replace("-gh", "").lastIndexOf("/"))); // routing layers routeLayer = new GeometryLayer(new EPSG3857()); mapView.getLayers().addLayer(routeLayer); // create markers for start & end, and a layer for them Bitmap olMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.olmarker); StyleSet<MarkerStyle> startMarkerStyleSet = new StyleSet<MarkerStyle>( MarkerStyle.builder().setBitmap(olMarker).setColor(Color.GREEN) .setSize(0.2f).build()); startMarker = new Marker(new MapPos(0, 0), new DefaultLabel("Start"), startMarkerStyleSet, null); StyleSet<MarkerStyle> stopMarkerStyleSet = new StyleSet<MarkerStyle>( MarkerStyle.builder().setBitmap(olMarker).setColor(Color.RED) .setSize(0.2f).build()); stopMarker = new Marker(new MapPos(0, 0), new DefaultLabel("Stop"), stopMarkerStyleSet, null); MarkerLayer markerLayer = new MarkerLayer(new EPSG3857()); mapView.getLayers().addLayer(markerLayer); markerLayer.add(startMarker); markerLayer.add(stopMarker); instructionLayer = new MarkerLayer(new EPSG3857()); mapView.getLayers().addLayer(instructionLayer); instructionUp = MarkerStyle.builder() .setBitmap(UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_up)) .build(); instructionLeft = MarkerStyle.builder() .setBitmap(UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_upthenleft)) .build(); instructionRight = MarkerStyle.builder() .setBitmap(UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_upthenright)) .build(); // rotation - 0 = north-up mapView.setMapRotation(0f); // tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed is 30 degrees. mapView.setTilt(90.0f); // Activate some mapview options to make it smoother - optional mapView.getOptions().setPreloading(true); mapView.getOptions().setSeamlessHorizontalPan(true); mapView.getOptions().setTileFading(true); mapView.getOptions().setKineticPanning(true); mapView.getOptions().setDoubleClickZoomIn(true); mapView.getOptions().setDualClickZoomOut(true); // set sky bitmap - optional, default - white mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP); mapView.getOptions().setSkyOffset(4.86f); mapView.getOptions().setSkyBitmap( UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.sky_small)); // Map background, visible if no map tiles loaded - optional, default - white mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP); mapView.getOptions().setBackgroundPlaneBitmap( UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.background_plane)); mapView.getOptions().setClearColor(Color.WHITE); // configure texture caching - optional, suggested mapView.getOptions().setTextureMemoryCacheSize(20 * 1024 * 1024); mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024); // define online map persistent caching - optional, suggested. Default - no caching mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath()); // set persistent raster cache limit to 100MB mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024); // 4. zoom buttons using Android widgets - optional // get the zoomcontrols that was defined in main.xml ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols); // set zoomcontrols listeners to enable zooming zoomControls.setOnZoomInClickListener(new View.OnClickListener() { public void onClick(final View v) { mapView.zoomIn(); } }); zoomControls.setOnZoomOutClickListener(new View.OnClickListener() { public void onClick(final View v) { mapView.zoomOut(); } }); } @Override protected void onStart() { mapView.startMapping(); super.onStart(); } @Override protected void onStop() { super.onStop(); mapView.stopMapping(); } @Override public void showRoute(final double fromLat, final double fromLon, final double toLat, final double toLon) { Log.debug("calculating path "+fromLat+","+fromLon+" to "+toLat+","+toLon); if(!graphLoaded){ Log.error("graph not loaded yet"); Toast.makeText(getApplicationContext(), "graph not loaded yet, cannot route", Toast.LENGTH_LONG).show(); return; } Projection proj = mapView.getLayers().getBaseLayer().getProjection(); stopMarker.setMapPos(proj.fromWgs84(toLon, toLat)); new AsyncTask<Void, Void, GHResponse>() { float time; protected GHResponse doInBackground(Void... v) { StopWatch sw = new StopWatch().start(); GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon) .setAlgorithm("dijkstrabi") .putHint("instructions", true) .putHint("douglas.minprecision", 1); GHResponse resp = gh.route(req); time = sw.stop().getSeconds(); return resp; } protected void onPostExecute(GHResponse res) { Log.debug("from:" + fromLat + "," + fromLon + " to:" + toLat + "," + toLon + " found path with distance:" + res.getDistance() / 1000f + ", nodes:" + res.getPoints().getSize() + ", time:" + time + " " + res.getDebugInfo()); Toast.makeText(getApplicationContext(), "the route is " + (int) (res.getDistance() / 100) / 10f + "km long, time:" + res.getMillis() / 60000f + "min, calculation time:" + time, Toast.LENGTH_LONG).show(); routeLayer.clear(); routeLayer.add(createPolyline(startMarker.getMapPos(), stopMarker.getMapPos(), res)); // add instruction markers instructionLayer.clear(); InstructionList instructions = res.getInstructions(); for(Instruction instruction : instructions){ Log.debug("name: "+instruction.getName() + " time: "+instruction.getTime() + " dist:" + Helper.round(instruction.getDistance(), 3) + " sign:"+ instruction.getSign() + " message: "+instruction.getAnnotation().getMessage() + " importance:"+instruction.getAnnotation().getImportance() ); instructionLayer.add(createRoutePoint( instruction.getPoints().getLongitude(0), instruction.getPoints().getLatitude(0), instruction.getName(), instruction.getTime(), Helper.round(instruction.getDistance(), 3), instruction.getSign())); } shortestPathRunning = false; } }.execute(); } protected Marker createRoutePoint(double lon, double lat, String name, long time, double distance, int indicator) { MarkerStyle style = null; String str = ""; switch(indicator){ case Instruction.FINISH: str = "finish"; break; case Instruction.TURN_SHARP_LEFT: case Instruction.TURN_LEFT: style = instructionLeft; str = "turn left"; break; case Instruction.TURN_SHARP_RIGHT: case Instruction.TURN_RIGHT: style = instructionRight; str = "turn right"; break; case Instruction.CONTINUE_ON_STREET: style = instructionUp; str = "continue"; break; case Instruction.REACHED_VIA: style = instructionUp; str = "stopover"; break; } if (!Helper.isEmpty(name)){ str += " to " + name; } Projection proj = mapView.getLayers().getBaseLayer().getProjection(); return new Marker(proj.fromWgs84(lon, lat), new DefaultLabel(str), style, null); } // creates Nutiteq line from GraphHopper response protected Line createPolyline(MapPos start, MapPos end, GHResponse response) { StyleSet<LineStyle> lineStyleSet = new StyleSet<LineStyle>(LineStyle.builder().setWidth(0.05f).setColor(Color.BLUE).build()); Projection proj = mapView.getLayers().getBaseLayer().getProjection(); int points = response.getPoints().getSize(); List<MapPos> geoPoints = new ArrayList<MapPos>(points+2); PointList tmp = response.getPoints(); geoPoints.add(start); for (int i = 0; i < points; i++) { geoPoints.add(proj.fromWgs84(tmp.getLongitude(i), tmp.getLatitude(i))); } geoPoints.add(end); String labelText = "" + (int) (response.getDistance() / 100) / 10f + "km, time:" + response.getMillis() / 60f + "min"; return new Line(geoPoints, new DefaultLabel("Route", labelText), lineStyleSet, null); } // opens GraphHopper graph file void openGraph(final String graphFile) { Log.debug("loading graph (" + graphFile + ") ... "); new AsyncTask<Void, Void, Path>() { protected Path doInBackground(Void... v) { try { GraphHopper tmpHopp = new GraphHopper().forMobile(); tmpHopp.setCHShortcuts("fastest"); tmpHopp.load(graphFile); Log.debug("found graph with " + tmpHopp.getGraph().getNodes() + " nodes"); gh = tmpHopp; graphLoaded = true; } catch (Throwable t) { Log.error(t.getMessage()); errorLoading = true; return null; } return null; } protected void onPostExecute(Path o) { if(graphLoaded) Toast.makeText(getApplicationContext(), "graph loaded, click on map to set route start and end", Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(), "graph loading problem", Toast.LENGTH_SHORT).show(); } }.execute(); } public MapView getMapView() { return mapView; } @Override public String getFileSelectMessage() { return "Select .map file in graphhopper graph (<mapname>_gh folder)"; } @Override public FileFilter getFileFilter() { return new FileFilter() { @Override public boolean accept(File file) { // accept only readable files if (file.canRead()) { if (file.isDirectory()) { // allow to select any directory return true; } else if (file.isFile() && file.getName().endsWith(".map")) { // accept files with given extension return true; } } return false; }; }; } @Override public void setStartMarker(MapPos startPos) { routeLayer.clear(); stopMarker.setVisible(false); startMarker.setMapPos(startPos); startMarker.setVisible(true); } @Override public void setStopMarker(MapPos pos) { stopMarker.setMapPos(pos); stopMarker.setVisible(true); } @Override public void routeResult(Route route) { // not used here, as Graphhopper routing is called from same application, // without using Route object and separate service class } }
40.312896
168
0.621145
80cfb865b7fb66a59263bd9a560143b20791ce56
305
package net.sourceforge.pmd.util.viewer.gui; /** * contains action command constants * * @author Boris Gruschko ( boris at gruschko.org ) */ public final class ActionCommands { public static final String COMPILE_ACTION = "Compile"; public static final String EVALUATE_ACTION = "Evaluate"; }
23.461538
60
0.734426
4bf4ed3c20e5a26c25db7c2c01b969d46e427c1f
4,815
/* * 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.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import javax.jcr.Node; import javax.jcr.Session; import org.apache.commons.lang.RandomStringUtils; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.junit.annotations.SlingAnnotationsTestRunner; import org.apache.sling.junit.annotations.TestReference; import org.apache.sling.models.factory.ModelFactory; import org.apache.sling.models.it.models.ConstructorInjectionTestModel; import org.apache.sling.models.it.models.FieldInjectionTestModel; import org.apache.sling.models.it.models.implextend.InvalidImplementsInterfacePropertyModel; import org.apache.sling.models.it.models.implextend.SampleServiceInterface; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(SlingAnnotationsTestRunner.class) public class ModelFactorySimpleTest { @TestReference private ResourceResolverFactory rrFactory; @TestReference private ModelFactory modelFactory; private String value; private ResourceResolver resolver; private Resource resource; private Node createdNode; @Before public void setUp() throws Exception { value = RandomStringUtils.randomAlphanumeric(10); resolver = rrFactory.getAdministrativeResourceResolver(null); Session session = resolver.adaptTo(Session.class); Node rootNode = session.getRootNode(); createdNode = rootNode.addNode("test_" + RandomStringUtils.randomAlphanumeric(10)); createdNode.setProperty("testProperty", value); session.save(); resource = resolver.getResource(createdNode.getPath()); } @After public void tearDown() throws Exception { if (createdNode != null) { createdNode.remove(); } if (resolver != null) { resolver.close(); } } @Test public void testCreateModel() { FieldInjectionTestModel model = modelFactory.createModel(resource, FieldInjectionTestModel.class); assertNotNull("Model is null", model); assertEquals("Test Property is not set correctly", value, model.getTestProperty()); assertNotNull("Filters is null", model.getFilters()); assertSame("Adaptable is not injected", resource, model.getResource()); } private static final class DummyClass { } @Test public void testIsModelClass() { assertTrue("Model is not detected as such", modelFactory.isModelClass(ConstructorInjectionTestModel.class)); assertFalse("Dummy class incorrectly detected as model class", modelFactory.isModelClass(DummyClass.class)); assertFalse("Model with invalid adaptable incorrectly detected as model class" , modelFactory.isModelClass(InvalidImplementsInterfacePropertyModel.class)); assertTrue("Model is not detected as such", modelFactory.isModelClass(SampleServiceInterface.class)); // being provided by two adapters } @Test public void testCanCreateFromAdaptable() { assertTrue("Model is not detected as such", modelFactory.canCreateFromAdaptable(resource, ConstructorInjectionTestModel.class)); assertTrue("Model is not detected as such", modelFactory.canCreateFromAdaptable(resource, SampleServiceInterface.class)); assertFalse("Model is incorrectly detected", modelFactory.canCreateFromAdaptable(new String(), ConstructorInjectionTestModel.class)); // invalid adaptable } @Test() public void testCanCreateFromAdaptableWithModelExceptin() { assertFalse("Model is incorrectly detected", modelFactory.canCreateFromAdaptable(resource, DummyClass.class)); // no model class } }
41.869565
163
0.752856
8c7c89b1fb5bd364cf91b198453e3aee759cdac5
116
package cn.wrh.android.preference.model; /** * @author bruce.wu * @date 2018/7/2 */ public class EmptyModel { }
12.888889
40
0.672414
6a31ce4071affe4caaacd04e8952b9a97938da62
1,968
// ----------------------------------------------------------------------- // <copyright file="ArtifactDeserializer.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.utils; import java.io.IOException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.microsoft.store.partnercenter.models.entitlements.Artifact; import com.microsoft.store.partnercenter.models.entitlements.ReservedInstanceArtifact; public class ArtifactDeserializer extends StdDeserializer<Artifact> { private static final long serialVersionUID = 2L; public ArtifactDeserializer() { this(null); } public ArtifactDeserializer(Class<?> vc) { super(vc); } @Override public Artifact deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = parser.readValueAsTree(); ObjectMapper mapper = (ObjectMapper)parser.getCodec(); ObjectReader reader = null; Object target = null; String artifcatType = node.get("artifactType").asText(); System.out.println(artifcatType); if(artifcatType.equalsIgnoreCase("reservedinstance")) { reader = mapper.readerFor(ReservedInstanceArtifact.class); } else { reader = mapper.readerFor(Artifact.class); } target = reader.readValue(node); return (Artifact)target; } }
32.262295
86
0.661585
f621c55467b4265449a4aa80eb06e16e592c36b2
481
package ru.yammi.module.misc; import ru.yammi.Yammi; import ru.yammi.config.Config; import ru.yammi.event.EventTarget; import ru.yammi.module.Category; import ru.yammi.module.Module; public class Panic extends Module { public Panic(){ super("Panic", Category.Misc, "Disable all modules"); } public void onEnable(){ for(Module module : Yammi.getInstance().getModules()){ module.setState(false); } Config.store(); } }
20.913043
62
0.656965
4c8eb8d40da2151a5454930776fc73fbdea87e50
668
package org.apache.spark.sql.columnar.compression; // no position private class LongDelta extends org.apache.spark.sql.columnar.compression.IntegralDelta<org.apache.spark.sql.catalyst.types.LongType$> implements scala.Product, scala.Serializable { static public int typeId () { throw new RuntimeException(); } static public boolean supports (org.apache.spark.sql.columnar.ColumnType<?, ?> columnType) { throw new RuntimeException(); } static protected long addDelta (long x, byte delta) { throw new RuntimeException(); } static protected scala.Tuple2<java.lang.Object, java.lang.Object> byteSizedDelta (long x, long y) { throw new RuntimeException(); } }
74.222222
182
0.770958
2d00a6c5bede3d63fafefb14a156f97b25451f7b
4,115
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package org.cratedb.action; import org.elasticsearch.cache.recycler.CacheRecycler; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.HandlesStreamInput; import java.io.IOException; import java.util.*; public class ReduceJobRequestContext { private final Map<UUID, ReduceJobContext> reduceJobs = new HashMap<>(); private final Map<UUID, List<BytesReference>> unreadStreams = new HashMap<>(); private final Object lock = new Object(); private final CacheRecycler cacheRecycler; public CacheRecycler cacheRecycler() { return cacheRecycler; } public ReduceJobRequestContext(CacheRecycler cacheRecycler) { this.cacheRecycler = cacheRecycler; } public ReduceJobContext get(UUID contextId) { synchronized (lock) { return reduceJobs.get(contextId); } } public void remove(UUID contextId) { reduceJobs.remove(contextId); } public void put(UUID contextId, ReduceJobContext status) throws IOException { List<BytesReference> bytesReferences; synchronized (lock) { reduceJobs.put(contextId, status); bytesReferences = unreadStreams.get(contextId); } if (bytesReferences != null) { for (BytesReference bytes : bytesReferences) { mergeFromBytesReference(bytes, status); } } } public void push(final SQLMapperResultRequest request) throws IOException { if (request.groupByResult != null) { request.status.merge(request.groupByResult); return; } synchronized (lock) { ReduceJobContext status = reduceJobs.get(request.contextId); if (request.failed) { status.countFailure(); return; } if (status == null) { List<BytesReference> bytesStreamOutputs = unreadStreams.get(request.contextId); if (bytesStreamOutputs == null) { bytesStreamOutputs = new ArrayList<>(); unreadStreams.put(request.contextId, bytesStreamOutputs); } bytesStreamOutputs.add(request.memoryOutputStream.bytes()); } else { mergeFromBytesReference(request.memoryOutputStream.bytes(), status); } } } private void mergeFromBytesReference(BytesReference bytesReference, ReduceJobContext status) throws IOException { SQLGroupByResult sqlGroupByResult = SQLGroupByResult.readSQLGroupByResult( status.parsedStatement, cacheRecycler, // required to wrap into HandlesStreamInput because it has a different readString() // implementation than BytesStreamInput alone. // the memoryOutputStream originates from a HandlesStreamOutput new HandlesStreamInput(new BytesStreamInput(bytesReference)) ); status.merge(sqlGroupByResult); } }
37.752294
117
0.677521
03efa224f1dd2f52f279f19154de95a6c6511ead
5,157
/* Galois, a framework to exploit amorphous data-parallelism in irregular programs. Copyright (C) 2010, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. File: IntGraph.java */ package galois.objects.graph; import galois.objects.GObject; /** * Interface used to represent graphs whose edges contain integer data. <br/> * Edges can be created <b>only</b> by invoking {@link ObjectGraph#addEdge}: invocations of * {@link Graph#addNeighbor(GNode, GNode)} will result in a exception, because no edge data has been specified. * * @param <N> the type of the object stored in each node */ public interface IntGraph<N extends GObject> extends Graph<N> { /** * Adds an edge to the graph containing the specified data. * * <p> * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * </p> * * @param src the source node of the edge * @param dst the destination node of the edge * @param data information to be stored in the new edge * @return true if there was no previous edge between the two nodes */ public boolean addEdge(GNode<N> src, GNode<N> dst, int data); /** * Adds an edge to the graph containing the specified data. * * @param src the source node of the edge * @param dst the destination node of the edge * @param data information to be stored in the new edge * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return true if there was no previous edge between the two nodes */ public boolean addEdge(GNode<N> src, GNode<N> dst, int data, byte flags); /** * Retrieves the data associated with an edge. * <p> * Be aware that this method will return -1 in two cases: * </p> * * <ul> * <li> there is no edge between the two nodes * <li> there is an edge between the two nodes, and its data is -1 * </ul> * <p> * In order to distinguish between the two cases, use {@link Graph#hasNeighbor(GNode, GNode)} * </p> * <p> * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * </p> * @param src the source node of the edge * @param dst the destination node of the edge * @return the data associated with the edge, or -1 if the edge does not exist */ public int getEdgeData(GNode<N> src, GNode<N> dst); /** * Retrieves the data associated with an edge. * <p> * Be aware that this method will return -1 in two cases: * </p> * <ul> * <li> there is no edge between the two nodes * <li> there is an edge between the two nodes, and its data is -1 * </ul> * <p> * In order to distinguish between the two cases, use {@link Graph#hasNeighbor(GNode, GNode)} * </p> * * @param src the source node of the edge * @param dst the destination node of the edge * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the data associated with the edge, or -1 if the edge does not exist */ public int getEdgeData(GNode<N> src, GNode<N> dst, byte flags); /** * Sets the data associated with an edge. * * <p> * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * </p> * * @param src the source node of the edge * @param dst the destination node of the edge * @param d the data to associate with the edge * @return the data previously associated with the edge, or -1 if the edge does not exist */ public int setEdgeData(GNode<N> src, GNode<N> dst, int d); /** * Sets the data associated with an edge. * * @param src the source node of the edge * @param dst the destination node of the edge * @param d the data to associate with the edge * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the data previously associated with the edge, or -1 if the edge does not exist */ public int setEdgeData(GNode<N> src, GNode<N> dst, int d, byte flags); }
39.068182
111
0.695172
67a8e28a1fa5149144b0e18e810202f12ddf2204
4,824
package com.github.lixiang2114.netty.context; import java.io.File; import java.nio.charset.Charset; import com.github.lixiang2114.netty.servlet.DefaultAction; import com.github.lixiang2114.netty.servlet.Servlet; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.MessageSizeEstimator; import io.netty.channel.RecvByteBufAllocator; import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory; import io.netty.handler.codec.http.multipart.HttpDataFactory; /** * @author Lixiang * @description Http服务器配置 */ public class ServerConfig { /** * 发送数据包的Qos选项 */ public Integer qos; /** * 服务端是否需要在读取完数据之后自动进行下次读取 * 默认值为true */ public Boolean autoRead; /** * Http服务端口 */ public Integer port=8080; /** * 服务端通道接收缓冲区大小 */ public Integer serverRcvBuf; /** * 客户端通道接收缓冲区大小 */ public Integer clientRcvBuf; /** * 客户端通道发送缓冲区大小 */ public Integer clientSndBuf; /** * Servlet应用配置 */ public Object servletConfig; /** * Http服务是否启动 */ public Boolean started=false; /** * 客户端通道关闭模式 * -1:close方法无阻塞,立即返回,同时操作系统将数据发送到对端 * 0:close方法无阻塞,立即返回,操作系统放弃通道缓冲区中的数据,直接向对端发送RST包,对端收到复位错误 * 正整数:阻塞电泳close方法的线程,直到延迟时间到或发送缓冲区中的数据发送完毕,若超时,则对端会收到复位错误 */ public Integer closeMode=-1; /** * 是否支持半关闭 * 设置为false表示在对端关闭通道后,本地端也同步将连接关闭,设置为true表示不关闭本地端连接, * 而是触发ChannelInboundHandler的userEventTriggered()方法,事件为ChannelInputShutdownEvent */ public Boolean halfClose=false; /** * 是否允许地址复用 * 设置为true表示不同的进程可以不同的IP地址绑定相同的端口 */ public Boolean reuseAddr=true; /** * 是否与客户端保持长连接 * 若设置为false则表示在每次接收完请求后便断开连接通道 */ public Boolean isKeepLive=true; /** * 是否启用TCP缓冲 * 缓冲是以延时为代价换取更少的数据包IO频次以优化网络效率,从而提升吞吐量 */ public Boolean tcpNoDelay=true; /** * 服务端上报超时时间(单位:毫秒) * 某些场景下也表示接收数据超时时间,默认值为0表示无限期等待, * 若设置一个非负整数值,则在等待时间超过该值时抛出SocketTimeoutException,但输入流并未关闭,可以继续读取数据 */ public Integer readTimeoutMills; /** * ByteBuf缓冲区分配器 * 默认实现为PooledByteBufAllocator */ public ByteBufAllocator allocator; /** * IO连接池最大队列尺寸 * 超过此尺寸后,新进入的客户端连接将被丢弃 */ public Integer maxQueueSize=1024; /** * 写缓冲区高水位标记点 */ public Integer writeBufferHigMark; /** * 写缓冲区低水位标记点 */ public Integer writeBufferLowMark; /** * Web应用服务器会话跟踪标识 */ public String sessionId="JSESSIONID"; /** * Servlet是否为单例全局共享 * 单例:全局共享同一个实例 * 多例:实例粒度到请求级别 */ public boolean servletSingleton=true; /** * 会话过期时间(单位:毫秒) * 默认30分钟(半小时) */ public long sessionExpire=30*60*1000L; /** * 客户端下发超时时间(单位:毫秒) * 某些场景下也表示发送数据超时时间 */ public Integer connTimeoutMills=30000; /** * 服务端Worker线程每次循环执行的最大写次数 * 默认值为16次,超过该次数则放入下次循环中去写,以留给其它客户端通道执行写操作的机会, * 该值设置得越大,则客户端通道以更大的延时为代价换取更大的吞吐量;反之,以更小的吞吐量换取更快的实时效率 */ public Integer maxWriteTimesPerLoop=16; /** * Http协议数据工厂 */ private DefaultHttpDataFactory dataFactory; /** * 客户端每次读取消息的最大数量 */ public Integer clientMaxMsgNumPerRead=1; /** * 服务端每次读取消息的最大数量 */ public Integer serverMaxMsgNumPerRead=16; /** * 每次请求的最大消息体尺寸(单位:字节),默认1MB */ public Integer maxContentLength=1024*1024; /** * Http消息体存在于内存中的最大尺寸(默认12MB) * 超过该尺寸将通过磁盘缓冲 */ public long maxDataSizeInMemory=0XC00000; /** * 会话调度初始延迟时间(单位:毫秒) */ public long sessionSchedulerInitDelay=15000L; /** * 接收缓冲区分配器 * 默认值为AdaptiveRecvByteBufAllocator.DEFAULT */ public RecvByteBufAllocator recvBufAllocator; /** * 消息尺寸大小估算器 * 默认值为DefaultMessageSizeEstimator.DEFAULT,用于估算ByteBuf、ByteBufHolder和FileRegion的大小 * 其中ByteBuf和ByteBufHolder为实际大小,FileRegion估算值为0,该值估算的字节数在计算水位时使用, * FileRegion为0可知FileRegion不影响高低水位 */ public MessageSizeEstimator msgSizeEsimator; /** * Http服务器消息编码类型 */ public Charset charset=Charset.defaultCharset(); /** * 会话调度间隔(上一次结束到下一次开始)时间(单位:毫秒) */ public long sessionSchedulerIntervalMillis=120000L; /** * 核心Servlet组件(全局共享) */ public Class<? extends Servlet> servletClass=DefaultAction.class; /** * Multipart中上传文件存储目录 */ public File uploadDirectory=new File(System.getProperty("user.dir")); public synchronized HttpDataFactory dataFactory() { if(null!=dataFactory) return dataFactory; return dataFactory=new DefaultHttpDataFactory(maxDataSizeInMemory); } public ServerConfig(){} public ServerConfig(int port){ this.port=port; } public ServerConfig(Class<? extends Servlet> servletClass){ this.servletClass=servletClass; } public ServerConfig(int port,Class<? extends Servlet> servletClass){ this.port=port; this.servletClass=servletClass; } public ServerConfig(Object servletConfig,Class<? extends Servlet> servletClass){ this.servletClass=servletClass; this.servletConfig=servletConfig; } public ServerConfig(int port,Object servletConfig,Class<? extends Servlet> servletClass){ this.port=port; this.servletClass=servletClass; this.servletConfig=servletConfig; } }
19.296
90
0.732794
ef0f3f8afbfd278989661c03562dc678be48c220
2,605
package fr.insee.vtl.engine.visitors.expression; import fr.insee.vtl.engine.exceptions.InvalidTypeException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ConditionalExprTest { private ScriptEngine engine; @BeforeEach public void setUp() { engine = new ScriptEngineManager().getEngineByName("vtl"); } @Test public void testNull() throws ScriptException { engine.eval("a := if null then \"true\" else \"false\";"); assertThat((Boolean) engine.getContext().getAttribute("a")).isNull(); engine.eval("b := if true then null else \"false\";"); assertThat((Boolean) engine.getContext().getAttribute("b")).isNull(); engine.eval("c := if false then \"true\" else null;"); assertThat((Boolean) engine.getContext().getAttribute("c")).isNull(); } @Test public void testIfExpr() throws ScriptException { ScriptContext context = engine.getContext(); engine.eval("s := if true then \"true\" else \"false\";"); assertThat(context.getAttribute("s")).isEqualTo("true"); engine.eval("l := if false then 1 else 0;"); assertThat(context.getAttribute("l")).isEqualTo(0L); } @Test public void testNvlExpr() throws ScriptException { ScriptContext context = engine.getContext(); engine.eval("s := nvl(\"toto\", \"default\");"); assertThat(context.getAttribute("s")).isEqualTo("toto"); engine.eval("s := nvl(null, \"default\");"); assertThat(context.getAttribute("s")).isEqualTo("default"); assertThatThrownBy(() -> { engine.eval("s := nvl(3, \"toto\");"); }).isInstanceOf(InvalidTypeException.class) .hasMessage("invalid type String, expected \"toto\" to be Long"); } @Test public void testIfTypeExceptions() { assertThatThrownBy(() -> { engine.eval("s := if \"\" then 1 else 2;"); }).isInstanceOf(InvalidTypeException.class) .hasMessage("invalid type String, expected \"\" to be Boolean"); assertThatThrownBy(() -> { engine.eval("s := if true then \"\" else 2;"); }).isInstanceOf(InvalidTypeException.class) .hasMessage("invalid type Long, expected 2 to be String"); } }
37.753623
81
0.639923
304084450345a137a40c71789a106acecd43098d
842
package com.evil.cbs_ticketvalidator.util; import android.content.Context; public class ErrorDialogPresenter { private final Context context; private final String title; private final String message; public ErrorDialogPresenter(Context context, String title, String message) { this.context = context; this.title = title; this.message = message; } public void showDialog() { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context); builder.setMessage(message) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(title) .setCancelable(false) .setPositiveButton("OK", (dialog, which) -> { dialog.dismiss(); }) .show(); } }
30.071429
95
0.612827
3d159526d4be42b1747a587e12486d4724a97527
1,355
package com.siakad.modul_penilaian.repository; import java.util.List; import java.util.UUID; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.sia.modul.domain.NilaiKuisioner; @Transactional @Repository public class NilaiKuisionerRepositoryImpl implements NilaiKuisionerRepository { @Autowired private SessionFactory sessionFactory; @Override public UUID insert(NilaiKuisioner nilaiKuisioner) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); UUID insertId = (UUID) session.save(nilaiKuisioner); tx.commit(); session.flush(); session.close(); return insertId; } @Override public List<NilaiKuisioner> getByPembPertanyaan(UUID idPemb, UUID idPertanyaan) { // TODO Auto-generated method stub String queryString = "SELECT nk FROM NilaiKuisioner nk WHERE nk.krs.pemb.idPemb = '" + idPemb + "' AND nk.pertanyaanKuisioner.idPertanyaanKuisioner = '" + idPertanyaan + "'"; Query query = sessionFactory.getCurrentSession().createQuery(queryString); return query.list(); } }
30.795455
176
0.790406
a2a86ddeadef1bb3944b759efd5e9889bc7a88a5
387
package com.github.tibolte.agendacalendarview; import com.github.tibolte.agendacalendarview.models.CalendarEvent; import com.github.tibolte.agendacalendarview.models.IDayItem; import java.util.Calendar; public interface CalendarPickerController { void onDaySelected(IDayItem dayItem); void onEventSelected(CalendarEvent event); void onScrollToDate(Calendar calendar); }
25.8
66
0.821705
a3442ea43ec2bb25175d5f829d94dc322d0f4a14
1,654
package mskubilov.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * //курс Петра Арсентьева job4j.ru. * * @author Maksim Skubilov [email protected] * @version 1.0 * @since 15.04.17 */ /** * Iterator of even numbers only. */ public class EvenIterator implements Iterator { /** * iterable array. */ private final int[] array; /** * array index position. */ private int index = 0; /** * position of next Even. */ private int nextEvenIndex; /** * @param array - iterable array. */ public EvenIterator(int[] array) { this.array = array; this.nextEvenIndex = nextEvenIndex(); } /** * @return hasNext return has next even element or not */ @Override public boolean hasNext() { return nextEvenIndex != -1; } /** * @return next even element. */ @Override public Object next() { Object result = null; if (hasNext()) { result = this.array[nextEvenIndex]; this.index = ++this.nextEvenIndex; this.nextEvenIndex = nextEvenIndex(); } if (result == null) { throw new NoSuchElementException("There is not Even numbers left in array!"); } return result; } /** * @return next even element. */ private int nextEvenIndex() { int result = -1; for (int i = index; i != this.array.length; i++) { if (this.array[i] % 2 == 0) { result = i; break; } } return result; } }
21.205128
89
0.534462
7ba439361bd16ecb78ad36eee04bfe4150d106d7
6,821
/** * Copyright 2012 Universitat Pompeu Fabra. * * 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.onexus.collection.store.elasticsearch.internal; import com.google.common.base.Joiner; import com.google.common.cache.LoadingCache; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.search.sort.SortOrder; import org.onexus.collection.api.Collection; import org.onexus.collection.api.Link; import org.onexus.collection.api.query.Filter; import org.onexus.collection.api.query.OrderBy; import org.onexus.collection.api.query.Query; import org.onexus.resource.api.IResourceManager; import org.onexus.resource.api.ORI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.onexus.collection.store.elasticsearch.internal.ElasticSearchUtils.refreshIndex; import static org.onexus.collection.store.elasticsearch.internal.filters.FilterAdapterFactory.filterAdapter; public class ElasticSearchQuery { private static final Joiner PATH_JOINER = Joiner.on("."); private LoadingCache<ORI, String> indexNameCache; private IResourceManager resourceManager; private Client client; private Query query; private SearchRequestBuilder searchRequest; private String fromIndexName; private ORI fromORI; private Map<ORI, List<String>> collectionPathList; private Map<ORI, String> collectionPath; public ElasticSearchQuery(IResourceManager resourceManager, LoadingCache<ORI, String> indexNameCache, Client client, Query query) { super(); this.indexNameCache = indexNameCache; this.resourceManager = resourceManager; this.query = query; this.client = client; // Create all collections paths. Using the links. this.collectionPathList = new HashMap<ORI, List<String>>(); this.collectionPath = new HashMap<ORI, String>(); buildPath(getFrom(), new ArrayList<String>(0)); // Build the query build(); } private void buildPath(ORI collectionOri, List<String> prefix) { if (collectionPathList.containsKey(collectionOri)) { List<String> previousPrefix = collectionPathList.get(collectionOri); // If there are to routes to the same collection // we prefer the shorter one. if (previousPrefix.size() < prefix.size()) { return; } } this.collectionPathList.put(collectionOri, prefix); this.collectionPath.put(collectionOri, PATH_JOINER.join(prefix)); Collection collection = resourceManager.load(Collection.class, collectionOri); if (collection.getLinks() != null) { for (Link link : collection.getLinks()) { ORI linkOri = link.getCollection().toAbsolute(collectionOri); List<String> linkPrefix = new ArrayList<String>(prefix.size() + 1); linkPrefix.addAll(prefix); linkPrefix.add(indexNameCache.getUnchecked(linkOri)); buildPath(linkOri, linkPrefix); } } } public boolean isLinked(ORI collection) { return collectionPathList.containsKey(collection); } public List<String> getPath(ORI collection) { return collectionPathList.get(collection); } private void build() { from(); where(); order(); limit(); } private void from() { // Form collection fromIndexName = convertAliasToIndexName(query.getFrom()); // Create request searchRequest = client.prepareSearch( fromIndexName ); searchRequest.setTypes("entity"); searchRequest.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); searchRequest.setExplain(false); } private void where() { Filter filter = query.getWhere(); if (filter != null) { searchRequest.setPostFilter(filterAdapter(filter).build(this, filter)); } } private void order() { for (OrderBy order : query.getOrders()) { String indexName = convertAliasToIndexName(order.getCollection()); searchRequest.addSort(convertToField(indexName, order.getField()), (order.isAscendent() ? SortOrder.ASC : SortOrder.DESC)); } } private void limit() { if (query.getOffset() != null) { searchRequest.setFrom(query.getOffset().intValue()); } if (query.getCount() != null) { searchRequest.setSize(query.getCount().intValue()); } } private String convertToField(String indexName, String fieldId) { if (fromIndexName.equals(indexName)) { return fieldId; } return indexName + "." + fieldId; } public String convertAliasToIndexName(String alias) { return indexNameCache.getUnchecked(convertAliasToAbsoluteORI(alias)); } public ORI convertAliasToAbsoluteORI(String alias) { ORI ori = query.getDefine().get(alias); if (query.getOn() != null) { ori = ori.toAbsolute(query.getOn()); } return ori; } public ORI getFrom() { if (fromORI == null) { fromORI = query.getDefine().get( query.getFrom()).toAbsolute( query.getOn() ); } return fromORI; } public String fieldPath(String collectionAlias, String fieldId) { if (collectionAlias.equals(query.getFrom())) { return fieldId; } return indexPath(collectionAlias) + "." + fieldId; } public String indexPath(String collectionAlias) { ORI ori = query.getDefine().get(collectionAlias).toAbsolute(query.getOn()); return collectionPath.get(ori); } public Query getOnexusQuery() { return query; } public SearchRequestBuilder getSearchRequest() { refreshIndex(client, fromIndexName); return searchRequest; } public IResourceManager getResourceManager() { return resourceManager; } public boolean isFromCollection(String collectionAlias) { return query.getFrom().equals(collectionAlias); } }
30.450893
135
0.664565
5a69c459e8569afaee40808bde0b7268812562d5
7,124
/******************************************************************************* * Copyright (c) 2022 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.sail.memory.benchmark; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.apache.commons.io.IOUtils; import org.eclipse.rdf4j.common.transaction.IsolationLevels; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.sail.memory.MemoryStore; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; /** * @author Håvard Ottestad */ @State(Scope.Benchmark) @Warmup(iterations = 20) @BenchmarkMode({ Mode.AverageTime }) @Fork(value = 1, jvmArgs = { "-Xms1G", "-Xmx1G" }) //@Fork(value = 1, jvmArgs = {"-Xms1G", "-Xmx1G", "-XX:StartFlightRecording=delay=60s,duration=120s,filename=recording.jfr,settings=profile", "-XX:FlightRecorderOptions=samplethreads=true,stackdepth=1024", "-XX:+UnlockDiagnosticVMOptions", "-XX:+DebugNonSafepoints"}) @Measurement(iterations = 10) @OutputTimeUnit(TimeUnit.MILLISECONDS) public class ParallelQueryBenchmark { private static final String query1; private static final String query4; private static final String query7_pathexpression1; private static final String query8_pathexpression2; static { try { query1 = IOUtils.toString(getResourceAsStream("benchmarkFiles/query1.qr"), StandardCharsets.UTF_8); query4 = IOUtils.toString(getResourceAsStream("benchmarkFiles/query4.qr"), StandardCharsets.UTF_8); query7_pathexpression1 = IOUtils.toString(getResourceAsStream("benchmarkFiles/query7-pathexpression1.qr"), StandardCharsets.UTF_8); query8_pathexpression2 = IOUtils.toString(getResourceAsStream("benchmarkFiles/query8-pathexpression2.qr"), StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } private SailRepository repository; @Setup(Level.Trial) public void beforeClass() throws IOException, InterruptedException { repository = new SailRepository(new MemoryStore()); try (SailRepositoryConnection connection = repository.getConnection()) { connection.begin(IsolationLevels.NONE); try (InputStream resourceAsStream = getResourceAsStream("benchmarkFiles/datagovbe-valid.ttl")) { connection.add(resourceAsStream, RDFFormat.TURTLE); } connection.commit(); } } @TearDown(Level.Trial) public void afterClass() { repository.shutDown(); } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include("ParallelQueryBenchmark.*") // adapt to run other benchmark tests .build(); new Runner(opt).run(); } @Benchmark public void mixedWorkload(Blackhole blackhole) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch startSignal = new CountDownLatch(1); getMixedWorkload(blackhole, startSignal, null) .forEach(executorService::submit); startSignal.countDown(); executorService.shutdown(); while (!executorService.isTerminated()) { executorService.awaitTermination(100, TimeUnit.MILLISECONDS); } } private ArrayList<Runnable> getMixedWorkload(Blackhole blackhole, CountDownLatch startSignal, SailRepositoryConnection connection) { ArrayList<Runnable> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(getRunnable(startSignal, connection, (localConnection) -> { long count = localConnection .prepareTupleQuery(query4) .evaluate() .stream() .count(); blackhole.consume(count); })); } for (int i = 0; i < 10; i++) { list.add(getRunnable(startSignal, connection, (localConnection) -> { long count = localConnection .prepareTupleQuery(query7_pathexpression1) .evaluate() .stream() .count(); blackhole.consume(count); })); } for (int i = 0; i < 10; i++) { list.add(getRunnable(startSignal, connection, (localConnection) -> { long count = localConnection .prepareTupleQuery(query8_pathexpression2) .evaluate() .stream() .count(); blackhole.consume(count); })); } for (int i = 0; i < 100; i++) { list.add(getRunnable(startSignal, connection, (localConnection) -> { blackhole.consume(localConnection.hasStatement(null, RDF.TYPE, null, false)); })); } for (int i = 0; i < 100; i++) { list.add(getRunnable(startSignal, connection, (localConnection) -> { blackhole.consume(localConnection.hasStatement(null, RDF.TYPE, null, true)); })); } for (int i = 0; i < 5; i++) { list.add(getRunnable(startSignal, connection, (localConnection) -> { long count = localConnection .prepareTupleQuery(query1) .evaluate() .stream() .count(); blackhole.consume(count); })); } Collections.shuffle(list, new Random(2948234)); return list; } private Runnable getRunnable(CountDownLatch startSignal, SailRepositoryConnection connection, Consumer<SailRepositoryConnection> workload) { return () -> { try { startSignal.await(); } catch (InterruptedException e) { throw new IllegalStateException(); } SailRepositoryConnection localConnection = connection; try { if (localConnection == null) { localConnection = repository.getConnection(); } workload.accept(localConnection); } finally { if (connection == null) { assert localConnection != null; localConnection.close(); } } }; } private static InputStream getResourceAsStream(String filename) { return ParallelQueryBenchmark.class.getClassLoader().getResourceAsStream(filename); } }
32.381818
267
0.724593
a5effc126d789ca5f948993bea616a6b6a8a4458
2,745
/* * Copyright (c) 2016-2017, Adam <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package deob.deobfuscators; import asm.ClassFile; import asm.ClassGroup; import asm.Method; import asm.attributes.Code; import asm.attributes.code.Instruction; import asm.attributes.code.instruction.types.LVTInstruction; import deob.Deobfuscator; import deob.deobfuscators.lvt.Mappings; /** * This deobfuscator is only required for fernflower which has a difficult time * when the same lvt index is used for variables of differing types (like object * and int), see IDEABKL-7230. * * @author Adam */ public class Lvt implements Deobfuscator { private int count = 0; private void process(Method method) { Code code = method.getCode(); if (code == null) { return; } Mappings mappings = new Mappings(code.getMaxLocals()); for (Instruction ins : code.getInstructions().getInstructions()) { if (!(ins instanceof LVTInstruction)) { continue; } LVTInstruction lv = (LVTInstruction) ins; Integer newIdx = mappings.remap(lv.getVariableIndex(), lv.type()); if (newIdx == null) { continue; } assert newIdx != lv.getVariableIndex(); Instruction newIns = lv.setVariableIndex(newIdx); assert ins == newIns; ++count; } } @Override public void run(ClassGroup group) { for (ClassFile cf : group.getClasses()) { for (Method m : cf.getMethods()) { process(m); } } } }
28.59375
82
0.730055
6e09b0c144d6307b0fc6028e21fac8db8ae2895e
959
package com.xjbg.rocketmq.util; import com.xjbg.rocketmq.MqConstants; import org.apache.commons.lang3.StringUtils; /** * @author kesc * @since 2019/4/6 */ public class ProfileUtil { /** * set once and remove after get*Message() */ private static final ThreadLocal<String> TOPIC_PROFILE = new ThreadLocal<>(); private static String topicPrefix = ""; public static void setTopicProfile(String topicProfile) { if (StringUtils.isNotBlank(topicProfile)) { ProfileUtil.topicPrefix = topicProfile + MqConstants.DASH; } } public static void setTopicProfileOnce(String topicProfile) { TOPIC_PROFILE.set(topicProfile); } public static String getTopicPrefix() { if (TOPIC_PROFILE.get() != null) { return TOPIC_PROFILE.get() + MqConstants.DASH; } return topicPrefix; } public static void remove() { TOPIC_PROFILE.remove(); } }
24.589744
81
0.651721
1ec77a7cdf6cc39586c83bc6cf98f58482461222
619
/* * Copyright (c) 2017. 联思智云(北京)科技有限公司. All rights reserved. */ package com.smartsuites.interpreter; import java.io.Serializable; /** * Interpreter result message */ public class InterpreterResultMessage implements Serializable { InterpreterResult.Type type; String data; public InterpreterResultMessage(InterpreterResult.Type type, String data) { this.type = type; this.data = data; } public InterpreterResult.Type getType() { return type; } public String getData() { return data; } public String toString() { return "%" + type.name().toLowerCase() + " " + data; } }
19.34375
77
0.688207
b46bc3de3549055930974defec068a94b7e34946
6,730
/* * Copyright (c) 2015, Brno University of Technology, Faculty of Information Technology * 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 sched-advisor 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 eu.juniper.sa.monitoring.agent; import eu.juniper.sa.monitoring.resources.MonitoredResourcesStrategyInterface; import eu.juniper.sa.monitoring.sensor.DataConnectionSensorInterface; import eu.juniper.sa.monitoring.sensor.ProgramInstanceSensorInterface; import java.io.IOException; import java.net.MalformedURLException; /** * The interface of monitoring agents which can be used to send metric values to * a monitoring service (e.g., HTTP service, file-storage service, etc.). The * metric values sent may be both the resource utilization and custom values and * they can be send by dynamic methods of the interface implementations, with a * predefined metric service URL and a predefined application ID. * * @author rychly */ public interface MonitoringAgentInterface { /** * Get the application ID. * * @return the application ID */ String getApplicationId(); /** * Get the default monitored resource strategy used by the agent. * * @return the default monitored resource strategy used by the agent */ MonitoredResourcesStrategyInterface getMonitoredResourcesDefaultStrategy(); /** * Send a set of given metrics of a particular type from the application to * the monitoring service. * * @param metricType a type of metrics in the set to send * @param metricNames names of metrics in the set to send * @param metricValues values of metrics in the set to send * @param timestampSec a timestamp in seconds of the metric set origin * @param hostname a hostname of a client sending the metric * @return the monitoring service response * @throws MalformedURLException if <code>monitoringServiceURL</code> is * malformed * @throws IOException if there is an HTTP error when connecting or sending * to the monitoring service */ String sendMetric(String metricType, String[] metricNames, String[] metricValues, double timestampSec, String hostname) throws MalformedURLException, IOException; /** * Send a set of given metrics of a particular type from the application to * the monitoring service. The method utilizes <code>getHostname()</code> * method of the default monitored resource strategy to get a hostname of a * client sending the metric. * * @param metricType a type of metrics in the set to send * @param metricNames names of metrics in the set to send * @param metricValues values of metrics in the set to send * @param timestampSec a timestamp in seconds of the metric set origin * @return the monitoring service response * @throws MalformedURLException if <code>monitoringServiceURL</code> is * malformed * @throws IOException if there is an HTTP error when connecting or sending * to the monitoring service */ String sendMetric(String metricType, String[] metricNames, String[] metricValues, double timestampSec) throws MalformedURLException, IOException; /** * Send the latest set of given metrics of a particular type from the * application to the monitoring service. The method utilizes methods of the * default monitored resource strategy, namely <code>getTimestamp()</code> * method to get a timestamp of metric to send and * <code>getHostname()</code> method to get a hostname of a client sending * the metric. * * @param metricType a type of metrics in the set to send * @param metricNames names of metrics in the set to send * @param metricValues values of metrics in the set to send * @return the monitoring service response * @throws MalformedURLException if <code>monitoringServiceURL</code> is * malformed * @throws IOException if there is an HTTP error when connecting or sending * to the monitoring service */ String sendMetric(String metricType, String[] metricNames, String[] metricValues) throws MalformedURLException, IOException; /** * Create a sensor for a data connection between Juniper programs that will * utilize this monitoring agent. * * @param receiverGlobalRank an MPI global rank of a receiving Juniper * program of a monitored connection (value of * <code>JuniperProgram.myGlobalRank</code>) * @param connectionName a name of an incomming monitored connection of a * Juniper program (value used in * <code>JuniperProgram.transferData(...)</code>) * @return a sensor for a data connection between Juniper programs that will * utilize this monitoring agent */ DataConnectionSensorInterface createDataConnectionSensor(int receiverGlobalRank, String connectionName); /** * Create a sensor for a Juniper program instance that will utilize this * monitoring agent. * * @param programGlobalRank an MPI global rank of a monitored Juniper * program (value of <code>JuniperProgram.myGlobalRank</code>) * @return a sensor that will utilize this monitoring agent */ ProgramInstanceSensorInterface createProgramInstanceSensor(int programGlobalRank); }
48.071429
166
0.738336
6524fe3f1a26676e52fcf0cd3f45de14c48d232f
4,507
package com.exaroton.bungee; import com.exaroton.api.server.Server; import com.exaroton.api.server.ServerStatus; import com.exaroton.api.ws.subscriber.ServerStatusSubscriber; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.TextComponent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.logging.Level; import java.util.logging.Logger; public class ServerStatusListener extends ServerStatusSubscriber { /** * bungee proxy */ private final ProxyServer proxy; /** * plugin logger */ private final Logger logger; /** * exaroton plugin */ private final ExarotonPlugin plugin; /** * optional command sender */ private CommandSender sender; /** * optional server name */ private String name; /** * is this server restricted */ private final boolean restricted; /** * server status that the user is waiting for */ private int expectedStatus; /** * exaroton server */ private final Server server; private final Map<Integer, List<CompletableFuture<Server>>> waitingFor = new HashMap<>(); public ServerStatusListener(ExarotonPlugin plugin, boolean restricted, Server server) { this.proxy = plugin.getProxy(); this.logger = plugin.getLogger(); this.plugin = plugin; this.restricted = restricted; this.server = server; } public ServerStatusListener setName(String name) { if (name != null) { this.name = name; } return this; } public String getName(Server server) { return name != null ? name : server.getName(); } public ServerStatusListener setSender(CommandSender sender, int expectedStatus) { if (sender != null) { this.sender = sender; this.expectedStatus = expectedStatus; } return this; } @Override public void statusUpdate(Server oldServer, Server newServer) { plugin.updateServer(newServer); if (waitingFor.containsKey(newServer.getStatus())) { for (CompletableFuture<Server> future: waitingFor.get(newServer.getStatus())) { future.complete(newServer); } } String serverName = this.name == null ? newServer.getName() : this.name; if (!oldServer.hasStatus(ServerStatus.ONLINE) && newServer.hasStatus(ServerStatus.ONLINE)) { if (proxy.getServers().containsKey(serverName)) { this.sendInfo("Server "+serverName+" already exists in bungee network", true); return; } proxy.getServers().put(serverName, plugin.constructServerInfo(serverName, newServer, restricted)); this.sendInfo(Message.statusChange(serverName, true).getMessage(), expectedStatus == ServerStatus.ONLINE); } else if (oldServer.hasStatus(ServerStatus.ONLINE) && !newServer.hasStatus(ServerStatus.ONLINE)) { proxy.getServers().remove(serverName); this.sendInfo(Message.statusChange(serverName, false).getMessage(), expectedStatus == ServerStatus.OFFLINE); } } /** * send message to all subscribed sources * @param message message */ public void sendInfo(String message, boolean unsubscribe) { logger.log(Level.INFO, message); TextComponent text = new TextComponent(message + ChatColor.RESET); if (sender != null && !sender.equals(proxy.getConsole())) { sender.sendMessage(text); if (unsubscribe) { //unsubscribe user from further updates this.sender = null; } } } /** * unsubscribe from this server */ public void unsubscribe() { this.server.unsubscribe(); } /** * wait until this server has reached this status * @param status expected status * @return server with status */ public CompletableFuture<Server> waitForStatus(int status) { CompletableFuture<Server> future = new CompletableFuture<>(); if (!waitingFor.containsKey(status)) { waitingFor.put(status, new ArrayList<>()); } waitingFor.get(status).add(future); return future; } }
29.651316
120
0.634568
3c65d28eab366279acce68acdcbf0ee294664b3c
2,271
package es.Zakan.NeightbourFight; import java.util.*; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.beans.factory.annotation.*; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/users") public class UsernameRestController { @Autowired private Username usernames; @PostMapping public ResponseEntity<Boolean> crearHistorialUsuario() { try { String ruta = "users/usernamesHistory.txt"; File file = new File(ruta); file.createNewFile(); } catch (Exception e) { //e.printStackTrace(); } return new ResponseEntity<>(true, HttpStatus.CREATED); } @GetMapping public List<String> getUsernames() { try { Path path = Paths.get("users/", "usernamesHistory.txt"); usernames.setUsuarios(Files.readAllLines(path, Charset.defaultCharset())); } catch (Exception e) { //e.printStackTrace(); } return usernames.getUsuarios(); } @PutMapping public ResponseEntity<Boolean> newUsers(@RequestBody String newUser) { File archivo; FileWriter escribir; PrintWriter linea; archivo = new File("users/usernamesHistory.txt"); if(!archivo.exists()){ try{ archivo.createNewFile(); escribir = new FileWriter (archivo,true); linea= new PrintWriter(escribir); linea.println(newUser); linea.close(); escribir.close(); }catch (IOException e){ //e.printStackTrace(); } }else { try{ escribir = new FileWriter (archivo,true); linea= new PrintWriter(escribir); linea.println(newUser); linea.close(); escribir.close(); }catch (IOException e){ //e.printStackTrace(); } } return new ResponseEntity<>(true, HttpStatus.CREATED); } @DeleteMapping public ResponseEntity<Boolean> borrarUsers() { try { String ruta = "users/usernamesHistory.txt"; File file = new File(ruta); file.delete(); } catch (Exception e) { //e.printStackTrace(); } return new ResponseEntity<>(true, HttpStatus.CREATED); } }
23.905263
86
0.646852
e9c1e604785a70469ff8e8512a795eee25e99ada
6,818
package com.iuriX.ustglobalproject; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.content.Intent; import android.app.Activity; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import modelo.Session; import modelo.busqueda.BusquedaInterface; import modelo.busqueda.ListaEmpleados; import modelo.busqueda.PeticionBusquedaJSON; import modelo.login.LoginActivity; import modelo.login.R; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import android.os.Handler; import com.iuriX.ustglobalproject.facetracker.FaceTrackerActivity; public class MainActivity extends Activity { private Button buscar; private EditText textoBusqueda; private BusquedaInterface service; LinearLayout logout; ImageView imageUsuario; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buscar = (Button)findViewById(R.id.buscar); textoBusqueda = (EditText)findViewById(R.id.textoBusqueda); logout = (LinearLayout)findViewById(R.id.logout); imageUsuario = (ImageView) findViewById(R.id.imageUsuario); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("") .setMessage("¿Está seguro de que desea salir?") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Session.getInstance().setSessionId(""); Intent logout = new Intent(getApplicationContext(), LoginActivity.class); startActivity(logout); } }) .setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ; }}); builder.show(); } }); if(Session.getInstance().getImagenBase64().equals("")){ Log.d("MainActivity", "Imagen vacía"); }else { byte[] decodedString = Base64.decode(Session.getInstance().getImagenBase64().getBytes(), Base64.URL_SAFE); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); imageUsuario.setImageBitmap(decodedByte); } } public void buscar(View v){ final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Cargando..."); progressDialog.show(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(getString(R.string.api_url)) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(BusquedaInterface.class); textoBusqueda.setError(null); boolean cancel = false; View focusView = null; final PeticionBusquedaJSON peticionBusquedaJSON = new PeticionBusquedaJSON(); peticionBusquedaJSON.setBusqueda(textoBusqueda.getText().toString()); peticionBusquedaJSON.setSessionId(Session.getInstance().getSessionId()); Call<ListaEmpleados> listaEmpleadosCall = service.getListaEmpleados(peticionBusquedaJSON); listaEmpleadosCall.enqueue(new Callback<ListaEmpleados>() { @Override public void onResponse(Call<ListaEmpleados> call, Response<ListaEmpleados> response) { progressDialog.dismiss(); int statusCode = response.code(); ListaEmpleados listaEmpleados1 = response.body(); //Session.getInstance().setId_empleado_seleccionado(listaEmpleados1.empleados.get().getId()); if (listaEmpleados1.getListaUsuarios().size() > 0) { Log.d("MainActivity", "onResponse" + statusCode + " " + listaEmpleados1); Intent intentBusqueda = new Intent(MainActivity.this, BusquedaActivity.class); Session.getInstance().setListaEmpleadosSession(listaEmpleados1); startActivity(intentBusqueda); findViewById(R.id.loadingPanel).setVisibility(View.GONE); } else { Toast.makeText(MainActivity.this, "Criterios no encontrados", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<ListaEmpleados> call, Throwable t) { progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "Error de conexión con el servidor",Toast.LENGTH_SHORT).show(); Log.d("LoginActivity", "onFailure: " + t.getMessage()); } }); } public void buscarFoto(View view) { //testeando... Intent fotoSearch = new Intent(getApplicationContext(), FaceTrackerActivity.class); startActivity(fotoSearch); } boolean twice; @Override public void onBackPressed() { Log.d("MainActivity","click"); if (twice == true) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); System.exit(0); } twice = true; Log.d("MainActivity", "twice: " + twice); Toast.makeText(MainActivity.this,"Presiona ATRÁS de nuevo para salir", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { twice = false; Log.d("MainActivity", "twice: " + twice); } },3000); } }
36.265957
119
0.608976
74a8101a1735fc62f511ab2f66d56471fc45cfb5
1,770
package com.vc.easy; /***** * Problem No: 9 * Category: Data Structures And Algorithms * Tags: Math, Leetcode, Easy * Title: Palindrome Number * MetaDescription: Java Solution to Data Structures And Algorithms problem, to determine whether an integer is a palindrome. It is an easy problem that uses the modulo Math technique to solve the problem. * Description: Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. * Input: 121 * Output: true * Input: -121 * Output: false * Similar Question: String to Integer (atoi), Reverse Bits, Palindrome Number *****/ class PalindromeNumber { /** * Gotchas * 1. Given number can be negative * 2. Reversed number might overflow out the range of integer * 3. Before reversing the given number, keep old value in some variable like so xOld = x * Because once we have reverse of number we can validate it against the given number like so xNew == x * * Algorithm * 1. If the given number is negative, set a flag and reverse the sign of a current number. * 2. While Given number > 0 * 2.1. Take the last digit of a given number by doing modulo operation and append that digit to a new number * 2.2. Divide the given number by 10 * 2.3. Continue running Step 2.1 to 2.2 until Given Number > 0 * 3. Validate if Given number is same as reverse of a number. **/ public boolean isPalindrome(int x) { if(x < 0) return false; int xNew = 0; int xOld = x; while(xOld > 0) { int digit = xOld % 10; xNew = xNew * 10 + digit; xOld = xOld / 10; } return xNew == x; } }
39.333333
206
0.641243
1934b5ff7640fb8bc0fa39925edb4e82b423dd62
481
package de.aservo.confapi.confluence.model; import de.aservo.confapi.commons.constants.ConfAPI; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.Collection; @Data @NoArgsConstructor @AllArgsConstructor @XmlRootElement(name = ConfAPI.CACHES) public class CachesBean { @XmlElement private Collection<CacheBean> caches; }
21.863636
51
0.817048
251e1811a29f9513a76ad866803a8bad3ea3f3f7
1,521
/* * ======================================================================== * * 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.cactus; /** * Cookie containing an HTTP Session id. * * @version $Id: HttpSessionCookie.java 238991 2004-05-22 11:34:50Z vmassol $ * @since 1.5 */ public class HttpSessionCookie extends Cookie { /** * @see Cookie#Cookie(String, String, String) * @param theDomain of the sessionCookie * @param theName of the SessionCookie * @param theValue of the SessionCookie */ public HttpSessionCookie(String theDomain, String theName, String theValue) { super(theDomain, theName, theValue); } }
36.214286
79
0.648258
95c0ebae2a67b3b96db04873a7ca77da7eeb5a9b
1,710
package tcl.lang.cmd; import java.io.File; import tcl.lang.Command; import tcl.lang.Interp; import tcl.lang.TclException; import tcl.lang.TclIO; import tcl.lang.TclInteger; import tcl.lang.TclList; import tcl.lang.TclObject; import tcl.lang.channel.Channel; import tcl.lang.channel.PipelineChannel; /** * implement TCL 'pid' command. JVM doesn't support PID queries directly so we * play some tricks here. If pid can't be found, -1 (or a list of -1) is * returned * * @author danb * */ public class PidCmd implements Command { /** * @return PID of the TCL process, or -1 if it can't be determined */ public static int getPid() { // This will work in solaris and linux try { return Integer.parseInt(new File("/proc/self").getCanonicalFile().getName()); } catch (Exception e) { return -1; // can't figure out PID } } public void cmdProc(Interp interp, TclObject[] objv) throws TclException { if (objv.length == 1) { // return JVM pid interp.setResult(getPid()); } else if (objv.length == 2) { // look up PIDs for a PipelineChannel Channel channel = TclIO.getChannel(interp, objv[1].toString()); if (channel == null) { throw new TclException(interp, "can not find channel named \"" + objv[1].toString() + "\""); } if (channel instanceof PipelineChannel) { int[] pids = ((PipelineChannel) channel).getPipeline().getProcessIdentifiers(); TclObject rv = TclList.newInstance(); for (int pid : pids) { TclList.append(interp, rv, TclInteger.newInstance(pid)); } interp.setResult(rv); } else { interp.setResult(""); } } else { throw new TclException(interp, "wrong # args: should be \"pid ?channelId?\""); } } }
27.580645
96
0.67193
dfd8e6a55af46c322bc6041d6685b5eb0775f289
2,474
/* * Copyright (c) 2011-2014 Pivotal Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.io.net.tcp.spec; import reactor.Environment; import reactor.io.net.tcp.TcpServer; import javax.annotation.Nonnull; /** * Helper class to make creating {@link reactor.io.net.tcp.TcpServer} instances more succinct. * * @author Jon Brisbin */ public abstract class TcpServers { protected TcpServers() { } /** * Create a {@link TcpServerSpec} for further configuration using the given {@link * reactor.Environment} and {@code serverImpl}. * * @param env * the {@link reactor.Environment} to use * @param serverImpl * the implementation of {@link reactor.io.net.tcp.TcpServer} * @param <IN> * type of the input * @param <OUT> * type of the output * * @return a {@link TcpServerSpec} to be further configured */ public static <IN, OUT> TcpServerSpec<IN, OUT> create(Environment env, @Nonnull Class<? extends TcpServer> serverImpl) { return new TcpServerSpec<IN, OUT>(serverImpl).env(env); } /** * Create a {@link TcpServerSpec} for further configuration using the given {@link * reactor.Environment} and {@code serverImpl}. * * @param env * the {@link reactor.Environment} to use * @param dispatcher * the type of dispatcher to use * @param serverImpl * the implementation of {@link reactor.io.net.tcp.TcpServer} * @param <IN> * type of the input * @param <OUT> * type of the output * * @return a {@link TcpServerSpec} to be further configured */ public static <IN, OUT> TcpServerSpec<IN, OUT> create(Environment env, String dispatcher, @Nonnull Class<? extends TcpServer> serverImpl) { return new TcpServerSpec<IN, OUT>(serverImpl).env(env).dispatcher(dispatcher); } }
31.717949
104
0.655214
efd6ad5bf8cbc091cb8af05bc9d27639e70632d9
1,135
package pl.itcraft.appstract.core.dto; import pl.itcraft.appstract.core.enums.UserRole; public class UserDto { private Long id; private String email; private String firstName; private String lastName; private UserRole role; private String avatarUrl; private boolean uploaded; public Long getId() { return id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public UserRole getRole() { return role; } public void setId(Long id) { this.id = id; } public void setRole(UserRole role) { this.role = role; } public String getAvatarUrl() { return avatarUrl; } public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } public boolean isUploaded() { return uploaded; } public void setUploaded(boolean uploaded) { this.uploaded = uploaded; } }
15.763889
48
0.711013
a66ef580e0995848f99775675377c57dede66d04
228
package com.bignerdranch.android.loginapp.Interface; import android.view.View; /** * Created by leoni on 4/27/2018. */ public interface ItemClickListener { void onClick(View view, int position,boolean isLongClick); }
17.538462
63
0.745614
6f275e69ded8e8710d6599bb071a4b5dbc7dd2b7
1,907
package de.thecodelabs.spring.auth.entity; import de.thecodelabs.spring.auth.model.Role; import de.thecodelabs.spring.auth.model.UserType; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity @Table(name = "user") public class User { private Long id; @NotNull @Size(min = 1, max = 255) private String username; private String password; private String passwordConfirm; // User info private String name; private String lastName; private Role role = Role.USER; private UserType userType = UserType.CUSTOM; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(unique = true) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Transient public String getPasswordConfirm() { return passwordConfirm; } public void setPasswordConfirm(String passwordConfirm) { this.passwordConfirm = passwordConfirm; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name = "role", nullable = false) @Enumerated(EnumType.STRING) public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } @Enumerated(EnumType.STRING) public UserType getUserType() { return userType; } public void setUserType(UserType userType) { this.userType = userType; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + '}'; } }
17.495413
57
0.706345
e5f249de991b4219d81974b899652a8857e9ce1a
2,057
/* Copyright (c) 2016 TOSHIBA CORPORATION. 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.toshiba.mwcloud.gs.hadoop.mapred; import java.io.IOException; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputFormat; import org.apache.hadoop.mapred.RecordWriter; import org.apache.hadoop.util.Progressable; import com.toshiba.mwcloud.gs.hadoop.io.GSRowWritable; /** * <div lang="ja"> * GridDBのRowオブジェクトを利用したGridDB用OutputFormatクラスです。 * </div><div lang="en"> * GridDB OutputFormat class using GridDB Row object. * </div> */ public class GSRowOutputFormat implements OutputFormat<NullWritable, GSRowWritable> { /* * (non Javadoc) * @see org.apache.hadoop.mapred.OutputFormat#getRecordWriter(org.apache.hadoop.fs.FileSystem, org.apache.hadoop.mapred.JobConf, java.lang.String, * org.apache.hadoop.util.Progressable) */ @Override public RecordWriter<NullWritable, GSRowWritable> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { RecordWriter<NullWritable, GSRowWritable> writer = new GSRowRecordWriter(job); return writer; } /* * (non Javadoc) * @see org.apache.hadoop.mapred.OutputFormat#checkOutputSpecs(org.apache.hadoop.fs.FileSystem, org.apache.hadoop.mapred.JobConf) */ @Override public void checkOutputSpecs(FileSystem ignored, JobConf job) throws IOException { } }
36.087719
150
0.74526
2a6458df6f1bb005e37e11c0191bc4e7ac6030e0
2,121
package com.example.popularmovies.api; import com.example.popularmovies.BuildConfig; import com.example.popularmovies.constants.Constants; import com.example.popularmovies.interfaces.TMDbInterface; import com.example.popularmovies.model.Detail; import com.example.popularmovies.model.ResultMovies; import com.example.popularmovies.model.Reviews; import com.example.popularmovies.model.Trailers; import io.reactivex.Observable; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Interface of the movie database website api via retrofit2 library. */ public class MoviesDbRepository { private TMDbInterface api; private MoviesDbRepository(TMDbInterface api) { this.api = api; } private static MoviesDbRepository repository; /** * * @return repository instance */ public static MoviesDbRepository getInstance() { if (repository == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); repository = new MoviesDbRepository(retrofit.create(TMDbInterface.class)); } return repository; } public TMDbInterface getApi(){ return this.api; } public void getMoviesByPageCb(Callback<ResultMovies> callback,String sort, int page){ api.getMovies(sort, BuildConfig.TMDbAPIKEY, Constants.LANGUAGE, page).enqueue(callback); } public Observable<Detail> getDetail(String id){ return api.getDetail(id, BuildConfig.TMDbAPIKEY, Constants.LANGUAGE,""); } public Observable<Trailers> getTrailers(String id){ return api.getTrailers(id, BuildConfig.TMDbAPIKEY, ""); } public Observable<Reviews> getReviews(String id,int page){ return api.getReviews(id,BuildConfig.TMDbAPIKEY,Constants.LANGUAGE,page); } }
31.191176
96
0.713343
e372ac06cc98049c964f1b8048e83a3f8ac314c3
3,855
/* * Copyright (c) 2004-2021, University of Oslo * 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 HISP project 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 OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.dxf2.importsummary; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; /** * @author Lars Helge Overland */ class ImportSummariesTest { @Test void testAddImportSummary() { ImportSummaries summaries = new ImportSummaries(); summaries.addImportSummary( new ImportSummary( ImportStatus.SUCCESS, "Great success", new ImportCount( 4, 2, 1, 2 ) ) ); summaries.addImportSummary( new ImportSummary( ImportStatus.WARNING, "Ouch warning", new ImportCount( 1, 2, 3, 0 ) ) ); summaries.addImportSummary( new ImportSummary( ImportStatus.SUCCESS, "Great failure", new ImportCount( 0, 0, 4, 3 ) ) ); assertEquals( 5, summaries.getImported() ); assertEquals( 4, summaries.getUpdated() ); assertEquals( 8, summaries.getIgnored() ); assertEquals( 5, summaries.getDeleted() ); } @Test void testGetImportStatus() { ImportSummaries summaries = new ImportSummaries(); summaries.addImportSummary( new ImportSummary( ImportStatus.SUCCESS, "Great success", new ImportCount( 4, 2, 1, 2 ) ) ); summaries.addImportSummary( new ImportSummary( ImportStatus.WARNING, "Ouch warning", new ImportCount( 1, 2, 3, 0 ) ) ); summaries.addImportSummary( new ImportSummary( ImportStatus.ERROR, "Great failure", new ImportCount( 0, 0, 4, 3 ) ) ); assertEquals( ImportStatus.ERROR, summaries.getStatus() ); summaries = new ImportSummaries(); summaries.addImportSummary( new ImportSummary( ImportStatus.SUCCESS, "Great success", new ImportCount( 4, 2, 1, 2 ) ) ); summaries.addImportSummary( new ImportSummary( ImportStatus.WARNING, "Ouch warning", new ImportCount( 1, 2, 3, 0 ) ) ); assertEquals( ImportStatus.WARNING, summaries.getStatus() ); summaries = new ImportSummaries(); summaries.addImportSummary( new ImportSummary( ImportStatus.SUCCESS, "Great success", new ImportCount( 4, 2, 1, 2 ) ) ); assertEquals( ImportStatus.SUCCESS, summaries.getStatus() ); summaries = new ImportSummaries(); assertEquals( ImportStatus.SUCCESS, summaries.getStatus() ); } }
47.592593
104
0.703243
8469f4dee77bd27a9523176dcd0d108acfe91130
375
package com.example.demo.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties public class Header { private String messageType; private String subMessageType; }
19.736842
61
0.826667
2efa6a3ec7995dc8851622d8b4a92170c6ee4570
657
package org.apache.spark.sql.execution.adaptive; public class BroadcastQueryStageExec$ implements scala.Serializable { /** * Static reference to the singleton instance of this Scala object. */ public static final BroadcastQueryStageExec$ MODULE$ = null; public BroadcastQueryStageExec$ () { throw new RuntimeException(); } /** * Returns true if the plan is a {@link BroadcastQueryStageExec} or a reused * {@link BroadcastQueryStageExec}. * @param plan (undocumented) * @return (undocumented) */ public boolean isBroadcastQueryStageExec (org.apache.spark.sql.execution.SparkPlan plan) { throw new RuntimeException(); } }
41.0625
126
0.738204
e63dc4c0e60021342ada994d321e2fd136029062
495
package eu.bcvsolutions.idm.core.api.event; import java.io.Serializable; /** * Empty processor - can be defined, when some result has to be added into event context outside some processor manually. * * @author Radek Tomiška * * @param <E> */ public class EmptyEntityEventProcessor<E extends Serializable> extends AbstractEntityEventProcessor<E> { @Override public EventResult<E> process(EntityEvent<E> event) { return null; } @Override public int getOrder() { return 0; } }
20.625
121
0.735354
dcc049c25ef8f97644ab396ae5af88a24d058b22
1,779
package com.draco18s.artifacts.block; import java.util.Random; import com.draco18s.artifacts.DragonArtifacts; import com.draco18s.artifacts.entity.TileEntityAntibuilder; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockAntibuilder extends BlockContainer { public static Block instance; public BlockAntibuilder() { super(Material.rock); setHardness(1.0F); setResistance(200.0F); setStepSound(Block.soundTypeStone); setCreativeTab(DragonArtifacts.tabGeneral); } @Override public void registerBlockIcons(IIconRegister iconRegister) { this.blockIcon = iconRegister.registerIcon("stonebrick_carved"); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileEntityAntibuilder(); } @Override public int quantityDropped(Random par1Random) { return 0; } /*public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, int par5) { if (!par1World.isRemote) { boolean flag = par1World.isBlockIndirectlyGettingPowered(par2, par3, par4); TEAntibuilder tab = (TEAntibuilder)par1World.getBlockTileEntity(par2, par3, par4); tab.setActive(!flag); //System.out.println("Antibuilder should be active: " + (!flag)); } }*/ }
29.163934
94
0.749297
2bc5e5bec14f36357533de041b0cc29ddbaed203
20,178
/* * Copyright 2016 Development Entropy (deventropy.org) Contributors * * 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.deventropy.shared.utils; import static org.junit.Assert.*; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.compressors.CompressorException; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.BoundedInputStream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Tests creating zip and jar files. * * @author Bindul Bhowmik */ public class DirectoryArchiverUtilTest { private static final String MANIFEST_FILE_ENTRY_NAME = "META-INF/MANIFEST.MF"; private static final int MAX_FILE_SIZE = 8 * 1024; // 8K private static final String ZIP_FILE_SUFFIX = ".zip"; private static final String JAR_FILE_SUFFIX = ".jar"; private static final String TAR_FILE_SUFFIX = ".tar"; private static final String TAR_GZ_FILE_SUFFIX = ".tar.gz"; private static final String VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+_{}|" + "\\;:'\"/?.>,<~!@#$%^&*()~` \n"; @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); private final String[] testFileStructure01 = new String[] { "temp/", "temp/test1/", "temp/test1/file1.txt", "temp/test2/file1.txt", "temp/test2/file2.bin", "tmp/test3/test4/test5/file3.bin", "tmp/test3/test4/test5/file3.txt" }; private final Random random = new Random(); @Test public void testZipArchiveNullPrefix () throws IOException { final String archiveFilePath = testZipArchive(null, testFileStructure01); assertTrue("Should test as .zip file (testZipArchiveNullPrefix)", archiveFilePath.endsWith(ZIP_FILE_SUFFIX)); } @Test public void testZipArchiveEmptyPrefix () throws IOException { final String archiveFilePath = testZipArchive("", testFileStructure01); assertTrue("Should test as .zip file (testZipArchiveEmptyPrefix)", archiveFilePath.endsWith(ZIP_FILE_SUFFIX)); } @Test public void testZipArchivePrefix () throws IOException { final String archiveFilePath = testZipArchive("prefix/path", testFileStructure01); assertTrue("Should test as .zip file (testZipArchivePrefix)", archiveFilePath.endsWith(ZIP_FILE_SUFFIX)); } @Test public void testZipArchiveWinPrefix () throws IOException { final String archiveFilePath = testZipArchive("prefix\\path\\win", testFileStructure01); assertTrue("Should test as .zip file (testZipArchiveWinPrefix)", archiveFilePath.endsWith(ZIP_FILE_SUFFIX)); } private String testZipArchive (final String prefix, final String[] fileStructure) throws IOException { final File rootFolder = tempFolder.newFolder(); createDirectoryTree(rootFolder, fileStructure); final String testArchiveName = "archive-test-" + random.nextInt() + ZIP_FILE_SUFFIX; final File archiveFile = tempFolder.newFile(testArchiveName); DirectoryArchiverUtil.createZipArchiveOfDirectory(archiveFile.getAbsolutePath(), rootFolder, prefix); assertTrue("Zip file should not be zero sized", archiveFile.length() > 0); checkZipArchive(archiveFile, rootFolder, prefix); return archiveFile.getPath(); } private void checkZipArchive (final File archiveFile, final File sourceDirectory, final String pathPrefix) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix); final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry ze = entries.nextElement(); if (ze.isDirectory()) { assertTrue("Directory in zip should be from us [" + ze.getName() + "]", archiveEntries.dirs.contains(ze.getName())); archiveEntries.dirs.remove(ze.getName()); } else { assertTrue("File in zip should be from us [" + ze.getName() + "]", archiveEntries.files.containsKey(ze.getName())); final byte[] inflatedMd5 = getMd5Digest(zipFile.getInputStream(ze), true); assertArrayEquals("MD5 hash of files should equal [" + ze.getName() + "]", archiveEntries.files.get(ze.getName()), inflatedMd5); archiveEntries.files.remove(ze.getName()); } } // Check that all files and directories have been accounted for assertTrue("All directories should be in the zip", archiveEntries.dirs.isEmpty()); assertTrue("All files should be in the zip", archiveEntries.files.isEmpty()); } finally { if (null != zipFile) { zipFile.close(); } } } @Test public void testJarArchiveNullPrefix () throws IOException { final String archiveFilePath = testJarArchive(null, testFileStructure01); assertTrue("Should test as .jar file (testJarArchiveNullPrefix)", archiveFilePath.endsWith(JAR_FILE_SUFFIX)); } @Test public void testJarArchiveEmptyPrefix () throws IOException { final String archiveFilePath = testJarArchive("", testFileStructure01); assertTrue("Should test as .jar file (testJarArchiveEmptyPrefix)", archiveFilePath.endsWith(JAR_FILE_SUFFIX)); } @Test public void testJarArchivePrefix () throws IOException { final String archiveFilePath = testJarArchive("prefix/path", testFileStructure01); assertTrue("Should test as .jar file (testJarArchivePrefix)", archiveFilePath.endsWith(JAR_FILE_SUFFIX)); } @Test public void testJarArchiveWinPrefix () throws IOException { final String archiveFilePath = testJarArchive("prefix\\path\\win", testFileStructure01); assertTrue("Should test as .jar file (testJarArchiveWinPrefix)", archiveFilePath.endsWith(JAR_FILE_SUFFIX)); } private String testJarArchive (final String prefix, final String[] fileStructure) throws IOException { final File rootFolder = tempFolder.newFolder(); createDirectoryTree(rootFolder, fileStructure); final String testArchiveName = "archive-test-" + random.nextInt() + JAR_FILE_SUFFIX; final File archiveFile = tempFolder.newFile(testArchiveName); DirectoryArchiverUtil.createJarArchiveOfDirectory(archiveFile.getAbsolutePath(), rootFolder, prefix); assertTrue("Jar file should not be zero sized", archiveFile.length() > 0); checkJarArchive(archiveFile, rootFolder, prefix); return archiveFile.getPath(); } private void checkJarArchive (final File archiveFile, final File sourceDirectory, final String pathPrefix) throws IOException { JarFile jarFile = null; try { jarFile = new JarFile(archiveFile); final Manifest manifest = jarFile.getManifest(); assertNotNull("Manifest should be present", manifest); assertEquals("Manifest version should be 1.0", "1.0", manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION)); final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) { // It is the manifest file, not added by use continue; } if (jarEntry.isDirectory()) { assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.dirs.contains(jarEntry.getName())); archiveEntries.dirs.remove(jarEntry.getName()); } else { assertTrue("File in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.files.containsKey(jarEntry.getName())); final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false); assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]", archiveEntries.files.get(jarEntry.getName()), inflatedMd5); archiveEntries.files.remove(jarEntry.getName()); } } // Check that all files and directories have been accounted for assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty()); assertTrue("All files should be in the jar", archiveEntries.files.isEmpty()); } finally { if (null != jarFile) { jarFile.close(); } } } @Test public void testTarArchiveNullPrefix () throws IOException { final String archiveFilePath = testTarArchive(null, testFileStructure01); assertTrue("Should test as .tar file (testZipArchiveNullPrefix)", archiveFilePath.endsWith(TAR_FILE_SUFFIX)); } @Test public void testTarArchiveEmptyPrefix () throws IOException { final String archiveFilePath = testTarArchive("", testFileStructure01); assertTrue("Should test as .tar file (testZipArchiveEmptyPrefix)", archiveFilePath.endsWith(TAR_FILE_SUFFIX)); } @Test public void testTarArchivePrefix () throws IOException { final String archiveFilePath = testTarArchive("prefix/path", testFileStructure01); assertTrue("Should test as .tar file (testZipArchivePrefix)", archiveFilePath.endsWith(TAR_FILE_SUFFIX)); } @Test public void testTarArchiveWinPrefix () throws IOException { final String archiveFilePath = testTarArchive("prefix\\path\\win", testFileStructure01); assertTrue("Should test as .tar file (testZipArchiveWinPrefix)", archiveFilePath.endsWith(TAR_FILE_SUFFIX)); } private String testTarArchive (final String prefix, final String[] fileStructure) throws IOException { final File rootFolder = tempFolder.newFolder(); createDirectoryTree(rootFolder, fileStructure); final String testArchiveName = "archive-test-" + random.nextInt() + TAR_FILE_SUFFIX; final File archiveFile = tempFolder.newFile(testArchiveName); DirectoryArchiverUtil.createTarArchiveOfDirectory(archiveFile.getAbsolutePath(), rootFolder, prefix); assertTrue("Tar file should not be zero sized", archiveFile.length() > 0); checkTarArchive(archiveFile, rootFolder, prefix); return archiveFile.getPath(); } private void checkTarArchive (final File archiveFile, final File sourceDirectory, final String pathPrefix) throws IOException { ArchiveInputStream tarInputStream = null; try { tarInputStream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.TAR, new BufferedInputStream(new FileInputStream(archiveFile))); final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix); ArchiveEntry tarEntry = null; while ((tarEntry = tarInputStream.getNextEntry()) != null) { if (tarEntry.isDirectory()) { assertTrue("Directory in tar should be from us [" + tarEntry.getName() + "]", archiveEntries.dirs.contains(tarEntry.getName())); archiveEntries.dirs.remove(tarEntry.getName()); } else { assertTrue("File in tar should be from us [" + tarEntry.getName() + "]", archiveEntries.files.containsKey(tarEntry.getName())); final byte[] inflatedMd5 = getMd5Digest(new BoundedInputStream(tarInputStream, tarEntry.getSize()), false); assertArrayEquals("MD5 hash of files should equal [" + tarEntry.getName() + "]", archiveEntries.files.get(tarEntry.getName()), inflatedMd5); archiveEntries.files.remove(tarEntry.getName()); } } // Check that all files and directories have been accounted for assertTrue("All directories should be in the tar", archiveEntries.dirs.isEmpty()); assertTrue("All files should be in the tar", archiveEntries.files.isEmpty()); } catch (ArchiveException e) { throw new IOException(e); } finally { if (null != tarInputStream) { tarInputStream.close(); } } } @Test public void testTarGzArchiveNullPrefix () throws IOException { final String archiveFilePath = testTarGzArchive(null, testFileStructure01); assertTrue("Should test as .tar.gz file (testZipArchiveNullPrefix)", archiveFilePath.endsWith(TAR_GZ_FILE_SUFFIX)); } @Test public void testTarGzArchiveEmptyPrefix () throws IOException { final String archiveFilePath = testTarGzArchive("", testFileStructure01); assertTrue("Should test as .tar.gz file (testZipArchiveEmptyPrefix)", archiveFilePath.endsWith(TAR_GZ_FILE_SUFFIX)); } @Test public void testTarGzArchivePrefix () throws IOException { final String archiveFilePath = testTarGzArchive("prefix/path", testFileStructure01); assertTrue("Should test as .tar.gz file (testZipArchivePrefix)", archiveFilePath.endsWith(TAR_GZ_FILE_SUFFIX)); } @Test public void testTarGzArchiveWinPrefix () throws IOException { final String archiveFilePath = testTarGzArchive("prefix\\path\\win", testFileStructure01); assertTrue("Should test as .tar.gz file (testZipArchiveWinPrefix)", archiveFilePath.endsWith(TAR_GZ_FILE_SUFFIX)); } private String testTarGzArchive (final String prefix, final String[] fileStructure) throws IOException { final File rootFolder = tempFolder.newFolder(); createDirectoryTree(rootFolder, fileStructure); final String testArchiveName = "archive-test-" + random.nextInt() + TAR_GZ_FILE_SUFFIX; final File archiveFile = tempFolder.newFile(testArchiveName); DirectoryArchiverUtil.createGZippedTarArchiveOfDirectory(archiveFile.getAbsolutePath(), rootFolder, prefix); assertTrue("Tar GZ file should not be zero sized", archiveFile.length() > 0); checkTarGzArchive(archiveFile, rootFolder, prefix); return archiveFile.getPath(); } private void checkTarGzArchive (final File archiveFile, final File sourceDirectory, final String pathPrefix) throws IOException { FileInputStream fin = null; CompressorInputStream gzIn = null; FileOutputStream out = null; final File unGzippedTar = tempFolder.newFile("archive-test-" + random.nextInt() + TAR_FILE_SUFFIX); try { fin = new FileInputStream(archiveFile); final BufferedInputStream in = new BufferedInputStream(fin); out = new FileOutputStream(unGzippedTar); gzIn = new CompressorStreamFactory().createCompressorInputStream(CompressorStreamFactory.GZIP, in); IOUtils.copy(gzIn, out); } catch (CompressorException e) { throw new IOException(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(gzIn); IOUtils.closeQuietly(fin); } checkTarArchive(unGzippedTar, sourceDirectory, pathPrefix); } private ArchiveEntries createArchiveEntries (final File sourceDirectory, final String pathPrefix) throws IOException { final ArchiveEntries archiveEntries = new ArchiveEntries(); final Path sourcePath = Paths.get(sourceDirectory.toURI()); final StringBuilder normalizedPathPrefix = new StringBuilder(); if (null != pathPrefix && !pathPrefix.isEmpty()) { normalizedPathPrefix.append(pathPrefix.replace("\\", "/")); if (normalizedPathPrefix.charAt(normalizedPathPrefix.length() - 1) != '/') { normalizedPathPrefix.append('/'); } } Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path> () { @Override public FileVisitResult preVisitDirectory (final Path dir, final BasicFileAttributes attrs) throws IOException { final Path relativeSourcePath = sourcePath.relativize(dir); String normalizedPath = normalizedPathPrefix.toString() + relativeSourcePath; if (!normalizedPath.isEmpty()) { if (!normalizedPath.endsWith("/")) { normalizedPath += "/"; } archiveEntries.dirs.add(normalizedPath.replace("\\", "/")); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile (final Path file, final BasicFileAttributes attrs) throws IOException { final Path relativeSourcePath = sourcePath.relativize(file); final String normalizedPath = normalizedPathPrefix.toString() + relativeSourcePath; final byte[] md5Digest = getMd5Digest(Files.newInputStream(file), true); archiveEntries.files.put(normalizedPath.replace("\\", "/"), md5Digest); return FileVisitResult.CONTINUE; } }); return archiveEntries; } private void createDirectoryTree (final File parentDir, final String... fileEntries) throws IOException { final String parentPath = parentDir.getAbsolutePath(); for (String fileEntry : fileEntries) { final File entry = new File (parentPath + "/" + fileEntry); if (fileEntry.endsWith("/")) { ensureDirectoryExists(entry); } else { // Create file ensureDirectoryExists(entry.getParentFile()); if (!entry.createNewFile()) { throw new IOException("Error creating file : " + entry.getAbsolutePath()); } if (fileEntry.endsWith(".txt")) { FileWriter fileWriter = null; try { fileWriter = new FileWriter(entry); // Write random characters final int fileSize = random.nextInt(MAX_FILE_SIZE); for (int i = 0; i < fileSize; i++) { fileWriter.write((char) (VALID_CHARS.charAt(random.nextInt(VALID_CHARS.length())))); } } finally { if (null != fileWriter) { try { fileWriter.flush(); } catch (IOException e) { // Ignore } try { fileWriter.close(); } catch (IOException e) { // Ignore } } } } else { FileOutputStream fos = null; try { fos = new FileOutputStream(entry); // Write random bytes final byte[] buf = new byte[random.nextInt(MAX_FILE_SIZE)]; random.nextBytes(buf); fos.write(buf); } finally { if (null != fos) { try { fos.flush(); } catch (IOException e) { // Ignore } try { fos.close(); } catch (IOException e) { // Ignore } } } } } } } private byte[] getMd5Digest (final InputStream inputStream, final boolean closeStream) throws IOException { try { final MessageDigest md = MessageDigest.getInstance("MD5"); final DigestInputStream dis = new DigestInputStream(inputStream, md); final byte[] buf = new byte[MAX_FILE_SIZE]; int len = 0; while (len != -1) { len = dis.read(buf); } return md.digest(); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } finally { if (closeStream && null != inputStream) { inputStream.close(); } } } private void ensureDirectoryExists (final File directory) throws IOException { if (!directory.exists()) { if (!directory.mkdirs()) { throw new IOException("Error creating file: " + directory.getAbsolutePath()); } } else if (!directory.isDirectory()) { throw new IOException("Requested directory does not exist: " + directory.getAbsolutePath()); } } private class ArchiveEntries { private Set<String> dirs = new HashSet<>(); private Map<String, byte[]> files = new HashMap<>(); } }
38.581262
114
0.735108
22bc6a279934ed5f7aa020a3722a1eacd75c6e85
5,013
package com.ctre.phoenix.motorcontrol; import com.ctre.phoenix.ErrorCode; import com.ctre.phoenix.motorcontrol.can.BaseTalon; import com.ctre.phoenix.motorcontrol.can.MotControllerJNI; /** * Collection of sensors available to the Talon FX. * <p> * For best performance and update-rate, we recommend using the * configSelectedFeedbackSensor() and getSelectedSensor*() routines. However * there are occasions where accessing raw sensor values may be useful or * convenient. Particularly if you are seeding one sensor based on another, or * need to circumvent sensor-phase. * <p> * Use the getTalonFXSensorCollection() routine inside your motor controller to create * a sensor collection. */ public class TalonFXSensorCollection { private long _handle; /** * Constructor for SensorCollection * * @param motorController Motor Controller to connect Collection to */ public TalonFXSensorCollection(BaseTalon motorController) { _handle = motorController.getHandle(); } /** * Get the IntegratedSensor position of the Talon FX, regardless of whether * it is actually being used for feedback. The units are 2048 per rotation. * Note : Future versions of software may support scaling features (rotations, radians, degrees, etc) depending on the configuration. * * @return the IntegratedSensor position. */ public double getIntegratedSensorPosition() { return MotControllerJNI.GetIntegratedSensorPosition(_handle); } /** * Get the IntegratedSensor absolute position of the Talon FX, regardless of whether * it is actually being used for feedback. This will be within one rotation (2048 units). * The signage and range will depend on the configuration. * Note : Future versions of software may support scaling features (rotations, radians, degrees, etc) depending on the configuration. * * @return the IntegratedSensor absolute position. */ public double getIntegratedSensorAbsolutePosition() { return MotControllerJNI.GetIntegratedSensorAbsolutePosition(_handle); } /** * Get the IntegratedSensor velocity of the Talon FX, regardless of whether * it is actually being used for feedback. * One unit represents one position unit per 100ms (2048 position units per 100ms). * The signage and range will depend on the configuration. * Note : Future versions of software may support scaling features (rotations, radians, degrees, etc) depending on the configuration. * * @return the IntegratedSensor velocity. */ public double getIntegratedSensorVelocity() { return MotControllerJNI.GetIntegratedSensorVelocity(_handle); } /** * Set the IntegratedSensor reported position. Typically this is used to "zero" the * sensor. This only works with IntegratedSensor. To set the selected sensor position * regardless of what type it is, see SetSelectedSensorPosition in the motor controller class. * * @param newPosition The position value to apply to the sensor. * @param timeoutMs Timeout value in ms. If nonzero, function will wait for * config success and report an error if it times out. * If zero, no blocking or checking is performed. * @return error code. */ public ErrorCode setIntegratedSensorPosition(double newPosition, int timeoutMs) { return ErrorCode.valueOf(MotControllerJNI.SetIntegratedSensorPosition(_handle, newPosition, timeoutMs)); } /** * Set the IntegratedSensor reported position based on the absolute position. * This can also be done automatically on power boot depending on configuration. * * @param timeoutMs Timeout value in ms. If nonzero, function will wait for * config success and report an error if it times out. * If zero, no blocking or checking is performed. * @return error code. */ public ErrorCode setIntegratedSensorPositionToAbsolute(int timeoutMs) { return ErrorCode.valueOf(MotControllerJNI.SetIntegratedSensorPositionToAbsolute(_handle, timeoutMs)); } /** * Is forward limit switch closed. * * @return '1' iff forward limit switch is closed, 0 iff switch is open. This function works * regardless if limit switch feature is enabled. Remote limit features do not impact this routine. */ public int isFwdLimitSwitchClosed() { return MotControllerJNI.IsFwdLimitSwitchClosed(_handle); } /** * Is reverse limit switch closed. * * @return '1' iff reverse limit switch is closed, 0 iff switch is open. This function works * regardless if limit switch feature is enabled. Remote limit features do not impact this routine. */ public int isRevLimitSwitchClosed() { return MotControllerJNI.IsRevLimitSwitchClosed(_handle); } }
43.591304
137
0.70377
77daef99267289d4ef5e6f0167d8847a70a03bff
317
package algorithm.settings.domain; import javax.xml.bind.annotation.XmlSeeAlso; /** * Superclass for all available UI settings. * * @author Lukas Brchl */ @XmlSeeAlso({PreprocessingSettings.class,PreviewSettings.class, MogSettings.class, EdgeDetectSettings.class}) public abstract class Settings { }
22.642857
110
0.760252
e6497a01905df33818e6f6959cae3b5a2b1eef4b
5,891
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.cloud.git.gogs; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.kie.cloud.git.AbstractGitProvider; import org.apache.http.client.fluent.Request; import org.kie.cloud.git.constants.GitConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GogsGitProvider extends AbstractGitProvider { private final String url; private final String user; private final String password; private static final String URL_API_SUFFIX = "/api/v1/"; private static final String URL_CREATE_REPOSITORY_SUFFIX = "user/repos"; private static final String URL_REPOSITORY_SUFFIX = "repos/"; private static final String URL_GIT_SUFFIX = ".git"; private static final Logger logger = LoggerFactory.getLogger(GogsGitProvider.class); public GogsGitProvider(String url, String user, String password) { this.url = url; this.user = user; this.password = password; } @Override public String createGitRepositoryWithPrefix(String repositoryPrefixName, String repositoryPath) { final String repositoryName = generateRepositoryName(repositoryPrefixName); createRepository(repositoryName); pushToGitRepository(getRepositoryUrl(repositoryName), repositoryPath, user, password); return repositoryName; } @Override public void deleteGitRepository(String repositoryName) { try { final int statusCode = Request.Delete(deleteRepositoryUrl(repositoryName)) .addHeader(HttpHeaders.AUTHORIZATION, authHeaderValue()) .execute() .returnResponse() .getStatusLine() .getStatusCode(); if (statusCode != HttpStatus.SC_NO_CONTENT) { logger.error("Bad status code while deleting Gogs project {}", statusCode); throw new RuntimeException("Bad status code while deleting Gogs project " + statusCode); } } catch (Exception e) { logger.error("Error while deleting Git repository {}", repositoryName); throw new RuntimeException("Error while deleting Git repository", e); } } @Override public String getRepositoryUrl(String repositoryName) { try { URL repositoryUrl = new URL(url); repositoryUrl = new URL(repositoryUrl, user + "/"); repositoryUrl = new URL(repositoryUrl, repositoryName + URL_GIT_SUFFIX); return repositoryUrl.toString(); } catch (MalformedURLException e) { logger.error("Unable to build repository url"); throw new RuntimeException("Unable to build repository url", e); } } private void createRepository(String repositoryName) { try { final int statusCode = Request.Post(createRepositoryUrl()) .addHeader(HttpHeaders.AUTHORIZATION, authHeaderValue()) .bodyString("{ \"name\" : \""+ repositoryName + "\" }", ContentType.APPLICATION_JSON) .execute() .returnResponse() .getStatusLine() .getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { logger.error("Bad status code while preparing Gogs project {}", statusCode); throw new RuntimeException("Bad status code while preparing Gogs project " + statusCode); } } catch (Exception e) { logger.error("Error while creating Git repository {}", repositoryName); throw new RuntimeException("Error while creating Git repository", e); } } private String createRepositoryUrl() { try { URL requestUrl = new URL(url); requestUrl = new URL(requestUrl, URL_API_SUFFIX); requestUrl = new URL(requestUrl, URL_CREATE_REPOSITORY_SUFFIX); return requestUrl.toString(); } catch (MalformedURLException e) { logger.error("Error building create repository url"); throw new RuntimeException("Error building create repository url", e); } } private String deleteRepositoryUrl(String repositoryName) { try { URL requestUrl = new URL(url); requestUrl = new URL(requestUrl, URL_API_SUFFIX); requestUrl = new URL(requestUrl, URL_REPOSITORY_SUFFIX); requestUrl = new URL(requestUrl, user + "/"); requestUrl = new URL(requestUrl, repositoryName); return requestUrl.toString(); } catch (MalformedURLException e) { logger.error("Error building delete repository url"); throw new RuntimeException("Error building delete repository url", e); } } private String authHeaderValue() { final String auth = user + ":" + password; byte[] encodedAuth = Base64.getEncoder().encode( auth.getBytes(StandardCharsets.UTF_8)); final String authHeader = "Basic " + new String(encodedAuth); return authHeader; } }
39.804054
111
0.650314
3a12bfe1e1c9468d6f8e2a6103e2743695bb3b75
1,976
package com.ikouz.algorithm.leetcode; import com.ikouz.algorithm.leetcode.utils.TestUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Given two arrays, write a function to compute their intersection. * <p> * Example: * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. * <p> * Note: * Each element in the result should appear as many times as it shows in both arrays. * The result can be in any order. * <p> * Follow up: * What if the given array is already sorted? How would you optimize your algorithm? * What if nums1's size is small compared to nums2's size? Which algorithm is better? * What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? * * @author liujiaming * @since 2017/07/13 */ public class HashTable_350_IntersectionofTwoArraysII { public static int[] intersect(int[] nums1, int[] nums2) { int[] arrLong = nums1.length > nums2.length ? nums1 : nums2; int[] arrShort = nums1.length > nums2.length ? nums2 : nums1; List<Integer> list = new ArrayList<>(); HashMap<Integer, Integer> map = new HashMap<>(arrShort.length); for (int i : arrShort) { if (map.containsKey(i)) { map.put(i, map.get(i) + 1); } else { map.put(i, 1); } } for (int i : arrLong) { if (map.containsKey(i) && map.get(i) > 0) { list.add(i); map.put(i, map.get(i) - 1); } } int[] ret = new int[list.size()]; for (int i = 0; i < list.size(); i++) { ret[i] = list.get(i); } return ret; } public static void main(String[] args) { int[] ints = TestUtil.buildIntArr("[1,1,2,3,4]"); int[] ints1 = TestUtil.buildIntArr("[1,2,5]"); TestUtil.printIntArr(intersect(ints, ints1)); } }
32.933333
138
0.586538
a843585c8de52e3ef5ed76b7fab5d917e12bbb25
2,310
package com.airbnb.lottie.p089c.p090a; import android.graphics.PointF; import com.airbnb.lottie.C5851x; import com.airbnb.lottie.p085a.p086a.C5678c; import com.airbnb.lottie.p085a.p086a.C5689n; import com.airbnb.lottie.p085a.p087b.C5713o; import com.airbnb.lottie.p089c.p091b.C5736b; import com.airbnb.lottie.p089c.p092c.C5762c; /* renamed from: com.airbnb.lottie.c.a.l */ /* compiled from: AnimatableTransform */ public class C5731l implements C5689n, C5736b { /* renamed from: a */ private final C5724e f9836a; /* renamed from: b */ private final C5732m<PointF, PointF> f9837b; /* renamed from: c */ private final C5726g f9838c; /* renamed from: d */ private final C5721b f9839d; /* renamed from: e */ private final C5723d f9840e; /* renamed from: f */ private final C5721b f9841f; /* renamed from: g */ private final C5721b f9842g; public C5731l() { this(new C5724e(), new C5724e(), new C5726g(), new C5721b(), new C5723d(), new C5721b(), new C5721b()); } public C5731l(C5724e anchorPoint, C5732m<PointF, PointF> position, C5726g scale, C5721b rotation, C5723d opacity, C5721b startOpacity, C5721b endOpacity) { this.f9836a = anchorPoint; this.f9837b = position; this.f9838c = scale; this.f9839d = rotation; this.f9840e = opacity; this.f9841f = startOpacity; this.f9842g = endOpacity; } /* renamed from: b */ public C5724e mo17988b() { return this.f9836a; } /* renamed from: e */ public C5732m<PointF, PointF> mo17991e() { return this.f9837b; } /* renamed from: g */ public C5726g mo17993g() { return this.f9838c; } /* renamed from: f */ public C5721b mo17992f() { return this.f9839d; } /* renamed from: d */ public C5723d mo17990d() { return this.f9840e; } /* renamed from: h */ public C5721b mo17994h() { return this.f9841f; } /* renamed from: c */ public C5721b mo17989c() { return this.f9842g; } /* renamed from: a */ public C5713o mo17987a() { return new C5713o(this); } /* renamed from: a */ public C5678c mo17986a(C5851x drawable, C5762c layer) { return null; } }
24.315789
159
0.622078
711ad59bac6e55aca4aba1a5714c13d7b0a4cfe7
645
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.search.api.config; import net.sf.mmm.util.xml.base.jaxb.JaxbBeanHolder; /** * This is the interface for a container {@link #getBean() holding} the {@link SearchConfiguration}. * * @see JaxbBeanHolder * * @param <T> is the generic type of the {@link #getBean() configuration}. * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public interface SearchConfigurationHolder<T extends SearchConfiguration> extends JaxbBeanHolder<T> { // nothing to add... }
30.714286
101
0.72093
b4c33671c42b533001da603f87b668baecb7d69d
2,605
package org.talend.mq; import java.util.Hashtable; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.ibm.mq.MQQueueManager; import junit.framework.TestCase; @PowerMockIgnore("javax.management.*") @RunWith(PowerMockRunner.class) @PrepareForTest(SharedWebSphereMQConnection.class) public class TestSharedWebShpereMQConn extends TestCase { Hashtable<String, Object> properties = new java.util.Hashtable<String, Object>(); @After public void clear() { SharedWebSphereMQConnection.clear(); } @Test public void testSameConnName() throws Exception { setUpPowerMock(); MQQueueManager mqConnection1 = SharedWebSphereMQConnection.getMQConnection("TALEND", properties, "conn"); setUpPowerMock(); MQQueueManager mqConnection2 = SharedWebSphereMQConnection.getMQConnection("TALEND", properties, "conn"); assertSame(mqConnection1, mqConnection2); } @Test public void testDiffConnName() throws Exception { setUpPowerMock(); MQQueueManager mqConnection1 = SharedWebSphereMQConnection.getMQConnection("TALEND", properties, "conn1"); setUpPowerMock(); MQQueueManager mqConnection2 = SharedWebSphereMQConnection.getMQConnection("TALEND", properties, "conn2"); assertNotSame(mqConnection1, mqConnection2); } @Before public void prepare() throws Exception { properties.put("hostname", "localhost"); properties.put("port", Integer.valueOf("1414")); properties.put("channel", "TALEND.CH"); properties.put("CCSID", new Integer(1208)); properties.put("transport", "MQSeries"); } private void setUpPowerMock() throws Exception { // we need to return new queue manager on every call of createQueueManager MQQueueManager queueManagerMock = Mockito.mock(MQQueueManager.class); // we need the queue manager to be "connected" every time. If it isn't, it won't be used, and a new one will // be created for the same connection name Mockito.when(queueManagerMock.isConnected()).thenReturn(true); PowerMockito.whenNew(MQQueueManager.class).withAnyArguments().thenReturn(queueManagerMock); } }
37.214286
117
0.710173
86f519e0105db1ccf90f25944cac5070f599e9ef
8,421
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation.testdata; import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker; /** Tests for !=. */ public class NullnessPropagationTransferCases5 { public void notEqualBothNull() { String str1 = null; if (str1 != null) { // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); if (null != str1) { // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); String str2 = null; if (str1 != str2) { // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } public void notEqualBothNonNull() { String str1 = "foo"; if (str1 != "bar") { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); if ("bar" != str1) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); String str2 = "bar"; if (str1 != str2) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } public void notEqualOneNullOtherNonNull() { String str1 = "foo"; if (str1 != null) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); if (null != str1) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); String str2 = null; if (str1 != str2) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); if (str2 != str1) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Bottom) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } public void notEqualOneNullableOtherNull(String nullableParam) { String str1 = nullableParam; if (str1 != null) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); if (null != str1) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); String str2 = null; if (str1 != str2) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); if (str2 != str1) { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Null) triggerNullnessChecker(str2); } public void notEqualOneNullableOtherNonNull(String nullableParam) { String str1 = nullableParam; if (str1 != "foo") { // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); if ("foo" != str1) { // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); } else { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); String str2 = "foo"; if (str1 != str2) { // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); if (str2 != str1) { // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } else { // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } // BUG: Diagnostic contains: (Nullable) triggerNullnessChecker(str1); // BUG: Diagnostic contains: (Non-null) triggerNullnessChecker(str2); } // TODO(eaftan): tests for bottom? }
30.733577
112
0.646954
b3b6449533e21030b877b21eb885319e999cbf41
392
package info.dong4j.idea.plugin.sdk.qcloud.cos.exception; public class FileLockException extends CosClientException { private static final long serialVersionUID = 1L; public FileLockException(Throwable t) { super(t); } public FileLockException(String msg) { super(msg); } @Override public boolean isRetryable() { return false; } }
19.6
59
0.670918
4f156baa4fcb0b622b426a32608cb20cfedf894e
42,900
/* ==================================================================== 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.poi.xslf.usermodel; import org.apache.poi.util.Beta; import org.apache.poi.util.Internal; import org.apache.poi.util.Units; import org.apache.poi.xslf.model.ParagraphPropertyFetcher; import org.apache.xmlbeans.XmlObject; import org.openxmlformats.schemas.drawingml.x2006.main.*; import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType; import java.awt.Color; import java.awt.Graphics2D; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Represents a paragraph of text within the containing text body. * The paragraph is the highest level text separation mechanism. * * @author Yegor Kozlov * @since POI-3.8 */ @Beta public class XSLFTextParagraph implements Iterable<XSLFTextRun>{ private final CTTextParagraph _p; private final List<XSLFTextRun> _runs; private final XSLFTextShape _shape; private List<TextFragment> _lines; private TextFragment _bullet; /** * the highest line in this paragraph. Used for line spacing. */ private double _maxLineHeight; XSLFTextParagraph(CTTextParagraph p, XSLFTextShape shape){ _p = p; _runs = new ArrayList<XSLFTextRun>(); _shape = shape; for(XmlObject ch : _p.selectPath("*")){ if(ch instanceof CTRegularTextRun){ CTRegularTextRun r = (CTRegularTextRun)ch; _runs.add(new XSLFTextRun(r, this)); } else if (ch instanceof CTTextLineBreak){ CTTextLineBreak br = (CTTextLineBreak)ch; CTRegularTextRun r = CTRegularTextRun.Factory.newInstance(); r.setRPr(br.getRPr()); r.setT("\n"); _runs.add(new XSLFTextRun(r, this)); } else if (ch instanceof CTTextField){ CTTextField f = (CTTextField)ch; CTRegularTextRun r = CTRegularTextRun.Factory.newInstance(); r.setRPr(f.getRPr()); r.setT(f.getT()); _runs.add(new XSLFTextRun(r, this)); } } } public String getText(){ StringBuilder out = new StringBuilder(); for (XSLFTextRun r : _runs) { out.append(r.getText()); } return out.toString(); } String getRenderableText(){ StringBuilder out = new StringBuilder(); for (XSLFTextRun r : _runs) { out.append(r.getRenderableText()); } return out.toString(); } @Internal public CTTextParagraph getXmlObject(){ return _p; } XSLFTextShape getParentShape() { return _shape; } public List<XSLFTextRun> getTextRuns(){ return _runs; } public Iterator<XSLFTextRun> iterator(){ return _runs.iterator(); } /** * Add a new run of text * * @return a new run of text */ public XSLFTextRun addNewTextRun(){ CTRegularTextRun r = _p.addNewR(); CTTextCharacterProperties rPr = r.addNewRPr(); rPr.setLang("en-US"); XSLFTextRun run = new XSLFTextRun(r, this); _runs.add(run); return run; } /** * Insert a line break * * @return text run representing this line break ('\n') */ public XSLFTextRun addLineBreak(){ CTTextLineBreak br = _p.addNewBr(); CTTextCharacterProperties brProps = br.addNewRPr(); if(_runs.size() > 0){ // by default line break has the font size of the last text run CTTextCharacterProperties prevRun = _runs.get(_runs.size() - 1).getRPr(); brProps.set(prevRun); } CTRegularTextRun r = CTRegularTextRun.Factory.newInstance(); r.setRPr(brProps); r.setT("\n"); XSLFTextRun run = new XSLFLineBreak(r, this, brProps); _runs.add(run); return run; } /** * Returns the alignment that is applied to the paragraph. * * If this attribute is omitted, then a value of left is implied. * @return ??? alignment that is applied to the paragraph */ public TextAlign getTextAlign(){ ParagraphPropertyFetcher<TextAlign> fetcher = new ParagraphPropertyFetcher<TextAlign>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetAlgn()){ TextAlign val = TextAlign.values()[props.getAlgn().intValue() - 1]; setValue(val); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue() == null ? TextAlign.LEFT : fetcher.getValue(); } /** * Specifies the alignment that is to be applied to the paragraph. * Possible values for this include left, right, centered, justified and distributed, * see {@link org.apache.poi.xslf.usermodel.TextAlign}. * * @param align text align */ public void setTextAlign(TextAlign align){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); if(align == null) { if(pr.isSetAlgn()) pr.unsetAlgn(); } else { pr.setAlgn(STTextAlignType.Enum.forInt(align.ordinal() + 1)); } } /** * @return the font to be used on bullet characters within a given paragraph */ public String getBulletFont(){ ParagraphPropertyFetcher<String> fetcher = new ParagraphPropertyFetcher<String>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetBuFont()){ setValue(props.getBuFont().getTypeface()); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue(); } public void setBulletFont(String typeface){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTTextFont font = pr.isSetBuFont() ? pr.getBuFont() : pr.addNewBuFont(); font.setTypeface(typeface); } /** * @return the character to be used in place of the standard bullet point */ public String getBulletCharacter(){ ParagraphPropertyFetcher<String> fetcher = new ParagraphPropertyFetcher<String>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetBuChar()){ setValue(props.getBuChar().getChar()); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue(); } public void setBulletCharacter(String str){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTTextCharBullet c = pr.isSetBuChar() ? pr.getBuChar() : pr.addNewBuChar(); c.setChar(str); } /** * * @return the color of bullet characters within a given paragraph. * A <code>null</code> value means to use the text font color. */ public Color getBulletFontColor(){ final XSLFTheme theme = getParentShape().getSheet().getTheme(); ParagraphPropertyFetcher<Color> fetcher = new ParagraphPropertyFetcher<Color>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetBuClr()){ XSLFColor c = new XSLFColor(props.getBuClr(), theme, null); setValue(c.getColor()); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue(); } /** * Set the color to be used on bullet characters within a given paragraph. * * @param color the bullet color */ public void setBulletFontColor(Color color){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTColor c = pr.isSetBuClr() ? pr.getBuClr() : pr.addNewBuClr(); CTSRgbColor clr = c.isSetSrgbClr() ? c.getSrgbClr() : c.addNewSrgbClr(); clr.setVal(new byte[]{(byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()}); } /** * Returns the bullet size that is to be used within a paragraph. * This may be specified in two different ways, percentage spacing and font point spacing: * <p> * If bulletSize >= 0, then bulletSize is a percentage of the font size. * If bulletSize < 0, then it specifies the size in points * </p> * * @return the bullet size */ public double getBulletFontSize(){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetBuSzPct()){ setValue(props.getBuSzPct().getVal() * 0.001); return true; } if(props.isSetBuSzPts()){ setValue( - props.getBuSzPts().getVal() * 0.01); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue() == null ? 100 : fetcher.getValue(); } /** * Sets the bullet size that is to be used within a paragraph. * This may be specified in two different ways, percentage spacing and font point spacing: * <p> * If bulletSize >= 0, then bulletSize is a percentage of the font size. * If bulletSize < 0, then it specifies the size in points * </p> */ public void setBulletFontSize(double bulletSize){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); if(bulletSize >= 0) { CTTextBulletSizePercent pt = pr.isSetBuSzPct() ? pr.getBuSzPct() : pr.addNewBuSzPct(); pt.setVal((int)(bulletSize*1000)); if(pr.isSetBuSzPts()) pr.unsetBuSzPts(); } else { CTTextBulletSizePoint pt = pr.isSetBuSzPts() ? pr.getBuSzPts() : pr.addNewBuSzPts(); pt.setVal((int)(-bulletSize*100)); if(pr.isSetBuSzPct()) pr.unsetBuSzPct(); } } /** * Specifies the indent size that will be applied to the first line of text in the paragraph. * * @param value the indent in points. */ public void setIndent(double value){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); if(value == -1) { if(pr.isSetIndent()) pr.unsetIndent(); } else { pr.setIndent(Units.toEMU(value)); } } /** * * @return the indent applied to the first line of text in the paragraph. */ public double getIndent(){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetIndent()){ setValue(Units.toPoints(props.getIndent())); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue() == null ? 0 : fetcher.getValue(); } /** * Specifies the left margin of the paragraph. This is specified in addition to the text body * inset and applies only to this text paragraph. That is the text body Inset and the LeftMargin * attributes are additive with respect to the text position. * * @param value the left margin of the paragraph */ public void setLeftMargin(double value){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); if(value == -1) { if(pr.isSetMarL()) pr.unsetMarL(); } else { pr.setMarL(Units.toEMU(value)); } } /** * * @return the left margin of the paragraph */ public double getLeftMargin(){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetMarL()){ double val = Units.toPoints(props.getMarL()); setValue(val); return true; } return false; } }; fetchParagraphProperty(fetcher); // if the marL attribute is omitted, then a value of 347663 is implied return fetcher.getValue() == null ? 0 : fetcher.getValue(); } /** * * @return the default size for a tab character within this paragraph in points */ public double getDefaultTabSize(){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetDefTabSz()){ double val = Units.toPoints(props.getDefTabSz()); setValue(val); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue() == null ? 0 : fetcher.getValue(); } public double getTabStop(final int idx){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetTabLst()){ CTTextTabStopList tabStops = props.getTabLst(); if(idx < tabStops.sizeOfTabArray() ) { CTTextTabStop ts = tabStops.getTabArray(idx); double val = Units.toPoints(ts.getPos()); setValue(val); return true; } } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue() == null ? 0. : fetcher.getValue(); } public void addTabStop(double value){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTTextTabStopList tabStops = pr.isSetTabLst() ? pr.getTabLst() : pr.addNewTabLst(); tabStops.addNewTab().setPos(Units.toEMU(value)); } /** * This element specifies the vertical line spacing that is to be used within a paragraph. * This may be specified in two different ways, percentage spacing and font point spacing: * <p> * If linespacing >= 0, then linespacing is a percentage of normal line height * If linespacing < 0, the absolute value of linespacing is the spacing in points * </p> * Examples: * <pre><code> * // spacing will be 120% of the size of the largest text on each line * paragraph.setLineSpacing(120); * * // spacing will be 200% of the size of the largest text on each line * paragraph.setLineSpacing(200); * * // spacing will be 48 points * paragraph.setLineSpacing(-48.0); * </code></pre> * * @param linespacing the vertical line spacing */ public void setLineSpacing(double linespacing){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); if(linespacing >= 0) spc.addNewSpcPct().setVal((int)(linespacing*1000)); else spc.addNewSpcPts().setVal((int)(-linespacing*100)); pr.setLnSpc(spc); } /** * Returns the vertical line spacing that is to be used within a paragraph. * This may be specified in two different ways, percentage spacing and font point spacing: * <p> * If linespacing >= 0, then linespacing is a percentage of normal line height. * If linespacing < 0, the absolute value of linespacing is the spacing in points * </p> * * @return the vertical line spacing. */ public double getLineSpacing(){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetLnSpc()){ CTTextSpacing spc = props.getLnSpc(); if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); return true; } return false; } }; fetchParagraphProperty(fetcher); double lnSpc = fetcher.getValue() == null ? 100 : fetcher.getValue(); if(lnSpc > 0) { // check if the percentage value is scaled CTTextNormalAutofit normAutofit = getParentShape().getTextBodyPr().getNormAutofit(); if(normAutofit != null) { double scale = 1 - (double)normAutofit.getLnSpcReduction() / 100000; lnSpc *= scale; } } return lnSpc; } /** * Set the amount of vertical white space that will be present before the paragraph. * This space is specified in either percentage or points: * <p> * If spaceBefore >= 0, then space is a percentage of normal line height. * If spaceBefore < 0, the absolute value of linespacing is the spacing in points * </p> * Examples: * <pre><code> * // The paragraph will be formatted to have a spacing before the paragraph text. * // The spacing will be 200% of the size of the largest text on each line * paragraph.setSpaceBefore(200); * * // The spacing will be a size of 48 points * paragraph.setSpaceBefore(-48.0); * </code></pre> * * @param spaceBefore the vertical white space before the paragraph. */ public void setSpaceBefore(double spaceBefore){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); if(spaceBefore >= 0) spc.addNewSpcPct().setVal((int)(spaceBefore*1000)); else spc.addNewSpcPts().setVal((int)(-spaceBefore*100)); pr.setSpcBef(spc); } /** * The amount of vertical white space before the paragraph * This may be specified in two different ways, percentage spacing and font point spacing: * <p> * If spaceBefore >= 0, then space is a percentage of normal line height. * If spaceBefore < 0, the absolute value of linespacing is the spacing in points * </p> * * @return the vertical white space before the paragraph */ public double getSpaceBefore(){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetSpcBef()){ CTTextSpacing spc = props.getSpcBef(); if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); return true; } return false; } }; fetchParagraphProperty(fetcher); double spcBef = fetcher.getValue() == null ? 0 : fetcher.getValue(); return spcBef; } /** * Set the amount of vertical white space that will be present after the paragraph. * This space is specified in either percentage or points: * <p> * If spaceAfter >= 0, then space is a percentage of normal line height. * If spaceAfter < 0, the absolute value of linespacing is the spacing in points * </p> * Examples: * <pre><code> * // The paragraph will be formatted to have a spacing after the paragraph text. * // The spacing will be 200% of the size of the largest text on each line * paragraph.setSpaceAfter(200); * * // The spacing will be a size of 48 points * paragraph.setSpaceAfter(-48.0); * </code></pre> * * @param spaceAfter the vertical white space after the paragraph. */ public void setSpaceAfter(double spaceAfter){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); if(spaceAfter >= 0) spc.addNewSpcPct().setVal((int)(spaceAfter*1000)); else spc.addNewSpcPts().setVal((int)(-spaceAfter*100)); pr.setSpcAft(spc); } /** * The amount of vertical white space after the paragraph * This may be specified in two different ways, percentage spacing and font point spacing: * <p> * If spaceBefore >= 0, then space is a percentage of normal line height. * If spaceBefore < 0, the absolute value of linespacing is the spacing in points * </p> * * @return the vertical white space after the paragraph */ public double getSpaceAfter(){ ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetSpcAft()){ CTTextSpacing spc = props.getSpcAft(); if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue() == null ? 0 : fetcher.getValue(); } /** * Specifies the particular level text properties that this paragraph will follow. * The value for this attribute formats the text according to the corresponding level * paragraph properties defined in the SlideMaster. * * @param level the level (0 ... 4) */ public void setLevel(int level){ CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); pr.setLvl(level); } /** * * @return the text level of this paragraph (0-based). Default is 0. */ public int getLevel(){ CTTextParagraphProperties pr = _p.getPPr(); if(pr == null) return 0; return pr.getLvl(); } /** * Returns whether this paragraph has bullets */ public boolean isBullet() { ParagraphPropertyFetcher<Boolean> fetcher = new ParagraphPropertyFetcher<Boolean>(getLevel()){ public boolean fetch(CTTextParagraphProperties props){ if(props.isSetBuNone()) { setValue(false); return true; } if(props.isSetBuFont() || props.isSetBuChar()){ setValue(true); return true; } return false; } }; fetchParagraphProperty(fetcher); return fetcher.getValue() == null ? false : fetcher.getValue(); } /** * * @param flag whether text in this paragraph has bullets */ public void setBullet(boolean flag) { if(isBullet() == flag) return; CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); if(!flag) { pr.addNewBuNone(); } else { pr.addNewBuFont().setTypeface("Arial"); pr.addNewBuChar().setChar("\u2022"); } } /** * Specifies that automatic numbered bullet points should be applied to this paragraph * * @param scheme type of auto-numbering * @param startAt the number that will start number for a given sequence of automatically numbered bullets (1-based). */ public void setBulletAutoNumber(ListAutoNumber scheme, int startAt) { if(startAt < 1) throw new IllegalArgumentException("Start Number must be greater or equal that 1") ; CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); CTTextAutonumberBullet lst = pr.isSetBuAutoNum() ? pr.getBuAutoNum() : pr.addNewBuAutoNum(); lst.setType(STTextAutonumberScheme.Enum.forInt(scheme.ordinal() + 1)); lst.setStartAt(startAt); } @Override public String toString(){ return "[" + getClass() + "]" + getText(); } List<TextFragment> getTextLines(){ return _lines; } /** * Returns wrapping width to break lines in this paragraph * * @param firstLine whether the first line is breaking * * @return wrapping width in points */ double getWrappingWidth(boolean firstLine, Graphics2D graphics){ // internal margins for the text box double leftInset = _shape.getLeftInset(); double rightInset = _shape.getRightInset(); RenderableShape rShape = new RenderableShape(_shape); Rectangle2D anchor = rShape.getAnchor(graphics); double leftMargin = getLeftMargin(); double indent = getIndent(); double width; if(!_shape.getWordWrap()) { // if wordWrap == false then we return the advance to the right border of the sheet width = _shape.getSheet().getSlideShow().getPageSize().getWidth() - anchor.getX(); } else { width = anchor.getWidth() - leftInset - rightInset - leftMargin; if(firstLine) { if(isBullet()){ if(indent > 0) width -= indent; } else { if(indent > 0) width -= indent; // first line indentation else if (indent < 0) { // hanging indentation: the first line start at the left margin width += leftMargin; } } } } return width; } public double draw(Graphics2D graphics, double x, double y){ double leftInset = _shape.getLeftInset(); double rightInset = _shape.getRightInset(); RenderableShape rShape = new RenderableShape(_shape); Rectangle2D anchor = rShape.getAnchor(graphics); double penY = y; double leftMargin = getLeftMargin(); boolean firstLine = true; double indent = getIndent(); //The vertical line spacing double spacing = getLineSpacing(); for(TextFragment line : _lines){ double penX = x + leftMargin; if(firstLine) { if(_bullet != null){ if(indent < 0) { // a negative value means "Hanging" indentation and // indicates the position of the actual bullet character. // (the bullet is shifted to right relative to the text) _bullet.draw(graphics, penX + indent, penY); } else if(indent > 0){ // a positive value means the "First Line" indentation: // the first line is indented and other lines start at the bullet ofset _bullet.draw(graphics, penX, penY); penX += indent; } else { // a zero indent means that the bullet and text have the same offset _bullet.draw(graphics, penX, penY); // don't let text overlay the bullet and advance by the bullet width penX += _bullet._layout.getAdvance() + 1; } } else { penX += indent; } } switch (getTextAlign()) { case CENTER: penX += (anchor.getWidth() - leftMargin - line.getWidth() - leftInset - rightInset) / 2; break; case RIGHT: penX += (anchor.getWidth() - line.getWidth() - leftInset - rightInset); break; default: break; } line.draw(graphics, penX, penY); if(spacing > 0) { // If linespacing >= 0, then linespacing is a percentage of normal line height. penY += spacing*0.01* line.getHeight(); } else { // positive value means absolute spacing in points penY += -spacing; } firstLine = false; } return penY - y; } AttributedString getAttributedString(Graphics2D graphics){ String text = getRenderableText(); AttributedString string = new AttributedString(text); XSLFFontManager fontHandler = (XSLFFontManager)graphics.getRenderingHint(XSLFRenderingHint.FONT_HANDLER); int startIndex = 0; for (XSLFTextRun run : _runs){ int length = run.getRenderableText().length(); if(length == 0) { // skip empty runs continue; } int endIndex = startIndex + length; string.addAttribute(TextAttribute.FOREGROUND, run.getFontColor(), startIndex, endIndex); // user can pass an custom object to convert fonts String fontFamily = run.getFontFamily(); if(fontHandler != null) { fontFamily = fontHandler.getRendererableFont(fontFamily, run.getPitchAndFamily()); } string.addAttribute(TextAttribute.FAMILY, fontFamily, startIndex, endIndex); float fontSz = (float)run.getFontSize(); string.addAttribute(TextAttribute.SIZE, fontSz , startIndex, endIndex); if(run.isBold()) { string.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIndex, endIndex); } if(run.isItalic()) { string.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIndex, endIndex); } if(run.isUnderline()) { string.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIndex, endIndex); string.addAttribute(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_TWO_PIXEL, startIndex, endIndex); } if(run.isStrikethrough()) { string.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, startIndex, endIndex); } if(run.isSubscript()) { string.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB, startIndex, endIndex); } if(run.isSuperscript()) { string.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, startIndex, endIndex); } startIndex = endIndex; } return string; } /** * ensure that the paragraph contains at least one character. * We need this trick to correctly measure text */ private void ensureNotEmpty(){ XSLFTextRun r = addNewTextRun(); r.setText(" "); CTTextCharacterProperties endPr = _p.getEndParaRPr(); if(endPr != null) { if(endPr.isSetSz()) r.setFontSize(endPr.getSz() / 100); } } /** * break text into lines * * @param graphics * @return array of text fragments, * each representing a line of text that fits in the wrapping width */ List<TextFragment> breakText(Graphics2D graphics){ _lines = new ArrayList<TextFragment>(); // does this paragraph contain text? boolean emptyParagraph = _runs.size() == 0; // ensure that the paragraph contains at least one character if(_runs.size() == 0) ensureNotEmpty(); String text = getRenderableText(); if(text.length() == 0) return _lines; AttributedString at = getAttributedString(graphics); AttributedCharacterIterator it = at.getIterator(); LineBreakMeasurer measurer = new LineBreakMeasurer(it, graphics.getFontRenderContext()) ; for (;;) { int startIndex = measurer.getPosition(); double wrappingWidth = getWrappingWidth(_lines.size() == 0, graphics) + 1; // add a pixel to compensate rounding errors // shape width can be smaller that the sum of insets (this was proved by a test file) if(wrappingWidth < 0) wrappingWidth = 1; int nextBreak = text.indexOf('\n', startIndex + 1); if(nextBreak == -1) nextBreak = it.getEndIndex(); TextLayout layout = measurer.nextLayout((float)wrappingWidth, nextBreak, true); if (layout == null) { // layout can be null if the entire word at the current position // does not fit within the wrapping width. Try with requireNextWord=false. layout = measurer.nextLayout((float)wrappingWidth, nextBreak, false); } if(layout == null) { // exit if can't break any more break; } int endIndex = measurer.getPosition(); // skip over new line breaks (we paint 'clear' text runs not starting or ending with \n) if(endIndex < it.getEndIndex() && text.charAt(endIndex) == '\n'){ measurer.setPosition(endIndex + 1); } TextAlign hAlign = getTextAlign(); if(hAlign == TextAlign.JUSTIFY || hAlign == TextAlign.JUSTIFY_LOW) { layout = layout.getJustifiedLayout((float)wrappingWidth); } AttributedString str = new AttributedString(it, startIndex, endIndex); TextFragment line = new TextFragment( layout, // we will not paint empty paragraphs emptyParagraph ? null : str); _lines.add(line); _maxLineHeight = Math.max(_maxLineHeight, line.getHeight()); if(endIndex == it.getEndIndex()) break; } if(isBullet() && !emptyParagraph) { String buCharacter = getBulletCharacter(); String buFont = getBulletFont(); if(buFont == null) buFont = getTextRuns().get(0).getFontFamily(); if(buCharacter != null && buFont != null && _lines.size() > 0) { AttributedString str = new AttributedString(buCharacter); TextFragment firstLine = _lines.get(0); AttributedCharacterIterator bit = firstLine._str.getIterator(); Color buColor = getBulletFontColor(); str.addAttribute(TextAttribute.FOREGROUND, buColor == null ? bit.getAttribute(TextAttribute.FOREGROUND) : buColor); str.addAttribute(TextAttribute.FAMILY, buFont); float fontSize = (Float)bit.getAttribute(TextAttribute.SIZE); float buSz = (float)getBulletFontSize(); if(buSz > 0) fontSize *= buSz* 0.01; else fontSize = -buSz; str.addAttribute(TextAttribute.SIZE, fontSize); TextLayout layout = new TextLayout(str.getIterator(), graphics.getFontRenderContext()); _bullet = new TextFragment(layout, str); } } return _lines; } CTTextParagraphProperties getDefaultMasterStyle(){ CTPlaceholder ph = _shape.getCTPlaceholder(); String defaultStyleSelector; if(ph == null) defaultStyleSelector = "otherStyle"; // no placeholder means plain text box else { switch(ph.getType().intValue()){ case STPlaceholderType.INT_TITLE: case STPlaceholderType.INT_CTR_TITLE: defaultStyleSelector = "titleStyle"; break; case STPlaceholderType.INT_FTR: case STPlaceholderType.INT_SLD_NUM: case STPlaceholderType.INT_DT: defaultStyleSelector = "otherStyle"; break; default: defaultStyleSelector = "bodyStyle"; break; } } int level = getLevel(); // wind up and find the root master sheet which must be slide master XSLFSheet masterSheet = _shape.getSheet(); while (masterSheet.getMasterSheet() != null){ masterSheet = masterSheet.getMasterSheet(); } XmlObject[] o = masterSheet.getXmlObject().selectPath( "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " + "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " + ".//p:txStyles/p:" + defaultStyleSelector +"/a:lvl" +(level+1)+ "pPr"); if(o.length == 1){ return (CTTextParagraphProperties)o[0]; } throw new IllegalArgumentException("Failed to fetch default style for " + defaultStyleSelector + " and level=" + level); } private boolean fetchParagraphProperty(ParagraphPropertyFetcher visitor){ boolean ok = false; if(_p.isSetPPr()) ok = visitor.fetch(_p.getPPr()); if(!ok) { XSLFTextShape shape = getParentShape(); ok = shape.fetchShapeProperty(visitor); if(!ok){ CTPlaceholder ph = shape.getCTPlaceholder(); if(ph == null){ // if it is a plain text box then take defaults from presentation.xml XMLSlideShow ppt = getParentShape().getSheet().getSlideShow(); CTTextParagraphProperties themeProps = ppt.getDefaultParagraphStyle(getLevel()); if(themeProps != null) ok = visitor.fetch(themeProps); } if(!ok){ // defaults for placeholders are defined in the slide master CTTextParagraphProperties defaultProps = getDefaultMasterStyle(); if(defaultProps != null) ok = visitor.fetch(defaultProps); } } } return ok; } void copy(XSLFTextParagraph p){ TextAlign srcAlign = p.getTextAlign(); if(srcAlign != getTextAlign()){ setTextAlign(srcAlign); } boolean isBullet = p.isBullet(); if(isBullet != isBullet()){ setBullet(isBullet); if(isBullet) { String buFont = p.getBulletFont(); if(buFont != null && !buFont.equals(getBulletFont())){ setBulletFont(buFont); } String buChar = p.getBulletCharacter(); if(buChar != null && !buChar.equals(getBulletCharacter())){ setBulletCharacter(buChar); } Color buColor = p.getBulletFontColor(); if(buColor != null && !buColor.equals(getBulletFontColor())){ setBulletFontColor(buColor); } double buSize = p.getBulletFontSize(); if(buSize != getBulletFontSize()){ setBulletFontSize(buSize); } } } double leftMargin = p.getLeftMargin(); if(leftMargin != getLeftMargin()){ setLeftMargin(leftMargin); } double indent = p.getIndent(); if(indent != getIndent()){ setIndent(indent); } double spaceAfter = p.getSpaceAfter(); if(spaceAfter != getSpaceAfter()){ setSpaceAfter(spaceAfter); } double spaceBefore = p.getSpaceBefore(); if(spaceBefore != getSpaceBefore()){ setSpaceBefore(spaceBefore); } double lineSpacing = p.getLineSpacing(); if(lineSpacing != getLineSpacing()){ setLineSpacing(lineSpacing); } List<XSLFTextRun> srcR = p.getTextRuns(); List<XSLFTextRun> tgtR = getTextRuns(); for(int i = 0; i < srcR.size(); i++){ XSLFTextRun r1 = srcR.get(i); XSLFTextRun r2 = tgtR.get(i); r2.copy(r1); } } }
39
136
0.56683
ca9df042043305165426fe511735d9347321f66d
2,379
package ResourceIO; import TextIO.ConfigEditor; import TextIO.TextParser; import Util.ColorIO; import Util.Tuple; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * The ImageLoader class loads and saves images as well as other utility methods */ public class ImageLoader { private final Map<String, BufferedImage> cachedImages = new HashMap<>(); /** * Takes in a filename and loads that file through Cache or the Resources Path * * @param name The name of the file * @return Returns a BufferedImage */ public BufferedImage LoadImage(String name) { try { if(cachedImages.get(name) == null) { // Load image from /Resources/Images/ BufferedImage loadedImage = ImageIO.read(new File("Resources/Images/" + name)); cachedImages.put(name, loadedImage); return loadedImage; } // Return the cached image return cachedImages.get(name); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Takes in String and writes the edited image to the desired location * * @param name The name of the file * @param image The final image */ public void SaveImage(String name, BufferedImage image) { try { ImageIO.write(image, "PNG", new File("Output/" + name)); } catch (IOException e) { e.printStackTrace(); } } /** * Generates Random Image based on the current Subject * * @return Return a randomly generated BufferedImage */ public BufferedImage RandomImage() { // THIS METHOD DOES NOT WORK YET AS THE IMAGES HAVE NOT BEEN IMPLEMENTED // Initialize variables ConfigEditor cfgEditor = new ConfigEditor(); TextParser txtParser = new TextParser(); ImageLoader imgLoader = this; String subject = cfgEditor.GetConfig("Subject"); try { return imgLoader.LoadImage(txtParser.GetTextClass(subject, "Nouns") + "/" + subject); } catch (Exception e) { e.printStackTrace(); } return null; } }
27.988235
97
0.617486
c795071c11e82da72ddedce2097ca967bfdd5323
1,898
/* * This file is part of the TinsPHP project published under the Apache License 2.0 * For the full copyright and license information, please have a look at LICENSE in the * root folder or visit the project's website http://tsphp.ch/wiki/display/TINS/License */ package ch.tsphp.tinsphp.inference_engine.test.integration.reference; import ch.tsphp.tinsphp.inference_engine.test.integration.testutils.reference.AReferenceEvalTypeScopeTest; import ch.tsphp.tinsphp.inference_engine.test.integration.testutils.reference.TypeScopeTestStruct; import org.antlr.runtime.RecognitionException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class ResolvePrimitiveLiteralTest extends AReferenceEvalTypeScopeTest { public ResolvePrimitiveLiteralTest(String testString, TypeScopeTestStruct[] theTestStructs) { super(testString, theTestStructs); } @Test public void test() throws RecognitionException { runTest(); } @Parameterized.Parameters public static Collection<Object[]> testStrings() { return Arrays.asList(new Object[][]{ {"null;", typeStruct("null", "nullType", "", 1, 0, 0)}, {"true;", typeStruct("true", "trueType", "", 1, 0, 0)}, {"false;", typeStruct("false", "falseType", "", 1, 0, 0)}, {"1;", typeStruct("1", "int", "", 1, 0, 0)}, {"1.2;", typeStruct("1.2", "float", "", 1, 0, 0)}, {"\"hello\";", typeStruct("\"hello\"", "string", "", 1, 0, 0)}, {"'hi';", typeStruct("'hi'", "string", "", 1, 0, 0)}, {"array(1,2);", typeStruct("(array 1 2)", "array", "", 1, 0, 0)}, {"[1,2];", typeStruct("(array 1 2)", "array", "", 1, 0, 0)}, }); } }
38.734694
106
0.632244
c93901610d4e21bab1c3042d2508794eb4a42dc8
2,017
/* * Copyright 2013 JBoss, by Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.websockets.impl; import io.undertow.websockets.core.WebSocketLogger; import io.undertow.websockets.core.WebSocketMessages; import io.undertow.websockets.api.SendCallback; /** * Wraps a array of {@link SendCallback}s to execute on {@link #onCompletion()} or {@link #onError(Throwable)} * * @author <a href="mailto:[email protected]">Norman Maurer</a> */ final class DelegatingSendCallback implements SendCallback { private final SendCallback[] callbacks; public DelegatingSendCallback(SendCallback... callbacks) { if (callbacks == null || callbacks.length == 0) { throw WebSocketMessages.MESSAGES.senderCallbacksEmpty(); } this.callbacks = callbacks; } @Override public void onCompletion() { for (SendCallback callback : callbacks) { try { StreamSinkChannelUtils.safeNotify(callback, null); } catch (Throwable cause) { WebSocketLogger.REQUEST_LOGGER.sendCallbackExecutionError(cause); } } } @Override public void onError(Throwable error) { for (SendCallback callback : callbacks) { try { StreamSinkChannelUtils.safeNotify(callback, error); } catch (Throwable cause) { WebSocketLogger.REQUEST_LOGGER.sendCallbackExecutionError(cause); } } } }
34.186441
110
0.673773
4165648747f1f8ef2ea004cc6d569ef7e0e51cfe
4,541
package io.oilfox.backend.api.shared.repositories; import io.oilfox.backend.db.db.UnitOfWork; import io.oilfox.backend.api.shared.builders.ReportBuilder; import org.hibernate.Criteria; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.util.HashMap; import java.util.List; /** * Created by ipusic on 2/9/16. */ public class ReportRepository { private static Logger logger = LoggerFactory.getLogger(ReportRepository.class); @Inject UnitOfWork unitOfWork; @SuppressWarnings("unchecked") public ReportBuilder.ReportResult getMeteringReport() { ReportBuilder reportBuilder = new ReportBuilder(); reportBuilder.addSelect("metering_raw.value", "meteringvalue"); reportBuilder.addSelect("cast(\"user\".id as varchar)", "userid"); reportBuilder.addSelect("\"user\".email", "email"); reportBuilder.addSelect("\"user\".firstname", "firstname"); reportBuilder.addSelect("\"user\".lastname", "lastname"); reportBuilder.addSelect("\"user\".zipcode", "userzipcode"); reportBuilder.addSelect("cast(tank.id as varchar)", "tankid"); reportBuilder.addSelect("tank.shape", "shape"); reportBuilder.addSelect("tank.volume", "volume"); reportBuilder.addSelect("tank.length", "length"); reportBuilder.addSelect("tank.street", "street"); reportBuilder.addSelect("tank.city", "city"); reportBuilder.addSelect("tank.country", "country"); reportBuilder.addSelect("tank.zipcode", "tankzipcode"); reportBuilder.addSelect("cast(oilfox.id as varchar)", "oilfoxid"); reportBuilder.addSelect("oilfox.name", "oilfoxname"); reportBuilder.addSelect("cast(oilfox.hwid as varchar)", "oilfoxhwid"); reportBuilder.addSelect("cast(oilfox.token as varchar)", "oilfoxtoken"); reportBuilder.setFrom("FROM metering_raw"); reportBuilder.addJoin("LEFT JOIN oilfox ON metering_raw.token = oilfox.token"); reportBuilder.addJoin("LEFT JOIN tank ON oilfox.tankid = tank.id"); reportBuilder.addJoin("LEFT JOIN \"user\" ON oilfox.userid = \"user\".id"); reportBuilder.setOrder("ORDER BY metering_raw.created_at DESC"); reportBuilder.setLimit("LIMIT 100"); List<HashMap<String, Object>> results = unitOfWork.db().createSQLQuery(reportBuilder.buildSql()) .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) .list(); return reportBuilder.buildResult(results); } @SuppressWarnings("unchecked") public ReportBuilder.ReportResult getOverviewReport() { ReportBuilder reportBuilder = new ReportBuilder(); reportBuilder.addSelect("oilfox.name", "oilfoxname"); reportBuilder.addSelect("cast(\"user\".id as varchar)", "userid"); reportBuilder.addSelect("\"user\".email", "email"); reportBuilder.addSelect("\"user\".firstname", "firstname"); reportBuilder.addSelect("\"user\".lastname", "lastname"); reportBuilder.addSelect("\"user\".zipcode", "userzipcode"); reportBuilder.addSelect("cast(tank.id as varchar)", "tankid"); reportBuilder.addSelect("tank.height", "height"); reportBuilder.addSelect("tank.shape", "shape"); reportBuilder.addSelect("tank.volume", "volume"); reportBuilder.addSelect("tank.length", "length"); reportBuilder.addSelect("tank.street", "street"); reportBuilder.addSelect("tank.city", "city"); reportBuilder.addSelect("tank.country", "country"); reportBuilder.addSelect("tank.zipcode", "tankzipcode"); reportBuilder.addSelect("cast(oilfox.id as varchar)", "oilfoxid"); reportBuilder.addSelect("cast(oilfox.token as varchar)", "oilfoxtoken"); reportBuilder.addSelect("oilfox.hwid", "oilfoxhwid"); reportBuilder.setFrom("FROM oilfox"); reportBuilder.addJoin("LEFT JOIN metering_raw ON oilfox.token = metering_raw.token"); reportBuilder.addJoin("FULL JOIN tank ON oilfox.tankid = tank.id"); reportBuilder.addJoin("LEFT JOIN \"user\" ON oilfox.userid = \"user\".id"); reportBuilder.setOrder("ORDER BY oilfox.created_at DESC, tank.created_at DESC"); reportBuilder.setLimit("LIMIT 100"); List<HashMap<String, Object>> results = unitOfWork.db().createSQLQuery(reportBuilder.buildSql()) .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) .list(); return reportBuilder.buildResult(results); } }
46.336735
104
0.681568
d73b11c59e14aec253a69344fd498c80b718cd3f
1,344
package com.server.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dao.AllusersMapper; import com.entity.Allusers; import com.server.AllusersServer; @Service public class AllusersServerImpi implements AllusersServer { @Resource private AllusersMapper gdao; @Override public Allusers allusersLogin(Map<String, Object> po) { System.out.println("userdao---"); return gdao.allusersLogin(po); } @Override public int add(Allusers po) { return gdao.insert(po); } @Override public int update(Allusers po) { return gdao.updateByPrimaryKeySelective(po); } @Override public int delete(int id) { return gdao.deleteByPrimaryKey(id); } @Override public List<Allusers> getAll(Map<String, Object> map) { return gdao.getAll(map); } @Override public Allusers quchongAllusers(Map<String, Object> account) { return null; } @Override public List<Allusers> getByPage(Map<String, Object> map) { return gdao.getByPage(map); } @Override public int getCount(Map<String, Object> map) { return gdao.getCount(map); } @Override public List<Allusers> select(Map<String, Object> map) { return gdao.select(map); } @Override public Allusers getById(int id) { return gdao.selectByPrimaryKey(id); } }
18.410959
63
0.732143
fb30a12db34220b5c38c72eeaa2589a91e69945d
4,325
package org.ninestar.crawling.pageanalyzer; import com.google.common.base.Joiner; import com.google.common.collect.Maps; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import crawlercommons.robots.BaseRobotRules; import crawlercommons.robots.SimpleRobotRulesParser; import org.ninestar.crawling.data.HtmlAnalysisResult; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.net.URL; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class PageAnalyzer { private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"; public static final String CONFIG_USER_AGENT = "UserAgent"; public static final String CONFIG_ANALYZE_ROBOTS_TXT = "RobotsTxt"; public static HtmlAnalysisResult analyze(Map<String, String> config, String url) { try { String userAgent = config.getOrDefault(CONFIG_USER_AGENT, DEFAULT_USER_AGENT); HttpResponse<String> response = Unirest.get(url) .header("User-Agent", userAgent) .asString(); return analyze(config, url, response.getBody(), response.getStatus(), response.getHeaders()); } catch (UnirestException e) { throw new RuntimeException(e); } } public static HtmlAnalysisResult analyze(Map<String, String> config, String url, String html) { return analyze(config, url, html, null, Maps.newHashMap()); } public static HtmlAnalysisResult analyze(Map<String, String> config, String url, String html, Integer status, Map<String, List<String>> headers) { try { HtmlAnalysisResult result = new HtmlAnalysisResult(); result.setUrl(url); result.setHttpStatus(status); result.setHeaders(headers.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> Joiner.on("\n").join(e.getValue())))); Document document = Jsoup.parse(html, url); result.setTitle(document.title()); List<String> meta = document.select("meta").stream().map(Element::toString).collect(Collectors.toList()); result.setMetaValues(meta); List<String> links = document.select("a").stream().map(e -> e.attr("abs:href")).collect(Collectors.toList()); result.setLinks(links); if (Boolean.parseBoolean(config.get(CONFIG_ANALYZE_ROBOTS_TXT))) { String robotsUrl = robotsTxtUrl(url); String userAgent = config.getOrDefault(CONFIG_USER_AGENT, DEFAULT_USER_AGENT); HttpResponse<String> response = Unirest.get(robotsUrl) .header("User-Agent", userAgent) .asString(); String robotsTxt = response.getBody(); parseRobotsTxt(userAgent, robotsUrl, robotsTxt, result); } return result; } catch (Exception e) { throw new RuntimeException(e); } } public static void parseRobotsTxt(String userAgent, String robotsUrl, String robotsTxt, HtmlAnalysisResult result) { result.setRobotsTxt(robotsTxt); SimpleRobotRulesParser robotsParser = new SimpleRobotRulesParser(); BaseRobotRules robotRules = robotsParser.parseContent(robotsUrl, robotsTxt.getBytes(), null, userAgent); result.setRobotsAllowedAll(robotRules.isAllowAll()); result.setRobotsAllowedNone(robotRules.isAllowNone()); result.setRobotsAllowedHome(robotRules.isAllowed("/")); result.setRobotsSitemaps(robotRules.getSitemaps()); result.setRobotsCrawlDelay(robotRules.getCrawlDelay()); } private static String robotsTxtUrl(String url) { try { URL urlObject = new URL(url); String portPart = urlObject.getPort() > 0 ? ":" + urlObject.getPort() : ""; return String.format("%s://%s%s/robots.txt", urlObject.getProtocol(), urlObject.getHost(), portPart); } catch (Exception e) { throw new RuntimeException(e); } } }
44.132653
160
0.660116
83ab77cf3a5948780e4222b7f0b5f9f0697fb0f7
4,396
/* * Orika - simpler, better and faster Java bean mapping * * Copyright (C) 2011-2013 Orika authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ma.glasnost.orika.test.inheritance; import org.junit.Assert; import org.junit.Test; import ma.glasnost.orika.CustomMapper; import ma.glasnost.orika.MapperFacade; import ma.glasnost.orika.MapperFactory; import ma.glasnost.orika.MappingContext; import ma.glasnost.orika.test.MappingUtil; public class InheritanceTestCase { private final MapperFactory factory = MappingUtil.getMapperFactory(); public void setUp() { } @Test public void testSimpleInheritance() { MapperFacade mapper = factory.getMapperFacade(); ChildEntity entity = new ChildEntity(); entity.setId(1L); entity.setName("Khettabi"); ChildDTO dto = mapper.map(entity, ChildDTO.class); Assert.assertEquals(entity.getId(), dto.getId()); Assert.assertEquals(entity.getName(), dto.getName()); } @Test public void resolveConcreteClass() { MapperFacade mapper = factory.getMapperFacade(); factory.registerClassMap(factory.classMap(ChildEntity.class, ChildDTO.class).byDefault().toClassMap()); ChildEntity entity = new ChildEntity(); entity.setId(1L); entity.setName("Khettabi"); BaseDTO dto = mapper.map(entity, BaseDTO.class); Assert.assertTrue(dto instanceof ChildDTO); Assert.assertEquals(entity.getName(), ((ChildDTO) dto).getName()); } @Test public void testDifferentLevelOfInheritance() { factory.registerClassMap(factory.classMap(ChildEntity.class, Child2DTO.class) .customize(new CustomMapper<ChildEntity, Child2DTO>() { @Override public void mapAtoB(ChildEntity a, Child2DTO b, MappingContext context) { b.setMessage("Hello " + a.getName()); } }).byDefault().toClassMap()); MapperFacade mapper = factory.getMapperFacade(); ChildEntity entity = new ChildEntity(); entity.setId(1L); entity.setName("Khettabi"); Child2DTO dto = mapper.map(entity, Child2DTO.class); Assert.assertEquals(entity.getId(), dto.getId()); Assert.assertEquals(entity.getName(), dto.getName()); Assert.assertEquals("Hello Khettabi", dto.getMessage()); } public static abstract class BaseEntity { private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } } public static abstract class BaseDTO { private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } } public static class ChildEntity extends BaseEntity { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class ChildDTO extends BaseDTO { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class Child2DTO extends ChildDTO { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } }
28.732026
111
0.586215
9cb65bf0b60ea8d3d44a7c813b5f3a73815e6e3f
892
package pom.equipo6.test; import org.junit.Test; import pom.equipo6.base.TestBase; import pom.equipo6.pages.VFAlojamientoPage; import pom.equipo6.pages.VFHomePage; public class alojamiento_falabella002 extends TestBase { protected VFHomePage pageHome = null; protected VFAlojamientoPage pageAlojamiento = null; @Test public void alojamientoSegundoFechaNoDefinida(){ pageHome = new VFHomePage(driver); pageHome.goHomePage(); pageAlojamiento = new VFAlojamientoPage(driver); pageAlojamiento.goAlojamientoToHome(); pageAlojamiento.selectDestino(); pageAlojamiento.confirmFechaAlojamiento(); pageAlojamiento.confirmAlojamiento(); pageAlojamiento.otherAlojamiento(); pageAlojamiento.selectSecondNoFecha(); pageAlojamiento.confirmSecondAlojamiento(); pageAlojamiento.checkText002(); } }
33.037037
56
0.738789
bb97675417211526de3c3ff35c858961d0559bae
1,661
/** * Copyright 2020 Association for the promotion of open-source insurance software and for the establishment of open interface standards in the insurance industry (Verein zur Foerderung quelloffener Versicherungssoftware und Etablierung offener Schnittstellenstandards in der Versicherungsbranche) * * 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.aposin.gem.ui.view.filter; import org.aposin.gem.core.api.model.IEnvironment; import org.aposin.gem.ui.lifecycle.Session; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; public class EnvironmentBySessionProjectFilter extends ViewerFilter { private final Session session; public EnvironmentBySessionProjectFilter(final Session session) { this.session = session; } @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof IEnvironment) { if (session.getSessionProject().equals(((IEnvironment) element).getProject())) { return true; } } return false; } }
40.512195
297
0.725467
b7ae3777a970306c5c9fb5b4c0e075181877e7a2
312
package com.yuyh.library.support; import android.support.annotation.IntDef; /** * 高亮区域形状 * * @author yuyh. * @date 2016/12/24. */ @IntDef({ HShape.CIRCLE, HShape.RECTANGLE, HShape.OVAL }) public @interface HShape { int CIRCLE = 0; int RECTANGLE = 1; int OVAL = 2; }
13
41
0.599359
1b97bc80e0fb97092c8cc6c23971218491cd2c2e
413
package cn.com.mfish.observer.fans; import cn.com.mfish.observer.blog.Blogger; /** * @author :qiufeng * @description:观察者抽象类 * @date :2022/4/4 19:40 */ public abstract class AbObserver implements Observer { public abstract void receiveNotify(String name); /** * 订阅某个博主 * * @param blogger */ public void subscribe(Blogger blogger) { blogger.subscribe(this); } }
17.208333
54
0.646489
8ed9fb94ea4f08fe855ebdf1a7933623fdced55b
7,190
package tk.traiders.ui; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.List; import java.util.Map; import tk.traiders.MainActivity; import tk.traiders.R; import tk.traiders.utils.MarshallerUtils; public abstract class ListFragment extends Fragment { protected abstract String getURL(); protected abstract RecyclerView.Adapter getAdapter(String response); private RequestQueue requestQueue; private RecyclerView recyclerView; private SwipeRefreshLayout swipeRefreshLayout; private ProgressBar progressBar_loading; private ImageView imageView_error; private TextView textView_error; private ImageView imageView_noData; private TextView textView_noData; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.list_common, container, false); progressBar_loading = rootView.findViewById(R.id.progressBar_loading); imageView_error = rootView.findViewById(R.id.imageView_error); textView_error = rootView.findViewById(R.id.textView_error); imageView_noData = rootView.findViewById(R.id.imageView_noData); textView_noData = rootView.findViewById(R.id.textView_noData); progressBar_loading.setVisibility(View.VISIBLE); imageView_error.setVisibility(View.GONE); textView_error.setVisibility(View.GONE); imageView_noData.setVisibility(View.GONE); textView_noData.setVisibility(View.GONE); recyclerView = rootView.findViewById(R.id.recylerView); recyclerView.setVisibility(View.VISIBLE); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(getParentFragment().getActivity())); swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { fetchData(); } }); requestQueue = Volley.newRequestQueue(getParentFragment().getActivity()); fetchData(); return rootView; } protected void fetchData() { StringRequest request = new StringRequest(Request.Method.GET, getURL(), new Response.Listener<String>() { @Override public void onResponse(String response) { String UTF8_response = MarshallerUtils.convertToUTF8(response); textView_error.setVisibility(View.GONE); imageView_error.setVisibility(View.GONE); progressBar_loading.setVisibility(View.GONE); swipeRefreshLayout.setRefreshing(false); recyclerView.setAdapter(getAdapter(UTF8_response)); if(recyclerView.getAdapter().getItemCount() == 0) { recyclerView.setVisibility(View.INVISIBLE); imageView_noData.setVisibility(View.VISIBLE); textView_noData.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); imageView_noData.setVisibility(View.GONE); textView_noData.setVisibility(View.GONE); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressBar_loading.setVisibility(View.GONE); imageView_error.setVisibility(View.VISIBLE); textView_error.setVisibility(View.VISIBLE); imageView_noData.setVisibility(View.GONE); textView_noData.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); swipeRefreshLayout.setRefreshing(false); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = MainActivity.getAuthorizationHeader(getActivity()); return headers != null ? headers : super.getHeaders(); } }; requestQueue.add(request); } protected void fetchDataWithFilters(String filterURL) { StringRequest request = new StringRequest(Request.Method.GET, filterURL, new Response.Listener<String>() { @Override public void onResponse(String response) { String UTF8_response = MarshallerUtils.convertToUTF8(response); textView_error.setVisibility(View.GONE); imageView_error.setVisibility(View.GONE); progressBar_loading.setVisibility(View.GONE); swipeRefreshLayout.setRefreshing(false); recyclerView.setAdapter(getAdapter(UTF8_response)); if(recyclerView.getAdapter().getItemCount() == 0) { recyclerView.setVisibility(View.INVISIBLE); imageView_noData.setVisibility(View.VISIBLE); textView_noData.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); imageView_noData.setVisibility(View.GONE); textView_noData.setVisibility(View.GONE); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressBar_loading.setVisibility(View.GONE); imageView_error.setVisibility(View.VISIBLE); textView_error.setVisibility(View.VISIBLE); imageView_noData.setVisibility(View.GONE); textView_noData.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); swipeRefreshLayout.setRefreshing(false); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = MainActivity.getAuthorizationHeader(getActivity()); return headers != null ? headers : super.getHeaders(); } }; requestQueue.add(request); } }
38.449198
132
0.66509
8f2bad262af923f5119456eafceefb3f9b2559ee
1,174
package me.i509.junkkyard.screen.api; import java.util.List; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.AbstractButtonWidget; import net.minecraft.client.render.item.ItemRenderer; /** * Provides access to additional context a screen can hold. */ @Environment(EnvType.CLIENT) public interface ScreenContext { /** * Gets the screen's context. * * @param screen the screen * @return the screen's context */ static ScreenContext from(Screen screen) { return (ScreenContext) screen; } /** * Gets all button widgets the screen holds. * * @return a list of all buttons on this screen. */ List<AbstractButtonWidget> getButtons(); /** * Gets the item renderer the screen holds. * * @return the item renderer */ ItemRenderer getItemRenderer(); /** * Gets the text renderer the screen holds. * * @return the text renderer. */ TextRenderer getTextRenderer(); /** * Gets the screen which owns this context. * * @return the owning screen */ Screen getScreen(); }
20.964286
60
0.717206
dac154ec54bbb65839c1a727988e6c14f1c0ff52
321
package arrays; public class Solution_905 { public int[] sortArrayByParity(int[] A) { int j = A.length - 1; int i = 0; while (i <= j) { if (A[i] % 2 == 1) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; j--; } else { i++; } } return A; } }
13.956522
43
0.392523
a5460e67994c81484e013dea0874a034ad9aaac4
28,874
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import dao.AlimentoDAO; import dao.EscolaDAO; import dao.EstoqueDAO; import dao.GastoDAO; import dao.RemessaDAO; import dao.Remessa_has_AlimentoDAO; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; import model.Alimento; import model.Escola; import model.Estoque; import model.Remessa_has_Alimento; /** * * @author Hugo */ public class TelaPrincipal extends javax.swing.JFrame { private ArrayList<Escola> listaEscola; private ArrayList<Estoque> listaEstoque; private ArrayList<Alimento> listaAlimento; private Escola escola; private Estoque estoque; private Alimento alimento = new Alimento(); private void disableButton() { jButtonRemover.setEnabled(false); jButtonAdicionarRemessa.setEnabled(false); } public TelaPrincipal() { initComponents(); carregaEscolaDAO(); disableButton(); } public Escola getEscola() { escola = listaEscola.get(jComboBoxEscola.getSelectedIndex()); return this.escola; } public Alimento getAlimento() { return this.alimento; } public Estoque getEstoque() { estoque = listaEstoque.get(jComboBoxEstoque.getSelectedIndex()); return this.estoque; } public void carregaEscolaDAO() { EscolaDAO dao = new EscolaDAO(); listaEscola = dao.getAllEscola(); for(int i = 0; i < listaEscola.size(); i++) { jComboBoxEscola.addItem(listaEscola.get(i).getNome()); } } public void carregaEstoqueDAO(int idEscola) { EstoqueDAO dao = new EstoqueDAO(); listaEstoque = dao.getAllEstoque(idEscola); jComboBoxEstoque.removeAllItems(); if(jComboBoxEstoque.getSelectedIndex() != 1) for(int i = 0; i < listaEstoque.size(); i++) { jComboBoxEstoque.addItem(listaEstoque.get(i).getNome()); } } public void carregaAlimentoComboBox(int idEstoque) { AlimentoDAO dao = new AlimentoDAO(); listaAlimento = dao.getAllAlimentoEstoque(idEstoque); jComboBoxAlimentoRemessa.removeAllItems(); for(int i = 0; i < listaAlimento.size(); i++) { jComboBoxAlimentoRemessa.addItem(listaAlimento.get(i).getNome()); } } public void carregaAlimentoDAO(int idEstoque) { DefaultTableModel model = (DefaultTableModel) jTableListaAlimento.getModel(); AlimentoDAO dao = new AlimentoDAO(); Remessa_has_AlimentoDAO daoRemessaAlimento = new Remessa_has_AlimentoDAO(); listaAlimento = dao.getAllAlimentoEstoque(idEstoque); model.setRowCount(0); float recebido = 0,anterior = 0; for (int i = 0; i < listaAlimento.size(); i++) { ArrayList<Remessa_has_Alimento> lista = daoRemessaAlimento.getListaRemessaAlimento(listaAlimento.get(i).getNome()); /* for (int j = 0; j < lista.size(); j++) { System.out.println("Lista: " + lista.get(j).getIdAlimento()); } System.out.println(lista.size()); */ if(lista.size() > 0) { anterior = 0; for( int j = 0; j < lista.size() - 1; j++) { anterior = anterior + lista.get(j).getRecebido(); } recebido = lista.get(lista.size() - 1).getRecebido(); } else { System.err.println("RemessaALimento = 0"); recebido = 0; } model.addRow(new String[] { listaAlimento.get(i).getNome(), Float.toString(anterior), Float.toString(recebido), "0", Float.toString(listaAlimento.get(i).getTotal()) }); } } public void tableRemessa(DefaultTableModel model, ArrayList<Remessa_has_Alimento> lista) { model.setRowCount(0); for (int i = 0; i < lista.size(); i++) { model.addRow(new String[] { Integer.toString(i + 1), lista.get(i).getIdAlimento(), lista.get(i).getDateRemessa(), Float.toString(lista.get(i).getRecebido()) }); } } public void carregaRemessaTable(String idAlimento) { DefaultTableModel model = (DefaultTableModel) jTableRemessa.getModel(); Remessa_has_AlimentoDAO dao = new Remessa_has_AlimentoDAO(); ArrayList<Remessa_has_Alimento> lista = new ArrayList<Remessa_has_Alimento>(); lista = dao.getListaRemessaAlimento(idAlimento); tableRemessa(model, lista); } public void limpaTableAlimento() { DefaultTableModel model = (DefaultTableModel) jTableListaAlimento.getModel(); model.setRowCount(0); } public void limpaTableRemessa() { DefaultTableModel model = (DefaultTableModel) jTableRemessa.getModel(); model.setRowCount(0); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabelEscola = new javax.swing.JLabel(); jButtonBuscar = new javax.swing.JButton(); jTabbedPaneAlimento = new javax.swing.JTabbedPane(); jPanelEstoque = new javax.swing.JPanel(); jLabelEstoque = new javax.swing.JLabel(); jComboBoxEstoque = new javax.swing.JComboBox<>(); jScrollPaneListaAlimento = new javax.swing.JScrollPane(); jTableListaAlimento = new javax.swing.JTable(); jButtonAdicionarAlimento = new javax.swing.JButton(); jButtonRemover = new javax.swing.JButton(); jButtonAdicionarRemessa = new javax.swing.JButton(); jPanelRemessa = new javax.swing.JPanel(); jComboBoxAlimentoRemessa = new javax.swing.JComboBox<>(); jLabelAlimento = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTableRemessa = new javax.swing.JTable(); jPanelMapaMerenda = new javax.swing.JPanel(); jButtonAdicionar = new javax.swing.JButton(); jComboBoxEscola = new javax.swing.JComboBox<>(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabelEscola.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabelEscola.setText("Escola:"); jButtonBuscar.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jButtonBuscar.setText("Buscar"); jButtonBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonBuscarActionPerformed(evt); } }); jLabelEstoque.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabelEstoque.setText("Estoque:"); jComboBoxEstoque.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBoxEstoqueItemStateChanged(evt); } }); jComboBoxEstoque.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxEstoqueActionPerformed(evt); } }); jTableListaAlimento.setModel(new javax.swing.table.DefaultTableModel ( null, new String [] { "Alimento", "Anterior", "Entrada", "Saida", "Saldo" } ) { @Override public boolean isCellEditable(int rowIndex, int mColIndex) { return false; } }); jTableListaAlimento.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTableListaAlimentoMouseClicked(evt); } }); jScrollPaneListaAlimento.setViewportView(jTableListaAlimento); jButtonAdicionarAlimento.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jButtonAdicionarAlimento.setText("Adicionar Alimento"); jButtonAdicionarAlimento.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAdicionarAlimentoActionPerformed(evt); } }); jButtonRemover.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jButtonRemover.setText("Remover Alimento"); jButtonRemover.setMaximumSize(new java.awt.Dimension(141, 25)); jButtonRemover.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonRemoverActionPerformed(evt); } }); jButtonAdicionarRemessa.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jButtonAdicionarRemessa.setText("Adicionar Remessa"); jButtonAdicionarRemessa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAdicionarRemessaActionPerformed(evt); } }); javax.swing.GroupLayout jPanelEstoqueLayout = new javax.swing.GroupLayout(jPanelEstoque); jPanelEstoque.setLayout(jPanelEstoqueLayout); jPanelEstoqueLayout.setHorizontalGroup( jPanelEstoqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelEstoqueLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelEstoqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelEstoqueLayout.createSequentialGroup() .addComponent(jLabelEstoque) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxEstoque, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelEstoqueLayout.createSequentialGroup() .addComponent(jButtonAdicionarAlimento) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE) .addComponent(jButtonAdicionarRemessa) .addGap(33, 33, 33) .addComponent(jButtonRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPaneListaAlimento)) .addContainerGap()) ); jPanelEstoqueLayout.setVerticalGroup( jPanelEstoqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelEstoqueLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelEstoqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelEstoque) .addComponent(jComboBoxEstoque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPaneListaAlimento, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanelEstoqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonAdicionarAlimento) .addComponent(jButtonRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonAdicionarRemessa)) .addContainerGap()) ); jTabbedPaneAlimento.addTab("Estoque", jPanelEstoque); jComboBoxAlimentoRemessa.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBoxAlimentoRemessaItemStateChanged(evt); } }); jComboBoxAlimentoRemessa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxAlimentoRemessaActionPerformed(evt); } }); jLabelAlimento.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabelAlimento.setText("Alimento:"); jTableRemessa.setModel(new javax.swing.table.DefaultTableModel ( null, new String [] { "", "Alimento", "Data", "Valor" } ) { @Override public boolean isCellEditable(int rowIndex, int mColIndex) { return false; } }); jScrollPane1.setViewportView(jTableRemessa); javax.swing.GroupLayout jPanelRemessaLayout = new javax.swing.GroupLayout(jPanelRemessa); jPanelRemessa.setLayout(jPanelRemessaLayout); jPanelRemessaLayout.setHorizontalGroup( jPanelRemessaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelRemessaLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelRemessaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(jPanelRemessaLayout.createSequentialGroup() .addComponent(jLabelAlimento) .addGap(18, 18, 18) .addComponent(jComboBoxAlimentoRemessa, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanelRemessaLayout.setVerticalGroup( jPanelRemessaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelRemessaLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelRemessaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBoxAlimentoRemessa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelAlimento)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPaneAlimento.addTab("Remessa", jPanelRemessa); jButtonAdicionar.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jButtonAdicionar.setText("Adicionar"); jButtonAdicionar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAdicionarActionPerformed(evt); } }); javax.swing.GroupLayout jPanelMapaMerendaLayout = new javax.swing.GroupLayout(jPanelMapaMerenda); jPanelMapaMerenda.setLayout(jPanelMapaMerendaLayout); jPanelMapaMerendaLayout.setHorizontalGroup( jPanelMapaMerendaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelMapaMerendaLayout.createSequentialGroup() .addContainerGap() .addComponent(jButtonAdicionar) .addContainerGap(411, Short.MAX_VALUE)) ); jPanelMapaMerendaLayout.setVerticalGroup( jPanelMapaMerendaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelMapaMerendaLayout.createSequentialGroup() .addContainerGap(236, Short.MAX_VALUE) .addComponent(jButtonAdicionar) .addContainerGap()) ); jTabbedPaneAlimento.addTab("Mapa da Merenda", jPanelMapaMerenda); jComboBoxEscola.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jComboBoxEscola.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBoxEscolaItemStateChanged(evt); } }); jComboBoxEscola.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxEscolaActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPaneAlimento) .addGroup(layout.createSequentialGroup() .addComponent(jButtonBuscar) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabelEscola, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxEscola, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelEscola, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBoxEscola, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addComponent(jButtonBuscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTabbedPaneAlimento) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonBuscarActionPerformed private void jComboBoxEscolaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxEscolaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBoxEscolaActionPerformed private void jComboBoxEscolaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxEscolaItemStateChanged // TODO add your handling code here: if(listaEscola.get(jComboBoxEscola.getSelectedIndex()) != null) carregaEstoqueDAO(listaEscola.get(jComboBoxEscola.getSelectedIndex()).getIdEscola()); }//GEN-LAST:event_jComboBoxEscolaItemStateChanged private void jButtonAdicionarRemessaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAdicionarRemessaActionPerformed TelaNovoAlimento novoAlimento = new TelaNovoAlimento(this,true); novoAlimento.setVisible(true); }//GEN-LAST:event_jButtonAdicionarRemessaActionPerformed private void jButtonRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoverActionPerformed AlimentoDAO daoAlimento = new AlimentoDAO(); RemessaDAO daoRemessa = new RemessaDAO(); int linhaSelecionada = jTableListaAlimento.getSelectedRow(); String nomeAlimento = listaAlimento.get(linhaSelecionada).getNome(); alimento = null; daoAlimento.removeAlimento(nomeAlimento); carregaAlimentoDAO(listaEstoque.get(jComboBoxEstoque.getSelectedIndex()).getIdEstoque()); if(jTableListaAlimento.getRowCount() == 0) { disableButton(); } else { System.out.println(linhaSelecionada); if(linhaSelecionada > 0) { jTableListaAlimento.setRowSelectionInterval(linhaSelecionada - 1, linhaSelecionada - 1); alimento = listaAlimento.get(linhaSelecionada - 1); } else { jTableListaAlimento.setRowSelectionInterval(linhaSelecionada, linhaSelecionada); alimento = listaAlimento.get(linhaSelecionada); } } }//GEN-LAST:event_jButtonRemoverActionPerformed private void jButtonAdicionarAlimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAdicionarAlimentoActionPerformed alimento = null; disableButton(); if(jTableListaAlimento.getRowCount() != 0) { jTableListaAlimento.removeRowSelectionInterval(0, jTableListaAlimento.getRowCount() - 1); } TelaNovoAlimento novoAlimento = new TelaNovoAlimento(this,true); novoAlimento.setVisible(true); }//GEN-LAST:event_jButtonAdicionarAlimentoActionPerformed private void jTableListaAlimentoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableListaAlimentoMouseClicked int selectedIndex = jTableListaAlimento.getSelectedRow(); jButtonRemover.setEnabled(true); jButtonAdicionarRemessa.setEnabled(true); alimento = listaAlimento.get(selectedIndex); System.out.println("Alimento = " + alimento.getNome()); jComboBoxAlimentoRemessa.setSelectedIndex(selectedIndex); }//GEN-LAST:event_jTableListaAlimentoMouseClicked private void jComboBoxEstoqueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxEstoqueActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBoxEstoqueActionPerformed private void jComboBoxEstoqueItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxEstoqueItemStateChanged if(jComboBoxEstoque.getSelectedIndex() != -1) { int idEstoque = listaEstoque.get(jComboBoxEstoque.getSelectedIndex()).getIdEstoque(); carregaAlimentoDAO(idEstoque); carregaAlimentoComboBox(idEstoque); } else { limpaTableAlimento(); } }//GEN-LAST:event_jComboBoxEstoqueItemStateChanged private void jComboBoxAlimentoRemessaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxAlimentoRemessaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBoxAlimentoRemessaActionPerformed private void jComboBoxAlimentoRemessaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxAlimentoRemessaItemStateChanged int linhaSelecionada = jComboBoxAlimentoRemessa.getSelectedIndex(); if(linhaSelecionada >= 0) { String idAlimento = jComboBoxAlimentoRemessa.getSelectedItem().toString(); carregaRemessaTable(idAlimento); if(linhaSelecionada >= 0) { jTableListaAlimento.setRowSelectionInterval(linhaSelecionada, linhaSelecionada); } } else { limpaTableRemessa(); } }//GEN-LAST:event_jComboBoxAlimentoRemessaItemStateChanged private void jButtonAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAdicionarActionPerformed TelaNovoMapaMerenda novoMapaMerenda = new TelaNovoMapaMerenda(this, rootPaneCheckingEnabled); novoMapaMerenda.setVisible(true); }//GEN-LAST:event_jButtonAdicionarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAdicionar; private javax.swing.JButton jButtonAdicionarAlimento; private javax.swing.JButton jButtonAdicionarRemessa; private javax.swing.JButton jButtonBuscar; private javax.swing.JButton jButtonRemover; private javax.swing.JComboBox<String> jComboBoxAlimentoRemessa; private javax.swing.JComboBox<String> jComboBoxEscola; private javax.swing.JComboBox<String> jComboBoxEstoque; private javax.swing.JLabel jLabelAlimento; private javax.swing.JLabel jLabelEscola; private javax.swing.JLabel jLabelEstoque; private javax.swing.JPanel jPanelEstoque; private javax.swing.JPanel jPanelMapaMerenda; private javax.swing.JPanel jPanelRemessa; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPaneListaAlimento; private javax.swing.JTabbedPane jTabbedPaneAlimento; private javax.swing.JTable jTableListaAlimento; private javax.swing.JTable jTableRemessa; // End of variables declaration//GEN-END:variables }
49.782759
185
0.634758
922e9751e069d726ecd13cc07f09125a030dc67e
1,397
package com.gbozza.android.gigagal.util; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.TimeUtils; public class Utils { public static void drawTextureRegion(SpriteBatch batch, TextureRegion region, Vector2 position) { drawTextureRegion(batch, region, position.x, position.y); } public static void drawTextureRegion(SpriteBatch batch, TextureRegion region, Vector2 position, Vector2 offset) { drawTextureRegion(batch, region, position.x - offset.x, position.y - offset.y); } public static void drawTextureRegion(SpriteBatch batch, TextureRegion region, float x, float y) { batch.draw( region.getTexture(), x, y, 0, 0, region.getRegionWidth(), region.getRegionHeight(), 1, 1, 0, region.getRegionX(), region.getRegionY(), region.getRegionWidth(), region.getRegionHeight(), false, false); } public static float secondsSince(long timeNanos) { return MathUtils.nanoToSec * (TimeUtils.nanoTime() - timeNanos); } }
31.75
117
0.606299
0c21a6277a8352dc88a39baf575e14d2f6d15700
573
package model; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import operation.ComboboxList; import system.DateAndClock; public class TransactionHistoryModel extends DateAndClock { public ObservableList<String> loadAllMonths() { ObservableList<String> list = FXCollections.observableArrayList((new ComboboxList()).getAllMonth()); return list; } public ObservableList<String> loadAllFilter() { ObservableList<String> list = FXCollections.observableArrayList((new ComboboxList()).getFilterList()); return list; } }
24.913043
104
0.790576
086f0ebae6f14fc00f11682b6399233dfaf6f176
535
package com.wizzardo.tools.collections.flow.flows; import java.util.Comparator; /** * Created by wizzardo on 16.04.16. */ public class FlowMaxWithComparator<A> extends FlowProcessOnEnd<A, A> { private final Comparator<? super A> comparator; public FlowMaxWithComparator(A def, Comparator<? super A> comparator) { this.comparator = comparator; result = def; } @Override public void process(A a) { if (result == null || comparator.compare(result, a) < 0) result = a; } }
24.318182
75
0.652336
2c7a0b81a849c1449c0fb9a3e81ca8572bb27a40
640
package no.bouvet.sandvika.oauth2.resource.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @SpringBootApplication @EnableResourceServer @EnableGlobalMethodSecurity(jsr250Enabled = true) public class ResourceServerApplication { public static void main(String[] args) { SpringApplication.run(ResourceServerApplication.class, args); } }
35.555556
102
0.839063
8b37f0001f7c68506a50320e2b56fd6dffb2ba2c
1,541
package com.handsomezhou.funnyalgorithm.model; /** * Created by zhoujq on 2017/10/31. */ public class AlgorithmQuestion { /** * id : 1 * question : 一个格子摆放的随机排序的算法? * questionDescription : 已知外部的大格子的总面积、长、宽是固定,其中分割的格子数也是固定的13个(不一定是13个,这个只是举例,但是随机前知道多少格)。现在我需求是想用某个算法,通过程序去做一个随机,让13个格子的位置随机变化(13个格子的面积、长、宽需要有限制,如面积不小于xx,长和宽不小于xx)。这应该是个比较复杂的算法,可以帮忙给出逻辑即可。 * questionSource : https://www.zhihu.com/question/48397239 * knowledgeKeywords : ["递归","深度搜索"] */ private long id; private String question; private String questionDescription; private String questionSource; private String knowledgeKeywords; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getQuestionDescription() { return questionDescription; } public void setQuestionDescription(String questionDescription) { this.questionDescription = questionDescription; } public String getQuestionSource() { return questionSource; } public void setQuestionSource(String questionSource) { this.questionSource = questionSource; } public String getKnowledgeKeywords() { return knowledgeKeywords; } public void setKnowledgeKeywords(String knowledgeKeywords) { this.knowledgeKeywords = knowledgeKeywords; } }
24.460317
192
0.681376
75d80be1f14294a9d3e16797ce3aa78c75cd2327
256
package com.woodplantation.werwolf.network.objects; /** * Created by Sebu on 12.01.2017. */ public class KickedInformation extends Command { private static final long serialVersionUID = -8637561830191718634L; public String message; }
23.272727
72
0.730469
d802a4b0e950b9bf790416f4fee11a07579c68fb
4,816
package com.emistoolbox.common.excelMerge; import java.util.List; import java.util.Map; import com.emistoolbox.common.excelMerge.ExcelMergeConfig.CellType; import com.emistoolbox.common.model.analysis.EmisAggregatorDef; import com.emistoolbox.common.model.analysis.EmisIndicator; import com.emistoolbox.common.model.meta.EmisMetaData; import com.emistoolbox.common.results.MetaResultValue; import com.emistoolbox.common.results.impl.MetaResultValueImpl; public class ExcelReportUtil { public static final String EXCEL_PREFIX_INDICATOR = "i:"; public static final String EXCEL_PREFIX_AGGREGATOR = "a:"; public static final String EXCEL_PREFIX_FIELD = "f:"; public static String getExcelIndicatorId(EmisIndicator i) { return EXCEL_PREFIX_INDICATOR + normalize(i.getName()); } public static EmisIndicator getIndicator(String id, List<EmisIndicator> indicators) { if (id == null) return null; if (id.startsWith(EXCEL_PREFIX_INDICATOR)) return findIndicator(id.substring(EXCEL_PREFIX_INDICATOR.length()), indicators); else if (id.startsWith(EXCEL_PREFIX_AGGREGATOR)) { int endPos = id.indexOf(":", EXCEL_PREFIX_AGGREGATOR.length()); if (endPos == -1) return null; else return findIndicator(id.substring(EXCEL_PREFIX_AGGREGATOR.length(), endPos), indicators); } return null; } public static String getAggregator(String id) { if (id == null) return null; if (!id.startsWith(EXCEL_PREFIX_AGGREGATOR)) return null; int startPos = id.indexOf(":", EXCEL_PREFIX_AGGREGATOR.length()); if (startPos == -1) return null; return id.substring(startPos + 1); } public static String getExcelAggregatorId(EmisIndicator i, EmisAggregatorDef a) { String key = findKey(i, a); if (key == null) return null; return getExcelAggregatorId(i, key); } public static String getExcelAggregatorId(EmisIndicator i, String key) { return EXCEL_PREFIX_AGGREGATOR + normalize(i.getName()) + ":" + key; } public static String getFieldId(EmisMetaData f) { return EXCEL_PREFIX_FIELD + f.getEntity().getName() + "." + f.getName(); } private static String normalize(String s) { return s == null ? null : s.replace(";", ","); }; private static EmisIndicator findIndicator(String id, List<EmisIndicator> indicators) { if (id == null) return null; for (EmisIndicator indicator : indicators) if (id.equals(normalize(indicator.getName()))) return indicator; return null; } private static String findKey(EmisIndicator indicator, EmisAggregatorDef aggr) { for (Map.Entry<String, EmisAggregatorDef> entry : indicator.getAggregators().entrySet()) if (aggr == entry.getValue()) return entry.getKey(); return null; } public static void addMetaResultValues(List<MetaResultValue> values, List<String> headers, ExcelReportConfig excelConfig, List<EmisIndicator> indicators) { for (ExcelMergeConfig config : excelConfig.getMergeConfigs()) addMetaResultValues(values, headers, config, indicators); } private static void addMetaResultValues(List<MetaResultValue> values, List<String> headers, ExcelMergeConfig config, List<EmisIndicator> indicators) { for (int i = 0; i < config.getCellCount(); i++) { if (config.getCellType(i) != CellType.LOOP_VARIABLE) continue; String variable = config.getCellValue(i); if (headers.contains(variable)) continue; MetaResultValue metaResultValue = getMetaResultValue(variable, indicators); if (metaResultValue == null) continue; headers.add(variable); values.add(metaResultValue); } } private static MetaResultValue getMetaResultValue(String id, List<EmisIndicator> indicators) { EmisIndicator indicator = ExcelReportUtil.getIndicator(id, indicators); if (indicator == null) return null; String key = ExcelReportUtil.getAggregator(id); if (key == null) return new MetaResultValueImpl(indicator); return new MetaResultValueImpl(indicator, key); } }
35.674074
158
0.609427
25dedb6edef360fd06b9318e6502cb01001c13e5
3,796
package com.fc.v2.service; import java.util.List; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.hutool.core.util.StrUtil; import com.fc.v2.common.base.BaseService; import com.fc.v2.common.support.ConvertUtil; import com.fc.v2.mapper.auto.GradeConfigMapper; import com.fc.v2.model.auto.GradeConfig; import com.fc.v2.model.auto.GradeConfigExample; import com.fc.v2.model.custom.Tablepar; import com.fc.v2.util.SnowflakeIdWorker; import com.fc.v2.util.StringUtils; /** * GradeConfigService * @Title: GradeConfigService.java  * @Package com.fc.v2.service  * @author shihangqi_自动生成 * @email ${email} * @date 2022-02-12 18:44:39   **/ @Service public class GradeConfigService implements BaseService<GradeConfig, GradeConfigExample>{ @Autowired private GradeConfigMapper gradeConfigMapper; /** * 分页查询 * @param pageNum * @param pageSize * @return */ public PageInfo<GradeConfig> list(Tablepar tablepar,GradeConfig gradeConfig){ GradeConfigExample testExample=new GradeConfigExample(); //搜索 if(StrUtil.isNotEmpty(tablepar.getSearchText())) {//小窗体 testExample.createCriteria().andLikeQuery2(tablepar.getSearchText()); }else {//大搜索 testExample.createCriteria().andLikeQuery(gradeConfig); } //表格排序 //if(StrUtil.isNotEmpty(tablepar.getOrderByColumn())) { // testExample.setOrderByClause(StringUtils.toUnderScoreCase(tablepar.getOrderByColumn()) +" "+tablepar.getIsAsc()); //}else{ // testExample.setOrderByClause("id ASC"); //} PageHelper.startPage(tablepar.getPage(), tablepar.getLimit()); List<GradeConfig> list= gradeConfigMapper.selectByExample(testExample); PageInfo<GradeConfig> pageInfo = new PageInfo<GradeConfig>(list); return pageInfo; } @Override public int deleteByPrimaryKey(String ids) { Long[] integers = ConvertUtil.toLongArray(",", ids); List<Long> stringB = Arrays.asList(integers); GradeConfigExample example=new GradeConfigExample(); example.createCriteria().andIdIn(stringB); return gradeConfigMapper.deleteByExample(example); } @Override public GradeConfig selectByPrimaryKey(String id) { Long id1 = Long.valueOf(id); return gradeConfigMapper.selectByPrimaryKey(id1); } @Override public int updateByPrimaryKeySelective(GradeConfig record) { return gradeConfigMapper.updateByPrimaryKeySelective(record); } /** * 添加 */ @Override public int insertSelective(GradeConfig record) { record.setId(null); return gradeConfigMapper.insertSelective(record); } @Override public int updateByExampleSelective(GradeConfig record, GradeConfigExample example) { return gradeConfigMapper.updateByExampleSelective(record, example); } @Override public int updateByExample(GradeConfig record, GradeConfigExample example) { return gradeConfigMapper.updateByExample(record, example); } @Override public List<GradeConfig> selectByExample(GradeConfigExample example) { return gradeConfigMapper.selectByExample(example); } @Override public long countByExample(GradeConfigExample example) { return gradeConfigMapper.countByExample(example); } @Override public int deleteByExample(GradeConfigExample example) { return gradeConfigMapper.deleteByExample(example); } /** * 修改权限状态展示或者不展示 * @param gradeConfig * @return */ public int updateVisible(GradeConfig gradeConfig) { return gradeConfigMapper.updateByPrimaryKeySelective(gradeConfig); } }
26.17931
125
0.726027
b0cd7886a0f845d52e40c3ff042940da0acf4d5c
221
package com.obdobion.billiardsFX.model.drills.sologames.bowlliards; /** * <p> * BreakModifier class. * </p> * * @author Chris DeGreef [email protected] */ public enum BreakModifier { SCRATCH }
15.785714
68
0.660633
c553c071bc1f00d3df1efd30a94f8caf81f0c820
22,426
import static org.junit.Assert.*; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import plantsInsects.Insect; import plantsInsects.InsectParams; import plantsInsects.ParameterSerializationHelper; import plantsInsects.Plant; import plantsInsects.PlantInsectBuilder; import plantsInsects.PlantParams; import repast.simphony.context.Context; import repast.simphony.context.DefaultContext; import repast.simphony.engine.environment.RunEnvironment; import repast.simphony.engine.environment.RunState; import repast.simphony.engine.schedule.ISchedule; import repast.simphony.engine.schedule.Schedule; import repast.simphony.parameter.Parameters; import repast.simphony.parameter.ParametersParser; import repast.simphony.scenario.ScenarioUtils; import repast.simphony.space.grid.Grid; import repast.simphony.space.grid.GridPoint; public class ContextBuilderTest { private Context context; private Grid<Object> grid; private Parameters params; @Before public void setUp() throws Exception { String scenarioDirString = "PlantsInsects.rs"; ScenarioUtils.setScenarioDir(new File(scenarioDirString)); File paramsFile = new File(ScenarioUtils.getScenarioDir(), "parameters.xml"); ParametersParser pp = new ParametersParser(paramsFile); params = pp.getParameters(); RunEnvironment.init(new Schedule(), null, params, true); } private void createPlantsAndInsectsSpecies(int plantCount, int insectCount) { ParameterSerializationHelper helper = new ParameterSerializationHelper(); ArrayList<PlantParams> pp = new ArrayList<PlantParams>(); for(int i = 1; i <= plantCount; i++) { PlantParams plant = new PlantParams(); plant.setPlantId("plant" + i); helper.savePlant(plant, params, false); pp.add(plant); params = ParameterSerializationHelper.getSavedParams(); } for(int i = 1; i <= insectCount; i++) { InsectParams ins = new InsectParams(pp); ins.setInsectId("insect" + i); helper.saveInsect(ins, params, false); params = ParameterSerializationHelper.getSavedParams(); } } private void createContext() { context = new DefaultContext(); PlantInsectBuilder builder = new PlantInsectBuilder(); context = builder.build(context); grid = (Grid<Object>) context.getProjection("grid"); RunState.init().setMasterContext(context); } private boolean leftRowHasOnly1PlantType() { int gridSize = params.getInteger("gridSize"); boolean allSameLeft = true; String prevLeftId = ""; for(int i = 0; i < gridSize; i++) { Plant p = getPlantAt(0, i); if(!prevLeftId.isEmpty()) { if(!prevLeftId.equals(p.getSpeciesParams().getPlantId())) { allSameLeft = false; break; } } prevLeftId = p.getSpeciesParams().getPlantId(); } return allSameLeft; } private boolean bottomRowHasOnly1PlantType() { int gridSize = params.getInteger("gridSize"); boolean allSameBottom = true; String prevBotId = ""; for(int i = 0; i < gridSize; i++) { Plant p = getPlantAt(i, 0); if(!prevBotId.isEmpty()) { if(!prevBotId.equals(p.getSpeciesParams().getPlantId())) { allSameBottom = false; break; } } prevBotId = p.getSpeciesParams().getPlantId(); } return allSameBottom; } private int getPlantCount(String plantId) { int count = 0; for(Object o: context.getObjects(Plant.class)) { Plant p = (Plant) o; if(p.getSpeciesParams().getPlantId().equals(plantId)) { count++; } } return count; } private Plant getPlantAt(int x, int y) { Plant result = null; for(Object o: grid.getObjectsAt(x, y)) { if(o.getClass() == Plant.class) { result = (Plant) o; break; } } return result; } @Test public void testGridSize() { Parameters params = RunEnvironment.getInstance().getParameters(); for(int gridSize = 10; gridSize <= 100; gridSize += 10) { params.setValue("gridSize", gridSize); RunEnvironment.getInstance().setParameters(params); createContext(); assertEquals("Error: grid height incorrect", gridSize, grid.getDimensions().getHeight()); assertEquals("Error: grid width incorrect", gridSize, grid.getDimensions().getWidth()); } } @Test public void testInsectDistributionNorth() { createPlantsAndInsectsSpecies(1, 1); params.setValue("insectIds", "insect1"); params.setValue("i_insect1_initial_dist", "North"); RunEnvironment.getInstance().setParameters(params); int gridSize = params.getInteger("gridSize"); int northBorder = gridSize - (gridSize / 20); createContext(); assertTrue("Error: insects not created", context.getObjects(Insect.class).size() > 0); for(Object o: context.getObjects(Insect.class)){ assertTrue("Error: an insect is too far south", grid.getLocation(o).getY() >= northBorder); } } @Test public void testInsectDistributionWest() { createPlantsAndInsectsSpecies(1, 1); params.setValue("insectIds", "insect1"); params.setValue("i_insect1_initial_dist", "West"); RunEnvironment.getInstance().setParameters(params); int gridSize = params.getInteger("gridSize"); int westBorder = gridSize / 20; createContext(); assertTrue(context.getObjects(Insect.class).size() > 0); for(Object o: context.getObjects(Insect.class)){ assertTrue("Error: an insect is too far east", grid.getLocation(o).getX() <= westBorder); } } @Test public void testInsectDistributionNorthWest() { createPlantsAndInsectsSpecies(1, 1); params.setValue("insectIds", "insect1"); params.setValue("i_insect1_initial_dist", "NorthWest"); RunEnvironment.getInstance().setParameters(params); int gridSize = params.getInteger("gridSize"); int westBorder = gridSize / 20; int northBorder = gridSize - (gridSize / 20); createContext(); assertTrue(context.getObjects(Insect.class).size() > 0); for(Object o: context.getObjects(Insect.class)){ assertTrue("Error: an insect is too far east", grid.getLocation(o).getX() <= westBorder); assertTrue("Error: an insect is too far south", grid.getLocation(o).getY() >= northBorder); } } /* This only tests if insect is within grid bounds. It doesn't test the randomness. */ @Test public void testInsectDistributionRandom() { Parameters params = RunEnvironment.getInstance().getParameters(); // this assumes the 'gen' insect is saved params.setValue("insectIds", "gen"); params.setValue("i_gen_initial_dist", "Random"); RunEnvironment.getInstance().setParameters(params); int gridSize = params.getInteger("gridSize"); int westBorder = gridSize / 20; int northBorder = gridSize - (gridSize / 20); createContext(); assertTrue(context.getObjects(Insect.class).size() > 0); for(Object o: context.getObjects(Insect.class)){ GridPoint p = grid.getLocation(o); assertTrue("Error: an insect is outside of bounds", p.getX() < gridSize && p.getX() >= 0); assertTrue("Error: an insect is outside of bounds", p.getY() < gridSize && p.getY() >= 0); } } @Test public void testPlantDistributionRandom2Plants() { createPlantsAndInsectsSpecies(2, 0); int gridSize = 100; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("plantDistribution", "Random"); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 2 species", p1s, p2s); assertFalse("Error: plants should be distributed randomly", allSameBottom); assertFalse("Error: plants should be distributed randomly", allSameLeft); } @Test public void testPlantDistributionRandom3Plants() { createPlantsAndInsectsSpecies(3, 0); int gridSize = 99; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2;plant3"); params.setValue("plantDistribution", "Random"); params.setValue("p_plant1_percentage", 0.33); params.setValue("p_plant2_percentage", 0.33); params.setValue("p_plant3_percentage", 0.33); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); int p3s = getPlantCount("plant3"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 3 species", p1s, p2s); assertEquals("Error: plant count should be equal for the 3 species", p2s, p3s); assertFalse("Error: plants should be distributed randomly", allSameBottom); assertFalse("Error: plants should be distributed randomly", allSameLeft); } @Test public void testPlantDistributionRows2Plants() { createPlantsAndInsectsSpecies(2, 0); int gridSize = 100; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("plantDistribution", "Rows"); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Rows)", p1s, p2s, (gridSize * gridSize) / 10); assertFalse("Error: bottom row should have different plants", allSameBottom); assertTrue("Error: left row should have the same plant", allSameLeft); } @Test public void testPlantDistributionRows3Plants() { createPlantsAndInsectsSpecies(3, 0); int gridSize = 99; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2;plant3"); params.setValue("plantDistribution", "Rows"); params.setValue("p_plant1_percentage", 0.33); params.setValue("p_plant2_percentage", 0.33); params.setValue("p_plant3_percentage", 0.33); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); int p3s = getPlantCount("plant3"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Rows)", p1s, p2s, (gridSize * gridSize) / 10); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Rows)", p2s, p3s, (gridSize * gridSize) / 10); assertFalse("Error: bottom row should have different plants", allSameBottom); assertTrue("Error: left row should have the same plant", allSameLeft); } @Test public void testPlantDistributionBorders2Plants() { createPlantsAndInsectsSpecies(2, 0); int gridSize = 100; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("plantDistribution", "Borders"); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Borders)", p1s, p2s, (gridSize * gridSize) / 10); assertTrue("Error: bottom row should have the same plant", allSameBottom); assertTrue("Error: left row should have the same plant", allSameLeft); } @Test public void testPlantDistributionBorders3Plants() { createPlantsAndInsectsSpecies(3, 0); int gridSize = 99; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2;plant3"); params.setValue("plantDistribution", "Borders"); params.setValue("p_plant1_percentage", 0.33); params.setValue("p_plant2_percentage", 0.33); params.setValue("p_plant3_percentage", 0.33); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); int p3s = getPlantCount("plant3"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Borders)", p1s, p2s, (gridSize * gridSize) / 10); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Borders)", p2s, p3s, (gridSize * gridSize) / 10); assertTrue("Error: bottom row should have the same plant", allSameBottom); assertTrue("Error: left row should have the same plant", allSameLeft); } @Test public void testPlantDistributionBlocks2Plants() { createPlantsAndInsectsSpecies(2, 0); int gridSize = 100; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("plantDistribution", "Blocks"); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Blocks)", p1s, p2s, (gridSize * gridSize) / 10); assertFalse("Error: bottom row should not have the same plant", allSameBottom); assertFalse("Error: left row should not have the same plant", allSameLeft); } @Test public void testPlantDistributionBlocks3Plants() { createPlantsAndInsectsSpecies(3, 0); int gridSize = 99; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2;plant3"); params.setValue("plantDistribution", "Blocks"); params.setValue("p_plant1_percentage", 0.33); params.setValue("p_plant2_percentage", 0.33); params.setValue("p_plant3_percentage", 0.33); RunEnvironment.getInstance().setParameters(params); createContext(); int p1s = getPlantCount("plant1"); int p2s = getPlantCount("plant2"); int p3s = getPlantCount("plant3"); boolean allSameBottom = bottomRowHasOnly1PlantType(); boolean allSameLeft = leftRowHasOnly1PlantType(); assertEquals("Error: total number of plants created is incorrect", context.getObjects(Plant.class).size(), gridSize * gridSize); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Blocks)", p1s, p2s, (gridSize * gridSize) / 10); assertEquals("Error: plant count should be equal for the 3 species (within 10% for Blocks)", p2s, p3s, (gridSize * gridSize) / 10); assertFalse("Error: bottom row should not have the same plant", allSameBottom); assertFalse("Error: left row should not have the same plant", allSameLeft); } @Test public void testInsectSensoryModeVisual() { createPlantsAndInsectsSpecies(2, 1); int gridSize = 2; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("insectIds", "insect1"); params.setValue("plantDistribution", "Blocks"); params.setValue("i_insect1_eggs_on_plants", "plant1-1;plant2-2"); params.setValue("i_insect1_max_eggs", 100); params.setValue("i_insect1_initial_count", 1); params.setValue("i_insect1_memory_size", 1); params.setValue("i_insect1_mortality", 0); params.setValue("i_insect1_mig_out", 0); RunEnvironment.getInstance().setParameters(params); createContext(); Insect ins = (Insect) context.getObjects(Insect.class).get(0); for (int i = 0; i < 10; ++i) { ins.step(); GridPoint newPt = grid.getLocation(ins); if(newPt == null) { System.out.println("testInsectSensoryModeVisual: Test invalid because insect died / migrated out during test"); break; } Plant p = getPlantAt(newPt.getX(), newPt.getY()); assertEquals("Error: insect should only visit preferred plant in Visual mode", p.getSpeciesParams().getPlantId(), "plant2"); } } @Test public void testInsectSensoryModeVisualWithHeight() { createPlantsAndInsectsSpecies(2, 1); int gridSize = 8; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("insectIds", "insect1"); params.setValue("plantDistribution", "Rows"); params.setValue("i_insect1_eggs_on_plants", "plant1-1;plant2-2"); params.setValue("i_insect1_initial_count", 1); params.setValue("i_insect1_max_flight_len", 8); params.setValue("i_insect1_max_eggs", 100); params.setValue("i_insect1_memory_size", 20); params.setValue("i_insect1_mortality", 0); params.setValue("i_insect1_mig_out", 0); params.setValue("p_plant1_height", "High"); params.setValue("p_plant2_height", "Short"); RunEnvironment.getInstance().setParameters(params); createContext(); Insect ins = (Insect) context.getObjects(Insect.class).get(0); int maxX = -1, minX = -1; for(int i = 0; i < gridSize; i++) { if(minX < 0 && getPlantAt(i, 0).getSpeciesParams().getPlantId().equals("plant2")) { minX = i; continue; } if(minX >= 0 && getPlantAt(i, 0).getSpeciesParams().getPlantId().equals("plant1")) { maxX = i - 1; break; } } grid.moveTo(ins, minX, 0); for (int i = 0; i < 16; ++i) { ins.step(); GridPoint newPt = grid.getLocation(ins); if(newPt == null) { System.out.println("testInsectSensoryModeVisualWithHeight: Test invalid because insect died / migrated out during test"); break; } Plant p = getPlantAt(newPt.getX(), newPt.getY()); //System.out.println("min: " + minX + " max: " + maxX + " act: " + newPt); if(i < 15) { assertEquals("Error: insect should only visit preferred plant in Visual mode", p.getSpeciesParams().getPlantId(), "plant2"); assertTrue("Error: insect shoud not leave the row because it shouldn't see other rows", newPt.getX() >= minX); assertTrue("Error: insect shoud not leave the row because it shouldn't see other rows", newPt.getX() <= maxX); } else { assertEquals("Error: insect should have visited all preferred plants in row at this point, moving to non-preferred because it can't see next preferred row", p.getSpeciesParams().getPlantId(), "plant1"); } grid.moveTo(ins, minX, 0); } } @Test public void testInsectSensoryModeContact() { createPlantsAndInsectsSpecies(2, 1); int gridSize = 2; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("insectIds", "insect1"); params.setValue("plantDistribution", "Blocks"); params.setValue("i_insect1_eggs_on_plants", "plant1-1;plant2-2"); params.setValue("i_insect1_max_eggs", 100); params.setValue("i_insect1_initial_count", 1); params.setValue("i_insect1_memory_size", 0); params.setValue("i_insect1_mortality", 0); params.setValue("i_insect1_mig_out", 0); params.setValue("i_insect1_sensory_mode", "Contact"); RunEnvironment.getInstance().setParameters(params); createContext(); Insect ins = (Insect) context.getObjects(Insect.class).get(0); int p1Times = 0, p2Times = 0; for (int i = 0; i < 10; ++i) { ins.step(); GridPoint newPt = grid.getLocation(ins); if(newPt == null) { System.out.println("testInsectSensoryModeContact: Test invalid because insect died / migrated out during test"); break; } Plant p = getPlantAt(newPt.getX(), newPt.getY()); if(p.getSpeciesParams().getPlantId().equals("plant1")) p1Times++; else p2Times++; } assertTrue("Error: should have visited both plants", p1Times > 0); assertTrue("Error: should have visited both plants", p2Times > 0); } @Test public void testInsectSensoryModeOlfactory() { createPlantsAndInsectsSpecies(2, 1); int gridSize = 5; params.setValue("gridSize", gridSize); params.setValue("plantIds", "plant1;plant2"); params.setValue("insectIds", "insect1"); params.setValue("plantDistribution", "Blocks"); params.setValue("i_insect1_eggs_on_plants", "plant1-1;plant2-2"); params.setValue("p_plant1_percentage", 0.4); params.setValue("p_plant2_percentage", 0.6); params.setValue("i_insect1_max_eggs", 100); params.setValue("i_insect1_initial_count", 1); params.setValue("i_insect1_memory_size", 0); params.setValue("i_insect1_mortality", 0); params.setValue("i_insect1_mig_out", 0); params.setValue("i_insect1_sensory_mode", "Olfactory"); params.setValue("i_insect1_max_flight_len", 3); RunEnvironment.getInstance().setParameters(params); createContext(); Insect ins = (Insect) context.getObjects(Insect.class).get(0); grid.moveTo(ins, 0, 0); ArrayList<GridPoint> allPoints = new ArrayList<GridPoint>(); for (int i = 0; i < 10; ++i) { ins.step(); GridPoint newPt = grid.getLocation(ins); if(newPt == null) { System.out.println("testInsectSensoryModeOlfactory: Test invalid because insect died / migrated out during test"); break; } Plant p = getPlantAt(newPt.getX(), newPt.getY()); assertEquals("Error: should fly over all unpreferred and land on preferred", p.getSpeciesParams().getPlantId(), "plant2"); assertTrue("Error: should land on closest preferred", newPt.getX() < 3 && newPt.getY() < 3); allPoints.add(newPt); grid.moveTo(ins, 0, 0); } Set<GridPoint> set = new HashSet<GridPoint>(allPoints); assertTrue("Error: should not have visited the same plant over and over again thanks to randomness", set.size() > 1); } }
37.129139
160
0.720904
a481e03cf492672628eb1e668b8f15072dbb2a9a
3,676
package eu.cityopt.opt.io; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectReader; import eu.cityopt.opt.io.JacksonBinder.Kind; @Singleton public class JacksonBinderScenario { /* XXX @JsonUnwrapped does not work on polymorphic properties, so we make ScenarioItem itself polymorphic. */ @JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="kind", visible=true) @JsonSubTypes({ @JsonSubTypes.Type(value=ExtParam.class, name="ext"), @JsonSubTypes.Type(value=Input.class, name="in"), @JsonSubTypes.Type(value=Output.class, name="out"), @JsonSubTypes.Type(value=DecisionVar.class, name="dv"), @JsonSubTypes.Type(value=Metric.class, name="met"), @JsonSubTypes.Type(value=Constr.class, name="con"), @JsonSubTypes.Type(value=Obj.class, name="obj") }) public abstract static class ScenarioItem { public String scenarioname; public String extparamvalsetname; public abstract JacksonBinder.Item getItem(); public Kind getKind() {return getItem().getKind();} } public abstract static class Item<Type extends JacksonBinder.Item> extends ScenarioItem { @JsonUnwrapped public Type item; @Override public Type getItem() {return item;} } //XXX We need these for @JsonSubTypes above. public static class ExtParam extends Item<JacksonBinder.ExtParam> {} public static class Input extends Item<JacksonBinder.Input> {} public static class Output extends Item<JacksonBinder.Output> {} public static class DecisionVar extends Item<JacksonBinder.DecisionVar> {} public static class Metric extends Item<JacksonBinder.Metric> {} public static class Constr extends Item<JacksonBinder.Constr> {} public static class Obj extends Item<JacksonBinder.Obj> {} @JsonIgnore private final List<ScenarioItem> items; /** * Read from a file. */ @Inject public JacksonBinderScenario( @Named("scenario") ObjectReader reader, @Named("scenario") Path file) throws JsonProcessingException, IOException { JacksonBinderScenario bd = reader.readValue(file.toUri().toURL()); this.items = bd.getItems(); } /** * Read from an input stream. */ public JacksonBinderScenario( ObjectReader reader, InputStream stream) throws JsonProcessingException, IOException { JacksonBinderScenario bd = reader.readValue(stream); this.items = bd.getItems(); } @JsonValue public List<ScenarioItem> getItems() {return items;} @JsonCreator public JacksonBinderScenario(List<ScenarioItem> items) { this.items = items; } /** * Sort items by kind (in place). */ public void sort() { Collections.sort( items, (x1, x2) -> x1.getKind().compareTo(x2.getKind())); } }
33.418182
78
0.693417
b5ca91a8f96f11f9f79f56be715f7b7fa8100fe6
10,600
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package simulator.gui; import analyzer.bl.AnalyzerManager; import general.beans.io_objects.CommandRun; import general.beans.io_objects.ExplorerLayer; import general.beans.io_objects.ProjectRun; import general.beans.io_objects.TestCaseRun; import general.beans.io_objects.TestGroupRun; import general.bl.GlobalAccess; import general.bl.GlobalParamter; import general.io.Mapper; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.awt.Color; import java.awt.GridLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.ScrollPaneConstants; import org.knowm.xchart.PieChart; import org.knowm.xchart.PieChartBuilder; import org.knowm.xchart.XChartPanel; import org.knowm.xchart.XYChart; import org.knowm.xchart.XYChartBuilder; import org.knowm.xchart.style.Styler; import simulator.beans.Kasse; import simulator.bl.CommandExecutionManager; import simulator.bl.ExecutionManager; import simulator.bl.SimulatorActionListener; /** * * @author Lukas Krobath */ public class SimulatorPanel extends javax.swing.JPanel { private DefaultListModel<ExplorerLayer> dlm; private static final Color[] SLICECOLOR = new Color[]{new Color(255, 0, 0), new Color(100, 100, 100), new Color(0, 255, 0), new Color(14, 36, 204)}; private PieChart ges; /** * Creates a new SimulatorPanel */ public SimulatorPanel() { initComponents(); dlm = new DefaultListModel<>(); ExecutionManager.getInstance().setDlm(dlm); liTestvorgang.setModel(dlm); ExecutionManager.getInstance().setEpLog(epLog); ExecutionManager.getInstance().setParent(this); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); liTestvorgang.setCellRenderer(new GegenstandRenderer()); ges = new PieChartBuilder().theme(Styler.ChartTheme.XChart).title("Gesamtübersicht").build(); ges.addSeries("Fehlgeschlagen", 1); ges.addSeries("Wird bearbeitet", 1); ges.addSeries("Erfolgreich", 1); ges.addSeries("Ausstehend", 1); ges.getStyler().setSeriesColors(ExecutionManager.getSLICECOLOR()); paGeneral.add(new XChartPanel(ges)); ExecutionManager.getInstance().setLiTestvorgang(liTestvorgang); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { paCenter = new javax.swing.JPanel(); paLeft = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); liTestvorgang = new javax.swing.JList<>(); jLabel1 = new javax.swing.JLabel(); paLog = new javax.swing.JPanel(); paGeneral = new javax.swing.JPanel(); paEinzel = new javax.swing.JPanel(); paS = new javax.swing.JPanel(); paSouth = new javax.swing.JPanel(); btTVStart = new javax.swing.JButton(); btTVStop = new javax.swing.JButton(); btNextStep = new javax.swing.JButton(); scrollPane = new javax.swing.JScrollPane(); epLog = new javax.swing.JEditorPane(); setName(""); // NOI18N setPreferredSize(new java.awt.Dimension(1000, 580)); setLayout(new java.awt.BorderLayout()); paCenter.setBorder(javax.swing.BorderFactory.createEmptyBorder(15, 15, 15, 15)); paCenter.setPreferredSize(new java.awt.Dimension(550, 263)); paCenter.setLayout(new java.awt.BorderLayout(25, 25)); paLeft.setPreferredSize(new java.awt.Dimension(350, 100)); paLeft.setLayout(new java.awt.BorderLayout(25, 25)); liTestvorgang.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jScrollPane1.setViewportView(liTestvorgang); paLeft.add(jScrollPane1, java.awt.BorderLayout.CENTER); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setText("Testgegenstände:"); paLeft.add(jLabel1, java.awt.BorderLayout.NORTH); paCenter.add(paLeft, java.awt.BorderLayout.WEST); paLog.setLayout(new java.awt.GridLayout(1, 2)); paGeneral.setLayout(new java.awt.BorderLayout()); paLog.add(paGeneral); paEinzel.setLayout(new java.awt.GridLayout(2, 2)); paLog.add(paEinzel); paCenter.add(paLog, java.awt.BorderLayout.CENTER); add(paCenter, java.awt.BorderLayout.CENTER); paS.setBorder(javax.swing.BorderFactory.createEmptyBorder(15, 15, 15, 15)); paS.setPreferredSize(new java.awt.Dimension(600, 340)); paS.setLayout(new java.awt.BorderLayout(25, 25)); paSouth.setBorder(javax.swing.BorderFactory.createEmptyBorder(20, 20, 20, 20)); paSouth.setPreferredSize(new java.awt.Dimension(350, 185)); paSouth.setLayout(new java.awt.GridLayout(3, 1, 25, 10)); btTVStart.setBackground(new java.awt.Color(51, 153, 0)); btTVStart.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btTVStart.setForeground(new java.awt.Color(255, 255, 255)); btTVStart.setText("Testvorgang starten"); btTVStart.setPreferredSize(new java.awt.Dimension(215, 50)); btTVStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onStart(evt); } }); paSouth.add(btTVStart); btTVStop.setBackground(new java.awt.Color(255, 0, 0)); btTVStop.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btTVStop.setForeground(new java.awt.Color(255, 255, 255)); btTVStop.setText("Testvorgang abbrechen"); btTVStop.setEnabled(false); btTVStop.setPreferredSize(new java.awt.Dimension(247, 80)); btTVStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onStop(evt); } }); paSouth.add(btTVStop); btNextStep.setBackground(new java.awt.Color(0, 0, 255)); btNextStep.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N btNextStep.setForeground(new java.awt.Color(255, 255, 255)); btNextStep.setText("Nächster Schritt >"); btNextStep.setEnabled(false); btNextStep.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onNextStep(evt); } }); paSouth.add(btNextStep); paS.add(paSouth, java.awt.BorderLayout.WEST); scrollPane.setPreferredSize(new java.awt.Dimension(111, 250)); epLog.setContentType("text/html"); // NOI18N epLog.setText("<html>\r\n <body>\r\n <h1>Log Nachrichten</h1>\n </body>\r\n</html>\r\n"); epLog.setFocusable(false); scrollPane.setViewportView(epLog); paS.add(scrollPane, java.awt.BorderLayout.CENTER); add(paS, java.awt.BorderLayout.SOUTH); }// </editor-fold>//GEN-END:initComponents /** * Starts a simulation process * * @param evt : Action Event of calling */ private void onStart(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onStart try { for (ExplorerLayer layer : ExecutionManager.getInstance().getTargets()) { System.out.println(layer.getDurchlauf_gegenstand()); } ExecutionManager.getInstance().startSimulation(); btTVStop.setEnabled(true); btTVStart.setEnabled(false); } catch (Exception e) { Object[] options = {"OK"}; int n = JOptionPane.showOptionDialog(this, "Es wurde kein Testsystem ausgewählt!\nSie werden automatisch in die Einstellungen weitergeleitet", "Fehler", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE, null, options, options[0]); GlobalAccess.getInstance().getTest_ide_main_frame().changeTool("settings"); } }//GEN-LAST:event_onStart /** * Stops a simulation process * * @param evt : Action Event of calling */ private void onStop(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onStop ExecutionManager.getInstance().stopSimulation(); btTVStop.setEnabled(false); btTVStart.setEnabled(true); }//GEN-LAST:event_onStop private void onNextStep(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onNextStep ExecutionManager.getInstance().setStepLock(ExecutionManager.getInstance().getStepLock() + 1); btNextStep.setEnabled(ExecutionManager.getInstance().isStepLockActivated()); }//GEN-LAST:event_onNextStep public void tvFinished() { btTVStop.setEnabled(false); btTVStart.setEnabled(true); } public JPanel getPaEinzel() { return paEinzel; } public void setPaEinzel(JPanel paEinzel) { this.paEinzel = paEinzel; } public PieChart getGes() { return ges; } public void setGes(PieChart ges) { this.ges = ges; } public JButton getBtNextStep() { return btNextStep; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btNextStep; private javax.swing.JButton btTVStart; private javax.swing.JButton btTVStop; private javax.swing.JEditorPane epLog; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JList<ExplorerLayer> liTestvorgang; private javax.swing.JPanel paCenter; private javax.swing.JPanel paEinzel; private javax.swing.JPanel paGeneral; private javax.swing.JPanel paLeft; private javax.swing.JPanel paLog; private javax.swing.JPanel paS; private javax.swing.JPanel paSouth; private javax.swing.JScrollPane scrollPane; // End of variables declaration//GEN-END:variables }
38.129496
152
0.67283
4a77ed1ef3f03df5d600344957aa0638e1e8c128
623
package com.shizheng.lreanexpandablerectclervview.musiclistdetail; public class MusicListBean { private String musicTitle; private String musicActor; private String coverImageUrl; public MusicListBean(String musicTitle,String musicActor,String coverImageUrl){ this.coverImageUrl = coverImageUrl; this.musicActor = musicActor; this.musicTitle = musicTitle; } public String getMusicActor() { return musicActor; } public String getMusicTitle() { return musicTitle; } public String getCoverImageUrl() { return coverImageUrl; } }
23.074074
83
0.696629
7b520193a10d23d73ffc50cadf371858e274e64d
2,340
/* * Copyright (C) [SonicCloudOrg] Sonic Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.cloud.sonic.controller.services; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import org.cloud.sonic.common.http.RespModel; import org.cloud.sonic.controller.models.domain.Devices; import org.cloud.sonic.controller.models.http.DeviceDetailChange; import org.cloud.sonic.controller.models.http.UpdateDeviceImg; import java.io.IOException; import java.util.List; import java.util.concurrent.CompletableFuture; /** * @author ZhouYiXun * @des 设备逻辑层 * @date 2021/8/16 22:51 */ public interface DevicesService extends IService<Devices> { boolean saveDetail(DeviceDetailChange deviceDetailChange); void updateDevicesUser(JSONObject jsonObject); void updateImg(UpdateDeviceImg updateDeviceImg); Page<Devices> findAll(List<String> iOSVersion, List<String> androidVersion, List<String> manufacturer, List<String> cpu, List<String> size, List<Integer> agentId, List<String> status, String deviceInfo, Page<Devices> pageable); List<Devices> findAll(int platform); List<Devices> findByIdIn(List<Integer> ids); Devices findByAgentIdAndUdId(int agentId, String udId); Devices findByUdId(String udId); JSONObject getFilterOption(); void deviceStatus(JSONObject jsonObject); Devices findById(int id); List<Devices> listByAgentId(int agentId); String getName(String model) throws IOException; void refreshDevicesBattery(JSONObject jsonObject); Integer findTemper(); RespModel<String> delete(int id); List<Devices> findByAgentForCabinet(int agentId); }
31.621622
106
0.744444
17bdaf803a256685862444500eca1ee8f2c635f4
2,584
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID 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 edu.internet2.middleware.shibboleth.common.config.attribute.resolver.principalConnector; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.opensaml.xml.util.DatatypeHelper; import org.opensaml.xml.util.XMLHelper; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; /** * Spring bean definition for transient principal connectors. */ public class StoredIDPrincipalConnectorBeanDefinitionParser extends BasePrincipalConnectrBeanDefinitionParser { /** Schema type. */ public static final QName SCHEMA_TYPE = new QName(PrincipalConnectorNamespaceHandler.NAMESPACE_URI, "StoredId"); /** {@inheritDoc} */ protected Class getBeanClass(Element arg0) { return StoredIDPrincipalConnectorFactoryBean.class; } /** {@inheritDoc} */ protected void doParse(String pluginId, Element pluginConfig, Map<QName, List<Element>> pluginConfigChildren, BeanDefinitionBuilder pluginBuilder, ParserContext parserContext) { super.doParse(pluginId, pluginConfig, pluginConfigChildren, pluginBuilder, parserContext); pluginBuilder.addPropertyReference("idProducer", DatatypeHelper.safeTrimOrNullString(pluginConfig .getAttributeNS(null, "storedIdDataConnectorRef"))); boolean noResultsIsError = false; if (pluginConfig.hasAttributeNS(null, "noResultIsError")) { noResultsIsError = XMLHelper.getAttributeValueAsBoolean(pluginConfig.getAttributeNodeNS(null, "noResultIsError")); } pluginBuilder.addPropertyValue("noResultIsError", noResultsIsError); } }
43.066667
116
0.759288
e1fd8f729b6a3043e02d7e14412f496820f74e75
378
package com.dmall.sso.service.impl.feign; import com.dmall.mms.api.service.ThirdPartyPlatformService; import org.springframework.cloud.openfeign.FeignClient; /** * @description: ThirdPartyPlatformFeign * @author: created by hang.yu on 2020/3/1 21:49 */ @FeignClient("dmall-service-impl-member") public interface ThirdPartyPlatformFeign extends ThirdPartyPlatformService {}
31.5
77
0.806878
c47517dc94cb50f3f5dfdb1b8d25e0035b1bece6
2,261
/* * Copyright 2018 TWO SIGMA OPEN SOURCE, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twosigma.beakerx.scala.magic.command; import com.twosigma.beakerx.kernel.KernelFunctionality; import com.twosigma.beakerx.kernel.magic.command.MagicCommandExecutionParam; import com.twosigma.beakerx.kernel.magic.command.MagicCommandFunctionality; import com.twosigma.beakerx.kernel.magic.command.outcome.MagicCommandOutcomeItem; public class EnableSparkSupportMagicCommand implements MagicCommandFunctionality { public static final String ENABLE_SPARK_SUPPORT = "%%spark"; private EnableSparkSupportMagicConfiguration command; private KernelFunctionality kernel; public EnableSparkSupportMagicCommand(KernelFunctionality kernel, SparkInitCommandFactory initCommandFactory) { this.kernel = kernel; this.command = new EnableSparkSupportMagicInitConfiguration(initCommandFactory); } @Override public String getMagicCommandName() { return ENABLE_SPARK_SUPPORT; } @Override public MagicCommandOutcomeItem execute(MagicCommandExecutionParam param) { if (command.isInit()) { return initSparkSupport(param); } else { return command.run(param); } } private MagicCommandOutcomeItem initSparkSupport(MagicCommandExecutionParam param) { MagicCommandOutcomeItem init = command.run(param); if (init.getStatus().equals(MagicCommandOutcomeItem.Status.OK)) { this.command = new EnableSparkSupportMagicSparkConfiguration(this.kernel); return this.command.run(param); } else { return init; } } interface EnableSparkSupportMagicConfiguration { MagicCommandOutcomeItem run(MagicCommandExecutionParam param); boolean isInit(); } }
35.328125
113
0.770013
0d0d0e572072402009a56a49b2cef6f4d36ae302
1,908
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.android_webview; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; /** * See {@link android.webkit.HttpAuthHandler}. */ @JNINamespace("android_webview") public class AwHttpAuthHandler { private long mNativeAwHttpAuthHandler; private final boolean mFirstAttempt; public void proceed(String username, String password) { if (mNativeAwHttpAuthHandler != 0) { AwHttpAuthHandlerJni.get().proceed( mNativeAwHttpAuthHandler, AwHttpAuthHandler.this, username, password); mNativeAwHttpAuthHandler = 0; } } public void cancel() { if (mNativeAwHttpAuthHandler != 0) { AwHttpAuthHandlerJni.get().cancel(mNativeAwHttpAuthHandler, AwHttpAuthHandler.this); mNativeAwHttpAuthHandler = 0; } } public boolean isFirstAttempt() { return mFirstAttempt; } @CalledByNative public static AwHttpAuthHandler create(long nativeAwAuthHandler, boolean firstAttempt) { return new AwHttpAuthHandler(nativeAwAuthHandler, firstAttempt); } private AwHttpAuthHandler(long nativeAwHttpAuthHandler, boolean firstAttempt) { mNativeAwHttpAuthHandler = nativeAwHttpAuthHandler; mFirstAttempt = firstAttempt; } @CalledByNative void handlerDestroyed() { mNativeAwHttpAuthHandler = 0; } @NativeMethods interface Natives { void proceed(long nativeAwHttpAuthHandler, AwHttpAuthHandler caller, String username, String password); void cancel(long nativeAwHttpAuthHandler, AwHttpAuthHandler caller); } }
31.278689
96
0.709119
b28012ee83bfc9710d768e524b06bb84e853e0c7
13,915
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.sql.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.sql.fluent.models.ManagedDatabaseSecurityAlertPolicyInner; import com.azure.resourcemanager.sql.models.SecurityAlertPolicyName; import reactor.core.publisher.Mono; /** * An instance of this class provides access to all the operations defined in * ManagedDatabaseSecurityAlertPoliciesClient. */ public interface ManagedDatabaseSecurityAlertPoliciesClient { /** * Gets a managed database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database's security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<ManagedDatabaseSecurityAlertPolicyInner>> getWithResponseAsync( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName); /** * Gets a managed database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database's security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<ManagedDatabaseSecurityAlertPolicyInner> getAsync( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName); /** * Gets a managed database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database's security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) ManagedDatabaseSecurityAlertPolicyInner get( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName); /** * Gets a managed database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database's security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<ManagedDatabaseSecurityAlertPolicyInner> getWithResponse( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName, Context context); /** * Creates or updates a database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @param parameters A managed database security alert policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<ManagedDatabaseSecurityAlertPolicyInner>> createOrUpdateWithResponseAsync( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName, ManagedDatabaseSecurityAlertPolicyInner parameters); /** * Creates or updates a database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @param parameters A managed database security alert policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<ManagedDatabaseSecurityAlertPolicyInner> createOrUpdateAsync( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName, ManagedDatabaseSecurityAlertPolicyInner parameters); /** * Creates or updates a database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @param parameters A managed database security alert policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) ManagedDatabaseSecurityAlertPolicyInner createOrUpdate( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName, ManagedDatabaseSecurityAlertPolicyInner parameters); /** * Creates or updates a database's security alert policy. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policy is defined. * @param securityAlertPolicyName The name of the security alert policy. * @param parameters A managed database security alert policy. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a managed database security alert policy. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<ManagedDatabaseSecurityAlertPolicyInner> createOrUpdateWithResponse( String resourceGroupName, String managedInstanceName, String databaseName, SecurityAlertPolicyName securityAlertPolicyName, ManagedDatabaseSecurityAlertPolicyInner parameters, Context context); /** * Gets a list of managed database's security alert policies. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policies are defined. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of managed database's security alert policies. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<ManagedDatabaseSecurityAlertPolicyInner> listByDatabaseAsync( String resourceGroupName, String managedInstanceName, String databaseName); /** * Gets a list of managed database's security alert policies. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policies are defined. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of managed database's security alert policies. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ManagedDatabaseSecurityAlertPolicyInner> listByDatabase( String resourceGroupName, String managedInstanceName, String databaseName); /** * Gets a list of managed database's security alert policies. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param managedInstanceName The name of the managed instance. * @param databaseName The name of the managed database for which the security alert policies are defined. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of managed database's security alert policies. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ManagedDatabaseSecurityAlertPolicyInner> listByDatabase( String resourceGroupName, String managedInstanceName, String databaseName, Context context); }
57.263374
116
0.751922