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
4b82bfb2c5483c5f43a6e700c23d347649ce0fe7
347
package com.github.cbuschka.zipdiff.io; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; public class UnclosableInputStream extends FilterInputStream { public UnclosableInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { // intentionally skipped } }
17.35
60
0.78098
146c0336844db0c46056f623b19cae801a073ac2
211
package net.messagevortex.transport.imap; /** * Created by Martin on 07.04.2018. */ public enum ImapConnectionState { CONNECTION_NOT_AUTHENTICATED, CONNECTION_AUTHENTICATED, CONNECTION_SELECTED }
19.181818
41
0.763033
0106ebe8b66b6ccf3ffa57dcc4e3a9159f5e8dce
28,308
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.Calendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Result; import javax.xml.validation.Schema; import javax.xml.validation.TypeInfoProvider; import javax.xml.validation.Validator; import javax.xml.validation.ValidatorHandler; import org.eclipse.persistence.internal.oxm.record.XMLEventReaderInputSource; import org.eclipse.persistence.internal.oxm.record.XMLEventReaderReader; import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderInputSource; import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderReader; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.oxm.NamespaceResolver; import org.eclipse.persistence.oxm.XMLContext; import org.eclipse.persistence.oxm.XMLDescriptor; import org.eclipse.persistence.oxm.XMLMarshaller; import org.eclipse.persistence.oxm.XMLRoot; import org.eclipse.persistence.oxm.XMLUnmarshaller; import org.eclipse.persistence.oxm.XMLUnmarshallerHandler; import org.eclipse.persistence.platform.xml.SAXDocumentBuilder; import org.eclipse.persistence.sessions.Project; import org.eclipse.persistence.testing.oxm.OXTestCase; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; public abstract class XMLMappingTestCases extends OXTestCase { protected Document controlDocument; protected Document writeControlDocument; protected XMLMarshaller xmlMarshaller; protected XMLUnmarshaller xmlUnmarshaller; protected XMLContext xmlContext; public String resourceName; protected DocumentBuilder parser; protected Project project; protected String controlDocumentLocation; protected String writeControlDocumentLocation; protected boolean expectsMarshalException; private boolean shouldRemoveEmptyTextNodesFromControlDoc = true; public XMLMappingTestCases(String name) throws Exception { super(name); setupParser(); } public boolean isUnmarshalTest() { return true; } public void setupControlDocs() throws Exception{ if(this.controlDocumentLocation != null) { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(controlDocumentLocation); resourceName = controlDocumentLocation; controlDocument = parser.parse(inputStream); if (shouldRemoveEmptyTextNodesFromControlDoc()) { removeEmptyTextNodes(controlDocument); } inputStream.close(); } if(this.writeControlDocumentLocation != null) { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(writeControlDocumentLocation); writeControlDocument = parser.parse(inputStream); if (shouldRemoveEmptyTextNodesFromControlDoc()) { removeEmptyTextNodes(writeControlDocument); } inputStream.close(); } } public void setUp() throws Exception { setupParser(); setupControlDocs(); xmlContext = getXMLContext(project); xmlMarshaller = createMarshaller(); xmlUnmarshaller = xmlContext.createUnmarshaller(); } protected XMLMarshaller createMarshaller() { XMLMarshaller xmlMarshaller = xmlContext.createMarshaller(); xmlMarshaller.setFormattedOutput(false); return xmlMarshaller; } public void tearDown() { parser = null; xmlContext = null; xmlMarshaller = null; xmlUnmarshaller = null; controlDocument = null; controlDocumentLocation = null; } protected void setupParser() { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setIgnoringElementContentWhitespace(true); parser = builderFactory.newDocumentBuilder(); } catch (Exception e) { e.printStackTrace(); fail("An exception occurred during setup"); } } protected void setSession(String sessionName) { xmlContext = getXMLContext(sessionName); xmlMarshaller = xmlContext.createMarshaller(); xmlMarshaller.setFormattedOutput(false); xmlUnmarshaller = xmlContext.createUnmarshaller(); } protected void setProject(Project project) { this.project = project; } protected Document getControlDocument() { return controlDocument; } /** * Override this function to implement different read/write control documents. * @return * @throws Exception */ protected Document getWriteControlDocument() throws Exception { if(writeControlDocument != null){ return writeControlDocument; } return getControlDocument(); } protected void setControlDocument(String xmlResource) throws Exception { this.controlDocumentLocation = xmlResource; } /** * Provide an alternative write version of the control document when rountrip is not enabled. * If this function is not called and getWriteControlDocument() is not overridden then the write and read control documents are the same. * @param xmlResource * @throws Exception */ protected void setWriteControlDocument(String xmlResource) throws Exception { writeControlDocumentLocation = xmlResource; } abstract protected Object getControlObject(); /* * Returns the object to be used in a comparison on a read * This will typically be the same object used to write */ public Object getReadControlObject() { return getControlObject(); } /* * Returns the object to be written to XML which will be compared * to the control document. */ public Object getWriteControlObject() { return getControlObject(); } public void testXMLToObjectFromInputStream() throws Exception { if(isUnmarshalTest()) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); Object testObject = xmlUnmarshaller.unmarshal(instream); instream.close(); xmlToObjectTest(testObject); } } public void testXMLToObjectFromNode() throws Exception { if(isUnmarshalTest()) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); Node node = parser.parse(instream); Object testObject = xmlUnmarshaller.unmarshal(node); instream.close(); xmlToObjectTest(testObject); } } public void testXMLToObjectFromXMLStreamReader() throws Exception { if(isUnmarshalTest() && null != XML_INPUT_FACTORY) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); XMLStreamReader xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(instream); XMLStreamReaderReader staxReader = new XMLStreamReaderReader(); staxReader.setErrorHandler(xmlUnmarshaller.getErrorHandler()); XMLStreamReaderInputSource inputSource = new XMLStreamReaderInputSource(xmlStreamReader); Object testObject = xmlUnmarshaller.unmarshal(staxReader, inputSource); instream.close(); xmlToObjectTest(testObject); } } public void testXMLToObjectFromXMLEventReader() throws Exception { if(isUnmarshalTest() && null != XML_INPUT_FACTORY) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); XMLEventReader xmlEventReader = XML_INPUT_FACTORY.createXMLEventReader(instream); XMLEventReaderReader staxReader = new XMLEventReaderReader(); staxReader.setErrorHandler(xmlUnmarshaller.getErrorHandler()); XMLEventReaderInputSource inputSource = new XMLEventReaderInputSource(xmlEventReader); Object testObject = xmlUnmarshaller.unmarshal(staxReader, inputSource); instream.close(); xmlToObjectTest(testObject); } } public void xmlToObjectTest(Object testObject) throws Exception { log("\n**xmlToObjectTest**"); log("Expected:"); Object controlObject = getReadControlObject(); if(null == controlObject) { log((String) null); } else { log(controlObject.toString()); } log("Actual:"); if(null == testObject) { log((String) null); } else { log(testObject.toString()); } if ((getReadControlObject() instanceof XMLRoot) && (testObject instanceof XMLRoot)) { XMLRoot controlObj = (XMLRoot)getReadControlObject(); XMLRoot testObj = (XMLRoot)testObject; compareXMLRootObjects(controlObj, testObj); } else { assertEquals(getReadControlObject(), testObject); } } public static void compareXMLRootObjects(XMLRoot controlObj, XMLRoot testObj) { assertEquals(controlObj.getLocalName(), testObj.getLocalName()); assertEquals(controlObj.getNamespaceURI(), testObj.getNamespaceURI()); if (null != controlObj.getObject() && null != testObj.getObject() && controlObj.getObject() instanceof java.util.Calendar && testObj.getObject() instanceof java.util.Calendar) { assertTrue(((Calendar)controlObj.getObject()).getTimeInMillis() == ((Calendar)testObj.getObject()).getTimeInMillis()); } else { assertEquals(controlObj.getObject(), testObj.getObject()); } assertEquals(controlObj.getSchemaType(), testObj.getSchemaType()); } public void objectToXMLDocumentTest(Document testDocument) throws Exception { log("**objectToXMLDocumentTest**"); log("Expected:"); log(getWriteControlDocument()); log("\nActual:"); log(testDocument); assertXMLIdentical(getWriteControlDocument(), testDocument); } public void testObjectToXMLDocument() throws Exception { Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); Document testDocument; try { testDocument = xmlMarshaller.objectToXML(objectToWrite); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); objectToXMLDocumentTest(testDocument); } public void testObjectToXMLStringWriter() throws Exception { StringWriter writer = new StringWriter(); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); try { xmlMarshaller.marshal(objectToWrite, writer); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); StringReader reader = new StringReader(writer.toString()); InputSource inputSource = new InputSource(reader); Document testDocument = parser.parse(inputSource); writer.close(); reader.close(); objectToXMLDocumentTest(testDocument); } public void testValidatingMarshal() throws Exception { StringWriter writer = new StringWriter(); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); XMLMarshaller validatingMarshaller = createMarshaller(); validatingMarshaller.setSchema(FakeSchema.INSTANCE); try { validatingMarshaller.marshal(objectToWrite, writer); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } StringReader reader = new StringReader(writer.toString()); InputSource inputSource = new InputSource(reader); Document testDocument = parser.parse(inputSource); writer.close(); reader.close(); objectToXMLDocumentTest(testDocument); } public void testObjectToOutputStream() throws Exception { Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { xmlMarshaller.marshal(objectToWrite, stream); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); InputStream is = new ByteArrayInputStream(stream.toByteArray()); Document testDocument = parser.parse(is); stream.close(); is.close(); objectToXMLDocumentTest(testDocument); } public void testObjectToOutputStreamASCIIEncoding() throws Exception { Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { xmlMarshaller.setEncoding("US-ASCII"); xmlMarshaller.marshal(objectToWrite, stream); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); InputStream is = new ByteArrayInputStream(stream.toByteArray()); Document testDocument = parser.parse(is); stream.close(); is.close(); objectToXMLDocumentTest(testDocument); } public void testObjectToXMLStreamWriter() throws Exception { if(XML_OUTPUT_FACTORY != null && staxResultClass != null) { StringWriter writer = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty(factory.IS_REPAIRING_NAMESPACES, new Boolean(false)); XMLStreamWriter streamWriter= factory.createXMLStreamWriter(writer); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); Result result = (Result)PrivilegedAccessHelper.invokeConstructor(staxResultStreamWriterConstructor, new Object[]{streamWriter}); try { xmlMarshaller.marshal(objectToWrite, result); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } streamWriter.flush(); int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); StringReader reader = new StringReader(writer.toString()); InputSource inputSource = new InputSource(reader); Document testDocument = parser.parse(inputSource); writer.close(); reader.close(); objectToXMLDocumentTest(testDocument); } } public void testObjectToXMLEventWriter() throws Exception { if(XML_OUTPUT_FACTORY != null && staxResultClass != null) { StringWriter writer = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty(factory.IS_REPAIRING_NAMESPACES, new Boolean(false)); XMLEventWriter eventWriter= factory.createXMLEventWriter(writer); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); Result result = (Result)PrivilegedAccessHelper.invokeConstructor(staxResultEventWriterConstructor, new Object[]{eventWriter}); try { xmlMarshaller.marshal(objectToWrite, result); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } eventWriter.flush(); int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); StringReader reader = new StringReader(writer.toString()); InputSource inputSource = new InputSource(reader); Document testDocument = parser.parse(inputSource); writer.close(); reader.close(); objectToXMLDocumentTest(testDocument); } } protected int getNamespaceResolverSize(XMLDescriptor desc){ int size = -1; if (desc != null) { NamespaceResolver nr = desc.getNamespaceResolver(); if (nr != null) { size = nr.getNamespaces().size(); }else{ size =0; } } return size; } public void testObjectToContentHandler() throws Exception { SAXDocumentBuilder builder = new SAXDocumentBuilder(); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); try { xmlMarshaller.marshal(objectToWrite, builder); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); Document controlDocument = getWriteControlDocument(); Document testDocument = builder.getDocument(); log("**testObjectToContentHandler**"); log("Expected:"); log(controlDocument); log("\nActual:"); log(testDocument); //Diff diff = new Diff(controlDocument, testDocument); //this.assertXMLEqual(diff, true); assertXMLIdentical(controlDocument, testDocument); } public void testXMLToObjectFromURL() throws Exception { if(isUnmarshalTest()) { java.net.URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); Object testObject = xmlUnmarshaller.unmarshal(url); xmlToObjectTest(testObject); } } public void testUnmarshallerHandler() throws Exception { if(isUnmarshalTest()) { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); XMLUnmarshallerHandler xmlUnmarshallerHandler = xmlUnmarshaller.getUnmarshallerHandler(); xmlReader.setContentHandler(xmlUnmarshallerHandler); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName); InputSource inputSource = new InputSource(inputStream); xmlReader.parse(inputSource); xmlToObjectTest(xmlUnmarshallerHandler.getResult()); } } public boolean shouldRemoveEmptyTextNodesFromControlDoc() { return shouldRemoveEmptyTextNodesFromControlDoc; } public void setShouldRemoveEmptyTextNodesFromControlDoc(boolean value) { this.shouldRemoveEmptyTextNodesFromControlDoc = value; } public void assertMarshalException(Exception exception) throws Exception { throw exception; } public static class FakeSchema extends Schema { public static FakeSchema INSTANCE = new FakeSchema(); private ValidatorHandler validatorHandler; private FakeSchema() { validatorHandler = new FakeValidatorHandler(); } @Override public Validator newValidator() { return null; } @Override public ValidatorHandler newValidatorHandler() { return validatorHandler; } } private static class FakeValidatorHandler extends ValidatorHandler { public void setDocumentLocator(Locator locator) { } public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } public void startPrefixMapping(String prefix, String uri) throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { } public void endElement(String uri, String localName, String qName) throws SAXException { } public void characters(char[] ch, int start, int length) throws SAXException { } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public void skippedEntity(String name) throws SAXException { } @Override public void setContentHandler(ContentHandler receiver) { } @Override public ContentHandler getContentHandler() { return null; } @Override public void setErrorHandler(ErrorHandler errorHandler) { } @Override public ErrorHandler getErrorHandler() { return null; } @Override public void setResourceResolver(LSResourceResolver resourceResolver) { } @Override public LSResourceResolver getResourceResolver() { return null; } @Override public TypeInfoProvider getTypeInfoProvider() { return null; } } }
37.345646
185
0.653314
107dce2c6b956317faa19e1cd50b245783f955cd
7,185
package io.smallrye.openapi.api.models; import java.util.ArrayList; import java.util.List; import org.eclipse.microprofile.openapi.models.Components; import org.eclipse.microprofile.openapi.models.ExternalDocumentation; import org.eclipse.microprofile.openapi.models.OpenAPI; import org.eclipse.microprofile.openapi.models.PathItem; import org.eclipse.microprofile.openapi.models.Paths; import org.eclipse.microprofile.openapi.models.info.Info; import org.eclipse.microprofile.openapi.models.security.SecurityRequirement; import org.eclipse.microprofile.openapi.models.servers.Server; import org.eclipse.microprofile.openapi.models.tags.Tag; import io.smallrye.openapi.runtime.util.ModelUtil; /** * An implementation of the {@link OpenAPI} OpenAPI model interface. */ public class OpenAPIImpl extends ExtensibleImpl<OpenAPI> implements OpenAPI, ModelImpl { private String openapi; private Info info; private ExternalDocumentation externalDocs; private List<Server> servers; private List<SecurityRequirement> security; private List<Tag> tags; private Paths paths; private Components components; /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getOpenapi() */ @Override public String getOpenapi() { return this.openapi; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setOpenapi(java.lang.String) */ @Override public void setOpenapi(String openapi) { this.openapi = openapi; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getInfo() */ @Override public Info getInfo() { return this.info; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setInfo(org.eclipse.microprofile.openapi.models.info.Info) */ @Override public void setInfo(Info info) { this.info = info; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getExternalDocs() */ @Override public ExternalDocumentation getExternalDocs() { return this.externalDocs; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setExternalDocs(org.eclipse.microprofile.openapi.models.ExternalDocumentation) */ @Override public void setExternalDocs(ExternalDocumentation externalDocs) { this.externalDocs = externalDocs; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getServers() */ @Override public List<Server> getServers() { return ModelUtil.unmodifiableList(this.servers); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setServers(java.util.List) */ @Override public void setServers(List<Server> servers) { this.servers = ModelUtil.replace(servers, ArrayList<Server>::new); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#addServer(org.eclipse.microprofile.openapi.models.servers.Server) */ @Override public OpenAPI addServer(Server server) { this.servers = ModelUtil.add(server, this.servers, ArrayList<Server>::new); return this; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#removeServer(org.eclipse.microprofile.openapi.models.servers.Server) */ @Override public void removeServer(Server server) { ModelUtil.remove(this.servers, server); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getSecurity() */ @Override public List<SecurityRequirement> getSecurity() { return ModelUtil.unmodifiableList(this.security); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setSecurity(java.util.List) */ @Override public void setSecurity(List<SecurityRequirement> security) { this.security = ModelUtil.replace(security, ArrayList<SecurityRequirement>::new); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#addSecurityRequirement(org.eclipse.microprofile.openapi.models.security.SecurityRequirement) */ @Override public OpenAPI addSecurityRequirement(SecurityRequirement securityRequirement) { ModelUtil.add(securityRequirement, this.security, ArrayList<SecurityRequirement>::new); return this; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#removeSecurityRequirement(org.eclipse.microprofile.openapi.models.security.SecurityRequirement) */ @Override public void removeSecurityRequirement(SecurityRequirement securityRequirement) { ModelUtil.remove(this.security, securityRequirement); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getTags() */ @Override public List<Tag> getTags() { return ModelUtil.unmodifiableList(this.tags); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setTags(java.util.List) */ @Override public void setTags(List<Tag> tags) { this.tags = ModelUtil.replace(tags, ArrayList<Tag>::new); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#addTag(org.eclipse.microprofile.openapi.models.tags.Tag) */ @Override public OpenAPI addTag(Tag tag) { if (tag == null) { return this; } if (this.tags == null) { this.tags = new ArrayList<>(); } if (!this.hasTag(tag.getName())) { this.tags.add(tag); } return this; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#removeTag(org.eclipse.microprofile.openapi.models.tags.Tag) */ @Override public void removeTag(Tag tag) { ModelUtil.remove(this.tags, tag); } /** * Returns true if the tag already exists in the OpenAPI document. * * @param name */ private boolean hasTag(String name) { if (this.tags == null || name == null) { return false; } return this.tags.stream().anyMatch(tag -> tag.getName().equals(name)); } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getPaths() */ @Override public Paths getPaths() { return this.paths; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setPaths(org.eclipse.microprofile.openapi.models.Paths) */ @Override public void setPaths(Paths paths) { this.paths = paths; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#getComponents() */ @Override public Components getComponents() { return this.components; } /** * @see org.eclipse.microprofile.openapi.models.OpenAPI#setComponents(org.eclipse.microprofile.openapi.models.Components) */ @Override public void setComponents(Components components) { this.components = components; } @Override // TODO: Remove method for MicroProfile OpenAPI 2.0 public OpenAPI path(String name, PathItem path) { if (this.paths == null) { this.paths = new PathsImpl(); } this.paths.addPathItem(name, path); return this; } }
29.813278
155
0.669868
510995f4adfab61e8f0dd66785eeb74ce2b32d3e
1,556
package icfpc2020; public class MessageImpl implements Message { private final long[] message; private final int length; public MessageImpl(String s) { this(s.length()); for (int i = 0; i < length; i++) { if (s.charAt(i) == '1') { setValue(i, 1); } } } public MessageImpl(int length) { this.length = length; message = new long[length / 64 + 1]; } public void setValue(int position, int value) { assert value == 0 || value == 1: "Wrong value " + value; assert position / 64 < message.length: "Wrong position " + position; message[position / 64] |= ((long) value) << position % 64; } @Override public int getLength() { return length; } @Override public int getValueAt(int position) { assert position / 64 < message.length: "Wrong position " + position; final long l = message[position / 64] & 1L << position % 64; return l != 0L ? 1: 0; } @Override public String toString() { final StringBuilder b = new StringBuilder(); for (int i = 0; i < length; i++) { b.append(getValueAt(i)); } return b.toString(); } public static void main(String[] args) { final String s = "110110000111011111100001001111110101000000"; final Message m = new MessageImpl(s); System.out.println(s); System.out.println(m.toString()); System.out.println(m.toString().equals(s)); } }
27.298246
76
0.556555
1aad50b4522d0213d36c79b2679f73b2d6e169bf
2,673
package com.xinqihd.sns.gameserver.admin.user; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collection; import javax.swing.JButton; import javax.swing.JDialog; import net.miginfocom.swing.MigLayout; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.util.WindowUtils; import com.xinqihd.sns.gameserver.admin.action.ActionName; import com.xinqihd.sns.gameserver.entity.user.PropData; import com.xinqihd.sns.gameserver.entity.user.PropDataSlot; public class ManagePropDataSlotDialog extends JDialog implements ActionListener { private PropData propData = null; private ArrayList<PropDataSlot> slots = new ArrayList<PropDataSlot>(); private ArrayList<PropDataSlotPanel> panels = new ArrayList<PropDataSlotPanel>(); private JButton okButton = new JButton("确定"); private JButton cancelButton = new JButton("取消"); public ManagePropDataSlotDialog(PropData propData, int size) { this.propData = propData; slots.addAll(propData.getSlots()); if ( size <= 0 ) { this.propData.setSlots(slots); } else { /** * 删除多余的插槽 */ if ( size < slots.size() ) { for ( int j=slots.size()-1; j>=size; j-- ) { slots.remove(j); } } for ( PropDataSlot slot : slots ) { panels.add(new PropDataSlotPanel(slot)); } if ( size > slots.size() ) { /** * 添加不足的插槽 */ for ( int j=slots.size(); j<size; j++ ) { PropDataSlot slot = new PropDataSlot(); slots.add(slot); panels.add(new PropDataSlotPanel(slot)); } } } init(); } public void init() { this.setSize(600, 400); Point c = WindowUtils.getPointForCentering(this); this.setLocation(c); this.setLayout(new MigLayout("wrap 3")); for ( PropDataSlotPanel panel : panels ) { this.add(panel, ""); } this.okButton.setActionCommand(ActionName.OK.name()); this.okButton.addActionListener(this); this.cancelButton.setActionCommand(ActionName.CANCEL.name()); this.cancelButton.addActionListener(this); JXPanel btnPanel = new JXPanel(); btnPanel.add(okButton); btnPanel.add(cancelButton); this.add(btnPanel, "dock south, width 100%"); this.pack(); this.setModal(true); } public void actionPerformed(ActionEvent e) { if ( ActionName.OK.name().equals(e.getActionCommand()) ) { ArrayList<PropDataSlot> slots = new ArrayList<PropDataSlot>(); for ( PropDataSlotPanel panel : panels ) { slots.add(panel.getPropDataSlot()); } this.propData.setSlots(slots); this.dispose(); } else if ( ActionName.CANCEL.name().equals(e.getActionCommand()) ) { this.dispose(); } } }
26.73
82
0.697344
d58a70b7584f38fc8148dae6a09a7eefb18623e8
295
package com.bazaarvoice.commons.data.dao.audit; import com.bazaarvoice.commons.data.model.AuditAction; import com.bazaarvoice.commons.data.model.User; public interface GenericAuditActionCriteria<U extends User> extends AuditActionCriteria<AuditAction<U>, U, GenericAuditActionCriteria<U>> { }
36.875
139
0.833898
85660818f9ced5d44eefc7ea243340a48b4bb440
1,017
package com.box.androidsdk.content; public class BoxConstants { public static final String TAG = "BoxContentSdk"; public static final String BASE_URI = "https://api.box.com/2.0"; public static final String BASE_UPLOAD_URI = "https://upload.box.com/api/2.0"; public static final String OAUTH_BASE_URI = "https://api.box.com"; public static final String FIELD_SIZE = "size"; public static final String FIELD_CONTENT_CREATED_AT = "content_created_at"; public static final String FIELD_CONTENT_MODIFIED_AT = "content_modified_at"; public static final String FIELD_COMMENT_COUNT = "comment_count"; public static final String ROOT_FOLDER_ID = "0"; public static final String KEY_CLIENT_ID = "client_id"; public static final String KEY_REDIRECT_URL = "redirect_uri"; public static final String KEY_CLIENT_SECRET = "client_secret"; public static final String KEY_BOX_DEVICE_ID = "boxdeviceid"; public static final String KEY_BOX_DEVICE_NAME = "boxdevicename"; }
40.68
82
0.754179
b90d4ee87c9778e50d59af95ea41622017c239cc
705
package com.epam.training.miservices.services.drugs.config; import com.epam.training.miservices.services.drugs.model.Drug; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; import org.springframework.web.servlet.config.annotation.CorsRegistry; @Configuration public class RestRepositoryConfiguration implements RepositoryRestConfigurer { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) { config.exposeIdsFor( Drug.class ); } }
39.166667
109
0.811348
9aeba409332a51bc2d60d7b060413f07d515cfa8
19,195
/* * Copyright (c) 2002-2015 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of JGoodies Software GmbH 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 com.jgoodies.forms.builder; import java.awt.Color; import java.awt.Component; import java.awt.FocusTraversalPolicy; import java.util.ResourceBundle; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import com.jgoodies.common.internal.ResourceBundleAccessor; import com.jgoodies.common.internal.StringResourceAccess; import com.jgoodies.common.internal.StringResourceAccessor; import com.jgoodies.common.swing.MnemonicUtils; import com.jgoodies.forms.FormsSetup; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; /** * A general purpose builder class that uses the FormLayout to lay out JPanels. * In addition to its superclass {@link PanelBuilder} this class provides * convenience behavior to map * resource keys to their associated internationalized (i15d) strings * when adding labels, titles and titled separators.<p> * * The localized texts used in methods {@code #addI15d*} can be * <em>marked texts</em>, i.e. strings with an optional mnemonic marker. * See the {@link MnemonicUtils} class comment for details.<p> * * For debugging purposes you can automatically set a tooltip for the * created labels that show its resource key. In case of an inproper * resource localization, the label will show the wrong text, and the tooltip * will help you identify the resource key with the broken localization. * This feature can be enabled by calling {@code setDebugToolTipsEnabled}. * If you want to enable it in a deployed application, you can set the system * parameter {@code I15dPanelBuilder.debugToolTipsEnabled} to "true".<p> * * Subclasses must implement the conversion from resource key * to the localized string in {@code #getI15dString(String)}. * For example class I15dPanelBuilder gets a ResourceBundle during * construction, and requests strings from that bundle. * * @author Karsten Lentzsch * @version $Revision: 1.12 $ * * @see ResourceBundle * * @since 1.1 * * @deprecated Replaced by the internationalization support provided * by the JGoodies Smart Client {@code Resources} class. * Although deprecated, this class will remain in the Forms library * for the next versions. */ @Deprecated public class I15dPanelBuilder extends PanelBuilder { /** * Holds the ResourceBundle used to look up internationalized * (i15d) String resources. */ private final StringResourceAccessor resources; private boolean debugToolTipsEnabled = FormsSetup.getDebugToolTipsEnabledDefault(); // Instance Creation **************************************************** /** * Constructs an I15dPanelBuilder for the given layout and resource bundle. * Uses an instance of JPanel as layout container. * * @param layout the FormLayout used to layout the container * @param bundle the ResourceBundle used to look up i15d strings * * @throws NullPointerException if {@code layout} or {@code bundle}, * is {@code null} */ public I15dPanelBuilder(FormLayout layout, ResourceBundle bundle){ this(layout, bundle, new JPanel(null)); } /** * Constructs an I15dPanelBuilder for the given FormLayout, resource bundle, * and layout container. * * @param layout the FormLayout used to layout the container * @param bundle the ResourceBundle used to lookup i15d strings * @param container the layout container * * @throws NullPointerException if {@code layout}, {@code bundle}, * or {@code container} is {@code null} */ public I15dPanelBuilder(FormLayout layout, ResourceBundle bundle, JPanel container){ this(layout, new ResourceBundleAccessor(bundle), container); } /** * Constructs an I15dPanelBuilder for the given FormLayout, resource bundle, * and layout container. * * @param layout the FormLayout used to layout the container * @param localizer used to lookup i15d strings * * @throws NullPointerException if {@code layout} is {@code null} */ public I15dPanelBuilder(FormLayout layout, StringResourceAccessor localizer){ this(layout, localizer, new JPanel(null)); } /** * Constructs an I15dPanelBuilder for the given FormLayout, resource bundle, * and layout container. * * @param layout the FormLayout used to layout the container * @param localizer used to lookup i15d strings * @param container the layout container * * @throws NullPointerException if {@code layout} or {@code container} is {@code null} */ public I15dPanelBuilder(FormLayout layout, StringResourceAccessor localizer, JPanel container){ super(layout, container); this.resources = localizer; } // Frequently Used Panel Properties *************************************** @Override public I15dPanelBuilder background(Color background) { super.background(background); return this; } @Override public I15dPanelBuilder border(Border border) { super.border(border); return this; } @Override public I15dPanelBuilder border(String emptyBorderSpec) { super.border(emptyBorderSpec); return this; } @Override public I15dPanelBuilder padding(EmptyBorder padding) { super.padding(padding); return this; } @Override public I15dPanelBuilder padding(String paddingSpec, Object... args) { super.padding(paddingSpec); return this; } @Override public I15dPanelBuilder opaque(boolean b) { super.opaque(b); return this; } @Override public I15dPanelBuilder focusTraversal(FocusTraversalPolicy policy) { super.focusTraversal(policy); return this; } public I15dPanelBuilder debugToolTipsEnabled(boolean b) { this.debugToolTipsEnabled = b; return this; } // Adding Labels and Separators ***************************************** /** * Adds an internationalized (i15d) textual label to the form using the * specified constraints. * * @param resourceKey the resource key for the label's text * @param constraints the label's cell constraints * @return the added label */ public final JLabel addI15dLabel(String resourceKey, CellConstraints constraints) { JLabel label = addLabel(getResourceString(resourceKey), constraints); if (isDebugToolTipsEnabled()) { label.setToolTipText(resourceKey); } return label; } /** * Adds an internationalized (i15d) textual label to the form using the * specified constraints. * * @param resourceKey the resource key for the label's text * @param encodedConstraints a string representation for the constraints * @return the added label */ public final JLabel addI15dLabel(String resourceKey, String encodedConstraints) { return addI15dLabel(resourceKey, new CellConstraints(encodedConstraints)); } /** * Adds an internationalized (i15d) label and component to the panel using * the given cell constraints. Sets the label as <i>the</i> component label * using {@link JLabel#setLabelFor(java.awt.Component)}.<p> * * <strong>Note:</strong> The {@link CellConstraints} objects for the label * and the component must be different. Cell constraints are implicitly * cloned by the {@code FormLayout} when added to the container. * However, in this case you may be tempted to reuse a * {@code CellConstraints} object in the same way as with many other * builder methods that require a single {@code CellConstraints} * parameter. * The pitfall is that the methods {@code CellConstraints.xy**(...)} * just set the coordinates but do <em>not</em> create a new instance. * And so the second invocation of {@code xy***(...)} overrides * the settings performed in the first invocation before the object * is cloned by the {@code FormLayout}.<p> * * <strong>Wrong:</strong><pre> * builder.addI15dLabel("name.key", * CC.xy(1, 7), // will be modified by the code below * nameField, * CC.xy(3, 7) // sets the single instance to (3, 7) * ); * </pre> * <strong>Correct:</strong><pre> * builder.addI15dLabel("name.key", * CC.xy(1, 7).clone(), // cloned before the next modification * nameField, * CC.xy(3, 7) // sets this instance to (3, 7) * ); * </pre> * * @param resourceKey the resource key for the label * @param labelConstraints the label's cell constraints * @param component the component to add * @param componentConstraints the component's cell constraints * @return the added label * @throws IllegalArgumentException if the same cell constraints instance * is used for the label and the component * @see JLabel#setLabelFor(java.awt.Component) */ public final JLabel addI15dLabel( String resourceKey, CellConstraints labelConstraints, Component component, CellConstraints componentConstraints) { JLabel label = addLabel(getResourceString(resourceKey), labelConstraints, component, componentConstraints); if (isDebugToolTipsEnabled()) { label.setToolTipText(resourceKey); } return label; } // Adding Labels for Read-Only Fields ************************************* /** * Adds an internationalized (i15d) textual label to the form using the * specified constraints that is intended to label a read-only component. * * @param resourceKey the resource key for the label's text * @param constraints the label's cell constraints * @return the added label * * @since 1.3 */ public final JLabel addI15dROLabel(String resourceKey, CellConstraints constraints) { JLabel label = addROLabel(getResourceString(resourceKey), constraints); if (isDebugToolTipsEnabled()) { label.setToolTipText(resourceKey); } return label; } /** * Adds an internationalized (i15d) textual label to the form using the * specified constraints that is intended to label a read-only component. * * @param resourceKey the resource key for the label's text * @param encodedConstraints a string representation for the constraints * @return the added label * * @since 1.3 */ public final JLabel addI15dROLabel(String resourceKey, String encodedConstraints) { return addI15dROLabel(resourceKey, new CellConstraints(encodedConstraints)); } /** * Adds an internationalized (i15d) label and component to the panel using * the given cell constraints. Intended for read-only components. * Sets the label as <i>the</i> component label * using {@link JLabel#setLabelFor(java.awt.Component)}.<p> * * <strong>Note:</strong> The {@link CellConstraints} objects for the label * and the component must be different. Cell constraints are implicitly * cloned by the {@code FormLayout} when added to the container. * However, in this case you may be tempted to reuse a * {@code CellConstraints} object in the same way as with many other * builder methods that require a single {@code CellConstraints} * parameter. * The pitfall is that the methods {@code CellConstraints.xy**(...)} * just set the coordinates but do <em>not</em> create a new instance. * And so the second invocation of {@code xy***(...)} overrides * the settings performed in the first invocation before the object * is cloned by the {@code FormLayout}.<p> * * <strong>Wrong:</strong><pre> * builder.addI15dROLabel("name.key", * CC.xy(1, 7), // will be modified by the code below * nameField, * CC.xy(3, 7) // sets the single instance to (3, 7) * ); * </pre> * <strong>Correct:</strong><pre> * builder.addI15dROLabel("name.key", * CC.xy(1, 7).clone(), // cloned before the next modification * nameField, * CC.xy(3, 7) // sets this instance to (3, 7) * ); * </pre> * <strong>Better:</strong><pre> * builder.addI15dROLabel("name.key", * CC.xy(1, 7) // creates a CellConstraints object * nameField, * CC.xy(3, 7) // creates another CellConstraints object * ); * </pre> * * @param resourceKey the resource key for the label * @param labelConstraints the label's cell constraints * @param component the component to add * @param componentConstraints the component's cell constraints * @return the added label * * @throws IllegalArgumentException if the same cell constraints instance * is used for the label and the component * * @see JLabel#setLabelFor(java.awt.Component) * * @since 1.3 */ public final JLabel addI15dROLabel( String resourceKey, CellConstraints labelConstraints, Component component, CellConstraints componentConstraints) { JLabel label = addROLabel( getResourceString(resourceKey), labelConstraints, component, componentConstraints); if (isDebugToolTipsEnabled()) { label.setToolTipText(resourceKey); } return label; } // Adding Titled Separators *********************************************** /** * Adds an internationalized (i15d) titled separator to the form using the * specified constraints. * * @param resourceKey the resource key for the separator title * @param constraints the separator's cell constraints * @return the added titled separator */ public final JComponent addI15dSeparator(String resourceKey, CellConstraints constraints) { JComponent component = addSeparator(getResourceString(resourceKey), constraints); if (isDebugToolTipsEnabled()) { component.setToolTipText(resourceKey); } return component; } /** * Adds an internationalized (i15d) titled separator to the form using * the specified constraints. * * @param resourceKey the resource key for the separator title * @param encodedConstraints a string representation for the constraints * @return the added titled separator */ public final JComponent addI15dSeparator(String resourceKey, String encodedConstraints) { return addI15dSeparator(resourceKey, new CellConstraints(encodedConstraints)); } /** * Adds a title to the form using the specified constraints. * * @param resourceKey the resource key for the separator title * @param constraints the separator's cell constraints * @return the added title label */ public final JLabel addI15dTitle(String resourceKey, CellConstraints constraints) { JLabel label = addTitle(getResourceString(resourceKey), constraints); if (isDebugToolTipsEnabled()) { label.setToolTipText(resourceKey); } return label; } /** * Adds a title to the form using the specified constraints. * * @param resourceKey the resource key for the separator title * @param encodedConstraints a string representation for the constraints * @return the added title label */ public final JLabel addI15dTitle(String resourceKey, String encodedConstraints) { return addI15dTitle(resourceKey, new CellConstraints(encodedConstraints)); } // Helper Code ************************************************************ protected final boolean isDebugToolTipsEnabled() { return debugToolTipsEnabled; } /** * Looks up and returns the internationalized (i15d) string for the given * resource key, for example from a {@code ResourceBundle} or * {@code ResourceMap}. * * @param key the key to look for in the resource map * @return the associated internationalized string, or the resource key * itself in case of a missing resource * @throws IllegalStateException if the localization is not possible, * for example, because no ResourceBundle or StringLocalizer * has been set */ protected final String getResourceString(String key) { return StringResourceAccess.getResourceString(resources, key); } }
38.856275
100
0.643709
0a35792cae86234db530b86c64bba83155e649ca
779
package org.spoofax.jsglr2.stack; import org.metaborg.parsetable.states.IState; public abstract class AbstractStackNode<ParseForest, StackNode extends IStackNode> implements IStackNode { public final IState state; public AbstractStackNode(IState state) { this.state = state; } public IState state() { return state; } public abstract Iterable<StackLink<ParseForest, StackNode>> getLinks(); public abstract StackLink<ParseForest, StackNode> addLink(StackLink<ParseForest, StackNode> link); public StackLink<ParseForest, StackNode> addLink(StackNode parent, ParseForest parseNode) { StackLink<ParseForest, StackNode> link = new StackLink<>((StackNode) this, parent, parseNode); return addLink(link); } }
27.821429
106
0.727856
af06a50f2f174fe8a7114c59e32ece2889365ccc
3,484
/* * Copyright 2017 Huawei Technologies Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openo.sdnhub.overlayvpndriver.controller.model; import java.util.List; import java.util.Objects; import org.openo.sdno.overlayvpn.model.uuid.AbstUuidModel; import org.openo.sdno.overlayvpn.verify.annotation.AIp; import org.openo.sdno.overlayvpn.verify.annotation.AString; /** * Model converting class, converting SDNO model to adapter model. <br> * * @author * @version SDNHUB Driver 0.5 Jan 20, 2017 */ public class VxLanDeviceModel extends AbstUuidModel { /** * vne id. */ private int vneId; /** * vxlan tunnel name. */ @AString(require = true) private String name; /** * local address */ @AIp @AString(require = true) private String localAddress; /** * Collection of vni. */ private List<Vni> vniList; /** * @return Returns vne id. */ public int getVneId() { return vneId; } /** * @return vneId vne id. */ public void setVneId(int vneId) { this.vneId = vneId; } /** * @return Returns vxlan tunnel name. */ public String getName() { return name; } /** * @param name vxlan tunnel name. */ public void setName(String name) { this.name = name; } /** * @return Returns the local address. */ public String getLocalAddress() { return localAddress; } /** * @param localAddress local address. */ public void setLocalAddress(String localAddress) { this.localAddress = localAddress; } /** * @return Returns the collection of vni. */ public List<Vni> getVniList() { return vniList; } /** * @param vniList collection of vni. */ public void setVniList(List<Vni> vniList) { this.vniList = vniList; } /** * Override equals Function.<br> * * @param obj other Object * @return true if this object equals to other object * @since SDNO 0.5 */ @Override public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } VxLanDeviceModel other = (VxLanDeviceModel)obj; if (!Objects.equals(vneId, other.vneId)) { return false; } if (!Objects.equals(name, other.name)) { return false; } if (!Objects.equals(localAddress, other.localAddress)) { return false; } if (!vniList.equals(other.vniList)) { return false; } return true; } @Override public int hashCode() { return Objects.hash(vneId, name, localAddress, vniList); } }
20.738095
75
0.582377
83d2a5b011628fe1e1b708285957ed7052649473
3,492
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.theoryinpractice.testng.model; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.execution.configurations.ConfigurationUtil; import com.intellij.ide.util.ClassFilter; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.project.Project; import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiParameter; import com.intellij.psi.search.GlobalSearchScope; import com.theoryinpractice.testng.util.TestNGUtil; import java.util.Arrays; import java.util.List; /** * @author Hani Suleiman */ public class TestClassFilter implements ClassFilter.ClassFilterWithScope { private static final String GUICE = "org.testng.annotations.Guice"; private static final List<String> INJECTION_ANNOTATIONS = Arrays.asList("com.google.inject.Inject", "org.testng.annotations.Factory"); private final GlobalSearchScope scope; private final Project project; private final boolean includeConfig; private final boolean checkClassCanBeInstantiated; public TestClassFilter(GlobalSearchScope scope, Project project, boolean includeConfig) { this(scope, project, includeConfig, false); } public TestClassFilter(GlobalSearchScope scope, Project project, boolean includeConfig, boolean checkClassCanBeInstantiated) { this.scope = scope; this.project = project; this.includeConfig = includeConfig; this.checkClassCanBeInstantiated = checkClassCanBeInstantiated; } public TestClassFilter intersectionWith(GlobalSearchScope scope) { return new TestClassFilter(this.scope.intersectWith(scope), project, includeConfig, checkClassCanBeInstantiated); } public boolean isAccepted(final PsiClass psiClass) { return ReadAction.compute(() -> { if (!ConfigurationUtil.PUBLIC_INSTANTIATABLE_CLASS.value(psiClass)) return false; //PsiManager manager = PsiManager.getInstance(project); //if(manager.getEffectiveLanguageLevel().compareTo(LanguageLevel.JDK_1_5) < 0) return true; boolean hasTest = TestNGUtil.hasTest(psiClass); if (hasTest) { if (checkClassCanBeInstantiated) { final PsiMethod[] constructors = psiClass.getConstructors(); if (constructors.length > 0) { boolean canBeInstantiated = false; for (PsiMethod constructor : constructors) { PsiParameter[] parameters = constructor.getParameterList().getParameters(); if (parameters.length == 0 || AnnotationUtil.isAnnotated(constructor, INJECTION_ANNOTATIONS, AnnotationUtil.CHECK_HIERARCHY) || parameters.length == 1 && parameters[0].getType().equalsToText(CommonClassNames.JAVA_LANG_STRING)) { canBeInstantiated = true; break; } } if (!canBeInstantiated && !AnnotationUtil.isAnnotated(psiClass, GUICE, 0)) { return false; } } } return true; } return includeConfig && TestNGUtil.hasConfig(psiClass, TestNGUtil.CONFIG_ANNOTATIONS_FQN_NO_TEST_LEVEL); }); } public Project getProject() { return project; } public GlobalSearchScope getScope() { return scope; } }
39.681818
140
0.711913
76930e2309d849aa2e265c818b369973144593b0
8,235
/* * 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.solr.handler.dataimport; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.WeakHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * A set of nested maps that can resolve variables by namespaces. Variables are * enclosed with a dollar sign then an opening curly brace, ending with a * closing curly brace. Namespaces are delimited with '.' (period). * </p> * <p> * This class also has special logic to resolve evaluator calls by recognizing * the reserved function namespace: dataimporter.functions.xxx * </p> * <p> * This class caches strings that have already been resolved from the current * dih import. * </p> * <b>This API is experimental and may change in the future.</b> * * * @since solr 1.3 */ public class VariableResolver { private static final Pattern DOT_PATTERN = Pattern.compile("[.]"); private static final Pattern PLACEHOLDER_PATTERN = Pattern .compile("[$][{](.*?)[}]"); private static final Pattern EVALUATOR_FORMAT_PATTERN = Pattern .compile("^(\\w*?)\\((.*?)\\)$"); private Map<String,Object> rootNamespace; private Map<String,Evaluator> evaluators; private Map<String,Resolved> cache = new WeakHashMap<>(); class Resolved { List<Integer> startIndexes = new ArrayList<>(2); List<Integer> endOffsets = new ArrayList<>(2); List<String> variables = new ArrayList<>(2); } public static final String FUNCTIONS_NAMESPACE = "dataimporter.functions."; public static final String FUNCTIONS_NAMESPACE_SHORT = "dih.functions."; public VariableResolver() { rootNamespace = new HashMap<>(); } public VariableResolver(Properties defaults) { rootNamespace = new HashMap<>(); for (Map.Entry<Object,Object> entry : defaults.entrySet()) { rootNamespace.put(entry.getKey().toString(), entry.getValue()); } } public VariableResolver(Map<String,Object> defaults) { rootNamespace = new HashMap<>(defaults); } /** * Resolves a given value with a name * * @param name * the String to be resolved * @return an Object which is the result of evaluation of given name */ public Object resolve(String name) { Object r = null; if (name != null) { String[] nameParts = DOT_PATTERN.split(name); CurrentLevel cr = currentLevelMap(nameParts, rootNamespace, false); Map<String,Object> currentLevel = cr.map; r = currentLevel.get(nameParts[nameParts.length - 1]); if (r == null && name.startsWith(FUNCTIONS_NAMESPACE) && name.length() > FUNCTIONS_NAMESPACE.length()) { return resolveEvaluator(FUNCTIONS_NAMESPACE, name); } if (r == null && name.startsWith(FUNCTIONS_NAMESPACE_SHORT) && name.length() > FUNCTIONS_NAMESPACE_SHORT.length()) { return resolveEvaluator(FUNCTIONS_NAMESPACE_SHORT, name); } if (r == null) { StringBuilder sb = new StringBuilder(); for(int i=cr.level ; i<nameParts.length ; i++) { if(sb.length()>0) { sb.append("."); } sb.append(nameParts[i]); } r = cr.map.get(sb.toString()); } if (r == null) { r = System.getProperty(name); } } return r == null ? "" : r; } private Object resolveEvaluator(String namespace, String name) { if (evaluators == null) { return ""; } Matcher m = EVALUATOR_FORMAT_PATTERN.matcher(name .substring(namespace.length())); if (m.find()) { String fname = m.group(1); Evaluator evaluator = evaluators.get(fname); if (evaluator == null) return ""; ContextImpl ctx = new ContextImpl(null, this, null, null, null, null, null); String g2 = m.group(2); return evaluator.evaluate(g2, ctx); } else { return ""; } } /** * Given a String with place holders, replace them with the value tokens. * * @return the string with the placeholders replaced with their values */ public String replaceTokens(String template) { if (template == null) { return null; } Resolved r = getResolved(template); if (r.startIndexes != null) { StringBuilder sb = new StringBuilder(template); for (int i = r.startIndexes.size() - 1; i >= 0; i--) { String replacement = resolve(r.variables.get(i)).toString(); sb.replace(r.startIndexes.get(i), r.endOffsets.get(i), replacement); } return sb.toString(); } else { return template; } } private Resolved getResolved(String template) { Resolved r = cache.get(template); if (r == null) { r = new Resolved(); Matcher m = PLACEHOLDER_PATTERN.matcher(template); while (m.find()) { String variable = m.group(1); r.startIndexes.add(m.start(0)); r.endOffsets.add(m.end(0)); r.variables.add(variable); } cache.put(template, r); } return r; } /** * Get a list of variables embedded in the template string. */ public List<String> getVariables(String template) { Resolved r = getResolved(template); if (r == null) { return Collections.emptyList(); } return new ArrayList<>(r.variables); } public void addNamespace(String name, Map<String,Object> newMap) { if (newMap != null) { if (name != null) { String[] nameParts = DOT_PATTERN.split(name); Map<String,Object> nameResolveLevel = currentLevelMap(nameParts, rootNamespace, false).map; nameResolveLevel.put(nameParts[nameParts.length - 1], newMap); } else { for (Map.Entry<String,Object> entry : newMap.entrySet()) { String[] keyParts = DOT_PATTERN.split(entry.getKey()); Map<String,Object> currentLevel = rootNamespace; currentLevel = currentLevelMap(keyParts, currentLevel, false).map; currentLevel.put(keyParts[keyParts.length - 1], entry.getValue()); } } } } class CurrentLevel { final Map<String,Object> map; final int level; CurrentLevel(int level, Map<String,Object> map) { this.level = level; this.map = map; } } private CurrentLevel currentLevelMap(String[] keyParts, Map<String,Object> currentLevel, boolean includeLastLevel) { int j = includeLastLevel ? keyParts.length : keyParts.length - 1; for (int i = 0; i < j; i++) { Object o = currentLevel.get(keyParts[i]); if (o == null) { if(i == j-1) { Map<String,Object> nextLevel = new HashMap<>(); currentLevel.put(keyParts[i], nextLevel); currentLevel = nextLevel; } else { return new CurrentLevel(i, currentLevel); } } else if (o instanceof Map<?,?>) { @SuppressWarnings("unchecked") Map<String,Object> nextLevel = (Map<String,Object>) o; currentLevel = nextLevel; } else { throw new AssertionError( "Non-leaf nodes should be of type java.util.Map"); } } return new CurrentLevel(j-1, currentLevel); } public void removeNamespace(String name) { rootNamespace.remove(name); } public void setEvaluators(Map<String,Evaluator> evaluators) { this.evaluators = evaluators; } }
32.94
79
0.639951
398e2fbf562d9eeab9f63edbfa5e50aee3654f82
1,085
package org.jtmc.core.signal.digital.sampler; import org.jtmc.core.signal.Signal; import org.jtmc.core.signal.Signal.DataPoint; import org.jtmc.core.signal.digital.BinarySignal; import org.jtmc.core.signal.sampler.Sampler; /** * Threshold converts an analog signal to a binary signal using the given * threshold. */ public class Threshold implements Sampler<Float, BinarySignal> { private float threshold; /** * Constructs a Threshold sampler with the given threshold, values * below it will be interpreted as 0, otherwise will be 1's. * * @param threshold Threshold */ public Threshold(float threshold) { this.threshold = threshold; } @Override public BinarySignal sample(Signal<Float> signal) { BinarySignal output = new BinarySignal(signal.getId()); boolean state = !(signal.first() > threshold); for (DataPoint<Float> point : signal.getData()) { boolean current = point.value > threshold; if (current != state) { output.add(point.time, current); state = current; } } return null; } }
26.463415
73
0.694009
35587589ef2022a4ee3edf3b8ad3e5ab4f32a173
2,869
package com.myezopen.myezopen.adapter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.provider.MediaStore; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.myezopen.myezopen.R; import com.myezopen.myezopen.Utils.DataUtils; import com.squareup.picasso.Picasso; import java.io.File; import java.util.List; public class ImageRecyclerAdapter extends RecyclerView.Adapter<ImageRecyclerAdapter.ImageHolder> { private List<String> dataList; private Context context; private LayoutInflater inflater; private OnRecyclerItemClickListener itemClickListener; public ImageRecyclerAdapter(Context context,List<String> dataList ) { this.dataList = dataList; this.context = context; inflater = LayoutInflater.from(context); } @Override public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ImageHolder(inflater.inflate(R.layout.item_image,parent,false),itemClickListener); } @Override public void onBindViewHolder(ImageHolder holder, int position) { String FileEnd = dataList.get(position).substring(dataList.get(position).lastIndexOf(".") + 1, dataList.get(position).length()).toLowerCase(); if (FileEnd.equals("mp4")){ Bitmap bitmap = DataUtils.getVideoThumbnail(dataList.get(position),350,200, MediaStore.Video.Thumbnails.MINI_KIND); holder.image.setImageBitmap(bitmap); holder.imgPlay.setVisibility(View.VISIBLE); }else { Picasso.with(context).load(new File(dataList.get(position))).resize(350,200).centerCrop().into(holder.image); } } public void setItemClickListener(OnRecyclerItemClickListener itemClickListener) { this.itemClickListener = itemClickListener; } @Override public int getItemCount() { return dataList.size(); } public static class ImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ private ImageView image; private ImageView imgPlay; private OnRecyclerItemClickListener itemClickListener; public ImageHolder(View itemView, OnRecyclerItemClickListener itemClickListener) { super(itemView); this.itemClickListener = itemClickListener; itemView.setOnClickListener(this); image = (ImageView) itemView.findViewById(R.id.image); imgPlay = (ImageView) itemView.findViewById(R.id.VideoFlag); } @Override public void onClick(View view) { if(itemClickListener == null) return; itemClickListener.click(itemView,getAdapterPosition()); } } }
37.75
150
0.719763
08c7648e4c6d77d088fe2fa0c9d7e763921b44a5
2,571
package com.github.puhiayang.handler.proxy; import com.github.puhiayang.bean.ClientRequest; import com.github.puhiayang.handler.response.SocksResponseHandler; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.util.Attribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.github.puhiayang.bean.Constans.CLIENTREQUEST_ATTRIBUTE_KEY; /** * socks的代理handler * * @author puhaiyang * created on 2019/10/25 20:56 */ public class SocksProxyHandler extends ChannelInboundHandlerAdapter implements IProxyHandler { private Logger logger = LoggerFactory.getLogger(HttpsProxyHandler.class); private ChannelFuture notHttpReuqstCf; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("[SocksProxyHandler]"); Attribute<ClientRequest> clientRequestAttribute = ctx.channel().attr(CLIENTREQUEST_ATTRIBUTE_KEY); ClientRequest clientRequest = clientRequestAttribute.get(); sendToServer(clientRequest, ctx, msg); } @Override public void sendToServer(ClientRequest clientRequest, ChannelHandlerContext ctx, Object msg) { //不是http请求就不管,全转发出去 if (notHttpReuqstCf == null) { //连接至目标服务器 Bootstrap bootstrap = new Bootstrap(); bootstrap.group(ctx.channel().eventLoop()) // 复用客户端连接线程池 .channel(ctx.channel().getClass()) // 使用NioSocketChannel来作为连接用的channel类 .handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new SocksResponseHandler(ctx.channel())); } }); notHttpReuqstCf = bootstrap.connect(clientRequest.getHost(), clientRequest.getPort()); notHttpReuqstCf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().writeAndFlush(msg); } else { ctx.channel().close(); } } }); } else { notHttpReuqstCf.channel().writeAndFlush(msg); } } @Override public void sendToClient(ClientRequest clientRequest, ChannelHandlerContext ctx, Object msg) { } }
37.26087
106
0.630883
caf4ceef20629154ec31c4e270b8e849cf3c3ba9
38,276
package exm.stc.ic.refcount; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.log4j.Logger; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import exm.stc.common.CompilerBackend.RefCount; import exm.stc.common.Logging; import exm.stc.common.exceptions.STCRuntimeError; import exm.stc.common.lang.Arg; import exm.stc.common.lang.FnID; import exm.stc.common.lang.PassedVar; import exm.stc.common.lang.RefCounting; import exm.stc.common.lang.RefCounting.RefCountType; import exm.stc.common.lang.Var; import exm.stc.common.lang.Var.Alloc; import exm.stc.common.lang.Var.VarCount; import exm.stc.common.util.Counters; import exm.stc.common.util.Pair; import exm.stc.common.util.Sets; import exm.stc.ic.aliases.AliasKey; import exm.stc.ic.opt.OptUtil; import exm.stc.ic.opt.TreeWalk; import exm.stc.ic.opt.TreeWalk.TreeWalker; import exm.stc.ic.refcount.RCTracker.RefCountCandidates; import exm.stc.ic.tree.Conditionals.Conditional; import exm.stc.ic.tree.ForeachLoops.AbstractForeachLoop; import exm.stc.ic.tree.ICContinuations.Continuation; import exm.stc.ic.tree.ICInstructions.Instruction; import exm.stc.ic.tree.ICTree.Block; import exm.stc.ic.tree.ICTree.BlockType; import exm.stc.ic.tree.ICTree.Function; import exm.stc.ic.tree.ICTree.GlobalVars; import exm.stc.ic.tree.ICTree.Statement; import exm.stc.ic.tree.ICTree.StatementType; import exm.stc.ic.tree.TurbineOp.RefCountOp; import exm.stc.ic.tree.TurbineOp.RefCountOp.RCDir; /** * Functions to insert reference count operations in IC tree. There are a number * of different strategies for actually inserting the reference counts, which * are all implemented in this module. For example, we can insert explicit * reference count instructions, or we can do tricky things like piggybacking * them on other operations, or canceling them out. * * * TODO: Merge together refcounts to place - e.g. read/write same var, * or two vars if they happen to alias same refcounted var */ public class RCPlacer { private final Logger logger = Logging.getSTCLogger(); private final Map<FnID, Function> functionMap; public RCPlacer(Map<FnID, Function> functionMap) { this.functionMap = functionMap; } public void placeAll(Logger logger, GlobalVars globals, Function fn, Block block, RCTracker increments, Set<Var> parentAssignedAliasVars) { for (RefCountType rcType: RefcountPass.RC_TYPES) { preprocessIncrements(increments, rcType); if (logger.isTraceEnabled()) { logger.trace("After preprocessing: \n" + increments); } // Cancel out increments and decrements cancelIncrements(logger, fn, block, increments, rcType); // Add decrements to block placeDecrements(logger, globals, fn, block, increments, rcType); // Add any remaining increments placeIncrements(globals, fn, block, increments, rcType, parentAssignedAliasVars); // Verify we didn't miss any RCUtil.checkRCZero(block, increments, rcType, true, true); } } /** * Do preprocessing of increments to get ready for placement. * This entails taking all increments/decrements for keys that aren't * the datum roots and moving the refcount to the datum root var key. * This simplifies the remainder of the pass. * @param increments * @param rcType */ private void preprocessIncrements(RCTracker increments, RefCountType rcType) { for (RCDir dir: RCDir.values()) { Iterator<Entry<AliasKey, Long>> it = increments.rcIter(rcType, dir).iterator(); List<Pair<Var, Long>> newRCs = new ArrayList<Pair<Var, Long>>(); // Remove all refcounts while (it.hasNext()) { Entry<AliasKey, Long> e = it.next(); Var rcVar = increments.getRefCountVar(e.getKey()); if (logger.isTraceEnabled()) { logger.trace(rcVar + " is refcount var for key " + e.getKey()); } newRCs.add(Pair.create(rcVar, e.getValue())); it.remove(); } // Add them back in with updated key for (Pair<Var, Long> newRC: newRCs) { increments.incr(newRC.val1, rcType, newRC.val2); } } } /** * Add decrement operations to block, performing optimized placement * where possible * @param logger * @param fn * @param block * @param increments * @param type */ private void placeDecrements(Logger logger, GlobalVars globals, Function fn, Block block, RCTracker increments, RefCountType type) { // First try to piggyback on variable declarations piggybackDecrementsOnDeclarations(logger, globals, fn, block, increments, type); // Then see if we can do the decrement on top of another operation piggybackOnStatements(logger, fn, block, increments, RCDir.DECR, type); if (block.getType() != BlockType.MAIN_BLOCK && RCUtil.isForeachLoop(block.getParentCont())) { // Add remaining decrements to foreach loop where they can be batched batchDecrementsForeach(block, increments, type); } // Add remaining decrements as cleanups at end of block addDecrementsAsCleanups(block, increments, type); } /** * Add reference increments at head of block * * @param fn * @param block * @param increments * @param rcType * @param parentAssignedAliasVars * assign alias vars from parent blocks that we can immediately * manipulate refcount of */ private void placeIncrements(GlobalVars globals, Function fn, Block block, RCTracker increments, RefCountType rcType, Set<Var> parentAssignedAliasVars) { // First try to piggy-back onto var declarations piggybackIncrementsOnDeclarations(globals, fn, block, increments, rcType); // Then see if we can do the increment on top of another operation piggybackOnStatements(logger, fn, block, increments, RCDir.INCR, rcType); // If we can't piggyback, put them at top of block before any tasks are // spawned addIncrementsAtTop(block, increments, rcType, parentAssignedAliasVars); } public void dumpDecrements(Block block, RCTracker increments) { // TODO: can we guarantee that the refcount var is available in the // current scope? for (RefCountType rcType: RefcountPass.RC_TYPES) { for (Entry<AliasKey, Long> e: increments.rcIter(rcType, RCDir.DECR)) { assert (e.getValue() <= 0); Var var = increments.getRefCountVar(e.getKey()); if (RefCounting.trackRefCount(var, rcType)) { Arg amount = Arg.newInt(e.getValue() * -1); block.addCleanup(var, RefCountOp.decrRef(rcType, var, amount)); } } } // Clear out all decrements increments.resetAll(RCDir.DECR); } /** * Insert all reference increments and decrements in place * * @param stmt the statement to insert before or after * null indicates end of the block * @param stmtIt * @param increments */ public void dumpIncrements(Statement stmt, Block block, ListIterator<Statement> stmtIt, RCTracker increments) { for (RefCountType rcType: RefcountPass.RC_TYPES) { for (Entry<AliasKey, Long> e: increments.rcIter(rcType, RCDir.INCR)) { // TODO: can we guarantee that the refcount var is available in the // current scope? Var var = increments.getRefCountVar(e.getKey()); assert(var != null); Long incr = e.getValue(); assert(incr >= 0); if (incr > 0 && RefCounting.trackRefCount(var, rcType)) { boolean varInit = stmt != null && stmt.type() == StatementType.INSTRUCTION && stmt.instruction().isInitialized(var); // TODO: what if not initialized in a conditional? Should insert before if (stmt != null && (stmt.type() == StatementType.INSTRUCTION && !(var.storage() == Alloc.ALIAS && varInit))) { insertIncrBefore(block, stmtIt, var, incr, rcType); } else { insertIncrAfter(block, stmtIt, var, incr, rcType); } } } } // Clear out all increments increments.resetAll(RCDir.INCR); } /** * Cancel out increments and decrements. We need to validate some * conditions to be sure that it's valid. In particular, we need * to make sure that there isn't a "trailing" read/write of a variable * that occurs after a reference count has been consumed by an instruction. * @param logger * @param fn * @param block * @param tracker * @param rcType */ private void cancelIncrements(Logger logger, Function fn, Block block, RCTracker tracker, RefCountType rcType) { if (!RCUtil.cancelEnabled()) { return; } // Set of keys that we might be able to cancel // Use var instead of key since we can now deal with concrete vars Set<Var> cancelCandidates = new HashSet<Var>(); // TODO: inelegant // Need to track which vars are associated with each refcount var ListMultimap<Var, AliasKey> rcVarToKey = ArrayListMultimap.create(); for (Entry<AliasKey, Long> e: tracker.rcIter(rcType, RCDir.DECR)) { long decr = e.getValue(); AliasKey key = e.getKey(); long incr = tracker.getCount(rcType, key, RCDir.INCR); assert(decr <= 0); assert(incr >= 0); if (incr != 0 && decr != 0) { Var rcVar = tracker.getRefCountVar(key); cancelCandidates.add(rcVar); rcVarToKey.put(rcVar, key); } } if (logger.isTraceEnabled()) { logger.trace("Cancel candidates " + rcType + ": " + cancelCandidates); } /* * Scan backwards up block to find out if we need to hold onto refcount * past point where it is consumed. */ // Set of variables where refcount was consumed by statement/continuation // after current position Set<Var> consumedAfter = new HashSet<Var>(); // Check that the data isn't actually used in block or sync continuations UseFinder useFinder = new UseFinder(tracker, rcType, cancelCandidates); ListIterator<Continuation> cit = block.continuationEndIterator(); while (cit.hasPrevious()) { Continuation cont = cit.previous(); useFinder.reset(); TreeWalk.walkSyncChildren(logger, fn, cont, useFinder); updateCancelCont(tracker, cont, useFinder.getUsedVars(), rcType, cancelCandidates, consumedAfter); } ListIterator<Statement> it = block.statementEndIterator(); while (it.hasPrevious()) { Statement stmt = it.previous(); if (stmt.type() == StatementType.INSTRUCTION) { Instruction inst = stmt.instruction(); updateCancel(tracker, inst, rcType, cancelCandidates, consumedAfter); } else { assert(stmt.type() == StatementType.CONDITIONAL); Conditional cond = stmt.conditional(); useFinder.reset(); TreeWalk.walkSyncChildren(logger, fn, cond, useFinder); updateCancelCont(tracker, cond, useFinder.getUsedVars(), rcType, cancelCandidates, consumedAfter); } } for (Var toCancel: cancelCandidates) { // Simple approach to cancelling: if we are totally free to // cancel, cancel as much as possible long incr = 0; long decr = 0; // Account for fact we may have multiple vars for key List<AliasKey> matchingKeys = rcVarToKey.get(toCancel); assert(!matchingKeys.isEmpty()); for (AliasKey key: matchingKeys) { incr += tracker.getCount(rcType, key, RCDir.INCR); decr += tracker.getCount(rcType, key, RCDir.DECR); } long cancelAmount = Math.min(incr, Math.abs(decr)); if (logger.isTraceEnabled()) { logger.trace("Cancel " + toCancel.toString() + " " + cancelAmount); } // cancel out increment and decrement tracker.cancel(toCancel, rcType, cancelAmount); tracker.cancel(toCancel, rcType, -cancelAmount); } } /** * Maintain list of cancel candidates based on what instruction does * @param tracker * @param inst * @param rcType * @param cancelCandidates * @param consumedAfter */ private void updateCancel(RCTracker tracker, Instruction inst, RefCountType rcType, Set<Var> cancelCandidates, Set<Var> consumedAfter) { List<VarCount> consumedVars; if (rcType == RefCountType.READERS) { consumedVars = inst.inRefCounts(functionMap).val1; } else { assert (rcType == RefCountType.WRITERS); consumedVars = inst.inRefCounts(functionMap).val2; } Set<Var> consumed = new HashSet<Var>(); for (VarCount v: consumedVars) { if (v.count != 0) { consumed.add(tracker.getRefCountVar(v.var)); } } if (logger.isTraceEnabled()) { logger.trace(inst + " | " + rcType + " consumed " + consumed); } if (rcType == RefCountType.READERS) { for (Arg in: inst.getInputs()) { if (in.isVar()) { Var inRCVar = tracker.getRefCountVar(in.getVar()); updateCancel(inRCVar, cancelCandidates, consumedAfter, true, consumed.contains(inRCVar)); } } for (Var read: inst.getReadOutputs(functionMap)) { Var readRCVar = tracker.getRefCountVar(read); updateCancel(readRCVar, cancelCandidates, consumedAfter, true, consumed.contains(readRCVar)); } } else { assert (rcType == RefCountType.WRITERS); for (Var modified: inst.getOutputs()) { Var modifiedRCVar = tracker.getRefCountVar(modified); updateCancel(modifiedRCVar, cancelCandidates, consumedAfter, true, consumed.contains(modifiedRCVar)); } } // Update with any remaining consumptions. Note that it doesn't // matter if we update consumption after use, but the other way // doesn't work for (Var consumedVar: consumed) { if (cancelCandidates.contains(consumedVar)) { Var consumedRCVar = tracker.getRefCountVar(consumedVar); updateCancel(consumedRCVar, cancelCandidates, consumedAfter, false, true); } } } private void updateCancelCont(RCTracker tracker, Continuation cont, List<Var> usedRCVars, RefCountType rcType, Set<Var> cancelCandidates, Set<Var> consumedAfter) { List<Var> consumedRCVars; if (!cont.isAsync()) { consumedRCVars = Collections.emptyList(); } else { if (rcType == RefCountType.READERS) { Collection<PassedVar> passed = cont.getPassedVars(); if (passed.isEmpty()) { consumedRCVars = Collections.emptyList(); } else { consumedRCVars = new ArrayList<Var>(passed.size()); for (PassedVar pv: passed) { consumedRCVars.add(tracker.getRefCountVar(pv.var)); } } } else { assert(rcType == RefCountType.WRITERS); Collection<Var> keepOpen = cont.getKeepOpenVars(); if (keepOpen.isEmpty()) { consumedRCVars = Collections.emptyList(); } else { consumedRCVars = new ArrayList<Var>(keepOpen.size()); for (Var v: keepOpen) { consumedRCVars.add(tracker.getRefCountVar(v)); } } } } for (Var usedRCVar: usedRCVars) { updateCancel(usedRCVar, cancelCandidates, consumedAfter, true, consumedRCVars.contains(usedRCVar)); } for (Var consumedRCVar: consumedRCVars) { updateCancel(consumedRCVar, cancelCandidates, consumedAfter, false, true); } } private void updateCancel(Var var, Set<Var> cancelCandidates, Set<Var> consumedAfter, boolean usedHere, boolean consumedHere) { if (logger.isTraceEnabled()) { logger.trace("updateCancel " + var + " usedHere: " + usedHere + " consumedHere: " + consumedHere); } if (consumedHere) { // For instructions that just consume a refcount, don't need to do // anything, just mark that it was consumed consumedAfter.add(var); return; } if (usedHere) { if (consumedAfter.contains(var)) { // We hold onto a refcount until later in block - ok return; } else { // The refcount is consumed by a prior instruction: can't safely // cancel cancelCandidates.remove(var); } } } /** * Try to piggyback reference decrements onto var declarations, for example if * a var is never read or written * * @param block * @param tracker * updated to reflect changes * @param abstractType */ private void piggybackDecrementsOnDeclarations(Logger logger, GlobalVars globals, Function fn, Block block, RCTracker tracker, RefCountType rcType) { if (!RCUtil.piggybackEnabled() || !RCUtil.cancelEnabled()) { // Don't support if no cancelling - can lead to double piggyback return; } final Set<Var> immDecrCandidates = Sets.createSet( block.variables().size()); for (Var blockVar : block.variables()) { if (blockVar.storage() != Alloc.ALIAS) { // NOTE: this block var will be it's own root since // it's allocated here assert(tracker.getRefCountVar(blockVar).equals(blockVar)) : blockVar; long incr = tracker.getCount(rcType, blockVar, RCDir.DECR); assert(incr <= 0); long baseRC = RefCounting.baseRefCount(blockVar, rcType, true, false); // -baseCount may correspond to the case when the value of the var is // thrown away, or where the var is never written. The exception is // if an instruction reads/writes the var without modifying the // refcount, // in which case we can't move the decrement to the front of the block // Shouldn't be less than this when var is declared in this // block. assert (incr >= -baseRC) : blockVar + " " + rcType + ": " + incr + " < base " + baseRC; if (incr < 0) { immDecrCandidates.add(blockVar); } } } // Check that the data isn't actually used in block or sync continuations // In the case of async continuations, there should be an increment to // pass the var UseFinder useFinder = new UseFinder(tracker, rcType, immDecrCandidates); useFinder.reset(); TreeWalk.walkSyncChildren(logger, fn, block, true, useFinder); immDecrCandidates.removeAll(useFinder.getUsedVars()); for (Var immDecrVar: immDecrCandidates) { assert(immDecrVar.storage() != Alloc.ALIAS) : immDecrVar; long incr = tracker.getCount(rcType, immDecrVar, RCDir.DECR); piggybackDecrement(globals, fn, block, tracker, rcType, immDecrVar, incr); } } private void piggybackDecrement(GlobalVars globals, Function fn, Block block, final RCTracker tracker, final RefCountType rcType, Var var, long incr) { assert(incr <= 0) : var + " " + incr; if (incr < 0) { if (var.storage() == Alloc.GLOBAL_VAR) { if (OptUtil.isEntryBlock(fn, block)) { globals.modifyInitRefcount(var, rcType, incr); tracker.cancel(var, rcType, -incr); } } else { block.modifyInitRefcount(var, rcType, incr); tracker.cancel(var, rcType, -incr); } } } /** * Try to piggyback decrement operations on instructions or continuations * in block * * @param logger * @param fn * @param block * @param tracker * @param rcType */ private void piggybackOnStatements(Logger logger, Function fn, Block block, RCTracker tracker, RCDir dir, RefCountType rcType) { if (!RCUtil.piggybackEnabled()) { return; } // Initially all decrements are candidates for piggybacking RefCountCandidates candidates = tracker.getVarCandidates(block, rcType, dir); if (logger.isTraceEnabled()) { logger.trace("Piggyback candidates: " + candidates); } UseFinder subblockWalker = new UseFinder(tracker, rcType, candidates.varKeySet()); // Depending on whether it's a decrement or an increment, we need // to traverse statements in a different direciton so that refcounts // can be disqualified in the right order boolean reverse = (dir == RCDir.DECR); if (reverse) { piggybackOnContinuations(logger, fn, block, tracker, dir, rcType, candidates, subblockWalker, reverse); } piggybackOnStatements(logger, fn, block, tracker, dir, rcType, candidates, subblockWalker, reverse); if (!reverse) { piggybackOnContinuations(logger, fn, block, tracker, dir, rcType, candidates, subblockWalker, reverse); } } private void piggybackOnStatements(Logger logger, Function fn, Block block, RCTracker tracker, RCDir dir, RefCountType rcType, RefCountCandidates candidates, UseFinder subblockWalker, boolean reverse) { // Vars where we were successful List<VarCount> successful = new ArrayList<VarCount>(); // scan up from bottom of block instructions to see if we can piggyback ListIterator<Statement> it = reverse ? block.statementEndIterator() : block.statementIterator(); while ((reverse && it.hasPrevious()) || (!reverse && it.hasNext())) { Statement stmt; if (reverse) { stmt = it.previous(); } else { stmt = it.next(); } switch (stmt.type()) { case INSTRUCTION: { Instruction inst = stmt.instruction(); if (logger.isTraceEnabled()) { logger.trace("Try piggyback " + dir + " on " + inst); } VarCount piggybacked; do { /* Process one at a time so that candidates is correctly updated * for each call based on previous changes */ piggybacked = inst.tryPiggyback(candidates, rcType); if (piggybacked != null && piggybacked.count != 0) { if (logger.isTraceEnabled()) { logger.trace("Piggybacked decr " + piggybacked + " on " + inst); } candidates.add(piggybacked.var, -piggybacked.count); successful.add(piggybacked); } } while (piggybacked != null && piggybacked.count != 0); // Make sure we don't modify before a use of the var by removing // from candidate set List<Var> used = findUses(inst, tracker, rcType, candidates.varKeySet()); removeCandidates(used, tracker, candidates); break; } case CONDITIONAL: // Walk continuation to find usages subblockWalker.reset(); TreeWalk.walkSyncChildren(logger, fn, stmt.conditional(), subblockWalker); removeCandidates(subblockWalker.getUsedVars(), tracker, candidates); break; default: throw new STCRuntimeError("Unknown statement type " + stmt.type()); } } if (logger.isTraceEnabled()) { logger.trace(successful); } // Update main increments map for (VarCount vc: successful) { assert(vc != null); tracker.cancel(tracker.getRefCountVar(vc.var), rcType, -vc.count); } } private void piggybackOnContinuations(Logger logger, Function fn, Block block, RCTracker tracker, RCDir dir, RefCountType rcType, RefCountCandidates candidates, UseFinder subblockWalker, boolean reverse) { // Try to piggyback on continuations, starting at bottom up ListIterator<Continuation> cit = reverse ? block.continuationEndIterator() : block.continuationIterator(); while ((reverse && cit.hasPrevious()) || (!reverse && cit.hasNext())) { Continuation cont; if (reverse) { cont = cit.previous(); } else { cont = cit.next(); } if (RCUtil.isAsyncForeachLoop(cont)) { AbstractForeachLoop loop = (AbstractForeachLoop) cont; VarCount piggybacked; do { /* Process one at a time so that candidates is correctly updated * for each call based on previous changes */ piggybacked = loop.tryPiggyBack(candidates, rcType, dir); if (piggybacked != null) { if (logger.isTraceEnabled()) { logger.trace("Piggybacked on foreach: " + piggybacked + " " + rcType + " " + piggybacked.count); } candidates.add(piggybacked.var, -piggybacked.count); tracker.cancel(tracker.getRefCountVar(piggybacked.var), rcType, -piggybacked.count); } } while (piggybacked != null); } // Walk continuation to find usages subblockWalker.reset(); TreeWalk.walkSyncChildren(logger, fn, cont, subblockWalker); removeCandidates(subblockWalker.getUsedVars(), tracker, candidates); } } /** * Find uses of refcounted variables in continuations. * Note that we only count root variables i.e. returned by getRefcountVar() * in RCTracker */ private final class UseFinder extends TreeWalker { private final RCTracker tracker; private final RefCountType rcType; private final Set<Var> varCandidates; /** * List into which usages are accumulated. Must * be reset by caller */ private final ArrayList<Var> varAccum; private UseFinder(RCTracker tracker, RefCountType rcType, Set<Var> varCandidates) { this.tracker = tracker; this.rcType = rcType; this.varCandidates = varCandidates; this.varAccum = new ArrayList<Var>(); } public void reset() { this.varAccum.clear(); } @Override public void visit(Continuation cont) { findUsesNonRec(cont, tracker, rcType, varCandidates, varAccum); } @Override public void visit(Instruction inst) { findUses(inst, tracker, rcType, varCandidates, varAccum); } public List<Var> getUsedVars() { return varAccum; } } private List<Var> findUses(Instruction inst, RCTracker tracker, RefCountType rcType, Set<Var> candidates) { ArrayList<Var> res = new ArrayList<Var>(); findUses(inst, tracker, rcType, candidates, res); return res; } /** * * @param inst * @param tracker required if keyCandidates != null * @param rcType * @param varCandidates * @param keyCandidates * @param varAccum required if varCandidates != null * @param keyAccum required if keyCandidates != null */ private void findUses(Instruction inst, RCTracker tracker, RefCountType rcType, Set<Var> varCandidates, List<Var> varAccum) { if (rcType == RefCountType.READERS) { for (Arg in : inst.getInputs()) { if (in.isVar()) { updateUses(in.getVar(), tracker, varCandidates, varAccum); } } for (Var read : inst.getReadOutputs(functionMap)) { updateUses(read, tracker, varCandidates, varAccum); } } else { assert (rcType == RefCountType.WRITERS); for (Var modified : inst.getOutputs()) { updateUses(modified, tracker, varCandidates, varAccum); } } } private void findUsesNonRec(Continuation cont, RCTracker tracker, RefCountType rcType, Set<Var> varCandidates, ArrayList<Var> varAccum) { if (rcType == RefCountType.READERS) { for (Var v: cont.requiredVars(false)) { updateUses(v, tracker, varCandidates, varAccum); } if (cont.isAsync() && rcType == RefCountType.READERS) { for (PassedVar pv: cont.getPassedVars()) { if (!pv.writeOnly) { updateUses(pv.var, tracker, varCandidates, varAccum); } } } else if (cont.isAsync() && rcType == RefCountType.WRITERS) { for (Var v: cont.getKeepOpenVars()) { updateUses(v, tracker, varCandidates, varAccum); } } } // Foreach loops have increments attached to them, // can't prematurely decrement if (RCUtil.isForeachLoop(cont)) { AbstractForeachLoop loop = (AbstractForeachLoop) cont; for (RefCount rc: loop.getStartIncrements()) { if (rc.type == rcType) { updateUses(rc.var, tracker, varCandidates, varAccum); } } } } private void updateUses(Var v, RCTracker tracker, Set<Var> varCandidates, List<Var> varAccum) { if (varCandidates != null && varCandidates.contains(v)) { varAccum.add(tracker.getRefCountVar(v)); } } private void removeCandidates(Collection<Var> vars, RCTracker tracker, RefCountCandidates candidates) { for (Var key: vars) { if (logger.isTraceEnabled()) { logger.trace("Remove candidate " + key); } candidates.reset(key); } } /** * Foreach loops have different method for handling decrements: we add them to * the parent continuation * * @param block * @param increments * @param rcType */ private void batchDecrementsForeach(Block block, RCTracker increments, RefCountType rcType) { if (!RCUtil.batchEnabled()) { return; } assert (block.getType() != BlockType.MAIN_BLOCK); Continuation parent = block.getParentCont(); AbstractForeachLoop loop = (AbstractForeachLoop) parent; Counters<Var> changes = new Counters<Var>(); for (Entry<AliasKey, Long> e : increments.rcIter(rcType, RCDir.DECR)) { Var var = increments.getRefCountVar(e.getKey()); if (RefCounting.trackRefCount(var, rcType)) { long count = e.getValue(); assert(count <= 0); if (count < 0 && RCUtil.definedOutsideCont(loop, block, var)) { // Decrement vars defined outside block long amount = count * -1; Arg amountArg = Arg.newInt(amount); loop.addEndDecrement(new RefCount(var, rcType, amountArg)); changes.add(var, amount); Logging.getSTCLogger().trace("Piggyback " + var + " " + rcType + " " + amount + " on foreach"); } } } // Build and merge to avoid concurrent modification problems increments.merge(changes, rcType, RCDir.DECR); } private void addDecrementsAsCleanups(Block block, RCTracker increments, RefCountType rcType) { Counters<Var> changes = new Counters<Var>(); for (Entry<AliasKey, Long> e : increments.rcIter(rcType, RCDir.DECR)) { Var var = increments.getRefCountVar(e.getKey()); if (RefCounting.trackRefCount(var, rcType)) { long count = e.getValue(); assert(count <= 0); addDecrement(block, changes, rcType, var, count); } } // Build and merge to avoid concurrent modification problems increments.merge(changes, rcType, RCDir.DECR); } private void addDecrement(Block block, Counters<Var> increments, RefCountType type, Var var, long count) { if (count < 0) { assert (RefCounting.trackRefCount(var, type)); Arg amount = Arg.newInt(count * -1); block.addCleanup(var, RefCountOp.decrRef(type, var, amount)); increments.add(var, amount.getInt()); if (logger.isTraceEnabled()) { logger.trace("Add " + var.name() + " " + type + " " + count + " as cleanup"); } } } private void insertIncr(Block block, ListIterator<Statement> stmtIt, Var var, Long val, RefCountType type, boolean before) { assert(val >= 0); if (val == 0) return; if (before) stmtIt.previous(); Instruction inst; Arg amount = Arg.newInt(val); inst = RefCountOp.incrRef(type, var, amount); inst.setParent(block); stmtIt.add(inst); if (before) stmtIt.next(); } private void insertIncrBefore(Block block, ListIterator<Statement> stmtIt, Var var, Long val, RefCountType type) { insertIncr(block, stmtIt, var, val, type, true); } private void insertIncrAfter(Block block, ListIterator<Statement> stmtIt, Var var, Long val, RefCountType type) { insertIncr(block, stmtIt, var, val, type, false); } private void addIncrementsAtTop(Block block, RCTracker increments, RefCountType rcType, Set<Var> parentAssignedAliasVars) { if (logger.isTraceEnabled()) { logger.trace("Leftover increments to add at top:"); logger.trace("=============================="); logger.trace(increments); } // Next try to just put at top of block Iterator<Entry<AliasKey, Long>> it = increments.rcIter(rcType, RCDir.INCR).iterator(); while (it.hasNext()) { Entry<AliasKey, Long> e = it.next(); Var var = increments.getRefCountVar(e.getKey()); if (RefCounting.trackRefCount(var, rcType)) { long count = e.getValue(); if (var.storage() != Alloc.ALIAS || parentAssignedAliasVars.contains(var)) { // add increments that we can at top addRefIncrementAtTop(block, rcType, var, count); it.remove(); } } } // Now put increments for alias vars after point when var declared ListIterator<Statement> stmtIt = block.statementIterator(); while (stmtIt.hasNext()) { Statement stmt = stmtIt.next(); if (logger.isTraceEnabled()) { for (Entry<AliasKey, Long> e: increments.rcIter(rcType, RCDir.INCR)) { logger.trace("Try to place: " + e.getKey() + " at " + stmt); } } switch (stmt.type()) { case INSTRUCTION: { for (Var init: stmt.instruction().getInitialized()) { if (init.storage() == Alloc.ALIAS) { addIncrForVar(block, increments, rcType, stmtIt, init); } } break; } case CONDITIONAL: { for (Var initAlias: findConditionalInitAliases(stmt.conditional())) { addIncrForVar(block, increments, rcType, stmtIt, initAlias); } break; } default: throw new STCRuntimeError("Unknown statement type " + stmt.type()); } } } /** * Find any alias variables that are initialized on * all branches of the continuation * @param cond * @return */ private Set<Var> findConditionalInitAliases(Conditional cond) { Set<Var> initAllBranches; if (cond.isExhaustiveSyncConditional()) { List<Set<Var>> branchesInit = new ArrayList<Set<Var>>(); for (Block b: cond.getBlocks()) { branchesInit.add(findBlockInitAliases(b)); } initAllBranches = Sets.intersection(branchesInit); } else { initAllBranches = Collections.emptySet(); } return initAllBranches; } private Set<Var> findBlockInitAliases(Block block) { HashSet<Var> result = new HashSet<Var>(); for (Statement stmt: block.getStatements()) { if (stmt.type() == StatementType.INSTRUCTION) { for (Var init: stmt.instruction().getInitialized()) { if (init.storage() == Alloc.ALIAS) { result.add(init); } } } else { assert(stmt.type() == StatementType.CONDITIONAL); result.addAll(findConditionalInitAliases(stmt.conditional())); } } return result; } private void addIncrForVar(Block block, RCTracker increments, RefCountType rcType, ListIterator<Statement> stmtIt, Var out) { // Alias var must be set at this point, insert refcount instruction long incr = increments.getCount(rcType, out, RCDir.INCR); assert (incr >= 0); if (incr > 0) { insertIncrAfter(block, stmtIt, out, incr, rcType); } increments.reset(rcType, out, RCDir.INCR); } /** * Try to implement refcount by adding to initial refcount of var declared * in this block. This is always possible for non-alias vars and we don't * run into any timing issues since the count is incremented as soon as * the variable is in existence * @param block * @param increments * @param rcType */ private void piggybackIncrementsOnDeclarations(GlobalVars globals, Function fn, Block block, RCTracker increments, RefCountType rcType) { if (!RCUtil.piggybackEnabled()) { return; } for (Var blockVar : block.variables()) { if (blockVar.storage() != Alloc.ALIAS) { long incr = increments.getCount(rcType, blockVar, RCDir.INCR); assert(incr >= 0); piggybackIncrement(globals, fn, block, increments, rcType, blockVar, incr); } } } private void piggybackIncrement(GlobalVars globals, Function fn, Block block, RCTracker increments, RefCountType rcType, Var var, long incr) { assert(incr >= 0); assert(incr == 0 || RefCounting.trackRefCount(var, rcType)) : var + " " + incr; if (incr == 0) { return; } if (var.storage() == Alloc.GLOBAL_VAR) { if (OptUtil.isEntryBlock(fn, block)) { // Globals in entry function are like regular block vars globals.modifyInitRefcount(var, rcType, incr); increments.cancel(var, rcType, -incr); } } else { block.modifyInitRefcount(var, rcType, incr); increments.cancel(var, rcType, -incr); } } /** * Add an increment instruction at top of block * * @param block * @param type * @param var * @param count */ private static void addRefIncrementAtTop(Block block, RefCountType type, Var var, long count) { assert (count >= 0) : var + ":" + count; if (count > 0) { // increment before anything spawned block.addInstructionFront(buildIncrInstruction(type, var, count)); } } private static Instruction buildIncrInstruction(RefCountType type, Var var, long count) { return RefCountOp.incrRef(type, var, Arg.newInt(count)); } }
34.482883
87
0.635359
24bc488be97a334183612fbaa67888c952fae2bb
639
package com.alicyu.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author zph * @classname DeptProvider8001_App * @description TODO * @date 2019/9/8 10:22 */ @SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient public class Config_Git_DeptProvider8001_App { public static void main(String[] args) { SpringApplication.run(Config_Git_DeptProvider8001_App.class,args); } }
29.045455
74
0.810642
d6ed97baaaeafa838e747a5fa83d879af9706942
4,808
package com.maxmind.geoip2.model; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.maxmind.geoip2.WebServiceClient; import com.maxmind.geoip2.exception.GeoIp2Exception; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.net.InetAddress; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.maxmind.geoip2.json.File.readJsonFile; import static org.junit.Assert.*; // In addition to testing the CityResponse, this code exercises the locale // handling of the models public class CityResponseTest { @Rule public final WireMockRule wireMockRule = new WireMockRule(0); @Before public void createClient() throws IOException, GeoIp2Exception, URISyntaxException { stubFor(get(urlEqualTo("/geoip/v2.1/city/1.1.1.2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/vnd.maxmind.com-city+json; charset=UTF-8; version=2.1") .withBody(readJsonFile("city0")))); } @Test public void testNames() throws Exception { WebServiceClient client = new WebServiceClient.Builder(6, "0123456789") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .locales(Arrays.asList("zh-CN", "ru")) .build(); CityResponse city = client.city(InetAddress.getByName("1.1.1.2")); assertEquals("country.getContinent().getName() does not return 北美洲", "北美洲", city.getContinent().getName()); assertEquals("country.getCountry().getName() does not return 美国", "美国", city.getCountry().getName()); assertEquals("toString() returns getName()", city.getCountry() .getName(), city.getCountry().getName()); } @Test public void russianFallback() throws Exception { WebServiceClient client = new WebServiceClient.Builder(42, "abcdef123456") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .locales(Arrays.asList("as", "ru")).build(); CityResponse city = client.city(InetAddress.getByName("1.1.1.2")); assertEquals( "country.getCountry().getName() does not return объединяет государства", "объединяет государства", city.getCountry().getName()); } @Test public void testFallback() throws Exception { WebServiceClient client = new WebServiceClient.Builder(42, "abcdef123456") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .locales(Arrays.asList("pt", "en", "zh-CN")).build(); CityResponse city = client.city(InetAddress.getByName("1.1.1.2")); assertEquals("en is returned when pt is missing", "North America", city.getContinent() .getName()); } @Test public void noFallback() throws Exception { WebServiceClient client = new WebServiceClient.Builder(42, "abcdef123456") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .locales(Arrays.asList("pt", "es", "af")).build(); CityResponse city = client.city(InetAddress.getByName("1.1.1.2")); assertNull("null is returned when locale is not available", city .getContinent().getName()); } @Test public void noLocale() throws Exception { WebServiceClient client = new WebServiceClient.Builder(42, "abcdef123456") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .build(); CityResponse city = client.city(InetAddress.getByName("1.1.1.2")); assertEquals("en is returned when no locales are specified", "North America", city .getContinent().getName()); } @Test public void testMissing() throws Exception { WebServiceClient client = new WebServiceClient.Builder(42, "abcdef123456") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .locales(Collections.singletonList("en")).build(); CityResponse city = client.city(InetAddress.getByName("1.1.1.2")); assertNotNull(city.getCity()); assertNull("null is returned when names object is missing", city .getCity().getName()); } }
37.5625
120
0.603369
0fe3d2c48ce526d271e886212cf93960efc806d6
4,850
package com.sequenceiq.it.verification; import static org.testng.Assert.fail; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Response; public class Verification { private static final Logger LOGGER = LoggerFactory.getLogger(Verification.class); private final String path; private final boolean regex; private final String httpMethod; private Map<Call, Response> requestResponseMap; private Integer atLeast; private Integer exactTimes; private final Collection<Pattern> patternList = new ArrayList<>(); private final Map<String, Integer> bodyContainsList = new HashMap<>(); public Verification(String path, String httpMethod, Map<Call, Response> requestResponseMap, boolean regex) { this.path = path; this.regex = regex; this.httpMethod = httpMethod; this.requestResponseMap = requestResponseMap; } public Verification(String path, String httpMethod, boolean regex) { this.path = path; this.regex = regex; this.httpMethod = httpMethod; } public Verification atLeast(int times) { atLeast = times; return this; } public Verification exactTimes(int times) { exactTimes = times; return this; } public Verification bodyContains(String text) { bodyContainsList.put(text, -1); return this; } public Verification bodyContains(String text, int times) { bodyContainsList.put(text, times); return this; } public Verification bodyRegexp(String regexp) { Pattern pattern = Pattern.compile(regexp); patternList.add(pattern); return this; } public void verify() { logVerify(); int times = getTimesMatched(); checkAtLeast(times); checkExactTimes(times); } public void verify(Map<Call, Response> requestResponseMap) { this.requestResponseMap = requestResponseMap; verify(); } private void logVerify() { LOGGER.info("Verification call: " + path); LOGGER.info("Body must contains: " + StringUtils.join(bodyContainsList, ",")); List<String> patternStringList = patternList.stream().map(Pattern::pattern).collect(Collectors.toList()); LOGGER.info("Body must match: " + StringUtils.join(patternStringList, ",")); } private void checkExactTimes(int times) { if (exactTimes != null) { if (exactTimes != times) { logRequests(); fail(path + " request should have been invoked exactly " + exactTimes + " times, but it was invoked " + times + " times"); } } } private void checkAtLeast(int times) { if (atLeast != null) { if (times < atLeast) { logRequests(); fail(path + " request should have been invoked at least " + atLeast + " times, but it was invoked " + times + " times"); } } } private int getTimesMatched() { int times = 0; for (Call call : requestResponseMap.keySet()) { boolean pathMatched = isPathMatched(call); if (call.getMethod().equals(httpMethod) && pathMatched) { int bodyContainsNumber = 0; for (Entry<String, Integer> stringIntegerEntry : bodyContainsList.entrySet()) { int count = StringUtils.countMatches(call.getPostBody(), stringIntegerEntry.getKey()); int required = stringIntegerEntry.getValue(); if ((required < 0 && count > 0) || (count == required)) { bodyContainsNumber++; } } int patternNumber = 0; for (Pattern pattern : patternList) { boolean patternMatch = pattern.matcher(call.getPostBody()).matches(); if (patternMatch) { patternNumber++; } } if (bodyContainsList.size() == bodyContainsNumber && patternList.size() == patternNumber) { times++; } } } return times; } private boolean isPathMatched(Call call) { boolean pathMatched; return regex ? Pattern.matches(path, call.getUri()) : call.getUri().equals(path); } private void logRequests() { LOGGER.info("Request received: "); requestResponseMap.keySet().forEach(call -> LOGGER.info("Request: " + call)); } }
31.290323
138
0.602268
6c559ead6aae8aac56aac18d07da7a7d0c8080f5
308
/** * iBizSys 5.0 用户自定义代码 * http://www.ibizsys.net */ package net.ibizsys.psrt.srv.common.demodel.datasyncout2.dataquery; /** * 实体数据查询 [DEFAULT]模型 */ public class DataSyncOut2DefaultDQModel extends DataSyncOut2DefaultDQModelBase { public DataSyncOut2DefaultDQModel() { super(); } }
19.25
80
0.704545
181a3aa0ea8ced5093a43ca3afd813e72cb2b6d1
8,876
package com.bee.scheduler.core.job; import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.ReferenceConfig; import com.alibaba.dubbo.config.RegistryConfig; import com.alibaba.dubbo.config.utils.ReferenceConfigCache; import com.alibaba.dubbo.config.utils.ReferenceConfigCache.KeyGenerator; import com.alibaba.dubbo.rpc.service.GenericService; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.bee.scheduler.core.Constants; import com.bee.scheduler.core.TaskExecutionContext; import com.bee.scheduler.core.TaskExecutionLog; import org.apache.commons.lang3.StringUtils; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; /** * @author weiwei Dubbo客户端组件,该组件提供调用dubbo服务的功能 */ public class DubboInvokerJobComponent extends JobComponent { private static Map<String, Class<?>> TYPE_ALIASES = new HashMap<>(); static { TYPE_ALIASES.put("string", String.class); TYPE_ALIASES.put("byte", Byte.class); TYPE_ALIASES.put("long", Long.class); TYPE_ALIASES.put("short", Short.class); TYPE_ALIASES.put("int", Integer.class); TYPE_ALIASES.put("integer", Integer.class); TYPE_ALIASES.put("double", Double.class); TYPE_ALIASES.put("float", Float.class); TYPE_ALIASES.put("boolean", Boolean.class); TYPE_ALIASES.put("string[]", String[].class); TYPE_ALIASES.put("byte[]", Byte[].class); TYPE_ALIASES.put("long[]", Long[].class); TYPE_ALIASES.put("short[]", Short[].class); TYPE_ALIASES.put("int[]", Integer[].class); TYPE_ALIASES.put("integer[]", Integer[].class); TYPE_ALIASES.put("double[]", Double[].class); TYPE_ALIASES.put("float[]", Float[].class); TYPE_ALIASES.put("boolean[]", Boolean[].class); TYPE_ALIASES.put("_byte", byte.class); TYPE_ALIASES.put("_long", long.class); TYPE_ALIASES.put("_short", short.class); TYPE_ALIASES.put("_int", int.class); TYPE_ALIASES.put("_integer", int.class); TYPE_ALIASES.put("_double", double.class); TYPE_ALIASES.put("_float", float.class); TYPE_ALIASES.put("_boolean", boolean.class); TYPE_ALIASES.put("_byte[]", byte[].class); TYPE_ALIASES.put("_long[]", long[].class); TYPE_ALIASES.put("_short[]", short[].class); TYPE_ALIASES.put("_int[]", int[].class); TYPE_ALIASES.put("_integer[]", int[].class); TYPE_ALIASES.put("_double[]", double[].class); TYPE_ALIASES.put("_float[]", float[].class); TYPE_ALIASES.put("_boolean[]", boolean[].class); TYPE_ALIASES.put("date", Date.class); TYPE_ALIASES.put("decimal", BigDecimal.class); TYPE_ALIASES.put("bigdecimal", BigDecimal.class); TYPE_ALIASES.put("biginteger", BigInteger.class); TYPE_ALIASES.put("object", Object.class); TYPE_ALIASES.put("date[]", Date[].class); TYPE_ALIASES.put("decimal[]", BigDecimal[].class); TYPE_ALIASES.put("bigdecimal[]", BigDecimal[].class); TYPE_ALIASES.put("biginteger[]", BigInteger[].class); TYPE_ALIASES.put("object[]", Object[].class); TYPE_ALIASES.put("map", Map.class); TYPE_ALIASES.put("hashmap", HashMap.class); TYPE_ALIASES.put("list", List.class); TYPE_ALIASES.put("arraylist", ArrayList.class); TYPE_ALIASES.put("collection", Collection.class); TYPE_ALIASES.put("iterator", Iterator.class); } public static final KeyGenerator REFERENCE_CONFIG_CACHE_KEY_GENERATOR = new KeyGenerator() { @Override public String generateKey(ReferenceConfig<?> referenceConfig) { String iName = referenceConfig.getInterface(); if (StringUtils.isBlank(iName)) { Class<?> clazz = referenceConfig.getInterfaceClass(); iName = clazz.getName(); } if (StringUtils.isBlank(iName)) { throw new IllegalArgumentException("No interface info in ReferenceConfig" + referenceConfig); } StringBuilder ret = new StringBuilder(); if (referenceConfig.getRegistry() == null) { if (StringUtils.isNotBlank(referenceConfig.getUrl())) { ret.append(referenceConfig.getUrl()).append("/"); } } else { ret.append(referenceConfig.getRegistry()).append("/"); } if (StringUtils.isNotBlank(referenceConfig.getGroup())) { ret.append(referenceConfig.getGroup()).append("/"); } ret.append(iName); if (StringUtils.isNotBlank(referenceConfig.getVersion())) { ret.append(":").append(referenceConfig.getVersion()); } return ret.toString(); } }; @Override public String getName() { return "DubboGenericInvoker"; } @Override public String getVersion() { return "1.1"; } @Override public String getAuthor() { return "weiwei"; } @Override public String getDescription() { return "基于dubbo开发,支持多种远程调用协议(dubbo、rmi、hessian)"; } @Override public String getParamTemplate() { StringBuilder t = new StringBuilder(); t.append("{\r"); t.append(" url:'',\r"); t.append(" registry:'zookeeper://127.0.0.1:2181',\r"); t.append(" service:'',\r"); t.append(" version:'',\r"); t.append(" group:'',\r"); t.append(" method:'',\r"); t.append(" timeout:10000,\r"); t.append(" loadbalance:'random',\r"); t.append(" params:[],\r"); t.append(" paramsType:[]\r"); t.append("}"); return t.toString(); } @Override public boolean run(TaskExecutionContext context) throws Exception { JSONObject taskParam = context.getTaskParam(); TaskExecutionLog taskLogger = context.getLogger(); String url = taskParam.getString("url"); String registry = taskParam.getString("registry"); String service = taskParam.getString("service"); String version = taskParam.getString("version"); String group = taskParam.getString("group"); String method = taskParam.getString("method"); Integer timeout = taskParam.getInteger("timeout"); String loadbalance = taskParam.getString("loadbalance"); JSONArray methodParamsType = JSONArray.parseArray(taskParam.getString("paramsType")); JSONArray methodParams = JSONArray.parseArray(taskParam.getString("params")); // RegistryConfig registry = new RegistryConfig(); // registry.setAddress(taskParam.getString("registry")); // registry.setUsername("aaa"); // registry.setPassword("bbb"); // 泛化引用远程服务 ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setApplication(new ApplicationConfig(Constants.SYSNAME)); referenceConfig.setUrl(url); RegistryConfig registryConfig = new RegistryConfig(registry); referenceConfig.setRegistry(registryConfig); referenceConfig.setInterface(service); referenceConfig.setVersion(version); referenceConfig.setGroup(group); referenceConfig.setGeneric(true); referenceConfig.setTimeout(timeout); referenceConfig.setLoadbalance(loadbalance); ReferenceConfigCache referenceConfigCache = ReferenceConfigCache.getCache("DEFAULT", REFERENCE_CONFIG_CACHE_KEY_GENERATOR); GenericService genericService = referenceConfigCache.get(referenceConfig); // GenericService genericService = referenceConfig.get(); // 解析类型别名 JSONArray paramTypeJsonArray = methodParamsType; String[] paramTypeStrArray = new String[paramTypeJsonArray.size()]; Class<?>[] paramTypeArray = new Class<?>[paramTypeJsonArray.size()]; for (int i = 0; i < paramTypeJsonArray.size(); i++) { String type = paramTypeJsonArray.getString(i); String typeLowerCase = type.toLowerCase(); paramTypeStrArray[i] = TYPE_ALIASES.containsKey(typeLowerCase) ? TYPE_ALIASES.get(typeLowerCase).getName() : type; paramTypeArray[i] = TYPE_ALIASES.containsKey(typeLowerCase) ? TYPE_ALIASES.get(typeLowerCase) : Map.class; } JSONArray argsJsonArray = methodParams; Object[] params = new Object[argsJsonArray.size()]; for (int i = 0; i < argsJsonArray.size(); i++) { params[i] = argsJsonArray.getObject(i, paramTypeArray[i]); } Object result = genericService.$invoke(method, paramTypeStrArray, params); taskLogger.info("任务执行成功 -> return:" + result + ""); return true; } }
40.903226
131
0.637675
9d9a105aec9d0d9e966e9b6b330d10c3032a0e37
6,474
package com.shoes.scarecrow.web.controller; import com.shoes.scarecrow.persistence.domain.Brand; import com.shoes.scarecrow.persistence.domain.BrandCondition; import com.shoes.scarecrow.persistence.service.BrandService; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.*; /** * Create with IntelliJ IDEA * Create by zz * Date 18-4-10 * Time 上午12:41 */ @Controller @RequestMapping("/brand") public class BrandController { private static Logger log = Logger.getLogger(BrandController.class); @Autowired private BrandService brandService; @RequestMapping("/allDetail") public void getBrandDetailByPage(int page, int limit, String name, HttpSession session, HttpServletResponse response){ log.info(session.getAttribute("userName")+"进入到分页获取品牌信息的方法,limit="+limit+",page="+page); Map<String,Object> map = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); BrandCondition condition = new BrandCondition(); condition.setName(name); condition.setPage(null); condition.setPageSize(null); condition.setStartRow(null); int total = brandService.queryCountByCondition(condition); condition.setPage(page); condition.setPageSize(limit); int start = (page-1)*limit; condition.setStartRow(start); List<Brand> list = brandService.queryByCondition(condition); // list = new ArrayList<>(); // for(int i=0;i<50;i++){ // Brand brand = new Brand(); // brand.setId(i); // brand.setName("品牌"+i); // brand.setCreateUser("创建人"+i); // brand.setCreateTime(new Date()); // brand.setUpdateUser("更新人"+i); // brand.setUpdateTime(new Date()); // brand.setRemark("备注"+i); // list.add(brand); // } map.put("code","0"); map.put("msg",""); map.put("count",total); map.put("data",list); try { log.info(session.getAttribute("userName")+"退出分页获取品牌信息的方法,result="+mapper.writeValueAsString(map)); } catch (IOException e) { e.printStackTrace(); } ObjectMapper objectMapper = new ObjectMapper(); try{ String retStr = objectMapper.writeValueAsString(map); response.setCharacterEncoding("utf-8"); PrintWriter printWriter = response.getWriter(); printWriter.print(retStr); }catch (IOException e){ log.error("请求brand/allDetail.do 写返回数据时发生错误。"+e.getMessage()); } } @RequestMapping("/addBrand") @ResponseBody public Map addBrand(HttpSession session, Brand brand){ ObjectMapper mapper = new ObjectMapper(); String userName = (String) session.getAttribute("userName"); brand.setCreateUser(userName); brand.setCreateTime(new Date()); brand.setUpdateUser(userName); brand.setUpdateTime(new Date()); brand.setYn(0); brand.setStatus(1); try{ log.info(session.getAttribute("userName")+"进入添加品牌方法"+mapper.writeValueAsString(brand)); }catch(IOException e ){ e.printStackTrace(); } int n = brandService.saveBrand(brand); Map map = new HashMap<String,Object>(); if(n==0){ map.put("success",false); }else{ map.put("success",true); } log.info(session.getAttribute("userName")+"离开添加品牌方法,添加结果影响行数:"+n); return map; } @RequestMapping("/updateBrand") @ResponseBody public Map updateBrand(Brand brand, HttpSession session){ ObjectMapper mapper = new ObjectMapper(); String userName = (String) session.getAttribute("userName"); brand.setUpdateUser(userName); brand.setUpdateTime(new Date()); try{ log.info(session.getAttribute("userName")+"进入修改品牌方法"+mapper.writeValueAsString(brand)); }catch(IOException e ){ e.printStackTrace(); } int n = brandService.updateBrand(brand); Map map = new HashMap<String,Object>(); if(n==0){ map.put("success",false); }else{ map.put("success",true); } log.info(session.getAttribute("userName")+"离开修改品牌方法,结果影响行数:"+n); return map; } @RequestMapping("/deleteBrand/{id}") @ResponseBody public Map deleteBrand(@PathVariable("id") Integer id, HttpSession session){ log.info(session.getAttribute("userName")+"进入删除品牌方法,删除品牌id="+id); int n = brandService.delBrand(id); Map map = new HashMap<String,Object>(); if(n==0){ map.put("success",false); }else{ map.put("success",true); } log.info(session.getAttribute("userName")+"离开删除品牌方法,结果影响行数:"+n); return map; } @RequestMapping("/shortBrand") public void getBrandShortMessage(HttpSession session, HttpServletResponse response){ log.info(session.getAttribute("userName")+"进入到获取品牌简单信息的方法"); Map<String,Object> map = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); List<Brand> list = new ArrayList<>(); for(int i=0;i<50;i++){ Brand brand = new Brand(); brand.setId(i); brand.setName("品牌"+i); list.add(brand); } map.put("data",list); try { log.info(session.getAttribute("userName")+"退出到获取品牌简单信息的方法,result="+mapper.writeValueAsString(map)); } catch (IOException e) { e.printStackTrace(); } ObjectMapper objectMapper = new ObjectMapper(); try{ String retStr = objectMapper.writeValueAsString(map); response.setCharacterEncoding("utf-8"); PrintWriter printWriter = response.getWriter(); printWriter.print(retStr); }catch (IOException e){ log.error("请求brand/allDetail.do 写返回数据时发生错误。"+e.getMessage()); } } }
37.639535
122
0.624344
e3ddcdd77af35515060d1b96485017fb7ce9c569
1,192
public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); c = new int[n + 1][3]; dp = new long[n + 1][6]; for (int i = 1; i <= n; i++) c[i][0] = in.scanInt(); for (int i = 1; i <= n; i++) c[i][1] = in.scanInt(); for (int i = 1; i <= n; i++) c[i][2] = in.scanInt(); int[] from = new int[n - 1]; int[] to = new int[n - 1]; for (int i = 0; i < n - 1; i++) { from[i] = in.scanInt(); to[i] = in.scanInt(); } G = CodeHash.packGraph(from, to, n); flag = true; map = new int[6]; map[0] = 3; map[1] = 5; map[2] = 1; map[3] = 4; map[4] = 0; map[5] = 2; this.dis = -1; this.farthest = -1; dfss(1, -1, 0); dfs(this.farthest, -1); if (!flag) { out.println(-1); return; } int which = 0; long ans = Long.MAX_VALUE; answer = new int[n + 1]; for (int i = 0; i < 6; i++) { if (ans > dp[this.farthest][i]) { ans = dp[this.farthest][i]; which = i; } } dfs1(this.farthest, -1, which); out.println(ans); for (int i = 1; i <= n; i++) { out.print(answer[i] + " "); } }
26.488889
67
0.438758
302a545f06ed72be7345f834130867e5e90a08a6
14,819
/* * Copyright 2012-2015, the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.flipkart.phantom.runtime.impl.server.netty.handler.thrift; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TMessage; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TTransport; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.group.ChannelGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; import com.flipkart.phantom.event.ServiceProxyEvent; import com.flipkart.phantom.event.ServiceProxyEventProducer; import com.flipkart.phantom.runtime.impl.server.netty.channel.thrift.ThriftNettyChannelBuffer; import com.flipkart.phantom.task.impl.collector.EventDispatchingSpanCollector; import com.flipkart.phantom.task.impl.interceptor.ServerRequestInterceptor; import com.flipkart.phantom.task.spi.Executor; import com.flipkart.phantom.task.spi.RequestContext; import com.flipkart.phantom.task.spi.repository.ExecutorRepository; import com.flipkart.phantom.thrift.impl.ThriftProxy; import com.flipkart.phantom.thrift.impl.ThriftProxyExecutor; import com.flipkart.phantom.thrift.impl.ThriftRequestWrapper; import com.github.kristofa.brave.Brave; import com.github.kristofa.brave.FixedSampleRateTraceFilter; import com.github.kristofa.brave.ServerSpan; import com.github.kristofa.brave.ServerTracer; import com.github.kristofa.brave.TraceFilter; import com.google.common.base.Optional; /** * <code>ThriftChannelHandler</code> is a sub-type of {@link SimpleChannelHandler} that acts as a proxy for Apache Thrift calls using the binary protocol. * It wraps the Thrift call using a {@link ThriftProxyExecutor} that provides useful features like monitoring, fallback etc. * * @author Regunath B * @version 1.0, 26 Mar 2013 */ public class ThriftChannelHandler extends SimpleChannelUpstreamHandler implements InitializingBean { /** Logger for this class*/ private static final Logger LOGGER = LoggerFactory.getLogger(ThriftChannelHandler.class); /** The default name of the server/service this channel handler is serving*/ private static final String DEFAULT_SERVICE_NAME = "Thrift Proxy"; /** Event Type for publishing all events which are generated here */ private final static String THRIFT_HANDLER = "THRIFT_HANDLER"; /** The default response size for creating dynamic channel buffers*/ private static final int DEFAULT_RESPONSE_SIZE = 4096; /** The default value for tracing frequency. This value indicates that tracing if OFF*/ private static final TraceFilter NO_TRACING = new FixedSampleRateTraceFilter(-1); /** Default host name and port where this ChannelHandler is available */ public static final String DEFAULT_HOST = "localhost"; // unresolved local host name public static final int DEFAULT_PORT = -1; // no valid port really /** The local host name value*/ private static String hostName = DEFAULT_HOST; static { try { hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LOGGER.warn("Unable to resolve local host name. Will use default host name : " + DEFAULT_HOST); } } /** The name for the service/server*/ private String serviceName = DEFAULT_SERVICE_NAME; /** The port where the server for this handler is listening on*/ private int hostPort; /** The default channel group*/ private ChannelGroup defaultChannelGroup; /** The Thrift TaskRepository to lookup ThriftServiceProxyClient from */ private ExecutorRepository<ThriftRequestWrapper, TTransport, ThriftProxy> repository; /** The ThriftHandler of this channel */ private String thriftProxy; /** The dynamic buffer response size*/ private int responseSize = DEFAULT_RESPONSE_SIZE; /** The Thrift binary protocol factory*/ private TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); /** The publisher used to broadcast events to Service Proxy Subscribers */ private ServiceProxyEventProducer eventProducer; /** The request tracing frequency for this channel handler*/ private TraceFilter traceFilter = NO_TRACING; /** The EventDispatchingSpanCollector instance used in tracing requests*/ private EventDispatchingSpanCollector eventDispatchingSpanCollector; /** * Interface method implementation. Checks if all mandatory properties have been set * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() throws Exception { Assert.notNull(this.defaultChannelGroup, "The 'defaultChannelGroup' may not be null"); Assert.notNull(this.repository, "The 'repository' may not be null"); Assert.notNull(this.thriftProxy, "The 'thriftProxy' may not be null"); Assert.notNull(this.eventProducer, "The 'eventProducer' may not be null"); Assert.notNull(this.eventDispatchingSpanCollector, "The 'eventDispatchingSpanCollector' may not be null"); } /** * Overriden superclass method. Stores the host port that this handler's server is listening on * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelBound(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) */ public void channelBound(ChannelHandlerContext ctx,ChannelStateEvent event) throws Exception { super.channelBound(ctx, event); if (InetSocketAddress.class.isAssignableFrom(event.getValue().getClass())) { this.hostPort = ((InetSocketAddress)event.getValue()).getPort(); } } /** * Overriden superclass method. Adds the newly created Channel to the default channel group and calls the super class {@link #channelOpen(ChannelHandlerContext, ChannelStateEvent)} method * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelOpen(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent) */ public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent event) throws Exception { super.channelOpen(ctx, event); this.defaultChannelGroup.add(event.getChannel()); } /** * Overridden method. Reads and processes Thrift calls sent to the service proxy. Expects data in the Thrift binary protocol. * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#handleUpstream(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelEvent) */ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent event) throws Exception { long receiveTime = System.currentTimeMillis(); if (MessageEvent.class.isAssignableFrom(event.getClass())) { // Prepare input and output ChannelBuffer input = (ChannelBuffer) ((MessageEvent) event).getMessage(); ChannelBuffer output = ChannelBuffers.dynamicBuffer(responseSize); TTransport clientTransport = new ThriftNettyChannelBuffer(input, output); //Get command name ThriftNettyChannelBuffer ttransport = new ThriftNettyChannelBuffer(input, null); TProtocol iprot = this.protocolFactory.getProtocol(ttransport); input.markReaderIndex(); TMessage message = iprot.readMessageBegin(); input.resetReaderIndex(); ThriftRequestWrapper thriftRequestWrapper = new ThriftRequestWrapper(); thriftRequestWrapper.setClientSocket(clientTransport); thriftRequestWrapper.setMethodName(message.name); // set the service name for the request thriftRequestWrapper.setServiceName(Optional.of(this.serviceName)); // Create and process a Server request interceptor. This will initialize the server tracing ServerRequestInterceptor<ThriftRequestWrapper, TTransport> serverRequestInterceptor = this.initializeServerTracing(thriftRequestWrapper); //Execute Executor<ThriftRequestWrapper,TTransport> executor = this.repository.getExecutor(message.name, this.thriftProxy, thriftRequestWrapper); // set the service name for the request thriftRequestWrapper.setServiceName(executor.getServiceName()); Optional<RuntimeException> transportError = Optional.absent(); try { executor.execute(); } catch (Exception e) { RuntimeException runtimeException = new RuntimeException("Error in executing Thrift request: " + thriftProxy + ":" + message.name, e); transportError = Optional.of(runtimeException); throw runtimeException; } finally { // finally inform the server request tracer serverRequestInterceptor.process(clientTransport, transportError); if (eventProducer != null) { // Publishes event both in case of success and failure. ServiceProxyEvent.Builder eventBuilder; if (executor == null) { eventBuilder = new ServiceProxyEvent.Builder(thriftProxy + ":" + message.name, THRIFT_HANDLER).withEventSource(getClass().getName()); } else { eventBuilder = executor.getEventBuilder().withCommandData(executor).withEventSource(executor.getClass().getName()); } eventBuilder.withRequestReceiveTime(receiveTime); eventProducer.publishEvent(eventBuilder.build()); } else { LOGGER.debug("eventProducer not set, not publishing event"); } } // write the result to the output channel buffer Channels.write(ctx, event.getFuture(), ((ThriftNettyChannelBuffer) clientTransport).getOutputBuffer()); } super.handleUpstream(ctx, event); } /** * Interface method implementation. Closes the underlying channel after logging a warning message * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent) */ public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent event) throws Exception { LOGGER.warn("Exception {} thrown on Channel {}. Disconnect initiated",event,event.getChannel()); event.getChannel().close(); super.exceptionCaught(ctx, event); } /** * Initializes server tracing for the specified request * @param executorHttpRequest the Http request * @return the initialized ServerRequestInterceptor */ private ServerRequestInterceptor<ThriftRequestWrapper, TTransport> initializeServerTracing(ThriftRequestWrapper executorRequest) { ServerRequestInterceptor<ThriftRequestWrapper, TTransport> serverRequestInterceptor = new ServerRequestInterceptor<ThriftRequestWrapper, TTransport>(); List<TraceFilter> traceFilters = Arrays.<TraceFilter>asList(this.traceFilter); ServerTracer serverTracer = Brave.getServerTracer(this.eventDispatchingSpanCollector, traceFilters); serverRequestInterceptor.setEndPointSubmitter(Brave.getEndPointSubmitter()); serverRequestInterceptor.setServerTracer(serverTracer); serverRequestInterceptor.setServiceHost(ThriftChannelHandler.hostName); serverRequestInterceptor.setServicePort(this.hostPort); serverRequestInterceptor.setServiceName(this.serviceName); // now process the request to initialize tracing serverRequestInterceptor.process(executorRequest); // set the server request context on the received request ServerSpan serverSpan = Brave.getServerSpanThreadBinder().getCurrentServerSpan(); RequestContext serverRequestContext = new RequestContext(); serverRequestContext.setCurrentServerSpan(serverSpan); executorRequest.setRequestContext(Optional.of(serverRequestContext)); return serverRequestInterceptor; } /** Start Getter/Setter methods*/ public ChannelGroup getDefaultChannelGroup() { return this.defaultChannelGroup; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public void setDefaultChannelGroup(ChannelGroup defaultChannelGroup) { this.defaultChannelGroup = defaultChannelGroup; } public ExecutorRepository<ThriftRequestWrapper,TTransport, ThriftProxy> getRepository() { return this.repository; } public void setRepository(ExecutorRepository<ThriftRequestWrapper,TTransport, ThriftProxy> repository) { this.repository = repository; } public int getResponseSize() { return this.responseSize; } public void setResponseSize(int responseSize) { this.responseSize = responseSize; } public String getThriftProxy() { return thriftProxy; } public void setThriftProxy(String thriftProxy) { this.thriftProxy = thriftProxy; } public void setEventProducer(ServiceProxyEventProducer eventProducer) { this.eventProducer = eventProducer; } public void setTraceFilter(TraceFilter traceFilter) { this.traceFilter = traceFilter; } public void setEventDispatchingSpanCollector(EventDispatchingSpanCollector eventDispatchingSpanCollector) { this.eventDispatchingSpanCollector = eventDispatchingSpanCollector; } /** End Getter/Setter methods */ }
49.396667
191
0.738241
f47acf05832dc81a5f0b6b7eacdc31f233f33e6a
672
package org.light4j.thread.control; /** * 线程yield()方法使用测试 * * @author longjiazuo * */ public class YieldTest extends Thread { public YieldTest(String name) { super(name); } @Override public void run() { for (int i = 0; i < 50; i++) { System.out.println(getName() + " " + i); if (i == 20) { Thread.yield(); } } } public static void main(String[] args) { // 启动两个并发线程 YieldTest yt1 = new YieldTest("高级线程"); // 将线程yt1设置成最高优先级 yt1.setPriority(Thread.MAX_PRIORITY); yt1.start(); YieldTest yt2 = new YieldTest("低级线程"); // 将线程yt2设置成最低优先级 yt2.setPriority(Thread.MIN_PRIORITY); yt2.start(); } }
19.2
44
0.596726
ab55e394cde2e67b463d6a3a7348fab6facc295d
359
/** * Agent which have location as Double 2D must extend this * */ package sim.engine; import sim.util.Int2D; /** include index and set,get location method with Double2D * * */ public abstract class AgentInt { public Int2D loc; public int index; public abstract Int2D getLocation(); public abstract void setLocation(Int2D location); }
19.944444
59
0.707521
f720045d51b145b77be3ca5c25e25e0d6393cf45
912
// CS 143, Win 2015 ms rs // p3 Assassin // // AssinNode.java Instructor-provided support class. // You must not modify this code to work with your own linked list class! /** Each AssassinNode object represents a single node in a linked list for a game of Assassin. */ public class AssassinNode { public String name; // this person's name public String killer; // name of who killed this person (null if alive) public AssassinNode next; // next node in the list (null if none) /** Constructs a new node to store the given name and no next node. */ public AssassinNode(String name) { this(name, null); } /** Constructs a new node to store the given name and a reference to the given next node. */ public AssassinNode(String name, AssassinNode next) { this.name = name; this.killer = null; this.next = next; } }
33.777778
80
0.653509
94f029a581c1a0576a1ee2ceed315f01372cdadf
437
package com.legyver.fenxlib.core.api.config; /** * Comparable interface for services to allow them to be run in order * @param <T> the type of the service */ public interface OrderedService<T extends OrderedService> extends Comparable<T> { default int compareTo(T o) { return this.order() - o.order(); } /** * Order in which the ServiceImpl is to be run * Lowest number ran first * @return the order */ int order(); }
23
81
0.697941
7d3de61cf0b4fe37ea6602d3140237ed376ba1a6
5,806
package dderrien.common.dao; import static com.googlecode.objectify.ObjectifyService.ofy; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import com.googlecode.objectify.Key; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.cmd.LoadType; import com.googlecode.objectify.cmd.Query; import dderrien.common.exception.ClientErrorException; import dderrien.common.exception.InvalidRangeException; import dderrien.common.model.AbstractBase; import dderrien.common.util.IntrospectionHelper; import dderrien.common.util.Range; public abstract class AbstractDao<T extends AbstractBase<T>> { private static final Logger logger = Logger.getLogger(AbstractDao.class.getName()); private static Pattern noOperatorPattern = Pattern.compile("^[a-zA-Z0-9_]+$"); private Class<T> entityClass; public Class<T> getModelClass() { return entityClass; } @SuppressWarnings("unchecked") public AbstractDao() { super(); entityClass = (Class<T>) IntrospectionHelper.getFirstTypeArgument(this.getClass()); } public Objectify getOfy() { return ofy(); } public T get(Long id) { if (id == null) { throw new ClientErrorException("Cannot look for an entity of class " + getModelClass().getName() + " because the given identifier is null!"); } return getQuery(getModelClass()).id(id).now(); } public T filter(String condition, Object value) { if (StringUtils.isEmpty(condition)) { throw new ClientErrorException("Cannot look for an entity of class " + getModelClass().getName() + " because the given condition is null!"); } return getQuery(getModelClass()).filter(condition, value).first().now(); } public List<T> select(Map<String, Object> params, Range range, List<String> orders) { Query<T> query = getQuery(getModelClass()); if (params == null) { params = new HashMap<String, Object>(); } logger.finest("filters applied to select query on " + getModelClass().getSimpleName() + " : " + params); for (String key : params.keySet()) { boolean valueProcessed = false; Object value = params.get(key); if (value == null) { continue; } if (value instanceof String) { String stringValue = (String) value; if (stringValue.length() == 0) { continue; } if (stringValue.endsWith("*")) { if (stringValue.length() == 1) { continue; } String truncatedStringValue = stringValue.substring(0, stringValue.length() - 1); query = query.filter(key + " >= ", truncatedStringValue).filter(key + " < ", truncatedStringValue + "\uFFFD"); valueProcessed = true; } } else if (value instanceof List) { List<?> listValue = (List<?>) value; if (listValue.size() == 0) { continue; } if (listValue.size() == 1) { query = query.filter(key + " = ", listValue.get(0)); } else { query = query.filter(key + " IN ", listValue); } valueProcessed = true; } if (!valueProcessed) { if (noOperatorPattern.matcher(key).matches()) { key = key + " = "; // required for Objectify 4 otherwise defaults to == which yields strange results } query = query.filter(key, value); } } if (range != null && range.isInitialized()) { query = applyRange(query, range); } if (orders != null && 0 < orders.size()) { for (String order : orders) { if (order.charAt(0) == '+') { query = query.order(order.substring(1)); } else { query = query.order(order); } } } logger.finest("Query: " + query); List<T> list = query.list(); if (range != null && range.isInitialized()) { range.setListSize(list.size()); } return list; } public Key<AbstractBase<T>> save(AbstractBase<T> candidate) { return getOfy().save().entity(candidate).now(); } public void delete(Long id) { if (id == null) { throw new ClientErrorException("Cannot delete an entity of class " + getModelClass().getName() + " because the given identifier is null!"); } getOfy().delete().type(getModelClass()).id(id).now(); } // ========================= protected LoadType<T> getQuery(Class<T> modelClass) { return getOfy().load().type(modelClass); } protected Query<T> applyRange(Query<T> query, Range range) { // Get the total number of matching entity keys int total = query.keys().list().size(); int startRow = range.getStartRow(); if (startRow > 0 && startRow > total - 1) { throw new InvalidRangeException("range header mal formed for scrolling : result set shorter than expected"); } range.setTotal(total); // Specify request boundaries query = query.offset(startRow); Integer count = range.getCount(); if (count != null) { query = query.limit(count); } return query; } }
33.177143
153
0.557354
1c42bcba0b825ce91e959b60dbcfa9c40895aba3
1,108
package com.saubiette.proyecto.vistas; import com.saubiette.vistas.componentes.Menu; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.PreserveOnRefresh; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.PWA; @Route("") @PWA(name = "Vaadin Application", shortName = "Vaadin App", description = "This is an example Vaadin application.", enableInstallPrompt = false) @CssImport(value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field") @CssImport("./styles/styles.css") @PreserveOnRefresh public class Home extends VerticalLayout { /** * */ private static final long serialVersionUID = 1L; public Home() { Menu m = new Menu(); Div div = new Div(); div.add(m); Span text = new Span("No tienes permisos para acceder a esta seccion"); text.getElement().setAttribute("font-size", "15"); text.getElement().setAttribute("color", "red"); add(m, div, text); } }
29.157895
144
0.73917
d22b94ace0e3445aa0eb4071fc01ebfe7e22e328
311
package com.fITsummer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FITsummerApplication { public static void main(String[] args) { SpringApplication.run(FITsummerApplication.class, args); } }
23.923077
68
0.826367
5e4048ceab32fee8d86a90dfe5a04e78703e206b
1,379
package org.reldb.rel.v0.storage.catalog; import org.reldb.rel.exceptions.ExceptionSemantic; import org.reldb.rel.v0.generator.SelectAttributes; import org.reldb.rel.v0.languages.tutoriald.Keywords; import org.reldb.rel.v0.storage.RelDatabase; import org.reldb.rel.v0.storage.relvars.RelvarGlobal; import org.reldb.rel.v0.storage.relvars.RelvarHeading; import org.reldb.rel.v0.storage.relvars.RelvarMetadata; import org.reldb.rel.v0.types.*; public class RelvarKeywordsMetadata extends RelvarMetadata { public static final long serialVersionUID = 0; static Heading getNewHeading() { return Keywords.getHeading(); } static RelvarHeading getNewKeyDefinition() { RelvarHeading keydef = new RelvarHeading(getNewHeading()); SelectAttributes keyAttributes = new SelectAttributes(); keyAttributes.add("Keyword"); keydef.addKey(keyAttributes); return keydef; } public RelvarKeywordsMetadata(RelDatabase database) { super(database, getNewKeyDefinition(), RelDatabase.systemOwner); } public RelvarHeading getHeadingDefinition(RelDatabase database) { return getNewKeyDefinition(); } public RelvarGlobal getRelvar(String name, RelDatabase database) { return new RelvarKeywords(database); } public void dropRelvar(RelDatabase database) { throw new ExceptionSemantic("RS0481: The " + Catalog.relvarKeywords + " relvar may not be dropped."); } }
32.069767
105
0.788978
2a73dffffad70c357384594068a56f21195d1195
164
package scene.graph; public class SceneNode extends Node { public SceneNode() { super(null); } @Override public Node getParent() { return this; } }
10.25
37
0.664634
4abe1b171cbb77befdbdc1c5b74c0e424b3f97f6
1,325
public class DCP029RunningLengthEncodeDecode { public static String encode(String s) { if (s.length() == 0) { return ""; } String result = ""; int count = 1; char currentChar = s.charAt(0); for (int i = 1; i < s.length(); i++) { char ch = s.charAt(i); if (ch == currentChar) { count++; } else { result = count > 1 ? result + count + currentChar : result + currentChar; count = 1; currentChar = s.charAt(i); } } result = count > 1 ? result + count + currentChar : result + currentChar; return result; } public static String decode(String s) { if (s.length() == 0) { return ""; } String result = ""; int count = 0; for (int i = 0; i < s.length(); i++) { char currentChar = s.charAt(i); if (Character.isDigit(currentChar)) { count = count * 10 + Character.getNumericValue(currentChar); } else { if (count > 1) { for (int j = 0; j < count; j++) { result += currentChar; } } else { result += currentChar; } count = 0; } } return result; } public static void main(String[] args) { System.out.println(encode("AAABCDDEFF")); System.out.println(decode("3ABC2DE2F")); } }
24.090909
81
0.518491
5429f27f419bfc7465eb7266666a19f4ada7acca
3,933
package com.morange.shiro.security.entity; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author : zhenyun.su * @since : 2019/1/24 * @Comment: 自定义全局异常 name 权限名称, permission 授权标识, text 菜单界面显示内容, heading true 目录,false 使用链接的菜单, link 内部链接, elink 外部链接, target 链接打开的页面显示的目标, icon 菜单图标, alert 警告内容, label 警告外观CSS CLASS, sort 菜单排序, operation_ids 操作, enable true 启用, false 为禁止, List<Permission> children 子菜单,正常支持3 层就够了 List<Operation> operations 根据operation_ids 存放操作权限 */ @Entity @Table(name="sys_permission", schema = "fitness", catalog = "") public class Permission implements Serializable{ @Id @Column(name="permit_id") @GeneratedValue(generator = "",strategy = GenerationType.IDENTITY) private Long id; @Column(name="parent_id") private Long pid; private String name; private String permission; private String text; private Boolean heading; private String link; private String elink; private String target; private String icon; private String alert; private String label ; private Integer sort ; @Column(name="operation_ids") private String oids; private Boolean enable ; @Transient private List<Permission> children = new ArrayList<>(); @Transient private List<Operation> operations = new ArrayList<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getPid() { return pid; } public void setPid(Long pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Boolean getHeading() { return heading; } public void setHeading(Boolean heading) { this.heading = heading; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getElink() { return elink; } public void setElink(String elink) { this.elink = elink; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getAlert() { return alert; } public void setAlert(String alert) { this.alert = alert; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getOids() { return oids; } public void setOids(String oids) { this.oids = oids; } public Boolean getEnable() { return enable; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public void setEnable(Boolean enable) { this.enable = enable; } public List<Permission> getChildren() { return children; } public void setChildren(List<Permission> children) { this.children = children; } public List<Operation> getOperations() { return operations; } public void setOperations(List<Operation> operations) { this.operations = operations; } @Override public String toString() { return "Permission{" + "id=" + id + ", pid=" + pid + ", name='" + name + '\'' + ", permission='" + permission + '\'' + ", text='" + text + '\'' + ", heading=" + heading + ", link='" + link + '\'' + ", elink='" + elink + '\'' + ", target='" + target + '\'' + ", icon='" + icon + '\'' + ", alert='" + alert + '\'' + ", label='" + label + '\'' + ", sort=" + sort + ", oids='" + oids + '\'' + ", enable=" + enable + ", children=" + children + ", operations=" + operations + '}'; } }
17.958904
67
0.645055
2bcb57f4f84e18814df7697ecf2ef5dd46e56600
3,391
/* Derby - Class org.apache.derby.impl.store.access.btree.index.B2IRowLocking2 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.derby.impl.store.access.btree.index; import org.apache.derby.shared.common.sanity.SanityManager; import org.apache.derby.shared.common.error.StandardException; import org.apache.derby.iapi.store.access.ConglomerateController; import org.apache.derby.iapi.store.raw.LockingPolicy; import org.apache.derby.iapi.store.raw.Transaction; import org.apache.derby.impl.store.access.btree.BTreeLockingPolicy; import org.apache.derby.impl.store.access.btree.BTreeRowPosition; import org.apache.derby.impl.store.access.btree.OpenBTree; /** The btree locking policy which implements read committed isolation level. It inherits all functionality from B2IRowLockingRR (repeatable read) except that it releases read locks after obtaining them. It provides a single implementation of unlockScanRecordAfterRead() which releases a read lock after it has been locked and processed. **/ class B2IRowLocking2 extends B2IRowLockingRR implements BTreeLockingPolicy { /************************************************************************** * Constructors for This class: ************************************************************************** */ B2IRowLocking2( Transaction rawtran, int lock_level, LockingPolicy locking_policy, ConglomerateController base_cc, OpenBTree open_btree) { super(rawtran, lock_level, locking_policy, base_cc, open_btree); } /************************************************************************** * Public Methods of This class: ************************************************************************** */ /** * Release read lock on a row. * * @param forUpdate Is the scan for update or for read only. * **/ public void unlockScanRecordAfterRead( BTreeRowPosition pos, boolean forUpdate) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(open_btree != null, "open_btree is null"); SanityManager.ASSERT( pos.current_lock_row_loc != null , "pos.current_lock_row_loc is null"); SanityManager.ASSERT( !pos.current_lock_row_loc.isNull(), "pos.current_lock_row_loc isNull()"); } // always unlock in read committed, so pass false for qualified arg. base_cc.unlockRowAfterRead(pos.current_lock_row_loc, forUpdate, false); } }
34.252525
79
0.647302
fd9a138df8a5256b4f6a3f2c7b4bece8686df69b
1,784
package pro.gravit.simplecabinet.web.model; import javax.persistence.*; import java.time.LocalDateTime; @Entity @Table(name = "orders") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class Order { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "orders_generator") @SequenceGenerator(name = "orders_generator", sequenceName = "orders_seq", allocationSize = 1) private long id; @ManyToOne @JoinColumn(name = "payment_id") private UserPayment payment; @ManyToOne @JoinColumn(name = "user_id") private User user; private long quantity; private OrderStatus status; private LocalDateTime createdAt; private LocalDateTime updatedAt; public long getId() { return id; } public UserPayment getPayment() { return payment; } public void setPayment(UserPayment payment) { this.payment = payment; } public long getQuantity() { return quantity; } public void setQuantity(long quantity) { this.quantity = quantity; } public OrderStatus getStatus() { return status; } public void setStatus(OrderStatus status) { this.status = status; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public LocalDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public enum OrderStatus { INITIATED, DELIVERY } }
22.024691
98
0.653027
ddbad89cf19e3b291b2107425feeac8c451ae38b
2,088
package org.zstack.header.network.service; import org.zstack.header.network.l3.L3NetworkEO; import org.zstack.header.network.l3.L3NetworkVO; import org.zstack.header.search.SqlTrigger; import org.zstack.header.search.TriggerIndex; import org.zstack.header.vo.ForeignKey; import org.zstack.header.vo.ForeignKey.ReferenceOption; import org.zstack.header.vo.SoftDeletionCascade; import org.zstack.header.vo.SoftDeletionCascades; import javax.persistence.*; @Entity @Table @TriggerIndex @SqlTrigger(foreignVOClass=L3NetworkVO.class, foreignVOJoinColumn="l3NetworkUuid") @SoftDeletionCascades({ @SoftDeletionCascade(parent = L3NetworkVO.class, joinColumn = "l3NetworkUuid"), @SoftDeletionCascade(parent = NetworkServiceProviderVO.class, joinColumn = "networkServiceProviderUuid") }) public class NetworkServiceL3NetworkRefVO { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column private long id; @Column @ForeignKey(parentEntityClass = L3NetworkEO.class, onDeleteAction = ReferenceOption.CASCADE) private String l3NetworkUuid; @Column @ForeignKey(parentEntityClass = NetworkServiceProviderVO.class, onDeleteAction = ReferenceOption.CASCADE) private String networkServiceProviderUuid; @Column private String networkServiceType; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getL3NetworkUuid() { return l3NetworkUuid; } public void setL3NetworkUuid(String l3NetworkUuid) { this.l3NetworkUuid = l3NetworkUuid; } public String getNetworkServiceProviderUuid() { return networkServiceProviderUuid; } public void setNetworkServiceProviderUuid(String networkServiceProviderUuid) { this.networkServiceProviderUuid = networkServiceProviderUuid; } public String getNetworkServiceType() { return networkServiceType; } public void setNetworkServiceType(String networkServiceType) { this.networkServiceType = networkServiceType; } }
29.408451
113
0.75
6ad23fe825d2dbedf10a55fefa55731a5cf2df50
12,115
/* * Copyright 2006-2016 Edward Smith * * 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 root.adt; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import org.junit.Before; import org.junit.Test; import junit.framework.TestCase; import root.lang.FastString; import root.lang.Itemizer; import root.lang.StringExtractor; /** * Test the {@link MapExtractable} class. * * @author Edward Smith * @version 0.5 * @since 0.5 */ public final class MapExtractableTest extends TestCase { private MapExtractable<FastString, FastString> map; private final FastString foo = new FastString("foo"); private final FastString bar = new FastString("bar"); private final FastString xyz = new FastString("xyz"); private final FastString oneTwoThree = new FastString("123"); public MapExtractableTest() { super("MapExtractable"); } @Override @Before public void setUp() throws Exception { this.map = new MapExtractable<>(); } @Test public void testClear() { assertEquals(0, this.map.size()); this.map.put(this.foo, this.bar); assertEquals(1, this.map.size()); this.map.clear(); assertEquals(0, this.map.size()); } @Test public void testClone() { this.map.put(this.foo, this.bar); this.map.put(this.xyz, this.oneTwoThree); assertEquals(2, this.map.size()); assertEquals(this.bar, this.map.get(this.foo)); assertEquals(this.oneTwoThree, this.map.get(this.xyz)); final MapExtractable<FastString, FastString> m = this.map.clone(); assertEquals(2, m.size()); assertEquals(this.bar, m.get(this.foo)); assertEquals(this.oneTwoThree, m.get(this.xyz)); assertFalse(this.map == m); } @Test public void testConstructorCapacity() { MapExtractable<FastString, FastString> m = new MapExtractable<>(17); assertEquals(0, m.size()); assertEquals(32, m.getCapacity()); // Test minimum capacity of 8 m = new MapExtractable<>(7); assertEquals(0, m.size()); assertEquals(8, m.getCapacity()); } @Test public void testConstructorDefault() { assertEquals(0, this.map.size()); assertEquals(8, this.map.getCapacity()); } @Test public void testConstructorMap() { final Map<FastString, FastString> stringMap = new HashMap<>(); stringMap.put(this.foo, this.bar); stringMap.put(this.xyz, this.oneTwoThree); final MapExtractable<FastString, FastString> m = new MapExtractable<>(stringMap); assertEquals(2, m.size()); assertEquals(8, m.getCapacity()); assertEquals(this.bar, m.get(this.foo)); assertEquals(this.oneTwoThree, m.get(this.xyz)); } @Test public void testContainsEntry() { assertFalse(this.map.containsEntry(this.foo, this.bar)); this.map.put(this.foo, this.bar); assertTrue(this.map.containsEntry(this.foo, this.bar)); assertFalse(this.map.containsEntry(this.foo, this.xyz)); } @Test public void testContainsKey() { assertFalse(this.map.containsKey(this.foo)); this.map.put(this.foo, this.bar); assertTrue(this.map.containsKey(this.foo)); assertFalse(this.map.containsKey(this.bar)); } @Test public void testContainsValue() { assertFalse(this.map.containsValue(this.bar)); this.map.put(this.foo, this.bar); assertTrue(this.map.containsValue(this.bar)); assertFalse(this.map.containsValue(this.foo)); } @Test public void testEntrySet() { Set<Entry<FastString, FastString>> entrySet = this.map.entrySet(); final MapEntry<FastString, FastString> entry = new MapEntry<>(this.foo, this.bar); assertEquals(0, entrySet.size()); assertFalse(entrySet.contains(entry)); this.map.put(this.foo, this.bar); this.map.put(this.xyz, this.oneTwoThree); entrySet = this.map.entrySet(); assertEquals(2, entrySet.size()); assertTrue(entrySet.contains(entry)); assertTrue(entrySet.contains(new MapEntry<FastString, FastString>(this.xyz, this.oneTwoThree))); assertFalse(entrySet.contains(new MapEntry<FastString, FastString>(this.bar, this.foo))); assertFalse(entrySet.contains(new MapEntry<FastString, FastString>(this.oneTwoThree, this.xyz))); } @Test public void testEquals() { final MapHashed<FastString, FastString> mapHashed = new MapHashed<>(); assertTrue(this.map.equals(mapHashed)); this.map.put(this.foo, this.bar); assertFalse(this.map.equals(mapHashed)); mapHashed.put(this.foo, this.bar); assertTrue(this.map.equals(mapHashed)); this.map.clear(); final HashMap<FastString, FastString> hashMap = new HashMap<>(); assertTrue(this.map.equals(hashMap)); this.map.put(this.foo, this.bar); assertFalse(this.map.equals(hashMap)); hashMap.put(this.foo, this.bar); assertTrue(this.map.equals(hashMap)); } @Test public void testExtract() { final StringExtractor extractor = new StringExtractor(); this.map.extract(extractor); assertEquals("{}", extractor.toString()); this.map.put(this.foo, this.bar); extractor.clear(); this.map.extract(extractor); assertEquals("{foo=bar}", extractor.toString()); this.map.put(this.xyz, this.oneTwoThree); extractor.clear(); this.map.extract(extractor); assertEquals("{foo=bar,xyz=123}", extractor.toString()); } @Test public void testGetCapacity() { assertEquals(8, this.map.getCapacity()); } @Test public void testGetSize() { assertEquals(0, this.map.getSize()); this.map.put(this.foo, this.bar); assertEquals(1, this.map.getSize()); } @Test public void testGetValue() { assertNull(this.map.get("foo")); this.map.put(this.foo, this.bar); assertEquals(this.bar, this.map.get(this.foo)); } @Test public void testGetValueByClass() { this.map.put(this.xyz, this.oneTwoThree); final FastString str = this.map.get(this.xyz, FastString.class); assertEquals(this.oneTwoThree, str); } @Test public void testGetValueByDefault() { assertEquals(this.xyz, this.map.get(this.foo, this.xyz)); this.map.put(this.foo, this.bar); assertEquals(this.bar, this.map.get(this.foo, this.xyz)); } @Test public void testHashCode() { assertEquals(0, this.map.hashCode()); this.map.put(this.foo, this.bar); assertEquals(101572, this.map.hashCode()); this.map.put(this.xyz, this.oneTwoThree); assertEquals(182301, this.map.hashCode()); } @Test public void testIsEmpty() { assertTrue(this.map.isEmpty()); this.map.put(this.foo, this.bar); assertFalse(this.map.isEmpty()); } @Test public void testIterator() { Itemizer<MapEntry<FastString, FastString>> itemizer = this.map.iterator(); // Test empty collector assertEquals(-1, itemizer.getIndex()); assertEquals(0, itemizer.getSize()); assertFalse(itemizer.hasNext()); assertTrue(itemizer == itemizer.iterator()); try { itemizer.next(); fail("Expected java.util.NoSuchElementException was not thrown"); } catch (final NoSuchElementException e) { } try { itemizer.remove(); fail("Expected java.lang.UnsupportedOperationException was not thrown"); } catch (final UnsupportedOperationException e) { } this.map.put(this.foo, this.bar); this.map.put(this.xyz, this.oneTwoThree); itemizer = this.map.iterator(); assertEquals(-1, itemizer.getIndex()); assertEquals(2, itemizer.getSize()); assertTrue(itemizer.hasNext()); MapEntry<FastString, FastString> entry = itemizer.next(); assertEquals(this.foo, entry.getKey()); assertEquals(this.bar, entry.getValue()); assertEquals(0, itemizer.getIndex()); assertTrue(itemizer.hasNext()); entry = itemizer.next(); assertEquals(this.xyz, entry.getKey()); assertEquals(this.oneTwoThree, entry.getValue()); assertEquals(1, itemizer.getIndex()); assertFalse(itemizer.hasNext()); itemizer.reset(); assertEquals(-1, itemizer.getIndex()); assertTrue(itemizer.hasNext()); itemizer.next(); assertTrue(itemizer.hasNext()); itemizer.next(); assertFalse(itemizer.hasNext()); } @Test public void testKeySet() { Set<FastString> keySet = this.map.keySet(); assertEquals(0, keySet.size()); assertFalse(keySet.contains(this.foo)); this.map.put(this.foo, this.bar); this.map.put(this.xyz, this.oneTwoThree); keySet = this.map.keySet(); assertEquals(2, keySet.size()); assertTrue(keySet.contains(this.foo)); assertTrue(keySet.contains(this.xyz)); assertFalse(keySet.contains(this.bar)); assertFalse(keySet.contains(this.oneTwoThree)); } @Test public void testPut() { assertEquals(0, this.map.size()); this.map.put(this.foo, this.bar); assertEquals(1, this.map.size()); assertEquals(this.bar, this.map.get(this.foo)); this.map.put(this.xyz, this.oneTwoThree); assertEquals(2, this.map.size()); assertEquals(this.oneTwoThree, this.map.get(this.xyz)); final FastString ugh = new FastString("ugh"); this.map.put(this.foo, ugh); assertEquals(2, this.map.size()); assertEquals(ugh, this.map.get(this.foo)); } @Test public void testPutAll() { final Map<FastString, FastString> stringMap = new HashMap<>(); stringMap.put(this.foo, this.bar); stringMap.put(this.xyz, this.oneTwoThree); assertEquals(0, this.map.size()); this.map.putAll(stringMap); assertEquals(2, this.map.size()); assertEquals(this.bar, this.map.get(this.foo)); assertEquals(this.oneTwoThree, this.map.get(this.xyz)); this.map.putAll(stringMap); assertEquals(2, this.map.size()); assertEquals(this.bar, this.map.get(this.foo)); assertEquals(this.oneTwoThree, this.map.get(this.xyz)); } @Test public void testRemove() { assertNull(this.map.remove(this.foo)); this.map.put(this.foo, this.bar); assertEquals(1, this.map.size()); assertEquals(this.bar, this.map.remove(this.foo)); assertEquals(0, this.map.size()); } @Test public void testSize() { assertEquals(0, this.map.size()); this.map.put(this.foo, this.bar); assertEquals(1, this.map.size()); } @Test public void testToImmutable() { MapImmutable<FastString, FastString> immutableMap = this.map.toImmutable(); assertEquals(0, immutableMap.map.getSize()); assertEquals(8, immutableMap.map.getCapacity()); final FastString abc = new FastString("abc"); final FastString def = new FastString("def"); final FastString ghi = new FastString("ghi"); final FastString jkl = new FastString("jkl"); this.map.put(this.foo, this.bar); this.map.put(this.xyz, this.oneTwoThree); this.map.put(abc, def); this.map.put(ghi, jkl); immutableMap = this.map.toImmutable(); assertEquals(4, immutableMap.map.getSize()); assertEquals(8, immutableMap.map.getCapacity()); assertEquals(this.bar, immutableMap.get(this.foo)); assertEquals(this.oneTwoThree, immutableMap.get(this.xyz)); assertEquals(def, immutableMap.get(abc)); assertEquals(jkl, immutableMap.get(ghi)); assertFalse(this.map == immutableMap.map); } public void testToString() { assertEquals("{}", this.map.toString()); this.map.put(this.foo, this.bar); assertEquals("{foo=bar}", this.map.toString()); this.map.put(this.xyz, this.oneTwoThree); assertEquals("{foo=bar,xyz=123}", this.map.toString()); } public void testValues() { Collection<FastString> valueCollection = this.map.values(); assertEquals(0, valueCollection.size()); assertFalse(valueCollection.contains(this.bar)); this.map.put(this.foo, this.bar); this.map.put(this.xyz, this.oneTwoThree); valueCollection = this.map.values(); assertEquals(2, valueCollection.size()); assertTrue(valueCollection.contains(this.bar)); assertTrue(valueCollection.contains(this.oneTwoThree)); assertFalse(valueCollection.contains(this.foo)); assertFalse(valueCollection.contains(this.xyz)); } } // End MapExtractableTest
26.222944
99
0.713578
a082f57a33654675c7685a5006a2fb07fcdd4ee6
7,419
/* * Copyright (c) 2008-2009, Matthias Mann * * 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 Matthias Mann 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 test; import de.matthiasmann.twl.EditField; import de.matthiasmann.twl.GUI; import de.matthiasmann.twl.ScrollPane; import de.matthiasmann.twl.ThemeInfo; import de.matthiasmann.twl.Timer; import de.matthiasmann.twl.TreeTable; import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.model.AbstractTreeTableModel; import de.matthiasmann.twl.model.AbstractTreeTableNode; import de.matthiasmann.twl.model.PersistentStringModel; import de.matthiasmann.twl.model.StringModel; import de.matthiasmann.twl.model.TreeTableNode; /** * * @author Matthias Mann */ public class TreeTableDemoDialog1 extends FadeFrame implements Runnable { private ScrollPane scrollPane; private Timer timer; private MyNode dynamicNode; public TreeTableDemoDialog1() { MyModel m = new MyModel(); PersistentStringModel psm = new PersistentStringModel( AppletPreferences.userNodeForPackage(getClass()), "demoEditField", "you can edit this"); MyNode a = m.insert("A", "1"); a.insert("Aa", "2"); a.insert("Ab", "3"); MyNode ac = a.insert("Ac", "4"); ac.insert("Ac1", "Hello"); ac.insert("Ac2", "World"); ac.insert("EditField", psm); a.insert("Ad", "5"); MyNode b = m.insert("B", "6"); b.insert("Ba", "7"); b.insert("Bb", "8"); b.insert("Bc", "9"); dynamicNode = b.insert("Dynamic", "stuff"); m.insert( new SpanString( "This is a very long string which will span into the next column.", 2), "Not visible"); m.insert("This is a very long string which will be clipped.", "This is visible"); TreeTable t = new TreeTable(m); t.setTheme("/table"); t.registerCellRenderer(SpanString.class, new SpanRenderer()); t.registerCellRenderer(StringModel.class, new EditFieldCellRenderer()); t.setDefaultSelectionManager(); scrollPane = new ScrollPane(t); scrollPane.setTheme("/tableScrollPane"); setTheme("scrollPaneDemoDialog1"); setTitle("Dynamic TreeTable"); add(scrollPane); } @Override protected void afterAddToGUI(GUI gui) { super.afterAddToGUI(gui); timer = gui.createTimer(); timer.setCallback(this); timer.setDelay(1500); timer.setContinuous(true); timer.start(); } int state; MyNode subNode; public void run() { // System.out.println("state="+state); switch (state++) { case 0: dynamicNode.insert("Counting", "3..."); break; case 1: dynamicNode.insert("Counting", "2..."); break; case 2: dynamicNode.insert("Counting", "1..."); break; case 3: subNode = dynamicNode.insert("this is a", "folder"); break; case 4: subNode.insert("first", "entry"); break; case 5: subNode.insert("now starting to remove", "counter"); break; case 6: case 7: case 8: dynamicNode.remove(0); break; case 9: subNode.insert("last", "entry"); break; case 10: dynamicNode.insert("now removing", "folder"); break; case 11: dynamicNode.remove(0); break; case 12: dynamicNode.insert("starting", "again"); break; case 13: dynamicNode.removeAll(); state = 0; break; } } public void centerScrollPane() { scrollPane.updateScrollbarSizes(); scrollPane.setScrollPositionX(scrollPane.getMaxScrollPosX() / 2); scrollPane.setScrollPositionY(scrollPane.getMaxScrollPosY() / 2); } static class MyNode extends AbstractTreeTableNode { private Object str0; private Object str1; public MyNode(TreeTableNode parent, Object str0, Object str1) { super(parent); this.str0 = str0; this.str1 = str1; setLeaf(true); } public Object getData(int column) { return (column == 0) ? str0 : str1; } public MyNode insert(Object str0, Object str1) { MyNode n = new MyNode(this, str0, str1); insertChild(n, getNumChildren()); setLeaf(false); return n; } public void remove(int idx) { removeChild(idx); } public void removeAll() { removeAllChildren(); } } static class MyModel extends AbstractTreeTableModel { private static final String[] COLUMN_NAMES = { "Left", "Right" }; public int getNumColumns() { return 2; } public String getColumnHeaderText(int column) { return COLUMN_NAMES[column]; } public MyNode insert(Object str0, String str1) { MyNode n = new MyNode(this, str0, str1); insertChild(n, getNumChildren()); return n; } } static class SpanString { private final String str; private final int span; public SpanString(String str, int span) { this.str = str; this.span = span; } @Override public String toString() { return str; } } static class SpanRenderer extends TreeTable.StringCellRenderer { int span; @Override public void setCellData(int row, int column, Object data) { super.setCellData(row, column, data); span = ((SpanString) data).span; } @Override public int getColumnSpan() { return span; } } static class EditFieldCellRenderer implements TreeTable.CellWidgetCreator { private StringModel model; private int editFieldHeight; public Widget updateWidget(Widget existingWidget) { EditField ef = (EditField) existingWidget; if (ef == null) { ef = new EditField(); } ef.setModel(model); return ef; } public void positionWidget(Widget widget, int x, int y, int w, int h) { widget.setPosition(x, y); widget.setSize(w, h); } public void applyTheme(ThemeInfo themeInfo) { editFieldHeight = themeInfo.getParameter("editFieldHeight", 10); } public String getTheme() { return "EditFieldCellRenderer"; } public void setCellData(int row, int column, Object data) { this.model = (StringModel) data; } public int getColumnSpan() { return 1; } public int getPreferredHeight() { return editFieldHeight; } public Widget getCellRenderWidget(int x, int y, int width, int height, boolean isSelected) { return null; } } }
26.308511
80
0.700094
5aabbcc53072dc8a2234194ec55a954d929bbb6d
1,835
package com.lxk.jdk.http; import com.google.common.collect.Maps; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.lxk.tool.util.HttpUtils; import org.junit.Test; import java.io.IOException; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * http test * * @author LiXuekai on 2020/7/15 */ public class HttpTest { /** * post 带参数 */ @Test public void once() throws IOException { String url = "http://192.168.100.127:8088/refresh"; Map<String, String> paramMap = Maps.newHashMapWithExpectedSize(2); paramMap.put("type", "AsyncStream"); HttpUtils.HttpClientResult httpClientResult = HttpUtils.doPost(url, paramMap); System.out.println(httpClientResult.getCode()); System.out.println(httpClientResult.getContent()); } @Test public void testClose() { initCloseEvent(); System.out.println("----"); } /** * 在JVM销毁前执行的一个线程 */ private void initCloseEvent() { ScheduledExecutorService monitorSchedule = new ScheduledThreadPoolExecutor( 1, new ThreadFactoryBuilder().setNameFormat( "import-user-thread-pool-%d").build(), new ThreadPoolExecutor.AbortPolicy()); monitorSchedule.scheduleWithFixedDelay(this::importUerInfo, 0, 1, TimeUnit.HOURS); Runtime.getRuntime().addShutdownHook(new Thread("do-when-jvm-is-shut-down") { @Override public void run() { monitorSchedule.shutdown(); System.out.println("shutdown program"); } }); } private void importUerInfo() { System.out.println("import user"); } }
30.081967
206
0.671935
9f0cdfba0767c24aba08dcb62101854b5bb7117c
10,325
package com.kehua.energy.monitor.app.business.local.setting.pattern.patternModelChild; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.InputType; import android.view.View; import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.facade.annotation.Route; import com.chad.library.adapter.base.BaseQuickAdapter; import com.flyco.dialog.listener.OnBtnClickL; import com.gyf.barlibrary.ImmersionBar; import com.hwangjr.rxbus.RxBus; import com.hwangjr.rxbus.annotation.Subscribe; import com.hwangjr.rxbus.annotation.Tag; import com.hwangjr.rxbus.thread.EventThread; import com.kehua.energy.monitor.app.R; import com.kehua.energy.monitor.app.base.XMVPActivity; import com.kehua.energy.monitor.app.business.input.InputActivity; import com.kehua.energy.monitor.app.business.local.setting.advanced.AdvancedContract; import com.kehua.energy.monitor.app.business.local.setting.advanced.AdvancedPresenter; import com.kehua.energy.monitor.app.cache.CacheManager; import com.kehua.energy.monitor.app.configuration.Config; import com.kehua.energy.monitor.app.di.component.DaggerActivityComponent; import com.kehua.energy.monitor.app.di.module.ActivityModule; import com.kehua.energy.monitor.app.model.entity.DeviceData; import com.kehua.energy.monitor.app.model.entity.PointInfo; import com.kehua.energy.monitor.app.model.entity.SettingEntity; import com.kehua.energy.monitor.app.model.entity.Standard; import com.kehua.energy.monitor.app.route.RouterMgr; import com.kehua.energy.monitor.app.utils.Utils; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; import io.reactivex.functions.Consumer; import me.walten.fastgo.di.component.AppComponent; import me.walten.fastgo.utils.XToast; import me.walten.fastgo.widget.XEditText; import me.walten.fastgo.widget.titlebar.XTitleBar; @Route(path = RouterMgr.LOCAL_SETTING_PATTERN_CHILD) public class LocalPatternChildActivity extends XMVPActivity<LocalPatternChildPresenter> implements LocalPatternChildContract.View, BaseQuickAdapter.OnItemClickListener { @Autowired String sGroup; PatternChildAdapter mAdapter; @BindView(R.id.recycler_view) RecyclerView mRecyclerView; @Inject AdvancedPresenter mAdvancedPresenter; @Override public int getLayoutResId() { return R.layout.activity_local_pattern_child; } @Override public void initView(@Nullable Bundle savedInstanceState) { setFullScreen(); cancelFullScreen(); mTitleBar.setListener(new XTitleBar.OnTitleBarListener() { @Override public void onClicked(View v, int action, String extra) { if (action == XTitleBar.ACTION_LEFT_BUTTON) { finish(); } } }); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); } @Override public void initData(@Nullable Bundle savedInstanceState) { if (!mPresenter.dealData(sGroup)) { finish(); } mTitleBar.getCenterTextView().setText(sGroup); } @Override public void setupComponent(@NonNull AppComponent appComponent) { DaggerActivityComponent.builder() .appComponent(appComponent) .activityModule(new ActivityModule(this)) .build() .inject(this); } @Override protected boolean enableImmersive(ImmersionBar immersionBar) { //immersionBar.statusBarDarkFont(true); return false; } @Override public void setData(List<PointInfo> data) { if (mAdapter == null) { mAdapter = new PatternChildAdapter(data); mAdapter.setOnItemClickListener(this); mRecyclerView.setAdapter(mAdapter); } mAdapter.setNewData(data); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); RxBus.get().register(this); mAdvancedPresenter.attachView(new AdvancedContract.View() { @Override public void onSetupData(List<SettingEntity> data) { //do nothing } @Override public void onUpdateData(Object o) { LocalPatternChildActivity.this.onUpdateData(o); } @Override public void showTipDialog(String title, String content, OnBtnClickL onBtnClickL) { //do nothing } @Override public void onStandardChoose(Standard standard) { //do nothing } @Override public void showTipDialog(int opsStatus, String msg) { LocalPatternChildActivity.this.showTipDialog(opsStatus, msg); } @Override public void showTipDialog(String msg) { LocalPatternChildActivity.this.showTipDialog(msg); } @Override public void startWaiting(String msg) { LocalPatternChildActivity.this.startWaiting(msg); } @Override public void stopWaiting() { LocalPatternChildActivity.this.stopWaiting(); } @Override public void showToast(int opsStatus, String msg) { LocalPatternChildActivity.this.showToast(opsStatus, msg); } @Override public void showToast(String msg) { LocalPatternChildActivity.this.showToast(msg); } @Override public void finishView() { LocalPatternChildActivity.this.finishView(); } }); } @Override protected void onDestroy() { super.onDestroy(); RxBus.get().unregister(this); } @Override protected void onResume() { super.onResume(); onUpdateData(null); } @Override @Subscribe( thread = EventThread.MAIN_THREAD, tags = { @Tag(Config.EVENT_CODE_COLLECT_SETTING_COMPLETE) } ) public void onUpdateData(Object o) { if (mAdapter != null) mAdapter.notifyDataSetChanged(); } @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { final PointInfo pointInfo = mAdapter.getItem(position); int adress = Integer.parseInt(pointInfo.getAddress().trim()); final DeviceData deviceData = CacheManager.getInstance().get(adress); InputActivity.openInput(LocalPatternChildActivity.this, new InputActivity.InputConfig() { @Override public void customSetting(XEditText editText) { } @Override public String getTitle() { return deviceData != null ? deviceData.getDescription() : null; } @Override public String getOldMsg() { return deviceData != null ? deviceData.getParseValue() : null; } @Override public String getHintMsg() { return null; } @Override public int getDigits() { if (pointInfo.getAccuracy() > -1) { return pointInfo.getAccuracy(); } else return 0; } @Override public int getInputType() { if (deviceData != null && "string".equals(pointInfo.getDataType())) { return InputType.TYPE_CLASS_TEXT; } else if (deviceData != null && ("double".equals(pointInfo.getDataType()))) { return InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL; }else if(deviceData != null && "double_signed".equals(pointInfo.getDataType())){ return InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL ; }else if(deviceData != null && "int_signed".equals(pointInfo.getDataType())){ return InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_CLASS_NUMBER ; } else { return InputType.TYPE_CLASS_NUMBER; } } @Override public String check(String msg) { return null; } @Override public void onResult(final String msg) { try { if (!"string".equals(pointInfo.getDataType())) { mAdvancedPresenter.save(Integer.valueOf(pointInfo.getAddress()), Integer.valueOf(msg.trim()), new Consumer<Boolean>() { @Override public void accept(Boolean success) throws Exception { if (deviceData != null && success) { deviceData.setParseValue(Utils.parseAccuracy(Integer.valueOf(msg), deviceData.getAccuracy())); mAdapter.notifyDataSetChanged(); } } }); } else { mAdvancedPresenter.save(Integer.valueOf(pointInfo.getAddress()), Integer.valueOf(pointInfo.getAddress()) + pointInfo.getByteCount() / 2 - 1, msg, new Consumer<Boolean>() { @Override public void accept(Boolean success) throws Exception { if (deviceData != null && success) { deviceData.setParseValue(msg); mAdapter.notifyDataSetChanged(); } } }); } } catch (Exception e) { XToast.error(getString(R.string.设置失败)); } } }); } @OnClick(R.id.tv_submit) void submit() { finish(); } }
34.76431
195
0.600291
61534be8df32f505f06590343e60a9ae9820a6d0
3,469
/* * Copyright (C) 2018 QAware GmbH * * 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 de.qaware.chronix.solr.ingestion.format; import com.google.common.collect.Lists; import de.qaware.chronix.timeseries.MetricTimeSeries; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; public class GraphiteFormatParserTest { private GraphiteFormatParser sut; @Before public void setUp() throws Exception { sut = new GraphiteFormatParser(); } @Test public void testParse() throws Exception { try (InputStream stream = GraphiteFormatParserTest.class.getResourceAsStream("/graphite.txt")) { assertNotNull(stream); List<MetricTimeSeries> series = Lists.newArrayList(sut.parse(stream)); // We should have two metrics assertThat(series.size(), is(2)); // test.bash.stats has 5 timestamps with 5 values MetricTimeSeries bashSeries = series.get(0); assertThat(bashSeries.getName(), is("test.bash.stats")); assertThat(bashSeries.getTimestamps().size(), is(5)); assertThat(bashSeries.getTimestamps().get(0), is(1475754111000L)); assertThat(bashSeries.getTimestamps().get(1), is(1475754112000L)); assertThat(bashSeries.getTimestamps().get(2), is(1475754113000L)); assertThat(bashSeries.getTimestamps().get(3), is(1475754114000L)); assertThat(bashSeries.getTimestamps().get(4), is(1475754115000L)); assertThat(bashSeries.getValues().size(), is(5)); assertThat(bashSeries.getValues().get(0), is(1.0)); assertThat(bashSeries.getValues().get(1), is(2.0)); assertThat(bashSeries.getValues().get(2), is(3.0)); assertThat(bashSeries.getValues().get(3), is(4.0)); assertThat(bashSeries.getValues().get(4), is(5.0)); // test.ps.stats has 4 timestamps with 4 values MetricTimeSeries psSeries = series.get(1); assertThat(psSeries.getName(), is("test.ps.stats")); assertThat(psSeries.getTimestamps().size(), is(4)); assertThat(psSeries.getTimestamps().get(0), is(1475754116000L)); assertThat(psSeries.getTimestamps().get(1), is(1475754117000L)); assertThat(psSeries.getTimestamps().get(2), is(1475754118000L)); assertThat(psSeries.getTimestamps().get(3), is(1475754119000L)); assertThat(psSeries.getValues().size(), is(4)); assertThat(psSeries.getValues().get(0), is(6.0)); assertThat(psSeries.getValues().get(1), is(7.0)); assertThat(psSeries.getValues().get(2), is(8.0)); assertThat(psSeries.getValues().get(3), is(9.0)); } } }
43.3625
104
0.658115
243c81ebf283057887ca7b78a498a325c2a2ab8b
233
package net.petrikainulainen.spring.jooq.todo.exception; /** * @author Petri Kainulainen */ public class NotFoundException extends RuntimeException { public NotFoundException(String message) { super(message); } }
19.416667
57
0.729614
e1b5404b5a3bb209bc17de304de9ed50ea9e8cd1
3,479
/* * Bytecode Analysis Framework * Copyright (C) 2003,2004 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.ba.bcp; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionHandle; import edu.umd.cs.findbugs.annotations.SuppressWarnings; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.Edge; import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame; /** * A "meta" PatternElement that matches any of a list of other child * PatternElements. An example of how this is useful is that you might want to * match invocations of any of a number of different methods. To do this, you * can create a MatchAny with some number of Invoke elements as children. * <p/> * <p> * Note that the minOccur() and maxOccur() counts of the child PatternElements * are ignored. A MatchAny element always matches exactly one instruction. * * @author David Hovemeyer * @see PatternElement */ public class MatchAny extends PatternElement { private PatternElement[] childList; /** * Constructor. * * @param childList * list of child PatternElements */ @SuppressWarnings("EI2") public MatchAny(PatternElement[] childList) { this.childList = childList; } @Override public PatternElement label(String label) { for (PatternElement aChildList : childList) { aChildList.label(label); } return this; } @Override public PatternElement setAllowTrailingEdges(boolean allowTrailingEdges) { // Just forward this on to all children, // since it is the children that the PatternMatcher will ask // about edges. for (PatternElement aChildList : childList) aChildList.setAllowTrailingEdges(allowTrailingEdges); return this; } @Override public MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after, BindingSet bindingSet) throws DataflowAnalysisException { for (PatternElement child : childList) { MatchResult matchResult = child.match(handle, cpg, before, after, bindingSet); if (matchResult != null) return matchResult; } return null; } @Override public boolean acceptBranch(Edge edge, InstructionHandle source) { // Note: when selecting branch instructions, only the actual // (child) PatternElement should be used. throw new IllegalStateException("shouldn't happen"); } @Override public int minOccur() { return 1; } @Override public int maxOccur() { return 1; } } // vim:ts=4
31.917431
124
0.694165
5a7a46efa0ddceb4b39cdb8c1ace3cf0e5be5614
5,068
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.conveyal.r5.speed_test.api.model; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; import java.util.TimeZone; /** * An Itinerary is one complete way of getting from the start location to the end location. */ public class Itinerary { /** * Duration of the trip on this itinerary, in seconds. */ public Long duration = 0L; /** * Time that the trip departs. */ public Calendar startTime = null; /** * Time that the trip arrives. */ public Calendar endTime = null; /** * How much time is spent walking, in seconds. */ public long walkTime = 0; /** * How much time is spent on transit, in seconds. */ public long transitTime = 0; /** * How much time is spent waiting for transit to arrive, in seconds. */ public long waitingTime = 0; /** * How far the user has to walk, in meters. */ public Double walkDistance = 0.0; /** * Indicates that the walk limit distance has been exceeded for this itinerary when true. */ public boolean walkLimitExceeded = false; /** * How much elevation is lost, in total, over the course of the trip, in meters. As an example, * a trip that went from the top of Mount Everest straight down to sea level, then back up K2, * then back down again would have an elevationLost of Everest + K2. */ public Double elevationLost = 0.0; /** * How much elevation is gained, in total, over the course of the trip, in meters. See * elevationLost. */ public Double elevationGained = 0.0; /** * The number of transfers this trip has. */ public Integer transfers = 0; /** * The cost of this trip */ // public Fare fare = new Fare(); /** * Weight of the itinerary, used for debugging */ public double weight = 0; /** * A list of Legs. Each Leg is either a walking (cycling, car) portion of the trip, or a transit * trip on a particular vehicle. So a trip where the use walks to the Q train, transfers to the * 6, then walks to their destination, has four legs. */ @XmlElementWrapper(name = "legs") @XmlElement(name = "leg") public List<Leg> legs = new ArrayList<Leg>(); /** * This itinerary has a greater slope than the user requested (but there are no possible * itineraries with a good slope). */ public boolean tooSloped = false; /** * adds leg to array list * @param leg */ public void addLeg(Leg leg) { if(leg != null) { if(leg.isWalkLeg()) { walkDistance += leg.distance; } legs.add(leg); } } /** * remove the leg from the list of legs * @param leg object to be removed */ public void removeLeg(Leg leg) { if(leg != null) { legs.remove(leg); } } /* public void fixupDates(CalendarServiceData service) { TimeZone startTimeZone = null; TimeZone timeZone = null; Iterator<Leg> it = legs.iterator(); while (it.hasNext()) { Leg leg = it.next(); if (leg.agencyId == null) { if (timeZone != null) { leg.setTimeZone(timeZone); } } else { timeZone = service.getTimeZoneForAgencyId(leg.agencyId); if (startTimeZone == null) { startTimeZone = timeZone; } } } if (timeZone != null) { Calendar calendar = Calendar.getInstance(startTimeZone); calendar.setTime(startTime.getTime()); startTime = calendar; // go back and set timezone for legs prior to first transit it = legs.iterator(); while (it.hasNext()) { Leg leg = it.next(); if (leg.agencyId == null) { leg.setTimeZone(startTimeZone); } else { break; } } calendar = Calendar.getInstance(timeZone); calendar.setTime(endTime.getTime()); endTime = calendar; } } */ }
29.811765
100
0.589384
5819b54539ef133bdbb920b61cf5ba6e04c7ba1a
480
package au.csiro.eis.ontology.beans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.gwt.user.client.rpc.IsSerializable; public class RuleTextVarBean extends RuleVarBean implements Serializable, IsSerializable { /** * List of rule atoms */ private static final long serialVersionUID = 1L; public RuleTextVarBean() { } public RuleTextVarBean(String val) { super.value = val; } }
16
90
0.741667
864a103b5810e00a64af56cc403c8384f97c59a7
857
package com.belonk.dao; import com.belonk.pojo.MyEmployeeDTO; /** * Created by sun on 2018/6/24. * * @author sunfuchang03@126.com * @version 1.0 * @since 1.0 */ public interface CustomEmployeeDao { /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Constants/Initializer * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Interfaces * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ MyEmployeeDTO findByIdWithDepartment(Long id); }
25.969697
120
0.250875
ee2d2c550ad7547c80c274be911a93e4bb5709b5
89
/** * Clustered Counters API. * * @api.public */ package org.infinispan.counter.api;
12.714286
35
0.662921
c5775ae3f349bf552573e6869c723e9ed0ff68c5
2,268
/** * Copyright (c) 2018, http://www.snakeyaml.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.snakeyaml.engine.usecases.external_test_suite; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.snakeyaml.engine.v1.api.DumpSettingsBuilder; import org.snakeyaml.engine.v1.api.LoadSettingsBuilder; import org.snakeyaml.engine.v1.api.lowlevel.Compose; import org.snakeyaml.engine.v1.api.lowlevel.Present; @org.junit.jupiter.api.Tag("fast") class EmitSuiteTest { private List<SuiteData> all = SuiteUtils.getAll().stream() .filter(data -> !SuiteUtils.deviationsWithSuccess.contains(data.getName())) .filter(data -> !SuiteUtils.deviationsWithError.contains(data.getName())) .collect(Collectors.toList()); @Test @DisplayName("Emit test suite") void runAll(TestInfo testInfo) { for (SuiteData data : all) { ParseResult result = SuiteUtils.parseData(data); if (data.getError()) { assertTrue(result.getError().isPresent(), "Expected error, but got none in file " + data.getName() + ", " + data.getLabel() + "\n" + result.getEvents()); } else { Present emit = new Present(new DumpSettingsBuilder().build()); //emit without errors String yaml = emit.emitToString(result.getEvents().iterator()); //eat your own dog food new Compose(new LoadSettingsBuilder().build()).composeAllFromString(yaml); } } } }
39.103448
123
0.676367
9ec42da2d4e59fe9a22ca1ea076457c4cd9822e3
148
package mareksebera.cz.redditswipe; import androidx.appcompat.app.AppCompatActivity; public class SettingsActivity extends AppCompatActivity { }
18.5
57
0.844595
257af79336c7f2f6ac960385c17e77b434a9f77f
770
package com.android.open9527.okhttp.config; import com.android.open9527.okhttp.annotation.HttpIgnore; /** * @author open_9527 * Create at 2021/1/4 * <p> **/ public final class RequestServer implements IRequestServer { /** * 主机地址 */ @HttpIgnore private String mHost; /** * 接口路径 */ @HttpIgnore private String mPath; public RequestServer(String host) { this(host, ""); } public RequestServer(String host, String path) { mHost = host; mPath = path; } @Override public String getHost() { return mHost; } @Override public String getPath() { return mPath; } @Override public String toString() { return mHost + mPath; } }
16.382979
60
0.581818
0dbef3ff192afa28bbdd8f3a12a8f0ca116f24b1
1,779
package pe.joedayz.ventas.controller; import java.io.Serializable; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import pe.joedayz.ventas.model.Movimiento; import pe.joedayz.ventas.repository.MovimientoRepository; import pe.joedayz.ventas.service.NegocioException; import pe.joedayz.ventas.service.RegistroMovimientos; @Named @ViewScoped public class ConsultaMovimientosBean implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Inject private RegistroMovimientos registroMovimiento; @Inject private MovimientoRepository movimientoRepository; private List<Movimiento> movimientos; private Movimiento movimientoSeleccionado; public void consultar(){ this.movimientos = movimientoRepository.todos(); } public List<Movimiento> getMovimientos() { return movimientos; } public void setMovimientos(List<Movimiento> movimientos) { this.movimientos = movimientos; } public void eliminar(){ FacesContext context = FacesContext.getCurrentInstance(); try{ this.registroMovimiento.eliminar(this.movimientoSeleccionado); this.consultar(); context.addMessage(null, new FacesMessage("Movimiento eliminado con exito")); }catch(NegocioException ex){ FacesMessage mensaje = new FacesMessage(ex.getMessage()); mensaje.setSeverity(FacesMessage.SEVERITY_ERROR); context.addMessage(null, mensaje); } } public Movimiento getMovimientoSeleccionado() { return movimientoSeleccionado; } public void setMovimientoSeleccionado(Movimiento movimientoSeleccionado) { this.movimientoSeleccionado = movimientoSeleccionado; } }
23.407895
80
0.785835
109c60df979c2b9ea050bf58a1121039e01ecb14
1,773
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author qybit * @create 2020-12-02 16:51 */ public class Solution { public char slowestKey(int[] releaseTimes, String keysPressed) { int mx = releaseTimes[0]; char c = keysPressed.charAt(0); for (int i = 1; i < releaseTimes.length; i++) { int dif = releaseTimes[i] - releaseTimes[i-1]; if (dif > mx) { c = keysPressed.charAt(i); mx = dif; } else if (dif == mx && c < keysPressed.charAt(i)) { c = keysPressed.charAt(i); } } return c; } /* * 草 看错题了 public char slowestKey(int[] releaseTimes, String keysPressed) { int n = releaseTimes.length; Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { if (i == 0) { map.put(keysPressed.charAt(i), releaseTimes[i]); } if (i > 0) { map.put(keysPressed.charAt(i), releaseTimes[i]-releaseTimes[i-1]); } } List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet()); list.sort((o1, o2) -> { if (Integer.compare(o1.getValue(), o2.getValue()) == 0) { return Character.compare(o1.getKey(), o2.getKey()); } return Integer.compare(o1.getValue(), o2.getValue()); }); char res=' '; int mx = 0; for (Map.Entry<Character, Integer> entry : list) { if (mx < entry.getValue()) { res = entry.getKey(); mx = entry.getValue(); } } return res; } */ }
29.55
83
0.491822
09db3bafd0960478100029f8cd2e8bde83ada128
4,925
package pl.allegro.tech.hermes.consumers.supervisor.workload; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import pl.allegro.tech.hermes.api.SubscriptionName; import pl.allegro.tech.hermes.common.exception.InternalProcessingException; import java.util.List; import java.util.Optional; import static org.slf4j.LoggerFactory.getLogger; public class HierarchicalConsumerAssignmentRegistry implements ConsumerAssignmentRegistry, SubscriptionAssignmentAware { private static final Logger logger = getLogger(HierarchicalConsumerAssignmentRegistry.class); public static final byte[] AUTO_ASSIGNED_MARKER = "AUTO_ASSIGNED".getBytes(); private final CuratorFramework curator; private final SubscriptionAssignmentPathSerializer pathSerializer; private final ConsumerAssignmentCache assignmentCache; private final CreateMode assignmentNodeCreationMode; public HierarchicalConsumerAssignmentRegistry(CuratorFramework curator, ConsumerAssignmentCache assignmentCache, SubscriptionAssignmentPathSerializer pathSerializer, CreateMode assignmentNodeCreationMode) { this.curator = curator; this.pathSerializer = pathSerializer; this.assignmentCache = assignmentCache; this.assignmentNodeCreationMode = assignmentNodeCreationMode; this.assignmentCache.registerAssignmentCallback(this); } @Override public void onSubscriptionAssigned(SubscriptionName subscriptionName) { } @Override public void onAssignmentRemoved(SubscriptionName subscriptionName) { removeSubscriptionEntryIfEmpty(subscriptionName); } @Override public Optional<String> watchedConsumerId() { return Optional.empty(); } @Override public WorkDistributionChanges updateAssignments(SubscriptionAssignmentView initialState, SubscriptionAssignmentView targetState) { if (initialState.equals(targetState)) { return WorkDistributionChanges.NO_CHANGES; } List<SubscriptionAssignment> deletions = initialState.deletions(targetState).getAllAssignments(); List<SubscriptionAssignment> additions = initialState.additions(targetState).getAllAssignments(); deletions.forEach(this::dropAssignment); additions.forEach(this::addAssignment); return new WorkDistributionChanges(deletions.size(), additions.size()); } private void dropAssignment(SubscriptionAssignment assignment) { String message = String.format("Dropping assignment [consumer=%s, subscription=%s]", assignment.getConsumerNodeId(), assignment.getSubscriptionName().getQualifiedName()); logger.info(message); askCuratorPolitely(() -> curator.delete().guaranteed().forPath( pathSerializer.serialize(assignment.getSubscriptionName(), assignment.getConsumerNodeId())), message); } private void addAssignment(SubscriptionAssignment assignment) { String message = String.format("Adding assignment [consumer=%s, subscription=%s]", assignment.getConsumerNodeId(), assignment.getSubscriptionName().getQualifiedName()); logger.info(message); askCuratorPolitely(() -> { String path = pathSerializer.serialize(assignment.getSubscriptionName(), assignment.getConsumerNodeId()); curator.create().creatingParentsIfNeeded().withMode(assignmentNodeCreationMode) .forPath(path, AUTO_ASSIGNED_MARKER); }, message); } private void removeSubscriptionEntryIfEmpty(SubscriptionName subscriptionName) { String message = String.format("Removing empty assignment node [subscription=%s]", subscriptionName.getQualifiedName()); askCuratorPolitely(() -> { if (curator.getChildren().forPath(pathSerializer.serialize(subscriptionName)).isEmpty()) { logger.info(message); curator.delete().guaranteed().forPath(pathSerializer.serialize(subscriptionName)); } }, message); } interface CuratorTask { void run() throws Exception; } private void askCuratorPolitely(CuratorTask task, String description) { try { task.run(); } catch (KeeperException.NodeExistsException | KeeperException.NoNodeException ex) { logger.warn("An error occurred while writing to assignment registry, ignoring. Action: {}", description, ex); // ignore } catch (Exception ex) { logger.error("An error occurred while writing to assignment registry. Action: {}", description, ex); throw new InternalProcessingException(ex); } } }
43.201754
135
0.707817
b4f1019568537323f97f5831e2d1913bae991d41
3,430
/** * Copyright 2019 Anthony Trinh * * 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 ch.qos.logback.classic.net; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import javax.mail.Address; import javax.mail.MessagingException; import ch.qos.logback.core.helpers.CyclicBuffer; import ch.qos.logback.core.spi.CyclicBufferTracker; import org.junit.After; import org.junit.Before; import org.junit.Test; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.Layout; public class DilutedSMTPAppenderTest { SMTPAppender appender; CyclicBufferTracker<ILoggingEvent> cbTracker; CyclicBuffer<ILoggingEvent> cb; @Before public void setUp() throws Exception { LoggerContext lc = new LoggerContext(); appender = new SMTPAppender(); appender.setContext(lc); appender.setName("smtp"); appender.setFrom("user@host.dom"); appender.setLayout(buildLayout(lc)); appender.setSMTPHost("mail2.qos.ch"); appender.setSubject("logging report"); appender.addTo("sebastien.nospam@qos.ch"); appender.start(); cbTracker = appender.getCyclicBufferTracker(); cb = cbTracker.getOrCreate("", 0); } private static Layout<ILoggingEvent> buildLayout(LoggerContext lc) { PatternLayout layout = new PatternLayout(); layout.setContext(lc); layout.setFileHeader("Some header\n"); layout.setPattern("%-4relative [%thread] %-5level %class - %msg%n"); layout.setFileFooter("Some footer"); layout.start(); return layout; } @After public void tearDown() throws Exception { appender = null; } @Test public void testStart() { assertEquals("sebastien.nospam@qos.ch%nopex", appender.getToAsListOfString().get(0)); assertEquals("logging report", appender.getSubject()); assertTrue(appender.isStarted()); } @Test public void testAppendNonTriggeringEvent() { LoggingEvent event = new LoggingEvent(); event.setThreadName("thead name"); event.setLevel(Level.DEBUG); appender.subAppend(cb, event); assertEquals(1, cb.length()); } @Test public void testEntryConditionsCheck() { appender.checkEntryConditions(); assertEquals(0, appender.getContext().getStatusManager().getCount()); } @Test public void testTriggeringPolicy() { appender.setEvaluator(null); appender.checkEntryConditions(); assertEquals(1, appender.getContext().getStatusManager().getCount()); } @Test public void testEntryConditionsCheckNoLayout() { appender.setLayout(null); appender.checkEntryConditions(); assertEquals(1, appender.getContext().getStatusManager().getCount()); } }
29.067797
89
0.731778
cf56d87be82ed640935b09adfd36a231f114ea7b
2,138
package SecretMirrorNFS; import java.util.Scanner; public class SecretChat { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder concealedMessage = new StringBuilder(sc.nextLine()); String instruction = sc.nextLine(); while(!instruction.equals("Reveal")){ String[] tokens = instruction.split(":\\|:"); switch (tokens[0]){ case "InsertSpace": int index = Integer.parseInt(tokens[1]); concealedMessage.insert(index," "); System.out.println(concealedMessage); break; case "Reverse": String substring =tokens[1]; if(concealedMessage.indexOf(substring) == -1){ System.out.println("error"); }else{ concealedMessage.delete(concealedMessage.indexOf(substring),concealedMessage.indexOf(substring) + substring.length()); StringBuilder reversedSubstring = new StringBuilder(substring).reverse(); concealedMessage.append(reversedSubstring); System.out.println(concealedMessage); } break; case "ChangeAll": String substringToReplace = tokens[1]; String replacement = tokens[2]; int substringIndex = concealedMessage.indexOf(substringToReplace); while(substringIndex != -1){ concealedMessage.replace(substringIndex,substringIndex + substringToReplace.length(),replacement); substringIndex += replacement.length(); substringIndex = concealedMessage.indexOf(substringToReplace,substringIndex); } System.out.println(concealedMessage); break; } instruction = sc.nextLine(); } System.out.println("You have a new text message: " + concealedMessage); } }
45.489362
141
0.54116
5fff21878c4f171ee180475d45330299bbd29dfa
3,286
/* * Copyright (C) 2014 desrever <desrever at nubits.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.nubits.nubot.trading.keys; /** * * @author desrever < desrever@nubits.com > */ public class ApiPermissions { //Class Variables private boolean valid_keys; private boolean deposit; private boolean get_info; private boolean merchant; private boolean trade; private boolean withdraw; //Constructor public ApiPermissions() { } public ApiPermissions(boolean valid_keys, boolean deposit, boolean get_info, boolean merchant, boolean trade, boolean withdraw) { this.valid_keys = valid_keys; this.deposit = deposit; this.get_info = get_info; this.merchant = merchant; this.trade = trade; this.withdraw = withdraw; } //Methods /** * @return the valid_keys */ public boolean isValid_keys() { return valid_keys; } /** * @param valid_keys the valid_keys to set */ public void setValid_keys(boolean valid_keys) { this.valid_keys = valid_keys; } /** * @return the deposit */ public boolean isDeposit() { return deposit; } /** * @param deposit the deposit to set */ public void setDeposit(boolean deposit) { this.deposit = deposit; } /** * @return the get_info */ public boolean isGet_info() { return get_info; } /** * @param get_info the get_info to set */ public void setGet_info(boolean get_info) { this.get_info = get_info; } /** * @return the merchant */ public boolean isMerchant() { return merchant; } /** * @param merchant the merchant to set */ public void setMerchant(boolean merchant) { this.merchant = merchant; } /** * @return the trade */ public boolean isTrade() { return trade; } /** * @param trade the trade to set */ public void setTrade(boolean trade) { this.trade = trade; } /** * @return the withdraw */ public boolean isWithdraw() { return withdraw; } /** * @param withdraw the withdraw to set */ public void setWithdraw(boolean withdraw) { this.withdraw = withdraw; } @Override public String toString() { return "ApiPermissions{" + "valid_keys=" + valid_keys + ", deposit=" + deposit + ", get_info=" + get_info + ", merchant=" + merchant + ", trade=" + trade + ", withdraw=" + withdraw + '}'; } }
23.985401
195
0.617468
86f05598ddf6ef2df4a06ab2a254c46f1df2ce19
2,019
/* * 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.camel.quarkus.component.browse.it; import java.util.List; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ProducerTemplate; import org.apache.camel.spi.BrowsableEndpoint; @Path("/browse") public class BrowseResource { public static final String MESSAGE = "Hello World"; @Inject CamelContext context; @Inject ProducerTemplate template; @GET @Produces(MediaType.TEXT_PLAIN) public Response getBrowsedExchanges() throws Exception { template.sendBody("direct:browse", MESSAGE); BrowsableEndpoint browse = context.getEndpoint("browse:messageReceived", BrowsableEndpoint.class); List<Exchange> exchanges = browse.getExchanges(); if (exchanges.size() == 1) { String result = exchanges.get(0).getMessage().getBody(String.class); return Response.ok(result).build(); } throw new IllegalStateException("Expected 1 browsed exchange but got " + exchanges.size()); } }
33.65
106
0.732046
0e8fabd3eb663f809ca49d24062fd55e323ccc3a
2,057
package cn.android_mobile.core.net.http.yjweb; import java.util.Stack; import cn.android_mobile.core.net.http.Http; import cn.android_mobile.core.net.http.yjweb.task.BaseServiceAsyncTask; import cn.android_mobile.core.net.http.yjweb.task.DeleteAsyncTask; import cn.android_mobile.core.net.http.yjweb.task.DeleteFileAsyncTask; import cn.android_mobile.core.net.http.yjweb.task.InsertAsyncTask; import cn.android_mobile.core.net.http.yjweb.task.QueryAsyncTask; import cn.android_mobile.core.net.http.yjweb.task.UpdateAsyncTask; import cn.android_mobile.core.net.http.yjweb.task.UploadAsyncTask; import com.google.gson.reflect.TypeToken; public class WDao { private Stack<BaseServiceAsyncTask> tasks=new Stack<BaseServiceAsyncTask>(); public WDao(){ } public void query(Class<?> c,QueryCondition qc,TypeToken<?> type,IServiceListener listener){ QueryAsyncTask task=new QueryAsyncTask(c, qc, type); tasks.add(task); task.setListener(listener); task.execute(); } public void insert(Class<?> c,Object obj,IServiceListener listener){ InsertAsyncTask task=new InsertAsyncTask(c, obj); tasks.add(task); task.setListener(listener); task.execute(); } public void update(Class<?> c,Object obj,IServiceListener listener){ UpdateAsyncTask task=new UpdateAsyncTask(c, obj); tasks.add(task); task.setListener(listener); task.execute(); } public void delete(Class<?> c,String uuid,IServiceListener listener){ DeleteAsyncTask task=new DeleteAsyncTask(c, uuid); tasks.add(task); task.setListener(listener); task.execute(); } public void deleteFile(String fileUrl,IServiceListener listener){ DeleteFileAsyncTask task=new DeleteFileAsyncTask(fileUrl); tasks.add(task); task.setListener(listener); task.execute(); } public void upload(String filePath,IServiceListener listener){ UploadAsyncTask task=new UploadAsyncTask(filePath); tasks.add(task); task.setListener(listener); task.execute(); } public void cancel(){ for (BaseServiceAsyncTask task : tasks) { task.cancel(true); } tasks.clear(); } }
32.140625
93
0.772484
3d6a178d1958441c57af68c85332e29fec5ef38b
10,358
package cncleveler; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Logger; /** * Provides a method to interpolate a Z offset at a specific (X,Y) coordinate based on the probe * data. * * Processes raw probe values passed to the constructor into an internal grid format that allows for * easy querying and interpolation. The (X,Y) values are offset buy the work coordinate offset. And * Z is offset so that Z=0 at (X,Y) = (0,0). * */ public class ProbeGrid { private static final Logger logger = Logger.getLogger((Main.class.getName())); List<Point3> probes = null; protected int xsize = 0; protected int ysize = 0; protected Double[] xgrid; protected Double[] ygrid; protected Double[][] zprobe; /** * Constructor, which requires a list of Point3(x,y,z) probe values. Processes the values into a * internal arrays for easier interpolation. * * @param probePoints List of raw probe points */ public ProbeGrid(List<Point3> rawProbePoints) { logger.info("Creating Probe Grid"); // Offset probe values to work coordinates offsetProbes(rawProbePoints); makeXYgrids(); makeZprobes(); logProbeGrid(); logger.info("Probe Grid Complete"); } /** * Computes the Z probe offset for a given an (x,y) coordinate by linearly interpolating the Z * probe data in both X and Y. Some references called this "bilinear interpolation". * * <pre> * Algorithm: * 1. Determine the Z values at points at A,B,C,D in the four probe grid corners around * point G at target (x,y). * A is at coordinates (xgrid[i], ygrid[j]). * B is at coordinates (xgrid[i], ygrid[j+1]). * C is at coordinates (xgrid[i+1],ygrid[j]). * D is at coordinates (xgrid[i+1],ygrid[j+1]). * 2. Linearly interpolate in Y between Z values at points A and B to obtain z_left * at point E at coordinates (xgrid[i], y). * 3. Linearly interpolate in Y between Z values at points C and D to obtain z_right * at point F at coordinates (xgrid[i+1], y). * 4. Linearly interpolate in X between z_left and z_right to obtain Z at point G at (X,Y). * * B D * | | * | | * | (x,y) | * z_left E-----G---------F z_right * | | * A C * * Note: Algebraically, it does not matter if we interpolate in X first between (A,C) and (B,D) * or Y first between (A,B) and (C,D). The result is the same. * * For values outside the grid (in either x or y), the closest 4 points within the grid are used * to extrapolate outside the grid. * </pre> * * @param x The X coordinate to use in interpolation * @param y The Y coordinate to use in interpolation * @return the interpolated Z value */ public double getProbeHeight(double x, double y) { double z1, z2; int i = findGridIndex(xgrid, x); int j = findGridIndex(ygrid, y); double y_ratio = (y - ygrid[j]) / (ygrid[j + 1] - ygrid[j]); // linear interpolate in y on left side; z1 = zprobe[j][i]; z2 = zprobe[j + 1][i]; double z_left = z1 + (z2 - z1) * y_ratio; // linear interpolate in y on right side; z1 = zprobe[j][i + 1]; z2 = zprobe[j + 1][i + 1]; double z_right = z1 + (z2 - z1) * y_ratio; double x_ratio = (x - xgrid[i]) / (xgrid[i + 1] - xgrid[i]); // linear interpolate in x between left and right sides; double z = z_left + (z_right - z_left) * x_ratio; return z; } /** * Given an array of n grid values and a value v, returns i such that grid[i] <= v < grid[i+1]. * For out-of-bounds values, returns 0 if v <= grid[0] or (n-2) if v >= grid[n-1]. Both the * returned value i and (i+1) will valid index to the array. * * @param grid a sorted array of grid values * @param v a value to search for * @return an index i such that grid[i] <= v < grid[i+1] */ private int findGridIndex(Double[] grid, double v) { int n = grid.length; for (int i = 1; i < n; i++) { if (v <= grid[i]) return i - 1; } return n - 2; } /** * Offsets each probe point to the Work Coordinate System (G54 .. G59) * * @param rawProbePoints the probe points from the GRBL log file in machine coordinates */ private void offsetProbes(List<Point3> rawProbePoints) { logger.info(" Offseting to probe grid by " + Config.probe_offset); probes = new ArrayList<Point3>(rawProbePoints.size()); for (Point3 p : rawProbePoints) { probes.add(p.relativeTo(Config.probe_offset)); } } /** * Creates the X grid and Y grid arrays from the raw probe data provided to the class * constructor. They contain the unique x and unique y values in sorted order to facilitate * indexing into the Z Probe array. */ private void makeXYgrids() { // Use a sorted set to get unique X and Y values in sorted order SortedSet<Double> xvalues = new TreeSet<Double>(); SortedSet<Double> yvalues = new TreeSet<Double>(); for (Point3 probe : probes) { xvalues.add(probe.x); yvalues.add(probe.y); } // Record the grid sizes xsize = xvalues.size(); ysize = yvalues.size(); // Convert to arrays for indexing xgrid = new Double[xsize]; ygrid = new Double[ysize]; xgrid = xvalues.toArray(xgrid); ygrid = yvalues.toArray(ygrid); // Because these are Doubles, check for near duplicate values as a sanity check. // For example, 15.0 and 14.999999999 checkForDuplicates(xgrid, "X"); checkForDuplicates(ygrid, "Y"); } /** * Creates the Z probe 2-dimensional array using the same index values as the xgrid and ygrid * arrays */ private void makeZprobes() { zprobe = new Double[ysize][xsize]; for (int i = 0; i < xsize; i++) { double x = xgrid[i]; for (int j = 0; j < ysize; j++) { double y = ygrid[j]; // find the z value at this (x,y) position zprobe[j][i] = Double.NaN; for (Point3 probe : probes) { if ((probe.x == x) && (probe.y == y)) { zprobe[j][i] = probe.z; break; } } if (Double.isNaN(zprobe[j][i])) { logger.severe(String.format("Missing Probe value at [%d,%d] (%.3f,%.3f)", i, j, x, y)); } } } // Offset so that Z = 0 at (x,y) = (0,0) double zOffset = getProbeHeight(0.0, 0.0); logger.info(String.format("Z offset = %.3f", zOffset)); // offset all probe values for (int i = 0; i < xsize; i++) { for (int j = 0; j < ysize; j++) { if (!Double.isNaN(zprobe[j][i])) { zprobe[j][i] -= zOffset; } } } } /** * Reviews the xgrid and ygrid array to check for near duplicates. Because the coordinate values * are floating point numbers reported by GRBL, there is a chance of round-off error in the * reported x or y coordinates. For example 15.0 and 14.999999999. This function checks for and * reports pairs of x or y coordinates that are less than 0.1 from each other. Results are * reported to the logger as a warning. */ private void checkForDuplicates(Double[] grid, String axis) { double prev = Double.NEGATIVE_INFINITY; for (double v : grid) { // We will never probe with less than a 0.01 mm [0.4 mil] grid if ((v - prev) < 0.01) { logger.warning(String.format("Near duplicate %s-Axis probe values: %.6f, %.6f", axis, prev, v)); } prev = v; } } /** * Prints the X and Y Grid and Z-probe array to the log file. */ private void logProbeGrid() { logger.info(" X grid size: " + xsize); logger.fine(" X grid = "); logger.fine(" " + arrayToString(xgrid)); logger.info(" Y grid size: " + ysize); logger.fine(" Y grid = "); logger.fine(" " + arrayToString(ygrid)); logger.fine(" Z probes = "); for (int j = 0; j < ysize; j++) { Double[] row = new Double[xsize]; for (int i = 0; i < xsize; i++) { row[i] = zprobe[j][i]; } logger.fine(" " + arrayToString(row)); } // Log the min/max value for each axis double maxZ = Double.NEGATIVE_INFINITY; double minZ = Double.POSITIVE_INFINITY; for (int j = 0; j < ysize; j++) { for (int i = 0; i < xsize; i++) { double z = zprobe[j][i]; minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z); } } Point3 min = new Point3(xgrid[0], ygrid[0], minZ); Point3 max = new Point3(xgrid[xsize - 1], ygrid[ysize - 1], maxZ); logger.info(" Min Z: " + min); logger.info(" Max Z: " + max); } /** * Converts an array of double to a printable string. * * @param grid array to convert */ private String arrayToString(Double[] grid) { StringBuilder sb = new StringBuilder(); sb.append("["); Boolean first = true; for (int i = 0; i < grid.length; i++) { if (!first) sb.append(", "); sb.append(String.format("%8.3f", grid[i])); first = false; } sb.append("]"); return sb.toString(); } }
32.572327
112
0.531859
9fa8a5d2faee06e9c597a4626afab450954c0ea4
21,024
/* * Copyright (C) 2008 The Android Open Source 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 android.app; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemProperties; import android.provider.Settings; import android.util.Printer; import android.util.Slog; import com.android.internal.util.FastPrintWriter; import java.io.PrintWriter; import java.io.StringWriter; /** * Describes an application error. * * A report has a type, which is one of * <ul> * <li> {@link #TYPE_NONE} uninitialized instance of {@link ApplicationErrorReport}. * <li> {@link #TYPE_CRASH} application crash. Information about the crash * is stored in {@link #crashInfo}. * <li> {@link #TYPE_ANR} application not responding. Information about the * ANR is stored in {@link #anrInfo}. * <li> {@link #TYPE_BATTERY} user reported application is using too much * battery. Information about the battery use is stored in {@link #batteryInfo}. * <li> {@link #TYPE_RUNNING_SERVICE} user reported application is leaving an * unneeded serive running. Information about the battery use is stored in * {@link #runningServiceInfo}. * </ul> */ public class ApplicationErrorReport implements Parcelable { // System property defining error report receiver for system apps static final String SYSTEM_APPS_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.system.apps"; // System property defining default error report receiver static final String DEFAULT_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.default"; /** * Uninitialized error report. */ public static final int TYPE_NONE = 0; /** * An error report about an application crash. */ public static final int TYPE_CRASH = 1; /** * An error report about an application that's not responding. */ public static final int TYPE_ANR = 2; /** * An error report about an application that's consuming too much battery. */ public static final int TYPE_BATTERY = 3; /** * A report from a user to a developer about a running service that the * user doesn't think should be running. */ public static final int TYPE_RUNNING_SERVICE = 5; /** * Type of this report. Can be one of {@link #TYPE_NONE}, * {@link #TYPE_CRASH}, {@link #TYPE_ANR}, {@link #TYPE_BATTERY}, * or {@link #TYPE_RUNNING_SERVICE}. */ public int type; /** * Package name of the application. */ public String packageName; /** * Package name of the application which installed the application this * report pertains to. * This identifies which market the application came from. */ public String installerPackageName; /** * Process name of the application. */ public String processName; /** * Time at which the error occurred. */ public long time; /** * Set if the app is on the system image. */ public boolean systemApp; /** * If this report is of type {@link #TYPE_CRASH}, contains an instance * of CrashInfo describing the crash; otherwise null. */ public CrashInfo crashInfo; /** * If this report is of type {@link #TYPE_ANR}, contains an instance * of AnrInfo describing the ANR; otherwise null. */ public AnrInfo anrInfo; /** * If this report is of type {@link #TYPE_BATTERY}, contains an instance * of BatteryInfo; otherwise null. */ public BatteryInfo batteryInfo; /** * If this report is of type {@link #TYPE_RUNNING_SERVICE}, contains an instance * of RunningServiceInfo; otherwise null. */ public RunningServiceInfo runningServiceInfo; /** * Create an uninitialized instance of {@link ApplicationErrorReport}. */ public ApplicationErrorReport() { } /** * Create an instance of {@link ApplicationErrorReport} initialized from * a parcel. */ ApplicationErrorReport(Parcel in) { readFromParcel(in); } public static ComponentName getErrorReportReceiver(Context context, String packageName, int appFlags) { // check if error reporting is enabled in secure settings int enabled = Settings.Global.getInt(context.getContentResolver(), Settings.Global.SEND_ACTION_APP_ERROR, 0); if (enabled == 0) { return null; } PackageManager pm = context.getPackageManager(); // look for receiver in the installer package String candidate = null; ComponentName result = null; try { candidate = pm.getInstallerPackageName(packageName); } catch (IllegalArgumentException e) { // the package could already removed } if (candidate != null) { result = getErrorReportReceiver(pm, packageName, candidate); if (result != null) { return result; } } // if the error app is on the system image, look for system apps // error receiver if ((appFlags&ApplicationInfo.FLAG_SYSTEM) != 0) { candidate = SystemProperties.get(SYSTEM_APPS_ERROR_RECEIVER_PROPERTY); result = getErrorReportReceiver(pm, packageName, candidate); if (result != null) { return result; } } // if there is a default receiver, try that candidate = SystemProperties.get(DEFAULT_ERROR_RECEIVER_PROPERTY); return getErrorReportReceiver(pm, packageName, candidate); } /** * Return activity in receiverPackage that handles ACTION_APP_ERROR. * * @param pm PackageManager instance * @param errorPackage package which caused the error * @param receiverPackage candidate package to receive the error * @return activity component within receiverPackage which handles * ACTION_APP_ERROR, or null if not found */ static ComponentName getErrorReportReceiver(PackageManager pm, String errorPackage, String receiverPackage) { if (receiverPackage == null || receiverPackage.length() == 0) { return null; } // break the loop if it's the error report receiver package that crashed if (receiverPackage.equals(errorPackage)) { return null; } Intent intent = new Intent(Intent.ACTION_APP_ERROR); intent.setPackage(receiverPackage); ResolveInfo info = pm.resolveActivity(intent, 0); if (info == null || info.activityInfo == null) { return null; } return new ComponentName(receiverPackage, info.activityInfo.name); } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(type); dest.writeString(packageName); dest.writeString(installerPackageName); dest.writeString(processName); dest.writeLong(time); dest.writeInt(systemApp ? 1 : 0); dest.writeInt(crashInfo != null ? 1 : 0); switch (type) { case TYPE_CRASH: if (crashInfo != null) { crashInfo.writeToParcel(dest, flags); } break; case TYPE_ANR: anrInfo.writeToParcel(dest, flags); break; case TYPE_BATTERY: batteryInfo.writeToParcel(dest, flags); break; case TYPE_RUNNING_SERVICE: runningServiceInfo.writeToParcel(dest, flags); break; } } public void readFromParcel(Parcel in) { type = in.readInt(); packageName = in.readString(); installerPackageName = in.readString(); processName = in.readString(); time = in.readLong(); systemApp = in.readInt() == 1; boolean hasCrashInfo = in.readInt() == 1; switch (type) { case TYPE_CRASH: crashInfo = hasCrashInfo ? new CrashInfo(in) : null; anrInfo = null; batteryInfo = null; runningServiceInfo = null; break; case TYPE_ANR: anrInfo = new AnrInfo(in); crashInfo = null; batteryInfo = null; runningServiceInfo = null; break; case TYPE_BATTERY: batteryInfo = new BatteryInfo(in); anrInfo = null; crashInfo = null; runningServiceInfo = null; break; case TYPE_RUNNING_SERVICE: batteryInfo = null; anrInfo = null; crashInfo = null; runningServiceInfo = new RunningServiceInfo(in); break; } } /** * Describes an application crash. */ public static class CrashInfo { /** * Class name of the exception that caused the crash. */ public String exceptionClassName; /** * Message stored in the exception. */ public String exceptionMessage; /** * File which the exception was thrown from. */ public String throwFileName; /** * Class which the exception was thrown from. */ public String throwClassName; /** * Method which the exception was thrown from. */ public String throwMethodName; /** * Line number the exception was thrown from. */ public int throwLineNumber; /** * Stack trace. */ public String stackTrace; /** * Create an uninitialized instance of CrashInfo. */ public CrashInfo() { } /** * Create an instance of CrashInfo initialized from an exception. */ public CrashInfo(Throwable tr) { StringWriter sw = new StringWriter(); PrintWriter pw = new FastPrintWriter(sw, false, 256); tr.printStackTrace(pw); pw.flush(); stackTrace = sanitizeString(sw.toString()); exceptionMessage = tr.getMessage(); // Populate fields with the "root cause" exception Throwable rootTr = tr; while (tr.getCause() != null) { tr = tr.getCause(); if (tr.getStackTrace() != null && tr.getStackTrace().length > 0) { rootTr = tr; } String msg = tr.getMessage(); if (msg != null && msg.length() > 0) { exceptionMessage = msg; } } exceptionClassName = rootTr.getClass().getName(); if (rootTr.getStackTrace().length > 0) { StackTraceElement trace = rootTr.getStackTrace()[0]; throwFileName = trace.getFileName(); throwClassName = trace.getClassName(); throwMethodName = trace.getMethodName(); throwLineNumber = trace.getLineNumber(); } else { throwFileName = "unknown"; throwClassName = "unknown"; throwMethodName = "unknown"; throwLineNumber = 0; } exceptionMessage = sanitizeString(exceptionMessage); } /** * Ensure that the string is of reasonable size, truncating from the middle if needed. */ private String sanitizeString(String s) { int prefixLength = 10 * 1024; int suffixLength = 10 * 1024; int acceptableLength = prefixLength + suffixLength; if (s != null && s.length() > acceptableLength) { String replacement = "\n[TRUNCATED " + (s.length() - acceptableLength) + " CHARS]\n"; StringBuilder sb = new StringBuilder(acceptableLength + replacement.length()); sb.append(s.substring(0, prefixLength)); sb.append(replacement); sb.append(s.substring(s.length() - suffixLength)); return sb.toString(); } return s; } /** * Create an instance of CrashInfo initialized from a Parcel. */ public CrashInfo(Parcel in) { exceptionClassName = in.readString(); exceptionMessage = in.readString(); throwFileName = in.readString(); throwClassName = in.readString(); throwMethodName = in.readString(); throwLineNumber = in.readInt(); stackTrace = in.readString(); } /** * Save a CrashInfo instance to a parcel. */ public void writeToParcel(Parcel dest, int flags) { int start = dest.dataPosition(); dest.writeString(exceptionClassName); dest.writeString(exceptionMessage); dest.writeString(throwFileName); dest.writeString(throwClassName); dest.writeString(throwMethodName); dest.writeInt(throwLineNumber); dest.writeString(stackTrace); int total = dest.dataPosition()-start; if (total > 20*1024) { Slog.d("Error", "ERR: exClass=" + exceptionClassName); Slog.d("Error", "ERR: exMsg=" + exceptionMessage); Slog.d("Error", "ERR: file=" + throwFileName); Slog.d("Error", "ERR: class=" + throwClassName); Slog.d("Error", "ERR: method=" + throwMethodName + " line=" + throwLineNumber); Slog.d("Error", "ERR: stack=" + stackTrace); Slog.d("Error", "ERR: TOTAL BYTES WRITTEN: " + (dest.dataPosition()-start)); } } /** * Dump a CrashInfo instance to a Printer. */ public void dump(Printer pw, String prefix) { pw.println(prefix + "exceptionClassName: " + exceptionClassName); pw.println(prefix + "exceptionMessage: " + exceptionMessage); pw.println(prefix + "throwFileName: " + throwFileName); pw.println(prefix + "throwClassName: " + throwClassName); pw.println(prefix + "throwMethodName: " + throwMethodName); pw.println(prefix + "throwLineNumber: " + throwLineNumber); pw.println(prefix + "stackTrace: " + stackTrace); } } /** * Describes an application not responding error. */ public static class AnrInfo { /** * Activity name. */ public String activity; /** * Description of the operation that timed out. */ public String cause; /** * Additional info, including CPU stats. */ public String info; /** * Create an uninitialized instance of AnrInfo. */ public AnrInfo() { } /** * Create an instance of AnrInfo initialized from a Parcel. */ public AnrInfo(Parcel in) { activity = in.readString(); cause = in.readString(); info = in.readString(); } /** * Save an AnrInfo instance to a parcel. */ public void writeToParcel(Parcel dest, int flags) { dest.writeString(activity); dest.writeString(cause); dest.writeString(info); } /** * Dump an AnrInfo instance to a Printer. */ public void dump(Printer pw, String prefix) { pw.println(prefix + "activity: " + activity); pw.println(prefix + "cause: " + cause); pw.println(prefix + "info: " + info); } } /** * Describes a battery usage report. */ public static class BatteryInfo { /** * Percentage of the battery that was used up by the process. */ public int usagePercent; /** * Duration in microseconds over which the process used the above * percentage of battery. */ public long durationMicros; /** * Dump of various info impacting battery use. */ public String usageDetails; /** * Checkin details. */ public String checkinDetails; /** * Create an uninitialized instance of BatteryInfo. */ public BatteryInfo() { } /** * Create an instance of BatteryInfo initialized from a Parcel. */ public BatteryInfo(Parcel in) { usagePercent = in.readInt(); durationMicros = in.readLong(); usageDetails = in.readString(); checkinDetails = in.readString(); } /** * Save a BatteryInfo instance to a parcel. */ public void writeToParcel(Parcel dest, int flags) { dest.writeInt(usagePercent); dest.writeLong(durationMicros); dest.writeString(usageDetails); dest.writeString(checkinDetails); } /** * Dump a BatteryInfo instance to a Printer. */ public void dump(Printer pw, String prefix) { pw.println(prefix + "usagePercent: " + usagePercent); pw.println(prefix + "durationMicros: " + durationMicros); pw.println(prefix + "usageDetails: " + usageDetails); pw.println(prefix + "checkinDetails: " + checkinDetails); } } /** * Describes a running service report. */ public static class RunningServiceInfo { /** * Duration in milliseconds that the service has been running. */ public long durationMillis; /** * Dump of debug information about the service. */ public String serviceDetails; /** * Create an uninitialized instance of RunningServiceInfo. */ public RunningServiceInfo() { } /** * Create an instance of RunningServiceInfo initialized from a Parcel. */ public RunningServiceInfo(Parcel in) { durationMillis = in.readLong(); serviceDetails = in.readString(); } /** * Save a RunningServiceInfo instance to a parcel. */ public void writeToParcel(Parcel dest, int flags) { dest.writeLong(durationMillis); dest.writeString(serviceDetails); } /** * Dump a BatteryInfo instance to a Printer. */ public void dump(Printer pw, String prefix) { pw.println(prefix + "durationMillis: " + durationMillis); pw.println(prefix + "serviceDetails: " + serviceDetails); } } public static final Parcelable.Creator<ApplicationErrorReport> CREATOR = new Parcelable.Creator<ApplicationErrorReport>() { public ApplicationErrorReport createFromParcel(Parcel source) { return new ApplicationErrorReport(source); } public ApplicationErrorReport[] newArray(int size) { return new ApplicationErrorReport[size]; } }; public int describeContents() { return 0; } /** * Dump the report to a Printer. */ public void dump(Printer pw, String prefix) { pw.println(prefix + "type: " + type); pw.println(prefix + "packageName: " + packageName); pw.println(prefix + "installerPackageName: " + installerPackageName); pw.println(prefix + "processName: " + processName); pw.println(prefix + "time: " + time); pw.println(prefix + "systemApp: " + systemApp); switch (type) { case TYPE_CRASH: crashInfo.dump(pw, prefix); break; case TYPE_ANR: anrInfo.dump(pw, prefix); break; case TYPE_BATTERY: batteryInfo.dump(pw, prefix); break; case TYPE_RUNNING_SERVICE: runningServiceInfo.dump(pw, prefix); break; } } }
32.09771
95
0.574677
ad03ab3df40849665706d6aa17a68659f24336d2
2,315
package home.smart.fly.animations.activity.transtions; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.StackView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import home.smart.fly.animations.R; import home.smart.fly.animations.utils.Tools; public class StackViewActivity extends AppCompatActivity { private Context mContext; @BindView(R.id.stackView) StackView mStackView; // private List<String> pics = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; setContentView(R.layout.activity_stack_view); ButterKnife.bind(this); initData(); mStackView.setAdapter(new ImageAdapter(pics, mContext)); } private class ImageAdapter extends BaseAdapter { private List<String> pics = new ArrayList<>(); private Context mContext; public ImageAdapter(List<String> pics, Context context) { this.pics = pics; mContext = context; } @Override public int getCount() { return this.pics.size(); } @Override public Object getItem(int position) { return this.pics.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView mImageView = new ImageView(mContext); // Glide.with(mContext).load(pics.get(position)).placeholder(R.drawable.a5).into(mImageView); mImageView.setImageResource(R.drawable.a5); return mImageView; } } private void initData() { String json = Tools.readStrFromAssets("pics.json", mContext); Gson gson = new Gson(); pics = gson.fromJson(json, new TypeToken<List<String>>() { }.getType()); } }
27.559524
104
0.662635
521c68ca3e8240ac8fe149f4125a046eb0898a4c
13,374
package com.sap.cloud.lm.sl.cf.process.steps; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.collections4.CollectionUtils; import org.cloudfoundry.client.lib.CloudControllerClient; import org.cloudfoundry.client.lib.domain.CloudApplication; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import com.sap.cloud.lm.sl.cf.client.lib.domain.CloudServiceInstanceExtended; import com.sap.cloud.lm.sl.cf.core.cf.v2.ApplicationCloudModelBuilder; import com.sap.cloud.lm.sl.cf.core.helpers.ModuleToDeployHelper; import com.sap.cloud.lm.sl.cf.core.model.ConfigurationSubscription; import com.sap.cloud.lm.sl.cf.core.model.DeployedMta; import com.sap.cloud.lm.sl.cf.core.model.DeployedMtaApplication; import com.sap.cloud.lm.sl.cf.core.model.DeployedMtaService; import com.sap.cloud.lm.sl.cf.core.persistence.service.ConfigurationSubscriptionService; import com.sap.cloud.lm.sl.cf.core.security.serialization.SecureSerialization; import com.sap.cloud.lm.sl.cf.process.Messages; import com.sap.cloud.lm.sl.cf.process.variables.Variables; import com.sap.cloud.lm.sl.mta.model.DeploymentDescriptor; import com.sap.cloud.lm.sl.mta.model.Module; @Named("buildCloudUndeployModelStep") @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class BuildCloudUndeployModelStep extends SyncFlowableStep { @Inject private ConfigurationSubscriptionService configurationSubscriptionService; @Inject private ModuleToDeployHelper moduleToDeployHelper; @Override protected StepPhase executeStep(ProcessContext context) { getStepLogger().debug(Messages.BUILDING_CLOUD_UNDEPLOY_MODEL); DeployedMta deployedMta = context.getVariable(Variables.DEPLOYED_MTA); if (deployedMta == null) { setComponentsToUndeploy(context, Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); return StepPhase.DONE; } List<String> deploymentDescriptorModules = getDeploymentDescriptorModules(context); List<ConfigurationSubscription> subscriptionsToCreate = context.getVariable(Variables.SUBSCRIPTIONS_TO_CREATE); Set<String> mtaModules = context.getVariable(Variables.MTA_MODULES); List<String> appNames = context.getVariable(Variables.APPS_TO_DEPLOY); List<String> serviceNames = getServicesToCreate(context); getStepLogger().debug(Messages.MTA_MODULES, mtaModules); List<DeployedMtaApplication> deployedAppsToUndeploy = computeModulesToUndeploy(deployedMta, mtaModules, appNames, deploymentDescriptorModules); getStepLogger().debug(Messages.MODULES_TO_UNDEPLOY, SecureSerialization.toJson(deployedAppsToUndeploy)); List<DeployedMtaApplication> appsWithoutChange = computeModulesWithoutChange(deployedAppsToUndeploy, mtaModules, deployedMta); getStepLogger().debug(Messages.MODULES_NOT_TO_BE_CHANGED, SecureSerialization.toJson(appsWithoutChange)); List<ConfigurationSubscription> subscriptionsToDelete = computeSubscriptionsToDelete(subscriptionsToCreate, deployedMta, context.getVariable(Variables.SPACE_GUID)); getStepLogger().debug(Messages.SUBSCRIPTIONS_TO_DELETE, SecureSerialization.toJson(subscriptionsToDelete)); Set<String> servicesForApplications = getServicesForApplications(context); List<String> servicesToDelete = computeServicesToDelete(appsWithoutChange, deployedMta.getServices(), servicesForApplications, serviceNames); getStepLogger().debug(Messages.SERVICES_TO_DELETE, servicesToDelete); List<CloudApplication> appsToUndeploy = computeAppsToUndeploy(deployedAppsToUndeploy, context.getControllerClient()); getStepLogger().debug(Messages.APPS_TO_UNDEPLOY, SecureSerialization.toJson(appsToUndeploy)); setComponentsToUndeploy(context, servicesToDelete, appsToUndeploy, subscriptionsToDelete); getStepLogger().debug(Messages.CLOUD_UNDEPLOY_MODEL_BUILT); return StepPhase.DONE; } @Override protected String getStepErrorMessage(ProcessContext context) { return Messages.ERROR_BUILDING_CLOUD_UNDEPLOY_MODEL; } private List<String> getDeploymentDescriptorModules(ProcessContext context) { DeploymentDescriptor deploymentDescriptor = context.getVariable(Variables.COMPLETE_DEPLOYMENT_DESCRIPTOR); if (deploymentDescriptor == null) { return Collections.emptyList(); } return deploymentDescriptor.getModules() .stream() .map(Module::getName) .collect(Collectors.toList()); } private List<String> getServicesToCreate(ProcessContext context) { return context.getVariable(Variables.SERVICES_TO_CREATE) .stream() .map(CloudServiceInstanceExtended::getName) .collect(Collectors.toList()); } private Set<String> getServicesForApplications(ProcessContext context) { List<Module> modules = context.getVariable(Variables.MODULES_TO_DEPLOY); if (CollectionUtils.isEmpty(modules)) { return Collections.emptySet(); } Set<String> servicesForApplications = new HashSet<>(); ApplicationCloudModelBuilder applicationCloudModelBuilder = getApplicationCloudModelBuilder(context); for (Module module : modules) { if (moduleToDeployHelper.isApplication(module)) { servicesForApplications.addAll(applicationCloudModelBuilder.getAllApplicationServices(module)); } } return servicesForApplications; } private List<DeployedMtaApplication> computeModulesWithoutChange(List<DeployedMtaApplication> modulesToUndeploy, Set<String> mtaModules, DeployedMta deployedMta) { return deployedMta.getApplications() .stream() .filter(existingModule -> shouldNotUndeployModule(modulesToUndeploy, existingModule)) .filter(existingModule -> shouldNotDeployModule(mtaModules, existingModule)) .collect(Collectors.toList()); } private boolean shouldNotUndeployModule(List<DeployedMtaApplication> modulesToUndeploy, DeployedMtaApplication existingModule) { String existingModuleName = existingModule.getModuleName(); return modulesToUndeploy.stream() .map(DeployedMtaApplication::getModuleName) .noneMatch(existingModuleName::equals); } private boolean shouldNotDeployModule(Set<String> mtaModules, DeployedMtaApplication existingModule) { String existingModuleName = existingModule.getModuleName(); return mtaModules.stream() .noneMatch(existingModuleName::equals); } private void setComponentsToUndeploy(ProcessContext context, List<String> services, List<CloudApplication> apps, List<ConfigurationSubscription> subscriptions) { context.setVariable(Variables.SUBSCRIPTIONS_TO_DELETE, subscriptions); context.setVariable(Variables.SERVICES_TO_DELETE, services); context.setVariable(Variables.APPS_TO_UNDEPLOY, apps); } private List<String> computeServicesToDelete(List<DeployedMtaApplication> appsWithoutChange, List<DeployedMtaService> deployedMtaServices, Set<String> servicesForApplications, List<String> servicesForCurrentDeployment) { return deployedMtaServices.stream() .map(DeployedMtaService::getName) .filter(service -> shouldDeleteService(service, appsWithoutChange, servicesForApplications, servicesForCurrentDeployment)) .sorted() .collect(Collectors.toList()); } private boolean shouldDeleteService(String service, List<DeployedMtaApplication> appsToKeep, Set<String> servicesForApplications, List<String> servicesForCurrentDeployment) { return appsToKeep.stream() .flatMap(module -> module.getBoundMtaServices() .stream()) .noneMatch(service::equalsIgnoreCase) && !servicesForApplications.contains(service) && !servicesForCurrentDeployment.contains(service); } private List<DeployedMtaApplication> computeModulesToUndeploy(DeployedMta deployedMta, Set<String> mtaModules, List<String> appsToDeploy, List<String> deploymentDescriptorModules) { return deployedMta.getApplications() .stream() .filter(deployedApplication -> shouldBeCheckedForUndeployment(deployedApplication, mtaModules, deploymentDescriptorModules)) .filter(deployedApplication -> shouldUndeployModule(deployedApplication, appsToDeploy)) .collect(Collectors.toList()); } private boolean shouldBeCheckedForUndeployment(DeployedMtaApplication deployedApplication, Set<String> mtaModules, List<String> deploymentDescriptorModules) { return mtaModules.contains(deployedApplication.getModuleName()) || !deploymentDescriptorModules.contains(deployedApplication.getModuleName()); } private boolean shouldUndeployModule(DeployedMtaApplication deployedMtaApplication, List<String> appsToDeploy) { // The deployed module may be in the list of MTA modules, but the actual application that was created from it may have a // different name: return !appsToDeploy.contains(deployedMtaApplication.getName()); } private List<CloudApplication> computeAppsToUndeploy(List<DeployedMtaApplication> modulesToUndeploy, CloudControllerClient client) { return modulesToUndeploy.stream() .map(appToUndeploy -> client.getApplication(appToUndeploy.getName(), false)) .filter(Objects::nonNull) .collect(Collectors.toList()); } private List<ConfigurationSubscription> computeSubscriptionsToDelete(List<ConfigurationSubscription> subscriptionsToCreate, DeployedMta deployedMta, String spaceId) { String mtaId = deployedMta.getMetadata() .getId(); List<ConfigurationSubscription> existingSubscriptions = configurationSubscriptionService.createQuery() .mtaId(mtaId) .spaceId(spaceId) .list(); return existingSubscriptions.stream() .filter(subscription -> !willBeCreatedOrUpdated(subscription, subscriptionsToCreate)) .collect(Collectors.toList()); } private boolean willBeCreatedOrUpdated(ConfigurationSubscription existingSubscription, List<ConfigurationSubscription> createdOrUpdatedSubscriptions) { return createdOrUpdatedSubscriptions.stream() .anyMatch(subscription -> areEqual(subscription, existingSubscription)); } private boolean areEqual(ConfigurationSubscription subscription1, ConfigurationSubscription subscription2) { return Objects.equals(subscription1.getAppName(), subscription2.getAppName()) && Objects.equals(subscription1.getSpaceId(), subscription2.getSpaceId()) && Objects.equals(subscription1.getResourceDto() .getName(), subscription2.getResourceDto() .getName()); } protected ApplicationCloudModelBuilder getApplicationCloudModelBuilder(ProcessContext context) { return StepsUtil.getApplicationCloudModelBuilder(context); } }
57.399142
140
0.640945
c476f9e24b4df2c3692b7c42e83f9152b75c0acc
2,193
package com.circumgraph.storage.internal.indexing; import com.circumgraph.model.ScalarDef; import com.circumgraph.model.SimpleValueDef; import com.circumgraph.storage.internal.AutoGeneratedIds; import com.circumgraph.storage.scalars.ScalarConversionException; import com.circumgraph.storage.types.ValueIndexer; import se.l4.silo.engine.index.search.types.SearchFieldType; /** * {@link ValueIndexer} for {@link ScalarDef#ID} that indexes the id as a * binary values. This allows exact matching and faceting but does not support * range queries. */ public class AutoGeneratedIdValueIndexer implements ValueIndexer { public static final AutoGeneratedIdValueIndexer INSTANCE = new AutoGeneratedIdValueIndexer(); private static final SearchFieldType<Object> FIELD_TYPE = SearchFieldType.forBinary() .map(AutoGeneratedIdValueIndexer::deserializeId, AutoGeneratedIdValueIndexer::serializeId) .build(); @Override public String getName() { return "AUTOGENERATED_ID"; } @Override public SimpleValueDef getType() { return ScalarDef.ID; } @Override public SearchFieldType<Object> getSearchFieldType() { return FIELD_TYPE; } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; return getClass() == obj.getClass(); } private static final byte[] serializeId(Object value) { long id; if(value instanceof Long l) { id = l; } else if(value instanceof String s) { id = AutoGeneratedIds.decode(s); } else { throw new ScalarConversionException("Invalid ID, got: " + value); } return new byte[] { (byte) id, (byte) (id >> 8), (byte) (id >> 16), (byte) (id >> 24), (byte) (id >> 32), (byte) (id >> 40), (byte) (id >> 48), (byte) (id >> 56) }; } private static final Object deserializeId(byte[] data) { return ((long) data[7] << 56) | ((long) data[6] & 0xff) << 48 | ((long) data[5] & 0xff) << 40 | ((long) data[4] & 0xff) << 32 | ((long) data[3] & 0xff) << 24 | ((long) data[2] & 0xff) << 16 | ((long) data[1] & 0xff) << 8 | ((long) data[0] & 0xff); } }
22.608247
94
0.678523
3c9f529a3d16e2e323af74bfd205527ca1f7c214
3,894
/*** * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.caelum.vraptor.util.test; import static com.google.common.base.Strings.isNullOrEmpty; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import javax.enterprise.inject.Vetoed; import javax.validation.ConstraintViolation; import br.com.caelum.vraptor.View; import br.com.caelum.vraptor.validator.AbstractValidator; import br.com.caelum.vraptor.validator.I18nMessage; import br.com.caelum.vraptor.validator.Message; import br.com.caelum.vraptor.validator.SimpleMessage; import br.com.caelum.vraptor.validator.ValidationException; import br.com.caelum.vraptor.validator.Validator; /** * Mocked Validator for testing your controllers. * * You can use the idiom: * MockValidator validator = new MockValidator(); * MyController controller = new MyController(..., validator); * * try { * controller.method(); * Assert.fail(); * } catch (ValidationError e) { * List&lt;Message&gt; errors = e.getErrors(); * // asserts * } * * or * * \@Test(expected=ValidationError.class) * * @author Lucas Cavalcanti */ @Vetoed public class MockValidator extends AbstractValidator { private List<Message> errors = new ArrayList<>(); @Override public Validator check(boolean condition, Message message) { return ensure(condition, message); } @Override public Validator addIf(boolean expression, Message message) { if (expression) { add(message); } return this; } @Override public Validator ensure(boolean expression, Message message) { return addIf(!expression, message); } @Override public Validator validate(Object object, Class<?>... groups) { return this; } @Override public Validator validate(String alias, Object object, Class<?>... groups) { return this; } @Override public <T> Validator addAll(String alias, Set<ConstraintViolation<T>> errors) { for (ConstraintViolation<T> v : errors) { String category = v.getPropertyPath().toString(); if (isNullOrEmpty(alias)) { category = alias + "." + category; } add(new SimpleMessage(category, v.getMessage())); } return this; } @Override public <T> Validator addAll(Set<ConstraintViolation<T>> errors) { return addAll((String) null, errors); } @Override public <T extends View> T onErrorUse(Class<T> view) { if(!this.errors.isEmpty()) { throw new ValidationException(errors); } return new MockResult().use(view); } @Override public Validator addAll(Collection<? extends Message> messages) { for(Message message: messages) { add(message); } return this; } @Override public Validator add(Message message) { errors.add(message); return this; } @Override public boolean hasErrors() { return !errors.isEmpty(); } @Override public List<Message> getErrors() { return errors; } public boolean containsMessage(String messageKey, Object... messageParameters) { I18nMessage expectedMessage = new I18nMessage("validation", messageKey, messageParameters); expectedMessage.setBundle(ResourceBundle.getBundle("messages")); for(Message error : this.getErrors()) { if(expectedMessage.getMessage().equals(error.getMessage())) { return true; } } return false; } }
25.285714
93
0.725732
af6d99dc86cad831363f7daefc2c7ba384e50bc8
2,613
package cards; import actions.DiscardPileToDrawAction; import actions.GainAttuneAction; import actions.PullFromBeyondAction; import basemod.abstracts.CustomCard; import com.megacrit.cardcrawl.actions.common.DrawCardAction; import com.megacrit.cardcrawl.actions.common.ExhaustAction; import com.megacrit.cardcrawl.actions.common.GainEnergyAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import mod.RitualistMod; import patches.MainEnum; public class EvilIntentions extends CustomCard { /* * UNC Skill * 1E Ritual * Ritual. Exhaust 2 cards. Gain 4 energy. Exhaust. */ //Text Declaration public static final String ID = RitualistMod.makeID("EvilIntentions"); private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); public static final String IMG = RitualistMod.makePath("customImages/evil.png"); public static final String NAME = cardStrings.NAME; public static final String DESCRIPTION = cardStrings.DESCRIPTION; public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION; // /Text Declaration/ //Stat Declaration private static final CardRarity RARITY = CardRarity.UNCOMMON; private static final CardTarget TARGET = CardTarget.SELF; private static final CardType TYPE = CardType.SKILL; public static final CardColor COLOR = MainEnum.Magenta; private static final int COST = 1; private static final int MAGIC = 3; // /Stat Declaration/ public EvilIntentions() { super(ID, NAME, IMG, COST, DESCRIPTION, TYPE, COLOR, RARITY, TARGET); baseMagicNumber = MAGIC; magicNumber = baseMagicNumber; exhaust = true; } // Actions the card should do. @Override public void use(AbstractPlayer p, AbstractMonster m) { addToBot(new ExhaustAction(p, p, 2, false)); addToBot(new GainEnergyAction(magicNumber)); } // Which card to return when making a copy of this card. @Override public AbstractCard makeCopy() { return new EvilIntentions(); } //Upgraded stats. @Override public void upgrade() { if (!upgraded) { upgradeName(); rawDescription = UPGRADE_DESCRIPTION; initializeDescription(); exhaust = false; } } }
32.259259
97
0.724072
58a34f2180b86a74a48a110758c7d25a11a9fa6d
902
package org.nybatis.core.db.session.executor.util; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.nybatis.core.db.sql.mapper.SqlType; public class Header { private List<String> name = new ArrayList<>(); private List<SqlType> type = new ArrayList<>(); public int size() { return name.size(); } public Header add( String name, SqlType sqlType ) { this.name.add( name ); this.type.add( sqlType ); return this; } public boolean contains( String name ) { return this.name.contains( name ); } public Header add( String name, int sqlType ) { return add( name, SqlType.find(sqlType) ); } public String getName( int index ) { return name.get( index ); } public SqlType getType( int index ) { return type.get( index ); } public Set<String> keySet() { return new LinkedHashSet<>( name ); } }
19.608696
52
0.686253
8123ab5ff79486869b221b4e543372f5dba9d571
118
package uk.gov.hmcts.reform.wataskmonitor.entities.documents; public enum DocumentNames { NOTICE_OF_APPEAL_PDF }
19.666667
61
0.813559
08d7934b93932607950b4558c458087b70c0d11b
717
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package io.github.mmm.ui.tvm.factory.media; import io.github.mmm.ui.api.factory.UiSingleWidgetFactoryNative; import io.github.mmm.ui.api.widget.media.UiVideoPlayer; import io.github.mmm.ui.tvm.widget.media.TvmVideoPlayer; /** * {@link UiSingleWidgetFactoryNative} for {@link UiVideoPlayer}. * * @since 1.0.0 */ public class TvmFactoryVideoPlayer implements UiSingleWidgetFactoryNative<UiVideoPlayer> { @Override public Class<UiVideoPlayer> getType() { return UiVideoPlayer.class; } @Override public UiVideoPlayer create() { return new TvmVideoPlayer(); } }
24.724138
90
0.746165
a4d9ee36633c59dc742f6b9f3ba28ed5bcedd390
5,218
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.jstestdriver.server; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.jstestdriver.annotations.MaxFormContentSize; import com.google.jstestdriver.annotations.Port; import com.google.jstestdriver.model.HandlerPathPrefix; import org.mortbay.jetty.Handler; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.security.SslSocketConnector; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.HashSessionIdManager; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.servlet.GzipFilter; import java.net.URL; import java.util.Random; import javax.servlet.Servlet; /** * Sippin' on Jetty and Guice. * * @author rdionne@google.com (Robert Dionne) */ public class JettyModule extends AbstractModule { private static final URL KEYSTORE = JettyModule.class.getClassLoader() .getResource("com/google/jstestdriver/keystore"); private static final String KEY_PASSWORD = "asdfgh"; private final int port; private final int sslPort; private final HandlerPathPrefix handlerPrefix; public JettyModule(int port, int sslPort, HandlerPathPrefix handlerPrefix) { this.port = port; this.sslPort = sslPort; this.handlerPrefix = handlerPrefix; } @Override protected void configure() { bindConstant().annotatedWith(Port.class).to(port); bindConstant().annotatedWith(MaxFormContentSize.class).to(Integer.MAX_VALUE); } @Provides @Singleton SslSocketConnector provideSslSocketConnector(@Port Integer port) { SslSocketConnector connector = new SslSocketConnector(); connector.setKeystore(KEYSTORE.toString()); connector.setKeyPassword(KEY_PASSWORD); connector.setPort(sslPort == -1 ? port + 1 : sslPort); return connector; } @Provides @Singleton SocketConnector provideSocketConnector(@Port Integer port) { SocketConnector connector = new SocketConnector(); connector.setPort(port); return connector; } @Provides @Singleton ServletHolder servletHolder(Servlet handlerServlet) { return new ServletHolder(handlerServlet); } @Provides @Singleton Server provideJettyServer(SocketConnector connector, SslSocketConnector sslConnector, @MaxFormContentSize Integer maxFormContentSize, ServletHolder servletHolder) { Server server = new Server(); server.setGracefulShutdown(1); server.addConnector(connector); server.addConnector(sslConnector); server.setSessionIdManager(new HashSessionIdManager(new Random())); Context context = new Context(server, "/", Context.SESSIONS); context.setMaxFormContentSize(maxFormContentSize); //context.addFilter(GzipFilter.class, handlerPrefix.prefixPath("/test/*"), Handler.ALL); // TODO(rdionne): Fix HttpServletRequest#getPathInfo() provided by // RequestHandlerServlet. context.addServlet(servletHolder, handlerPrefix.prefixPath("/")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/cache")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/capture/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/cmd")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/favicon.ico")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/fileSet")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/forward/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/heartbeat")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/hello")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/proxy/*", "jstd")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/gateway/*", "jstd")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/log")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/query/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/runner/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/slave/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/test/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/quit")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/quit/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/static/*")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/bcr")); context.addServlet(servletHolder, handlerPrefix.prefixPath("/bcr/*")); context.addServlet(servletHolder, "/*"); return server; } }
39.530303
92
0.761594
99f6c87764a7fc8359c02c1612481a790826cd2e
1,014
package de.arguments.optional; import de.arguments.exceptions.ArgumentsException; public class OptionalDoubleArray extends OptionalArray { public OptionalDoubleArray(char id, Double[] defaultt) throws ArgumentsException { super(id); this.defaultt = defaultt; type = "DoubleArray"; } public OptionalDoubleArray(char id, String alias, Double[] defaultt) throws ArgumentsException { super(id, alias); this.defaultt = defaultt; type = "DoubleArray"; } @SuppressWarnings("unchecked") @Override public Double[] getValue() throws ArgumentsException { if (valueNotSet()) { return (Double[]) defaultt; } return (Double[]) value; } @Override public void setValue(Object value) throws ArgumentsException { if (!(value instanceof Double[])) { throw new ArgumentsException("Object " + value + " is not a Double[]!"); } this.value = (Double[]) value; } @SuppressWarnings("unchecked") @Override public Double[] getDefault() { return (Double[]) defaultt; } }
19.882353
69
0.704142
681f02d8c356d6946e06e8b975615f7cba362b6f
1,195
package Servlet; import Service.updateService; import bean.Command; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Created by ziheng on 2017/8/16. */ @WebServlet("/updatewinServlets") public class updatewinServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String ids=request.getParameter("ids").trim(); updateService updateservice=new updateService(); List<Command> updateList=updateservice.queryMessagebyID(ids); request.setAttribute("ids",ids); request.setAttribute("updateList",updateList); request.getRequestDispatcher("update.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
36.212121
123
0.745607
e7ae83f98583d079f2b6877e10d3fb6c3abc1d7f
2,149
package chapter6classes; import java.util.Random; import java.util.Scanner; public class Chapter6Classes { static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); Random random = new Random(); Double.parseDouble("10.5"); Mug trailsEdgeMug = new Mug(); trailsEdgeMug.setColor("silver"); System.out.println("My mug is " + trailsEdgeMug.getColor()); Mug disneyMug = new Mug(); disneyMug.setColor("blue"); System.out.println("My mug is " + disneyMug.getColor()); System.out.println("Enter the name of your student"); String name = keyboard.nextLine(); Student firstStudent = new Student(name); //firstStudent.setName(name); - use the constructor instead getGradesForStudent(firstStudent); // overloaded constructor, it has a different set of parameters Student secondStudent = new Student(name, 100, 100, 100, 100); } public static void getGradesForStudent(Student student){ System.out.println("Enter the score for project 1 for " + student.getName()); int score1 = Integer.parseInt(keyboard.nextLine()); student.setProject1Grade(score1); System.out.println("Enter the score for project 2 for " + student.getName()); int score2 = Integer.parseInt(keyboard.nextLine()); student.setProject2Grade(score2); System.out.println("Enter the score for project 3 for " + student.getName()); int score3 = Integer.parseInt(keyboard.nextLine()); student.setProject3Grade(score3); System.out.println("Enter the score for the final project for " + student.getName()); int finalScore = Integer.parseInt(keyboard.nextLine()); student.setFinalProjectGrade(finalScore); System.out.println("The final grade for " + student.getName() + " is: " + student.getOverallGrade()); } }
34.66129
93
0.614705
6c6ca58a6d2d9ba06480d3d887d50dc013266f81
12,564
/* Copyright 2002-2014 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.propagation.analytical; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.commons.math3.util.FastMath; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.orekit.Utils; import org.orekit.bodies.CelestialBodyFactory; import org.orekit.errors.OrekitException; import org.orekit.errors.OrekitMessages; import org.orekit.frames.Frame; import org.orekit.frames.FramesFactory; import org.orekit.orbits.CartesianOrbit; import org.orekit.orbits.EquinoctialOrbit; import org.orekit.orbits.KeplerianOrbit; import org.orekit.orbits.Orbit; import org.orekit.orbits.PositionAngle; import org.orekit.propagation.AdditionalStateProvider; import org.orekit.propagation.SpacecraftState; import org.orekit.time.AbsoluteDate; import org.orekit.time.DateComponents; import org.orekit.time.TimeComponents; import org.orekit.time.TimeScale; import org.orekit.time.TimeScalesFactory; import org.orekit.utils.PVCoordinates; import org.orekit.utils.TimeStampedPVCoordinates; public class TabulatedEphemerisTest { @Test public void testInterpolationFullEcksteinHechlerOrbit() throws OrekitException { // with full Eckstein-Hechler Cartesian orbit, // including non-Keplerian acceleration, interpolation is very good checkInterpolation(new StateFilter() { public SpacecraftState filter(SpacecraftState state) { return state; } }, 6.62e-4, 1.89e-5); } @Test public void testInterpolationKeplerianAcceleration() throws OrekitException { // with Keplerian-only acceleration, interpolation is quite wrong checkInterpolation(new StateFilter() { public SpacecraftState filter(SpacecraftState state) { CartesianOrbit c = (CartesianOrbit) state.getOrbit(); Vector3D p = c.getPVCoordinates().getPosition(); Vector3D v = c.getPVCoordinates().getVelocity(); double r2 = p.getNormSq(); double r = FastMath.sqrt(r2); Vector3D kepA = new Vector3D(-c.getMu() / (r * r2), c.getPVCoordinates().getPosition()); return new SpacecraftState(new CartesianOrbit(new TimeStampedPVCoordinates(c.getDate(), p, v, kepA), c.getFrame(), c.getMu()), state.getAttitude(), state.getMass(), state.getAdditionalStates()); } }, 8.5, 0.22); } private void checkInterpolation(StateFilter f, double expectedDP, double expectedDV) throws OrekitException { double mass = 2500; double a = 7187990.1979844316; double e = 0.5e-4; double i = 1.7105407051081795; double omega = 1.9674147913622104; double OMEGA = FastMath.toRadians(261); double lv = 0; final AbsoluteDate initDate = new AbsoluteDate(new DateComponents(2004, 01, 01), TimeComponents.H00, TimeScalesFactory.getUTC()); final AbsoluteDate finalDate = new AbsoluteDate(new DateComponents(2004, 01, 02), TimeComponents.H00, TimeScalesFactory.getUTC()); double deltaT = finalDate.durationFrom(initDate); Orbit transPar = new KeplerianOrbit(a, e, i, omega, OMEGA, lv, PositionAngle.TRUE, FramesFactory.getEME2000(), initDate, mu); int nbIntervals = 720; EcksteinHechlerPropagator eck = new EcksteinHechlerPropagator(transPar, mass, ae, mu, c20, c30, c40, c50, c60); AdditionalStateProvider provider = new AdditionalStateProvider() { public String getName() { return "dt"; } public double[] getAdditionalState(SpacecraftState state) { return new double[] { state.getDate().durationFrom(initDate) }; } }; eck.addAdditionalStateProvider(provider); try { eck.addAdditionalStateProvider(provider); Assert.fail("an exception should have been thrown"); } catch (OrekitException oe) { Assert.assertEquals(OrekitMessages.ADDITIONAL_STATE_NAME_ALREADY_IN_USE, oe.getSpecifier()); } List<SpacecraftState> tab = new ArrayList<SpacecraftState>(nbIntervals + 1); for (int j = 0; j<= nbIntervals; j++) { AbsoluteDate current = initDate.shiftedBy((j * deltaT) / nbIntervals); tab.add(f.filter(eck.propagate(current))); } try { new Ephemeris(tab, nbIntervals + 2); Assert.fail("an exception should have been thrown"); } catch (MathIllegalArgumentException miae) { // expected } Ephemeris te = new Ephemeris(tab, 2); Assert.assertEquals(0.0, te.getMaxDate().durationFrom(finalDate), 1.0e-9); Assert.assertEquals(0.0, te.getMinDate().durationFrom(initDate), 1.0e-9); double maxP = 0; double maxV = 0; for (double dt = 0; dt < 3600; dt += 1) { AbsoluteDate date = initDate.shiftedBy(dt); CartesianOrbit c1 = (CartesianOrbit) eck.propagate(date).getOrbit(); CartesianOrbit c2 = (CartesianOrbit) te.propagate(date).getOrbit(); maxP = FastMath.max(maxP, Vector3D.distance(c1.getPVCoordinates().getPosition(), c2.getPVCoordinates().getPosition())); maxV = FastMath.max(maxV, Vector3D.distance(c1.getPVCoordinates().getVelocity(), c2.getPVCoordinates().getVelocity())); } Assert.assertEquals(expectedDP, maxP, 0.1 * expectedDP); Assert.assertEquals(expectedDV, maxV, 0.1 * expectedDV); } private interface StateFilter { public SpacecraftState filter(final SpacecraftState state); } @Test public void testPiWraping() throws OrekitException { TimeScale utc= TimeScalesFactory.getUTC(); Frame frame = FramesFactory.getEME2000(); double mu=CelestialBodyFactory.getEarth().getGM(); AbsoluteDate t0 = new AbsoluteDate(2009, 10, 29, 0, 0, 0, utc); AbsoluteDate t1 = new AbsoluteDate(t0, 1320.0); Vector3D p1 = new Vector3D(-0.17831296727974E+08, 0.67919502669856E+06, -0.16591008368477E+07); Vector3D v1 = new Vector3D(-0.38699705630724E+04, -0.36209408682762E+04, -0.16255053872347E+03); SpacecraftState s1 = new SpacecraftState(new EquinoctialOrbit(new PVCoordinates(p1, v1), frame, t1, mu)); AbsoluteDate t2 = new AbsoluteDate(t0, 1440.0); Vector3D p2 = new Vector3D(-0.18286942572033E+08, 0.24442124296930E+06, -0.16777961761695E+07); Vector3D v2 = new Vector3D(-0.37252897467918E+04, -0.36246628128896E+04, -0.14917724596280E+03); SpacecraftState s2 = new SpacecraftState(new EquinoctialOrbit(new PVCoordinates(p2, v2), frame, t2, mu)); AbsoluteDate t3 = new AbsoluteDate(t0, 1560.0); Vector3D p3 = new Vector3D(-0.18725635245837E+08, -0.19058407701834E+06, -0.16949352249614E+07); Vector3D v3 = new Vector3D(-0.35873348682393E+04, -0.36248828501784E+04, -0.13660045394149E+03); SpacecraftState s3 = new SpacecraftState(new EquinoctialOrbit(new PVCoordinates(p3, v3), frame, t3, mu)); Ephemeris ephem= new Ephemeris(Arrays.asList(s1, s2, s3), 2); AbsoluteDate tA = new AbsoluteDate(t0, 24 * 60); Vector3D pA = ephem.propagate(tA).getPVCoordinates(frame).getPosition(); Assert.assertEquals(1.766, Vector3D.distance(pA, s1.shiftedBy(tA.durationFrom(s1.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); Assert.assertEquals(0.000, Vector3D.distance(pA, s2.shiftedBy(tA.durationFrom(s2.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); Assert.assertEquals(1.556, Vector3D.distance(pA, s3.shiftedBy(tA.durationFrom(s3.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); AbsoluteDate tB = new AbsoluteDate(t0, 25 * 60); Vector3D pB = ephem.propagate(tB).getPVCoordinates(frame).getPosition(); Assert.assertEquals(2.646, Vector3D.distance(pB, s1.shiftedBy(tB.durationFrom(s1.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); Assert.assertEquals(2.619, Vector3D.distance(pB, s2.shiftedBy(tB.durationFrom(s2.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); Assert.assertEquals(2.632, Vector3D.distance(pB, s3.shiftedBy(tB.durationFrom(s3.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); AbsoluteDate tC = new AbsoluteDate(t0, 26 * 60); Vector3D pC = ephem.propagate(tC).getPVCoordinates(frame).getPosition(); Assert.assertEquals(6.851, Vector3D.distance(pC, s1.shiftedBy(tC.durationFrom(s1.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); Assert.assertEquals(1.605, Vector3D.distance(pC, s2.shiftedBy(tC.durationFrom(s2.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); Assert.assertEquals(0.000, Vector3D.distance(pC, s3.shiftedBy(tC.durationFrom(s3.getDate())).getPVCoordinates(frame).getPosition()), 1.0e-3); } @Test public void testGetFrame() throws MathIllegalArgumentException, IllegalArgumentException, OrekitException { // setup Frame frame = FramesFactory.getICRF(); AbsoluteDate date = AbsoluteDate.JULIAN_EPOCH; // create ephemeris with 2 arbitrary points SpacecraftState state = new SpacecraftState( new KeplerianOrbit(1e9, 0.01, 1, 1, 1, 1, PositionAngle.TRUE, frame, date, mu)); Ephemeris ephem = new Ephemeris(Arrays.asList(state, state.shiftedBy(1)), 2); // action + verify Assert.assertSame(ephem.getFrame(), frame); } @Before public void setUp() { Utils.setDataRoot("regular-data"); mu = 3.9860047e14; ae = 6.378137e6; c20 = -1.08263e-3; c30 = 2.54e-6; c40 = 1.62e-6; c50 = 2.3e-7; c60 = -5.5e-7; } @After public void tearDown() { mu = Double.NaN; ae = Double.NaN; c20 = Double.NaN; c30 = Double.NaN; c40 = Double.NaN; c50 = Double.NaN; c60 = Double.NaN; } private double mu; private double ae; private double c20; private double c30; private double c40; private double c50; private double c60; }
44.711744
133
0.608325
9b1a0c9a32c5227a655868dc6f9873edb5ec9e00
2,072
package servlet; import beans.ChiTietDonHang; import beans.DonHang; import beans.SanPham; import beans.Users; import conn.ConnectionUtils; import utils.DBUtils; import utils.MyUtils; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.List; @WebServlet(name = "Statistic", value = "/Statistic") public class Statistic extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<ChiTietDonHang> listSPDaMua; List<SanPham> listSP; List<DonHang> listDH; HttpSession session = request.getSession(); Users u = MyUtils.getLoginedUser(session); if(u == null) { String contextPath = request.getContextPath(); response.sendRedirect(contextPath + "/signIn"); } else { if (u.getRoleID() == 2 || u.getRoleID() == 3) { try { Connection conn = MyUtils.getStoredConnection(request); listSPDaMua = DBUtils.getSoLuongSPDaMua(conn); listSP = DBUtils.getAllSanPham(conn); listDH = DBUtils.getDanhThuTheoNgay(conn); request.setAttribute("listSP", listSP); request.setAttribute("listSPDaMua", listSPDaMua); request.setAttribute("listDT", listDH); request.getRequestDispatcher("/WEB-INF/views/statistics.jsp").forward(request, response); } catch (SQLException e) { e.printStackTrace(); } } else { request.getRequestDispatcher("/WEB-INF/views/errorAccess.jsp").forward(request, response); } } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
32.888889
122
0.623069
6f90a964ddb49bcacae26a5d26e808d7c923094f
1,172
package com.ornithopter.quick.plugins; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; public class AppInfo extends Info { private Drawable icon; private PackageManager pm; private String mPackageName; public static final String SEARCH_FIELD_TAG_PACKAGE_NAME = "packageName"; public AppInfo(ResolveInfo info, PackageManager pm){ super(); this.pm = pm; this.Name = info.loadLabel(pm).toString(); this.mPackageName = info.activityInfo.packageName; } public AppInfo(String cacheStr, PackageManager pm){ super(cacheStr); this.pm = pm; } public Drawable getIcon(){ if(icon == null) { try { icon = pm.getApplicationIcon(mPackageName); } catch (NameNotFoundException e) { e.printStackTrace(); } } return icon; } public String getName() { return Name; } public String getPackageName(){ return mPackageName; } @Override String[] getInfo() { return new String[]{mPackageName}; } @Override void fillInfoFromCache(String[] splits) { mPackageName = splits[0]; } }
20.561404
74
0.728669
4fdbb382f4acac867463b6ab6380f2aca34b2d6c
759
package piza.otavio.cambadaforum.exceptions; /** * Exception that is the parent to all of the project's custom exceptions * * @author Otavio Sartorelli de Toledo Piza * @version 2020-09-21 */ public class CambadaForumException extends Exception { private static final long serialVersionUID = 1L; // Serial UID protected final String message; // Stores exception message /** * Constructor that allows for the user to add a message to the exception * * @param message that will be part of the exception */ CambadaForumException(String message) { this.message = message; } /** * Gets the message from the exception * * @return the message from the exception */ @Override public String getMessage() { return message; } }
23.71875
74
0.720685
54a59c381c269cc88d08dc0850316f981a8b4d83
2,635
package dev.vality.cm.service; import dev.vality.cm.model.ClaimModel; import dev.vality.cm.model.ClaimStatusEnum; import dev.vality.cm.model.ClaimStatusModel; import dev.vality.cm.model.MetadataModel; import dev.vality.cm.search.ClaimPageSearchParameters; import dev.vality.cm.search.ClaimPageSearchRequest; import dev.vality.cm.search.ClaimPageSearchResponse; import dev.vality.damsel.claim_management.Claim; import dev.vality.damsel.claim_management.Modification; import dev.vality.damsel.claim_management.ModificationChange; import org.springframework.data.domain.Page; import java.util.List; public interface ClaimManagementService { Claim createClaim(String partyId, List<Modification> changeset); void updateClaim(String partyId, long claimId, int revision, List<Modification> changeset); ClaimModel getClaim(String partyId, long claimId); ClaimModel failClaimAcceptance(String partyId, long claimId, int revision); ClaimModel pendingAcceptanceClaim(String partyId, long claimId, int revision); ClaimModel acceptClaim(String partyId, long claimId, int revision); ClaimModel revokeClaim(String partyId, long claimId, int revision, String reason); ClaimModel denyClaim(String partyId, long claimId, int revision, String reason); ClaimModel requestClaimReview(String partyId, long claimId, int revision); ClaimModel requestClaimChanges(String partyId, long claimId, int revision); ClaimModel changeStatus(String partyId, long claimId, int revision, ClaimStatusModel targetClaimStatus, List<ClaimStatusEnum> expectedStatuses); ClaimPageSearchResponse searchClaims(ClaimPageSearchRequest claimSearchRequest, String continuationToken, int limit); Page<ClaimModel> searchClaims(ClaimPageSearchRequest claimSearchRequest, ClaimPageSearchParameters claimSearchParameters); MetadataModel getMetadata(String partyId, long claimId, String key); void setMetadata(String partyId, long claimId, String key, MetadataModel metadataModel); void removeMetadata(String partyId, long claimId, String key); void updateModification(String partyId, long id, int revision, long modificationId, ModificationChange modificationChange); void removeModification(String partyId, long id, int revision, long modificationId); }
39.924242
95
0.70778
762a7fd1164456fb4137f0402327a45ced11c0a5
3,620
package com.lts.tasktracker.monitor; import com.lts.core.constant.Constants; import com.lts.core.constant.EcTopic; import com.lts.core.factory.NamedThreadFactory; import com.lts.core.logger.Logger; import com.lts.core.logger.LoggerFactory; import com.lts.core.support.SystemClock; import com.lts.ec.EventInfo; import com.lts.ec.EventSubscriber; import com.lts.ec.Observer; import com.lts.tasktracker.domain.TaskTrackerAppContext; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * 当TaskTracker和JobTracker断开超过了一段时间,TaskTracker立即停止当前的所有任务 * * @author Robert HG (254963746@qq.com) on 9/9/15. */ public class StopWorkingMonitor { private static final Logger LOGGER = LoggerFactory.getLogger(StopWorkingMonitor.class); private TaskTrackerAppContext appContext; private AtomicBoolean start = new AtomicBoolean(false); private final ScheduledExecutorService SCHEDULED_CHECKER = Executors.newScheduledThreadPool(1, new NamedThreadFactory("LTS-StopWorking-Monitor", true)); private ScheduledFuture<?> scheduledFuture; private String ecSubscriberName = StopWorkingMonitor.class.getSimpleName(); private EventSubscriber eventSubscriber; private Long offlineTimestamp = null; public StopWorkingMonitor(TaskTrackerAppContext appContext) { this.appContext = appContext; } public void start() { try { if (start.compareAndSet(false, true)) { eventSubscriber = new EventSubscriber(ecSubscriberName, new Observer() { @Override public void onObserved(EventInfo eventInfo) { // 当JobTracker可用的时候,置为null, 重新统计 offlineTimestamp = null; } }); appContext.getEventCenter().subscribe(eventSubscriber, EcTopic.JOB_TRACKER_AVAILABLE); scheduledFuture = SCHEDULED_CHECKER.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { if (offlineTimestamp == null && appContext.getRemotingClient().isServerEnable()) { offlineTimestamp = SystemClock.now(); } if (offlineTimestamp != null && SystemClock.now() - offlineTimestamp > Constants.DEFAULT_TASK_TRACKER_OFFLINE_LIMIT_MILLIS) { // 停止所有任务 appContext.getRunnerPool().stopWorking(); offlineTimestamp = null; } } catch (Throwable t) { LOGGER.error("Check ", t); } } }, 3, 3, TimeUnit.SECONDS); LOGGER.info("start succeed "); } } catch (Throwable t) { LOGGER.error("start failed ", t); } } public void stop() { try { if (start.compareAndSet(true, false)) { scheduledFuture.cancel(true); SCHEDULED_CHECKER.shutdown(); appContext.getEventCenter().unSubscribe(EcTopic.JOB_TRACKER_AVAILABLE, eventSubscriber); LOGGER.info("stop succeed "); } } catch (Throwable t) { LOGGER.error("stop failed ", t); } } }
38.510638
156
0.598895
b28c17a45c393e99b6f42f937bcc2d320c474360
807
package TestsPackage; import static org.junit.Assert.*; import java.util.ArrayList; import models.Ball; import models.GreenView; import models.Position; import org.junit.Test; public class GreenViewTest { @Test public void test() { GreenView gv = new GreenView(new Position(-5,0.5,2), 2.75, 2, new Position(0,0,200), 10); Ball ball = new Ball(new Position(0,0,200)); ArrayList<Position> positions = new ArrayList<Position>(); positions.add(new Position(0,0,200)); positions.add(new Position(0,0,200)); positions.add(new Position(0,0,200)); ball.setTrajectory(positions); ball.hit(); ball.tickAction(); ball.tickAction(); ball.tickAction(); gv.updateBall(ball); double x = gv.getFlyBallAbsoluteX(); double z = gv.getFlyBallAbsoluteZ(); assertEquals(5, x,0); } }
21.810811
91
0.703841
cb1fac1e137b57d5121aa1d3b05bb0c0a32ec4f9
301
package cn.star.autorder.usermanager.service; import java.util.Set; import cn.star.autorder.usermanager.entity.User; public interface UserService { User findByUsername(String username); Set<String> findRoles(String username); Set<String> findPermissions(String username); }
18.8125
49
0.747508
0e1ba3801b471b9fed81b421860ab661110c1f74
4,022
package com.example.anroid.testaescipher; import android.util.Base64; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESCipher { private static final String characterEncoding = "UTF-8"; private static final String cipherTransformation = "AES/CBC/PKCS5Padding"; private static final String aesEncryptionAlgorithm = "AES"; private static final String messageDigestAlgorithm = "SHA-256"; private static final int ivSize = 16; private static byte[] keyBytes; private static AESCipher instance = null; AESCipher(String key) { try { MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm); md.update(key.getBytes(characterEncoding)); keyBytes = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public static AESCipher getInstance(String key) { if (instance == null) { instance = new AESCipher(key); } return instance; } public String encrypt_string(final String plainMessage) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { return Base64.encodeToString(encrypt(plainMessage.getBytes()), Base64.DEFAULT); } public String decrypt_string(final String encryptedMessage) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { byte[] encryptedBytes = decrypt(Base64.decode(encryptedMessage, Base64.DEFAULT)); return new String(encryptedBytes); } public byte[] encrypt(byte[] plainMessage) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { SecretKeySpec keySpec = new SecretKeySpec(keyBytes, aesEncryptionAlgorithm); SecureRandom random = new SecureRandom(); byte[] ivBytes = new byte[ivSize]; random.nextBytes(ivBytes); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance(cipherTransformation); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] inputBytes = new byte[ivBytes.length + plainMessage.length]; System.arraycopy(ivBytes, 0, inputBytes, 0, ivBytes.length); System.arraycopy(plainMessage, 0, inputBytes, ivBytes.length, plainMessage.length); return cipher.doFinal(inputBytes); } public byte[] decrypt(byte[] encryptMessage) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { byte[] ivBytes = Arrays.copyOfRange(encryptMessage, 0, ivSize); byte[] inputBytes = Arrays.copyOfRange(encryptMessage, ivSize, encryptMessage.length); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, aesEncryptionAlgorithm); Cipher cipher = Cipher.getInstance(cipherTransformation); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); return cipher.doFinal(inputBytes); } }
39.048544
226
0.724764
4804e7aa7658d733f7a2cd56d2d9f417a2e6556f
1,984
package com.github.malavv.brewru.protocol; import com.google.gson.*; import java.util.ArrayList; import java.util.List; public interface StepJson { enum Type { equipment, ingredient, heating, cooling, fermenting, miscellaneous, processTarget, unknown } class Ing implements StepJson { private String ing; private QtyJson qty; private QtyJson temp; public String getIng() { return ing; } public QtyJson getQty() { return qty; } public QtyJson getTemp() { return temp; } } class Heating implements StepJson { private List<JsonObject> targets; } class Adapter implements JsonDeserializer<StepJson> { private StepJson ing(JsonElement json, JsonDeserializationContext c) { Ing i = new Ing(); i.ing = json.getAsJsonObject().get("ing").getAsString(); i.qty = c.deserialize(json.getAsJsonObject().get("qty"), QtyJson.class); i.temp = c.deserialize(json.getAsJsonObject().get("temp"), QtyJson.class); return i; } private StepJson heating(JsonElement json, JsonDeserializationContext c) { Heating i = new Heating(); i.targets = new ArrayList<>(); json.getAsJsonObject().get("targets").getAsJsonArray() .forEach(t -> i.targets.add(t.getAsJsonObject())); return i; } @Override public StepJson deserialize(JsonElement json, java.lang.reflect.Type t, JsonDeserializationContext c) throws JsonParseException { int type = json.getAsJsonObject().get("type").getAsInt(); switch (Type.values()[type]) { case equipment: break; case ingredient: return ing(json, c); case heating: return heating(json, c); case cooling: break; case fermenting: break; case miscellaneous: break; case processTarget: break; case unknown: break; } return c.deserialize(json, t); } } }
26.453333
143
0.632056
850d8f813a00206ec4949912b989c9b784714fcf
1,322
package de.otto.wickettester; import java.util.Iterator; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; /** * Returns true if one of the siblings matches the criteria * * @author Oliver Langer (oliver.langer@ottogroup.com) */ public class HavingSiblingComponentMatcher<T extends Component, CT extends Component> implements ComponentMatcher<T, T> { private final ComponentMatcher<CT, CT> matcher; public HavingSiblingComponentMatcher(final ComponentMatcher<CT, CT> matcher) { this.matcher = matcher; } @SuppressWarnings("unchecked") @Override public T match(final T component) { if (component == null) { return null; } final MarkupContainer parent = component.getParent(); if (parent == null) { return null; } T toReturn = null; final Iterator<Component> children = parent.iterator(); while (children.hasNext()) { final CT next = (CT) children.next(); if (matcher.match(next) != null) { toReturn = (T) next; } } return toReturn; } @Override public String criterionAsString() { return String.format("having a direct parent (%s)", matcher.criterionAsString()); } }
25.423077
121
0.627837
d15609ac64fd411d43b1e35586549d633b98ab4f
4,906
package querqy.rewrite; import org.junit.Test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class QuerqyTemplateEngineTest { @Test(expected = TemplateParseException.class) public void testErrorForReferenceOnMultilineTemplate() throws TemplateParseException, IOException { new QuerqyTemplateEngine(resource("templating/error/embedded-reference-on-multiline.txt")); } @Test(expected = TemplateParseException.class) public void testErrorForReferenceOnMultilineTemplate2() throws TemplateParseException, IOException { new QuerqyTemplateEngine(resource("templating/error/embedded-reference-on-multiline-2.txt")); } @Test(expected = TemplateParseException.class) public void testErrorForMissingTemplateBody() throws TemplateParseException, IOException { new QuerqyTemplateEngine(resource("templating/error/missing-body-for-template.txt")); } @Test(expected = TemplateParseException.class) public void testErrorForMissingTemplateDefinition() throws TemplateParseException, IOException { new QuerqyTemplateEngine(resource("templating/error/missing-template-definition.txt")); } @Test(expected = TemplateParseException.class) public void testErrorForNonMatchingParams() throws TemplateParseException, IOException { new QuerqyTemplateEngine(resource("templating/error/non-matching-params.txt")); } @Test(expected = TemplateParseException.class) public void testErrorForNonMatchingParams2() throws TemplateParseException, IOException { new QuerqyTemplateEngine(resource("templating/error/non-matching-params-2.txt")); } @Test public void testParseParameters() throws TemplateParseException, IOException { QuerqyTemplateEngine querqyTemplateEngine = new QuerqyTemplateEngine(new StringReader("")); Map<String, String> parameters; parameters = querqyTemplateEngine.parseParameters(" a = 1 "); assertThat(parameters).containsExactly( new AbstractMap.SimpleEntry<>("a", "1")); parameters = querqyTemplateEngine.parseParameters("a = 1 || b=2"); assertThat(parameters).containsExactly( new AbstractMap.SimpleEntry<>("a", "1"), new AbstractMap.SimpleEntry<>("b", "2")); } @Test public void testRendering() throws IOException, TemplateParseException { QuerqyTemplateEngine querqyTemplateEngine = new QuerqyTemplateEngine( resource("templating/input-rendering.txt")); assertThat(list(querqyTemplateEngine.renderedRules.reader)) .isEqualTo(list(resource("templating/expected-rendering.txt"))); } @Test public void testLineNumberMapping() throws IOException, TemplateParseException { List<String> linesOfInput = list(resource("templating/input-line-number-mapping.txt")); Map<Integer, String> numberedLinesOfInput = numberedLines(linesOfInput); QuerqyTemplateEngine querqyTemplateEngine = new QuerqyTemplateEngine( resource("templating/input-line-number-mapping.txt")); List<String> linesOfOutput = list(querqyTemplateEngine.renderedRules.reader); Map<Integer, String> numberedLinesOfOutput = numberedLines(linesOfOutput); Map<Integer, Integer> lineNumberMapping = querqyTemplateEngine.renderedRules.lineNumberMapping; assertThat(numberedLinesOfOutput.get(3)).isEqualTo(numberedLinesOfInput.get(lineNumberMapping.get(3))); assertThat(numberedLinesOfOutput.get(7)).isEqualTo(numberedLinesOfInput.get(lineNumberMapping.get(7))); assertThat(numberedLinesOfOutput.get(12)).isEqualTo(numberedLinesOfInput.get(lineNumberMapping.get(12))); assertThat(numberedLinesOfOutput.get(19)).isEqualTo(numberedLinesOfInput.get(lineNumberMapping.get(19))); } private Reader resource(String resourceName) { return new InputStreamReader(getClass().getClassLoader().getResourceAsStream(resourceName)); } private List<String> list(Reader reader) throws IOException { BufferedReader bufferedReader = new BufferedReader(reader); List<String> lines = new ArrayList<>(); String line; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } return lines; } private Map<Integer, String> numberedLines(List<String> lines) { Map<Integer, String> numberedLines = new HashMap<>(); for (String line : lines) { numberedLines.put(numberedLines.size() + 1, line); } return numberedLines; } }
40.213115
113
0.726254
becbb5284a77fab141000bf871e56b01f19903fe
862
package com.nettyboot.biznode; import com.alibaba.fastjson.JSONObject; import com.nettyboot.config.RequestInfo; import com.nettyboot.rpcmessage.MessageHelper; import com.nettyboot.rpcmessage.MessageType; import com.nettyboot.rpcmessage.SimpleMessage; import com.nettyboot.rpcserver.HandlerContext; import io.netty.channel.ChannelHandlerContext; public class BiznodeHandlerContext extends HandlerContext { @Override public void handleMessage(ChannelHandlerContext context, SimpleMessage message) { SimpleMessage response = new SimpleMessage(MessageType.response, message.getMsgid()); response.setData(XLogicManager.executeLogic(convertToRequestInfo(message))); context.writeAndFlush(message); } public RequestInfo convertToRequestInfo(SimpleMessage message) { return JSONObject.toJavaObject((JSONObject)message.getData(), RequestInfo.class); } }
35.916667
87
0.835267
9243d3d1df1415e3a183d5c175d28390e0e5cf88
1,318
package Ds.src.DAAAssessment; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class StringOfTwo { static String stringWithTwo(String input){ String inputarray[]=input.split(" "); String result=""; HashMap<String,Integer> hmap= new HashMap<>(); for(int i=0;i<inputarray.length;i++){ if(!hmap.isEmpty() && hmap.containsKey(inputarray[i])){ hmap.put(inputarray[i], Integer.valueOf(hmap.get(inputarray[i])+1)); } else hmap.put(inputarray[i],1); } for(String key:hmap.keySet()){ if(hmap.get(key)==2){ result=key; break; } } return result; } public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n=sc.nextInt(); String resultArray[]=new String[n]; int index=0; while(n>0){ int length=sc.nextInt(); String input=""; for(int i=0;i<length;i++){ input+=sc.next(); input+=" "; } resultArray[index]=stringWithTwo(input); index++; n--; } System.out.println(Arrays.toString(resultArray)); sc.close(); } }
27.458333
84
0.515175
bf8de57464249d70b8c5d5ea5cf2fcd166940311
19,133
package fi.riista.util.jpa; import com.google.common.base.Preconditions; import fi.riista.feature.common.entity.EntityLifecycleFields_; import fi.riista.feature.common.entity.HasID; import fi.riista.feature.common.entity.LifecycleEntity; import fi.riista.feature.common.entity.LifecycleEntity_; import fi.riista.util.DateUtil; import io.vavr.Function3; import org.joda.time.DateTime; import org.joda.time.Interval; import org.joda.time.LocalDate; import org.springframework.data.jpa.domain.Specification; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Stream; public final class JpaSpecs { private JpaSpecs() { throw new AssertionError(); } @Nonnull public static <T> Specification<T> conjunction() { return (root, query, cb) -> cb.conjunction(); } @Nonnull public static <T> Specification<T> disjunction() { return (root, query, cb) -> cb.disjunction(); } @Nonnull public static <ID extends Serializable, T extends HasID<ID>> Specification<T> withId(@Nonnull final ID id) { Objects.requireNonNull(id); return (root, query, cb) -> cb.equal(root.get(root.getModel().getId(id.getClass())), id); } @Nonnull public static <ID extends Serializable, T extends HasID<ID>> Specification<T> withIds( @Nullable final Collection<ID> ids) { return (root, query, cb) -> JpaPreds.idInCollection(cb, root, ids); } @Nonnull public static <ID extends Serializable, T extends HasID<ID>> Specification<T> withId( @Nonnull final SingularAttribute<? super T, ID> attribute, @Nonnull final ID id) { Objects.requireNonNull(attribute, "attribute must not be null"); Objects.requireNonNull(id, "id must not be null"); return (root, query, cb) -> cb.equal(root.get(attribute), id); } @Nonnull public static <T> Specification<T> isNull(@Nonnull final SingularAttribute<? super T, ?> attribute) { Objects.requireNonNull(attribute); return (root, query, cb) -> cb.isNull(root.get(attribute)); } @Nonnull public static <T> Specification<T> isNotNull(@Nonnull final SingularAttribute<? super T, ?> attribute) { Objects.requireNonNull(attribute); return (root, query, cb) -> cb.isNotNull(root.get(attribute)); } @Nonnull public static <T, U> Specification<T> equal( @Nonnull final SingularAttribute<? super T, U> attribute, @Nullable final U value) { Objects.requireNonNull(attribute, "attribute must not be null"); return (root, query, cb) -> JpaPreds.equal(cb, root.get(attribute), value); } @Nonnull public static <T, X, Y> Specification<T> equal( @Nonnull final SingularAttribute<? super T, X> attribute1, @Nonnull final SingularAttribute<? super X, Y> attribute2, @Nullable final Y value) { Objects.requireNonNull(attribute1, "attribute1 must not be null"); Objects.requireNonNull(attribute2, "attribute2 must not be null"); return (root, query, cb) -> JpaPreds.equal(cb, root.join(attribute1).get(attribute2), value); } @Nonnull public static <T, X, Y> Specification<T> equal( @Nonnull final PluralAttribute<? super T, ?, X> attribute1, @Nonnull final SingularAttribute<? super X, Y> attribute2, @Nullable final Y value) { Objects.requireNonNull(attribute1, "attribute1 must not be null"); Objects.requireNonNull(attribute2, "attribute2 must not be null"); return (root, query, cb) -> JpaPreds.equal(cb, CriteriaUtils.join(root, attribute1).get(attribute2), value); } @Nonnull public static <T, X, Y, Z> Specification<T> equal( @Nonnull final SingularAttribute<? super T, X> attribute1, @Nonnull final SingularAttribute<? super X, Y> attribute2, @Nonnull final SingularAttribute<? super Y, Z> attribute3, @Nullable final Z value) { Objects.requireNonNull(attribute1, "attribute1 must not be null"); Objects.requireNonNull(attribute2, "attribute2 must not be null"); Objects.requireNonNull(attribute3, "attribute3 must not be null"); return (root, query, cb) -> JpaPreds.equal(cb, root.join(attribute1).join(attribute2).get(attribute3), value); } @Nonnull public static <T, U> Specification<T> notEqual( @Nonnull final SingularAttribute<? super T, U> attribute, @Nullable final U value) { Objects.requireNonNull(attribute, "attribute must not be null"); return (root, query, cb) -> { final Path<U> path = root.get(attribute); return value == null ? cb.isNotNull(path) : cb.or(cb.isNull(path), cb.notEqual(path, value)); }; } @Nonnull public static <T, U> Specification<T> isNotEmpty(@Nonnull final PluralAttribute<T, java.util.Set<U>, U> attribute) { Objects.requireNonNull(attribute); return (root, query, cb) -> cb.isNotEmpty(root.get(attribute)); } @Nonnull public static <T, U> Specification<T> inCollection( @Nonnull final SingularAttribute<? super T, U> attribute, @Nullable final Collection<? extends U> values) { Objects.requireNonNull(attribute, "attribute must not be null"); return (root, query, cb) -> JpaPreds.inCollection(cb, root.get(attribute), values); } @Nonnull @SafeVarargs public static <T, U> Specification<T> inArray( @Nonnull final SingularAttribute<? super T, U> attribute, @Nullable final U... values) { Objects.requireNonNull(attribute, "attribute must not be null"); return inCollection(attribute, values != null ? Arrays.asList(values) : Collections.<U> emptyList()); } @Nonnull public static <T, U> Specification<T> inCollection( @Nonnull final SetAttribute<? super T, U> setAttribute, @Nullable final Collection<U> values) { Objects.requireNonNull(setAttribute, "setAttribute must not be null"); return (root, query, cb) -> JpaPreds.inCollection(cb, root.join(setAttribute), values); } @Nonnull public static <T, ID extends Serializable, U extends HasID<ID>> Specification<T> inIdCollection( @Nonnull final SingularAttribute<? super T, U> attribute, @Nonnull final SingularAttribute<? super U, ID> idAttribute, @Nullable final Collection<ID> values) { Objects.requireNonNull(attribute, "attribute must not be null"); Objects.requireNonNull(idAttribute, "idAttribute must not be null"); return (root, query, cb) -> JpaPreds.inCollection(cb, root.get(attribute).get(idAttribute), values); } @Nonnull public static <T, ID extends Serializable, U extends HasID<ID>> Specification<T> hasRelationWithId( @Nonnull final SingularAttribute<? super T, U> entityAttribute, @Nonnull final SingularAttribute<? super U, ID> idAttribute, @Nonnull final ID id) { Objects.requireNonNull(entityAttribute, "entityAttribute must not be null"); Objects.requireNonNull(idAttribute, "idAttribute must not be null"); Objects.requireNonNull(id, "id must not be null"); return (root, query, cb) -> cb.equal(root.get(entityAttribute).get(idAttribute), id); } @Nonnull public static <T, U, ID extends Serializable, V extends HasID<ID>> Specification<T> joinPathToId( @Nonnull final SingularAttribute<? super T, U> entityAttribute1, @Nonnull final SingularAttribute<? super U, V> entityAttribute2, @Nonnull final SingularAttribute<? super V, ID> idAttribute, @Nonnull final ID id) { Objects.requireNonNull(entityAttribute1, "entityAttribute1 must not be null"); Objects.requireNonNull(entityAttribute2, "entityAttribute2 must not be null"); Objects.requireNonNull(idAttribute, "idAttribute must not be null"); Objects.requireNonNull(id, "id must not be null"); return (root, query, cb) -> cb.equal(root.join(entityAttribute1).get(entityAttribute2).get(idAttribute), id); } @Nonnull public static <T, U, V> Specification<U> pathToValueExists( @Nonnull final SingularAttribute<T, U> entityAttribute1, @Nonnull final SingularAttribute<? super T, V> entityAttribute2, @Nonnull final V value) { Objects.requireNonNull(entityAttribute1, "entityAttribute1 must not be null"); Objects.requireNonNull(entityAttribute2, "entityAttribute2 must not be null"); Objects.requireNonNull(value, "value must not be null"); return JpaSubQuery.inverseOf(entityAttribute1) .exists((root, cb) -> cb.equal(root.get(entityAttribute2), value)); } @Nonnull public static <T, U, ID extends Serializable, V extends HasID<ID>> Specification<U> pathToIdExists( @Nonnull final SingularAttribute<T, U> entityAttribute1, @Nonnull final SingularAttribute<? super T, V> entityAttribute2, @Nonnull final SingularAttribute<? super V, ID> idAttribute, @Nonnull final ID id) { Objects.requireNonNull(entityAttribute1, "entityAttribute1 must not be null"); Objects.requireNonNull(entityAttribute2, "entityAttribute2 must not be null"); Objects.requireNonNull(idAttribute, "idAttribute must not be null"); Objects.requireNonNull(id, "id must not be null"); return JpaSubQuery.inverseOf(entityAttribute1) .exists((root, cb) -> cb.equal(root.get(entityAttribute2).get(idAttribute), id)); } @Nonnull public static <T, U, V, ID extends Serializable, X extends HasID<ID>> Specification<U> pathToIdExists( @Nonnull final SingularAttribute<T, U> entityAttribute1, @Nonnull final SingularAttribute<? super T, V> entityAttribute2, @Nonnull final SingularAttribute<? super V, X> entityAttribute3, @Nonnull final SingularAttribute<? super X, ID> idAttribute, @Nonnull final ID id) { Objects.requireNonNull(entityAttribute1, "entityAttribute1 must not be null"); Objects.requireNonNull(entityAttribute2, "entityAttribute2 must not be null"); Objects.requireNonNull(entityAttribute3, "entityAttribute3 must not be null"); Objects.requireNonNull(idAttribute, "idAttribute must not be null"); Objects.requireNonNull(id, "id must not be null"); return JpaSubQuery.inverseOf(entityAttribute1) .exists((root, cb) -> cb.equal(root.join(entityAttribute2).get(entityAttribute3).get(idAttribute), id)); } @Nonnull public static <T> Specification<T> withinInterval( @Nonnull final SingularAttribute<? super T, DateTime> dateAttribute, @Nonnull final Interval interval) { Objects.requireNonNull(dateAttribute, "dateAttribute must not be null"); Objects.requireNonNull(interval, "interval must not be null"); return (root, query, cb) -> JpaPreds.withinInterval(cb, root.get(dateAttribute), interval); } @Nonnull public static <T> Specification<T> withinInterval( @Nonnull final SingularAttribute<? super T, DateTime> dateAttribute, @Nullable final LocalDate beginDate, @Nullable final LocalDate endDate) { Objects.requireNonNull(dateAttribute, "dateAttribute must not be null"); return (root, query, cb) -> JpaPreds.withinInterval(cb, root.get(dateAttribute), beginDate, endDate); } @Nonnull public static <T> Specification<T> withinInterval( @Nonnull final SingularAttribute<? super T, LocalDate> beginDateAttribute, @Nonnull final SingularAttribute<? super T, LocalDate> endDateAttribute, @Nonnull final LocalDate dateOfInterest) { Objects.requireNonNull(beginDateAttribute, "beginDateAttribute must not be null"); Objects.requireNonNull(endDateAttribute, "endDateAttribute must not be null"); Objects.requireNonNull(dateOfInterest, "dateOfInterest must not be null"); return (root, query, cb) -> JpaPreds.withinInterval( cb, root.get(beginDateAttribute), root.get(endDateAttribute), dateOfInterest); } @Nonnull public static <T> Specification<T> overlapsInterval( @Nonnull final SingularAttribute<? super T, LocalDate> dateAttribute, @Nonnull final Interval interval) { Objects.requireNonNull(dateAttribute, "dateAttribute must not be null"); Objects.requireNonNull(interval, "interval must not be null"); return (root, query, cb) -> JpaPreds.overlapsInterval(cb, root.get(dateAttribute), interval); } @Nonnull public static <T> Specification<T> overlapsInterval( @Nonnull final SingularAttribute<? super T, LocalDate> beginDateAttribute, @Nonnull final SingularAttribute<? super T, LocalDate> endDateAttribute, @Nullable final DateTime beginTime, @Nullable final DateTime endTime) { return (root, query, cb) -> JpaPreds.overlapsInterval( cb, root.get(beginDateAttribute), root.get(endDateAttribute), beginTime, endTime); } @Nonnull public static <T> Specification<T> withinHuntingYear( @Nonnull final SingularAttribute<? super T, DateTime> dateAttribute, final int firstCalendarYearOfHuntingYear) { return withinInterval(dateAttribute, DateUtil.huntingYearInterval(firstCalendarYearOfHuntingYear)); } @Nonnull public static <T extends LifecycleEntity<? extends Serializable>> Specification<T> creationTimeOlderThan( @Nonnull final DateTime olderThan) { Objects.requireNonNull(olderThan); return (root, query, cb) -> { final Path<DateTime> dateField = root.get(LifecycleEntity_.lifecycleFields).get(EntityLifecycleFields_.creationTime); return cb.lessThan(dateField, olderThan); }; } @Nonnull public static <T extends LifecycleEntity<? extends Serializable>> Specification<T> creationTimeBetween( @Nonnull final DateTime start, @Nonnull final DateTime end) { Objects.requireNonNull(start); Objects.requireNonNull(end); return (root, query, cb) -> { final Path<DateTime> dateField = root.get(LifecycleEntity_.lifecycleFields).get(EntityLifecycleFields_.creationTime); return cb.between(dateField, start, end); }; } @Nonnull public static <T extends LifecycleEntity<? extends Serializable>> Specification<T> dateFieldBefore( @Nonnull final SingularAttribute<? super T, DateTime> dateAttribute, @Nonnull final DateTime before) { Objects.requireNonNull(dateAttribute, "dateAttribute must not be null"); Objects.requireNonNull(before, "before must not be null"); return (root, query, cb) -> cb.lessThan(root.get(dateAttribute), before); } @Nonnull public static <T, U> Specification<T> fetch(@Nonnull final SingularAttribute<? super T, U> attribute) { return fetch(attribute, null); } @Nonnull public static <T, U> Specification<T> fetch( @Nonnull final SingularAttribute<? super T, U> attribute, @Nullable final JoinType joinType) { Objects.requireNonNull(attribute, "attribute must not be null"); return (root, query, cb) -> { if (joinType != null) { root.fetch(attribute, joinType); } else { root.fetch(attribute); } return cb.and(); }; } @Nonnull public static <T> Specification<T> likeIgnoreCase( @Nonnull final SingularAttribute<? super T, String> attribute, @Nonnull final String value) { Objects.requireNonNull(attribute, "attribute must not be null"); Objects.requireNonNull(value, "value must not be null"); return (root, query, cb) -> JpaPreds.containsLikeIgnoreCase(cb, root.get(attribute), value); } @Nonnull public static <T extends LifecycleEntity<? extends Serializable>> Specification<T> notSoftDeleted() { return (root, query, cb) -> JpaPreds.notSoftDeleted(cb, root); } @Nonnull public static <T> Specification<T> and(@Nonnull final Collection<? extends Specification<T>> specs) { Objects.requireNonNull(specs); Preconditions.checkArgument(specs.size() > 0, "At least one specification must be given"); return reduceConjunction(specs::stream); } @Nonnull @SafeVarargs public static <T> Specification<T> and(@Nonnull final Specification<T>... specs) { Objects.requireNonNull(specs); Preconditions.checkArgument(specs.length > 0, "At least one specification must be given"); return specs.length == 1 ? specs[0] : reduceConjunction(() -> Arrays.stream(specs)); } @Nonnull public static <T> Specification<T> or(@Nonnull final Collection<? extends Specification<T>> specs) { Objects.requireNonNull(specs); Preconditions.checkArgument(specs.size() > 0, "At least one specification must be given"); return reduceDisjunction(specs::stream); } @Nonnull @SafeVarargs public static <T> Specification<T> or(@Nonnull final Specification<T>... specs) { Objects.requireNonNull(specs); Preconditions.checkArgument(specs.length > 0, "At least one specification must be given"); return specs.length == 1 ? specs[0] : reduceDisjunction(() -> Arrays.stream(specs)); } private static <T> Specification<T> reduceConjunction(final Supplier<Stream<? extends Specification<T>>> streamSupplier) { return reduce(streamSupplier, (first, second, cb) -> cb.and(first, second)); } private static <T> Specification<T> reduceDisjunction(final Supplier<Stream<? extends Specification<T>>> streamSupplier) { return reduce(streamSupplier, (first, second, cb) -> cb.or(first, second)); } private static <T> Specification<T> reduce(final Supplier<Stream<? extends Specification<T>>> streamSupplier, final Function3<Predicate, Predicate, CriteriaBuilder, Predicate> reducer) { return (root, query, cb) -> streamSupplier.get() .map(spec -> spec.toPredicate(root, query, cb)) .reduce((p1, p2) -> reducer.apply(p1, p2, cb)) .get(); } }
42.143172
126
0.673026
4071ad1e95213a8f4c3d41d209628a4c3da11a17
3,594
package org.ftccommunity.ftcxtensible.util; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.hardware.DcMotor; public final class RandomUtility { /** * Changes the target position of a {@link DcMotor} by if a button on a {@link com.qualcomm.robotcore.hardware.Gamepad} * has been pressed. The button is represented by a {@code boolean} value: {@code true} if the * button is currently pressed, and {@code false} if the button is not currently pressed. * * @param button the current button state * (example: {@link com.qualcomm.robotcore.hardware.Gamepad#a} * @param lastButtonState the last state that the button was in. * In other words, the value of the same button as it was in the last * iteration of the {@link OpMode#loop()} * @param dcMotor the {@code DcMotor} to adjust the target parameter. This doesn't configure * the motor for use of a target position. This just the pre-existing target * position of the motor * @param incrementByAmount by how much should the target position be incremented by * @return the current button value. This allows for: * <code>lastTime = changeMotorTargetOnButtonPress(gamepad1.a, lastTime, motor, 720);</code> */ static boolean changeMotorTargetOnButtonPress(boolean button, boolean lastButtonState, final DcMotor dcMotor, int incrementByAmount) { if (dcMotor == null) throw new NullPointerException("dcMotor can't be null"); if (!lastButtonState && button) { dcMotor.setTargetPosition(dcMotor.getTargetPosition() + incrementByAmount); } return button; } /** * Changes the target position of a {@link DcMotor} by if a button on a {@link com.qualcomm.robotcore.hardware.Gamepad} * has been released. The button is represented by a {@code boolean} value: {@code true} if the * button is currently pressed, and {@code false} if the button is not currently pressed. * * @param button the current button state * (example: {@link com.qualcomm.robotcore.hardware.Gamepad#a} * @param lastButtonState the last state that the button was in. * In other words, the value of the same button as it was in the last * iteration of the {@link OpMode#loop()} * @param dcMotor the {@code DcMotor} to adjust the target parameter. This doesn't configure * the motor for use of a target position. This just the pre-existing target * position of the motor * @param incrementByAmount by how much should the target position be incremented by * @return the current button value. This allows for: * <code>lastTime = changeMotorTargetOnButtonPress(gamepad1.a, lastTime, motor, 720);</code> */ static boolean changeMotorTargetOnButtonRelease(boolean button, boolean lastButtonState, final DcMotor dcMotor, int incrementByAmount) { if (dcMotor == null) throw new NullPointerException("dcMotor can't be null"); if (lastButtonState && !button) { dcMotor.setTargetPosition(dcMotor.getTargetPosition() + incrementByAmount); } return button; } boolean closeTo(double current, double wanted, double tolerance) { return Math.abs(current - wanted) < tolerance; } }
57.967742
140
0.646355
a7c21e8a3e2bee3d14ea2a9d36e16f041c0b18d1
3,155
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ec2.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * DescribeClientVpnEndpointsResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeClientVpnEndpointsResultStaxUnmarshaller implements Unmarshaller<DescribeClientVpnEndpointsResult, StaxUnmarshallerContext> { public DescribeClientVpnEndpointsResult unmarshall(StaxUnmarshallerContext context) throws Exception { DescribeClientVpnEndpointsResult describeClientVpnEndpointsResult = new DescribeClientVpnEndpointsResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return describeClientVpnEndpointsResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("clientVpnEndpoint", targetDepth)) { describeClientVpnEndpointsResult.withClientVpnEndpoints(new ArrayList<ClientVpnEndpoint>()); continue; } if (context.testExpression("clientVpnEndpoint/item", targetDepth)) { describeClientVpnEndpointsResult.withClientVpnEndpoints(ClientVpnEndpointStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("nextToken", targetDepth)) { describeClientVpnEndpointsResult.setNextToken(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return describeClientVpnEndpointsResult; } } } } private static DescribeClientVpnEndpointsResultStaxUnmarshaller instance; public static DescribeClientVpnEndpointsResultStaxUnmarshaller getInstance() { if (instance == null) instance = new DescribeClientVpnEndpointsResultStaxUnmarshaller(); return instance; } }
40.448718
146
0.696989
084bbd0ed34149b60fd321e359fbf8933626a6f5
407
package com.xpleemoon.main.router.path; public class PathConstants { private static final String PATH_ROOT = "/main"; private static final String PATH_VIEW = "/view"; private static final String PATH_SERVICE = "/service"; public static final String PATH_VIEW_MAIN = PATH_ROOT + PATH_VIEW + "/main"; public static final String PATH_SERVICE_MAIN = PATH_ROOT + PATH_SERVICE + "/main"; }
33.916667
86
0.732187
ebdf80a3700d918bfcc69eee6f718aff9a2c48dc
10,261
/* * 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 com.com2008.journalmanagementsystem.frame; import com.com2008.journalmanagementsystem.model.EditorOnBoard; import com.com2008.journalmanagementsystem.model.Journal; import com.com2008.journalmanagementsystem.util.database.Database; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Box; import javax.swing.BoxLayout; import static javax.swing.BoxLayout.Y_AXIS; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; /** * * @author Jorda */ public class PassChiefPanel extends javax.swing.JPanel { /** * */ private static final long serialVersionUID = 1L; /** * Creates new form PassChiefPanel * * Panel that allows chief editors to pass the chief editor role */ public PassChiefPanel(String email) { initComponents(); //get journals and the amount of editors on the //board of that journal List<Journal> journals = null; List<List<EditorOnBoard>> editorBoards = new ArrayList<>(); try { journals = Database.read("Journal", new Journal(null,null,email)); for (Journal journal : journals){ List<EditorOnBoard> journalEditors = Database.read("EditorOnBoard", new EditorOnBoard(journal.getIssn(),null)); editorBoards.add(journalEditors); } } catch (SQLException e) { e.printStackTrace(); } //for each editor get the journal info and //create a button for each editor which can become //the new chief editorListPanel.setLayout(new BoxLayout(editorListPanel,Y_AXIS)); ArrayList<JButton> buttonList = new ArrayList<>(); for (int i=0; i<journals.size();i++){ JLabel journalLabel = new JLabel("Journal: "+journals.get(i).getJournalName()); journalLabel.setFont(new Font("Tahoma",Font.PLAIN,14)); editorListPanel.add(journalLabel); editorListPanel.add(Box.createRigidArea(new Dimension(20, 20))); if (editorBoards.get(i).size() > 1) { //if you aren't the only editor for (int j=0; j<editorBoards.get(i).size();j++){ if (!(email.toLowerCase().equals(editorBoards.get(i).get(j).getEmail().toLowerCase()))) { //skip if the current editor on board is user buttonList.add(new JButton("Change Chief to "+editorBoards.get(i).get(j).getEmail())); //add button listener with information from the current journal buttonList.get(buttonList.size()-1).addActionListener( new PassChiefPanel.ChangeChiefActionListener( journals.get(i),email,editorBoards.get(i).get(j).getEmail())); editorListPanel.add(buttonList.get(buttonList.size()-1)); editorListPanel.add(Box.createRigidArea(new Dimension(10, 10))); } } editorListPanel.add(Box.createRigidArea(new Dimension(10, 10))); } else { JLabel noEditorsLabel = new JLabel("There are no other editors on this journal"); editorListPanel.add(noEditorsLabel); editorListPanel.add(Box.createRigidArea(new Dimension(20, 20))); } } //refresh the panel editorListPanel.revalidate(); editorListPanel.repaint(); } private class ChangeChiefActionListener implements ActionListener { String userEmail; String newEmail; Journal thisJournal; public ChangeChiefActionListener(Journal jo, String userEm, String newEm) { this.userEmail = userEm; this.newEmail = newEm; this.thisJournal = jo; } public void actionPerformed(ActionEvent e) { //get the most up to date version of the journal\ Journal updatedJournal = null; try { updatedJournal = Database.read("Journal", new Journal(thisJournal.getIssn(),null,null)).get(0); } catch (SQLException ex) { Logger.getLogger(PassChiefPanel.class.getName()).log(Level.SEVERE, null, ex); } //if you are still the chief of this journal //(user may have tranferred chief and tried to press the button again) if (updatedJournal.getCheifEmail().toLowerCase().equals(userEmail.toLowerCase())){ try { Database.update("Journal",thisJournal,new Journal(null,null,newEmail)); int journalAmount = Database.read("Journal", new Journal(null,null,userEmail)).size(); System.out.println(journalAmount); if (journalAmount == 0){ //if you are no longer chief of any journal //log out user since you no longer have chief privilidges JOptionPane.showMessageDialog(null, "You are no longer chief " + "editor of any journals\n You will now be logged out", "Logout", JOptionPane.INFORMATION_MESSAGE); JFrame fr = (JFrame)SwingUtilities.getRoot(editorListPanel); fr.dispose(); LoginFrame newLogFrame = new LoginFrame(); newLogFrame.setVisible(true); } } catch (SQLException ex) { Logger.getLogger(PassChiefPanel.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog(null, "You are no longer the chief of " + "this journal", "Error", JOptionPane.ERROR_MESSAGE); JButton parentButton = (JButton)e.getSource(); parentButton.setEnabled(false); } } } /** * 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() { editorListPanel = new javax.swing.JPanel(); titlePanel = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); javax.swing.GroupLayout editorListPanelLayout = new javax.swing.GroupLayout(editorListPanel); editorListPanel.setLayout(editorListPanelLayout); editorListPanelLayout.setHorizontalGroup( editorListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 380, Short.MAX_VALUE) ); editorListPanelLayout.setVerticalGroup( editorListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 27, Short.MAX_VALUE) ); lblTitle.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N lblTitle.setText("Change Chief Editor"); javax.swing.GroupLayout titlePanelLayout = new javax.swing.GroupLayout(titlePanel); titlePanel.setLayout(titlePanelLayout); titlePanelLayout.setHorizontalGroup( titlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(titlePanelLayout.createSequentialGroup() .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); titlePanelLayout.setVerticalGroup( titlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(titlePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editorListPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(titlePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editorListPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(229, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel editorListPanel; private javax.swing.JLabel lblTitle; private javax.swing.JPanel titlePanel; // End of variables declaration//GEN-END:variables }
46.640909
169
0.637462
b7d3be6ad62c4bddfeece0d70367ea5b88978fad
1,118
/* * Copyright (c) 2010-2013 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.05.20 at 05:41:15 PM CEST // package com.evolveum.prism.xml.ns._public.types_3; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import com.evolveum.midpoint.prism.JaxbVisitable; import com.evolveum.midpoint.prism.JaxbVisitor; import com.evolveum.midpoint.prism.Objectable; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ObjectType", propOrder = { }) public abstract class ObjectType implements JaxbVisitable, Objectable { @Override public void accept(JaxbVisitor visitor) { visitor.visit(this); } }
30.216216
108
0.758497
15cd5ceea58b9ad6ff7a3ea0e6f5b3da602cd46b
2,101
/* * Permute.java */ import java.util.Random; /** * A utility class for permuting various things in various ways. */ public class Permute { // --- the basic function --- /** * Permute the elements of p. */ public static void permute(int[] p, Random random) { int temp; // a decent algorithm, I think, and in any case better than random retries // you could optimize by calling random.nextInt(p.length!) // and taking remainders on division by i, // but that would only work if p.length! fit within the precision. for (int i=p.length; i>1; i--) { // choose one of the i remaining values to go in spot i-1 // note, iterate only down to i=2, at i=1 there is only one value and one spot left int j = random.nextInt(i); if (j != i-1) { // swap j and i-1 temp = p[i-1]; p[i-1] = p[j]; p[j] = temp; } } } // --- helpers --- /** * Make an array of length n using the numbers from base to base+(n-1), in order. */ public static int[] sequence(int base, int n) { int[] p = new int[n]; for (int i=0; i<n; i++) p[i] = base+i; return p; } /** * Permute the numbers from 0 to n-1. */ public static int[] permute(int n, Random random) { int[] p = sequence(0,n); permute(p,random); return p; } /** * Make a random array of length n1 using the numbers from 0 to n2-1, * using every number once before using any number twice. */ public static int[] permute(int n1, int n2, Random random) { int[] p = new int[n1]; if (n1 <= n2) { // there are enough numbers to go around int[] q = permute(n2,random); System.arraycopy(q,0,p,0,n1); } else { // have to use some numbers twice int i = 0; for ( ; i<n2; i++) p[i] = i; for ( ; i<n1; i++) p[i] = random.nextInt(n2); permute(p,random); } return p; } }
24.430233
93
0.518325
0fb72a94df459660cea3cbcde4da9a9ac5f354a3
593
package org.tlh.examstack.module.sys.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.tlh.examstack.module.sys.config.freemarker.ShiroTags; import javax.annotation.PostConstruct; @Configuration public class FreeMarkerConfig { @Autowired private freemarker.template.Configuration configuration; @PostConstruct public void setSharedVariable() { try { configuration.setSharedVariable("shiro", new ShiroTags()); } catch (Exception e) { e.printStackTrace(); } } }
24.708333
64
0.768971
9994448871c84e27d942a552120887747f73b70b
1,697
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig.errorhandling; import com.intellij.codeInspection.LocalInspectionTool; import com.siyeh.ig.LightJavaInspectionTestCase; public class ThrownCaughtLocallyInspectionTest extends LightJavaInspectionTestCase { @Override protected LocalInspectionTool getInspection() { return new ThrowCaughtLocallyInspection(); } public void testLambdaOrAnonymous() { doTest("class C {\n" + "private Object bar() {\n" + " try{\n" + " Runnable runnable = () -> {\n" + " throw new RuntimeException();\n" + " };\n" + "" + " Runnable runnableLambda = ()-> {\n" + "" + " throw new RuntimeException();\n" + " " + " };\n" + " }\n" + " catch (RuntimeException e){\n" + " throw new RuntimeException(e);\n" + " }\n" + " return null;\n" + " }" + "}"); } }
33.94
84
0.560401
fccb26b1e9828b9b88b298c4842a4b74e2e10267
1,439
package cn.com.i_zj.udrive_az.web; import android.graphics.Bitmap; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; /** * @author JayQiu * @create 2018/11/19 * @Describe */ public class UWebViewClient extends WebViewClient { private WebStatusListener webStatusListener; @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { String title = view.getTitle(); if (webStatusListener != null) { webStatusListener.start(); } super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); String title = view.getTitle(); if (webStatusListener != null) { webStatusListener.loadFinish(title); } } public void setWebStatusListener(WebStatusListener webStatusListener) { this.webStatusListener = webStatusListener; } public interface WebStatusListener { void start(); void loadFinish(String title); } }
24.389831
87
0.676859