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
8ef3b1de10dac1f150cc1f3005e307cad2045064
1,201
/* * 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 org.redkale.test.convert; import org.redkale.convert.json.JsonConvert; /** * * @author zhangjx */ public class One { protected String key; protected int code; protected byte[] bytes = new byte[]{3, 4, 5}; protected int[] ints = new int[]{3000, 4000, 5000}; public One(int code) { this.code = code; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public int[] getInts() { return ints; } public void setInts(int[] ints) { this.ints = ints; } public String toString() { return JsonConvert.root().convertTo(this); } }
18.765625
80
0.552873
d2c7b55e51822aea8cd2cf96a309358cb9206822
1,621
package org.wikipedia.feed.mainpage; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.wikipedia.R; import org.wikipedia.feed.view.FeedAdapter; import org.wikipedia.feed.view.StaticCardView; import org.wikipedia.history.HistoryEntry; import java.text.DateFormat; import java.util.Date; public class MainPageCardView extends StaticCardView<MainPageCard> { public MainPageCardView(@NonNull Context context) { super(context); } @Override public void setCard(@NonNull final MainPageCard card) { super.setCard(card); setTitle(getString(R.string.view_main_page_card_title)); setSubtitle(String.format(getString(R.string.view_main_page_card_subtitle), DateFormat.getDateInstance().format(new Date()))); setIcon(R.drawable.ic_today_24dp); setContainerBackground(R.color.green50); setAction(R.drawable.ic_arrow_forward_black_24dp, R.string.view_main_page_card_action); } protected void onContentClick(View v) { goToMainPage(); } protected void onActionClick(View v) { goToMainPage(); } @Override public void setCallback(@Nullable FeedAdapter.Callback callback) { super.setCallback(callback); } private void goToMainPage() { if (getCallback() != null && getCard() != null) { getCallback().onSelectPage(getCard(), new HistoryEntry(MainPageClient.getMainPageTitle(), HistoryEntry.SOURCE_FEED_MAIN_PAGE)); } } }
31.173077
95
0.697717
dd733c602ce2fab165ccf234026df0bbacd50aac
1,756
package org.ovirt.engine.ui.uicommonweb.models.hosts; import java.util.Collections; import org.ovirt.engine.core.compat.*; import org.ovirt.engine.ui.uicompat.*; import org.ovirt.engine.core.common.businessentities.*; import org.ovirt.engine.core.common.vdscommands.*; import org.ovirt.engine.core.common.queries.*; import org.ovirt.engine.core.common.action.*; import org.ovirt.engine.ui.frontend.*; import org.ovirt.engine.ui.uicommonweb.*; import org.ovirt.engine.ui.uicommonweb.models.*; import org.ovirt.engine.core.common.*; import org.ovirt.engine.core.common.businessentities.*; import org.ovirt.engine.ui.uicommonweb.*; import org.ovirt.engine.ui.uicommonweb.models.*; @SuppressWarnings("unused") public class HostVLan extends Model { private VdsNetworkInterface privateInterface; public VdsNetworkInterface getInterface() { return privateInterface; } public void setInterface(VdsNetworkInterface value) { privateInterface = value; } private String name; public String getName() { return name; } public void setName(String value) { if (!StringHelper.stringsEqual(name, value)) { name = value; OnPropertyChanged(new PropertyChangedEventArgs("Name")); } } private String networkName; public String getNetworkName() { return networkName; } public void setNetworkName(String value) { if (!StringHelper.stringsEqual(networkName, value)) { networkName = value; OnPropertyChanged(new PropertyChangedEventArgs("NetworkName")); } } private String address; public String getAddress() { return address; } public void setAddress(String value) { if (!StringHelper.stringsEqual(address, value)) { address = value; OnPropertyChanged(new PropertyChangedEventArgs("Address")); } } }
23.413333
66
0.756834
32b21680ae0f77d81a2821214df44bbca7433cbb
1,836
// Copyright 2000-2021 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.intellij.openapi.module; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; public abstract class PrimaryModuleManager { public static final ExtensionPointName<PrimaryModuleManager> EP_NAME = new ExtensionPointName<>("com.intellij.primaryModuleManager"); /** * @return main (primary) module for IDE that supports project attach */ @Nullable public abstract Module getPrimaryModule(@NotNull Project project); private static Module getPrimaryModuleByContentRoot(@NotNull Project project) { VirtualFile baseDir = project.getBaseDir(); if (baseDir == null) { return null; } ModuleManager moduleManager = ModuleManager.getInstance(project); return ContainerUtil.find(moduleManager.getModules(), module -> Arrays.asList(ModuleRootManager.getInstance(module).getContentRoots()).contains(baseDir)); } /** * @return if exists, asks IDE customization to provide main/primary module, * otherwise use content roots of module to check if it's a main module. */ public static Module findPrimaryModule(@NotNull Project project) { for (PrimaryModuleManager primaryModuleManager : EP_NAME.getExtensions()) { Module primaryModule = primaryModuleManager.getPrimaryModule(project); if (primaryModule != null) { return primaryModule; } } return getPrimaryModuleByContentRoot(project); } }
39.913043
158
0.767974
3b125f3b67fbed1588148d87b1a2e984f74fda52
4,169
package com.oracle.dragon.model; public class LocalDragonConfiguration { private String redirect; private String ocid; private String databaseServiceURL; private String sqlDevWebAdmin; private String sqlDevWeb; private String apexURL; private String omlURL; private String graphStudioURL; private String sqlAPI; private String sodaAPI; private String version; private String apexVersion; private String ordsVersion; private String uploadBucketName; private String manualBackupBucketName; private String dbName; private String dbUserName; private String dbUserPassword; private String walletFile; private String extractedWallet; public LocalDragonConfiguration() { } public String getDatabaseServiceURL() { return databaseServiceURL; } public void setDatabaseServiceURL(String databaseServiceURL) { this.databaseServiceURL = databaseServiceURL; } public String getSqlDevWebAdmin() { return sqlDevWebAdmin; } public void setSqlDevWebAdmin(String sqlDevWebAdmin) { this.sqlDevWebAdmin = sqlDevWebAdmin; } public String getSqlDevWeb() { return sqlDevWeb; } public void setSqlDevWeb(String sqlDevWeb) { this.sqlDevWeb = sqlDevWeb; } public String getApexURL() { return apexURL; } public void setApexURL(String apexURL) { this.apexURL = apexURL; } public String getOmlURL() { return omlURL; } public void setOmlURL(String omlURL) { this.omlURL = omlURL; } public String getGraphStudioURL() { return graphStudioURL; } public void setGraphStudioURL(String graphStudioURL) { this.graphStudioURL = graphStudioURL; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getApexVersion() { return apexVersion; } public void setApexVersion(String apexVersion) { this.apexVersion = apexVersion; } public String getOrdsVersion() { return ordsVersion; } public void setOrdsVersion(String ordsVersion) { this.ordsVersion = ordsVersion; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public String getDbUserName() { return dbUserName; } public void setDbUserName(String dbUserName) { this.dbUserName = dbUserName; } public String getDbUserPassword() { return dbUserPassword; } public void setDbUserPassword(String dbUserPassword) { this.dbUserPassword = dbUserPassword; } public String getSqlAPI() { return sqlAPI; } public void setSqlAPI(String sqlAPI) { this.sqlAPI = sqlAPI; } public String getSodaAPI() { return sodaAPI; } public void setSodaAPI(String sodaAPI) { this.sodaAPI = sodaAPI; } public String getWalletFile() { return walletFile; } public void setWalletFile(String walletFile) { this.walletFile = walletFile; } public String getExtractedWallet() { return extractedWallet; } public void setExtractedWallet(String extractedWallet) { this.extractedWallet = extractedWallet; } public String getRedirect() { return redirect; } public void setRedirect(String redirect) { this.redirect = redirect; } public String getOcid() { return ocid; } public void setOcid(String ocid) { this.ocid = ocid; } public String getUploadBucketName() { return uploadBucketName; } public void setUploadBucketName(String uploadBucketName) { this.uploadBucketName = uploadBucketName; } public String getManualBackupBucketName() { return manualBackupBucketName; } public void setManualBackupBucketName(String manualBackupBucketName) { this.manualBackupBucketName = manualBackupBucketName; } }
22.058201
74
0.656512
8cc9686badd34aa637c7bc83435e8f9247c88cf7
2,498
package aug.bueno.review.microservice.integration.test; import aug.bueno.custom.MongoDataFile; import aug.bueno.custom.junit.extension.MongoSpringCustomExtension; import aug.bueno.review.microservice.domain.Review; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith({SpringExtension.class, MongoSpringCustomExtension.class}) @SpringBootTest @AutoConfigureMockMvc public class ReviewServiceIntegrationTest { @Autowired private MockMvc mockMvc; @Autowired private MongoTemplate mongoTemplate; public MongoTemplate getMongoTemplate() { return mongoTemplate; } @Test @MongoDataFile(value = "sample.json", classType = Review.class, collectionName = "Reviews") void testGetReviewByIdFound() throws Exception { mockMvc.perform(get("/review/{id}", 1)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(header().string(HttpHeaders.ETAG, "\"1\"")) .andExpect(header().string(HttpHeaders.LOCATION, "/review/1")) .andExpect(jsonPath("$.id", is("1"))) .andExpect(jsonPath("$.productId", is(1))) .andExpect(jsonPath("$.entries[0].username", is("user1"))) //TODO Adjustments in the df to perform comparative //.andExpect(jsonPath("$.entries[0].date", is(df.format(now)))) .andExpect(jsonPath("$.entries.length()", is(1))); } }
43.824561
95
0.743395
f38a40800f4064184d7f243b7e4e268e158dcd04
433
package com.trtjk.health.app.internal.di.components; import android.app.Activity; import com.trtjk.health.app.internal.di.PerActivity; import com.trtjk.health.app.internal.di.modules.ActivityModule; import dagger.Component; /** * Created by WangChao on 18/3/6. */ @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { Activity activity(); }
24.055556
85
0.787529
ad4f87f7ad0e08604072a722442102e40e304ef8
7,809
/* * 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 dk.statsbiblioteket.summa.support.enrich; import dk.statsbiblioteket.summa.common.Logging; import dk.statsbiblioteket.summa.common.Record; import dk.statsbiblioteket.summa.common.configuration.Configuration; import dk.statsbiblioteket.summa.common.filter.Payload; import dk.statsbiblioteket.summa.common.filter.object.MARCObjectFilter; import dk.statsbiblioteket.summa.common.marc.MARCObject; import dk.statsbiblioteket.util.Strings; import dk.statsbiblioteket.util.qa.QAInfo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** * Creates a sub-Record with ID 'marcdump_<counter>' that holds the cleaned MARC record (parsed and serialized). * </p><p> * Optionally the generated XML will be in directly indexable Summadocument format. This produces the fields * {@code marc_leader}, {@code marc_control_<control_field_tag>}*, {@code marc_controls} (all defined control fields), * {@code marc_field_<field><subfield_code>}*, {@code marc_fields} (all defined fields. * </p><p> * Important: This filter requires the input Payload to have its MARC-XML embedded as Record content, * not Payload stream. */ @QAInfo(level = QAInfo.Level.NORMAL, state = QAInfo.State.IN_DEVELOPMENT, author = "te") public class MARCXMLCopyFilter extends MARCObjectFilter { private static Log log = LogFactory.getLog(MARCXMLCopyFilter.class); private static XMLOutputFactory factory = null; // TODO: Consider adding direct Solr public enum OUTPUT {marc21slim, directsumma} /** * The output from the processor. * </p><p> * Optional. Default is marc21slim. Valid values are marc21slim and directsumma. */ public static final String CONF_OUTPUT = "marcxmlcopyfilter.output"; public static final String DEFAULT_OUTPUT = OUTPUT.marc21slim.toString(); private int created = 0; private final OUTPUT output; public MARCXMLCopyFilter(Configuration conf) { super(conf); output = OUTPUT.valueOf(conf.getString(CONF_OUTPUT, DEFAULT_OUTPUT)); log.info("Created MARCXMLCopyFilter with output=" + output); } @Override protected MARCObject adjust(Payload payload, MARCObject marcObject) { if (payload.getRecord() == null) { throw new IllegalArgumentException( "MARC copy does not accept Payload streams as input. A Record must be present"); } List<Record> children = payload.getRecord().getChildren() == null ? new ArrayList<Record>() : new ArrayList<>(payload.getRecord().getChildren()); children.add(new Record("marcdump_" + created++, "marc", getContent(payload, marcObject))); payload.getRecord().setChildren(children); return marcObject; } protected byte[] getContent(Payload payload, MARCObject marcObject) { try { switch (output) { case marc21slim: return getMARC(marcObject); case directsumma: return getDirectSumma(payload, marcObject); default: throw new UnsupportedOperationException("The output format '" + output + "' is unsupported"); } } catch (UnsupportedEncodingException e) { log.error("utf-8 should be supported", e); return null; } catch (XMLStreamException e) { Logging.logProcess("MARCXMLCopyFilter", "Unable to serialize MARC object to output " + output, Logging.LogLevel.WARN, payload, e); return null; } } private byte[] getMARC(MARCObject marcObject) throws UnsupportedEncodingException, XMLStreamException { return marcObject.toXML().getBytes("utf-8"); } private byte[] getDirectSumma(Payload payload, MARCObject marcObject) throws XMLStreamException, UnsupportedEncodingException { StringWriter sw = new StringWriter(); XMLStreamWriter xml = getFactory().createXMLStreamWriter(sw); xml.setDefaultNamespace("http://statsbiblioteket.dk/summa/2008/Document"); xml.writeStartDocument(); xml.writeCharacters("\n"); xml.writeStartElement("http://statsbiblioteket.dk/summa/2008/Document", "SummaDocument"); xml.writeNamespace(null, "http://statsbiblioteket.dk/summa/2008/Document"); xml.writeAttribute("version", "1.0"); xml.writeAttribute("id", "invalid"); xml.writeCharacters("\n"); xml.writeStartElement("fields"); xml.writeCharacters("\n"); if (marcObject.getLeader() != null) { writeField(xml, "marc_leader", marcObject.getLeader().getContent()); } for (MARCObject.ControlField controlField: marcObject.getControlFields()) { writeField(xml, "marc_control_" + controlField.getTag(), controlField.getContent()); writeField(xml, "marc_controls", controlField.getTag()); } for (MARCObject.DataField dataField: marcObject.getDataFields()) { for (MARCObject.SubField subField: dataField.getSubFields()) { writeField(xml, "marc_field_" + dataField.getTag() + subField.getCode(), subField.getContent()); writeField(xml, "marc_fields", dataField.getTag() + subField.getCode()); } } xml.writeEndElement(); // fields xml.writeCharacters("\n"); xml.writeEndElement(); // Summadocument xml.writeCharacters("\n"); xml.flush(); return sw.toString().getBytes("utf-8"); } private static final Pattern VALID_FIELD = Pattern.compile("[-a-zA-Z0-9_.]+"); private final Set<String> discarded = new HashSet<>(); private void writeField(XMLStreamWriter xml, String field, String content) throws XMLStreamException { if (content == null || content.isEmpty()) { return; } if (!VALID_FIELD.matcher(field).matches()) { discarded.add(field); return; } xml.writeCharacters(" "); xml.writeStartElement("field"); xml.writeAttribute("name", field); xml.writeCharacters(content); xml.writeEndElement(); xml.writeCharacters("\n"); } private synchronized XMLOutputFactory getFactory() { if (factory == null) { factory = XMLOutputFactory.newInstance(); } return factory; } @Override public void close(boolean success) { super.close(success); if (discarded.isEmpty()) { log.info("Closing MARCXMLCopyFilter with no invalid field names"); } else { log.info("Closing MARCXMLCopyFilter with " + discarded + " unique discarded field names: " + Strings.join(discarded, ", ")); } } }
41.31746
118
0.660008
09151f03ec29a8912315df3d8e55ff6a00527fa4
3,380
package edu.umich.soar.gridmap2d; public enum Direction { NONE (0, Names.kNone, 0, new int[] {0, 0}) { }, NORTH (1, Names.kNorth, 3 * Math.PI / 2, new int[] {0, -1}) { }, EAST (2, Names.kEast, 0, new int[] {1, 0}) { }, SOUTH (4, Names.kSouth, Math.PI / 2, new int[] {0, 1}) { }, WEST (8, Names.kWest, Math.PI, new int[] {-1, 0}) { }; private final int indicator; private final String id; private final double radians; private final int[] delta; private Direction backward; private Direction left; private Direction right; static { Direction.NORTH.backward = Direction.SOUTH; Direction.EAST.backward = Direction.WEST; Direction.SOUTH.backward = Direction.NORTH; Direction.WEST.backward = Direction.EAST; Direction.NORTH.left = Direction.WEST; Direction.EAST.left = Direction.NORTH; Direction.SOUTH.left = Direction.EAST; Direction.WEST.left = Direction.SOUTH; Direction.NORTH.right = Direction.EAST; Direction.EAST.right = Direction.SOUTH; Direction.SOUTH.right = Direction.WEST; Direction.WEST.right = Direction.NORTH; } Direction(int indicator, String id, double radians, int[] delta) { this.indicator = indicator; this.id = id; this.radians = radians; this.delta = delta; } public int indicator() { return indicator; } public String id() { return id; } public double radians() { return radians; } public Direction backward() { return backward; } public Direction left() { return left; } public Direction right() { return right; } public static Direction parse(String name) { if (name.length() == 0) { return null; } switch (name.charAt(0)) { case 'N': case 'n': if (name.equalsIgnoreCase(Direction.NONE.id)) { return Direction.NONE; } // assume north return Direction.NORTH; case 'E': case 'e': return Direction.EAST; case 'S': case 's': return Direction.SOUTH; case 'W': case 'w': return Direction.WEST; default: break; } return null; } // translate point toward cell in direction, storing result in destination // if destination null, use point public static int[] translate(int[] point, Direction direction, int[] destination) { if (destination == null) { destination = point; } destination[0] = point[0] + direction.delta[0]; destination[1] = point[1] + direction.delta[1]; return destination; } public static int[] translate(int[] point, Direction direction) { return translate(point, direction, null); } public static double toDisplayRadians(double internalRadians) { while (internalRadians < 0) { internalRadians += 2 * Math.PI; } return fmod(internalRadians + Math.PI / 2, 2 * Math.PI); } public static double toInternalRadians(double displayRadians) { while (displayRadians < 0) { displayRadians += 2 * Math.PI; } displayRadians = fmod(displayRadians - Math.PI / 2, 2 * Math.PI); while (displayRadians < 0) { displayRadians += 2 * Math.PI; } return displayRadians; } public static double fmod(double a, double mod) { double result = a; assert mod > 0; while (Math.abs(result) >= mod) { if (result > 0) { result -= mod; } else { result += mod; } } return result; } }
23.636364
86
0.631361
2076353817e04c3e720925546a41dd2503b89de0
18,847
package com.gpergrossi.util.geom.ranges; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; import java.util.function.Predicate; import com.gpergrossi.util.data.Iterators; import com.gpergrossi.util.geom.shapes.Rect; import com.gpergrossi.util.geom.vectors.Int2D; import com.gpergrossi.util.geom.vectors.Int2D.StoredBit; import com.gpergrossi.util.geom.vectors.Int2D.StoredByte; import com.gpergrossi.util.geom.vectors.Int2D.StoredFloat; import com.gpergrossi.util.geom.vectors.Int2D.StoredInteger; public class Int2DRange { public final int minX, maxX; public final int minY, maxY; public final int width, height; public static Int2DRange fromRect(Rect rect) { int minX = (int) Math.floor(rect.minX()); int minY = (int) Math.floor(rect.minY()); int maxX = (int) Math.ceil(rect.maxX()); int maxY = (int) Math.ceil(rect.maxY()); return new Int2DRange(minX, minY, maxX, maxY); } public Int2DRange(Int2DRange range) { this(range.minX, range.minY, range.maxX, range.maxY); } public Int2DRange(Int2D start, Int2D end) { this(start.x(), start.y(), end.x(), end.y()); } public Int2DRange(int minX, int minY, int maxX, int maxY) { this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; this.width = Math.max(maxX - minX + 1, 0); this.height = Math.max(maxY - minY + 1, 0); } protected Int2DRange resize(int minX, int minY, int maxX, int maxY) { return new Int2DRange(minX, minY, maxX, maxY); } public int size() { return width*height; } public boolean isEmpty() { return size() == 0; } public boolean contains(int x, int y) { return (x >= minX && y >= minY && x <= maxX && y <= maxY); } public boolean contains(Int2D pt) { return contains(pt.x(), pt.y()); } public boolean onBorder(int x, int y, int borderPadding) { return contains(x, y) && (x < minX+borderPadding || y < minY + borderPadding || x > maxX-borderPadding || y > maxY-borderPadding); } public boolean onBorder(Int2D pt, int borderPadding) { return onBorder(pt.x(), pt.y(), borderPadding); } public Int2DRange grow(int padXMin, int padYMin, int padXMax, int padYMax) { return resize(minX-padXMin, minY-padYMin, maxX+padXMax, maxY+padYMax); } public Int2DRange grow(int padX, int padY) { return grow(padX, padY, padX, padY); } public Int2DRange grow(int pad) { return grow(pad, pad); } public Int2DRange shrink(int insetX, int insetY) { return grow(-insetX, -insetY); } public Int2DRange shrink(int inset) { return grow(-inset, -inset); } public Int2DRange scale(int scaleUp) { return resize(minX*scaleUp, minY*scaleUp, maxX*scaleUp, maxY*scaleUp); } public Int2DRange intersect(Int2DRange other) { int minX = Math.max(this.minX, other.minX); int minY = Math.max(this.minY, other.minY); int maxX = Math.min(this.maxX, other.maxX); int maxY = Math.min(this.maxY, other.maxY); return resize(minX, minY, maxX, maxY); } public Int2DRange offset(int offsetX, int offsetY) { return resize(minX+offsetX, minY+offsetY, maxX+offsetX, maxY+offsetY); } public int indexFor(Int2D pt) { return indexFor(pt.x(), pt.y()); } public int indexFor(int x, int y) { return (y-minY)*width+(x-minX); } public int randomX(Random random) { return random.nextInt(width)+minX; } public int randomY(Random random) { return random.nextInt(height)+minY; } public Int2D randomTile(Random random) { return new Int2D(randomX(random), randomY(random)); } public String toString() { return "("+minX+", "+minY+") to ("+maxX+", "+maxY+")"; } public Iterable<Int2D.WithIndex> getAllMutable() { return new Iterable<Int2D.WithIndex>() { @Override public Iterator<Int2D.WithIndex> iterator() { return new Iterator<Int2D.WithIndex>() { private Int2D.WithIndex mutable = new Int2D.WithIndex(Int2DRange.this, 0, 0, 0); private int x = 0, y = 0, index = 0; @Override public boolean hasNext() { return index < size(); } @Override public Int2D.WithIndex next() { if (!hasNext()) throw new NoSuchElementException(); mutable.x(x+minX); mutable.y(y+minY); mutable.index = index; index++; x++; if (x == width) { x = 0; y++; } return mutable; } }; } }; } public Iterable<Int2D.WithIndex> getAll() { return new Iterable<Int2D.WithIndex>() { @Override public Iterator<Int2D.WithIndex> iterator() { return new Iterator<Int2D.WithIndex>() { private int x = 0, y = 0, index = 0; @Override public boolean hasNext() { return index < size(); } @Override public Int2D.WithIndex next() { if (!hasNext()) throw new NoSuchElementException(); Int2D.WithIndex result = new Int2D.WithIndex(Int2DRange.this, x+minX, y+minY, index); index++; x++; if (x == width) { x = 0; y++; } return result; } }; } }; } public Floats createFloats() { return new Floats(this); } public Floats copyFloats(Floats floats, int dstStartX, int dstStartY) { Floats result = new Floats(this); Floats.copyRange(floats, result, dstStartX, dstStartY); return result; } public Integers createIntegers() { return new Integers(this); } public Integers createIntegers(int[] intArray) { return new Integers(this.minX, this.minY, this.maxX, this.maxY, intArray); } public Bits createBits() { return new Bits(this); } public static class Floats extends Int2DRange { public static void copyRange(Floats src, Floats dest, int dstStartX, int dstStartY) { int minX = Math.max(src.minX, dest.minX-dstStartX); int minY = Math.max(src.minY, dest.minY-dstStartY); int maxX = Math.min(src.maxX, dest.maxX-dstStartX); int maxY = Math.min(src.maxY, dest.maxY-dstStartY); for (int y = minY; y <= maxY; y++) { for (int x = minX; x <= maxX; x++) { dest.set(x+dstStartX, y+dstStartY, src.get(x, y)); } } } public final float[] data; public Floats(Int2DRange range) { this(range.minX, range.minY, range.maxX, range.maxY); } public Floats(Int2D start, Int2D end) { this(start.x(), start.y(), end.x(), end.y()); } public Floats(int minX, int minY, int maxX, int maxY) { super(minX, minY, maxX, maxY); this.data = new float[size()]; } @Override protected Floats resize(int minX, int minY, int maxX, int maxY) { Floats result = new Floats(minX, minY, maxX, maxY); copyRange(this, result, 0, 0); return result; } @Override public Floats grow(int padX, int padY) { return resize(minX-padX, minY-padY, maxX+padX, maxY+padY); } @Override public Floats grow(int pad) { return grow(pad, pad); } @Override public Floats shrink(int insetX, int insetY) { return grow(-insetX, -insetY); } @Override public Floats shrink(int inset) { return grow(-inset, -inset); } @Override public Floats intersect(Int2DRange other) { int minX = Math.max(this.minX, other.minX); int minY = Math.max(this.minY, other.minY); int maxX = Math.min(this.maxX, other.maxX); int maxY = Math.min(this.maxY, other.maxY); return resize(minX, minY, maxX, maxY); } public float get(int index) { return data[index]; } public void set(int index, float value) { data[index] = value; } public float get(int x, int y) { return data[(y-minY)*width+(x-minX)]; } public void set(int x, int y, float value) { data[(y-minY)*width+(x-minX)] = value; } public Iterable<StoredFloat> getAllFloats() { return Iterators.cast(Floats.super.getAllMutable(), t -> new Int2D.StoredFloat(Floats.this, t.x(), t.y(), t.index)); } public Int2DRange asRange() { return new Int2DRange(this); } public float getSafe(int x, int y, float defaultValue) { if (!this.contains(x, y)) return defaultValue; return this.get(x, y); } public Int2DRange getTrimmedRange(Predicate<Float> predicateRemovable) { int trimMinY = -1, trimMaxY = -1; for (int y = 0; y < height; y++) { if (trimMinY == -1) for (int x = 0; x < width; x++) { if (predicateRemovable.test(data[y*width + x])) continue; trimMinY = y; break; } int yr = height-1-y; if (trimMaxY == -1) for (int x = 0; x < width; x++) { if (predicateRemovable.test(data[yr*width + x])) continue; trimMaxY = yr; break; } if (trimMinY != -1 && trimMaxY != -1) break; } int trimMinX = -1, trimMaxX = -1; for (int x = 0; x < width; x++) { if (trimMinX == -1) for (int y = 0; y < height; y++) { if (predicateRemovable.test(data[y*width + x])) continue; trimMinX = x; break; } int xr = width-1-x; if (trimMaxX == -1) for (int y = 0; y < height; y++) { if (predicateRemovable.test(data[y*width + xr])) continue; trimMaxX = xr; break; } if (trimMinX != -1 && trimMaxX != -1) break; } return new Int2DRange(this.minX + trimMinX, this.minY + trimMinY, this.minX + trimMaxX, this.minY + trimMaxY); } public float lerp(float x, float y, float outOfBoundsValue) { int floorx = (int) Math.floor(x); int floory = (int) Math.floor(y); float v00, v01, v10, v11; if (floorx < minX-1 || floory < minY-1 || floorx > maxX || floory > maxY) { return outOfBoundsValue; } else if (floorx >= minX && floory >= minY && floorx <= maxX-1 && floory <= maxY-1) { int index = ((floory-minY)*width + (floorx-minX)); v00 = data[index]; v01 = data[index+1]; v10 = data[index+width]; v11 = data[index+width+1]; } else { v00 = getSafe(floorx, floory, outOfBoundsValue); v01 = getSafe(floorx+1, floory, outOfBoundsValue); v10 = getSafe(floorx, floory+1, outOfBoundsValue); v11 = getSafe(floorx+1, floory+1, outOfBoundsValue); } return lerp2d(x-floorx, y-floory, v00, v10, v01, v11); } /** * Two-dimensional linear interpolation. (x, y) in the range of (0, 0) to (1, 1) */ private static float lerp2d(float x, float y, float lowXlowY, float lowXhighY, float highXlowY, float highXhighY) { float lowX = lerp1d(y, lowXlowY, lowXhighY); float highX = lerp1d(y, highXlowY, highXhighY); return lerp1d(x, lowX, highX); } /** * Linear interpolation between lowX and highX as x moves between 0 and 1 */ private static float lerp1d(float x, float lowX, float highX) { return (1f-x)*lowX + x*highX; } } public static class Bytes extends Int2DRange { public static void copyRange(Bytes src, Bytes dest, int dstStartX, int dstStartY) { int minX = Math.max(src.minX, dest.minX-dstStartX); int minY = Math.max(src.minY, dest.minY-dstStartY); int maxX = Math.min(src.maxX, dest.maxX-dstStartX); int maxY = Math.min(src.maxY, dest.maxY-dstStartY); for (int y = minY; y <= maxY; y++) { for (int x = minX; x <= maxX; x++) { dest.set(x+dstStartX, y+dstStartY, src.get(x, y)); } } } public final byte[] data; public Bytes(Int2DRange range) { this(range.minX, range.minY, range.maxX, range.maxY); } public Bytes(Int2D start, Int2D end) { this(start.x(), start.y(), end.x(), end.y()); } public Bytes(int minX, int minY, int maxX, int maxY) { super(minX, minY, maxX, maxY); this.data = new byte[size()]; } @Override protected Bytes resize(int minX, int minY, int maxX, int maxY) { Bytes result = new Bytes(minX, minY, maxX, maxY); copyRange(this, result, 0, 0); return result; } @Override public Bytes grow(int padX, int padY) { return resize(minX-padX, minY-padY, maxX+padX, maxY+padY); } @Override public Bytes grow(int pad) { return grow(pad, pad); } @Override public Bytes shrink(int insetX, int insetY) { return grow(-insetX, -insetY); } @Override public Bytes shrink(int inset) { return grow(-inset, -inset); } @Override public Bytes intersect(Int2DRange other) { int minX = Math.max(this.minX, other.minX); int minY = Math.max(this.minY, other.minY); int maxX = Math.min(this.maxX, other.maxX); int maxY = Math.min(this.maxY, other.maxY); return resize(minX, minY, maxX, maxY); } public byte get(int index) { return data[index]; } public void set(int index, byte value) { data[index] = value; } public byte get(int x, int y) { if (x < minX || x > maxX) throw new IndexOutOfBoundsException("x = "+x+" is out of bounds ["+minX+", "+maxX+"]"); if (y < minY || y > maxY) throw new IndexOutOfBoundsException("y = "+y+" is out of bounds ["+minY+", "+maxY+"]"); return data[(y-minY)*width+(x-minX)]; } public void set(int x, int y, byte value) { data[(y-minY)*width+(x-minX)] = value; } public Iterable<StoredByte> getAllBytes() { return Iterators.cast(Bytes.super.getAllMutable(), t -> new Int2D.StoredByte(Bytes.this, t.x(), t.y(), t.index)); } public Int2DRange asRange() { return new Int2DRange(this); } public byte getSafe(int x, int y, byte defaultValue) { if (!this.contains(x, y)) return defaultValue; return this.get(x, y); } } public static class Integers extends Int2DRange { public static void copyRange(Integers src, Integers dest, int dstStartX, int dstStartY) { int minX = Math.max(src.minX, dest.minX-dstStartX); int minY = Math.max(src.minY, dest.minY-dstStartY); int maxX = Math.min(src.maxX, dest.maxX-dstStartX); int maxY = Math.min(src.maxY, dest.maxY-dstStartY); for (int y = minY; y <= maxY; y++) { for (int x = minX; x <= maxX; x++) { dest.set(x+dstStartX, y+dstStartY, src.get(x, y)); } } } public final int[] data; public Integers(Int2DRange range) { this(range.minX, range.minY, range.maxX, range.maxY); } public Integers(Int2D start, Int2D end) { this(start.x(), start.y(), end.x(), end.y()); } public Integers(int minX, int minY, int maxX, int maxY) { super(minX, minY, maxX, maxY); this.data = new int[size()]; } public Integers(int minX, int minY, int maxX, int maxY, int[] intArray) { super(minX, minY, maxX, maxY); if (intArray.length < size()) throw new IllegalArgumentException("Provided int array is not big enough"); this.data = intArray; } @Override protected Integers resize(int minX, int minY, int maxX, int maxY) { Integers result = new Integers(minX, minY, maxX, maxY); copyRange(this, result, 0, 0); return result; } @Override public Integers grow(int padX, int padY) { return resize(minX-padX, minY-padY, maxX+padX, maxY+padY); } @Override public Integers grow(int pad) { return grow(pad, pad); } @Override public Integers shrink(int insetX, int insetY) { return grow(-insetX, -insetY); } @Override public Integers shrink(int inset) { return grow(-inset, -inset); } @Override public Integers intersect(Int2DRange other) { int minX = Math.max(this.minX, other.minX); int minY = Math.max(this.minY, other.minY); int maxX = Math.min(this.maxX, other.maxX); int maxY = Math.min(this.maxY, other.maxY); return resize(minX, minY, maxX, maxY); } public int get(int index) { return data[index]; } public void set(int index, int value) { data[index] = value; } public int get(int x, int y) { return data[(y-minY)*width+(x-minX)]; } public void set(int x, int y, int value) { data[(y-minY)*width+(x-minX)] = value; } public Iterable<StoredInteger> getAllIntegers() { return Iterators.cast(Integers.super.getAllMutable(), t -> new Int2D.StoredInteger(Integers.this, t.x(), t.y(), t.index)); } public Int2DRange asRange() { return new Int2DRange(this); } public int getSafe(int x, int y, int defaultValue) { if (!this.contains(x, y)) return defaultValue; return this.get(x, y); } } public static class Bits extends Int2DRange { public static void copyRange(Bits src, Bits dest, int dstStartX, int dstStartY) { int minX = Math.max(src.minX, dest.minX-dstStartX); int minY = Math.max(src.minY, dest.minY-dstStartY); int maxX = Math.min(src.maxX, dest.maxX-dstStartX); int maxY = Math.min(src.maxY, dest.maxY-dstStartY); for (int y = minY; y <= maxY; y++) { for (int x = minX; x <= maxX; x++) { dest.set(x+dstStartX, y+dstStartY, src.get(x, y)); } } } public final int[] data; public Bits(Int2DRange range) { this(range.minX, range.minY, range.maxX, range.maxY); } public Bits(Int2D start, Int2D end) { this(start.x(), start.y(), end.x(), end.y()); } public Bits(int minX, int minY, int maxX, int maxY) { super(minX, minY, maxX, maxY); this.data = new int[(size() / 32)+1]; } @Override protected Bits resize(int minX, int minY, int maxX, int maxY) { Bits result = new Bits(minX, minY, maxX, maxY); copyRange(this, result, 0, 0); return result; } @Override public Bits grow(int padX, int padY) { return resize(minX-padX, minY-padY, maxX+padX, maxY+padY); } @Override public Bits grow(int pad) { return grow(pad, pad); } @Override public Bits shrink(int insetX, int insetY) { return grow(-insetX, -insetY); } @Override public Bits shrink(int inset) { return grow(-inset, -inset); } @Override public Bits intersect(Int2DRange other) { int minX = Math.max(this.minX, other.minX); int minY = Math.max(this.minY, other.minY); int maxX = Math.min(this.maxX, other.maxX); int maxY = Math.min(this.maxY, other.maxY); return resize(minX, minY, maxX, maxY); } public boolean get(int index) { int slot = Math.floorDiv(index, 32); int mask = (1 << Math.floorMod(index, 32)); try { return (data[slot] & mask) == mask; } catch (Exception e) { System.out.println("new Int2DRange.Bits ("+minX+", "+minY+", "+maxX+", "+maxY+"), size = "+size()+", data.length = "+data.length); System.out.println("Accessing index "+index+" with slot="+slot+" and mask="+mask); throw e; } } public void set(int index, boolean value) { int slot = Math.floorDiv(index, 32); int mask = (1 << Math.floorMod(index, 32)); data[slot] = (data[slot] & ~mask) | (value ? mask : 0); } public boolean get(int x, int y) { return get((y-minY)*width+(x-minX)); } public void set(int x, int y, boolean value) { set((y-minY)*width+(x-minX), value); } public Iterable<StoredBit> getAllBits() { return Iterators.cast(Bits.super.getAllMutable(), t -> new Int2D.StoredBit(Bits.this, t.x(), t.y(), t.index)); } public Int2DRange asRange() { return new Int2DRange(this); } public boolean getSafe(int x, int y, boolean defaultValue) { if (!this.contains(x, y)) return defaultValue; return this.get(x, y); } } }
26.507736
134
0.63469
0e40cdb34fb42154770670242a6784c7bed58fb6
79
package hd.dp.decorator; public interface Car { void run(); void show(); }
9.875
24
0.670886
be7b7e1b43cfc15242bbbee1b27a17740361f266
7,126
package uk.ac.ebi.interpro.scan.model; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import java.util.HashSet; import java.util.Set; /** * Models a match based upon the RPSBlast algorithm against a * protein sequence. * * @author Gift Nuka * @version $Id$ * @since 5.16 */ @Entity @Table(name = "rpsblast_match") @XmlType(name = "RPSBlastMatchType") public class RPSBlastMatch extends Match<RPSBlastMatch.RPSBlastLocation> { protected RPSBlastMatch() { } public RPSBlastMatch(Signature signature, String signatureModels, Set<RPSBlastLocation> locations) { super(signature, signatureModels, locations); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RPSBlastMatch)) return false; return new EqualsBuilder() .appendSuper(super.equals(o)) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(41, 59) .appendSuper(super.hashCode()) .toHashCode(); } public Object clone() throws CloneNotSupportedException { final Set<RPSBlastLocation> clonedLocations = new HashSet<>(this.getLocations().size()); for (RPSBlastLocation location : this.getLocations()) { clonedLocations.add((RPSBlastLocation) location.clone()); } return new RPSBlastMatch(this.getSignature(), this.getSignatureModels(), clonedLocations); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } /** * Location of RPS-Blast (e.g. CDD) match on a protein sequence * * @author Gift Nuka */ @Entity @Table(name = "rpsblast_location") @XmlType(name = "RPSBlastLocationType", namespace = "http://www.ebi.ac.uk/interpro/resources/schemas/interproscan5") //@XmlType(name = "RPSBlastLocationType", namespace = "http://www.ebi.ac.uk/interpro/resources/schemas/interproscan5", propOrder = { "start", "end", "score", "evalue"}) public static class RPSBlastLocation extends LocationWithSites<RPSBlastLocation.RPSBlastSite, LocationFragment> { @Column(nullable = false, name = "evalue") private double evalue; @Column(nullable = false, name = "score") private double score; protected RPSBlastLocation() { } public RPSBlastLocation(int start, int end, double score, double evalue, Set<RPSBlastSite> sites) { super(new RPSBlastLocationFragment(start, end), sites); setScore(score); setEvalue(evalue); } @XmlAttribute(required = true) public double getEvalue() { return evalue; } private void setEvalue(double evalue) { this.evalue = evalue; } @XmlAttribute(required = true) public double getScore() { return score; } private void setScore(double score) { this.score = score; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RPSBlastLocation)) return false; return new EqualsBuilder() .appendSuper(super.equals(o)) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(41, 59) .appendSuper(super.hashCode()) .toHashCode(); } public Object clone() throws CloneNotSupportedException { final Set<RPSBlastSite> clonedSites = new HashSet<>(this.getSites().size()); for (RPSBlastSite site : this.getSites()) { clonedSites.add((RPSBlastSite) site.clone()); } return new RPSBlastLocation(this.getStart(), this.getEnd(), this.getScore(), this.getEvalue(), clonedSites); } /** * Location fragment of a RPSBlast match on a protein sequence */ @Entity @Table(name = "rpsblast_location_fragment") @XmlType(name = "RPSBlastLocationFragmentType", namespace = "http://www.ebi.ac.uk/interpro/resources/schemas/interproscan5") public static class RPSBlastLocationFragment extends LocationFragment { protected RPSBlastLocationFragment() { } public RPSBlastLocationFragment(int start, int end) { super(start, end); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RPSBlastLocationFragment)) return false; return new EqualsBuilder() .appendSuper(super.equals(o)) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(141, 159) .appendSuper(super.hashCode()) .toHashCode(); } public Object clone() throws CloneNotSupportedException { return new RPSBlastLocationFragment(this.getStart(), this.getEnd()); } } @Entity @Table(name = "rpsblast_site") @XmlType(name = "RPSBlastSiteType", namespace = "http://www.ebi.ac.uk/interpro/resources/schemas/interproscan5") public static class RPSBlastSite extends Site { protected RPSBlastSite() { } public RPSBlastSite(String description, Set<SiteLocation> siteLocations) { super(description, siteLocations); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RPSBlastSite)) return false; return new EqualsBuilder() .appendSuper(super.equals(o)) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(41, 59) .appendSuper(super.hashCode()) .toHashCode(); } public Object clone() throws CloneNotSupportedException { final Set<SiteLocation> clonedSiteLocations = new HashSet<>(this.getSiteLocations().size()); for (SiteLocation sl : this.getSiteLocations()) { clonedSiteLocations.add((SiteLocation) sl.clone()); } return new RPSBlastSite(this.getDescription(), clonedSiteLocations); } } } }
32.83871
172
0.578164
a0675b0d70883abf52c665cef2ec658d7f696480
10,229
package org.usfirst.frc.team4488.robot.systems.drive; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.can.TalonFX; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import java.util.ArrayList; import java.util.Optional; import org.usfirst.frc.team4488.lib.PreferencesParser; import org.usfirst.frc.team4488.lib.app.math.Rotation2d; import org.usfirst.frc.team4488.lib.drive.DriveHelper; import org.usfirst.frc.team4488.lib.logging.Logging; import org.usfirst.frc.team4488.lib.logging.StringTrackable; import org.usfirst.frc.team4488.lib.loops.Loop; import org.usfirst.frc.team4488.lib.loops.Looper; import org.usfirst.frc.team4488.lib.sensors.NavX; import org.usfirst.frc.team4488.robot.Constants; import org.usfirst.frc.team4488.robot.RobotMap; import org.usfirst.frc.team4488.robot.app.WestCoastStateEstimator; import org.usfirst.frc.team4488.robot.routines.defaults.DefaultRoutine; import org.usfirst.frc.team4488.robot.routines.defaults.FalconDriveRoutine; import org.usfirst.frc.team4488.robot.systems.SmartPDP; public class FalconDrive extends WestCoastDrive { private static FalconDrive inst = null; public static synchronized FalconDrive getInstance() { if (inst == null) inst = new FalconDrive(); return inst; } private TalonFX leftMaster; private TalonFX leftFollower; private TalonFX rightMaster; private TalonFX rightFollower; private Optional<Solenoid> shifter; private FalconDriveRoutine defaultRoutine = new FalconDriveRoutine(this); private static final int gearShiftThresh = 90; // inch per sec private boolean autoShifterModeEnabled = false; private boolean prevAutoCycle; private DriveGear newGear; private DriveGear currentGear; private WestCoastStateEstimator stateEstimator = new WestCoastStateEstimator(this); private DriveHelper driveHelper = new DriveHelper(this, 0.1, 0.1); private final double wheelDiameter; private final double ticksPerRotation; private static final double rampRate = 0.5; private Loop loop = new Loop() { public void onStart(double timestamp) { updatePID(); rightMaster.setNeutralMode(NeutralMode.Brake); leftMaster.setNeutralMode(NeutralMode.Brake); stop(); } public void onLoop(double timestamp) { if (newGear != currentGear) { gearShiftUpdate(); } } public void onStop(double timestamp) { rightMaster.setNeutralMode(NeutralMode.Coast); leftMaster.setNeutralMode(NeutralMode.Coast); stop(); } }; public FalconDrive() { leftMaster = new TalonFX(RobotMap.FalconDriveLeftM); leftFollower = new TalonFX(RobotMap.FalconDriveLeftF); rightMaster = new TalonFX(RobotMap.FalconDriveRightM); rightFollower = new TalonFX(RobotMap.FalconDriveRightF); if (RobotMap.hasShifters) { shifter = Optional.of(new Solenoid(RobotMap.PCM, RobotMap.DriveGearShiftSolenoid)); } else { shifter = Optional.empty(); } rightMaster.setInverted(true); rightFollower.setInverted(true); leftFollower.follow(leftMaster); rightFollower.follow(rightMaster); rightMaster.configOpenloopRamp(rampRate); leftMaster.configOpenloopRamp(rampRate); rightMaster.setNeutralMode(NeutralMode.Brake); leftMaster.setNeutralMode(NeutralMode.Brake); PreferencesParser prefs = PreferencesParser.getInstance(); wheelDiameter = prefs.getDouble("DriveWheelDiameter"); ticksPerRotation = prefs.getDouble("DriveTicksPerRotation"); } public void stop() { setPowers(0, 0); } public WestCoastStateEstimator getStateEstimator() { return stateEstimator; } public void controllerUpdate(double leftStickX, double leftStickY, double rightStickX) { driveHelper.Drive(leftStickY, rightStickX); } public void configForPathFollowing() { configVelocity(); updatePID(); } public void configPercentVbus() {} public void configVelocity() {} public void setPowers(double leftPower, double rightPower) { leftMaster.set(ControlMode.PercentOutput, leftPower); rightMaster.set(ControlMode.PercentOutput, rightPower); } public synchronized void updateVelocitySetpoint( double left_inches_per_sec, double right_inches_per_sec) { final double max_desired = Math.max(Math.abs(left_inches_per_sec), Math.abs(right_inches_per_sec)); final double scale = max_desired > Constants.kDriveHighGearMaxSetpoint ? Constants.kDriveHighGearMaxSetpoint / max_desired : 1.0; double leftVelocitySetpoint = inchesPerSecondToTicksPer100MS(left_inches_per_sec * scale); double rightVelocitySetpoint = inchesPerSecondToTicksPer100MS(right_inches_per_sec * scale); SmartDashboard.putNumber("left vel", leftVelocitySetpoint); SmartDashboard.putNumber("right vel", rightVelocitySetpoint); leftMaster.set(ControlMode.Velocity, leftVelocitySetpoint); rightMaster.set(ControlMode.Velocity, rightVelocitySetpoint); } private double inchesPerSecondToTicksPer100MS(double inches_per_second) { return (inches_per_second / (wheelDiameter * Math.PI) * ticksPerRotation) / 10; } private double ticksPer100MsToInchesPerSecond(double ticksPer100Ms) { return (ticksPer100Ms / ticksPerRotation) * wheelDiameter * Math.PI * 10; } public Rotation2d getAngleRotation2d() { return Rotation2d.fromDegrees(-1 * NavX.getInstance().getAHRS().getYaw()); } public void updatePID() { PreferencesParser prefs = PreferencesParser.getInstance(); double p = prefs.tryGetDouble("DriveVelocityP", 0); double i = prefs.tryGetDouble("DriveVelocityI", 0); double d = prefs.tryGetDouble("DriveVelocityD", 0); double f = prefs.tryGetDouble("DriveVelocityF", 0); int iZone = (int) prefs.tryGetDouble("DriveVelocityIZone", 0); double ramp = prefs.tryGetDouble("DriveVelocityRamp", 0); leftMaster.config_kP(0, p, 0); leftMaster.config_kI(0, i, 0); leftMaster.config_kD(0, d, 0); leftMaster.config_kF(0, f, 0); leftMaster.config_IntegralZone(0, iZone, 0); leftMaster.configClosedloopRamp(ramp, 0); leftFollower.configNeutralDeadband(0, 0); rightMaster.config_kP(0, p, 0); rightMaster.config_kI(0, i, 0); rightMaster.config_kD(0, d, 0); rightMaster.config_kF(0, f, 0); rightMaster.config_IntegralZone(0, iZone, 0); rightMaster.configClosedloopRamp(ramp, 0); rightFollower.configNeutralDeadband(0, 0); } public double getLeftDistance() { return (leftMaster.getSelectedSensorPosition(0)) * wheelDiameter * Math.PI / ticksPerRotation; } public double getRightDistance() { return (rightMaster.getSelectedSensorPosition(0)) * wheelDiameter * Math.PI / ticksPerRotation; } public double getLeftSpeed() { return ticksPer100MsToInchesPerSecond(leftMaster.getSelectedSensorVelocity(0)); } public double getRightSpeed() { return ticksPer100MsToInchesPerSecond(rightMaster.getSelectedSensorVelocity(0)); } /** @return Linear speed in inches per second. */ public double getLinearSpeed() { return (getLeftSpeed() + getRightSpeed()) / 2; } public void writeToLog() {} public void updateSmartDashboard() { SmartDashboard.putNumber("gyro", getAngleRotation2d().getDegrees()); SmartDashboard.putNumber("left speed", getLeftSpeed()); SmartDashboard.putNumber("right speed", getRightSpeed()); SmartDashboard.putNumber("left ticks", leftMaster.getSelectedSensorPosition(0)); SmartDashboard.putNumber("right ticks", rightMaster.getSelectedSensorPosition(0)); } public void zeroSensors() { leftMaster.getSensorCollection().setIntegratedSensorPosition(0, 0); rightMaster.getSensorCollection().setIntegratedSensorPosition(0, 0); } public void reset() {} @Override public void setUpTrackables() { Logging logger = Logging.getInstance(); StringTrackable powerTrackable = () -> { double leftPower = Math.round(leftMaster.getMotorOutputPercent() * 100) / 100; double rightPower = Math.round(rightMaster.getMotorOutputPercent() * 100) / 100; String message = String.valueOf(leftPower); message += ", "; message += String.valueOf(rightPower); return message; }; logger.addStringTrackable(powerTrackable, "DrivePowers", 10, "LeftPower, RightPower"); logger.addStringTrackable( () -> currentGear == DriveGear.HighGear ? "high" : "low", "DriveGear", 10, "Gear Low/High"); } public void updatePrefs() {} public void resetAngle() { NavX.getInstance().zeroYaw(); } public void registerEnabledLoops(Looper enabledLoop) { enabledLoop.register(loop); } public DefaultRoutine getDefaultRoutine() { return defaultRoutine; } private void gearShiftUpdate() { if (newGear == DriveGear.HighGear) { shifter.ifPresent(solenoid -> solenoid.set(true)); currentGear = DriveGear.HighGear; } else { shifter.ifPresent(solenoid -> solenoid.set(false)); currentGear = DriveGear.LowGear; } } public void setDriveGears(boolean toggleManualMode, boolean toggleAutoMode) { if (toggleAutoMode && !prevAutoCycle) { autoShifterModeEnabled = !autoShifterModeEnabled; } if (autoShifterModeEnabled) { if (Math.abs(getLinearSpeed()) > gearShiftThresh || toggleManualMode) { newGear = DriveGear.HighGear; } else { newGear = DriveGear.LowGear; } } else if (toggleManualMode) { newGear = DriveGear.HighGear; } else { newGear = DriveGear.LowGear; } prevAutoCycle = toggleAutoMode; } public ArrayList<TalonFX> getFXs() { ArrayList<TalonFX> list = new ArrayList<TalonFX>(); list.add(leftMaster); list.add(leftFollower); list.add(rightMaster); list.add(rightFollower); return list; } public double getCurrentDraw() { double currentDraw = 0; for (int i : RobotMap.FalconDrivePDPPorts) { currentDraw += SmartPDP.getInstance().getCurrent(i); } return currentDraw; } }
33.211039
100
0.723433
ee5e1043a035cd33c9b70ab64ade9905a237d570
7,131
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * 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.teiid.translator.odata; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.Response.Status; import org.odata4j.core.OEntities; import org.odata4j.core.OEntity; import org.odata4j.core.OProperty; import org.odata4j.edm.EdmDataServices; import org.odata4j.edm.EdmEntitySet; import org.odata4j.format.Entry; import org.odata4j.format.FormatWriter; import org.odata4j.format.FormatWriterFactory; import org.teiid.GeneratedKeys; import org.teiid.language.Command; import org.teiid.metadata.RuntimeMetadata; import org.teiid.metadata.Schema; import org.teiid.metadata.Table; import org.teiid.translator.DataNotAvailableException; import org.teiid.translator.ExecutionContext; import org.teiid.translator.TranslatorException; import org.teiid.translator.UpdateExecution; import org.teiid.translator.WSConnection; import org.teiid.translator.ws.BinaryWSProcedureExecution; public class ODataUpdateExecution extends BaseQueryExecution implements UpdateExecution { private ODataUpdateVisitor visitor; private ODataEntitiesResponse response; public ODataUpdateExecution(Command command, ODataExecutionFactory translator, ExecutionContext executionContext, RuntimeMetadata metadata, WSConnection connection) throws TranslatorException { super(translator, executionContext, metadata, connection); this.visitor = new ODataUpdateVisitor(translator, metadata); this.visitor.visitNode(command); if (!this.visitor.exceptions.isEmpty()) { throw this.visitor.exceptions.get(0); } } @Override public void close() { } @Override public void cancel() throws TranslatorException { } @Override public void execute() throws TranslatorException { if (this.visitor.getMethod().equals("DELETE")) { //$NON-NLS-1$ // DELETE BinaryWSProcedureExecution execution = executeDirect(this.visitor.getMethod(), this.visitor.buildURL(), null, getDefaultHeaders()); if (execution.getResponseCode() != Status.OK.getStatusCode() && (execution.getResponseCode() != Status.NO_CONTENT.getStatusCode())) { throw buildError(execution); } } else if(this.visitor.getMethod().equals("PUT")) { //$NON-NLS-1$ // UPDATE Schema schema = visitor.getTable().getParent(); EdmDataServices edm = new TeiidEdmMetadata(schema.getName(), ODataEntitySchemaBuilder.buildMetadata(schema)); BinaryWSProcedureExecution execution = executeDirect("GET", this.visitor.buildURL(), null, getDefaultHeaders()); //$NON-NLS-1$ if (execution.getResponseCode() == Status.OK.getStatusCode()) { String etag = getHeader(execution, "ETag"); //$NON-NLS-1$ String payload = buildPayload(this.visitor.getTable().getName(), this.visitor.getPayload(), edm); this.response = executeWithReturnEntity(this.visitor.getMethod(), this.visitor.buildURL(), payload, this.visitor.getTable().getName(), edm, etag, Status.OK, Status.NO_CONTENT); if (this.response != null) { if (this.response.hasError()) { throw this.response.getError(); } } } } else if (this.visitor.getMethod().equals("POST")) { //$NON-NLS-1$ // INSERT Schema schema = visitor.getTable().getParent(); EdmDataServices edm = new TeiidEdmMetadata(schema.getName(), ODataEntitySchemaBuilder.buildMetadata( schema)); String payload = buildPayload(this.visitor.getTable().getName(), this.visitor.getPayload(), edm); this.response = executeWithReturnEntity(this.visitor.getMethod(), this.visitor.buildURL(), payload, this.visitor.getTable().getName(), edm, null, Status.CREATED); if (this.response != null) { if (this.response.hasError()) { throw this.response.getError(); } } } } private String buildPayload(String entitySet, final List<OProperty<?>> props, EdmDataServices edm) { // this is remove the teiid specific model name from the entity type name. final EdmEntitySet ees = ODataEntitySchemaBuilder.removeModelName(edm.getEdmEntitySet(entitySet)); Entry entry = new Entry() { public String getUri() { return null; } public OEntity getEntity() { return OEntities.createRequest(ees, props, null); } }; StringWriter sw = new StringWriter(); FormatWriter<Entry> fw = FormatWriterFactory.getFormatWriter(Entry.class, null, "ATOM", null); //$NON-NLS-1$ fw.write(null, sw, entry); return sw.toString(); } @Override public int[] getUpdateCounts() throws DataNotAvailableException, TranslatorException { if (this.visitor.getMethod().equals("DELETE")) { //$NON-NLS-1$ //DELETE return (this.response != null)?new int[]{1}:new int[]{0}; } else if(this.visitor.getMethod().equals("PUT")) { //$NON-NLS-1$ // UPDATE; // conflicting implementation found where some sent 200 with content; other with 204 no-content return (this.response != null)?new int[]{1}:new int[]{0}; } else if (this.visitor.getMethod().equals("POST")) { //$NON-NLS-1$ //INSERT if (this.response != null && this.response.hasRow()) { if (this.executionContext.getCommandContext().isReturnAutoGeneratedKeys()) { addAutoGeneretedKeys(); } return new int[]{1}; } } return new int[] {0}; } private void addAutoGeneretedKeys() { OEntity entity = this.response.getResultsIter().next().getEntity(); Table table = this.visitor.getEnityTable(); int cols = table.getPrimaryKey().getColumns().size(); Class<?>[] columnDataTypes = new Class<?>[cols]; String[] columnNames = new String[cols]; //this is typically expected to be an int/long, but we'll be general here. we may eventual need the type logic off of the metadata importer for (int i = 0; i < cols; i++) { columnDataTypes[i] = table.getPrimaryKey().getColumns().get(i).getJavaType(); columnNames[i] = table.getPrimaryKey().getColumns().get(i).getName(); } GeneratedKeys generatedKeys = this.executionContext.getCommandContext().returnGeneratedKeys(columnNames, columnDataTypes); List<Object> vals = new ArrayList<Object>(columnDataTypes.length); for (int i = 0; i < columnDataTypes.length; i++) { OProperty<?> prop = entity.getProperty(columnNames[i]); Object value = this.translator.retrieveValue(prop.getValue(), columnDataTypes[i]); vals.add(value); } generatedKeys.addKey(vals); } }
41.219653
180
0.716449
452c6af580bb4dd9d855a8e446fd7636257f29a2
1,169
package mostwanted.domain.dtos.raceImportDtos; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "race") @XmlAccessorType(XmlAccessType.FIELD) public class RaceImportDto { @XmlElement(name = "laps") private Integer laps; @XmlElement(name = "district-name") private String districtName; @XmlElement(name = "entries") private EntryRootDto entryRootDto; public RaceImportDto() { } @NotNull public Integer getLaps() { return this.laps; } public void setLaps(Integer laps) { this.laps = laps; } @NotNull public String getDistrictName() { return this.districtName; } public void setDistrictName(String districtName) { this.districtName = districtName; } public EntryRootDto getEntryRootDto() { return this.entryRootDto; } public void setEntryRootDto(EntryRootDto entryRootDto) { this.entryRootDto = entryRootDto; } }
22.921569
60
0.70231
b1e4ab6b556424e62baa88c6fe988ea147ce2d85
790
package com.arthas.service.shell.handlers.shell; import com.arthas.service.shell.impl.ShellImpl; import com.arthas.service.shell.system.ExecStatus; import com.arthas.service.shell.system.Job; import com.arthas.service.shell.term.SignalHandler; import com.arthas.service.shell.term.Term; /** * @author beiwei30 on 23/11/2016. */ public class SuspendHandler implements SignalHandler { private ShellImpl shell; public SuspendHandler(ShellImpl shell) { this.shell = shell; } @Override public boolean deliver(int key) { Term term = shell.term(); Job job = shell.getForegroundJob(); if (job != null) { term.echo(shell.statusLine(job, ExecStatus.STOPPED)); job.suspend(); } return true; } }
23.235294
65
0.670886
5b9a23a4ea957c523e74c5c604abc70943a75b6e
1,855
package com.example.xianghaapp.util; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.example.xianghaapp.model.base.BaseModel; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Created by Administrator on 2016/8/10. */ public class BitMapCallBack implements BaseModel.OnLoadCompleteListener{ private ImageView imageView; public BitMapCallBack(ImageView imageView) { this.imageView = imageView; } @Override public void onLoadComplete(byte[] bs, String PATH) { if (bs!=null) { String tag = (String) imageView.getTag(); if (bs.length != 0 && tag != null && tag.equals(PATH)) { FileOutputStream fos = null; try { Bitmap image = BitmapFactory.decodeByteArray(bs, 0, bs.length); imageView.setImageBitmap(image); File externalCacheDir = imageView.getContext().getExternalCacheDir(); File file=new File(externalCacheDir,PATH.replaceAll("/","")+".jpg"); fos = new FileOutputStream(file); //1 // image.compress(Bitmap.CompressFormat.JPEG,100,fos); //2 fos.write(bs,0,bs.length); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (fos!=null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
30.409836
85
0.538544
789533162d01eb59d5ac6d1d9bc9a86ee770ddcc
1,347
/* * Copyright (c) 2011, 2018 Purdue University. * 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 etalon.purdue.edu.base.ui; /** * Created by hussein on 6/10/16. */ import etalon.purdue.edu.base.BaseActivityHelper; import etalon.purdue.edu.base.BaseBMHelper; /** * The type Console setter. */ public class ConsoleSetter implements Runnable { /** * The Bm helper. */ BaseBMHelper bmHelper; /** * Instantiates a new Console setter. * * @param bmHelper the bm helper */ public ConsoleSetter(BaseBMHelper bmHelper) { this.bmHelper = bmHelper; } @Override public void run() { BaseActivityHelper.setSystemOutputs(bmHelper, bmHelper.getTag()); synchronized (bmHelper) { bmHelper.ready = true; bmHelper.notifyAll(); //Log.e("testErr", "Done bmHelper"); } } }
25.415094
75
0.697847
09ce093090b67d40a3bb59e88ba49033bd706209
6,237
package com.deyatech.apply.controller; import com.deyatech.apply.entity.OpenReplyTemplate; import com.deyatech.apply.vo.OpenReplyTemplateVo; import com.deyatech.apply.service.OpenReplyTemplateService; import com.deyatech.common.entity.RestResult; import lombok.extern.slf4j.Slf4j; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.Serializable; import java.util.Collection; import java.util.List; import org.springframework.web.bind.annotation.RestController; import com.deyatech.common.base.BaseController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; /** * <p> * 前端控制器 * </p> * @author: lee. * @since 2020-01-16 */ @Slf4j @RestController @RequestMapping("/apply/openReplyTemplate") @Api(tags = {"接口"}) public class OpenReplyTemplateController extends BaseController { @Autowired OpenReplyTemplateService openReplyTemplateService; /** * 单个保存或者更新 * * @param openReplyTemplate * @return */ @PostMapping("/saveOrUpdate") @ApiOperation(value="单个保存或者更新", notes="根据对象保存或者更新信息") @ApiImplicitParam(name = "openReplyTemplate", value = "对象", required = true, dataType = "OpenReplyTemplate", paramType = "query") public RestResult<Boolean> saveOrUpdate(OpenReplyTemplate openReplyTemplate) { log.info(String.format("保存或者更新: %s ", JSONUtil.toJsonStr(openReplyTemplate))); boolean result = openReplyTemplateService.saveOrUpdate(openReplyTemplate); return RestResult.ok(result); } /** * 批量保存或者更新 * * @param openReplyTemplateList * @return */ @PostMapping("/saveOrUpdateBatch") @ApiOperation(value="批量保存或者更新", notes="根据对象集合批量保存或者更新信息") @ApiImplicitParam(name = "openReplyTemplateList", value = "对象集合", required = true, allowMultiple = true, dataType = "OpenReplyTemplate", paramType = "query") public RestResult<Boolean> saveOrUpdateBatch(Collection<OpenReplyTemplate> openReplyTemplateList) { log.info(String.format("批量保存或者更新: %s ", JSONUtil.toJsonStr(openReplyTemplateList))); boolean result = openReplyTemplateService.saveOrUpdateBatch(openReplyTemplateList); return RestResult.ok(result); } /** * 根据OpenReplyTemplate对象属性逻辑删除 * * @param openReplyTemplate * @return */ @PostMapping("/removeByOpenReplyTemplate") @ApiOperation(value="根据OpenReplyTemplate对象属性逻辑删除", notes="根据对象逻辑删除信息") @ApiImplicitParam(name = "openReplyTemplate", value = "对象", required = true, dataType = "OpenReplyTemplate", paramType = "query") public RestResult<Boolean> removeByOpenReplyTemplate(OpenReplyTemplate openReplyTemplate) { log.info(String.format("根据OpenReplyTemplate对象属性逻辑删除: %s ", openReplyTemplate)); boolean result = openReplyTemplateService.removeByBean(openReplyTemplate); return RestResult.ok(result); } /** * 根据ID批量逻辑删除 * * @param ids * @return */ @PostMapping("/removeByIds") @ApiOperation(value="根据ID批量逻辑删除", notes="根据对象ID批量逻辑删除信息") @ApiImplicitParam(name = "ids", value = "对象ID集合", required = true, allowMultiple = true, dataType = "Serializable", paramType = "query") public RestResult<Boolean> removeByIds(@RequestParam("ids[]") List<String> ids) { log.info(String.format("根据id批量删除: %s ", JSONUtil.toJsonStr(ids))); boolean result = openReplyTemplateService.removeByIds(ids); return RestResult.ok(result); } /** * 根据OpenReplyTemplate对象属性获取 * * @param openReplyTemplate * @return */ @GetMapping("/getByOpenReplyTemplate") @ApiOperation(value="根据OpenReplyTemplate对象属性获取", notes="根据对象属性获取信息") @ApiImplicitParam(name = "openReplyTemplate", value = "对象", required = false, dataType = "OpenReplyTemplate", paramType = "query") public RestResult<OpenReplyTemplateVo> getByOpenReplyTemplate(OpenReplyTemplate openReplyTemplate) { openReplyTemplate = openReplyTemplateService.getByBean(openReplyTemplate); OpenReplyTemplateVo openReplyTemplateVo = openReplyTemplateService.setVoProperties(openReplyTemplate); log.info(String.format("根据id获取:%s", JSONUtil.toJsonStr(openReplyTemplateVo))); return RestResult.ok(openReplyTemplateVo); } /** * 根据OpenReplyTemplate对象属性检索所有 * * @param openReplyTemplate * @return */ @GetMapping("/listByOpenReplyTemplate") @ApiOperation(value="根据OpenReplyTemplate对象属性检索所有", notes="根据OpenReplyTemplate对象属性检索所有信息") @ApiImplicitParam(name = "openReplyTemplate", value = "对象", required = false, dataType = "OpenReplyTemplate", paramType = "query") public RestResult<Collection<OpenReplyTemplateVo>> listByOpenReplyTemplate(OpenReplyTemplate openReplyTemplate) { Collection<OpenReplyTemplate> openReplyTemplates = openReplyTemplateService.listByBean(openReplyTemplate); Collection<OpenReplyTemplateVo> openReplyTemplateVos = openReplyTemplateService.setVoProperties(openReplyTemplates); log.info(String.format("根据OpenReplyTemplate对象属性检索所有: %s ",JSONUtil.toJsonStr(openReplyTemplateVos))); return RestResult.ok(openReplyTemplateVos); } /** * 根据OpenReplyTemplate对象属性分页检索 * * @param openReplyTemplate * @return */ @GetMapping("/pageByOpenReplyTemplate") @ApiOperation(value="根据OpenReplyTemplate对象属性分页检索", notes="根据OpenReplyTemplate对象属性分页检索信息") @ApiImplicitParam(name = "openReplyTemplate", value = "对象", required = false, dataType = "OpenReplyTemplate", paramType = "query") public RestResult<IPage<OpenReplyTemplateVo>> pageByOpenReplyTemplate(OpenReplyTemplate openReplyTemplate) { IPage<OpenReplyTemplateVo> openReplyTemplates = openReplyTemplateService.pageByBean(openReplyTemplate); openReplyTemplates.setRecords(openReplyTemplateService.setVoProperties(openReplyTemplates.getRecords())); log.info(String.format("根据OpenReplyTemplate对象属性分页检索: %s ",JSONUtil.toJsonStr(openReplyTemplates))); return RestResult.ok(openReplyTemplates); } }
42.719178
161
0.735129
7d0677fc46b46982066a441f46a5436e3ff4d06e
628
package com.example.practice_pro.sbJedis.service.impl; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; /** * 集群ServiceImpl * @ClassName ClusterServiceImpl * @Description 集群ServiceImpl * @Author hongguo.zhu * @Date 2022/1/5 15:54 * @Version 1.0 */ @Service @RequiredArgsConstructor public class ClusterServiceImpl { @Autowired private StringRedisTemplate stringRedisTemplate; public String clusterCreate(){ return null; } }
19.625
63
0.772293
195f613ec15781d5ada1476d034eb2b73cd475a7
1,859
/* * Copyright (c) 2021 Microsoft Corporation * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0 * * SPDX-License-Identifier: Apache-2.0 * * Contributors: * Microsoft Corporation - initial API and implementation * */ package org.eclipse.dataspaceconnector.iam.did.keys; import com.nimbusds.jose.jwk.RSAKey; import org.eclipse.dataspaceconnector.spi.monitor.Monitor; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.InputStream; import java.nio.file.Paths; import java.security.KeyStore; import static java.lang.String.format; /** * Temporary key loader until DID key management is implemented. * * TODO HACKATHON-1 TASK 6A Usage of these functions in main code needs to be removed. */ public class TemporaryKeyLoader { private static final String TEST_KEYSTORE = "edc-test-keystore.jks"; private static final String PASSWORD = "test123"; private static RSAKey keys; @Nullable public static RSAKey loadKeys(Monitor monitor) { if (keys == null) { try { var url = Paths.get("secrets" + File.separator + TEST_KEYSTORE).toUri().toURL(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream stream = url.openStream()) { keyStore.load(stream, PASSWORD.toCharArray()); } keys = RSAKey.load(keyStore, "testkey", PASSWORD.toCharArray()); } catch (Exception e) { monitor.info(format("Cannot load test keys - the keystore %s should be placed in the secrets directory", TEST_KEYSTORE)); return null; } } return keys; } }
32.614035
137
0.665949
a099b4d3c34ca6e0aa03f9e9dcd83f4e498a8012
5,946
/* file: DataStructuresMatrix.java */ /******************************************************************************* * Copyright 2014-2018 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* // Content: // Java example of using matrix data structures //////////////////////////////////////////////////////////////////////////////// */ /** * <a name="DAAL-EXAMPLE-JAVA-DATASTRUCTURESMATRIX"> * @example DataStructuresMatrix.java */ package com.intel.daal.examples.datasource; import java.nio.DoubleBuffer; import com.intel.daal.data_management.data.Matrix; import com.intel.daal.data_management.data.NumericTable; import com.intel.daal.examples.utils.Service; import com.intel.daal.services.DaalContext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; class DataStructuresMatrix { private static final int nVectorsMatrix = 10; private static final int nFeaturesMatrix = 11; private static final int firstReadRow = 0; private static final int nRead = 5; private static DaalContext context = new DaalContext(); public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { System.out.println("Matrix numeric table example\n"); int readFeatureIdx; double[] data = { 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1, 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f, 1.8f, 1.9f, 2, 2.0f, 2.1f, 2.2f, 2.3f, 2.4f, 2.5f, 2.6f, 2.7f, 2.8f, 2.9f, 3, 3.0f, 3.1f, 3.2f, 3.3f, 3.4f, 3.5f, 3.6f, 3.7f, 3.8f, 3.9f, 4, 4.0f, 4.1f, 4.2f, 4.3f, 4.4f, 4.5f, 4.6f, 4.7f, 4.8f, 4.9f, 5, 5.0f, 5.1f, 5.2f, 5.3f, 5.4f, 5.5f, 5.6f, 5.7f, 5.8f, 5.9f, 1, 6.0f, 6.1f, 6.2f, 6.3f, 6.4f, 6.5f, 6.6f, 6.7f, 6.8f, 6.9f, 2, 7.0f, 7.1f, 7.2f, 7.3f, 7.4f, 7.5f, 7.6f, 7.7f, 7.8f, 7.9f, 3, 8.0f, 8.1f, 8.2f, 8.3f, 8.4f, 8.5f, 8.6f, 8.7f, 8.8f, 8.9f, 4, 9.0f, 9.1f, 9.2f, 9.3f, 9.4f, 9.5f, 9.6f, 9.7f, 9.8f, 9.9f, 5 }; Matrix dataTable = new Matrix(context, data, nFeaturesMatrix, nVectorsMatrix); /* Read a block of rows */ DoubleBuffer dataDouble = DoubleBuffer.allocate(nRead * nFeaturesMatrix); dataDouble = dataTable.getBlockOfRows(firstReadRow, nRead, dataDouble); System.out.printf("%d rows are read\n", nRead); printDoubleBuffer(dataDouble, nFeaturesMatrix, nRead, "Print 5 rows from matrix data array as float:"); dataTable.releaseBlockOfRows(firstReadRow, nRead, dataDouble); readFeatureIdx = 2; /* Set new values in Matrix */ dataTable.set(firstReadRow, readFeatureIdx, (double)-1); dataTable.set(firstReadRow + 1, readFeatureIdx, (double)-2); dataTable.set(firstReadRow + 2, readFeatureIdx, (double)-3); /* Read a feature (column) */ DoubleBuffer dataDoubleFeatures = DoubleBuffer.allocate((int) nVectorsMatrix); dataDoubleFeatures = dataTable.getBlockOfColumnValues(readFeatureIdx, firstReadRow, nVectorsMatrix, dataDoubleFeatures); printDoubleBuffer(dataDoubleFeatures, 1, nVectorsMatrix, "Print the third feature of matrix data:"); dataTable.releaseBlockOfColumnValues(readFeatureIdx, firstReadRow, nVectorsMatrix, dataDoubleFeatures); context.dispose(); } private static void printDoubleBuffer(DoubleBuffer buf, long nColumns, long nRows, String message) { int step = (int) nColumns; System.out.println(message); for (int i = 0; i < nRows; i++) { for (int j = 0; j < nColumns; j++) { System.out.format("%6.3f ", buf.get(i * step + j)); } System.out.println(""); } System.out.println(""); } }
45.389313
128
0.645308
22b0831cf584d0f8fb6fcba31ba805f33ce0425c
1,138
/* * 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.google.codeu.servlets; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/blobstore-upload-url") /** * Servlet to get Blobstore Url, and redirect from request to MessageServlet */ public class BlobstoreUploadUrlServlet extends HttpServlet{ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Get the Blobstore URL BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); String uploadUrl = blobstoreService.createUploadUrl("/messages") ; response.setContentType("text/html"); response.getOutputStream().println(uploadUrl); } }
35.5625
98
0.793497
881f0dab769fd2fc4ecee357018fb31c9d379bf3
3,610
package io.ona.kujaku.sample.activities; import android.os.Bundle; import androidx.annotation.NonNull; import android.util.Log; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.OnMapReadyCallback; import com.mapbox.mapboxsdk.maps.Style; import io.ona.kujaku.exceptions.WmtsCapabilitiesException; import io.ona.kujaku.listeners.WmtsCapabilitiesListener; import io.ona.kujaku.sample.BuildConfig; import io.ona.kujaku.sample.R; import io.ona.kujaku.services.WmtsCapabilitiesService; import io.ona.kujaku.wmts.model.WmtsCapabilities; import io.ona.kujaku.views.KujakuMapView; public class WmtsActivity extends BaseNavigationDrawerActivity { private static final String TAG = WmtsActivity.class.getName(); private KujakuMapView kujakuMapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, BuildConfig.MAPBOX_SDK_ACCESS_TOKEN); kujakuMapView = findViewById(R.id.wmts_mapView); WmtsCapabilitiesService wmtsService = new WmtsCapabilitiesService(getString(R.string.wmts_capabilities_url)); wmtsService.requestData(); wmtsService.setListener(new WmtsCapabilitiesListener() { @Override public void onCapabilitiesReceived(WmtsCapabilities capabilities) { try { kujakuMapView.addWmtsLayer(capabilities); } catch (WmtsCapabilitiesException ex) { Log.e(TAG, "A WmtsCapabilitiesException occurs", ex); } } @Override public void onCapabilitiesError(Exception ex) { Log.e(TAG,"Capabilities Exception", ex); } }); kujakuMapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull MapboxMap mapboxMap) { mapboxMap.setStyle(Style.MAPBOX_STREETS); mapboxMap.easeCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(30.96088179449847 , -99.1250589414584) , 5.441840862122009) ); } }); } @Override protected void onResume() { super.onResume(); if (kujakuMapView != null) kujakuMapView.onResume(); } @Override protected int getContentView() { return R.layout.wmts_map_view; } @Override protected int getSelectedNavigationItem() { return R.id.nav_wmts_activity; } @Override protected void onStart() { super.onStart(); if (kujakuMapView != null) kujakuMapView.onStart(); } @Override protected void onStop() { super.onStop(); if (kujakuMapView != null) kujakuMapView.onStop(); } @Override protected void onPause() { super.onPause(); if (kujakuMapView != null) kujakuMapView.onPause(); } @Override protected void onDestroy() { super.onDestroy(); if (kujakuMapView != null) kujakuMapView.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (kujakuMapView != null) kujakuMapView.onSaveInstanceState(outState); } @Override public void onLowMemory() { super.onLowMemory(); if (kujakuMapView != null) kujakuMapView.onLowMemory(); } }
30.59322
117
0.658726
083deb0378887ca3acf8221c65ac9b1a1bbb023d
583
package com.BankingApp.exception; import javax.persistence.PersistenceException; public class BankingException extends PersistenceException { public BankingException() { super(); // TODO Auto-generated constructor stub } public BankingException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public BankingException(String message) { super(message); // TODO Auto-generated constructor stub } public BankingException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
18.21875
59
0.753002
23149331e75831a6dc7862f5066023422547e79f
1,703
package oasis.names.tc.ebxml_regrep.xsd.query._3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="PersonQueryType", propOrder={"addressFilter", "personNameFilter", "telephoneNumberFilter", "emailAddressFilter"}) @XmlSeeAlso({UserQueryType.class}) public class PersonQueryType extends RegistryObjectQueryType { @XmlElement(name="AddressFilter") protected List<FilterType> addressFilter; @XmlElement(name="PersonNameFilter") protected FilterType personNameFilter; @XmlElement(name="TelephoneNumberFilter") protected List<FilterType> telephoneNumberFilter; @XmlElement(name="EmailAddressFilter") protected List<FilterType> emailAddressFilter; public List<FilterType> getAddressFilter() { if (this.addressFilter == null) { this.addressFilter = new ArrayList(); } return this.addressFilter; } public FilterType getPersonNameFilter() { return this.personNameFilter; } public void setPersonNameFilter(FilterType value) { this.personNameFilter = value; } public List<FilterType> getTelephoneNumberFilter() { if (this.telephoneNumberFilter == null) { this.telephoneNumberFilter = new ArrayList(); } return this.telephoneNumberFilter; } public List<FilterType> getEmailAddressFilter() { if (this.emailAddressFilter == null) { this.emailAddressFilter = new ArrayList(); } return this.emailAddressFilter; } }
26.609375
128
0.758661
a12c2e0ed607428b660b19762df653eabdf8b642
1,690
package com.example; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer { // @Value("${spring.resources.static-locations}") // String resourceLocations; // @Override // public void addResourceHandlers(ResourceHandlerRegistry registry) { // registry // .addResourceHandler("/resources/**") // .addResourceLocations("/resources/"); // } @Bean public ViewResolver getViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("resources/static/"); resolver.setPrefix("resources/templates/"); resolver.setSuffix(".html"); return resolver; } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } // @Override // public void addResourceHandlers(ResourceHandlerRegistry registry) { // registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); // } }
35.957447
95
0.752663
3b5dfac3aab098eaa659921a35f5d839ba2fbbad
6,412
package egovframework.com.cop.bbs.service.impl; import static org.junit.Assert.assertEquals; import java.util.Date; import javax.annotation.Resource; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import egovframework.com.cmm.LoginVO; import egovframework.com.cmm.util.EgovUserDetailsHelper; import egovframework.com.cop.bbs.service.BoardMaster; import egovframework.com.cop.bbs.service.BoardMasterVO; import egovframework.com.test.EgovTestV1; import egovframework.rte.fdl.cmmn.exception.FdlException; import egovframework.rte.fdl.idgnr.EgovIdGnrService; import egovframework.rte.fdl.string.EgovDateUtil; import lombok.extern.slf4j.Slf4j; @Slf4j @ContextConfiguration(classes = { EgovBBSMasterDAOTest_AAA_Configuration.class }) public class EgovBBSMasterDAOTest_selectBBSMasterDetail extends EgovTestV1 { @Autowired private EgovBBSMasterDAO egovBBSMasterDAO; @Resource(name = "egovBBSMstrIdGnrService") private EgovIdGnrService egovBBSMstrIdGnrService; @Resource(name = "egovNttIdGnrService") private EgovIdGnrService egovNttIdGnrService; @Resource(name = "egovBlogIdGnrService") private EgovIdGnrService egovBlogIdGnrService; @Test public void test() { log.debug("test"); // given BoardMasterVO boardMasterVO = testData(); // when BoardMasterVO bbsMasterDetail = egovBBSMasterDAO.selectBBSMasterDetail(boardMasterVO); debug(bbsMasterDetail); // then assertEquals(bbsMasterDetail.getBbsId(), boardMasterVO.getBbsId()); assertEquals(bbsMasterDetail.getBbsId(), boardMasterVO.getBbsId()); assertEquals(bbsMasterDetail.getBbsTyCode(), boardMasterVO.getBbsTyCode()); assertEquals(bbsMasterDetail.getBbsNm(), boardMasterVO.getBbsNm()); assertEquals(bbsMasterDetail.getBbsIntrcn(), boardMasterVO.getBbsIntrcn()); assertEquals(bbsMasterDetail.getReplyPosblAt(), boardMasterVO.getReplyPosblAt()); assertEquals(bbsMasterDetail.getFileAtchPosblAt(), boardMasterVO.getFileAtchPosblAt()); assertEquals(bbsMasterDetail.getAtchPosblFileNumber(), boardMasterVO.getAtchPosblFileNumber()); assertEquals(bbsMasterDetail.getAtchPosblFileSize(), boardMasterVO.getAtchPosblFileSize()); assertEquals(bbsMasterDetail.getTmplatId(), boardMasterVO.getTmplatId()); assertEquals(bbsMasterDetail.getFrstRegisterId(), boardMasterVO.getFrstRegisterId()); // assertEquals(bbsMasterDetail.getFrstRegisterNm(), boardMasterVO.getFrstRegisterNm()); // assertEquals(bbsMasterDetail.getFrstRegisterPnttm(), boardMasterVO.getFrstRegisterPnttm()); // assertEquals(bbsMasterDetail.getBbsTyCodeNm(), boardMasterVO.getBbsTyCodeNm()); assertEquals(bbsMasterDetail.getTmplatNm(), boardMasterVO.getTmplatNm()); assertEquals(bbsMasterDetail.getAuthFlag(), boardMasterVO.getAuthFlag()); assertEquals(bbsMasterDetail.getTmplatCours(), boardMasterVO.getTmplatCours()); assertEquals(bbsMasterDetail.getCmmntyId(), boardMasterVO.getCmmntyId()); assertEquals(bbsMasterDetail.getBlogId(), boardMasterVO.getBlogId()); } public BoardMasterVO testData() { BoardMaster boardMaster = new BoardMaster(); try { boardMaster.setBbsId(egovBBSMstrIdGnrService.getNextStringId()); } catch (FdlException e) { log.error(e.getMessage()); } String today = " " + EgovDateUtil.toString(new Date(), null, null); LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); boardMaster.setBbsTyCode("BBST01"); // COM101 BBST01 통합게시판 boardMaster.setBbsNm("test 게시판명" + today); // 게시판명 boardMaster.setBbsIntrcn("test 게시판소개" + today); // 게시판소개 boardMaster.setReplyPosblAt("Y"); // 답장가능여부 boardMaster.setFileAtchPosblAt("Y"); // 파일첨부가능여부 boardMaster.setAtchPosblFileNumber(3); // 첨부가능파일숫자 boardMaster.setTmplatId(""); // 템플릿ID boardMaster.setUseAt("Y"); // 사용여부 boardMaster.setCmmntyId(""); // 커뮤니티ID boardMaster.setFrstRegisterId(loginVO.getUniqId()); // 최초등록자ID try { boardMaster.setBlogId(egovBlogIdGnrService.getNextStringId()); } catch (FdlException e) { log.error(e.getMessage()); } // 블로그 ID boardMaster.setBlogAt("Y"); // 블로그 여부 egovBBSMasterDAO.insertBBSMasterInf(boardMaster); BoardMasterVO boardMasterVO = new BoardMasterVO(); boardMasterVO.setBbsId(boardMaster.getBbsId()); boardMasterVO.setUniqId(loginVO.getUniqId()); boardMasterVO.setBbsTyCode(boardMaster.getBbsTyCode()); boardMasterVO.setBbsNm(boardMaster.getBbsNm()); boardMasterVO.setBbsIntrcn(boardMaster.getBbsIntrcn()); boardMasterVO.setReplyPosblAt(boardMaster.getReplyPosblAt()); boardMasterVO.setFileAtchPosblAt(boardMaster.getFileAtchPosblAt()); boardMasterVO.setAtchPosblFileNumber(boardMaster.getAtchPosblFileNumber()); boardMasterVO.setAtchPosblFileSize(boardMaster.getAtchPosblFileSize()); boardMasterVO.setTmplatId(boardMaster.getTmplatId()); boardMasterVO.setFrstRegisterId(boardMaster.getFrstRegisterId()); boardMasterVO.setCmmntyId(boardMaster.getCmmntyId()); boardMasterVO.setBlogId(boardMaster.getBlogId()); return boardMasterVO; } void debug(BoardMasterVO bbsMasterDetail) { log.debug("bbsMasterDetail={}", bbsMasterDetail); log.debug("getBbsId={}", bbsMasterDetail.getBbsId()); log.debug("getAuthFlag={}", bbsMasterDetail.getAuthFlag()); log.debug("bbsId={}", bbsMasterDetail.getBbsId()); log.debug("bbsTyCode={}", bbsMasterDetail.getBbsTyCode()); log.debug("bbsNm={}", bbsMasterDetail.getBbsNm()); log.debug("bbsIntrcn={}", bbsMasterDetail.getBbsIntrcn()); log.debug("replyPosblAt={}", bbsMasterDetail.getReplyPosblAt()); log.debug("fileAtchPosblAt={}", bbsMasterDetail.getFileAtchPosblAt()); log.debug("atchPosblFileNumber={}", bbsMasterDetail.getAtchPosblFileNumber()); log.debug("atchPosblFileSize={}", bbsMasterDetail.getAtchPosblFileSize()); log.debug("tmplatId={}", bbsMasterDetail.getTmplatId()); log.debug("frstRegisterId={}", bbsMasterDetail.getFrstRegisterId()); log.debug("frstRegisterNm={}", bbsMasterDetail.getFrstRegisterNm()); log.debug("frstRegisterPnttm={}", bbsMasterDetail.getFrstRegisterPnttm()); log.debug("bbsTyCodeNm={}", bbsMasterDetail.getBbsTyCodeNm()); log.debug("tmplatNm={}", bbsMasterDetail.getTmplatNm()); log.debug("authFlag={}", bbsMasterDetail.getAuthFlag()); log.debug("tmplatCours={}", bbsMasterDetail.getTmplatCours()); log.debug("cmmntyId={}", bbsMasterDetail.getCmmntyId()); log.debug("blogId={}", bbsMasterDetail.getBlogId()); } }
43.324324
97
0.786494
035b99e5533c2d348a13727db1de06e55040339e
534
package com.fds.repository.qlvtdb; public class AccessRole { private String shortName; private String title; private String permission; public String getShortName() { return shortName; } public void setShortName(String shortName) { this.shortName = shortName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } }
21.36
47
0.728464
c6390434e0b2aa313f6467bc82fafd7c623e3525
221
package io.crnk.gen.typescript.processor; import java.util.Set; import io.crnk.gen.typescript.model.TSSource; @FunctionalInterface public interface TSSourceProcessor { Set<TSSource> process(Set<TSSource> sources); }
18.416667
46
0.800905
8429683f3dd96241a8a69783c5fc9cb0aa6af13b
3,301
package com.softmotions.ncms.atm; import java.io.IOException; import java.util.Objects; import java.util.UUID; import org.atmosphere.config.managed.Decoder; import org.atmosphere.config.managed.Encoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.inject.Inject; /** * @author Adamansky Anton (adamansky@softmotions.com) */ public class WSMessage { private static final Logger log = LoggerFactory.getLogger(WSMessage.class); private final String uuid; private final ObjectNode data; private final ObjectMapper mapper; public WSMessage(ObjectMapper mapper, ObjectNode onode) { this.mapper = mapper; this.data = onode; if (!data.path("uuid").isTextual()) { uuid = UUID.randomUUID().toString(); data.put("uuid", uuid); } else { this.uuid = data.path("uuid").asText(); } } public WSMessage(ObjectMapper mapper, String sdata) throws IOException { this(mapper, (ObjectNode) mapper.readTree(sdata)); } public WSMessage(ObjectMapper mapper) { this.mapper = mapper; uuid = UUID.randomUUID().toString(); data = mapper.createObjectNode(); data.put("uuid", uuid); } public String getUuid() { return uuid; } public ObjectNode getData() { return data; } public ObjectMapper getMapper() { return mapper; } public String getType() { return data.path("type").asText(); } public WSMessage put(String key, String value) { data.put(key, value); return this; } public WSMessage put(String key, Boolean value) { data.put(key, value); return this; } public WSMessage put(String key, Long value) { data.put(key, value); return this; } public WSMessage putPOJO(String key, Object value) { data.putPOJO(key, value); return this; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WSMessage that = (WSMessage) o; return Objects.equals(uuid, that.uuid); } public int hashCode() { return Objects.hash(uuid); } public String toString() { try { return mapper.writeValueAsString(data); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } public static class EncoderDecoder implements Decoder<String, WSMessage>, Encoder<WSMessage, String> { private final ObjectMapper mapper; @Inject public EncoderDecoder(ObjectMapper mapper) { this.mapper = mapper; } @Override public String encode(WSMessage m) { return m.toString(); } @Override public WSMessage decode(String s) { try { return new WSMessage(mapper, s); } catch (IOException e) { log.error("", e); throw new RuntimeException(e); } } } }
24.819549
106
0.606483
aca0a90fa204215f904dc265f2856b2ef9fe8d92
12,157
// Copyright (c) 2018-2022 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.google.apigee.callouts; import com.apigee.flow.execution.ExecutionContext; import com.apigee.flow.execution.ExecutionResult; import com.apigee.flow.execution.IOIntensive; import com.apigee.flow.execution.spi.Execution; import com.apigee.flow.message.MessageContext; import com.google.apigee.encoding.Base16; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.spec.MGF1ParameterSpec; import java.security.spec.PSSParameterSpec; import java.util.Base64; import java.util.Map; import java.util.function.Function; @IOIntensive public class RsaSignature extends RsaBase implements Execution { protected static final String DEFAULT_PRIMARY_HASH = "SHA-256"; protected static final String DEFAULT_SCHEME = "PKCS1_V1.5"; protected static final String DEFAULT_SIGNATURE_ALGORITHM = "SHA256WithRSA"; protected static final String DEFAULT_SIGNATURE_PROVIDER = "BC"; public RsaSignature(Map properties) { super(properties); } enum SignAction { SIGN, VERIFY }; enum SigningScheme { PKCS1V15, PSS, INVALID, NOT_SPECIFIED; public static SigningScheme forName(String name) { if (name == null) return SigningScheme.NOT_SPECIFIED; if ("PSS".equals(name) || "RSASSA-PSS".equals(name)) return SigningScheme.PSS; if ("PKCS1V15".equals(name) || "PKCS1_V1.5".equals(name) || "RSASSA-PKCS1-v1_5".equals(name)) return SigningScheme.PKCS1V15; return SigningScheme.INVALID; } }; static class HashFunctions { public String primary; public String mgf1; } static class SigningConfiguration { public SigningScheme scheme; public HashFunctions hashes; public String signatureProvider; public SigningConfiguration() { hashes = new HashFunctions(); scheme = SigningScheme.NOT_SPECIFIED; } } String getVarPrefix() { return "signing_"; } private EncodingType _getEncodingTypeProperty(MessageContext msgCtxt, String propName) throws Exception { return EncodingType.valueOf(_getStringProp(msgCtxt, propName, "NONE").toUpperCase()); } private EncodingType getEncodeResult(MessageContext msgCtxt) throws Exception { return _getEncodingTypeProperty(msgCtxt, "encode-result"); } private static SignAction findByName(String name) { for (SignAction action : SignAction.values()) { if (name.equals(action.name())) { return action; } } return null; } private SignAction getAction(MessageContext msgCtxt) throws Exception { String action = this.properties.get("action"); if (action != null) action = action.trim(); if (action == null || action.equals("")) { throw new IllegalStateException("specify an action."); } action = resolveVariableReferences(action, msgCtxt); SignAction cryptoAction = findByName(action.toUpperCase()); if (cryptoAction == null) throw new IllegalStateException("specify a valid action."); return cryptoAction; } protected byte[] getSourceBytes(SignAction action, MessageContext msgCtxt) throws Exception { Object source1 = msgCtxt.getVariable(getSourceVar()); if (source1 instanceof byte[]) { return (byte[]) source1; } if (source1 instanceof String) { EncodingType decodingKind = _getEncodingTypeProperty(msgCtxt, "decode-source"); return decodeString((String) source1, decodingKind); } // coerce and hope for the best return (source1.toString()).getBytes(StandardCharsets.UTF_8); } protected byte[] getSignatureBytes(MessageContext msgCtxt) throws Exception { String signatureVar = _getStringProp(msgCtxt, "signature-source", "signature"); Object sig = msgCtxt.getVariable(signatureVar); if (sig instanceof byte[]) { return (byte[]) sig; } if (sig instanceof String) { EncodingType decodingKind = _getEncodingTypeProperty(msgCtxt, "decode-signature"); return decodeString((String) sig, decodingKind); } // coerce and hope for the best return (sig.toString()).getBytes(StandardCharsets.UTF_8); } protected SigningScheme getScheme(MessageContext msgCtxt) throws Exception { String schemeString = _getStringProp(msgCtxt, "scheme", DEFAULT_SCHEME); SigningScheme scheme = SigningScheme.forName(schemeString.toUpperCase()); if (scheme == SigningScheme.INVALID) { throw new IllegalStateException("unrecognized scheme"); } msgCtxt.setVariable(varName("scheme"), scheme.name()); return scheme; } private static Signature getSignatureInstance(SigningConfiguration sigConfig) throws Exception { if (sigConfig.scheme == SigningScheme.PKCS1V15) { // RSASSA-PKCS1-v1_5 String signingAlgorithm = sigConfig.hashes.primary.equals("SHA-256") ? "SHA256withRSA" : "SHA1withRSA"; return Signature.getInstance(signingAlgorithm, sigConfig.signatureProvider); } // RSASSA-PSS if (sigConfig.hashes == null) { throw new IllegalStateException("missing PSS hashes"); } String signingAlgorithm = sigConfig.hashes.primary.equals("SHA-256") ? "SHA256withRSA/PSS" : "SHA1withRSA/PSS"; Signature signature = Signature.getInstance(signingAlgorithm, sigConfig.signatureProvider); MGF1ParameterSpec mgf1pspec = getMGF1ParameterSpec(sigConfig.hashes.mgf1); int saltLength = (sigConfig.hashes.mgf1.equals("SHA-1")) ? 20 : (sigConfig.hashes.mgf1.equals("SHA-256")) ? 32 : 0; int trailer = 1; signature.setParameter( new PSSParameterSpec( sigConfig.hashes.primary, "MGF1", mgf1pspec, saltLength, trailer)); return signature; } public static byte[] sign(PrivateKey privateKey, byte[] data, SigningConfiguration sigConfig) throws Exception { Signature signer = getSignatureInstance(sigConfig); signer.initSign(privateKey); signer.update(data); return signer.sign(); } public static boolean verify( PublicKey publicKey, byte[] data, byte[] signature, SigningConfiguration sigConfig) throws Exception { Signature verifier = getSignatureInstance(sigConfig); verifier.initVerify(publicKey); verifier.update(data); boolean result = verifier.verify(signature); return result; } private void clearVariables(MessageContext msgCtxt) { msgCtxt.removeVariable(varName("error")); msgCtxt.removeVariable(varName("exception")); msgCtxt.removeVariable(varName("stacktrace")); msgCtxt.removeVariable(varName("action")); } private void setSignatureOutputVariables(MessageContext msgCtxt, byte[] result) throws Exception { EncodingType outputEncodingWanted = getEncodeResult(msgCtxt); String outputVar = getOutputVar(msgCtxt); Function<byte[], Object> encoder = null; if (outputEncodingWanted == EncodingType.NONE) { // Emit the result as a Java byte array. // Will be retrievable only by another Java callout. msgCtxt.setVariable(varName("output_encoding"), "none"); encoder = (a) -> a; // nop } else if (outputEncodingWanted == EncodingType.BASE64) { msgCtxt.setVariable(varName("output_encoding"), "base64"); encoder = (a) -> Base64.getEncoder().encodeToString(a); } else if (outputEncodingWanted == EncodingType.BASE64URL) { msgCtxt.setVariable(varName("output_encoding"), "base64url"); encoder = (a) -> Base64.getUrlEncoder().withoutPadding().encodeToString(a); } else if (outputEncodingWanted == EncodingType.BASE16) { msgCtxt.setVariable(varName("output_encoding"), "base16"); encoder = (a) -> Base16.encode(a); } else { throw new IllegalStateException("unhandled encoding"); } msgCtxt.setVariable(outputVar, encoder.apply(result)); } private void emitKeyPair(MessageContext msgCtxt, KeyPair keypair) { String privateKeyString = "-----BEGIN PRIVATE KEY-----\n" + Base64.getMimeEncoder().encodeToString(keypair.getPrivate().getEncoded()) + "\n-----END PRIVATE KEY-----\n"; msgCtxt.setVariable(varName("output-privatekey-pem"), privateKeyString); String publicKeyString = "-----BEGIN PUBLIC KEY-----\n" + Base64.getMimeEncoder().encodeToString(keypair.getPublic().getEncoded()) + "\n-----END PUBLIC KEY-----\n"; msgCtxt.setVariable(varName("output-publickey-pem"), publicKeyString); } KeyPair generateKeyPair() throws java.security.NoSuchAlgorithmException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.generateKeyPair(); return kp; } SigningConfiguration initSigningConfiguration(MessageContext msgCtxt) throws Exception { String padding = _getStringProp(msgCtxt, "padding", null); if (padding != null) { throw new IllegalStateException("padding is not a supported configuration option"); } SigningConfiguration config = new SigningConfiguration(); config.scheme = getScheme(msgCtxt); String primaryHash = _getStringProp(msgCtxt, "primary-hash", DEFAULT_PRIMARY_HASH); msgCtxt.setVariable(varName("primary-hash"), primaryHash); config.hashes.primary = primaryHash; if (config.scheme == SigningScheme.PSS) { String mgf1 = getMgf1Hash(msgCtxt, primaryHash); msgCtxt.setVariable(varName("mgf1"), mgf1); config.hashes.mgf1 = mgf1; } else if (config.scheme != SigningScheme.PKCS1V15) { throw new IllegalStateException("padding is not a supported configuration option"); } config.signatureProvider = _getStringProp(msgCtxt, "signature-provider", DEFAULT_SIGNATURE_PROVIDER); return config; } public ExecutionResult execute(MessageContext msgCtxt, ExecutionContext exeCtxt) { boolean debug = false; try { clearVariables(msgCtxt); debug = getDebug(msgCtxt); SignAction action = getAction(msgCtxt); // sign or verify msgCtxt.setVariable(varName("action"), action.name().toLowerCase()); SigningConfiguration sigConfig = initSigningConfiguration(msgCtxt); byte[] source = getSourceBytes(action, msgCtxt); if (action == SignAction.SIGN) { boolean wantGenerateKey = _getBooleanProperty(msgCtxt, "generate-key", false); KeyPair keypair = null; PrivateKey privateKey = null; if (wantGenerateKey) { keypair = generateKeyPair(); privateKey = keypair.getPrivate(); } else { privateKey = getPrivateKey(msgCtxt); } byte[] signature = sign(privateKey, source, sigConfig); setSignatureOutputVariables(msgCtxt, signature); if (keypair != null) { emitKeyPair(msgCtxt, keypair); } } else { msgCtxt.setVariable(varName("verified"), "false"); PublicKey publicKey = getPublicKey(msgCtxt); byte[] signature = getSignatureBytes(msgCtxt); boolean verified = verify(publicKey, source, signature, sigConfig); msgCtxt.setVariable(varName("verified"), Boolean.toString(verified)); if (!verified) { msgCtxt.setVariable(varName("error"), "verification of the signature failed"); return ExecutionResult.ABORT; } } } catch (Exception e) { if (debug) { e.printStackTrace(); String stacktrace = getStackTraceAsString(e); msgCtxt.setVariable(varName("stacktrace"), stacktrace); } setExceptionVariables(e, msgCtxt); return ExecutionResult.ABORT; } return ExecutionResult.SUCCESS; } }
36.289552
100
0.700173
2772013e9315b9ccb1326e6bf472d661db0abe7e
107
package org.seasar.doma.internal.apt.processor.dao; public class IllegalConstructorDelegateDaoDelegate {}
26.75
53
0.850467
1e6d0116af0b661886a514bc254ad7d35647513c
4,262
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.vpc.v20170312.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeDirectConnectGatewayCcnRoutesRequest extends AbstractModel{ /** * The ID of the Direct Connect gateway, such as `dcg-prpqlmg1`. */ @SerializedName("DirectConnectGatewayId") @Expose private String DirectConnectGatewayId; /** * The route learning type of the CCN. Available values: <li>`BGP` - Automatic learning.</li> <li>`STATIC` - Static means user-configured. This is the default value.</li> */ @SerializedName("CcnRouteType") @Expose private String CcnRouteType; /** * Offset. */ @SerializedName("Offset") @Expose private Long Offset; /** * The returned quantity. */ @SerializedName("Limit") @Expose private Long Limit; /** * Get The ID of the Direct Connect gateway, such as `dcg-prpqlmg1`. * @return DirectConnectGatewayId The ID of the Direct Connect gateway, such as `dcg-prpqlmg1`. */ public String getDirectConnectGatewayId() { return this.DirectConnectGatewayId; } /** * Set The ID of the Direct Connect gateway, such as `dcg-prpqlmg1`. * @param DirectConnectGatewayId The ID of the Direct Connect gateway, such as `dcg-prpqlmg1`. */ public void setDirectConnectGatewayId(String DirectConnectGatewayId) { this.DirectConnectGatewayId = DirectConnectGatewayId; } /** * Get The route learning type of the CCN. Available values: <li>`BGP` - Automatic learning.</li> <li>`STATIC` - Static means user-configured. This is the default value.</li> * @return CcnRouteType The route learning type of the CCN. Available values: <li>`BGP` - Automatic learning.</li> <li>`STATIC` - Static means user-configured. This is the default value.</li> */ public String getCcnRouteType() { return this.CcnRouteType; } /** * Set The route learning type of the CCN. Available values: <li>`BGP` - Automatic learning.</li> <li>`STATIC` - Static means user-configured. This is the default value.</li> * @param CcnRouteType The route learning type of the CCN. Available values: <li>`BGP` - Automatic learning.</li> <li>`STATIC` - Static means user-configured. This is the default value.</li> */ public void setCcnRouteType(String CcnRouteType) { this.CcnRouteType = CcnRouteType; } /** * Get Offset. * @return Offset Offset. */ public Long getOffset() { return this.Offset; } /** * Set Offset. * @param Offset Offset. */ public void setOffset(Long Offset) { this.Offset = Offset; } /** * Get The returned quantity. * @return Limit The returned quantity. */ public Long getLimit() { return this.Limit; } /** * Set The returned quantity. * @param Limit The returned quantity. */ public void setLimit(Long Limit) { this.Limit = Limit; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "DirectConnectGatewayId", this.DirectConnectGatewayId); this.setParamSimple(map, prefix + "CcnRouteType", this.CcnRouteType); this.setParamSimple(map, prefix + "Offset", this.Offset); this.setParamSimple(map, prefix + "Limit", this.Limit); } }
30.661871
99
0.670108
8988ff1e394727f1275ed30e122fcfa142fa8e92
1,171
package com.optimaize.command4j.ext.extensions.failover; import com.optimaize.command4j.Command; import com.optimaize.command4j.commands.BaseCommand; import com.optimaize.command4j.ext.extensions.failover.autoretry.AutoRetryExtension; import com.optimaize.command4j.ext.extensions.failover.autoretry.AutoRetryStrategy; import org.jetbrains.annotations.NotNull; /** * A hub-class for easy access to built-in failover extensions. * * @author Fabian Kessler */ public class FailoverExtensions { public static final FailoverExtensions INSTANCE = new FailoverExtensions(); private FailoverExtensions(){} /** * Uses the {@link AutoRetryExtension}. * @see AutoRetryExtension */ public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) { return new AutoRetryExtension.Interceptor<>(cmd); } /** * @see AutoRetryExtension */ public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd, @NotNull AutoRetryStrategy strategy) { return new AutoRetryExtension.Interceptor<>(cmd, strategy); } }
30.815789
101
0.69257
c5e666be1e37546a216abf5f41d37e76f5dab33e
4,426
package com.mars.mvc.util; import com.alibaba.fastjson.JSONObject; import com.mars.common.annotation.api.MarsDataCheck; import com.mars.common.util.MatchUtil; import com.mars.common.util.MesUtil; import com.mars.common.util.StringUtil; import com.mars.server.server.request.HttpMarsRequest; import com.mars.server.server.request.HttpMarsResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 校验前端传参 */ public class ParamsCheckUtil { private static Logger logger = LoggerFactory.getLogger(ParamsCheckUtil.class); /** * 校验参数 * @param params 参数集合 * @param method 要执行的方法 * @return 校验结果 */ public static JSONObject checkParam(Object[] params, Method method){ if(params == null){ return null; } Class requestClass = HttpMarsRequest.class; Class responseClass = HttpMarsResponse.class; Class mapClass = Map.class; for(Object obj : params){ if(obj == null){ return null; } Class cls = obj.getClass(); if(requestClass.equals(cls) || responseClass.equals(cls) || mapClass.equals(cls)){ continue; } JSONObject result = checkParam(cls,obj,method); if(result != null){ return result; } } return null; } /** * 校验参数 * @param cls 参数类型 * @param obj 参数对象 * @return 校验结果 */ private static JSONObject checkParam(Class<?> cls, Object obj, Method method) { try { Field[] fields = cls.getDeclaredFields(); for(Field field : fields){ field.setAccessible(true); /* 获取校验的注解 */ MarsDataCheck marsDataCheck = field.getAnnotation(MarsDataCheck.class); if(marsDataCheck == null){ continue; } /* 判断此注解是否生效与当前api,如果不生效那就直接跳入下一次循环 */ String[] apis = marsDataCheck.apis(); if(!isThisApi(apis,method)){ continue; } /* 校验参数是否符合规则 */ Object val = field.get(obj); int errorCode = 1128; if(!reg(val,marsDataCheck.reg())){ return MesUtil.getMes(errorCode,marsDataCheck.msg()); } if(!notNull(marsDataCheck, val)){ return MesUtil.getMes(errorCode,marsDataCheck.msg()); } } return null; } catch (Exception e){ logger.error("校验参数出现异常",e); return null; } } /** * 校验正则 * @param val 数据 * @param reg 正则 * @return 结果 */ private static boolean reg(Object val,String reg){ if(StringUtil.isNull(reg)){ return true; } if(StringUtil.isNull(val)){ return false; } Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(val.toString()); return matcher.matches(); } /** * 校验长度 * @param val 数据 * @param marsDataCheck 注解 * @return 结果 */ private static boolean length(MarsDataCheck marsDataCheck, Object val){ long valLen = val.toString().length(); if(valLen < marsDataCheck.minLength() || valLen > marsDataCheck.maxLength()){ return false; } return true; } /** * 非空校验 * @param marsDataCheck 注解 * @param val 数据 * @return 结果 */ private static boolean notNull(MarsDataCheck marsDataCheck, Object val){ if(!marsDataCheck.notNull()){ return true; } if(StringUtil.isNull(val)){ return false; } return length(marsDataCheck, val); } /** * 校验apis列表里是否包含此api * @param method 此api * @param apis api列表 * @return */ private static boolean isThisApi(String[] apis, Method method){ if(apis == null || apis.length < 1){ return true; } for(String api : apis){ if(MatchUtil.isMatch(api,method.getName())){ return true; } } return false; } }
27.153374
94
0.544284
76165f370dc20261fcda38bd4dcc95dd3828dca8
315
package com.vmware.vim25; /** * @author Stefan Dilk <stefan.dilk@freenet.ag> * @since 6.7.2 */ public enum CryptoManagerKmipCryptoKeyStatusKeyUnavailableReason { KeyStateClusterInvalid, KeyStateClusterUnreachable, KeyStateMissingInCache, KeyStateMissingInKMS, KeyStateNotActiveOrEnabled }
19.6875
66
0.768254
e1d0ae160398406f062d42520cf808787edaf242
608
class ComputationGraph implements Serializable, Model, NeuralNetwork { /** * Set the specified input for the ComputationGraph */ public void setInput(int inputNum, INDArray input) { if (inputs == null) { //May be null after clear() inputs = new INDArray[numInputArrays]; } inputs[inputNum] = input; } private transient INDArray[] inputs; /** * The number of input arrays to the network. Many networks only have 1 input; however, a ComputationGraph may * have an arbitrary number (&gt;=1) separate input arrays */ private int numInputArrays; }
27.636364
114
0.674342
860e05ee7f7b725aeb2e5c74a3c1155b442b8e68
136
@jdk.internal.PreviewFeature(feature = jdk.internal.PreviewFeature.Feature.TEXT_BLOCKS) module producer { exports org.myorg.preview; }
34
87
0.816176
5c8ff4003bd3adf69a8190f237022204e0e0efad
591
package toti.templating.tags; import java.util.Map; import toti.templating.Tag; public class IfTag implements Tag { @Override public String getName() { return "if"; } @Override public String getPairStartCode(Map<String, String> params) { return getNotPairCode(params) + "{initNode(new HashMap<>());"; } @Override public String getPairEndCode(Map<String, String> params) { return "flushNode();}"; } @Override public String getNotPairCode(Map<String, String> params) { return String.format("if((boolean)(%s))", params.get("cond")); } }
19.7
65
0.670051
d04af425fe1caa3b58a16909a1da2e85a61ed710
2,499
// https://www.codewars.com/kata/who-likes-it/train/java // My solution class Solution { public static String whoLikesIt(String... names) { if(names.length == 0) return "no one likes this"; if(names.length == 1) return names[0] + " likes this"; if(names.length == 2) return names[0] + " and " + names[1] + " like this"; if(names.length == 3) return names[0] + ", " + names[1] + " and " + names[2] + " like this"; return names[0] + ", " + names[1] + " and " + String.valueOf(names.length - 2) +" others like this"; } } // ... class Solution { public static String whoLikesIt(String... names) { switch (names.length) { case 0: return "no one likes this"; case 1: return String.format("%s likes this", names[0]); case 2: return String.format("%s and %s like this", names[0], names[1]); case 3: return String.format("%s, %s and %s like this", names[0], names[1], names[2]); default: return String.format("%s, %s and %d others like this", names[0], names[1], names.length - 2); } } } // ... import java.util.Arrays; import java.util.List; class Solution { public static String whoLikesIt(String... names) { //Do your magic here StringBuilder output = new StringBuilder(); List<String> values = Arrays.asList(names); if (values.isEmpty()) { output.append("no one likes this"); } else if (values.size() == 1) { output.append(values.get(0)) .append(" likes this"); } else if (values.size() == 2) { output.append(values.get(0)) .append(" and ") .append(values.get(1)) .append(" like this"); } else if (values.size() == 3) { output.append(values.get(0)) .append(", ") .append(values.get(1)) .append(" and ") .append(values.get(2)) .append(" like this"); } else { output.append(values.get(0)) .append(", ") .append(values.get(1)) .append(" and ") .append(values.size() - 2) .append(" others like this"); } return output.toString(); } }
32.881579
110
0.47619
2a069c0daca167b45e36817dde4c5063d282db3f
1,574
/* * Copyright 2018-2019 the Justify authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.leadpony.justify.cli; import javax.json.JsonString; import javax.json.JsonValue; import org.leadpony.justify.api.InstanceType; import org.leadpony.justify.api.Localizable; import org.leadpony.justify.spi.FormatAttribute; /** * A custom format attribute representing resource locations. * * @author leadpony */ public class PathOrUrlFormatAttribute implements FormatAttribute { @Override public String name() { return "pathOrUrl"; } @Override public Localizable localizedName() { return locale -> Message.PATH_OR_URL.toString(); } @Override public InstanceType valueType() { return InstanceType.STRING; } @Override public boolean test(JsonValue value) { String string = ((JsonString) value).getString(); try { Location.at(string); return true; } catch (IllegalArgumentException e) { return false; } } }
27.137931
75
0.692503
d5082b5a871c4e963d1748ea3ae44ba2a0c3ff4c
6,088
/* * 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.guacamole.protocol; import org.junit.Assert; import org.junit.Test; /** * Unit test for GuacamoleProtocolVersion. Verifies that Guacamole protocol * version string parsing works as required. */ public class GuacamoleProtocolVersionTest { /** * Verifies that valid version strings are parsed successfully. */ @Test public void testValidVersionParse() { GuacamoleProtocolVersion version = GuacamoleProtocolVersion.parseVersion("VERSION_012_102_398"); Assert.assertNotNull(version); Assert.assertEquals(12, version.getMajor()); Assert.assertEquals(102, version.getMinor()); Assert.assertEquals(398, version.getPatch()); } /** * Verifies that invalid version strings fail to parse. */ @Test public void testInvalidVersionParse() { Assert.assertNull(GuacamoleProtocolVersion.parseVersion("potato")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION___")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION__2_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1__3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1_2_")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_A_2_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1_B_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1_2_C")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("_1_2_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("version_1_2_3")); } /** * Verifies that the atLeast() function defined by GuacamoleProtocolVersion * behaves as required for a series of three versions which are in strictly * increasing order (a &lt; b &lt; c). * * @param a * The String representation of the version which is known to be the * smaller than versions b and c. * * @param b * The String representation of the version which is known to be * larger than version a but smaller than version c. * * @param c * The String representation of the version which is known to be the * larger than versions a and b. */ private void testVersionCompare(String a, String b, String c) { GuacamoleProtocolVersion verA = GuacamoleProtocolVersion.parseVersion(a); GuacamoleProtocolVersion verB = GuacamoleProtocolVersion.parseVersion(b); GuacamoleProtocolVersion verC = GuacamoleProtocolVersion.parseVersion(c); Assert.assertTrue(verC.atLeast(verB)); Assert.assertTrue(verC.atLeast(verA)); Assert.assertTrue(verB.atLeast(verA)); Assert.assertFalse(verB.atLeast(verC)); Assert.assertFalse(verA.atLeast(verC)); Assert.assertFalse(verA.atLeast(verB)); Assert.assertTrue(verA.atLeast(verA)); Assert.assertTrue(verB.atLeast(verB)); Assert.assertTrue(verC.atLeast(verC)); } /** * Verifies that version order comparisons using atLeast() behave as * required. */ @Test public void testVersionCompare() { testVersionCompare("VERSION_0_0_1", "VERSION_0_0_2", "VERSION_0_0_3"); testVersionCompare("VERSION_0_1_0", "VERSION_0_2_0", "VERSION_0_3_0"); testVersionCompare("VERSION_1_0_0", "VERSION_2_0_0", "VERSION_3_0_0"); testVersionCompare("VERSION_1_2_3", "VERSION_1_3_3", "VERSION_2_0_0"); } /** * Verifies that versions can be tested for equality using equals(). */ @Test public void testVersionEquals() { GuacamoleProtocolVersion version; version = GuacamoleProtocolVersion.parseVersion("VERSION_012_102_398"); Assert.assertTrue(version.equals(version)); Assert.assertTrue(version.equals(new GuacamoleProtocolVersion(12, 102, 398))); Assert.assertFalse(version.equals(new GuacamoleProtocolVersion(12, 102, 399))); Assert.assertFalse(version.equals(new GuacamoleProtocolVersion(12, 103, 398))); Assert.assertFalse(version.equals(new GuacamoleProtocolVersion(11, 102, 398))); version = GuacamoleProtocolVersion.parseVersion("VERSION_1_0_0"); Assert.assertTrue(version.equals(GuacamoleProtocolVersion.VERSION_1_0_0)); Assert.assertFalse(version.equals(GuacamoleProtocolVersion.VERSION_1_1_0)); version = GuacamoleProtocolVersion.parseVersion("VERSION_1_1_0"); Assert.assertTrue(version.equals(GuacamoleProtocolVersion.VERSION_1_1_0)); Assert.assertFalse(version.equals(GuacamoleProtocolVersion.VERSION_1_0_0)); } /** * Verifies that versions can be converted to their Guacamole protocol * representation through calling toString(). */ @Test public void testToString() { Assert.assertEquals("VERSION_1_0_0", GuacamoleProtocolVersion.VERSION_1_0_0.toString()); Assert.assertEquals("VERSION_1_1_0", GuacamoleProtocolVersion.VERSION_1_1_0.toString()); Assert.assertEquals("VERSION_12_103_398", new GuacamoleProtocolVersion(12, 103, 398).toString()); } }
40.052632
105
0.715013
d2821a24f1c0c8994a879aa6f0aa79a14a4d2c88
1,009
package com.example.frameanimation; import androidx.appcompat.app.AppCompatActivity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.view.View; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView=findViewById(R.id.frame_image); final AnimationDrawable drawable= (AnimationDrawable) imageView.getBackground(); findViewById(R.id.start).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawable.start(); } }); findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawable.stop(); } }); } }
30.575758
88
0.666006
2561306ef0510c3b0dab657158b8fa5cad41dab6
691
package com.github.blutorange.log4jcat; import java.io.IOException; /** * The interface for reading the data of the log file to be trimmed. * As the algorithm uses a binary search, it must support random access. * Implementation are responsible for the encoding. * @author madgaksha */ abstract class ARandomAccessInput implements IRandomAccessInput { @Override public boolean isEof() throws IOException { return tell() >= length(); } @Override public String readLines() throws IOException { if (isEof()) return null; final StringBuilder sb = new StringBuilder((int)(length()-tell())); do { sb.append(readLine()); } while (!isEof()); return sb.toString(); } }
25.592593
72
0.7178
928e006f182bf980f5369cdcedc1327f5a457134
232
package org.springframework.aop.aspectj.annotation; public class NotLockable { private int intValue; public int getIntValue() { return intValue; } public void setIntValue(int intValue) { this.intValue = intValue; } }
14.5
51
0.737069
831bafe9eabc847dc86ecddfd7f7f60f0be48cc7
2,878
package org.dotwebstack.framework.service.openapi.param; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toList; import static org.dotwebstack.framework.core.helpers.ExceptionHelper.illegalArgumentException; import static org.dotwebstack.framework.service.openapi.exception.OpenApiExceptionHelper.parameterValidationException; import com.google.common.collect.ImmutableList; import io.swagger.v3.oas.models.media.Schema; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import lombok.NonNull; public class ParamValueCaster { public static final String NUMBER_TYPE = "number"; public static final String INTEGER_TYPE = "integer"; private ParamValueCaster() {} public static Object cast(String value, @NonNull Schema<?> schema) { if (value == null) { return null; } if ("string".equals(schema.getType())) { return value; } try { switch (schema.getType()) { case NUMBER_TYPE: return castNumber(value, schema.getFormat()); case INTEGER_TYPE: return castInteger(value, schema.getFormat()); case "boolean": return Boolean.parseBoolean(value); default: throw illegalArgumentException("Could not cast scalar value [{}] with schema type [{}] and format [{}]", value, schema.getType(), schema.getFormat()); } } catch (NumberFormatException e) { throw parameterValidationException("Could not cast scalar value [{}] with schema type [{}] and format {}", value, schema.getType(), schema.getFormat(), e); } } public static ImmutableList<Object> castList(@NonNull List<String> list, @NonNull Schema<?> schema) { return list.stream() .map(i -> cast(i, schema)) .collect(collectingAndThen(toList(), ImmutableList::copyOf)); } public static ImmutableList<Object> castArray(@NonNull String[] array, @NonNull Schema<?> schema) { return castList(Arrays.asList(array), schema); } private static Object castNumber(String value, String format) { if ("float".equals(format)) { return Float.parseFloat(value); } else if ("double".equals(format)) { return Double.parseDouble(value); } else if (format == null) { return new BigDecimal(value); } else { throw illegalArgumentException("Unsupported format [{}] for number type", format); } } private static Object castInteger(String value, String format) { if ("int64".equals(format)) { return Long.parseLong(value); } else if ("int32".equals(format)) { return Integer.parseInt(value); } else if (format == null) { return new BigInteger(value); } else { throw illegalArgumentException("Unsupported format [{}] for integer type", format); } } }
34.674699
119
0.684851
6c26147565f3055069846e015885df15feb13608
2,188
package ru.job4j.control; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * *@author Andrey Bukhtoyarov (andreymedoed@gmail.com). *@version %Id%. *@since 0.1. */ public class ContainsWordTest { @Test public void whenCocaColaAndColaThenTrue() { ContainsWord contWord = new ContainsWord(); String firstWord = "coca-cola"; String secondWord = "cola"; boolean result = contWord.contains(firstWord, secondWord); boolean expected = true; assertThat( result, is(expected) ); } @Test public void whenSunglassesAndColaThenFalse() { ContainsWord contWord = new ContainsWord(); String firstWord = "sunglasses"; String secondWord = "cola"; boolean result = contWord.contains(firstWord, secondWord); boolean expected = false; assertThat( result, is(expected) ); } @Test public void whenSunglassesAndSunThenTrue() { ContainsWord contWord = new ContainsWord(); String firstWord = "sunglasses"; String secondWord = "sun"; boolean result = contWord.contains(firstWord, secondWord); boolean expected = true; assertThat( result, is(expected) ); } @Test public void whenCocaColaAndCaCoThenTrue() { ContainsWord contWord = new ContainsWord(); String firstWord = "coca-cola"; String secondWord = "ca-co"; boolean result = contWord.contains(firstWord, secondWord); boolean expected = true; assertThat( result, is(expected) ); } @Test public void whenCocaColaAndBiggerWordThenFalse() { ContainsWord contWord = new ContainsWord(); String firstWord = "coca-cola"; String secondWord = "Panathinaikos"; boolean result = contWord.contains(firstWord, secondWord); boolean expected = false; assertThat( result, is(expected) ); } }
23.031579
66
0.583638
1b2475b4e7ffd80e5611ad2a60cd6ef9c60c93ee
3,447
/* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.neural.networks.training; import java.io.File; import junit.framework.Assert; import junit.framework.TestCase; import org.encog.Encog; import org.encog.ml.CalculateScore; import org.encog.ml.data.MLDataSet; import org.encog.ml.data.basic.BasicMLData; import org.encog.ml.data.basic.BasicMLDataPair; import org.encog.ml.data.basic.BasicMLDataSet; import org.encog.ml.data.buffer.BufferedMLDataSet; import org.encog.ml.ea.train.EvolutionaryAlgorithm; import org.encog.neural.neat.NEATNetwork; import org.encog.neural.neat.NEATPopulation; import org.encog.neural.neat.NEATUtil; import org.encog.neural.networks.XOR; import org.encog.util.TempDir; import org.encog.util.simple.EncogUtility; public class TestNEAT extends TestCase { public final TempDir TEMP_DIR = new TempDir(); public final File EGB_FILENAME = TEMP_DIR.createFile("encogtest.egb"); public void testNEATBuffered() { BufferedMLDataSet buffer = new BufferedMLDataSet(EGB_FILENAME); buffer.beginLoad(2, 1); for(int i=0;i<XOR.XOR_INPUT.length;i++) { buffer.add(new BasicMLDataPair( new BasicMLData(XOR.XOR_INPUT[i]), new BasicMLData(XOR.XOR_IDEAL[i]))); } buffer.endLoad(); NEATPopulation pop = new NEATPopulation(2,1,1000); pop.setInitialConnectionDensity(1.0);// not required, but speeds training pop.reset(); CalculateScore score = new TrainingSetScore(buffer); // train the neural network final EvolutionaryAlgorithm train = NEATUtil.constructNEATTrainer(pop,score); do { train.iteration(); } while(train.getError() > 0.01 && train.getIteration()<10000); Encog.getInstance().shutdown(); NEATNetwork network = (NEATNetwork)train.getCODEC().decode(train.getBestGenome()); Assert.assertTrue(train.getError()<0.01); Assert.assertTrue(network.calculateError(buffer)<0.01); } public void testNEAT() { MLDataSet trainingSet = new BasicMLDataSet(XOR.XOR_INPUT, XOR.XOR_IDEAL); NEATPopulation pop = new NEATPopulation(2,1,1000); pop.setInitialConnectionDensity(1.0);// not required, but speeds training pop.reset(); CalculateScore score = new TrainingSetScore(trainingSet); // train the neural network final EvolutionaryAlgorithm train = NEATUtil.constructNEATTrainer(pop,score); do { train.iteration(); } while(train.getError() > 0.01); // test the neural network Encog.getInstance().shutdown(); Assert.assertTrue(train.getError()<0.01); NEATNetwork network = (NEATNetwork)train.getCODEC().decode(train.getBestGenome()); Assert.assertTrue(network.calculateError(trainingSet)<0.01); } }
34.128713
84
0.751668
0446f016d1a5e281a10d053c5586486b17678d5b
5,687
/* * Copyright (C) 2010-2014 The MPDroid 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 com.audiokernel.euphonyrmt.cover; import com.audiokernel.euphonyrmt.MPDApplication; import com.audiokernel.euphonyrmt.helpers.AlbumInfo; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import java.util.ArrayList; import java.util.List; import static android.text.TextUtils.isEmpty; public class LocalCover implements ICoverRetriever { public static final String RETRIEVER_NAME = "User's HTTP Server"; private static final String[] EXT = { // "jpg", "png", "jpeg", --ZV -- irrelevant when server is smart "jpg" }; private static final String PLACEHOLDER_FILENAME = "%placeholder_filename"; // Note that having two PLACEHOLDER_FILENAME is on purpose private static final String[] FILENAMES = { "%placeholder_custom" // , PLACEHOLDER_FILENAME, "cover", "folder", "front", "Cover", "Folder", "Front" -- ZV -- irrelevant because Loon server is smart }; private static final String[] SUB_FOLDERS = { "" // "", "artwork", "Covers" -- ZV -- irrelevant when server is smart }; // private final static String URL = "%s/%s/%s"; private static final String URL_PREFIX = "http://"; private final MPDApplication mApp = MPDApplication.getInstance(); private final SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(mApp); public static void appendPathString(final Uri.Builder builder, final String baseString) { if (baseString != null && !baseString.isEmpty()) { final String[] components = baseString.split("/"); for (final String component : components) { builder.appendPath(component); } } } public static String buildCoverUrl(String serverName, String musicPath, final String path, final String fileName) { if (musicPath.startsWith(URL_PREFIX)) { int hostPortEnd = musicPath.indexOf(URL_PREFIX.length(), '/'); if (hostPortEnd == -1) { hostPortEnd = musicPath.length(); } serverName = musicPath.substring(URL_PREFIX.length(), hostPortEnd); musicPath = musicPath.substring(hostPortEnd); } final Uri.Builder uriBuilder = Uri.parse(URL_PREFIX + serverName).buildUpon(); appendPathString(uriBuilder, musicPath); appendPathString(uriBuilder, path); appendPathString(uriBuilder, fileName); final Uri uri = uriBuilder.build(); return uri.toString(); } @Override public String[] getCoverUrl(final AlbumInfo albumInfo) throws Exception { if (isEmpty(albumInfo.getPath())) { return new String[0]; } String lfilename; // load URL parts from settings final String musicPath = mSettings.getString("musicPath", "music/"); FILENAMES[0] = mSettings.getString("coverFileName", null); if (musicPath != null) { // load server name/ip final String serverName = mApp.oMPDAsyncHelper.getConnectionSettings().server; String url; final List<String> urls = new ArrayList<>(); for (final String subfolder : SUB_FOLDERS) { for (String baseFilename : FILENAMES) { for (final String ext : EXT) { if (baseFilename == null || (baseFilename.startsWith("%") && !baseFilename .equals(PLACEHOLDER_FILENAME))) { continue; } if (baseFilename.equals(PLACEHOLDER_FILENAME) && albumInfo.getFilename() != null) { final int dotIndex = albumInfo.getFilename().lastIndexOf('.'); if (dotIndex == -1) { continue; } baseFilename = albumInfo.getFilename().substring(0, dotIndex); } // Add file extension except for the filename coming // from settings if (!baseFilename.equals(FILENAMES[0])) { lfilename = subfolder + '/' + baseFilename + '.' + ext; } else { lfilename = baseFilename; } url = buildCoverUrl(serverName, musicPath, albumInfo.getPath(), lfilename); if (!urls.contains(url)) { urls.add(url); } } } } return urls.toArray(new String[urls.size()]); } else { return null; } } @Override public String getName() { return RETRIEVER_NAME; } @Override public boolean isCoverLocal() { return false; } }
35.767296
142
0.575347
707d7ce848760803e6137b851f7693dc8028a867
19,328
/* * Copyright 2017-2022 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.iot.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateFleetMetricRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the fleet metric to update. * </p> */ private String metricName; /** * <p> * The search query string. * </p> */ private String queryString; /** * <p> * The type of the aggregation query. * </p> */ private AggregationType aggregationType; /** * <p> * The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple of 60. * </p> */ private Integer period; /** * <p> * The field to aggregate. * </p> */ private String aggregationField; /** * <p> * The description of the fleet metric. * </p> */ private String description; /** * <p> * The version of the query. * </p> */ private String queryVersion; /** * <p> * The name of the index to search. * </p> */ private String indexName; /** * <p> * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW metric</a>. * </p> */ private String unit; /** * <p> * The expected version of the fleet metric record in the registry. * </p> */ private Long expectedVersion; /** * <p> * The name of the fleet metric to update. * </p> * * @param metricName * The name of the fleet metric to update. */ public void setMetricName(String metricName) { this.metricName = metricName; } /** * <p> * The name of the fleet metric to update. * </p> * * @return The name of the fleet metric to update. */ public String getMetricName() { return this.metricName; } /** * <p> * The name of the fleet metric to update. * </p> * * @param metricName * The name of the fleet metric to update. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withMetricName(String metricName) { setMetricName(metricName); return this; } /** * <p> * The search query string. * </p> * * @param queryString * The search query string. */ public void setQueryString(String queryString) { this.queryString = queryString; } /** * <p> * The search query string. * </p> * * @return The search query string. */ public String getQueryString() { return this.queryString; } /** * <p> * The search query string. * </p> * * @param queryString * The search query string. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withQueryString(String queryString) { setQueryString(queryString); return this; } /** * <p> * The type of the aggregation query. * </p> * * @param aggregationType * The type of the aggregation query. */ public void setAggregationType(AggregationType aggregationType) { this.aggregationType = aggregationType; } /** * <p> * The type of the aggregation query. * </p> * * @return The type of the aggregation query. */ public AggregationType getAggregationType() { return this.aggregationType; } /** * <p> * The type of the aggregation query. * </p> * * @param aggregationType * The type of the aggregation query. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withAggregationType(AggregationType aggregationType) { setAggregationType(aggregationType); return this; } /** * <p> * The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple of 60. * </p> * * @param period * The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple * of 60. */ public void setPeriod(Integer period) { this.period = period; } /** * <p> * The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple of 60. * </p> * * @return The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple * of 60. */ public Integer getPeriod() { return this.period; } /** * <p> * The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple of 60. * </p> * * @param period * The time in seconds between fleet metric emissions. Range [60(1 min), 86400(1 day)] and must be multiple * of 60. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withPeriod(Integer period) { setPeriod(period); return this; } /** * <p> * The field to aggregate. * </p> * * @param aggregationField * The field to aggregate. */ public void setAggregationField(String aggregationField) { this.aggregationField = aggregationField; } /** * <p> * The field to aggregate. * </p> * * @return The field to aggregate. */ public String getAggregationField() { return this.aggregationField; } /** * <p> * The field to aggregate. * </p> * * @param aggregationField * The field to aggregate. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withAggregationField(String aggregationField) { setAggregationField(aggregationField); return this; } /** * <p> * The description of the fleet metric. * </p> * * @param description * The description of the fleet metric. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of the fleet metric. * </p> * * @return The description of the fleet metric. */ public String getDescription() { return this.description; } /** * <p> * The description of the fleet metric. * </p> * * @param description * The description of the fleet metric. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * The version of the query. * </p> * * @param queryVersion * The version of the query. */ public void setQueryVersion(String queryVersion) { this.queryVersion = queryVersion; } /** * <p> * The version of the query. * </p> * * @return The version of the query. */ public String getQueryVersion() { return this.queryVersion; } /** * <p> * The version of the query. * </p> * * @param queryVersion * The version of the query. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withQueryVersion(String queryVersion) { setQueryVersion(queryVersion); return this; } /** * <p> * The name of the index to search. * </p> * * @param indexName * The name of the index to search. */ public void setIndexName(String indexName) { this.indexName = indexName; } /** * <p> * The name of the index to search. * </p> * * @return The name of the index to search. */ public String getIndexName() { return this.indexName; } /** * <p> * The name of the index to search. * </p> * * @param indexName * The name of the index to search. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withIndexName(String indexName) { setIndexName(indexName); return this; } /** * <p> * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW metric</a>. * </p> * * @param unit * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW * metric</a>. * @see FleetMetricUnit */ public void setUnit(String unit) { this.unit = unit; } /** * <p> * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW metric</a>. * </p> * * @return Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW * metric</a>. * @see FleetMetricUnit */ public String getUnit() { return this.unit; } /** * <p> * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW metric</a>. * </p> * * @param unit * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW * metric</a>. * @return Returns a reference to this object so that method calls can be chained together. * @see FleetMetricUnit */ public UpdateFleetMetricRequest withUnit(String unit) { setUnit(unit); return this; } /** * <p> * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW metric</a>. * </p> * * @param unit * Used to support unit transformation such as milliseconds to seconds. The unit must be supported by <a * href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html">CW * metric</a>. * @return Returns a reference to this object so that method calls can be chained together. * @see FleetMetricUnit */ public UpdateFleetMetricRequest withUnit(FleetMetricUnit unit) { this.unit = unit.toString(); return this; } /** * <p> * The expected version of the fleet metric record in the registry. * </p> * * @param expectedVersion * The expected version of the fleet metric record in the registry. */ public void setExpectedVersion(Long expectedVersion) { this.expectedVersion = expectedVersion; } /** * <p> * The expected version of the fleet metric record in the registry. * </p> * * @return The expected version of the fleet metric record in the registry. */ public Long getExpectedVersion() { return this.expectedVersion; } /** * <p> * The expected version of the fleet metric record in the registry. * </p> * * @param expectedVersion * The expected version of the fleet metric record in the registry. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFleetMetricRequest withExpectedVersion(Long expectedVersion) { setExpectedVersion(expectedVersion); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMetricName() != null) sb.append("MetricName: ").append(getMetricName()).append(","); if (getQueryString() != null) sb.append("QueryString: ").append(getQueryString()).append(","); if (getAggregationType() != null) sb.append("AggregationType: ").append(getAggregationType()).append(","); if (getPeriod() != null) sb.append("Period: ").append(getPeriod()).append(","); if (getAggregationField() != null) sb.append("AggregationField: ").append(getAggregationField()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getQueryVersion() != null) sb.append("QueryVersion: ").append(getQueryVersion()).append(","); if (getIndexName() != null) sb.append("IndexName: ").append(getIndexName()).append(","); if (getUnit() != null) sb.append("Unit: ").append(getUnit()).append(","); if (getExpectedVersion() != null) sb.append("ExpectedVersion: ").append(getExpectedVersion()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateFleetMetricRequest == false) return false; UpdateFleetMetricRequest other = (UpdateFleetMetricRequest) obj; if (other.getMetricName() == null ^ this.getMetricName() == null) return false; if (other.getMetricName() != null && other.getMetricName().equals(this.getMetricName()) == false) return false; if (other.getQueryString() == null ^ this.getQueryString() == null) return false; if (other.getQueryString() != null && other.getQueryString().equals(this.getQueryString()) == false) return false; if (other.getAggregationType() == null ^ this.getAggregationType() == null) return false; if (other.getAggregationType() != null && other.getAggregationType().equals(this.getAggregationType()) == false) return false; if (other.getPeriod() == null ^ this.getPeriod() == null) return false; if (other.getPeriod() != null && other.getPeriod().equals(this.getPeriod()) == false) return false; if (other.getAggregationField() == null ^ this.getAggregationField() == null) return false; if (other.getAggregationField() != null && other.getAggregationField().equals(this.getAggregationField()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getQueryVersion() == null ^ this.getQueryVersion() == null) return false; if (other.getQueryVersion() != null && other.getQueryVersion().equals(this.getQueryVersion()) == false) return false; if (other.getIndexName() == null ^ this.getIndexName() == null) return false; if (other.getIndexName() != null && other.getIndexName().equals(this.getIndexName()) == false) return false; if (other.getUnit() == null ^ this.getUnit() == null) return false; if (other.getUnit() != null && other.getUnit().equals(this.getUnit()) == false) return false; if (other.getExpectedVersion() == null ^ this.getExpectedVersion() == null) return false; if (other.getExpectedVersion() != null && other.getExpectedVersion().equals(this.getExpectedVersion()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMetricName() == null) ? 0 : getMetricName().hashCode()); hashCode = prime * hashCode + ((getQueryString() == null) ? 0 : getQueryString().hashCode()); hashCode = prime * hashCode + ((getAggregationType() == null) ? 0 : getAggregationType().hashCode()); hashCode = prime * hashCode + ((getPeriod() == null) ? 0 : getPeriod().hashCode()); hashCode = prime * hashCode + ((getAggregationField() == null) ? 0 : getAggregationField().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getQueryVersion() == null) ? 0 : getQueryVersion().hashCode()); hashCode = prime * hashCode + ((getIndexName() == null) ? 0 : getIndexName().hashCode()); hashCode = prime * hashCode + ((getUnit() == null) ? 0 : getUnit().hashCode()); hashCode = prime * hashCode + ((getExpectedVersion() == null) ? 0 : getExpectedVersion().hashCode()); return hashCode; } @Override public UpdateFleetMetricRequest clone() { return (UpdateFleetMetricRequest) super.clone(); } }
30.582278
123
0.595664
31cff004ac3c5a31d891f3a1ee96e12b74669407
3,634
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos.implementation.directconnectivity; import com.azure.cosmos.CosmosClientException; import com.azure.cosmos.GoneException; import com.azure.cosmos.implementation.Configs; import com.azure.cosmos.implementation.FailureValidator; import com.azure.cosmos.implementation.IAuthorizationTokenProvider; import com.azure.cosmos.implementation.OperationType; import com.azure.cosmos.implementation.ResourceType; import com.azure.cosmos.implementation.RxDocumentServiceRequest; import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; import org.mockito.Matchers; import org.mockito.Mockito; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import reactor.core.Exceptions; import reactor.core.publisher.Mono; import java.util.concurrent.TimeUnit; public class ReplicatedResourceClientTest { protected static final int TIMEOUT = 60000; private IAddressResolver addressResolver; private TransportClient transportClient; private boolean enableReadRequestsFallback; public boolean forceAddressRefresh; private GatewayServiceConfigurationReader serviceConfigReader; private IAuthorizationTokenProvider authorizationTokenProvider; @BeforeClass(groups = "unit") public void before_ReplicatedResourceClientTest() throws Exception { addressResolver = Mockito.mock(IAddressResolver.class); transportClient = Mockito.mock(TransportClient.class); serviceConfigReader = Mockito.mock(GatewayServiceConfigurationReader.class); authorizationTokenProvider = Mockito.mock(IAuthorizationTokenProvider.class); } /** * This test will verify that Gone exception will be retired * fixed number of time before throwing error. */ @Test(groups = { "unit" }, timeOut = TIMEOUT) public void invokeAsyncWithGoneException() { Configs configs = new Configs(); ReplicatedResourceClient resourceClient = new ReplicatedResourceClient(configs, new AddressSelector(addressResolver, Protocol.HTTPS), null, transportClient, serviceConfigReader, authorizationTokenProvider, enableReadRequestsFallback, false); FailureValidator validator = FailureValidator.builder().instanceOf(CosmosClientException.class).build(); RxDocumentServiceRequest request = Mockito.spy(RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document)); Mockito.when(addressResolver.resolveAsync(Matchers.any(), Matchers.anyBoolean())) .thenReturn(Mono.error(new GoneException())); Mono<StoreResponse> response = resourceClient.invokeAsync(request, null); validateFailure(response, validator, TIMEOUT); //method will fail 7 time (first try ,last try , and 5 retries within 30 sec(1,2,4,8,15 wait)) Mockito.verify(addressResolver, Mockito.times(7)).resolveAsync(Matchers.any(), Matchers.anyBoolean()); } public static void validateFailure(Mono<StoreResponse> single, FailureValidator validator, long timeout) { TestSubscriber<StoreResponse> testSubscriber = new TestSubscriber<>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); Assertions.assertThat(testSubscriber.errorCount()).isEqualTo(1); Throwable throwable = Exceptions.unwrap(testSubscriber.errors().get(0)); validator.validate(throwable); } }
48.453333
147
0.771326
a7fe1ea21f3ce2f7418bc9c969b182b344698cf4
8,435
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package com.finalist.tree; import java.io.PrintWriter; import java.io.Writer; import javax.swing.tree.TreeModel; /** * Class reponsible for rendering the HTML tree (+/-, lines, scripts etc.) * The HTML uses a number of gif's that are located using the ImgBaseUrl. * Gifs needed:<UL> * <LI>leaflast.gif</LI> * <LI>vertline-leaf.gif</LI> * <LI>minlast.gif</LI> * <LI>pluslast.gif</LI> * <LI>min.gif</LI> * <LI>plus.gif</LI> * <LI>vertline.gif</LI> * <LI>spacer.gif</LI> * </UL> * * @author Edwin van der Elst * Date :Sep 15, 2003 * */ public class HTMLTree { private TreeCellRenderer cellRenderer = new DefaultCellRenderer(); private String imgBaseUrl = "editors/img/"; public boolean expandAll = false; public String treeId = ""; public TreeModel model; public HTMLTree() { model = null; } public HTMLTree(TreeModel model) { this.model = model; } public HTMLTree(TreeModel model, String treeId) { this.model = model; this.treeId = treeId; } public String buildImgUrl(String image) { return getImgBaseUrl() + image; } /** * @return */ public TreeCellRenderer getCellRenderer() { return cellRenderer; } /** * Determine which image to show in the tree structure * @return complete URL * @param isLeaf - boolean, true if a node has no children (no + sign in front) * @param isLast - boolean, true if a node is the last child of it's parent */ public String getImage(boolean isLeaf, boolean isLast) { String img; if (isLeaf) { if (isLast) { img = buildImgUrl("leaflast.gif"); } else { img = buildImgUrl("vertline-leaf.gif"); } } else { if (isLast) { if (expandAll) { img = buildImgUrl("minlast.gif"); } else { img = buildImgUrl("pluslast.gif"); } } else { if (expandAll) { img = buildImgUrl("min.gif"); } else { img = buildImgUrl("plus.gif"); } } } return img; } /** * @return */ public String getImgBaseUrl() { return imgBaseUrl; } /** * @return */ public TreeModel getModel() { return model; } /** * @return */ public boolean isExpandAll() { return expandAll; } public void renderCookieScripts(PrintWriter pw) { pw.println("function saveCookie(name,value,days) {"); pw.println(" if (days) {"); pw.println(" var date = new Date();"); pw.println(" date.setTime(date.getTime()+(days*24*60*60*1000))"); pw.println(" var expires = '; expires='+date.toGMTString()"); pw.println(" } else expires = ''"); pw.println(" document.cookie = name+'='+value+expires+'; path=/'"); pw.println("}"); pw.println("function readCookie(name) {"); pw.println(" var nameEQ = name + '='"); pw.println(" var ca = document.cookie.split(';')"); pw.println(" for(var i=0;i<ca.length;i++) {"); pw.println(" var c = ca[i];"); pw.println(" while (c.charAt(0)==' ') c = c.substring(1,c.length)"); pw.println(" if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length)"); pw.println(" }"); pw.println(" return null"); pw.println("}"); pw.println("function deleteCookie(name) {"); pw.println(" saveCookie(name,'',-1)"); pw.println("}"); pw.println("function restoreTree() {"); pw.println(" for(var i=1; i<10; i++) {"); pw.println(" var lastclicknode = readCookie('lastnode" + treeId + "'+i);"); pw.println(" if(lastclicknode!=null) { clickNode(lastclicknode); }"); pw.println(" }"); pw.println("}"); } public void render(Writer out) { PrintWriter pw = new PrintWriter(out); pw.println("<script>"); renderCookieScripts(pw); pw.println("function clickNode(node) {"); pw.println(" var level = node.split('_').length;"); pw.println(" saveCookie('lastnode" + treeId + "'+level,node,1);"); pw.println(" el=document.getElementById(node);"); pw.println(" img = document.getElementById('img_'+node);"); pw.println(" if (el!=null && img != null) {"); pw.println(" if (el.style.display=='none') {"); pw.println(" el.style.display='inline';"); pw.println(" if (img.src.indexOf('last.gif')!=-1 ) {"); pw.println(" img.src='" + getImgBaseUrl() + "minlast.gif'; } else { "); pw.println(" img.src='" + getImgBaseUrl() + "min.gif'; }"); pw.println(" } else {"); pw.println(" el.style.display='none';"); pw.println(" if (img.src.indexOf('last.gif')!=-1) {"); pw.println(" img.src='" + getImgBaseUrl() + "pluslast.gif';"); pw.println(" } else { "); pw.println(" img.src='" + getImgBaseUrl() + "plus.gif';"); pw.println(" }"); pw.println(" }"); pw.println(" }"); pw.println("}"); pw.println("</script>"); renderNode(model.getRoot(), 0, pw, "node", "", getImage(false, true), true); pw.flush(); } private void renderNode(Object node, int level, PrintWriter out, String base, String preHtml, String myImg, boolean isLast) { String nodeName = base + "_" + level; if (!model.isLeaf(node)) { out.print("<a href='javascript:clickNode(\"" + nodeName + "\")'>"); out.print("<img src='" + myImg + "' border='0' align='center' valign='middle' id='img_" + nodeName + "'/>"); out.print("</a>&nbsp;"); } else { out.print("<img src='" + myImg + "' border='0' align='center' valign='middle'/>&nbsp;"); } String icon = getCellRenderer().getIcon(node); if (icon != null) { out.print("<img src='"+buildImgUrl(icon)+"' border='0' align='center' valign='middle'/> "); } getCellRenderer().render(node, out); out.println("</nobr><br/>"); if (!model.isLeaf(node)) { String style = expandAll ? "block" : "none"; out.println("<div id='" + nodeName + "' style='display: " + style + "'>"); if(level==0) { // will be closed before <br/> (in the above statement) preHtml += "<nobr>"; } // Render childs ..... if (isLast) { preHtml += "<img src='" + buildImgUrl("spacer.gif") + "' align='center' valign='middle' border='0'/>"; } else { preHtml += "<img src='" + buildImgUrl("vertline.gif") + "' align='center' valign='middle' border='0'/>"; } int count = model.getChildCount(node); for (int i = 0; i < count; i++) { Object child = model.getChild(node, i); out.print(preHtml); String img = getImage(model.isLeaf(child), (i == count - 1)); renderNode(child, level + 1, out, base + "_" + i, preHtml, img, (i == count - 1)); } out.println("</div>\n"); } } /** * @param cellRenderer */ public void setCellRenderer(TreeCellRenderer cellRenderer) { this.cellRenderer = cellRenderer; } /** * @param expandAll */ public void setExpandAll(boolean expandAll) { this.expandAll = expandAll; } /** * @param imgBaseUrl */ public void setImgBaseUrl(String imgBaseUrl) { this.imgBaseUrl = imgBaseUrl; } /** * @param model */ public void setModel(TreeModel model) { this.model = model; } }
32.194656
128
0.555661
e9655f7998cb0e9671963f7803906aa1fd56f73a
1,571
package model; import javax.swing.JOptionPane; import org.openqa.selenium.WebDriver; import controler.Navegador; import view.TelaPrincipal; public class DocumentoU extends Navegador { public static WebDriver paginaDocUaberta; public static void inicioDocU() { try { WebDriver paginaDocU = abrirNavegador("https://sei.trf5.jus.br/sei/"); criarDiretorio(); paginaDocUaberta = paginaDocU; tirarPrint(paginaDocU, "USUARIO_INTERNO"); segundaTela(paginaDocUaberta); } catch (Exception e) { e.printStackTrace(); int tn = JOptionPane.showConfirmDialog(null, "Falha ao tirar print! USUARIO_INTERNO - Deseja tentar novamente?"); TelaPrincipal.frame.setVisible(false); if (tn == 1) { segundaTela(paginaDocUaberta); }else if(tn == 2) { fecharNavegador(); TelaPrincipal.frame.setVisible(true); }else { fecharNavegador(); inicioDocU(); } } } public static void segundaTela(WebDriver paginaDocU) { try { paginaDocU.get("https://sei.trf5.jus.br/sei/controlador_externo.php?acao=usuario_externo_logar&id_orgao_acesso_externo=0"); tirarPrint(paginaDocU, "USUARIO_EXTERNO"); fecharNavegador(); }catch(Exception e) { e.printStackTrace(); int tn = JOptionPane.showConfirmDialog(null, "Falha ao tirar print! USUARIO_INTERNO - Deseja tentar novamente?"); TelaPrincipal.frame.setVisible(false); if (tn == 1 || tn == 2) { fecharNavegador(); TelaPrincipal.frame.setVisible(true); }else { segundaTela(paginaDocUaberta); } } } }
29.641509
127
0.693826
dccd2ef4834d4c5900c493efce28b8a07e4bea8b
3,044
/* FeatureIDE - A Framework for Feature-Oriented Software Development * Copyright (C) 2005-2013 FeatureIDE team, University of Magdeburg, Germany * * This file is part of FeatureIDE. * * FeatureIDE 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. * * FeatureIDE 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 FeatureIDE. If not, see <http://www.gnu.org/licenses/>. * * See http://www.fosd.de/featureide/ for further information. */ package de.ovgu.featureide.ui.views.collaboration.figures; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.GridLayout; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import de.ovgu.featureide.ui.views.collaboration.GUIDefaults; import de.ovgu.featureide.ui.views.collaboration.model.Collaboration; /** * An instance of this class represents the graphical representation of the * Collaboration. * * @author Constanze Adler */ public class CollaborationFigure extends Figure implements GUIDefaults{ private final Label label = new Label(); public boolean selected = true; public boolean isConfiguration = false; public CollaborationFigure(Collaboration coll) { super(); selected = coll.selected; isConfiguration = coll.isConfiguration; GridLayout gridLayout = new GridLayout(1, true); gridLayout.verticalSpacing = GRIDLAYOUT_VERTICAL_SPACING; gridLayout.marginHeight = GRIDLAYOUT_MARGIN_HEIGHT - 1; this.setLayoutManager(gridLayout); this.setBackgroundColor(ROLE_BACKGROUND); if (selected) { this.setBorder(COLL_BORDER_SELECTED); } else { this.setBorder(COLL_BORDER_UNSELECTED); } if (isConfiguration) if (selected) label.setIcon(IMAGE_CURRENT_CONFIGURATION); else label.setIcon(IMAGE_CONFIGURATION); label.setFont(DEFAULT_FONT); label.setLocation(new Point(COLLABORATION_INSETS.left, COLLABORATION_INSETS.top)); this.setName(coll.getName()); this.add(label); this.setOpaque(true); } private void setName(String name){ label.setText(name); Dimension labelSize = label.getPreferredSize(); if (labelSize.equals(label.getSize())) return; label.setSize(labelSize); Rectangle bounds = getBounds(); int w = COLLABORATION_INSETS.getWidth(); int h = COLLABORATION_INSETS.getHeight(); bounds.setSize(labelSize.expand(w, h)); Dimension oldSize = getSize(); if (!oldSize.equals(0, 0)) { int dx = (oldSize.width - bounds.width) / 2; bounds.x += dx; } setBounds(bounds); } }
31.381443
84
0.750986
a1669100ede87cd22819af7a8236ea40b2214cf8
1,302
/* * Copyright 2016 Code Above Lab LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codeabovelab.dm.cluman.job; import lombok.Data; /** * Criteria for event subscription */ @Data public final class JobEventCriteriaImpl implements JobEventCriteria { private final String id; private final String type; public static boolean matcher(JobEventCriteria pattern, JobEventCriteria event) { if(pattern == null) { return true; } String patternId = pattern.getId(); String patternType = pattern.getType(); boolean matchId = patternId == null || patternId.equals(event.getId()); boolean matchType = patternType == null || patternType.equals(event.getType()); return matchId && matchType; } }
31.756098
87
0.701997
8fd33dd1220f3b6cd9c3e5d76bd9d76662b86e15
11,943
package com.eolwral.osmonitor.ui; import java.io.File; import java.io.FileWriter; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.eolwral.osmonitor.R; import com.eolwral.osmonitor.core.logPriority; import com.eolwral.osmonitor.core.logcatInfo; import com.eolwral.osmonitor.core.logcatInfoList; import com.eolwral.osmonitor.ipc.IpcService; import com.eolwral.osmonitor.ipc.IpcService.ipcClientListener; import com.eolwral.osmonitor.ipc.ipcCategory; import com.eolwral.osmonitor.ipc.ipcData; import com.eolwral.osmonitor.ipc.ipcMessage; import com.eolwral.osmonitor.settings.Settings; import com.eolwral.osmonitor.util.UserInterfaceUtil; public class ProcessLogViewFragment extends DialogFragment implements ipcClientListener { // ipc client private static IpcService ipcService = IpcService.getInstance(); // set pid public final static String TARGETPID = "TargetPID"; public final static String TARGETNAME = "TargetName"; private int targetPID = 0; private String targetName = ""; // data private ArrayList<logcatInfo> viewLogcatData = new ArrayList<logcatInfo>(); private byte logType = ipcCategory.LOGCAT_MAIN_R; private MessageListAdapter messageList = null; private Settings settings = null; private TextView messageCount = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // settings settings = Settings.getInstance(getActivity().getApplicationContext()); // set list messageList = new MessageListAdapter(getActivity().getApplicationContext()); // get pid targetPID = getArguments().getInt(TARGETPID); targetName = getArguments().getString(TARGETNAME); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.ui_message_fragment, container, false); // set count messageCount = ((TextView) v.findViewById(R.id.id_message_count)); // set list ListView list = (ListView) v.findViewById(android.R.id.list); list.setAdapter(messageList); // set title getDialog().setTitle(targetName); Button exportButton = (Button) v.findViewById(R.id.id_message_exportbtn); exportButton.setVisibility(View.VISIBLE); exportButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Resources exportRes = getActivity().getResources(); final Calendar calendar = Calendar.getInstance(); final SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd-hh.mm.ss", Locale.getDefault()); Builder exportDialog = new AlertDialog.Builder(getActivity()); View exportView = LayoutInflater.from(getActivity()).inflate( R.layout.ui_message_export, null); TextView exportFile = (TextView) exportView .findViewById(R.id.id_export_filename); exportFile.setText("Log-" + formatter.format(calendar.getTime())); exportDialog.setView(exportView); exportDialog.setTitle(exportRes.getText(R.string.ui_menu_logexport)); exportDialog.setNegativeButton( exportRes.getText(R.string.ui_text_cancel), null); exportDialog.setPositiveButton( exportRes.getText(R.string.ui_text_okay), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String FileName = ((EditText) ((AlertDialog) dialog) .findViewById(R.id.id_export_filename)).getText() .toString(); exportLog(FileName); } }); exportDialog.create().show(); } }); return v; } private void exportLog(String fileName) { if (fileName.trim().equals("")) return; if (!fileName.contains(".csv")) fileName += ".csv"; try { File logFile = new File(Environment.getExternalStorageDirectory() .getPath() + "/" + fileName); if (logFile.exists()) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.ui_menu_logexport) .setMessage(R.string.ui_text_fileexist) .setPositiveButton(R.string.ui_text_okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).create().show(); return; } logFile.createNewFile(); int LogCount = viewLogcatData.size(); FileWriter logWriter = new FileWriter(logFile); final Calendar calendar = Calendar.getInstance(); for (int index = 0; index < LogCount; index++) { StringBuilder logLine = new StringBuilder(); calendar.setTimeInMillis(viewLogcatData.get(index).seconds() * 1000); logLine.append(DateFormat.format("yyyy-MM-dd hh:mm:ss", calendar.getTime()) + ","); switch (viewLogcatData.get(index).priority()) { case logPriority.SILENT: logLine.append("SILENT,"); break; case logPriority.UNKNOWN: logLine.append("UNKNOWN,"); break; case logPriority.DEFAULT: logLine.append("DEFAULT,"); break; case logPriority.VERBOSE: logLine.append("VERBOSE,"); break; case logPriority.WARN: logLine.append("WARNING,"); break; case logPriority.INFO: logLine.append("INFORMATION,"); break; case logPriority.FATAL: logLine.append("FATAL,"); break; case logPriority.ERROR: logLine.append("ERROR,"); break; case logPriority.DEBUG: logLine.append("DEBUG,"); break; } logLine.append(viewLogcatData.get(index).tag() + ","); logLine.append(viewLogcatData.get(index).message() + "\n"); logWriter.write(logLine.toString()); } logWriter.close(); } catch (Exception e) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.ui_menu_logexport) .setMessage(e.getMessage()) .setPositiveButton(R.string.ui_text_okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).create().show(); return; } new AlertDialog.Builder(getActivity()) .setTitle(R.string.ui_menu_logexport) .setMessage(R.string.ui_text_exportdone) .setPositiveButton(R.string.ui_text_okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).create().show(); return; } @Override public void onStart() { super.onStart(); ipcService.removeRequest(this); byte newCommand[] = { logType }; ipcService.addRequest(newCommand, 0, this); } @Override public void onStop() { super.onStop(); ipcService.removeRequest(this); } @Override public void onRecvData(byte [] result) { if (result == null) { byte newCommand[] = new byte[1]; newCommand[0] = logType; ipcService.addRequest(newCommand, settings.getInterval(), this); return; } // clean up viewLogcatData.clear(); // convert data ipcMessage ipcMessageResult = ipcMessage.getRootAsipcMessage(ByteBuffer.wrap(result)); for (int index = 0; index < ipcMessageResult.dataLength(); index++) { try { ipcData rawData = ipcMessageResult.data(index); logcatInfoList list = logcatInfoList.getRootAslogcatInfoList(rawData.payloadAsByteBuffer().asReadOnlyBuffer()); for (int count = 0; count < list.listLength(); count++) { logcatInfo lgInfo = list.list(count); // filter if (lgInfo.pid() != this.targetPID) continue; viewLogcatData.add(lgInfo); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // refresh messageList.refresh(); // send command again byte newCommand[] = new byte[1]; newCommand[0] = logType; ipcService.addRequest(newCommand, settings.getInterval(), this); } /** * implement viewholder class for connection list */ private class ViewHolder { // main information TextView time; TextView tag; TextView level; TextView msg; } private class MessageListAdapter extends BaseAdapter { private LayoutInflater itemInflater = null; private ViewHolder holder = null; public MessageListAdapter(Context mContext) { itemInflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return viewLogcatData.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View sv = null; // prepare view if (convertView == null) { sv = (View) itemInflater.inflate(R.layout.ui_message_item, parent, false); holder = new ViewHolder(); holder.time = ((TextView) sv.findViewById(R.id.id_message_time)); holder.level = ((TextView) sv.findViewById(R.id.id_message_level)); holder.tag = ((TextView) sv.findViewById(R.id.id_message_tag)); holder.msg = ((TextView) sv.findViewById(R.id.id_message_text)); sv.setTag(holder); } else { sv = (View) convertView; holder = (ViewHolder) sv.getTag(); } // draw current color for each item if (position % 2 == 0) sv.setBackgroundColor(getResources().getColor(R.color.dkgrey_osmonitor)); else sv.setBackgroundColor(getResources().getColor(R.color.black_osmonitor)); // get data logcatInfo item = viewLogcatData.get(position); final Calendar calendar = Calendar.getInstance(); final java.text.DateFormat convertTool = java.text.DateFormat .getDateTimeInstance(); calendar.setTimeInMillis(item.seconds() * 1000); holder.time.setText(convertTool.format(calendar.getTime())); holder.tag.setText(item.tag()); holder.msg.setText(item.message().toString()); holder.level.setTextColor(Color.BLACK); holder.level.setBackgroundColor(UserInterfaceUtil.getLogcatColor(item.priority())); holder.level.setText(UserInterfaceUtil.getLogcatTag(item.priority())); // avoid to trigger errors when refreshing sv.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); return sv; } public void refresh() { messageCount.setText(String.format("%,d", viewLogcatData.size())); notifyDataSetChanged(); } } }
30.159091
119
0.657875
e5a67e3491a9deedc2bb7931567d68e6ddfdc077
1,744
package autograderutils.results; import java.io.InputStream; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JUnitAutograderResultFromFile extends AutograderResult{ private int score, totalPoints; private String feedback; private String summary; private String testResults; public JUnitAutograderResultFromFile(InputStream resultFile) { try(Scanner scanner = new Scanner(resultFile)) { StringBuilder stringBuilder = new StringBuilder(); String line = null; int testResultStart = 0; while(scanner.hasNextLine()) { line = scanner.nextLine(); if(line.startsWith("----")) { feedback = stringBuilder.toString(); testResultStart = stringBuilder.length() + line.length() + 1; } stringBuilder.append(line) .append('\n'); // scanner strips line ending, add it back in. } summary = stringBuilder.toString(); testResults = stringBuilder.substring(testResultStart); } // Grab numbers from feedback; try { if(feedback != null) { Matcher matcher = Pattern.compile("\\d+").matcher(feedback); matcher.find(); score = Integer.parseInt(matcher.group()); matcher.find(); totalPoints = Integer.parseInt(matcher.group()); } } catch(Exception e) { // Swallow this exception so that the object is constructed. } } @Override public int getScore() { return score; } @Override public int getTotal() { return totalPoints; } @Override public String getFeedback() { return feedback; } @Override public String getSummary() { return summary; } @Override public String getTestResults() { return testResults; } @Override public int getNumberOfTests() { return 0; } }
21.8
68
0.696674
bccf2399facc70fc090278ce9e24b58649d5419a
178
package io.github.coolcrabs.testprogram; import org.junit.jupiter.api.Test; public class BruhTest { @Test void ugg() { TestProgram.main(new String[0]); } }
16.181818
40
0.662921
8a90bb0f915d702cd91cdabe51e229acd34371ee
4,276
package gov.dot.its.datahub.adminapi.business; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.elasticsearch.ElasticsearchStatusException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import gov.dot.its.datahub.adminapi.dao.DataAssetsDao; import gov.dot.its.datahub.adminapi.model.ApiError; import gov.dot.its.datahub.adminapi.model.ApiMessage; import gov.dot.its.datahub.adminapi.model.ApiResponse; import gov.dot.its.datahub.adminapi.model.DataAsset; import gov.dot.its.datahub.adminapi.utils.ApiUtils; @Service public class DataAssetsServiceImpl implements DataAssetsService { private static final Logger logger = LoggerFactory.getLogger(ConfigurationServiceImpl.class); private static final String MESSAGE_TEMPLATE = "{} : {} "; @Autowired private DataAssetsDao dataAssetsDao; @Autowired private ApiUtils apiUtils; @Override public ApiResponse<List<DataAsset>> dataAssets(HttpServletRequest request) { logger.info("Request: Data Assets"); final String RESPONSE_MSG = "Response: GET Data Assets. "; ApiResponse<List<DataAsset>> apiResponse = new ApiResponse<>(); List<ApiError> errors = new ArrayList<>(); try { List<DataAsset> dataAssets = dataAssetsDao.getDataAssets(); if (!dataAssets.isEmpty()) { apiResponse.setResponse(HttpStatus.OK, dataAssets, null, null, request); logger.info(MESSAGE_TEMPLATE, RESPONSE_MSG,HttpStatus.OK.toString()+" "+dataAssets.size()); return apiResponse; } apiResponse.setResponse(HttpStatus.NO_CONTENT, null, null, null, request); logger.info(MESSAGE_TEMPLATE, RESPONSE_MSG, HttpStatus.NO_CONTENT.toString()); return apiResponse; } catch(ElasticsearchStatusException | IOException e) { return apiResponse.setResponse(HttpStatus.INTERNAL_SERVER_ERROR, null, null, apiUtils.getErrorsFromException(errors, e), request); } } @Override public ApiResponse<DataAsset> dataAsset(HttpServletRequest request, String id) { logger.info("Request: Get DataAsset by ID"); final String RESPONSE_MSG = "Response: GET DataAsset "; List<ApiError> errors = new ArrayList<>(); ApiResponse<DataAsset> apiResponse = new ApiResponse<>(); List<ApiMessage> messages = new ArrayList<>(); try { DataAsset dataAsset = dataAssetsDao.getDataAssetById(id); if (dataAsset != null) { apiResponse.setResponse(HttpStatus.OK, dataAsset, messages, null, request); logger.info(MESSAGE_TEMPLATE, RESPONSE_MSG,HttpStatus.OK.toString()); return apiResponse; } apiResponse.setResponse(HttpStatus.NOT_FOUND, null, null, null, request); logger.info(MESSAGE_TEMPLATE, RESPONSE_MSG, HttpStatus.NOT_FOUND.toString()); return apiResponse; } catch(ElasticsearchStatusException | IOException e) { return apiResponse.setResponse(HttpStatus.INTERNAL_SERVER_ERROR, null, null, apiUtils.getErrorsFromException(errors, e), request); } } @Override public ApiResponse<DataAsset> updateDataAsset(HttpServletRequest request, DataAsset dataAsset) { logger.info("Request: Update DataAsset"); final String RESPONSE_MSG = "Response: PUT DataAsset "; List<ApiError> errors = new ArrayList<>(); List<ApiMessage> messages = new ArrayList<>(); ApiResponse<DataAsset> apiResponse = new ApiResponse<>(); try { dataAsset.setDhLastUpdate(apiUtils.getCurrentUtcTimestamp()); String result = dataAssetsDao.updateDataAsset(dataAsset); if (result != null) { messages.add(new ApiMessage(result)); logger.info(MESSAGE_TEMPLATE, RESPONSE_MSG,HttpStatus.OK.toString()+" "+result); apiResponse.setResponse(HttpStatus.OK, dataAsset, messages, null, request); return apiResponse; } logger.info(MESSAGE_TEMPLATE, RESPONSE_MSG, HttpStatus.INTERNAL_SERVER_ERROR.toString()); apiResponse.setResponse(HttpStatus.INTERNAL_SERVER_ERROR, null, null, null, request); return apiResponse; } catch(ElasticsearchStatusException | IOException e) { return apiResponse.setResponse(HttpStatus.INTERNAL_SERVER_ERROR, null, null, apiUtils.getErrorsFromException(errors, e), request); } } }
34.764228
133
0.770814
dd810a88bd46c1cd6e8ea2e40f19e1f20c4c8db3
684
package no.ibear.config; import io.smallrye.config.ConfigMapping; import io.smallrye.config.WithDefault; import io.smallrye.config.WithName; import java.util.List; import java.util.Optional; import javax.validation.constraints.Positive; @ConfigMapping(prefix = "greeting") public interface GreetingConfiguration { String greeting(); @WithName("suffix") @WithDefault("Señor") String getSuffix(); @WithName("name") Optional<String> getName(); @WithName("content") ContentConfig getContent(); interface ContentConfig { @Positive @WithName("prizeAmount") Integer getPrizeAmount(); @WithName("recipients") List<String> getRecipients(); } }
20.727273
45
0.733918
61481bd7e4602d913415de230009213a404e5cff
1,827
/** * © 2019 isp-insoft GmbH */ package com.isp.memate; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import com.isp.memate.ServerLog.logType; /** * Starts the server and connects every user with its own socket. * * @author nwe * @since 23.10.2019 */ public class Main { private final static boolean debug = true; /** * @param args Path for the databse */ public static void main( final String args[] ) { if ( !debug ) { new SendServerInformationsToClients().start(); } ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket( debug ? 3142 : 3141 ); //Default is 3141 - Debug is 3142 ServerLog.newLog( logType.INFO, "Starte MateServer auf Port: " + serverSocket.getLocalPort() ); } catch ( final IOException e ) { ServerLog.newLog( logType.ERROR, "Der Server konnte nicht gestartet werden" ); e.printStackTrace(); } final String dataBasePath; if ( args.length > 0 ) { dataBasePath = args[ 0 ]; } else { dataBasePath = Database.getTargetFolder().toFile().toString() + File.separator + "MeMate.db"; } ServerLog.newLog( logType.INFO, "Datenbankverbindung wird hergestellt...." ); final Database database = new Database( dataBasePath ); while ( true ) { try { socket = serverSocket.accept(); } catch ( final IOException e ) { ServerLog.newLog( logType.ERROR, "Es konnte keine Verbindung zwischen Client und Server aufgebaut werden" ); e.printStackTrace(); } final SocketThread socketThread = new SocketThread( socket, database ); SocketPool.addSocket( socketThread ); socketThread.start(); } } }
25.027397
116
0.637657
6dab1568e00dfa89fdb6cf1febec2d247e720024
279
package com.taibai.admin.api.dto; import com.taibai.admin.api.entity.Role; import lombok.Data; import lombok.EqualsAndHashCode; /** * @Auther: DZL * @Date: 2019/11/25 * @Description: 角色dto */ @Data @EqualsAndHashCode(callSuper = true) public class RoleDTO extends Role { }
17.4375
40
0.734767
d86b79f1273f3110bc40381817db3cfc2be8d3f2
1,097
package app.bennsandoval.com.woodmin.models.v3.shop; import com.google.gson.annotations.SerializedName; import app.bennsandoval.com.woodmin.models.v3.orders.Meta; public class Store { private String name; private String description; @SerializedName("URL") private String url; @SerializedName("wc_version") private String wcVersion; private Meta meta; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getWcVersion() { return wcVersion; } public void setWcVersion(String wcVersion) { this.wcVersion = wcVersion; } public Meta getMeta() { return meta; } public void setMeta(Meta meta) { this.meta = meta; } }
19.245614
58
0.628988
55dc7d4bb64d0d2378afa3cedcfd1af8a0328737
922
package jit.edu.paas.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; /** * @author jitwxs * @since 2018/7/9 23:54 */ @Data public class UserDockerInfoVO { /** * 最后登录时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date lastLogin; /** * 最后登录IP */ private String ip; /** * 项目数 */ private Integer projectNum; /** * 容器数目 */ private Integer containerNum; /** * 容器运行数目 */ private Integer containerRunningNum; /** * 容器暂停数目 */ private Integer containerPauseNum; /** * 容器停止数目 */ private Integer containerStopNum; /** * 上传镜像数目 */ private Integer uploadImageNum; /** * Hub镜像数目 */ private Integer hubImageNum; /** * 服务数目 */ private Integer serviceNum; }
15.896552
68
0.558568
7b327dac45c40ba8fd2918df2ae90fc1643bcc9b
5,490
/** * 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.storm.spout; import static org.apache.storm.spout.CheckPointState.State.COMMITTED; import static org.apache.storm.spout.CheckPointState.State.COMMITTING; import static org.apache.storm.spout.CheckPointState.State.PREPARING; /** * Captures the current state of the transaction in {@link CheckpointSpout}. The state transitions are as follows. * <pre> * ROLLBACK(tx2) * <------------- PREPARE(tx2) COMMIT(tx2) * COMMITTED(tx1)-------------> PREPARING(tx2) --------------> COMMITTING(tx2) -----------------> COMMITTED (tx2) * * </pre> * * <p>During recovery, if a previous transaction is in PREPARING state, it is rolled back since all bolts in the topology might not have * prepared (saved) the data for commit. If the previous transaction is in COMMITTING state, it is rolled forward (committed) since some * bolts might have already committed the data. * * <p>During normal flow, the state transitions from PREPARING to COMMITTING to COMMITTED. In case of failures the * prepare/commit operation is retried. */ public class CheckPointState { private long txid; private State state; public CheckPointState(long txid, State state) { this.txid = txid; this.state = state; } // for kryo public CheckPointState() { } public long getTxid() { return txid; } public State getState() { return state; } /** * Get the next state based on this checkpoint state. * * @param recovering if in recovering phase * @return the next checkpoint state based on this state. */ public CheckPointState nextState(boolean recovering) { CheckPointState nextState; switch (state) { case PREPARING: nextState = recovering ? new CheckPointState(txid - 1, COMMITTED) : new CheckPointState(txid, COMMITTING); break; case COMMITTING: nextState = new CheckPointState(txid, COMMITTED); break; case COMMITTED: nextState = recovering ? this : new CheckPointState(txid + 1, PREPARING); break; default: throw new IllegalStateException("Unknown state " + state); } return nextState; } /** * Get the next action to perform based on this checkpoint state. * * @param recovering if in recovering phase * @return the next action to perform based on this state */ public Action nextAction(boolean recovering) { Action action; switch (state) { case PREPARING: action = recovering ? Action.ROLLBACK : Action.PREPARE; break; case COMMITTING: action = Action.COMMIT; break; case COMMITTED: action = recovering ? Action.INITSTATE : Action.PREPARE; break; default: throw new IllegalStateException("Unknown state " + state); } return action; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckPointState that = (CheckPointState) o; if (txid != that.txid) { return false; } return state == that.state; } @Override public int hashCode() { int result = (int) (txid ^ (txid >>> 32)); result = 31 * result + (state != null ? state.hashCode() : 0); return result; } @Override public String toString() { return "CheckPointState{" + "txid=" + txid + ", state=" + state + '}'; } public enum State { /** * The checkpoint spout has committed the transaction. */ COMMITTED, /** * The checkpoint spout has started committing the transaction and the commit is in progress. */ COMMITTING, /** * The checkpoint spout has started preparing the transaction for commit and the prepare is in progress. */ PREPARING } public enum Action { /** * prepare transaction for commit. */ PREPARE, /** * commit the previously prepared transaction. */ COMMIT, /** * rollback the previously prepared transaction. */ ROLLBACK, /** * initialize the state. */ INITSTATE } }
32.105263
139
0.589253
3551308ff75cc12813a7d98b72d5bf037bdf1475
462
package test; import org.noear.solon.annotation.Controller; import org.noear.solon.annotation.Mapping; import org.noear.solon.core.handle.Context; import org.noear.solon.core.handle.Handler; /** * @author noear 2021/8/8 created */ @Mapping(value = "/user/**", before = true) @Controller public class UserInterceptor implements Handler { @Override public void handle(Context ctx) throws Exception { // throw new NullPointerException(); } }
24.315789
54
0.731602
bf8cbce15301ba3e95b603654b4358484b6aaeda
7,665
/* * Copyright 2020 nuwansa. * * 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.cloudimpl.db4ji2.idx.str; import com.cloudimpl.db4ji2.core.old.LongComparable; import com.cloudimpl.db4ji2.core.old.MergeItem; import com.google.common.util.concurrent.RateLimiter; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * @author nuwansa */ public class StringColumnIndex extends StringQueryBlockAggregator { private final String columnName; private final StringMemBlockPool memPool; private final StringCompactionManager compactMan; private StringMemBlock currentBlock; private final Supplier<StringEntry> entrySupplier; private final CopyOnWriteArrayList<StringQueryable> queryables = new CopyOnWriteArrayList<>(); public StringColumnIndex(String colName, StringMemBlockPool pool,Supplier<StringEntry> entrySupplier) { this.columnName = colName; this.entrySupplier = entrySupplier; memPool = pool; compactMan = new StringCompactionManager(this); compactMan.init(7); currentBlock = memPool.aquire(); add(currentBlock); } public void put(CharSequence key, long value) { boolean ok = currentBlock.put(memPool.getLongBuffer(), key, value); if (!ok) { compactMan.submit(new MergeItem<>(0, currentBlock)); currentBlock = memPool.aquire(); if (currentBlock == null) { // throw new Db4jException System.out.println("columnIndex :" + columnName + " not enough blocks available in pool"); try { System.gc(); Thread.sleep(1000); currentBlock = memPool.aquire(); } catch (InterruptedException ex) { Logger.getLogger(StringColumnIndex.class.getName()).log(Level.SEVERE, null, ex); } } add(currentBlock); currentBlock.put(memPool.getLongBuffer(), key, value); } } protected synchronized void remove(StringQueryable query) { queryables.remove(query); } public int getQueryBlockCount() { return queryables.size(); } public Supplier<StringEntry> getEntrySupplier() { return entrySupplier; } protected synchronized void update(List<? extends StringQueryable> removables, StringQueryable update) { queryables.removeAll(removables); queryables.add(update); } @Override protected synchronized Stream<StringQueryable> getBlockStream() { return queryables.stream(); } protected synchronized void add(StringQueryable query) { queryables.add(query); } protected void release(StringQueryable queryable) { if (queryable instanceof StringMemBlock) { memPool.release((StringMemBlock) queryable); } // else if (queryable instanceof BTree) { // BTree.class.cast(queryable).close(); // } } public void dumpStats() { queryables.stream() .collect(Collectors.groupingBy(c -> c.getSize())) .forEach((i, list) -> System.out.println("k:" + i + "->" + list.size())); ; } public static void main(String[] args) throws InterruptedException { System.out.println("max: "+Integer.MAX_VALUE); StringColumnIndex idx = new StringColumnIndex("Test",new DirectStringMemBlockPool(4096 * 1280 * 32, 4096),()->new StringEntry()); // List<Integer> list1 = // Arrays.asList(IntStream.range(0, 20_000_000).boxed().toArray(Integer[]::new)); // Collections.shuffle(list1); int i = 0; int size = 10_000_000; String[] arr = IntStream.range(0, (int)size).mapToObj(k->StringBTree.randomString()).toArray(String[]::new); int rate = 0; long start = System.currentTimeMillis(); CharSequence lasKey = null; CharSequence firstKey = null; RateLimiter limiter = RateLimiter.create(400000); while (i < size) { // limiter.acquire(); lasKey = arr[i];//StringBTree.randomString(); if (firstKey == null) { firstKey = lasKey; } idx.put(lasKey, i); if (i % 1000000 == 0) { System.out.println("query : " + idx.getQueryBlockCount()); // System.gc(); } rate++; long end = System.currentTimeMillis(); if (end - start >= 1000) { System.out.println( "rate-----------------------------------: " + rate + " : " + idx.getQueryBlockCount() + " current : " + (i)); rate = 0; start = System.currentTimeMillis(); } i++; } CharSequence vlk = lasKey; // list1.forEach(i -> idx.put(i, i * 10)); System.out.println("completed:---------------------------------------------"); // int size = list1.size(); System.out.println("laskKey: " + vlk); System.out.println("firstKey: " + firstKey); StreamSupport.stream(((Iterable<StringEntry>) () -> idx.findEQ((vlk))).spliterator(), false).limit(1000) .forEach(System.out::println); start = System.currentTimeMillis(); System.out.println( StreamSupport.stream(((Iterable<StringEntry>) () -> idx.all(true)).spliterator(), false).limit(1000).count()); long end = System.currentTimeMillis(); System.out.println("time : " + (end - start)); // list1 = null; Thread.sleep(10000); System.out.println( StreamSupport.stream(((Iterable<StringEntry>) () -> idx.all(true)).spliterator(), false).count()); start = System.currentTimeMillis(); idx.findGE(firstKey).forEachRemaining(t -> { // System.out.println(">" + t.getStringBlock().toString(t._getKey())); }); end = System.currentTimeMillis(); System.out.println("diff: " + (end - start)); start = System.currentTimeMillis(); idx.findEQ(firstKey) .forEachRemaining( t -> { System.out.println("=" + t.getStringBlock().toString(t._getKey())); }); end = System.currentTimeMillis(); System.out.println("diff: " + (end - start)); System.out.println("xxx: " + idx.getQueryBlockCount()); idx.dumpStats(); // idx.all(true) // .forEachRemaining( // entry -> { // System.out.println("e: " + entry); // }); Thread.sleep(100000000); } }
38.325
137
0.581344
debca8e32d838cd00e4509ec21e0e482b122e120
1,370
package org.datalift.lov.local.objects; import org.datalift.lov.local.LovUtil; public class ResultItemMatch implements JSONSerializable { private String property = null; private String propertyPrefixed = null; private String value = null; private String valueShort = null; public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public String getPropertyPrefixed() { return propertyPrefixed; } public void setPropertyPrefixed(String propertyPrefixed) { this.propertyPrefixed = propertyPrefixed; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getValueShort() { return valueShort; } public void setValueShort(String valueShort) { this.valueShort = valueShort; } @Override public String toJSON() { StringBuilder jsonResult = new StringBuilder(); // beginning of json jsonResult.append("{"); jsonResult.append("\"property\": " + LovUtil.toJSON(property) + ","); jsonResult.append("\"propertyPrefixed\": " + LovUtil.toJSON(propertyPrefixed) + ","); jsonResult.append("\"value\": " + LovUtil.toJSON(value) + ","); jsonResult.append("\"valueShort\": " + LovUtil.toJSON(valueShort)); // end of json jsonResult.append("}"); return jsonResult.toString(); } }
21.746032
87
0.710219
4825b6ad93ce0eb21bf22b9ed2e29afe02d3a28b
4,944
package io.blockchainetl.bitcoin.domain; import com.google.common.base.Objects; import org.apache.avro.reflect.Nullable; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.DefaultCoder; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; @DefaultCoder(AvroCoder.class) @JsonIgnoreProperties(ignoreUnknown = true) public class Block { @Nullable private String type; @Nullable private String hash; @Nullable private Long size; @Nullable @JsonProperty("stripped_size") private Long strippedSize; @Nullable private Long weight; @Nullable private Long number; @Nullable private Long version; @Nullable @JsonProperty("merkle_root") private String merkleRoot; @Nullable @JsonProperty("timestamp") private Long timestamp; @Nullable private String nonce; @Nullable private String bits; @Nullable @JsonProperty("coinbase_param") private String coinbaseParam; @Nullable @JsonProperty("transaction_count") private Long transactionCount; public Block() {} public String getType() { return type; } public void setType(String type) { this.type = type; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public Long getStrippedSize() { return strippedSize; } public void setStrippedSize(Long strippedSize) { this.strippedSize = strippedSize; } public Long getWeight() { return weight; } public void setWeight(Long weight) { this.weight = weight; } public Long getNumber() { return number; } public void setNumber(Long number) { this.number = number; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getMerkleRoot() { return merkleRoot; } public void setMerkleRoot(String merkleRoot) { this.merkleRoot = merkleRoot; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public String getNonce() { return nonce; } public void setNonce(String nonce) { this.nonce = nonce; } public String getBits() { return bits; } public void setBits(String bits) { this.bits = bits; } public String getCoinbaseParam() { return coinbaseParam; } public void setCoinbaseParam(String coinbaseParam) { this.coinbaseParam = coinbaseParam; } public Long getTransactionCount() { return transactionCount; } public void setTransactionCount(Long transactionCount) { this.transactionCount = transactionCount; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Block block = (Block) o; return Objects.equal(type, block.type) && Objects.equal(hash, block.hash) && Objects.equal(size, block.size) && Objects.equal(strippedSize, block.strippedSize) && Objects.equal(weight, block.weight) && Objects.equal(number, block.number) && Objects.equal(version, block.version) && Objects.equal(merkleRoot, block.merkleRoot) && Objects.equal(timestamp, block.timestamp) && Objects.equal(nonce, block.nonce) && Objects.equal(bits, block.bits) && Objects.equal(coinbaseParam, block.coinbaseParam) && Objects.equal(transactionCount, block.transactionCount); } @Override public int hashCode() { return Objects.hashCode(type, hash, size, strippedSize, weight, number, version, merkleRoot, timestamp, nonce, bits, coinbaseParam, transactionCount); } @Override public String toString() { return Objects.toStringHelper(this) .add("type", type) .add("hash", hash) .add("size", size) .add("strippedSize", strippedSize) .add("weight", weight) .add("number", number) .add("version", version) .add("merkleRoot", merkleRoot) .add("timestamp", timestamp) .add("nonce", nonce) .add("bits", bits) .add("coinbaseParam", coinbaseParam) .add("transactionCount", transactionCount) .toString(); } }
23.102804
118
0.601133
6efb72faa6c4bc49dde84e54c26949447b18a193
709
package Hyrdrasheads; //UNFINISHED //UNFINISHED //UNFINISHED //UNFINISHED //UNFINISHED import java.util.Scanner; public class HydrasHeads { public static void main(String[] args) { Scanner s = new Scanner(System.in); int head = s.nextInt(); int tail = s.nextInt(); boolean cando = true; int count = 0; //second move: -1tail; +2tail; // third move: -2tail; +1head; //fourth move: -2head; +0rest; if(tail == 0) { count = -1; cando = false; } while(head !=0 && tail!= 0 && cando==true) { if(head<0) head=0; if(tail<0) tail=0; if(head==0 && tail==0) { cando =false; } System.out.println(count); } }
17.725
47
0.558533
c7f4e67569a69e76fbcd575c977ef26748e5c730
2,118
package com.fiveonevr.apollo.client.utils; import com.google.common.io.CharStreams; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class NetUtil { private static final int DEFAULT_TIMEOUT_IN_SECONDS = 5000; /** * ping the url, return true if ping ok, false otherwise */ public static boolean pingUrl(String address) { try { URL urlObj = new URL(address); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_TIMEOUT_IN_SECONDS); connection.setReadTimeout(DEFAULT_TIMEOUT_IN_SECONDS); int statusCode = connection.getResponseCode(); cleanUpConnection(connection); return (200 <= statusCode && statusCode <= 399); } catch (Throwable ignore) { } return false; } /** * according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html, we should clean up the * connection by reading the response body so that the connection could be reused. */ private static void cleanUpConnection(HttpURLConnection conn) { InputStreamReader isr = null; InputStreamReader esr = null; try { isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); CharStreams.toString(isr); } catch (IOException e) { InputStream errorStream = conn.getErrorStream(); if (errorStream != null) { esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8); try { CharStreams.toString(esr); } catch (IOException ioe) { //ignore } } } finally { if (isr != null) { try { isr.close(); } catch (IOException ex) { // ignore } } if (esr != null) { try { esr.close(); } catch (IOException ex) { // ignore } } } } }
27.868421
120
0.649669
70131cf38defe9c8525f0d52b49888e9d5ff11f8
342
package pocket4j.action.modify; import java.util.Date; public class UnfavoriteAction extends BaseModifyAction { public UnfavoriteAction(final int itemId) { super(itemId); } public UnfavoriteAction(final int itemId, final Date time) { super(itemId, time); } @Override public String getActionName() { return "unfavorite"; } }
17.1
61
0.745614
e4d3d4086780f863564cf92b9d0f436f6e3903c6
671
package br.gov.sp.fatec.gedam.service.stat; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import br.gov.sp.fatec.gedam.model.entity.stat.Driver; @Repository public interface DriverRepository extends JpaRepository<Driver, Long>{ public Optional<Driver> findById(Long id); public Optional<Driver> findByNome(String nome); public boolean existsByNome(String nome); @Query("select d from Driver d order by upper(d.nome)") public List<Driver> buscarTodosOsDrivers(); }
26.84
70
0.773472
60c65643b284b22c68c3e419afc875e706fdf85e
655
package easy.array; import java.util.Arrays; public class DecompressRunLengthEncodedList_1313 { public int[] decompressRLElist(int[] nums) { int size = 0; for (int i = 0; i < nums.length; i += 2) size += nums[i]; int[] result = new int[size]; for (int i = 0, j = 0, k = 1; i < result.length; j += 2, k += 2) { while (nums[j]-- > 0) result[i++] = nums[k]; } return result; } public static void main(String[] args) { System.out.println(Arrays.toString(new DecompressRunLengthEncodedList_1313().decompressRLElist(new int[]{1, 1, 2, 3}))); } }
29.772727
128
0.551145
0e4413d47535771da9745188286bd53dfdc56c68
94
package com.example.service.business; public class AccountService { public void sun() {} }
13.428571
37
0.744681
21f1fac7d41512a495f093ced440454b013772be
1,520
package com.ajasuja.codepath.todo.fragment; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.widget.DatePicker; import com.ajasuja.codepath.todo.activity.MainActivity; import com.ajasuja.codepath.todo.db.Todo; import java.util.Calendar; /** * Created by ajasuja on 2/13/17. */ public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user System.out.println("on date set ... "); Todo todoItem = (Todo) getArguments().getSerializable("TodoItem"); DatePickerDialogListener datePickerDialogListener = (MainActivity) getActivity(); datePickerDialogListener.onDateSelected(todoItem, year, month, day); } public interface DatePickerDialogListener { void onDateSelected(Todo todo, int year, int month, int day); } }
35.348837
102
0.719737
5a4acdb235a7890d0d35b45d47ff4b9c9454ec84
1,926
package org.zstack.header.vm; import org.zstack.header.vo.EntityGraph; import org.zstack.header.vo.ForeignKey; import javax.persistence.*; @Entity @Table @EntityGraph( parents = { @EntityGraph.Neighbour(type = VmInstanceVO.class, myField = "vmUuid", targetField = "uuid") } ) public class VmInstanceNumaNodeVO { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column private Long id; @Column @ForeignKey(parentEntityClass = VmInstanceEO.class, onDeleteAction = ForeignKey.ReferenceOption.CASCADE) private String vmUuid; @Column private Integer vNodeID; @Column private String vNodeCPUs; @Column private Long vNodeMemSize; @Column private String vNodeDistance; @Column private Integer pNodeID; public VmInstanceNumaNodeVO() {} public Long getId() { return id; } public String getVmUuid() { return vmUuid; } public void setVmUuid(String vmUuid) { this.vmUuid = vmUuid; } public Integer getvNodeID() { return vNodeID; } public void setvNodeID(Integer vNodeID) { this.vNodeID = vNodeID; } public String getvNodeCPUs() { return vNodeCPUs; } public void setvNodeCPUs(String vNodeCPUs) { this.vNodeCPUs = vNodeCPUs; } public Long getvNodeMemSize() { return vNodeMemSize; } public void setvNodeMemSize(Long vNodeMemSize) { this.vNodeMemSize = vNodeMemSize; } public String getvNodeDistance() { return vNodeDistance; } public void setvNodeDistance(String vNodeDistance) { this.vNodeDistance = vNodeDistance; } public Integer getpNodeID() { return pNodeID; } public void setpNodeID(Integer pNodeID) { this.pNodeID = pNodeID; } public void setId(Long id) { this.id = id; } }
19.454545
108
0.639148
66d3e479c994b8c3504c3751242896bf350f86f0
4,801
package com.mobiledevpro.facebook; import android.app.Application; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import java.io.File; import java.util.Arrays; /** * Helper for working with Facebook SDK * <p> * Created by Dmitriy V. Chernysh on 07.12.17. * <p> * https://fb.com/mobiledevpro/ * https://github.com/dmitriy-chernysh * #MobileDevPro */ public class FBLoginShareHelper implements IFBLoginShareHelper { public static final int REQUEST_CODE = 10001; private static FBLoginShareHelper sHelper; private CallbackManager mLoginCallbackManager; private IFBLoginResultCallbacks mLoginResultCallbacks; private FBLoginShareHelper() { } public static FBLoginShareHelper getInstance() { if (sHelper == null) { sHelper = new FBLoginShareHelper(); } return sHelper; } /** * Init Facebook SDK * <p> * NOTE: call this in the main Application class in onCreate() method * * @param app Application class * @param appID Facebook App ID (from Facebook developer console) */ @Override public void init(Application app, String appID) { FacebookSdk.setApplicationId(appID); FacebookSdk.sdkInitialize(app.getApplicationContext(), REQUEST_CODE); AppEventsLogger.activateApp(app); } /** * Login to Facebook Page where user is admin * * @param fragment Fragment */ @Override public void loginAsPageAdmin(final Fragment fragment, @NonNull IFBLoginResultCallbacks outCallbacks) { mLoginResultCallbacks = outCallbacks; final LoginManager loginManager = LoginManager.getInstance(); //logout before new login loginManager.logOut(); mLoginCallbackManager = CallbackManager.Factory.create(); loginManager.registerCallback(mLoginCallbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { //show chooser to select facebook account/page FBGraphApiHelper.showAccountChooser(fragment.getActivity(), loginResult.getAccessToken(), mLoginResultCallbacks); } @Override public void onCancel() { mLoginResultCallbacks.onFail("Login cancelled"); } @Override public void onError(FacebookException error) { mLoginResultCallbacks.onFail("Login error: " + error.toString()); } }); //fo login with publish access loginManager.logInWithPublishPermissions( fragment, Arrays.asList(FBPermissions.PAGES_PUBLISH_ACCESS) ); } @Override public void logout() { LoginManager.getInstance().logOut(); } /** * Handle login result * <p> * NOTE: call this on onActivityResult() by request code (REQUEST_CODE) * * @param requestCode Request code * @param resultCode Result code * @param data Result data */ @Override public void onLoginResult(int requestCode, int resultCode, Intent data) { if (mLoginCallbackManager == null) return; mLoginCallbackManager.onActivityResult(requestCode, resultCode, data); } @Override public void uploadVideoToPageAsync(String accessToken, String userOrPageId, @NonNull File localVideoFile, String videoTitle, String videoDescription, @NonNull IFBVideoUploadResultCallbacks callbacks) { AccessToken token = new AccessToken( accessToken, AccessToken.getCurrentAccessToken().getApplicationId(), userOrPageId, Arrays.asList(FBPermissions.PAGES_PUBLISH_ACCESS), null, AccessToken.getCurrentAccessToken().getSource(), AccessToken.getCurrentAccessToken().getExpires(), AccessToken.getCurrentAccessToken().getLastRefresh() ); FBGraphApiHelper.uploadVideoAsync( token, userOrPageId, localVideoFile, videoTitle, videoDescription, callbacks ); } }
31.794702
129
0.631119
b0c4df05500f11619a74e306ab4e26f6bf3f40bd
11,270
package soot.jimple.infoflow.methodSummary.generator; import java.util.HashSet; import java.util.Set; import soot.jimple.infoflow.InfoflowConfiguration; /** * Configuration class for the data flow summary generator * * @author Steven Arzt * */ public class SummaryGeneratorConfiguration extends InfoflowConfiguration { protected boolean loadFullJAR = false; protected String androidPlatformDir = ""; protected Set<String> excludes = null; protected boolean summarizeHashCodeEquals = false; protected boolean validateResults = true; protected boolean applySummariesOnTheFly = true; protected Set<String> additionalSummaryDirectories; protected long classSummaryTimeout = -1; private int repeatCount = 1; static { SummaryGeneratorConfiguration.setMergeNeighbors(true); } /** * Creates a new instance of the SummaryGeneratorConfiguration class and * initializes it with the default configuration options */ public SummaryGeneratorConfiguration() { // Set the default data flow configuration setEnableExceptionTracking(false); setStaticFieldTrackingMode(StaticFieldTrackingMode.None); setCodeEliminationMode(CodeEliminationMode.PropagateConstants); setIgnoreFlowsInSystemPackages(false); setStopAfterFirstFlow(false); setEnableArraySizeTainting(false); setExcludeSootLibraryClasses(false); setWriteOutputFiles(false); getPathConfiguration().setPathBuildingAlgorithm(PathBuildingAlgorithm.None); getPathConfiguration().setPathReconstructionMode(PathReconstructionMode.Fast); } @Override public void merge(InfoflowConfiguration config) { super.merge(config); if (config instanceof SummaryGeneratorConfiguration) { SummaryGeneratorConfiguration summaryConfig = (SummaryGeneratorConfiguration) config; this.androidPlatformDir = summaryConfig.androidPlatformDir; this.loadFullJAR = summaryConfig.loadFullJAR; this.excludes = summaryConfig.excludes == null || summaryConfig.excludes.isEmpty() ? null : new HashSet<>(summaryConfig.excludes); this.summarizeHashCodeEquals = summaryConfig.summarizeHashCodeEquals; this.validateResults = summaryConfig.validateResults; this.repeatCount = summaryConfig.repeatCount; this.applySummariesOnTheFly = summaryConfig.applySummariesOnTheFly; { Set<String> otherAdditionalDirs = summaryConfig.additionalSummaryDirectories; this.additionalSummaryDirectories = otherAdditionalDirs == null || otherAdditionalDirs.isEmpty() ? null : new HashSet<>(otherAdditionalDirs); } this.classSummaryTimeout = summaryConfig.classSummaryTimeout; } } /** * Sets the directory in which the Android platform JARs are located. This * option must be set when generating summariers for classes inside an APK file. * * @param androidPlatformDir The directory in which the Android platform JARs * are located */ public void setAndroidPlatformDir(String androidPlatformDir) { this.androidPlatformDir = androidPlatformDir; } /** * Gets the directory in which the Android platform JARs are located. This * option must be set when generating summariers for classes inside an APK file. * * @return The directory in which the Android platform JARs are located */ public String getAndroidPlatformDir() { return androidPlatformDir; } /** * Sets whether the target JAR file shall be loaded fully before the analysis * starts. More precisely, this instructs StubDroid to not only explicitly load * the target classes, but put the whole target JAR into Soot's process * directory. This is, for instance, useful when analyzing all classes derived * from a certain superclass. * * @param loadFullJAR True if the target JAR file shall be fully loaded before * performing the analysis, otherwise false. */ public void setLoadFullJAR(boolean loadFullJAR) { this.loadFullJAR = loadFullJAR; } /** * Gets whether the target JAR file shall be loaded fully before the analysis * starts. More precisely, this instructs StubDroid to not only explicitly load * the target classes, but put the whole target JAR into Soot's process * directory. This is, for instance, useful when analyzing all classes derived * from a certain superclass. * * @return True if the target JAR file shall be fully loaded before performing * the analysis, otherwise false. */ public boolean getLoadFullJAR() { return this.loadFullJAR; } /** * Sets the set of classes to be excluded from the analysis. Use pkg.* to * exclude all classes in package "pkg" * * @param excludes The set of classes and packages to be excluded */ public void setExcludes(Set<String> excludes) { this.excludes = excludes; } /** * Gets the set of classes to be excluded from the analysis. * * @return The set of classes and packages to be excluded */ public Set<String> getExcludes() { return this.excludes; } /** * Gets whether hashCode() and equals() methods should also be summarized * * @return True if hashCode() and equals() methods shall be summarized, false * otherwise */ public boolean getSummarizeHashCodeEquals() { return summarizeHashCodeEquals; } /** * Sets whether hashCode() and equals() methods should also be summarized * * @param summarizeHashCodeEquals True if hashCode() and equals() methods shall * be summarized, false otherwise */ public void setSummarizeHashCodeEquals(boolean summarizeHashCodeEquals) { this.summarizeHashCodeEquals = summarizeHashCodeEquals; } /** * Sets the number of time the analysis of every class shall be repeated. This * is useful for measurements and evaluations. * * @param repeatCount The number of time the analysis of every class shall be * repeated */ public void setRepeatCount(int repeatCount) { this.repeatCount = repeatCount; } /** * Gets the number of time the analysis of every class shall be repeated. This * is useful for measurements and evaluations. * * @return The number of time the analysis of every class shall be repeated */ public int getRepeatCount() { return this.repeatCount; } /** * Sets whether the computed data flows shall be validated * * @param validateResults True if the computed data flows shall be validated, * otherwise false */ public void setValidateResults(boolean validateResults) { this.validateResults = validateResults; } /** * Gets whether the computed data flows shall be validated * * @return True if the computed data flows shall be validated, otherwise false */ public boolean getValidateResults() { return this.validateResults; } /** * Gets whether the summary generator shall apply the generated summaries on the * fly. With this option enabled, the classes to be processed will be sorted * according to their dependencies.When processing the second class, it will * apply the summary of the first class. * * @return True if the generated summaries shall be applied on the fly, false * otherwise */ public boolean getApplySummariesOnTheFly() { return applySummariesOnTheFly; } /** * Sets whether the summary generator shall apply the generated summaries on the * fly. With this option enabled, the classes to be processed will be sorted * according to their dependencies.When processing the second class, it will * apply the summary of the first class. * * @param applySummariesOnTheFly True if the generated summaries shall be * applied on the fly, false otherwise */ public void setApplySummariesOnTheFly(boolean applySummariesOnTheFly) { this.applySummariesOnTheFly = applySummariesOnTheFly; } /** * Gets the directories in which the summary generator shall look for existing * summaries to integrate * * @return The directories from which existing summaries shall be loaded */ public Set<String> getAdditionalSummaryDirectories() { return additionalSummaryDirectories; } /** * Adds an additional directory in which the summary generator shall look for * existing summaries to speed up the generation of new ones * * @param directory The directory from which to load the summaries */ public void addAdditionalSummaryDirectory(String directory) { if (additionalSummaryDirectories == null) additionalSummaryDirectories = new HashSet<>(); additionalSummaryDirectories.add(directory); } /** * Gets the timeout after which StubDroid shall abort generating summaries for a * single class * * @return The timeout, in seconds, after which StubDroid shall abort generating * summaries for a single class */ public long getClassSummaryTimeout() { return classSummaryTimeout; } /** * Sets the timeout after which StubDroid shall abort generating summaries for a * single class * * @param classSummaryTimeout The timeout, in seconds, after which StubDroid * shall abort generating summaries for a single * class */ public void setClassSummaryTimeout(long classSummaryTimeout) { this.classSummaryTimeout = classSummaryTimeout; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((additionalSummaryDirectories == null) ? 0 : additionalSummaryDirectories.hashCode()); result = prime * result + ((androidPlatformDir == null) ? 0 : androidPlatformDir.hashCode()); result = prime * result + (applySummariesOnTheFly ? 1231 : 1237); result = prime * result + (int) (classSummaryTimeout ^ (classSummaryTimeout >>> 32)); result = prime * result + ((excludes == null) ? 0 : excludes.hashCode()); result = prime * result + (loadFullJAR ? 1231 : 1237); result = prime * result + repeatCount; result = prime * result + (summarizeHashCodeEquals ? 1231 : 1237); result = prime * result + (validateResults ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SummaryGeneratorConfiguration other = (SummaryGeneratorConfiguration) obj; if (additionalSummaryDirectories == null) { if (other.additionalSummaryDirectories != null) return false; } else if (!additionalSummaryDirectories.equals(other.additionalSummaryDirectories)) return false; if (androidPlatformDir == null) { if (other.androidPlatformDir != null) return false; } else if (!androidPlatformDir.equals(other.androidPlatformDir)) return false; if (applySummariesOnTheFly != other.applySummariesOnTheFly) return false; if (classSummaryTimeout != other.classSummaryTimeout) return false; if (excludes == null) { if (other.excludes != null) return false; } else if (!excludes.equals(other.excludes)) return false; if (loadFullJAR != other.loadFullJAR) return false; if (repeatCount != other.repeatCount) return false; if (summarizeHashCodeEquals != other.summarizeHashCodeEquals) return false; if (validateResults != other.validateResults) return false; return true; } }
33.641791
107
0.732742
08cbc8ff10f9fc0086944b556595e8e8601f61ba
2,327
package br.com.persistencia.java.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.hibernate.annotations.ForeignKey; @Entity public class Dependente { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long idDependente; private String nomeDependente; private String sexoDependente; private String aniversarioDependente; private String parentescoDependente; @ManyToOne @JoinColumn(name = "idFuncionario") private Funcionario funcionario; public long getIdDependente() { return idDependente; } public void setIdDependente(long idDependente) { this.idDependente = idDependente; } public String getNomeDependente() { return nomeDependente; } public void setNomeDependente(String nomeDependente) { this.nomeDependente = nomeDependente; } public String getSexoDependente() { return sexoDependente; } public void setSexoDependente(String sexoDependente) { this.sexoDependente = sexoDependente; } public String getAniversarioDependente() { return aniversarioDependente; } public void setAniversarioDependente(String aniversarioDependente) { this.aniversarioDependente = aniversarioDependente; } public String getParentescoDependente() { return parentescoDependente; } public void setParentescoDependente(String parentescoDependente) { this.parentescoDependente = parentescoDependente; } public Funcionario getFuncionario() { return funcionario; } public void setFuncionario(Funcionario funcionario) { this.funcionario = funcionario; } public Dependente() { } @Override public String toString() { return "Dependente{" + "idDependente=" + idDependente + ", nomeDependente='" + nomeDependente + '\'' + ", sexoDependente='" + sexoDependente + '\'' + ", aniversarioDependente='" + aniversarioDependente + '\'' + ", parentescoDependente='" + parentescoDependente + '\'' + '}'; } }
25.293478
76
0.681135
34d1fce2cb4c02946e50242bc45c481704cb6112
4,626
package com.example.web; import com.example.domain.Option; import com.example.domain.Question; import com.example.domain.Questionnaire; import com.example.repository.QuestionnaireRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.util.CollectionUtils; import static org.hamcrest.Matchers.containsString; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(CreateQuestionnaireController.class) public class CreateQuestionnaireControllerTests { @Autowired private MockMvc mvc; @MockBean private QuestionnaireRepository questionnaireRepository; private Questionnaire questionnaire; @Before public void setUp() throws Exception { questionnaire = PrepareData.generateTestQuestionnaire(); } @Test public void testCreateQuestionnaireSuccess() throws Exception { given(questionnaireRepository.save(any(Questionnaire.class))).willReturn(questionnaire); mvc.perform(buildRequest(questionnaire)) .andExpect(status().isFound()) .andExpect(flash().attribute("questionnaireId", 2L)); } @Test public void testCreateQuestionnaireFailureDueQuestionsEmpty() throws Exception { questionnaire.setQuestions(null); given(questionnaireRepository.save(any(Questionnaire.class))).willReturn(questionnaire); mvc.perform(buildRequest(questionnaire)) .andExpect(status().isOk()) .andExpect(content().string(containsString("At least one question is needed."))); } @Test public void testCreateQuestionnaireFailureDueOptionTextEmpty() throws Exception { questionnaire.getQuestions().get(1).getOptions().get(0).setText(null); given(questionnaireRepository.save(any(Questionnaire.class))).willReturn(questionnaire); mvc.perform(buildRequest(questionnaire)) .andExpect(status().isOk()) .andExpect(content().string(containsString("Option text is required."))); } private MockHttpServletRequestBuilder buildRequest(Questionnaire questionnaire) { MockHttpServletRequestBuilder createRequestBuilder = post("/create") .param("title", questionnaire.getTitle()) .param("description", questionnaire.getDescription()); if (!CollectionUtils.isEmpty(questionnaire.getQuestions())) { for (int i = 0; i < questionnaire.getQuestions().size(); i++) { Question question = questionnaire.getQuestions().get(i); String questionPrefix = "questions[" + i + "]."; createRequestBuilder .param(questionPrefix + "sequenceNumber", String.valueOf(question.getSequenceNumber())) .param(questionPrefix + "content", question.getContent()) .param(questionPrefix + "required", String.valueOf(question.isRequired())) .param(questionPrefix + "type", question.getType().name()); if (question.isHasOthersOption()) { createRequestBuilder .param(questionPrefix + "hasOthersOption", "true") .param(questionPrefix + "othersOptionText", question.getOthersOptionText()); } if (!CollectionUtils.isEmpty(question.getOptions())) { for (int j = 0; j < question.getOptions().size(); j++) { Option option = question.getOptions().get(j); String optionPrefix = questionPrefix + "options[" + j + "]."; createRequestBuilder .param(optionPrefix + "sequenceNumber", String.valueOf(option.getSequenceNumber())) .param(optionPrefix + "text", option.getText()); } } } } return createRequestBuilder; } }
45.352941
115
0.667315
5e69108ee96d3c7cffc0e97f156b8589dc4294a6
8,329
/* * Copyright (c) 2019-2022 Choko (choko@curioswitch.org) * SPDX-License-Identifier: MIT */ package org.curioswitch.common.protobuf.json; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.io.SerializedString; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Message; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public final class SerializeSupport { // The implementations of the repeated members is all almost the same, so it may make sense to // codegen them. However, codegen of loops is complicated and more shared code should make it // slightly easier for the JVM to optimize. Anyways, the maintenance cost is low since it's // highly unlikely additional types will ever be added. public static void printRepeatedSignedInt32(List<Integer> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printSignedInt32(values.get(i), gen); } gen.writeEndArray(); } public static void printSignedInt32(int value, JsonGenerator gen) throws IOException { gen.writeNumber(value); } public static void printRepeatedSignedInt64(List<Long> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printSignedInt64(values.get(i), gen); } gen.writeEndArray(); } public static void printSignedInt64(long value, JsonGenerator gen) throws IOException { gen.writeString(Long.toString(value)); } public static void printRepeatedUnsignedInt32(List<Integer> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printUnsignedInt32(values.get(i), gen); } gen.writeEndArray(); } public static void printUnsignedInt32(int value, JsonGenerator gen) throws IOException { gen.writeNumber(normalizeUnsignedInt32(value)); } public static long normalizeUnsignedInt32(int value) { return value >= 0 ? value : value & 0x00000000FFFFFFFFL; } public static void printRepeatedUnsignedInt64(List<Long> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printUnsignedInt64(values.get(i), gen); } gen.writeEndArray(); } public static void printUnsignedInt64(long value, JsonGenerator gen) throws IOException { gen.writeString(normalizeUnsignedInt64(value)); } public static String normalizeUnsignedInt64(long value) { return value >= 0 ? Long.toString(value) // Pull off the most-significant bit so that BigInteger doesn't think // the number is negative, then set it again using setBit(). : BigInteger.valueOf(value & Long.MAX_VALUE).setBit(Long.SIZE - 1).toString(); } public static void printRepeatedBool(List<Boolean> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printBool(values.get(i), gen); } gen.writeEndArray(); } public static void printBool(boolean value, JsonGenerator gen) throws IOException { gen.writeBoolean(value); } public static void printRepeatedFloat(List<Float> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printFloat(values.get(i), gen); } gen.writeEndArray(); } public static void printFloat(float value, JsonGenerator gen) throws IOException { gen.writeNumber(value); } public static void printRepeatedDouble(List<Double> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printDouble(values.get(i), gen); } gen.writeEndArray(); } public static void printDouble(double value, JsonGenerator gen) throws IOException { gen.writeNumber(value); } public static void printRepeatedString(List<String> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printString(values.get(i), gen); } gen.writeEndArray(); } public static void printString(String value, JsonGenerator gen) throws IOException { gen.writeString(value); } public static void printRepeatedBytes(List<ByteString> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printBytes(values.get(i), gen); } gen.writeEndArray(); } public static void printBytes(ByteString value, JsonGenerator gen) throws IOException { gen.writeBinary(value.toByteArray()); } // Note: I hope no one ever actually calls this method... public static void printRepeatedNull(List<Integer> values, JsonGenerator gen) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printNull(values.get(i), gen); } gen.writeEndArray(); } public static void printNull(int unused, JsonGenerator gen) throws IOException { gen.writeNull(); } public static void printRepeatedEnum( List<Integer> values, JsonGenerator gen, EnumDescriptor descriptor) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printEnum(values.get(i), gen, descriptor); } gen.writeEndArray(); } public static void printEnum(int value, JsonGenerator gen, EnumDescriptor descriptor) throws IOException { EnumValueDescriptor valueDescriptor = descriptor.findValueByNumber(value); if (valueDescriptor == null) { gen.writeNumber(value); } else { gen.writeString(valueDescriptor.getName()); } } public static void printEnum(EnumValueDescriptor value, JsonGenerator gen) throws IOException { if (value.getIndex() == -1) { gen.writeString(Integer.toString(value.getNumber())); } else { gen.writeString(value.getName()); } } public static <T extends Message> void printRepeatedMessage( List<T> values, JsonGenerator gen, TypeSpecificMarshaller<T> serializer) throws IOException { int numElements = values.size(); gen.writeStartArray(); for (int i = 0; i < numElements; i++) { printMessage(values.get(i), gen, serializer); } gen.writeEndArray(); } public static <T extends Message> void printMessage( T value, JsonGenerator gen, TypeSpecificMarshaller<T> serializer) throws IOException { serializer.writeValue(value, gen); } public static SerializedString serializeString(String name) { SerializedString s = new SerializedString(name); // Eagerly compute encodings. s.asQuotedChars(); s.asQuotedUTF8(); s.asUnquotedUTF8(); return s; } @SuppressWarnings("UnnecessaryLambda") private static final Comparator<Entry<String, ?>> STRING_KEY_COMPARATOR = (o1, o2) -> { ByteString s1 = ByteString.copyFromUtf8(o1.getKey()); ByteString s2 = ByteString.copyFromUtf8(o2.getKey()); return ByteString.unsignedLexicographicalComparator().compare(s1, s2); }; @SuppressWarnings({"rawtypes", "unchecked"}) public static Iterator<? extends Entry<?, ?>> mapIterator( Map<?, ?> map, boolean sortingMapKeys, boolean stringKey) { if (!sortingMapKeys) { return map.entrySet().iterator(); } Comparator cmp = stringKey ? STRING_KEY_COMPARATOR : Map.Entry.comparingByKey(); List<Entry<?, ?>> sorted = new ArrayList<>(map.entrySet()); sorted.sort(cmp); return sorted.iterator(); } private SerializeSupport() {} }
32.791339
100
0.696842
2cb4e963c43ed0bb2bfefe453926d483b3a02123
4,672
package tss.tpm; import tss.*; // -----------This is an auto-generated file: do not edit //>>> /** This command allows qualification of the sending (copying) of an Object to an Attached * Component (AC). Qualification includes selection of the receiving AC and the method of * authentication for the AC, and, in certain circumstances, the Object to be sent may be * specified. */ public class TPM2_Policy_AC_SendSelect_REQUEST extends ReqStructure { /** Handle for the policy session being extended * Auth Index: None */ public TPM_HANDLE policySession; /** The Name of the Object to be sent */ public byte[] objectName; /** The Name associated with authHandle used in the TPM2_AC_Send() command */ public byte[] authHandleName; /** The Name of the Attached Component to which the Object will be sent */ public byte[] acName; /** If SET, objectName will be included in the value in policySessionpolicyDigest */ public byte includeObject; public TPM2_Policy_AC_SendSelect_REQUEST() { policySession = new TPM_HANDLE(); } /** @param _policySession Handle for the policy session being extended * Auth Index: None * @param _objectName The Name of the Object to be sent * @param _authHandleName The Name associated with authHandle used in the TPM2_AC_Send() command * @param _acName The Name of the Attached Component to which the Object will be sent * @param _includeObject If SET, objectName will be included in the value in * policySessionpolicyDigest */ public TPM2_Policy_AC_SendSelect_REQUEST(TPM_HANDLE _policySession, byte[] _objectName, byte[] _authHandleName, byte[] _acName, byte _includeObject) { policySession = _policySession; objectName = _objectName; authHandleName = _authHandleName; acName = _acName; includeObject = _includeObject; } /** TpmMarshaller method */ @Override public void toTpm(TpmBuffer buf) { buf.writeSizedByteBuf(objectName); buf.writeSizedByteBuf(authHandleName); buf.writeSizedByteBuf(acName); buf.writeByte(includeObject); } /** TpmMarshaller method */ @Override public void initFromTpm(TpmBuffer buf) { objectName = buf.readSizedByteBuf(); authHandleName = buf.readSizedByteBuf(); acName = buf.readSizedByteBuf(); includeObject = buf.readByte(); } /** @deprecated Use {@link #toBytes()} instead * @return Wire (marshaled) representation of this object */ public byte[] toTpm () { return toBytes(); } /** Static marshaling helper * @param byteBuf Wire representation of the object * @return New object constructed from its wire representation */ public static TPM2_Policy_AC_SendSelect_REQUEST fromBytes (byte[] byteBuf) { return new TpmBuffer(byteBuf).createObj(TPM2_Policy_AC_SendSelect_REQUEST.class); } /** @deprecated Use {@link #fromBytes(byte[])} instead * @param byteBuf Wire representation of the object * @return New object constructed from its wire representation */ public static TPM2_Policy_AC_SendSelect_REQUEST fromTpm (byte[] byteBuf) { return fromBytes(byteBuf); } /** Static marshaling helper * @param buf Wire representation of the object * @return New object constructed from its wire representation */ public static TPM2_Policy_AC_SendSelect_REQUEST fromTpm (TpmBuffer buf) { return buf.createObj(TPM2_Policy_AC_SendSelect_REQUEST.class); } @Override public String toString() { TpmStructurePrinter _p = new TpmStructurePrinter("TPM2_Policy_AC_SendSelect_REQUEST"); toStringInternal(_p, 1); _p.endStruct(); return _p.toString(); } @Override public void toStringInternal(TpmStructurePrinter _p, int d) { _p.add(d, "TPM_HANDLE", "policySession", policySession); _p.add(d, "byte[]", "objectName", objectName); _p.add(d, "byte[]", "authHandleName", authHandleName); _p.add(d, "byte[]", "acName", acName); _p.add(d, "byte", "includeObject", includeObject); } @Override public int numHandles() { return 1; } @Override public int numAuthHandles() { return 0; } @Override public TPM_HANDLE[] getHandles() { return new TPM_HANDLE[] {policySession}; } @Override public SessEncInfo sessEncInfo() { return new SessEncInfo(2, 1); } } //<<<
34.607407
153
0.65732
06541b8904c949b191a31fce3bd348e21d4ca416
2,194
package com.SEproject.guiderapp.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.DrawableCompat; /** * Some helper methods */ public final class Utils { /** * Returns white or black according to which will suit the current app background color * @param color app background color * @return white or black text color */ public static int getTextColor(int color) { int redColorValue = (color >> 16) & 0xFF; int greenColorValue = (color >> 8) & 0xFF; int blueColorValue = (color) & 0xFF; if ((redColorValue * 0.299 + greenColorValue * 0.587 + blueColorValue * 0.114) > 186) //black return 0; else //white return 16777215; } /** * Convert vector drawable to be used as a bitmap * @param context * @param drawableId * @return */ public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) { Drawable drawable = ContextCompat.getDrawable(context, drawableId); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { drawable = (DrawableCompat.wrap(drawable)).mutate(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } @NonNull public static Bitmap getBitmapFromDrawable(@NonNull Drawable drawable) { final Bitmap bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bmp); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bmp; } }
30.901408
133
0.653145
8461d403444a6ef07fa93b717e57bfcbca098938
2,518
package hr.fer.zemris.java.hw14.dao; import java.util.List; import javax.servlet.ServletContext; import javax.sql.DataSource; import hr.fer.zemris.java.hw14.models.Poll; import hr.fer.zemris.java.hw14.models.PollOption; /** * Interface towards data subsystem for retrieving/updating table values. * * @author dbrcina * */ public interface DAO { /** * Checks whether <i>Polls</i> and <i>PollOptions</i> tables exist in * database.<br> * If one of them (or both) doesn't exist, they are created and filled with some * appropriate data (<i>votesCount</i> are randomly generated).<br> * Also, if one of them is empty, it is also filled with some appropriate * data.<br> * Connection is established by {@link DataSource#getConnection()}. * * @param context application context. * @param cpds pool connection. * @throws DAOException if something goes wrong while creating/updating tables. */ void validateDBTables(ServletContext context, DataSource cpds) throws DAOException; /** * Retrieves all {@link Poll} polls from database. * * @return list of polls. * @throws DAOException if something goes wrong while retrieving data. */ List<Poll> getPolls() throws DAOException; /** * Getter for {@link Poll} poll from database as determined by * <code>pollID</code>.<br> * If poll doesn't exist, <code>null</code> is returned. * * @param pollID poll ID. * @return instance of {@link Poll} or <code>null</code>. * @throws DAOException if something goes wrong while retrieving data. */ Poll getPoll(long pollID) throws DAOException; /** * Getter for {@link PollOption} poll options from database as determined by * <code>ID</code>.<br> * If poll option doesn't exist, <code>null</code> is returned.<br> * Parameter <code>field</code> determines whether poll options need to be * selected by <i>"pollID"</i> or <i>"id"</i>. Every other field input is * invalid. * * @param ID ID. * @param field field. * @return list of poll options or <code>null</code>. * @throws DAOException if something goes wrong while retrieving data. */ List<PollOption> getPollOptions(long ID, String field) throws DAOException; /** * Updates <code>pollOption's</code> current number of votes by * <code>votes</code>. * * @param pollOption poll option. * @param votes number of votes. * @throws DAOException if something goes wrong while updating data. */ void addVotes(PollOption pollOption, long votes) throws DAOException; }
32.282051
84
0.704527
8e68a6b4db31ee6f00bc3644a7f585ee01e8baa8
2,249
package com.akasa.kitafit.activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.akasa.kitafit.R; import com.akasa.kitafit.model.member; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class Video extends AppCompatActivity { RecyclerView Mrecyclerview; FirebaseDatabase database; DatabaseReference reference; FirebaseRecyclerOptions<member> options; FirebaseRecyclerAdapter<member, ViewHolder> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); Mrecyclerview = findViewById(R.id.recyclerview_video); Mrecyclerview.setHasFixedSize(true); Mrecyclerview.setLayoutManager(new LinearLayoutManager(this)); database = FirebaseDatabase.getInstance(); reference = database.getReference("video"); } @Override protected void onStart () { super.onStart(); options = new FirebaseRecyclerOptions.Builder<member>() .setQuery(reference, member.class).build(); adapter = new FirebaseRecyclerAdapter<member, ViewHolder>(options) { @Override protected void onBindViewHolder(@NonNull ViewHolder holder, int i, @NonNull member model) { holder.setVideo(getApplication(), model.getTitle(), model.getUrl()); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false); return new ViewHolder(view); } }; adapter.startListening(); Mrecyclerview.setAdapter(adapter); } }
30.808219
106
0.711427
681dd34a8c91545286ffcd7b7bdeaeebb65ece3d
1,357
package com.canyonmodded.server.network.beta.v1_7; import com.canyonmodded.server.network.MinecraftBetaBuffer; import com.canyonmodded.server.network.MinecraftPacket; import com.canyonmodded.server.network.beta.handler.MinecraftBetaSessionHandler; public class PlayerLook implements MinecraftPacket { private float yaw; private float pitch; private boolean onGround; public PlayerLook() { } public PlayerLook(float yaw, float pitch, boolean onGround) { this.yaw = yaw; this.pitch = pitch; this.onGround = onGround; } @Override public void decode(MinecraftBetaBuffer buf, int protocolVersion, Direction direction) { this.yaw = buf.readFloat(); this.pitch = buf.readFloat(); this.onGround = buf.readBoolean(); } @Override public void encode(MinecraftBetaBuffer buf, int protocolVersion, Direction direction) { buf.writeFloat(this.yaw); buf.writeFloat(this.pitch); buf.writeBoolean(this.onGround); } @Override public void handle(MinecraftBetaSessionHandler handler) { handler.handle(this); } @Override public String toString() { return "PlayerLook{" + "yaw=" + yaw + ", pitch=" + pitch + ", onGround=" + onGround + '}'; } }
27.693878
91
0.645542
b7b811e813db592352da387ae7dcc5f1af629efd
4,449
package testsikulixandselenium; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.sikuli.script.ImagePath; import org.sikuli.script.Match; import org.sikuli.script.Pattern; import org.sikuli.script.Region; public class Main { public static void main(String[] args) { System.out.println(ImagePath.getBundlePath()); // print current bundlePath ImagePath.setBundlePath("src/images"); // set custom bundlePath System.out.println(ImagePath.getBundlePath()); // print new bundlePath // 1. URL String myUrl = "https://sede-tu.seg-social.gob.es/wps/portal/"; // 2. Get the driver System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = null; ChromeOptions options = new ChromeOptions(); driver = new ChromeDriver(options); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS); // Set implicit wait driver.get(myUrl); final WebDriver driverFinal = driver; // 3. Get the browser wait Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(4)) .pollingEvery(Duration.ofSeconds(1)).ignoring(NoSuchElementException.class); // 4. click on the icon for accessing by certificate String myXpath = "//a[@title='Acceso como interesado' and @class='btnGo']"; String myXpath2 = "//a[@title='Acceder con Certificado']"; // webElementGetterClicker(myXpath, wait, driver); // webElementGetterClicker(myXpath2, wait, driver); driver.findElement(By.xpath(myXpath)).click(); System.out.println("Finished clicking"); new Thread(new Runnable() { public void run() { // 5. Now displays a window offering the available certificates // and use Sikulix for selecting certificate for XIMO DANTE // using OCR and click on button to accept the certificate // System.out.println("Here we go"); Point top = driverFinal.manage().window().getPosition(); Dimension dim = driverFinal.manage().window().getSize(); try { TimeUnit.SECONDS.sleep(1); // OCR recognition utils.SikulixUtils.click(top.getX(), top.getY(), dim.getWidth(), dim.getHeight(),"FRANCISCO-JAVIER"); utils.SikulixUtils.click(top.getX(), top.getY(), dim.getWidth(), dim.getHeight(),"Aceptar"); // System.out.println("Found name match"); //Region region = new Region(top.getX(), top.getY(), dim.getWidth(), dim.getHeight()); // The image of the button to click //Pattern image = new Pattern("1616752672767.png"); //Match match = region.find(image); // System.out.println("Found image match"); //match.click(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }).start(); driver.findElement(By.xpath(myXpath2)).click(); // WebElement webElement = driver.findElement(By.xpath(myXpath2)); // ((JavascriptExecutor)driver).executeScript("arguments[0].click()",webElement); // System.out.println("Finished clicking"); } public static void webElementGetterClicker(String myXpath, Wait<WebDriver> wait, WebDriver driver) { WebElement webElement = null; /* * try { webElement = wait.until(new Function<WebDriver, WebElement>() { public * WebElement apply(WebDriver browser) { WebElement wE = null; for (WebElement * webElem : browser.findElements(By.xpath(myXpath))) { * System.out.println("WebElem=" + webElem.toString()); wE = webElem; if * ((wE.isDisplayed() && wE.isEnabled())) break; } return wE; } }); webElement = * driver.findElement(By.xpath(myXpath)); } catch (Exception e) { * e.printStackTrace(); } */ /* webElement = */driver.findElement(By.xpath(myXpath)).click(); // Click the element // System.out.println("Proceding with click"); // webElement.click(); System.out.println("Finished clicking"); } }
40.081081
106
0.715442
7c134f272c8e2cdabd49ab95b58a326f2e7a3392
2,409
package org.nem.core.model; import java.util.*; /** * An enumeration of block chain features. */ public enum BlockChainFeature { //region pox /** * The block chain uses the proof of importance consensus algorithm. */ PROOF_OF_IMPORTANCE(0x00000001), /** * The block chain uses the proof of stake consensus algorithm. */ PROOF_OF_STAKE(0x00000002), //endregion //region weighted balances /** * The block chain uses a time-based vesting of balances. */ WB_TIME_BASED_VESTING(0x00000004), /** * The block chain immediately vests all balances. * This is only recommended for an environment where the participating nodes can be trusted, i.e. a private network. */ WB_IMMEDIATE_VESTING(0x00000008), //endregion //region other /** * Gaps between blocks should be more stable. */ STABILIZE_BLOCK_TIMES(0x00000010); //endregion private final int value; BlockChainFeature(final Integer value) { this.value = value; } /** * Gets the underlying value. * * @return The value. */ public int value() { return this.value; } /** * Gets a block chain feature given a string representation. * * @param status The string representation. * @return The block chain feature. */ public static BlockChainFeature fromString(final String status) { final BlockChainFeature feature = valueOf(status); if (null == feature) { throw new IllegalArgumentException(String.format("Invalid block chain feature: '%s'", status)); } return feature; } /** * Merges multiple block chain features into a single integer (bitmask). * * @param featureArray The features to join. * @return The joined features. */ public static int or(final BlockChainFeature... featureArray) { int featureBits = 0; for (final BlockChainFeature features : featureArray) { featureBits |= features.value(); } return featureBits; } /** * Explodes an integer feature bitmask into its component block chain features. * * @param featureBits The bitmask to explode. * @return The block chain features. */ public static BlockChainFeature[] explode(final int featureBits) { final List<BlockChainFeature> features = new ArrayList<>(); for (final BlockChainFeature feature : values()) { if (0 != (feature.value & featureBits)) { features.add(feature); } } return features.toArray(new BlockChainFeature[features.size()]); } }
21.9
117
0.703611
451ca55c99a03d686bdd2fa709c1be4eda0e17cd
4,372
/* * 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 com.android.commands.monkey; import android.app.IActivityManager; import android.hardware.input.InputManager; import android.os.SystemClock; import android.view.IWindowManager; import android.view.InputDevice; import android.view.KeyCharacterMap; import android.view.KeyEvent; /** * monkey key event */ public class MonkeyKeyEvent extends MonkeyEvent { private int mDeviceId; private long mEventTime; private long mDownTime; private int mAction; private int mKeyCode; private int mScanCode; private int mMetaState; private int mRepeatCount; private KeyEvent mKeyEvent; public MonkeyKeyEvent(int action, int keyCode) { this(-1, -1, action, keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0); } public MonkeyKeyEvent(long downTime, long eventTime, int action, int keyCode, int repeatCount, int metaState, int device, int scanCode) { super(EVENT_TYPE_KEY); mDownTime = downTime; mEventTime = eventTime; mAction = action; mKeyCode = keyCode; mRepeatCount = repeatCount; mMetaState = metaState; mDeviceId = device; mScanCode = scanCode; } public MonkeyKeyEvent(KeyEvent e) { super(EVENT_TYPE_KEY); mKeyEvent = e; } public int getKeyCode() { return mKeyEvent != null ? mKeyEvent.getKeyCode() : mKeyCode; } public int getAction() { return mKeyEvent != null ? mKeyEvent.getAction() : mAction; } public long getDownTime() { return mKeyEvent != null ? mKeyEvent.getDownTime() : mDownTime; } public long getEventTime() { return mKeyEvent != null ? mKeyEvent.getEventTime() : mEventTime; } public void setDownTime(long downTime) { if (mKeyEvent != null) { throw new IllegalStateException("Cannot modify down time of this key event."); } mDownTime = downTime; } public void setEventTime(long eventTime) { if (mKeyEvent != null) { throw new IllegalStateException("Cannot modify event time of this key event."); } mEventTime = eventTime; } @Override public boolean isThrottlable() { return (getAction() == KeyEvent.ACTION_UP); } @Override public int injectEvent(IWindowManager iwm, IActivityManager iam, int verbose) { if (verbose > 1) { String note; if (mAction == KeyEvent.ACTION_UP) { note = "ACTION_UP"; } else { note = "ACTION_DOWN"; } try { System.out.println(":Sending Key (" + note + "): " + mKeyCode + " // " + MonkeySourceRandom.getKeyName(mKeyCode)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(":Sending Key (" + note + "): " + mKeyCode + " // Unknown key event"); } } KeyEvent keyEvent = mKeyEvent; if (keyEvent == null) { long eventTime = mEventTime; if (eventTime <= 0) { eventTime = SystemClock.uptimeMillis(); } long downTime = mDownTime; if (downTime <= 0) { downTime = eventTime; } keyEvent = new KeyEvent(downTime, eventTime, mAction, mKeyCode, mRepeatCount, mMetaState, mDeviceId, mScanCode, KeyEvent.FLAG_FROM_SYSTEM, InputDevice.SOURCE_KEYBOARD); } if (!InputManager.getInstance().injectInputEvent(keyEvent, InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT)) { return MonkeyEvent.INJECT_FAIL; } return MonkeyEvent.INJECT_SUCCESS; } }
31.912409
113
0.622598
3f357cf29abffe55f0ae30c0a3bbcdae3baea4c5
1,463
package com.anderson.datastructures; import java.util.Iterator; public class QueueUsingLinkedList<Item> implements Iterable<Item> { private Node first; private Node last; private int N; public QueueUsingLinkedList() { N = 0; } public Boolean isEmpty() { return null == first; } public int size() { return N; } public void enqueue(Item data) { Node oldLast = last; last = new Node(data); last.next = null; if (isEmpty()) { first = last; } else { oldLast.next = last; } N++; } public Item dequeue() { Item item = first.item; first = first.next; if (isEmpty()) last = null; N--; return item; } @Override public Iterator<Item> iterator() { return new QueueIterator(); } private class Node { Item item; Node next; Node(Item data) { item = data; } } private class QueueIterator implements Iterator<Item> { private Node current = first; @Override public boolean hasNext() { return current != null; } @Override public Item next() { Item data = current.item; current = current.next; return data; } @Override public void remove() { } } }
19.77027
67
0.501025
5c4ce27a45c7572053d3a163d430a0b4a8a91bf5
1,823
package org.riverock.webmill.trash; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.List; import javax.xml.bind.JAXBException; import org.hibernate.Session; import org.riverock.common.exception.DatabaseException; import org.riverock.dbrevision.annotation.schema.db.DbForeignKey; import org.riverock.dbrevision.db.Database; import org.riverock.dbrevision.db.DatabaseFactory; import org.riverock.dbrevision.db.DatabaseStructureManager; import org.riverock.dbrevision.utils.Utils; import org.riverock.webmill.portal.dao.HibernateUtils; import org.riverock.webmill.portal.dao.HibernateUtilsTest; /** * User: SMaslyukov * Date: 03.08.2007 * Time: 20:59:52 */ public class GetForeignKeysTest { public static void main(String[] args) throws DatabaseException, SQLException, FileNotFoundException, JAXBException { HibernateUtilsTest.prepareSession(); Session session = HibernateUtils.getSession(); /* Database adapter = DatabaseFactory.getInstance(session.connection(), Database.Family.MYSQL); DatabaseMetaData metaData = adapter.getConnection().getMetaData(); String dbSchema = metaData.getUserName(); System.out.println("dbSchema = " + dbSchema); List<DbForeignKey> fks = DatabaseStructureManager.getDataTable()getForeignKeys(adapter, dbSchema, "aaa"); if (fks.isEmpty()) { throw new RuntimeException("fk is empty"); } if (fks.size()>1) { throw new RuntimeException("fk is not one"); } FileOutputStream outputStream = new FileOutputStream("fk.xml"); Utils.writeObjectAsXml(fks.get(0), outputStream, "DbForeignKey", "utf-8"); */ session.close(); } }
30.383333
121
0.72463
6b3129a45b07846fe77227d079f6785cfb7d87b4
298
package items.weapons; import items.Item; public class Arrow extends Item { private static final long serialVersionUID = 1L; public static final int ARROW_DAMAGE = 5; public Arrow() { super(); this.setDamage(ARROW_DAMAGE); setWeight(.1); setImageID(2, 1); this.name = "Arrow"; } }
17.529412
49
0.704698
b737d04d9d302ea4d89e8b9f003105c5b4aac392
4,854
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.spi.debugger.ui; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JEditorPane; import javax.swing.UIManager; import org.netbeans.editor.EditorUI; import org.netbeans.editor.Utilities; import org.netbeans.editor.ext.ToolTipSupport; import org.netbeans.modules.debugger.ui.views.ToolTipView; /** * A base class for an action that shows an expanded tooltip. * It can be used as a * {@link PinWatchUISupport.ValueProvider#getHeadActions(org.netbeans.api.debugger.Watch) head action} * for a pin watch to display the structured value of a watch. * * @since 2.54 * @author Martin Entlicher */ public abstract class AbstractExpandToolTipAction extends AbstractAction { private final Icon toExpandIcon = UIManager.getIcon ("Tree.collapsedIcon"); // NOI18N private final Icon toCollapsIcon = UIManager.getIcon ("Tree.expandedIcon"); // NOI18N private boolean expanded; /** * Create a new expand tooltip action. */ protected AbstractExpandToolTipAction() { putValue(Action.SMALL_ICON, toExpandIcon); putValue(Action.LARGE_ICON_KEY, toExpandIcon); } /** * Open a tooltip view. * Call {@link #openTooltipView(java.lang.String, java.lang.Object)} method * to open the tooltip view. */ protected abstract void openTooltipView(); /** * Open a tooltip view for the expression and variable the expression evaluates to. * @param expression the tooltip's expression * @param var the evaluated variable * @return An instance of tooltip support that allows to control the display * of the tooltip, or <code>null</code> when it's not possible to show it. * It can be used e.g. to close the tooltip when it's no longer applicable, * when the debugger resumes, etc. */ protected final ToolTipSupport openTooltipView(String expression, Object var) { ToolTipView toolTipView = ToolTipView.createToolTipView(expression, var); JEditorPane currentEditor = EditorContextDispatcher.getDefault().getMostRecentEditor(); EditorUI eui = Utilities.getEditorUI(currentEditor); if (eui != null) { final ToolTipSupport toolTipSupport = eui.getToolTipSupport(); toolTipSupport.setToolTipVisible(true, false); toolTipSupport.setToolTip(toolTipView); toolTipSupport.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (ToolTipSupport.PROP_STATUS.equals(evt.getPropertyName())) { if (!toolTipSupport.isToolTipVisible()) { expanded = false; putValue(Action.SMALL_ICON, toExpandIcon); putValue(Action.LARGE_ICON_KEY, toExpandIcon); toolTipSupport.removePropertyChangeListener(this); } } } }); return toolTipSupport; } else { return null; } } @Override public final void actionPerformed(ActionEvent e) { expanded = !expanded; if (expanded) { openTooltipView(); putValue(Action.SMALL_ICON, toCollapsIcon); putValue(Action.LARGE_ICON_KEY, toCollapsIcon); } else { hideTooltipView(); putValue(Action.SMALL_ICON, toExpandIcon); putValue(Action.LARGE_ICON_KEY, toExpandIcon); } } private void hideTooltipView() { JEditorPane currentEditor = EditorContextDispatcher.getDefault().getMostRecentEditor(); EditorUI eui = Utilities.getEditorUI(currentEditor); if (eui != null) { eui.getToolTipSupport().setToolTipVisible(false, false); } } }
39.786885
102
0.675319
97b6becedc01c5be9a04ddc00b3f6c0d5520724a
251
package icu.random.util.event; public enum EventType { person, address, random_sentence, random_sentences, sentence_limits, lorem_limits, lorem_bytes, lorem_words, lorem_paragraphs, lorem_paragraphs_break, lorem_lists, uuid }
14.764706
30
0.756972
4f5b9bebdaf12a49fa4ef2e24628f67a40aff73e
1,367
package ht.treechop.client.gui.widget; import com.mojang.blaze3d.vertex.PoseStack; import ht.treechop.client.gui.util.GUIUtil; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.network.chat.Component; public class TextWidget extends AbstractWidget { private Font font; public TextWidget(int x, int y, Font font, Component text) { super(x, y, font.width(text.getString()), GUIUtil.TEXT_LINE_HEIGHT, text); this.font = font; } public void render(PoseStack poseStack, int mouseX, int mouseY, float partialTicks, boolean rightAligned) { render(poseStack, mouseX, mouseY, partialTicks, rightAligned ? -font.width(getMessage()) : 0); } @SuppressWarnings("NullableProblems") @Override public void render(PoseStack poseStack, int mouseX, int mouseY, float partialTicks) { render(poseStack, mouseX, mouseY, partialTicks, 0); } @SuppressWarnings({"SuspiciousNameCombination"}) public void render(PoseStack poseStack, int mouseX, int mouseY, float partialTicks, int xOffset) { drawString(poseStack, font, getMessage(), x + xOffset, y, 0xFFFFFF); } @Override public void updateNarration(NarrationElementOutput out) { // TODO } }
35.051282
111
0.726408
289864200c090f4e372ef561be42fd88e16ef136
437
package io.c8y.legacycode.hardtowritetests.construct; import java.io.IOException; import java.net.URL; import io.c8y.legacycode.hardtowritetests.statical.User; public class LegacyDatabase { private String content; public void connect() throws IOException { content = new URL("http://important/db").getContent().toString(); } public UserData getDataFor(User user) { return new UserData(Boolean.parseBoolean(content)); } }
20.809524
67
0.76659
ddbe7ac7bf749c3582e218e78d614627a542d54c
240
package com.mmorpg.framework.net.session; /** * @author Ariescat * @version 2020/2/19 11:52 */ public enum GameSessionStatusUpdateCause { PLayerLogoutMessage, RequestExitWorld, RegisterSession, Robot, TimeoutReset, RoLeCreate }
14.117647
42
0.758333
5332249c9adb9d8be2dc444d72f2ab0224bf64a3
12,028
package de.slux.line.friday.data.war; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import de.slux.line.friday.FridayBotApplication; import de.slux.line.friday.logic.war.WarDeathLogic; /** * The status of the war of a specific group. This is also used to gather group * information in general * * @author slux */ public class WarGroup { public enum HistoryType { HistoryTypeDeathReport(0), HistoryTypePlacementReport(1); private final int value; private HistoryType(int value) { this.value = value; } public int getValue() { return value; } } public enum GroupStatus { GroupStatusInactive(0), GroupStatusActive(1); private final int value; private GroupStatus(int value) { this.value = value; } public int getValue() { return value; } } public enum GroupFeature { GroupFeatureWar(1), GroupFeatureEvent(2), GroupFeatureWarEvent(3); private final int value; private GroupFeature(int value) { this.value = value; } public int getValue() { return value; } } public static final Integer TOTAL_AW_NODES = 55; private List<WarDeath> deathReports; private String groupId; private String groupName; private GroupStatus groupStatus; private GroupFeature groupFeature; private Date lastActivity; /** * Ctor */ public WarGroup() { this.deathReports = new ArrayList<WarDeath>(); } /** * Reset the internal death reports */ public void reset() { this.deathReports.clear(); } /** * @return the deathReports */ public List<WarDeath> getDeathReports() { return deathReports; } /** * Add death report * * @param deaths * @param node * @param champName * @param userName */ public void addDeath(int deaths, int node, String champName, String userName) { this.deathReports.add(new WarDeath(node, deaths, champName, userName)); } /** * Get the war death report * * @return string that describes the report */ public String getReport() { StringBuilder report = new StringBuilder("*** WAR DEATH REPORT ***"); TotalDeathReport totDeathReport = calculateDeathReport(); // Calculate how many missing nodes in the report Set<Integer> reportedNodes = new HashSet<>(); for (WarDeath wd : this.deathReports) { reportedNodes.add(wd.getNodeNumber()); } report.append("\nTotal lost points: " + totDeathReport.getTotalLostPoints()); report.append("\nTotal deaths: " + totDeathReport.getTotalDeaths()); report.append("\nTrue deaths: " + totDeathReport.getTrueDeaths()); report.append("\nReported nodes: " + reportedNodes.size() + "/" + TOTAL_AW_NODES); if (reportedNodes.size() >= TOTAL_AW_NODES - 10 && reportedNodes.size() < TOTAL_AW_NODES) { // We show the missing nodes if the alliance goes hardcore List<Integer> missingNodes = new ArrayList<>(); for (int i = 1; i <= TOTAL_AW_NODES; i++) { if (!reportedNodes.contains(i)) missingNodes.add(i); } report.append("\nNodes to report: " + missingNodes); } return report.toString(); } /** * Calculate the current death report * * @return the current death report */ public TotalDeathReport calculateDeathReport() { int totalLostPoints = 0; int totalDeaths = 0; int trueDeaths = 0; // Node, deaths Map<Integer, Integer> totalDeathsPerNode = new HashMap<Integer, Integer>(); for (WarDeath wdr : this.deathReports) { if (!totalDeathsPerNode.containsKey(wdr.getNodeNumber())) totalDeathsPerNode.put(wdr.getNodeNumber(), 0); totalDeathsPerNode.put(wdr.getNodeNumber(), wdr.getNodeDeaths() + totalDeathsPerNode.get(wdr.getNodeNumber())); } for (Integer deaths : totalDeathsPerNode.values()) { int nodeLostPoints = deaths * WarDeathLogic.WAR_POINTS_LOST_PER_DEATH; if (nodeLostPoints > WarDeathLogic.WAR_POINTS_LOST_CAP) nodeLostPoints = WarDeathLogic.WAR_POINTS_LOST_CAP; totalLostPoints += nodeLostPoints; totalDeaths += deaths; } for (Map.Entry<Integer, Integer> deathsPerNode : totalDeathsPerNode.entrySet()) { trueDeaths += Math.min(deathsPerNode.getValue(), 3); } return new TotalDeathReport(totalLostPoints, totalDeaths, trueDeaths); } /** * Get the summary text but compact view * * @return the compact human readable version of the getSummary() */ public List<String> getSummaryTextCompact() { List<String> outcome = new ArrayList<String>(); StringBuilder sb = new StringBuilder("*** WAR DEATH SUMMARY ***\n"); List<WarDeath> reports = getDeathReports(); // We sort by node number Collections.sort(reports, new Comparator<WarDeath>() { @Override public int compare(WarDeath o1, WarDeath o2) { return o1.getNodeNumber() - o2.getNodeNumber(); } }); for (WarDeath wd : reports) { if (sb.length() > FridayBotApplication.MAX_LINE_MESSAGE_SIZE) { // We need to split it and clear outcome.add(sb.toString()); sb.setLength(0); } if (wd.getNodeDeaths() > 0) { sb.append(wd.getNodeNumber()); sb.append(". "); sb.append(wd.getChampName()); sb.append(" : ["); sb.append(wd.getNodeDeaths()); sb.append("] "); sb.append(wd.getUserName()); sb.append("\n"); } } if (reports.isEmpty()) sb.append("Nothing to report\n\n"); sb.append("\n"); sb.append(getReport()); outcome.add(sb.toString()); return outcome; } /** * Get the summary as text CSV export * * @return the human readable version of the getSummary() */ public String getSummaryTextCsv() { StringBuilder sb = new StringBuilder("Node,Deaths,Champion,Summoner\n"); List<WarDeath> reports = getDeathReports(); // We organize by players Map<String, List<WarDeath>> reportsByPlayer = new TreeMap<>(); for (WarDeath wd : reports) { if (!reportsByPlayer.containsKey(wd.getUserName())) { List<WarDeath> playerReports = new ArrayList<>(); playerReports.add(wd); reportsByPlayer.put(wd.getUserName(), playerReports); } else { reportsByPlayer.get(wd.getUserName()).add(wd); } } for (Entry<String, List<WarDeath>> playerReport : reportsByPlayer.entrySet()) { // We sort by node number Collections.sort(playerReport.getValue(), new Comparator<WarDeath>() { @Override public int compare(WarDeath o1, WarDeath o2) { return o1.getNodeNumber() - o2.getNodeNumber(); } }); for (WarDeath wd : playerReport.getValue()) { sb.append(wd.getNodeNumber()); sb.append(","); sb.append(wd.getNodeDeaths()); sb.append(","); sb.append(wd.getChampName()); sb.append(","); sb.append(playerReport.getKey()); sb.append("\n"); } } return sb.toString(); } /** * Get the summary as text * * @return the human readable version of the getSummary() */ public List<String> getSummaryText() { List<String> outcome = new ArrayList<String>(); StringBuilder sb = new StringBuilder("*** WAR DEATH SUMMARY ***\n"); List<WarDeath> reports = getDeathReports(); // We organize by players Map<String, List<WarDeath>> reportsByPlayer = new TreeMap<>(); for (WarDeath wd : reports) { if (!reportsByPlayer.containsKey(wd.getUserName())) { List<WarDeath> playerReports = new ArrayList<>(); playerReports.add(wd); reportsByPlayer.put(wd.getUserName(), playerReports); } else { reportsByPlayer.get(wd.getUserName()).add(wd); } } for (Entry<String, List<WarDeath>> playerReport : reportsByPlayer.entrySet()) { sb.append(playerReport.getKey()); sb.append('\n'); // We sort by node number Collections.sort(playerReport.getValue(), new Comparator<WarDeath>() { @Override public int compare(WarDeath o1, WarDeath o2) { return o1.getNodeNumber() - o2.getNodeNumber(); } }); for (WarDeath wd : playerReport.getValue()) { if (sb.length() > FridayBotApplication.MAX_LINE_MESSAGE_SIZE) { // We need to split it and clear outcome.add(sb.toString()); sb.setLength(0); } sb.append(wd.getNodeNumber()); sb.append(". "); sb.append(wd.getChampName()); sb.append(" : ["); sb.append(wd.getNodeDeaths()); sb.append("]\n"); } sb.append('\n'); } if (reports.isEmpty()) sb.append("Nothing to report\n\n"); sb.append("\n"); sb.append(getReport()); outcome.add(sb.toString()); return outcome; } /** * Undo last inserted death report */ public void undoLast() { if (this.deathReports.size() > 0) this.deathReports.remove(this.deathReports.size() - 1); } /** * Internal class to get the overall current death report status. This is an * immutable class * * @author Slux * */ public class TotalDeathReport { int trueDeaths; int totalLostPoints; int totalDeaths; /** * @param totalLostPoints * @param totalDeaths * @param trueDeaths */ public TotalDeathReport(int totalLostPoints, int totalDeaths, int trueDeaths) { super(); this.totalLostPoints = totalLostPoints; this.totalDeaths = totalDeaths; this.trueDeaths = trueDeaths; } /** * @return the totalLostPoints */ public int getTotalLostPoints() { return totalLostPoints; } /** * @return the totalDeaths */ public int getTotalDeaths() { return totalDeaths; } /** * @return the trueDeaths */ public int getTrueDeaths() { return trueDeaths; } } /** * @return the groupId */ public String getGroupId() { return groupId; } /** * @param groupId * the groupId to set */ public void setGroupId(String groupId) { this.groupId = groupId; } /** * @return the groupName */ public String getGroupName() { return groupName; } /** * @param groupName * the groupName to set */ public void setGroupName(String groupName) { this.groupName = groupName; } /** * @return the groupStatus */ public GroupStatus getGroupStatus() { return groupStatus; } /** * @param groupStatus * the groupStatus to set */ public void setGroupStatus(GroupStatus groupStatus) { this.groupStatus = groupStatus; } /** * @return the groupFeature */ public GroupFeature getGroupFeature() { return groupFeature; } /** * @param groupFeature * the groupFeature to set */ public void setGroupFeature(GroupFeature groupFeature) { this.groupFeature = groupFeature; } /** * get the status from the integer * * @param status * @return the status enum or null */ public static GroupStatus statusOf(int status) { if (GroupStatus.GroupStatusActive.getValue() == status) { return GroupStatus.GroupStatusActive; } if (GroupStatus.GroupStatusInactive.getValue() == status) { return GroupStatus.GroupStatusInactive; } return null; } /** * get the feature from the integer * * @param feature * @return the feature enum or null */ public static GroupFeature featureOf(int feature) { if (GroupFeature.GroupFeatureWar.getValue() == feature) { return GroupFeature.GroupFeatureWar; } if (GroupFeature.GroupFeatureEvent.getValue() == feature) { return GroupFeature.GroupFeatureEvent; } if (GroupFeature.GroupFeatureWarEvent.getValue() == feature) { return GroupFeature.GroupFeatureWarEvent; } return null; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "WarGroup [deathReports=" + deathReports + ", groupId=" + groupId + ", groupName=" + groupName + ", groupStatus=" + groupStatus + ", groupFeature=" + groupFeature + ", lastActivity=" + lastActivity + "]"; } /** * @return the lastActivity */ public Date getLastActivity() { return lastActivity; } /** * @param lastActivity * the lastActivity to set */ public void setLastActivity(Date lastActivity) { this.lastActivity = lastActivity; } }
23.086372
112
0.671267