hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1bbc7e07ebf3c059f044a60e065945b4407f42 | 2,209 | java | Java | Java_2048_WS/src/java/WS/JogoWS.java | MarcosJr1/Java_2048_WS | d294d5177b52658b9e787572052c6fc0a06b911a | [
"MIT"
] | null | null | null | Java_2048_WS/src/java/WS/JogoWS.java | MarcosJr1/Java_2048_WS | d294d5177b52658b9e787572052c6fc0a06b911a | [
"MIT"
] | null | null | null | Java_2048_WS/src/java/WS/JogoWS.java | MarcosJr1/Java_2048_WS | d294d5177b52658b9e787572052c6fc0a06b911a | [
"MIT"
] | null | null | null | 28.320513 | 92 | 0.582164 | 11,746 | /*
* 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.
*/
//Using package of the WebService
package WS;
//<editor-fold defaultstate="collapsed" desc=".:: Imports ::.">
import com.google.gson.Gson;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import modelos.GameCommands;
import utils.Arquivo;
//</editor-fold>
@Path("/")
public class JogoWS {
//<editor-fold defaultstate="collapsed" desc=".:: Constants ::.">
String filePath = "C:\\logWS\\comando.txt";
public String RESPONSE_ERROR = "{" + "\"Commands Available" + "\":"
+ " \n\t\t[" + "\n\t\tUp,"
+ "\n\t\tDown," + "\n\t\tLeft,"
+ "\n\t\tRight," + "\n\t\tRestart,"
+ "\n\t\tUndo," + "\n\t\tRedo,"
+ "\n\t\tBonus" + "\n]}";
@Context
private UriInfo context;
//</editor-fold>
public JogoWS() {
}
//<editor-fold defaultstate="collapsed" desc=".:: Withdraw ::.">
@GET
@Produces({"application/json"})
@Path("withdraw")
public String withdraw() {
String content = Arquivo.Read(filePath);
return content;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=".:: Insert ::.">
@POST
@Consumes({"application/json"})
@Produces({"application/json"})
@Path("insert")
public String insert(String content) {
System.out.println("Content: " + content);
Gson g = new Gson();
GameCommands gc = (GameCommands) g.fromJson(content, GameCommands.class);
if (gc.getOption() == null || gc.getOption().trim().equals("") || !gc.validMove()) {
throw new WebApplicationException(Response
.status(Response.Status.BAD_REQUEST)
.entity(RESPONSE_ERROR).build());
}
boolean writed = Arquivo.Write(filePath, content);
if (writed) {
return content;
} else {
throw new WebApplicationException(Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("SERVER ERROR").build());
}
}
//</editor-fold>
}
|
3e1bbcb41836ce9b48d7d79be34d25b9198814fb | 10,120 | java | Java | sdk/dnsresolver/azure-resourcemanager-dnsresolver/src/main/java/com/azure/resourcemanager/dnsresolver/models/DnsResolver.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 1 | 2022-01-08T06:43:30.000Z | 2022-01-08T06:43:30.000Z | sdk/dnsresolver/azure-resourcemanager-dnsresolver/src/main/java/com/azure/resourcemanager/dnsresolver/models/DnsResolver.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | null | null | null | sdk/dnsresolver/azure-resourcemanager-dnsresolver/src/main/java/com/azure/resourcemanager/dnsresolver/models/DnsResolver.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | null | null | null | 34.896552 | 120 | 0.604545 | 11,747 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.dnsresolver.models;
import com.azure.core.management.Region;
import com.azure.core.management.SubResource;
import com.azure.core.management.SystemData;
import com.azure.core.util.Context;
import com.azure.resourcemanager.dnsresolver.fluent.models.DnsResolverInner;
import java.util.Map;
/** An immutable client-side representation of DnsResolver. */
public interface DnsResolver {
/**
* Gets the id property: Fully qualified resource Id for the resource.
*
* @return the id value.
*/
String id();
/**
* Gets the name property: The name of the resource.
*
* @return the name value.
*/
String name();
/**
* Gets the type property: The type of the resource.
*
* @return the type value.
*/
String type();
/**
* Gets the location property: The geo-location where the resource lives.
*
* @return the location value.
*/
String location();
/**
* Gets the tags property: Resource tags.
*
* @return the tags value.
*/
Map<String, String> tags();
/**
* Gets the etag property: ETag of the DNS resolver.
*
* @return the etag value.
*/
String etag();
/**
* Gets the systemData property: Metadata pertaining to creation and last modification of the resource.
*
* @return the systemData value.
*/
SystemData systemData();
/**
* Gets the virtualNetwork property: The reference to the virtual network. This cannot be changed after creation.
*
* @return the virtualNetwork value.
*/
SubResource virtualNetwork();
/**
* Gets the dnsResolverState property: The current status of the DNS resolver. This is a read-only property and any
* attempt to set this value will be ignored.
*
* @return the dnsResolverState value.
*/
DnsResolverState dnsResolverState();
/**
* Gets the provisioningState property: The current provisioning state of the DNS resolver. This is a read-only
* property and any attempt to set this value will be ignored.
*
* @return the provisioningState value.
*/
ProvisioningState provisioningState();
/**
* Gets the resourceGuid property: The resourceGuid property of the DNS resolver resource.
*
* @return the resourceGuid value.
*/
String resourceGuid();
/**
* Gets the region of the resource.
*
* @return the region of the resource.
*/
Region region();
/**
* Gets the name of the resource region.
*
* @return the name of the resource region.
*/
String regionName();
/**
* Gets the inner com.azure.resourcemanager.dnsresolver.fluent.models.DnsResolverInner object.
*
* @return the inner object.
*/
DnsResolverInner innerModel();
/** The entirety of the DnsResolver definition. */
interface Definition
extends DefinitionStages.Blank,
DefinitionStages.WithLocation,
DefinitionStages.WithResourceGroup,
DefinitionStages.WithCreate {
}
/** The DnsResolver definition stages. */
interface DefinitionStages {
/** The first stage of the DnsResolver definition. */
interface Blank extends WithLocation {
}
/** The stage of the DnsResolver definition allowing to specify location. */
interface WithLocation {
/**
* Specifies the region for the resource.
*
* @param location The geo-location where the resource lives.
* @return the next definition stage.
*/
WithResourceGroup withRegion(Region location);
/**
* Specifies the region for the resource.
*
* @param location The geo-location where the resource lives.
* @return the next definition stage.
*/
WithResourceGroup withRegion(String location);
}
/** The stage of the DnsResolver definition allowing to specify parent resource. */
interface WithResourceGroup {
/**
* Specifies resourceGroupName.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @return the next definition stage.
*/
WithCreate withExistingResourceGroup(String resourceGroupName);
}
/**
* The stage of the DnsResolver definition which contains all the minimum required properties for the resource
* to be created, but also allows for any other optional properties to be specified.
*/
interface WithCreate
extends DefinitionStages.WithTags,
DefinitionStages.WithVirtualNetwork,
DefinitionStages.WithIfMatch,
DefinitionStages.WithIfNoneMatch {
/**
* Executes the create request.
*
* @return the created resource.
*/
DnsResolver create();
/**
* Executes the create request.
*
* @param context The context to associate with this operation.
* @return the created resource.
*/
DnsResolver create(Context context);
}
/** The stage of the DnsResolver definition allowing to specify tags. */
interface WithTags {
/**
* Specifies the tags property: Resource tags..
*
* @param tags Resource tags.
* @return the next definition stage.
*/
WithCreate withTags(Map<String, String> tags);
}
/** The stage of the DnsResolver definition allowing to specify virtualNetwork. */
interface WithVirtualNetwork {
/**
* Specifies the virtualNetwork property: The reference to the virtual network. This cannot be changed after
* creation..
*
* @param virtualNetwork The reference to the virtual network. This cannot be changed after creation.
* @return the next definition stage.
*/
WithCreate withVirtualNetwork(SubResource virtualNetwork);
}
/** The stage of the DnsResolver definition allowing to specify ifMatch. */
interface WithIfMatch {
/**
* Specifies the ifMatch property: ETag of the resource. Omit this value to always overwrite the current
* resource. Specify the last-seen ETag value to prevent accidentally overwriting any concurrent changes..
*
* @param ifMatch ETag of the resource. Omit this value to always overwrite the current resource. Specify
* the last-seen ETag value to prevent accidentally overwriting any concurrent changes.
* @return the next definition stage.
*/
WithCreate withIfMatch(String ifMatch);
}
/** The stage of the DnsResolver definition allowing to specify ifNoneMatch. */
interface WithIfNoneMatch {
/**
* Specifies the ifNoneMatch property: Set to '*' to allow a new resource to be created, but to prevent
* updating an existing resource. Other values will be ignored..
*
* @param ifNoneMatch Set to '*' to allow a new resource to be created, but to prevent updating an existing
* resource. Other values will be ignored.
* @return the next definition stage.
*/
WithCreate withIfNoneMatch(String ifNoneMatch);
}
}
/**
* Begins update for the DnsResolver resource.
*
* @return the stage of resource update.
*/
DnsResolver.Update update();
/** The template for DnsResolver update. */
interface Update extends UpdateStages.WithTags, UpdateStages.WithIfMatch {
/**
* Executes the update request.
*
* @return the updated resource.
*/
DnsResolver apply();
/**
* Executes the update request.
*
* @param context The context to associate with this operation.
* @return the updated resource.
*/
DnsResolver apply(Context context);
}
/** The DnsResolver update stages. */
interface UpdateStages {
/** The stage of the DnsResolver update allowing to specify tags. */
interface WithTags {
/**
* Specifies the tags property: Tags for DNS Resolver..
*
* @param tags Tags for DNS Resolver.
* @return the next definition stage.
*/
Update withTags(Map<String, String> tags);
}
/** The stage of the DnsResolver update allowing to specify ifMatch. */
interface WithIfMatch {
/**
* Specifies the ifMatch property: ETag of the resource. Omit this value to always overwrite the current
* resource. Specify the last-seen ETag value to prevent accidentally overwriting any concurrent changes..
*
* @param ifMatch ETag of the resource. Omit this value to always overwrite the current resource. Specify
* the last-seen ETag value to prevent accidentally overwriting any concurrent changes.
* @return the next definition stage.
*/
Update withIfMatch(String ifMatch);
}
}
/**
* Refreshes the resource to sync with Azure.
*
* @return the refreshed resource.
*/
DnsResolver refresh();
/**
* Refreshes the resource to sync with Azure.
*
* @param context The context to associate with this operation.
* @return the refreshed resource.
*/
DnsResolver refresh(Context context);
}
|
3e1bbcc2dc7d37bfdd4ce685d2e47dd116998fcc | 7,506 | java | Java | src/main/java/org/ipfsbox/battery/api/IPFSCluster.java | dtubenetwork/java-ipfs-cluster-api | 053da1f19ffee82298eff0a7c05a63a74aa54f2a | [
"MIT"
] | 1 | 2021-12-24T03:19:58.000Z | 2021-12-24T03:19:58.000Z | src/main/java/org/ipfsbox/battery/api/IPFSCluster.java | M-Poplar/java-ipfs-cluster-api | e33c5c19f3a99c7ea4fee12ee49c174395a68914 | [
"MIT"
] | null | null | null | src/main/java/org/ipfsbox/battery/api/IPFSCluster.java | M-Poplar/java-ipfs-cluster-api | e33c5c19f3a99c7ea4fee12ee49c174395a68914 | [
"MIT"
] | 1 | 2020-12-29T07:12:08.000Z | 2020-12-29T07:12:08.000Z | 28.648855 | 88 | 0.492539 | 11,748 | package org.ipfsbox.battery.api;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.ipfs.multiaddr.MultiAddress;
import org.ipfsbox.battery.api.http.HttpUtil;
import java.io.*;
/**
* @author liang
* @Date 2018.5.9
* */
public class IPFSCluster {
public final String host;
public final int port;
private final String version;
public final Pins pins = new Pins();
public final Peers peers = new Peers();
public final Sync sync = new Sync();
public final Recover recover = new Recover();
public final Allocation allocation = new Allocation();
public final Health health = new Health();
public IPFSCluster(String host, int port) {
this(host, port, "");
}
public IPFSCluster(String multiaddr) {
this(new MultiAddress(multiaddr));
}
public IPFSCluster(MultiAddress addr) {
this(addr.getHost(), addr.getTCPPort(), "");
}
public IPFSCluster(String host, int port, String version) {
this.host = host;
this.port = port;
this.version = version;
}
public class Pins {
public JSONArray ls() {
String url = "http://" + host + ":" + port + "/pins";
JSONArray result = new JSONArray();
try {
String request = HttpUtil.get(url);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONObject ls(String cid){
String url = "http://" + host + ":" + port + "/pins" + "/" + cid;
JSONObject result = new JSONObject();
try {
String request = HttpUtil.get(url);
result = JSONObject.parseObject(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONArray add(String cid){
String url = "http://" + host + ":" + port + "/pins/" + cid;
JSONArray result = new JSONArray();
try {
String request = HttpUtil.post(url, null);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONArray rm (String cid) {
String url = "http://" + host + ":" + port + "/pins/" + cid;
JSONArray result = new JSONArray();
try {
String request = HttpUtil.delete(url);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
public class Peers {
public JSONArray ls(){
String url = "http://" + host + ":" + port + "/peers";
JSONArray result = new JSONArray();
try {
String request = HttpUtil.get(url);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONArray rm (String cid) {
String url = "http://" + host + ":" + port + "/peers/" + cid;
JSONArray result = new JSONArray();
try {
String request = HttpUtil.delete(url);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
public class Sync {
public JSONArray sync(){
String url = "http://" + host + ":" + port + "/pins/sync";
JSONArray result = new JSONArray();
try {
String request = HttpUtil.post(url, null);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONObject sync(String cid){
String url = url = "http://" + host + ":" + port + "/pins/" + cid + "/sync";
JSONObject result = new JSONObject();
try {
String request = HttpUtil.post(url, null);
result = JSONObject.parseObject(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
public class Recover {
public JSONArray recover(){
String url = "http://" + host + ":" + port + "/pins/recover";
JSONArray result = new JSONArray();
try {
String request = HttpUtil.post(url, null);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONObject recover(String cid){
String url = "http://" + host + ":" + port + "/pins/" + cid + "/recover";
JSONObject result = new JSONObject();
try {
String request = HttpUtil.post(url, null);
result = JSONObject.parseObject(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
public class Allocation {
public JSONArray ls() {
String url = "http://" + host + ":" + port + "/allocations";
JSONArray result = new JSONArray();
try {
String request = HttpUtil.get(url);
result = JSONArray.parseArray(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONObject ls(String cid){
String url = "http://" + host + ":" + port + "/allocations" + "/" + cid;
JSONObject result = new JSONObject();
try {
String request = HttpUtil.get(url);
result = JSONObject.parseObject(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
public class Health {
public JSONObject graph(){
String url = "http://" + host + ":" + port + "/health/graph";
JSONObject result = new JSONObject();
try {
String request = HttpUtil.get(url);
result = JSONObject.parseObject(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
public JSONObject id() {
String url = "http://" + host + ":" + port + "/id";
JSONObject result = new JSONObject();
try {
String request = HttpUtil.get(url);
result = JSONObject.parseObject(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public JSONObject version() {
String url = "http://" + host + ":" + port + "/version";
JSONObject result = new JSONObject();
try {
String request = HttpUtil.get(url);
result = JSONObject.parseObject(request);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
|
3e1bbce2654750072a91772cd181bfb9efe02995 | 5,002 | java | Java | src/test/java/dev/negrel/fxchess/engine/ChessBoardTest.java | negrel/fxchess | 4b10115364d8764f8dcf742f6a3036fc3a445e00 | [
"MIT"
] | null | null | null | src/test/java/dev/negrel/fxchess/engine/ChessBoardTest.java | negrel/fxchess | 4b10115364d8764f8dcf742f6a3036fc3a445e00 | [
"MIT"
] | null | null | null | src/test/java/dev/negrel/fxchess/engine/ChessBoardTest.java | negrel/fxchess | 4b10115364d8764f8dcf742f6a3036fc3a445e00 | [
"MIT"
] | null | null | null | 34.979021 | 160 | 0.565774 | 11,749 | package dev.negrel.fxchess.engine;
import dev.negrel.fxchess.engine.board_exception.IllegalPositionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ChessBoardTest {
ChessBoard board;
@BeforeEach
void classInit() {
this.board = new ChessBoard();
this.board.clearBoard();
}
@Test
void init() {
board.init();
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
board.smartPrint();
String expectedOutput = """
8 │ [97;40mR[39;m | [97;40mk[39;m | [97;40mB[39;m | [97;40mQ[39;m | [97;40mK[39;m | [97;40mB[39;m | [97;40mk[39;m | [97;40mR[39;m |\s
7 │ [97;40mP[39;m | [97;40mP[39;m | [97;40mP[39;m | [97;40mP[39;m | [97;40mP[39;m | [97;40mP[39;m | [97;40mP[39;m | [97;40mP[39;m |\s
6 │ | | | | | | | |\s
5 │ | | | | | | | |\s
4 │ | | | | | | | |\s
3 │ | | | | | | | |\s
2 │ [30;107mP[39;m | [30;107mP[39;m | [30;107mP[39;m | [30;107mP[39;m | [30;107mP[39;m | [30;107mP[39;m | [30;107mP[39;m | [30;107mP[39;m |\s
1 │ [30;107mR[39;m | [30;107mk[39;m | [30;107mB[39;m | [30;107mQ[39;m | [30;107mK[39;m | [30;107mB[39;m | [30;107mk[39;m | [30;107mR[39;m |\s
──┼────────────────────────────────
0 │ 1 2 3 4 5 6 7 8
""";
assertEquals(expectedOutput, outContent.toString());
}
@Test
void occupation() throws IllegalPositionException {
Movable m = mock(Piece.class);
assertFalse(board.isOccupied(new Coord()));
board.setOccupation(new Coord(), m);
assertTrue(board.isOccupied(new Coord()));
board.setOccupation(new Coord(), null);
assertFalse(board.isOccupied(new Coord()));
}
/* These tests show us the pain that it is to test bad exception.
* IllegalPositionException should be raised in the Coord constructor.
*/
@Test
void occupationThrowIllegalPositionException() {
Movable m = mock(Piece.class);
assertThrows(IllegalPositionException.class, () -> board.setOccupation(new Coord(1000, 1000), m));
assertThrows(IllegalPositionException.class, () -> board.setOccupation(new Coord(5, 1000), m));
assertThrows(IllegalPositionException.class, () -> board.setOccupation(new Coord(1000, 5), m));
assertThrows(IllegalPositionException.class, () -> board.setOccupation(new Coord(-1, -1), m));
assertThrows(IllegalPositionException.class, () -> board.setOccupation(new Coord(-1, 5), m));
assertThrows(IllegalPositionException.class, () -> board.setOccupation(new Coord(5, -1), m));
assertThrows(IllegalPositionException.class, () -> board.isOccupied(new Coord(1000, 1000)));
assertThrows(IllegalPositionException.class, () -> board.isOccupied(new Coord(1000, 5)));
assertThrows(IllegalPositionException.class, () -> board.isOccupied(new Coord(5, 1000)));
assertThrows(IllegalPositionException.class, () -> board.isOccupied(new Coord(-1, -1)));
assertThrows(IllegalPositionException.class, () -> board.isOccupied(new Coord(-1, 5)));
assertThrows(IllegalPositionException.class, () -> board.isOccupied(new Coord(5, -1)));
}
@Test
void smartPrintEmptyBoard() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
board.smartPrint();
String expectedOutput = """
8 │ | | | | | | | |\s
7 │ | | | | | | | |\s
6 │ | | | | | | | |\s
5 │ | | | | | | | |\s
4 │ | | | | | | | |\s
3 │ | | | | | | | |\s
2 │ | | | | | | | |\s
1 │ | | | | | | | |\s
──┼────────────────────────────────
0 │ 1 2 3 4 5 6 7 8
""";
assertEquals(expectedOutput, outContent.toString());
}
@Test
void smartPrintBoard() throws IllegalPositionException {
Movable mockT = mock(Piece.class);
when(mockT.toString()).thenReturn("T");
Movable mockZ = mock(Piece.class);
when(mockZ.toString()).thenReturn("Z");
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
board.setOccupation(new Coord(0, 0), mockT);
board.setOccupation(new Coord(2, 3), mockZ);
board.smartPrint();
String expectedOutput = """
8 │ | | | | | | | |\s
7 │ | | | | | | | |\s
6 │ | | | | | | | |\s
5 │ | | | | | | | |\s
4 │ | | Z | | | | | |\s
3 │ | | | | | | | |\s
2 │ | | | | | | | |\s
1 │ T | | | | | | | |\s
──┼────────────────────────────────
0 │ 1 2 3 4 5 6 7 8
""";
assertEquals(expectedOutput, outContent.toString());
}
}
|
3e1bbd4d3f0ff6b9197117bbc79fc113c31ad572 | 402 | java | Java | src/main/java/io/healthathome/dto/Message.java | untaljohanperez/HealthAtHome | e1765f0942cd59625ebbbfe91f98b42c863e4ed0 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/healthathome/dto/Message.java | untaljohanperez/HealthAtHome | e1765f0942cd59625ebbbfe91f98b42c863e4ed0 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/healthathome/dto/Message.java | untaljohanperez/HealthAtHome | e1765f0942cd59625ebbbfe91f98b42c863e4ed0 | [
"Apache-2.0"
] | null | null | null | 18.272727 | 49 | 0.629353 | 11,750 | package io.healthathome.dto;
public class Message {
private String message;
private Message(String message) {
this.message = message;
}
public static Message build(String message) {
return new Message(message);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
3e1bbde66f6f1dca859e473b1104c4e2a78f5136 | 439 | java | Java | test/server/src/main/java/uk/co/blackpepper/bowman/test/server/model/NullLinkedCollectionEntity.java | mohsenie/bowman | baea63178234ad119d93eef1617effd677f904df | [
"Apache-2.0"
] | 42 | 2017-08-14T17:05:17.000Z | 2021-07-16T12:46:42.000Z | test/server/src/main/java/uk/co/blackpepper/bowman/test/server/model/NullLinkedCollectionEntity.java | mohsenie/bowman | baea63178234ad119d93eef1617effd677f904df | [
"Apache-2.0"
] | 39 | 2017-08-31T21:18:03.000Z | 2021-05-19T08:23:15.000Z | test/server/src/main/java/uk/co/blackpepper/bowman/test/server/model/NullLinkedCollectionEntity.java | mohsenie/bowman | baea63178234ad119d93eef1617effd677f904df | [
"Apache-2.0"
] | 19 | 2017-08-31T13:52:02.000Z | 2020-11-19T15:48:05.000Z | 20.904762 | 52 | 0.813212 | 11,751 | package uk.co.blackpepper.bowman.test.server.model;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class NullLinkedCollectionEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany
private Set<SimpleEntity> linked;
}
|
3e1bbfd2388792111bc5a7d16d7d39e1b79bf1d9 | 16,191 | java | Java | generated-tests/qmosa/tests/s1014/78_caloriecount/evosuite-tests/com/lts/io/ArchiveScanner_ESTest.java | blindsubmissions/icse19replication | 42a7c172efa86d7d01f7e74b58612cc255c6eb0f | [
"MIT"
] | null | null | null | generated-tests/qmosa/tests/s1014/78_caloriecount/evosuite-tests/com/lts/io/ArchiveScanner_ESTest.java | blindsubmissions/icse19replication | 42a7c172efa86d7d01f7e74b58612cc255c6eb0f | [
"MIT"
] | null | null | null | generated-tests/qmosa/tests/s1014/78_caloriecount/evosuite-tests/com/lts/io/ArchiveScanner_ESTest.java | blindsubmissions/icse19replication | 42a7c172efa86d7d01f7e74b58612cc255c6eb0f | [
"MIT"
] | null | null | null | 37.653488 | 206 | 0.650794 | 11,752 | /*
* This file was automatically generated by EvoSuite
* Fri Aug 24 14:45:56 GMT 2018
*/
package com.lts.io;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.lts.io.ArchiveScanner;
import com.lts.io.ImprovedFile;
import java.io.File;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.System;
import org.evosuite.runtime.mock.java.io.MockFile;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.FileSystemHandling;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class ArchiveScanner_ESTest extends ArchiveScanner_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile(".WAR");
ImprovedFile improvedFile1 = new ImprovedFile(improvedFile0, "");
File file0 = ImprovedFile.buildName("You have unsaved changes. Save them now?", 1000000L, "# ", improvedFile1);
ImprovedFile improvedFile2 = ImprovedFile.createTempImprovedFile("You have unsaved changes. Save them now?", "B&wC\"lk/x", file0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile2);
// Undeclared exception!
try {
archiveScanner0.scandir(improvedFile0, "", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 1
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
String string0 = "!";
ImprovedFile improvedFile0 = new ImprovedFile("!", "!");
improvedFile0.setWritable(true);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
archiveScanner0.toFileType(improvedFile0);
boolean boolean0 = true;
// Undeclared exception!
try {
archiveScanner0.processDirectory(improvedFile0, "!", true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 2
/*Coverage entropy=1.3321790402101223
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
String string0 = "%q|xlAOX@ 0&i:)";
MockFile mockFile0 = new MockFile("%q|xlAOX@ 0&i:)", "%q|xlAOX@ 0&i:)");
File file0 = ImprovedFile.buildName("%q|xlAOX@ 0&i:)", (-1L), "%q|xlAOX@ 0&i:)", mockFile0);
ImprovedFile improvedFile0 = ImprovedFile.createTempImprovedFile("E6l", "E6l", file0);
improvedFile0.setWritable(true, true);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
archiveScanner0.toFileType(improvedFile0);
// Undeclared exception!
try {
archiveScanner0.processFile("%q|xlAOX@ 0&i:)");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 3
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
MockFile mockFile0 = new MockFile("%q|xlAOX@ 0&i:)", "%q|xlAOX@ 0&i:)");
File file0 = ImprovedFile.buildName("%q|xlAOX@ 0&i:)", (-1L), "%q|xlAOX@ 0&i:)", mockFile0);
ImprovedFile improvedFile0 = ImprovedFile.createTempImprovedFile("E6l", "E6l", file0);
improvedFile0.setWritable(true, true);
ImprovedFile improvedFile1 = ImprovedFile.createTempImprovedFile(".jar", "/resources/swing.properties", file0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile1);
try {
archiveScanner0.scandir(improvedFile1, "E6l", true);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// IO error scanning directory /home/ubuntu/ext1/evosuite_readability_gen/projects/78_caloriecount/%q|xlAOX@ 0&i:)/%q|xlAOX@ 0&i:)/%q|xlAOX@ 0&i:)-1.%q|xlAOX@ 0&i:)/.jar1/resources/swing.properties
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 4
/*Coverage entropy=1.464816384890813
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("# ");
ImprovedFile improvedFile1 = new ImprovedFile(improvedFile0, "# ");
File file0 = ImprovedFile.buildName((String) null, 1L, "com.lts.application.errors.settingLookAndFeel", improvedFile0);
ImprovedFile.createTempImprovedFile("o+@O ", "o+@O ", file0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile1);
// Undeclared exception!
try {
archiveScanner0.scandir(file0, "N=>4IOWmd2]", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 5
/*Coverage entropy=1.3592367006650063
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
File file0 = ImprovedFile.buildName((String) null, 0L, "98k\"", (File) null);
ImprovedFile improvedFile0 = ImprovedFile.createTempImprovedFile("98k\"", "urZ]q3TUoJ$2S.jar", file0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
boolean boolean0 = true;
// Undeclared exception!
try {
archiveScanner0.scandir(file0, "98k\"", true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 6
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
String[] stringArray0 = new String[6];
stringArray0[0] = ".H4,G3qY";
stringArray0[1] = ";k1";
stringArray0[2] = "Hv;x2@hW=cu8o2u~";
stringArray0[3] = "com.lts.io.ArchiveScanner";
stringArray0[4] = "";
stringArray0[5] = ".EAR";
archiveScanner0.includes = stringArray0;
// Undeclared exception!
try {
archiveScanner0.processArchive((File) null, "Ppf5O\";~");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 7
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
String string0 = "B&w\\C\"lk/x";
FileSystemHandling.appendStringToFile((EvoSuiteFile) null, "B&wC\"lk/x");
ImprovedFile improvedFile0 = new ImprovedFile("D:]SW,:C3FRn$zyQ`");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, true, true);
File file0 = ImprovedFile.buildName("Encountered error while trying to remove temp files at ", 2702L, "B&wC\"lk/x", improvedFile0);
ImprovedFile improvedFile1 = ImprovedFile.createTempDirectory("D:]SW,:C3FRn$zyQ`", "D:]SW,:C3FRn$zyQ`", file0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
archiveScanner0.scandir(improvedFile1, "vbQh", false);
try {
ImprovedFile.backup((File) improvedFile1, true);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// java.io.FileNotFoundException
//
verifyException("com.lts.io.ImprovedFile", e);
}
}
/**
//Test case number: 8
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("You have unsaved changes. Save them now?");
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, ".WAR.jar");
File file0 = ImprovedFile.buildName("You have unsaved changes. Save them now?", 1000000L, "You have unsaved changes. Save them now?", improvedFile0);
MockFile.createTempFile("You have unsaved changes. Save them now?", "You have unsaved changes. Save them now?", file0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[4];
stringArray0[0] = "You have unsaved changes. Save them now?";
stringArray0[1] = "You have unsaved changes. Save them now?";
stringArray0[2] = "You have unsaved changes. Save them now?";
archiveScanner0.includes = archiveScanner0.DEFAULT_ARCHIVE_EXTENSIONS;
archiveScanner0.myTempdir = improvedFile0;
System.setCurrentTimeMillis(1000000L);
// Undeclared exception!
try {
archiveScanner0.processFile("You have unsaved changes. Save them now?");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 9
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[3];
stringArray0[0] = "";
stringArray0[1] = "";
stringArray0[2] = "";
archiveScanner0.includes = stringArray0;
// Undeclared exception!
try {
archiveScanner0.processDirectory(improvedFile0, "P15E}izWnJ\"/Mq>|m", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 10
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
String string0 = "46[im/<oY~)*.;RR[:X";
ImprovedFile improvedFile0 = new ImprovedFile("46[im/<oY~)*.;RR[:X");
improvedFile0.mkdir();
improvedFile0.setReadOnly();
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, ".WAR.jar");
ImprovedFile improvedFile1 = new ImprovedFile(".WAR.jar", ".WAR.jar");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[4];
archiveScanner0.addDefaultExcludes();
stringArray0[0] = ".WAR.jar";
stringArray0[1] = ".WAR.jar";
stringArray0[2] = "46[im/<oY~)*.;RR[:X";
archiveScanner0.includes = stringArray0;
System.setCurrentTimeMillis(0L);
System.setCurrentTimeMillis(1);
// Undeclared exception!
try {
archiveScanner0.processFile("46[im/<oY~)*.;RR[:X");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 11
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[3];
archiveScanner0.excludes = stringArray0;
stringArray0[0] = "";
stringArray0[1] = "";
archiveScanner0.includes = stringArray0;
// Undeclared exception!
try {
archiveScanner0.processArchive(improvedFile0, "");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 12
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("0r");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[3];
archiveScanner0.excludes = archiveScanner0.DEFAULT_ARCHIVE_EXTENSIONS;
archiveScanner0.setBasedir((File) improvedFile0);
stringArray0[0] = "0r";
stringArray0[1] = "0r";
archiveScanner0.includes = stringArray0;
improvedFile0.createTempDir("[A|9", "0r");
// Undeclared exception!
try {
archiveScanner0.processArchive(improvedFile0, "0r");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 13
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[3];
archiveScanner0.excludes = stringArray0;
stringArray0[0] = "";
stringArray0[1] = "";
archiveScanner0.includes = stringArray0;
// Undeclared exception!
try {
archiveScanner0.processDirectory(improvedFile0, "", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 14
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("46[im/<oY~)*.;RR[:X");
improvedFile0.getCanonicalPath();
improvedFile0.mkdir();
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "46[im/<oY~)*.;RR[:X");
FileSystemHandling.appendStringToFile((EvoSuiteFile) null, "46[im/<oY~)*.;RR[:X");
ImprovedFile improvedFile1 = new ImprovedFile(".WAR.jar", ".WAR.jar");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[4];
archiveScanner0.addDefaultExcludes();
stringArray0[0] = ".WAR.jar";
stringArray0[1] = ".WAR.jar";
stringArray0[2] = "46[im/<oY~)*.;RR[:X";
archiveScanner0.includes = stringArray0;
// Undeclared exception!
try {
archiveScanner0.processDirectory(improvedFile0, "46[im/<oY~)*.;RR[:X", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
}
|
3e1bc034d3e38716d5a99ea7dbd46154c70a2670 | 339 | java | Java | src/com/diamonddevgroup/device/DeviceNative.java | diamondobama/CN1-Device | 224905b5990c9e422b5e9f0a7179168380c0d49e | [
"MIT"
] | 4 | 2018-05-16T16:08:49.000Z | 2020-05-27T16:55:48.000Z | src/com/diamonddevgroup/device/DeviceNative.java | diamondobama/CN1-Device | 224905b5990c9e422b5e9f0a7179168380c0d49e | [
"MIT"
] | 4 | 2018-12-11T09:03:24.000Z | 2020-11-16T15:54:24.000Z | src/com/diamonddevgroup/device/DeviceNative.java | diamondobama/CN1-Device | 224905b5990c9e422b5e9f0a7179168380c0d49e | [
"MIT"
] | 1 | 2019-05-05T13:54:36.000Z | 2019-05-05T13:54:36.000Z | 17.842105 | 55 | 0.728614 | 11,753 | package com.diamonddevgroup.device;
import com.codename1.system.NativeInterface;
/**
* @deprecated internal implementation detail
* @author Diamond
*/
public interface DeviceNative extends NativeInterface {
public String manufacturer();
public String name();
public String model();
public boolean isNotch();
}
|
3e1bc03500c7fad5c6309803c7a5193e0bf27742 | 2,299 | java | Java | LintCode-master/Java/Max Area of Island.java | specter01wj/LintCode_playground | 6049d7767329f6271fd6fda38de9ba4c144058fe | [
"MIT"
] | 4 | 2018-08-06T10:48:49.000Z | 2019-06-04T01:19:27.000Z | LintCode-master/Java/Max Area of Island.java | specter01wj/LintCode_playground | 6049d7767329f6271fd6fda38de9ba4c144058fe | [
"MIT"
] | null | null | null | LintCode-master/Java/Max Area of Island.java | specter01wj/LintCode_playground | 6049d7767329f6271fd6fda38de9ba4c144058fe | [
"MIT"
] | null | null | null | 29.474359 | 214 | 0.560244 | 11,754 | E
虽然Easy, 但用到DFS最基本的想法.
1. dive deep
2. mark VISITED
3. sum it up
更要注意, 要从符合条件value==1的地方开始dfs.
对于什么island都没有的情况,area应该位0, 而不是Integer.MIN_VALUE, 问清楚考官那小伙, 别写顺手。
```
/*
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
*/
/*
Thoughts:
DFS to all directions:
dx = {0, 1, 0, -1}
dy = {1, 0, -1, 0}
1. Each DFS deep dive returns the result area
2. Compare result with max area
Note: when island is found and counted into area, it needs to be flipped to other digits just to avoid revisiting.
*/
class Solution {
private static int[] DX = {0, 1, 0, -1};
private static int[] DY = {1, 0, -1, 0};
private static int VISITED = -1;
public int maxAreaOfIsland(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int maxArea = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
maxArea = Math.max(maxArea, dfs(grid, i, j));
}
}
}
return maxArea;
}
private int dfs(int[][] grid, int x, int y) {
if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && grid[x][y] == 1) {
grid[x][y] = VISITED;
int currentLevelSum = 1;
for (int i = 0; i < DX.length; i++) {
currentLevelSum += dfs(grid, x + DX[i], y + DY[i]);
}
return currentLevelSum;
}
return 0;
}
}
``` |
3e1bc05f691e6fda218c5fe73d8f7069c7848a80 | 1,977 | java | Java | tinkerforge-driver/src/main/java/c8y/tinkerforge/bricklet/HumidityBricklet.java | sjdhanasekaran/cumulocity-parkingPi-javaAgent | 3c6b5330ac0f9281d5c782ae6f9bd5f9c96cd334 | [
"MIT"
] | 5 | 2022-01-26T13:51:07.000Z | 2022-03-10T07:45:39.000Z | tinkerforge-driver/src/main/java/c8y/tinkerforge/bricklet/HumidityBricklet.java | sjdhanasekaran/cumulocity-parkingPi-javaAgent | 3c6b5330ac0f9281d5c782ae6f9bd5f9c96cd334 | [
"MIT"
] | 11 | 2021-10-08T12:59:51.000Z | 2022-03-25T07:44:11.000Z | tinkerforge-driver/src/main/java/c8y/tinkerforge/bricklet/HumidityBricklet.java | sjdhanasekaran/cumulocity-parkingPi-javaAgent | 3c6b5330ac0f9281d5c782ae6f9bd5f9c96cd334 | [
"MIT"
] | 6 | 2018-05-23T08:53:57.000Z | 2020-08-30T22:39:45.000Z | 34.684211 | 105 | 0.750126 | 11,755 | /*
* Copyright (C) 2013 Cumulocity GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package c8y.tinkerforge.bricklet;
import java.math.BigDecimal;
import c8y.HumidityMeasurement;
import c8y.HumiditySensor;
import com.tinkerforge.BrickletHumidity;
import com.tinkerforge.Device;
public class HumidityBricklet extends BaseSensorBricklet {
private HumidityMeasurement humidity = new HumidityMeasurement();
public HumidityBricklet(String id, Device device) {
super(id, device, "Humidity", new HumiditySensor());
}
@Override
public void initialize() throws Exception {
// Nothing to do here.
}
@Override
public void run() {
try {
BrickletHumidity hb = (BrickletHumidity) getDevice();
BigDecimal h = new BigDecimal((double) hb.getHumidity() / 10.0);
humidity.setHumidity(h);
super.sendMeasurement(humidity);
} catch (Exception x) {
logger.warn("Cannot read humidity from bricklet", x);
}
}
}
|
3e1bc167f44a03f54e0d895354deac384d53aebe | 8,665 | java | Java | Utility/src/de/dfki/mapmatching/QuadNode.java | poxrucker/multi-modal-mobility-simulator | de64b746b4dc0f665d98d0ee9c432be37e74685d | [
"Apache-2.0"
] | null | null | null | Utility/src/de/dfki/mapmatching/QuadNode.java | poxrucker/multi-modal-mobility-simulator | de64b746b4dc0f665d98d0ee9c432be37e74685d | [
"Apache-2.0"
] | null | null | null | Utility/src/de/dfki/mapmatching/QuadNode.java | poxrucker/multi-modal-mobility-simulator | de64b746b4dc0f665d98d0ee9c432be37e74685d | [
"Apache-2.0"
] | null | null | null | 31.423913 | 108 | 0.597486 | 11,756 | package de.dfki.mapmatching;
/* *********************************************************************** *
* QuadNode.java *
* *********************************************************************** *
* date created : August, 2012 *
* email : efpyi@example.com *
* author : Kirsty Williams *
* version : 1.0 *
* *********************************************************************** */
import java.util.ArrayList;
public class QuadNode<T> {
private QuadLeaf<T> leaf = null;
private boolean hasChildren = false;
private QuadNode<T> NW = null;
private QuadNode<T> NE = null;
private QuadNode<T> SE = null;
private QuadNode<T> SW = null;
private final Box bounds;
public QuadNode(double minX, double minY, double maxX, double maxY) {
this.bounds = new Box(minX, minY, maxX, maxY);
}
public boolean put(QuadLeaf<T> leaf) {
if (this.hasChildren) return getChild(leaf.x, leaf.y).put(leaf);
if (this.leaf == null) {
this.leaf = leaf;
return true;
}
if (this.leaf.x == leaf.x && this.leaf.y == leaf.y) {
boolean changed = false;
for (T value : leaf.values) {
if (!this.leaf.values.contains(value)) {
changed = this.leaf.values.add(value) || changed;
}
}
return changed;
}
this.divide();
return getChild(leaf.x, leaf.y).put(leaf);
}
public boolean put(double x, double y, T value) {
return put(new QuadLeaf<T>(x, y, value));
}
public boolean remove(double x, double y, T value) {
if (this.hasChildren) return getChild(x, y).remove(x, y, value);
if (this.leaf != null && this.leaf.x == x && this.leaf.y == y) {
if (this.leaf.values.remove(value)) {
if (this.leaf.values.size() == 0) {
this.leaf = null;
}
return true;
}
}
return false;
}
public Box getBounds() {
return this.bounds;
}
public void clear() {
if (this.hasChildren) {
this.NW.clear();
this.NE.clear();
this.SE.clear();
this.SW.clear();
this.NW = null;
this.NE = null;
this.SE = null;
this.SW = null;
this.hasChildren = false;
} else {
if (this.leaf != null) {
this.leaf.values.clear();
this.leaf = null;
}
}
}
public T get(double x, double y, AbstractDouble bestDistance) {
if (this.hasChildren) {
T closest = null;
QuadNode<T> bestChild = this.getChild(x, y);
if (bestChild != null) {
closest = bestChild.get(x, y, bestDistance);
}
if (bestChild != this.NW && this.NW.bounds.calcDist(x, y) < bestDistance.value) {
T value = this.NW.get(x, y, bestDistance);
if (value != null) { closest = value; }
}
if (bestChild != this.NE && this.NE.bounds.calcDist(x, y) < bestDistance.value) {
T value = this.NE.get(x, y, bestDistance);
if (value != null) { closest = value; }
}
if (bestChild != this.SE && this.SE.bounds.calcDist(x, y) < bestDistance.value) {
T value = this.SE.get(x, y, bestDistance);
if (value != null) { closest = value; }
}
if (bestChild != this.SW && this.SW.bounds.calcDist(x, y) < bestDistance.value) {
T value = this.SW.get(x, y, bestDistance);
if (value != null) { closest = value; }
}
return closest;
}
if (this.leaf != null && this.leaf.values.size() > 0) {
T value = this.leaf.values.get(0);
double distance = Math.sqrt(
(this.leaf.x - x) * (this.leaf.x - x)
+ (this.leaf.y - y) * (this.leaf.y - y));
if (distance < bestDistance.value) {
bestDistance.value = distance;
return value;
}
}
return null;
}
public ArrayList<T> get(double x, double y, double maxDistance, ArrayList<T> values) {
if (this.hasChildren) {
if (this.NW.bounds.calcDist(x, y) <= maxDistance) {
this.NW.get(x, y, maxDistance, values);
}
if (this.NE.bounds.calcDist(x, y) <= maxDistance) {
this.NE.get(x, y, maxDistance, values);
}
if (this.SE.bounds.calcDist(x, y) <= maxDistance) {
this.SE.get(x, y, maxDistance, values);
}
if (this.SW.bounds.calcDist(x, y) <= maxDistance) {
this.SW.get(x, y, maxDistance, values);
}
return values;
}
if (this.leaf != null && this.leaf.values.size() > 0) {
double distance = Math.sqrt(
(this.leaf.x - x) * (this.leaf.x - x)
+ (this.leaf.y - y) * (this.leaf.y - y));
if (distance <= maxDistance) {
values.addAll(this.leaf.values);
}
}
return values;
}
public ArrayList<T> get(Box bounds, ArrayList<T> values) {
if (this.hasChildren) {
if (this.NW.bounds.intersects(bounds)) {
this.NW.get(bounds, values);
}
if (this.NE.bounds.intersects(bounds)) {
this.NE.get(bounds, values);
}
if (this.SE.bounds.intersects(bounds)) {
this.SE.get(bounds, values);
}
if (this.SW.bounds.intersects(bounds)) {
this.SW.get(bounds, values);
}
return values;
}
if (this.leaf != null && this.leaf.values.size() > 0 && bounds.contains(this.leaf.x, this.leaf.y)) {
values.addAll(this.leaf.values);
}
return values;
}
public int execute(Box globalBounds, QuadTree.Executor<T> executor) {
int count = 0;
if (this.hasChildren) {
if (this.NW.bounds.intersects(globalBounds)) {
count += this.NW.execute(globalBounds, executor);
}
if (this.NE.bounds.intersects(globalBounds)) {
count += this.NE.execute(globalBounds, executor);
}
if (this.SE.bounds.intersects(globalBounds)) {
count += this.SE.execute(globalBounds, executor);
}
if (this.SW.bounds.intersects(globalBounds)) {
count += this.SW.execute(globalBounds, executor);
}
return count;
}
if (this.leaf != null && this.leaf.values.size() > 0 && globalBounds.contains(this.leaf.x, this.leaf.y)) {
count += this.leaf.values.size();
for (T object : this.leaf.values) executor.execute(this.leaf.x, this.leaf.y, object);
}
return count;
}
private void divide() {
this.NW = new QuadNode<T>(this.bounds.minX, this.bounds.centreY, this.bounds.centreX, this.bounds.maxY);
this.NE = new QuadNode<T>(this.bounds.centreX, this.bounds.centreY, this.bounds.maxX, this.bounds.maxY);
this.SE = new QuadNode<T>(this.bounds.centreX, this.bounds.minY, this.bounds.maxX, this.bounds.centreY);
this.SW = new QuadNode<T>(this.bounds.minX, this.bounds.minY, this.bounds.centreX, this.bounds.centreY);
this.hasChildren = true;
if (this.leaf != null) {
getChild(this.leaf.x, this.leaf.y).put(this.leaf);
this.leaf = null;
}
}
private QuadNode<T> getChild(double x, double y) {
if (this.hasChildren) {
if (x < this.bounds.centreX) {
if (y < this.bounds.centreY)
return this.SW;
return this.NW;
}
if (y < this.bounds.centreY)
return this.SE;
return this.NE;
}
return null;
}
public QuadLeaf<T> firstLeaf() {
if (this.hasChildren) {
QuadLeaf<T> leaf = this.SW.firstLeaf();
if (leaf == null) { leaf = this.NW.firstLeaf(); }
if (leaf == null) { leaf = this.SE.firstLeaf(); }
if (leaf == null) { leaf = this.NE.firstLeaf(); }
return leaf;
}
return this.leaf;
}
public boolean nextLeaf(QuadLeaf<T> currentLeaf, AbstractLeaf<T> nextLeaf) {
if (this.hasChildren) {
boolean found = false;
if (currentLeaf.x <= this.bounds.centreX && currentLeaf.y <= this.bounds.centreY) {
found = this.SW.nextLeaf(currentLeaf, nextLeaf);
if (found) {
if (nextLeaf.value == null) { nextLeaf.value = this.NW.firstLeaf(); }
if (nextLeaf.value == null) { nextLeaf.value = this.SE.firstLeaf(); }
if (nextLeaf.value == null) { nextLeaf.value = this.NE.firstLeaf(); }
return true;
}
}
if (currentLeaf.x <= this.bounds.centreX && currentLeaf.y >= this.bounds.centreY) {
found = this.NW.nextLeaf(currentLeaf, nextLeaf);
if (found) {
if (nextLeaf.value == null) { nextLeaf.value = this.SE.firstLeaf(); }
if (nextLeaf.value == null) { nextLeaf.value = this.NE.firstLeaf(); }
return true;
}
}
if (currentLeaf.x >= this.bounds.centreX && currentLeaf.y <= this.bounds.centreY) {
found = this.SE.nextLeaf(currentLeaf, nextLeaf);
if (found) {
if (nextLeaf.value == null) { nextLeaf.value = this.NE.firstLeaf(); }
return true;
}
}
if (currentLeaf.x >= this.bounds.centreX && currentLeaf.y >= this.bounds.centreY) {
return this.NE.nextLeaf(currentLeaf, nextLeaf);
}
return false;
}
return currentLeaf == this.leaf;
}
public QuadLeaf<T> nextLeaf(QuadLeaf<T> currentLeaf) {
AbstractLeaf<T> nextLeaf = new AbstractLeaf<T>(null);
nextLeaf(currentLeaf, nextLeaf);
return nextLeaf.value;
}
} |
3e1bc2c08ef8a2535f8dcb5ff4e47f046d16c204 | 785 | java | Java | Java/Eta/Applications/PerfTools/src/main/java/com/refinitiv/eta/perftools/transportperf/TransportTestRole.java | Georggi/Real-Time-SDK | 2afc005be700d93dd8f80d92d8dd80b41120e096 | [
"Apache-2.0"
] | 107 | 2015-07-27T23:43:04.000Z | 2019-01-03T07:11:27.000Z | Java/Eta/Applications/PerfTools/src/main/java/com/refinitiv/eta/perftools/transportperf/TransportTestRole.java | Georggi/Real-Time-SDK | 2afc005be700d93dd8f80d92d8dd80b41120e096 | [
"Apache-2.0"
] | 91 | 2015-07-28T15:40:43.000Z | 2018-12-31T09:37:19.000Z | Java/Eta/Applications/PerfTools/src/main/java/com/refinitiv/eta/perftools/transportperf/TransportTestRole.java | Georggi/Real-Time-SDK | 2afc005be700d93dd8f80d92d8dd80b41120e096 | [
"Apache-2.0"
] | 68 | 2015-07-27T08:35:47.000Z | 2019-01-01T07:59:39.000Z | 39.25 | 80 | 0.51465 | 11,757 | /*|-----------------------------------------------------------------------------
*| This source code is provided under the Apache 2.0 license --
*| and is provided AS IS with no warranty or guarantee of fit for purpose. --
*| See the project's LICENSE.md for details. --
*| Copyright (C) 2019-2022 Refinitiv. All rights reserved. --
*|-----------------------------------------------------------------------------
*/
package com.refinitiv.eta.perftools.transportperf;
/** Transport performance test role. */
public class TransportTestRole
{
public static final int UNINIT = 0x00;
public static final int WRITER = 0x01;
public static final int READER = 0x02;
public static final int REFLECTOR = 0x04;
}
|
3e1bc304aca2c0f1234e208fcb407c6589f472ff | 1,470 | java | Java | src/main/java/io/github/tehstoneman/betterstorage/client/renderer/BetterStorageColorHandler.java | kellixon/BetterStorageToo | f4f233110df2c036837d1bcf9f5669bfb9d96a41 | [
"MIT"
] | null | null | null | src/main/java/io/github/tehstoneman/betterstorage/client/renderer/BetterStorageColorHandler.java | kellixon/BetterStorageToo | f4f233110df2c036837d1bcf9f5669bfb9d96a41 | [
"MIT"
] | null | null | null | src/main/java/io/github/tehstoneman/betterstorage/client/renderer/BetterStorageColorHandler.java | kellixon/BetterStorageToo | f4f233110df2c036837d1bcf9f5669bfb9d96a41 | [
"MIT"
] | null | null | null | 33.409091 | 103 | 0.788435 | 11,758 | package io.github.tehstoneman.betterstorage.client.renderer;
import java.awt.Color;
import io.github.tehstoneman.betterstorage.common.block.BetterStorageBlocks;
import io.github.tehstoneman.betterstorage.common.tileentity.TileEntityCardboardBox;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.color.BlockColors;
import net.minecraft.client.renderer.color.IBlockColor;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly( Side.CLIENT )
public class BetterStorageColorHandler
{
public static Minecraft minecraft = Minecraft.getMinecraft();
public static void registerColorHandlers()
{
final BlockColors blockColors = minecraft.getBlockColors();
registerBlockColorHandlers( blockColors );
}
private static void registerBlockColorHandlers( BlockColors blockColors )
{
final IBlockColor cardboardBoxColorHandler = ( state, blockAccess, pos, tintIndex ) ->
{
if( blockAccess != null && pos != null )
{
final TileEntity tileEntity = blockAccess.getTileEntity( pos );
if( tileEntity instanceof TileEntityCardboardBox )
{
final TileEntityCardboardBox box = (TileEntityCardboardBox)tileEntity;
final int color = box.getColor();
return color;
}
}
return Color.WHITE.getRGB();
};
blockColors.registerBlockColorHandler( cardboardBoxColorHandler, BetterStorageBlocks.CARDBOARD_BOX );
}
}
|
3e1bc33b48a52612ae8bab446074f3e99aeb5398 | 480 | java | Java | admin/src/main/java/com/uton/admin/system/domain/RoleWithMenu.java | runxinfu/SpringBoot | 4656c6bf72083bcd6589d7342bd6ec3297cb85e0 | [
"Apache-2.0"
] | 1 | 2018-12-28T06:05:31.000Z | 2018-12-28T06:05:31.000Z | admin/src/main/java/com/uton/admin/system/domain/RoleWithMenu.java | runxinfu/SpringBoot | 4656c6bf72083bcd6589d7342bd6ec3297cb85e0 | [
"Apache-2.0"
] | null | null | null | admin/src/main/java/com/uton/admin/system/domain/RoleWithMenu.java | runxinfu/SpringBoot | 4656c6bf72083bcd6589d7342bd6ec3297cb85e0 | [
"Apache-2.0"
] | null | null | null | 15 | 67 | 0.720833 | 11,759 | package com.uton.admin.system.domain;
import java.util.List;
public class RoleWithMenu extends Role{
private static final long serialVersionUID = 2013847071068967187L;
private Long menuId;
private List<Long> menuIds;
public Long getMenuId() {
return menuId;
}
public void setMenuId(Long menuId) {
this.menuId = menuId;
}
public List<Long> getMenuIds() {
return menuIds;
}
public void setMenuIds(List<Long> menuIds) {
this.menuIds = menuIds;
}
}
|
3e1bc6926fda3d9eebf307d56b30378cd6a6bfdc | 188 | java | Java | jpo-ode-plugins/src/main/java/us/dot/its/jpo/ode/plugin/j2735/J2735HeadingConfidence.java | kijeongeun/jpo-ode | be7ff5a9d0af9a9a9db17145fbebcf54df6b745b | [
"Apache-2.0"
] | null | null | null | jpo-ode-plugins/src/main/java/us/dot/its/jpo/ode/plugin/j2735/J2735HeadingConfidence.java | kijeongeun/jpo-ode | be7ff5a9d0af9a9a9db17145fbebcf54df6b745b | [
"Apache-2.0"
] | null | null | null | jpo-ode-plugins/src/main/java/us/dot/its/jpo/ode/plugin/j2735/J2735HeadingConfidence.java | kijeongeun/jpo-ode | be7ff5a9d0af9a9a9db17145fbebcf54df6b745b | [
"Apache-2.0"
] | 1 | 2022-01-13T05:04:51.000Z | 2022-01-13T05:04:51.000Z | 13.428571 | 40 | 0.781915 | 11,760 | package us.dot.its.jpo.ode.plugin.j2735;
public enum J2735HeadingConfidence {
UNAVAILABLE,
PREC10DEG,
PREC05DEG,
PREC01DEG,
PREC0_1DEG,
PREC0_05DEG,
PREC0_01DEG,
PREC0_0125DEG
}
|
3e1bc7531f756813ce5912a437dac0111b81e8e9 | 1,593 | java | Java | anchor-bean/src/main/java/org/anchoranalysis/bean/annotation/NonNegative.java | anchorimageanalysis/anchor | 28a5b068841a405e66bd9e0e29d287b0e7afb0b9 | [
"MIT"
] | null | null | null | anchor-bean/src/main/java/org/anchoranalysis/bean/annotation/NonNegative.java | anchorimageanalysis/anchor | 28a5b068841a405e66bd9e0e29d287b0e7afb0b9 | [
"MIT"
] | 136 | 2020-02-17T10:33:05.000Z | 2022-02-13T12:10:58.000Z | anchor-bean/src/main/java/org/anchoranalysis/bean/annotation/NonNegative.java | anchoranalysis/anchor | b8a267ebcc69412200388f8e4959aed7c08ea828 | [
"MIT"
] | null | null | null | 40.846154 | 94 | 0.730697 | 11,761 | /*-
* #%L
* anchor-bean
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
package org.anchoranalysis.bean.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* The bean-field should have a value {@code >= 0}.
*
* <p>Only applicable to numerical types (Integer, Short, Double, Long etc.)
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface NonNegative {}
|
3e1bc7806e0b05eb3553f8bb1d7ba18e1d91f9ae | 1,475 | java | Java | sdk/containerservice/mgmt-v2020_12_01/src/main/java/com/microsoft/azure/management/containerservice/v2020_12_01/implementation/PrivateLinkResourceImpl.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 3 | 2021-09-15T16:25:19.000Z | 2021-12-17T05:41:00.000Z | sdk/containerservice/mgmt-v2020_12_01/src/main/java/com/microsoft/azure/management/containerservice/v2020_12_01/implementation/PrivateLinkResourceImpl.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 12 | 2019-07-17T16:18:54.000Z | 2019-07-17T21:30:02.000Z | sdk/containerservice/mgmt-v2020_12_01/src/main/java/com/microsoft/azure/management/containerservice/v2020_12_01/implementation/PrivateLinkResourceImpl.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1 | 2022-01-31T19:22:33.000Z | 2022-01-31T19:22:33.000Z | 25.431034 | 108 | 0.696271 | 11,762 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.containerservice.v2020_12_01.implementation;
import com.microsoft.azure.management.containerservice.v2020_12_01.PrivateLinkResource;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import java.util.List;
class PrivateLinkResourceImpl extends WrapperImpl<PrivateLinkResourceInner> implements PrivateLinkResource {
private final ContainerServiceManager manager;
PrivateLinkResourceImpl(PrivateLinkResourceInner inner, ContainerServiceManager manager) {
super(inner);
this.manager = manager;
}
@Override
public ContainerServiceManager manager() {
return this.manager;
}
@Override
public String groupId() {
return this.inner().groupId();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public String privateLinkServiceID() {
return this.inner().privateLinkServiceID();
}
@Override
public List<String> requiredMembers() {
return this.inner().requiredMembers();
}
@Override
public String type() {
return this.inner().type();
}
}
|
3e1bc7ea076cd9be4eb520b66741f9191a8ac51f | 1,395 | java | Java | src/test/java/org/study/creational/factorymethod/LogisticsClientTest.java | vlstus/GoF-Patterns | eee73846da9c3d2183f8852480fc77e71072e3a4 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/study/creational/factorymethod/LogisticsClientTest.java | vlstus/GoF-Patterns | eee73846da9c3d2183f8852480fc77e71072e3a4 | [
"Apache-2.0"
] | 11 | 2021-02-24T15:24:13.000Z | 2021-04-25T13:34:50.000Z | src/test/java/org/study/creational/factorymethod/LogisticsClientTest.java | vlstus/GoF-Patterns | eee73846da9c3d2183f8852480fc77e71072e3a4 | [
"Apache-2.0"
] | null | null | null | 36.710526 | 69 | 0.73405 | 11,763 | package org.study.creational.factorymethod;
import org.junit.jupiter.api.Test;
import org.study.creational.factorymethod.logistic.BoatLogistics;
import org.study.creational.factorymethod.logistic.TruckLogistics;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.jupiter.api.Assertions.*;
class LogisticsClientTest {
@Test
void shouldUseTruckLogistics() {
String expectedPrefix = "Transporting shipment with Truck #";
LogisticsClient client = new LogisticsClient();
client.logistics = new TruckLogistics();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PrintStream consoleCapturingStream = new PrintStream(buffer);
System.setOut(consoleCapturingStream);
client.orderTransportation();
assertTrue(buffer.toString().startsWith(expectedPrefix));
}
@Test
void shouldUseBoatLogistics() {
String expectedPrefix = "Transporting shipment with Boat #";
LogisticsClient client = new LogisticsClient();
client.logistics = new BoatLogistics();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PrintStream consoleCapturingStream = new PrintStream(buffer);
System.setOut(consoleCapturingStream);
client.orderTransportation();
assertTrue(buffer.toString().startsWith(expectedPrefix));
}
} |
3e1bc7f5207d15ec12bac78bf69bb5787692b737 | 1,685 | java | Java | app/src/main/java/com/chen/beth/ui/OnScrollListener.java | chenyaoyang/Beth | 1ff4597688f5f86c1e15b47f84762d6ee2c61b0b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/chen/beth/ui/OnScrollListener.java | chenyaoyang/Beth | 1ff4597688f5f86c1e15b47f84762d6ee2c61b0b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/chen/beth/ui/OnScrollListener.java | chenyaoyang/Beth | 1ff4597688f5f86c1e15b47f84762d6ee2c61b0b | [
"Apache-2.0"
] | null | null | null | 30.636364 | 92 | 0.662908 | 11,764 | package com.chen.beth.ui;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chen.beth.Utils.LogUtil;
import com.chen.beth.models.TransactionSummaryBean;
import org.greenrobot.eventbus.EventBus;
public class OnScrollListener extends RecyclerView.OnScrollListener {
private boolean isSlidingUp = false, enable = false;
private int prePos = -1;
private int itemCount,lastItemPosition, preloadPos;
public OnScrollListener(int preloadPos){
this.preloadPos = preloadPos;
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (!enable){
return;
}
isSlidingUp = dy>0;
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
itemCount = manager.getItemCount();
lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
if (isSlidingUp && lastItemPosition!=prePos){
prePos = lastItemPosition;
if (lastItemPosition == itemCount-preloadPos){
LogUtil.d(this.getClass(),"开始预加载");
enable = false;
preLoad.onPreLoad();
}
}
}
private void handleSucceed(TransactionSummaryBean[] beans){
if (beans.length!=0){
EventBus.getDefault().post(beans);
}
}
private IPreLoad preLoad;
public void setOnPreLoad(IPreLoad preLoad){
this.preLoad = preLoad;
}
public void setEnable(boolean b){
enable = b;
}
}
|
3e1bc8b55eaced62b23007f61a066d4f42007181 | 7,069 | java | Java | test/jdk/java/net/MulticastSocket/NoLoopbackPackets.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | test/jdk/java/net/MulticastSocket/NoLoopbackPackets.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | test/jdk/java/net/MulticastSocket/NoLoopbackPackets.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | 37.61828 | 104 | 0.526797 | 11,765 | /*
* Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4742177
* @library /test/lib
* @summary Re-test IPv6 (and specifically MulticastSocket) with latest Linux & USAGI code
*/
import java.util.*;
import java.net.*;
import jdk.test.lib.NetworkConfiguration;
import jdk.test.lib.net.IPSupport;
public class NoLoopbackPackets {
private static String osname;
static boolean isWindows() {
if (osname == null)
osname = System.getProperty("os.name");
return osname.contains("Windows");
}
private static final String MESSAGE = "hello world (" + System.nanoTime() + ")";
public static void main(String[] args) throws Exception {
if (isWindows()) {
System.out.println("The test only run on non-Windows OS. Bye.");
return;
}
MulticastSocket msock = null;
List<SocketAddress> failedGroups = new ArrayList<SocketAddress>();
Sender sender = null;
Thread senderThread = null;
try {
msock = new MulticastSocket();
int port = msock.getLocalPort();
// we will send packets to three multicast groups :-
// 172.16.31.10, fc00:e968:6179::de52:7100.1.1.2, and fc00:e968:6179::de52:7100:1
//
List<SocketAddress> groups = new ArrayList<SocketAddress>();
if (IPSupport.hasIPv4()) {
groups.add(new InetSocketAddress(InetAddress.getByName("172.16.31.10"), port));
}
NetworkConfiguration nc = NetworkConfiguration.probe();
if (IPSupport.hasIPv6() && nc.hasTestableIPv6Address()) {
groups.add(new InetSocketAddress(InetAddress.getByName("fc00:e968:6179::de52:7100.1.1.2"), port));
groups.add(new InetSocketAddress(InetAddress.getByName("fc00:e968:6179::de52:7100:1"), port));
}
if (groups.isEmpty()) {
System.err.println("Nothing to test: there are no network interfaces");
}
sender = new Sender(groups);
senderThread = new Thread(sender);
senderThread.start();
// Now try to receive multicast packets. we should not see any of them
// since we disable loopback mode.
//
msock.setSoTimeout(5000); // 5 seconds
byte[] buf = new byte[1024];
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) 'z';
}
DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
byte[] expected = MESSAGE.getBytes();
assert expected.length <= buf.length;
for (SocketAddress group : groups) {
System.out.println("joining group: " + group);
msock.joinGroup(group, null);
try {
do {
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) 'a';
}
msock.receive(packet);
byte[] data = packet.getData();
int len = packet.getLength();
if (expected(data, len, expected)) {
failedGroups.add(group);
break;
} else {
System.err.println("WARNING: Unexpected packet received from "
+ group + ": "
+ len + " bytes");
System.err.println("\t as text: " + new String(data, 0, len));
}
} while (true);
} catch (SocketTimeoutException e) {
// we expect this
System.out.println("Received expected exception from " + group + ": " + e);
} finally {
msock.leaveGroup(group, null);
}
}
} finally {
if (msock != null) try { msock.close(); } catch (Exception e) {}
if (sender != null) {
sender.stop();
}
}
try {
if (failedGroups.size() > 0) {
System.out.println("We should not receive anything from following groups, but we did:");
for (SocketAddress group : failedGroups)
System.out.println(group);
throw new RuntimeException("test failed.");
}
} finally {
if (senderThread != null) {
senderThread.join();
}
}
}
static boolean expected(byte[] data, int len, byte[] expected) {
if (len != expected.length) return false;
for (int i = 0; i < len; i++) {
if (data[i] != expected[i]) return false;
}
return true;
}
static class Sender implements Runnable {
private List<SocketAddress> sendToGroups;
private volatile boolean stop;
public Sender(List<SocketAddress> groups) {
sendToGroups = groups;
}
public void run() {
byte[] buf = MESSAGE.getBytes();
List<DatagramPacket> packets = new ArrayList<DatagramPacket>();
try (MulticastSocket msock = new MulticastSocket()) {
for (SocketAddress group : sendToGroups) {
DatagramPacket packet = new DatagramPacket(buf, buf.length, group);
packets.add(packet);
}
msock.setLoopbackMode(true); // disable loopback mode
while (!stop) {
for (DatagramPacket packet : packets) {
msock.send(packet);
}
Thread.sleep(1000); // 1 second
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
void stop() {
stop = true;
}
}
}
|
3e1bc8cd4f8c9e17a0ef1e492dec77ea41e9db2b | 1,217 | java | Java | ngDesk-Websocket-Service/src/main/java/com/ngdesk/websocket/workflow/dao/Condition.java | SubscribeIT/ngDesk | 07909d755fb2c0e459cbb816543a4898829397d1 | [
"Apache-2.0"
] | 2 | 2021-11-10T04:57:47.000Z | 2022-01-05T04:24:35.000Z | ngDesk-Websocket-Service/src/main/java/com/ngdesk/websocket/workflow/dao/Condition.java | SubscribeIT/ngDesk | 07909d755fb2c0e459cbb816543a4898829397d1 | [
"Apache-2.0"
] | 206 | 2021-08-30T04:46:44.000Z | 2022-02-22T12:06:45.000Z | ngDesk-Websocket-Service/src/main/java/com/ngdesk/websocket/workflow/dao/Condition.java | SubscribeIT/ngDesk | 07909d755fb2c0e459cbb816543a4898829397d1 | [
"Apache-2.0"
] | 1 | 2021-12-10T08:36:13.000Z | 2021-12-10T08:36:13.000Z | 18.439394 | 92 | 0.748562 | 11,766 | package com.ngdesk.websocket.workflow.dao;
import javax.validation.constraints.Pattern;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Condition {
@JsonProperty("REQUIREMENT_TYPE")
private String requirementType;
@JsonProperty("CONDITION")
private String condition;
@JsonProperty("OPERATOR")
private String operator;
@JsonProperty("CONDITION_VALUE")
private String value;
public Condition() {
}
public Condition(String requirementType, String condition, String operator, String value) {
super();
this.requirementType = requirementType;
this.condition = condition;
this.operator = operator;
this.value = value;
}
public String getRequirementType() {
return requirementType;
}
public void setRequirementType(String requirementType) {
this.requirementType = requirementType;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
3e1bca14f24184ef6bcb9d05051e57ad8722ed5c | 98 | java | Java | src/main/java/com/ggp/IAction.java | schlndh/general-deepstack | ddaca45a2bd4cfea7e59b4240c20676f434fcdd0 | [
"MIT"
] | null | null | null | src/main/java/com/ggp/IAction.java | schlndh/general-deepstack | ddaca45a2bd4cfea7e59b4240c20676f434fcdd0 | [
"MIT"
] | 43 | 2018-07-03T08:59:40.000Z | 2019-05-06T13:14:04.000Z | src/main/java/com/ggp/IAction.java | schlndh/general-deepstack | ddaca45a2bd4cfea7e59b4240c20676f434fcdd0 | [
"MIT"
] | null | null | null | 14 | 47 | 0.795918 | 11,767 | package com.ggp;
import java.io.Serializable;
public interface IAction extends Serializable {
}
|
3e1bca410dfa1bf62f97232a750d237e6423ef24 | 1,368 | java | Java | Moviest/app/src/main/java/com/ozan/moviest/helper/BaseActivity.java | ozanurkn/Moviest | 36999fc0c70344f5df3d45f7c633eb0b676da5c5 | [
"Apache-2.0"
] | null | null | null | Moviest/app/src/main/java/com/ozan/moviest/helper/BaseActivity.java | ozanurkn/Moviest | 36999fc0c70344f5df3d45f7c633eb0b676da5c5 | [
"Apache-2.0"
] | null | null | null | Moviest/app/src/main/java/com/ozan/moviest/helper/BaseActivity.java | ozanurkn/Moviest | 36999fc0c70344f5df3d45f7c633eb0b676da5c5 | [
"Apache-2.0"
] | null | null | null | 30.4 | 89 | 0.681287 | 11,768 | package com.ozan.moviest.helper;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
public abstract class BaseActivity<T extends ViewDataBinding> extends AppCompatActivity {
protected View mainView;
protected ViewDataBinding binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
int layoutId = getLayoutId();
super.onCreate(savedInstanceState);
try{
binding = DataBindingUtil.setContentView(this,layoutId);
if (binding != null){
mainView = binding.getRoot();
}else {
mainView = LayoutInflater.from(this).inflate(layoutId,null);
setContentView(mainView);
}
}catch (NoClassDefFoundError e){
mainView = LayoutInflater.from(this).inflate(layoutId,null);
}
Controller.currentContext = getContext();
initView();
}
public T getBinding() {
return (T) binding;
}
protected abstract Context getContext();
protected abstract void initView();
protected abstract int getLayoutId();
}
|
3e1bcabb9e8ec94ee69ec2071caa70dbaa2b0478 | 4,386 | java | Java | dump/src/main/java/com/networknt/dump/DumpHandler.java | anilmuppalla/light-4j | 1cd338b0ef5a9971314090c00f58f9c39763da31 | [
"Apache-2.0"
] | null | null | null | dump/src/main/java/com/networknt/dump/DumpHandler.java | anilmuppalla/light-4j | 1cd338b0ef5a9971314090c00f58f9c39763da31 | [
"Apache-2.0"
] | null | null | null | dump/src/main/java/com/networknt/dump/DumpHandler.java | anilmuppalla/light-4j | 1cd338b0ef5a9971314090c00f58f9c39763da31 | [
"Apache-2.0"
] | null | null | null | 33.480916 | 115 | 0.654127 | 11,769 | /*
* Copyright (c) 2016 Network New Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.dump;
import com.networknt.config.Config;
import com.networknt.handler.MiddlewareHandler;
import com.networknt.utility.Constants;
import com.networknt.utility.ModuleRegistry;
import io.undertow.Handlers;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HeaderValues;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Handler that dumps request and response to a log based on the dump.json config
* <p>
* Created by steve on 01/09/16.
*/
public class DumpHandler implements MiddlewareHandler {
public static final String CONFIG_NAME = "dump";
public static final String ENABLED = "enabled";
static final String REQUEST = "request";
static final String RESPONSE = "response";
static final String HEADERS = "headers";
static final String COOKIES = "cookies";
static final String QUERY_PARAMETERS = "queryParameters";
static final Logger audit = LoggerFactory.getLogger(Constants.AUDIT_LOGGER);
static final Logger logger = LoggerFactory.getLogger(DumpHandler.class);
public static Map<String, Object> config =
Config.getInstance().getJsonMapConfigNoCache(CONFIG_NAME);
private volatile HttpHandler next;
public DumpHandler() {
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
Map<String, Object> result = new LinkedHashMap<>();
Map<String, Object> config = Config.getInstance().getJsonMapConfig(CONFIG_NAME);
}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
Object object = config.get(ENABLED);
return object != null && (Boolean) object;
}
@Override
public void register() {
ModuleRegistry.registerModule(DumpHandler.class.getName(), config, null);
}
private void dumpRequest(Map<String, Object> result, HttpServerExchange exchange, Object configObject) {
Map<String, Object> requestMap = new LinkedHashMap<>();
if (configObject instanceof Boolean) {
if ((Boolean) configObject) {
}
} else if (configObject instanceof List<?>) {
}
}
private void dumpRequestHeaders(Map<String, Object> result, HttpServerExchange exchange, Object configObject) {
Map<String, Object> headerMap = new LinkedHashMap<>();
if (configObject instanceof Boolean) {
if ((Boolean) configObject) {
for (HeaderValues header : exchange.getRequestHeaders()) {
for (String value : header) {
headerMap.put(header.getHeaderName().toString(), value);
}
}
}
} else if (configObject instanceof List<?>) {
// configObject is a list of header names
List headerList = (List<String>) configObject;
for (HeaderValues header : exchange.getRequestHeaders()) {
for (String value : header) {
String name = header.getHeaderName().toString();
if (headerList.contains(name)) {
headerMap.put(header.getHeaderName().toString(), value);
}
}
}
} else {
logger.error("Header configuration is incorrect.");
}
if (headerMap.size() > 0) {
result.put(HEADERS, headerMap);
}
}
}
|
3e1bcb1560397f0ca7b4d50ced4c8b01ddb48428 | 349 | java | Java | app/src/main/java/com/coolweather/android/gson/Now.java | hackeryang/coolweather | 01a7c514ebafa51ca5bd3368207b127d5cf9a9d8 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/coolweather/android/gson/Now.java | hackeryang/coolweather | 01a7c514ebafa51ca5bd3368207b127d5cf9a9d8 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/coolweather/android/gson/Now.java | hackeryang/coolweather | 01a7c514ebafa51ca5bd3368207b127d5cf9a9d8 | [
"Apache-2.0"
] | null | null | null | 17.45 | 50 | 0.659026 | 11,770 | package com.coolweather.android.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by root on 18-1-10.
*/
public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More{
@SerializedName("txt")
public String info;
}
}
|
3e1bcc8bb627471c8e11f14b77355f73b006407c | 1,671 | java | Java | src/main/java/gg/fel/cvut/cz/data/readonly/Race.java | Game-Group-AIC/sc-wrapper | 9365ed744873e7cf2c3b5372630cf532a333d4a5 | [
"MIT"
] | null | null | null | src/main/java/gg/fel/cvut/cz/data/readonly/Race.java | Game-Group-AIC/sc-wrapper | 9365ed744873e7cf2c3b5372630cf532a333d4a5 | [
"MIT"
] | null | null | null | src/main/java/gg/fel/cvut/cz/data/readonly/Race.java | Game-Group-AIC/sc-wrapper | 9365ed744873e7cf2c3b5372630cf532a333d4a5 | [
"MIT"
] | null | null | null | 22.890411 | 87 | 0.733094 | 11,771 | package gg.fel.cvut.cz.data.readonly;
import gg.fel.cvut.cz.api.IRace;
import gg.fel.cvut.cz.api.ITechType;
import gg.fel.cvut.cz.api.IUnitType;
import gg.fel.cvut.cz.api.IUpgradeType;
import gg.fel.cvut.cz.api.IWeaponType;
import gg.fel.cvut.cz.counters.BWReplayCounter;
import gg.fel.cvut.cz.data.AContainerForType;
import gg.fel.cvut.cz.enums.RaceTypeEnum;
import java.io.Serializable;
import java.util.Optional;
import java.util.stream.Stream;
//TODO implement
public class Race extends AContainerForType<bwapi.Race, RaceTypeEnum> implements IRace,
Serializable {
public Race(BWReplayCounter bwCounter, RaceTypeEnum raceType) {
super(bwCounter, raceType);
}
@Override
public RaceTypeEnum getRaceType() {
return type;
}
@Override
public Optional<IUnitType> getWorker() {
return Optional.empty();
}
@Override
public Optional<IUnitType> getCenter() {
return Optional.empty();
}
@Override
public Optional<IUnitType> getRefinery() {
return Optional.empty();
}
@Override
public Optional<IUnitType> getTransport() {
return Optional.empty();
}
@Override
public Optional<IUnitType> getSupplyProvider() {
return Optional.empty();
}
@Override
public Optional<Stream<IUnitType>> getAllUnitTypesOfThisRace() {
return Optional.empty();
}
@Override
public Optional<Stream<ITechType>> getAllTechTypesOfThisRace() {
return Optional.empty();
}
@Override
public Optional<Stream<IUpgradeType>> getAllUpgradeTypesOfThisRace() {
return Optional.empty();
}
@Override
public Optional<Stream<IWeaponType>> getAllWeaponTypesOfThisRace() {
return Optional.empty();
}
}
|
3e1bcd588beb0ffb449cee13f31e79a2acd91022 | 2,228 | java | Java | Rectangle.java | bullgom/GUI-Editor | 837593213333dc72108bb6aa045b1f07b6c08035 | [
"MIT"
] | null | null | null | Rectangle.java | bullgom/GUI-Editor | 837593213333dc72108bb6aa045b1f07b6c08035 | [
"MIT"
] | null | null | null | Rectangle.java | bullgom/GUI-Editor | 837593213333dc72108bb6aa045b1f07b6c08035 | [
"MIT"
] | null | null | null | 29.315789 | 116 | 0.537253 | 11,772 | import java.awt.*;
public class Rectangle extends Fillable_Figure {
java.awt.Rectangle rectangle;
public Rectangle(Color fill_color, Color line_color, float line_thickness, int width, int height, int x, int y)
{
super(fill_color,
255,
line_color,
line_thickness,
255,
width, height,
x, y, Figure.TOPLEFT,0);
rectangle = new java.awt.Rectangle(x, y, width, height);
}
public void set_width(int width){
super.set_width(width);
rectangle.setSize(get_width(),get_height());
}
public void set_height(int height){
super.set_height(height);
rectangle.setSize(get_width(),get_height());
}
public void set_location(int x, int y){
super.set_location(x, y);
rectangle.setLocation(x,y);
}
public void set_location(Point p){
super.set_location(p);
rectangle.setLocation(p);
}
public void render(Graphics2D g)
{
g.rotate(Math.toRadians(get_rotate_angle()),
get_render_location().x - get_width()/2,
get_render_location().y - get_height()/2);
Color color = new Color(
get_fill_color().getRed(),
get_fill_color().getGreen(),
get_fill_color().getBlue(),
get_fill_transparency());
g.setColor(color);
g.fillRect(get_render_location().x,
get_render_location().y,
get_width(),
get_height());
g.setStroke(new BasicStroke(get_line_thickness()));
Color line_color = new Color(
get_line_color().getRed(),
get_line_color().getGreen(),
get_line_color().getBlue(),
get_line_transparency());
g.setColor(line_color);
g.drawRect(get_render_location().x,
get_render_location().y,
get_width(),
get_height());
}
@Override
public boolean contains(Point point) {
return rectangle.contains(point);
}
}
|
3e1bce7384152a84ae07ad24e27d223779020701 | 430 | java | Java | xmodule-common-security/src/main/java/com/penglecode/xmodule/common/security/support/SecurityPermsSynchronizeEvent.java | penggle/xmodule | 98210aa53d5958cda86f13b8b8f6eabd4ac4b93f | [
"Apache-2.0"
] | 24 | 2019-07-16T10:57:33.000Z | 2022-01-26T03:43:59.000Z | xmodule-common-security/src/main/java/com/penglecode/xmodule/common/security/support/SecurityPermsSynchronizeEvent.java | lvscxl/xmodule | e9f985bb45f64b21d7c63bdad9e7ce9f8185951c | [
"Apache-2.0"
] | 2 | 2020-08-27T10:07:22.000Z | 2020-09-11T06:28:30.000Z | xmodule-common-security/src/main/java/com/penglecode/xmodule/common/security/support/SecurityPermsSynchronizeEvent.java | lvscxl/xmodule | e9f985bb45f64b21d7c63bdad9e7ce9f8185951c | [
"Apache-2.0"
] | 20 | 2019-06-30T15:17:10.000Z | 2021-11-20T05:43:53.000Z | 21.5 | 70 | 0.744186 | 11,773 | package com.penglecode.xmodule.common.security.support;
import org.springframework.context.ApplicationEvent;
/**
* Security权限配置信息(用户-角色-资源)变更的同步Event
*
* @author pengpeng
* @date 2018年6月4日 上午9:50:11
*/
public class SecurityPermsSynchronizeEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
public SecurityPermsSynchronizeEvent(Object source) {
super(source);
}
}
|
3e1bcee0c30e17f1ec37f0458109b480b89266d3 | 8,898 | java | Java | RxPay/src/main/java/com/tamsiree/rxpay/alipay/Base64.java | December-peonyq/GodStar884 | b30c6d17878a95532840677923d1a1cb83706581 | [
"Apache-2.0"
] | 2,999 | 2018-06-12T05:22:30.000Z | 2019-07-16T06:19:20.000Z | RxPay/src/main/java/com/tamsiree/rxpay/alipay/Base64.java | December-peonyq/GodStar884 | b30c6d17878a95532840677923d1a1cb83706581 | [
"Apache-2.0"
] | 147 | 2019-07-22T09:11:44.000Z | 2022-02-07T10:51:24.000Z | RxPay/src/main/java/com/tamsiree/rxpay/alipay/Base64.java | December-peonyq/GodStar884 | b30c6d17878a95532840677923d1a1cb83706581 | [
"Apache-2.0"
] | 744 | 2018-06-12T08:51:32.000Z | 2019-07-16T05:40:49.000Z | 33.078067 | 89 | 0.483367 | 11,775 | package com.tamsiree.rxpay.alipay;
/**
* @author tamsiree
*/
public final class Base64 {
private static final int BASELENGTH = 128;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static char PAD = '=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = '+';
lookUpBase64Alphabet[63] = '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
: numberTriplets;
char[] encodedData = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte[] decodedData = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
return null;
}// if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
|
3e1bcf5b2a41719b3d9a0985aedbe10344ee1779 | 1,402 | java | Java | resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientMessageBodyReaderContext.java | soul2zimate/resteasy2 | 5fca9d3089069947d1085e093ed4ce93c506cb89 | [
"Apache-2.0"
] | null | null | null | resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientMessageBodyReaderContext.java | soul2zimate/resteasy2 | 5fca9d3089069947d1085e093ed4ce93c506cb89 | [
"Apache-2.0"
] | 6 | 2019-07-02T17:19:20.000Z | 2022-03-31T19:45:04.000Z | resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientMessageBodyReaderContext.java | soul2zimate/resteasy2 | 5fca9d3089069947d1085e093ed4ce93c506cb89 | [
"Apache-2.0"
] | null | null | null | 30.565217 | 285 | 0.76458 | 11,776 | package org.jboss.resteasy.client.core;
import org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl;
import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Map;
/**
* @author <a href="mailto:efpyi@example.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClientMessageBodyReaderContext extends MessageBodyReaderContextImpl
{
Map<String, Object> attributes;
public ClientMessageBodyReaderContext(MessageBodyReaderInterceptor[] interceptors, MessageBodyReader reader, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream inputStream, Map<String, Object> attributes)
{
super(interceptors, reader, type, genericType, annotations, mediaType, headers, inputStream);
this.attributes = attributes;
}
@Override
public Object getAttribute(String attribute)
{
return attributes.get(attribute);
}
@Override
public void setAttribute(String name, Object value)
{
attributes.put(name, value);
}
@Override
public void removeAttribute(String name)
{
attributes.remove(name);
}
}
|
3e1bcf66485bac6e9f6c7493487fbf3a3cd97e0a | 7,043 | java | Java | src/java/filter/LoginFilter.java | geovanealberto/LPWSD | ed1b8b01667e511576d5013943d092126c25175c | [
"MIT"
] | null | null | null | src/java/filter/LoginFilter.java | geovanealberto/LPWSD | ed1b8b01667e511576d5013943d092126c25175c | [
"MIT"
] | null | null | null | src/java/filter/LoginFilter.java | geovanealberto/LPWSD | ed1b8b01667e511576d5013943d092126c25175c | [
"MIT"
] | null | null | null | 32.159817 | 102 | 0.546784 | 11,777 | /*
* 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 filter;
import Modelo.TbUsuario;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author alunoces
*/
public class LoginFilter implements Filter {
private static final boolean debug = true;
// The filter configuration object we are associated with. If
// this value is null, this filter instance is not currently
// configured.
private FilterConfig filterConfig = null;
public LoginFilter() {
}
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("LoginFilter:DoBeforeProcessing");
}
}
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("LoginFilter:DoAfterProcessing");
}
}
/**
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (debug) {
log("LoginFilter:doFilter()");
}
doBeforeProcessing(request, response);
Throwable problem = null;
try {
HttpSession sess = ((HttpServletRequest)request).getSession(false);
String paginaAcessada = ((HttpServletRequest)request).getRequestURI();
TbUsuario usuarioLogado = null;
if (sess != null)
usuarioLogado = (TbUsuario)sess.getAttribute("usuario");
if (!"/LPWSD/faces/login.xhtml".equals(paginaAcessada))
{
if (usuarioLogado == null) {
((HttpServletResponse)response).sendRedirect("/LPWSD/faces/login.xhtml");
}
}
else
{
if (usuarioLogado != null) {
((HttpServletResponse)response).sendRedirect("/LPWSD");
}
}
chain.doFilter(request, response);
} catch (Throwable t) {
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
// If there was a problem, we want to rethrow it if it is
// a known type, otherwise log it.
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
/**
* Return the filter configuration object for this filter.
*/
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
/**
* Set the filter configuration object for this filter.
*
* @param filterConfig The filter configuration object
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* Destroy method for this filter
*/
public void destroy() {
}
/**
* Init method for this filter
*/
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (debug) {
log("LoginFilter:Initializing filter");
}
}
}
/**
* Return a String representation of this object.
*/
@Override
public String toString() {
if (filterConfig == null) {
return ("LoginFilter()");
}
StringBuffer sb = new StringBuffer("LoginFilter(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private void sendProcessingError(Throwable t, ServletResponse response) {
String stackTrace = getStackTrace(t);
if (stackTrace != null && !stackTrace.equals("")) {
try {
response.setContentType("text/html");
PrintStream ps = new PrintStream(response.getOutputStream());
PrintWriter pw = new PrintWriter(ps);
pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N
// PENDING! Localize this for next official release
pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
pw.print(stackTrace);
pw.print("</pre></body>\n</html>"); //NOI18N
pw.close();
ps.close();
response.getOutputStream().close();
} catch (Exception ex) {
}
} else {
try {
PrintStream ps = new PrintStream(response.getOutputStream());
t.printStackTrace(ps);
ps.close();
response.getOutputStream().close();
} catch (Exception ex) {
}
}
}
public static String getStackTrace(Throwable t) {
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex) {
}
return stackTrace;
}
public void log(String msg) {
filterConfig.getServletContext().log(msg);
}
}
|
3e1bd03a747e401c46b1ca494e5c88644badc9e5 | 6,298 | java | Java | alpha/MyBox/src/main/java/mara/mybox/controller/WebAddressController.java | Mararsh/MyBox | be9c143971e7c1a2c9d7bdba450e49750b6c037b | [
"Apache-2.0"
] | 76 | 2018-06-12T09:02:49.000Z | 2022-03-31T03:43:39.000Z | alpha/MyBox/src/main/java/mara/mybox/controller/WebAddressController.java | Mararsh/MyBox | be9c143971e7c1a2c9d7bdba450e49750b6c037b | [
"Apache-2.0"
] | 1,377 | 2018-06-16T23:16:41.000Z | 2022-03-29T03:01:43.000Z | alpha/MyBox/src/main/java/mara/mybox/controller/WebAddressController.java | Mararsh/MyBox | be9c143971e7c1a2c9d7bdba450e49750b6c037b | [
"Apache-2.0"
] | 18 | 2018-11-18T04:33:06.000Z | 2022-03-08T07:47:09.000Z | 31.49 | 106 | 0.500794 | 11,778 | package mara.mybox.controller;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tab;
import javafx.scene.image.ImageView;
import mara.mybox.db.data.WebHistory;
import mara.mybox.db.table.TableWebHistory;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.SingletonTask;
import mara.mybox.fxml.StyleTools;
import mara.mybox.imagefile.ImageFileReaders;
import mara.mybox.tools.IconTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2018-7-31
* @License Apache License Version 2.0
*/
public class WebAddressController extends BaseWebViewController {
protected TableWebHistory tableWebHistory;
protected Tab addressTab;
protected List<String> failedAddress;
@FXML
protected ComboBox<String> urlSelector;
public WebAddressController() {
baseTitle = message("WebBrowser");
}
@Override
public void initValues() {
try {
super.initValues();
if (urlSelector != null) {
tableWebHistory = new TableWebHistory();
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
@Override
public void initControls() {
try {
super.initControls();
if (urlSelector != null) {
List<String> his = tableWebHistory.recent(20);
if (!his.isEmpty()) {
urlSelector.getItems().addAll(his);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public void initTab(WebBrowserController parent, Tab tab) {
this.baseName = parent.baseName;
this.addressTab = tab;
}
@Override
public void goAction() {
if (!checkBeforeNextAction() || urlSelector == null) {
return;
}
boolean ret = webViewController.loadAddress(urlSelector.getEditor().getText());
if (ret) {
sourceFile = webViewController.sourceFile;
}
}
@Override
public void addressChanged() {
if (urlSelector != null) {
Platform.runLater(() -> {
urlSelector.getEditor().setStyle(null);
String address;
if (webViewController != null) {
address = webViewController.address;
} else {
address = urlSelector.getValue();
}
urlSelector.getItems().clear();
List<String> urls = tableWebHistory.recent(20);
if (!urls.isEmpty()) {
urlSelector.getItems().addAll(urls);
}
urlSelector.getEditor().setText(address);
writeHis(address);
});
}
}
public void writeHis(String address) {
SingletonTask bgTask = new SingletonTask<Void>(this) {
private ImageView tabImage = null;
@Override
protected boolean handle() {
try {
WebHistory his = new WebHistory();
his.setAddress(address);
his.setVisitTime(new Date());
String title = webEngine.getTitle();
his.setTitle(title != null ? title : "");
his.setIcon("");
if (failedAddress == null || !failedAddress.contains(address)) {
try {
File iconFile = IconTools.readIcon(address, true);
if (iconFile != null && iconFile.exists()) {
his.setIcon(iconFile.getAbsolutePath());
if (addressTab != null) {
BufferedImage image = ImageFileReaders.readImage(iconFile);
if (image != null) {
tabImage = new ImageView(SwingFXUtils.toFXImage(image, null));
}
}
}
} catch (Exception e) {
}
}
if (tabImage == null) {
if (failedAddress == null) {
failedAddress = new ArrayList<>();
}
failedAddress.add(address);
}
tableWebHistory.insertData(his);
return true;
} catch (Exception e) {
error = e.toString();
return false;
}
}
@Override
protected void whenSucceeded() {
if (addressTab != null) {
if (tabImage == null) {
tabImage = StyleTools.getIconImage("iconMyBox.png");
}
tabImage.setFitWidth(20);
tabImage.setFitHeight(20);
addressTab.setGraphic(tabImage);
}
}
};
start(bgTask, false);
}
@Override
public void addressInvalid() {
super.addressInvalid();
if (urlSelector != null) {
Platform.runLater(() -> {
urlSelector.getEditor().setStyle(UserConfig.badStyle());
});
}
}
@Override
public void pageLoaded() {
try {
if (addressTab != null) {
String title = webEngine.getTitle();
addressTab.setText(title != null ? title.substring(0, Math.min(10, title.length())) : "");
}
super.pageLoaded();
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
@Override
public boolean keyEnter() {
if (urlSelector != null && urlSelector.isFocused()) {
goAction();
return true;
}
return false;
}
}
|
3e1bd0ea8aedb82748cda6ef8aaab296f3e4a2a8 | 1,015 | java | Java | agent/plugin-api/src/main/java/org/glowroot/agent/plugin/api/internal/ReadableQueryMessage.java | rajdavies/glowroot | c7f1c9cb993e796a55fef0ef54839dead8a78dcf | [
"Apache-2.0"
] | 1,018 | 2015-02-27T12:14:23.000Z | 2022-03-31T05:07:13.000Z | agent/plugin-api/src/main/java/org/glowroot/agent/plugin/api/internal/ReadableQueryMessage.java | rajdavies/glowroot | c7f1c9cb993e796a55fef0ef54839dead8a78dcf | [
"Apache-2.0"
] | 838 | 2015-04-25T17:51:24.000Z | 2022-03-30T14:40:19.000Z | agent/plugin-api/src/main/java/org/glowroot/agent/plugin/api/internal/ReadableQueryMessage.java | nicokosi/glowroot | 1df8de07a8d97be69ebf2fae898228a894b6c04a | [
"Apache-2.0"
] | 270 | 2015-02-27T11:23:47.000Z | 2022-03-28T04:07:58.000Z | 32.741935 | 97 | 0.751724 | 11,779 | /*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.agent.plugin.api.internal;
import java.util.Map;
// this interface exists to provide access to QueryMessageImpl from glowroot without making
// QueryMessageImpl accessible to plugins (at least not through the org.glowroot.agent.plugin.api
// package)
public interface ReadableQueryMessage {
String getPrefix();
String getSuffix();
Map<String, ?> getDetail();
}
|
3e1bd1ef415b419232d2b93b7f35d2608acddbee | 461 | java | Java | tools/junit_runner/src/build/please/cover/result/CoverageRunResult.java | edrogers/please | b1e1587a589647a4dcb16c0ccc08595166c2cbad | [
"Apache-2.0"
] | null | null | null | tools/junit_runner/src/build/please/cover/result/CoverageRunResult.java | edrogers/please | b1e1587a589647a4dcb16c0ccc08595166c2cbad | [
"Apache-2.0"
] | 1 | 2020-04-28T15:06:28.000Z | 2020-04-28T16:04:49.000Z | tools/junit_runner/src/build/please/cover/result/CoverageRunResult.java | edrogers/please | b1e1587a589647a4dcb16c0ccc08595166c2cbad | [
"Apache-2.0"
] | 4 | 2021-09-28T16:38:54.000Z | 2022-03-17T17:22:18.000Z | 28.8125 | 70 | 0.789588 | 11,780 | package build.please.cover.result;
import build.please.test.result.TestSuiteResult;
import build.please.vendored.org.jacoco.core.analysis.CoverageBuilder;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class CoverageRunResult {
public List<TestSuiteResult> testResults = new LinkedList<>();
public Set<String> testClassNames = new HashSet<>();
public CoverageBuilder coverageBuilder;
}
|
3e1bd2283a44fa564ce7ac63b61955b87c46d5a6 | 4,333 | java | Java | sdk/cosmos/mgmt-v2020_06_01_preview/src/main/java/com/microsoft/azure/management/cosmosdb/v2020_06_01_preview/CassandraTableGetPropertiesResource.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 3 | 2021-09-15T16:25:19.000Z | 2021-12-17T05:41:00.000Z | sdk/cosmos/mgmt-v2020_06_01_preview/src/main/java/com/microsoft/azure/management/cosmosdb/v2020_06_01_preview/CassandraTableGetPropertiesResource.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 12 | 2019-07-17T16:18:54.000Z | 2019-07-17T21:30:02.000Z | sdk/cosmos/mgmt-v2020_06_01_preview/src/main/java/com/microsoft/azure/management/cosmosdb/v2020_06_01_preview/CassandraTableGetPropertiesResource.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1 | 2022-01-31T19:22:33.000Z | 2022-01-31T19:22:33.000Z | 25.639053 | 114 | 0.643434 | 11,781 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.cosmosdb.v2020_06_01_preview;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The CassandraTableGetPropertiesResource model.
*/
public class CassandraTableGetPropertiesResource {
/**
* Name of the Cosmos DB Cassandra table.
*/
@JsonProperty(value = "id", required = true)
private String id;
/**
* Time to live of the Cosmos DB Cassandra table.
*/
@JsonProperty(value = "defaultTtl")
private Integer defaultTtl;
/**
* Schema of the Cosmos DB Cassandra table.
*/
@JsonProperty(value = "schema")
private CassandraSchema schema;
/**
* Analytical TTL.
*/
@JsonProperty(value = "analyticalStorageTtl")
private Integer analyticalStorageTtl;
/**
* A system generated property. A unique identifier.
*/
@JsonProperty(value = "_rid", access = JsonProperty.Access.WRITE_ONLY)
private String _rid;
/**
* A system generated property that denotes the last updated timestamp of
* the resource.
*/
@JsonProperty(value = "_ts", access = JsonProperty.Access.WRITE_ONLY)
private Object _ts;
/**
* A system generated property representing the resource etag required for
* optimistic concurrency control.
*/
@JsonProperty(value = "_etag", access = JsonProperty.Access.WRITE_ONLY)
private String _etag;
/**
* Get name of the Cosmos DB Cassandra table.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Set name of the Cosmos DB Cassandra table.
*
* @param id the id value to set
* @return the CassandraTableGetPropertiesResource object itself.
*/
public CassandraTableGetPropertiesResource withId(String id) {
this.id = id;
return this;
}
/**
* Get time to live of the Cosmos DB Cassandra table.
*
* @return the defaultTtl value
*/
public Integer defaultTtl() {
return this.defaultTtl;
}
/**
* Set time to live of the Cosmos DB Cassandra table.
*
* @param defaultTtl the defaultTtl value to set
* @return the CassandraTableGetPropertiesResource object itself.
*/
public CassandraTableGetPropertiesResource withDefaultTtl(Integer defaultTtl) {
this.defaultTtl = defaultTtl;
return this;
}
/**
* Get schema of the Cosmos DB Cassandra table.
*
* @return the schema value
*/
public CassandraSchema schema() {
return this.schema;
}
/**
* Set schema of the Cosmos DB Cassandra table.
*
* @param schema the schema value to set
* @return the CassandraTableGetPropertiesResource object itself.
*/
public CassandraTableGetPropertiesResource withSchema(CassandraSchema schema) {
this.schema = schema;
return this;
}
/**
* Get analytical TTL.
*
* @return the analyticalStorageTtl value
*/
public Integer analyticalStorageTtl() {
return this.analyticalStorageTtl;
}
/**
* Set analytical TTL.
*
* @param analyticalStorageTtl the analyticalStorageTtl value to set
* @return the CassandraTableGetPropertiesResource object itself.
*/
public CassandraTableGetPropertiesResource withAnalyticalStorageTtl(Integer analyticalStorageTtl) {
this.analyticalStorageTtl = analyticalStorageTtl;
return this;
}
/**
* Get a system generated property. A unique identifier.
*
* @return the _rid value
*/
public String _rid() {
return this._rid;
}
/**
* Get a system generated property that denotes the last updated timestamp of the resource.
*
* @return the _ts value
*/
public Object _ts() {
return this._ts;
}
/**
* Get a system generated property representing the resource etag required for optimistic concurrency control.
*
* @return the _etag value
*/
public String _etag() {
return this._etag;
}
}
|
3e1bd38b9bc4a1bdf2ad80836a4fe07d9156d4fc | 2,539 | java | Java | alexp/src/main/java/alexp/macrobase/ingest/HttpCsvStreamReader.java | myrtakis/macrobase | ce1dd9fd38580f4135104d52c2ab0188e995d4ef | [
"Apache-2.0"
] | 1 | 2022-03-30T16:00:39.000Z | 2022-03-30T16:00:39.000Z | alexp/src/main/java/alexp/macrobase/ingest/HttpCsvStreamReader.java | myrtakis/macrobase | ce1dd9fd38580f4135104d52c2ab0188e995d4ef | [
"Apache-2.0"
] | null | null | null | alexp/src/main/java/alexp/macrobase/ingest/HttpCsvStreamReader.java | myrtakis/macrobase | ce1dd9fd38580f4135104d52c2ab0188e995d4ef | [
"Apache-2.0"
] | 2 | 2020-02-07T22:04:56.000Z | 2022-03-30T16:27:50.000Z | 36.271429 | 93 | 0.701063 | 11,782 | package alexp.macrobase.ingest;
import alexp.macrobase.utils.ThrowingConsumer;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import edu.stanford.futuredata.macrobase.datamodel.DataFrame;
import edu.stanford.futuredata.macrobase.datamodel.Schema;
import edu.stanford.futuredata.macrobase.ingest.CSVDataFrameParser;
import edu.stanford.futuredata.macrobase.ingest.DataFrameLoader;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.function.Consumer;
public class HttpCsvStreamReader implements StreamingDataFrameLoader {
private final String url;
private final List<String> requiredColumns;
private Map<String, Schema.ColType> columnTypes = new HashMap<>();
public HttpCsvStreamReader(String url, List<String> requiredColumns) throws IOException {
this.url = url;
this.requiredColumns = requiredColumns;
}
@Override
public HttpCsvStreamReader setColumnTypes(Map<String, Schema.ColType> types) {
this.columnTypes = types;
return this;
}
@Override
public void load(ThrowingConsumer<DataFrame> resultCallback) throws Exception {
URL url = new URL(this.url);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder inputBuff = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
if (inputLine.trim().equalsIgnoreCase("_END_PART_")) {
resultCallback.accept(parseCsv(inputBuff.toString()));
inputBuff = new StringBuilder();
} else {
inputBuff.append(inputLine).append("\n");
}
}
in.close();
if (inputBuff.length() > 0) {
resultCallback.accept(parseCsv(inputBuff.toString()));
}
}
private DataFrame parseCsv(String csvData) throws Exception {
CsvParserSettings settings = new CsvParserSettings();
settings.getFormat().setLineSeparator("\n");
CsvParser csvParser = new CsvParser(settings);
csvParser.beginParsing(new ByteArrayInputStream(csvData.getBytes("UTF-8")));
DataFrameLoader loader = new CSVDataFrameParser(csvParser, requiredColumns);
loader.setColumnTypes(columnTypes);
return loader.load();
}
}
|
3e1bd3fd935a2d80ef5ab8fc2c3ae33657bc32b9 | 1,687 | java | Java | app/src/main/java/danieer/galvez/testrappi/network/network/utils/NetworkUtils.java | Moldycord/TestRappi | 53c0798611c70b43e058e1bbaa19622c18bd5b20 | [
"MIT"
] | null | null | null | app/src/main/java/danieer/galvez/testrappi/network/network/utils/NetworkUtils.java | Moldycord/TestRappi | 53c0798611c70b43e058e1bbaa19622c18bd5b20 | [
"MIT"
] | null | null | null | app/src/main/java/danieer/galvez/testrappi/network/network/utils/NetworkUtils.java | Moldycord/TestRappi | 53c0798611c70b43e058e1bbaa19622c18bd5b20 | [
"MIT"
] | null | null | null | 37.488889 | 115 | 0.741553 | 11,783 | package danieer.galvez.testrappi.network.network.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkUtils {
public static final String BASE_URL = "http://api.themoviedb.org/3/";
public static final String API_KEY = "74t3tndxag9o7h0890bnpfzh4olk2h9x";
public static final String IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w200/";
public static final String BACKDROP_BASE_URL = "https://image.tmdb.org/t/p/w780/";
public static final String YOUTUBE_URL = "https://www.youtube.com/watch?v=";
public static final String POPULAR_MOVIES_ENDPOINT = "movie/popular";
public static final String TOP_RATED_MOVIES_ENDPOINT = "movie/top_rated";
public static final String UPCOMING_MOVIES_ENDPOINT = "movie/upcoming";
public static final String MOVIE_DETAILS_ENDPOINT = "movie/{movie_id}";
public static final String MOVIE_ID = "movie_id";
public static final String API_KEY_QUERY = "api_key";
public static final String PAGE_NO = "page";
public static final String APPEND_TO_RESPONSE = "append_to_response";
public static boolean checkNetworkConnection(Context context) {
boolean connected = false;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi != null && wifi.isConnected() || mobile != null && mobile.isConnected())
connected = true;
return connected;
}
}
|
3e1bd40b9e787b6e8c379627018cb4d364bb569c | 3,173 | java | Java | service/src/main/java/com/myhome/security/MyHomeAuthorizationFilter.java | HemantJoshi11/MyHome | 6a6b1b7b00558e5aab35f8ffd54295a24411ccb7 | [
"Apache-2.0"
] | 63 | 2020-06-24T06:40:57.000Z | 2022-03-07T17:36:31.000Z | service/src/main/java/com/myhome/security/MyHomeAuthorizationFilter.java | HemantJoshi11/MyHome | 6a6b1b7b00558e5aab35f8ffd54295a24411ccb7 | [
"Apache-2.0"
] | 244 | 2020-04-06T14:30:27.000Z | 2022-03-13T01:31:28.000Z | service/src/main/java/com/myhome/security/MyHomeAuthorizationFilter.java | HemantJoshi11/MyHome | 6a6b1b7b00558e5aab35f8ffd54295a24411ccb7 | [
"Apache-2.0"
] | 97 | 2020-06-20T14:08:22.000Z | 2022-03-22T09:42:35.000Z | 39.17284 | 99 | 0.78254 | 11,784 | /*
* Copyright 2020 Prathab Murugan
*
* 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.myhome.security;
import com.myhome.security.jwt.AppJwt;
import com.myhome.security.jwt.AppJwtEncoderDecoder;
import java.io.IOException;
import java.util.Collections;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
public class MyHomeAuthorizationFilter extends BasicAuthenticationFilter {
private final Environment environment;
private final AppJwtEncoderDecoder appJwtEncoderDecoder;
public MyHomeAuthorizationFilter(
AuthenticationManager authenticationManager,
Environment environment,
AppJwtEncoderDecoder appJwtEncoderDecoder) {
super(authenticationManager);
this.environment = environment;
this.appJwtEncoderDecoder = appJwtEncoderDecoder;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
String authHeaderName = environment.getProperty("authorization.token.header.name");
String authHeaderPrefix = environment.getProperty("authorization.token.header.prefix");
String authHeader = request.getHeader(authHeaderName);
if (authHeader == null || !authHeader.startsWith(authHeaderPrefix)) {
chain.doFilter(request, response);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String authHeader =
request.getHeader(environment.getProperty("authorization.token.header.name"));
if (authHeader == null) {
return null;
}
String token =
authHeader.replace(environment.getProperty("authorization.token.header.prefix"), "");
AppJwt jwt = appJwtEncoderDecoder.decode(token, environment.getProperty("token.secret"));
if (jwt.getUserId() == null) {
return null;
}
return new UsernamePasswordAuthenticationToken(jwt.getUserId(), null, Collections.emptyList());
}
}
|
3e1bd47ba91209c41ada12401059de02a8217c21 | 3,671 | java | Java | core/src/com/duast/game/listeners/GameInputListener.java | duast-dev/magic-cross | 23119251f155c999d405e0846e6721ee144f3bc5 | [
"Apache-2.0"
] | null | null | null | core/src/com/duast/game/listeners/GameInputListener.java | duast-dev/magic-cross | 23119251f155c999d405e0846e6721ee144f3bc5 | [
"Apache-2.0"
] | null | null | null | core/src/com/duast/game/listeners/GameInputListener.java | duast-dev/magic-cross | 23119251f155c999d405e0846e6721ee144f3bc5 | [
"Apache-2.0"
] | null | null | null | 34.308411 | 108 | 0.566058 | 11,785 | package com.duast.game.listeners;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.duast.game.screens.GameScreen;
import com.duast.game.stages.GameStage;
import com.duast.game.ui.WinDialog;
import com.duast.game.utils.C;
import com.duast.game.utils.Coordinates;
/**
* Created by alex on 10/8/16.
*/
public class GameInputListener extends InputListener {
private GameScreen screen;
private float x0, y0;
private Coordinates t_coords; //touch coordinates
private int line, coord;
private boolean isTouchValid = false;
public GameInputListener(GameScreen screen) {
this.screen = screen;
t_coords = new Coordinates();
}
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if(!screen.isTouchable()) return false;
//set starting position
this.x0 = x;
this.y0 = y;
//transform touch position in coordinates
int square_size = screen.getGameStage().getCross().getSquareSize()+C.DIST;
t_coords.setX((int) ((x0- C.PAD_LR)/square_size));
t_coords.setY((int) ((y0-C.PAD_DOWN)/square_size));
int ss = screen.getGameStage().getCross().size()/3;
if(t_coords.x>=ss && t_coords.x<=ss*2-1 && t_coords.y>=0 && t_coords.y<=ss*3-1) isTouchValid = true;
if(t_coords.y>=ss && t_coords.y<=ss*2-1 && t_coords.x>=0 && t_coords.x<=ss*3-1) isTouchValid = true;
line = -1;
if(isTouchValid) {
screen.getGameStage().getHighlights().show(C.ROW_COLUMN);
screen.getGameStage().getHighlights().setCoords(t_coords);
screen.getUiStage().getTimer().start();
}
return true;
}
@Override
public void touchDragged(InputEvent event, float x, float y, int pointer) {
if(isTouchValid) {
//calculate drag distance
float dx = x - x0;
float dy = y - y0;
if (line == C.ROW) dy = 0;
else if (line == C.COLUMN) dx = 0;
int dir = 0; //direction (+1 is UP or RIGHT; -1 is DOWN or LEFT; 0 is don't move)
int square_size = screen.getGameStage().getCross().getSquareSize();
int sector_size = screen.getGameStage().getCross().size() / 3;
if (Math.abs(dx) > square_size / 1.8f) {
dir = (int) Math.signum(dx);
this.x0 = x; //set new starting x
if (line == -1) {
line = C.ROW;
coord = t_coords.y;
screen.getGameStage().getHighlights().hide(C.COLUMN);
}
}
if (Math.abs(dy) > square_size / 1.8f) {
dir = (int) Math.signum(dy);
this.y0 = y; //set new starting y
if (line == -1) {
line = C.COLUMN;
coord = t_coords.x;
screen.getGameStage().getHighlights().hide(C.ROW);
}
}
if (coord > sector_size - 1 && coord < sector_size * 2 && dir != 0) {
screen.getGameStage().getCross().move(coord, dir, line);
}
}
}
@Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if(isTouchValid) {
screen.getGameStage().getHighlights().hide(C.ROW_COLUMN);
isTouchValid = false;
}
if(screen.getGameStage().getCross().checkWin()) {
screen.setTouchable(false);
screen.getUiStage().addActor(new WinDialog(screen));
}
}
}
|
3e1bd577f2f194e6ac78cac78f1cd62fba94d375 | 1,230 | java | Java | src/main/java/com/example/tongue/domain/merchant/DiscountCustomerEntitlement.java | alexanderommel/Spring-Boot-Tongue | 657c077a44a7450c8bd3268484b69933fd5d010a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/main/java/com/example/tongue/domain/merchant/DiscountCustomerEntitlement.java | alexanderommel/Spring-Boot-Tongue | 657c077a44a7450c8bd3268484b69933fd5d010a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/main/java/com/example/tongue/domain/merchant/DiscountCustomerEntitlement.java | alexanderommel/Spring-Boot-Tongue | 657c077a44a7450c8bd3268484b69933fd5d010a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | 18.923077 | 57 | 0.655285 | 11,786 | package com.example.tongue.domain.merchant;
import com.example.tongue.integration.customers.Customer;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class DiscountCustomerEntitlement {
@Id @GeneratedValue
private Long id;
@ManyToOne
private Customer customer;
@ManyToOne
private Discount discount;
private Boolean redeemed=Boolean.FALSE;
private int usages=0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Discount getDiscount() {
return discount;
}
public void setDiscount(Discount discount) {
this.discount = discount;
}
public Boolean getRedeemed() {
return redeemed;
}
public void setRedeemed(Boolean redeemed) {
this.redeemed = redeemed;
}
public int getUsages() {
return usages;
}
public void setUsages(int usages) {
this.usages = usages;
}
}
|
3e1bd604f1b8d26b0c9f7cab406d9221e42ddc6f | 1,171 | java | Java | xzlx-web-api/src/main/java/com/xzlx/web/api/web/controller/TbLineController.java | diliuzu/xiaozhu | 1c435d4445ba826dffa351e0a645227cac8a5b6f | [
"Apache-2.0"
] | null | null | null | xzlx-web-api/src/main/java/com/xzlx/web/api/web/controller/TbLineController.java | diliuzu/xiaozhu | 1c435d4445ba826dffa351e0a645227cac8a5b6f | [
"Apache-2.0"
] | null | null | null | xzlx-web-api/src/main/java/com/xzlx/web/api/web/controller/TbLineController.java | diliuzu/xiaozhu | 1c435d4445ba826dffa351e0a645227cac8a5b6f | [
"Apache-2.0"
] | null | null | null | 34.441176 | 123 | 0.770282 | 11,787 | package com.xzlx.web.api.web.controller;
import com.xzlx.commons.util.dto.BaseResult;
import com.xzlx.commons.util.persistance.BasePageDTO;
import com.xzlx.web.api.dao.TbLineDAO;
import com.xzlx.web.api.service.TbLineService;
import com.xzlx.web.api.web.dto.Line;
import com.xzlx.web.api.web.dto.TbLineDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("api/v1/lines")
public class TbLineController {
@Autowired
TbLineService tbLineService;
@GetMapping("areas/{area_id}")
public BaseResult getLinesByAreaId(@PathVariable(value = "area_id") Integer areaId,BasePageDTO<TbLineDTO> basePageDTO){
basePageDTO=tbLineService.getLinesByAreaId(areaId,basePageDTO);
return BaseResult.createBaseResult(200,"成功",basePageDTO);
}
@GetMapping("strategies/{strategy_id}")
public BaseResult getLinesByStrategyId(@PathVariable(value = "strategy_id") Integer strategyId){
List<Line> lines=tbLineService.getLinesByStrategyId(strategyId);
return BaseResult.success(200,"成功",lines);
}
}
|
3e1bd635b51488ebed863816840cf35529207a95 | 1,867 | java | Java | app/src/main/java/co/fddittmar/planbuilder/view/adapter/ExercisesAdapter.java | fernnando/PlanBuilder | f2e5b49d7079312cc7d38e2c25d32931e44b278a | [
"MIT"
] | null | null | null | app/src/main/java/co/fddittmar/planbuilder/view/adapter/ExercisesAdapter.java | fernnando/PlanBuilder | f2e5b49d7079312cc7d38e2c25d32931e44b278a | [
"MIT"
] | 3 | 2017-09-06T00:15:37.000Z | 2017-09-11T05:55:26.000Z | app/src/main/java/co/fddittmar/planbuilder/view/adapter/ExercisesAdapter.java | fernnando/PlanBuilder | f2e5b49d7079312cc7d38e2c25d32931e44b278a | [
"MIT"
] | null | null | null | 28.287879 | 89 | 0.676486 | 11,788 | package co.fddittmar.planbuilder.view.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import co.fddittmar.planbuilder.R;
import co.fddittmar.planbuilder.data.model.Exercise;
/**
* Adapter to represent a list of Exercises items
*/
public class ExercisesAdapter extends RecyclerView.Adapter<ExercisesAdapter.ViewHolder> {
private List<Exercise> exercises;
public ExercisesAdapter(List<Exercise> exercises ){
this.exercises = exercises;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from( parent.getContext() )
.inflate(R.layout.item_exercise, parent, false);
return new ViewHolder( view );
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setData( exercises.get( position ) );
}
@Override
public int getItemCount() {
return exercises.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView tvName;
private TextView tvReps;
private TextView tvWeight;
private ViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tv_exercise_name);
tvReps = (TextView) itemView.findViewById(R.id.tv_exercise_reps);
tvWeight = (TextView) itemView.findViewById(R.id.tv_exercise_weight);
}
private void setData( Exercise exercise ){
tvName.setText( exercise.getName() );
tvReps.setText( String.valueOf(exercise.getReps()) );
tvWeight.setText( String.valueOf(exercise.getWeight()) );
}
}
}
|
3e1bd70a2a2d08f5dd16d27869ac8c2c5156e8a1 | 1,266 | java | Java | java_book/src/main/java/com/cwl/service/part_1/ThreadJoin.java | Daniel201618/git_learning | 638afdcd53c1e857bde0ef45543f9e8d45ef2336 | [
"MIT"
] | null | null | null | java_book/src/main/java/com/cwl/service/part_1/ThreadJoin.java | Daniel201618/git_learning | 638afdcd53c1e857bde0ef45543f9e8d45ef2336 | [
"MIT"
] | null | null | null | java_book/src/main/java/com/cwl/service/part_1/ThreadJoin.java | Daniel201618/git_learning | 638afdcd53c1e857bde0ef45543f9e8d45ef2336 | [
"MIT"
] | null | null | null | 22.607143 | 79 | 0.518167 | 11,789 | package com.cwl.service.part_1;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author cwl
* @description: TODO
* @date 2019/12/1717:37
*/
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = create(1);
Thread thread2 = create(1);
List<Thread> list = new ArrayList<>();
list.add(thread1);
list.add(thread2);
for (Thread thread : list) {
thread.start();
}
//for (Thread thread : list) {
// thread.join();
//}
thread1.join();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "#" + i);
shortSleep();
}
}
private static Thread create(int seq) {
return new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "#" + i);
shortSleep();
}
});
}
private static void shortSleep() {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
3e1bd911ca73f472567d37ad4c585f3fb13ffbbf | 35,225 | java | Java | Uzumzki-project/2018/ball/src/main/java/com/xiaoyi/ssm/controller/wxapp/ApiTrainTeamController.java | 15207108156/Naruto-Uzumaki | 120ecaec28948e26dfdd0205923a8f8e6bb212d0 | [
"MIT"
] | null | null | null | Uzumzki-project/2018/ball/src/main/java/com/xiaoyi/ssm/controller/wxapp/ApiTrainTeamController.java | 15207108156/Naruto-Uzumaki | 120ecaec28948e26dfdd0205923a8f8e6bb212d0 | [
"MIT"
] | null | null | null | Uzumzki-project/2018/ball/src/main/java/com/xiaoyi/ssm/controller/wxapp/ApiTrainTeamController.java | 15207108156/Naruto-Uzumaki | 120ecaec28948e26dfdd0205923a8f8e6bb212d0 | [
"MIT"
] | null | null | null | 36.654527 | 173 | 0.709042 | 11,790 | package com.xiaoyi.ssm.controller.wxapp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyi.ssm.dto.ApiMessage;
import com.xiaoyi.ssm.model.Member;
import com.xiaoyi.ssm.model.TrainCoach;
import com.xiaoyi.ssm.model.TrainCourse;
import com.xiaoyi.ssm.model.TrainEnter;
import com.xiaoyi.ssm.model.TrainOrderComment;
import com.xiaoyi.ssm.model.TrainTeam;
import com.xiaoyi.ssm.model.TrainTeamCoach;
import com.xiaoyi.ssm.model.TrainTeamCollect;
import com.xiaoyi.ssm.model.TrainTeamFeedback;
import com.xiaoyi.ssm.model.TrainTeamImage;
import com.xiaoyi.ssm.model.TrainTeamLog;
import com.xiaoyi.ssm.model.TrainTeamPhone;
import com.xiaoyi.ssm.model.Venue;
import com.xiaoyi.ssm.model.VenueCheck;
import com.xiaoyi.ssm.model.VenueEnter;
import com.xiaoyi.ssm.service.TrainCoachService;
import com.xiaoyi.ssm.service.TrainCourseService;
import com.xiaoyi.ssm.service.TrainEnterService;
import com.xiaoyi.ssm.service.TrainOrderCommentService;
import com.xiaoyi.ssm.service.TrainTeamCoachService;
import com.xiaoyi.ssm.service.TrainTeamCollectService;
import com.xiaoyi.ssm.service.TrainTeamFeedbackService;
import com.xiaoyi.ssm.service.TrainTeamImageService;
import com.xiaoyi.ssm.service.TrainTeamLogService;
import com.xiaoyi.ssm.service.TrainTeamPhoneService;
import com.xiaoyi.ssm.service.TrainTeamService;
import com.xiaoyi.ssm.service.VenueCheckService;
import com.xiaoyi.ssm.service.VenueEnterService;
import com.xiaoyi.ssm.service.VenueService;
import com.xiaoyi.ssm.util.Arith;
import com.xiaoyi.ssm.util.DateUtil;
import com.xiaoyi.ssm.util.Global;
import com.xiaoyi.ssm.util.HttpUtils;
import com.xiaoyi.ssm.util.MapUtils;
import com.xiaoyi.ssm.util.RedisUtil;
import com.xiaoyi.ssm.util.StringUtil;
import com.xiaoyi.ssm.util.Utils;
/**
* @Description: 培训机构接口控制器
* @author 宋高俊
* @date 2018年9月29日 下午7:01:57
*/
@Controller("wxappTrainTeamController")
@RequestMapping("wxapp/train/team")
public class ApiTrainTeamController {
@Autowired
private TrainTeamService trainTeamService;
@Autowired
private VenueService venueService;
@Autowired
private TrainCoachService trainCoachService;
@Autowired
private TrainCourseService trainCourseService;
@Autowired
private TrainTeamImageService trainTeamImageService;
@Autowired
private TrainTeamFeedbackService trainTeamFeedbackService;
@Autowired
private TrainTeamPhoneService trainTeamPhoneService;
@Autowired
private VenueCheckService venueCheckService;
@Autowired
private TrainEnterService trainEnterService;
@Autowired
private VenueEnterService venueEnterService;
@Autowired
private TrainOrderCommentService trainOrderCommentService;
@Autowired
private TrainTeamCollectService trainTeamCollectService;
@Autowired
private TrainTeamLogService trainTeamLogService;
@Autowired
private TrainTeamCoachService trainTeamCoachService;
/**
* @Description: 获取培训机构主页面数据
* @author 宋高俊
* @param request
* @return
* @date 2018年10月8日 下午2:48:07
*/
@RequestMapping(value = "/manager/getMyTrainTeam/details")
@ResponseBody
public ApiMessage getMyCoachDetails(HttpServletRequest request, String trainTeamId) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
// 培训机构当前教练数据
TrainTeamCoach trainTeamCoach = trainTeamCoachService.selectByMemberTeam(member.getId(), trainTeamId);
// 培训机构数据
TrainTeam trainTeam = trainTeamService.selectByPrimaryKey(trainTeamId);
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", trainTeam.getId()); // 机构ID
map.put("headImage", trainTeam.getHeadImage()); // 机构封面
map.put("title", trainTeam.getTitle()); // 机构名称
map.put("name", trainTeamCoach.getTrainCoach().getName()); // 当前教练姓名
map.put("type", trainTeamCoach.getTeachType());// 教学身份1=主教练2=教练3=助教4=其他
map.put("manager", trainTeamCoach.getManager()); // 教练所属机构身份0=普通教练1=创建人2=管理员
return new ApiMessage(200, "获取成功", map);
}
/**
* @Description: 获取机构设置
* @author 宋高俊
* @param request
* @return
* @date 2018年10月8日 下午2:48:07
*/
@RequestMapping(value = "/manager/getMyTrainTeam")
@ResponseBody
public ApiMessage getMyCoach(HttpServletRequest request, String trainTeamId) {
TrainTeam trainTeam = trainTeamService.selectByPrimaryKey(trainTeamId);
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", trainTeam.getId()); // 机构ID
map.put("title", trainTeam.getTitle()); // 机构名称
map.put("headImage", trainTeam.getHeadImage()); // 封面图
map.put("address", trainTeam.getAddress()); // 地址
map.put("longitude", trainTeam.getLongitude()); // 经度
map.put("latitude", trainTeam.getLatitude()); // 纬度
map.put("phone", trainTeam.getPhone()); // 机构电话
map.put("freeClasses", trainTeam.getFreeClasses()); // 免费试课
map.put("freeParking", trainTeam.getFreeParking()); // 免费停车
map.put("teachClass", trainTeam.getTeachClass()); // 开课科目
map.put("brandContent", trainTeam.getBrandContent()); // 机构介绍
map.put("titleFlag", trainTeam.getTitleFlag()); // 是否可以修改名称
map.put("ballHour1", trainTeam.getBallHour1());
map.put("ballHour2", trainTeam.getBallHour2());
map.put("ballHour3", trainTeam.getBallHour3());
List<String> images = new ArrayList<String>();
List<TrainTeamImage> trainTeamImages = trainTeamImageService.selectByTrainTeamID(trainTeam.getId());
for (int i = 0; i < trainTeamImages.size(); i++) {
images.add(trainTeamImages.get(i).getPath());
}
map.put("images", images); // 机构风采
return new ApiMessage(200, "获取成功", map);
}
/**
* @Description: 修改机构设置
* @author 宋高俊
* @param request
* @return
* @date 2018年10月8日 下午2:48:07
*/
@RequestMapping(value = "/manager/updateMyTrainTeam")
@ResponseBody
public ApiMessage updateMyCoach(HttpServletRequest request, TrainTeam trainTeam, String images) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
// 培训机构当前教练数据
TrainCoach trainCoach = trainCoachService.selectByMemberTeam(member.getId(), trainTeam.getId());
TrainTeamCoach trainTeamCoach = trainTeamCoachService.selectByCoachTeam(trainCoach.getId(), trainTeam.getId());
if (trainTeamCoach.getManager() != 1 && trainTeamCoach.getManager() != 2) {
return new ApiMessage(400, "权限不足");
}
trainTeam.setModifyTime(new Date());
TrainTeam lodTrainTeam = trainTeamService.selectByPrimaryKey(trainTeam.getId());
if (!lodTrainTeam.getTitle().equals(trainTeam.getTitle())) {
if (lodTrainTeam.getTitleFlag() == 1) {
trainTeam.setTitleFlag(0);
} else {
return new ApiMessage(400, "每月名称只可修改一次");
}
}
int flag = trainTeamService.updateByPrimaryKeySelective(trainTeam);
if (flag > 0) {
trainTeamImageService.deleteByTeamAll(trainTeam.getId());
String[] urls = images.split(";");
for (int i = 0; i < urls.length; i++) {
TrainTeamImage trainTeamImage = new TrainTeamImage();
trainTeamImage.setId(Utils.getUUID());
trainTeamImage.setCreateTime(new Date());
trainTeamImage.setModifyTime(new Date());
trainTeamImage.setPath(urls[i]);
trainTeamImage.setTrainTeamId(trainTeam.getId());
trainTeamImageService.insertSelective(trainTeamImage);
}
TrainTeamLog trainTeamLog = new TrainTeamLog();
trainTeamLog.setId(Utils.getUUID());
trainTeamLog.setCreateTime(new Date());
trainTeamLog.setTrainTeamId(trainTeam.getId());
trainTeamLog.setContent(member.getAppnickname()+"在客户端修改培训机构数据");
trainTeamLogService.insertSelective(trainTeamLog);
return new ApiMessage(200, "修改成功");
} else {
return new ApiMessage(400, "修改失败");
}
}
/**
* @Description: 获取所有的教学场地
* @author 宋高俊
* @param request
* @return
* @date 2018年10月10日 上午11:37:26
*/
@RequestMapping(value = "/manager/getMyTrainVenue")
@ResponseBody
public ApiMessage getMyTrainVenue(HttpServletRequest request, String trainTeamId) {
List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
// 可用的状态
List<Venue> listVenue = venueService.selectByTrainTeamID(trainTeamId);
for (int i = 0; i < listVenue.size(); i++) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", listVenue.get(i).getId()); // 场地ID
map.put("headImage", listVenue.get(i).getImage()); // 封面图
map.put("title", listVenue.get(i).getName()); // 场地名称
map.put("address", listVenue.get(i).getAddress()); // 场地地址
map.put("lnt", listVenue.get(i).getLongitude()); // 经度
map.put("lat", listVenue.get(i).getLatitude()); // 纬度
map.put("type", "1"); // 审核状态(0=审核中1=审核通过2=审核不通过)
listMaps.add(map);
}
// 待审的状态
List<VenueCheck> listVenueCheck = venueCheckService.selectByTrainTeamID(trainTeamId);
for (int i = 0; i < listVenueCheck.size(); i++) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", listVenueCheck.get(i).getId()); // 场地ID
map.put("headImage", listVenueCheck.get(i).getHeadImage()); // 封面图
map.put("title", listVenueCheck.get(i).getTitle()); // 场地名称
map.put("address", listVenueCheck.get(i).getAddress()); // 场地地址
map.put("lnt", listVenueCheck.get(i).getLng()); // 经度
map.put("lat", listVenueCheck.get(i).getLat()); // 纬度
map.put("type", listVenueCheck.get(i).getCheckFlag()); // 审核状态(0=审核中1=审核通过2=审核不通过)
listMaps.add(map);
}
return new ApiMessage(200, "获取成功", listMaps);
}
/**
* @Description: 根据场地名和经纬度获取教学场地
* @author 宋高俊
* @param request
* @return
* @date 2018年10月10日 上午11:37:26
*/
@RequestMapping(value = "/manager/searchMyTrainVenue")
@ResponseBody
public ApiMessage searchMyTrainVenue(HttpServletRequest request, String name, Double longitude, Double latitude) {
// 用户数据
// String token = (String) request.getAttribute("token");
// Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
// // 根据用户ID查询教练数据
// TrainCoach trainCoach = trainCoachService.selectByMemberId(member.getId());
List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
List<Venue> list = venueService.selectTrainVenue(name, longitude, latitude);
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", list.get(i).getId()); // 场地ID
map.put("title", list.get(i).getName()); // 场地名称
map.put("address", list.get(i).getAddress()); // 场地地址
map.put("lnt", list.get(i).getLongitude()); // 经度
map.put("lat", list.get(i).getLatitude()); // 纬度
listMaps.add(map);
}
return new ApiMessage(200, "获取成功", listMaps);
}
/**
* @Description: 根据ID删除教学场地
* @author 宋高俊
* @param request
* @return
* @date 2018年10月10日 上午11:37:26
*/
@RequestMapping(value = "/manager/deleteMyTrainVenue")
@ResponseBody
public ApiMessage deleteMyTrainVenue(HttpServletRequest request, String id, int type, String trainTeamId) {
if (type == 1) {
// 根据培训机构ID删除场地
int flag = venueService.deleteByTeamVenue(trainTeamId, id);
if (flag > 0) {
TrainTeam trainTeam = trainTeamService.selectByPrimaryKey(trainTeamId);
trainTeam.setVenueNumber(trainTeam.getVenueNumber() - 1);
trainTeamService.updateByPrimaryKeySelective(trainTeam);
return new ApiMessage(200, "删除成功");
}
}else {
int flag = venueCheckService.deleteByPrimaryKey(id);
if (flag > 0) {
return new ApiMessage(200, "删除成功");
}
}
return new ApiMessage(400, "删除失败");
}
/**
* @Description: 保存教学场地
* @author 宋高俊
* @param request
* @return
* @date 2018年10月10日 下午2:43:48
*/
@RequestMapping(value = "/manager/saveMyTrainVenue")
@ResponseBody
public ApiMessage saveMyTrainVenue(HttpServletRequest request, String title, String address, double longitude,
double latitude, String headImage, String phone, String content, Integer type, String trainTeamId) {
// 根据用户ID查询教练数据
VenueCheck vc = new VenueCheck();
vc.setId(Utils.getUUID());
vc.setCreateTime(new Date());
vc.setModifyTime(new Date());
vc.setTitle(title);
vc.setBallType(type);
vc.setPhone(phone);
vc.setContent(content);
vc.setLng(longitude);
vc.setLat(latitude);
vc.setAddress(address);
vc.setTrainTeamId(trainTeamId);
vc.setCheckFlag(0);
int flag = venueCheckService.insertSelective(vc);
if (flag > 0) {
// // 增加培训机构使用场地
// TrainTeamVenue trainTeamVenue = new TrainTeamVenue();
// trainTeamVenue.setId(Utils.getUUID());
// trainTeamVenue.setTrainTeamId(trainCoach.getTrainTeamId());
// trainTeamVenue.setTrainVenueId(vc.getId());
// venueService.saveTeamVenue(trainTeamVenue);
// // 修改培训机构使用场地数量
// TrainTeam trainTeam = trainTeamService.selectByPrimaryKey(trainCoach.getTrainTeamId());
// trainTeam.setVenueNumber(trainTeam.getVenueNumber() + 1);
// trainTeamService.updateByPrimaryKeySelective(trainTeam);
return new ApiMessage(200, "添加成功");
} else {
return new ApiMessage(400, "添加失败");
}
}
/**
* @Description: 反馈线下报名
* @author 宋高俊
* @param request
* @param content
* @return
* @date 2018年10月12日 上午10:47:38
*/
@RequestMapping(value = "/manager/saveTrainTeamFeedback")
@ResponseBody
public ApiMessage saveTrainTeamFeedback(HttpServletRequest request, String content, String id) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
TrainTeamFeedback trainTeamFeedback = new TrainTeamFeedback();
trainTeamFeedback.setId(Utils.getUUID());
trainTeamFeedback.setContent(content);
trainTeamFeedback.setCreateTime(new Date());
trainTeamFeedback.setMemberId(member.getId());
trainTeamFeedback.setTrainTeamId(id);
int flag = trainTeamFeedbackService.insertSelective(trainTeamFeedback);
if (flag > 0) {
return new ApiMessage(200, "添加成功");
} else {
return new ApiMessage(400, "添加失败");
}
}
/**
* @Description: 统计拨打电话次数
* @author 宋高俊
* @param request
* @param id
* @return
* @date 2018年10月15日 上午11:35:27
*/
@RequestMapping(value = "/manager/countTrainTeamPhone")
@ResponseBody
public ApiMessage countTrainTeamPhone(HttpServletRequest request, String id) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
TrainTeamPhone trainTeamPhone = new TrainTeamPhone();
trainTeamPhone.setId(Utils.getUUID());
trainTeamPhone.setCreateTime(new Date());
trainTeamPhone.setMemberId(member.getId());
trainTeamPhone.setTrainTeamId(id);
int flag = trainTeamPhoneService.insertSelective(trainTeamPhone);
if (flag > 0) {
return new ApiMessage(200, "添加成功");
} else {
return new ApiMessage(400, "添加失败");
}
}
/**
* @Description: 培训机构入驻申请接口
* @author 宋高俊
* @param request
* @param trainEnter
* @return
* @date 2018年10月17日 下午3:36:38
*/
@RequestMapping(value = "/addTrainEnter")
@ResponseBody
public ApiMessage addTrainEnter(HttpServletRequest request, TrainEnter trainEnter) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
trainEnter.setId(Utils.getUUID());
trainEnter.setCreateTime(new Date());
trainEnter.setMemberId(member.getId());
trainEnter.setCheckFlag(0);
int flag = trainEnterService.insertSelective(trainEnter);
if (flag > 0) {
return new ApiMessage(200, "添加成功");
} else {
return new ApiMessage(400, "添加失败");
}
}
/**
* @Description: 场馆入驻申请接口
* @author 宋高俊
* @param request
* @return
* @date 2018年10月17日 下午3:36:38
*/
@RequestMapping(value = "/addVenueEnter")
@ResponseBody
public ApiMessage addVenueEnter(HttpServletRequest request, VenueEnter venueEnter) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
// 使用百度地图根据经纬度获取地址信息
String jsonString = HttpUtils.sendGet("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=" + venueEnter.getLatitude() + "," + venueEnter.getLongitude()
+ "&output=json&pois=0&ak=" + Global.Baidu_Map_KRY, null);
if (!StringUtil.isBank(jsonString)) {
try {
jsonString = jsonString.replace("renderReverse&&renderReverse(", "");
jsonString = jsonString.substring(0, jsonString.length() - 1);
JSONObject jsonObject = JSONObject.parseObject(jsonString);
String cityName = jsonObject.getJSONObject("result").getJSONObject("addressComponent").getString("city");
String districtName = jsonObject.getJSONObject("result").getJSONObject("addressComponent").getString("district");
if (!StringUtil.isBank(cityName)) {
cityName = cityName.substring(0, cityName.length() - 1);
} else {
return new ApiMessage(400, "城市不存在");
}
if (StringUtil.isBank(districtName)) {
districtName = cityName;
} else {
districtName = districtName.substring(0, districtName.length() - 1);
}
venueEnter.setCityName(cityName);
venueEnter.setDistrictName(districtName);
} catch (Exception e) {
e.printStackTrace();
}
}
venueEnter.setId(Utils.getUUID());
venueEnter.setCreateTime(new Date());
venueEnter.setMemberId(member.getId());
venueEnter.setCheckFlag(0);
int flag = venueEnterService.insertSelective(venueEnter);
if (flag > 0) {
return new ApiMessage(200, "添加成功");
} else {
return new ApiMessage(400, "添加失败");
}
}
/**
* @Description: 获取初始化参数
* @author 宋高俊
* @return
* @date 2018年10月18日 下午2:58:34
*/
@RequestMapping(value = "/getVenueEnter")
@ResponseBody
public ApiMessage getVenueEnter(HttpServletRequest request) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
List<TrainTeam> list = trainTeamService.selectByMemberManager(member.getId(), 1);
List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", list.get(i).getId()); // 机构ID
map.put("title", list.get(i).getTitle()); // 机构名称
listMaps.add(map);
}
return new ApiMessage(200, "获取成功", listMaps);
}
/**
* @Description: 根据名称模糊查询场馆
* @author 宋高俊
* @param name
* @return
* @date 2018年10月18日 下午2:58:34
*/
@RequestMapping(value = "/likeVenueName")
@ResponseBody
public ApiMessage likeVenueName(String name) {
List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
List<Venue> list = venueService.selectByName(name);
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", list.get(i).getId()); // 场地ID
map.put("name", list.get(i).getName()); // 场地名称
map.put("address", list.get(i).getAddress()); // 场地地址
map.put("contactPhone", list.get(i).getContactPhone()); // 场地电话
listMaps.add(map);
}
return new ApiMessage(200, "获取成功", listMaps);
}
/**
* @Description: 根据场馆查询驻场的培训机构
* @author 宋高俊
* @param id
* @return
* @date 2018年10月18日 下午3:49:46
*/
@RequestMapping(value = "/enterTrainTeam")
@ResponseBody
public ApiMessage enterTrainTeam(String id, Double lng, Double lat) {
List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
List<TrainTeam> list =trainTeamService.selectByVenue(id);
for (int i = 0; i < list.size(); i++) {
TrainTeam trainTeam = list.get(i);
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", trainTeam.getId()); // ID
map.put("headImage", trainTeam.getHeadImage()); // 封面图片
map.put("title", trainTeam.getTitle()); // 培训机构名称
map.put("venueNumber", trainTeam.getVenueNumber()); // 开课球馆数量
map.put("area", (int) MapUtils.getDistance(lng, lat, trainTeam.getLongitude(), trainTeam.getLatitude())); // 距离
map.put("freeParking", trainTeam.getFreeParking()); // 是否能免费停车
map.put("freeClasses", trainTeam.getFreeClasses()); // 是否能免费试课
map.put("teachClass", trainTeam.getTeachClass()); // 开设科目
map.put("trainOrderCommentSum", trainOrderCommentService.countByTeamId(trainTeam.getId(), DateUtil.getPreTime(new Date(), 4, -2))); // 近期上课人数
map.put("minAmount", trainTeam.getMinAmount().intValue()); // 最低价格
listmap.add(map);
}
return new ApiMessage(200, "获取成功", listmap);
}
/**
* @Description: 场馆附近的培训机构
* @author 宋高俊
* @param id
* @return
* @date 2018年10月24日 上午10:36:15
*/
@RequestMapping(value = "/nearbyTrainTeam")
@ResponseBody
public ApiMessage nearbyTrainTeam(String id, int maxArea) {
Venue venue = venueService.selectByPrimaryKey(id);
double offset = 0.5;
double lng1 = Arith.sub(venue.getLongitude(), offset);
double lng2 = Arith.add(venue.getLongitude(), offset);
double lat1 = Arith.sub(venue.getLatitude(), offset);
double lat2 = Arith.add(venue.getLatitude(), offset);
List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
List<TrainTeam> list =trainTeamService.selectByNearbyMapTrainTeam(lng1, lng2, lat1, lat2);
for (int i = 0; i < list.size(); i++) {
TrainTeam trainTeam = list.get(i);
int area = (int) MapUtils.getDistance(venue.getLongitude(), venue.getLatitude(), trainTeam.getLongitude(), trainTeam.getLatitude());
if (area > maxArea) {
continue;
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", trainTeam.getId()); // ID
map.put("headImage", trainTeam.getHeadImage()); // 封面图片
map.put("title", trainTeam.getTitle()); // 培训机构名称
map.put("venueNumber", trainTeam.getVenueNumber()); // 开课球馆数量
map.put("area", area); // 距离
map.put("freeParking", trainTeam.getFreeParking()); // 是否能免费停车
map.put("freeClasses", trainTeam.getFreeClasses()); // 是否能免费试课
map.put("teachClass", trainTeam.getTeachClass()); // 开设科目
map.put("trainOrderCommentSum", trainOrderCommentService.countByTeamId(trainTeam.getId(), DateUtil.getPreTime(new Date(), 4, -2))); // 近期上课人数
map.put("minAmount", trainTeam.getMinAmount().intValue()); // 最低价格
listmap.add(map);
}
return new ApiMessage(200, "获取成功", listmap);
}
/**
* @Description: 收藏/取消收藏培训机构
* @author 宋高俊
* @param collectFlag 1 = 收藏 0 = 取消收藏
* @return
* @date 2018年10月23日 下午8:00:33
*/
@RequestMapping(value = "/collectTrainTeam")
@ResponseBody
public ApiMessage collectTrainTeam(String id, Integer collectFlag, HttpServletRequest request) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
if (collectFlag == 1) {
TrainTeamCollect ttc = new TrainTeamCollect();
ttc.setId(Utils.getUUID());
ttc.setCreateTime(new Date());
ttc.setTrainTeamId(id);
ttc.setMemberId(member.getId());
trainTeamCollectService.insertSelective(ttc);
} else {
trainTeamCollectService.deleteByIdAndMember(id, member.getId());
}
return new ApiMessage(200, "操作成功");
}
/**
* @Description: 查询我收藏的培训机构
* @author 宋高俊
* @param request
* @return
* @date 2018年10月24日 上午9:08:14
*/
@RequestMapping(value = "/getTrainTeamCollect")
@ResponseBody
public ApiMessage getTrainTeamCollect(HttpServletRequest request) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
List<TrainTeam> list =trainTeamService.selectByCollect(member.getId());
for (int i = 0; i < list.size(); i++) {
TrainTeam trainTeam = list.get(i);
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", trainTeam.getId()); // ID
map.put("headImage", trainTeam.getHeadImage()); // 封面图片
map.put("title", trainTeam.getTitle()); // 培训机构名称
map.put("freeParking", trainTeam.getFreeParking()); // 是否能免费停车
map.put("freeClasses", trainTeam.getFreeClasses()); // 是否能免费试课
map.put("teachClass", trainTeam.getTeachClass()); // 开设科目
map.put("trainOrderCommentSum", trainOrderCommentService.countByTeamId(trainTeam.getId(), DateUtil.getPreTime(new Date(), 4, -2))); // 近期上课人数
listmap.add(map);
}
return new ApiMessage(200, "获取成功", listmap);
}
/**
* @Description: 获取培训机构课程详细数据
* @author 宋高俊
* @return
* @date 2018年9月30日 上午11:13:14
*/
@RequestMapping(value = "/trainTeam/course/details")
@ResponseBody
public ApiMessage trainTeamcoursedetails(HttpServletRequest request, String id) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
TrainCourse trainCourse = trainCourseService.selectByPrimaryKey(id);
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", trainCourse.getId()); // ID
map.put("headImage", trainCourse.getHeadImage()); // 封面
map.put("title", trainCourse.getTitle()); // 标题
map.put("amount", trainCourse.getAmount()); // 价格
map.put("minAge", trainCourse.getMinAge() + "~" + trainCourse.getMaxAge() + "岁"); // 适合年龄
map.put("classHour", trainCourse.getClassHour() + "课时"); // 价格
map.put("toTeachNumber", trainCourse.getToTeachNumber() + "人以下"); // 适合人数
map.put("toTeachTime", trainCourse.getToTeachTime()); // 上课时间
map.put("classTrait", trainCourse.getClassTrait().split(";")); // 课程亮点
TrainCoach trainCoach = trainCoachService.selectByPrimaryKey(trainCourse.getTrainCoachId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", trainCoach.getId()); // ID
jsonObject.put("headImage", trainCoach.getHeadImage()); // 头像
jsonObject.put("name", trainCoach.getName()); // 姓名
TrainTeamCoach trainTeamCoach = trainTeamCoachService.selectByCoachTeam(trainCoach.getId(), trainCourse.getTrainTeamId());
// 教练身份
jsonObject.put("type", trainTeamCoach.getTeachType() == 1 ? "主教练" : trainTeamCoach.getTeachType() == 2 ? "教练" : trainTeamCoach.getTeachType() == 3 ? "助教" : "其他"); // 类型
jsonObject.put("workingAge", trainCoach.getWorkingAge()); // 教龄
map.put("trainCoach", jsonObject); // 授课教练
map.put("payMake", trainCourse.getPayMake()); // 预约信息
map.put("payAdjust", trainCourse.getPayAdjust()); // 调课说明
map.put("payRefund", trainCourse.getPayRefund()); // 退款说明
map.put("applyFlag", trainCourse.getApplyFlag()); // 是否允许报名
TrainCourse tc = trainCourseService.selectByMember(id, member.getId());
if (tc != null) {
map.put("collectFlag", 1); // 是否收藏
}else {
map.put("collectFlag", 0); // 是否收藏
}
return new ApiMessage(200, "获取成功", map);
}
/**
* @Description: 获取培训机构详情数据
* @author 宋高俊
* @return
* @date 2018年9月30日 上午11:13:14
*/
@RequestMapping(value = "/trainTeam/details")
@ResponseBody
public ApiMessage trainTeamdetails(HttpServletRequest request, String id, Double lng, Double lat) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
TrainTeam trainTeam = trainTeamService.selectByPrimaryKey(id);
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", trainTeam.getId()); // ID
map.put("headImage", trainTeam.getHeadImage()); // 封面图片
map.put("title", trainTeam.getTitle()); // 名称
map.put("phone", trainTeam.getPhone()); // 电话
map.put("brandContent", trainTeam.getBrandContent()); // 介绍
JSONArray venueJsonArray = new JSONArray();
List<Venue> listVenues = venueService.selectByTrainTeamID(id);
for (int i = 0; i < listVenues.size(); i++) {
Venue venue = listVenues.get(i);
JSONObject jsonObject = new JSONObject();
jsonObject.put("lng", venue.getLongitude()); // 经度
jsonObject.put("lat", venue.getLatitude()); // 纬度
jsonObject.put("title", venue.getName()); // 场馆名
jsonObject.put("area", (int) MapUtils.getDistance(lng, lat, trainTeam.getLongitude(), trainTeam.getLatitude())); // 距离
jsonObject.put("address", venue.getAddress()); // 详细地址
venueJsonArray.add(jsonObject);
}
map.put("trainVenues", venueJsonArray); // 地址集合
JSONArray coachJsonArray = new JSONArray();
List<TrainCoach> listCoachs = trainCoachService.selectByTrainTeamID(id);
for (int i = 0; i < listCoachs.size(); i++) {
TrainCoach trainCoach = listCoachs.get(i);
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", trainCoach.getId()); // id
jsonObject.put("headImage", trainCoach.getHeadImage()); // 头像
jsonObject.put("name", trainCoach.getName()); // 姓名
jsonObject.put("workingAge", trainCoach.getWorkingAge()); // 教龄
coachJsonArray.add(jsonObject);
}
map.put("trainCoachs", coachJsonArray); // 教练集合
// JSONArray classJsonArray = new JSONArray();
// List<TrainCourse> listCourses = trainCourseService.selectByTrainTeamID(id);
// for (int i = 0; i < listCourses.size(); i++) {
// TrainCourse trainCourse = listCourses.get(i);
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("id", trainCourse.getId()); // ID
// jsonObject.put("headImage", trainCourse.getHeadImage()); // 封面
// jsonObject.put("title", trainCourse.getTitle()); // 标题
// jsonObject.put("amount", trainCourse.getAmount()); // 价格
// jsonObject.put("minAge", trainCourse.getMinAge() + "~" + trainCourse.getMaxAge() + "岁"); // 适合年龄
// jsonObject.put("classHour", trainCourse.getClassHour() + "课时"); // 价格
// jsonObject.put("toTeachNumber", trainCourse.getToTeachNumber() + "人以下"); // 价格
// classJsonArray.add(jsonObject);
// }
// map.put("trainCourses", classJsonArray); // 课程集合
TrainTeamCollect ttc = trainTeamCollectService.selectByMember(id, member.getId());
if (ttc != null) {
map.put("collectFlag", 1); // 是否收藏
}else {
map.put("collectFlag", 0); // 是否收藏
}
// 总评价数
map.put("commentSum", trainOrderCommentService.countByTeamAll(id));
// 近期10条评价
List<TrainOrderComment> list = trainOrderCommentService.selectByTeamTen(id);
List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>();
for (int i = 0; i < list.size(); i++) {
Map<String, Object> commentMap = new HashMap<String, Object>();
commentMap.put("id", list.get(i).getId()); // ID
commentMap.put("createTime", DateUtil.getFormat(list.get(i).getCreateTime())); // 时间
commentMap.put("title", list.get(i).getTrainCourse().getTitle()); // 课程名称
commentMap.put("classHour", list.get(i).getClassHour()); // 课时
commentMap.put("appnickname", list.get(i).getMember().getAppnickname()); // 用户昵称
commentMap.put("content", list.get(i).getContent()); // 评价内容
commentMap.put("appavatarurl", list.get(i).getMember().getAppavatarurl()); // 用户头像
commentMap.put("headImage", list.get(i).getTrainCoach().getHeadImage()); // 教练头像
commentMap.put("commentSelect", list.get(i).getCommentSelect()); // 评价选择(1=好评2=中评3=差评4=拒绝评价)
maps.add(commentMap);
}
map.put("commentTen", maps);
return new ApiMessage(200, "获取成功", map);
}
/**
* @Description: 机构管理数据
* @author 宋高俊
* @param request
* @param trainTeamId
* @return
* @date 2018年11月5日 下午3:52:39
*/
@RequestMapping(value = "/manager/getTrainTeamManager")
@ResponseBody
public ApiMessage getTrainTeamManager(HttpServletRequest request, String trainTeamId) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
// 判断是否是机构的教练
TrainTeamCoach trainTeamCoach = trainTeamCoachService.selectByMemberTeam(member.getId(), trainTeamId);
if (trainTeamCoach == null) {
return new ApiMessage(400, "您不是该机构的教练");
}
TrainTeam trainTeam = trainTeamService.selectByPrimaryKey(trainTeamId);
Map<String, Object> map = new HashMap<String, Object>();
// 可用的状态
List<Venue> listVenue = venueService.selectByTrainTeamID(trainTeamId);
// 待审的状态
List<VenueCheck> listVenueCheck = venueCheckService.selectByTrainTeamID(trainTeamId);
List<TrainTeamCoach> list = trainTeamCoachService.selectByTrainTeamID(trainTeamId);
int trainVenue = listVenue.size() + listVenueCheck.size();
map.put("trainVenueSum", trainVenue);// 教学场地数量
map.put("trainCoachSum", list.size());// 教练团队数量
TrainCoach trainCoach = trainCoachService.selectByPrimaryKey(trainTeam.getTrainCoachId());
map.put("coachId", trainCoach.getId());// 回款ID
map.put("account", trainCoach.getName());// 回款账号
TrainCoach trainCoachManager = trainCoachService.selectByTeamManager(trainTeamId);
map.put("trainCoachManagerId", trainCoachManager.getId());// 馆长ID
map.put("manager", trainTeamCoach.getManager());// 教练身份0=外聘1=馆长2=管理
return new ApiMessage(200, "获取成功", map);
}
/**
* @Description: 设置机构回款账户
* @author 宋高俊
* @param request
* @param trainTeamId
* @return
* @date 2018年11月6日 下午3:29:38
*/
@RequestMapping(value = "/manager/setTrainCoach")
@ResponseBody
public ApiMessage setTrainCoach(HttpServletRequest request, String trainTeamId, String trainCoachId) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
TrainTeamCoach trainTeamCoach = trainTeamCoachService.selectByMemberTeam(member.getId(), trainTeamId);
if (trainTeamCoach.getManager() == 1) {
TrainTeam trainTeam = new TrainTeam();
trainTeam.setId(trainTeamId);
trainTeam.setTrainCoachId(trainCoachId);
trainTeamService.updateByPrimaryKeySelective(trainTeam);
return new ApiMessage(200, "修改成功");
}else {
return new ApiMessage(400, "当前用户权限不足");
}
}
/**
* @Description: 转让馆长接口
* @author 宋高俊
* @param request
* @return
* @date 2018年10月18日 下午7:49:43
*/
@RequestMapping(value = "/trainTeam/updateManager")
@ResponseBody
public ApiMessage updateManager(HttpServletRequest request, String trainTeamId, String trainCoachId) {
// 用户数据
String token = (String) request.getAttribute("token");
Member member = (Member) RedisUtil.getRedisOne(Global.redis_member, token);
// 查询当前身份是否是馆长
TrainTeamCoach trainTeamCoach = trainTeamCoachService.selectByMemberTeam(member.getId(), trainTeamId);
if (trainTeamCoach != null) {
if (trainTeamCoach.getManager() == 1) {
TrainTeamCoach newTrainTeamCoach = trainTeamCoachService.selectByCoachTeam(trainCoachId,trainTeamId);
if (newTrainTeamCoach != null) {
trainTeamCoach.setManager(2);
trainTeamCoachService.updateByPrimaryKeySelective(trainTeamCoach);
newTrainTeamCoach.setManager(1);
trainTeamCoachService.updateByPrimaryKeySelective(newTrainTeamCoach);
return new ApiMessage(200, "修改成功");
}
}
}
return new ApiMessage(400, "权限不足");
}
@RequestMapping(value = "/managerFlag")
@ResponseBody
public ApiMessage managerFlag(HttpServletRequest request) {
return new ApiMessage(400, "权限不足");
}
}
|
3e1bd93a07985ff3bd184652a58e7ae489a45c47 | 1,770 | java | Java | src/main/java/com/sisllc/mathformulas/ci/ch02/Q27PalindromeB.java | javaugi/cimathformulas | 5a3f16b8ecdac12aef0affb58bf6ed61325a862a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/sisllc/mathformulas/ci/ch02/Q27PalindromeB.java | javaugi/cimathformulas | 5a3f16b8ecdac12aef0affb58bf6ed61325a862a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/sisllc/mathformulas/ci/ch02/Q27PalindromeB.java | javaugi/cimathformulas | 5a3f16b8ecdac12aef0affb58bf6ed61325a862a | [
"Apache-2.0"
] | null | null | null | 27.230769 | 92 | 0.520339 | 11,791 | package com.sisllc.mathformulas.ci.ch02;
import com.sisllc.mathformulas.ci.lib.LinkedListNode;
import java.util.Stack;
/**
*
*
* @author javaugi
* @version $LastChangedRevision $LastChangedDate Last Modified Author:
* $LastChangedBy
*/
public class Q27PalindromeB {
public static boolean isPalindrome(LinkedListNode head) {
LinkedListNode fast = head;
LinkedListNode slow = head;
Stack<Integer> stack = new Stack<Integer>();
while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
/* Has odd number of elements, so skip the middle */
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
int top = stack.pop().intValue();
System.out.println(slow.data + " " + top);
if (top != slow.data) {
return false;
}
slow = slow.next;
}
return true;
}
public static void main(String[] args) {
int length = 9;
LinkedListNode[] nodes = new LinkedListNode[length];
for (int i = 0; i < length; i++) {
nodes[i] = new LinkedListNode(i >= length / 2 ? length - i - 1 : i, null, null);
}
for (int i = 0; i < length; i++) {
if (i < length - 1) {
nodes[i].setNext(nodes[i + 1]);
}
if (i > 0) {
nodes[i].setPrevious(nodes[i - 1]);
}
}
//nodes[length - 2].data = 9; // Uncomment to ruin palindrome
LinkedListNode head = nodes[0];
System.out.println(head.printForward());
System.out.println(isPalindrome(head));
}
}
|
3e1bd95a30b1e367dbb79f1abf5cb9416da7d1a0 | 470 | java | Java | service-p/src/main/java/com/ouyeel/provider/servicep/SpringBootServletInitializr.java | r2ys/dubbo-MonitoringRetry | e45142c44ae20f105c4c2585ccff3fef18dd24af | [
"Apache-2.0"
] | null | null | null | service-p/src/main/java/com/ouyeel/provider/servicep/SpringBootServletInitializr.java | r2ys/dubbo-MonitoringRetry | e45142c44ae20f105c4c2585ccff3fef18dd24af | [
"Apache-2.0"
] | null | null | null | service-p/src/main/java/com/ouyeel/provider/servicep/SpringBootServletInitializr.java | r2ys/dubbo-MonitoringRetry | e45142c44ae20f105c4c2585ccff3fef18dd24af | [
"Apache-2.0"
] | 1 | 2022-01-04T14:26:02.000Z | 2022-01-04T14:26:02.000Z | 24.736842 | 81 | 0.821277 | 11,792 | package com.ouyeel.provider.servicep;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
* Author Black
* Date 2017/11/21
* Time 10:42
*/
public class SpringBootServletInitializr extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ServicePApplication.class);
}
}
|
3e1bd976e89f32c8037fc7335e828c66793b604c | 1,861 | java | Java | mcr-scheduler/src/main/java/edu/tamu/aser/internaljuc/Reex_AbstractOwnableSynchronizer.java | WingedVampires/GC-MCR | e9b1ec263e247676620fb146dea99b526c4f5c82 | [
"BSD-3-Clause"
] | 45 | 2017-11-22T19:40:44.000Z | 2021-06-07T03:20:39.000Z | mcr-scheduler/src/main/java/edu/tamu/aser/internaljuc/Reex_AbstractOwnableSynchronizer.java | WingedVampires/GC-MCR | e9b1ec263e247676620fb146dea99b526c4f5c82 | [
"BSD-3-Clause"
] | 5 | 2017-11-28T16:05:54.000Z | 2020-09-13T06:23:43.000Z | mcr-scheduler/src/main/java/edu/tamu/aser/internaljuc/Reex_AbstractOwnableSynchronizer.java | WingedVampires/GC-MCR | e9b1ec263e247676620fb146dea99b526c4f5c82 | [
"BSD-3-Clause"
] | 15 | 2017-08-29T20:43:15.000Z | 2020-11-18T14:17:51.000Z | 31.542373 | 73 | 0.700699 | 11,793 | /*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package edu.tamu.aser.internaljuc;
/**
* A synchronizer that may be exclusively owned by a thread. This
* class provides a basis for creating locks and related synchronizers
* that may entail a notion of ownership. The
* <tt>AbstractOwnableSynchronizer</tt> class itself does not manage or
* use this information. However, subclasses and tools may use
* appropriately maintained values to help control and monitor access
* and provide diagnostics.
*
* @since 1.6
* @author Doug Lea
*/
public abstract class Reex_AbstractOwnableSynchronizer
implements java.io.Serializable {
/** Use serial ID even though all fields transient. */
private static final long serialVersionUID = 3737899427754241961L;
/**
* Empty constructor for use by subclasses.
*/
protected Reex_AbstractOwnableSynchronizer() { }
/**
* The current owner of exclusive mode synchronization.
*/
private transient Thread exclusiveOwnerThread;
/**
* Sets the thread that currently owns exclusive access. A
* <tt>null</tt> argument indicates that no thread owns access.
* This method does not otherwise impose any synchronization or
* <tt>volatile</tt> field accesses.
*/
protected final void setExclusiveOwnerThread(Thread t) {
exclusiveOwnerThread = t;
}
/**
* Returns the thread last set by
* <tt>setExclusiveOwnerThread</tt>, or <tt>null</tt> if never
* set. This method does not otherwise impose any synchronization
* or <tt>volatile</tt> field accesses.
* @return the owner thread
*/
protected final Thread getExclusiveOwnerThread() {
return exclusiveOwnerThread;
}
}
|
3e1bd9eb80b09c63ccdfa64e8aa3cd6061b86349 | 593 | java | Java | back-end/hospital-api/src/main/java/net/pladema/establishment/repository/entity/AgeGroup.java | eamanu/HistorialClinica-LaRioja | 988cd5fae4b9b9bd3a17518b7e55585df5ef7218 | [
"Apache-2.0"
] | null | null | null | back-end/hospital-api/src/main/java/net/pladema/establishment/repository/entity/AgeGroup.java | eamanu/HistorialClinica-LaRioja | 988cd5fae4b9b9bd3a17518b7e55585df5ef7218 | [
"Apache-2.0"
] | null | null | null | back-end/hospital-api/src/main/java/net/pladema/establishment/repository/entity/AgeGroup.java | eamanu/HistorialClinica-LaRioja | 988cd5fae4b9b9bd3a17518b7e55585df5ef7218 | [
"Apache-2.0"
] | 1 | 2021-12-31T09:59:53.000Z | 2021-12-31T09:59:53.000Z | 20.448276 | 52 | 0.765599 | 11,794 | package net.pladema.establishment.repository.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "age_group")
@Getter
@Setter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class AgeGroup {
@Id
@Column(name = "id")
@EqualsAndHashCode.Include
private Short id;
@Column(name = "description", nullable = false)
private String description;
}
|
3e1bda120d1fb0e47cfd90f58af21c2af539e51e | 11,121 | java | Java | ps/src/main/java/edu/snu/spl/cruise/ps/mlapps/lasso/LassoTrainer.java | snuspl/cruise | 7c250f030c0327ba0f44905c9c65068f9ff211a2 | [
"Apache-2.0"
] | 24 | 2017-12-18T11:34:56.000Z | 2020-10-08T10:17:48.000Z | ps/src/main/java/edu/snu/spl/cruise/ps/mlapps/lasso/LassoTrainer.java | snuspl/cruise | 7c250f030c0327ba0f44905c9c65068f9ff211a2 | [
"Apache-2.0"
] | null | null | null | ps/src/main/java/edu/snu/spl/cruise/ps/mlapps/lasso/LassoTrainer.java | snuspl/cruise | 7c250f030c0327ba0f44905c9c65068f9ff211a2 | [
"Apache-2.0"
] | 2 | 2018-09-08T20:46:30.000Z | 2022-02-03T06:50:16.000Z | 36.946844 | 120 | 0.694902 | 11,795 | /*
* Copyright (C) 2017 Seoul National 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 edu.snu.spl.cruise.ps.mlapps.lasso;
import edu.snu.spl.cruise.common.math.linalg.Matrix;
import edu.snu.spl.cruise.common.math.linalg.MatrixFactory;
import edu.snu.spl.cruise.common.math.linalg.VectorFactory;
import edu.snu.spl.cruise.common.math.linalg.Vector;
import edu.snu.spl.cruise.ps.CruisePSParameters.*;
import edu.snu.spl.cruise.ps.core.worker.ETModelAccessor;
import edu.snu.spl.cruise.ps.core.worker.ModelAccessor;
import edu.snu.spl.cruise.ps.core.worker.Trainer;
import edu.snu.spl.cruise.services.et.evaluator.api.Table;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.reef.tang.annotations.Parameter;
import javax.inject.Inject;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link Trainer} class for the LassoREEF application.
* Based on lasso regression via stochastic coordinate descent, proposed in
* S. Shalev-Shwartz and A. Tewari, Stochastic Methods for l1-regularized Loss Minimization, 2011.
*
* For each mini-batch, the trainer pulls the whole model from the server,
* and then update all the model values.
* The trainer computes and pushes the optimal model value for all the dimensions to
* minimize the objective function - square loss with l1 regularization.
*/
final class LassoTrainer implements Trainer<LassoData> {
private static final Logger LOG = Logger.getLogger(LassoTrainer.class.getName());
/**
* Period(epochs) to print model parameters to check whether the training is working or not.
*/
private static final int PRINT_MODEL_PERIOD = 50;
/**
* Threshold for a number to be regarded as zero.
*/
private static final double ZERO_THRESHOLD = 1e-9;
private final int numFeatures;
private final float lambda;
private float stepSize;
private final double decayRate;
private final int decayPeriod;
private Vector oldModel;
private Vector newModel;
private final VectorFactory vectorFactory;
private final MatrixFactory matrixFactory;
private final ModelAccessor<Integer, Vector, Vector> modelAccessor;
/**
* A list from 0 to {@code numPartitions} that will be used during {@link #pullModels()} and {@link #pushGradients()}.
*/
private List<Integer> modelPartitionIndices;
/**
* Number of model partitions.
*/
private final int numPartitions;
/**
* Number of features of each model partition.
*/
private final int numFeaturesPerPartition;
@Inject
private LassoTrainer(final ModelAccessor<Integer, Vector, Vector> modelAccessor,
@Parameter(Lambda.class) final float lambda,
@Parameter(NumFeatures.class) final int numFeatures,
@Parameter(StepSize.class) final float stepSize,
@Parameter(DecayRate.class) final double decayRate,
@Parameter(DecayPeriod.class) final int decayPeriod,
@Parameter(NumFeaturesPerPartition.class) final int numFeaturesPerPartition,
final VectorFactory vectorFactory,
final MatrixFactory matrixFactory) {
this.modelAccessor = modelAccessor;
this.numFeatures = numFeatures;
this.lambda = lambda;
this.stepSize = stepSize;
this.decayRate = decayRate;
if (decayRate <= 0.0 || decayRate > 1.0) {
throw new IllegalArgumentException("decay_rate must be larger than 0 and less than or equal to 1");
}
this.decayPeriod = decayPeriod;
if (decayPeriod <= 0) {
throw new IllegalArgumentException("decay_period must be a positive value");
}
this.vectorFactory = vectorFactory;
this.matrixFactory = matrixFactory;
this.oldModel = vectorFactory.createDenseZeros(numFeatures);
if (numFeatures % numFeaturesPerPartition != 0) {
throw new IllegalArgumentException("Uneven model partitions");
}
this.numFeaturesPerPartition = numFeaturesPerPartition;
this.numPartitions = numFeatures / numFeaturesPerPartition;
this.modelPartitionIndices = new ArrayList<>(numPartitions);
for (int partitionIdx = 0; partitionIdx < numPartitions; partitionIdx++) {
modelPartitionIndices.add(partitionIdx);
}
}
@Override
public void initGlobalSettings() {
}
/**
* {@inheritDoc} <br>
* 1) Pull model from server. <br>
* 2) Compute the optimal value, dot(x_i, y - Sigma_{j != i} x_j * model(j)) / dot(x_i, x_i) for each dimension
* (in cyclic).
* When computing the optimal value, precalculate sigma_{all j} x_j * model(j) and calculate
* Sigma_{j != i} x_j * model(j) fast by just subtracting x_i * model(i)
* 3) Push value to server.
*/
@Override
public void runMiniBatch(final Collection<LassoData> miniBatchTrainingData) {
final int numInstancesToProcess = miniBatchTrainingData.size();
pullModels();
// After get feature vectors from each instances, make it concatenate them into matrix for the faster calculation.
// Pre-calculate sigma_{all j} x_j * model(j) and assign the value into 'preCalculate' vector.
final Pair<Matrix, Vector> featureMatrixAndValues = convertToFeaturesAndValues(miniBatchTrainingData);
final Matrix featureMatrix = featureMatrixAndValues.getLeft();
final Vector yValues = featureMatrixAndValues.getRight();
final Vector preCalculate = featureMatrix.mmul(newModel);
final Vector columnVector = vectorFactory.createDenseZeros(numInstancesToProcess);
// For each dimension, compute the optimal value.
for (int featureIdx = 0; featureIdx < numFeatures; featureIdx++) {
if (closeToZero(newModel.get(featureIdx))) {
continue;
}
for (int rowIdx = 0; rowIdx < numInstancesToProcess; rowIdx++) {
columnVector.set(rowIdx, featureMatrix.get(rowIdx, featureIdx));
}
final double columnNorm = columnVector.dot(columnVector);
if (closeToZero(columnNorm)) {
continue;
}
preCalculate.subi(columnVector.scale(newModel.get(featureIdx)));
newModel.set(featureIdx,
(float) sthresh((columnVector.dot(yValues.sub(preCalculate))) / columnNorm, lambda, columnNorm));
preCalculate.addi(columnVector.scale(newModel.get(featureIdx)));
}
pushGradients();
}
@Override
public void onEpochFinished(final int epochIdx) {
if ((epochIdx + 1) % PRINT_MODEL_PERIOD == 0) {
for (int i = 0; i < numFeatures; i++) {
LOG.log(Level.INFO, "model : {0}", newModel.get(i));
}
}
if (decayRate != 1 && (epochIdx + 1) % decayPeriod == 0) {
final double prevStepSize = stepSize;
stepSize *= decayRate;
LOG.log(Level.INFO, "{0} epochs have passed. Step size decays from {1} to {2}",
new Object[]{decayPeriod, prevStepSize, stepSize});
}
}
@Override
public Map<CharSequence, Double> evaluateModel(final Collection<LassoData> inputData,
final Collection<LassoData> testData,
final Table modelTable) {
// Calculate the loss value.
pullModels(modelTable);
final double trainingLoss = computeLoss(inputData);
final double testLoss = computeLoss(testData);
LOG.log(Level.INFO, "Training Loss: {0}, Test Loss: {1}", new Object[] {trainingLoss, testLoss});
final Map<CharSequence, Double> map = new HashMap<>();
map.put("training_loss", trainingLoss);
map.put("test_loss", trainingLoss);
return map;
}
/**
* Convert the training data examples into a form for more efficient computation.
* @param instances training data examples
* @return the pair of feature matrix and vector composed of y values.
*/
private Pair<Matrix, Vector> convertToFeaturesAndValues(final Collection<LassoData> instances) {
final List<Vector> features = new LinkedList<>();
final Vector values = vectorFactory.createDenseZeros(instances.size());
int instanceIdx = 0;
for (final LassoData instance : instances) {
features.add(instance.getFeature());
values.set(instanceIdx++, instance.getValue());
}
return Pair.of(matrixFactory.horzcatVecSparse(features).transpose(), values);
}
@Override
public void cleanup() {
}
/**
* Pull up-to-date model parameters from server.
*/
private void pullModels() {
final List<Vector> partialModels = modelAccessor.pull(modelPartitionIndices);
oldModel = vectorFactory.concatDense(partialModels);
newModel = oldModel.copy();
}
/**
* Pull up-to-date model parameters from server.
*/
private void pullModels(final Table modelTable) {
final List<Vector> partialModels = ((ETModelAccessor) modelAccessor).pull(modelPartitionIndices, modelTable);
oldModel = vectorFactory.concatDense(partialModels);
newModel = oldModel.copy();
}
/**
* Push the gradients to parameter server.
*/
private void pushGradients() {
final Vector gradient = newModel.sub(oldModel);
for (int partitionIndex = 0; partitionIndex < numPartitions; ++partitionIndex) {
final int partitionStart = partitionIndex * numFeaturesPerPartition;
final int partitionEnd = (partitionIndex + 1) * numFeaturesPerPartition;
modelAccessor.push(partitionIndex, vectorFactory.createDenseZeros(numFeaturesPerPartition)
.axpy(stepSize, gradient.slice(partitionStart, partitionEnd)));
}
}
/**
* Soft thresholding function, widely used with l1 regularization.
*/
private static double sthresh(final double x, final double lambda, final double columnNorm) {
if (Math.abs(x) <= lambda / columnNorm) {
return 0;
} else if (x >= 0) {
return x - lambda / columnNorm;
} else {
return x + lambda / columnNorm;
}
}
/**
* Predict the y value for the feature value.
*/
private double predict(final Vector feature) {
return newModel.dot(feature);
}
/**
* Compute the loss value for the data.
*/
private double computeLoss(final Collection<LassoData> data) {
double squaredErrorSum = 0;
for (final LassoData entry : data) {
final Vector feature = entry.getFeature();
final double value = entry.getValue();
final double prediction = predict(feature);
squaredErrorSum += (value - prediction) * (value - prediction);
}
return squaredErrorSum;
}
/**
* @return {@code true} if the value is close to 0.
*/
private boolean closeToZero(final double value) {
return Math.abs(value) < ZERO_THRESHOLD;
}
}
|
3e1bdab3d946c38b69c288c1a6273307e89a652e | 1,233 | java | Java | asciily-foundation-springboot/src/main/java/com/asciily/foundation/config/dubbo/provider/DubboServerAnnotaionConfiguration.java | swxiao/asciily-foundation | 881ca50cd47f254fbae3037d24e841f9aab1279f | [
"Apache-2.0"
] | null | null | null | asciily-foundation-springboot/src/main/java/com/asciily/foundation/config/dubbo/provider/DubboServerAnnotaionConfiguration.java | swxiao/asciily-foundation | 881ca50cd47f254fbae3037d24e841f9aab1279f | [
"Apache-2.0"
] | null | null | null | asciily-foundation-springboot/src/main/java/com/asciily/foundation/config/dubbo/provider/DubboServerAnnotaionConfiguration.java | swxiao/asciily-foundation | 881ca50cd47f254fbae3037d24e841f9aab1279f | [
"Apache-2.0"
] | null | null | null | 29.261905 | 139 | 0.752644 | 11,796 | /**
* Copyright [2015-2017]
*
* 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.asciily.foundation.config.dubbo.provider;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import com.alibaba.dubbo.config.spring.AnnotationBean;
/**
*
* @author xiaosw<hzdkv@example.com>
* @since 2017年1月17日
*/
@Configurable
@Import(value = { DubboProviderConfiguration.class })
public class DubboServerAnnotaionConfiguration {
/**
* 启动motan
*
* @return
*/
@Bean
public AnnotationBean annotationBean() {
AnnotationBean bean = new AnnotationBean();
bean.setPackage("com");
return bean;
}
}
|
3e1bdab7586be6dbb1304864939e3d1febdfab79 | 1,897 | java | Java | src/test/java/com/orientechnologies/orient/jdbc/OrientJdbcConnectionTest.java | orientechnologies/orientdb-jdbc | 1cd2542848bfe411eafda3010a5a79ed9780de3e | [
"Apache-2.0"
] | 7 | 2015-01-26T14:47:35.000Z | 2020-04-13T15:17:18.000Z | src/test/java/com/orientechnologies/orient/jdbc/OrientJdbcConnectionTest.java | orientechnologies/orientdb-jdbc | 1cd2542848bfe411eafda3010a5a79ed9780de3e | [
"Apache-2.0"
] | 22 | 2015-01-01T06:30:54.000Z | 2016-06-01T07:06:17.000Z | src/test/java/com/orientechnologies/orient/jdbc/OrientJdbcConnectionTest.java | orientechnologies/orientdb-jdbc | 1cd2542848bfe411eafda3010a5a79ed9780de3e | [
"Apache-2.0"
] | 12 | 2015-01-02T18:00:08.000Z | 2017-06-07T04:08:37.000Z | 27.897059 | 96 | 0.727464 | 11,797 | package com.orientechnologies.orient.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;
import org.hamcrest.Matchers;
import org.junit.Test;
import static java.sql.ResultSet.CONCUR_READ_ONLY;
import static java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT;
import static java.sql.ResultSet.TYPE_FORWARD_ONLY;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.*;
public class OrientJdbcConnectionTest extends OrientJdbcBaseTest {
@Test
public void shouldCreateStatement() throws Exception {
Statement stmt = conn.createStatement();
assertNotNull(stmt);
stmt.close();
}
@Test
public void checkSomePrecondition() throws Exception {
assertFalse(conn.isClosed());
conn.isReadOnly();
conn.isValid(0);
conn.setAutoCommit(true);
assertTrue(conn.getAutoCommit());
// conn.setTransactionIsolation(Connection.TRANSACTION_NONE);
// assertEquals(Connection.TRANSACTION_NONE,
// conn.getTransactionIsolation());
}
@Test
public void shouldCreateDifferentTypeOfStatement() throws Exception {
Statement stmt = conn.createStatement();
assertNotNull(stmt);
stmt = conn.createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY);
assertNotNull(stmt);
stmt = conn.createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, HOLD_CURSORS_OVER_COMMIT);
assertNotNull(stmt);
}
@Test
public void shouldConnectUsingPool() throws Exception {
String dbUrl = "memory:test";
Properties p = new Properties();
p.setProperty("db.usePool", "TRUE");
Connection connection = DriverManager.getConnection(dbUrl, p);
assertNotNull(connection);
assertThat(connection,is(notNullValue()));
connection.close();
}
}
|
3e1bdb104e14d169747278da5561959535c9836c | 2,107 | java | Java | admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/service/persistence/PersistenceManagerContext.java | leoyey/BroadleafCommerce | d855a2a9dbf8892c3635fa99baedc4a2d6951d6e | [
"Apache-2.0"
] | 1 | 2020-09-20T00:13:18.000Z | 2020-09-20T00:13:18.000Z | admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/service/persistence/PersistenceManagerContext.java | leoyey/BroadleafCommerce | d855a2a9dbf8892c3635fa99baedc4a2d6951d6e | [
"Apache-2.0"
] | null | null | null | admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/service/persistence/PersistenceManagerContext.java | leoyey/BroadleafCommerce | d855a2a9dbf8892c3635fa99baedc4a2d6951d6e | [
"Apache-2.0"
] | null | null | null | 32.921875 | 174 | 0.738965 | 11,798 | /*
* #%L
* BroadleafCommerce Open Admin Platform
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.openadmin.server.service.persistence;
import java.util.Stack;
import org.broadleafcommerce.common.classloader.release.ThreadLocalManager;
/**
* @author Jeff Fischer
*/
public class PersistenceManagerContext {
private static final ThreadLocal<PersistenceManagerContext> BROADLEAF_PERSISTENCE_MANAGER_CONTEXT = ThreadLocalManager.createThreadLocal(PersistenceManagerContext.class);
public static PersistenceManagerContext getPersistenceManagerContext() {
return BROADLEAF_PERSISTENCE_MANAGER_CONTEXT.get();
}
public static void addPersistenceManagerContext(PersistenceManagerContext persistenceManagerContext) {
BROADLEAF_PERSISTENCE_MANAGER_CONTEXT.set(persistenceManagerContext);
}
private static void clear() {
BROADLEAF_PERSISTENCE_MANAGER_CONTEXT.remove();
}
private final Stack<PersistenceManager> persistenceManager = new Stack<PersistenceManager>();
public void addPersistenceManager(PersistenceManager persistenceManager) {
this.persistenceManager.add(persistenceManager);
}
public PersistenceManager getPersistenceManager() {
return persistenceManager.peek();
}
public void remove() {
if (!persistenceManager.empty()) {
persistenceManager.pop();
}
if (persistenceManager.empty()) {
PersistenceManagerContext.clear();
}
}
}
|
3e1bdb7aa7252491736a616572d4113f2dbec3b8 | 2,931 | java | Java | api/src/test/java/de/vinado/boot/secrets/DefaultSecretResolverTest.java | V1ncNet/spring-boot-secrets | 52da2e644d6bf2e605c2e7af05ccb791d2bb430c | [
"Apache-2.0"
] | null | null | null | api/src/test/java/de/vinado/boot/secrets/DefaultSecretResolverTest.java | V1ncNet/spring-boot-secrets | 52da2e644d6bf2e605c2e7af05ccb791d2bb430c | [
"Apache-2.0"
] | null | null | null | api/src/test/java/de/vinado/boot/secrets/DefaultSecretResolverTest.java | V1ncNet/spring-boot-secrets | 52da2e644d6bf2e605c2e7af05ccb791d2bb430c | [
"Apache-2.0"
] | null | null | null | 28.182692 | 92 | 0.703855 | 11,799 | package de.vinado.boot.secrets;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import java.io.File;
import java.net.URI;
import java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Vincent Nadoll
*/
class DefaultSecretResolverTest {
private ResourceLoader resourceLoader;
private DefaultSecretResolver resolver;
@BeforeEach
void setUp() {
resourceLoader = new DefaultResourceLoader();
resolver = new DefaultSecretResolver(resourceLoader);
}
@Test
void initializingNullArguments_shouldThrowException() {
assertThrows(IllegalArgumentException.class, () -> new DefaultSecretResolver(null));
}
@Test
void classpathResource_shouldLoadResourceContent() {
Optional<String> resolved = resolver.loadContent("classpath:spring_mail_host");
assertEquals("localhost", resolved);
}
@Test
void fileResource_shouldLoadResourceContent() {
Optional<String> resolved = resolver.loadContent(fromFile("spring_mail_host"));
assertEquals("localhost", resolved);
}
@Test
void nullLocation_shouldNotResolve() {
Optional<String> resolved = resolver.loadContent((String) null);
assertFalse(resolved.isPresent());
}
@Test
void text_shouldNotResolve() {
Optional<String> resolved = resolver.loadContent(UUID.randomUUID().toString());
assertFalse(resolved.isPresent());
}
@Test
void emptyLocation_shouldNotResolve() {
Optional<String> resolved = resolver.loadContent("");
assertFalse(resolved.isPresent());
}
@Test
void emptyResource_shouldNotResolve() {
Optional<String> resolved = resolver.loadContent("classpath:secret.empty");
assertFalse(resolved.isPresent());
}
@Test
void nonExistingClasspathResource_shouldNotResolve() {
Optional<String> resolved = resolver.loadContent("classpath:foo");
assertFalse(resolved.isPresent());
}
@Test
void nonExistingFileResource_shouldNotResolve() {
Optional<String> resolved = resolver.loadContent(fromFile("foo"));
assertFalse(resolved.isPresent());
}
private static URI fromFile(String name) {
String pathname = System.getProperty("user.dir") + "/src/test/resources/" + name;
File file = new File(pathname);
return file.toURI();
}
private static void assertEquals(String expected, Optional<String> actual) {
assertTrue(actual.isPresent());
Assertions.assertEquals(expected, actual.get());
}
}
|
3e1bdbed0174b5e07e3214c342a991e7db900f2b | 671 | java | Java | src/HomeworkJul/Jul29/HeightWithScanner.java | alex2406/Homework | 6ac32b6f9a8af79c8866908814d491ff6d6f2e7c | [
"MIT"
] | null | null | null | src/HomeworkJul/Jul29/HeightWithScanner.java | alex2406/Homework | 6ac32b6f9a8af79c8866908814d491ff6d6f2e7c | [
"MIT"
] | null | null | null | src/HomeworkJul/Jul29/HeightWithScanner.java | alex2406/Homework | 6ac32b6f9a8af79c8866908814d491ff6d6f2e7c | [
"MIT"
] | null | null | null | 37.277778 | 122 | 0.636364 | 11,800 | package HomeworkJul.Jul29;
import java.util.Scanner;
class HeightWithScanner {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
double userHeight;
System.out.println("What is your height?(cm)");//813
userHeight = input.nextDouble();
double inches = userHeight * 0.3937;
int intPart = (int) inches;
double feet = intPart / 12;
double rest = intPart - feet * 12;
System.out.printf("Your height in integer inches is %d\n",intPart);
System.out.printf("Height in integer inches converted to feet and inches: %.1f feet and %.1f inch\n", feet, rest);
}
}
|
3e1bdc27c07bb4d40c23310f575ceacaaa816f21 | 15,102 | java | Java | app/src/main/java/org/gnucash/android/model/Budget.java | karen-ly/gnucash-android | 879596c1ff4bde9e10c7f3626e2554b148cb5882 | [
"Apache-2.0"
] | 1,070 | 2015-01-01T19:17:46.000Z | 2022-03-18T12:51:39.000Z | app/src/main/java/org/gnucash/android/model/Budget.java | karen-ly/gnucash-android | 879596c1ff4bde9e10c7f3626e2554b148cb5882 | [
"Apache-2.0"
] | 602 | 2015-01-21T18:17:45.000Z | 2022-03-10T08:54:35.000Z | app/src/main/java/org/gnucash/android/model/Budget.java | karen-ly/gnucash-android | 879596c1ff4bde9e10c7f3626e2554b148cb5882 | [
"Apache-2.0"
] | 585 | 2015-01-07T06:37:37.000Z | 2022-02-25T08:12:32.000Z | 36.038186 | 144 | 0.604702 | 11,801 | /*
* Copyright (c) 2015 Ngewi Fet <efpyi@example.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.model;
import android.support.annotation.NonNull;
import android.util.Log;
import org.joda.time.LocalDateTime;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Budgets model
* @author Ngewi Fet <efpyi@example.com>
*/
public class Budget extends BaseModel {
private String mName;
private String mDescription;
private Recurrence mRecurrence;
private List<BudgetAmount> mBudgetAmounts = new ArrayList<>();
private long mNumberOfPeriods = 12; //default to 12 periods per year
/**
* Default constructor
*/
public Budget(){
//nothing to see here, move along
}
/**
* Overloaded constructor.
* Initializes the name and amount of this budget
* @param name String name of the budget
*/
public Budget(@NonNull String name){
this.mName = name;
}
public Budget(@NonNull String name, @NonNull Recurrence recurrence){
this.mName = name;
this.mRecurrence = recurrence;
}
/**
* Returns the name of the budget
* @return name of the budget
*/
public String getName() {
return mName;
}
/**
* Sets the name of the budget
* @param name String name of budget
*/
public void setName(@NonNull String name) {
this.mName = name;
}
/**
* Returns the description of the budget
* @return String description of budget
*/
public String getDescription() {
return mDescription;
}
/**
* Sets the description of the budget
* @param description String description
*/
public void setDescription(String description) {
this.mDescription = description;
}
/**
* Returns the recurrence for this budget
* @return Recurrence object for this budget
*/
public Recurrence getRecurrence() {
return mRecurrence;
}
/**
* Set the recurrence pattern for this budget
* @param recurrence Recurrence object
*/
public void setRecurrence(@NonNull Recurrence recurrence) {
this.mRecurrence = recurrence;
}
/**
* Return list of budget amounts associated with this budget
* @return List of budget amounts
*/
public List<BudgetAmount> getBudgetAmounts() {
return mBudgetAmounts;
}
/**
* Set the list of budget amounts
* @param budgetAmounts List of budget amounts
*/
public void setBudgetAmounts(List<BudgetAmount> budgetAmounts) {
this.mBudgetAmounts = budgetAmounts;
for (BudgetAmount budgetAmount : mBudgetAmounts) {
budgetAmount.setBudgetUID(getUID());
}
}
/**
* Adds a BudgetAmount to this budget
* @param budgetAmount Budget amount
*/
public void addBudgetAmount(BudgetAmount budgetAmount){
budgetAmount.setBudgetUID(getUID());
mBudgetAmounts.add(budgetAmount);
}
/**
* Returns the budget amount for a specific account
* @param accountUID GUID of the account
* @return Money amount of the budget or null if the budget has no amount for the account
*/
public Money getAmount(@NonNull String accountUID){
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (budgetAmount.getAccountUID().equals(accountUID))
return budgetAmount.getAmount();
}
return null;
}
/**
* Returns the budget amount for a specific account and period
* @param accountUID GUID of the account
* @param periodNum Budgeting period, zero-based index
* @return Money amount or zero if no matching {@link BudgetAmount} is found for the period
*/
public Money getAmount(@NonNull String accountUID, int periodNum){
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (budgetAmount.getAccountUID().equals(accountUID)
&& (budgetAmount.getPeriodNum() == periodNum || budgetAmount.getPeriodNum() == -1)){
return budgetAmount.getAmount();
}
}
return Money.getZeroInstance();
}
/**
* Returns the sum of all budget amounts in this budget
* <p><b>NOTE:</b> This method ignores budgets of accounts which are in different currencies</p>
* @return Money sum of all amounts
*/
public Money getAmountSum(){
Money sum = null; //we explicitly allow this null instead of a money instance, because this method should never return null for a budget
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (sum == null){
sum = budgetAmount.getAmount();
} else {
try {
sum = sum.add(budgetAmount.getAmount().abs());
} catch (Money.CurrencyMismatchException ex){
Log.i(getClass().getSimpleName(), "Skip some budget amounts with different currency");
}
}
}
return sum;
}
/**
* Returns the number of periods covered by this budget
* @return Number of periods
*/
public long getNumberOfPeriods() {
return mNumberOfPeriods;
}
/**
* Returns the timestamp of the start of current period of the budget
* @return Start timestamp in milliseconds
*/
public long getStartofCurrentPeriod(){
LocalDateTime localDate = new LocalDateTime();
int interval = mRecurrence.getMultiplier();
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.millisOfDay().withMinimumValue().plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMinimumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMinimumValue().minusDays(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMinimumValue().minusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMinimumValue().minusYears(interval);
break;
}
return localDate.toDate().getTime();
}
/**
* Returns the end timestamp of the current period
* @return End timestamp in milliseconds
*/
public long getEndOfCurrentPeriod(){
LocalDateTime localDate = new LocalDateTime();
int interval = mRecurrence.getMultiplier();
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.millisOfDay().withMaximumValue().plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMaximumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMaximumValue().plusWeeks(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMaximumValue().plusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMaximumValue().plusYears(interval);
break;
}
return localDate.toDate().getTime();
}
public long getStartOfPeriod(int periodNum){
LocalDateTime localDate = new LocalDateTime(mRecurrence.getPeriodStart().getTime());
int interval = mRecurrence.getMultiplier() * periodNum;
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.millisOfDay().withMinimumValue().plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMinimumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMinimumValue().minusDays(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMinimumValue().minusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMinimumValue().minusYears(interval);
break;
}
return localDate.toDate().getTime();
}
/**
* Returns the end timestamp of the period
* @param periodNum Number of the period
* @return End timestamp in milliseconds of the period
*/
public long getEndOfPeriod(int periodNum){
LocalDateTime localDate = new LocalDateTime();
int interval = mRecurrence.getMultiplier() * periodNum;
switch (mRecurrence.getPeriodType()){
case HOUR:
localDate = localDate.plusHours(interval);
break;
case DAY:
localDate = localDate.millisOfDay().withMaximumValue().plusDays(interval);
break;
case WEEK:
localDate = localDate.dayOfWeek().withMaximumValue().plusWeeks(interval);
break;
case MONTH:
localDate = localDate.dayOfMonth().withMaximumValue().plusMonths(interval);
break;
case YEAR:
localDate = localDate.dayOfYear().withMaximumValue().plusYears(interval);
break;
}
return localDate.toDate().getTime();
}
/**
* Sets the number of periods for the budget
* @param numberOfPeriods Number of periods as long
*/
public void setNumberOfPeriods(long numberOfPeriods) {
this.mNumberOfPeriods = numberOfPeriods;
}
/**
* Returns the number of accounts in this budget
* @return Number of budgeted accounts
*/
public int getNumberOfAccounts(){
Set<String> accountSet = new HashSet<>();
for (BudgetAmount budgetAmount : mBudgetAmounts) {
accountSet.add(budgetAmount.getAccountUID());
}
return accountSet.size();
}
/**
* Returns the list of budget amounts where only one BudgetAmount is present if the amount of the budget amount
* is the same for all periods in the budget.
* BudgetAmounts with different amounts per period are still return separately
* <p>
* This method is used during import because GnuCash desktop saves one BudgetAmount per period for the whole budgeting period.
* While this can be easily displayed in a table form on the desktop, it is not feasible in the Android app.
* So we display only one BudgetAmount if it covers all periods in the budgeting period
* </p>
* @return List of {@link BudgetAmount}s
*/
public List<BudgetAmount> getCompactedBudgetAmounts(){
Map<String, List<BigDecimal>> accountAmountMap = new HashMap<>();
for (BudgetAmount budgetAmount : mBudgetAmounts) {
String accountUID = budgetAmount.getAccountUID();
BigDecimal amount = budgetAmount.getAmount().asBigDecimal();
if (accountAmountMap.containsKey(accountUID)){
accountAmountMap.get(accountUID).add(amount);
} else {
List<BigDecimal> amounts = new ArrayList<>();
amounts.add(amount);
accountAmountMap.put(accountUID, amounts);
}
}
List<BudgetAmount> compactBudgetAmounts = new ArrayList<>();
for (Map.Entry<String, List<BigDecimal>> entry : accountAmountMap.entrySet()) {
List<BigDecimal> amounts = entry.getValue();
BigDecimal first = amounts.get(0);
boolean allSame = true;
for (BigDecimal bigDecimal : amounts) {
allSame &= bigDecimal.equals(first);
}
if (allSame){
if (amounts.size() == 1) {
for (BudgetAmount bgtAmount : mBudgetAmounts) {
if (bgtAmount.getAccountUID().equals(entry.getKey())) {
compactBudgetAmounts.add(bgtAmount);
break;
}
}
} else {
BudgetAmount bgtAmount = new BudgetAmount(getUID(), entry.getKey());
bgtAmount.setAmount(new Money(first, Commodity.DEFAULT_COMMODITY));
bgtAmount.setPeriodNum(-1);
compactBudgetAmounts.add(bgtAmount);
}
} else {
//if not all amounts are the same, then just add them as we read them
for (BudgetAmount bgtAmount : mBudgetAmounts) {
if (bgtAmount.getAccountUID().equals(entry.getKey())){
compactBudgetAmounts.add(bgtAmount);
}
}
}
}
return compactBudgetAmounts;
}
/**
* Returns a list of budget amounts where each period has it's own budget amount
* <p>Any budget amounts in the database with a period number of -1 are expanded to individual budget amounts for all periods</p>
* <p>This method is useful with exporting budget amounts to XML</p>
* @return List of expande
*/
public List<BudgetAmount> getExpandedBudgetAmounts(){
List<BudgetAmount> amountsToAdd = new ArrayList<>();
List<BudgetAmount> amountsToRemove = new ArrayList<>();
for (BudgetAmount budgetAmount : mBudgetAmounts) {
if (budgetAmount.getPeriodNum() == -1){
amountsToRemove.add(budgetAmount);
String accountUID = budgetAmount.getAccountUID();
for (int period = 0; period < mNumberOfPeriods; period++) {
BudgetAmount bgtAmount = new BudgetAmount(getUID(), accountUID);
bgtAmount.setAmount(budgetAmount.getAmount());
bgtAmount.setPeriodNum(period);
amountsToAdd.add(bgtAmount);
}
}
}
List<BudgetAmount> expandedBudgetAmounts = new ArrayList<>(mBudgetAmounts);
for (BudgetAmount bgtAmount : amountsToRemove) {
expandedBudgetAmounts.remove(bgtAmount);
}
for (BudgetAmount bgtAmount : amountsToAdd) {
expandedBudgetAmounts.add(bgtAmount);
}
return expandedBudgetAmounts;
}
}
|
3e1bdd0610f4a4f9a3d526a13f730f55affe0ad8 | 2,281 | java | Java | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/lang/ir/inst/PrimitiveConversionInstruction.java | anatawa12/intellij-community | d2557a13699986aa174a8969952711130718e7a1 | [
"Apache-2.0"
] | null | null | null | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/lang/ir/inst/PrimitiveConversionInstruction.java | anatawa12/intellij-community | d2557a13699986aa174a8969952711130718e7a1 | [
"Apache-2.0"
] | null | null | null | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/lang/ir/inst/PrimitiveConversionInstruction.java | anatawa12/intellij-community | d2557a13699986aa174a8969952711130718e7a1 | [
"Apache-2.0"
] | null | null | null | 40.017544 | 140 | 0.752302 | 11,802 | // Copyright 2000-2018 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.codeInspection.dataFlow.lang.ir.inst;
import com.intellij.codeInspection.dataFlow.DfaMemoryState;
import com.intellij.codeInspection.dataFlow.types.DfPrimitiveType;
import com.intellij.codeInspection.dataFlow.types.DfType;
import com.intellij.codeInspection.dataFlow.value.DfaBinOpValue;
import com.intellij.codeInspection.dataFlow.value.DfaValue;
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory;
import com.intellij.codeInspection.dataFlow.value.DfaVariableValue;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.psi.PsiType;
import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A unary instruction that converts a primitive value from the stack to the desired type
*/
public class PrimitiveConversionInstruction extends EvalInstruction {
@NotNull private final PsiPrimitiveType myTargetType;
public PrimitiveConversionInstruction(@NotNull PsiPrimitiveType targetType, @Nullable PsiExpression expression) {
super(expression, 1);
myTargetType = targetType;
}
@Override
public @NotNull DfaValue eval(@NotNull DfaValueFactory factory,
@NotNull DfaMemoryState state,
@NotNull DfaValue @NotNull ... arguments) {
DfaValue value = arguments[0];
PsiPrimitiveType type = myTargetType;
if (value instanceof DfaBinOpValue) {
value = ((DfaBinOpValue)value).tryReduceOnCast(state, type);
}
if (value instanceof DfaVariableValue &&
(type.equals(value.getType()) ||
TypeConversionUtil.isSafeConversion(type, value.getType()) &&
TypeConversionUtil.isSafeConversion(PsiType.INT, type))) {
return value;
}
DfType dfType = state.getDfType(value);
if (dfType instanceof DfPrimitiveType) {
return factory.fromDfType(((DfPrimitiveType)dfType).castTo(type));
}
return factory.getUnknown();
}
@Override
public String toString() {
return "CONVERT_PRIMITIVE " + myTargetType.getPresentableText();
}
}
|
3e1bdd06c1e4a9175bf37941d7b46852ddc18d65 | 524 | java | Java | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java | elmarquez/spring-data-mock | db7ddf5204c17917798ed902673f0c9824aab153 | [
"MIT"
] | null | null | null | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java | elmarquez/spring-data-mock | db7ddf5204c17917798ed902673f0c9824aab153 | [
"MIT"
] | null | null | null | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/error/RepositoryDefinitionException.java | elmarquez/spring-data-mock | db7ddf5204c17917798ed902673f0c9824aab153 | [
"MIT"
] | null | null | null | 29.444444 | 105 | 0.720755 | 11,803 | package com.mmnaseri.utils.spring.data.error;
/**
* @author Milad Naseri (upchh@example.com)
* @since 1.0 (4/8/16)
*/
public class RepositoryDefinitionException extends RepositoryMockException {
public RepositoryDefinitionException(Class<?> repositoryInterface, String message) {
super(repositoryInterface + ": " + message);
}
public RepositoryDefinitionException(Class<?> repositoryInterface, String message, Throwable cause) {
super(repositoryInterface + ": " + message, cause);
}
}
|
3e1bde2452bd3a526e30388c93f182fa2df44ae9 | 3,135 | java | Java | src/main/java/com/threathunter/bordercollie/slot/compute/graph/extension/incident/IncidentVariableMeta.java | threathunterX/offline | 52df01b6fa90414a1c237896db8e1c066ce782f8 | [
"Apache-2.0"
] | 1 | 2019-05-01T09:42:27.000Z | 2019-05-01T09:42:27.000Z | src/main/java/com/threathunter/bordercollie/slot/compute/graph/extension/incident/IncidentVariableMeta.java | threathunterX/offline | 52df01b6fa90414a1c237896db8e1c066ce782f8 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/threathunter/bordercollie/slot/compute/graph/extension/incident/IncidentVariableMeta.java | threathunterX/offline | 52df01b6fa90414a1c237896db8e1c066ce782f8 | [
"Apache-2.0"
] | 4 | 2019-06-24T05:47:58.000Z | 2020-09-29T04:56:57.000Z | 18.772455 | 165 | 0.60925 | 11,804 | package com.threathunter.bordercollie.slot.compute.graph.extension.incident;
import com.threathunter.common.Identifier;
import com.threathunter.common.NamedType;
import com.threathunter.model.*;
import java.util.List;
import java.util.Map;
/**
*
*/
public class IncidentVariableMeta extends VariableMeta {
public static final String TYPE = "incident";
private String app;
private String name;
private boolean topValue;
private boolean keyTopValue;
private String dimension;
private List<Property> groupbyKeys;
public IncidentVariableMeta(final String dimension, final String app, final String name, boolean isTopValue, boolean isKeyTopValue, List<Property> groupbyKeys) {
this.dimension = dimension;
this.app = app;
this.name = name;
this.topValue = isTopValue;
this.keyTopValue = isKeyTopValue;
this.groupbyKeys = groupbyKeys;
}
@Override
public Identifier getId() {
return null;
}
@Override
public String getApp() {
return app;
}
@Override
public String getName() {
return name;
}
@Override
public String getType() {
if (topValue || keyTopValue) {
return "top";
}
return "aggregate";
}
@Override
public String getStatus() {
return null;
}
@Override
public boolean isDerived() {
return false;
}
@Override
public List<Identifier> getSrcVariableMetasID() {
return null;
}
@Override
public Identifier getSrcEventMetaID() {
return null;
}
@Override
public boolean isInternal() {
return false;
}
@Override
public int getPriority() {
return 0;
}
@Override
public List<Property> getProperties() {
return null;
}
@Override
public boolean hasProperty(Property property) {
return false;
}
@Override
public Map<String, NamedType> getDataSchema() {
return null;
}
@Override
public long getExpireDate() {
return 0;
}
@Override
public long getTtl() {
return 0;
}
@Override
public Property findPropertyByName(String s) {
return null;
}
@Override
public List<PropertyMapping> getPropertyMappings() {
return null;
}
@Override
public PropertyCondition getPropertyCondition() {
return null;
}
@Override
public PropertyReduction getPropertyReduction() {
return null;
}
@Override
public String getRemark() {
return null;
}
@Override
public String getVisibleName() {
return null;
}
@Override
public String getDimension() {
return dimension;
}
@Override
public String getModule() {
return null;
}
@Override
public String getValueType() {
return null;
}
@Override
public Object to_json_object() {
return null;
}
@Override
public List<Property> getGroupKeys() {
return this.groupbyKeys;
}
}
|
3e1bdf06319080f83539f52c4fa73dd444ee00d4 | 1,442 | java | Java | core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/GeneratedTextFile.java | cloudecho/mybatis-generator | 5b2d9f9e850f6410051805feca900fe2c242b0f7 | [
"Apache-2.0"
] | null | null | null | core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/GeneratedTextFile.java | cloudecho/mybatis-generator | 5b2d9f9e850f6410051805feca900fe2c242b0f7 | [
"Apache-2.0"
] | null | null | null | core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/GeneratedTextFile.java | cloudecho/mybatis-generator | 5b2d9f9e850f6410051805feca900fe2c242b0f7 | [
"Apache-2.0"
] | null | null | null | 32.772727 | 116 | 0.709431 | 11,805 | /**
* Copyright 2006-2016 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.generator.api;
/**
* The Class GeneratedTextFile.
*
* @author yong.ma
*/
public class GeneratedTextFile extends GeneratedXmlFile {
private final String formattedContent;
/**
* Instantiates a new generated text file.
*
* @param formattedContent the text content
* @param fileName the file name
* @param targetPackage the target package
* @param targetProject the target project
*/
public GeneratedTextFile(String formattedContent, String fileName, String targetPackage, String targetProject) {
super(null, fileName, targetPackage, targetProject, false, null);
this.formattedContent = formattedContent;
}
@Override
public String getFormattedContent() {
return this.formattedContent;
}
}
|
3e1bdf30546fa869a2361aed577d1815092de099 | 6,276 | java | Java | src/main/java/uk/co/boothen/gradle/wsimport/WsImportTask.java | szonyim/gradle-wsimport | 5f0502a16199ce0f3020aa39d46ae18d7d9b0a63 | [
"Apache-2.0"
] | 8 | 2018-10-08T14:57:15.000Z | 2021-01-19T07:50:05.000Z | src/main/java/uk/co/boothen/gradle/wsimport/WsImportTask.java | szonyim/gradle-wsimport | 5f0502a16199ce0f3020aa39d46ae18d7d9b0a63 | [
"Apache-2.0"
] | 21 | 2018-11-16T15:48:44.000Z | 2021-11-30T17:11:50.000Z | src/main/java/uk/co/boothen/gradle/wsimport/WsImportTask.java | szonyim/gradle-wsimport | 5f0502a16199ce0f3020aa39d46ae18d7d9b0a63 | [
"Apache-2.0"
] | 14 | 2018-11-16T14:07:32.000Z | 2021-10-06T10:49:16.000Z | 32.020408 | 90 | 0.692001 | 11,806 | /*
* Copyright 2019 Boothen Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.boothen.gradle.wsimport;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.CacheableTask;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
import org.gradle.workers.WorkQueue;
import org.gradle.workers.WorkerExecutor;
import java.io.File;
import javax.inject.Inject;
@CacheableTask
public class WsImportTask extends DefaultTask {
private final WorkerExecutor workerExecutor;
private Property<Configuration> jaxwsToolsConfiguration;
private Property<Boolean> keep;
private Property<Boolean> extension;
private Property<Boolean> verbose;
private Property<Boolean> quiet;
private Property<Boolean> debug;
private Property<Boolean> xnocompile;
private Property<Boolean> xadditionalHeaders;
private Property<Boolean> xNoAddressingDatabinding;
private Property<Boolean> xdebug;
private Property<String> target;
private Property<String> encoding;
private Property<Wsdl> wsdl;
private Property<String> wsdlSourceRoot;
private Property<File> generatedSourceRoot;
private Property<File> generatedClassesRoot;
private Property<File> projectDir;
@Inject
public WsImportTask(WorkerExecutor workerExecutor) {
this.workerExecutor = workerExecutor;
jaxwsToolsConfiguration = getProject().getObjects().property(Configuration.class);
keep = getProject().getObjects().property(Boolean.class);
extension = getProject().getObjects().property(Boolean.class);
verbose = getProject().getObjects().property(Boolean.class);
quiet = getProject().getObjects().property(Boolean.class);
debug = getProject().getObjects().property(Boolean.class);
xnocompile = getProject().getObjects().property(Boolean.class);
xadditionalHeaders = getProject().getObjects().property(Boolean.class);
xNoAddressingDatabinding = getProject().getObjects().property(Boolean.class);
xdebug = getProject().getObjects().property(Boolean.class);
target = getProject().getObjects().property(String.class);
encoding = getProject().getObjects().property(String.class);
wsdl = getProject().getObjects().property(Wsdl.class);
wsdlSourceRoot = getProject().getObjects().property(String.class);
generatedSourceRoot = getProject().getObjects().property(File.class);
generatedClassesRoot = getProject().getObjects().property(File.class);
projectDir = getProject().getObjects().property(File.class);
}
@Input
public Property<Boolean> getKeep() {
return keep;
}
@Input
public Property<Boolean> getExtension() {
return extension;
}
@Input
public Property<Boolean> getVerbose() {
return verbose;
}
@Input
public Property<Boolean> getQuiet() {
return quiet;
}
@Input
public Property<Boolean> getDebug() {
return debug;
}
@Input
public Property<Boolean> getXnocompile() {
return xnocompile;
}
@Input
public Property<Boolean> getXadditionalHeaders() {
return xadditionalHeaders;
}
@Input
public Property<String> getTarget() {
return target;
}
@Input
public Property<String> getEncoding() {
return encoding;
}
@Input
public Property<Boolean> getXNoAddressingDatabinding() {
return xNoAddressingDatabinding;
}
@Input
public Property<Boolean> getXdebug() {
return xdebug;
}
@Input
public Property<String> getWsdlSourceRoot() {
return wsdlSourceRoot;
}
@Input
public Property<Wsdl> getWsdl() {
return wsdl;
}
@Input
public Property<File> getProjectDir() {
return projectDir;
}
@InputFiles
@PathSensitive(PathSensitivity.NAME_ONLY)
public Property<Configuration> getJaxwsToolsConfiguration() {
return jaxwsToolsConfiguration;
}
@OutputDirectory
public Property<File> getGeneratedSourceRoot() {
return generatedSourceRoot;
}
@OutputDirectory
public Property<File> getGeneratedClassesRoot() {
return generatedClassesRoot;
}
@TaskAction
public void taskAction() {
WorkQueue workQueue = workerExecutor.classLoaderIsolation(workerSpec -> {
workerSpec.getClasspath().from(jaxwsToolsConfiguration);
});
workQueue.submit(WsImportWorkAction.class, parameters -> {
parameters.getKeep().set(keep);
parameters.getExtension().set(extension);
parameters.getVerbose().set(verbose);
parameters.getQuiet().set(quiet);
parameters.getDebug().set(debug);
parameters.getXnocompile().set(xnocompile);
parameters.getXadditionalHeaders().set(xadditionalHeaders);
parameters.getXNoAddressingDatabinding().set(xNoAddressingDatabinding);
parameters.getXdebug().set(xdebug);
parameters.getTarget().set(target);
parameters.getEncoding().set(encoding);
parameters.getWsdlSourceRoot().set(wsdlSourceRoot);
parameters.getGeneratedSourceRoot().set(generatedSourceRoot);
parameters.getGeneratedClassesRoot().set(generatedClassesRoot);
parameters.getWsdl().set(wsdl);
parameters.getProjectRoot().set(projectDir);
});
}
}
|
3e1bdf8686489c2158e13f5c6f46bec1136349d8 | 934 | java | Java | APINoMaven/src/main/java/dependencies/logback-1.2.3/logback-1.2.3/logback-examples/src/main/java/chapters/layouts/MySampleConverter.java | avatar-use-cases/CCO-LD-Avatar | ec98761657245e9ef33afce5caa3b107209c36e0 | [
"Apache-2.0"
] | 9 | 2017-01-25T00:49:40.000Z | 2019-07-04T04:17:21.000Z | org.jpat.scuba.external.slf4j/logback-1.2.3/logback-examples/src/main/java/chapters/layouts/MySampleConverter.java | JPAT-ROSEMARY/SCUBA | 0d7dcee9e62e724af8dc006e1399d5c3e7b77dd1 | [
"MIT"
] | 2 | 2019-04-23T19:18:03.000Z | 2022-01-21T23:25:48.000Z | APINoMaven/src/main/java/dependencies/logback-1.2.3/logback-examples/src/main/java/chapters/layouts/MySampleConverter.java | avatar-use-cases/CCO-LD-Avatar | ec98761657245e9ef33afce5caa3b107209c36e0 | [
"Apache-2.0"
] | 5 | 2017-06-25T19:37:12.000Z | 2021-01-20T20:31:55.000Z | 31.133333 | 72 | 0.716274 | 11,807 | /**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package chapters.layouts;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class MySampleConverter extends ClassicConverter {
long start = System.nanoTime();
@Override
public String convert(ILoggingEvent event) {
long nowInNanos = System.nanoTime();
return Long.toString(nowInNanos - start);
}
}
|
3e1be0089becfc1789c0df8d28411c502a76dedf | 1,681 | java | Java | instrumentation/mongodb-async-3.11/src/main/java/com/nr/agent/mongo/NRCallbackWrapper.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | null | null | null | instrumentation/mongodb-async-3.11/src/main/java/com/nr/agent/mongo/NRCallbackWrapper.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | 2 | 2022-03-07T15:33:31.000Z | 2022-03-21T15:47:42.000Z | instrumentation/mongodb-async-3.11/src/main/java/com/nr/agent/mongo/NRCallbackWrapper.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | null | null | null | 29.491228 | 83 | 0.66746 | 11,808 | /*
*
* * Copyright 2021 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.nr.agent.mongo;
import com.mongodb.async.SingleResultCallback;
import com.newrelic.agent.bridge.AgentBridge;
import com.newrelic.api.agent.DatastoreParameters;
import com.newrelic.api.agent.NewRelic;
import com.newrelic.api.agent.Segment;
import com.newrelic.api.agent.Token;
import com.newrelic.api.agent.Trace;
import java.util.concurrent.atomic.AtomicBoolean;
public class NRCallbackWrapper<T> implements SingleResultCallback<T> {
private static final AtomicBoolean isNotTransformed = new AtomicBoolean(true);
public Token token = null;
public Segment segment = null;
public DatastoreParameters params = null;
private SingleResultCallback<T> delegate = null;
public NRCallbackWrapper(SingleResultCallback<T> d) {
delegate = d;
if (isNotTransformed.get()) {
AgentBridge.instrumentation.retransformUninstrumentedClass(getClass());
isNotTransformed.set(false);
}
}
@Override
@Trace(async = true)
public void onResult(T result, Throwable t) {
// could be NoOpToken if a txn wasn't started
if (token != null) {
token.linkAndExpire();
token = null;
}
// could be NoOpSegment if a txn wasn't started
if (segment != null) {
if (params != null) {
segment.reportAsExternal(params);
}
segment.end();
} else if (params != null) {
NewRelic.getAgent().getTracedMethod().reportAsExternal(params);
}
delegate.onResult(result, t);
}
}
|
3e1be0c8de385081e017d6f18204d0cf036066ad | 2,899 | java | Java | core/src/main/java/com/huawei/openstack4j/model/compute/builder/QuotaSetUpdateBuilder.java | wuchen-huawei/huaweicloud-sdk-java | 1e4b76c737d23c5d5df59405015ea136651b6fc1 | [
"Apache-2.0"
] | 46 | 2018-09-30T08:55:22.000Z | 2021-11-07T20:02:57.000Z | core/src/main/java/com/huawei/openstack4j/model/compute/builder/QuotaSetUpdateBuilder.java | wuchen-huawei/huaweicloud-sdk-java | 1e4b76c737d23c5d5df59405015ea136651b6fc1 | [
"Apache-2.0"
] | 18 | 2019-04-11T02:37:30.000Z | 2021-04-30T09:03:38.000Z | core/src/main/java/com/huawei/openstack4j/model/compute/builder/QuotaSetUpdateBuilder.java | wuchen-huawei/huaweicloud-sdk-java | 1e4b76c737d23c5d5df59405015ea136651b6fc1 | [
"Apache-2.0"
] | 42 | 2019-01-22T07:54:00.000Z | 2021-12-13T01:14:14.000Z | 34.511905 | 95 | 0.541566 | 11,809 | /*******************************************************************************
* Copyright 2016 ContainX and OpenStack4j
*
* 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.huawei.openstack4j.model.compute.builder;
import com.huawei.openstack4j.common.Buildable.Builder;
import com.huawei.openstack4j.model.compute.QuotaSetUpdate;
/**
* A builder which creates a QuotaSetUpdate object
*
* @author Jeremy Unruh
*/
public interface QuotaSetUpdateBuilder extends Builder<QuotaSetUpdateBuilder, QuotaSetUpdate> {
/**
* Metadata items permitted
*/
QuotaSetUpdateBuilder metadataItems(int metadataitems);
/**
* Injected file maximum length
*/
QuotaSetUpdateBuilder injectedFileContentBytes(int injectedFileContentBytes);
/**
* Number of inject-able files
*/
QuotaSetUpdateBuilder injectedFiles(int injectedFiles);
/**
* Quantity of instanceable RAM (MBytes)
*/
QuotaSetUpdateBuilder ram(int ram);
/**
* Number of floating IP
*/
QuotaSetUpdateBuilder floatingIps(int floatingIps);
/**
* Number of permitted instances
*/
QuotaSetUpdateBuilder instances(int instances);
/**
* Number of instanceable cores
*/
QuotaSetUpdateBuilder cores(int cores);
/**
* Number of security groups permitted
*/
QuotaSetUpdateBuilder securityGroups(int securityGroups);
/**
* Number of rules per security group permitted
*/
QuotaSetUpdateBuilder securityGroupRules(int securityGroupRules);
/**
* Injected file path name maximum length
*/
QuotaSetUpdateBuilder injectedFilePathBytes(int injectedFilePathBytes);
/**
* Number of keypairs
*/
QuotaSetUpdateBuilder keyPairs(int keyPairs);
}
|
3e1be105e62257671606e6d36c9827948a39697f | 2,932 | java | Java | jodd-madvoc/src/main/java/jodd/madvoc/petite/PetiteWebApp.java | nicky-chen/jodd | 4bba7643c564a5a3fb54397208666b9f82a0446d | [
"BSD-2-Clause"
] | 1 | 2018-03-16T13:00:59.000Z | 2018-03-16T13:00:59.000Z | jodd-madvoc/src/main/java/jodd/madvoc/petite/PetiteWebApp.java | nicky-chen/jodd | 4bba7643c564a5a3fb54397208666b9f82a0446d | [
"BSD-2-Clause"
] | null | null | null | jodd-madvoc/src/main/java/jodd/madvoc/petite/PetiteWebApp.java | nicky-chen/jodd | 4bba7643c564a5a3fb54397208666b9f82a0446d | [
"BSD-2-Clause"
] | null | null | null | 39.093333 | 104 | 0.789222 | 11,810 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.madvoc.petite;
import jodd.madvoc.WebApp;
import jodd.petite.AutomagicPetiteConfigurator;
import jodd.petite.PetiteContainer;
import java.util.Objects;
import java.util.function.Supplier;
/**
* {@link WebApp WebApplication} that uses {@link jodd.petite.PetiteContainer Petite container}
* for retrieving all instances.
*/
public class PetiteWebApp extends WebApp {
public static final String PETITE_CONTAINER_NAME = "petiteContainer";
/**
* Provides {@link PetiteContainer Petite container} instance that will be used as application context.
*/
private Supplier<PetiteContainer> petiteContainerSupplier = () -> {
PetiteContainer pc = new PetiteContainer();
new AutomagicPetiteConfigurator().configure(pc);
return pc;
};
/**
* Supplies a Petite container to be used.
*/
public PetiteWebApp withPetiteContainer(Supplier<PetiteContainer> petiteContainerSupplier) {
Objects.requireNonNull(petiteContainerSupplier);
this.petiteContainerSupplier = petiteContainerSupplier;
return this;
}
@Override
protected void registerMadvocComponents() {
super.registerMadvocComponents();
PetiteContainer petiteContainer = petiteContainerSupplier.get();
madvocContainer.registerComponentInstance(PETITE_CONTAINER_NAME, petiteContainer);
madvocContainer.registerComponent(PetiteMadvocController.class);
madvocContainer.registerComponent(PetiteFilterManager.class);
madvocContainer.registerComponent(PetiteInterceptorManager.class);
madvocContainer.registerComponent(PetiteResultsManager.class);
}
} |
3e1be114a0a472e50aa8415d47c15fab16ccf10a | 160 | java | Java | files/fwd/Lower.java | m301/JLFG | 6e66c59dcdb1eef02e58f4b35df79123749bbca9 | [
"MIT"
] | 3 | 2017-07-01T10:43:04.000Z | 2017-07-23T06:00:03.000Z | files/fwd/Lower.java | m301/JLFG | 6e66c59dcdb1eef02e58f4b35df79123749bbca9 | [
"MIT"
] | null | null | null | files/fwd/Lower.java | m301/JLFG | 6e66c59dcdb1eef02e58f4b35df79123749bbca9 | [
"MIT"
] | null | null | null | 17.777778 | 54 | 0.6625 | 11,811 | import java.*;
class Lower
{
public static void main(String args[])
{
String s="THIS IS STRING";
System.out.println("LOWERCASE :: "+s.toLowerCase());
}
} |
3e1be1722fe517952c7728ee0281d1f8609c39c2 | 4,474 | java | Java | azure-functions-gradle-plugin/src/main/java/com/microsoft/azure/plugin/functions/gradle/AzureFunctionsExtension.java | andxu/azure-gradle-plugins-2 | 44ff414d1befc86a4bdccdfb31f36c332a2fd6aa | [
"MIT"
] | null | null | null | azure-functions-gradle-plugin/src/main/java/com/microsoft/azure/plugin/functions/gradle/AzureFunctionsExtension.java | andxu/azure-gradle-plugins-2 | 44ff414d1befc86a4bdccdfb31f36c332a2fd6aa | [
"MIT"
] | null | null | null | azure-functions-gradle-plugin/src/main/java/com/microsoft/azure/plugin/functions/gradle/AzureFunctionsExtension.java | andxu/azure-gradle-plugins-2 | 44ff414d1befc86a4bdccdfb31f36c332a2fd6aa | [
"MIT"
] | null | null | null | 22.039409 | 94 | 0.686634 | 11,812 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.plugin.functions.gradle;
import com.microsoft.azure.plugin.functions.gradle.configuration.GradleRuntimeConfiguration;
import com.microsoft.azure.plugin.functions.gradle.configuration.auth.GradleAuthConfiguration;
import com.microsoft.azure.plugin.functions.gradle.configuration.deploy.Deployment;
import groovy.lang.Closure;
import org.gradle.api.Project;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Optional;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
public class AzureFunctionsExtension {
@Nullable
private Boolean allowTelemetry;
@Nullable
private String localDebug;
@Nullable
private String subscription;
@Nullable
private String resourceGroup;
private String appName;
@Nullable
private String region;
@Nullable
private String pricingTier;
@Nullable
private String appServicePlanResourceGroup;
@Nullable
private String appServicePlanName;
@Nullable
private GradleAuthConfiguration authentication;
@Nullable
private Deployment deployment;
@Nullable
private GradleRuntimeConfiguration runtime;
private Map<String, Object> appSettings;
private final Project project;
public AzureFunctionsExtension(Project project) {
this.project = project;
}
@Input
@Optional
public String getLocalDebug() {
return this.localDebug;
}
@Input
@Optional
public String getResourceGroup() {
return resourceGroup;
}
@Input
public String getAppName() {
return appName;
}
@Input
@Optional
public String getRegion() {
return region;
}
@Input
@Optional
public String getSubscription() {
return subscription;
}
@Input
@Optional
public String getPricingTier() {
return pricingTier;
}
@Input
@Optional
public String getAppServicePlanName() {
return appServicePlanName;
}
@Input
@Optional
public String getAppServicePlanResourceGroup() {
return appServicePlanResourceGroup;
}
@Input
@Optional
public GradleAuthConfiguration getAuthentication() {
return authentication;
}
@Input
@Optional
public Deployment getDeployment() {
return deployment;
}
@Input
@Optional
public Map<String, Object> getAppSettings() {
return appSettings;
}
@Input
@Optional
public GradleRuntimeConfiguration getRuntime() {
return runtime;
}
@Input
@Optional
public Boolean getAllowTelemetry() {
return allowTelemetry;
}
public void setAllowTelemetry(Boolean allowTelemetry) {
this.allowTelemetry = allowTelemetry;
}
public void setResourceGroup(String resourceGroup) {
this.resourceGroup = resourceGroup;
}
public void setAppName(String appName) {
this.appName = appName;
}
public void setRegion(String region) {
this.region = region;
}
public void setSubscription(String subscription) {
this.subscription = subscription;
}
public void setPricingTier(String pricingTier) {
this.pricingTier = pricingTier;
}
public void setAuthentication(Closure closure) {
this.authentication = new GradleAuthConfiguration();
project.configure(authentication, closure);
}
public void setDeployment(Closure closure) {
deployment = new Deployment();
project.configure(deployment, closure);
}
public void setRuntime(Closure closure) {
runtime = new GradleRuntimeConfiguration();
project.configure(runtime, closure);
}
public void setAppServicePlanName(String appServicePlanName) {
this.appServicePlanName = appServicePlanName;
}
public void setAppServicePlanResourceGroup(String appServicePlanResourceGroup) {
this.appServicePlanResourceGroup = appServicePlanResourceGroup;
}
public void setAppSettings(Closure closure) {
this.appSettings = new HashMap<>();
project.configure(appSettings, closure);
}
public void setLocalDebug(String localDebug) {
this.localDebug = localDebug;
}
}
|
3e1be1ee82a6d9e54cfd10bd6c1357a70e6ec095 | 4,374 | java | Java | src/test/java/org/perscholas/musicpollwebsite/database/loader/DataLoader.java | ekand/music-poll-repository-public | 4c693fad29d5e3f97d9917699c0424dc5cc53e66 | [
"MIT"
] | null | null | null | src/test/java/org/perscholas/musicpollwebsite/database/loader/DataLoader.java | ekand/music-poll-repository-public | 4c693fad29d5e3f97d9917699c0424dc5cc53e66 | [
"MIT"
] | null | null | null | src/test/java/org/perscholas/musicpollwebsite/database/loader/DataLoader.java | ekand/music-poll-repository-public | 4c693fad29d5e3f97d9917699c0424dc5cc53e66 | [
"MIT"
] | null | null | null | 43.74 | 186 | 0.673297 | 11,813 | package org.perscholas.musicpollwebsite.database.loader;
import org.perscholas.musicpollwebsite.controller.HomeController;
import org.perscholas.musicpollwebsite.database.repository.*;
import org.perscholas.musicpollwebsite.database.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
@Component // uncomment this to load data in a fresh database
class DataLoader {
Logger logger = LoggerFactory.getLogger(DataLoader.class);
private final UserRepository userRepository;
private final UserRoleRepository userRoleRepository;
private final PollRepository pollRepository;
private final SongRepository songRepository;
private final VoteRepository voteRepository;
public DataLoader(UserRepository userRepository, UserRoleRepository userRoleRepository, PollRepository pollRepository, SongRepository songRepository, VoteRepository voteRepository) {
this.userRepository = userRepository;
this.userRoleRepository = userRoleRepository;
this.pollRepository = pollRepository;
this.songRepository = songRepository;
this.voteRepository = voteRepository;
}
@PostConstruct
private void loadData() {
logger.info("checking if user id 1 is present in database");
if (userRepository.findById(1).isPresent()) {
logger.info("user 1 found; exiting the data loader");
return;
}
try {
logger.info("user 1 not found; loading data into the database");
User user1 = new User("admin", "$2a$12$8Bw4ciRYTDa2tzad5uwK4uat9Ps0Esfzt8j/5EX5d53GWiAs7rzvG");
userRepository.save(user1);
UserRole userRoleUser1User = new UserRole("USER", user1);
userRoleRepository.save(userRoleUser1User);
UserRole userRoleUser1Admin = new UserRole("ADMIN", user1);
userRoleRepository.save(userRoleUser1Admin);
User user2 = new User("Jerry", "$2a$12$bu.7.555Cp.H45OWkRGmAud1uDbuThevyixWgRQMT5Mfxz5O0TORu");
userRepository.save(user2);
UserRole userRoleUser2User = new UserRole("USER", user2);
userRoleRepository.save(userRoleUser2User);
User user3 = new User("Bob", "$2a$12$zEwu.qWnFOIHo1dtnt5qXePen2y6vxFPTuKBW5jpIAUOQRYHmHPI2");
userRepository.save(user3);
userRoleRepository.save(new UserRole("USER", user3));
User user4 = new User("Sally", "$2a$12$blbPse75lfJOOH33yfxDxup35XROenReU.aBTHrA82VduHjyOGsfm");
userRepository.save(user4);
userRoleRepository.save(new UserRole("USER", user4));
// poll one with votes
Song SongOneA = new Song("Californication");
Song songOneB = new Song("Under the Bridge");
Song songOneC = new Song("Can't Stop");
List<Song> songListOne = addSongs(SongOneA, songOneB, songOneC);
Poll poll1 = new Poll("Red Hot Chili Peppers songs", songListOne);
pollRepository.save(poll1);
Vote voteOne = new Vote(poll1.getId(), SongOneA.getId(), user1.getId());
Vote voteTwo = new Vote(poll1.getId(), songOneC.getId(), user2.getId());
voteRepository.save(voteOne);
voteRepository.save(voteTwo);
// poll two
List<Song> songListTwo = addSongs(new Song("Good Times Bad Times"), new Song("Come Together"), new Song("Baba O'Riley"));
Poll poll2 = new Poll("Classic Rock", songListTwo);
pollRepository.save(poll2);
List<Song> songListThree = addSongs(new Song("All The Small Things"), new Song("Basketcase"), new Song("The Kids Aren't Alright"));
Poll poll3 = new Poll("Punk Rock", songListThree);
pollRepository.save(poll3);
} catch (Exception e) {
logger.warn(String.valueOf(e));
}
}
private List<Song> addSongs(Song songTwoA, Song songTwoB, Song songTwoC) {
songRepository.save(songTwoA);
songRepository.save(songTwoB);
songRepository.save(songTwoC);
List<Song> songList = new ArrayList<>();
songList.add(songTwoA);
songList.add(songTwoB);
songList.add(songTwoC);
return songList;
}
} |
3e1be28ac0de9d1566714a8a0997b2008481f609 | 2,597 | java | Java | components/camel-netty/src/main/java/org/apache/camel/component/netty/SharedSingletonObjectPool.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 13 | 2018-08-29T09:51:58.000Z | 2022-02-22T12:00:36.000Z | components/camel-netty/src/main/java/org/apache/camel/component/netty/SharedSingletonObjectPool.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 12 | 2019-11-13T03:09:32.000Z | 2022-02-01T01:05:20.000Z | components/camel-netty/src/main/java/org/apache/camel/component/netty/SharedSingletonObjectPool.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 202 | 2020-07-23T14:34:26.000Z | 2022-03-04T18:41:20.000Z | 29.850575 | 122 | 0.699268 | 11,814 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.netty;
import java.util.NoSuchElementException;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
/**
* An {@link org.apache.commons.pool.ObjectPool} that uses a single shared instance.
* <p/>
* This implementation will always return <tt>1</tt> in {@link #getNumActive()} and
* return <tt>0</tt> in {@link #getNumIdle()}.
*/
public class SharedSingletonObjectPool<T> implements ObjectPool<T> {
private final PoolableObjectFactory<T> factory;
private volatile T t;
public SharedSingletonObjectPool(PoolableObjectFactory<T> factory) {
this.factory = factory;
}
@Override
public synchronized T borrowObject() throws Exception, NoSuchElementException, IllegalStateException {
if (t == null) {
t = factory.makeObject();
}
return t;
}
@Override
public void returnObject(T obj) throws Exception {
// noop
}
@Override
public void invalidateObject(T obj) throws Exception {
t = null;
}
@Override
public void addObject() throws Exception, IllegalStateException, UnsupportedOperationException {
// noop
}
@Override
public int getNumIdle() throws UnsupportedOperationException {
return 0;
}
@Override
public int getNumActive() throws UnsupportedOperationException {
return 1;
}
@Override
public void clear() throws Exception, UnsupportedOperationException {
t = null;
}
@Override
public void close() throws Exception {
t = null;
}
@Override
public void setFactory(PoolableObjectFactory<T> factory) throws IllegalStateException, UnsupportedOperationException {
// noop
}
}
|
3e1be2afb3fb182462731b7ad3fc5d661fe3c7b3 | 416 | java | Java | base.core/src/main/java/eapli/base/formularioPreenchido/persistencia/FormularioPreenchidoRepositorio.java | Nbdy05/LAPR4 | c41ad49fc671a2326e41e57e844b0a4aaa7783fe | [
"MIT"
] | null | null | null | base.core/src/main/java/eapli/base/formularioPreenchido/persistencia/FormularioPreenchidoRepositorio.java | Nbdy05/LAPR4 | c41ad49fc671a2326e41e57e844b0a4aaa7783fe | [
"MIT"
] | null | null | null | base.core/src/main/java/eapli/base/formularioPreenchido/persistencia/FormularioPreenchidoRepositorio.java | Nbdy05/LAPR4 | c41ad49fc671a2326e41e57e844b0a4aaa7783fe | [
"MIT"
] | null | null | null | 32 | 103 | 0.855769 | 11,815 | package eapli.base.formularioPreenchido.persistencia;
import eapli.base.formulario.domain.Formulario;
import eapli.base.formularioPreenchido.domain.FormularioPreenchido;
import eapli.framework.domain.repositories.DomainRepository;
import java.util.Set;
public interface FormularioPreenchidoRepositorio extends DomainRepository<Long, FormularioPreenchido> {
Set<FormularioPreenchido> formularioRespostas();
}
|
3e1be376bc9a7bd573146cd005f77101f584f4f5 | 370 | java | Java | datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/database/store/aggregators/bplustree/intkeysfloatvalues/AggregatorBPlusTreeIntKeysFloatValuesGetResult.java | YoufuLi/radlog | 669c2b28f7ef4f9f6d94d353a3b180c1ad3b99e5 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | 2 | 2020-12-08T01:53:18.000Z | 2021-01-08T17:46:53.000Z | datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/database/store/aggregators/bplustree/intkeysfloatvalues/AggregatorBPlusTreeIntKeysFloatValuesGetResult.java | YoufuLi/radlog | 669c2b28f7ef4f9f6d94d353a3b180c1ad3b99e5 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2021-08-31T03:40:28.000Z | 2021-08-31T06:38:38.000Z | datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/database/store/aggregators/bplustree/intkeysfloatvalues/AggregatorBPlusTreeIntKeysFloatValuesGetResult.java | YoufuLi/radlog | 669c2b28f7ef4f9f6d94d353a3b180c1ad3b99e5 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | null | null | null | 30.833333 | 91 | 0.843243 | 11,816 | package edu.ucla.cs.wis.bigdatalog.database.store.aggregators.bplustree.intkeysfloatvalues;
import java.io.Serializable;
public class AggregatorBPlusTreeIntKeysFloatValuesGetResult implements Serializable {
private static final long serialVersionUID = 1L;
public boolean success;
public double value;
public AggregatorBPlusTreeIntKeysFloatValuesGetResult(){}
}
|
3e1be3f557434abffeed9c446be46e3677119635 | 419 | java | Java | NLPCCd/Hive/349_1.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | NLPCCd/Hive/349_1.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | NLPCCd/Hive/349_1.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | 20.95 | 70 | 0.732697 | 11,817 | //,temp,sample_2959.java,2,16,temp,sample_2965.java,2,19
//,3
public class xxx {
public Void call() {
while (!isShutdown.get() && !Thread.currentThread().isInterrupted()) {
try {
TaskInfo taskInfo = getNextTask();
taskInfo.setInDelayedQueue(false);
processEvictedTask(taskInfo);
} catch (InterruptedException e) {
if (isShutdown.get()) {
log.info("delayedtaskscheduler thread interrupted after shutdown");
}
}
}
}
}; |
3e1be4e864a98f1b3a8457b59dc1327b54ba35aa | 1,877 | java | Java | consulo-xstylesheet/src/main/java/consulo/xstylesheet/codeInsight/PropertyIsNotValidInspection.java | consulo/consulo-css | 22be73f42d1e7399140f7f88370082d6d1a5fb54 | [
"Apache-2.0"
] | null | null | null | consulo-xstylesheet/src/main/java/consulo/xstylesheet/codeInsight/PropertyIsNotValidInspection.java | consulo/consulo-css | 22be73f42d1e7399140f7f88370082d6d1a5fb54 | [
"Apache-2.0"
] | 12 | 2016-06-13T07:40:28.000Z | 2021-12-23T15:08:19.000Z | consulo-xstylesheet/src/main/java/consulo/xstylesheet/codeInsight/PropertyIsNotValidInspection.java | consulo/consulo-css | 22be73f42d1e7399140f7f88370082d6d1a5fb54 | [
"Apache-2.0"
] | 1 | 2016-04-12T23:07:36.000Z | 2016-04-12T23:07:36.000Z | 30.770492 | 117 | 0.760256 | 11,818 | /*
* Copyright 2013 must-be.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.xstylesheet.codeInsight;
import javax.annotation.Nonnull;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import consulo.xstylesheet.definition.XStyleSheetProperty;
import consulo.xstylesheet.psi.PsiXStyleSheetProperty;
/**
* @author VISTALL
* @since 03.07.13.
*/
public class PropertyIsNotValidInspection extends LocalInspectionTool
{
@Nonnull
@Override
public PsiElementVisitor buildVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly)
{
return new PsiElementVisitor()
{
@Override
public void visitElement(PsiElement element)
{
if(element instanceof PsiXStyleSheetProperty)
{
XStyleSheetProperty xStyleSheetProperty = ((PsiXStyleSheetProperty) element).getXStyleSheetProperty();
if(xStyleSheetProperty == null)
{
PsiElement nameIdentifier = ((PsiXStyleSheetProperty) element).getNameIdentifier();
if(nameIdentifier == null)
{
return;
}
holder.registerProblem(nameIdentifier, "Invalid property name", ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
}
}
};
}
}
|
3e1be4fb96d9127c48505a92dbd28b1b3b0e9679 | 2,421 | java | Java | dopaas-uci/dopaas-uci-core/src/main/java/com/wl4g/dopaas/uci/pcm/redmine/model/RedmineProjects.java | wl4g/nops-cloud | 1d094d15b35ab6e8ea9710ffaa8aa2df2addafe9 | [
"Apache-2.0"
] | 72 | 2018-12-04T13:48:25.000Z | 2020-05-06T06:51:02.000Z | dopaas-uci/dopaas-uci-core/src/main/java/com/wl4g/dopaas/uci/pcm/redmine/model/RedmineProjects.java | wl4g/nops-cloud | 1d094d15b35ab6e8ea9710ffaa8aa2df2addafe9 | [
"Apache-2.0"
] | 7 | 2019-04-24T03:30:04.000Z | 2020-04-18T12:16:36.000Z | dopaas-uci/dopaas-uci-core/src/main/java/com/wl4g/dopaas/uci/pcm/redmine/model/RedmineProjects.java | wl4g/nops-cloud | 1d094d15b35ab6e8ea9710ffaa8aa2df2addafe9 | [
"Apache-2.0"
] | 24 | 2018-12-04T13:48:31.000Z | 2020-04-15T07:36:08.000Z | 20.87931 | 95 | 0.705615 | 11,819 | /*
* Copyright 2017 ~ 2050 the original author or authors <anpch@example.com, kenaa@example.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.dopaas.uci.pcm.redmine.model;
import java.util.Date;
import java.util.List;
/**
* {@link RedmineProjects}
*
* @author Wangl.sir <lyhxr@example.com, 983708408@qq.com>
* @version 2020年1月7日 v1.0.0
*/
public class RedmineProjects extends BaseRedmine {
private List<Project> projects;
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public static class Project {
private int id;
private String name;
private String identifier;
private String description;
private int status;
private boolean is_public;
private Date created_on;
private Date updated_on;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public void setIs_public(boolean is_public) {
this.is_public = is_public;
}
public boolean getIs_public() {
return is_public;
}
public void setCreated_on(Date created_on) {
this.created_on = created_on;
}
public Date getCreated_on() {
return created_on;
}
public void setUpdated_on(Date updated_on) {
this.updated_on = updated_on;
}
public Date getUpdated_on() {
return updated_on;
}
}
} |
3e1be5ee8369294d3e8af4c5bc65bcb8b0065d26 | 946 | java | Java | Java/Strings/Java Strings Introduction/Solution.java | sharath273kumar/HackerRank_solutions | 7f21f33bb528599db02d1fc16eb4f98393e3d9bf | [
"MIT"
] | 2 | 2018-03-26T02:22:46.000Z | 2019-07-06T13:46:37.000Z | Java/Strings/Java Strings Introduction/Solution.java | sharath273kumar/HackerRank_solutions | 7f21f33bb528599db02d1fc16eb4f98393e3d9bf | [
"MIT"
] | null | null | null | Java/Strings/Java Strings Introduction/Solution.java | sharath273kumar/HackerRank_solutions | 7f21f33bb528599db02d1fc16eb4f98393e3d9bf | [
"MIT"
] | 2 | 2018-07-19T05:19:29.000Z | 2021-01-08T11:09:56.000Z | 28.666667 | 72 | 0.556025 | 11,820 | // Author: Rodney Shaghoulian
// Github: github.com/rshaghoulian
// HackerRank: hackerrank.com/rshaghoulian
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/* Save input */
Scanner scan = new Scanner(System.in);
String A = scan.next();
String B = scan.next();
scan.close();
/* Sum lengths */
System.out.println(A.length() + B.length());
/* Compare lexicographical ordering */
System.out.println(A.compareTo(B) > 0 ? "Yes" : "No");
/* Print the Strings in desired format */
System.out.println(capFirstLetter(A) + " " + capFirstLetter(B));
}
private static String capFirstLetter(String str) {
if (str == null || str.length() == 0) {
return "";
} else {
return str.substring(0,1).toUpperCase() + str.substring(1);
}
}
}
|
3e1be75b30137f3539937f9cec75399ef7cbef75 | 5,517 | java | Java | ole-app/olefs/src/main/java/org/kuali/ole/select/businessobject/OleSufficientFundCheck.java | VU-libtech/OLE-INST | 9f5efae4dfaf810fa671c6ac6670a6051303b43d | [
"ECL-2.0"
] | 1 | 2017-01-26T03:50:56.000Z | 2017-01-26T03:50:56.000Z | ole-app/olefs/src/main/java/org/kuali/ole/select/businessobject/OleSufficientFundCheck.java | VU-libtech/OLE-INST | 9f5efae4dfaf810fa671c6ac6670a6051303b43d | [
"ECL-2.0"
] | 3 | 2020-11-16T20:28:08.000Z | 2021-03-22T23:41:19.000Z | ole-app/olefs/src/main/java/org/kuali/ole/select/businessobject/OleSufficientFundCheck.java | VU-libtech/OLE-INST | 9f5efae4dfaf810fa671c6ac6670a6051303b43d | [
"ECL-2.0"
] | null | null | null | 30.313187 | 132 | 0.73917 | 11,821 | /*
* Copyright 2013 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.ole.select.businessobject;
import org.kuali.ole.coa.businessobject.Account;
import org.kuali.ole.coa.businessobject.SufficientFundsCode;
import org.kuali.rice.core.api.mo.common.active.MutableInactivatable;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
public class OleSufficientFundCheck extends PersistableBusinessObjectBase implements MutableInactivatable {
private Integer sufficientFundCheckId;
private String chartOfAccountsCode;
private String accountNumber;
private String encumbExpenseMethod;
private String encumbExpenseConstraintType;
private BigDecimal encumbranceAmount;
private BigDecimal expenseAmount;
// private String encumbExpenseType;
/*
* private String expenseMethod; private String expenseConstraintType; private BigDecimal expenseAmount; private String
* expenseType;
*/
private Account account;
private boolean active;
private OleSufficientFundsCheckType oleSufficientFundsCheckType;
private SufficientFundsCode sufficientFundsCode;
private String notificationOption;
public Integer getSufficientFundCheckId() {
return sufficientFundCheckId;
}
public void setSufficientFundCheckId(Integer sufficientFundCheckId) {
this.sufficientFundCheckId = sufficientFundCheckId;
}
public String getChartOfAccountsCode() {
return chartOfAccountsCode;
}
public void setChartOfAccountsCode(String chartOfAccountsCode) {
this.chartOfAccountsCode = chartOfAccountsCode;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
/*
* public String getExpenseMethod() { return expenseMethod; } public void setExpenseMethod(String expenseMethod) {
* this.expenseMethod = expenseMethod; } public String getExpenseConstraintType() { return expenseConstraintType; } public void
* setExpenseConstraintType(String expenseConstraintType) { this.expenseConstraintType = expenseConstraintType; } public
* BigDecimal getExpenseAmount() { return expenseAmount; } public void setExpenseAmount(BigDecimal expenseAmount) {
* this.expenseAmount = expenseAmount; } public String getExpenseType() { return expenseType; } public void
* setExpenseType(String expenseType) { this.expenseType = expenseType; }
*/
public String getEncumbExpenseMethod() {
return encumbExpenseMethod;
}
public void setEncumbExpenseMethod(String encumbExpenseMethod) {
this.encumbExpenseMethod = encumbExpenseMethod;
}
public String getEncumbExpenseConstraintType() {
return encumbExpenseConstraintType;
}
public void setEncumbExpenseConstraintType(String encumbExpenseConstraintType) {
this.encumbExpenseConstraintType = encumbExpenseConstraintType;
}
/*
* public String getEncumbExpenseType() { return encumbExpenseType; } public void setEncumbExpenseType(String encumbExpenseType)
* { this.encumbExpenseType = encumbExpenseType; }
*/
public BigDecimal getEncumbranceAmount() {
return encumbranceAmount;
}
public void setEncumbranceAmount(BigDecimal encumbranceAmount) {
this.encumbranceAmount = encumbranceAmount;
}
public BigDecimal getExpenseAmount() {
return expenseAmount;
}
public void setExpenseAmount(BigDecimal expenseAmount) {
this.expenseAmount = expenseAmount;
}
@Override
public boolean isActive() {
return active;
}
@Override
public void setActive(boolean active) {
this.active = active;
}
public OleSufficientFundsCheckType getOleSufficientFundsCheckType() {
return oleSufficientFundsCheckType;
}
public void setOleSufficientFundsCheckType(OleSufficientFundsCheckType oleSufficientFundsCheckType) {
this.oleSufficientFundsCheckType = oleSufficientFundsCheckType;
}
public SufficientFundsCode getSufficientFundsCode() {
return sufficientFundsCode;
}
public void setSufficientFundsCode(SufficientFundsCode sufficientFundsCode) {
this.sufficientFundsCode = sufficientFundsCode;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getNotificationOption() {
return notificationOption;
}
public void setNotificationOption(String notificationOption) {
this.notificationOption = notificationOption;
}
protected LinkedHashMap toStringMapper() {
LinkedHashMap m = new LinkedHashMap();
m.put("sufficientFundCheckId", this.sufficientFundCheckId);
return m;
}
} |
3e1be959e9bf3f03b9cf847911f94a22440d1ebb | 578 | java | Java | android-app/app/src/main/java/babasmatatu/hackerthon/com/babasmatatu/api_models/routes/Journey.java | tevin/babas-matatu | 22ca165340dbb2c438581db9d7185462cbaa71f6 | [
"MIT"
] | null | null | null | android-app/app/src/main/java/babasmatatu/hackerthon/com/babasmatatu/api_models/routes/Journey.java | tevin/babas-matatu | 22ca165340dbb2c438581db9d7185462cbaa71f6 | [
"MIT"
] | null | null | null | android-app/app/src/main/java/babasmatatu/hackerthon/com/babasmatatu/api_models/routes/Journey.java | tevin/babas-matatu | 22ca165340dbb2c438581db9d7185462cbaa71f6 | [
"MIT"
] | null | null | null | 15.210526 | 65 | 0.546713 | 11,822 | package babasmatatu.hackerthon.com.babasmatatu.api_models.routes;
/**
* Created by munene on 4/7/2018.
*/
public class Journey
{
private String id;
private Steps[] steps;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public Steps[] getSteps ()
{
return steps;
}
public void setSteps (Steps[] steps)
{
this.steps = steps;
}
@Override
public String toString()
{
return "ClassPojo [id = "+id+", steps = "+steps+"]";
}
}
|
3e1be97dccc4bd2c1d31456e941e56e8aaaff56a | 697 | java | Java | src/main/java/com/bernardomg/tabletop/dreadball/model/package-info.java | Bernardo-MG/dreadball-toolkit-webpage | e11a972b4ff12e131e8128e5b64f8449c48749a0 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/bernardomg/tabletop/dreadball/model/package-info.java | Bernardo-MG/dreadball-toolkit-webpage | e11a972b4ff12e131e8128e5b64f8449c48749a0 | [
"Apache-2.0"
] | 84 | 2016-06-04T20:15:47.000Z | 2018-04-17T06:09:20.000Z | src/main/java/com/bernardomg/tabletop/dreadball/model/package-info.java | Bernardo-MG/dreadball-toolkit-webpage | e11a972b4ff12e131e8128e5b64f8449c48749a0 | [
"Apache-2.0"
] | null | null | null | 33.190476 | 80 | 0.731707 | 11,823 | /**
* Copyright 2018 the original author or authors
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Forms beans.
*/
package com.bernardomg.tabletop.dreadball.model;
|
3e1bea908b9244618d31b2d4ab745f1ebabce1b9 | 4,246 | java | Java | src/org/pipservices3/commons/run/FixedRateTimer.java | pip-services3-java/pip-services3-commons-java | 39ffcb7fcf0bbec7f1351139e1f8eedb7bd5b802 | [
"MIT"
] | null | null | null | src/org/pipservices3/commons/run/FixedRateTimer.java | pip-services3-java/pip-services3-commons-java | 39ffcb7fcf0bbec7f1351139e1f8eedb7bd5b802 | [
"MIT"
] | 3 | 2020-05-15T21:04:22.000Z | 2021-12-09T20:30:41.000Z | src/org/pipservices3/commons/run/FixedRateTimer.java | pip-services3-java/pip-services3-commons-java | 39ffcb7fcf0bbec7f1351139e1f8eedb7bd5b802 | [
"MIT"
] | null | null | null | 21.336683 | 81 | 0.634008 | 11,824 | package org.pipservices3.commons.run;
import java.util.*;
import org.pipservices3.commons.errors.*;
/**
* Timer that is triggered in equal time intervals.
* <p>
* It has summetric cross-language implementation
* and is often used by Pip.Services toolkit to
* perform periodic processing and cleanup in microservices.
* <p>
* ### Example ###
* <pre>
* {@code
* class MyComponent {
* FixedRateTimer timer = new FixedRateTimer(() -> { this.cleanup }, 60000, 0);
* ...
* public void open(String correlationId) {
* ...
* timer.start();
* ...
* }
*
* public void open(String correlationId) {
* ...
* timer.stop();
* ...
* }
*
* private void cleanup() {
* ...
* }
* ...
* }
* }
* </pre>
* @see INotifiable
*/
public class FixedRateTimer implements IClosable {
private INotifiable _task;
private long _delay;
private long _interval;
private Timer _timer = new Timer("pip-commons-timer", true);
private boolean _started = false;
private Object _lock = new Object();
/**
* Creates new instance of the timer.
*/
public FixedRateTimer() {
}
/**
* Creates new instance of the timer and sets its values.
*
* @param task (optional) a Notifiable object to call when timer is
* triggered.
* @param interval (optional) an interval to trigger timer in milliseconds.
* @param delay (optional) a delay before the first triggering in
* milliseconds.
*
* @see #setTask(INotifiable)
* @see #setInterval(long)
* @see #setDelay(long)
*/
public FixedRateTimer(INotifiable task, long interval, long delay) {
_task = task;
_interval = interval;
_delay = delay;
}
/**
* Gets the INotifiable object that receives notifications from this timer.
*
* @return the INotifiable object or null if it is not set.
*/
public INotifiable getTask() {
return _task;
}
/**
* Sets a new INotifiable object to receive notifications from this timer.
*
* @param task a INotifiable object to be triggered.
*/
public void setTask(INotifiable task) {
_task = task;
}
/**
* Gets initial delay before the timer is triggered for the first time.
*
* @return the delay in milliseconds.
*/
public long getDelay() {
return _delay;
}
/**
* Sets initial delay before the timer is triggered for the first time.
*
* @param delay a delay in milliseconds.
*/
public void setDelay(long delay) {
_delay = delay;
}
/**
* Gets periodic timer triggering interval.
*
* @return the interval in milliseconds
*/
public long getInterval() {
return _interval;
}
/**
* Sets periodic timer triggering interval.
*
* @param interval an interval in milliseconds.
*/
public void setInterval(long interval) {
_interval = interval;
}
/**
* Checks if the timer is started.
*
* @return true if the timer is started and false if it is stopped.
*/
public boolean isStarted() {
return _started;
}
/**
* Starts the timer.
*
* Initially the timer is triggered after delay. After that it is triggered
* after interval until it is stopped.
*
* @see #stop()
*/
public void start() {
synchronized (_lock) {
// Stop previously set timer
_timer.purge();
// Set a new timer
TimerTask task = new TimerTask() {
@Override
public void run() {
try {
_task.notify("pip-commons-timer", new Parameters());
} catch (Exception ex) {
// Ignore or better log!
}
}
};
_timer.scheduleAtFixedRate(task, _delay, _interval);
// Set started flag
_started = true;
}
}
/**
* Stops the timer.
*
* @see #start()
*/
public void stop() {
synchronized (_lock) {
// Stop the timer
_timer.purge();
// Unset started flag
_started = false;
}
}
/**
* Closes the timer.
*
* This is required by ICloseable interface, but besides that it is identical to
* stop().
*
* @param correlationId (optional) transaction id to trace execution through
* call chain.
* @throws ApplicationException when error or null no errors occured.
*
* @see #stop()
*/
public void close(String correlationId) throws ApplicationException {
stop();
}
}
|
3e1beae63f359d34a52cbc675e8bf3f20983d56b | 27,460 | java | Java | erp_desktop_all/src_comisiones/com/bydan/erp/comisiones/presentation/swing/jinternalframes/auxiliar/ComisionConfigModel.java | jarocho105/pre2 | f032fc63741b6deecdfee490e23dfa9ef1f42b4f | [
"Apache-2.0"
] | 1 | 2018-01-05T17:50:03.000Z | 2018-01-05T17:50:03.000Z | erp_desktop_all/src_comisiones/com/bydan/erp/comisiones/presentation/swing/jinternalframes/auxiliar/ComisionConfigModel.java | jarocho105/pre2 | f032fc63741b6deecdfee490e23dfa9ef1f42b4f | [
"Apache-2.0"
] | null | null | null | erp_desktop_all/src_comisiones/com/bydan/erp/comisiones/presentation/swing/jinternalframes/auxiliar/ComisionConfigModel.java | jarocho105/pre2 | f032fc63741b6deecdfee490e23dfa9ef1f42b4f | [
"Apache-2.0"
] | null | null | null | 40.621302 | 275 | 0.771012 | 11,825 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.comisiones.presentation.swing.jinternalframes.auxiliar;
import com.bydan.erp.seguridad.business.entity.Usuario;
import com.bydan.erp.seguridad.business.entity.Opcion;
import com.bydan.erp.seguridad.business.entity.PerfilOpcion;
import com.bydan.erp.seguridad.business.entity.PerfilCampo;
import com.bydan.erp.seguridad.business.entity.PerfilAccion;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario;
import com.bydan.erp.seguridad.business.entity.Modulo;
import com.bydan.erp.seguridad.business.entity.Accion;
//import com.bydan.erp.seguridad.business.entity.PerfilAccion;
import com.bydan.erp.seguridad.util.SistemaConstantesFunciones;
import com.bydan.erp.seguridad.util.SistemaConstantesFuncionesAdditional;
import com.bydan.erp.seguridad.business.logic.SistemaLogicAdditional;
import com.bydan.erp.comisiones.util.ComisionConfigConstantesFunciones;
import com.bydan.erp.comisiones.util.ComisionConfigParameterReturnGeneral;
//import com.bydan.erp.comisiones.util.ComisionConfigParameterGeneral;
import com.bydan.framework.erp.business.dataaccess.ConstantesSql;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.DatoGeneralMinimo;
import com.bydan.framework.erp.business.entity.GeneralEntity;
import com.bydan.framework.erp.business.entity.Mensajes;
//import com.bydan.framework.erp.business.entity.MaintenanceType;
import com.bydan.framework.erp.util.MaintenanceType;
import com.bydan.framework.erp.util.FuncionesReporte;
import com.bydan.framework.erp.business.logic.DatosCliente;
import com.bydan.framework.erp.business.logic.Pagination;
import com.bydan.erp.comisiones.presentation.swing.jinternalframes.ComisionConfigBeanSwingJInternalFrame;
import com.bydan.framework.erp.presentation.desktop.swing.TablaGeneralTotalModel;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverter;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate;
import com.bydan.framework.erp.presentation.desktop.swing.DateRenderer;
import com.bydan.framework.erp.presentation.desktop.swing.DateEditorRenderer;
import com.bydan.framework.erp.presentation.desktop.swing.BooleanRenderer;
import com.bydan.framework.erp.presentation.desktop.swing.BooleanEditorRenderer;
import com.bydan.framework.erp.presentation.desktop.swing.TextFieldRenderer;
import com.bydan.framework.erp.presentation.desktop.swing.*;
//import com.bydan.framework.erp.presentation.desktop.swing.TextFieldEditorRenderer;
import com.bydan.framework.erp.presentation.desktop.swing.HeaderRenderer;
import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase;
import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing;
import com.bydan.framework.erp.presentation.desktop.swing.MainJFrame;
import com.bydan.framework.erp.resources.imagenes.AuxiliarImagenes;
import com.bydan.erp.comisiones.resources.reportes.AuxiliarReportes;
import com.bydan.erp.comisiones.util.*;
import com.bydan.erp.comisiones.business.logic.*;
import com.bydan.erp.seguridad.business.logic.*;
import com.bydan.erp.inventario.business.logic.*;
//EJB
//PARAMETROS
//EJB PARAMETROS
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.util.*;
import com.bydan.erp.comisiones.business.entity.*;
//import com.bydan.framework.erp.business.entity.ConexionBeanFace;
//import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.inventario.presentation.swing.jinternalframes.*;
import java.net.NetworkInterface;
import java.net.InterfaceAddress;
import java.net.InetAddress;
import javax.naming.InitialContext;
import java.lang.Long;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.io.Serializable;
import java.util.Hashtable;
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.view.JasperViewer;
import org.apache.log4j.Logger;
import com.bydan.framework.erp.business.entity.Reporte;
//VALIDACION
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRSaver;
import net.sf.jasperreports.engine.xml.JRXmlWriter;
import com.bydan.erp.comisiones.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.comisiones.presentation.swing.jinternalframes.ComisionConfigJInternalFrame;
import com.bydan.erp.comisiones.presentation.swing.jinternalframes.ComisionConfigDetalleFormJInternalFrame;
import java.util.EventObject;
import java.util.EventListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import org.jdesktop.beansbinding.Binding.SyncFailure;
import org.jdesktop.beansbinding.BindingListener;
import org.jdesktop.beansbinding.Bindings;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.PropertyStateEvent;
import org.jdesktop.swingbinding.JComboBoxBinding;
import org.jdesktop.swingbinding.SwingBindings;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import com.bydan.erp.seguridad.business.entity.*;
import com.bydan.erp.inventario.business.entity.*;
import com.bydan.erp.seguridad.util.*;
import com.bydan.erp.inventario.util.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.inventario.presentation.web.jsf.sessionbean.*;
@SuppressWarnings("unused")
public class ComisionConfigModel extends FocusTraversalPolicy implements TableModel, Serializable {
private static final long serialVersionUID = 1L;
public JInternalFrameBase jInternalFrameBase;
private String[] columnNames = {
Constantes2.S_SELECCIONAR
,ComisionConfigConstantesFunciones.LABEL_ID
,ComisionConfigConstantesFunciones.LABEL_IDEMPRESA
,ComisionConfigConstantesFunciones.LABEL_IDTIPOCOMISIONCONFIG
,ComisionConfigConstantesFunciones.LABEL_IDNIVELLINEA
,ComisionConfigConstantesFunciones.LABEL_CONVENDEDOR
,ComisionConfigConstantesFunciones.LABEL_CONVENTAS
,ComisionConfigConstantesFunciones.LABEL_CONCOBROS
,ComisionConfigConstantesFunciones.LABEL_CONREMESATRANSITO
,ComisionConfigConstantesFunciones.LABEL_CONPENALIDAD
,ComisionConfigConstantesFunciones.LABEL_CONABONO
};
public List<ComisionConfig> comisionconfigs;
//NO SE UTILIZA
public ComisionConfigModel(List<ComisionConfig> comisionconfigs,JInternalFrameBase jInternalFrameBase) {
this.comisionconfigs=comisionconfigs;
this.jInternalFrameBase=jInternalFrameBase;
}
public ComisionConfigModel(JInternalFrameBase jInternalFrameBase) {
this.comisionconfigs=new ArrayList<ComisionConfig>();
this.jInternalFrameBase=jInternalFrameBase;
}
@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
@Override
public int getRowCount() {
return this.comisionconfigs.size();
}
@Override
public int getColumnCount() {
return this.columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0: return this.comisionconfigs.get(rowIndex).getIsSelected();
case 1: return this.comisionconfigs.get(rowIndex).getId();
case 2: return this.comisionconfigs.get(rowIndex).getid_empresa();
case 3: return this.comisionconfigs.get(rowIndex).getid_tipo_comision_config();
case 4: return this.comisionconfigs.get(rowIndex).getid_nivel_linea();
case 5: return this.comisionconfigs.get(rowIndex).getcon_vendedor();
case 6: return this.comisionconfigs.get(rowIndex).getcon_ventas();
case 7: return this.comisionconfigs.get(rowIndex).getcon_cobros();
case 8: return this.comisionconfigs.get(rowIndex).getcon_remesa_transito();
case 9: return this.comisionconfigs.get(rowIndex).getcon_penalidad();
case 10: return this.comisionconfigs.get(rowIndex).getcon_abono();
default: return null;
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0: return Boolean.class;
case 1: return Long.class;
case 2: return Long.class;
case 3: return Long.class;
case 4: return Long.class;
case 5: return Boolean.class;
case 6: return Boolean.class;
case 7: return Boolean.class;
case 8: return Boolean.class;
case 9: return Boolean.class;
case 10: return Boolean.class;
default: return String.class;
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0: return true;
case 1: return true;
case 2: return true;
case 3: return true;
case 4: return true;
case 5: return true;
case 6: return true;
case 7: return true;
case 8: return true;
case 9: return true;
case 10: return true;
default: return true;
}
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
ComisionConfig comisionconfig = this.comisionconfigs.get(rowIndex);
Boolean esCampoValor=false;
String sTipo="";
ComisionConfigBeanSwingJInternalFrame comisionconfigBeanSwingJInternalFrame=(ComisionConfigBeanSwingJInternalFrame)this.jInternalFrameBase;
switch (columnIndex) {
case 0: try {comisionconfig.setIsSelected((Boolean) value);} catch (Exception e) {e.printStackTrace();} break;
case 1: try {comisionconfig.setId((Long) value);} catch (Exception e) {e.printStackTrace();} break;
case 2: try {comisionconfig.setid_empresa((Long) value);comisionconfig.setempresa_descripcion(comisionconfigBeanSwingJInternalFrame.getActualEmpresaForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break;
case 3: try {comisionconfig.setid_tipo_comision_config((Long) value);comisionconfig.settipocomisionconfig_descripcion(comisionconfigBeanSwingJInternalFrame.getActualTipoComisionConfigForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break;
case 4: try {comisionconfig.setid_nivel_linea((Long) value);comisionconfig.setnivellinea_descripcion(comisionconfigBeanSwingJInternalFrame.getActualNivelLineaForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break;
case 5: try {comisionconfig.setcon_vendedor((Boolean) value);} catch (Exception e) {e.printStackTrace();} break;
case 6: try {comisionconfig.setcon_ventas((Boolean) value);} catch (Exception e) {e.printStackTrace();} break;
case 7: try {comisionconfig.setcon_cobros((Boolean) value);} catch (Exception e) {e.printStackTrace();} break;
case 8: try {comisionconfig.setcon_remesa_transito((Boolean) value);} catch (Exception e) {e.printStackTrace();} break;
case 9: try {comisionconfig.setcon_penalidad((Boolean) value);} catch (Exception e) {e.printStackTrace();} break;
case 10: try {comisionconfig.setcon_abono((Boolean) value);} catch (Exception e) {e.printStackTrace();} break;
}
fireTableCellUpdated(rowIndex, columnIndex);
if(esCampoValor) {
jInternalFrameBase.procesoActualizarFilaTotales(esCampoValor,sTipo);
}
}
/*FUNCIONES PARA FOCUS TRAVERSAL POLICY*/
private Component componentTab=new JTextField();
private ComisionConfigDetalleFormJInternalFrame comisionconfigJInternalFrame=null;
public ComisionConfigModel(ComisionConfigDetalleFormJInternalFrame comisionconfigJInternalFrame) {
this.comisionconfigJInternalFrame=comisionconfigJInternalFrame;
}
public Component getComponentAfter(Container focusCycleRoot, Component component) {
componentTab=this.comisionconfigJInternalFrame.getjButtonActualizarToolBarComisionConfig();
if(component!=null && component.equals(this.comisionconfigJInternalFrame.getjButtonActualizarToolBarComisionConfig())) {
componentTab=this.comisionconfigJInternalFrame.getjButtonEliminarToolBarComisionConfig();
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.getjButtonEliminarToolBarComisionConfig())) {
componentTab=this.comisionconfigJInternalFrame.getjButtonCancelarToolBarComisionConfig();
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.getjButtonCancelarToolBarComisionConfig())) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxid_empresaComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_abonoComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxTiposAccionesFormularioComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxTiposAccionesFormularioComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jButtonEliminarComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jButtonEliminarComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jButtonActualizarComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jButtonActualizarComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jButtonCancelarComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxid_empresaComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxid_tipo_comision_configComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxid_tipo_comision_configComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxid_nivel_lineaComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxid_nivel_lineaComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_vendedorComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_vendedorComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_ventasComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_ventasComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_cobrosComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_cobrosComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_remesa_transitoComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_remesa_transitoComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_penalidadComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_penalidadComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_abonoComisionConfig;
return componentTab;
}
return componentTab;
}
public Component getComponentBefore(Container focusCycleRoot, Component component) {
componentTab=this.comisionconfigJInternalFrame.getjButtonActualizarToolBarComisionConfig();
if(component!=null && component.equals(this.comisionconfigJInternalFrame.getjButtonEliminarToolBarComisionConfig())) {
componentTab=this.comisionconfigJInternalFrame.getjButtonActualizarToolBarComisionConfig();
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.getjButtonCancelarToolBarComisionConfig())) {
componentTab=this.comisionconfigJInternalFrame.getjButtonEliminarToolBarComisionConfig();
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxid_empresaComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.getjButtonCancelarToolBarComisionConfig();
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxTiposAccionesFormularioComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_abonoComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jButtonEliminarComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxTiposAccionesFormularioComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jButtonActualizarComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jButtonEliminarComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jButtonCancelarComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jButtonActualizarComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxid_tipo_comision_configComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxid_empresaComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jComboBoxid_nivel_lineaComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxid_tipo_comision_configComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_vendedorComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jComboBoxid_nivel_lineaComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_ventasComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_vendedorComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_cobrosComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_ventasComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_remesa_transitoComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_cobrosComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_penalidadComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_remesa_transitoComisionConfig;
return componentTab;
}
if(component!=null && component.equals(this.comisionconfigJInternalFrame.jCheckBoxcon_abonoComisionConfig)) {
componentTab=this.comisionconfigJInternalFrame.jCheckBoxcon_penalidadComisionConfig;
return componentTab;
}
return componentTab;
}
public Component getDefaultComponent(Container focusCycleRoot) {
componentTab=this.comisionconfigJInternalFrame.getjButtonActualizarToolBarComisionConfig();
return componentTab;
}
public Component getFirstComponent(Container focusCycleRoot) {
componentTab=this.comisionconfigJInternalFrame.getjButtonActualizarToolBarComisionConfig();
return componentTab;
}
public Component getLastComponent(Container focusCycleRoot) {
componentTab=this.comisionconfigJInternalFrame.getjButtonCancelarToolBarComisionConfig();
return componentTab;
}
public ComisionConfigDetalleFormJInternalFrame getcomisionconfigJInternalFrame() {
return this.comisionconfigJInternalFrame;
}
public void setcomisionconfigJInternalFrame(ComisionConfigDetalleFormJInternalFrame comisionconfigJInternalFrame) {
this.comisionconfigJInternalFrame=comisionconfigJInternalFrame;
}
public Component getComponentTab() {
return this.componentTab;
}
public void setComponentTab(Component componentTab) {
this.componentTab=componentTab;
}
/*FUNCIONES PARA FOCUS TRAVERSAL POLICY FIN*/
/*FUNCIONES PARA AbstractTableModel*/
/*
Notas:
* Si Cambia version se copia variables y metodos que no son sobreescritos en esta clase.(Usa Jdk 8)
* Se copia del Jdk javax.swing.table.AbstractTableModel
* Los argumentos usados es de tipo Interface TableModel no de Clase AbstractTableModel
* Si se cambia y/o actualiza jdj, toca actualizar el código nuevamente
*/
protected EventListenerList listenerList = new EventListenerList();
public int findColumn(String columnName) {
for (int i = 0; i < getColumnCount(); i++) {
if (columnName.equals(getColumnName(i))) {
return i;
}
}
return -1;
}
public void addTableModelListener(TableModelListener l) {
listenerList.add(TableModelListener.class, l);
}
public void removeTableModelListener(TableModelListener l) {
listenerList.remove(TableModelListener.class, l);
}
public TableModelListener[] getTableModelListeners() {
return listenerList.getListeners(TableModelListener.class);
}
public void fireTableDataChanged() {
fireTableChanged(new TableModelEvent(this));
}
public void fireTableStructureChanged() {
fireTableChanged(new TableModelEvent(this, TableModelEvent.HEADER_ROW));
}
public void fireTableRowsInserted(int firstRow, int lastRow) {
fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
}
public void fireTableRowsUpdated(int firstRow, int lastRow) {
fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE));
}
public void fireTableRowsDeleted(int firstRow, int lastRow) {
fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE));
}
public void fireTableCellUpdated(int row, int column) {
fireTableChanged(new TableModelEvent(this, row, row, column));
}
public void fireTableChanged(TableModelEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TableModelListener.class) {
((TableModelListener)listeners[i+1]).tableChanged(e);
}
}
}
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
/*FUNCIONES PARA AbstractTableModel FIN*/
}
|
3e1beb3817193e4ea57dffc2ea2ae5db02cc01a4 | 771 | java | Java | src/main/java/guru/springframework/converters/NotesCommandToNotes.java | fedorovsf/spring5-mysql-recipe-app | e461ba1ac591d27e67f4a37858d33e4f718c59de | [
"MIT"
] | null | null | null | src/main/java/guru/springframework/converters/NotesCommandToNotes.java | fedorovsf/spring5-mysql-recipe-app | e461ba1ac591d27e67f4a37858d33e4f718c59de | [
"MIT"
] | null | null | null | src/main/java/guru/springframework/converters/NotesCommandToNotes.java | fedorovsf/spring5-mysql-recipe-app | e461ba1ac591d27e67f4a37858d33e4f718c59de | [
"MIT"
] | null | null | null | 25.7 | 76 | 0.71725 | 11,826 | package guru.springframework.converters;
import guru.springframework.commands.NotesCommand;
import guru.springframework.domain.Notes;
import lombok.Synchronized;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
/**
* Created by sergei on 15/12/2018.
*/
@Component
public class NotesCommandToNotes implements Converter<NotesCommand, Notes> {
@Synchronized
@Nullable
@Override
public Notes convert(NotesCommand source) {
if(source == null) {
return null;
}
final Notes notes = new Notes();
notes.setId(source.getId());
notes.setRecipeNotes(source.getRecipeNotes());
return notes;
}
}
|
3e1becb34ee23ce4342ce09a35a5d8b87fe280be | 17,896 | java | Java | src/main/java/water/api/Parse.java | panzelon/h2o-2 | be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1 | [
"Apache-2.0"
] | 882 | 2015-05-22T02:59:21.000Z | 2022-02-17T05:02:48.000Z | src/main/java/water/api/Parse.java | VonRosenchild/h2o-2 | be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1 | [
"Apache-2.0"
] | 1 | 2022-02-22T12:15:02.000Z | 2022-02-22T12:15:02.000Z | src/main/java/water/api/Parse.java | VonRosenchild/h2o-2 | be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1 | [
"Apache-2.0"
] | 392 | 2015-05-22T17:04:11.000Z | 2022-02-22T09:04:39.000Z | 43.970516 | 170 | 0.616395 | 11,827 | package water.api;
import dontweave.gson.JsonObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.regex.Pattern;
import water.*;
import water.parser.CsvParser;
import water.parser.CustomParser;
import water.parser.GuessSetup;
import water.util.RString;
abstract public class Parse extends Request {
private final ParserType _parserType= new ParserType(PARSER_TYPE);
private final Separator _separator = new Separator(SEPARATOR);
private final Bool _header = new Bool(HEADER,false,"Use first line as a header");
private final Bool _hashHeader= new Bool("header_with_hash",false,"Header begins with #"); // for Informatica output
protected final Bool _sQuotes = new Bool("single_quotes",false,"Enable single quotes as field quotation character");
protected final HeaderKey _hdrFrom = new HeaderKey("header_from_file",false);
protected final Str _excludeExpression = new Str("exclude","");
protected final ExistingCSVKey _source = new ExistingCSVKey(SOURCE_KEY);
protected final NewH2OHexKey _dest = new NewH2OHexKey(DEST_KEY);
protected final Bool _blocking = new Bool("blocking",false,"Synchronously wait until parse completes");
@SuppressWarnings("unused")
private final Preview _preview = new Preview(PREVIEW);
public Parse() {
_excludeExpression.setRefreshOnChange();
_header.setRefreshOnChange();
_hashHeader.setRefreshOnChange();
_blocking._hideInQuery = true;
}
// private static String toHTML(ParseSetupGuessException e){
// StringBuilder sb = new StringBuilder("<h3>Unable to Parse</h3>");
// if(!e.getMessage().isEmpty())sb.append("<div>" + e.getMessage() + "</div>");
// if(e._failed != null && e._failed.length > 0){
// sb.append("<div>\n<b>Found " + e._failed.length + " files which are not compatible with the given setup:</b></div>");
// int n = e._failed.length;
// if(n > 5){
// sb.append("<div>" + e._failed[0] + "</div>");
// sb.append("<div>" + e._failed[1] + "</div>");
// sb.append("<div>...</div>");
// sb.append("<div>" + e._failed[n-2] + "</div>");
// sb.append("<div>" + e._failed[n-1] + "</div>");
// } else for(int i = 0; i < n;++i)
// sb.append("<div>" + e._failed[n-1] + "</div>");
// } else if(e._gSetup == null || !e._gSetup.valid()) {
// sb.append("Failed to find consistent parser setup for the given files!");
// }
// return sb.toString();
// }
protected static class PSetup {
final transient ArrayList<Key> _keys;
final transient Key [] _failedKeys;
final CustomParser.PSetupGuess _setup;
PSetup( ArrayList<Key> keys, Key [] fkeys, CustomParser.PSetupGuess pguess) { _keys=keys; _failedKeys = fkeys; _setup = pguess; }
};
// An H2O Key Query, which runs the basic CSV parsing heuristics. Accepts
// Key wildcards, and gathers all matching Keys for simultaneous parsing.
// Multi-key parses are only allowed on compatible CSV files, and only 1 is
// allowed to have headers.
public class ExistingCSVKey extends TypeaheadInputText<PSetup> {
public ExistingCSVKey(String name) {
super(TypeaheadKeysRequest.class, name, true);
// addPrerequisite(_parserType);
// addPrerequisite(_separator);
}
@Override protected PSetup parse(String input) throws IllegalArgumentException {
final Pattern p = makePattern(input);
final Pattern exclude;
if(_hdrFrom.specified())
_header.setValue(true);
if(_hashHeader.value())
_header.setValue(true);
exclude = _excludeExpression.specified()?makePattern(_excludeExpression.value()):null;
// boolean badkeys = false;
final Key [] keyAry = H2O.KeySnapshot.globalSnapshot().filter(new H2O.KVFilter() {
@Override
public boolean filter(H2O.KeyInfo k) {
if(k._rawData && k._nrows > 0) {
String ks = k._key.toString();
return (p.matcher(ks).matches() && (exclude == null || !exclude.matcher(ks).matches()));
}
return false;
}
}).keys();
ArrayList<Key> keys = new ArrayList<Key>(keyAry.length);
for(Key k:keyAry)keys.add(k);
// now we assume the first key has the header
Key hKey = null;
if(_hdrFrom.specified()){
hKey = _hdrFrom.value()._key;
_header.setValue(true);
}
CustomParser.ParserSetup userSetup = new CustomParser.ParserSetup(_parserType.value(),_separator.value(),_header.value(), _hashHeader.value(), _sQuotes.value());
CustomParser.PSetupGuess setup = null;
try {
setup = GuessSetup.guessSetup(keys, hKey, userSetup,!_header.specified());
}catch(GuessSetup.ParseSetupGuessException e){
throw new IllegalArgumentException(e.getMessage());
}
if(setup._isValid){
if(setup._hdrFromFile != null)
_hdrFrom.setValue(DKV.get(setup._hdrFromFile));
if(!_header.specified())
_header.setValue(setup._setup._header);
else
setup._setup._header = _header.value();
if(!_header.value())
_hdrFrom.disable("Header is disabled.");
PSetup res = new PSetup(keys,null,setup);
_parserType.setValue(setup._setup._pType);
_separator.setValue(setup._setup._separator);
_hdrFrom._hideInQuery = _header._hideInQuery = _separator._hideInQuery = setup._setup._pType != CustomParser.ParserType.CSV;
Set<String> dups = setup.checkDupColumnNames();
if(!dups.isEmpty())
throw new IllegalArgumentException("Column labels must be unique but these labels are repeated: " + dups.toString());
return res;
} else
throw new IllegalArgumentException("Invalid parser setup. " + setup.toString());
}
private final String keyRow(Key k){
return "<tr><td>" + k + "</td></tr>\n";
}
@Override
public String queryComment(){
if(!specified())return "";
PSetup p = value();
StringBuilder sb = new StringBuilder();
if(p._keys.size() <= 10){
for(Key k:p._keys)
sb.append(keyRow(k));
} else {
int n = p._keys.size();
for(int i = 0; i < 5; ++i)
sb.append(keyRow(p._keys.get(i)));
sb.append("<tr><td>...</td></tr>\n");
for(int i = 5; i > 0; --i)
sb.append(keyRow(p._keys.get(n-i)));
}
return
"<div class='alert'><b> Found " + p._keys.size() + " files matching the expression.</b><br/>\n" +
"<table>\n" +
sb.toString() +
"</table></div>";
}
private Pattern makePattern(String input) {
// Reg-Ex pattern match all keys, like file-globbing.
// File-globbing: '?' allows an optional single character, regex needs '.?'
// File-globbing: '*' allows any characters, regex needs '*?'
// File-globbing: '\' is normal character in windows, regex needs '\\'
String patternStr = input.replace("?",".?").replace("*",".*?").replace("\\","\\\\").replace("(","\\(").replace(")","\\)");
Pattern p = Pattern.compile(patternStr);
return p;
}
@Override protected PSetup defaultValue() { return null; }
@Override protected String queryDescription() { return "An existing H2O key (or regex of keys) of CSV text"; }
}
// A Query String, which defaults to the source Key with a '.hex' suffix
protected class NewH2OHexKey extends Str {
NewH2OHexKey(String name) {
super(name,null/*not required flag*/);
addPrerequisite(_source);
}
@Override protected String defaultValue() {
PSetup setup = _source.value();
if( setup == null ) return null;
String n = setup._keys.get(0).toString();
// blahblahblah/myName.ext ==> myName
int sep = n.lastIndexOf(File.separatorChar);
if( sep > 0 ) n = n.substring(sep+1);
int dot = n.lastIndexOf('.');
if( dot > 0 ) n = n.substring(0, dot);
if( !Character.isJavaIdentifierStart(n.charAt(0)) ) n = "X"+n;
char[] cs = n.toCharArray();
for( int i=1; i<cs.length; i++ )
if( !Character.isJavaIdentifierPart(cs[i]) )
cs[i] = '_';
n = new String(cs);
int i = 0;
String res = n + Extensions.HEX;
Key k = Key.make(res);
while(DKV.get(k) != null)
k = Key.make(res = n + ++i + Extensions.HEX);
return res;
}
@Override protected String queryDescription() { return "Destination hex key"; }
}
public class HeaderKey extends H2OExistingKey {
public HeaderKey(String name, boolean required) {
super(name, required);
}
@Override protected String queryElement() {
StringBuilder sb = new StringBuilder(super.queryElement() + "\n");
try{
String [] colnames = _source.value() != null ? _source.value()._setup._setup._columnNames : null;
if(colnames != null){
sb.append("<table class='table table-striped table-bordered'>").append("<tr><th>Header:</th>");
for( String s : colnames ) sb.append("<th>").append(s).append("</th>");
sb.append("</tr></table>");
}
} catch( Exception e ) { }
return sb.toString();
}
}
// A Query Bool, which includes a pretty HTML-ized version of the first few
// parsed data rows. If the value() is TRUE, we display as-if the first row
// is a label/header column, and if FALSE not.
public class Preview extends Argument {
Preview(String name) {
super(name,false);
// addPrerequisite(_source);
// addPrerequisite(_separator);
// addPrerequisite(_parserType);
// addPrerequisite(_header);
setRefreshOnChange();
}
@Override protected String queryElement() {
// first determine the value to put in the field
// if no original value was supplied, use the provided one
String[][] data = null;
PSetup psetup = _source.value();
if(psetup == null)
return _source.specified()?"<div class='alert alert-error'><b>Found no valid setup!</b></div>":"";
StringBuilder sb = new StringBuilder();
if(psetup._failedKeys != null){
sb.append("<div class='alert alert-error'>");
sb.append("<div>\n<b>Found " + psetup._failedKeys.length + " files which are not compatible with the given setup:</b></div>");
int n = psetup._failedKeys.length;
if(n > 5){
sb.append("<div>" + psetup._failedKeys[0] + "</div>\n");
sb.append("<div>" + psetup._failedKeys[1] + "</div>\n");
sb.append("<div>...</div>");
sb.append("<div>" + psetup._failedKeys[n-2] + "</div>\n");
sb.append("<div>" + psetup._failedKeys[n-1] + "</div>\n");
} else for(int i = 0; i < n;++i)
sb.append("<div>" + psetup._failedKeys[n-1] + "</div>\n");
sb.append("</div>\n");
}
String [] err = psetup._setup._errors;
boolean hasErrors = err != null && err.length > 0;
boolean parsedOk = psetup._setup._isValid;
String parseMsgType = hasErrors?parsedOk?"warning":"error":"success";
sb.append("<div class='alert alert-" + parseMsgType + "'><b>" + psetup._setup.toString() + "</b>");
if(hasErrors)
for(String s:err)sb.append("<div>" + s + "</div>");
sb.append("</div>");
if(psetup._setup != null)
data = psetup._setup._data;
String [] header = psetup._setup._setup._columnNames;
if( data != null ) {
sb.append("<table class='table table-striped table-bordered'>");
int j = 0;
if( psetup._setup._setup._header && header != null) { // Obvious header display, if asked for
sb.append("<tr><th>Row#</th>");
for( String s : header ) sb.append("<th>").append(s).append("</th>");
sb.append("</tr>");
if(header == data[0]) ++j;
}
for( int i=j; i<data.length; i++ ) { // The first few rows
sb.append("<tr><td>Row ").append(i-j).append("</td>");
for( String s : data[i] ) sb.append("<td>").append(s).append("</td>");
sb.append("</tr>");
}
sb.append("</table>");
}
return sb.toString();
}
@Override protected Object parse(String input) throws IllegalArgumentException {return null;}
@Override protected Object defaultValue() {return null;}
@Override protected String queryDescription() {
return "Preview of the parsed data";
}
@Override protected String jsRefresh(String callbackName) {
return "";
}
@Override protected String jsValue() {
return "";
}
}
public static String link(Key k, String content) {
return link(k.toString(),content);
}
public static String link(String k, String content) {
RString rs = new RString("<a href='Parse.query?%key_param=%$key'>%content</a>");
rs.replace("key_param", SOURCE_KEY);
rs.replace("key", k.toString());
rs.replace("content", content);
return rs.toString();
}
//@Override protected Response serve() {
// PSetup p = _source.value();
// if(!p._setup._isValid)
// return Response.error("Given parser setup is not valid, I can not parse this file.");
// CustomParser.ParserSetup setup = p._setup._setup;
// setup._singleQuotes = _sQuotes.value();
// Key dest = Key.make(_dest.value());
// try {
// // Make a new Setup, with the 'header' flag set according to user wishes.
// Key[] keys = p._keys.toArray(new Key[p._keys.size()]);
// Job job = ParseDataset.forkParseDataset(dest, keys,setup);
// if (_blocking.value()) {
// Job.waitUntilJobEnded(job.self());
// }
// JsonObject response = new JsonObject();
// response.addProperty(RequestStatics.JOB, job.self().toString());
// response.addProperty(RequestStatics.DEST_KEY,dest.toString());
// Response r = Progress.redirect(response, job.self(), dest);
// r.setBuilder(RequestStatics.DEST_KEY, new KeyElementBuilder());
// return r;
// } catch( Throwable e ) {
// return Response.error(e);
// }
//}
private class Separator extends InputSelect<Byte> {
public Separator(String name) {
super(name,false);
setRefreshOnChange();
}
@Override protected String queryDescription() { return "Utilized separator"; }
@Override protected String[] selectValues() { return DEFAULT_IDX_DELIMS; }
@Override protected String[] selectNames() { return DEFAULT_DELIMS; }
@Override protected Byte defaultValue() {return CsvParser.AUTO_SEP;}
public void setValue(Byte b){record()._value = b;}
@Override protected String selectedItemValue(){ return value() != null ? value().toString() : defaultValue().toString(); }
@Override protected Byte parse(String input) throws IllegalArgumentException {
Byte result = Byte.valueOf(input);
return result;
}
}
private class ParserType extends InputSelect<CustomParser.ParserType> {
public ParserType(String name) {
super(name,false);
setRefreshOnChange();
_values = new String [CustomParser.ParserType.values().length-1];
int i = 0;
for(CustomParser.ParserType t:CustomParser.ParserType.values())
if(t != CustomParser.ParserType.XLSX)
_values[i++] = t.name();
}
private final String [] _values;
@Override protected String queryDescription() { return "File type"; }
@Override protected String[] selectValues() {
return _values;
}
@Override protected String[] selectNames() {
return _values;
}
@Override protected CustomParser.ParserType defaultValue() {
return CustomParser.ParserType.AUTO;
}
public void setValue(CustomParser.ParserType pt){record()._value = pt;}
@Override protected String selectedItemValue(){
return value() != null ? value().toString() : defaultValue().toString(); }
@Override protected CustomParser.ParserType parse(String input) throws IllegalArgumentException {
return CustomParser.ParserType.valueOf(input);
}
}
/** List of white space delimiters */
static final String[] WHITE_DELIMS = { "NULL", "SOH (start of heading)", "STX (start of text)", "ETX (end of text)", "EOT (end of transmission)",
"ENQ (enquiry)", "ACK (acknowledge)", "BEL '\\a' (bell)", "BS '\b' (backspace)", "HT '\\t' (horizontal tab)", "LF '\\n' (new line)", " VT '\\v' (vertical tab)",
"FF '\\f' (form feed)", "CR '\\r' (carriage ret)", "SO (shift out)", "SI (shift in)", "DLE (data link escape)", "DC1 (device control 1) ", "DC2 (device control 2)",
"DC3 (device control 3)", "DC4 (device control 4)", "NAK (negative ack.)", "SYN (synchronous idle)", "ETB (end of trans. blk)", "CAN (cancel)", "EM (end of medium)",
"SUB (substitute)", "ESC (escape)", "FS (file separator)", "GS (group separator)", "RS (record separator)", "US (unit separator)", "' ' SPACE" };
/** List of all ASCII delimiters */
static final String[] DEFAULT_DELIMS = new String[127];
static final String[] DEFAULT_IDX_DELIMS = new String[127];
static {
int i = 0;
for (i = 0; i < WHITE_DELIMS.length; i++) DEFAULT_DELIMS[i] = String.format("%s: '%02d'", WHITE_DELIMS[i],i);
for (;i < 126; i++) {
String s = null; // Escape HTML entities manually or use StringEscapeUtils from Apache
switch ((char)i) {
case '&': s = "&"; break;
case '<': s = "<"; break;
case '>': s = ">"; break;
case '\"': s = """; break;
default : s = Character.toString((char)i);
}
DEFAULT_DELIMS[i] = String.format("%s: '%02d'", s, i);
}
for (i = 0; i < 126; i++) DEFAULT_IDX_DELIMS[i] = String.valueOf(i);
DEFAULT_DELIMS[i] = "AUTO";
DEFAULT_IDX_DELIMS[i] = String.valueOf(CsvParser.AUTO_SEP);
};
}
|
3e1becce533fb09f04d67d46eec2a10a76b8138e | 2,140 | java | Java | geode-benchmarks/src/main/java/org/apache/geode/benchmark/tasks/PutStringTask.java | jdeppe-pivotal/geode-benchmarks | df05773d4994bcd95973e88af2b2ea473e88d711 | [
"Apache-2.0"
] | 7 | 2019-03-17T04:58:42.000Z | 2022-01-17T08:27:20.000Z | geode-benchmarks/src/main/java/org/apache/geode/benchmark/tasks/PutStringTask.java | jdeppe-pivotal/geode-benchmarks | df05773d4994bcd95973e88af2b2ea473e88d711 | [
"Apache-2.0"
] | 26 | 2018-11-21T21:10:21.000Z | 2022-02-10T21:29:11.000Z | geode-benchmarks/src/main/java/org/apache/geode/benchmark/tasks/PutStringTask.java | jdeppe-pivotal/geode-benchmarks | df05773d4994bcd95973e88af2b2ea473e88d711 | [
"Apache-2.0"
] | 33 | 2018-11-20T00:49:14.000Z | 2022-01-17T08:27:21.000Z | 31.470588 | 83 | 0.747664 | 11,828 | /*
* 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.geode.benchmark.tasks;
import static java.lang.String.valueOf;
import java.io.Serializable;
import java.util.Map;
import org.yardstickframework.BenchmarkConfiguration;
import org.yardstickframework.BenchmarkDriverAdapter;
import org.apache.geode.benchmark.LongRange;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.Region;
/**
* Task workload to perform get operations on keys within 0
* and the keyRange (exclusive)
*/
public class PutStringTask extends BenchmarkDriverAdapter implements Serializable {
private final LongRange keyRange;
private Region<String, String> region;
private long offset;
private String[] keys;
public PutStringTask(LongRange keyRange) {
this.keyRange = keyRange;
}
@Override
public void setUp(BenchmarkConfiguration cfg) throws Exception {
super.setUp(cfg);
final Cache cache = CacheFactory.getAnyInstance();
region = cache.getRegion("region");
offset = keyRange.getMin();
keys = new String[(int) (keyRange.getMax() - offset)];
keyRange.forEach(i -> keys[(int) i] = valueOf(i));
}
@Override
public boolean test(Map<Object, Object> ctx) throws Exception {
final String key = keys[(int) (keyRange.random() - offset)];
region.put(key, key);
return true;
}
}
|
3e1becd4d97dc8b5e3d0521dd2eeb86589ae3b1b | 521 | java | Java | src/main/java/br/com/customer/api/customer/api/api/dto/CustomerFilter.java | New-Customer-API/customer-api | a59a224d7ba9837eea362457d94d48376ee6deaf | [
"MIT"
] | null | null | null | src/main/java/br/com/customer/api/customer/api/api/dto/CustomerFilter.java | New-Customer-API/customer-api | a59a224d7ba9837eea362457d94d48376ee6deaf | [
"MIT"
] | 1 | 2021-04-19T15:13:57.000Z | 2021-04-19T15:13:57.000Z | src/main/java/br/com/customer/api/customer/api/api/dto/CustomerFilter.java | New-Customer-API/customer-api | a59a224d7ba9837eea362457d94d48376ee6deaf | [
"MIT"
] | 1 | 2021-04-23T13:24:29.000Z | 2021-04-23T13:24:29.000Z | 21.708333 | 49 | 0.733205 | 11,829 | package br.com.customer.api.customer.api.api.dto;
import lombok.Data;
@Data
public class CustomerFilter {
private String fullName;
private String nickName;
private String document;
private String documentType;
private String email;
private String country;
private String city;
private String state;
private String neighborhood;
private String complement;
private String number;
private String countryCode;
private String areaCode;
private String phoneNumber;
}
|
3e1bed6076cfa51725ea19717f89fc5fa34643a7 | 4,858 | java | Java | processing/src/main/java/org/apache/druid/segment/vector/NilVectorSelector.java | jimjoamz/druid | 7d5666109c9d4952fc66af170c7d46918d7378dd | [
"Apache-2.0"
] | 5,813 | 2015-01-01T14:14:54.000Z | 2018-07-06T11:13:03.000Z | processing/src/main/java/org/apache/druid/segment/vector/NilVectorSelector.java | jimjoamz/druid | 7d5666109c9d4952fc66af170c7d46918d7378dd | [
"Apache-2.0"
] | 4,320 | 2015-01-02T18:37:24.000Z | 2018-07-06T14:51:01.000Z | processing/src/main/java/org/apache/druid/segment/vector/NilVectorSelector.java | jimjoamz/druid | 7d5666109c9d4952fc66af170c7d46918d7378dd | [
"Apache-2.0"
] | 1,601 | 2015-01-05T05:37:05.000Z | 2018-07-06T11:13:04.000Z | 27.139665 | 118 | 0.717373 | 11,830 | /*
* 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.druid.segment.vector;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.segment.IdLookup;
import org.apache.druid.segment.QueryableIndexStorageAdapter;
import javax.annotation.Nullable;
public class NilVectorSelector
implements VectorValueSelector, VectorObjectSelector, SingleValueDimensionVectorSelector, IdLookup
{
private static final boolean[] DEFAULT_NULLS_VECTOR = new boolean[QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE];
private static final int[] DEFAULT_INT_VECTOR = new int[QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE];
private static final long[] DEFAULT_LONG_VECTOR = new long[QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE];
private static final float[] DEFAULT_FLOAT_VECTOR = new float[QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE];
private static final double[] DEFAULT_DOUBLE_VECTOR = new double[QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE];
private static final Object[] DEFAULT_OBJECT_VECTOR = new Object[QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE];
static {
for (int i = 0; i < DEFAULT_NULLS_VECTOR.length; i++) {
DEFAULT_NULLS_VECTOR[i] = NullHandling.sqlCompatible();
}
}
private final VectorSizeInspector vectorSizeInspector;
private final boolean[] nulls;
private final int[] ints;
private final long[] longs;
private final float[] floats;
private final double[] doubles;
private final Object[] objects;
private NilVectorSelector(
final VectorSizeInspector vectorSizeInspector,
final boolean[] nulls,
final int[] ints,
final long[] longs,
final float[] floats,
final double[] doubles,
final Object[] objects
)
{
this.vectorSizeInspector = vectorSizeInspector;
this.nulls = nulls;
this.ints = ints;
this.longs = longs;
this.floats = floats;
this.doubles = doubles;
this.objects = objects;
}
public static NilVectorSelector create(final VectorSizeInspector vectorSizeInspector)
{
if (vectorSizeInspector.getMaxVectorSize() <= QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE) {
// Reuse static vars when possible.
return new NilVectorSelector(
vectorSizeInspector,
DEFAULT_NULLS_VECTOR,
DEFAULT_INT_VECTOR,
DEFAULT_LONG_VECTOR,
DEFAULT_FLOAT_VECTOR,
DEFAULT_DOUBLE_VECTOR,
DEFAULT_OBJECT_VECTOR
);
} else {
return new NilVectorSelector(
vectorSizeInspector,
new boolean[vectorSizeInspector.getMaxVectorSize()],
new int[vectorSizeInspector.getMaxVectorSize()],
new long[vectorSizeInspector.getMaxVectorSize()],
new float[vectorSizeInspector.getMaxVectorSize()],
new double[vectorSizeInspector.getMaxVectorSize()],
new Object[vectorSizeInspector.getMaxVectorSize()]
);
}
}
@Override
public long[] getLongVector()
{
return longs;
}
@Override
public float[] getFloatVector()
{
return floats;
}
@Override
public double[] getDoubleVector()
{
return doubles;
}
@Nullable
@Override
public boolean[] getNullVector()
{
return nulls;
}
@Override
public int[] getRowVector()
{
return ints;
}
@Override
public int getValueCardinality()
{
return 1;
}
@Nullable
@Override
public String lookupName(final int id)
{
assert id == 0 : "id = " + id;
return null;
}
@Override
public boolean nameLookupPossibleInAdvance()
{
return true;
}
@Nullable
@Override
public IdLookup idLookup()
{
return this;
}
@Override
public int lookupId(@Nullable final String name)
{
return NullHandling.isNullOrEquivalent(name) ? 0 : -1;
}
@Override
public Object[] getObjectVector()
{
return objects;
}
@Override
public int getCurrentVectorSize()
{
return vectorSizeInspector.getCurrentVectorSize();
}
@Override
public int getMaxVectorSize()
{
return vectorSizeInspector.getMaxVectorSize();
}
}
|
3e1bed83678268340763f2517e57805356cafa05 | 454 | java | Java | tests/deployment/src/test/java/org/jboss/weld/deployments/stateless/localview/EarDeployedLocalEEInjectionTest.java | mojavelinux/arquillian | 899ac3062308ce75649e63e06136016a1a2c1812 | [
"Apache-2.0"
] | null | null | null | tests/deployment/src/test/java/org/jboss/weld/deployments/stateless/localview/EarDeployedLocalEEInjectionTest.java | mojavelinux/arquillian | 899ac3062308ce75649e63e06136016a1a2c1812 | [
"Apache-2.0"
] | null | null | null | tests/deployment/src/test/java/org/jboss/weld/deployments/stateless/localview/EarDeployedLocalEEInjectionTest.java | mojavelinux/arquillian | 899ac3062308ce75649e63e06136016a1a2c1812 | [
"Apache-2.0"
] | null | null | null | 28.375 | 130 | 0.795154 | 11,831 | package org.jboss.weld.deployments.stateless.localview;
import org.jboss.arquillian.api.Deployment;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
public class EarDeployedLocalEEInjectionTest extends LocalEEInjectionTest
{
@Deployment
public static EnterpriseArchive assemble()
{
return createEnterpriseArchive(WarDeployedLocalEEInjectionTest.assemble().addClass(EarDeployedLocalEEInjectionTest.class));
}
}
|
3e1beda766c39a4f1d671bb8ecad50212b6caf5d | 1,446 | java | Java | echo_master_service/modules/json2pojo/src/test/java/in/dream_lab/echo/test/DataflowInputTest.java | dream-lab/echo | 3ba3e83068e733bc2330e0d1c9176d3fc2fb7e20 | [
"Apache-2.0"
] | 17 | 2017-07-15T01:18:07.000Z | 2022-02-07T19:28:00.000Z | echo_master_service/modules/json2pojo/src/test/java/in/dream_lab/echo/test/DataflowInputTest.java | dream-lab/echo | 3ba3e83068e733bc2330e0d1c9176d3fc2fb7e20 | [
"Apache-2.0"
] | 16 | 2017-08-02T09:14:43.000Z | 2019-07-01T03:38:17.000Z | echo_master_service/modules/json2pojo/src/test/java/in/dream_lab/echo/test/DataflowInputTest.java | dream-lab/echo | 3ba3e83068e733bc2330e0d1c9176d3fc2fb7e20 | [
"Apache-2.0"
] | 10 | 2017-10-01T03:48:04.000Z | 2022-02-07T19:28:01.000Z | 32.133333 | 86 | 0.616183 | 11,832 | package in.dream_lab.echo.test;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import in.dream_lab.echo.utils.DataflowInput;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
/**
* Created by pushkar on 5/26/17.
*/
public class DataflowInputTest {
@Test
public void testDeserialize() {
try {
BufferedReader reader = new BufferedReader(
new FileReader("../../input-dags/trivial-dag-1.json"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String json = builder.toString();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
DataflowInput dataflowInput = mapper.readValue(json, DataflowInput.class);
assert(dataflowInput.getProcessors()
.iterator().next()
.getProperties().get(0)
.getAdditionalProperties().get("Batch Size").equals("10"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
3e1bedce49ea8d48b0c3bdfdda98cda6cf76f971 | 3,950 | java | Java | sources/android-28/com/android/mtp/MtpFileWriter.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | sources/android-28/com/android/mtp/MtpFileWriter.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | sources/android-28/com/android/mtp/MtpFileWriter.java | FTC-10161/FtcRobotController | ee6c7efdff947ccd0abfab64405a91176768e7c0 | [
"MIT"
] | 1,141 | 2015-01-01T22:54:40.000Z | 2022-02-09T22:08:26.000Z | 36.238532 | 95 | 0.675696 | 11,833 | /*
* Copyright (C) 2016 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.mtp;
import android.content.Context;
import android.mtp.MtpObjectInfo;
import android.os.ParcelFileDescriptor;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import com.android.internal.util.Preconditions;
import java.io.File;
import java.io.IOException;
class MtpFileWriter implements AutoCloseable {
final ParcelFileDescriptor mCacheFd;
final String mDocumentId;
boolean mDirty;
MtpFileWriter(Context context, String documentId) throws IOException {
mDocumentId = documentId;
mDirty = false;
final File tempFile = File.createTempFile("mtp", "tmp", context.getCacheDir());
mCacheFd = ParcelFileDescriptor.open(
tempFile,
ParcelFileDescriptor.MODE_READ_WRITE |
ParcelFileDescriptor.MODE_TRUNCATE |
ParcelFileDescriptor.MODE_CREATE);
tempFile.delete();
}
String getDocumentId() {
return mDocumentId;
}
int write(long offset, int size, byte[] bytes) throws IOException, ErrnoException {
Preconditions.checkArgumentNonnegative(offset, "offset");
Preconditions.checkArgumentNonnegative(size, "size");
Preconditions.checkArgument(size <= bytes.length);
if (size == 0) {
return 0;
}
mDirty = true;
Os.lseek(mCacheFd.getFileDescriptor(), offset, OsConstants.SEEK_SET);
return Os.write(mCacheFd.getFileDescriptor(), bytes, 0, size);
}
void flush(MtpManager manager, MtpDatabase database, int[] operationsSupported)
throws IOException, ErrnoException {
// Skip unnecessary flush.
if (!mDirty) {
return;
}
// Get the placeholder object info.
final Identifier identifier = database.createIdentifier(mDocumentId);
final MtpObjectInfo placeholderObjectInfo =
manager.getObjectInfo(identifier.mDeviceId, identifier.mObjectHandle);
// Delete the target object info if it already exists (as a placeholder).
manager.deleteDocument(identifier.mDeviceId, identifier.mObjectHandle);
// Create the target object info with a correct file size and upload the file.
final long size = Os.lseek(mCacheFd.getFileDescriptor(), 0, OsConstants.SEEK_END);
final MtpObjectInfo targetObjectInfo = new MtpObjectInfo.Builder(placeholderObjectInfo)
.setCompressedSize(size)
.build();
Os.lseek(mCacheFd.getFileDescriptor(), 0, OsConstants.SEEK_SET);
final int newObjectHandle = manager.createDocument(
identifier.mDeviceId, targetObjectInfo, mCacheFd);
final MtpObjectInfo newObjectInfo = manager.getObjectInfo(
identifier.mDeviceId, newObjectHandle);
final Identifier parentIdentifier =
database.getParentIdentifier(identifier.mDocumentId);
database.updateObject(
identifier.mDocumentId,
identifier.mDeviceId,
parentIdentifier.mDocumentId,
operationsSupported,
newObjectInfo,
size);
mDirty = false;
}
@Override
public void close() throws IOException {
mCacheFd.close();
}
}
|
3e1bedf38af353af3450b1e99e69d967a8d438a6 | 1,551 | java | Java | src/main/java/org/project/openbaton/nubomedia/paas/model/openshift/HorizontalPodAutoscaler.java | nubomedia/nubomedia-paas | f85df66e0b8cf5a2e926afc6ec4f4de6857638c7 | [
"Apache-2.0"
] | 19 | 2016-10-11T14:23:08.000Z | 2020-04-07T15:38:45.000Z | src/main/java/org/project/openbaton/nubomedia/paas/model/openshift/HorizontalPodAutoscaler.java | nubomedia/nubomedia-paas | f85df66e0b8cf5a2e926afc6ec4f4de6857638c7 | [
"Apache-2.0"
] | 8 | 2016-07-30T09:37:30.000Z | 2017-03-14T18:39:06.000Z | src/main/java/org/project/openbaton/nubomedia/paas/model/openshift/HorizontalPodAutoscaler.java | nubomedia/nubomedia-paas | f85df66e0b8cf5a2e926afc6ec4f4de6857638c7 | [
"Apache-2.0"
] | 9 | 2016-10-10T08:35:42.000Z | 2020-05-25T14:57:25.000Z | 24.619048 | 89 | 0.691812 | 11,834 | /*
*
* * (C) Copyright 2016 NUBOMEDIA (http://www.nubomedia.eu)
* *
* * 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.project.openbaton.nubomedia.paas.model.openshift;
/**
* Created by maa on 07.02.16.
*/
public class HorizontalPodAutoscaler {
private final String kind = "HorizontalPodAutoscaler";
private final String apiVersion = "extensions/v1beta1"; //TODO Change when are official
private Metadata metadata;
private HPASpec spec;
public HorizontalPodAutoscaler(Metadata metadata, HPASpec spec) {
this.metadata = metadata;
this.spec = spec;
}
public HorizontalPodAutoscaler() {}
public String getKind() {
return kind;
}
public String getApiVersion() {
return apiVersion;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public HPASpec getSpec() {
return spec;
}
public void setSpec(HPASpec spec) {
this.spec = spec;
}
}
|
3e1bee0435e4f85c3c1054d8518f06fade01b43e | 1,848 | java | Java | src/SouleveMalade.java | Shakabrahh/Projet_LP | 8c58c71852affc39da847c3c8af2b7ac8ef34fe3 | [
"MIT"
] | null | null | null | src/SouleveMalade.java | Shakabrahh/Projet_LP | 8c58c71852affc39da847c3c8af2b7ac8ef34fe3 | [
"MIT"
] | null | null | null | src/SouleveMalade.java | Shakabrahh/Projet_LP | 8c58c71852affc39da847c3c8af2b7ac8ef34fe3 | [
"MIT"
] | null | null | null | 28.875 | 99 | 0.669913 | 11,835 | import java.util.Objects;
/** The type Souleve malade. */
public class SouleveMalade extends Article {
private final Double capLevage;
private final Double degPivo;
/**
* Constructeur de la classe SouleveMalade.
*
* @param reference Référence de l'article
* @param marque Marque de l'article
* @param modele Modèle de l'article
* @param prixParJour Prix par jour pour la location
* @param stock Nombre d'articles disponibles en magasin
* @param capLevage Capacité de levage de l'article
* @param degPivo Capacité de rotation de l'article
*/
public SouleveMalade(
String reference,
String marque,
String modele,
Double prixParJour,
int stock,
Double capLevage,
Double degPivo) {
super(reference, marque, modele, prixParJour, stock);
this.capLevage = capLevage;
this.degPivo = degPivo;
}
/**
* Test d'égalité entre deux instances de SouleveMalade.
*
* @param o l'article à tester
* @return Vrai si les deux Clients sont les mêmes, faux autrement
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SouleveMalade)) return false;
if (!super.equals(o)) return false;
SouleveMalade that = (SouleveMalade) o;
return Objects.equals(capLevage, that.capLevage) && Objects.equals(degPivo, that.degPivo);
}
@Override
public int hashCode() {
int result = capLevage != null ? capLevage.hashCode() : 0;
result = 31 * result + (degPivo != null ? degPivo.hashCode() : 0);
return result;
}
/**
* Affichage des attributs.
*
* @return Attributs du SouleveMalade sous la forme d'une chaine de caractère
*/
@Override
public String toString() {
return "SouleveMalade{" + "capLevage=" + capLevage + ", degPivo=" + degPivo + super.toString();
}
}
|
3e1bee5cbd8482bfef6c4720766af2e44b337f85 | 3,150 | java | Java | backend/vms-public/src/main/java/de/vms/vulnerability/model/dto/VulnerabilityDto.java | daubli/iast-vms | 68a22136e80dc42c16ad1ca8baf8fdc0c9409c11 | [
"MIT"
] | 2 | 2021-07-29T00:26:52.000Z | 2021-09-28T14:47:23.000Z | backend/vms-public/src/main/java/de/vms/vulnerability/model/dto/VulnerabilityDto.java | daubli/iast-vms | 68a22136e80dc42c16ad1ca8baf8fdc0c9409c11 | [
"MIT"
] | null | null | null | backend/vms-public/src/main/java/de/vms/vulnerability/model/dto/VulnerabilityDto.java | daubli/iast-vms | 68a22136e80dc42c16ad1ca8baf8fdc0c9409c11 | [
"MIT"
] | 1 | 2021-12-27T03:03:47.000Z | 2021-12-27T03:03:47.000Z | 24.230769 | 99 | 0.687302 | 11,836 | package de.vms.vulnerability.model.dto;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.vms.agent.model.dto.AgentDto;
import de.vms.vulnerability.model.Severity;
import de.vms.vulnerability.model.VulnerabilityStatus;
import de.vms.vulnerability.model.VulnerabilityType;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class VulnerabilityDto {
private UUID id;
UUID agentId;
Severity severity;
VulnerabilityType type;
String description;
LocalDateTime firstDetected;
LocalDateTime lastDetected;
VulnerabilityStatus status;
@JsonProperty("incidents")
List<IncidentDto> incidentsOrNull = new ArrayList<>();
@JsonProperty("detectedOnAgents")
Set<AgentDto> detectedOnAgentsOrNull;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getAgentId() {
return agentId;
}
public void setAgentId(UUID agentId) {
this.agentId = agentId;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public VulnerabilityType getType() {
return type;
}
public void setType(VulnerabilityType type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", locale = "de-DE",
timezone = "Europe/Berlin")
public LocalDateTime getLastDetected() {
return lastDetected;
}
public void setLastDetected(LocalDateTime lastDetected) {
this.lastDetected = lastDetected;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", locale = "de-DE",
timezone = "Europe/Berlin")
public LocalDateTime getFirstDetected() {
return firstDetected;
}
public void setFirstDetected(LocalDateTime firstDetected) {
this.firstDetected = firstDetected;
}
public List<IncidentDto> getIncidentsOrNull() {
return incidentsOrNull;
}
public void setIncidentsOrNull(List<IncidentDto> incidentsOrNull) {
this.incidentsOrNull = incidentsOrNull;
}
public void addIncident(IncidentDto incidentDto) {
incidentsOrNull.add(incidentDto);
}
public Set<AgentDto> getDetectedOnAgentsOrNull() {
return detectedOnAgentsOrNull;
}
public void setDetectedOnAgentsOrNull(Set<AgentDto> detectedOnAgentsOrNull) {
this.detectedOnAgentsOrNull = detectedOnAgentsOrNull;
}
public VulnerabilityStatus getStatus() {
return status;
}
public void setStatus(VulnerabilityStatus status) {
this.status = status;
}
} |
3e1bef1d4775cef515d4308247a77c26c280d72a | 4,357 | java | Java | xchange-binance/src/main/java/org/knowm/xchange/binance/Binance.java | ZorgeR/XChange | 0ab945fb6c999c49ad8313656eb262863d0068d9 | [
"MIT"
] | 1 | 2021-04-04T20:39:54.000Z | 2021-04-04T20:39:54.000Z | xchange-binance/src/main/java/org/knowm/xchange/binance/Binance.java | ZorgeR/XChange | 0ab945fb6c999c49ad8313656eb262863d0068d9 | [
"MIT"
] | null | null | null | xchange-binance/src/main/java/org/knowm/xchange/binance/Binance.java | ZorgeR/XChange | 0ab945fb6c999c49ad8313656eb262863d0068d9 | [
"MIT"
] | null | null | null | 31.572464 | 116 | 0.714482 | 11,837 | package org.knowm.xchange.binance;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.binance.dto.BinanceException;
import org.knowm.xchange.binance.dto.marketdata.BinanceAggTrades;
import org.knowm.xchange.binance.dto.marketdata.BinanceOrderbook;
import org.knowm.xchange.binance.dto.marketdata.BinancePrice;
import org.knowm.xchange.binance.dto.marketdata.BinancePriceQuantity;
import org.knowm.xchange.binance.dto.marketdata.BinanceTicker24h;
import org.knowm.xchange.binance.dto.meta.BinanceTime;
import org.knowm.xchange.binance.dto.meta.exchangeinfo.BinanceExchangeInfo;
@Path("")
@Produces(MediaType.APPLICATION_JSON)
public interface Binance {
@GET
@Path("api/v1/ping")
/**
* Test connectivity to the Rest API.
* @return
* @throws IOException
*/
Object ping() throws IOException;
@GET
@Path("api/v1/time")
/**
* Test connectivity to the Rest API and get the current server time.
* @return
* @throws IOException
*/
BinanceTime time() throws IOException;
@GET
@Path("api/v1/exchangeInfo")
/**
* Current exchange trading rules and symbol information.
* @return
* @throws IOException
*/
BinanceExchangeInfo exchangeInfo() throws IOException;
@GET
@Path("api/v1/depth")
/**
*
* @param symbol
* @param limit optional, default 100; max 100.
* @return
* @throws IOException
* @throws BinanceException
*/
BinanceOrderbook depth(@QueryParam("symbol") String symbol, @QueryParam("limit") Integer limit)
throws IOException, BinanceException;
@GET
@Path("api/v1/aggTrades")
/**
* Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will
* have the quantity aggregated.<br/>
* If both startTime and endTime are sent, limit should not be sent AND the distance between startTime and endTime
* must be less than 24 hours.<br/>
* If frondId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.
* @param symbol
* @param fromId optional, ID to get aggregate trades from INCLUSIVE.
* @param startTime optional, Timestamp in ms to get aggregate trades from INCLUSIVE.
* @param endTime optional, Timestamp in ms to get aggregate trades until INCLUSIVE.
* @param limit optional, Default 500; max 500.
* @return
* @throws IOException
* @throws BinanceException
*/
List<BinanceAggTrades> aggTrades(@QueryParam("symbol") String symbol, @QueryParam("fromId") Long fromId
, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime
, @QueryParam("limit") Integer limit)
throws IOException, BinanceException;
@GET
@Path("api/v1/klines")
/**
* Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.<br/>
* If startTime and endTime are not sent, the most recent klines are returned.
* @param symbol
* @param interval
* @param limit optional, default 500; max 500.
* @param startTime optional
* @param endTime optional
* @return
* @throws IOException
* @throws BinanceException
*/
List<Object[]> klines(@QueryParam("symbol") String symbol, @QueryParam("interval") String interval
, @QueryParam("limit") Integer limit, @QueryParam("startTime") Long startTime
, @QueryParam("endTime") Long endTime)
throws IOException, BinanceException;
@GET
@Path("api/v1/ticker/24hr")
/**
* 24 hour price change statistics.
* @param symbol
* @return
* @throws IOException
* @throws BinanceException
*/
BinanceTicker24h ticker24h(@QueryParam("symbol") String symbol) throws IOException, BinanceException;
@GET
@Path("api/v1/ticker/allPrices")
/**
* Latest price for all symbols.
* @return
* @throws IOException
* @throws BinanceException
*/
List<BinancePrice> tickerAllPrices() throws IOException, BinanceException;
@GET
@Path("api/v1/ticker/allBookTickers")
/**
* Best price/qty on the order book for all symbols.
* @return
* @throws IOException
* @throws BinanceException
*/
List<BinancePriceQuantity> tickerAllBookTickers() throws IOException, BinanceException;
}
|
3e1befd0062fc732053f9aeadbb6ccdafc6ce4d1 | 1,027 | java | Java | platform/lang-api/src/com/intellij/navigation/GotoRelatedProvider.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | platform/lang-api/src/com/intellij/navigation/GotoRelatedProvider.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | platform/lang-api/src/com/intellij/navigation/GotoRelatedProvider.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | 34.233333 | 158 | 0.769231 | 11,838 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.navigation;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
/**
* Provides items for "Navigate -> Related Symbol" action.
* <p>
* If related items are represented as icons on the gutter use {@link com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider}
* to provide both line markers and 'goto related' targets
* <p>
* Use extension point `com.intellij.gotoRelatedProvider`.
*/
public abstract class GotoRelatedProvider {
@NotNull
public List<? extends GotoRelatedItem> getItems(@NotNull PsiElement psiElement) {
return Collections.emptyList();
}
@NotNull
public List<? extends GotoRelatedItem> getItems(@NotNull DataContext context) {
return Collections.emptyList();
}
}
|
3e1bf0c24da9ca9dfaee124ce1023d58d160c44c | 6,096 | java | Java | framework/base/src/main/java/org/apache/ofbiz/base/container/AdminServerContainer.java | lodhiravi/ofbiz-framework | 812aaae07cebe60f5721b55c0ac8c2eb0e59248a | [
"Apache-2.0"
] | 461 | 2017-03-14T06:34:40.000Z | 2022-03-23T08:21:26.000Z | framework/base/src/main/java/org/apache/ofbiz/base/container/AdminServerContainer.java | lodhiravi/ofbiz-framework | 812aaae07cebe60f5721b55c0ac8c2eb0e59248a | [
"Apache-2.0"
] | 476 | 2019-04-29T05:43:23.000Z | 2022-03-30T06:36:37.000Z | framework/base/src/main/java/org/apache/ofbiz/base/container/AdminServerContainer.java | lodhiravi/ofbiz-framework | 812aaae07cebe60f5721b55c0ac8c2eb0e59248a | [
"Apache-2.0"
] | 426 | 2017-04-06T11:40:34.000Z | 2022-03-31T21:16:14.000Z | 37.398773 | 136 | 0.632054 | 11,839 | /*******************************************************************************
* 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.ofbiz.base.container;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.ofbiz.base.start.Config;
import org.apache.ofbiz.base.start.Start;
import org.apache.ofbiz.base.start.Start.ServerState;
import org.apache.ofbiz.base.start.StartupCommand;
import org.apache.ofbiz.base.util.UtilValidate;
/**
* The AdminServer provides a way to communicate with a running
* OFBiz instance after it has started and send commands to that instance
* such as inquiring on server status or requesting system shutdown
*/
public final class AdminServerContainer implements Container {
/**
* Commands communicated between AdminClient and AdminServer
*/
public enum OfbizSocketCommand {
SHUTDOWN, STATUS, FAIL
}
private String name;
private Thread serverThread;
private ServerSocket serverSocket;
private Config cfg = Start.getInstance().getConfig();
@Override
public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException {
this.name = name;
try {
serverSocket = new ServerSocket(cfg.getAdminPort(), 1, cfg.getAdminAddress());
} catch (IOException e) {
String msg = "Couldn't create server socket(" + cfg.getAdminAddress() + ":" + cfg.getAdminPort() + ")";
throw new ContainerException(msg, e);
}
if (cfg.getAdminPort() > 0) {
serverThread = new Thread(this::run, "OFBiz-AdminServer");
} else {
serverThread = new Thread("OFBiz-AdminServer"); // Dummy thread
System.out.println("Admin socket not configured; set to port 0");
}
serverThread.setDaemon(false);
}
// Listens for administration commands.
private void run() {
System.out.println("Admin socket configured on - " + cfg.getAdminAddress() + ":" + cfg.getAdminPort());
while (!Thread.interrupted()) {
try (Socket client = serverSocket.accept()) {
System.out.println("Received connection from - " + client.getInetAddress() + " : " + client.getPort());
processClientRequest(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public boolean start() throws ContainerException {
serverThread.start();
return true;
}
@Override
public void stop() throws ContainerException {
if (serverThread.isAlive()) {
serverThread.interrupt();
}
}
@Override
public String getName() {
return name;
}
private void processClientRequest(Socket client) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), StandardCharsets.UTF_8), true)) {
// read client request and prepare response
String clientRequest = reader.readLine();
OfbizSocketCommand clientCommand = determineClientCommand(clientRequest);
String serverResponse = prepareResponseToClient(clientCommand);
// send response back to client
writer.println(serverResponse);
// if the client request is shutdown, execute shutdown sequence
if (clientCommand.equals(OfbizSocketCommand.SHUTDOWN)) {
writer.flush();
Start.getInstance().stop();
}
}
}
private OfbizSocketCommand determineClientCommand(String request) {
if (!isValidRequest(request)) {
return OfbizSocketCommand.FAIL;
}
return OfbizSocketCommand.valueOf(request.substring(request.indexOf(':') + 1));
}
/**
* Validates if request is a suitable String
* @param request
* @return boolean which shows if request is suitable
*/
private boolean isValidRequest(String request) {
return UtilValidate.isNotEmpty(request)
&& request.contains(":")
&& request.substring(0, request.indexOf(':')).equals(cfg.getAdminKey())
&& !request.substring(request.indexOf(':') + 1).isEmpty();
}
private static String prepareResponseToClient(OfbizSocketCommand control) {
String response = null;
ServerState state = Start.getInstance().getCurrentState();
switch (control) {
case SHUTDOWN:
if (state == ServerState.STOPPING) {
response = "IN-PROGRESS";
} else {
response = "OK";
}
break;
case STATUS:
response = state.toString();
break;
case FAIL:
response = "FAIL";
break;
}
return response;
}
}
|
3e1bf1bad6c5d0dcafb99b8203a9c9f71321baca | 2,884 | java | Java | backend/src/test/java/br/com/cartola/metrics/AtletasTest.java | samfrezza/cartola-metrics | 4b6b8c9fa3ea654145f7d984a0e83341e330c0ca | [
"Apache-2.0"
] | null | null | null | backend/src/test/java/br/com/cartola/metrics/AtletasTest.java | samfrezza/cartola-metrics | 4b6b8c9fa3ea654145f7d984a0e83341e330c0ca | [
"Apache-2.0"
] | null | null | null | backend/src/test/java/br/com/cartola/metrics/AtletasTest.java | samfrezza/cartola-metrics | 4b6b8c9fa3ea654145f7d984a0e83341e330c0ca | [
"Apache-2.0"
] | null | null | null | 34.333333 | 94 | 0.686893 | 11,840 | package br.com.cartola.metrics;
import br.com.cartola.metrics.model.Atleta;
import br.com.cartola.metrics.model.Rodada;
import br.com.cartola.metrics.model.cartola.AtletasResponse;
import br.com.cartola.metrics.model.cartola.PartidasResponse;
import br.com.cartola.metrics.repository.RodadaRepository;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
@RunWith(SpringRunner.class)
@SpringBootTest
@Ignore
public class AtletasTest {
@Autowired
private RodadaRepository rodadaRepo;
@Test
public void insertRodada() throws IOException {
Path dir = Paths.get("src", "main", "resources", "atletas");
for (int i = 2; i <= 10; i++) {
File arquivo = new File(dir.toString() + "/atletas-rodada-" + i + ".json");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
AtletasResponse atletaResponse = mapper.readValue(arquivo, AtletasResponse.class);
PartidasResponse partidaResponse = new RestTemplate()
.getForObject("https://api.cartolafc.globo.com/partidas/" + i,
PartidasResponse.class);
Rodada rodada = new Rodada();
rodada.setAtletas(atletaResponse.getAtletas());
rodada.setPartidas(partidaResponse.getPartidas());
rodada.setId(i);
rodadaRepo.save(rodada);
}
}
@Test
public void insertPrimeiraRodada() throws IOException {
Path dir = Paths.get("src", "main", "resources", "atletas");
File arquivo = new File(dir.toString() + "/atletas-rodada-1.json");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
AtletasResponse atletaResponse = mapper.readValue(arquivo, AtletasResponse.class);
PartidasResponse partidaResponse = new RestTemplate()
.getForObject("https://api.cartolafc.globo.com/partidas/1",
PartidasResponse.class);
for (Atleta a : atletaResponse.getAtletas()) {
a.setPontos_num(a.getMedia_num());
}
Rodada rodada = new Rodada();
rodada.setAtletas(atletaResponse.getAtletas());
rodada.setPartidas(partidaResponse.getPartidas());
rodada.setId(1);
rodadaRepo.save(rodada);
}
}
|
3e1bf1f8957933f94ca2d0d2d73ec89be6658f36 | 1,825 | java | Java | ZimbraSoap/src/java/com/zimbra/soap/base/PartInfoInterface.java | fciubotaru/z-pec | 82335600341c6fb1bb8a471fd751243a90bc4d57 | [
"MIT"
] | 5 | 2019-03-26T07:51:56.000Z | 2021-08-30T07:26:05.000Z | ZimbraSoap/src/java/com/zimbra/soap/base/PartInfoInterface.java | fciubotaru/z-pec | 82335600341c6fb1bb8a471fd751243a90bc4d57 | [
"MIT"
] | 1 | 2015-08-18T19:03:32.000Z | 2015-08-18T19:03:32.000Z | ZimbraSoap/src/java/com/zimbra/soap/base/PartInfoInterface.java | fciubotaru/z-pec | 82335600341c6fb1bb8a471fd751243a90bc4d57 | [
"MIT"
] | 13 | 2015-03-11T00:26:35.000Z | 2020-07-26T16:25:18.000Z | 37.244898 | 77 | 0.750685 | 11,841 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.soap.base;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlAccessorType(XmlAccessType.NONE)
public interface PartInfoInterface {
public PartInfoInterface createFromPartAndContentType(String part,
String contentType);
public void setSize(Integer size);
public void setContentDisposition(String contentDisposition);
public void setContentFilename(String contentFilename);
public void setContentId(String contentId);
public void setLocation(String location);
public void setBody(Boolean body);
public void setTruncatedContent(Boolean truncatedContent);
public void setContent(String content);
public String getPart();
public String getContentType();
public Integer getSize();
public String getContentDisposition();
public String getContentFilename();
public String getContentId();
public String getLocation();
public Boolean getBody();
public Boolean getTruncatedContent();
public String getContent();
public void setMimePartInterfaces(Iterable<PartInfoInterface> mimeParts);
public void addMimePartInterface(PartInfoInterface mimePart);
public List<PartInfoInterface> getMimePartInterfaces();
}
|
3e1bf2034fa8550f6896c86c7a948cdba6713bd3 | 3,471 | java | Java | src/game/PakConfiguration.java | Kiritsu/pakMan | bfc2673964f71f9a5777c77afdca874aed3b6c8f | [
"MIT"
] | null | null | null | src/game/PakConfiguration.java | Kiritsu/pakMan | bfc2673964f71f9a5777c77afdca874aed3b6c8f | [
"MIT"
] | 1 | 2018-12-11T23:07:41.000Z | 2018-12-11T23:07:41.000Z | src/game/PakConfiguration.java | Kiritsu/pakMan | bfc2673964f71f9a5777c77afdca874aed3b6c8f | [
"MIT"
] | null | null | null | 19.721591 | 80 | 0.624604 | 11,842 | package game;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
public class PakConfiguration {
private HashMap<String, HashMap<String, String>> rawFile;
private HashMap<String, String> texts;
private Keys keys;
private int level;
public PakConfiguration() {
texts = new HashMap<String, String>();
rawFile = new HashMap<String, HashMap<String, String>>();
keys = new Keys();
}
/**
* Parses the configuration and update the different class attributes.
* @param path
* @throws Exception
*/
public void parseAll(String path) throws Exception {
boolean block = parseTexts(path);
if (!block) {
throw new Exception("Erreur during parse.");
}
applyKeys();
applyTexts();
applyLevel();
}
/**
* Parses our ini configuration file.
* @param path of the configuration file.
*/
public boolean parseTexts(String path) {
try {
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
String element = "";
while ((st = br.readLine()) != null) {
System.out.println(st);
if (st.startsWith("[") && st.endsWith("]")) {
element = st.replace("[", "").replace("]", "");
continue;
}
if (element.equals("")) {
continue;
}
rawFile.putIfAbsent(element, new HashMap<String, String>());
String[] kvp = st.split("\\=");
if (kvp.length != 2) {
continue;
}
rawFile.get(element).putIfAbsent(kvp[0], kvp[1]);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Updates our Keys class with the keys from the configuration.
*/
public void applyKeys() {
HashMap<String, String> keys = rawFile.get("KEYS");
this.keys.setStart(keys.get("start").charAt(0));
this.keys.setLeft(keys.get("left").charAt(0));
this.keys.setRight(keys.get("right").charAt(0));
this.keys.setUp(keys.get("up").charAt(0));
this.keys.setDown(keys.get("down").charAt(0));
}
/**
* Updates our texts attribute with the TEXTS values of our configuration file.
*/
public void applyTexts() {
texts = rawFile.get("TEXTS");
}
/**
* Sets the level on which we must start.
*/
public void applyLevel() {
HashMap<String, String> levelConfig = rawFile.get("GAME_CONFIG");
this.level = Integer.valueOf(levelConfig.get("level"));
}
public int getLevel() {
return this.level;
}
public Keys getKeys() {
return this.keys;
}
/**
* Returns a string associated with the given key.
*/
public String getTextByKey(String key) {
return texts.get(key);
}
public class Keys {
private char start;
private char left;
private char right;
private char up;
private char down;
public Keys() {
this.start = ' ';
this.left = 'q';
this.right = 'd';
this.up = 'z';
this.down = 'd';
}
public char getStart() {
return start;
}
public void setStart(char start) {
this.start = start;
}
public char getLeft() {
return left;
}
public void setLeft(char left) {
this.left = left;
}
public char getRight() {
return right;
}
public void setRight(char right) {
this.right = right;
}
public char getUp() {
return up;
}
public void setUp(char up) {
this.up = up;
}
public char getDown() {
return down;
}
public void setDown(char down) {
this.down = down;
}
}
}
|
3e1bf225b5b269f5ebd3db5794d13fc10a39947c | 1,984 | java | Java | src/main/java/com/suqizhao/questionStore/mapper/QuestionAnswserMapper.java | SuQiZhao/question-store-server | 5c8aeb1462e9307315959cbddd436b6f8a7f6c4c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/suqizhao/questionStore/mapper/QuestionAnswserMapper.java | SuQiZhao/question-store-server | 5c8aeb1462e9307315959cbddd436b6f8a7f6c4c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/suqizhao/questionStore/mapper/QuestionAnswserMapper.java | SuQiZhao/question-store-server | 5c8aeb1462e9307315959cbddd436b6f8a7f6c4c | [
"Apache-2.0"
] | null | null | null | 32.52459 | 154 | 0.60131 | 11,843 | package com.suqizhao.questionStore.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.suqizhao.questionStore.entity.QuestionAnswser;
import com.suqizhao.framework.pagination.Paging;
import com.suqizhao.questionStore.param.QuestionAnswserPageParam;
import com.suqizhao.questionStore.vo.QuestionAnswserQueryVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.util.Date;
/**
* <pre>
* Mapper 接口
* </pre>
*
* @author sqizhao
* @since 2020-04-26
*/
@Repository
public interface QuestionAnswserMapper extends BaseMapper<QuestionAnswser> {
/**
* 根据ID获取查询对象
*
* @param id
* @return
*/
QuestionAnswserQueryVo getQuestionAnswserById(Serializable id);
/**
* 获取分页对象
*
* @param page
* @param questionAnswserPageParam
* @return
*/
IPage<QuestionAnswserQueryVo> getQuestionAnswserPageList(@Param("page") Page page, @Param("param") QuestionAnswserPageParam questionAnswserPageParam);
/**
*
* @param page
* @param questionId
* @param userId
* @param isBest
* @return
*/
Page<QuestionAnswserQueryVo> findAnswserPage(@Param("page") Page page,
@Param("questionId") String questionId,
@Param("userId") String userId,
@Param("isBest") String isBest,
@Param("questionTitle") String questionTitle,
@Param("content") String content,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
}
|
3e1bf2399fb3cccb7e6d7d1203a787e311df023c | 1,816 | java | Java | javalite-common/src/main/java/org/javalite/validation/length/AttributeLengthValidator.java | erdoganforesight/javalite | 6db3f8eed04a05541bbc1b45868e39fc5f4e0b8a | [
"Apache-2.0"
] | 631 | 2015-01-01T08:09:04.000Z | 2019-09-19T10:37:47.000Z | javalite-common/src/main/java/org/javalite/validation/length/AttributeLengthValidator.java | erdoganforesight/javalite | 6db3f8eed04a05541bbc1b45868e39fc5f4e0b8a | [
"Apache-2.0"
] | 537 | 2015-01-01T00:30:31.000Z | 2019-09-20T16:29:31.000Z | javalite-common/src/main/java/org/javalite/validation/length/AttributeLengthValidator.java | erdoganforesight/javalite | 6db3f8eed04a05541bbc1b45868e39fc5f4e0b8a | [
"Apache-2.0"
] | 197 | 2015-01-04T12:31:20.000Z | 2019-08-20T13:18:29.000Z | 28.375 | 85 | 0.664097 | 11,844 | package org.javalite.validation.length;
import org.javalite.validation.Validatable;
import org.javalite.validation.ValidatorAdapter;
import java.util.Locale;
/**
* Attribute length validator.
*/
public class AttributeLengthValidator extends ValidatorAdapter {
private final String attributeName;
private LengthOption lengthOption;
private boolean allowBlank;
private AttributeLengthValidator(String attributeName) {
this.attributeName = attributeName;
}
public static AttributeLengthValidator on(String attribute) {
return new AttributeLengthValidator(attribute);
}
public void validate(Validatable m) {
Object value = m.get(this.attributeName);
if(allowBlank && (null == value || "".equals(value))) {
return;
}
if(null == value) {
m.addFailedValidator(this, this.attributeName);
return;
}
if(!(value instanceof String)) {
throw new IllegalArgumentException("Attribute must be a String");
} else {
if(!this.lengthOption.validate((String) m.get(this.attributeName))) {
//somewhat confusingly this adds an error for a validator.
m.addFailedValidator(this, this.attributeName);
}
}
}
public AttributeLengthValidator with(LengthOption lengthOption) {
this.lengthOption = lengthOption;
this.setMessage(lengthOption.getParametrizedMessage());
return this;
}
public AttributeLengthValidator allowBlank(boolean allowBlank) {
this.allowBlank = allowBlank;
return this;
}
public String formatMessage(Locale locale, Object... params) {
return super.formatMessage(locale, this.lengthOption.getMessageParameters());
}
}
|
3e1bf23fe86574aeb557d21931efcd9976e3e40c | 23,095 | java | Java | jodd-json/src/main/java/jodd/json/JsonParser.java | nicky-chen/jodd | 4bba7643c564a5a3fb54397208666b9f82a0446d | [
"BSD-2-Clause"
] | 1 | 2018-03-16T13:00:59.000Z | 2018-03-16T13:00:59.000Z | jodd-json/src/main/java/jodd/json/JsonParser.java | nicky-chen/jodd | 4bba7643c564a5a3fb54397208666b9f82a0446d | [
"BSD-2-Clause"
] | null | null | null | jodd-json/src/main/java/jodd/json/JsonParser.java | nicky-chen/jodd | 4bba7643c564a5a3fb54397208666b9f82a0446d | [
"BSD-2-Clause"
] | null | null | null | 21.584112 | 93 | 0.612297 | 11,845 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.json;
import jodd.introspector.ClassDescriptor;
import jodd.introspector.ClassIntrospector;
import jodd.introspector.PropertyDescriptor;
import jodd.json.meta.JsonAnnotationManager;
import jodd.util.CharArraySequence;
import jodd.util.CharUtil;
import jodd.util.StringPool;
import java.math.BigInteger;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static jodd.json.JoddJsonDefaults.DEFAULT_CLASS_METADATA_NAME;
/**
* Simple, developer-friendly JSON parser. It focuses on easy usage
* and type mappings. Uses Jodd's type converters, so it is natural
* companion for Jodd projects.
* <p>
* See: http://www.ietf.org/rfc/rfc4627.txt
*/
public class JsonParser extends JsonParserBase {
/**
* Static ctor.
*/
public static JsonParser create() {
return new JsonParser();
}
private static final char[] T_RUE = new char[] {'r', 'u', 'e'};
private static final char[] F_ALSE = new char[] {'a', 'l', 's', 'e'};
private static final char[] N_ULL = new char[] {'u', 'l', 'l'};
/**
* Map keys.
*/
public static final String KEYS = "keys";
/**
* Array or map values.
*/
public static final String VALUES = "values";
protected int ndx = 0;
protected CharSequence input;
protected int total;
protected Path path;
protected boolean useAltPaths = JoddJson.get().defaults().isUseAltPathsByParser();
protected Class rootType;
protected MapToBean mapToBean;
protected boolean looseMode;
public JsonParser() {
text = new char[512];
}
/**
* Resets JSON parser, so it can be reused.
*/
protected void reset() {
this.ndx = 0;
this.textLen = 0;
this.path = new Path();
if (useAltPaths) {
path.altPath = new Path();
}
if (classMetadataName != null) {
mapToBean = createMapToBean(classMetadataName);
}
}
/**
* Enables usage of additional paths.
*/
public JsonParser useAltPaths() {
this.useAltPaths = true;
return this;
}
/**
* Enables 'loose' mode for parsing. When 'loose' mode is enabled,
* JSON parsers swallows also invalid JSONs:
* <ul>
* <li>invalid escape character sequence is simply added to the output</li>
* <li>strings can be quoted with single-quotes</li>
* <li>strings can be unquoted, but may not contain escapes</li>
* </ul>
*/
public JsonParser looseMode(boolean looseMode) {
this.looseMode = looseMode;
return this;
}
// ---------------------------------------------------------------- mappings
protected Map<Path, Class> mappings;
/**
* Maps a class to JSONs root.
*/
public JsonParser map(Class target) {
rootType = target;
return this;
}
/**
* Maps a class to given path. For arrays, append <code>values</code>
* to the path to specify component type (if not specified by
* generics).
*/
public JsonParser map(String path, Class target) {
if (path == null) {
rootType = target;
return this;
}
if (mappings == null) {
mappings = new HashMap<>();
}
mappings.put(Path.parse(path), target);
return this;
}
/**
* Replaces type with mapped type for current path.
*/
protected Class replaceWithMappedTypeForPath(Class target) {
if (mappings == null) {
return target;
}
Class newType;
// first try alt paths
Path altPath = path.getAltPath();
if (altPath != null) {
if (!altPath.equals(path)) {
newType = mappings.get(altPath);
if (newType != null) {
return newType;
}
}
}
// now check regular paths
newType = mappings.get(path);
if (newType != null) {
return newType;
}
return target;
}
// ---------------------------------------------------------------- converters
protected Map<Path, ValueConverter> convs;
/**
* Defines {@link jodd.json.ValueConverter} to use on given path.
*/
public JsonParser withValueConverter(String path, ValueConverter valueConverter) {
if (convs == null) {
convs = new HashMap<>();
}
convs.put(Path.parse(path), valueConverter);
return this;
}
/**
* Lookups for value converter for current path.
*/
protected ValueConverter lookupValueConverter() {
if (convs == null) {
return null;
}
return convs.get(path);
}
// ---------------------------------------------------------------- class meta data name
protected String classMetadataName = JoddJson.get().defaults().getClassMetadataName();
/**
* Sets local class meta-data name.
*/
public JsonParser setClassMetadataName(String name) {
classMetadataName = name;
return this;
}
public JsonParser withClassMetadata(boolean useMetadata) {
if (useMetadata) {
classMetadataName = DEFAULT_CLASS_METADATA_NAME;
}
else {
classMetadataName = null;
}
return this;
}
// ---------------------------------------------------------------- parse
/**
* Parses input JSON as given type.
*/
@SuppressWarnings("unchecked")
public <T> T parse(String input, Class<T> targetType) {
rootType = targetType;
return _parse(input);
}
/**
* Parses input JSON to {@link JsonObject}, special case of {@link #parse(String, Class)}.
*/
public JsonObject parseAsJsonObject(String input) {
return new JsonObject(parse(input));
}
/**
* Parses input JSON to {@link JsonArray}, special case of parsing.
*/
public JsonArray parseAsJsonArray(String input) {
return new JsonArray(parse(input));
}
/**
* Parses input JSON to a list with specified component type.
*/
public <T> List<T> parseAsList(String string, Class<T> componentType) {
return new JsonParser()
.map(JsonParser.VALUES, componentType)
.parse(string);
}
/**
* Parses input JSON to a list with specified key and value types.
*/
public <K, V> Map<K, V> parseAsMap(
String string, Class<K> keyType, Class<V> valueType) {
return new JsonParser()
.map(JsonParser.KEYS, keyType)
.map(JsonParser.VALUES, valueType)
.parse(string);
}
/**
* Parses input JSON string.
*/
public <T> T parse(String input) {
return _parse(input);
}
/**
* Parses input JSON as given type.
*/
@SuppressWarnings("unchecked")
public <T> T parse(char[] input, Class<T> targetType) {
rootType = targetType;
return _parse(CharArraySequence.of(input));
}
/**
* Parses input JSON char array.
*/
public <T> T parse(char[] input) {
return _parse(CharArraySequence.of(input));
}
private <T> T _parse(CharSequence input) {
this.input = input;
this.total = input.length();
reset();
skipWhiteSpaces();
Object value;
try {
value = parseValue(rootType, null, null);
}
catch (IndexOutOfBoundsException iofbex) {
syntaxError("End of JSON");
return null;
}
skipWhiteSpaces();
if (ndx != total) {
syntaxError("Trailing chars");
return null;
}
// convert map to target type
if (classMetadataName != null && rootType == null) {
if (value instanceof Map) {
Map map = (Map) value;
value = mapToBean.map2bean(map, null);
}
}
return (T) value;
}
// ---------------------------------------------------------------- parser
/**
* Parses a JSON value.
* @param targetType target type to convert, may be <code>null</code>
* @param componentType component type for maps and arrays, may be <code>null</code>
*/
protected Object parseValue(Class targetType, Class keyType, Class componentType) {
ValueConverter valueConverter;
char c = input.charAt(ndx);
switch (c) {
case '\'':
if (!looseMode) {
break;
}
case '"':
ndx++;
Object string = parseStringContent(c);
valueConverter = lookupValueConverter();
if (valueConverter != null) {
return valueConverter.convert(string);
}
if (targetType != null && targetType != String.class) {
string = convertType(string, targetType);
}
return string;
case '{':
ndx++;
return parseObjectContent(targetType, keyType, componentType);
case '[':
ndx++;
return parseArrayContent(targetType, componentType);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
Object number = parseNumber();
valueConverter = lookupValueConverter();
if (valueConverter != null) {
return valueConverter.convert(number);
}
if (targetType != null) {
number = convertType(number, targetType);
}
return number;
case 'n':
ndx++;
if (match(N_ULL)) {
valueConverter = lookupValueConverter();
if (valueConverter != null) {
return valueConverter.convert(null);
}
return null;
}
break;
case 't':
ndx++;
if (match(T_RUE)) {
Object value = Boolean.TRUE;
valueConverter = lookupValueConverter();
if (valueConverter != null) {
return valueConverter.convert(value);
}
if (targetType != null) {
value = convertType(value, targetType);
}
return value;
}
break;
case 'f':
ndx++;
if (match(F_ALSE)) {
Object value = Boolean.FALSE;
valueConverter = lookupValueConverter();
if (valueConverter != null) {
return valueConverter.convert(value);
}
if (targetType != null) {
value = convertType(value, targetType);
}
return value;
}
break;
}
if (looseMode) {
// try to parse unquoted string
Object string = parseUnquotedStringContent();
valueConverter = lookupValueConverter();
if (valueConverter != null) {
return valueConverter.convert(string);
}
if (targetType != null && targetType != String.class) {
string = convertType(string, targetType);
}
return string;
}
syntaxError("Invalid char: " + input.charAt(ndx));
return null;
}
// ---------------------------------------------------------------- string
protected char[] text;
protected int textLen;
/**
* Parses a string.
*/
protected String parseString() {
char quote = '\"';
if (looseMode) {
quote = consumeOneOf('\"', '\'');
if (quote == 0) {
return parseUnquotedStringContent();
}
} else {
consume(quote);
}
return parseStringContent(quote);
}
/**
* Parses string content, once when starting quote has been consumer.
*/
protected String parseStringContent(final char quote) {
int startNdx = ndx;
// roll-out until the end of the string or the escape char
while (true) {
char c = input.charAt(ndx);
if (c == quote) {
// no escapes found, just use existing string
ndx++;
return input.subSequence(startNdx, ndx - 1).toString();
}
if (c == '\\') {
break;
}
ndx++;
}
// escapes found, proceed differently
textLen = ndx - startNdx;
growEmpty();
for (int i = startNdx, j = 0; j < textLen; i++, j++) {
text[j] = input.charAt(i);
}
//System.arraycopy(input, startNdx, text, 0, textLen);
// escape char, process everything until the end
while (true) {
char c = input.charAt(ndx);
if (c == quote) {
// done
ndx++;
final String str = new String(text, 0, textLen);
textLen = 0;
return str;
}
if (c == '\\') {
// escape char found
ndx++;
c = input.charAt(ndx);
switch (c) {
case '\"' : c = '\"'; break;
case '\\' : c = '\\'; break;
case '/' : c = '/'; break;
case 'b' : c = '\b'; break;
case 'f' : c = '\f'; break;
case 'n' : c = '\n'; break;
case 'r' : c = '\r'; break;
case 't' : c = '\t'; break;
case 'u' :
ndx++;
c = parseUnicode();
break;
default:
if (looseMode) {
if (c != '\'') {
c = '\\';
ndx--;
}
}
else {
syntaxError("Invalid escape char: " + c);
}
}
}
text[textLen] = c;
textLen++;
growAndCopy();
ndx++;
}
}
/**
* Grows empty text array.
*/
protected void growEmpty() {
if (textLen >= text.length) {
int newSize = textLen << 1;
text = new char[newSize];
}
}
/**
* Grows text array when {@code text.length == textLen}.
*/
protected void growAndCopy() {
if (textLen == text.length) {
int newSize = text.length << 1;
char[] newText = new char[newSize];
if (textLen > 0) {
System.arraycopy(text, 0, newText, 0, textLen);
}
text = newText;
}
}
/**
* Parses 4 characters and returns unicode character.
*/
protected char parseUnicode() {
int i0 = CharUtil.hex2int(input.charAt(ndx++));
int i1 = CharUtil.hex2int(input.charAt(ndx++));
int i2 = CharUtil.hex2int(input.charAt(ndx++));
int i3 = CharUtil.hex2int(input.charAt(ndx));
return (char) ((i0 << 12) + (i1 << 8) + (i2 << 4) + i3);
}
// ---------------------------------------------------------------- un-quoted
private final static char[] UNQOUTED_DELIMETERS = ",:[]{}\\\"'".toCharArray();
/**
* Parses un-quoted string content.
*/
protected String parseUnquotedStringContent() {
int startNdx = ndx;
while (true) {
char c = input.charAt(ndx);
if (c <= ' ' || CharUtil.equalsOne(c, UNQOUTED_DELIMETERS)) {
int currentNdx = ndx;
// done
skipWhiteSpaces();
return input.subSequence(startNdx, currentNdx).toString();
}
ndx++;
}
}
// ---------------------------------------------------------------- number
/**
* Parses JSON numbers.
*/
protected Number parseNumber() {
int startIndex = ndx;
char c = input.charAt(ndx);
boolean isDouble = false;
boolean isExp = false;
if (c == '-') {
ndx++;
}
while (true) {
if (isEOF()) {
break;
}
c = input.charAt(ndx);
if (c >= '0' && c <= '9') {
ndx++;
continue;
}
if (c <= 32) { // white space
break;
}
if (c == ',' || c == '}' || c == ']') { // delimiter
break;
}
if (c == '.') {
isDouble = true;
}
else if (c == 'e' || c == 'E') {
isExp = true;
}
ndx++;
}
final String value = input.subSequence(startIndex, ndx).toString();
if (isDouble) {
return Double.valueOf(value);
}
long longNumber;
if (isExp) {
longNumber = Double.valueOf(value).longValue();
}
else {
if (value.length() >= 19) {
// if string is 19 chars and longer, it can be over the limit
BigInteger bigInteger = new BigInteger(value);
if (isGreaterThenLong(bigInteger)) {
return bigInteger;
}
longNumber = bigInteger.longValue();
}
else {
longNumber = Long.parseLong(value);
}
}
if ((longNumber >= Integer.MIN_VALUE) && (longNumber <= Integer.MAX_VALUE)) {
return Integer.valueOf((int) longNumber);
}
return Long.valueOf(longNumber);
}
private static boolean isGreaterThenLong(BigInteger bigInteger) {
if (bigInteger.compareTo(MAX_LONG) > 0) {
return true;
}
if (bigInteger.compareTo(MIN_LONG) < 0) {
return true;
}
return false;
}
private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
// ---------------------------------------------------------------- array
/**
* Parses arrays, once when open bracket has been consumed.
*/
protected Object parseArrayContent(Class targetType, Class componentType) {
// detect special case
if (targetType == Object.class) {
targetType = List.class;
}
// continue
targetType = replaceWithMappedTypeForPath(targetType);
if (componentType == null && targetType != null && targetType.isArray()) {
componentType = targetType.getComponentType();
}
path.push(VALUES);
componentType = replaceWithMappedTypeForPath(componentType);
Collection<Object> target = newArrayInstance(targetType);
boolean koma = false;
mainloop:
while (true) {
skipWhiteSpaces();
char c = input.charAt(ndx);
if (c == ']') {
if (koma) {
syntaxError("Trailing comma");
}
ndx++;
path.pop();
return target;
}
Object value = parseValue(componentType, null, null);
target.add(value);
skipWhiteSpaces();
c = input.charAt(ndx);
switch (c) {
case ']': ndx++; break mainloop;
case ',': ndx++; koma = true; break;
default: syntaxError("Invalid char: expected ] or ,");
}
}
path.pop();
if (targetType != null) {
return convertType(target, targetType);
}
return target;
}
// ---------------------------------------------------------------- object
/**
* Parses object, once when open bracket has been consumed.
*/
protected Object parseObjectContent(Class targetType, Class valueKeyType, Class valueType) {
// detect special case
if (targetType == Object.class) {
targetType = Map.class;
}
// continue
targetType = replaceWithMappedTypeForPath(targetType);
Object target;
boolean isTargetTypeMap = true;
boolean isTargetRealTypeMap = true;
ClassDescriptor targetTypeClassDescriptor = null;
JsonAnnotationManager.TypeData typeData = null;
if (targetType != null) {
targetTypeClassDescriptor = ClassIntrospector.get().lookup(targetType);
// find if the target is really a map
// because when classMetadataName != null we are forcing
// map usage locally in this method
isTargetRealTypeMap = targetTypeClassDescriptor.isMap();
typeData = JsonAnnotationManager.get().lookupTypeData(targetType);
}
if (isTargetRealTypeMap) {
// resolve keys only for real maps
path.push(KEYS);
valueKeyType = replaceWithMappedTypeForPath(valueKeyType);
path.pop();
}
if (classMetadataName == null) {
// create instance of target type, no 'class' information
target = newObjectInstance(targetType);
isTargetTypeMap = isTargetRealTypeMap;
} else {
// all beans will be created first as a map
target = new HashMap();
}
boolean koma = false;
mainloop:
while (true) {
skipWhiteSpaces();
char c = input.charAt(ndx);
if (c == '}') {
if (koma) {
syntaxError("Trailing comma");
}
ndx++;
break;
}
koma = false;
String key = parseString();
String keyOriginal = key;
skipWhiteSpaces();
consume(':');
skipWhiteSpaces();
// read the type of the simple property
PropertyDescriptor pd = null;
Class propertyType = null;
Class keyType = null;
Class componentType = null;
// resolve simple property
if (!isTargetRealTypeMap) {
// replace key with real property value
key = JsonAnnotationManager.get().resolveRealName(targetType, key);
}
if (!isTargetTypeMap) {
pd = targetTypeClassDescriptor.getPropertyDescriptor(key, true);
if (pd != null) {
propertyType = pd.getType();
keyType = pd.resolveKeyType(true);
componentType = pd.resolveComponentType(true);
}
}
Object value;
if (!isTargetTypeMap) {
// *** inject into bean
path.push(key);
value = parseValue(propertyType, keyType, componentType);
path.pop();
if (typeData.rules.match(keyOriginal, !typeData.strict)) {
if (pd != null) {
// only inject values if target property exist
injectValueIntoObject(target, pd, value);
}
}
}
else {
Object keyValue = key;
if (valueKeyType != null) {
keyValue = convertType(key, valueKeyType);
}
// *** add to map
if (isTargetRealTypeMap) {
path.push(VALUES, key);
valueType = replaceWithMappedTypeForPath(valueType);
} else {
path.push(key);
}
value = parseValue(valueType, null, null);
path.pop();
((Map) target).put(keyValue, value);
}
skipWhiteSpaces();
c = input.charAt(ndx);
switch (c) {
case '}': ndx++; break mainloop;
case ',': ndx++; koma = true; break;
default: syntaxError("Invalid char: expected } or ,");
}
}
// done
// convert Map to target type
if (classMetadataName != null) {
target = mapToBean.map2bean((Map) target, targetType);
}
return target;
}
// ---------------------------------------------------------------- scanning tools
/**
* Consumes char at current position. If char is different, throws the exception.
*/
protected void consume(char c) {
if (input.charAt(ndx) != c) {
syntaxError("Invalid char: expected " + c);
}
ndx++;
}
/**
* Consumes one of the allowed char at current position.
* If char is different, return <code>0</code>.
* If matched, returns matched char.
*/
protected char consumeOneOf(char c1, char c2) {
char c = input.charAt(ndx);
if ((c != c1) && (c != c2)) {
return 0;
}
ndx++;
return c;
}
/**
* Returns <code>true</code> if scanning is at the end.
*/
protected boolean isEOF() {
return ndx >= total;
}
/**
* Skips whitespaces. For the simplification, whitespaces are
* considered any characters less or equal to 32 (space).
*/
protected final void skipWhiteSpaces() {
while (true) {
if (isEOF()) {
return;
}
if (input.charAt(ndx) > 32) {
return;
}
ndx++;
}
}
/**
* Matches char buffer with content on given location.
*/
protected final boolean match(char[] target) {
for (char c : target) {
if (input.charAt(ndx) != c) {
return false;
}
ndx++;
}
return true;
}
// ---------------------------------------------------------------- error
/**
* Throws {@link jodd.json.JsonException} indicating a syntax error.
*/
protected void syntaxError(String message) {
String left = "...";
String right = "...";
int offset = 10;
int from = ndx - offset;
if (from < 0) {
from = 0;
left = StringPool.EMPTY;
}
int to = ndx + offset;
if (to > input.length()) {
to = input.length();
right = StringPool.EMPTY;
}
CharSequence str = input.subSequence(from, to);
throw new JsonException(
"Syntax error! " + message + "\n" +
"offset: " + ndx + " near: \"" + left + str + right + "\"");
}
} |
3e1bf285a85cc5d0e878625ebcb104b6e609c20a | 642 | java | Java | src/main/java/team/stiff/pomelo/handler/ListenerPriority.java | EBSmash/CousinWare1.12.2Updated-master-main | f0eee6d7dc841f036da1b71adcd96379799f9a06 | [
"MIT"
] | 22 | 2021-01-10T20:58:45.000Z | 2021-12-19T18:11:35.000Z | src/main/java/team/stiff/pomelo/handler/ListenerPriority.java | EBSmash/CousinWare1.12.2Updated-master-main | f0eee6d7dc841f036da1b71adcd96379799f9a06 | [
"MIT"
] | 4 | 2021-12-23T02:26:17.000Z | 2021-12-23T03:11:49.000Z | src/main/java/team/stiff/pomelo/handler/ListenerPriority.java | EBSmash/CousinWare1.12.2Updated-master-main | f0eee6d7dc841f036da1b71adcd96379799f9a06 | [
"MIT"
] | 5 | 2021-12-23T02:25:52.000Z | 2021-12-24T10:08:15.000Z | 22.137931 | 79 | 0.674455 | 11,846 | package team.stiff.pomelo.handler;
/**
* Designates the order within a listener of event distribution. This
* is not globally sorted as the current structure of stored event listeners is
* too complex to properly sort without major code refactoring.
*
* todo: hint hint...
*/
public enum ListenerPriority {
LOWEST(-750),
LOWER(-500),
LOW(-250),
NORMAL(0),
HIGH(250),
HIGHER(500),
HIGHEST(750);
private final int priorityLevel;
ListenerPriority(final int priorityLevel) {
this.priorityLevel = priorityLevel;
}
public int getPriorityLevel() {
return priorityLevel;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.