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
sequence
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
sequence
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
sequence
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
3e00001c6884b6b2f9d926ffac9335875da9b56b
2,387
java
Java
src/main/java/org/bian/dto/BQInstructionRetrieveOutputModelCardFinancialSettlementProcedureInstanceRecord.java
bianapis/sd-card-financial-settlement-v2.0
471652dcb2731cd10ccc07874ff8ac6afb838a96
[ "Apache-2.0" ]
null
null
null
src/main/java/org/bian/dto/BQInstructionRetrieveOutputModelCardFinancialSettlementProcedureInstanceRecord.java
bianapis/sd-card-financial-settlement-v2.0
471652dcb2731cd10ccc07874ff8ac6afb838a96
[ "Apache-2.0" ]
null
null
null
src/main/java/org/bian/dto/BQInstructionRetrieveOutputModelCardFinancialSettlementProcedureInstanceRecord.java
bianapis/sd-card-financial-settlement-v2.0
471652dcb2731cd10ccc07874ff8ac6afb838a96
[ "Apache-2.0" ]
null
null
null
36.723077
258
0.818182
0
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * BQInstructionRetrieveOutputModelCardFinancialSettlementProcedureInstanceRecord */ public class BQInstructionRetrieveOutputModelCardFinancialSettlementProcedureInstanceRecord { private String cardFinancialSettlementServiceSchedule = null; private String participantAcquirerBankReference = null; private String participantIssuerBankReference = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Defines the type and scheduling of card settlement processing, includes Issuer and Acquirer involvement/scheduling details as necessary * @return cardFinancialSettlementServiceSchedule **/ public String getCardFinancialSettlementServiceSchedule() { return cardFinancialSettlementServiceSchedule; } public void setCardFinancialSettlementServiceSchedule(String cardFinancialSettlementServiceSchedule) { this.cardFinancialSettlementServiceSchedule = cardFinancialSettlementServiceSchedule; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Refers to the Acquiring bank for which the Network orchestrates settlement processing * @return participantAcquirerBankReference **/ public String getParticipantAcquirerBankReference() { return participantAcquirerBankReference; } public void setParticipantAcquirerBankReference(String participantAcquirerBankReference) { this.participantAcquirerBankReference = participantAcquirerBankReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Refers to the Issuing bank for which the Network orchestrates settlement processing * @return participantIssuerBankReference **/ public String getParticipantIssuerBankReference() { return participantIssuerBankReference; } public void setParticipantIssuerBankReference(String participantIssuerBankReference) { this.participantIssuerBankReference = participantIssuerBankReference; } }
3e00004ad6ed9f24f7117c8e2ad0760ff26b6268
3,743
java
Java
realestate/src/main/java/vn/edu/uit/realestate/Controller/RealEstateKindController.java
Fijetso/realestate
9a00fb87e6a5d1b8ee791a7cde6b3f39df774d1d
[ "Apache-2.0" ]
null
null
null
realestate/src/main/java/vn/edu/uit/realestate/Controller/RealEstateKindController.java
Fijetso/realestate
9a00fb87e6a5d1b8ee791a7cde6b3f39df774d1d
[ "Apache-2.0" ]
7
2021-03-09T02:50:35.000Z
2022-03-02T03:49:53.000Z
realestate/src/main/java/vn/edu/uit/realestate/Controller/RealEstateKindController.java
Fijetso/realestate
9a00fb87e6a5d1b8ee791a7cde6b3f39df774d1d
[ "Apache-2.0" ]
null
null
null
47.379747
143
0.776383
1
package vn.edu.uit.realestate.Controller; import java.net.URI; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import vn.edu.uit.realestate.ExceptionHandler.ExistContentException; import vn.edu.uit.realestate.ExceptionHandler.NotFoundException; import vn.edu.uit.realestate.Relational.Model.RealEstateKind; import vn.edu.uit.realestate.Relational.Model.Trade; import vn.edu.uit.realestate.Relational.Repository.RealEstateKindRepository; @RestController public class RealEstateKindController { @Autowired private RealEstateKindRepository realEstateKindRepository; @GetMapping("/realestatekinds") public ResponseEntity<List<RealEstateKind>> getRealEstateKinds() { List<RealEstateKind> realEstateKinds = realEstateKindRepository.findAll(); if (realEstateKinds.isEmpty() == true) { throw new NotFoundException("Cannot find any Real Estate Kind"); } return new ResponseEntity<>(realEstateKinds, HttpStatus.OK); } @GetMapping("/realestatekinds/{id}") public ResponseEntity<RealEstateKind> getRealEstateKindById(@PathVariable long id) { Optional<RealEstateKind> foundRealEstate = realEstateKindRepository.findById(id); if (foundRealEstate.isPresent()==false) { throw new NotFoundException("Cannot find any Real Estate Kind with id="+id); } return new ResponseEntity<>(foundRealEstate.get(), HttpStatus.OK); } @PostMapping("/realestatekinds") public ResponseEntity<RealEstateKind> postRealEstateKind(@Valid @RequestBody RealEstateKind realEstateKind) throws Exception { realEstateKindRepository.save(realEstateKind); URI location = ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(realEstateKind.getId()).toUri(); return ResponseEntity.created(location).build(); } @GetMapping("/realestatekinds/{realEstateKindId}/trades") public ResponseEntity<List<Trade>> getTradesByRealEstateKindId(@PathVariable Long realEstateKindId) { Optional<RealEstateKind> foundRealEstateKind = realEstateKindRepository.findById(realEstateKindId); if (foundRealEstateKind.isPresent()==false) { throw new NotFoundException("Cannot find any Real Estate Kind with id="+realEstateKindId); } List<Trade> trades = foundRealEstateKind.get().getTrades(); if(trades.isEmpty() == true) throw new NotFoundException("Cannot find any Trade with Real Estate Kind Id="+realEstateKindId); return new ResponseEntity<>(trades, HttpStatus.OK); } @DeleteMapping("/realestatekinds/{id}") public void deleteRealEstateKindById(@PathVariable long id) throws Exception { Optional<RealEstateKind> foundRealEstate = realEstateKindRepository.findById(id); if (foundRealEstate.isPresent()==false) { throw new NotFoundException("Cannot find any Real Estate Kind with id="+id); } if(foundRealEstate.get().getTrades().isEmpty()==false) { throw new ExistContentException("There still exist 'Trade' in this Real Estate Kind. You should delete all these Trades before delete."); } realEstateKindRepository.deleteById(id); } }
3e0000a84e57ffdb1c99d83ebd42aa2a8cde2687
526
java
Java
src/java/elpoeta/felurian/domain/Variedad.java
elPoeta/FelurianPayPal
aaf42b96bbcbe935046a90f8b80f54b9e2a90a6e
[ "MIT" ]
null
null
null
src/java/elpoeta/felurian/domain/Variedad.java
elPoeta/FelurianPayPal
aaf42b96bbcbe935046a90f8b80f54b9e2a90a6e
[ "MIT" ]
null
null
null
src/java/elpoeta/felurian/domain/Variedad.java
elPoeta/FelurianPayPal
aaf42b96bbcbe935046a90f8b80f54b9e2a90a6e
[ "MIT" ]
null
null
null
15.939394
69
0.553232
2
package elpoeta.felurian.domain; /** * * @author elpoeta */ public class Variedad { private Integer id; private String nombre; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Override public String toString() { return "Variedad{" + "id=" + id + ", nombre=" + nombre + '}'; } }
3e0000e9ccf68f74695b5511775311ff493fa92c
5,215
java
Java
src/main/java/com/hbm/render/model/ModelCalStock.java
Syncinus/Hbm-s-Nuclear-Tech-GIT
3ccc662ea0ca016d0d0a507864e2c0ec950c2807
[ "Unlicense" ]
null
null
null
src/main/java/com/hbm/render/model/ModelCalStock.java
Syncinus/Hbm-s-Nuclear-Tech-GIT
3ccc662ea0ca016d0d0a507864e2c0ec950c2807
[ "Unlicense" ]
null
null
null
src/main/java/com/hbm/render/model/ModelCalStock.java
Syncinus/Hbm-s-Nuclear-Tech-GIT
3ccc662ea0ca016d0d0a507864e2c0ec950c2807
[ "Unlicense" ]
null
null
null
30.857988
106
0.6907
3
package com.hbm.render.model; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; public class ModelCalStock extends ModelBase { ModelRenderer Shape8; ModelRenderer Shape9; ModelRenderer Shape10; ModelRenderer Shape11; ModelRenderer Shape12; ModelRenderer Shape13; ModelRenderer Shape14; ModelRenderer Shape15; ModelRenderer Shape16; ModelRenderer Shape17; ModelRenderer Shape18; ModelRenderer Shape19; ModelRenderer Shape20; ModelRenderer Shape21; ModelRenderer Shape22; public ModelCalStock() { textureWidth = 64; textureHeight = 32; Shape8 = new ModelRenderer(this, 0, 0); Shape8.addBox(0F, 0F, 0F, 15, 6, 3); Shape8.setRotationPoint(0F, 1F, -1.5F); Shape8.setTextureSize(64, 32); Shape8.mirror = true; setRotation(Shape8, 0F, 0F, 0F); Shape9 = new ModelRenderer(this, 0, 9); Shape9.addBox(0F, 0F, 0F, 6, 1, 2); Shape9.setRotationPoint(7F, 7F, -1F); Shape9.setTextureSize(64, 32); Shape9.mirror = true; setRotation(Shape9, 0F, 0F, 0F); Shape10 = new ModelRenderer(this, 0, 12); Shape10.addBox(0F, 0F, 0F, 2, 5, 2); Shape10.setRotationPoint(10F, 8F, -1F); Shape10.setTextureSize(64, 32); Shape10.mirror = true; setRotation(Shape10, 0F, 0F, -0.2617994F); Shape11 = new ModelRenderer(this, 0, 26); Shape11.addBox(0F, 0F, 0F, 3, 4, 2); Shape11.setRotationPoint(19F, 3F, -1F); Shape11.setTextureSize(64, 32); Shape11.mirror = true; setRotation(Shape11, 0F, 0F, 0F); Shape12 = new ModelRenderer(this, 0, 22); Shape12.addBox(-4F, 0F, 0F, 4, 2, 2); Shape12.setRotationPoint(19F, 3F, -1F); Shape12.setTextureSize(64, 32); Shape12.mirror = true; setRotation(Shape12, 0F, 0F, -0.1115358F); Shape13 = new ModelRenderer(this, 10, 28); Shape13.addBox(-5F, -2F, 0F, 5, 2, 2); Shape13.setRotationPoint(19F, 7F, -1F); Shape13.setTextureSize(64, 32); Shape13.mirror = true; setRotation(Shape13, 0F, 0F, 0.2617994F); Shape14 = new ModelRenderer(this, 12, 23); Shape14.addBox(0F, 0F, 0F, 1, 3, 2); Shape14.setRotationPoint(22F, 3F, -1F); Shape14.setTextureSize(64, 32); Shape14.mirror = true; setRotation(Shape14, 0F, 0F, 0.3490659F); Shape15 = new ModelRenderer(this, 42, 0); Shape15.addBox(0F, 0F, 0F, 3, 5, 8); Shape15.setRotationPoint(3F, 4F, -9.5F); Shape15.setTextureSize(64, 32); Shape15.mirror = true; setRotation(Shape15, 0F, 0F, 0F); Shape16 = new ModelRenderer(this, 36, 0); Shape16.addBox(0F, 0F, 0F, 2, 1, 1); Shape16.setRotationPoint(3.5F, 3.5F, -4F); Shape16.setTextureSize(64, 32); Shape16.mirror = true; setRotation(Shape16, 0F, 0F, 0F); Shape17 = new ModelRenderer(this, 36, 0); Shape17.addBox(0F, 0F, 0F, 2, 1, 1); Shape17.setRotationPoint(3.5F, 2.7F, -3.5F); Shape17.setTextureSize(64, 32); Shape17.mirror = true; setRotation(Shape17, 0F, 0F, 0F); Shape18 = new ModelRenderer(this, 36, 0); Shape18.addBox(0F, 0F, 0F, 2, 1, 1); Shape18.setRotationPoint(3.5F, 2.2F, -2.8F); Shape18.setTextureSize(64, 32); Shape18.mirror = true; setRotation(Shape18, 0F, 0F, 0F); Shape19 = new ModelRenderer(this, 36, 0); Shape19.addBox(0F, 0F, 0F, 2, 1, 1); Shape19.setRotationPoint(3.5F, 1.8F, -2F); Shape19.setTextureSize(64, 32); Shape19.mirror = true; setRotation(Shape19, 0F, 0F, 0F); Shape20 = new ModelRenderer(this, 16, 9); Shape20.addBox(0F, 0F, 0F, 6, 1, 4); Shape20.setRotationPoint(7F, 4F, -2F); Shape20.setTextureSize(64, 32); Shape20.mirror = true; setRotation(Shape20, 0F, 0F, 0F); Shape21 = new ModelRenderer(this, 8, 12); Shape21.addBox(0F, 0F, 0F, 2, 1, 1); Shape21.setRotationPoint(11F, 0F, 0F); Shape21.setTextureSize(64, 32); Shape21.mirror = true; setRotation(Shape21, 0F, 0F, 0F); Shape22 = new ModelRenderer(this, 8, 14); Shape22.addBox(0F, 0F, 0F, 2, 1, 2); Shape22.setRotationPoint(11F, -1F, 0F); Shape22.setTextureSize(64, 32); Shape22.mirror = true; setRotation(Shape22, -0.3490659F, 0F, 0F); } public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); Shape8.render(f5); Shape9.render(f5); Shape10.render(f5); Shape11.render(f5); Shape12.render(f5); Shape13.render(f5); Shape14.render(f5); Shape15.render(f5); Shape16.render(f5); Shape17.render(f5); Shape18.render(f5); Shape19.render(f5); Shape20.render(f5); Shape21.render(f5); Shape22.render(f5); } public void renderAll(float f5) { Shape8.render(f5); Shape9.render(f5); Shape10.render(f5); Shape11.render(f5); Shape12.render(f5); Shape13.render(f5); Shape14.render(f5); Shape15.render(f5); Shape16.render(f5); Shape17.render(f5); Shape18.render(f5); Shape19.render(f5); Shape20.render(f5); Shape21.render(f5); Shape22.render(f5); } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } }
3e000102d739f6ff1609530a21c82139e5bef8ee
3,637
java
Java
src/ds/tcp/client_server/Server.java
tabsnospaces/distributed-systems-for-fun
54e605265a4d78656aba815184b869b96227d3a9
[ "Apache-2.0" ]
null
null
null
src/ds/tcp/client_server/Server.java
tabsnospaces/distributed-systems-for-fun
54e605265a4d78656aba815184b869b96227d3a9
[ "Apache-2.0" ]
null
null
null
src/ds/tcp/client_server/Server.java
tabsnospaces/distributed-systems-for-fun
54e605265a4d78656aba815184b869b96227d3a9
[ "Apache-2.0" ]
null
null
null
30.057851
79
0.523783
4
package ds.tcp.client_server; import java.net.*; import java.io.*; import java.util.Scanner; /** * * @author yuzo */ public class Server { public static void main(String args[]) { try { int serverPort = 6666; ServerSocket serverSocket = new ServerSocket(serverPort); while (true) { System.out.println("Waiting for connections..."); Socket clientSocket = serverSocket.accept(); System.out.println("Client Accepted..."); new Thread(new ThreadServerReceiver(clientSocket)).start(); new Thread(new ThreadServerSender(clientSocket)).start(); } } catch (IOException e) { System.out.println("Server socket: " + e.getMessage()); } } } class ThreadServerReceiver implements Runnable { DataInputStream input; DataOutputStream output; Socket serverSocket; public ThreadServerReceiver(Socket serverSocket) { try { this.serverSocket = serverSocket; this.input = new DataInputStream(serverSocket.getInputStream()); this.output = new DataOutputStream(serverSocket.getOutputStream()); } catch (IOException ioe) { System.out.println("IOE: " + ioe.getMessage()); } } @Override public void run() { try { String buffer; while (true) { buffer = this.input.readUTF(); System.out.println(buffer); if (buffer.equals("SAIR")) { break; } } } catch (EOFException eofe) { System.out.println("EOF: " + eofe.getMessage()); } catch (IOException ioe) { System.out.println("IOE: " + ioe.getMessage()); } finally { try { this.input.close(); this.output.close(); this.serverSocket.close(); System.exit(0); } catch (IOException ioe) { System.err.println("IOE: " + ioe); } } System.out.println("ThreadServerReceiver terminated."); } } class ThreadServerSender implements Runnable { DataInputStream input; DataOutputStream output; Socket serverSocket; public ThreadServerSender(Socket serverSocket) { try { this.serverSocket = serverSocket; input = new DataInputStream(serverSocket.getInputStream()); output = new DataOutputStream(serverSocket.getOutputStream()); } catch (IOException ioe) { System.out.println("IOE: " + ioe.getMessage()); } } @Override public void run() { Scanner reader = new Scanner(System.in); try { String buffer; while (true) { buffer = reader.nextLine(); this.output.writeUTF(buffer); if (buffer.equals("SAIR")) { break; } } } catch (EOFException eofe) { System.out.println("EOFE: " + eofe.getMessage()); } catch (IOException ioe) { System.out.println("IOE: " + ioe.getMessage()); } finally { // try { //// this.input.close(); //// this.output.close(); //// this.serverSocket.close(); //// System.exit(0); // } catch (IOException ioe) { // System.err.println("IOE: " + ioe); // } } System.out.println("ThreadServerSender terminated."); } }
3e000281de32fee98f383337ccac5048f1d1b42d
1,078
java
Java
QuickSort.java
rithwik00/Sorting-Algorithms
ed4c1e88f310eefe0d8a1918bed5ce9dfdaeffdf
[ "MIT" ]
null
null
null
QuickSort.java
rithwik00/Sorting-Algorithms
ed4c1e88f310eefe0d8a1918bed5ce9dfdaeffdf
[ "MIT" ]
null
null
null
QuickSort.java
rithwik00/Sorting-Algorithms
ed4c1e88f310eefe0d8a1918bed5ce9dfdaeffdf
[ "MIT" ]
null
null
null
22
57
0.427644
5
class QuickSort { static void swap (int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = low - 1; for(int j = low; j < high; j++) { if (arr[j] < pivot) { i++; swap(arr, i, j); } } swap(arr, i + 1, high); return (i + 1); } static void quickSort(int[] arr, int low, int high) { if(low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } static void printArray(int[] arr, int size) { for(int i = 0; i < size; i++) System.out.print(arr[i] + " "); System.out.println(); } public static void main(String[] args) { int[] arr = {10,7,8,9,1,5}; int n = arr.length; quickSort(arr, 0, n - 1); printArray(arr, n); } }
3e0002c0fd11b51daff2b6f07e8dd00f3bfb9111
190
java
Java
src/main/java/innerclass/People.java
ThinkDifferenter/demo4java
7a382000eadc20ffbc735724005c7bfafb9205b8
[ "Apache-2.0" ]
null
null
null
src/main/java/innerclass/People.java
ThinkDifferenter/demo4java
7a382000eadc20ffbc735724005c7bfafb9205b8
[ "Apache-2.0" ]
null
null
null
src/main/java/innerclass/People.java
ThinkDifferenter/demo4java
7a382000eadc20ffbc735724005c7bfafb9205b8
[ "Apache-2.0" ]
null
null
null
15.833333
45
0.542105
6
package innerclass; public class People { public People getWoman(){ class Woman extends People{ //局部内部类 int age =0; } return new Woman(); } }
3e0002e6ac2e53c5372fb23b7ffddf61d4b9e6f5
13,993
java
Java
portal-api/src/main/java/com/channelsharing/hongqu/portal/api/service/impl/UserInfoServiceImpl.java
Gradven/portal-api
2f3740df0591e95e368713b0bb502e122d9ff650
[ "Apache-2.0" ]
1
2022-02-10T03:51:11.000Z
2022-02-10T03:51:11.000Z
portal-api/src/main/java/com/channelsharing/hongqu/portal/api/service/impl/UserInfoServiceImpl.java
Gradven/portal-api
2f3740df0591e95e368713b0bb502e122d9ff650
[ "Apache-2.0" ]
null
null
null
portal-api/src/main/java/com/channelsharing/hongqu/portal/api/service/impl/UserInfoServiceImpl.java
Gradven/portal-api
2f3740df0591e95e368713b0bb502e122d9ff650
[ "Apache-2.0" ]
null
null
null
30.353579
159
0.670192
7
/** * Copyright &copy; 2016-2022 liuhangjun All rights reserved. */ package com.channelsharing.hongqu.portal.api.service.impl; import com.channelsharing.hongqu.portal.api.constant.Constant; import com.channelsharing.hongqu.portal.api.entity.UserInfo; import com.channelsharing.hongqu.portal.api.enums.UserStatus; import com.channelsharing.hongqu.portal.api.service.UserInfoService; import com.channelsharing.cloud.sms.SmsSenderFactory; import com.channelsharing.common.cache.CacheDuration; import com.channelsharing.common.cache.ExpireTimeConstant; import com.channelsharing.common.exception.BadRequestException; import com.channelsharing.common.exception.ForbiddenException; import com.channelsharing.common.exception.NotFoundException; import com.channelsharing.common.exception.OccupiedException; import com.channelsharing.common.service.CrudServiceImpl; import com.channelsharing.common.utils.DateUtils; import com.channelsharing.common.utils.EmailUtil; import com.channelsharing.common.utils.IdGen; import com.channelsharing.common.utils.RandomUtil; import com.channelsharing.hongqu.portal.api.dao.UserInfoDao; import com.channelsharing.hongqu.portal.api.enums.AccountType; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.validation.constraints.NotNull; import java.util.List; /** * 用户信息Service * @author liuhangjun * @version 2017-06-15 */ @CacheDuration(duration = ExpireTimeConstant.ONE_DAY) @Service public class UserInfoServiceImpl extends CrudServiceImpl<UserInfoDao, UserInfo> implements UserInfoService { public static final String PORTAL_CACHE_PREFIX = Constant.PORTAL_CACHE_PREFIX; @Resource private EmailUtil emailUtil; private static final String MSG_CONTENT = "{verificationCode}"; /** * * @param userId * @return */ @Cacheable(value = PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #userId", unless = "#result == null") public UserInfo findOne(Long userId){ UserInfo userInfo = new UserInfo(); userInfo.setId(userId); UserInfo userInfoResult = super.findOne(userInfo); if (userInfoResult == null){ return null; } return userInfoResult; } public UserInfo findOne(Long id, Long currentUserId){ UserInfo model = new UserInfo(); model.setId(id); UserInfo userInfo = super.findOne(model); if (userInfo == null) return new UserInfo(); userInfo.setActivationCode(null); return userInfo; } /** * 检查昵称是否被占用 * @param userInfo * @param nickname */ public void isNicknameOccupied(UserInfo userInfo, String nickname){ if (super.dao.isNicknameOccupied(userInfo != null ? userInfo.getId() : null, nickname)) { throw new OccupiedException("昵称", nickname); } } /** * 检查email是否被占用 * @param userInfo * @param email */ public void isEmailOccupied(UserInfo userInfo, String email){ if (super.dao.isEmailOccupied(userInfo != null ? userInfo.getId() : null, email)) { throw new OccupiedException("邮箱地址", email); } } /** * 检查此邮箱是否有注册 * @param email * @return */ public boolean isExistEmail(String email){ return super.dao.isEmailOccupied(null, email); } /** * 检查此手机号码是否有注册 * @param mobile * @return */ public boolean isExistMobile(String mobile){ return super.dao.isMobileOccupied(null, mobile); } /** * 检查mobile是否被占用 * * @param userInfo * @param mobile */ public void isMobileOccupied(UserInfo userInfo, String mobile) { if (super.dao.isMobileOccupied(userInfo != null ? userInfo.getId() : null, mobile)) { throw new OccupiedException("手机号码", mobile); } } /** * 以邮件的方式发送激活码 * * @param userInfo */ @Cacheable(value = PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #userInfo.id", unless = "#result == null") @Transactional public void sendActivationCode(@NotNull UserInfo userInfo) { if (userInfo.getEmail() != null) { this.isEmailOccupied(null, userInfo.getEmail()); UserInfo entity = new UserInfo(); entity.setEmail(userInfo.getEmail()); entity.setAccountType(AccountType.email.getCode()); entity.setStatus(UserStatus.forbidden.getCode()); String activationCode = RandomUtil.getRandomNumString(6); entity.setActivationCode(activationCode); this.add(entity); String today = DateUtils.getDate(); String content = "亲爱的" + Constant.APP_NAME + "用户,您好!\n" + "您本次操作的激活码是" + activationCode + ",请输入后继续操作。\n" + "如果您没有进行过操作,请忽略此邮件。此邮件为自动发布,无需回复。\n" + "\n" + Constant.APP_NAME + "\n" + today; emailUtil.sendSimpleMail(userInfo.getEmail(), Constant.APP_NAME + "激活码", content); } else { this.isMobileOccupied(null, userInfo.getMobile()); UserInfo entity = new UserInfo(); entity.setMobile(userInfo.getMobile()); entity.setAccountType(AccountType.mobile.getCode()); entity.setStatus(UserStatus.forbidden.getCode()); entity.setActivationCode(RandomUtil.getRandomNumString(6)); this.add(entity); SmsSenderFactory.getSmsSender().sendSms(entity.getMobile(), StringUtils.replace(MSG_CONTENT, "{verificationCode}", entity.getActivationCode())); } } /** * 找回密码时,发送验证码 * * @param userInfo */ @Cacheable(value = PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #userInfo.id", unless = "#result == null") public void sendVerifyCode(@NotNull UserInfo userInfo) { if (userInfo.getEmail() != null) { if (!this.isExistEmail(userInfo.getEmail())) throw new NotFoundException("邮箱不存在,请注册此邮箱"); UserInfo entity = new UserInfo(); entity.setEmail(userInfo.getEmail()); entity.setAccountType(AccountType.email.getCode()); String activationCode = RandomUtil.getRandomNumString(6); entity.setActivationCode(activationCode); super.dao.update(entity); String today = DateUtils.getDate(); String content = "亲爱的" + Constant.APP_NAME + "用户,您好!\n" + "您本次操作的验证码是" + activationCode + ",请输入后继续操作。\n" + "如果您没有进行过操作,请忽略此邮件。此邮件为自动发布,无需回复。\n" + "\n" + Constant.APP_NAME + "\n" + today; emailUtil.sendSimpleMail(userInfo.getEmail(), Constant.APP_NAME + "验证码", content); } else { if (!this.isExistMobile(userInfo.getMobile())) throw new NotFoundException("手机号不存在,请注册此手机号"); UserInfo entity = new UserInfo(); entity.setMobile(userInfo.getMobile()); entity.setAccountType(AccountType.mobile.getCode()); entity.setActivationCode(RandomUtil.getRandomNumString(6)); super.dao.update(entity); SmsSenderFactory.getSmsSender().sendSms(entity.getMobile(), StringUtils.replace(MSG_CONTENT, "{verificationCode}", entity.getActivationCode())); } } /** * 激活用户 * @param userInfo */ @Cacheable(value = PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #result.id", unless = "#result == null") @Transactional public UserInfo activateUser(@NotNull UserInfo userInfo) { UserInfo entity = new UserInfo(); entity.setEmail(userInfo.getEmail()); entity.setMobile(userInfo.getMobile()); UserInfo retEntity = super.dao.findOne(entity); if (retEntity == null) { throw new BadRequestException("此用户不存在"); } if (retEntity.getStatus().equals(UserStatus.activated.getCode())) { throw new BadRequestException("此用户已被激活,可重置密码"); } if (retEntity != null) { String activationCode = retEntity.getActivationCode(); if (StringUtils.isBlank(activationCode)) throw new ForbiddenException("请先获取验证码!"); if (!StringUtils.equals(activationCode, userInfo.getActivationCode())) throw new BadRequestException("验证码不正确,请重新输入!"); } entity.setStatus(UserStatus.activated.getCode()); super.dao.update(entity); return retEntity; } /** * 验证用户 * @param userInfo */ @CacheEvict(value = PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #result.id") @Transactional public UserInfo verifyUser(@NotNull UserInfo userInfo){ UserInfo entity = new UserInfo(); entity.setEmail(userInfo.getEmail()); entity.setMobile(userInfo.getMobile()); UserInfo retEntity = super.dao.findOne(entity); if (retEntity != null){ String verifyCode = retEntity.getActivationCode(); if (StringUtils.isBlank(verifyCode)) throw new ForbiddenException("请先获取验证码!"); if (!StringUtils.equals(verifyCode, userInfo.getActivationCode())) throw new BadRequestException("验证码不正确,请重新输入!"); } entity.setActivationCode(""); entity.setStatus(UserStatus.activated.getCode()); super.dao.update(entity); return retEntity; } /** * 用户账户登录逻辑 * 1、用户名不存在,则提醒用户名密码错误 * 2、用户未激活,则提醒先激活用户 * 3、用户登录错误次数过多,请找回密码 * 4、登录成功,返回用户信息 * 5、登录错误次数归零 * @param userInfo */ @CacheEvict(value = PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #result.id") @Transactional public UserInfo login(@NotNull UserInfo userInfo){ UserInfo retUserInfo = null; if (userInfo.getEmail() != null || userInfo.getMobile() != null ) { retUserInfo = super.findOne(userInfo); } if (retUserInfo == null) throw new BadRequestException("用户名或密码错误"); if (retUserInfo.getStatus() == UserStatus.forbidden.getCode()) throw new BadRequestException("未激活"); //允许的最大错误登录次数 int maxLoginErrorTimes = 5; if (retUserInfo.getLoginErrorTimes() >= maxLoginErrorTimes) throw new ForbiddenException("密码错误次数已超过" + maxLoginErrorTimes + "次,请选择找回密码"); //比较密码是否可以对应上 String password = retUserInfo.getPassword(); String reqPassword = DigestUtils.sha512Hex(userInfo.getPassword()); logger.debug("Request password is: [{}]; digest password is: [{}] ", userInfo.getPassword(), reqPassword); if (!StringUtils.equals(reqPassword, password)) { UserInfo updateErrorTimes = new UserInfo(); updateErrorTimes.setLoginErrorTimes(retUserInfo.getLoginErrorTimes() + 1); updateErrorTimes.setId(retUserInfo.getId()); super.dao.update(updateErrorTimes); throw new BadRequestException("用户名或密码错误"); } super.dao.clearLoginErrorTimes(userInfo); return retUserInfo; } /** * 第三方用户登录处理逻辑 * 先根据第三方的id判断数据库中是否有此用户, * 如果有那么直接返回用户信息, * 如果没有,那么插入一条用户信息到表中,然后返回此用户信息 * * @param userInfo * @return */ @Transactional public UserInfo thirdLogin(@NotNull UserInfo userInfo){ UserInfo retUserInfo; UserInfo thirdUser = new UserInfo(); thirdUser.setThirdPartyUserId(userInfo.getThirdPartyUserId()); //首先查询是否有此用户 retUserInfo = super.findOne(thirdUser); if (retUserInfo == null){ //如果昵称重复,那么在昵称后面加个4位长的随机数 String nickname = userInfo.getNickname(); if (super.dao.isNicknameOccupied(null, nickname)){ nickname = nickname + "_" + StringUtils.substring(IdGen.uuid(), 0, 4); userInfo.setNickname(nickname); } //首次登录为激活状态 userInfo.setStatus(UserStatus.activated.getCode()); //新用户插入用户表 super.add(userInfo); retUserInfo = super.findOne(thirdUser); } return retUserInfo; } /** * 更新用户信息 * @param userInfo */ @CacheEvict(value = PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #userInfo.id") @Transactional @Override public void modify(@NotNull UserInfo userInfo){ this.isEmailOccupied(userInfo, userInfo.getEmail()); this.isNicknameOccupied(userInfo, userInfo.getNickname()); super.dao.update(userInfo); } /** * 初始化用户,只要昵称和密码 * @param userInfo */ @Transactional public void initUserInfo(UserInfo userInfo){ this.isNicknameOccupied(userInfo, userInfo.getNickname()); String password = DigestUtils.sha512Hex(userInfo.getPassword()); userInfo.setPassword(password); super.dao.update(userInfo); } /** * 修改用户密码 * 先判断旧密码是否可以对应上 * @param userId * @param oldPassword * @param newPassword */ @Transactional public void modifyPassword(Long userId, String oldPassword, String newPassword){ UserInfo entity = new UserInfo(); entity.setId(userId); UserInfo retUserInfo = super.dao.findOne(entity); if (!DigestUtils.sha512Hex(oldPassword).equals(retUserInfo.getPassword())) throw new BadRequestException("原始密码错误"); else { entity.setPassword(DigestUtils.sha512Hex(newPassword)); super.dao.update(entity); } } /** * 重置密码功能, * 说明:验证码的数据库字段与激活码是同一个字段 * 更新密码,并把验证码(激活码)字段设置为null * 验证码可以请求多次,这里没有做次数限制,以后再补充 * @param userInfo */ @Transactional public void resetPassword(UserInfo userInfo) { userInfo.setPassword(DigestUtils.sha512Hex(userInfo.getPassword())); userInfo.setActivationCode(null); super.dao.update(userInfo); } /** * 根据ids获取到用户数据 * @param ids * @return */ public List<UserInfo> findByIds(List<Long> ids){ return super.dao.findByIds(ids); } }
3e00032d5bbc1892914ec94df1717dc46088cc75
1,920
java
Java
sample/build/generated/source/r/debug/jp/co/cyberagent/android/gpuimage/sample/R.java
messi49/GPUImageTest
80667ca2ddf7578bd77a0b39debe1fb8143dddc9
[ "Apache-2.0" ]
1
2017-04-11T06:26:58.000Z
2017-04-11T06:26:58.000Z
sample/build/generated/source/r/debug/jp/co/cyberagent/android/gpuimage/sample/R.java
messi49/GPUImageTest
80667ca2ddf7578bd77a0b39debe1fb8143dddc9
[ "Apache-2.0" ]
null
null
null
sample/build/generated/source/r/debug/jp/co/cyberagent/android/gpuimage/sample/R.java
messi49/GPUImageTest
80667ca2ddf7578bd77a0b39debe1fb8143dddc9
[ "Apache-2.0" ]
null
null
null
39.183673
72
0.721354
8
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package jp.co.cyberagent.android.gpuimage.sample; public final class R { public static final class attr { } public static final class drawable { public static final int ic_action_search=0x7f020000; public static final int ic_launcher=0x7f020001; public static final int ic_switch_camera=0x7f020002; public static final int lookup_amatorka=0x7f020003; } public static final class id { public static final int bar=0x7f070001; public static final int button_camera=0x7f070009; public static final int button_capture=0x7f070005; public static final int button_choose_filter=0x7f070004; public static final int button_gallery=0x7f070008; public static final int button_save=0x7f070007; public static final int gpuimage=0x7f070006; public static final int img_switch_camera=0x7f070002; public static final int seekBar=0x7f070003; public static final int surfaceView=0x7f070000; } public static final class layout { public static final int activity_camera=0x7f030000; public static final int activity_gallery=0x7f030001; public static final int activity_main=0x7f030002; } public static final class raw { public static final int tone_cuver_sample=0x7f040000; } public static final class string { public static final int app_name=0x7f050000; public static final int title_activity_activity_main=0x7f050001; } public static final class style { public static final int AppTheme=0x7f060000; public static final int AppTheme_Fullscreen=0x7f060002; public static final int AppTheme_NoActionBar=0x7f060001; } }
3e000478a0e785e0a00b3c43057c8f73302e7215
6,355
java
Java
src/main/java/com/krupatek/courier/view/rate/PlaceGenerationForm.java
Atharva-tech/courier
ebf6e3788ebf5d1183ef8872048d9498cd4377bd
[ "Unlicense" ]
null
null
null
src/main/java/com/krupatek/courier/view/rate/PlaceGenerationForm.java
Atharva-tech/courier
ebf6e3788ebf5d1183ef8872048d9498cd4377bd
[ "Unlicense" ]
null
null
null
src/main/java/com/krupatek/courier/view/rate/PlaceGenerationForm.java
Atharva-tech/courier
ebf6e3788ebf5d1183ef8872048d9498cd4377bd
[ "Unlicense" ]
null
null
null
37.163743
152
0.679465
9
package com.krupatek.courier.view.rate; import com.krupatek.courier.model.AccountCopy; import com.krupatek.courier.model.PlaceGeneration; import com.krupatek.courier.model.State; import com.krupatek.courier.model.Zones; import com.krupatek.courier.repository.PlaceGenerationRepository; import com.krupatek.courier.repository.StateRepository; import com.krupatek.courier.service.PlaceGenerationService; import com.krupatek.courier.service.StateService; import com.krupatek.courier.service.ZonesService; import com.krupatek.courier.utils.ViewUtils; import com.vaadin.flow.component.Key; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H4; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.binder.Binder; import com.vaadin.flow.data.binder.ValidationException; import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.component.select.Select; import com.vaadin.flow.component.button.Button; //import org.hibernate.sql.Select; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.TreeSet; import java.util.stream.Collectors; public class PlaceGenerationForm extends Div { public PlaceGenerationForm(ZonesService zonesService, PlaceGenerationRepository placeGenerationRepository, PlaceGenerationService placeGenerationService, StateService stateService){ super(); Dialog dialog=new Dialog(); HorizontalLayout horizontalLayout = new HorizontalLayout(); horizontalLayout.setPadding(true); horizontalLayout.setMargin(false); Binder<PlaceGeneration> binder=new Binder<>(PlaceGeneration.class); PlaceGeneration placeGeneration=placeGenerationRepository.findAll().get(0); FormLayout formLayout = new FormLayout(); formLayout.setResponsiveSteps( new FormLayout.ResponsiveStep("25em", 1), new FormLayout.ResponsiveStep("25em", 2)); formLayout.setMaxWidth("25em"); formLayout.add(ViewUtils.addCloseButton(dialog), 2); H4 title = new H4(); title.setSizeFull(); title.setText("Place Generation"); formLayout.add(title, 2); TextField cityTxt = new TextField(); cityTxt.setLabel("City : "); cityTxt.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(cityTxt, 2); binder.forField(cityTxt).asRequired("City name is mandatory").bind(str -> "", PlaceGeneration::setCityName); cityTxt.addValueChangeListener(e -> { if (e.getValue() != null && e.getValue().length() > 3) { String cityName = e.getValue(); // TODO // PlaceGeneration - cityName Optional<PlaceGeneration> placeGenerationOptional = placeGenerationService.findByCityName(cityName); if(placeGenerationOptional.isPresent()){ // Show error cityTxt.setInvalid(true); cityTxt.setErrorMessage("City Already Exists !!"); } else { cityTxt.setInvalid(false); binder.readBean(placeGenerationOptional.get()); } } }); // cityTxt.setValue((placeGeneration.getCityName())); ComboBox<String> stateSelect=new ComboBox<>(); stateSelect.setWidth("50"); stateSelect.setLabel("State :"); formLayout.add(stateSelect,2); TreeSet<String> stateSource=stateService.findAll().parallelStream().map(State::getStateName).collect(Collectors.toCollection(TreeSet::new)); stateSelect.setItems(stateSource); //stateSelect.setValue(stateSource.first()); ComboBox<String> placeCodeSelect=new ComboBox<>(); placeCodeSelect.setWidth("50"); placeCodeSelect.setLabel("Place code :"); formLayout.add(placeCodeSelect,2); TreeSet<String> placeCodeSource= zonesService.findAll().parallelStream().map(Zones::getZoneCode).collect(Collectors.toCollection(TreeSet::new)); placeCodeSelect.setItems(placeCodeSource); //placeCodeSelect.setValue(placeCodeSource.first()); //ComboBox<String> stateComboBox = new ComboBox<>(); // stateComboBox.setLabel("State :"); // formLayout.add(stateComboBox,2); // List<PlaceGeneration> placeGenerationList=placeGenerationService.findAll(); // List<String> stateNameList=new ArrayList<>(); // placeGenerationList.forEach(c->stateNameList.add(c.getStateName())); // stateComboBox.setItems(stateNameList); //binder.bind(stateComboBox,PlaceGeneration::getStateName,PlaceGeneration::setStateName); // ComboBox<String> placeCodeComboBox = new ComboBox<>(); // placeCodeComboBox.setLabel("Place Code :"); // formLayout.add(placeCodeComboBox,2); // List<String> placeCodeNameList=new ArrayList<>(); // placeGenerationList.forEach(c->placeCodeNameList.add(c.getPlaceCode())); // placeCodeComboBox.setItems(placeCodeNameList); Button save=new Button("Save", event->{ try{ binder.writeBean(placeGeneration); placeGeneration.setCityName(cityTxt.getValue()); placeGeneration.setStateName(stateSelect.getValue()); placeGeneration.setPlaceCode(placeCodeSelect.getValue()); placeGenerationService.saveAndFlush(placeGeneration); Notification.show("Details saved successfully"); }catch (ValidationException e){ Notification.show("Details could not be saved"); } }); Button cancel=new Button("Cancel",event->dialog.close()); HorizontalLayout actions=new HorizontalLayout(); actions.add(save,cancel); formLayout.add(actions,4); horizontalLayout.add(formLayout); dialog.add(horizontalLayout); dialog.open(); } }
3e00048dc204bb3046b64663dabc69552737397e
1,044
java
Java
src/main/java/IP/recursion/WellFormedBrackets.java
skilllessons/coding-interview-prep-today
3262d606505b0c95cbddffb89c5d09aeae733515
[ "Apache-2.0" ]
1
2020-08-18T03:01:17.000Z
2020-08-18T03:01:17.000Z
src/main/java/IP/recursion/WellFormedBrackets.java
skilllessons/coding-interview-prep-today
3262d606505b0c95cbddffb89c5d09aeae733515
[ "Apache-2.0" ]
null
null
null
src/main/java/IP/recursion/WellFormedBrackets.java
skilllessons/coding-interview-prep-today
3262d606505b0c95cbddffb89c5d09aeae733515
[ "Apache-2.0" ]
2
2020-08-25T14:21:11.000Z
2021-10-08T04:15:58.000Z
23.727273
93
0.542146
10
package main.java.IP.recursion; import java.util.ArrayList; import java.util.List; public class WellFormedBrackets { static String[] find_all_well_formed_brackets(int n) { List<String> result = new ArrayList<>(); helper(n,0,0,new StringBuilder(), result); String[] finalResult = new String[result.size()]; int count = 0; for(String s : result) { finalResult[count] = s; count++; } return finalResult; } static void helper(int n, int open, int close, StringBuilder slate, List<String> result){ if(slate.length() == n*2){ result.add(slate.toString()); return; } if (open < n){ slate.append("("); helper(n,open+1, close,slate,result); slate.deleteCharAt(slate.length()-1); } if (close < open) { slate.append(")"); helper(n,open, close+1,slate,result); slate.deleteCharAt(slate.length()-1); } } }
3e0004c401393282608d9438e6c7659735daa3af
855
java
Java
immutable/forestop/impl/OpenclMem.java
benrayfield/HumanAiNetNeural
502a1dc185b9ae7362a15ff89653c6d7f357e003
[ "MIT" ]
1
2020-01-04T00:36:22.000Z
2020-01-04T00:36:22.000Z
immutable/forestop/impl/OpenclMem.java
benrayfield/HumanAiNetNeural
502a1dc185b9ae7362a15ff89653c6d7f357e003
[ "MIT" ]
null
null
null
immutable/forestop/impl/OpenclMem.java
benrayfield/HumanAiNetNeural
502a1dc185b9ae7362a15ff89653c6d7f357e003
[ "MIT" ]
null
null
null
18.586957
63
0.706433
11
package immutable.forestop.impl; import java.io.IOException; import java.lang.ref.WeakReference; import org.lwjgl.opencl.CL10; import org.lwjgl.opencl.CLMem; import immutable.forestop.Mem; public class OpenclMem implements Mem{ public CLMem clmem; //public final WeakReference<CLMem> clmem; /** TODO can this be read from CLMem instead of storing it? */ public final Class eltype; /** TODO can this be read from CLMem instead of storing it? */ public final int size; public OpenclMem(CLMem clmem, Class eltype, int size){ this.clmem = clmem; this.eltype = eltype; this.size = size; } public Class eltype(){ return eltype; } public int size(){ return size; } protected void finalize(){ close(); } public synchronized void close(){ if(clmem != null){ CL10.clReleaseMemObject(clmem); clmem = null; } } }
3e000590e977dc3c8af38bccc8b208146a8fbbd5
248
java
Java
app/src/main/java/yooco/uchain/uchainwallet/data/remote/INetCallback.java
Seven777Sylvia/UC
04f0e01b06a07479f57584d0ca06b0a56a395280
[ "Apache-2.0" ]
null
null
null
app/src/main/java/yooco/uchain/uchainwallet/data/remote/INetCallback.java
Seven777Sylvia/UC
04f0e01b06a07479f57584d0ca06b0a56a395280
[ "Apache-2.0" ]
null
null
null
app/src/main/java/yooco/uchain/uchainwallet/data/remote/INetCallback.java
Seven777Sylvia/UC
04f0e01b06a07479f57584d0ca06b0a56a395280
[ "Apache-2.0" ]
null
null
null
17.714286
62
0.721774
12
package yooco.uchain.uchainwallet.data.remote; /** * Created by SteelCabbage on 2018/3/26. */ public interface INetCallback<T> { void onSuccess(int statusCode, String msg, String result); void onFailed(int failedCode, String msg); }
3e0005d6ce59ee3e79ac3f51a1611a9887aae39a
1,259
java
Java
openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java
chardon1/onap-sdc
b2370800befb9c7c557a0651717a8fd604736542
[ "Apache-2.0" ]
15
2018-10-02T14:54:35.000Z
2022-03-01T18:27:14.000Z
openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java
chardon1/onap-sdc
b2370800befb9c7c557a0651717a8fd604736542
[ "Apache-2.0" ]
6
2021-12-14T21:00:42.000Z
2022-02-27T17:07:08.000Z
openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java
chardon1/onap-sdc
b2370800befb9c7c557a0651717a8fd604736542
[ "Apache-2.0" ]
31
2018-05-30T19:18:29.000Z
2022-03-01T06:16:47.000Z
29.27907
114
0.75139
13
/* * Copyright © 2016-2018 European Support Limited * * 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.openecomp.sdc.versioning; import java.util.Collection; import java.util.function.Predicate; import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.types.Item; public interface ItemManager { Collection<Item> list(Predicate<Item> predicate); Item get(String itemId); Item create(Item item); void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, VersionStatus removedVersionStatus); void archive(Item item); void restore(Item item); void delete(Item item); void updateName(String itemId, String name); void update(Item item); }
3e000719ba31418f590a89b2bbadbce333e1d782
1,361
java
Java
src/main/java/edu/bator/cards/Ally.java
robmat/shadow_era_ai
b6ff43e9a835fe32fee1aa97f54524f0b39e9100
[ "MIT" ]
null
null
null
src/main/java/edu/bator/cards/Ally.java
robmat/shadow_era_ai
b6ff43e9a835fe32fee1aa97f54524f0b39e9100
[ "MIT" ]
null
null
null
src/main/java/edu/bator/cards/Ally.java
robmat/shadow_era_ai
b6ff43e9a835fe32fee1aa97f54524f0b39e9100
[ "MIT" ]
null
null
null
28.957447
85
0.735489
14
package edu.bator.cards; import static java.util.Objects.nonNull; import edu.bator.cards.util.ArmorUtil; import edu.bator.cards.util.BonusUtil; import edu.bator.game.GameState; import java.util.function.BiConsumer; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class Ally extends Card { public enum Affinity { UNDEAD, WULVEN, TWILIGHT, HOMUNCULUS, TEMPLAR, RAVAGER, ALDMOR } public Ally(Card cloneFrom) { super(cloneFrom); } public void attackTarget(GameState gameState, Card target) { Card attackSource = this; BiConsumer<GameState, Card> attackEvent = (stateOfTheGame, card) -> { if (nonNull(attackSource.getAttack(stateOfTheGame)) && nonNull( target.getCurrentHp(gameState))) { target.setCurrentHp(target.currentHpWithoutBonus() - ArmorUtil .attachmentModifiesAttack(target, attackSource, gameState)); } }; attackTarget(attackEvent, target, gameState); } @Override public Integer getAttack(GameState gameState) { int attack = super.getAttack(gameState) + BonusUtil.attackBonus(gameState, this); return Math.max(attack, 0); } @Override public Integer getCurrentHp(GameState gameState) { return super.getCurrentHp(gameState) + BonusUtil.hpBonus(gameState, this); } }
3e00074f5c109f4295efc8a6e05b5127991ca12a
4,380
java
Java
src/main/java/ch/uzh/ifi/seal/soprafs20/cluechecker/ClueChecker.java
Marinolino/sopra-fs20-group11-justone-server
c88673d0aba4223126dddc53b8848994f4e93bb7
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/uzh/ifi/seal/soprafs20/cluechecker/ClueChecker.java
Marinolino/sopra-fs20-group11-justone-server
c88673d0aba4223126dddc53b8848994f4e93bb7
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/uzh/ifi/seal/soprafs20/cluechecker/ClueChecker.java
Marinolino/sopra-fs20-group11-justone-server
c88673d0aba4223126dddc53b8848994f4e93bb7
[ "Apache-2.0" ]
null
null
null
39.818182
171
0.636301
15
package ch.uzh.ifi.seal.soprafs20.cluechecker; import ch.uzh.ifi.seal.soprafs20.constant.ClueStatus; import ch.uzh.ifi.seal.soprafs20.entity.game.Clue; import ch.uzh.ifi.seal.soprafs20.entity.game.Game; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public final class ClueChecker { private ClueChecker(){ } public static Clue checkClue(Clue clueInput, Game game) throws IOException { List<String> stringClues = new ArrayList<>(); //check if the clue input is valid if (clueInput.getClueWord() == null || clueInput.getClueWord().isBlank() || clueInput.getClueWord().contains(" ") || clueInput.getClueWord().equals("OVERTIMED")) { clueInput.setValid(ClueStatus.INVALID); return clueInput; } //add all clues that are already saved in the game for (Clue existingClue : game.getClues()){ stringClues.add(existingClue.getClueWord()); } for (String clue: stringClues) { //check if the clue already exists if (checkForDuplicate(clueInput.getClueWord(), clue)) { clueInput.setValid(ClueStatus.DUPLICATE); return clueInput; } } //check if the clue is equal to the chosen word if (game.getChosenWord().equals(clueInput.getClueWord())){ clueInput.setValid(ClueStatus.INVALID); return clueInput; } //check if clue is contained in chosenWord or vice versa if (checkIfClueOrWordSubstring(clueInput.getClueWord(), game.getChosenWord())) { clueInput.setValid((ClueStatus.INVALID)); return clueInput; } //create list of homophones String str = ClueChecker.makeRequest(game.getChosenWord()); ArrayList<String> wordList = ClueChecker.makeList(str); //check if clue is homophone of chosenword for (int i = 0; i<wordList.size(); i++) { if (wordList.get(i).equalsIgnoreCase("\"" + clueInput.getClueWord() + "\"")) { clueInput.setValid(ClueStatus.INVALID); return clueInput; } } //check if clue is plural of chosenword or vice versa. if (clueInput.getClueWord().equalsIgnoreCase(game.getChosenWord() + "s") || game.getChosenWord().equalsIgnoreCase(clueInput.getClueWord() + "s")) { clueInput.setValid(ClueStatus.INVALID); return clueInput; } clueInput.setValid(ClueStatus.VALID); return clueInput; } //checks if the clue already exists //returns true if the clues are duplicates, false otherwise private static boolean checkForDuplicate(String newClue, String existingClue){ //remove all whitespaces newClue = newClue.replaceAll("\\s+",""); existingClue = existingClue.replaceAll("\\s+",""); //changes both strings to lowercase and compares them return newClue.equalsIgnoreCase(existingClue); } // private static boolean checkIfClueOrWordSubstring(String newClue, String chosenWord){ return chosenWord.toLowerCase().contains(newClue.toLowerCase()) || newClue.toLowerCase().contains(chosenWord.toLowerCase()); } private static String makeRequest(String chosenWord) throws IOException { String response; String urlString = "https://api.datamuse.com/words?rel_hom=" + chosenWord; URL url = new URL(urlString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder content = new StringBuilder(); response = content.append(in.readLine()).toString(); in.close(); return response; } private static ArrayList<String> makeList(String rawList) { String[] tempList; ArrayList<String> finalList = new ArrayList<>(); tempList = rawList.split(":|\\,"); for (int i = 0; i < tempList.length; i ++) { if ((i-1)%6 == 0) { finalList.add(tempList[i]); } } return finalList; } }
3e000777f05224fe96c01a21f5bdd9fd8113332c
1,477
java
Java
simplity/core/src/main/java/org/simplity/core/dm/field/ChildRecord.java
simplity/simplity
3d67e612c112917f8567c5ec6f00bb10e894a459
[ "MIT" ]
3
2017-02-03T05:19:53.000Z
2021-05-24T22:24:06.000Z
simplity/core/src/main/java/org/simplity/core/dm/field/ChildRecord.java
simplity/simplity
3d67e612c112917f8567c5ec6f00bb10e894a459
[ "MIT" ]
124
2016-08-27T05:14:14.000Z
2017-12-28T02:30:36.000Z
simplity/core/src/main/java/org/simplity/core/dm/field/ChildRecord.java
simplity/simplity
3d67e612c112917f8567c5ec6f00bb10e894a459
[ "MIT" ]
2
2021-11-27T10:15:25.000Z
2022-01-01T20:07:34.000Z
37.871795
86
0.758294
16
/* * Copyright (c) 2019 simplity.org * * 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, OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.simplity.core.dm.field; import org.simplity.core.dm.Record; /** * data structure that is defined in another record */ public class ChildRecord extends DataStructureField { @Override protected void resolverReference(Record parentRecord, Record defaultRefferedRecord) { /* * purpose of referred record is different here.. */ return; } }
3e00079da60ac8e4e82fc7f96273aa639647ff79
1,597
java
Java
common/src/main/java/com/styx/common/utils/convert/DateFormatUtil.java
zxwgdft/styx
1b48397d3e4f980fb6cf9d2d2a7536c74bf2199b
[ "Apache-2.0" ]
null
null
null
common/src/main/java/com/styx/common/utils/convert/DateFormatUtil.java
zxwgdft/styx
1b48397d3e4f980fb6cf9d2d2a7536c74bf2199b
[ "Apache-2.0" ]
null
null
null
common/src/main/java/com/styx/common/utils/convert/DateFormatUtil.java
zxwgdft/styx
1b48397d3e4f980fb6cf9d2d2a7536c74bf2199b
[ "Apache-2.0" ]
null
null
null
32.591837
111
0.611146
17
package com.styx.common.utils.convert; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 通过线程变量提高效率,使用jmh测试结果几乎快100倍 * <p> * 10线程 5轮测试结果如下(测试时只获取了两种format,如果format多了以后可能会稍微影响map命中率,但影响较小) * Benchmark Mode Cnt Score Error Units * thread local方式 thrpt 5 386642994.134 ± 4473165.392 ops/s * new Object方式 thrpt 5 3391447.593 ± 327200.206 ops/s */ public class DateFormatUtil { private final static Map<String, ThreadLocal<SimpleDateFormat>> threadLocalMap = new ConcurrentHashMap<>(); private static ThreadLocal<SimpleDateFormat> getThreadLocal(final String format) { ThreadLocal<SimpleDateFormat> threadLocal = threadLocalMap.get(format); if (threadLocal == null) { synchronized (threadLocalMap) { threadLocal = threadLocalMap.get(format); if (threadLocal == null) { threadLocal = new ThreadLocal<SimpleDateFormat>() { public SimpleDateFormat initialValue() { return new SimpleDateFormat(format); } }; threadLocalMap.put(format, threadLocal); } } } return threadLocal; } /** * 通过线程变量创建并获取安全的{@link SimpleDateFormat} * * @param format * @return */ public static SimpleDateFormat getThreadSafeFormat(String format) { return getThreadLocal(format).get(); } }
3e0007b700f6dcf839b5a05c1e3e30a8ec7fb680
4,907
java
Java
app/src/main/java/com/example/android/miwok/PhrasesActivity.java
DhyanSh/Miwok-Language-App
5f20e381af73c39480034cc108622ef92dec6d74
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/PhrasesActivity.java
DhyanSh/Miwok-Language-App
5f20e381af73c39480034cc108622ef92dec6d74
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/PhrasesActivity.java
DhyanSh/Miwok-Language-App
5f20e381af73c39480034cc108622ef92dec6d74
[ "Apache-2.0" ]
null
null
null
39.256
124
0.665987
18
package com.example.android.miwok; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import static android.media.AudioManager.AUDIOFOCUS_GAIN; import static android.media.AudioManager.AUDIOFOCUS_LOSS; import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT; public class PhrasesActivity extends AppCompatActivity { private MediaPlayer mediaPlayer; private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { releaseMediaPlayer(); } }; private AudioManager mAudioManager ; AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){ mediaPlayer.pause(); mediaPlayer.seekTo(0); } else if (focusChange == AUDIOFOCUS_GAIN){ mediaPlayer.start(); } else if (focusChange == AUDIOFOCUS_LOSS){ releaseMediaPlayer(); } } }; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word_list); final ArrayList<Word> words = new ArrayList<Word>(); words.add(new Word("Where are you going?","minto wuksus",R.raw.phrase_where_are_you_going)); words.add(new Word("What is your name?","tinnә oyaase'nә",R.raw.phrase_what_is_your_name)); words.add(new Word("My name is...","oyaaset...",R.raw.phrase_my_name_is)); words.add(new Word("How are you feeling?","michәksәs?",R.raw.phrase_how_are_you_feeling)); words.add(new Word("I’m feeling good.","kuchi achit",R.raw.phrase_im_feeling_good)); words.add(new Word("Are you coming?","әәnәs'aa?",R.raw.phrase_are_you_coming)); words.add(new Word("Yes, I’m coming.","hәә’ әәnәm",R.raw.phrase_yes_im_coming)); words.add(new Word("I’m coming.","әәnәm",R.raw.phrase_im_coming)); words.add(new Word("Let’s go.","yoowutis",R.raw.phrase_lets_go)); words.add(new Word("Come here.","әnni'nem",R.raw.phrase_come_here)); WordAdapter adapter = new WordAdapter(this,words,R.color.category_phrases); ListView listView =(ListView) findViewById(R.id.list); listView.setAdapter(adapter); mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { releaseMediaPlayer(); int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, // Use the music stream. AudioManager.STREAM_MUSIC, // Request permanent focus. AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // Start playback mediaPlayer = MediaPlayer.create(PhrasesActivity.this,words.get(position).getSound()); mediaPlayer.start(); mediaPlayer.setOnCompletionListener(mCompletionListener); } } }); } @Override protected void onStop() { super.onStop(); releaseMediaPlayer(); } private void releaseMediaPlayer() { // If the media player is not null, then it may be currently playing a sound. if (mediaPlayer != null) { // Regardless of the current state of the media player, release its resources // because we no longer need it. mediaPlayer.release(); // Set the media player back to null. For our code, we've decided that // setting the media player to null is an easy way to tell that the media player // is not configured to play an audio file at the moment. mediaPlayer = null; mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener); } } }
3e0008320be5f6216f1b1fa820cb0e5175d8fd42
1,079
java
Java
_nami/nami/src/test/java/feature/JsonTest.java
greenflute/noear_solon
9aa5eefaa080705cb337286bfd36719d11196dfc
[ "Apache-2.0" ]
232
2019-02-15T03:44:00.000Z
2022-03-27T08:44:51.000Z
_nami/nami/src/test/java/feature/JsonTest.java
greenflute/noear_solon
9aa5eefaa080705cb337286bfd36719d11196dfc
[ "Apache-2.0" ]
26
2019-11-21T04:47:38.000Z
2022-03-15T13:44:21.000Z
_nami/nami/src/test/java/feature/JsonTest.java
greenflute/noear_solon
9aa5eefaa080705cb337286bfd36719d11196dfc
[ "Apache-2.0" ]
31
2019-07-15T14:36:27.000Z
2022-03-13T09:59:25.000Z
27.666667
70
0.55607
19
package feature; public class JsonTest { // @Test // public void test1(){ // ISerializer serializer = new FastjsonSerializer(); // // String str1 = "\"\""; // String str11 = serializer.deserialize(str1, String.class); // assert "".equals(str11); // // String str2 = "false"; // boolean str22 = serializer.deserialize(str2, Boolean.class); // assert str22 == false; // // String str3 = "12"; // int str33 = serializer.deserialize(str3, Integer.class); // assert str33 == 12; // } // // @Test // public void test2(){ // ISerializer serializer = new SnackSerializer(); // // String str1 = "\"\""; // String str11 = serializer.deserialize(str1, String.class); // assert "".equals(str11); // // String str2 = "false"; // boolean str22 = serializer.deserialize(str2, Boolean.class); // assert str22 == false; // // String str3 = "12"; // int str33 = serializer.deserialize(str3, Integer.class); // assert str33 == 12; // } }
3e00086783cc7e9ffbd4b8902a9f12f31c193d48
1,645
java
Java
app/src/main/java/ca/lakeland/plantsd/flightlogger/Adapters/ChecklistAdapter.java
splant10/FlightLogger
40e339be29f0f82561f2d120472fb7d860a4126a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ca/lakeland/plantsd/flightlogger/Adapters/ChecklistAdapter.java
splant10/FlightLogger
40e339be29f0f82561f2d120472fb7d860a4126a
[ "Apache-2.0" ]
1
2016-07-26T20:50:15.000Z
2016-07-27T16:45:14.000Z
app/src/main/java/ca/lakeland/plantsd/flightlogger/Adapters/ChecklistAdapter.java
splant10/FlightLogger
40e339be29f0f82561f2d120472fb7d860a4126a
[ "Apache-2.0" ]
null
null
null
26.967213
92
0.645593
20
package ca.lakeland.plantsd.flightlogger.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import ca.lakeland.plantsd.flightlogger.Objects.DoneChecklist; import ca.lakeland.plantsd.flightlogger.R; /** * Created by plantsd on 6/3/2016. */ public class ChecklistAdapter extends ArrayAdapter<DoneChecklist> { List checklists; LayoutInflater vi; public ChecklistAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ChecklistAdapter(Context context, int resource, List<DoneChecklist> checklists) { super(context, resource, checklists); this.checklists = checklists; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.adapter_checklist_row, null); } DoneChecklist dc = (DoneChecklist) checklists.get(position); if (dc != null) { TextView txt1 = (TextView) v.findViewById(R.id.txtChecklistDate); if (txt1 != null) { txt1.setText(dc.getDate()); } TextView txt2 = (TextView) v.findViewById(R.id.txtChecklistAuthor); if (txt2 != null) { String auth = "Completed by " + dc.getAuthor(); txt2.setText(auth); } } return v; } }
3e00086ff391c7d666c3f0243e910b5ff9fb041a
1,061
java
Java
Ktr4j/src/main/java/com/kotor4j/materials/MaterialWithClipping.java
Otaka/Ktr4j
536e52b50b28e999cfced9b6f6b6a96b5871c168
[ "Apache-2.0" ]
null
null
null
Ktr4j/src/main/java/com/kotor4j/materials/MaterialWithClipping.java
Otaka/Ktr4j
536e52b50b28e999cfced9b6f6b6a96b5871c168
[ "Apache-2.0" ]
1
2021-02-03T19:23:06.000Z
2021-02-03T19:23:06.000Z
Ktr4j/src/main/java/com/kotor4j/materials/MaterialWithClipping.java
Otaka/Ktr4j
536e52b50b28e999cfced9b6f6b6a96b5871c168
[ "Apache-2.0" ]
null
null
null
24.674419
90
0.678605
21
package com.kotor4j.materials; import com.jme3.asset.AssetManager; import com.jme3.light.LightList; import com.jme3.material.Material; import com.jme3.material.MaterialDef; import com.jme3.renderer.RenderManager; import com.jme3.scene.Geometry; /** * @author Dmitry */ public class MaterialWithClipping extends Material { int x=0; int y=0; int width = 8000; int height = 8000; public MaterialWithClipping(MaterialDef def) { super(def); } public MaterialWithClipping(AssetManager contentMan, String defName) { super(contentMan, defName); } @Override public void render(Geometry geometry, LightList lights, RenderManager renderManager) { renderManager.getRenderer().setClipRect(x, y, width,height); super.render(geometry, lights, renderManager); renderManager.getRenderer().clearClipRect(); } public void setClipping(int x, int y, int width, int height){ this.x=x; this.y=y; this.width=width; this.height=height; } }
3e0008bc59843d8cedea2681d4f3fab3320ce950
1,156
java
Java
Chapter9/src/edu/packt/neuralnet/Neuron.java
xushjie1987/neural-networking-4j
d83fe51410355b698fca288395d78cf6ef324e6d
[ "Apache-2.0" ]
1
2017-12-30T10:43:19.000Z
2017-12-30T10:43:19.000Z
Chapter9/src/edu/packt/neuralnet/Neuron.java
xushjie1987/neural-networking-4j
d83fe51410355b698fca288395d78cf6ef324e6d
[ "Apache-2.0" ]
null
null
null
Chapter9/src/edu/packt/neuralnet/Neuron.java
xushjie1987/neural-networking-4j
d83fe51410355b698fca288395d78cf6ef324e6d
[ "Apache-2.0" ]
null
null
null
19.266667
68
0.752595
22
package edu.packt.neuralnet; import java.util.ArrayList; import java.util.Random; public class Neuron { private ArrayList<Double> listOfWeightIn; private ArrayList<Double> listOfWeightOut; private double outputValue; private double error; private double sensibility; public double initNeuron(){ Random r = new Random(); return r.nextDouble(); } public ArrayList<Double> getListOfWeightIn() { return listOfWeightIn; } public void setListOfWeightIn(ArrayList<Double> listOfWeightIn) { this.listOfWeightIn = listOfWeightIn; } public ArrayList<Double> getListOfWeightOut() { return listOfWeightOut; } public void setListOfWeightOut(ArrayList<Double> listOfWeightOut) { this.listOfWeightOut = listOfWeightOut; } public double getOutputValue() { return outputValue; } public void setOutputValue(double outputValue) { this.outputValue = outputValue; } public double getError() { return error; } public void setError(double error) { this.error = error; } public double getSensibility() { return sensibility; } public void setSensibility(double sensibility) { this.sensibility = sensibility; } }
3e00096f051c969facc1d7c76fbe60adf6bf7a9c
555
java
Java
app/src/main/java/com/felix/simplebook/database/TypeBean.java
1162242970/Bill
f9088225888d8b31445ff59253e8b13541ea5d62
[ "Apache-2.0" ]
1
2018-07-02T14:52:05.000Z
2018-07-02T14:52:05.000Z
app/src/main/java/com/felix/simplebook/database/TypeBean.java
1162242970/Bill
f9088225888d8b31445ff59253e8b13541ea5d62
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/felix/simplebook/database/TypeBean.java
1162242970/Bill
f9088225888d8b31445ff59253e8b13541ea5d62
[ "Apache-2.0" ]
null
null
null
16.323529
67
0.625225
23
package com.felix.simplebook.database; import org.litepal.crud.DataSupport; import java.io.Serializable; /** * Created by chaofei.xue on 2017/11/29. */ public class TypeBean extends DataSupport implements Serializable { private String type; private long id; public TypeBean() { } public TypeBean(String type) { this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } public long getId() { return id; } }
3e000b7176d779487eeea45d11bbb34cde912443
1,858
java
Java
core/src/main/java/com/flowci/core/user/service/UserService.java
trency92/flow-core-x
16bd725bea0b51739c07f7deade10e84797e95a9
[ "Apache-2.0" ]
886
2017-08-01T10:14:18.000Z
2020-03-23T08:53:12.000Z
core/src/main/java/com/flowci/core/user/service/UserService.java
trency92/flow-core-x
16bd725bea0b51739c07f7deade10e84797e95a9
[ "Apache-2.0" ]
118
2017-11-14T06:24:01.000Z
2020-03-23T22:19:21.000Z
core/src/main/java/com/flowci/core/user/service/UserService.java
trency92/flow-core-x
16bd725bea0b51739c07f7deade10e84797e95a9
[ "Apache-2.0" ]
107
2017-07-12T13:47:12.000Z
2020-02-28T03:36:24.000Z
23.518987
75
0.664693
24
/* * Copyright 2018 flow.ci * * 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.flowci.core.user.service; import com.flowci.core.user.domain.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Collection; import java.util.List; import java.util.Optional; /** * @author yang */ public interface UserService { /** * List all users */ Page<User> list(Pageable pageable); /** * List users by given emails */ List<User> list(Collection<String> emails); /** * Get default admin user */ Optional<User> defaultAdmin(); /** * Create default admin user */ User createDefaultAdmin(String email, String passwordOnMd5); /** * Create user by email and password; */ User create(String email, String passwordOnMd5, User.Role role); /** * Get user by email */ User getByEmail(String email); /** * Change password for current user */ void changePassword(String old, String newOne); /** * Change role for target user * @param email target user email * @param newRole new role will be change */ void changeRole(String email, User.Role newRole); /** * Delete user by email */ User delete(String email); }
3e000bd6a1f5d0ba3a2cb539e970729b1a5f5f6c
9,540
java
Java
src/test/java/org/jsoup/select/TraversorTest.java
JsoupMaster/jsoup
cb0f4d2823cb39a3c6af2797b5906115aff94e7b
[ "MIT" ]
null
null
null
src/test/java/org/jsoup/select/TraversorTest.java
JsoupMaster/jsoup
cb0f4d2823cb39a3c6af2797b5906115aff94e7b
[ "MIT" ]
5
2019-11-02T04:59:21.000Z
2019-12-06T02:49:41.000Z
src/test/java/org/jsoup/select/TraversorTest.java
JsoupMaster/jsoup
cb0f4d2823cb39a3c6af2797b5906115aff94e7b
[ "MIT" ]
null
null
null
41.12069
106
0.557023
25
package org.jsoup.select; import static org.junit.Assert.assertEquals; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Node; import org.junit.Test; public class TraversorTest { // Note: NodeTraversor.traverse(new NodeVisitor) is tested in // ElementsTest#traverse() @Test public void HeadToTailFilterVisit() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new HeadToTailTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { accum.append("<").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { accum.append("</").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.toString()); } @Test public void HeadToTailFilterSkipChildren() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new HeadToTailTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { accum.append("<").append(node.nodeName()).append(">"); // OMIT contents of p: return ("p".equals(node.nodeName())) ? FilterResult.SKIP_CHILDREN : FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { accum.append("</").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("<div><p></p></div><div><#text></#text></div>", accum.toString()); } @Test public void HeadToTailFilterSkipEntirely() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new HeadToTailTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { // OMIT p: if ("p".equals(node.nodeName())) return FilterResult.SKIP_ENTIRELY; accum.append("<").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { accum.append("</").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("<div></div><div><#text></#text></div>", accum.toString()); } @Test public void HeadToTailFilterRemove() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There be <b>bold</b></div>"); NodeTraversor nodeTraversor = new HeadToTailTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { // Delete "p" in head: return ("p".equals(node.nodeName())) ? FilterResult.REMOVE : FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { // Delete "b" in tail: return ("b".equals(node.nodeName())) ? FilterResult.REMOVE : FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("<div></div>\n<div>\n There be \n</div>", doc.select("body").html()); } @Test public void HeadToTailFilterStop() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new HeadToTailTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { accum.append("<").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { accum.append("</").append(node.nodeName()).append(">"); // Stop after p. return ("p".equals(node.nodeName())) ? FilterResult.STOP : FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("<div><p><#text></#text></p>", accum.toString()); } @Test public void TailToHeadFilterVisit() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new TailToHeadTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { accum.append("<").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { accum.append("</").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("</div></#text><#text><div></div></p></#text><#text><p><div>", accum.toString()); } @Test public void TailToHeadFilterSkipChildren() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new TailToHeadTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { accum.append("<").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { accum.append("</").append(node.nodeName()).append(">"); // OMIT contents of p: return ("p".equals(node.nodeName())) ? FilterResult.SKIP_CHILDREN : FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("</div></#text><#text><div></div></p><p><div>", accum.toString()); } @Test public void TailToHeadFilterSkipEntirely() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new TailToHeadTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { accum.append("<").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { // OMIT p: if ("p".equals(node.nodeName())) return FilterResult.SKIP_ENTIRELY; accum.append("</").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("</div></#text><#text><div></div><div>", accum.toString()); } @Test public void TailToHeadFilterRemove() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There be <b>bold</b></div>"); NodeTraversor nodeTraversor = new TailToHeadTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { // Delete "p" in head: return ("p".equals(node.nodeName())) ? FilterResult.REMOVE : FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { // Delete "b" in tail: return ("b".equals(node.nodeName())) ? FilterResult.REMOVE : FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("<div></div>\n<div>\n There be \n</div>", doc.select("body").html()); } @Test public void TailToHeadFilterStop() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); NodeTraversor nodeTraversor = new TailToHeadTraversor(); nodeTraversor.filter(new NodeFilter() { @Override public FilterResult head(Node node, int depth) { accum.append("<").append(node.nodeName()).append(">"); return FilterResult.CONTINUE; } @Override public FilterResult tail(Node node, int depth) { accum.append("</").append(node.nodeName()).append(">"); // Stop after p. return ("p".equals(node.nodeName())) ? FilterResult.STOP : FilterResult.CONTINUE; } }, doc.select("div")); assertEquals("</div></#text><#text><div></div></p>", accum.toString()); } }
3e000bf238a10149c57c7bdf18cc19f448de5a84
189
java
Java
src/main/java/ru/devsand/eventregistrator/collection/QueueProcessor.java
kisliakovsky/EventRegistrator
b51e310e62fe0f9437651d571c0e863e6ca55084
[ "MIT" ]
null
null
null
src/main/java/ru/devsand/eventregistrator/collection/QueueProcessor.java
kisliakovsky/EventRegistrator
b51e310e62fe0f9437651d571c0e863e6ca55084
[ "MIT" ]
null
null
null
src/main/java/ru/devsand/eventregistrator/collection/QueueProcessor.java
kisliakovsky/EventRegistrator
b51e310e62fe0f9437651d571c0e863e6ca55084
[ "MIT" ]
null
null
null
23.625
76
0.798942
26
package ru.devsand.eventregistrator.collection; import java.util.Queue; import java.util.function.Consumer; public interface QueueProcessor<E, Q extends Queue<E>> extends Consumer<Q> { }
3e000c5ae04f16290cd51ad3deef75db1cf6c16e
1,255
java
Java
analyzed_libs/jdk1.6.0_06_src/java/util/UnknownFormatFlagsException.java
jgaltidor/VarJ
3a25102f8a1a406f5e458cb7d8945cc33b6a4fea
[ "MIT" ]
1
2017-01-26T20:25:00.000Z
2017-01-26T20:25:00.000Z
analyzed_libs/jdk1.6.0_06_src/java/util/UnknownFormatFlagsException.java
jgaltidor/VarJ
3a25102f8a1a406f5e458cb7d8945cc33b6a4fea
[ "MIT" ]
null
null
null
analyzed_libs/jdk1.6.0_06_src/java/util/UnknownFormatFlagsException.java
jgaltidor/VarJ
3a25102f8a1a406f5e458cb7d8945cc33b6a4fea
[ "MIT" ]
null
null
null
24.134615
74
0.663745
27
/* * @(#)UnknownFormatFlagsException.java 1.3 05/11/17 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.util; /** * Unchecked exception thrown when an unknown flag is given. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * * @version 1.3, 11/17/05 * @since 1.5 */ public class UnknownFormatFlagsException extends IllegalFormatException { private static final long serialVersionUID = 19370506L; private String flags; /** * Constructs an instance of this class with the specified flags. * * @param f * The set of format flags which contain an unknown flag */ public UnknownFormatFlagsException(String f) { if (f == null) throw new NullPointerException(); this.flags = f; } /** * Returns the set of flags which contains an unknown flag. * * @return The flags */ public String getFlags() { return flags; } // javadoc inherited from Throwable.java public String getMessage() { return "Flags = " + flags; } }
3e000c888945ca3a23fab6ee444fd5365c89522f
1,038
java
Java
elide-datastore/elide-datastore-aggregation/src/main/java/com/yahoo/elide/datastores/aggregation/annotation/Join.java
vandanabhandari/elide
e891dec78d7a2e0639691c404b33e666b131b2b9
[ "Apache-2.0" ]
936
2015-10-16T21:27:51.000Z
2022-03-28T01:34:06.000Z
elide-datastore/elide-datastore-aggregation/src/main/java/com/yahoo/elide/datastores/aggregation/annotation/Join.java
vandanabhandari/elide
e891dec78d7a2e0639691c404b33e666b131b2b9
[ "Apache-2.0" ]
1,613
2015-10-16T19:16:19.000Z
2022-03-24T21:17:44.000Z
elide-datastore/elide-datastore-aggregation/src/main/java/com/yahoo/elide/datastores/aggregation/annotation/Join.java
vandanabhandari/elide
e891dec78d7a2e0639691c404b33e666b131b2b9
[ "Apache-2.0" ]
261
2015-10-16T18:14:35.000Z
2022-03-28T01:34:13.000Z
28.054054
106
0.691715
28
/* * Copyright 2020, Yahoo Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE file in project root for terms. */ package com.yahoo.elide.datastores.aggregation.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Join { /** * Join ON clause constraint for customizing relationship joins. {{..}} is used for column references. * * @return join constraint like <code>{{col1}} = {{joinField.col2}}</code> */ String value(); /** * Join type. * @return join type like {@code left, inner, full or cross} */ JoinType type() default JoinType.LEFT; /** * Whether this joins to one or to many rows. * @return true if it joins to one row. */ boolean toOne() default false; }
3e000d0d8de064a8075ff2b3721ff5f7a70ec9d3
181
java
Java
src/main/java/com/imbus/bank/announcementModule/bo/AnnouncementBo.java
kitman0000/BankManagementSystem
ef8fcb845e85a7b466a43306e74c2db1468e1f91
[ "MIT" ]
null
null
null
src/main/java/com/imbus/bank/announcementModule/bo/AnnouncementBo.java
kitman0000/BankManagementSystem
ef8fcb845e85a7b466a43306e74c2db1468e1f91
[ "MIT" ]
null
null
null
src/main/java/com/imbus/bank/announcementModule/bo/AnnouncementBo.java
kitman0000/BankManagementSystem
ef8fcb845e85a7b466a43306e74c2db1468e1f91
[ "MIT" ]
null
null
null
13.923077
45
0.734807
29
package com.imbus.bank.announcementModule.bo; import lombok.Data; @Data public class AnnouncementBo { private int id; private String title; private String author; }
3e000d97d09692cce3e1084fd67331a4eb9e4545
5,827
java
Java
open-metadata-implementation/access-services/subject-area/subject-area-api/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/properties/classifications/Folder.java
JPWKU/egeria
4dc404fd1b077c39a90e50fb195fb4977314ba5c
[ "Apache-2.0" ]
null
null
null
open-metadata-implementation/access-services/subject-area/subject-area-api/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/properties/classifications/Folder.java
JPWKU/egeria
4dc404fd1b077c39a90e50fb195fb4977314ba5c
[ "Apache-2.0" ]
null
null
null
open-metadata-implementation/access-services/subject-area/subject-area-api/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/properties/classifications/Folder.java
JPWKU/egeria
4dc404fd1b077c39a90e50fb195fb4977314ba5c
[ "Apache-2.0" ]
null
null
null
40.186207
138
0.728334
30
/* SPDX-License-Identifier: Apache-2.0 */ package org.odpi.openmetadata.accessservices.subjectarea.properties.classifications; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.odpi.openmetadata.accessservices.subjectarea.properties.classifications.Classification; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.EnumPropertyValue; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.MapPropertyValue; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.PrimitivePropertyValue; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceProperties; import org.odpi.openmetadata.accessservices.subjectarea.ffdc.exceptions.InvalidParameterException; import java.io.Serializable; import java.util.*; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonProperty; import org.odpi.openmetadata.accessservices.subjectarea.properties.enums.*; /** * Defines that a collection should be treated like a file folder. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class Folder extends Classification { private static final Logger log = LoggerFactory.getLogger( Folder.class); private static final String className = Folder.class.getName(); private Map<String, Object> extraAttributes; public static final String[] PROPERTY_NAMES_SET_VALUES = new String[] { "orderBy", "otherPropertyName", // Terminate the list null }; public static final String[] ATTRIBUTE_NAMES_SET_VALUES = new String[] { "otherPropertyName", // Terminate the list null }; public static final String[] ENUM_NAMES_SET_VALUES = new String[] { "orderBy", // Terminate the list null }; public static final String[] MAP_NAMES_SET_VALUES = new String[] { // Terminate the list null }; // note the below definitions needs to be fully qualified public static final java.util.Set<String> PROPERTY_NAMES_SET = new HashSet(new HashSet<>(Arrays.asList(PROPERTY_NAMES_SET_VALUES))); public static final java.util.Set<String> ATTRIBUTE_NAMES_SET = new HashSet(new HashSet<>(Arrays.asList(ATTRIBUTE_NAMES_SET_VALUES))); public static final java.util.Set<String> ENUM_NAMES_SET = new HashSet(new HashSet<>(Arrays.asList(ENUM_NAMES_SET_VALUES))); public static final java.util.Set<String> MAP_NAMES_SET = new HashSet(new HashSet<>(Arrays.asList(MAP_NAMES_SET_VALUES))); /** * Default constructor */ public Folder() { super.classificationName="Folder"; } @Override public InstanceProperties obtainInstanceProperties() { final String methodName = "obtainInstanceProperties"; if (log.isDebugEnabled()) { log.debug("==> Method: " + methodName); } InstanceProperties instanceProperties = new InstanceProperties(); EnumPropertyValue enumPropertyValue=null; enumPropertyValue = new EnumPropertyValue(); // definition for how elements in the collection should be ordered. if (orderBy !=null) { enumPropertyValue.setOrdinal(orderBy.ordinal()); enumPropertyValue.setSymbolicName(orderBy.name()); instanceProperties.setProperty("orderBy",enumPropertyValue); } MapPropertyValue mapPropertyValue=null; PrimitivePropertyValue primitivePropertyValue=null; primitivePropertyValue = new PrimitivePropertyValue(); primitivePropertyValue.setPrimitiveValue(otherPropertyName); instanceProperties.setProperty("otherPropertyName",primitivePropertyValue); if (log.isDebugEnabled()) { log.debug("<== Method: " + methodName); } return instanceProperties; } private OrderBy orderBy; /** * {@literal Definition for how elements in the collection should be ordered. } * @return {@code OrderBy } */ public OrderBy getOrderBy() { return this.orderBy; } public void setOrderBy(OrderBy orderBy) { this.orderBy = orderBy; } private String otherPropertyName; /** * {@literal Name of property to use for ordering. } * @return {@code String } */ public String getOtherPropertyName() { return this.otherPropertyName; } public void setOtherPropertyName(String otherPropertyName) { this.otherPropertyName = otherPropertyName; } /** * Get the extra attributes - ones that are in addition to the standard types. * @return extra attributes */ public Map<String, Object> getExtraAttributes() { return extraAttributes; } public void setExtraAttributes(Map<String, Object> extraAttributes) { this.extraAttributes = extraAttributes; } }
3e000e81bfb27945fe5c5a4dcfdee101299a56f0
8,721
java
Java
src/main/java/org/usfirst/frc/team4944/robot/custom/XboxController.java
EmperorPopo/2020-robot-code-Imported
7e9bf1ee133b93ddfbe77ef0d0c42a871ccf2c23
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/usfirst/frc/team4944/robot/custom/XboxController.java
EmperorPopo/2020-robot-code-Imported
7e9bf1ee133b93ddfbe77ef0d0c42a871ccf2c23
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/usfirst/frc/team4944/robot/custom/XboxController.java
EmperorPopo/2020-robot-code-Imported
7e9bf1ee133b93ddfbe77ef0d0c42a871ccf2c23
[ "BSD-3-Clause" ]
null
null
null
19.77551
104
0.695562
31
package org.usfirst.frc.team4944.robot.custom; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.buttons.POVButton; import edu.wpi.first.wpilibj.command.Command; /* * When Creating a new XboxController: XboxController controller = new XboxController(Port#); * * This class allows you to add commands to every button on the Xbox controller : * controller.addCommandToA(Command c); * * While also providing the means to check the values for every form of input on the * controller : controller.getBUTTONNAMEButton() (ex: controller.getAButton();) * * USE THIS INSTEAD OF A JOYSTICK */ public class XboxController extends Joystick { Button A, B, X, Y, leftBumper, rightBumper, leftMenu, rightMenu, leftStick, rightStick; POVButton dpad0, dpad45, dpad90, dpad135, dpad180, dpad225, dpad270, dpad315; Boolean AToggle, BToggle, XToggle, YToggle, RBToggle, LBToggle, RTToggle, LTToggle, LMToggle, RMToggle; Boolean prevA, prevB, prevX, prevY, prevRB, prevLB, prevRT, prevLT; Button leftTrig, rightTrig; public XboxController(int port) { super(port); this.A = new JoystickButton(this, 1); this.B = new JoystickButton(this, 2); this.X = new JoystickButton(this, 3); this.Y = new JoystickButton(this, 4); this.leftBumper = new JoystickButton(this, 5); this.rightBumper = new JoystickButton(this, 6); this.leftMenu = new JoystickButton(this, 7); this.rightMenu = new JoystickButton(this, 8); this.leftStick = new JoystickButton(this, 9); this.rightStick = new JoystickButton(this, 10); this.AToggle = false; this.BToggle = false; this.XToggle = false; this.YToggle = false; this.RBToggle = false; this.LBToggle = false; this.RTToggle = false; this.LTToggle = false; this.LMToggle = false; this.RMToggle = false; this.rightTrig = new Button() { @Override public boolean get() { return getRawAxis(3) > 0.75; } }; this.leftTrig = new Button() { @Override public boolean get() { return getRawAxis(2) > 0.75; } }; } // A BUTTON public boolean getAButton() { return this.getRawButton(1); } public void toggleAButton() { if (this.AToggle) { this.AToggle = false; } else if (!this.AToggle) { this.AToggle = true; } } public boolean getAToggle() { if (this.AToggle) { return true; } else { return false; } } public void addCommandToA(Command c) { A.whenActive(c); } public void addWhenReleasedToA(Command c) { A.whenReleased(c); } public void addWhenHeldToA(Command c) { A.whileHeld(c); } public void addWhenPressedToA(Command c) { A.whenPressed(c); } // B BUTTON public boolean getBButton() { return this.getRawButton(2); } public void toggleBButton() { if (this.BToggle) { this.BToggle = false; } else if (!this.BToggle) { this.BToggle = true; } } public boolean getBToggle() { if (this.BToggle) { return true; } else { return false; } } public void addCommandToB(Command c) { B.whenActive(c); } public void addWhenReleasedToB(Command c) { B.whenReleased(c); } public void addWhenHeldToB(Command c) { B.whileHeld(c); } public void addWhenPressedToB(Command c) { B.whenPressed(c); } // X BUTTON public boolean getXButton() { return this.getRawButton(3); } public void toggleXButton() { if (this.XToggle) { this.XToggle = false; } else if (!this.XToggle) { this.XToggle = true; } } public boolean getXToggle() { if (this.XToggle) { return true; } else { return false; } } public void addCommandToX(Command c) { X.whenActive(c); } public void addWhenReleasedToX(Command c) { X.whenReleased(c); } public void addWhenHeldToX(Command c) { X.whileHeld(c); } public void addWhenPressedToX(Command c) { X.whenPressed(c); } // Y BUTTON public boolean getYButton() { return this.getRawButton(4); } public void toggleYButton() { if (this.YToggle) { this.YToggle = false; } else if (!this.YToggle) { this.YToggle = true; } } public boolean getYToggle() { if (this.YToggle) { return true; } else { return false; } } public void addCommandToY(Command c) { Y.whenActive(c); } public void addWhenReleasedToY(Command c) { Y.whenReleased(c); } public void addWhenHeldToY(Command c) { Y.whileHeld(c); } public void addWhenPressedToY(Command c) { Y.whenPressed(c); } // LEFT BUMPER public boolean getLeftBumper() { return this.getRawButton(5); } public void toggleLeftBumper() { if (this.LBToggle) { this.LBToggle = false; } else if (!this.LBToggle) { this.LBToggle = true; } } public boolean getLBToggle() { if (this.LBToggle) { return true; } else { return false; } } public void addCommandToLeftBumper(Command c) { leftBumper.whenActive(c); } public void addWhenReleasedToLeftBumper(Command c) { leftBumper.whenReleased(c); } public void addWhenHeldToLeftBumper(Command c) { leftBumper.whileHeld(c); } public void addWhenPressedToLeftBumper(Command c) { leftBumper.whenPressed(c); } // RIGHT BUMPER public boolean getRightBumper() { return this.getRawButton(6); } public void toggleRightBumper() { if (this.RBToggle) { this.RBToggle = false; } else if (!this.RBToggle) { this.RBToggle = true; } } public boolean getRBToggle() { if (this.RBToggle) { return true; } else { return false; } } public void addCommandToRightBumper(Command c) { rightBumper.whenActive(c); } public void addWhenReleasedToRightBumper(Command c) { rightBumper.whenReleased(c); } public void addWhenHeldToRightBumper(Command c) { rightBumper.whileHeld(c); } public void addWhenPressedToRightBumper(Command c) { rightBumper.whenPressed(c); } // LEFT MENU BUTTON public boolean getLeftMenu() { return this.getRawButton(7); } public void toggleLeftMenu() { if (this.LMToggle) { this.LMToggle = false; } else if (!this.LMToggle) { this.LMToggle = true; } } public boolean getLMToggle() { if (this.LMToggle) { return true; } else { return false; } } public void addCommandToLeftMenu(Command c) { leftMenu.whenActive(c); } public void addWhenReleasedToLeftMenu(Command c) { leftMenu.whenReleased(c); } public void addWhenHeldToLeftMenu(Command c) { leftMenu.whileHeld(c); } public void addWhenPressedToLeftMenu(Command c) { leftMenu.whenPressed(c); } // RIGHT MENU BUTTON public boolean getRightMenu() { return this.getRawButton(8); } public void toggleRightMenu() { if (this.RMToggle) { this.RMToggle = false; } else if (!this.RMToggle) { this.RMToggle = true; } } public boolean getRMToggle() { if (this.RMToggle) { return true; } else { return false; } } public void addCommandToRightMenu(Command c) { rightMenu.whenActive(c); } public void addWhenReleasedToRightMenu(Command c) { rightMenu.whenReleased(c); } public void addWhenHeldToRightMenu(Command c) { rightMenu.whileHeld(c); } public void addWhenPressedToRightMenu(Command c) { rightMenu.whenPressed(c); } // LEFT STICK BUTTON public void addCommandToLeftStick(Command c) { leftStick.whenPressed(c); } public boolean getLeftStickButton() { return this.getRawButton(9); } // RIGHT STICK BUTTON public void addCommandToRightStick(Command c) { rightStick.whenPressed(c); } public boolean getRightStickButton() { return this.getRawButton(10); } // LEFT TRIGGER public double getLeftTriggerAnalog() { return this.getRawAxis(2); } public boolean getLeftTriggerDown() { return this.getLeftTriggerAnalog() >= 0.75; } public void addWhenPressedToLeftTrigger(Command c) { this.leftTrig.whenPressed(c); } public void addWhenReleasedToLeftTrigger(Command c) { this.leftTrig.whenReleased(c); } public void addWhenHeldToLeftTrigger(Command c) { this.leftTrig.whileHeld(c); } // RIGHT TRIGGER public double getRightTriggerAnalog() { return this.getRawAxis(3); } public boolean getRightTriggerDown() { return this.getRightTriggerAnalog() >= 0.75; } public void addWhenPressedToRightTrigger(Command c) { this.rightTrig.whenPressed(c); } public void addWhenReleasedToRightTrigger(Command c) { this.rightTrig.whenReleased(c); } public void addWhenHeldRightTrigger(Command c) { this.rightTrig.whileHeld(c); } // LEFT STICK public double getLeftStickX() { return this.getRawAxis(0); } public double getLeftStickY() { return this.getRawAxis(1); } // RIGHT STICK public double getRightStickX() { return this.getRawAxis(4); } public double getRightStickY() { return this.getRawAxis(5); } }
3e000f05d2c5fc639dd99e36c1ac46aa1298c02c
672
java
Java
openTCS-CommAdapter-Serial/src/guiceConfig/java/com/lvsrobot/serial/SerialAdapterKernelInjectionModule.java
touchmii/OpenTCS-4
e3973bd72da63011369a1935de7303bf11bc2a1f
[ "MIT" ]
21
2021-07-31T09:35:59.000Z
2022-03-25T18:23:45.000Z
openTCS-CommAdapter-Serial/src/guiceConfig/java/com/lvsrobot/serial/SerialAdapterKernelInjectionModule.java
wmhui007/OpenTCS-4
768dc0aebf63b5ac79f869dabcb35f9ebfb4deee
[ "MIT" ]
2
2021-01-21T12:39:47.000Z
2021-07-29T09:56:22.000Z
openTCS-CommAdapter-Serial/src/guiceConfig/java/com/lvsrobot/serial/SerialAdapterKernelInjectionModule.java
wmhui007/OpenTCS-4
768dc0aebf63b5ac79f869dabcb35f9ebfb4deee
[ "MIT" ]
17
2020-09-24T00:09:50.000Z
2021-07-07T12:20:41.000Z
32
104
0.796131
32
/** * Copyright (c) Fraunhofer IML */ package com.lvsrobot.serial; import com.google.inject.assistedinject.FactoryModuleBuilder; import org.opentcs.customizations.kernel.KernelInjectionModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SerialAdapterKernelInjectionModule extends KernelInjectionModule { private static final Logger LOG = LoggerFactory.getLogger(SerialAdapterKernelInjectionModule.class); @Override protected void configure() { install(new FactoryModuleBuilder().build(ExampleAdapterComponentsFactory.class)); vehicleCommAdaptersBinder().addBinding().to(ExampleCommAdapterFactory.class); } }
3e000fdf723be691e486a4c3d393134ddd4e02ac
679
java
Java
client/eu-client-service/src/main/java/com/mkl/eu/client/service/vo/enumeration/SiegeUndermineResultEnum.java
BAMGames/eu
d1eb2c8cfc45252285a1b1c1293071b464536ac3
[ "MIT" ]
2
2019-08-21T21:21:20.000Z
2019-11-24T15:43:20.000Z
client/eu-client-service/src/main/java/com/mkl/eu/client/service/vo/enumeration/SiegeUndermineResultEnum.java
BAMGames/eu
d1eb2c8cfc45252285a1b1c1293071b464536ac3
[ "MIT" ]
12
2019-11-14T10:22:15.000Z
2022-02-01T00:58:02.000Z
client/eu-client-service/src/main/java/com/mkl/eu/client/service/vo/enumeration/SiegeUndermineResultEnum.java
BAMGames/eu
d1eb2c8cfc45252285a1b1c1293071b464536ac3
[ "MIT" ]
2
2016-03-10T17:45:36.000Z
2017-04-12T13:56:55.000Z
30.863636
105
0.683358
33
package com.mkl.eu.client.service.vo.enumeration; /** * Enumeration of status for sieges. * * @author MKL */ public enum SiegeUndermineResultEnum { /** Siegework minus. Siege will go on. */ SIEGE_WORK_MINUS, /** Siegework plus. Siege will go on. */ SIEGE_WORK_PLUS, /** Breach. Besieger had a breach and will immediately perform an assault and maybe end the siege. */ BREACH_TAKEN, /** Breach. Besieger had a breach but choose not to use it immediately. */ BREACH_NOT_TAKEN, /** The fortress falls but any troop inside are given back. The siege ends. */ WAR_HONOUR, /** The fortress surrenders. The siege ends. */ SURRENDER }
3e0010296eca4684b30359cd700b455fc3a4528a
4,928
java
Java
src/main/java/org/everit/atlassian/restclient/jiracloud/v2/model/FieldLastUsed.java
BorvizRobi/atlassian-restclient-jiracloud
28a81e5b38ad6a34407d7e58ea0ec07eca510ba8
[ "Apache-2.0" ]
null
null
null
src/main/java/org/everit/atlassian/restclient/jiracloud/v2/model/FieldLastUsed.java
BorvizRobi/atlassian-restclient-jiracloud
28a81e5b38ad6a34407d7e58ea0ec07eca510ba8
[ "Apache-2.0" ]
null
null
null
src/main/java/org/everit/atlassian/restclient/jiracloud/v2/model/FieldLastUsed.java
BorvizRobi/atlassian-restclient-jiracloud
28a81e5b38ad6a34407d7e58ea0ec07eca510ba8
[ "Apache-2.0" ]
null
null
null
29.195266
274
0.676125
34
/* * Copyright © 2011 Everit Kft. (http://www.everit.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. */ /* * The Jira Cloud platform REST API * Jira Cloud platform REST API documentation * * The version of the OpenAPI document: 1001.0.0-SNAPSHOT * Contact: envkt@example.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.everit.atlassian.restclient.jiracloud.v2.model; import java.util.Objects; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; /** * Information about the most recent use of a field. */ @ApiModel(description = "Information about the most recent use of a field.") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-10-28T14:12:34.799+01:00[Europe/Prague]") public class FieldLastUsed { /** * Last used value type: * *TRACKED*: field is tracked and a last used date is available. * *NOT\\_TRACKED*: field is not tracked, last used date is not available. * *NO\\_INFORMATION*: field is tracked, but no last used date is available. */ public enum TypeEnum { TRACKED("TRACKED"), NOT_TRACKED("NOT_TRACKED"), NO_INFORMATION("NO_INFORMATION"); private String value; TypeEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static TypeEnum fromValue(String value) { for (TypeEnum b : TypeEnum.values()) { if (b.value.equalsIgnoreCase(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } @JsonProperty("type") private TypeEnum type; @JsonProperty("value") private OffsetDateTime value; public FieldLastUsed type(TypeEnum type) { this.type = type; return this; } /** * Last used value type: * *TRACKED*: field is tracked and a last used date is available. * *NOT\\_TRACKED*: field is not tracked, last used date is not available. * *NO\\_INFORMATION*: field is tracked, but no last used date is available. * @return type **/ @ApiModelProperty(value = "Last used value type: * *TRACKED*: field is tracked and a last used date is available. * *NOT\\_TRACKED*: field is not tracked, last used date is not available. * *NO\\_INFORMATION*: field is tracked, but no last used date is available.") public TypeEnum getType() { return type; } public void setType(TypeEnum type) { this.type = type; } public FieldLastUsed value(OffsetDateTime value) { this.value = value; return this; } /** * The date when the value of the field last changed. * @return value **/ @ApiModelProperty(value = "The date when the value of the field last changed.") public OffsetDateTime getValue() { return value; } public void setValue(OffsetDateTime value) { this.value = value; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FieldLastUsed fieldLastUsed = (FieldLastUsed) o; return Objects.equals(this.type, fieldLastUsed.type) && Objects.equals(this.value, fieldLastUsed.value); } @Override public int hashCode() { return Objects.hash(type, value); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class FieldLastUsed {\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" value: ").append(toIndentedString(value)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0010312e6c2daea5c628e0f90ca17d4a45ec06
431
java
Java
src/test/java/com/github/xuqplus/hi/leetcode/q1200/q1202/ATest.java
xuqplus/hi-leetcode
c1c6ce860393ff2179ccd23ddfb13901881d61de
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/xuqplus/hi/leetcode/q1200/q1202/ATest.java
xuqplus/hi-leetcode
c1c6ce860393ff2179ccd23ddfb13901881d61de
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/xuqplus/hi/leetcode/q1200/q1202/ATest.java
xuqplus/hi-leetcode
c1c6ce860393ff2179ccd23ddfb13901881d61de
[ "Apache-2.0" ]
null
null
null
16.576923
63
0.62645
35
package com.github.xuqplus.hi.leetcode.q1200.q1202; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; /** * 交换字符串中的元素 * medium * https://leetcode-cn.com/problems/smallest-string-with-swaps/ */ @Slf4j public class ATest { @Test void a() { Solution solution = new Solution(); log.info("{}", solution.run()); } } class Solution { public int run() { return 0; } }
3e0013263a6f25d3e40f41681677af285edb0738
2,169
java
Java
kodejava-lang-package/src/main/java/org/kodejava/example/lang/LoadResourceFile.java
kodejava/kodejava.project
a99fdbbf5a0bca6c79dd1ee2b520d74f1d9d13d4
[ "BSD-2-Clause" ]
null
null
null
kodejava-lang-package/src/main/java/org/kodejava/example/lang/LoadResourceFile.java
kodejava/kodejava.project
a99fdbbf5a0bca6c79dd1ee2b520d74f1d9d13d4
[ "BSD-2-Clause" ]
3
2020-06-18T15:53:00.000Z
2021-12-09T20:36:34.000Z
kodejava-lang-package/src/main/java/org/kodejava/example/lang/LoadResourceFile.java
kodejava/kodejava.project
a99fdbbf5a0bca6c79dd1ee2b520d74f1d9d13d4
[ "BSD-2-Clause" ]
null
null
null
41.711538
76
0.687875
36
package org.kodejava.example.lang; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; public class LoadResourceFile { public static void main(String[] args) throws Exception { LoadResourceFile demo = new LoadResourceFile(); demo.loadUsingClassMethod(); demo.loadUsingClassLoaderMethod(); } private void loadUsingClassMethod() throws IOException { System.out.println("LoadResourceFile.loadUsingClassMethod"); Properties properties = new Properties(); // Load resource relatively to the LoadResourceFile package. // This actually load resource from // "/org/kodejava/example/lang/database.conf". URL resource = getClass().getResource("database.conf"); properties.load(new FileReader(new File(resource.getFile()))); System.out.println("JDBC Driver: " + properties.get("jdbc.driver")); // Load resource using absolute name. This will read resource // from the root of the package. This will load "/database.conf". InputStream is = getClass().getResourceAsStream("/database.conf"); properties.load(is); System.out.println("JDBC Driver: " + properties.get("jdbc.driver")); } private void loadUsingClassLoaderMethod() throws IOException { System.out.println("LoadResourceFile.loadUsingClassLoaderMethod"); Properties properties = new Properties(); // When using the ClassLoader method the resource name should // not started with "/". This method will not apply any // absolute/relative transformation to the resource name. ClassLoader classLoader = getClass().getClassLoader(); URL resource = classLoader.getResource("database.conf"); properties.load(new FileReader(new File(resource.getFile()))); System.out.println("JDBC URL: " + properties.get("jdbc.url")); InputStream is = classLoader.getResourceAsStream("database.conf"); properties.load(is); System.out.println("JDBC URL: " + properties.get("jdbc.url")); } }
3e00135347787f671945fb1217c0e23a2685d3fb
7,458
java
Java
src/main/java/com/moon/core/lang/CharUtil.java
moon-util/moon-util
28c5cb418861da4d0a5a035a3de919b86b939c0e
[ "MIT" ]
5
2019-04-30T09:23:32.000Z
2022-01-04T05:28:43.000Z
src/main/java/com/moon/core/lang/CharUtil.java
moon-util/moon-util
28c5cb418861da4d0a5a035a3de919b86b939c0e
[ "MIT" ]
7
2020-09-08T07:47:18.000Z
2022-01-04T16:47:25.000Z
src/main/java/com/moon/core/lang/CharUtil.java
moon-util/moon-util
28c5cb418861da4d0a5a035a3de919b86b939c0e
[ "MIT" ]
1
2022-01-04T05:28:49.000Z
2022-01-04T05:28:49.000Z
25.895833
111
0.496246
37
package com.moon.core.lang; import java.util.Objects; import static com.moon.core.lang.ThrowUtil.noInstanceError; /** * @author moonsky */ public final class CharUtil { private CharUtil() { noInstanceError(); } /** * 字符片段是否相等 * * @param src 字符数组 1 * @param srcStart 起始位置 * @param srcEnd 结束位置 * @param dest 字符数组 2 * @param destStart 起始位置 * @param destEnd 结束位置 * * @return 如果两个字符数组指定片段内的内容相同返回 true,否则返回 false */ public static boolean isRegionMatches( char[] src, int srcStart, int srcEnd, char[] dest, int destStart, int destEnd ) { int srcCnt = srcEnd - srcStart, destCnt = destEnd - destStart; if (srcCnt != destCnt || srcStart < 0 || destStart < 0) { return false; } int srcLen = src.length; if (srcEnd >= srcLen) { return false; } int destLen = dest.length; if (destEnd >= destLen) { return false; } for (int i = 0; i < srcCnt; i++) { if (src[srcStart + i] != dest[destStart + i]) { return false; } } return true; } /** * 字符片段是否相等 * <p> * 这个方法默认由调用方保证索引位置安全 * * @param src 字符数组 1 * @param srcStart 起始位置 * @param dest 字符数组 2 * @param destStart 起始位置 * * @return 如果两个字符数组指定片段内的内容相同返回 true,否则返回 false */ public static boolean isSafeRegionMatches(char[] src, int srcStart, char[] dest, int destStart) { int count = dest.length - destStart; if (srcStart + count <= src.length) { for (int i = 0; i < count; i++) { if (src[srcStart + i] != dest[destStart + i]) { return false; } } return true; } return false; } public static int indexOf(final char[] src, final char[] test) { return indexOf(src, test, 0); } public static int indexOf(final char[] src, final char[] test, int fromIndex) { BooleanUtil.requireFalse(fromIndex < 0); if (src == test) { return fromIndex > 0 ? -1 : 0; } final int l1 = src.length, l2 = test.length; if (fromIndex == l1) { return -1; } BooleanUtil.requireTrue(fromIndex < l1); if (l2 == 0) { return fromIndex; } if (l2 > l1) { return -1; } final char first = test[0]; for (int i = fromIndex, idx, actIdx; i < l1; i++) { if (src[i] == first) { idx = 1; for (; idx < l2; idx++) { actIdx = idx + i; if (actIdx < l1) { if (src[actIdx] != test[idx]) { break; } } else { return -1; } } if (idx >= l2) { return i; } } } return -1; } public static boolean isVarStarting(int ch) { return isLetter(ch) || is_(ch) || is$(ch) || isChinese(ch); } public static boolean isVar(int ch) { return isLetterOrDigit(ch) || is_(ch) || is$(ch) || isChinese(ch); } public static boolean is_(int ch) { return isUnderscore(ch); } public static boolean is$(int ch) { return ch == '$'; } public static boolean isUnderscore(int ch) { return ch == '_'; } public static boolean isChineseYuan(int ch) { return ch == '¥'; } public static boolean isDollar(int ch) { return is$(ch); } /** * "[4e00-9fa5]" * * @param ch 字符 * * @return 是否是汉字 */ public static boolean isChinese(int ch) { return ch < 40870 && ch > 19967; } public static boolean isLetterOrDigit(int ch) { return isDigit(ch) || isLetter(ch); } /** * A-Z,a-z * * @param ch 字符 * * @return 是否是字母 */ public static boolean isLetter(int ch) { return isLowerCase(ch) || isUpperCase(ch); } /** * A-Z * * @param ch 字符 * * @return 是否是大写字母 */ public static boolean isUpperCase(int ch) { return ch > 64 && ch < 91; } /** * a-z * * @param ch 字符 * * @return 是否是小写字母 */ public static boolean isLowerCase(int ch) { return ch > 96 && ch < 123; } /** * 0-9 * * @param ch 字符 * * @return 是否是数字 */ public static boolean isDigit(int ch) { return ch > 47 && ch < 58; } public static boolean equalsIgnoreCase(int ch1, int ch2) { return ch1 == ch2 || (isLowerCase(ch1) ? ch1 - 32 == ch2 : (isUpperCase(ch1) && ch2 - 32 == ch1)); } public static boolean isASCIICode(int ch) { return ch < 128; } public static boolean isChar(Object o) { if (o instanceof Character) { return true; } if (o instanceof Integer) { int value = ((Number) o).intValue(); return value > -1 && value < 65536; } return false; } /** * 字符转换为数字 * <pre> * 0-9: 0 - 9; * A-Z: 10 - 36; * a-z: 37 - 61; * (other): -1 * </pre> * * @param codePoint * * @return */ public static int toDigitMaxAs62(int codePoint) { if (isDigit(codePoint)) { return codePoint - 48; } if (isUpperCase(codePoint)) { return codePoint - 55; } if (isLowerCase(codePoint)) { return codePoint - 61; } return -1; } /** * null : '0' * false : '0' * (other): '1' * * @param bool * * @return */ public static char toCharValue(Boolean bool) { return (char) (bool == null || !bool ? 48 : 49); } public static char toCharValue(long value) { return (char) value; } public static char toCharValue(float value) { return (char) value; } public static char toCharValue(double value) { return (char) value; } /** * 当且仅当字符串包含一个字符时,返回这个字符,否则抛出异常 * * @param cs * * @return 字符串中仅有的一个字符 * * @throws NullPointerException 当 cs == null 时,空指针异常 * @throws IllegalArgumentException 当 cs 长度不符合要求 1 时抛出异常 */ public static char toCharValue(CharSequence cs) { Objects.requireNonNull(cs, "Can not cast to char from a null value."); if (cs.length() == 1) { return cs.charAt(0); } throw new IllegalArgumentException(String.format("Can not cast to char of: %s", cs)); } /** * @param o 带转换值 * * @return 转换后的值 * * @see IntUtil#toIntValue(Object) */ public static char toCharValue(Object o) { if (o == null) { return 0; } if (o instanceof Character) { return (Character) o; } if (o instanceof Number) { return (char) ((Number) o).intValue(); } if (o instanceof CharSequence) { return toCharValue(o.toString()); } if (o instanceof Boolean) { return toCharValue((Boolean) o); } try { return toCharValue(ParseSupportUtil.unboxing(o)); } catch (Exception e) { throw new IllegalArgumentException(String.format("Can not cast to char of: %s", o), e); } } }
3e0013b9f1b6f31ec681a04046f355f186563a90
3,364
java
Java
app/src/main/java/com/yhy/widget/demo/activity/SliderActivity.java
yhyzgn/Widgets
c19f53982b5f5285cd967ec15e313458ee305d15
[ "Apache-2.0" ]
10
2017-08-28T07:24:23.000Z
2021-11-25T12:31:00.000Z
app/src/main/java/com/yhy/widget/demo/activity/SliderActivity.java
SilentWolf1993/Widgets
c19f53982b5f5285cd967ec15e313458ee305d15
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yhy/widget/demo/activity/SliderActivity.java
SilentWolf1993/Widgets
c19f53982b5f5285cd967ec15e313458ee305d15
[ "Apache-2.0" ]
3
2018-12-03T01:50:46.000Z
2021-03-24T03:42:08.000Z
29.761062
137
0.569432
38
package com.yhy.widget.demo.activity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.yhy.widget.layout.slider.SlideLayout; import com.yhy.widget.demo.R; import com.yhy.widget.demo.activity.base.BaseActivity; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; /** * author : 颜洪毅 * e-mail : ychag@example.com * time : 2017-10-14 9:31 * version: 1.0.0 * desc : */ public class SliderActivity extends BaseActivity { private SlideLayout slSlide; private TextView tvMenu; private ViewPager vpContent; @Override protected int getLayout() { return R.layout.activity_slider; } @Override protected void initView() { slSlide = (SlideLayout) findViewById(R.id.sl_slide); tvMenu = (TextView) findViewById(R.id.tv_menu); vpContent = (ViewPager) findViewById(R.id.vp_content); } @Override protected void initData() { vpContent.setAdapter(new PagerAdapter() { @Override public int getCount() { return 4; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView iv = new ImageView(SliderActivity.this); iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); iv.setScaleType(ImageView.ScaleType.CENTER_CROP); if (position == 0) { iv.setImageResource(R.mipmap.img_pager_1); } else if (position == 1) { iv.setImageResource(R.mipmap.img_pager_2); } else if (position == 2) { iv.setImageResource(R.mipmap.img_pager_3); } else { iv.setImageResource(R.mipmap.img_pager_4); } container.addView(iv); return iv; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } }); } @Override protected void initEvent() { tvMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { slSlide.close(); } }); slSlide.setOnSlideEnableWatcher(new SlideLayout.OnSlideEnableWatcher() { @Override public boolean shouldEnable() { //第二页禁用侧边栏 return vpContent.getCurrentItem() != 1; } }); slSlide.setOnStateChangeListener(new SlideLayout.OnStateChangeListener() { @Override public void onOpened() { tvMenu.setText("已打开"); } @Override public void onClosed() { tvMenu.setText("已关闭"); } @Override public void onDragging(float percent, int dx, int total) { tvMenu.setText("比例:" + percent); } }); } }
3e00145696cd8009222a22b788d063184917ffd0
13,921
java
Java
convalida-databinding/src/main/java/convalida/databinding/ValidationBindings.java
WellingtonCosta/aav
ae6a5f27c19292c7db2456346db868ed40d80a19
[ "Apache-2.0" ]
186
2017-07-25T13:56:00.000Z
2019-07-31T16:40:25.000Z
convalida-databinding/src/main/java/convalida/databinding/ValidationBindings.java
WellingtonCosta/aav
ae6a5f27c19292c7db2456346db868ed40d80a19
[ "Apache-2.0" ]
35
2017-08-10T17:00:56.000Z
2019-02-27T20:11:15.000Z
convalida-databinding/src/main/java/convalida/databinding/ValidationBindings.java
WellingtonCosta/aav
ae6a5f27c19292c7db2456346db868ed40d80a19
[ "Apache-2.0" ]
21
2017-10-06T07:44:46.000Z
2019-08-02T22:16:09.000Z
31.928899
80
0.568422
39
package convalida.databinding; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.databinding.BindingAdapter; import convalida.validators.BetweenValidator; import convalida.validators.CnpjValidator; import convalida.validators.ConfirmEmailValidator; import convalida.validators.ConfirmPasswordValidator; import convalida.validators.CpfValidator; import convalida.validators.CreditCardValidator; import convalida.validators.EmailValidator; import convalida.validators.FutureDateValidator; import convalida.validators.Ipv4Validator; import convalida.validators.Ipv6Validator; import convalida.validators.IsbnValidator; import convalida.validators.LengthValidator; import convalida.validators.NumericLimitValidator; import convalida.validators.OnlyNumberValidator; import convalida.validators.PasswordValidator; import convalida.validators.PastDateValidator; import convalida.validators.PatternValidator; import convalida.validators.RequiredValidator; import convalida.validators.UrlValidator; import static convalida.databinding.ViewTagUtils.addValidatorToField; /** * @author WellingtonCosta on 29/03/18. */ public class ValidationBindings { @BindingAdapter(value = { "requiredErrorMessage", "requiredAutoDismiss" }, requireAll = false) public static void requiredValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss ) { addValidatorToField(field, new RequiredValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true )); } @BindingAdapter(value = { "emailErrorMessage", "emailAutoDismiss", "emailRequired" }, requireAll = false) public static void emailValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new EmailValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "confirmEmailEmailField", "confirmEmailErrorMessage", "confirmEmailAutoDismiss" }, requireAll = false) public static void confirmEmailValidationBindings( @NonNull EditText confirmEmailField, @NonNull EditText emailField, @NonNull String errorMessage, Boolean autoDismiss ) { addValidatorToField(confirmEmailField, new ConfirmEmailValidator( emailField, confirmEmailField, errorMessage, autoDismiss != null ? autoDismiss : true )); } @BindingAdapter(value = { "patternErrorMessage", "patternPattern", "patternAutoDismiss", "patternRequired" }, requireAll = false) public static void patternValidationBindings( @NonNull EditText field, @NonNull String errorMessage, @NonNull String pattern, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new PatternValidator( field, errorMessage, pattern, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "lengthMin", "lengthMax", "lengthErrorMessage", "lengthAutoDismiss", "lengthRequired" }, requireAll = false) public static void lengthValidationBindings( @NonNull EditText field, int min, int max, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new LengthValidator( field, errorMessage, min, max, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "onlyNumberErrorMessage", "onlyNumberAutoDismiss", "onlyNumberRequired" }, requireAll = false) public static void onlyNumberValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new OnlyNumberValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "passwordErrorMessage", "passwordMinLength", "passwordPattern", "passwordAutoDismiss" }, requireAll = false) public static void passwordValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Integer minLength, String pattern, Boolean autoDismiss ) { addValidatorToField(field, new PasswordValidator( field, errorMessage, minLength != null ? minLength : 0, pattern != null ? pattern : "", autoDismiss != null ? autoDismiss : true )); } @BindingAdapter(value = { "confirmPasswordPasswordField", "confirmPasswordErrorMessage", "confirmPasswordAutoDismiss" }, requireAll = false) public static void confirmPasswordValidationBindings( @NonNull EditText confirmPasswordField, @NonNull EditText passwordField, @NonNull String errorMessage, Boolean autoDismiss ) { addValidatorToField(confirmPasswordField, new ConfirmPasswordValidator( passwordField, confirmPasswordField, errorMessage, autoDismiss != null ? autoDismiss : true )); } @BindingAdapter(value = { "cpfErrorMessage", "cpfAutoDismiss", "cpfRequired" }, requireAll = false) public static void cpfValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new CpfValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "cnpjErrorMessage", "cnpjAutoDismiss", "cnpjRequired" }, requireAll = false) public static void cnpjValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new CnpjValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "isbnErrorMessage", "isbnAutoDismiss", "isbnRequired" }, requireAll = false) public static void isbnValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new IsbnValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "betweenStartErrorMessage", "betweenStartAutoDismiss", "betweenLimitField", "betweenLimitErrorMessage", "betweenLimitAutoDismiss" }, requireAll = false) public static void betweenValidationBindings( @NonNull EditText startField, @NonNull String startErrorMessage, Boolean startAutoDismiss, EditText limitField, @NonNull String limitErrorMessage, Boolean limitAutoDismiss ) { addValidatorToField(startField, new BetweenValidator( startField, limitField, startErrorMessage, limitErrorMessage, startAutoDismiss != null ? startAutoDismiss : true, limitAutoDismiss != null ? limitAutoDismiss : true )); } @BindingAdapter(value = { "creditCardErrorMessage", "creditCardAutoDismiss", "creditCardRequired" }, requireAll = false) public static void creditCardValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new CreditCardValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "numericLimitErrorMessage", "numericLimitAutoDismiss", "numericLimitMin", "numericLimitMax", "numericLimitRequired" }, requireAll = false) public static void numericLimitValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, @NonNull String min, @NonNull String max, Boolean required ) { addValidatorToField(field, new NumericLimitValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, min, max, required != null ? required : true )); } @BindingAdapter(value = { "ipv4ErrorMessage", "ipv4AutoDismiss", "ipv4Required" }, requireAll = false) public static void ipv4ValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new Ipv4Validator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "ipv6ErrorMessage", "ipv6AutoDismiss", "ipv6Required" }, requireAll = false) public static void ipv6ValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new Ipv6Validator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "urlErrorMessage", "urlAutoDismiss", "urlRequired" }, requireAll = false) public static void urlValidationBindings( @NonNull EditText field, @NonNull String errorMessage, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new UrlValidator( field, errorMessage, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "pastDateErrorMessage", "pastDateDateFormat", "pastDateLimitDate", "pastDateAutoDismiss", "pastDateRequired" }, requireAll = false) public static void pastDateValidationBindings( @NonNull EditText field, @NonNull String errorMessage, @NonNull String dateFormat, @NonNull String limitDate, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new PastDateValidator( field, errorMessage, dateFormat, limitDate, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = { "futureDateErrorMessage", "futureDateDateFormat", "futureDateLimitDate", "futureDateAutoDismiss", "futureDateRequired" }, requireAll = false) public static void futureDateValidationBindings( @NonNull EditText field, @NonNull String errorMessage, @NonNull String dateFormat, @NonNull String limitDate, Boolean autoDismiss, Boolean required ) { addValidatorToField(field, new FutureDateValidator( field, errorMessage, dateFormat, limitDate, autoDismiss != null ? autoDismiss : true, required != null ? required : true )); } @BindingAdapter(value = "validationAction") public static void validationActionBindings(Button button, Integer action) { button.setTag(R.id.validation_action, action); } }
3e001523bd540a30361633d89cc69eba883c3f40
3,609
java
Java
app/controllers/Forms.java
pellerito/to.science.api
d1a48f610f8b35b6cfad77c7af36c443867570db
[ "Apache-2.0" ]
1
2020-12-04T01:15:28.000Z
2020-12-04T01:15:28.000Z
app/controllers/Forms.java
pellerito/to.science.api
d1a48f610f8b35b6cfad77c7af36c443867570db
[ "Apache-2.0" ]
99
2015-01-15T07:41:41.000Z
2020-07-01T18:32:44.000Z
app/controllers/Forms.java
pellerito/to.science.api
d1a48f610f8b35b6cfad77c7af36c443867570db
[ "Apache-2.0" ]
5
2016-03-02T13:24:20.000Z
2020-11-12T12:57:06.000Z
26.536765
135
0.670269
40
package controllers; import java.util.HashMap; import java.util.Map; import actions.Modify; import authenticate.BasicAuth; import authenticate.User; import authenticate.UserDB; import helper.HttpArchiveException; import helper.JsonMapper; import models.Message; import models.Node; import play.data.DynamicForm; import play.data.Form; import play.libs.F.Promise; import play.mvc.Result; @BasicAuth public class Forms extends MyController { public static Promise<Result> getCatalogForm(String pid) { return new CreateAction().call((userId) -> { try { DynamicForm form = Form.form(); return ok(views.html.catalogForm.render(pid, form)); } catch (Exception e) { throw new HttpArchiveException(500, e); } }); } public static Promise<Result> postCatalogForm() { return new CreateAction().call((userId) -> { try { DynamicForm form = Form.form().bindFromRequest(); String alephId = form.get("alephId"); String pid = form.get("pid"); Node previewNode = new Node(); previewNode.setPid("preview:1"); String metadata = new Modify().getLobid2DataAsNtripleString(previewNode, alephId); previewNode.setMetadata2(metadata); flash("message", "Preview! Press 'Create' on the page bottom to create new object."); return ok( views.html.catalogPreview.render(pid, previewNode, null, alephId)); } catch (Exception e) { throw new HttpArchiveException(500, e); } }); } public static Promise<Result> getArticleForm() { return new CreateAction().call((userId) -> { try { return JsonMessage(new Message( "Here the user will be able add bibligraphic data for articles.", 501)); } catch (Exception e) { throw new HttpArchiveException(500, e); } }); } public static Promise<Result> getWebpageForm() { return new CreateAction().call((userId) -> { try { return JsonMessage(new Message( "Here the user will be able to Link a HT-Number to the Form in order to import Aleph data and to configure a webpage gathering.", 501)); } catch (Exception e) { throw new HttpArchiveException(500, e); } }); } public static Promise<Result> getPartForm() { return new CreateAction().call((userId) -> { try { return JsonMessage(new Message( "Here the user will be able to create a new part Form.", 501)); } catch (Exception e) { throw new HttpArchiveException(500, e); } }); } public static Promise<Result> getFileForm() { return new CreateAction().call((userId) -> { try { return JsonMessage(new Message( "Here the user will be able to upload a new file.", 501)); } catch (Exception e) { throw new HttpArchiveException(500, e); } }); } public static Promise<Result> getLoginForm() { return Promise.promise(() -> { try { if (models.Globals.users.isLoggedIn(ctx())) { return redirect(routes.Forms.getLogoutForm()); } Form<User> userForm = Form.form(User.class); return ok(views.html.login.render(userForm)); } catch (Exception e) { throw new HttpArchiveException(500, e); } }); } public static Promise<Result> getLogoutForm() { try { return Promise.promise(() -> { return ok(views.html.logout.render()); }); } catch (Exception e) { throw new HttpArchiveException(500, e); } } public static Promise<Result> postLogout() { return new CreateAction().call((userId) -> { flash("message", "Goodby " + session().get("username") + ". You were successfully logged out"); session().clear(); return redirect(routes.Application.index()); }); } }
3e0015e43b82a5f1c64a6ceb71f09978c053288b
13,945
java
Java
src/main/java/org/jennings/websats/satellites.java
david618/websats
ef09edcdd0693b777211b86fd2feb17722e41b09
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jennings/websats/satellites.java
david618/websats
ef09edcdd0693b777211b86fd2feb17722e41b09
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jennings/websats/satellites.java
david618/websats
ef09edcdd0693b777211b86fd2feb17722e41b09
[ "Apache-2.0" ]
null
null
null
40.42029
128
0.477375
41
/* * To run in Jetty * Add to webapps Folder of Jetty * java -jar start.jar -Djetty.port=9999 */ package org.jennings.websats; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashSet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jennings.mvnsat.Sat; import org.json.JSONArray; import org.json.JSONObject; /** * * @author david */ @WebServlet(name = "satellites", urlPatterns = {"/satellites"}) public class satellites extends HttpServlet { private static Sats satDB = null; //private static Long msgNum = null; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if satDB servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (satDB == null) { satDB = new Sats(); } String strFormat = ""; String strNums = ""; String strNames = ""; String strTime = ""; String strGeomType = ""; String strDel = "|"; String strNtimes = ""; // Populate the parameters ignoring case Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); if (paramName.equalsIgnoreCase("f")) { strFormat = request.getParameter(paramName); } else if (paramName.equalsIgnoreCase("gt")) { strGeomType = request.getParameter(paramName); } else if (paramName.equalsIgnoreCase("t")) { strTime = request.getParameter(paramName); } else if (paramName.equalsIgnoreCase("names")) { strNames = request.getParameter(paramName); } else if (paramName.equalsIgnoreCase("nums")) { strNums = request.getParameter(paramName); } else if (paramName.equalsIgnoreCase("n")) { strNtimes = request.getParameter(paramName); } } String fmt = "txt"; if (strFormat.equalsIgnoreCase("txt") || strFormat.equalsIgnoreCase("")) { fmt = "txt"; } else if (strFormat.equalsIgnoreCase("ndjson")) { fmt = "ndjson"; } else if (strFormat.equalsIgnoreCase("json")) { fmt = "json"; } else if (strFormat.equalsIgnoreCase("geojson")) { fmt = "geojson"; } else { throw new Exception("Unsupported Format. Supported formats: txt, json, ndjson, geojson"); } String geomType = ""; if (!strGeomType.equalsIgnoreCase("")) { if (strGeomType.equalsIgnoreCase("geojson")) { geomType = "geojson"; } else if (strGeomType.equalsIgnoreCase("esri")) { geomType = "esri"; } else { throw new Exception("Unsupported Geometry Type. Must be esri or geojson"); } } long t = System.currentTimeMillis(); /* if (!strTime.equalsIgnoreCase("")) { t = Long.parseLong(strTime); if (t < 10000000000L) { // Assume it seconds convert to ms t = t * 1000; } } */ int ntimes = 1; if (!strNtimes.equalsIgnoreCase("")) { try { ntimes = Integer.parseInt(strNtimes); if (ntimes < 1) { ntimes = 1; } else if (ntimes > 5000) { ntimes = 5000; } } catch (Exception e) { throw new Exception("n must be an integer"); } } HashSet<String> sats = new HashSet<>(); if (strNames.equalsIgnoreCase("") && strNums.equalsIgnoreCase("")) { sats = satDB.getAllNums(); } if (!strNums.equalsIgnoreCase("")) { // Nums were specified sats = satDB.getSatsByNum(strNums); } else if (!strNames.equalsIgnoreCase("")) { // Names were specified sats = satDB.getSatsByName(strNames); } JSONArray results = new JSONArray(); //String strLines = ""; long st = System.currentTimeMillis(); long et = st; int n = 0; PrintWriter out = response.getWriter(); while (n < ntimes) { long t1 = t + (et - st); for (String sat : sats) { Sat pos = satDB.getSatNum(sat).getPos(t1); JSONObject result = new JSONObject(); JSONArray line = new JSONArray(); JSONArray lines = new JSONArray(); /* if (msgNum == null || msgNum > 1000000000L) { msgNum = 1L; } else { msgNum += 1; } */ if (fmt.equalsIgnoreCase("geojson")) { result.put("type", "Feature"); JSONObject properties = new JSONObject(); properties.put("name", pos.getName()); properties.put("num", pos.getNum()); properties.put("timestamp", pos.GetEpoch().epochTimeMillis()); properties.put("dtg", pos.GetEpoch()); properties.put("lon", pos.GetLon()); properties.put("lat", pos.GetParametricLat()); properties.put("alt", pos.getAltitude()); //properties.put("msgnum", msgNum); result.put("properties", properties); JSONObject geom = new JSONObject(); geom.put("type", "Point"); JSONArray coord = new JSONArray("[" + pos.GetLon() + ", " + pos.GetParametricLat() + "]"); geom.put("coordinates", coord); result.put("geometry", geom); results.put(result); } else if (fmt.equalsIgnoreCase("json") || fmt.equalsIgnoreCase("ndjson") || fmt.equalsIgnoreCase("txt")) { JSONObject geom2 = new JSONObject(); if (geomType.equalsIgnoreCase("geojson")) { JSONArray coord = new JSONArray("[" + pos.GetLon() + ", " + pos.GetParametricLat() + "]"); geom2.put("coordinates", coord); } else { geom2.put("x", pos.GetLon()); geom2.put("y", pos.GetParametricLat()); } if (fmt.equalsIgnoreCase("json") || fmt.equalsIgnoreCase("ndjson")) { result.put("name", pos.getName()); result.put("num", sat); result.put("timestamp", pos.GetEpoch().epochTimeMillis()); result.put("dtg", pos.GetEpoch()); result.put("lon", pos.GetLon()); result.put("lat", pos.GetParametricLat()); result.put("alt", pos.getAltitude()); //result.put("msgnum", msgNum); if (!geomType.equalsIgnoreCase("")) { result.put("geometry", geom2); } if (fmt.equalsIgnoreCase("json")) { results.put(result); } else { out.println(result.toString()); } } else if (geomType.equalsIgnoreCase("")) { // Default is no geom at all just lon,lat // strLines += pos.getName() + strDel + pos.getNum() + strDel + pos.GetEpoch().epochTimeMillis() // + strDel + pos.GetEpoch() + strDel + pos.GetLon() + strDel + pos.GetParametricLat() // + strDel + pos.getAltitude() + "\n"; String oline = pos.getName() + strDel + pos.getNum() + strDel + pos.GetEpoch().epochTimeMillis() + strDel + pos.GetEpoch() + strDel + pos.GetLon() + strDel + pos.GetParametricLat() + strDel + pos.getAltitude() + ""; // String oline = pos.getName() + strDel + pos.getNum() + strDel + pos.GetEpoch().epochTimeMillis() // + strDel + pos.GetEpoch() + strDel + pos.GetLon() + strDel + pos.GetParametricLat() // + strDel + pos.getAltitude() + strDel + msgNum + ""; out.println(oline); } else { // Default to delimited the geom is inside quotes and replace quotes with \" // strLines += pos.getName() + strDel + pos.getNum() + strDel + pos.GetEpoch().epochTimeMillis() // + "\"" + geom2.toString().replace("\"", "\\\"") + "\"" + "\n"; String oline = pos.getName() + strDel + pos.getNum() + strDel + pos.GetEpoch().epochTimeMillis() + "\"" + geom2.toString().replace("\"", "\\\"") + "\"" + ""; out.println(oline); } } else { throw new Exception("Invalid format. Supported formats: txt,json,geojson"); } } n += 1; st = System.currentTimeMillis(); } // Process the list of satellites JSONObject resp = new JSONObject(); if (fmt.equalsIgnoreCase("geojson")) { response.setContentType("application/json;charset=UTF-8"); JSONObject featureCollection = new JSONObject(); featureCollection.put("type", "FeatureCollection"); featureCollection.put("features", results); //out.println(featureCollection); featureCollection.write(out); } else if (fmt.equalsIgnoreCase("json")) { response.setContentType("application/json;charset=UTF-8"); if (results.length() > 1) { results.write(out); //out.println(results.toString()); } else { out.println(results.get(0).toString()); } } else { // Pipe Delimited response.setContentType("text/plain;charset=UTF-8"); // out.println(strLines); } } catch (Exception e) { try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Error Creating Satellite Array</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Could build satellite array.</h1>"); out.println("<h2>Error: " + e.getMessage() + "</h2>"); out.println("</body>"); out.println("</html>"); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if satDB servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if satDB servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns satDB short description of the servlet. * * @return satDB String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
3e00161a19af0d5204b6cb487145ecbd8695512f
2,672
java
Java
examples/showcase/src/test/functional/org/springside/examples/showcase/functional/BaseFunctionalTestCase.java
deluxebear/springside4
824dcb96368b76269bc25416a1a620c3c4152490
[ "Apache-2.0" ]
1
2020-08-03T08:22:42.000Z
2020-08-03T08:22:42.000Z
examples/showcase/src/test/functional/org/springside/examples/showcase/functional/BaseFunctionalTestCase.java
deluxebear/springside4
824dcb96368b76269bc25416a1a620c3c4152490
[ "Apache-2.0" ]
null
null
null
examples/showcase/src/test/functional/org/springside/examples/showcase/functional/BaseFunctionalTestCase.java
deluxebear/springside4
824dcb96368b76269bc25416a1a620c3c4152490
[ "Apache-2.0" ]
null
null
null
30.022472
111
0.761228
42
package org.springside.examples.showcase.functional; import java.net.URL; import java.sql.Driver; import org.eclipse.jetty.server.Server; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.SimpleDriverDataSource; import org.springside.modules.test.data.DataFixtures; import org.springside.modules.test.jetty.JettyFactory; import org.springside.modules.utils.PropertiesLoader; /** * 功能测试基类. * * 在整个测试期间启动一次Jetty Server, 并在每个TestCase Class执行前中重新载入默认数据. * * @author calvin */ public class BaseFunctionalTestCase { protected static String baseUrl; protected static Server jettyServer; protected static SimpleDriverDataSource dataSource; protected static PropertiesLoader propertiesLoader = new PropertiesLoader("classpath:/application.properties", "classpath:/application.functional.properties", "classpath:/application.functional-local.properties"); private static Logger logger = LoggerFactory.getLogger(BaseFunctionalTestCase.class); @BeforeClass public static void beforeClass() throws Exception { baseUrl = propertiesLoader.getProperty("baseUrl"); Boolean isEmbedded = new URL(baseUrl).getHost().equals("localhost") && propertiesLoader.getBoolean("embeddedForLocal"); if (isEmbedded) { startJettyOnce(); } buildDataSourceOnce(); reloadSampleData(); } /** * 启动Jetty服务器, 仅启动一次. */ protected static void startJettyOnce() throws Exception { if (jettyServer == null) { //设定Spring的profile System.setProperty("spring.profiles.active", "functional"); jettyServer = JettyFactory.createServerInSource(new URL(baseUrl).getPort(), ShowcaseServer.CONTEXT); JettyFactory.setTldJarNames(jettyServer, ShowcaseServer.TLD_JAR_NAMES); jettyServer.start(); logger.info("Jetty Server started at {}", baseUrl); } } /** * 构造数据源,仅构造一次. */ protected static void buildDataSourceOnce() throws ClassNotFoundException { if (dataSource == null) { dataSource = new SimpleDriverDataSource(); dataSource.setDriverClass((Class<? extends Driver>) Class.forName(propertiesLoader .getProperty("jdbc.driver"))); dataSource.setUrl(propertiesLoader.getProperty("jdbc.url")); dataSource.setUsername(propertiesLoader.getProperty("jdbc.username")); dataSource.setPassword(propertiesLoader.getProperty("jdbc.password")); } } /** * 载入默认数据. */ protected static void reloadSampleData() throws Exception { String dbType = propertiesLoader.getProperty("db.type", "h2"); DataFixtures.executeScript(dataSource, "classpath:data/" + dbType + "cleanup-data.sql", "classpath:data/" + dbType + "import-data.sql"); } }
3e001648bf4aaf2a92d08736e97a0180960d7ade
6,505
java
Java
core-api/src/main/java/com/sequenceiq/cloudbreak/api/endpoint/v4/stacks/request/cluster/ClusterV4Request.java
prabhjyotsingh/cloudbreak
4f735996a73d19dca8fe2617eaf125debe25ea38
[ "Apache-2.0" ]
null
null
null
core-api/src/main/java/com/sequenceiq/cloudbreak/api/endpoint/v4/stacks/request/cluster/ClusterV4Request.java
prabhjyotsingh/cloudbreak
4f735996a73d19dca8fe2617eaf125debe25ea38
[ "Apache-2.0" ]
1
2019-05-27T12:58:48.000Z
2019-05-27T12:58:48.000Z
core-api/src/main/java/com/sequenceiq/cloudbreak/api/endpoint/v4/stacks/request/cluster/ClusterV4Request.java
prabhjyotsingh/cloudbreak
4f735996a73d19dca8fe2617eaf125debe25ea38
[ "Apache-2.0" ]
null
null
null
29.434389
145
0.724827
43
package com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.cluster; import java.util.HashSet; import java.util.Set; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.sequenceiq.cloudbreak.api.endpoint.v4.JsonEntity; import com.sequenceiq.cloudbreak.api.endpoint.v4.common.ExecutorType; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.cluster.ambari.AmbariV4Request; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.cluster.cm.ClouderaManagerV4Request; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.cluster.customcontainer.CustomContainerV4Request; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.cluster.gateway.GatewayV4Request; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.cluster.storage.CloudStorageV4Request; import com.sequenceiq.cloudbreak.doc.ModelDescriptions.ClusterModelDescription; import com.sequenceiq.cloudbreak.doc.ModelDescriptions.StackModelDescription; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) public class ClusterV4Request implements JsonEntity { @ApiModelProperty(hidden = true) private String name; @Size(max = 15, min = 5, message = "The length of the username has to be in range of 5 to 15") @Pattern(regexp = "(^[a-z][-a-z0-9]*[a-z0-9]$)", message = "The username can only contain lowercase alphanumeric characters and hyphens and has start with an alphanumeric character") @NotNull @ApiModelProperty(value = StackModelDescription.USERNAME, required = true) private String userName; @NotNull @Pattern.List({ @Pattern(regexp = "^.*[a-zA-Z].*$", message = "The password should contain at least one letter."), @Pattern(regexp = "^.*[0-9].*$", message = "The password should contain at least one number.") }) @Size(max = 100, min = 8, message = "The length of the password has to be in range of 8 to 100") @ApiModelProperty(value = StackModelDescription.PASSWORD, required = true) private String password; @ApiModelProperty(ClusterModelDescription.LDAP_CONFIG_NAME) private String ldapName; @ApiModelProperty(ClusterModelDescription.RDSCONFIG_NAMES) private Set<String> databases = new HashSet<>(); @ApiModelProperty(ClusterModelDescription.PROXY_NAME) private String proxyName; @Valid @ApiModelProperty(StackModelDescription.CLOUD_STORAGE) private CloudStorageV4Request cloudStorage; @Valid @ApiModelProperty(ClusterModelDescription.CM_REQUEST) private ClouderaManagerV4Request cm; @Valid @ApiModelProperty(ClusterModelDescription.AMBARI_REQUEST) private AmbariV4Request ambari; private GatewayV4Request gateway; @Valid private String kerberosName; @ApiModelProperty(ClusterModelDescription.CUSTOM_CONTAINERS) private CustomContainerV4Request customContainer; @ApiModelProperty(ClusterModelDescription.CUSTOM_QUEUE) private String customQueue; @ApiModelProperty(ClusterModelDescription.EXECUTOR_TYPE) private ExecutorType executorType = ExecutorType.DEFAULT; @ApiModelProperty(ClusterModelDescription.BLUEPRINT_NAME) private String blueprintName; @ApiModelProperty(ClusterModelDescription.VALIDATE_BLUEPRINT) private Boolean validateBlueprint = Boolean.TRUE; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public ExecutorType getExecutorType() { return executorType; } public void setExecutorType(ExecutorType executorType) { this.executorType = executorType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<String> getDatabases() { return databases; } public void setDatabases(Set<String> databases) { this.databases = databases; } public String getProxyName() { return proxyName; } public void setProxyName(String proxyName) { this.proxyName = proxyName; } public CloudStorageV4Request getCloudStorage() { return cloudStorage; } public void setCloudStorage(CloudStorageV4Request cloudStorage) { this.cloudStorage = cloudStorage; } public ClouderaManagerV4Request getCm() { return cm; } public void setCm(ClouderaManagerV4Request cm) { this.cm = cm; } public AmbariV4Request getAmbari() { return ambari; } public void setAmbari(AmbariV4Request ambari) { this.ambari = ambari; } public GatewayV4Request getGateway() { return gateway; } public void setGateway(GatewayV4Request gateway) { this.gateway = gateway; } public String getLdapName() { return ldapName; } public void setLdapName(String ldapName) { this.ldapName = ldapName; } public String getKerberosName() { return kerberosName; } public void setKerberosName(String kerberosName) { this.kerberosName = kerberosName; } public String getCustomQueue() { return customQueue; } public void setCustomQueue(String customQueue) { this.customQueue = customQueue; } public CustomContainerV4Request getCustomContainer() { return customContainer; } public void setCustomContainer(CustomContainerV4Request customContainer) { this.customContainer = customContainer; } public String getBlueprintName() { return blueprintName; } public void setBlueprintName(String blueprintName) { this.blueprintName = blueprintName; } public Boolean getValidateBlueprint() { return validateBlueprint; } public void setValidateBlueprint(Boolean validateBlueprint) { this.validateBlueprint = validateBlueprint; } }
3e0016a9e4e1a80053c8811f20c1f0c4db96a1de
1,298
java
Java
eddsa/src/main/java/io/moatwel/crypto/eddsa/SchemeProvider.java
halu5071/edwards
dd9c9afe5fc03791be2befc2bf8ddf966dae0a04
[ "Apache-2.0" ]
6
2018-08-01T00:35:38.000Z
2020-03-31T07:36:45.000Z
eddsa/src/main/java/io/moatwel/crypto/eddsa/SchemeProvider.java
halu5071/edwards
dd9c9afe5fc03791be2befc2bf8ddf966dae0a04
[ "Apache-2.0" ]
5
2018-09-05T15:07:27.000Z
2022-01-26T06:17:34.000Z
eddsa/src/main/java/io/moatwel/crypto/eddsa/SchemeProvider.java
halu5071/edwards
dd9c9afe5fc03791be2befc2bf8ddf966dae0a04
[ "Apache-2.0" ]
1
2020-03-31T07:36:33.000Z
2020-03-31T07:36:33.000Z
24.490566
94
0.642527
44
package io.moatwel.crypto.eddsa; import io.moatwel.crypto.EdDsaSigner; import io.moatwel.crypto.PrivateKey; /** * Provide scheme used for creating public key, singing, verifying. * * @author halu5071 (Yasunori Horii) */ public abstract class SchemeProvider { private final Curve curve; protected SchemeProvider(Curve curve) { if (curve == null) { throw new NullPointerException("Curve must not be null"); } this.curve = curve; } public Curve getCurve() { return curve; } public abstract EdDsaSigner getSigner(); public abstract PublicKeyDelegate getPublicKeyDelegate(); public abstract PrivateKey generatePrivateKey(); /** * Return a pre-hashed byte array. * * <p> * check the pre-hash function of each schemes. * * @param input byte array which will be hashed. * @return hashed byte array */ public abstract byte[] preHash(byte[] input); /** * Return byte array which the result of 'dom' operation * <p> * see <a href="https://tools.ietf.org/html/rfc8032#section-2" target="_blank">RFC8032</a> * * @param context context of signing and verifying * @return byte array */ public abstract byte[] dom(byte[] context); }
3e001709ce1f3b9625cc56e7fa2b9577f81c2db1
6,974
java
Java
timetracker-web/src/main/java/com/github/kshashov/timetracker/web/ui/views/admin/projects/ProjectsViewModel.java
kshashov/TimeTracker
696ba1e26f56fcbacbc821b8be54f68b41b904f7
[ "MIT" ]
null
null
null
timetracker-web/src/main/java/com/github/kshashov/timetracker/web/ui/views/admin/projects/ProjectsViewModel.java
kshashov/TimeTracker
696ba1e26f56fcbacbc821b8be54f68b41b904f7
[ "MIT" ]
null
null
null
timetracker-web/src/main/java/com/github/kshashov/timetracker/web/ui/views/admin/projects/ProjectsViewModel.java
kshashov/TimeTracker
696ba1e26f56fcbacbc821b8be54f68b41b904f7
[ "MIT" ]
null
null
null
38.744444
173
0.683539
45
package com.github.kshashov.timetracker.web.ui.views.admin.projects; import com.github.kshashov.timetracker.data.entity.Project; import com.github.kshashov.timetracker.data.entity.user.ProjectRole; import com.github.kshashov.timetracker.data.entity.user.Role; import com.github.kshashov.timetracker.data.entity.user.User; import com.github.kshashov.timetracker.data.enums.ProjectPermissionType; import com.github.kshashov.timetracker.data.repo.user.ProjectRolesRepository; import com.github.kshashov.timetracker.data.service.admin.projects.AuthorizedProjectsService; import com.github.kshashov.timetracker.data.service.admin.projects.ProjectInfo; import com.github.kshashov.timetracker.data.utils.RolePermissionsHelper; import com.github.kshashov.timetracker.web.security.HasUser; import com.github.kshashov.timetracker.web.ui.util.CrudEntity; import com.github.kshashov.timetracker.web.ui.util.DataHandler; import com.google.common.eventbus.EventBus; import com.vaadin.flow.data.binder.ValidationResult; import com.vaadin.flow.spring.annotation.SpringComponent; import com.vaadin.flow.spring.annotation.UIScope; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import rx.Observable; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.List; import java.util.function.Function; @Slf4j @UIScope @SpringComponent public class ProjectsViewModel implements HasUser, DataHandler { private final EventBus eventBus; private final AuthorizedProjectsService projectsService; private final ProjectRolesRepository projectRolesRepository; private final RolePermissionsHelper rolePermissionsHelper; private final PublishSubject<ProjectDialog> createProjectDialogObservable = PublishSubject.create(); private final PublishSubject<ProjectDialog> updateProjectDialogObservable = PublishSubject.create(); private final BehaviorSubject<CrudEntity<ProjectRole>> selectedProjectObservable = BehaviorSubject.create(); private final BehaviorSubject<CrudEntity<List<ProjectRole>>> projectsObservable = BehaviorSubject.create(); private final User user; private ProjectRole selectedProject; @Autowired public ProjectsViewModel( EventBus eventBus, AuthorizedProjectsService projectsService, ProjectRolesRepository projectRolesRepository, RolePermissionsHelper rolePermissionsHelper) { this.eventBus = eventBus; this.projectsService = projectsService; this.projectRolesRepository = projectRolesRepository; this.rolePermissionsHelper = rolePermissionsHelper; this.user = getUser(); select(null); } public void select(ProjectRole projectRole) { CrudEntity.CrudAccess projectAccess = projectRole == null ? CrudEntity.CrudAccess.READ_ONLY : checkAccess(projectRole.getRole()); selectedProject = projectRole; selectedProjectObservable.onNext(new CrudEntity<>(projectRole, projectAccess)); } public void createProject() { var project = new Project(); project.setIsActive(true); createProjectDialogObservable.onNext(new ProjectsViewModel.ProjectDialog( project, bean -> handleDataManipulation( () -> { ProjectInfo projectInfo = new ProjectInfo(bean.getTitle()); return projectsService.createProject(user, projectInfo); }, result -> reloadProjects()) )); } public void updateProject(Project project) { updateProjectDialogObservable.onNext(new ProjectsViewModel.ProjectDialog( project, bean -> handleDataManipulation( () -> { ProjectInfo projectInfo = new ProjectInfo(bean.getTitle()); return projectsService.updateProject(user, bean.getId(), projectInfo); }, result -> reloadProjects()) )); } public void activateProject(Project project) { handleDataManipulation( () -> projectsService.activateProject(user, project.getId()), () -> reloadProjects()); } public void deleteProject(Project project) { handleDataManipulation( () -> projectsService.deleteOrDeactivateProject(user, project.getId()), result -> { if (!result) { notifyPopup("The project with some actions are moved into inactive state instead of deletion, because there are closed working logs related to it."); } reloadProjects(); }); } public void reloadProjects() { var projectRoles = projectRolesRepository.findWithProjectByUserOrderByProjectTitleAsc(user); if (selectedProject != null) { // Restore selection projectRoles.stream().filter(pr -> pr.getProject().getId().equals(selectedProject.getProject().getId())) .findFirst() .ifPresentOrElse(this::select, () -> selectedProject = null); } if ((selectedProject == null) && (projectRoles.size() > 0)) { // Select first item select(projectRoles.iterator().next()); } else if (selectedProject == null) { select(null); } projectsObservable.onNext(new CrudEntity<>(projectRoles, CrudEntity.CrudAccess.FULL_ACCESS)); } public Observable<CrudEntity<ProjectRole>> project() { return selectedProjectObservable; } public Observable<CrudEntity<List<ProjectRole>>> projects() { return projectsObservable; } public Observable<ProjectDialog> createProjectDialogs() { return createProjectDialogObservable; } public Observable<ProjectsViewModel.ProjectDialog> updateProjectDialogs() { return updateProjectDialogObservable; } private CrudEntity.CrudAccess checkAccess(Role role) { if (rolePermissionsHelper.hasPermission(role, ProjectPermissionType.EDIT_PROJECT_INFO)) { return CrudEntity.CrudAccess.FULL_ACCESS; } else if (rolePermissionsHelper.hasPermission(role, ProjectPermissionType.VIEW_PROJECT_INFO)) { return CrudEntity.CrudAccess.READ_ONLY; } return CrudEntity.CrudAccess.DENIED; } @Override public Logger getLogger() { return log; } @Override public EventBus eventBus() { return eventBus; } @Getter @AllArgsConstructor public static class ProjectDialog { private final Project project; private final Function<Project, ValidationResult> validator; } }
3e0018167517f1fd2c22ef1d1181626ddacd10fd
451
java
Java
src/main/java/ru/mail/polis/lsm/DAOFactory.java
IlyaAAAA/2021-highload-dht
896aaf8a6976efd9b0346cecde1403e75fe2cd89
[ "Apache-2.0" ]
null
null
null
src/main/java/ru/mail/polis/lsm/DAOFactory.java
IlyaAAAA/2021-highload-dht
896aaf8a6976efd9b0346cecde1403e75fe2cd89
[ "Apache-2.0" ]
null
null
null
src/main/java/ru/mail/polis/lsm/DAOFactory.java
IlyaAAAA/2021-highload-dht
896aaf8a6976efd9b0346cecde1403e75fe2cd89
[ "Apache-2.0" ]
null
null
null
19.608696
73
0.649667
46
package ru.mail.polis.lsm; import ru.mail.polis.lsm.sachuk.ilya.DaoImpl; import java.io.IOException; public final class DAOFactory { private DAOFactory() { // Only static methods } /** * Create an instance of {@link DAO} with supplied {@link DAOConfig}. */ public static DAO create(DAOConfig config) throws IOException { assert config.dir.toFile().exists(); return new DaoImpl(config); } }
3e0018a87d259795e79ac0a6b08100f80e5ac527
15,177
java
Java
core/trino-main/src/main/java/io/trino/sql/planner/plan/WindowNode.java
julian-cn/trino
3082ef8475f67132f0be0f82809d86460fb975ee
[ "Apache-2.0" ]
3,603
2020-12-27T23:06:56.000Z
2022-03-31T22:17:28.000Z
core/trino-main/src/main/java/io/trino/sql/planner/plan/WindowNode.java
julian-cn/trino
3082ef8475f67132f0be0f82809d86460fb975ee
[ "Apache-2.0" ]
4,315
2020-12-28T00:55:19.000Z
2022-03-31T23:55:11.000Z
core/trino-main/src/main/java/io/trino/sql/planner/plan/WindowNode.java
julian-cn/trino
3082ef8475f67132f0be0f82809d86460fb975ee
[ "Apache-2.0" ]
954
2020-12-28T02:03:33.000Z
2022-03-31T14:21:35.000Z
35.131944
253
0.64354
47
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.sql.planner.plan; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import io.trino.metadata.ResolvedFunction; import io.trino.sql.planner.OrderingScheme; import io.trino.sql.planner.Symbol; import io.trino.sql.tree.Expression; import io.trino.sql.tree.FrameBound; import io.trino.sql.tree.WindowFrame; import javax.annotation.concurrent.Immutable; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.concat; import static io.trino.sql.tree.FrameBound.Type.CURRENT_ROW; import static io.trino.sql.tree.FrameBound.Type.UNBOUNDED_PRECEDING; import static io.trino.sql.tree.WindowFrame.Type.RANGE; import static java.util.Objects.requireNonNull; @Immutable public class WindowNode extends PlanNode { private final PlanNode source; private final Set<Symbol> prePartitionedInputs; private final Specification specification; private final int preSortedOrderPrefix; private final Map<Symbol, Function> windowFunctions; private final Optional<Symbol> hashSymbol; @JsonCreator public WindowNode( @JsonProperty("id") PlanNodeId id, @JsonProperty("source") PlanNode source, @JsonProperty("specification") Specification specification, @JsonProperty("windowFunctions") Map<Symbol, Function> windowFunctions, @JsonProperty("hashSymbol") Optional<Symbol> hashSymbol, @JsonProperty("prePartitionedInputs") Set<Symbol> prePartitionedInputs, @JsonProperty("preSortedOrderPrefix") int preSortedOrderPrefix) { super(id); requireNonNull(source, "source is null"); requireNonNull(specification, "specification is null"); requireNonNull(windowFunctions, "windowFunctions is null"); requireNonNull(hashSymbol, "hashSymbol is null"); checkArgument(specification.getPartitionBy().containsAll(prePartitionedInputs), "prePartitionedInputs must be contained in partitionBy"); Optional<OrderingScheme> orderingScheme = specification.getOrderingScheme(); checkArgument(preSortedOrderPrefix == 0 || (orderingScheme.isPresent() && preSortedOrderPrefix <= orderingScheme.get().getOrderBy().size()), "Cannot have sorted more symbols than those requested"); checkArgument(preSortedOrderPrefix == 0 || ImmutableSet.copyOf(prePartitionedInputs).equals(ImmutableSet.copyOf(specification.getPartitionBy())), "preSortedOrderPrefix can only be greater than zero if all partition symbols are pre-partitioned"); this.source = source; this.prePartitionedInputs = ImmutableSet.copyOf(prePartitionedInputs); this.specification = specification; this.windowFunctions = ImmutableMap.copyOf(windowFunctions); this.hashSymbol = hashSymbol; this.preSortedOrderPrefix = preSortedOrderPrefix; } @Override public List<PlanNode> getSources() { return ImmutableList.of(source); } @Override public List<Symbol> getOutputSymbols() { return ImmutableList.copyOf(concat(source.getOutputSymbols(), windowFunctions.keySet())); } public Set<Symbol> getCreatedSymbols() { return ImmutableSet.copyOf(windowFunctions.keySet()); } @JsonProperty public PlanNode getSource() { return source; } @JsonProperty public Specification getSpecification() { return specification; } public List<Symbol> getPartitionBy() { return specification.getPartitionBy(); } public Optional<OrderingScheme> getOrderingScheme() { return specification.orderingScheme; } @JsonProperty public Map<Symbol, Function> getWindowFunctions() { return windowFunctions; } public List<Frame> getFrames() { return windowFunctions.values().stream() .map(WindowNode.Function::getFrame) .collect(toImmutableList()); } @JsonProperty public Optional<Symbol> getHashSymbol() { return hashSymbol; } @JsonProperty public Set<Symbol> getPrePartitionedInputs() { return prePartitionedInputs; } @JsonProperty public int getPreSortedOrderPrefix() { return preSortedOrderPrefix; } @Override public <R, C> R accept(PlanVisitor<R, C> visitor, C context) { return visitor.visitWindow(this, context); } @Override public PlanNode replaceChildren(List<PlanNode> newChildren) { return new WindowNode(getId(), Iterables.getOnlyElement(newChildren), specification, windowFunctions, hashSymbol, prePartitionedInputs, preSortedOrderPrefix); } @Immutable public static class Specification { private final List<Symbol> partitionBy; private final Optional<OrderingScheme> orderingScheme; @JsonCreator public Specification( @JsonProperty("partitionBy") List<Symbol> partitionBy, @JsonProperty("orderingScheme") Optional<OrderingScheme> orderingScheme) { requireNonNull(partitionBy, "partitionBy is null"); requireNonNull(orderingScheme, "orderingScheme is null"); this.partitionBy = ImmutableList.copyOf(partitionBy); this.orderingScheme = requireNonNull(orderingScheme, "orderingScheme is null"); } @JsonProperty public List<Symbol> getPartitionBy() { return partitionBy; } @JsonProperty public Optional<OrderingScheme> getOrderingScheme() { return orderingScheme; } @Override public int hashCode() { return Objects.hash(partitionBy, orderingScheme); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Specification other = (Specification) obj; return Objects.equals(this.partitionBy, other.partitionBy) && Objects.equals(this.orderingScheme, other.orderingScheme); } } @Immutable public static class Frame { public static final Frame DEFAULT_FRAME = new WindowNode.Frame( RANGE, UNBOUNDED_PRECEDING, Optional.empty(), Optional.empty(), CURRENT_ROW, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); private final WindowFrame.Type type; private final FrameBound.Type startType; private final Optional<Symbol> startValue; private final Optional<Symbol> sortKeyCoercedForFrameStartComparison; private final FrameBound.Type endType; private final Optional<Symbol> endValue; private final Optional<Symbol> sortKeyCoercedForFrameEndComparison; // This information is only used for printing the plan. private final Optional<Expression> originalStartValue; private final Optional<Expression> originalEndValue; @JsonCreator public Frame( @JsonProperty("type") WindowFrame.Type type, @JsonProperty("startType") FrameBound.Type startType, @JsonProperty("startValue") Optional<Symbol> startValue, @JsonProperty("sortKeyCoercedForFrameStartComparison") Optional<Symbol> sortKeyCoercedForFrameStartComparison, @JsonProperty("endType") FrameBound.Type endType, @JsonProperty("endValue") Optional<Symbol> endValue, @JsonProperty("sortKeyCoercedForFrameEndComparison") Optional<Symbol> sortKeyCoercedForFrameEndComparison, @JsonProperty("originalStartValue") Optional<Expression> originalStartValue, @JsonProperty("originalEndValue") Optional<Expression> originalEndValue) { this.startType = requireNonNull(startType, "startType is null"); this.startValue = requireNonNull(startValue, "startValue is null"); this.sortKeyCoercedForFrameStartComparison = requireNonNull(sortKeyCoercedForFrameStartComparison, "sortKeyCoercedForFrameStartComparison is null"); this.endType = requireNonNull(endType, "endType is null"); this.endValue = requireNonNull(endValue, "endValue is null"); this.sortKeyCoercedForFrameEndComparison = requireNonNull(sortKeyCoercedForFrameEndComparison, "sortKeyCoercedForFrameEndComparison is null"); this.type = requireNonNull(type, "type is null"); this.originalStartValue = requireNonNull(originalStartValue, "originalStartValue is null"); this.originalEndValue = requireNonNull(originalEndValue, "originalEndValue is null"); if (startValue.isPresent()) { checkArgument(originalStartValue.isPresent(), "originalStartValue must be present if startValue is present"); if (type == RANGE) { checkArgument(sortKeyCoercedForFrameStartComparison.isPresent(), "for frame of type RANGE, sortKeyCoercedForFrameStartComparison must be present if startValue is present"); } } if (endValue.isPresent()) { checkArgument(originalEndValue.isPresent(), "originalEndValue must be present if endValue is present"); if (type == RANGE) { checkArgument(sortKeyCoercedForFrameEndComparison.isPresent(), "for frame of type RANGE, sortKeyCoercedForFrameEndComparison must be present if endValue is present"); } } } @JsonProperty public WindowFrame.Type getType() { return type; } @JsonProperty public FrameBound.Type getStartType() { return startType; } @JsonProperty public Optional<Symbol> getStartValue() { return startValue; } @JsonProperty public Optional<Symbol> getSortKeyCoercedForFrameStartComparison() { return sortKeyCoercedForFrameStartComparison; } @JsonProperty public FrameBound.Type getEndType() { return endType; } @JsonProperty public Optional<Symbol> getEndValue() { return endValue; } @JsonProperty public Optional<Symbol> getSortKeyCoercedForFrameEndComparison() { return sortKeyCoercedForFrameEndComparison; } @JsonProperty public Optional<Expression> getOriginalStartValue() { return originalStartValue; } @JsonProperty public Optional<Expression> getOriginalEndValue() { return originalEndValue; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Frame frame = (Frame) o; return type == frame.type && startType == frame.startType && Objects.equals(startValue, frame.startValue) && Objects.equals(sortKeyCoercedForFrameStartComparison, frame.sortKeyCoercedForFrameStartComparison) && endType == frame.endType && Objects.equals(endValue, frame.endValue) && Objects.equals(sortKeyCoercedForFrameEndComparison, frame.sortKeyCoercedForFrameEndComparison); } @Override public int hashCode() { return Objects.hash(type, startType, startValue, sortKeyCoercedForFrameStartComparison, endType, endValue, sortKeyCoercedForFrameEndComparison); } } @Immutable public static final class Function { private final ResolvedFunction resolvedFunction; private final List<Expression> arguments; private final Frame frame; private final boolean ignoreNulls; @JsonCreator public Function( @JsonProperty("resolvedFunction") ResolvedFunction resolvedFunction, @JsonProperty("arguments") List<Expression> arguments, @JsonProperty("frame") Frame frame, @JsonProperty("ignoreNulls") boolean ignoreNulls) { this.resolvedFunction = requireNonNull(resolvedFunction, "resolvedFunction is null"); this.arguments = requireNonNull(arguments, "arguments is null"); this.frame = requireNonNull(frame, "frame is null"); this.ignoreNulls = ignoreNulls; } @JsonProperty public ResolvedFunction getResolvedFunction() { return resolvedFunction; } @JsonProperty public List<Expression> getArguments() { return arguments; } @JsonProperty public Frame getFrame() { return frame; } @JsonProperty public boolean isIgnoreNulls() { return ignoreNulls; } @Override public int hashCode() { return Objects.hash(resolvedFunction, arguments, frame, ignoreNulls); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Function other = (Function) obj; return Objects.equals(this.resolvedFunction, other.resolvedFunction) && Objects.equals(this.arguments, other.arguments) && Objects.equals(this.frame, other.frame) && this.ignoreNulls == other.ignoreNulls; } } }
3e0018d8508c1e024cd3a89fd8b281e56a9cc065
123
java
Java
build/stx/libjava/tests/java/src-tests-INVOKEX-missing-methods/stx/libjava/tests/mocks/MissingMethodI.java
GunterMueller/ST_STX_Fork
d891b139f3c016b81feeb5bf749e60585575bff7
[ "MIT" ]
1
2020-01-23T20:46:08.000Z
2020-01-23T20:46:08.000Z
build/stx/libjava/tests/java/src-tests-INVOKEX-missing-methods/stx/libjava/tests/mocks/MissingMethodI.java
GunterMueller/ST_STX_Fork
d891b139f3c016b81feeb5bf749e60585575bff7
[ "MIT" ]
null
null
null
build/stx/libjava/tests/java/src-tests-INVOKEX-missing-methods/stx/libjava/tests/mocks/MissingMethodI.java
GunterMueller/ST_STX_Fork
d891b139f3c016b81feeb5bf749e60585575bff7
[ "MIT" ]
null
null
null
20.5
52
0.796748
48
package stx.libjava.tests.mocks; @stx.libjava.annotation.Package("stx:libjava/tests") public interface MissingMethodI { }
3e001ac89e27ac2dee1da72fe9878fc12ba82abd
2,572
java
Java
schnitzelhunt/src/test/java/com/schnitzelhunt/schnitzelhunt/service/GameServiceTest.java
MartinGallauner/SchnitzelHunt
8a017ad57e6fefab213845bd3aababe124e16944
[ "MIT" ]
null
null
null
schnitzelhunt/src/test/java/com/schnitzelhunt/schnitzelhunt/service/GameServiceTest.java
MartinGallauner/SchnitzelHunt
8a017ad57e6fefab213845bd3aababe124e16944
[ "MIT" ]
null
null
null
schnitzelhunt/src/test/java/com/schnitzelhunt/schnitzelhunt/service/GameServiceTest.java
MartinGallauner/SchnitzelHunt
8a017ad57e6fefab213845bd3aababe124e16944
[ "MIT" ]
null
null
null
29.227273
110
0.700622
49
package com.schnitzelhunt.schnitzelhunt.service; import com.schnitzelhunt.schnitzelhunt.persistence.Game; import com.schnitzelhunt.schnitzelhunt.persistence.Player; import com.schnitzelhunt.schnitzelhunt.persistence.repository.GameRepository; import com.schnitzelhunt.schnitzelhunt.webservice.dto.GameUpdateDTO; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.NoSuchElementException; import java.util.Optional; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class GameServiceTest { @InjectMocks private GameService gameService; @Mock private PlayerService playerService; @Mock private GameRepository gameRepository; @Test public void getGame() { Game mockGame = getMockGame(); when(gameRepository.findById(5L)).thenReturn(Optional.of(mockGame)); Game searchedGame = gameService.getGame(5L); assertThat(searchedGame, is(mockGame)); } @Test(expected = NoSuchElementException.class) public void getGame_NotFound() { Game mockGame = getMockGame(); Game searchedGame = gameService.getGame(5L); assertThat(searchedGame, is(mockGame)); } @Test public void createGame_validRequest() { GameUpdateDTO gameRequest = createValidGameRequest(); when(playerService.getPlayer(anyLong())).thenReturn(Player.builder().name("mocker").id(666L).build()); Game game = gameService.createGame(gameRequest); assertThat(game.getTitle(), is(gameRequest.getTitle())); assertThat(game.getMissions().size(), is(0)); } @Test(expected = IllegalArgumentException.class) public void createGame_invalidRequest() { GameUpdateDTO gameRequest = createValidGameRequest(); gameRequest.setTitle(null); Game game = gameService.createGame(gameRequest); assertThat(game.getTitle(), is(gameRequest.getTitle())); assertThat(game.getMissions().size(), is(0)); } private GameUpdateDTO createValidGameRequest() { return GameUpdateDTO.builder() .id(5L) .title("Mock Game") .raiderId(5L) .creatorId(1L) .build(); } private Game getMockGame() { return Game.builder().build(); } }
3e001bcf5993e039ad3b4acb2b1d0a7ec6dc6c85
1,138
java
Java
src/main/java/cn/ms/neural/common/NamedThreadFactory.java
vwyuheng/neural
2073e34475f34d0cf9d7cec934315f1543751f3e
[ "MIT" ]
null
null
null
src/main/java/cn/ms/neural/common/NamedThreadFactory.java
vwyuheng/neural
2073e34475f34d0cf9d7cec934315f1543751f3e
[ "MIT" ]
null
null
null
src/main/java/cn/ms/neural/common/NamedThreadFactory.java
vwyuheng/neural
2073e34475f34d0cf9d7cec934315f1543751f3e
[ "MIT" ]
2
2018-04-09T15:32:03.000Z
2018-12-12T03:43:36.000Z
25.863636
86
0.743409
50
package cn.ms.neural.common; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * InternalThreadFactory. * * @author lry */ public class NamedThreadFactory implements ThreadFactory { private static final AtomicInteger POOL_SEQ = new AtomicInteger(1); private final AtomicInteger mThreadNum = new AtomicInteger(1); private final String mPrefix; private final boolean mDaemo; private final ThreadGroup mGroup; public NamedThreadFactory() { this("pool-" + POOL_SEQ.getAndIncrement(), false); } public NamedThreadFactory(String prefix) { this(prefix, false); } public NamedThreadFactory(String prefix, boolean daemo) { mPrefix = prefix + "-thread-"; mDaemo = daemo; SecurityManager s = System.getSecurityManager(); mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); } public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); Thread ret = new Thread(mGroup, runnable, name, 0); ret.setDaemon(mDaemo); return ret; } public ThreadGroup getThreadGroup() { return mGroup; } }
3e001be235733bea242b6461a5f3fa412291712d
968
java
Java
app/src/main/java/doandkeep/com/practice/ablum/ui/SectionViewHolder.java
DoAndKeep/practice
65bd127afcd9e0406a750e227f36e2d9142c4e7a
[ "Apache-2.0" ]
1
2019-11-23T06:43:21.000Z
2019-11-23T06:43:21.000Z
app/src/main/java/doandkeep/com/practice/ablum/ui/SectionViewHolder.java
DoAndKeep/practice
65bd127afcd9e0406a750e227f36e2d9142c4e7a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/doandkeep/com/practice/ablum/ui/SectionViewHolder.java
DoAndKeep/practice
65bd127afcd9e0406a750e227f36e2d9142c4e7a
[ "Apache-2.0" ]
null
null
null
26.888889
85
0.672521
51
package doandkeep.com.practice.ablum.ui; import android.view.View; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import doandkeep.com.practice.R; import doandkeep.com.practice.ablum.vo.Section; public class SectionViewHolder extends RecyclerView.ViewHolder { private TextView textView; public SectionViewHolder(@NonNull View itemView) { super(itemView); textView = itemView.findViewById(R.id.name); initListener(); } private void initListener() { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO 点击查看详情... Toast.makeText(view.getContext(), "查看详情", Toast.LENGTH_SHORT).show(); } }); } public void bind(Section section) { textView.setText(section.title); } }
3e001c3bad14851771d1a7a0f903a4635b8d6588
16,041
java
Java
generator/src/main/java/org/stjs/generator/plugin/MainGenerationPlugin.java
st-js/st-js
a97a611b39709477b8f6ddb3a05fa64b1976db17
[ "Apache-2.0" ]
97
2015-01-04T11:25:16.000Z
2021-09-26T07:55:01.000Z
generator/src/main/java/org/stjs/generator/plugin/MainGenerationPlugin.java
Brogramr786/st-js
a97a611b39709477b8f6ddb3a05fa64b1976db17
[ "Apache-2.0" ]
83
2015-01-11T21:32:27.000Z
2022-02-01T16:30:43.000Z
generator/src/main/java/org/stjs/generator/plugin/MainGenerationPlugin.java
Brogramr786/st-js
a97a611b39709477b8f6ddb3a05fa64b1976db17
[ "Apache-2.0" ]
30
2015-02-19T19:49:22.000Z
2021-12-01T03:46:03.000Z
49.971963
107
0.802568
52
package org.stjs.generator.plugin; import org.stjs.generator.GenerationContext; import org.stjs.generator.check.CheckVisitor; import org.stjs.generator.check.declaration.ArrayTypeForbiddenCheck; import org.stjs.generator.check.declaration.ClassDuplicateMemberNameCheck; import org.stjs.generator.check.declaration.ClassEnumWithoutMembersCheck; import org.stjs.generator.check.declaration.ClassGlobalForbidInnerCheck; import org.stjs.generator.check.declaration.ClassGlobalInstanceMembersCheck; import org.stjs.generator.check.declaration.ClassImplementJavascriptFunctionCheck; import org.stjs.generator.check.declaration.ClassNamespaceCheck; import org.stjs.generator.check.declaration.FieldInitializerCheck; import org.stjs.generator.check.declaration.MethodDeclarationTemplateCheck; import org.stjs.generator.check.declaration.MethodOverloadCheck; import org.stjs.generator.check.declaration.MethodSynchronizedCheck; import org.stjs.generator.check.declaration.MethodVarArgParamCheck; import org.stjs.generator.check.declaration.MethodWrongNameCheck; import org.stjs.generator.check.expression.IdentifierAccessOuterScopeCheck; import org.stjs.generator.check.expression.IdentifierAccessServerSideCheck; import org.stjs.generator.check.expression.IdentifierGlobalScopeNameClashCheck; import org.stjs.generator.check.expression.MemberSelectGlobalScopeNameClashCheck; import org.stjs.generator.check.expression.MemberSelectOuterScopeCheck; import org.stjs.generator.check.expression.MemberSelectServerSideCheck; import org.stjs.generator.check.expression.MethodInvocationMapConstructorCheck; import org.stjs.generator.check.expression.MethodInvocationOuterScopeCheck; import org.stjs.generator.check.expression.MethodInvocationServerSideCheck; import org.stjs.generator.check.expression.MethodInvocationSuperSynthCheck; import org.stjs.generator.check.expression.NewArrayForbiddenCheck; import org.stjs.generator.check.expression.NewClassInlineFunctionCheck; import org.stjs.generator.check.expression.NewClassObjectInitCheck; import org.stjs.generator.check.statement.AssertCheck; import org.stjs.generator.check.statement.BlockInstanceCheck; import org.stjs.generator.check.statement.SynchronizedCheck; import org.stjs.generator.check.statement.VariableFinalInLoopCheck; import org.stjs.generator.check.statement.VariableWrongNameCheck; import org.stjs.generator.visitor.DiscriminatorKey; import org.stjs.generator.writer.CommentWriter; import org.stjs.generator.writer.CompilationUnitWriter; import org.stjs.generator.writer.WriterVisitor; import org.stjs.generator.writer.declaration.ClassWriter; import org.stjs.generator.writer.declaration.MethodWriter; import org.stjs.generator.writer.expression.ArrayAccessWriter; import org.stjs.generator.writer.expression.AssignmentWriter; import org.stjs.generator.writer.expression.BinaryWriter; import org.stjs.generator.writer.expression.CompoundAssignmentWriter; import org.stjs.generator.writer.expression.ConditionalWriter; import org.stjs.generator.writer.expression.IdentifierWriter; import org.stjs.generator.writer.expression.InstanceofWriter; import org.stjs.generator.writer.expression.LiteralWriter; import org.stjs.generator.writer.expression.MemberSelectWriter; import org.stjs.generator.writer.expression.MethodInvocationWriter; import org.stjs.generator.writer.expression.NewArrayWriter; import org.stjs.generator.writer.expression.NewClassWriter; import org.stjs.generator.writer.expression.ParenthesizedWriter; import org.stjs.generator.writer.expression.TypeCastWriter; import org.stjs.generator.writer.expression.UnaryWriter; import org.stjs.generator.writer.statement.AssertWriter; import org.stjs.generator.writer.statement.BlockWriter; import org.stjs.generator.writer.statement.BreakWriter; import org.stjs.generator.writer.statement.CaseWriter; import org.stjs.generator.writer.statement.CatchWriter; import org.stjs.generator.writer.statement.ContinueWriter; import org.stjs.generator.writer.statement.DoWhileLoopWriter; import org.stjs.generator.writer.statement.EmptyStatementWriter; import org.stjs.generator.writer.statement.EnhancedForLoopWriter; import org.stjs.generator.writer.statement.ExpressionStatementWriter; import org.stjs.generator.writer.statement.ForLoopWriter; import org.stjs.generator.writer.statement.IfWriter; import org.stjs.generator.writer.statement.LabeledStatementWriter; import org.stjs.generator.writer.statement.ReturnWriter; import org.stjs.generator.writer.statement.SwitchWriter; import org.stjs.generator.writer.statement.SynchronizedWriter; import org.stjs.generator.writer.statement.ThrowWriter; import org.stjs.generator.writer.statement.TryWriter; import org.stjs.generator.writer.statement.VariableWriter; import org.stjs.generator.writer.statement.WhileLoopWriter; import org.stjs.generator.writer.templates.AdapterTemplate; import org.stjs.generator.writer.templates.ArrayTemplate; import org.stjs.generator.writer.templates.AssertTemplate; import org.stjs.generator.writer.templates.DefaultTemplate; import org.stjs.generator.writer.templates.DeleteTemplate; import org.stjs.generator.writer.templates.GetTemplate; import org.stjs.generator.writer.templates.InvokeTemplate; import org.stjs.generator.writer.templates.JsTemplate; import org.stjs.generator.writer.templates.MapTemplate; import org.stjs.generator.writer.templates.MethodToPropertyTemplate; import org.stjs.generator.writer.templates.OrTemplate; import org.stjs.generator.writer.templates.PrefixTemplate; import org.stjs.generator.writer.templates.PropertiesTemplate; import org.stjs.generator.writer.templates.PutTemplate; import org.stjs.generator.writer.templates.SetTemplate; import org.stjs.generator.writer.templates.SuffixTemplate; import org.stjs.generator.writer.templates.TypeOfTemplate; import org.stjs.generator.writer.templates.fields.PathGetterMemberSelectTemplate; import org.stjs.generator.writer.templates.fields.DefaultAssignmentTemplate; import org.stjs.generator.writer.templates.fields.DefaultCompoundAssignmentTemplate; import org.stjs.generator.writer.templates.fields.DefaultIdentifierTemplate; import org.stjs.generator.writer.templates.fields.DefaultMemberSelectTemplate; import org.stjs.generator.writer.templates.fields.DefaultUnaryTemplate; import org.stjs.generator.writer.templates.fields.GetterIdentifierTemplate; import org.stjs.generator.writer.templates.fields.GetterMemberSelectTemplate; import org.stjs.generator.writer.templates.fields.GlobalGetterIdentifierTemplate; import org.stjs.generator.writer.templates.fields.GlobalGetterMemberSelectTemplate; import org.stjs.generator.writer.templates.fields.GlobalSetterAssignmentTemplate; import org.stjs.generator.writer.templates.fields.GlobalSetterCompoundAssignmentTemplate; import org.stjs.generator.writer.templates.fields.GlobalSetterUnaryTemplate; import org.stjs.generator.writer.templates.fields.SetterAssignmentTemplate; import org.stjs.generator.writer.templates.fields.SetterCompoundAssignmentTemplate; import org.stjs.generator.writer.templates.fields.SetterUnaryTemplate; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; /** * this is the main generation plugin that adds all the needed checks and writers. * * @author acraciun * @version $Id: $Id */ public class MainGenerationPlugin<JS> implements STJSGenerationPlugin<JS> { /** * <p>newContext.</p> * * @return a {@link org.stjs.generator.GenerationContext} object. */ public GenerationContext<JS> newContext() { return null; } /** {@inheritDoc} */ @Override public void contributeCheckVisitor(CheckVisitor visitor) { visitor.contribute(new VariableFinalInLoopCheck()); visitor.contribute(new VariableWrongNameCheck()); visitor.contribute(new MethodVarArgParamCheck()); visitor.contribute(new FieldInitializerCheck()); visitor.contribute(new ClassDuplicateMemberNameCheck()); visitor.contribute(new NewClassInlineFunctionCheck()); visitor.contribute(new ClassImplementJavascriptFunctionCheck()); visitor.contribute(new ClassGlobalInstanceMembersCheck()); visitor.contribute(new ClassNamespaceCheck()); visitor.contribute(new MethodOverloadCheck()); visitor.contribute(new NewClassObjectInitCheck()); visitor.contribute(new ArrayTypeForbiddenCheck()); visitor.contribute(new ClassEnumWithoutMembersCheck()); visitor.contribute(new NewArrayForbiddenCheck()); visitor.contribute(new BlockInstanceCheck()); visitor.contribute(new MethodInvocationMapConstructorCheck()); visitor.contribute(new SynchronizedCheck()); visitor.contribute(new MethodSynchronizedCheck()); visitor.contribute(new AssertCheck()); visitor.contribute(new IdentifierGlobalScopeNameClashCheck()); visitor.contribute(new MemberSelectGlobalScopeNameClashCheck()); visitor.contribute(new MethodDeclarationTemplateCheck()); visitor.contribute(new IdentifierAccessOuterScopeCheck()); visitor.contribute(new MethodInvocationOuterScopeCheck()); visitor.contribute(new MemberSelectOuterScopeCheck()); visitor.contribute(new ClassGlobalForbidInnerCheck()); visitor.contribute(new MethodInvocationSuperSynthCheck()); visitor.contribute(new IdentifierAccessServerSideCheck()); visitor.contribute(new MemberSelectServerSideCheck()); visitor.contribute(new MethodInvocationServerSideCheck()); visitor.contribute(new MethodWrongNameCheck()); } /** {@inheritDoc} */ @Override public void contributeWriteVisitor(WriterVisitor<JS> visitor) { visitor.contribute(new CompilationUnitWriter<JS>()); visitor.contribute(new ClassWriter<JS>()); visitor.contribute(new MethodWriter<JS>()); visitor.contribute(new ArrayAccessWriter<JS>()); visitor.contribute(new AssignmentWriter<JS>()); visitor.contribute(new BinaryWriter<JS>()); visitor.contribute(new CompoundAssignmentWriter<JS>()); visitor.contribute(new ConditionalWriter<JS>()); visitor.contribute(new IdentifierWriter<JS>()); visitor.contribute(new InstanceofWriter<JS>()); visitor.contribute(new LiteralWriter<JS>()); visitor.contribute(new MemberSelectWriter<JS>()); visitor.contribute(new MethodInvocationWriter<JS>()); visitor.contribute(new NewArrayWriter<JS>()); visitor.contribute(new NewClassWriter<JS>()); visitor.contribute(new ParenthesizedWriter<JS>()); visitor.contribute(new TypeCastWriter<JS>()); visitor.contribute(new UnaryWriter<JS>()); visitor.contribute(new AssertWriter<JS>()); visitor.contribute(new BlockWriter<JS>()); visitor.contribute(new BreakWriter<JS>()); visitor.contribute(new CaseWriter<JS>()); visitor.contribute(new CatchWriter<JS>()); visitor.contribute(new ContinueWriter<JS>()); visitor.contribute(new DoWhileLoopWriter<JS>()); visitor.contribute(new EmptyStatementWriter<JS>()); visitor.contribute(new EnhancedForLoopWriter<JS>()); visitor.contribute(new ExpressionStatementWriter<JS>()); visitor.contribute(new ForLoopWriter<JS>()); visitor.contribute(new IfWriter<JS>()); visitor.contribute(new LabeledStatementWriter<JS>()); visitor.contribute(new ReturnWriter<JS>()); visitor.contribute(new SwitchWriter<JS>()); visitor.contribute(new SynchronizedWriter<JS>()); visitor.contribute(new TryWriter<JS>()); visitor.contribute(new VariableWriter<JS>()); visitor.contribute(new WhileLoopWriter<JS>()); visitor.contribute(new ThrowWriter<JS>()); addMethodCallTemplates(visitor); addFieldTemplates(visitor); addJavaDocCommentFilter(visitor); } private void addJavaDocCommentFilter(WriterVisitor<JS> visitor) { CommentWriter<JS> cw = new CommentWriter<JS>(); visitor.addFilter(cw, ClassTree.class); visitor.addFilter(cw, MethodTree.class); visitor.addFilter(cw, VariableTree.class); } private DiscriminatorKey template(String name) { return DiscriminatorKey.of(MethodInvocationWriter.class.getSimpleName(), name); } private DiscriminatorKey assignTemplate(String name) { return DiscriminatorKey.of(AssignmentWriter.class.getSimpleName(), name); } private DiscriminatorKey unaryTemplate(String name) { return DiscriminatorKey.of(UnaryWriter.class.getSimpleName(), name); } private DiscriminatorKey compoundAssignTemplate(String name) { return DiscriminatorKey.of(CompoundAssignmentWriter.class.getSimpleName(), name); } private DiscriminatorKey identifierTemplate(String name) { return DiscriminatorKey.of(IdentifierWriter.class.getSimpleName(), name); } private DiscriminatorKey memberSelectTemplate(String name) { return DiscriminatorKey.of(MemberSelectWriter.class.getSimpleName(), name); } /** * <p>addMethodCallTemplates.</p> * * @param visitor a {@link org.stjs.generator.writer.WriterVisitor} object. */ protected void addMethodCallTemplates(WriterVisitor<JS> visitor) { visitor.contribute(template("adapter"), new AdapterTemplate<JS>()); visitor.contribute(template("array"), new ArrayTemplate<JS>()); visitor.contribute(template("delete"), new DeleteTemplate<JS>()); visitor.contribute(template("get"), new GetTemplate<JS>()); visitor.contribute(template("invoke"), new InvokeTemplate<JS>()); visitor.contribute(template("js"), new JsTemplate<JS>()); visitor.contribute(template("map"), new MapTemplate<JS>()); visitor.contribute(template("toProperty"), new MethodToPropertyTemplate<JS>()); visitor.contribute(template("or"), new OrTemplate<JS>()); visitor.contribute(template("prefix"), new PrefixTemplate<JS>()); visitor.contribute(template("suffix"), new SuffixTemplate<JS>()); visitor.contribute(template("properties"), new PropertiesTemplate<JS>()); visitor.contribute(template("put"), new PutTemplate<JS>()); visitor.contribute(template("set"), new SetTemplate<JS>()); visitor.contribute(template("typeOf"), new TypeOfTemplate<JS>()); visitor.contribute(template("assert"), new AssertTemplate<JS>()); visitor.contribute(template("none"), new DefaultTemplate<JS>()); } /** * <p>addFieldTemplates.</p> * * @param visitor a {@link org.stjs.generator.writer.WriterVisitor} object. */ protected void addFieldTemplates(WriterVisitor<JS> visitor) { String none = "none"; String property = "property"; String gproperty = "gproperty"; String path = "path"; visitor.contribute(assignTemplate(none), new DefaultAssignmentTemplate<JS>()); visitor.contribute(assignTemplate(property), new SetterAssignmentTemplate<JS>()); visitor.contribute(assignTemplate(gproperty), new GlobalSetterAssignmentTemplate<JS>()); visitor.contribute(unaryTemplate(none), new DefaultUnaryTemplate<JS>()); visitor.contribute(unaryTemplate(property), new SetterUnaryTemplate<JS>()); visitor.contribute(unaryTemplate(gproperty), new GlobalSetterUnaryTemplate<JS>()); visitor.contribute(compoundAssignTemplate(none), new DefaultCompoundAssignmentTemplate<JS>()); visitor.contribute(compoundAssignTemplate(property), new SetterCompoundAssignmentTemplate<JS>()); visitor.contribute(compoundAssignTemplate(gproperty), new GlobalSetterCompoundAssignmentTemplate<JS>()); visitor.contribute(identifierTemplate(none), new DefaultIdentifierTemplate<JS>()); visitor.contribute(identifierTemplate(property), new GetterIdentifierTemplate<JS>()); visitor.contribute(identifierTemplate(gproperty), new GlobalGetterIdentifierTemplate<JS>()); visitor.contribute(memberSelectTemplate(none), new DefaultMemberSelectTemplate<JS>()); visitor.contribute(memberSelectTemplate(property), new GetterMemberSelectTemplate<JS>()); visitor.contribute(memberSelectTemplate(gproperty), new GlobalGetterMemberSelectTemplate<JS>()); visitor.contribute(memberSelectTemplate(path), new PathGetterMemberSelectTemplate<JS>()); } /** {@inheritDoc} */ @Override public boolean loadByDefault() { return true; } }
3e001ca4f8b0a03224129e9d6c227eca215f561d
1,806
java
Java
java/com/p1nesap/ezdungeon/ui/GoldIndicator.java
paulm1/EZDungeon
3a7ebe9ea58ad907157dad2c2304b87b54a772ee
[ "Unlicense" ]
1
2016-04-03T07:17:47.000Z
2016-04-03T07:17:47.000Z
java/com/p1nesap/ezdungeon/ui/GoldIndicator.java
p1nesap/EZDungeon
3a7ebe9ea58ad907157dad2c2304b87b54a772ee
[ "Unlicense" ]
null
null
null
java/com/p1nesap/ezdungeon/ui/GoldIndicator.java
p1nesap/EZDungeon
3a7ebe9ea58ad907157dad2c2304b87b54a772ee
[ "Unlicense" ]
null
null
null
22.575
71
0.673311
53
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.p1nesap.ezdungeon.ui; import com.p1nesap.noosa.BitmapText; import com.p1nesap.noosa.Game; import com.p1nesap.noosa.ui.Component; import com.p1nesap.ezdungeon.Dungeon; import com.p1nesap.ezdungeon.scenes.PixelScene; public class GoldIndicator extends Component { private static final float TIME = 2f; private int lastValue = 0; private BitmapText tf; private float time; @Override protected void createChildren() { tf = new BitmapText( PixelScene.font1x ); tf.hardlight( 0xFFFF00 ); add( tf ); visible = false; } @Override protected void layout() { tf.x = x + (width - tf.width()) / 2; tf.y = bottom() - tf.height(); } @Override public void update() { super.update(); if (visible) { time -= Game.elapsed; if (time > 0) { tf.alpha( time > TIME / 2 ? 1f : time * 2 / TIME ); } else { visible = false; } } if (Dungeon.gold != lastValue) { lastValue = Dungeon.gold; tf.text( Integer.toString( lastValue ) ); tf.measure(); visible = true; time = TIME; layout(); } } }
3e001d1c6dc6ee5587f3b273a4760fea57a967fd
1,657
java
Java
src/main/java/org/jitsi/xmpp/extensions/jingle/CoinPacketExtension.java
Celebrate-future/jitsi-xmpp-extensions
0362d50ab99b6f7d1e6b1f4f5a321a7a6ad82799
[ "Apache-2.0" ]
13
2019-05-24T04:17:26.000Z
2022-01-12T03:30:16.000Z
src/main/java/org/jitsi/xmpp/extensions/jingle/CoinPacketExtension.java
Celebrate-future/jitsi-xmpp-extensions
0362d50ab99b6f7d1e6b1f4f5a321a7a6ad82799
[ "Apache-2.0" ]
19
2019-04-03T17:34:23.000Z
2022-03-16T16:33:07.000Z
src/main/java/org/jitsi/xmpp/extensions/jingle/CoinPacketExtension.java
Celebrate-future/jitsi-xmpp-extensions
0362d50ab99b6f7d1e6b1f4f5a321a7a6ad82799
[ "Apache-2.0" ]
46
2019-05-25T18:27:51.000Z
2022-03-29T05:41:36.000Z
25.890625
75
0.66204
54
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.xmpp.extensions.jingle; import org.jitsi.xmpp.extensions.*; /** * Represents the conference information. * * @author Sebastien Vincent */ public class CoinPacketExtension extends AbstractPacketExtension { /** * Name of the XML element representing the extension. */ public final static String ELEMENT = "conference-info"; /** * Namespace. */ public final static String NAMESPACE = "urn:xmpp:coin:1"; /** * IsFocus attribute name. */ public final static String ISFOCUS_ATTR_NAME = "isfocus"; /** * Constructs a new <tt>coin</tt> extension. * */ public CoinPacketExtension() { super(NAMESPACE, ELEMENT); } /** * Constructs a new <tt>coin</tt> extension. * * @param isFocus <tt>true</tt> if the peer is a conference focus; * otherwise, <tt>false</tt> */ public CoinPacketExtension(boolean isFocus) { super(NAMESPACE, ELEMENT); setAttribute(ISFOCUS_ATTR_NAME, isFocus); } }
3e001e9337e1592ff742a63ceb6fd92f21ae9174
18,554
java
Java
modules/core/src/main/java/org/eclipse/imagen/RenderedImageList.java
ktgw0316/imagen
b8d2de20b53501e85d8e41b325adf00fc826ae25
[ "Apache-2.0" ]
15
2019-05-07T08:31:33.000Z
2020-10-26T01:56:08.000Z
modules/core/src/main/java/org/eclipse/imagen/RenderedImageList.java
ktgw0316/imagen
b8d2de20b53501e85d8e41b325adf00fc826ae25
[ "Apache-2.0" ]
7
2019-04-29T19:14:06.000Z
2019-05-24T02:38:17.000Z
modules/core/src/main/java/org/eclipse/imagen/RenderedImageList.java
ktgw0316/imagen
b8d2de20b53501e85d8e41b325adf00fc826ae25
[ "Apache-2.0" ]
10
2019-04-18T15:27:07.000Z
2022-03-02T11:36:34.000Z
35.476099
93
0.6314
55
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.eclipse.imagen; import java.awt.Rectangle; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Vector; /** * A <code>CollectionImage</code> which is also a * <code>RenderedImage</code>. The underlying <code>Collection</code> * in this case is required to be a <code>List</code> containing only * <code>RenderedImage</code>s. * * <p> Instances of this class may be returned from either a * <code>RenderedImageFactory</code> or from a * <code>CollectionImageFactory</code>. This class would be * particularly useful for implementing operations the result of which * includes a single primary image and one or more secondary or * dependant images the data of which are less likely to be requested. * * <p> Invocations of <code>RenderedImage</code> methods on an instance * of this class will be forwarded to the first <code>RenderedImage</code> * in the underlying <code>List</code>, i.e., the image at index zero. * This should be the index assigned to the primary image in the case * alluded to above. If there are no images in the <code>List</code> * when a <code>RenderedImage</code> method is invoked an * <code>IllegalStateException</code> will be thrown. * * <p> One example of the use of this class is in generating a classmap * image using a classification algorithm. A by-product image of such an * operation is often an error image wherein the value of each pixel is * some measure of the classification error at that pixel. In this case * the classmap image would be stored at index zero in the internal list * and the error image at the unity index. The error image would be * an <code>OpImage</code> that has the classmap image as its source. * The result is that a reference to the error image is always available * with the classmap image but the computation of the error image pixel * values may be deferred until such time as the data are needed, if ever. * * <p> Methods defined in the <code>RenderedImage</code> and <code>List</code> * interfaces are not all commented in detail. The <code>List</code> methods * merely forward the call in most cases directly to the underlying * <code>List</code>; as previously stated, <code>RenderedImage</code> method * invocations are forwarded to the <code>RenderedImage</code> at position * zero in the <code>List</code>. * * @since JAI 1.1 * @see CollectionImage * @see java.awt.image.RenderedImage * @see java.util.List */ public class RenderedImageList extends CollectionImage implements List, RenderedImage, Serializable { /** * Creates an empty <code>RenderedImageList</code>. */ protected RenderedImageList() { super(); } /** * Creates a <code>RenderedImageList</code> from the supplied * <code>List</code>. * * @throws <code>IllegalArgumentException</code> if any objects in the * <code>List</code> are not <code>RenderedImage</code>s. * @throws <code>IllegalArgumentException</code> if the <code>List</code> * is empty. * @throws <code>IllegalArgumentException</code> if the <code>List</code> * parameter is <code>null</code>. */ public RenderedImageList(List renderedImageList) { super(); // separate throws, for better error reporting if ( renderedImageList == null ) { throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList0")); } if ( renderedImageList.isEmpty() ) { throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList1")); } Iterator iter = renderedImageList.iterator(); imageCollection = new Vector(); while( iter.hasNext() ) { Object item = iter.next(); if ( item instanceof RenderedImage ) { imageCollection.add(item); } else { throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList2")); } } } /// --- RenderedImage methods. --- /** * Returns the image <code>Collection</code> as a <code>List</code>. */ private List getList() { return (List)imageCollection; } /** * Returns the first image in the underlying list of * <code>RenderedImage</code>s. * The call is forwarded to the first image in the <code>List</code>. */ public RenderedImage getPrimaryImage() { return (RenderedImage)getList().get(0); } /** * Returns the X coordinate of the leftmost column of the * primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getMinX() { return ((RenderedImage) getList().get(0)).getMinX(); } /** * Returns the X coordinate of the uppermost row of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getMinY() { return ((RenderedImage) getList().get(0)).getMinY(); } /** * Returns the width of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getWidth() { return ((RenderedImage) getList().get(0)).getWidth(); } /** * Returns the height of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getHeight() { return ((RenderedImage) getList().get(0)).getHeight(); } /** * Returns the width of a tile of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getTileWidth() { return ((RenderedImage) getList().get(0)).getTileWidth(); } /** * Returns the height of a tile of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getTileHeight() { return ((RenderedImage) getList().get(0)).getTileHeight(); } /** * Returns the X coordinate of the upper-left pixel of tile (0, 0) * of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getTileGridXOffset() { return ((RenderedImage) getList().get(0)).getTileGridXOffset(); } /** * Returns the Y coordinate of the upper-left pixel of tile (0, 0) * of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getTileGridYOffset() { return ((RenderedImage) getList().get(0)).getTileGridYOffset(); } /** * Returns the horizontal index of the leftmost column of tiles * of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getMinTileX() { return ((RenderedImage) getList().get(0)).getMinTileX(); } /** * Returns the number of tiles of the primary image along the * tile grid in the horizontal direction. * The call is forwarded to the first image in the <code>List</code>. */ public int getNumXTiles() { return ((RenderedImage) getList().get(0)).getNumXTiles(); } /** * Returns the vertical index of the uppermost row of tiles * of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public int getMinTileY() { return ((RenderedImage) getList().get(0)).getMinTileY(); } /** * Returns the number of tiles of the primary image along the * tile grid in the vertical direction. * The call is forwarded to the first image in the <code>List</code>. */ public int getNumYTiles() { return ((RenderedImage) getList().get(0)).getNumYTiles(); } /** * Returns the SampleModel of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public SampleModel getSampleModel() { return ((RenderedImage) getList().get(0)).getSampleModel(); } /** * Returns the ColorModel of the primary image. * The call is forwarded to the first image in the <code>List</code>. */ public ColorModel getColorModel() { return ((RenderedImage) getList().get(0)).getColorModel(); } /** * Gets a property from the property set of this image. If the * property name is not recognized, * <code>java.awt.Image.UndefinedProperty</code> will be returned. * The call is forwarded to the first image in the <code>List</code>. * * @param name the name of the property to get, as a * <code>String</code>. * @return a reference to the property * <code>Object</code>, or the value * <code>java.awt.Image.UndefinedProperty.</code> * @throws IllegalArgumentException if <code>name</code> is * <code>null</code>. */ public Object getProperty(String name) { if ( name == null ) { throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList0")); } return ((RenderedImage) getList().get(0)).getProperty(name); } /** * Returns a list of the properties recognized by this image. If * no properties are available, <code>null</code> will be * returned. * The call is forwarded to the first image in the <code>List</code>. * * @return an array of <code>String</code>s representing valid * property names. */ public String[] getPropertyNames() { return ((RenderedImage) getList().get(0)).getPropertyNames(); } /** * Returns a <code>Vector</code> containing the image sources. * The call is forwarded to the first image in the <code>List</code>. */ public Vector getSources() { return ((RenderedImage) getList().get(0)).getSources(); } /** * Returns tile (<code>tileX</code>, <code>tileY</code>) of the * primary image as a <code>Raster</code>. Note that <code>tileX</code> * and <code>tileY</code> are indices into the tile array, not pixel * locations. * The call is forwarded to the first image in the <code>List</code>. * * @param tileX The X index of the requested tile in the tile array. * @param tileY The Y index of the requested tile in the tile array. */ public Raster getTile(int tileX, int tileY) { return ((RenderedImage) getList().get(0)).getTile(tileX, tileY); } /** * Returns the entire primary image in a single <code>Raster</code>. * For images with multiple tiles this will require making a copy. * The returned <code>Raster</code> is semantically a copy. * The call is forwarded to the first image in the <code>List</code>. * * @return a <code>Raster</code> containing a copy of this image's data. */ public Raster getData() { return ((RenderedImage) getList().get(0)).getData(); } /** * Returns an arbitrary rectangular region of the primary image * in a <code>Raster</code>. The returned <code>Raster</code> is * semantically a copy. * The call is forwarded to the first image in the <code>List</code>. * * @param bounds the region of the <code>RenderedImage</code> to be * returned. */ public Raster getData(Rectangle bounds) { return ((RenderedImage) getList().get(0)).getData(bounds); } /** * Copies an arbitrary rectangular region of the primary image * into a caller-supplied WritableRaster. The region to be * computed is determined by clipping the bounds of the supplied * WritableRaster against the bounds of the image. The supplied * WritableRaster must have a SampleModel that is compatible with * that of the image. * * <p> If the raster argument is null, the entire image will * be copied into a newly-created WritableRaster with a SampleModel * that is compatible with that of the image. * The call is forwarded to the first image in the <code>List</code>. * * @param dest a WritableRaster to hold the returned portion of * the image. * @return a reference to the supplied WritableRaster, or to a * new WritableRaster if the supplied one was null. */ public WritableRaster copyData(WritableRaster dest) { return ((RenderedImage) getList().get(0)).copyData(dest); } /// --- List methods. --- /** * Inserts the specified element at the specified position in this list. * * @throws IllegalArgumentException if the specified element * is not a <code>RenderedImage</code>. * @throws IndexOutOfBoundsException if the index is out of range * (index &lt; 0 || index &gt; size()). */ public void add(int index, Object element) { if ( element instanceof RenderedImage ) { if ( index >=0 && index <= imageCollection.size() ) { ((List)imageCollection).add(index, element); } else { throw new IndexOutOfBoundsException(JaiI18N.getString("RenderedImageList3")); } } else { throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList2")); } } /** * Inserts into this <code>List</code> at the indicated position * all elements in the specified <code>Collection</code> which are * <code>RenderedImage</code>s. * * @return <code>true</code> if this <code>List</code> changed * as a result of the call. * @throws IndexOutOfBoundsException if the index is out of range * (index &lt; 0 || index &gt; size()). */ public boolean addAll(int index, Collection c) { // Add only elements of c which are RenderedImages. if ( index < 0 || index > imageCollection.size() ) { throw new IndexOutOfBoundsException(JaiI18N.getString("RenderedImageList3")); } // Only allow RenderedImages Vector temp = null; Iterator iter = c.iterator(); while( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof RenderedImage ) { if ( temp == null ) { temp = new Vector(); } temp.add( o ); } } return ((List)imageCollection).addAll(index, temp); } /** * @return the <code>RenderedImage</code> object at the * specified index. * * @param index index of element to return. * @return the element at the specified position in this list. * * @throws IndexOutOfBoundsException if the index is out of range (index * &lt; 0 || index &gt;= size()). */ public Object get(int index) { if ( index < 0 || index >= imageCollection.size() ) { throw new IndexOutOfBoundsException(JaiI18N.getString("RenderedImageList3")); } return ((List)imageCollection).get(index); } public int indexOf(Object o) { // Do not throw an <code>IllegalArgumentException</code> even // if o is not a RenderedImage. return ((List)imageCollection).indexOf(o); } public int lastIndexOf(Object o) { // Do not throw an <code>IllegalArgumentException</code> even // if o is not a RenderedImage. return ((List)imageCollection).lastIndexOf(o); } public ListIterator listIterator() { return ((List)imageCollection).listIterator(); } public ListIterator listIterator(int index) { return ((List)imageCollection).listIterator(index); } public Object remove(int index) { return ((List)imageCollection).remove(index); } public Object set(int index, Object element) { if ( element instanceof RenderedImage ) { return ((List)imageCollection).set(index, element); } throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList2")); } public List subList(int fromIndex, int toIndex) { return ((List)imageCollection).subList(fromIndex, toIndex); } // --- Collection methods: overridden to require RenderedImages. --- /** * Adds the specified object to this <code>List</code>. * * @throws IllegalArgumentException if <code>o</code> is <code>null</code> * or is not an <code>RenderedImage</code>. * * @return <code>true</code> if and only if the parameter is added to the * <code>List</code>. */ public boolean add(Object o) { if ( o == null ) { throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList0")); } if ( o instanceof RenderedImage ) { imageCollection.add(o); return true; } else { throw new IllegalArgumentException(JaiI18N.getString("RenderedImageList2")); } } /** * Adds to this <code>List</code> all elements in the specified * <code>Collection</code> which are <code>RenderedImage</code>s. * * @return <code>true</code> if this <code>List</code> changed * as a result of the call. */ public boolean addAll(Collection c) { Iterator iter = c.iterator(); boolean status = false; while( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof RenderedImage ) { imageCollection.add(o); status = true; } } return status; } }
3e001f5bd5e81aed72729acc28ac5cd0c8a325a2
301
java
Java
rest/src/main/java/game/geography/rest/LandResource.java
Hans-and-Peter/game-geography
17ed9e87065f74ead08945b9775e3f6da8aa6134
[ "BSD-2-Clause" ]
null
null
null
rest/src/main/java/game/geography/rest/LandResource.java
Hans-and-Peter/game-geography
17ed9e87065f74ead08945b9775e3f6da8aa6134
[ "BSD-2-Clause" ]
null
null
null
rest/src/main/java/game/geography/rest/LandResource.java
Hans-and-Peter/game-geography
17ed9e87065f74ead08945b9775e3f6da8aa6134
[ "BSD-2-Clause" ]
null
null
null
18.8125
58
0.591362
56
package game.geography.rest; /** * Warning: This class fields are public API. */ public class LandResource { /** * Name of the land, e.g. 'Stormland'. */ public String landName; /** * Name of the owner of that land, e.g. 'King Ragnar'. */ public String owner; }
3e001f731e8af6b237e84dfedcff90e0075a2a58
1,004
java
Java
chapter_010/mapping/src/main/java/ru/sdroman/carsales/repository/ModelRepository.java
roman-sd/java-a-to-z
5f59ece8793e0a3df099ff079954aaa7d900a918
[ "Apache-2.0" ]
null
null
null
chapter_010/mapping/src/main/java/ru/sdroman/carsales/repository/ModelRepository.java
roman-sd/java-a-to-z
5f59ece8793e0a3df099ff079954aaa7d900a918
[ "Apache-2.0" ]
null
null
null
chapter_010/mapping/src/main/java/ru/sdroman/carsales/repository/ModelRepository.java
roman-sd/java-a-to-z
5f59ece8793e0a3df099ff079954aaa7d900a918
[ "Apache-2.0" ]
null
null
null
22.818182
125
0.600598
57
package ru.sdroman.carsales.repository; import ru.sdroman.carsales.models.Model; import java.util.List; /** * @author sdroman * @since 06.2018 */ public class ModelRepository extends Repository { /** * Returns list of model. * * @return List */ public List<Model> getModels() { return super.execute(session -> session.createQuery("from ru.sdroman.carsales.models.Model").list()); } /** * Returns model by name. * * @param name String * @return Model */ public Model getModelByName(String name) { return (Model) super.execute(session -> session.createQuery("from ru.sdroman.carsales.models.Model where name=:name") .setParameter("name", name) .uniqueResult()); } /** * Adds model to db. * * @param model Model * @return int modelId */ public int addModel(Model model) { return (int) super.execute(session -> session.save(model)); } }
3e001fa184547af1ef2f25f5525d6e19d6b2db0b
841
java
Java
template/@__scope__@-@__template__@-platform.git/@__scope__@-@__template__@-server/src/main/java/com/@__company__@/@__scope__@/@__template__@/domain/support/ConstantContext.java
biticcf/template_jdk1.8_webmvc_platform
62a03040071e7db87ce136aa11adcd20bdd410e4
[ "Apache-2.0" ]
5
2019-02-15T06:35:08.000Z
2020-09-11T01:20:17.000Z
template/@__scope__@-@__template__@-platform.git/@__scope__@-@__template__@-server/src/main/java/com/@__company__@/@__scope__@/@__template__@/domain/support/ConstantContext.java
biticcf/template_jdk1.8_webflux_platform
13890e03428972dc1a169324ebd5802022aec048
[ "Apache-2.0" ]
null
null
null
template/@__scope__@-@__template__@-platform.git/@__scope__@-@__template__@-server/src/main/java/com/@__company__@/@__scope__@/@__template__@/domain/support/ConstantContext.java
biticcf/template_jdk1.8_webflux_platform
13890e03428972dc1a169324ebd5802022aec048
[ "Apache-2.0" ]
null
null
null
25.342857
91
0.785795
58
/** * */ package com.@__company__@.@__scope__@.@efpyi@example.com; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import com.@__company__@.@__scope__@.@ychag@example.com; import com.github.biticcf.mountain.core.common.service.ReferContext; /** * @Author: DanielCao * @Date: 2017年5月8日 * @Time: 下午6:27:27 * */ @Service("constantContext") public class ConstantContext implements ReferContext { @Autowired private DemoDomainRepository demoDomainRepository; @Autowired private RedisTemplate<String, Object> redisTemplate; public DemoDomainRepository getDemoDomainRepository() { return demoDomainRepository; } public RedisTemplate<String, Object> getRedisTemplate() { return redisTemplate; } }
3e002027becdbb5fca00e3aedf4b6ef13e42965c
8,892
java
Java
project5/gradingScript/P5coord.java
wmwmss/CS211OOP
f3e58c523f7d5231850ea8a220a55b2868d32b27
[ "MIT" ]
null
null
null
project5/gradingScript/P5coord.java
wmwmss/CS211OOP
f3e58c523f7d5231850ea8a220a55b2868d32b27
[ "MIT" ]
null
null
null
project5/gradingScript/P5coord.java
wmwmss/CS211OOP
f3e58c523f7d5231850ea8a220a55b2868d32b27
[ "MIT" ]
null
null
null
66.358209
125
0.724134
59
import org.junit.*; import static org.junit.Assert.*; import java.util.*; public class P5coord { private static Object[][][] data = { {{5, "Coordinate class grader"}, {"coordinate_constructor", 1.0, "constructor exists"}, {"coordinate_getxy_.*", 1.0, "X,Y getters"}, {"coordinate_plus_xy_.*", 1.0, "plus(int,int)"}, {"coordinate_plus_delta_.*", 1.0, "plus(Coordinate)"}, {"coordinate_tostring_.*", 1.0, "toString"}, }, }; private final double ERR = GradeHelper.ERR; public static void main(String args[]){ GradeHelper.tester(new P5coord().getClass(), data, args); } @Test(timeout=1000) public void coordinate_constructor() throws Exception { new Coordinate(0,0); } private int[][] coordinates = { {0,0}, {0,1}, {1,0}, {0,-1}, {-1,0}, {1,1}, {1,-1}, {-1,1}, {-1,-1}, {48,49}, {2, 300}, {-32,43}, {-2,243}, {234,-234}, {34,-24}, {-23,-38} }; private void check_coord(int i) throws Exception { int[] pair = coordinates[i]; int x = pair[0]; int y = pair[1]; Coordinate c = new Coordinate(x,y); String errMsg = String.format("Coordinate (%d, %d) incorrect ", x, y); assertEquals(errMsg + "X", x, c.getX()); assertEquals(errMsg + "Y", y, c.getY()); } @Test(timeout=1000) public void coordinate_getxy_0() throws Exception { check_coord(0); } @Test(timeout=1000) public void coordinate_getxy_1() throws Exception { check_coord(1); } @Test(timeout=1000) public void coordinate_getxy_2() throws Exception { check_coord(2); } @Test(timeout=1000) public void coordinate_getxy_3() throws Exception { check_coord(3); } @Test(timeout=1000) public void coordinate_getxy_4() throws Exception { check_coord(4); } @Test(timeout=1000) public void coordinate_getxy_5() throws Exception { check_coord(5); } @Test(timeout=1000) public void coordinate_getxy_6() throws Exception { check_coord(6); } @Test(timeout=1000) public void coordinate_getxy_7() throws Exception { check_coord(7); } @Test(timeout=1000) public void coordinate_getxy_8() throws Exception { check_coord(8); } @Test(timeout=1000) public void coordinate_getxy_9() throws Exception { check_coord(9); } @Test(timeout=1000) public void coordinate_getxy_a() throws Exception { check_coord(10); } @Test(timeout=1000) public void coordinate_getxy_b() throws Exception { check_coord(11); } @Test(timeout=1000) public void coordinate_getxy_c() throws Exception { check_coord(12); } @Test(timeout=1000) public void coordinate_getxy_d() throws Exception { check_coord(13); } @Test(timeout=1000) public void coordinate_getxy_e() throws Exception { check_coord(14); } @Test(timeout=1000) public void coordinate_getxy_f() throws Exception { check_coord(15); } private void check_plus_xy(int a, int b) throws Exception { int[] pair1 = coordinates[a], pair2 = coordinates[b], pair3 = {pair1[0]+pair2[0], pair1[1]+pair2[1]}; Coordinate c = new Coordinate(pair1[0], pair1[1]).plus(pair2[0], pair2[1]); String errMsg = String.format("Coordinate (%d, %d).plus(%d, %d) incorrect ", pair1[0], pair1[1], pair2[0], pair2[1]); assertEquals(errMsg + "X", pair3[0], c.getX()); assertEquals(errMsg + "Y", pair3[1], c.getY()); } @Test(timeout=1000) public void coordinate_plus_xy_00() throws Exception { check_plus_xy(0,0); } @Test(timeout=1000) public void coordinate_plus_xy_12() throws Exception { check_plus_xy(1,2); } @Test(timeout=1000) public void coordinate_plus_xy_24() throws Exception { check_plus_xy(2,4); } @Test(timeout=1000) public void coordinate_plus_xy_36() throws Exception { check_plus_xy(3,6); } @Test(timeout=1000) public void coordinate_plus_xy_48() throws Exception { check_plus_xy(4,8); } @Test(timeout=1000) public void coordinate_plus_xy_5a() throws Exception { check_plus_xy(5,10); } @Test(timeout=1000) public void coordinate_plus_xy_6c() throws Exception { check_plus_xy(6,12); } @Test(timeout=1000) public void coordinate_plus_xy_7e() throws Exception { check_plus_xy(7,14); } @Test(timeout=1000) public void coordinate_plus_xy_81() throws Exception { check_plus_xy(8,1); } @Test(timeout=1000) public void coordinate_plus_xy_93() throws Exception { check_plus_xy(9,3); } @Test(timeout=1000) public void coordinate_plus_xy_a5() throws Exception { check_plus_xy(10,5); } @Test(timeout=1000) public void coordinate_plus_xy_b7() throws Exception { check_plus_xy(11,7); } @Test(timeout=1000) public void coordinate_plus_xy_c9() throws Exception { check_plus_xy(12,9); } @Test(timeout=1000) public void coordinate_plus_xy_db() throws Exception { check_plus_xy(13,11); } @Test(timeout=1000) public void coordinate_plus_xy_ec() throws Exception { check_plus_xy(14,13); } @Test(timeout=1000) public void coordinate_plus_xy_ff() throws Exception { check_plus_xy(15,15); } private void check_plus_delta(int a, int b) throws Exception { int[] pair1 = coordinates[a], pair2 = coordinates[b], pair3 = {pair1[0]+pair2[0], pair1[1]+pair2[1]}; Coordinate c = new Coordinate(pair1[0], pair1[1]).plus(new Coordinate(pair2[0], pair2[1])); String errMsg = String.format("Coordinate (%d, %d).plus( (%d, %d) ) incorrect ", pair1[0], pair1[1], pair2[0], pair2[1]); assertEquals(errMsg + "X", pair3[0], c.getX()); assertEquals(errMsg + "Y", pair3[1], c.getY()); } @Test(timeout=1000) public void coordinate_plus_delta_00() throws Exception { check_plus_delta(0,0); } @Test(timeout=1000) public void coordinate_plus_delta_12() throws Exception { check_plus_delta(1,2); } @Test(timeout=1000) public void coordinate_plus_delta_24() throws Exception { check_plus_delta(2,4); } @Test(timeout=1000) public void coordinate_plus_delta_36() throws Exception { check_plus_delta(3,6); } @Test(timeout=1000) public void coordinate_plus_delta_48() throws Exception { check_plus_delta(4,8); } @Test(timeout=1000) public void coordinate_plus_delta_5a() throws Exception { check_plus_delta(5,10); } @Test(timeout=1000) public void coordinate_plus_delta_6c() throws Exception { check_plus_delta(6,12); } @Test(timeout=1000) public void coordinate_plus_delta_7e() throws Exception { check_plus_delta(7,14); } @Test(timeout=1000) public void coordinate_plus_delta_81() throws Exception { check_plus_delta(8,1); } @Test(timeout=1000) public void coordinate_plus_delta_93() throws Exception { check_plus_delta(9,3); } @Test(timeout=1000) public void coordinate_plus_delta_a5() throws Exception { check_plus_delta(10,5); } @Test(timeout=1000) public void coordinate_plus_delta_b7() throws Exception { check_plus_delta(11,7); } @Test(timeout=1000) public void coordinate_plus_delta_c9() throws Exception { check_plus_delta(12,9); } @Test(timeout=1000) public void coordinate_plus_delta_db() throws Exception { check_plus_delta(13,11); } @Test(timeout=1000) public void coordinate_plus_delta_ec() throws Exception { check_plus_delta(14,13); } @Test(timeout=1000) public void coordinate_plus_delta_ff() throws Exception { check_plus_delta(15,15); } private void check_tostring(int i) throws Exception { int[] pair = coordinates[i]; int x = pair[0]; int y = pair[1]; Coordinate c = new Coordinate(x,y); String expected = String.format("(%d, %d)", x, y); assertEquals("incorrect toString()", expected, c.toString()); } @Test(timeout=1000) public void coordinate_tostring_0() throws Exception { check_tostring(0); } @Test(timeout=1000) public void coordinate_tostring_1() throws Exception { check_tostring(1); } @Test(timeout=1000) public void coordinate_tostring_2() throws Exception { check_tostring(2); } @Test(timeout=1000) public void coordinate_tostring_3() throws Exception { check_tostring(3); } @Test(timeout=1000) public void coordinate_tostring_4() throws Exception { check_tostring(4); } @Test(timeout=1000) public void coordinate_tostring_5() throws Exception { check_tostring(5); } @Test(timeout=1000) public void coordinate_tostring_6() throws Exception { check_tostring(6); } @Test(timeout=1000) public void coordinate_tostring_7() throws Exception { check_tostring(7); } @Test(timeout=1000) public void coordinate_tostring_8() throws Exception { check_tostring(8); } @Test(timeout=1000) public void coordinate_tostring_9() throws Exception { check_tostring(9); } @Test(timeout=1000) public void coordinate_tostring_a() throws Exception { check_tostring(10); } @Test(timeout=1000) public void coordinate_tostring_b() throws Exception { check_tostring(11); } @Test(timeout=1000) public void coordinate_tostring_c() throws Exception { check_tostring(12); } @Test(timeout=1000) public void coordinate_tostring_d() throws Exception { check_tostring(13); } @Test(timeout=1000) public void coordinate_tostring_e() throws Exception { check_tostring(14); } @Test(timeout=1000) public void coordinate_tostring_f() throws Exception { check_tostring(15); } }
3e00207ecf3a368b1de9a52ab3b52557d8afabae
1,820
java
Java
mango-core/src/main/java/mango/serialization/protostuff/ProtostuffSerializer.java
coolUtilSleep/mango
7d7b45ba1342580351defa6e31f045f25ab58c70
[ "Apache-2.0" ]
154
2017-12-01T09:26:05.000Z
2022-03-11T11:15:40.000Z
mango-core/src/main/java/mango/serialization/protostuff/ProtostuffSerializer.java
fowuyu/mango
5fe3f620b54d220db07b99700ed9b9deb67a2c85
[ "Apache-2.0" ]
5
2018-02-08T08:56:54.000Z
2022-03-14T01:24:46.000Z
mango-core/src/main/java/mango/serialization/protostuff/ProtostuffSerializer.java
fowuyu/mango
5fe3f620b54d220db07b99700ed9b9deb67a2c85
[ "Apache-2.0" ]
90
2017-11-16T14:45:58.000Z
2022-03-11T11:14:56.000Z
31.929825
94
0.652198
60
package mango.serialization.protostuff; import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.ProtostuffIOUtil; import com.dyuproject.protostuff.Schema; import com.dyuproject.protostuff.runtime.RuntimeSchema; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import mango.codec.Serializer; import java.io.IOException; import java.util.concurrent.ExecutionException; /** * @author Ricky Fung */ public class ProtostuffSerializer implements Serializer { private static final LoadingCache<Class<?>, Schema<?>> schemas = CacheBuilder.newBuilder() .build(new CacheLoader<Class<?>, Schema<?>>() { @Override public Schema<?> load(Class<?> cls) throws Exception { return RuntimeSchema.createFrom(cls); } }); @Override public byte[] serialize(Object msg) throws IOException { LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); try { Schema schema = getSchema(msg.getClass()); byte[] arr = ProtostuffIOUtil.toByteArray(msg, schema, buffer); return arr; } finally { buffer.clear(); } } @Override public <T> T deserialize(byte[] buf, Class<T> type) throws IOException { Schema<T> schema = getSchema(type); T msg = schema.newMessage(); ProtostuffIOUtil.mergeFrom(buf, msg, schema); return (T) msg; } private static Schema getSchema(Class<?> cls) throws IOException { try { return schemas.get(cls); } catch (ExecutionException e) { throw new IOException("create protostuff schema error", e); } } }
3e0020b5d96dcb4b4d4153b0b44fc379ec6b562c
1,359
java
Java
project-structures/clean/usecase/src/test/java/lin/louis/clean/usecase/OrderFinderTest.java
l-lin/architecture-cheat-sheet
ab93da38cb83675c1c7fd9d9bedd5e959aaf45c9
[ "MIT" ]
12
2018-02-28T05:42:34.000Z
2021-03-08T11:30:15.000Z
project-structures/clean/usecase/src/test/java/lin/louis/clean/usecase/OrderFinderTest.java
l-lin/architecture-cheat-sheet
ab93da38cb83675c1c7fd9d9bedd5e959aaf45c9
[ "MIT" ]
null
null
null
project-structures/clean/usecase/src/test/java/lin/louis/clean/usecase/OrderFinderTest.java
l-lin/architecture-cheat-sheet
ab93da38cb83675c1c7fd9d9bedd5e959aaf45c9
[ "MIT" ]
2
2020-05-11T15:43:41.000Z
2022-03-01T13:46:32.000Z
27.18
94
0.797645
61
package lin.louis.clean.usecase; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.BDDMockito; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import lin.louis.clean.entity.Order; import lin.louis.clean.entity.OrderNotFoundException; import lin.louis.clean.usecase.port.OrderRepository; @ExtendWith(MockitoExtension.class) class OrderFinderTest { private static final String ORDER_ID = "123"; @Mock private OrderRepository orderRepository; private OrderFinder orderFinder; @BeforeEach void setUp() { orderFinder = new OrderFinder(orderRepository); } @Test void shouldReturnAnOrder_whenFound() { var order = new Order(); order.setOrderId(ORDER_ID); BDDMockito.given(orderRepository.findById(ORDER_ID)).willReturn(Optional.of(order)); var orderFound = orderFinder.findById(ORDER_ID); Assertions.assertNotNull(orderFound); Assertions.assertEquals(ORDER_ID, orderFound.getOrderId()); } @Test void shouldThrowOrderNotFoundException_whenNotFound() { BDDMockito.given(orderRepository.findById(ORDER_ID)).willReturn(Optional.empty()); Assertions.assertThrows(OrderNotFoundException.class, () -> orderFinder.findById(ORDER_ID)); } }
3e002143bae26de37ce76188e690af1d5b4efabf
650
java
Java
uyaki-cloud-microservices/uyaki-cloud-microservices-auth/src/main/java/com/uyaki/cloud/microservices/auth/model/om/RoleUser.java
uyaki/uyaki-cloud
02e1694cf301c1d480351e2e0936758bb2471a4d
[ "MIT" ]
1
2019-09-29T08:03:15.000Z
2019-09-29T08:03:15.000Z
uyaki-cloud-microservices/uyaki-cloud-microservices-auth/src/main/java/com/uyaki/cloud/microservices/auth/model/om/RoleUser.java
uyaki/uyaki-cloud
02e1694cf301c1d480351e2e0936758bb2471a4d
[ "MIT" ]
8
2020-06-18T17:36:32.000Z
2022-03-15T02:30:52.000Z
uyaki-cloud-microservices/uyaki-cloud-microservices-auth/src/main/java/com/uyaki/cloud/microservices/auth/model/om/RoleUser.java
uyaba/uyaba-cloud
02e1694cf301c1d480351e2e0936758bb2471a4d
[ "MIT" ]
2
2019-10-09T02:18:38.000Z
2019-10-17T10:12:40.000Z
17.567568
52
0.615385
62
package com.uyaki.cloud.microservices.auth.model.om; import java.io.Serializable; public class RoleUser implements Serializable { private Long id; private Long roleid; private Long userid; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getRoleid() { return roleid; } public void setRoleid(Long roleid) { this.roleid = roleid; } public Long getUserid() { return userid; } public void setUserid(Long userid) { this.userid = userid; } }
3e00219df9fad1d81610e36364e745cd307a9e23
3,109
java
Java
src/utils/FileServerThread.java
enrico404/MyDFS
43e1d4f5e3850badeb31e038cf865ff064632ef8
[ "MIT" ]
3
2020-03-24T13:00:01.000Z
2022-02-13T10:27:38.000Z
src/utils/FileServerThread.java
enrico404/MyDFS
43e1d4f5e3850badeb31e038cf865ff064632ef8
[ "MIT" ]
null
null
null
src/utils/FileServerThread.java
enrico404/MyDFS
43e1d4f5e3850badeb31e038cf865ff064632ef8
[ "MIT" ]
null
null
null
29.056075
128
0.616275
63
package utils; import Server.ServerInterface; import java.awt.image.ColorConvertOp; import java.io.IOException; import java.io.Serializable; import java.security.SignatureException; /** * Classe di supporto per il file transfer system, estende la classe Thread. Al posto di istanziare un FileServer si istanzierà * un thread di questa classe, in questo modo si potranno gestire trasferimenti multipli di file da più client */ public class FileServerThread extends Thread{ /** * porta utilizzata per il trasferimento del file */ private int port; /** * percorso del nuovo file trasferito */ private String path; /** * riferimento al fileServer che si occupa del trasferimento di file */ private FileServer fs; /** * flag che indica alla classe se essere verbose o meno */ private boolean verbose = true; /** * Dimensione del file che verrà trasferito */ private long size; /** * Costruttore con parametri della classe * @param Port numero di porta in cui mettere in ascolto il thread * @param Path percorso di destinazione del file, verrà passato alla classe FIleServer che si occupa del vero e proprio * trasferimento * @throws IOException */ public FileServerThread(int Port, String Path, long Size) throws IOException { port = Port; path = Path; size = Size; fs = new FileServer(verbose); } /** * Costruttore con parametri della classe * @param Port numero di porta in cui mettere in ascolto il thread * @param Path percorso di destinazione del file, verrà passato alla classe FIleServer che si occupa del vero e proprio * trasferimento * @param Verbose flag che indica alla classe se essere verbose o meno * @throws IOException */ public FileServerThread(int Port, String Path, boolean Verbose, long Size) throws IOException { port = Port; path = Path; verbose = Verbose; size = Size; fs = new FileServer(verbose); } /** * Metodo che va a chiamare il corrispettivo metodo per il setting del percorso del file di destinazione nel file server. * Server per iniziare il trasferimento di un nuovo file. * @param Path percorso del file di destinazione * */ public void setPath(String Path, long Size, boolean Verbose){ path = Path; size = Size; verbose = Verbose; fs.setPath(path,size, verbose); } /** * Getter dell'attributo path * @return Stringa contenente il percorso in cui verrà salvato il nuovo file */ public String getPath(){ return path; } /** * Codice che viene eseguito allo start del thread */ public void run(){ try { fs.bind(port, path, size); fs.start(); } catch (IOException e) { e.printStackTrace(); } } }
3e0021c1cde1c38658ff6619497410e6486a74dd
1,861
java
Java
src/main/java/com/thanple/thinking/berkeleyDB/demoframework/BerkeleyTransaction.java
thanple/ThinkingInTechnology
bbc7d21926c8ab27f7681f63b136934c176c3bee
[ "MIT" ]
null
null
null
src/main/java/com/thanple/thinking/berkeleyDB/demoframework/BerkeleyTransaction.java
thanple/ThinkingInTechnology
bbc7d21926c8ab27f7681f63b136934c176c3bee
[ "MIT" ]
null
null
null
src/main/java/com/thanple/thinking/berkeleyDB/demoframework/BerkeleyTransaction.java
thanple/ThinkingInTechnology
bbc7d21926c8ab27f7681f63b136934c176c3bee
[ "MIT" ]
null
null
null
26.971014
100
0.638904
64
package com.thanple.thinking.berkeleyDB.demoframework; import com.sleepycat.je.Environment; import com.sleepycat.je.Transaction; import com.sleepycat.je.TransactionConfig; import java.util.ArrayList; import java.util.concurrent.TimeUnit; /** * Created by Thanple on 2017/1/13. */ public class BerkeleyTransaction { //加锁最长时间 private static final int LOCK_TIME_OUT = 10000; private static ThreadLocal<Transaction> current = new ThreadLocal<>(); private static ThreadLocal<ArrayList<Boolean>> results = new ThreadLocal<ArrayList<Boolean>>(){ protected ArrayList initialValue() { return new ArrayList(); } }; public static void clearResults(){ current.remove(); results.get().clear(); } public static Transaction currentTransaction(){ return current.get(); } public static void setTransaction(Transaction transaction){ current.set(transaction); } public static void savePoint(Boolean point){ results.get().add(point); } //开启事务 public static void startTransaction(){ Environment environment = BerkeleyDBManager.getInstance().getEnvironment(); if(null == BerkeleyTransaction.currentTransaction()){ Transaction transaction = environment.beginTransaction(null, TransactionConfig.DEFAULT); transaction.setLockTimeout(LOCK_TIME_OUT, TimeUnit.MILLISECONDS); BerkeleyTransaction.setTransaction(transaction); } } //提交或者回滚事务 public static boolean commit(){ boolean rs = true; for(Boolean e : results.get()){ if(!e){ current.get().abort(); rs = false; break; } } if(rs) current.get().commit(); clearResults(); //清空事务记录 return rs; } }
3e0023b80c93002f22126ad8c326ddfc3be6530f
224
java
Java
boutique-ware/src/test/java/com/boutique/ware/BoutiqueWareApplicationTests.java
linzai745/boutique
f7e7e3242fa461ebd166357870a7b2b8904ca27e
[ "MIT" ]
null
null
null
boutique-ware/src/test/java/com/boutique/ware/BoutiqueWareApplicationTests.java
linzai745/boutique
f7e7e3242fa461ebd166357870a7b2b8904ca27e
[ "MIT" ]
null
null
null
boutique-ware/src/test/java/com/boutique/ware/BoutiqueWareApplicationTests.java
linzai745/boutique
f7e7e3242fa461ebd166357870a7b2b8904ca27e
[ "MIT" ]
null
null
null
16
60
0.758929
65
package com.boutique.ware; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class BoutiqueWareApplicationTests { @Test void contextLoads() { } }
3e0023e81091db684adbbc150f936ea7d8ab9290
130
java
Java
com/stream/adpater/class/Main.java
zhangchuanchuan/DesignMode
f1daa1cb935d82a413d9a498e7e60c42ef970101
[ "Apache-2.0" ]
null
null
null
com/stream/adpater/class/Main.java
zhangchuanchuan/DesignMode
f1daa1cb935d82a413d9a498e7e60c42ef970101
[ "Apache-2.0" ]
null
null
null
com/stream/adpater/class/Main.java
zhangchuanchuan/DesignMode
f1daa1cb935d82a413d9a498e7e60c42ef970101
[ "Apache-2.0" ]
null
null
null
18.571429
42
0.646154
66
public class Main { public static void main(String[] args) { Adapter adapter = new Adapter(); adapter.function(); } }
3e00241efe73aef55d44e05c7214605beac8bff9
2,018
java
Java
igesture-framework/src/main/java/org/ximtec/igesture/batch/core/jdom/JdomBatchParameter.java
UeliKurmann/igesture
95dd46fb321851c1e2a989e0c7c8328f57b43f4d
[ "Apache-2.0" ]
null
null
null
igesture-framework/src/main/java/org/ximtec/igesture/batch/core/jdom/JdomBatchParameter.java
UeliKurmann/igesture
95dd46fb321851c1e2a989e0c7c8328f57b43f4d
[ "Apache-2.0" ]
null
null
null
igesture-framework/src/main/java/org/ximtec/igesture/batch/core/jdom/JdomBatchParameter.java
UeliKurmann/igesture
95dd46fb321851c1e2a989e0c7c8328f57b43f4d
[ "Apache-2.0" ]
null
null
null
28.111111
83
0.612648
67
/* * @(#)$Id$ * * Author : Ueli Kurmann, dycjh@example.com * * * Purpose : * * ----------------------------------------------------------------------- * * Revision Information: * * Date Who Reason * * 15.10.2008 ukurmann Initial Release * * ----------------------------------------------------------------------- * * Copyright 1999-2009 ETH Zurich. All Rights Reserved. * * This software is the proprietary information of ETH Zurich. * Use is subject to license terms. * */ package org.ximtec.igesture.batch.core.jdom; import org.jdom.Element; import org.ximtec.igesture.batch.core.BatchParameter; /** * Comment * @version 1.0 15.10.2008 * @author Ueli Kurmann */ public class JdomBatchParameter { public static String ROOT_TAG = "parameter"; public static String ATTRIBUTE_NAME = "name"; public static BatchParameter unmarshal(Element parameter) { final BatchParameter batchParameter = new BatchParameter(); batchParameter.setName(parameter.getAttributeValue(ATTRIBUTE_NAME)); final Element parameterValue = ((Element)parameter.getChildren().get(0)); if (parameterValue.getName().equals(JdomBatchForValue.ROOT_TAG)) { batchParameter.setIncrementalValue(JdomBatchForValue .unmarshal(parameterValue)); } else if (parameterValue.getName().equals(JdomBatchPowerSetValue.ROOT_TAG)) { batchParameter.setPermutationValue(JdomBatchPowerSetValue .unmarshal(parameterValue)); } else if (parameterValue.getName().equals(JdomBatchSequenceValue.ROOT_TAG)) { batchParameter.setSequenceValue(JdomBatchSequenceValue .unmarshal(parameterValue)); } else if (parameterValue.getName().equals(JdomBatchValue.ROOT_TAG)) { batchParameter.setValue(JdomBatchValue.unmarshal(parameterValue)); } return batchParameter; } // unmarshal }
3e0024c6c45de63a8a238d222df4c01ba4fdcd50
5,482
java
Java
scribejava-core/src/test/java/com/github/scribejava/core/oauth/OAuth20ServiceTest.java
v0o0v/scribejava
124745961e999ccede90e2348c6012f8d335eb8a
[ "MIT" ]
2,918
2015-10-19T16:51:56.000Z
2022-03-21T14:39:23.000Z
scribejava-core/src/test/java/com/github/scribejava/core/oauth/OAuth20ServiceTest.java
v0o0v/scribejava
124745961e999ccede90e2348c6012f8d335eb8a
[ "MIT" ]
466
2015-10-24T15:25:07.000Z
2022-03-03T22:09:38.000Z
scribejava-core/src/test/java/com/github/scribejava/core/oauth/OAuth20ServiceTest.java
v0o0v/scribejava
124745961e999ccede90e2348c6012f8d335eb8a
[ "MIT" ]
914
2015-10-20T15:28:47.000Z
2022-03-30T03:07:07.000Z
46.457627
120
0.707953
68
package com.github.scribejava.core.oauth; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.scribejava.core.base64.Base64; import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.OAuth2Authorization; import com.github.scribejava.core.model.OAuthConstants; import java.io.IOException; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import org.junit.Test; import java.nio.charset.Charset; import java.util.concurrent.ExecutionException; public class OAuth20ServiceTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Test public void shouldProduceCorrectRequestSync() throws IOException, InterruptedException, ExecutionException { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); final OAuth2AccessToken token = service.getAccessTokenPasswordGrant("user1", "password1"); assertNotNull(token); final JsonNode response = OBJECT_MAPPER.readTree(token.getRawResponse()); assertEquals(OAuth20ServiceUnit.TOKEN, response.get(OAuthConstants.ACCESS_TOKEN).asText()); assertEquals(OAuth20ServiceUnit.EXPIRES, response.get("expires_in").asInt()); final String authorize = Base64.encode( String.format("%s:%s", service.getApiKey(), service.getApiSecret()).getBytes(Charset.forName("UTF-8"))); assertEquals(OAuthConstants.BASIC + ' ' + authorize, response.get(OAuthConstants.HEADER).asText()); assertEquals("user1", response.get("query-username").asText()); assertEquals("password1", response.get("query-password").asText()); assertEquals("password", response.get("query-grant_type").asText()); } @Test public void shouldProduceCorrectRequestAsync() throws ExecutionException, InterruptedException, IOException { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); final OAuth2AccessToken token = service.getAccessTokenPasswordGrantAsync("user1", "password1").get(); assertNotNull(token); final JsonNode response = OBJECT_MAPPER.readTree(token.getRawResponse()); assertEquals(OAuth20ServiceUnit.TOKEN, response.get(OAuthConstants.ACCESS_TOKEN).asText()); assertEquals(OAuth20ServiceUnit.EXPIRES, response.get("expires_in").asInt()); final String authorize = Base64.encode( String.format("%s:%s", service.getApiKey(), service.getApiSecret()).getBytes(Charset.forName("UTF-8"))); assertEquals(OAuthConstants.BASIC + ' ' + authorize, response.get(OAuthConstants.HEADER).asText()); assertEquals("user1", response.get("query-username").asText()); assertEquals("password1", response.get("query-password").asText()); assertEquals("password", response.get("query-grant_type").asText()); } @Test public void testOAuthExtractAuthorization() { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); OAuth2Authorization authorization = service.extractAuthorization("https://cl.ex.com/cb?code=SplxlOB&state=xyz"); assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?state=xyz&code=SplxlOB"); assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?key=value&state=xyz&code=SplxlOB"); assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?state=xyz&code=SplxlOB&key=value&"); assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?code=SplxlOB&state="); assertEquals("SplxlOB", authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?code=SplxlOB"); assertEquals("SplxlOB", authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?code="); assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?code"); assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb?"); assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https://cl.ex.com/cb"); assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); } }
3e0024ef29e970c0eb53e103f7aac5b50dcfdfd4
8,689
java
Java
app/src/main/java/com/noobsever/codingcontests/Screens/BaseActivity.java
prit29/Coders-Calendar
edcfe3c678dc2d10c925c5bddbab90959e05eedb
[ "MIT" ]
5
2020-09-18T07:55:31.000Z
2022-01-18T03:03:47.000Z
app/src/main/java/com/noobsever/codingcontests/Screens/BaseActivity.java
prit29/Coders-Calendar
edcfe3c678dc2d10c925c5bddbab90959e05eedb
[ "MIT" ]
49
2020-09-28T22:12:00.000Z
2021-01-27T11:07:38.000Z
app/src/main/java/com/noobsever/codingcontests/Screens/BaseActivity.java
prit29/Coders-Calendar
edcfe3c678dc2d10c925c5bddbab90959e05eedb
[ "MIT" ]
18
2020-09-24T15:28:08.000Z
2021-06-11T15:31:49.000Z
39.857798
230
0.527794
69
package com.noobsever.codingcontests.Screens; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import com.google.android.material.navigation.NavigationView; import com.noobsever.codingcontests.BuildConfig; import com.noobsever.codingcontests.Models.ContestObject; import com.noobsever.codingcontests.R; import com.noobsever.codingcontests.Utils.Constants; import com.noobsever.codingcontests.Utils.Methods; import com.noobsever.codingcontests.ViewModel.ApiViewModel; import com.noobsever.codingcontests.ViewModel.RoomViewModel; import java.util.List; public class BaseActivity extends AppCompatActivity { DrawerLayout drawerLayout; ActionBarDrawerToggle actionBarDrawerToggle; Toolbar toolbar; ApiViewModel apiViewModel; RoomViewModel mRoomViewModel; boolean doubleBackPressExitOnce = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base); NavigationView navigationView = findViewById(R.id.nav_view); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); drawerLayout = findViewById(R.id.drawer_layout); actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.design_default_color_on_primary)); drawerLayout.addDrawerListener(actionBarDrawerToggle); navigationView.setNavigationItemSelectedListener (new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.nav_settings: drawerLayout.closeDrawers(); new Handler().postDelayed(new Runnable() { public void run() { startActivity(new Intent(getApplicationContext(), SettingsActivity.class)); } }, 500); break; case R.id.nav_notifications: drawerLayout.closeDrawers(); new Handler().postDelayed(new Runnable() { public void run() { startActivity(new Intent(getApplicationContext(), NotificationActivity.class)); } }, 500); break; case R.id.nav_help: drawerLayout.closeDrawers(); new Handler().postDelayed(new Runnable() { public void run() { startActivity(new Intent(getApplicationContext(), HelpActivity.class)); } }, 500); break; case R.id.nav_suggest: drawerLayout.closeDrawers(); new Handler().postDelayed(new Runnable() { public void run() { startActivity(new Intent(getApplicationContext(), SuggestUsActivity.class)); } }, 500); break; case R.id.nav_share: drawerLayout.closeDrawers(); new Handler().postDelayed(new Runnable() { public void run() { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey get ready to give back to back competitive coding contests, Check out our Coder's Calendar app at: https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID); sendIntent.setType("text/plain"); startActivity(sendIntent); } }, 500); break; case R.id.nav_open: drawerLayout.closeDrawers(); new Handler().postDelayed(new Runnable() { public void run() { Uri uri = Uri.parse("https://github.com/prit29/Coders-Calendar"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }, 500); break; } return true; } }); mRoomViewModel = new ViewModelProvider(this).get(RoomViewModel.class); apiViewModel = new ViewModelProvider(this).get(ApiViewModel.class); apiViewModel.init(); new Methods.InternetCheck(this).isInternetConnectionAvailable(new Methods.InternetCheck.InternetCheckListener() { @Override public void onComplete(boolean connected) { if(connected){ Log.e("INTERNET","CONNECTED"); Methods.setPreferences(BaseActivity.this,Constants.ISINTERNET, Constants.ISINTERNET,1); apiViewModel.fetchContestFromApi(); }else{ Methods.setPreferences(BaseActivity.this,Constants.ISINTERNET, Constants.ISINTERNET,0); } } }); apiViewModel.getAllContests().observe(BaseActivity.this, new Observer<List<ContestObject>>() { @Override public void onChanged(List<ContestObject> contestObjects) { mRoomViewModel.deleteAndAddAllTuples(contestObjects); } }); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else { if(doubleBackPressExitOnce) { super.onBackPressed(); return; } this.doubleBackPressExitOnce = true; Methods.showToast(this,"Press Back Again to Exit"); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackPressExitOnce = false; } },2000); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); actionBarDrawerToggle.syncState(); } @Override public void finish() { super.finish(); } @Override public void startActivity(Intent intent) { super.startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.appbar_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_layout: // add action break; case R.id.menu_search: // add action break; default: return super.onOptionsItemSelected(item); } return true; } }
3e00260445cea6910f25e5ad93c30ac51634c6a0
1,491
java
Java
cdmi-radio/src/main/java/pw/cdmi/open/controller/ApplicationController.java
w2cdmi/cdmi-aws-all
a1a1d79dd0e25bbe8e5bc6c641012216d7beb9c5
[ "Apache-2.0" ]
null
null
null
cdmi-radio/src/main/java/pw/cdmi/open/controller/ApplicationController.java
w2cdmi/cdmi-aws-all
a1a1d79dd0e25bbe8e5bc6c641012216d7beb9c5
[ "Apache-2.0" ]
9
2020-11-16T20:43:44.000Z
2022-03-25T19:12:11.000Z
cdmi-radio/src/main/java/pw/cdmi/open/controller/ApplicationController.java
w2cdmi/cdmi-aws-all
a1a1d79dd0e25bbe8e5bc6c641012216d7beb9c5
[ "Apache-2.0" ]
null
null
null
31.723404
94
0.693494
70
package pw.cdmi.open.controller; import java.io.FileInputStream; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import pw.cdmi.open.model.entity.SiteApplication; import pw.cdmi.open.service.SingleSiteApplicationService; /************************************************************ * 控制类,处理与应用站点信息的请求操作 * * @author 伍伟 * @version iSoc Service Platform, 2015-5-19 ************************************************************/ @Controller @RequestMapping(value = "/app") public class ApplicationController { private static final Logger logger = LoggerFactory.getLogger(ApplicationController.class); @Autowired private SingleSiteApplicationService appService; /** * 上传Liense文件,激活该应用系统并获得应用的相关授权信息,secretkey相当于密钥 * @return */ @RequestMapping(value = "", method = RequestMethod.POST) @ResponseBody public JSONObject registerSite(FileInputStream license) { SiteApplication app = appService.registerAplication(); JSONObject object = new JSONObject(); object.put("appkey", app.getAppKey()); object.put("secretkey", app.getAppSecret()); return object; } }
3e002614e003c300d00ef974582335d1ae86b7f4
1,666
java
Java
src/main/java/net/grilledham/hamhacks/mixin/MixinHeldItemRenderer.java
Gri11edHam/HamHacks
783424a65f8a7c9f576487197127199bdeb2091c
[ "MIT" ]
null
null
null
src/main/java/net/grilledham/hamhacks/mixin/MixinHeldItemRenderer.java
Gri11edHam/HamHacks
783424a65f8a7c9f576487197127199bdeb2091c
[ "MIT" ]
null
null
null
src/main/java/net/grilledham/hamhacks/mixin/MixinHeldItemRenderer.java
Gri11edHam/HamHacks
783424a65f8a7c9f576487197127199bdeb2091c
[ "MIT" ]
null
null
null
72.434783
645
0.839736
71
package net.grilledham.hamhacks.mixin; import net.grilledham.hamhacks.modules.render.HUD; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.item.HeldItemRenderer; import net.minecraft.client.render.model.json.ModelTransformation; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(HeldItemRenderer.class) public class MixinHeldItemRenderer { @Inject(method = "renderItem(Lnet/minecraft/entity/LivingEntity;Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;I)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/item/ItemRenderer;renderItem(Lnet/minecraft/entity/LivingEntity;Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/world/World;III)V", shift = At.Shift.BEFORE)) public void scaleHandItem(LivingEntity entity, ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, CallbackInfo ci) { HUD.getInstance().applyHandTransform(entity, stack, renderMode, leftHanded, matrices, vertexConsumers, light); } }
3e002688b886381b27880d19b7852743a8668a2e
1,000
java
Java
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/dataframe/action/GetDataFrameTransformsStatsActionRequestTests.java
Megamiun/elasticsearch
e1f9aec6cb74f9c38e4f309dc8c8056b7c802d41
[ "Apache-2.0" ]
3
2017-05-31T14:46:18.000Z
2022-02-15T08:04:05.000Z
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/dataframe/action/GetDataFrameTransformsStatsActionRequestTests.java
Megamiun/elasticsearch
e1f9aec6cb74f9c38e4f309dc8c8056b7c802d41
[ "Apache-2.0" ]
61
2015-01-09T10:44:57.000Z
2018-04-17T14:56:08.000Z
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/dataframe/action/GetDataFrameTransformsStatsActionRequestTests.java
Megamiun/elasticsearch
e1f9aec6cb74f9c38e4f309dc8c8056b7c802d41
[ "Apache-2.0" ]
4
2015-09-18T20:09:38.000Z
2019-08-07T12:46:41.000Z
35.714286
109
0.764
72
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.dataframe.action; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.test.AbstractWireSerializingTestCase; import org.elasticsearch.xpack.core.dataframe.action.GetDataFrameTransformsStatsAction.Request; public class GetDataFrameTransformsStatsActionRequestTests extends AbstractWireSerializingTestCase<Request> { @Override protected Request createTestInstance() { if (randomBoolean()) { return new Request(MetaData.ALL); } return new Request(randomAlphaOfLengthBetween(1, 20)); } @Override protected Writeable.Reader<Request> instanceReader() { return Request::new; } }
3e0026c581fffbaa579c731e7646506ccc9ea667
1,709
java
Java
Mage.Sets/src/mage/cards/u/UndeadAugur.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/u/UndeadAugur.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/u/UndeadAugur.java
zeffirojoe/mage
71260c382a4e3afef5cdf79adaa00855b963c166
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
31.648148
105
0.72323
73
package mage.cards.u; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.DiesThisOrAnotherCreatureTriggeredAbility; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.LoseLifeSourceControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.TargetController; import mage.filter.common.FilterCreaturePermanent; import java.util.UUID; /** * @author TheElk801 */ public final class UndeadAugur extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent(SubType.ZOMBIE, "Zombie you control"); static { filter.add(TargetController.YOU.getControllerPredicate()); } public UndeadAugur(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{B}{B}"); this.subtype.add(SubType.ZOMBIE); this.subtype.add(SubType.WIZARD); this.power = new MageInt(2); this.toughness = new MageInt(2); // Whenever Undead Augur or another Zombie you control dies, you draw a card and you lose 1 life. Ability ability = new DiesThisOrAnotherCreatureTriggeredAbility( new DrawCardSourceControllerEffect(1).setText("you draw a card"), false, filter ); ability.addEffect(new LoseLifeSourceControllerEffect(1).concatBy("and")); this.addAbility(ability); } private UndeadAugur(final UndeadAugur card) { super(card); } @Override public UndeadAugur copy() { return new UndeadAugur(this); } }
3e00273168f2a240b6d828b8c6c380c843b34ea2
1,043
java
Java
app/src/main/java/com/vann/csdn/db/DBHelper.java
dyglcc/csdn_dyg
8972b1b8206c4ed06b9104746180db13cd9fe60d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/vann/csdn/db/DBHelper.java
dyglcc/csdn_dyg
8972b1b8206c4ed06b9104746180db13cd9fe60d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/vann/csdn/db/DBHelper.java
dyglcc/csdn_dyg
8972b1b8206c4ed06b9104746180db13cd9fe60d
[ "Apache-2.0" ]
null
null
null
28.888889
80
0.6625
74
package com.vann.csdn.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * author: bwl on 2016-03-28. * email: envkt@example.com */ public class DBHelper extends SQLiteOpenHelper { public static final int DB_VERSION = 1; public static final String DB_NAME = "csdn"; public static final String TABLE_CSDN = "tb_csdn"; public DBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table if not exists " + TABLE_CSDN + "(id integer primary key autoincrement, title,text,link text," + "imgLink text,content text,date text,newsType integer);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < newVersion) { db.execSQL("drop table if exists " + TABLE_CSDN); onCreate(db); } } }
3e00273fb093410bf97858ed95135b34856ca1e8
12,588
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/SquirtleCraterOldAuto.java
alphagenesis6436/alphagen19
d848731cd01a93e64bdca4c2215d0438786f4911
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/SquirtleCraterOldAuto.java
alphagenesis6436/alphagen19
d848731cd01a93e64bdca4c2215d0438786f4911
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/SquirtleCraterOldAuto.java
alphagenesis6436/alphagen19
d848731cd01a93e64bdca4c2215d0438786f4911
[ "MIT" ]
null
null
null
41.544554
131
0.564665
75
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.Servo; import static org.firstinspires.ftc.teamcode.GoldPosition.CENTER; import static org.firstinspires.ftc.teamcode.GoldPosition.LEFT; import static org.firstinspires.ftc.teamcode.GoldPosition.NOT_FOUND; import static org.firstinspires.ftc.teamcode.GoldPosition.RIGHT; /** * Updated by Alex on 2/10/2019. */ @Autonomous(name = "SquirtleCraterOldAuto", group = "default") @Disabled public class SquirtleCraterOldAuto extends SquirtleOp { //Declare and Initialize any variables needed for this specific autonomous program GoldPosition goldPosition = NOT_FOUND; String goldPos = "NOT FOUND"; boolean latchReset = false; public SquirtleCraterOldAuto() {} @Override public void init() { //Initialize motors & set direction driveTrain.syncOpMode(gamepad1, telemetry, hardwareMap); driveTrain.setDrivePwrMax(DRIVE_PWR_MAX); driveTrain.setMotors(); telemetry.addData(">", "Drive Train Initialization Successful"); latchMotor = hardwareMap.dcMotor.get("lm"); telemetry.addData(">", "Latch Initialization Successful"); scoringMotor = hardwareMap.dcMotor.get("sm"); scoringMotor.setDirection(DcMotorSimple.Direction.FORWARD); telemetry.addData(">", "Scoring Mechanism Initialization Successful"); intakeMotor = hardwareMap.dcMotor.get("im"); intakeMotor.setDirection(DcMotorSimple.Direction.REVERSE); tiltServo1 = hardwareMap.servo.get("ts1"); tiltServo1.setDirection(Servo.Direction.FORWARD); tiltServo2 = hardwareMap.servo.get("ts2"); tiltServo2.setDirection(Servo.Direction.REVERSE); telemetry.addData(">", "Intake Initialization Successful"); extenderMotor1 = hardwareMap.dcMotor.get("em1"); extenderMotor1.setDirection(DcMotorSimple.Direction.REVERSE); extenderMotor2 = hardwareMap.dcMotor.get("em2"); extenderMotor2.setDirection(DcMotorSimple.Direction.FORWARD); telemetry.addData(">", "Extender Initialization Successful"); driveTrain.initializeIMU(); initializeDogeforia(); telemetry.addData(">", "Vuforia Initialization Successful"); telemetry.addData(">", "Press Start to continue"); } @Override public void loop(){ //Display Data to be displayed throughout entire Autonomous telemetry.addData(stateGoal, state); telemetry.addData("current time", String.format("%.1f", this.time)); telemetry.addData("state time", String.format("%.1f", this.time - setTime)); telemetry.addData("Gold Position", goldPos); switch (goldPosition) { case NOT_FOUND: goldPos = "NOT FOUND"; break; case LEFT: goldPos = "LEFT"; break; case CENTER: goldPos = "CENTER"; break; case RIGHT: goldPos = "RIGHT"; break; } telemetry.addLine(); //retract latch if (state > 4) { if (!latchReset) { extendLatch(-LATCH_PWR, 0); } else { latchMotor.setPower(0); } if (latchValueReached) { latchReset = true; } } //Use Switch statement to proceed through Autonomous strategy (only use even cases for steps) switch(state){ case 0: //Use this state to reset all hardware devices stateGoal = "Initial Calibration"; tiltServo1.setPosition(TILT_START_POS); tiltServo2.setPosition(TILT_START_POS); scoringMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); scoringMotor.setPower(0); latchMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); latchMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); calibrateAutoVariables(); resetEncoders(); state++; break; case 2: stateGoal = "Lower Robot to Ground - Latch Pwr Up"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) extendLatch(LATCH_PWR, 19.4); if (latchValueReached) { //Use a boolean value that reads true when state goal is completed latchMotor.setPower(0); state++; } break; case 4: stateGoal = "Turn to have hook unlatch - Turn 15 cw"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.turnAbsolute(15); if (driveTrain.angleTargetReached) { //Use a boolean value that reads true when state goal is completed driveTrain.stopDriveMotors(); state++; } break; case 6: stateGoal = "Move Toward Sampling Field - Drive Backward"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.moveForward(-0.9, -1); if (driveTrain.encoderTargetReached) { //Use a boolean value that reads true when state goal is completed driveTrain.stopDriveMotors(); state++; } break; case 8: stateGoal = "Turn to original angle"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.turnAbsolute(0); if (driveTrain.angleTargetReached) { //Use a boolean value that reads true when state goal is completed driveTrain.stopDriveMotors(); state++; } break; case 10: stateGoal = "Move Toward Sampling Field - Drive Backward"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.moveForward(-0.9, -0.25); if (driveTrain.encoderTargetReached) { //Use a boolean value that reads true when state goal is completed driveTrain.stopDriveMotors(); state++; } break; case 12: stateGoal = "Turn to have phone face sampling field - Turn 90 ccw"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.turnAbsolute(-90); if (driveTrain.angleTargetReached) { //Use a boolean value that reads true when state goal is completed driveTrain.stopDriveMotors(); state++; } break; case 14: //Search for Gold Mineral by Driving Backward and using GoldMineralDetector stateGoal = "Scan for Gold Mineral - Drive Backward"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.moveForward(-0.25, -1.75); if (goldAligned()) { //if gold found, then it's either center or left position driveTrain.stopDriveMotors(); goldPosition = (Math.abs(driveTrain.getRevolutions()) <= 0.75) ? CENTER : LEFT; state += 3; //skip alignment step for gold in right position } else if (driveTrain.encoderTargetReached) { //if gold not found within 1.5 revolutions, then cube is right position driveTrain.stopDriveMotors(); goldPosition = RIGHT; state++; } break; case 16: //Drive Forward to face gold cube stateGoal = "Align to Cube in Right Position - Drive Forward (SKIP UNLESS RIGHT)"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); if (goldPosition == RIGHT) { driveTrain.moveForward(0.90, 2.55); } else { driveTrain.moveForward(0, 0); } if (driveTrain.encoderTargetReached) { driveTrain.stopDriveMotors(); state++; } break; case 18: stateGoal = "Turn to have front of robot face sampling field - Turn 90 cw"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); if (goldPosition == CENTER) { driveTrain.turnAbsolute(-5); } else { driveTrain.turnAbsolute(0); } if (driveTrain.angleTargetReached) { //Use a boolean value that reads true when state goal is completed driveTrain.stopDriveMotors(); state++; } break; case 20: stateGoal = "Move Toward Lander and Bring Intake Down - Drive Forward"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.moveForward(0.9, 0.45); setTiltServos(TILT_MIN); if (driveTrain.encoderTargetReached) { //Use a boolean value that reads true when state goal is completed driveTrain.stopDriveMotors(); state++; } break; case 22: //Knock off cube - Drive Forward stateGoal = "Knock off cube - Drive Backward"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); driveTrain.moveForward(-0.90, -1.3); intakeMotor.setPower(-0.50); if (driveTrain.encoderTargetReached) { driveTrain.stopDriveMotors(); intakeMotor.setPower(0); state++; } break; case 24: //Park in Crater stateGoal = "Park in Crater - Drive Backward"; //Display any current data needed to be seen during this state (if none is needed, omit this comment) driveTrain.runConstantSpeed(); setTiltServos(TILT_SCORE - 0.20); driveTrain.moveForward(-0.90, -0.75); extendIntake(0.2); if (driveTrain.encoderTargetReached) { extendIntake(0); setTiltServos(TILT_MIN + 0.03); driveTrain.stopDriveMotors(); state++; } break; case 1000: //Run When Autonomous is Complete stateGoal = "Autonomous Complete"; //Set all motors to zero and servos to initial positions calibrateAutoVariables(); resetEncoders(); break; default://Default state used to reset all hardware devices to ensure no errors stateGoal = "Calibrating"; calibrateAutoVariables(); resetEncoders(); if (waitSec(0.01)) { state++; setTime = this.time; } break; } } //Create any methods needed for this specific autonomous program }
3e0027b1349feec99158d8e312d3a1ada7d2b709
2,491
java
Java
app/src/main/java/com/marverenic/music/model/ModelUtil.java
stefb965/Jockey
0466ef6790f9666fcdee5dffec133a06e2a3eafc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/marverenic/music/model/ModelUtil.java
stefb965/Jockey
0466ef6790f9666fcdee5dffec133a06e2a3eafc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/marverenic/music/model/ModelUtil.java
stefb965/Jockey
0466ef6790f9666fcdee5dffec133a06e2a3eafc
[ "Apache-2.0" ]
null
null
null
31.935897
99
0.628262
76
package com.marverenic.music.model; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.text.Collator; public class ModelUtil { /** * Checks Strings from ContentResolvers and replaces the default unknown value of * {@link MediaStore#UNKNOWN_STRING} with another String if needed * @param value The value returned from the ContentResolver * @param convertValue The value to replace unknown Strings with * @return A String with localized unknown values if needed, otherwise the original value */ public static String parseUnknown(String value, String convertValue) { if (value == null || value.equals(MediaStore.UNKNOWN_STRING)) { return convertValue; } else { return value; } } public static int stringToInt(String string, int defaultValue) { try { return Integer.parseInt(string); } catch (NumberFormatException e) { return defaultValue; } } public static long stringToLong(String string, long defaultValue) { try { return Long.parseLong(string); } catch (NumberFormatException e) { return defaultValue; } } public static int compareLong(long lhs, long rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } public static int compareTitle(@Nullable String left, @Nullable String right) { return Collator.getInstance().compare(sortableTitle(left), sortableTitle(right)); } /** * Creates a sortable String from a title, so that leading "the"s and "a"s can be removed. This * method will also strip the title's original case. * @param title The title to create a sortable String from * @return A new String with the same contents of {@code title}, but with any leading articles * removed to conform to English standards. */ @NonNull public static String sortableTitle(@Nullable String title) { if (title == null) { return ""; } title = title.toLowerCase(); if (title.startsWith("the ")) { return title.substring(4); } else if (title.startsWith("a ")) { return title.substring(2); } else { return title; } } public static int hashLong(long value) { return (int) (value ^ (value >>> 32)); } }
3e0028ac438206aaf2a7b48df9e4622baa1e3748
2,882
java
Java
event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java
DongHuaLu/java-design-patterns
434ad4f89e989d2ef1a03acdf66db4a7d80ce22b
[ "MIT" ]
14
2018-06-09T08:45:48.000Z
2021-08-19T15:42:08.000Z
event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java
DongHuaLu/java-design-patterns
434ad4f89e989d2ef1a03acdf66db4a7d80ce22b
[ "MIT" ]
24
2020-07-17T08:29:26.000Z
2021-07-14T06:12:13.000Z
event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java
DongHuaLu/java-design-patterns
434ad4f89e989d2ef1a03acdf66db4a7d80ce22b
[ "MIT" ]
16
2017-09-10T10:36:57.000Z
2022-01-25T06:28:36.000Z
32.382022
97
0.72762
77
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * 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 com.iluwatar.event.aggregator; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.PrintStream; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Date: 12/12/15 - 3:04 PM * * @author Jeroen Meulemeester */ public class KingJoffreyTest { /** * The mocked standard out {@link PrintStream}, required since {@link KingJoffrey} does nothing * except for writing to std-out using {@link System#out} */ private final PrintStream stdOutMock = mock(PrintStream.class); /** * Keep the original std-out so it can be restored after the test */ private final PrintStream stdOutOrig = System.out; /** * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test */ @Before public void setUp() { System.setOut(this.stdOutMock); } /** * Removed the mocked std-out {@link PrintStream} again from the {@link System} class */ @After public void tearDown() { System.setOut(this.stdOutOrig); } /** * Test if {@link KingJoffrey} tells us what event he received */ @Test public void testOnEvent() { final KingJoffrey kingJoffrey = new KingJoffrey(); for (final Event event : Event.values()) { verifyZeroInteractions(this.stdOutMock); kingJoffrey.onEvent(event); final String expectedMessage = "Received event from the King's Hand: " + event.toString(); verify(this.stdOutMock, times(1)).println(expectedMessage); verifyNoMoreInteractions(this.stdOutMock); } } }
3e00292dce4e0fea232dd80d7e7097c4920f4b9d
2,094
java
Java
ADC Modules/ADC Application/src/com/armadialogcreator/application/ApplicationStateSubscriber.java
kayler-renslow/arma-dialog-creator
706afc4382c02fffea87fb8bdee5e54ee851a3d8
[ "MIT" ]
90
2016-09-05T16:21:22.000Z
2022-03-23T22:22:49.000Z
ADC Modules/ADC Application/src/com/armadialogcreator/application/ApplicationStateSubscriber.java
kayler-renslow/arma-dialog-creator
706afc4382c02fffea87fb8bdee5e54ee851a3d8
[ "MIT" ]
52
2017-07-02T21:48:40.000Z
2021-03-29T00:08:51.000Z
ADC Modules/ADC Application/src/com/armadialogcreator/application/ApplicationStateSubscriber.java
kayler-renslow/arma-dialog-creator
706afc4382c02fffea87fb8bdee5e54ee851a3d8
[ "MIT" ]
17
2016-10-18T17:36:04.000Z
2021-04-22T21:30:16.000Z
18.051724
67
0.746418
78
package com.armadialogcreator.application; import org.jetbrains.annotations.NotNull; /** @author K @since 01/03/2019 */ public interface ApplicationStateSubscriber { /** Default implementation does nothing. @see ApplicationState#ADCInitializing */ default void adcInitializing() { } /** Default implementation does nothing. @see ApplicationState#SystemDataInitializing */ default void systemDataInitializing() { } /** Default implementation does nothing. @see ApplicationState#SystemDataLoaded */ default void systemDataLoaded() { } /** Default implementation does nothing. @see ApplicationState#ApplicationDataLoaded */ default void applicationDataLoaded() { } /** Default implementation does nothing. @see ApplicationState#ApplicationExit */ default void applicationExit() { } /** Default implementation does nothing. @see ApplicationState#ProjectInitializing */ default void projectInitializing(@NotNull Project project) { } /** Default implementation does nothing. @see ApplicationState#ProjectDataLoaded */ default void projectDataLoaded(@NotNull Project project) { } /** Default implementation does nothing. @see ApplicationState#ProjectReady */ default void projectReady(@NotNull Project project) { } /** Default implementation does nothing. @see ApplicationState#ProjectClosed */ default void projectClosed(@NotNull Project project) { } /** Default implementation does nothing. @see ApplicationState#WorkspaceInitializing */ default void workspaceInitializing(@NotNull Workspace workspace) { } /** Default implementation does nothing. @see ApplicationState#WorkspaceReady */ default void workspaceReady(@NotNull Workspace workspace) { } /** Default implementation does nothing. @see ApplicationState#WorkspaceDataLoaded */ default void workspaceDataLoaded(@NotNull Workspace workspace) { } /** Default implementation does nothing. @see ApplicationState#WorkspaceClosed */ default void workspaceClosed(@NotNull Workspace workspace) { } }
3e00299d2e23261418b17a0afc2f8eaa4683d3f6
996
java
Java
renfeid-core/src/main/java/net/renfei/services/aliyun/model/AliyunGreenAO.java
renfei/renfeid
a9813049143df7622e3a35becd98a92987a1540d
[ "Apache-2.0" ]
5
2021-11-12T08:05:26.000Z
2022-03-02T02:12:50.000Z
renfeid-core/src/main/java/net/renfei/services/aliyun/model/AliyunGreenAO.java
moutainhigh/renfeid
627fb36ae88b89e76486c79e97e14f560d09f823
[ "Apache-2.0" ]
24
2021-11-12T14:11:22.000Z
2022-03-31T11:23:28.000Z
renfeid-core/src/main/java/net/renfei/services/aliyun/model/AliyunGreenAO.java
moutainhigh/renfeid
627fb36ae88b89e76486c79e97e14f560d09f823
[ "Apache-2.0" ]
7
2021-11-12T14:08:38.000Z
2022-03-17T08:43:52.000Z
18.444444
48
0.554217
79
package net.renfei.services.aliyun.model; import java.util.List; /** * 阿里云绿网请求对象 * * @author renfei */ public class AliyunGreenAO { private List<String> scenes; private List<Task> tasks; public static class Task { private String dataId; /** * 待检测的文本,长度不超过10000个字符 */ private String content; public String getDataId() { return dataId; } public void setDataId(String dataId) { this.dataId = dataId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } public List<String> getScenes() { return scenes; } public void setScenes(List<String> scenes) { this.scenes = scenes; } public List<Task> getTasks() { return tasks; } public void setTasks(List<Task> tasks) { this.tasks = tasks; } }
3e002a0b7d1f961c9d7fbb89b98f2e77811567ad
1,347
java
Java
src/main/java/com/happy3w/math/section/SectionItemValueComparator.java
boroborome/math
e2f881d5d2a6745878dd958a115173d038ad94d0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/happy3w/math/section/SectionItemValueComparator.java
boroborome/math
e2f881d5d2a6745878dd958a115173d038ad94d0
[ "Apache-2.0" ]
1
2022-01-13T06:34:54.000Z
2022-01-13T06:34:54.000Z
src/main/java/com/happy3w/math/section/SectionItemValueComparator.java
boroborome/math
e2f881d5d2a6745878dd958a115173d038ad94d0
[ "Apache-2.0" ]
null
null
null
29.933333
114
0.599852
80
package com.happy3w.math.section; import java.util.Comparator; public class SectionItemValueComparator<T> { private final Comparator<T> valueComparator; public SectionItemValueComparator(Comparator<T> valueComparator) { this.valueComparator = valueComparator; } public int compareValue(T value, SectionItemValue<T> o1, ItemValueType type1) { int kind1 = getValueKind(o1, type1); if (kind1 != 0) { return -kind1; } int crValue = valueComparator.compare(value, o1.getValue()); if (crValue == 0 && !o1.isInclude()) { return -type1.getValue(); } return crValue; } public int compare(SectionItemValue<T> o1, ItemValueType type1, SectionItemValue<T> o2, ItemValueType type2) { int kind1 = getValueKind(o1, type1); int kind2 = getValueKind(o2, type2); int crKind = kind1 - kind2; if (crKind != 0 || kind1 != 0) { return crKind; } return valueComparator.compare(o1.getValue(), o2.getValue()); } private int getValueKind(SectionItemValue<T> itemValue, ItemValueType type) { if (itemValue.getValue() != null) { return 0; } else if (type == ItemValueType.from) { return -1; } else { return 1; } } }
3e002aa57c9b48e7c115db4350cb496a6c5acf91
487
java
Java
fast-cloud-core/src/main/java/com/fast/cloud/core/base/tips/Tip.java
SPBuckTeeth/fast-cloud-guns
25dae4f19e2407f1c9617df01c42774d7228ae59
[ "Apache-2.0" ]
null
null
null
fast-cloud-core/src/main/java/com/fast/cloud/core/base/tips/Tip.java
SPBuckTeeth/fast-cloud-guns
25dae4f19e2407f1c9617df01c42774d7228ae59
[ "Apache-2.0" ]
null
null
null
fast-cloud-core/src/main/java/com/fast/cloud/core/base/tips/Tip.java
SPBuckTeeth/fast-cloud-guns
25dae4f19e2407f1c9617df01c42774d7228ae59
[ "Apache-2.0" ]
null
null
null
16.233333
44
0.609856
82
package com.fast.cloud.core.base.tips; /** * 返回给前台的提示(最终转化为json形式) * * @author fengshuonan * @Date 2017年1月11日 下午11:58:00 */ public abstract class Tip { protected int code; protected String message; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
3e002b755490fe22a3bd9960fe9a47cc86568435
12,496
java
Java
beethoven-core/src/main/java/io/beethoven/service/TaskExecutorService.java
davimonteiro/beethoven
15adcf046f6a7bc6403c9ac136f154f85a71c2e2
[ "Unlicense" ]
7
2018-04-10T16:29:52.000Z
2021-12-22T19:46:30.000Z
beethoven-core/src/main/java/io/beethoven/service/TaskExecutorService.java
davimonteiro/beethoven
15adcf046f6a7bc6403c9ac136f154f85a71c2e2
[ "Unlicense" ]
null
null
null
beethoven-core/src/main/java/io/beethoven/service/TaskExecutorService.java
davimonteiro/beethoven
15adcf046f6a7bc6403c9ac136f154f85a71c2e2
[ "Unlicense" ]
null
null
null
46.281481
143
0.701905
83
/** * The MIT License * Copyright © 2018 Davi Monteiro * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * 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 io.beethoven.service; import akka.actor.ActorSystem; import io.beethoven.dsl.*; import io.beethoven.engine.TaskInstance; import io.beethoven.engine.core.ActorPath; import io.beethoven.engine.core.DeciderActor; import io.beethoven.engine.core.ReporterActor; import io.beethoven.repository.ContextualInputRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static akka.actor.ActorRef.noSender; import static io.beethoven.engine.core.ActorPath.*; import static io.beethoven.engine.core.ActorPath.DECIDER_ACTOR; import static org.springframework.web.reactive.function.BodyInserters.fromObject; /** * @author Davi Monteiro */ @Service public class TaskExecutorService { @Autowired private ContextualInputRepository contextualInputRepository; @Autowired private WebClient.Builder webClientBuilder; @Autowired private ActorSystem actorSystem; public void execute(Task task, String workflowInstanceName) { TaskInstance taskInstance = buildTaskInstance(task, workflowInstanceName); // Build a http request WebClient.RequestHeadersSpec request = buildHttpRequest( task.getHttpRequest(), task.getWorkflowName(), workflowInstanceName); // Perform the request request.retrieve().bodyToFlux(String.class) .subscribe( response -> handleSuccessResponse( taskInstance, response), throwable -> handleFailureResponse( taskInstance, throwable)); notifyDeciderActor(taskInstance); notifyReporterActor(taskInstance); } private void handleSuccessResponse(TaskInstance taskInstance, String response) { taskInstance.setResponse(response); contextualInputRepository.saveLocalInput(taskInstance.getWorkflowInstanceName(), buildContextualInput(taskInstance)); sendEvent(new DeciderActor.TaskCompletedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName())); sendEvent(new ReporterActor.ReportTaskCompletedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName(), taskInstance.getTaskInstanceName(), response)); } private void handleFailureResponse(TaskInstance taskInstance, Throwable throwable) { taskInstance.setFailure(throwable); contextualInputRepository.saveLocalInput(taskInstance.getWorkflowInstanceName(), buildContextualInput(taskInstance)); sendEvent(new DeciderActor.TaskFailedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName())); sendEvent(new ReporterActor.ReportTaskFailedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName(), taskInstance.getTaskInstanceName(), throwable)); } private ContextualInput buildContextualInput(TaskInstance taskInstance) { String inputKey = "${" + taskInstance.getTaskName() + ".response}"; return new ContextualInput(inputKey, taskInstance.getResponse()); } private WebClient.RequestHeadersSpec buildHttpRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { WebClient.RequestHeadersSpec request = null; switch (httpRequest.getMethod()) { case GET: request = buildGetRequest(httpRequest, workflowName, workflowInstanceName); break; case POST: request = buildPostRequest(httpRequest, workflowName, workflowInstanceName); break; case PUT: request = buildPutRequest(httpRequest, workflowName, workflowInstanceName); break; case DELETE: request = buildDeleteRequest(httpRequest, workflowName, workflowInstanceName); break; } return request; } private WebClient.RequestHeadersSpec buildGetRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().get() .uri(httpRequest.getUrl(), uriVariables); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private WebClient.RequestHeadersSpec buildPostRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); String body = buildBody(httpRequest.getBody(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().post() .uri(httpRequest.getUrl(), uriVariables) .body(BodyInserters.fromPublisher(Flux.just(body), String.class)); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private WebClient.RequestHeadersSpec buildPutRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); String body = buildBody(httpRequest.getBody(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().put() .uri(httpRequest.getUrl(), uriVariables) .body(fromObject(body)); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private WebClient.RequestHeadersSpec buildDeleteRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().delete() .uri(httpRequest.getUrl(), uriVariables); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private String buildBody(String body, String workflowName, String workflowInstanceName) { return contextualInputRepository.findGlobalContextualInput(workflowName, body) .map(ContextualInput::getValue) .orElseGet( () -> contextualInputRepository.findLocalContextualInput(workflowInstanceName, body) .map(ContextualInput::getValue) .orElse(body)); } private List<String> buildUriVariables(List<String> uriVariables, String workflowName, String workflowInstanceName) { List<String> newVariables = new ArrayList<>(); for (String uriVariable : uriVariables) { contextualInputRepository.findGlobalContextualInput(workflowName, uriVariable) .ifPresent(contextualInput -> newVariables.add(contextualInput.getValue())); contextualInputRepository.findLocalContextualInput(workflowInstanceName, uriVariable) .ifPresent(contextualInput -> newVariables.add(contextualInput.getValue())); } return newVariables; } private void buildHeaders(WebClient.RequestHeadersSpec request, List<Header> headers, String workflowName, String workflowInstanceName) { for (Header header : headers) { request.header(header.getName(), header.getValue()); contextualInputRepository.findGlobalContextualInput(workflowName, header.getValue()) .ifPresent(contextualInput -> request.header(header.getName(), contextualInput.getValue())); contextualInputRepository.findLocalContextualInput(workflowInstanceName, header.getValue()) .ifPresent(contextualInput -> request.header(header.getName(), contextualInput.getValue())); } } private void buildQueryParams(WebClient.RequestHeadersSpec request, List<Param> params, String workflowName, String workflowInstanceName) { for (Param param : params) { request.attribute(param.getName(), param.getValue()); contextualInputRepository.findGlobalContextualInput(workflowName, param.getValue()) .ifPresent(contextualInput -> request.header(param.getName(), contextualInput.getValue())); contextualInputRepository.findLocalContextualInput(workflowInstanceName, param.getValue()) .ifPresent(contextualInput -> request.header(param.getName(), contextualInput.getValue())); } } private TaskInstance buildTaskInstance(Task task, String workflowInstanceName) { String taskInstanceName = UUID.randomUUID().toString(); TaskInstance taskInstance = new TaskInstance(); taskInstance.setWorkflowName(task.getWorkflowName()); taskInstance.setWorkflowInstanceName(workflowInstanceName); taskInstance.setTaskName(task.getName()); taskInstance.setTaskInstanceName(taskInstanceName); return taskInstance; } private void notifyDeciderActor(TaskInstance taskInstance) { sendEvent(new DeciderActor.TaskStartedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName())); } private void notifyReporterActor(TaskInstance taskInstance) { sendEvent(new ReporterActor.ReportTaskStartedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName(), taskInstance.getTaskInstanceName())); } private void sendEvent(DeciderActor.TaskEvent taskEvent) { actorSystem.actorSelection(DECIDER_ACTOR).tell(taskEvent, noSender()); } private void sendEvent(ReporterActor.ReportTaskEvent reportTaskEvent) { actorSystem.actorSelection(REPORT_ACTOR).tell(reportTaskEvent, noSender()); } }
3e002bd0fa090a6399075fb2d3750f91b04764d9
1,168
java
Java
BoxJavaLibraryV2/tst/com/box/boxjavalibv2/requests/DeleteEmailAliasRequestTest.java
tdtran/box-java-sdk-v2
de65ec96f81874f66919799507f1099a6a4a4645
[ "Apache-2.0" ]
2
2018-04-18T03:48:56.000Z
2019-01-24T07:21:41.000Z
BoxJavaLibraryV2/tst/com/box/boxjavalibv2/requests/DeleteEmailAliasRequestTest.java
tdtran/box-java-sdk-v2
de65ec96f81874f66919799507f1099a6a4a4645
[ "Apache-2.0" ]
null
null
null
BoxJavaLibraryV2/tst/com/box/boxjavalibv2/requests/DeleteEmailAliasRequestTest.java
tdtran/box-java-sdk-v2
de65ec96f81874f66919799507f1099a6a4a4645
[ "Apache-2.0" ]
3
2015-08-26T10:08:18.000Z
2019-11-06T14:02:24.000Z
34.352941
144
0.770548
84
package com.box.boxjavalibv2.requests; import java.io.IOException; import junit.framework.Assert; import org.apache.http.HttpStatus; import org.junit.Test; import com.box.boxjavalibv2.exceptions.AuthFatalFailureException; import com.box.boxjavalibv2.testutils.TestUtils; import com.box.restclientv2.RestMethod; import com.box.restclientv2.exceptions.BoxRestException; public class DeleteEmailAliasRequestTest extends RequestTestBase { @Test public void testUri() { Assert.assertEquals("/users/123/email_aliases/456", DeleteEmailAliasRequest.getUri("123", "456")); } @Test public void testRequestIsWellFormed() throws BoxRestException, IllegalStateException, IOException, AuthFatalFailureException { String userId = "testuserid"; String emailId = "testemailid"; DeleteEmailAliasRequest request = new DeleteEmailAliasRequest(CONFIG, JSON_PARSER, userId, emailId, null); testRequestIsWellFormed(request, TestUtils.getConfig().getApiUrlAuthority(), TestUtils.getConfig().getApiUrlPath().concat(DeleteEmailAliasRequest.getUri(userId, emailId)), HttpStatus.SC_OK, RestMethod.DELETE); } }
3e002bf029dbc65e351006e86e9fd9a39b3f4359
338
java
Java
src/main/java/me/owenlynch/brown_decaf/BitSetIterable.java
olynch/brown_decaf
30b4b54ec9e1becf53094c13de88af5408d213c4
[ "MIT" ]
null
null
null
src/main/java/me/owenlynch/brown_decaf/BitSetIterable.java
olynch/brown_decaf
30b4b54ec9e1becf53094c13de88af5408d213c4
[ "MIT" ]
null
null
null
src/main/java/me/owenlynch/brown_decaf/BitSetIterable.java
olynch/brown_decaf
30b4b54ec9e1becf53094c13de88af5408d213c4
[ "MIT" ]
null
null
null
18.777778
86
0.745562
85
package me.owenlynch.brown_decaf; class BitSetIterable extends java.util.BitSet implements java.lang.Iterable<Integer> { static final long serialVersionUID = 1; public BitSetIterable(int nbits) { super(nbits); } public BitSetIterable() { super(); } public BitSetIterator iterator() { return new BitSetIterator(this); } }
3e002ca055a174ec9089245ef83fac027e3a9882
1,648
java
Java
barlom-server/domain/barlom-metamodel/src/main/java/org/barlom/domain/metamodel/impl/commands/PackageCreationCmd.java
martin-nordberg/grestler
304170356c833cb7d5c03cd530fa8bfff6b60737
[ "Apache-2.0" ]
null
null
null
barlom-server/domain/barlom-metamodel/src/main/java/org/barlom/domain/metamodel/impl/commands/PackageCreationCmd.java
martin-nordberg/grestler
304170356c833cb7d5c03cd530fa8bfff6b60737
[ "Apache-2.0" ]
null
null
null
barlom-server/domain/barlom-metamodel/src/main/java/org/barlom/domain/metamodel/impl/commands/PackageCreationCmd.java
martin-nordberg/grestler
304170356c833cb7d5c03cd530fa8bfff6b60737
[ "Apache-2.0" ]
null
null
null
30.518519
112
0.736044
86
// // (C) Copyright 2015 Martin E. Nordberg III // Apache 2.0 License // package org.barlom.domain.metamodel.impl.commands; import org.barlom.domain.metamodel.api.elements.IPackage; import org.barlom.domain.metamodel.spi.commands.IMetamodelCommandWriter; import org.barlom.domain.metamodel.spi.commands.PackageCreationCmdRecord; import org.barlom.domain.metamodel.spi.queries.IMetamodelRepositorySpi; import javax.json.JsonObject; import java.util.UUID; /** * Command to create a package. */ final class PackageCreationCmd extends AbstractMetamodelCommand<PackageCreationCmdRecord> { /** * Constructs a new command. * * @param metamodelRepository the repository the command will act upon. * @param cmdWriter the command's persistence provider. */ PackageCreationCmd( IMetamodelRepositorySpi metamodelRepository, IMetamodelCommandWriter<PackageCreationCmdRecord> cmdWriter ) { super( metamodelRepository, cmdWriter ); } @Override protected PackageCreationCmdRecord parseJson( JsonObject jsonCmdArgs ) { return new PackageCreationCmdRecord( jsonCmdArgs ); } @Override protected void writeChangesToMetamodel( PackageCreationCmdRecord record ) { // Extract the package attributes from the command JSON. UUID parentPackageId = record.pkg.parentPackageId; // Look up the related parent package. IPackage parentPackage = this.getMetamodelRepository().findPackageById( parentPackageId ); // Create the new package. this.getMetamodelRepository().loadPackage( record.pkg, parentPackage ); } }
3e002ce436cbc6af66f242c8bfb9dd526df070bb
283
java
Java
DesignPatterns/src/com/designpattern/behavioral/null_object/RealObject.java
tyybjcc/Design-Patterns-in-java
b9eaedf1bfd14970ee056bca61d9c024cad3abba
[ "Apache-2.0" ]
1
2015-05-27T11:04:25.000Z
2015-05-27T11:04:25.000Z
DesignPatterns/src/com/designpattern/behavioral/null_object/RealObject.java
tyybjcc/Design-Patterns-in-java
b9eaedf1bfd14970ee056bca61d9c024cad3abba
[ "Apache-2.0" ]
null
null
null
DesignPatterns/src/com/designpattern/behavioral/null_object/RealObject.java
tyybjcc/Design-Patterns-in-java
b9eaedf1bfd14970ee056bca61d9c024cad3abba
[ "Apache-2.0" ]
null
null
null
21.769231
65
0.696113
87
package com.designpattern.behavioral.null_object; public class RealObject implements Object{ private String name; public RealObject(String _name) { this.name = _name; } public void request() { System.out.println("real object "+ this.name +" requests..."); } }
3e002d6a62f99f200ef9e0122d94cc4d5bf06267
631
java
Java
Core Java/Generics (Partial)/GenDemo.java
arifparvez14/JAVA
4b3b954b8ab7916684c4a6c8a999d35268881627
[ "MIT" ]
null
null
null
Core Java/Generics (Partial)/GenDemo.java
arifparvez14/JAVA
4b3b954b8ab7916684c4a6c8a999d35268881627
[ "MIT" ]
null
null
null
Core Java/Generics (Partial)/GenDemo.java
arifparvez14/JAVA
4b3b954b8ab7916684c4a6c8a999d35268881627
[ "MIT" ]
null
null
null
20.354839
69
0.510301
88
class Gen<T> { T ob; Gen(T o){ ob = o; } T getOb(){ return ob; } void showType(){ System.out.println("Type of T is " +ob.getClass().getName()); } } public class GenDemo { public static void main(String[] args) { Gen<Integer>iOb; iOb = new Gen<Integer>(88); iOb.showType(); int v = iOb.getOb(); System.out.println("value: "+v); System.out.println(); Gen<String>strOb = new Gen<String>("Generics Test"); strOb.showType(); String str = strOb.getOb(); System.out.println("value: "+str); } }
3e002eb23514e5ff1f894d16998fa72631974f38
531
java
Java
taokeeper-common/src/main/java/common/toolkit/java/exception/SSHException.java
DavidBate/taokeeper
a8b32df9d328c7fc7be6d1b83d24c6763c0e270b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
taokeeper-common/src/main/java/common/toolkit/java/exception/SSHException.java
DavidBate/taokeeper
a8b32df9d328c7fc7be6d1b83d24c6763c0e270b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
taokeeper-common/src/main/java/common/toolkit/java/exception/SSHException.java
DavidBate/taokeeper
a8b32df9d328c7fc7be6d1b83d24c6763c0e270b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
19.777778
71
0.666667
89
package common.toolkit.java.exception; /** * * Description: Exception of SSH handle * @author 银时 nnheo@example.com */ public class SSHException extends Exception { public SSHException() { super(); } public SSHException( String message ) { super( message ); } public SSHException( String message, Throwable cause ) { super(message, cause); } public SSHException(Throwable cause) { super(cause); } private static final long serialVersionUID = -5365630128856068164L; }
3e002edc50be81f25b3d14cbe9ba8ac96fff6f30
4,506
java
Java
core/src/main/java/com/google/errorprone/bugpatterns/ArrayEquals.java
gaul/error-prone
03495e209823c554a2733d5a37764ab310cb3ddb
[ "Apache-2.0" ]
1
2016-11-23T10:18:47.000Z
2016-11-23T10:18:47.000Z
core/src/main/java/com/google/errorprone/bugpatterns/ArrayEquals.java
andrewgaul/error-prone
03495e209823c554a2733d5a37764ab310cb3ddb
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/google/errorprone/bugpatterns/ArrayEquals.java
andrewgaul/error-prone
03495e209823c554a2733d5a37764ab310cb3ddb
[ "Apache-2.0" ]
null
null
null
44.613861
97
0.73968
90
/* * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.Category.JDK; import static com.google.errorprone.BugPattern.MaturityLevel.MATURE; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.argument; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.predicates.TypePredicates.isArray; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; /** * @author upchh@example.com (Eddie Aftandilian) */ @BugPattern(name = "ArrayEquals", summary = "Reference equality used to compare arrays", explanation = "Generally when comparing arrays for equality, the programmer intends to check that the " + "the contents of the arrays are equal rather than that they are actually the same " + "object. But many commonly used equals methods compare arrays for reference equality " + "rather than content equality. These include the instance .equals() method, Guava's " + "com.google.common.base.Objects#equal(), and the JDK's java.util.Objects#equals().\n\n" + "If reference equality is needed, == should be used instead for clarity. Otherwise, " + "use java.util.Arrays#equals() to compare the contents of the arrays.", category = JDK, severity = ERROR, maturity = MATURE) public class ArrayEquals extends BugChecker implements MethodInvocationTreeMatcher { /** * Matches when the equals instance method is used to compare two arrays. */ private static final Matcher<MethodInvocationTree> instanceEqualsMatcher = Matchers.allOf( instanceMethod().onClass(isArray()).named("equals"), argument(0, Matchers.<ExpressionTree>isArrayType())); /** * Matches when the Guava com.google.common.base.Objects#equal or the JDK7 * java.util.Objects#equals method is used to compare two arrays. */ private static final Matcher<MethodInvocationTree> staticEqualsMatcher = allOf( anyOf( staticMethod().onClass("com.google.common.base.Objects").named("equal"), staticMethod().onClass("java.util.Objects").named("equals")), argument(0, Matchers.<ExpressionTree>isArrayType()), argument(1, Matchers.<ExpressionTree>isArrayType())); /** * Suggests replacing with Arrays.equals(a, b). Also adds the necessary import statement for * java.util.Arrays. */ @Override public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) { String arg1; String arg2; if (instanceEqualsMatcher.matches(t, state)) { arg1 = ((JCFieldAccess) t.getMethodSelect()).getExpression().toString(); arg2 = t.getArguments().get(0).toString(); } else if (staticEqualsMatcher.matches(t, state)) { arg1 = t.getArguments().get(0).toString(); arg2 = t.getArguments().get(1).toString(); } else { return NO_MATCH; } Fix fix = SuggestedFix.builder() .replace(t, "Arrays.equals(" + arg1 + ", " + arg2 + ")") .addImport("java.util.Arrays") .build(); return describeMatch(t, fix); } }
3e002ef6b623c2e3126007ff3829c1ba8a7286cf
982
java
Java
samples/flatbuffers-demo/src/main/java/com/alibaba/fastffi/demo/ffi/FFIWeapon.java
zhanglei1949/fastFFI
5ed0691fe397659417521e3b4032361d7afea9ba
[ "ECL-2.0", "Apache-2.0" ]
50
2021-09-23T07:20:44.000Z
2022-03-30T05:05:43.000Z
samples/flatbuffers-demo/src/main/java/com/alibaba/fastffi/demo/ffi/FFIWeapon.java
zhanglei1949/fastFFI
5ed0691fe397659417521e3b4032361d7afea9ba
[ "ECL-2.0", "Apache-2.0" ]
21
2021-11-01T09:27:50.000Z
2022-03-08T02:43:57.000Z
samples/flatbuffers-demo/src/main/java/com/alibaba/fastffi/demo/ffi/FFIWeapon.java
zhanglei1949/fastFFI
5ed0691fe397659417521e3b4032361d7afea9ba
[ "ECL-2.0", "Apache-2.0" ]
7
2021-10-09T03:00:07.000Z
2022-02-11T02:15:29.000Z
31.677419
75
0.754582
91
/* * Copyright 1999-2021 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastffi.demo.ffi; import com.alibaba.fastffi.CXXHead; import com.alibaba.fastffi.FFIGen; import com.alibaba.fastffi.FFIPointer; import com.alibaba.fastffi.FFITypeAlias; @FFIGen @FFITypeAlias("MyGame::Sample::Weapon") @CXXHead("monster_generated.h") public interface FFIWeapon extends FFIPointer { FFIFBString name(); short damage(); }
3e002f26f773e2407d38c05ebfe9109f5c1a3de0
772
java
Java
src/main/java/com/github/ennoxhd/aig/GuiUtils.java
TheGitTourist/ascii-image-generator
cc7ceea1954bd12373373394b607c9ec0e174d93
[ "MIT" ]
1
2021-04-04T09:31:47.000Z
2021-04-04T09:31:47.000Z
src/main/java/com/github/ennoxhd/aig/GuiUtils.java
TheGitTourist/ascii-image-generator
cc7ceea1954bd12373373394b607c9ec0e174d93
[ "MIT" ]
14
2020-08-28T21:09:44.000Z
2021-04-25T15:56:10.000Z
src/main/java/com/github/ennoxhd/aig/GuiUtils.java
TheGitTourist/ascii-image-generator
cc7ceea1954bd12373373394b607c9ec0e174d93
[ "MIT" ]
null
null
null
20.864865
71
0.709845
92
package com.github.ennoxhd.aig; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * Provides general GUI utilities. */ final class GuiUtils { /** * Private default constructor (not used). */ private GuiUtils() {} /** * Tracks if the GUI is initialized. * @see #initializeGui() */ private static boolean isInitialized = false; /** * Sets the system default LaF. */ static final void initializeGui() { if(isInitialized) return; try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // do nothing } finally { isInitialized = true; } } }
3e002f337d95edb76932b229a9f6ef7b59101efb
3,030
java
Java
components/sbm-recipes-mule-to-boot/src/generated/java/org/mulesoft/schema/mule/http/HttpPollingConnectorType.java
Maarc/spring-boot-migrator
fb5c15a15aec1890df4d72ef7b02ce72a13e8bef
[ "Apache-2.0" ]
32
2022-02-28T09:21:27.000Z
2022-03-31T05:11:17.000Z
components/sbm-recipes-mule-to-boot/src/generated/java/org/mulesoft/schema/mule/http/HttpPollingConnectorType.java
Maarc/spring-boot-migrator
fb5c15a15aec1890df4d72ef7b02ce72a13e8bef
[ "Apache-2.0" ]
32
2022-03-01T14:54:05.000Z
2022-03-31T09:43:55.000Z
components/sbm-recipes-mule-to-boot/src/generated/java/org/mulesoft/schema/mule/http/HttpPollingConnectorType.java
Maarc/spring-boot-migrator
fb5c15a15aec1890df4d72ef7b02ce72a13e8bef
[ "Apache-2.0" ]
10
2022-02-28T11:15:36.000Z
2022-03-31T21:58:11.000Z
26.12069
125
0.623432
93
package org.mulesoft.schema.mule.http; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for httpPollingConnectorType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="httpPollingConnectorType"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://www.mulesoft.org/schema/mule/http}httpConnectorType"&gt; * &lt;attribute name="pollingFrequency" type="{http://www.mulesoft.org/schema/mule/core}substitutableLong" /&gt; * &lt;attribute name="checkEtag" type="{http://www.mulesoft.org/schema/mule/core}substitutableBoolean" /&gt; * &lt;attribute name="discardEmptyContent" type="{http://www.mulesoft.org/schema/mule/core}substitutableBoolean" /&gt; * &lt;anyAttribute processContents='lax' namespace='##other'/&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "httpPollingConnectorType") public class HttpPollingConnectorType extends HttpConnectorType { @XmlAttribute(name = "pollingFrequency") protected String pollingFrequency; @XmlAttribute(name = "checkEtag") protected String checkEtag; @XmlAttribute(name = "discardEmptyContent") protected String discardEmptyContent; /** * Gets the value of the pollingFrequency property. * * @return * possible object is * {@link String } * */ public String getPollingFrequency() { return pollingFrequency; } /** * Sets the value of the pollingFrequency property. * * @param value * allowed object is * {@link String } * */ public void setPollingFrequency(String value) { this.pollingFrequency = value; } /** * Gets the value of the checkEtag property. * * @return * possible object is * {@link String } * */ public String getCheckEtag() { return checkEtag; } /** * Sets the value of the checkEtag property. * * @param value * allowed object is * {@link String } * */ public void setCheckEtag(String value) { this.checkEtag = value; } /** * Gets the value of the discardEmptyContent property. * * @return * possible object is * {@link String } * */ public String getDiscardEmptyContent() { return discardEmptyContent; } /** * Sets the value of the discardEmptyContent property. * * @param value * allowed object is * {@link String } * */ public void setDiscardEmptyContent(String value) { this.discardEmptyContent = value; } }
3e0031246b01ace7d7c4ec0512a9c4ff3fca49d8
694
java
Java
sun-flower-collection-mq/src/test/java/com/sun/flower/mq/MqBaseTest.java
bobchen124/sun-flower-collection
e3ce13864444ebd64b307009da59105b7413bfd4
[ "Apache-2.0" ]
2
2019-03-29T02:31:10.000Z
2019-04-19T16:54:13.000Z
sun-flower-collection-mq/src/test/java/com/sun/flower/mq/MqBaseTest.java
bobchen124/sun-flower-collection
e3ce13864444ebd64b307009da59105b7413bfd4
[ "Apache-2.0" ]
3
2019-04-19T16:54:08.000Z
2021-08-09T20:52:54.000Z
sun-flower-collection-mq/src/test/java/com/sun/flower/mq/MqBaseTest.java
bobchen124/sun-flower-collection
e3ce13864444ebd64b307009da59105b7413bfd4
[ "Apache-2.0" ]
1
2021-04-13T16:54:47.000Z
2021-04-13T16:54:47.000Z
21.030303
67
0.716138
94
package com.sun.flower.mq; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; /** * @Desc: * @Author: chenbo * @Date: 2019/5/2 17:51 **/ @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class MqBaseTest { @Resource AmqpTemplate amqpTemplate; @Test public void sendTest() { //Message message = amqpTemplate.("test-demo", "test-msg"); //log.info("ret = {}", JSONObject.toJSONString(ret)); } }
3e00314012653bcd898971f74a67d8cd7aadf4f6
3,344
java
Java
src/main/java/net/sourceforge/plantuml/creole/Bullet.java
Banno/sbt-plantuml-plugin
99050a3cc8e4667d8c627bfbdd6596aa68de4ccd
[ "ECL-2.0", "Apache-2.0" ]
7
2016-04-25T20:32:19.000Z
2021-11-15T17:48:23.000Z
src/main/java/net/sourceforge/plantuml/creole/Bullet.java
Banno/sbt-plantuml-plugin
99050a3cc8e4667d8c627bfbdd6596aa68de4ccd
[ "ECL-2.0", "Apache-2.0" ]
6
2016-02-26T08:32:28.000Z
2018-01-24T16:50:36.000Z
src/main/java/net/sourceforge/plantuml/creole/Bullet.java
Banno/sbt-plantuml-plugin
99050a3cc8e4667d8c627bfbdd6596aa68de4ccd
[ "ECL-2.0", "Apache-2.0" ]
5
2016-02-21T23:42:23.000Z
2017-11-29T11:57:41.000Z
32.784314
98
0.726675
95
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2017, Arnaud Roques * * Project Info: http://plantuml.com * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.creole; import java.awt.geom.Dimension2D; import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.graphic.FontConfiguration; import net.sourceforge.plantuml.graphic.HtmlColor; import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.ugraphic.UChangeBackColor; import net.sourceforge.plantuml.ugraphic.UChangeColor; import net.sourceforge.plantuml.ugraphic.UEllipse; import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.URectangle; import net.sourceforge.plantuml.ugraphic.UStroke; import net.sourceforge.plantuml.ugraphic.UTranslate; public class Bullet implements Atom { private final FontConfiguration fontConfiguration; private final int order; public Bullet(FontConfiguration fontConfiguration, int order) { this.fontConfiguration = fontConfiguration; this.order = order; } private double getWidth(StringBounder stringBounder) { final Dimension2D dim = stringBounder.calculateDimension(fontConfiguration.getFont(), "W"); return dim.getWidth() * (order + 1); } public void drawU(UGraphic ug) { if (order == 0) { drawU0(ug); } else { drawU1(ug); } } public Dimension2D calculateDimension(StringBounder stringBounder) { if (order == 0) { return calculateDimension0(stringBounder); } return calculateDimension1(stringBounder); } private void drawU0(UGraphic ug) { final HtmlColor color = fontConfiguration.getColor(); ug = ug.apply(new UChangeColor(color)).apply(new UChangeBackColor(color)).apply(new UStroke(0)); // final double width = getWidth(ug.getStringBounder()); ug = ug.apply(new UTranslate(3, 0)); ug.draw(new UEllipse(5, 5)); } public double getStartingAltitude(StringBounder stringBounder) { return -5; } private Dimension2D calculateDimension0(StringBounder stringBounder) { return new Dimension2DDouble(getWidth(stringBounder), 5); } private void drawU1(UGraphic ug) { final HtmlColor color = fontConfiguration.getColor(); ug = ug.apply(new UChangeColor(color)).apply(new UChangeBackColor(color)).apply(new UStroke(0)); final double width = getWidth(ug.getStringBounder()); ug = ug.apply(new UTranslate(width - 5, 0)); ug.draw(new URectangle(3.5, 3.5)); } private Dimension2D calculateDimension1(StringBounder stringBounder) { return new Dimension2DDouble(getWidth(stringBounder), 3); } }
3e0031ab1a93db42bfef5022c154bd4362dc22b9
654
java
Java
sdn-data-process-engine-middleware/opendaylight/hydrogen-client/src/test/java/de/tuberlin/cit/sdn/opendaylight/hydrogen/client/BaseTest.java
dos-group/vs.msc.ws14
fa3a786217df33d906aa05a5d1ada1a1751d22fd
[ "Apache-2.0" ]
3
2015-03-31T13:43:53.000Z
2019-04-16T11:57:03.000Z
sdn-data-process-engine-middleware/opendaylight/hydrogen-client/src/test/java/de/tuberlin/cit/sdn/opendaylight/hydrogen/client/BaseTest.java
dos-group/vs.msc.ws14
fa3a786217df33d906aa05a5d1ada1a1751d22fd
[ "Apache-2.0" ]
5
2015-01-02T10:01:31.000Z
2016-03-10T10:07:06.000Z
sdn-data-process-engine-middleware/opendaylight/hydrogen-client/src/test/java/de/tuberlin/cit/sdn/opendaylight/hydrogen/client/BaseTest.java
citlab/vs.msc.ws14
fa3a786217df33d906aa05a5d1ada1a1751d22fd
[ "Apache-2.0" ]
1
2016-03-09T22:34:58.000Z
2016-03-09T22:34:58.000Z
32.7
97
0.697248
96
package de.tuberlin.cit.sdn.opendaylight.hydrogen.client; import de.tuberlin.cit.sdn.opendaylight.commons.OdlSettings; import java.io.IOException; import java.util.Properties; public class BaseTest { protected OdlSettings settings; public void init() throws IOException { Properties properties = new Properties(); properties.load(this.getClass().getClassLoader().getResourceAsStream("test.properties")); settings = new OdlSettings(properties.getProperty("ip"), properties.getProperty("user"), properties.getProperty("password"), properties.getProperty("port")); } }
3e0031e56d265fa7a52ea790de3ae37678a6e1fe
145
java
Java
RoleService.java
Natalia1904/doing-1.0
68b6ce5c10ebc841989b6c8e68e6477ce530732a
[ "MIT" ]
null
null
null
RoleService.java
Natalia1904/doing-1.0
68b6ce5c10ebc841989b6c8e68e6477ce530732a
[ "MIT" ]
null
null
null
RoleService.java
Natalia1904/doing-1.0
68b6ce5c10ebc841989b6c8e68e6477ce530732a
[ "MIT" ]
null
null
null
16.111111
37
0.731034
97
package by.burim.doing.service; import by.burim.doing.entities.Role; public interface RoleService { Iterable<Role> loadAllRoles(); }
3e00331ecc793655d6b03f7087ddf24abd8b2860
13,179
java
Java
d3x-morpheus-viz/src/main/java/com/d3x/morpheus/viz/jfree/JFPiePlot.java
tipplerow/d3x-morpheus
a09568026a195a8b803a8b2fa0c8087535facf33
[ "Apache-2.0" ]
11
2018-11-19T21:59:11.000Z
2021-11-09T05:52:42.000Z
d3x-morpheus-viz/src/main/java/com/d3x/morpheus/viz/jfree/JFPiePlot.java
tipplerow/d3x-morpheus
a09568026a195a8b803a8b2fa0c8087535facf33
[ "Apache-2.0" ]
6
2018-09-30T15:56:14.000Z
2018-10-01T20:53:50.000Z
d3x-morpheus-viz/src/main/java/com/d3x/morpheus/viz/jfree/JFPiePlot.java
tipplerow/d3x-morpheus
a09568026a195a8b803a8b2fa0c8087535facf33
[ "Apache-2.0" ]
8
2019-04-13T05:03:57.000Z
2022-03-31T09:05:58.000Z
31.304038
150
0.589498
98
/* * Copyright (C) 2014-2018 D3X Systems - All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.d3x.morpheus.viz.jfree; import java.awt.*; import java.text.AttributedString; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.jfree.chart.labels.PieSectionLabelGenerator; import org.jfree.chart.plot.PiePlot3D; import org.jfree.chart.plot.RingPlot; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.general.PieDataset; import org.jfree.ui.RectangleInsets; import com.d3x.morpheus.viz.chart.pie.PieModel; import com.d3x.morpheus.viz.chart.pie.PieLabels; import com.d3x.morpheus.viz.chart.pie.PiePlot; import com.d3x.morpheus.viz.chart.pie.PieSection; import com.d3x.morpheus.viz.html.HtmlCode; import com.d3x.morpheus.viz.util.ColorModel; /** * An implementation of the PiePlot interface against JFreeChart. * * @author Xavier Witdouck * * <p><strong>This is open source software released under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0 License</a></strong></p> */ class JFPiePlot<X extends Comparable,S extends Comparable> implements PiePlot<X,S> { private ColorModel colorModel; private org.jfree.chart.plot.PiePlot plot; private Color sectionOutlineColor = Color.WHITE; private Stroke sectionOutlineStroke = new BasicStroke(1f); private JFPieModel<X,S> model = new JFPieModel<>(); private Map<X,PieSection> sectionMap = new HashMap<>(); private MorpheusPieLabels labels = new MorpheusPieLabels(); /** * Constructor * @param is3d true for a 3D Pie Plot */ JFPiePlot(boolean is3d) { this.plot = is3d ? new MorpheusPiePlot3D() : new MorpheusPiePlot2D(); this.plot.setDataset(model); this.colorModel = ColorModel.DEFAULT.get(); this.plot.setSectionOutlinesVisible(true); this.plot.setOutlineVisible(false); this.plot.setIgnoreNullValues(true); this.plot.setIgnoreZeroValues(true); this.plot.setAutoPopulateSectionPaint(true); this.plot.setBaseSectionOutlinePaint(sectionOutlineColor); this.plot.setBaseSectionOutlineStroke(sectionOutlineStroke); this.plot.setLabelPadding(new RectangleInsets(2, 10, 2, 10)); this.plot.setInteriorGap(0.02); this.plot.setStartAngle(0d); this.plot.setSimpleLabels(true); this.plot.setToolTipGenerator(this::toolTip); this.plot.setStartAngle(90); this.labels().on().withPercent(); if (plot instanceof RingPlot) { ((RingPlot)plot).setSectionDepth(1d); ((RingPlot)plot).setSeparatorsVisible(false); } else if (plot instanceof PiePlot3D) { ((PiePlot3D)plot).setDepthFactor(0.2d); } } @Override public PieModel<X,S> data() { return model; } @Override public PieLabels labels() { return labels; } @Override public PieSection section(X itemKey) { PieSection section = sectionMap.get(itemKey); if (section == null) { section = new MorpheusPieSection(itemKey); sectionMap.put(itemKey, section); } return section; } @Override public PiePlot<X,S> withStartAngle(double degrees) { this.plot.setStartAngle(90 - degrees); return this; } @Override public PiePlot<X,S> withPieHole(double percent) { if (plot instanceof RingPlot) { ((RingPlot)plot).setSectionDepth(1d - percent); } return this; } @Override public PiePlot<X,S> withSectionOutlineColor(Color color) { this.sectionOutlineColor = color; this.plot.setBaseSectionOutlinePaint(color); return this; } /** * Toggles the selection for the item specified * @param itemKey the section key */ void toggle(Comparable itemKey) { //todo; add selection logic to mimic Google chart behaviour } /** * Highlights a section by adjusting the outline for that section * @param itemKey the item key */ void highlight(Comparable itemKey) { try { this.model.keys().forEach(key -> { if (itemKey.equals(key)) { plot.setSectionOutlineStroke(key, new BasicStroke(1.5f)); plot.setSectionOutlinePaint(key, Color.BLACK); } else { plot.setSectionOutlineStroke(key, sectionOutlineStroke); plot.setSectionOutlinePaint(key, sectionOutlineColor); } }); } catch (Exception ex) { ex.printStackTrace(); } } /** * Returns the tooltip for the section key * @param dataset the dataset * @param key the section key * @return the tooltip, null for none */ private String toolTip(PieDataset dataset, Comparable key) { try { final double value = Optional.ofNullable(dataset.getValue(key)).map(Number::doubleValue).orElse(Double.NaN); if (!Double.isNaN(value)) { return HtmlCode.createHtml(writer -> { writer.newElement("html", html -> { final double total = DatasetUtilities.calculatePieDatasetTotal(dataset); final double percent = value / total; final StringBuilder text = new StringBuilder(); text.append(labels.valueFormat.format(value)); text.append(" ("); text.append(labels.percentFormat.format(percent)); text.append(")"); html.newElement("h2", h2 -> h2.text(key.toString())); html.newElement("h3", h3 -> h3.text(text.toString())); }); }); } else { return null; } } catch (Exception ex) { ex.printStackTrace(); return null; } } /** * Returns a reference to the underlying JFreeChart Plot object * @return the underlying plot object */ org.jfree.chart.plot.PiePlot underlying() { return plot; } private enum LabelType { NAME, VALUE, PERCENT } /** * An implementation of the PieLabels interface for JFreeChart */ private class MorpheusPieLabels implements PieLabels { private LabelType labelType = LabelType.PERCENT; private DecimalFormat valueFormat = new DecimalFormat("###,##0.##;-###,##0.##"); private DecimalFormat percentFormat = new DecimalFormat("0.##'%';-0.##'%'"); /** * Constructor */ MorpheusPieLabels() { this.percentFormat.setMultiplier(100); } @Override public PieLabels off() { plot.setLabelGenerator(null); return this; } @Override public PieLabels on() { plot.setLabelGenerator(new MorpheusPieSectionLabelGenerator()); return this; } @Override public PieLabels withName() { this.labelType = LabelType.NAME; return this; } @Override public PieLabels withValue() { this.labelType = LabelType.VALUE; return this; } @Override public PieLabels withPercent() { this.labelType = LabelType.PERCENT; return this; } @Override public PieLabels withFont(Font font) { plot.setLabelFont(font); return this; } @Override public PieLabels withTextColor(Color color) { plot.setLabelPaint(color); return this; } @Override public PieLabels withBackgroundColor(Color color) { plot.setLabelBackgroundPaint(color); return this; } } /** * An implementation of the PieSection interface for JFreeChart */ private class MorpheusPieSection implements PieSection { private X itemKey; private Color color; /** * Constructor * @param itemKey the key for this section */ MorpheusPieSection(X itemKey) { this.itemKey = itemKey; } @Override public PieSection withColor(Color color) { this.color = color; return this; } @Override public PieSection withOffset(double offset) { plot.setExplodePercent(itemKey, offset); return this; } } /** * An extension of JFreeChart PiePlot with Morpheus customizations */ private class MorpheusPiePlot2D extends org.jfree.chart.plot.RingPlot { @Override protected Paint lookupSectionPaint(Comparable key, boolean autoPopulate) { return getColor(key); } @Override() public Paint getSectionPaint(Comparable key) { return getColor(key); } /** * Returns the Pie section color for key * @param key the key for pie section * @return the section color */ @SuppressWarnings("unchecked") private Paint getColor(Comparable key) { try { final PieDataset dataset = getDataset(); if (dataset != null) { final MorpheusPieSection section = (MorpheusPieSection)section((X)key); return section.color != null ? section.color : colorModel.getColor(key); } return super.getSectionPaint(key); } catch (Exception ex) { ex.printStackTrace(); return super.getSectionPaint(key); } } } /** * An extension of JFreeChart PiePlot with Morpheus customizations */ private class MorpheusPiePlot3D extends org.jfree.chart.plot.PiePlot3D { @Override protected Paint lookupSectionPaint(Comparable key, boolean autoPopulate) { return getColor(key); } @Override() public Paint getSectionPaint(Comparable key) { return getColor(key); } /** * Returns the Pie section color for key * @param key the key for pie section * @return the section color */ @SuppressWarnings("unchecked") private Paint getColor(Comparable key) { try { final PieDataset dataset = getDataset(); if (dataset != null) { final MorpheusPieSection section = (MorpheusPieSection)section((X)key); return section.color != null ? section.color : colorModel.getColor(key); } return super.getSectionPaint(key); } catch (Exception ex) { ex.printStackTrace(); return super.getSectionPaint(key); } } } /** * An implementation of the PieSectionLabelGenerator to label pie sections */ private class MorpheusPieSectionLabelGenerator implements PieSectionLabelGenerator { @Override public String generateSectionLabel(PieDataset dataset, Comparable key) { try { if (labels.labelType == LabelType.NAME) { return key.toString(); } else if (labels.labelType == LabelType.VALUE) { final double value = Optional.ofNullable(dataset.getValue(key)).map(Number::doubleValue).orElse(Double.NaN); return Double.isNaN(value) ? "" : labels.valueFormat.format(value); } else if (labels.labelType == LabelType.PERCENT) { final double value = Optional.ofNullable(dataset.getValue(key)).map(Number::doubleValue).orElse(Double.NaN); final double total = DatasetUtilities.calculatePieDatasetTotal(dataset); final double percent = value / total; return labels.percentFormat.format(percent); } else { return null; } } catch (Exception ex) { ex.printStackTrace(); return null; } } @Override public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key) { return null; } } }
3e0033c6edabfdcc22d1b3570a4652e6ce6f6d51
109
java
Java
src/minecraft/zeonClient/main/Category.java
A-D-I-T-Y-A/Zeon-Client
ae97932a82f5cd095d4ab7bd922d2354f0031131
[ "MIT" ]
2
2021-03-25T15:50:33.000Z
2021-07-01T08:42:13.000Z
src/minecraft/zeonClient/main/Category.java
A-D-I-T-Y-A/Zeon-Client
ae97932a82f5cd095d4ab7bd922d2354f0031131
[ "MIT" ]
null
null
null
src/minecraft/zeonClient/main/Category.java
A-D-I-T-Y-A/Zeon-Client
ae97932a82f5cd095d4ab7bd922d2354f0031131
[ "MIT" ]
null
null
null
18.166667
53
0.715596
99
package zeonClient.main; public enum Category { COMBAT, MOVEMENT, RENDER, PLAYER, WORLD, OTHER, GUI }
3e003585061d9661d954e16d8c803aa24c3fe37d
2,969
java
Java
src/test/java/org/lefmaroli/display/SimpleGrayScaleImage.java
LefMarOli/PerlinNoiseJava
ce48dfd0cd06b8597e5eb8b356d5e12141c07590
[ "MIT" ]
null
null
null
src/test/java/org/lefmaroli/display/SimpleGrayScaleImage.java
LefMarOli/PerlinNoiseJava
ce48dfd0cd06b8597e5eb8b356d5e12141c07590
[ "MIT" ]
10
2021-05-04T15:46:58.000Z
2022-03-31T21:02:36.000Z
src/test/java/org/lefmaroli/display/SimpleGrayScaleImage.java
LefMarOli/PerlinNoiseJava
ce48dfd0cd06b8597e5eb8b356d5e12141c07590
[ "MIT" ]
null
null
null
28.548077
97
0.636915
100
package org.lefmaroli.display; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class SimpleGrayScaleImage { private static final Color[] COLORS = new Color[256]; static { for (var i = 0; i <= 255; i++) { COLORS[i] = new Color(i, i, i); } } private final BufferedImage image; private final int pixelScale; private final JFrame framedImage; private final JLabel label; private final int[][] colors; private final int width; private final int length; public SimpleGrayScaleImage(double[][] data, int pixelScale) { assertDataIsRectangular(data); this.width = data.length; this.length = data[0].length; this.pixelScale = pixelScale; this.colors = new int[width][length]; image = new BufferedImage(width, length, BufferedImage.TYPE_BYTE_GRAY); this.label = new JLabel(); framedImage = initializeImageFrame(label); updateImage(data); } private static void assertDataIsRectangular(double[][] data) { if (data.length < 1) { throw new IllegalArgumentException("Provided data is empty"); } int rowLength = data[0].length; for (double[] row : data) { if (row.length != rowLength) { throw new IllegalArgumentException("Provided data doesn't have same length across rows"); } } } public void setVisible() { this.framedImage.setVisible(true); } public void updateImage(double[][] newData) { assertNewDataHasSameDimensions(newData); for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { int colorIndex = (int) (newData[i][j] * 255); colors[i][j] = colorIndex; } } SwingUtilities.invokeLater( () -> { Graphics2D g = (Graphics2D) image.getGraphics(); for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { g.setColor(COLORS[colors[i][j]]); g.fillRect(i, j, pixelScale, pixelScale); } } label.setIcon(new ImageIcon(image)); framedImage.pack(); }); } public void dispose() { framedImage.dispose(); } private void assertNewDataHasSameDimensions(double[][] data) { if (data.length != width) { throw new IllegalArgumentException("Provided data has changed width"); } for (double[] row : data) { if (row.length != length) { throw new IllegalArgumentException( "Provided data doesn't have same length as original data"); } } } private JFrame initializeImageFrame(JLabel label) { JFrame frame = new JFrame(); frame.setSize(image.getWidth(), image.getHeight()); frame.getContentPane().add(label, BorderLayout.CENTER); frame.setLocationRelativeTo(null); return frame; } }