hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
454296ce2410e7e5197e6cb37cd653f3f4bde853
| 1,317
|
package com.example.jack.easyforecast;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements LocalFragment.OnFragmentInteractionListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new LocalFragment())
.commit();
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
| 28.021277
| 107
| 0.783599
|
3a1ef6d5e7f20ad963db420c71579eeb5292dddc
| 2,723
|
package org.rs2server.rs2.event;
import org.rs2server.rs2.model.Entity;
import org.rs2server.rs2.util.Benchmark;
import org.rs2server.rs2.util.Benchmarks;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class CycleEventHandler {
/**
* The instance of this class
*/
private static CycleEventHandler instance;
/**
* Returns the instance of this class
*
* @return
*/
public static CycleEventHandler getInstance() {
if (CycleEventHandler.instance == null) {
CycleEventHandler.instance = new CycleEventHandler();
}
return CycleEventHandler.instance;
}
/**
* Holds all of our events currently being ran
*/
private Queue<CycleEventContainer> events;
private Queue<CycleEventContainer> eventsToAdd;
/**
* Creates a new instance of this class
*/
public CycleEventHandler() {
events = new LinkedList<CycleEventContainer>();
eventsToAdd = new LinkedList<CycleEventContainer>();
}
/**
* Add an event to the list
*
* @param owner
* @param event
* @param cycles
* @return the container
*/
public CycleEventContainer addEvent(Entity owner, CycleEvent event, int cycles) {
CycleEventContainer container = new CycleEventContainer(owner, event, cycles);
if (owner.getClientIndex() == -1)
return container;
eventsToAdd.add(container);
return container;
}
/**
* Execute and remove events
*/
public void tick() {
//List<CycleEventContainer> remove = new ArrayList<CycleEventContainer>();
Benchmark b = Benchmarks.getBenchmark("cycleEvents");
b.start();
events.addAll(eventsToAdd);
eventsToAdd.clear();
for (Iterator<CycleEventContainer> cycleEvents = events.iterator(); cycleEvents.hasNext();) {
CycleEventContainer c = cycleEvents.next();
if (c != null) {
if (c.getOwner() == null || c.getOwner().getClientIndex() == -1)
cycleEvents.remove();
else {
if (c.needsExecution()) {
c.execute();
}
if (!c.isRunning()) {
cycleEvents.remove();
}
}
}
}
b.stop();
}
/**
* Returns the amount of events currently running
*
* @return amount
*/
public int getEventsCount() {
return events.size();
}
/**
* Stops all events which are being ran by the given owner
*
* @param owner
*/
/*
All events endGame when index == -1, which happens after unregister
public void stopEvents(Entity owner) {
for (CycleEventContainer c : events) {
if (c.getOwner() == owner) {
c.endGame();
}
}
} */
}
| 24.097345
| 95
| 0.620639
|
a2fec89b0de39e20fefb6e613310ca87a17d58ad
| 5,405
|
package org.riversun.rfcode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class implements the basic structure of the Random Forests. It contains methods to run the classification.
*
* Modified:
* author Tom Misawa(riversun.org@gmail.com)
* version July 10, 2019
* Copyright: MIT Licence
*
* Original:
* author Martin Pielot
* version June 30, 2015
* Copyright: MIT Licence
*/
public abstract class _RandomForest {
/**
* Tells the implementing class to run the classification
*
* @param predictions a list in which the classifier will store the predictions of each individual tree.
*/
protected abstract void runClassifiers(List<Prediction> predictions);
public String MyClass;
/**
* Flag that decides the voting strategy: when false, the class is decided by a simple majority vote; when true, the
* decision takes the number of positive leafs returned by each tree into account. True by default.
*/
public final boolean use_votes = true;
/** Runs the classification. The features have to be set by updating the fields of the implementing class. */
public Prediction runClassification() {
// Runs the classifier and stores each classifiers vote into an array
List<Prediction> predictions = new ArrayList<Prediction>();
runClassifiers(predictions);
// Count the number of votes and leafs for each label
Map<String, Integer> winners = new HashMap<String, Integer>();
Map<String, Integer> votes = new HashMap<String, Integer>();
int totalVotes = 0;
for (Prediction prediction : predictions) {
if (prediction != null) {
inc(winners, prediction.label, 1);
inc(votes, prediction.label, prediction.numPos);
totalVotes += prediction.getNumLeafs();
}
}
// Determine the label with the highest vote count
String winner = winner(use_votes ? votes : winners);
int numPosVotes = votes.get(winner);
int numNegVotes = totalVotes - numPosVotes;
// Create prediction object from the results and return as final result
Prediction result = new Prediction(winner, numPosVotes, numNegVotes);
return result;
}
/**
* Determines the winner from the given votes
*
* @param votes the list with the number of votes for each label
* @return the label with the highest number of votes
*/
private String winner(Map<String, Integer> votes) {
String winner = "";
int maxVotes = 0;
for (String label : votes.keySet()) {
int voteCount = votes.get(label);
if (voteCount > maxVotes) {
winner = label;
maxVotes = voteCount;
}
}
return winner;
}
/**
* Increases the votes for the given classifier by the given number
*
* @param votes Map containing the votes for each label
* @param label the label to which the votes shall be added
* @param voteCount the number of votes to add
*/
private void inc(Map<String, Integer> votes, String label, int voteCount) {
int count = 0;
if (votes.containsKey(label)) {
count = votes.get(label);
}
votes.put(label, count + voteCount);
}
/**
* This class encapsulates the prediction returned by the Random Forest classifier
* Modified:
* author Tom Misawa(riversun.org@gmail.com)
* version July 10, 2019
*
* Original:
* author Martin Pielot
* version June 30, 2015
*/
public static class Prediction {
/** The class label of the prediction, e.g. 'picked' */
public String label;
/** The number of votes FOR this label */
public int numPos;
/** The number of votes for OTHER labels */
public int numNeg;
/** The total number of votes */
public int total;
/** Probability - how certain the classifier is that the prediction is correct */
public double p;
/**
* Creates a new instance of a Prediction object
*
* @param label The class label of the prediction, e.g. 'picked'
* @param numPositive The number of votes FOR this label
* @param numNegative The number of votes for OTHER labels
*/
public Prediction(String label, double numPositive, double numNegative) {
this.label = label;
this.numPos = (int) (numPositive + 0.5);
this.numNeg = (int) (numNegative + 0.5);
this.total = this.numPos + this.numNeg;
this.p = getProbability();
}
/** Probability - how certain the classifier is that the prediction is correct */
private double getProbability() {
if (total == 0)
return 0;
int c = 10000;
double p = c * numPos / total;
return p / c;
}
/** The total number of votes */
public int getNumLeafs() {
return total;
}
@Override
public String toString() {
return label + ", \tpropability: " + p + ", (positive/negative)=( " + numPos + " / " + numNeg + " )";
}
}
}
| 33.364198
| 120
| 0.603885
|
853a1e9130491e96ba4c88dc63c7972dd2cb8abc
| 3,198
|
package com.huaweicloud.sdk.osm.v2.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huaweicloud.sdk.core.SdkResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/** Response Object */
public class ListHistoryOperateLogsResponse extends SdkResponse {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "total_count")
private Integer totalCount;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "ops_list")
private List<OperateLog> opsList = null;
public ListHistoryOperateLogsResponse withTotalCount(Integer totalCount) {
this.totalCount = totalCount;
return this;
}
/** 总记录数 minimum: 0 maximum: 9223372036854775807
*
* @return totalCount */
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public ListHistoryOperateLogsResponse withOpsList(List<OperateLog> opsList) {
this.opsList = opsList;
return this;
}
public ListHistoryOperateLogsResponse addOpsListItem(OperateLog opsListItem) {
if (this.opsList == null) {
this.opsList = new ArrayList<>();
}
this.opsList.add(opsListItem);
return this;
}
public ListHistoryOperateLogsResponse withOpsList(Consumer<List<OperateLog>> opsListSetter) {
if (this.opsList == null) {
this.opsList = new ArrayList<>();
}
opsListSetter.accept(this.opsList);
return this;
}
/** 操作列表
*
* @return opsList */
public List<OperateLog> getOpsList() {
return opsList;
}
public void setOpsList(List<OperateLog> opsList) {
this.opsList = opsList;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListHistoryOperateLogsResponse listHistoryOperateLogsResponse = (ListHistoryOperateLogsResponse) o;
return Objects.equals(this.totalCount, listHistoryOperateLogsResponse.totalCount)
&& Objects.equals(this.opsList, listHistoryOperateLogsResponse.opsList);
}
@Override
public int hashCode() {
return Objects.hash(totalCount, opsList);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ListHistoryOperateLogsResponse {\n");
sb.append(" totalCount: ").append(toIndentedString(totalCount)).append("\n");
sb.append(" opsList: ").append(toIndentedString(opsList)).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 ");
}
}
| 29.072727
| 107
| 0.647592
|
8c36ad2c1faf2dd55ab71fb7c73c7a2a3e7f035e
| 244
|
package com.dm.uap.dingtalk.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("dRoles")
public class DRoleController {
}
| 22.181818
| 62
| 0.831967
|
cd1e7ff0ea63bd366078c36488ec5989e98eb686
| 5,403
|
package net.cthesky.y86.Simulator;
import net.cthesky.y86.Instructions.*;
import java.util.HashMap;
import java.util.Map;
/**
* Project: Y86-net.cthesky.y86.Simulator
* Author: CtheSky
* Create Date: 2017/3/9
* Description:
* All rights reserved.
*/
public class Y86Simulator {
public Register[] registers;
public Memory memory;
public boolean ZF, SF, OF;
public int PC;
public int stat;
public Map<Integer, Integer> breakpoints;
/**
* Initialize simulator with given memory
* @param memory Memory object with y86 code loaded
*/
public Y86Simulator(Memory memory) {
registers = new Register[8];
registers[0] = new Register("%eax");
registers[1] = new Register("%ecx");
registers[2] = new Register("%edx");
registers[3] = new Register("%ebx");
registers[4] = new Register("%esp");
registers[5] = new Register("%ebp");
registers[6] = new Register("%esi");
registers[7] = new Register("%edi");
this.memory = memory;
PC = 0;
stat = 1;
breakpoints = new HashMap<>();
}
/**
* Run y86 code loaded
* @throws IllegalStateException when error occurs during execution
*/
public void run() throws IllegalStateException {
while (stat == 1) {
Instruction instruction = fetch();
execute(instruction);
}
}
/**
* Run the code until a breakpoint is reached
* @throws IllegalStateException when error occurs during execution
*/
public void continueToBreakpoint() throws IllegalStateException {
while (stat == 1) {
Instruction instruction = fetch();
execute(instruction);
if (breakpoints.containsKey(PC))
break;
}
}
/**
* Run only one instruction
* @throws IllegalStateException
*/
public void step() throws IllegalStateException {
if (stat == 1) {
Instruction instruction = fetch();
execute(instruction);
}
}
/**
* Returns a well-formatted representing all info of simulator
* @return String
*/
public String getResult() {
String state = "State: " + getStateString();
String pc = "PC: " + "0x" + PC;
String cc = "Condition Codes: " +
" ZF: " + (ZF ? "1": "0") +
" SF: " + (SF ? "1": "0") +
" OF: " + (OF ? "1": "0");
String registerInfo = "Changed Register State:\n";
for (Register r : registers) {
String value = Integer.toHexString(r.value);
if (value.length() < 8)
value = "00000000".substring(0, 8 - value.length()) + value;
registerInfo += r.name + ":0x00000000 " + "0x" + value + "\n";
}
String memoryInfo = "Changed Memory State:\n";
for (Memory.MemoLine ml : memory.changedMemory()) {
String addr = Integer.toHexString(ml.address / 8);
if (addr.length() < 4)
addr = "0000".substring(0, 4 - addr.length()) + addr;
String content = Integer.toHexString(ml.content);
if (content.length() < 8)
content = "00000000".substring(0, 8 - content.length()) + content;
memoryInfo += "0x" + addr + ":00000000 " + "0x" + content + "\n";
}
return state + "\n" + pc + "\n" + cc + "\n" + registerInfo + memoryInfo;
}
/**
* Return state of simulator
* @return String
*/
public String getStateString() {
if (stat == 1) return "AOK";
if (stat == 2) return "HLT";
if (stat == 3) return "ADR";
if (stat == 4) return "INS";
return "Unknown State";
}
/**
* Returns the register object of given name, return null when name doesn't match any register
* @param name String of register name
* @return According register object
*/
public Register getRegister(String name) {
switch (name) {
case "%eax": return registers[0];
case "%ecx": return registers[1];
case "%edx": return registers[2];
case "%ebx": return registers[3];
case "%esp": return registers[4];
case "%ebp": return registers[5];
case "%esi": return registers[6];
case "%edi": return registers[7];
default: return null;
}
}
private Instruction fetch() {
byte first = (byte)memory.get(PC * 8, 1);
Instruction ins = InstructionDispatcher.getInstruction(first);
if (ins == null) {
stat = 4;
String address = "address -> 0x" + Integer.toHexString(PC);
String content = "content -> 0x" + Integer.toHexString(first);
String msg = "Invalid instruction: " + address + content;
throw new IllegalStateException(msg);
}
return ins;
}
private void execute(Instruction instruction) {
instruction.execute(this);
}
public class Register {
public String name;
public int value;
public Register(String name) {
this.name = name;
}
@Override
public String toString() {
return name + " -> " + Integer.toHexString(value);
}
}
}
| 30.353933
| 98
| 0.543032
|
60243e87bc00f2ece28c1108b8167c5108c4dd14
| 399
|
package xyz.erupt.core.exception;
import lombok.extern.slf4j.Slf4j;
/**
* @author YuePeng
* date 2018-12-15
*/
@Slf4j
public class EruptNoLegalPowerException extends RuntimeException {
private static final String NO_LEGAL_POWER = "权限不足,该操作将被记录!";
public EruptNoLegalPowerException() {
//TODO 需要记录IP或者其他操作
throw new EruptWebApiRuntimeException(NO_LEGAL_POWER);
}
}
| 21
| 66
| 0.73183
|
18c90bb58a226b0e26402527c4a187c07d7796bd
| 2,487
|
package com.skytala.eCommerce.domain.accounting.relations.fixedAsset.mapper.identType;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.ofbiz.entity.GenericValue;
import com.skytala.eCommerce.domain.accounting.relations.fixedAsset.model.identType.FixedAssetIdentType;
public class FixedAssetIdentTypeMapper {
public static Map<String, Object> map(FixedAssetIdentType fixedassetidenttype) {
Map<String, Object> returnVal = new HashMap<String, Object>();
if(fixedassetidenttype.getFixedAssetIdentTypeId() != null ){
returnVal.put("fixedAssetIdentTypeId",fixedassetidenttype.getFixedAssetIdentTypeId());
}
if(fixedassetidenttype.getDescription() != null ){
returnVal.put("description",fixedassetidenttype.getDescription());
}
return returnVal;
}
public static FixedAssetIdentType map(Map<String, Object> fields) {
FixedAssetIdentType returnVal = new FixedAssetIdentType();
if(fields.get("fixedAssetIdentTypeId") != null) {
returnVal.setFixedAssetIdentTypeId((String) fields.get("fixedAssetIdentTypeId"));
}
if(fields.get("description") != null) {
returnVal.setDescription((String) fields.get("description"));
}
return returnVal;
}
public static FixedAssetIdentType mapstrstr(Map<String, String> fields) throws Exception {
FixedAssetIdentType returnVal = new FixedAssetIdentType();
if(fields.get("fixedAssetIdentTypeId") != null) {
returnVal.setFixedAssetIdentTypeId((String) fields.get("fixedAssetIdentTypeId"));
}
if(fields.get("description") != null) {
returnVal.setDescription((String) fields.get("description"));
}
return returnVal;
}
public static FixedAssetIdentType map(GenericValue val) {
FixedAssetIdentType returnVal = new FixedAssetIdentType();
returnVal.setFixedAssetIdentTypeId(val.getString("fixedAssetIdentTypeId"));
returnVal.setDescription(val.getString("description"));
return returnVal;
}
public static FixedAssetIdentType map(HttpServletRequest request) throws Exception {
FixedAssetIdentType returnVal = new FixedAssetIdentType();
Map<String, String[]> paramMap = request.getParameterMap();
if(paramMap.containsKey("fixedAssetIdentTypeId")) {
returnVal.setFixedAssetIdentTypeId(request.getParameter("fixedAssetIdentTypeId"));
}
if(paramMap.containsKey("description")) {
returnVal.setDescription(request.getParameter("description"));
}
return returnVal;
}
}
| 27.94382
| 104
| 0.782871
|
4b969085c3409c594744c5a719df21f2005ba08b
| 197
|
package system.web.filter.chain;
import java.util.Set;
/**
*
* @author wangchunzi
*/
public abstract class FilterModels {
public abstract void put(Set<Class> modelClass);
}
| 14.071429
| 53
| 0.659898
|
250bcc3419c489fba0759192733a8f04f710e129
| 786
|
/*
* @copyright defined in LICENSE.txt
*/
package hera.transport;
import static org.junit.Assert.assertNotNull;
import hera.AbstractTestCase;
import hera.api.model.Block;
import org.junit.Test;
import types.Blockchain;
import types.Blockchain.BlockBody;
import types.Blockchain.Tx;
public class BlockConverterTest extends AbstractTestCase {
@Test
public void testConvert() {
final ModelConverter<Block, Blockchain.Block> converter = new BlockConverterFactory().create();
final Blockchain.Block rpcBlock = Blockchain.Block.newBuilder()
.setBody(BlockBody.newBuilder()
.addTxs(Tx.newBuilder().build())
.build())
.build();
final Block converted = converter.convertToDomainModel(rpcBlock);
assertNotNull(converted);
}
}
| 25.354839
| 99
| 0.729008
|
dcb07c8cdf3a0fe5954aeef0046bd216ccf4c4b4
| 1,077
|
package com.api.starter.util.utils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtils {
/**
* 签发token
* @param userName 用户名
* @return token
*/
public static String create(String userName) {
String token = Jwts.builder()
.setSubject(userName)
.setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
.signWith(SignatureAlgorithm.HS512, "MyJwtSecret")
.compact();
return token;
}
/**
* 解析token
* @param token token
* @return 用户名
*/
public static String parse(String token) {
String username = null;
try {
username = Jwts.parser()
.setSigningKey("MyJwtSecret")
.parseClaimsJws(token.replace("Bearer ", ""))
.getBody()
.getSubject();
} catch (Exception e) {
e.printStackTrace();
}
return username;
}
}
| 24.477273
| 90
| 0.53389
|
3e84b883f54d147fc27781d4b077170551af2a0f
| 211
|
package com.github.sachil.uplayer.upnp;
import org.fourthline.cling.support.model.TransportState;
public interface TransportStateChangedListener {
public void transportStateChanged(TransportState state);
}
| 23.444444
| 57
| 0.838863
|
ef49df8b7005e5ede18daa1e1d519f7ce1d8ec9f
| 5,596
|
/*
Copyright 2017 Digital Learning Sciences (DLS) at the
University Corporation for Atmospheric Research (UCAR),
P.O. Box 3000, Boulder, CO 80307
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package edu.ucar.dls.harvestmanager;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Map;
import org.dlese.dpc.util.Utils;
import org.dlese.dpc.xml.Dom4jUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import edu.ucar.dls.harvest.Config;
public class MetadataDAO {
private String metadatahandle=null;
private String partnerid=null;
private String nativeformat=null;
private String targetformat=null;
private String target_xml=null;
private String resourceUrl = null;
private String resourcehandle = null;
private String sessionid = null;
private String collectionName = null;
private Timestamp created_date = null;
private String setspec = null;
private Element targetXMLRootElement = null;
public MetadataDAO(ResultSet rs, Map<String, String>collectionNameMap, boolean containsResource)
{
try {
this.metadatahandle = rs.getString("metadatahandle");
this.partnerid = rs.getString("partnerid");
this.nativeformat = rs.getString("nativeformat");
this.targetformat = rs.getString("targetformat");
this.setspec = rs.getString("setspec");
this.created_date = rs.getTimestamp("created_date");
if(this.setspec!=null && collectionNameMap.containsKey(this.setspec))
this.collectionName = collectionNameMap.get(this.setspec);
this.sessionid = rs.getString("sessionid");
if(containsResource)
{
this.resourceUrl = rs.getString("url");
this.resourcehandle = rs.getString("resourcehandle");
}
byte[] blob = rs.getBytes("target_xml");
if(blob!=null)
try {
this.target_xml = new String(blob, Config.ENCODING);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public String getMetadatahandle() {
return metadatahandle;
}
public String getPartnerid() {
return partnerid;
}
public String getCreateddate() {
try {
return Utils.convertDateToString(created_date, "EEE, MMM d, yyyy h:mm:ss a zzz");
} catch (Throwable t) {
return created_date.toString();
}
}
public String getNativeformat() {
return nativeformat;
}
public String getTargetformat() {
return targetformat;
}
public String getTarget_xml() {
return target_xml;
}
public String getResourceUrl() {
return resourceUrl;
}
public String getResourcehandle() {
return resourcehandle;
}
public String getSessionid() {
return sessionid;
}
public String getSetspec() {
return setspec;
}
public String getTitle()
{
Element rootElement = this.getTargetXMLDomRootElement();
if(rootElement != null)
{
if(this.targetformat.equals("nsdl_dc"))
{
String value = rootElement.valueOf("*[name()='dc:title'][@xml:lang='en']");
if (value==null||value=="")
value= rootElement.valueOf("*[name()='dc:title']");
return value;
}
else if(this.targetformat.equals("comm_para"))
return rootElement.valueOf("*[name()='paradataTitle']");
else if(this.targetformat.equals("comm_anno"))
return rootElement.valueOf("*[name()='title']");
}
return null;
}
public String getDescription()
{
Element rootElement = this.getTargetXMLDomRootElement();
if(rootElement != null)
{
if(this.targetformat.equals("nsdl_dc"))
{
String value = rootElement.valueOf("*[name()='dc:description'][@xml:lang='en'] ");
if (value==null||value=="")
value= rootElement.valueOf("*[name()='dc:description']");
return value;
}
else if(this.targetformat.equals("comm_para"))
return rootElement.valueOf("*[name()='paradataDescription'] ");
}
return null;
}
public String getDocumentUrl()
{
Element rootElement = this.getTargetXMLDomRootElement();
if(rootElement != null)
{
if(this.targetformat.equals("nsdl_dc"))
return rootElement.valueOf("*[name()='dc:identifier'][@xsi:type='dct:URI']");
else if(this.targetformat.equals("comm_para"))
return rootElement.valueOf("*[name()='usageDataResourceURL'][contains(.,'http:') or contains(.,'https:') or contains(.,'ftp:') or contains(.,'www')]");
else if(this.targetformat.equals("comm_anno"))
return rootElement.valueOf("*[name()='annotatedID'][@idType='URL']");
}
return null;
}
private Element getTargetXMLDomRootElement()
{
if( targetXMLRootElement==null && this.target_xml!=null)
{
Document document;
try {
document = Dom4jUtils.getXmlDocument(this.target_xml);
this.targetXMLRootElement = document.getRootElement();
}
catch (DocumentException e) {
// do nothing just don't show anything
}
}
return this.targetXMLRootElement;
}
public String getCollectionName() {
return collectionName;
}
}
| 28.697436
| 155
| 0.706576
|
8185d216a415ee06d0e070c9a88646f093683f1e
| 2,018
|
package com.chihoc.CHSectionListView;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by ChiHo on 2016/11/17.
*/
public abstract class CHBaseFragment extends Fragment {
protected int mViewId;
protected View mContainerView;
protected Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity.getBaseContext();
}
@Override
public void onDestroy() {
super.onDestroy();
}
public String getTitle(){
return String.valueOf(getActivity().getTitle());
}
public void setTitle(String title) {
getActivity().setTitle(title);
}
protected void setContainerView(int viewId) {
mViewId = viewId;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mContainerView == null) {
mContainerView = inflater.inflate(mViewId, null);
initView(mContainerView);
}
ViewGroup parent = (ViewGroup) mContainerView.getParent();
if (parent != null) {
parent.removeView(mContainerView);
}
return mContainerView;
}
protected void initView(View view) {
}
/**
* 判断方法是否被重写
* @param obj 对象
* @param name 方法名
* @return 是否重写
*/
protected boolean isMethodOverriden(Object obj, String name, Class<?>... parameterTypes)
{
try {
Class<?> clazz = obj.getClass();
return clazz.getDeclaredMethod(name, parameterTypes) != null;
}
catch (SecurityException | NoSuchMethodException ignored) {
}
return false;
}
}
| 24.313253
| 103
| 0.64222
|
13ef3b254e3a0f09b05626bbebde50bf16235f2e
| 805
|
package com.mindcoders.phial.internal.util;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.Window;
import java.io.IOException;
/**
* Created by rost on 10/23/17.
*/
public final class ScreenShotUtil {
private ScreenShotUtil() {
//to hide
}
@NonNull
public static Bitmap takeScreenShot(Window window) throws IOException {
final View rootView = window.getDecorView().getRootView();
final boolean drawingCacheEnabled = rootView.isDrawingCacheEnabled();
rootView.setDrawingCacheEnabled(true);
try {
return Bitmap.createBitmap(rootView.getDrawingCache());
} finally {
rootView.setDrawingCacheEnabled(drawingCacheEnabled);
}
}
}
| 25.15625
| 77
| 0.695652
|
80e260ca5f5f89f1b3c587963b93febb9ec2d56a
| 3,041
|
/*
* 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 marquez.db;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import marquez.db.mappers.JobRowMapper;
import marquez.db.models.JobRow;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
@RegisterRowMapper(JobRowMapper.class)
public interface JobDao {
@SqlUpdate(
"INSERT INTO jobs ("
+ "uuid, "
+ "type, "
+ "created_at, "
+ "updated_at, "
+ "namespace_uuid, "
+ "name, "
+ "description, "
+ "current_version_uuid"
+ ") VALUES ("
+ ":uuid, "
+ ":type, "
+ ":createdAt, "
+ ":updatedAt, "
+ ":namespaceUuid, "
+ ":name, "
+ ":description, "
+ ":currentVersionUuid)")
void insert(@BindBean JobRow row);
@SqlQuery(
"SELECT EXISTS (SELECT 1 FROM jobs AS j "
+ "INNER JOIN namespaces AS n "
+ " ON (n.name = :namespaceName AND "
+ " j.namespace_uuid = n.uuid AND "
+ " j.name = :jobName))")
boolean exists(String namespaceName, String jobName);
/**
* Updates the current version of the job
*
* @param rowUuid the jobs.uuid
* @param updatedAt when it was updated
* @param currentVersionUuid job_versions.uuid for the current version
*/
@SqlUpdate(
"UPDATE jobs "
+ "SET updated_at = :updatedAt, "
+ " current_version_uuid = :currentVersionUuid "
+ "WHERE uuid = :rowUuid")
void updateVersion(UUID rowUuid, Instant updatedAt, UUID currentVersionUuid);
@SqlQuery(
"SELECT j.*, n.name AS namespace_name FROM jobs AS j "
+ "INNER JOIN namespaces AS n "
+ " ON (n.name = :namespaceName AND "
+ " j.namespace_uuid = n.uuid AND "
+ " j.name = :jobName)")
Optional<JobRow> find(String namespaceName, String jobName);
@SqlQuery(
"SELECT j.*, n.name AS namespace_name FROM jobs AS j "
+ "INNER JOIN namespaces AS n "
+ " ON (n.name = :namespaceName AND j.namespace_uuid = n.uuid) "
+ "ORDER BY j.name "
+ "LIMIT :limit OFFSET :offset")
List<JobRow> findAll(String namespaceName, int limit, int offset);
@SqlQuery("SELECT COUNT(*) FROM jobs")
int count();
}
| 33.054348
| 79
| 0.619204
|
a1ed5e0ca891231308861b9cb4cdeadc85c5f6e3
| 524
|
package com.baomidou.springmvc.service.system.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.springmvc.mapper.system.PictureMapper;
import com.baomidou.springmvc.model.system.Picture;
import com.baomidou.springmvc.service.system.IPictureService;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author z77z123
* @since 2018-02-23
*/
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements IPictureService {
}
| 24.952381
| 104
| 0.793893
|
81f8830ea1eff6d0c0bed2809714c8b44eeda03c
| 5,155
|
package de.mide.blinkerpause;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
/**
* App demonstriert wie unter Verwendung geeigneter Lifecycle-Methoden ein
* Thread pausiert werden kann, solange die zugehörige Activity-Instanz
* nicht sichtbar ist.
* <br><br>
*
* This project is licensed under the terms of the BSD 3-Clause License.
*/
public class MainActivity extends Activity {
/** Tag für Log-Messages dieser Activity. */
public static final String TAG4LOGGING = "BlinkerPause";
/**
* UI-Element, dessen Hintergrund-Farbe durch einen Thread
* ständig geändert wird, so dass ein Blink-Effekt entsteht.
*/
protected TextView _blinkendesTextview = null;
/** Thread-Instanz, die den "Blink-Effekt" des TextView-Elements erzeugt. */
protected BlinkerThread _blinkerThread = null;
/**
* Lifecycle-Methode:
* Layout-Datei laden und Referenz auf blinkendes TextView-Element holen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_blinkendesTextview = findViewById(R.id.textview_blinkend);
}
/**
* Lifecycle-Methode der Activity für Übergang von Zustand
* "unsichtbar" nach "sichtbar"; es wird eine Instanz von
* {@link BlinkerThread} erzeugt und gestartet.
*/
@Override
protected void onStart() {
super.onStart();
_blinkerThread = new BlinkerThread();
_blinkerThread.start();
Log.i(TAG4LOGGING, "Blinker-Thread wurde gestartet.");
}
/**
* Lifecycle-Methode der Activity für Übergang von Zustand
* "sichtbar" nach "unsichtbar"; die Instanz von
* {@link BlinkerThread} wird beendet.
*/
@Override
protected void onStop() {
_blinkerThread.beenden();
Log.i(TAG4LOGGING, "Blinker-Thread wurde gestoppt.");
super.onStop();
}
/**
* Event-Handler für den Button, öffnet mit einem expliziten
* Intent eine andere Activity.
*
* @param view Button-Objekt, auf das geklickt wurde
*/
public void onKlickAufButton(View view) {
Intent intent = new Intent(this, ZweiteActivity.class);
startActivity(intent);
}
/* *************************** */
/* *** Start innere Klasse *** */
/* *************************** */
/**
* Innere Thread-Klasse für den Blinker-Effekt.
*/
protected class BlinkerThread extends Thread {
/** Anhand dieser Member-Variable erkennt der Thread, dass er sich beenden soll. */
protected boolean __beenden = false;
/**
* Setzt ein Thread-internes Flag, damit der Thread Bescheid weiß, dass er nach
* der nächsten Iteration sich beenden soll.
*/
public void beenden() {
__beenden = true;
}
/**
* Der Inhalt dieser Methode wird von einem Hintergrund-Thread (Worker-Thread)
* ausgeführt; hier ist das "Blinken" implementiert.
*/
@Override
public void run() {
int zaehler = 0;
while(true) { // Endlos-Schleife
if (__beenden == true) {
break;
}
// Farbe in Abhängigkeit davon, ob Wert in "zaehler" gerade oder ungerade ist, setzen.
if (++zaehler % 2 == 0) {
_blinkendesTextview.post(new Runnable() {
@Override
public void run() {
_blinkendesTextview.setBackgroundColor( 0xFFFFFF00 ); // Gelb mit voller Deck-Kraft
}
});
Log.i(TAG4LOGGING, "Blinker: EIN (" + zaehler + ")");
} else {
_blinkendesTextview.post(new Runnable() {
@Override
public void run() {
_blinkendesTextview.setBackgroundColor( 0xFFD0D0D0 ); // Grauton
}
});
Log.i(TAG4LOGGING, "Blinker: AUS (" + zaehler + ")");
}
try {
Thread.sleep(1000); // Eine Sekunde warten, ohne dabei CPU-Zeit zu verschwenden
}
catch (InterruptedException ex) {
Log.e(TAG4LOGGING, "Exception während Warten aufgetreten: " + ex);
}
} // Endlos-Schleife
// Wenn wir bis zu dieser Stelle kommen (da Endlos-Schleife geht dies nur über "break"),
// dann wird der Thread beendet (Ende run()-Methode => Ende Thread).
}
};
/* *************************** */
/* *** Ende innere Klasse *** */
/* *************************** */
};
| 29.797688
| 112
| 0.540252
|
2b93e9421b89015ce0436a342c72c2741714c2f8
| 280
|
// to show the working of insert() method
class insertMethod
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("VishwanathSingh");
sb.insert(10," Pratap ");
System.out.print("String : "+sb);
}
}
| 20
| 64
| 0.575
|
a1bc5e4ce4cd2c4c78fda2a6ad7b44aa486d2728
| 50,545
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: grpc/gcp/handshaker.proto
package io.grpc.alts.internal;
/**
* Protobuf type {@code grpc.gcp.HandshakerResult}
*/
public final class HandshakerResult extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:grpc.gcp.HandshakerResult)
HandshakerResultOrBuilder {
private static final long serialVersionUID = 0L;
// Use HandshakerResult.newBuilder() to construct.
private HandshakerResult(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private HandshakerResult() {
applicationProtocol_ = "";
recordProtocol_ = "";
keyData_ = com.google.protobuf.ByteString.EMPTY;
keepChannelOpen_ = false;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private HandshakerResult(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
applicationProtocol_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
recordProtocol_ = s;
break;
}
case 26: {
keyData_ = input.readBytes();
break;
}
case 34: {
io.grpc.alts.internal.Identity.Builder subBuilder = null;
if (peerIdentity_ != null) {
subBuilder = peerIdentity_.toBuilder();
}
peerIdentity_ = input.readMessage(io.grpc.alts.internal.Identity.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(peerIdentity_);
peerIdentity_ = subBuilder.buildPartial();
}
break;
}
case 42: {
io.grpc.alts.internal.Identity.Builder subBuilder = null;
if (localIdentity_ != null) {
subBuilder = localIdentity_.toBuilder();
}
localIdentity_ = input.readMessage(io.grpc.alts.internal.Identity.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(localIdentity_);
localIdentity_ = subBuilder.buildPartial();
}
break;
}
case 48: {
keepChannelOpen_ = input.readBool();
break;
}
case 58: {
io.grpc.alts.internal.RpcProtocolVersions.Builder subBuilder = null;
if (peerRpcVersions_ != null) {
subBuilder = peerRpcVersions_.toBuilder();
}
peerRpcVersions_ = input.readMessage(io.grpc.alts.internal.RpcProtocolVersions.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(peerRpcVersions_);
peerRpcVersions_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.alts.internal.HandshakerProto.internal_static_grpc_gcp_HandshakerResult_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.alts.internal.HandshakerProto.internal_static_grpc_gcp_HandshakerResult_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.alts.internal.HandshakerResult.class, io.grpc.alts.internal.HandshakerResult.Builder.class);
}
public static final int APPLICATION_PROTOCOL_FIELD_NUMBER = 1;
private volatile java.lang.Object applicationProtocol_;
/**
* <pre>
* The application protocol negotiated for this connection.
* </pre>
*
* <code>string application_protocol = 1;</code>
*/
public java.lang.String getApplicationProtocol() {
java.lang.Object ref = applicationProtocol_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
applicationProtocol_ = s;
return s;
}
}
/**
* <pre>
* The application protocol negotiated for this connection.
* </pre>
*
* <code>string application_protocol = 1;</code>
*/
public com.google.protobuf.ByteString
getApplicationProtocolBytes() {
java.lang.Object ref = applicationProtocol_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
applicationProtocol_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RECORD_PROTOCOL_FIELD_NUMBER = 2;
private volatile java.lang.Object recordProtocol_;
/**
* <pre>
* The record protocol negotiated for this connection.
* </pre>
*
* <code>string record_protocol = 2;</code>
*/
public java.lang.String getRecordProtocol() {
java.lang.Object ref = recordProtocol_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
recordProtocol_ = s;
return s;
}
}
/**
* <pre>
* The record protocol negotiated for this connection.
* </pre>
*
* <code>string record_protocol = 2;</code>
*/
public com.google.protobuf.ByteString
getRecordProtocolBytes() {
java.lang.Object ref = recordProtocol_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
recordProtocol_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int KEY_DATA_FIELD_NUMBER = 3;
private com.google.protobuf.ByteString keyData_;
/**
* <pre>
* Cryptographic key data. The key data may be more than the key length
* required for the record protocol, thus the client of the handshaker
* service needs to truncate the key data into the right key length.
* </pre>
*
* <code>bytes key_data = 3;</code>
*/
public com.google.protobuf.ByteString getKeyData() {
return keyData_;
}
public static final int PEER_IDENTITY_FIELD_NUMBER = 4;
private io.grpc.alts.internal.Identity peerIdentity_;
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public boolean hasPeerIdentity() {
return peerIdentity_ != null;
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public io.grpc.alts.internal.Identity getPeerIdentity() {
return peerIdentity_ == null ? io.grpc.alts.internal.Identity.getDefaultInstance() : peerIdentity_;
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public io.grpc.alts.internal.IdentityOrBuilder getPeerIdentityOrBuilder() {
return getPeerIdentity();
}
public static final int LOCAL_IDENTITY_FIELD_NUMBER = 5;
private io.grpc.alts.internal.Identity localIdentity_;
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public boolean hasLocalIdentity() {
return localIdentity_ != null;
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public io.grpc.alts.internal.Identity getLocalIdentity() {
return localIdentity_ == null ? io.grpc.alts.internal.Identity.getDefaultInstance() : localIdentity_;
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public io.grpc.alts.internal.IdentityOrBuilder getLocalIdentityOrBuilder() {
return getLocalIdentity();
}
public static final int KEEP_CHANNEL_OPEN_FIELD_NUMBER = 6;
private boolean keepChannelOpen_;
/**
* <pre>
* Indicate whether the handshaker service client should keep the channel
* between the handshaker service open, e.g., in order to handle
* post-handshake messages in the future.
* </pre>
*
* <code>bool keep_channel_open = 6;</code>
*/
public boolean getKeepChannelOpen() {
return keepChannelOpen_;
}
public static final int PEER_RPC_VERSIONS_FIELD_NUMBER = 7;
private io.grpc.alts.internal.RpcProtocolVersions peerRpcVersions_;
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public boolean hasPeerRpcVersions() {
return peerRpcVersions_ != null;
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public io.grpc.alts.internal.RpcProtocolVersions getPeerRpcVersions() {
return peerRpcVersions_ == null ? io.grpc.alts.internal.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_;
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public io.grpc.alts.internal.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder() {
return getPeerRpcVersions();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getApplicationProtocolBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, applicationProtocol_);
}
if (!getRecordProtocolBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, recordProtocol_);
}
if (!keyData_.isEmpty()) {
output.writeBytes(3, keyData_);
}
if (peerIdentity_ != null) {
output.writeMessage(4, getPeerIdentity());
}
if (localIdentity_ != null) {
output.writeMessage(5, getLocalIdentity());
}
if (keepChannelOpen_ != false) {
output.writeBool(6, keepChannelOpen_);
}
if (peerRpcVersions_ != null) {
output.writeMessage(7, getPeerRpcVersions());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getApplicationProtocolBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, applicationProtocol_);
}
if (!getRecordProtocolBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, recordProtocol_);
}
if (!keyData_.isEmpty()) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, keyData_);
}
if (peerIdentity_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getPeerIdentity());
}
if (localIdentity_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(5, getLocalIdentity());
}
if (keepChannelOpen_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(6, keepChannelOpen_);
}
if (peerRpcVersions_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(7, getPeerRpcVersions());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.grpc.alts.internal.HandshakerResult)) {
return super.equals(obj);
}
io.grpc.alts.internal.HandshakerResult other = (io.grpc.alts.internal.HandshakerResult) obj;
boolean result = true;
result = result && getApplicationProtocol()
.equals(other.getApplicationProtocol());
result = result && getRecordProtocol()
.equals(other.getRecordProtocol());
result = result && getKeyData()
.equals(other.getKeyData());
result = result && (hasPeerIdentity() == other.hasPeerIdentity());
if (hasPeerIdentity()) {
result = result && getPeerIdentity()
.equals(other.getPeerIdentity());
}
result = result && (hasLocalIdentity() == other.hasLocalIdentity());
if (hasLocalIdentity()) {
result = result && getLocalIdentity()
.equals(other.getLocalIdentity());
}
result = result && (getKeepChannelOpen()
== other.getKeepChannelOpen());
result = result && (hasPeerRpcVersions() == other.hasPeerRpcVersions());
if (hasPeerRpcVersions()) {
result = result && getPeerRpcVersions()
.equals(other.getPeerRpcVersions());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + APPLICATION_PROTOCOL_FIELD_NUMBER;
hash = (53 * hash) + getApplicationProtocol().hashCode();
hash = (37 * hash) + RECORD_PROTOCOL_FIELD_NUMBER;
hash = (53 * hash) + getRecordProtocol().hashCode();
hash = (37 * hash) + KEY_DATA_FIELD_NUMBER;
hash = (53 * hash) + getKeyData().hashCode();
if (hasPeerIdentity()) {
hash = (37 * hash) + PEER_IDENTITY_FIELD_NUMBER;
hash = (53 * hash) + getPeerIdentity().hashCode();
}
if (hasLocalIdentity()) {
hash = (37 * hash) + LOCAL_IDENTITY_FIELD_NUMBER;
hash = (53 * hash) + getLocalIdentity().hashCode();
}
hash = (37 * hash) + KEEP_CHANNEL_OPEN_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getKeepChannelOpen());
if (hasPeerRpcVersions()) {
hash = (37 * hash) + PEER_RPC_VERSIONS_FIELD_NUMBER;
hash = (53 * hash) + getPeerRpcVersions().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.alts.internal.HandshakerResult parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.grpc.alts.internal.HandshakerResult parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.alts.internal.HandshakerResult parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.grpc.alts.internal.HandshakerResult prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code grpc.gcp.HandshakerResult}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:grpc.gcp.HandshakerResult)
io.grpc.alts.internal.HandshakerResultOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.alts.internal.HandshakerProto.internal_static_grpc_gcp_HandshakerResult_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.alts.internal.HandshakerProto.internal_static_grpc_gcp_HandshakerResult_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.alts.internal.HandshakerResult.class, io.grpc.alts.internal.HandshakerResult.Builder.class);
}
// Construct using io.grpc.alts.internal.HandshakerResult.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
applicationProtocol_ = "";
recordProtocol_ = "";
keyData_ = com.google.protobuf.ByteString.EMPTY;
if (peerIdentityBuilder_ == null) {
peerIdentity_ = null;
} else {
peerIdentity_ = null;
peerIdentityBuilder_ = null;
}
if (localIdentityBuilder_ == null) {
localIdentity_ = null;
} else {
localIdentity_ = null;
localIdentityBuilder_ = null;
}
keepChannelOpen_ = false;
if (peerRpcVersionsBuilder_ == null) {
peerRpcVersions_ = null;
} else {
peerRpcVersions_ = null;
peerRpcVersionsBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.grpc.alts.internal.HandshakerProto.internal_static_grpc_gcp_HandshakerResult_descriptor;
}
@java.lang.Override
public io.grpc.alts.internal.HandshakerResult getDefaultInstanceForType() {
return io.grpc.alts.internal.HandshakerResult.getDefaultInstance();
}
@java.lang.Override
public io.grpc.alts.internal.HandshakerResult build() {
io.grpc.alts.internal.HandshakerResult result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public io.grpc.alts.internal.HandshakerResult buildPartial() {
io.grpc.alts.internal.HandshakerResult result = new io.grpc.alts.internal.HandshakerResult(this);
result.applicationProtocol_ = applicationProtocol_;
result.recordProtocol_ = recordProtocol_;
result.keyData_ = keyData_;
if (peerIdentityBuilder_ == null) {
result.peerIdentity_ = peerIdentity_;
} else {
result.peerIdentity_ = peerIdentityBuilder_.build();
}
if (localIdentityBuilder_ == null) {
result.localIdentity_ = localIdentity_;
} else {
result.localIdentity_ = localIdentityBuilder_.build();
}
result.keepChannelOpen_ = keepChannelOpen_;
if (peerRpcVersionsBuilder_ == null) {
result.peerRpcVersions_ = peerRpcVersions_;
} else {
result.peerRpcVersions_ = peerRpcVersionsBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.grpc.alts.internal.HandshakerResult) {
return mergeFrom((io.grpc.alts.internal.HandshakerResult)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.grpc.alts.internal.HandshakerResult other) {
if (other == io.grpc.alts.internal.HandshakerResult.getDefaultInstance()) return this;
if (!other.getApplicationProtocol().isEmpty()) {
applicationProtocol_ = other.applicationProtocol_;
onChanged();
}
if (!other.getRecordProtocol().isEmpty()) {
recordProtocol_ = other.recordProtocol_;
onChanged();
}
if (other.getKeyData() != com.google.protobuf.ByteString.EMPTY) {
setKeyData(other.getKeyData());
}
if (other.hasPeerIdentity()) {
mergePeerIdentity(other.getPeerIdentity());
}
if (other.hasLocalIdentity()) {
mergeLocalIdentity(other.getLocalIdentity());
}
if (other.getKeepChannelOpen() != false) {
setKeepChannelOpen(other.getKeepChannelOpen());
}
if (other.hasPeerRpcVersions()) {
mergePeerRpcVersions(other.getPeerRpcVersions());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.grpc.alts.internal.HandshakerResult parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.grpc.alts.internal.HandshakerResult) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object applicationProtocol_ = "";
/**
* <pre>
* The application protocol negotiated for this connection.
* </pre>
*
* <code>string application_protocol = 1;</code>
*/
public java.lang.String getApplicationProtocol() {
java.lang.Object ref = applicationProtocol_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
applicationProtocol_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The application protocol negotiated for this connection.
* </pre>
*
* <code>string application_protocol = 1;</code>
*/
public com.google.protobuf.ByteString
getApplicationProtocolBytes() {
java.lang.Object ref = applicationProtocol_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
applicationProtocol_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The application protocol negotiated for this connection.
* </pre>
*
* <code>string application_protocol = 1;</code>
*/
public Builder setApplicationProtocol(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
applicationProtocol_ = value;
onChanged();
return this;
}
/**
* <pre>
* The application protocol negotiated for this connection.
* </pre>
*
* <code>string application_protocol = 1;</code>
*/
public Builder clearApplicationProtocol() {
applicationProtocol_ = getDefaultInstance().getApplicationProtocol();
onChanged();
return this;
}
/**
* <pre>
* The application protocol negotiated for this connection.
* </pre>
*
* <code>string application_protocol = 1;</code>
*/
public Builder setApplicationProtocolBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
applicationProtocol_ = value;
onChanged();
return this;
}
private java.lang.Object recordProtocol_ = "";
/**
* <pre>
* The record protocol negotiated for this connection.
* </pre>
*
* <code>string record_protocol = 2;</code>
*/
public java.lang.String getRecordProtocol() {
java.lang.Object ref = recordProtocol_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
recordProtocol_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The record protocol negotiated for this connection.
* </pre>
*
* <code>string record_protocol = 2;</code>
*/
public com.google.protobuf.ByteString
getRecordProtocolBytes() {
java.lang.Object ref = recordProtocol_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
recordProtocol_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The record protocol negotiated for this connection.
* </pre>
*
* <code>string record_protocol = 2;</code>
*/
public Builder setRecordProtocol(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
recordProtocol_ = value;
onChanged();
return this;
}
/**
* <pre>
* The record protocol negotiated for this connection.
* </pre>
*
* <code>string record_protocol = 2;</code>
*/
public Builder clearRecordProtocol() {
recordProtocol_ = getDefaultInstance().getRecordProtocol();
onChanged();
return this;
}
/**
* <pre>
* The record protocol negotiated for this connection.
* </pre>
*
* <code>string record_protocol = 2;</code>
*/
public Builder setRecordProtocolBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
recordProtocol_ = value;
onChanged();
return this;
}
private com.google.protobuf.ByteString keyData_ = com.google.protobuf.ByteString.EMPTY;
/**
* <pre>
* Cryptographic key data. The key data may be more than the key length
* required for the record protocol, thus the client of the handshaker
* service needs to truncate the key data into the right key length.
* </pre>
*
* <code>bytes key_data = 3;</code>
*/
public com.google.protobuf.ByteString getKeyData() {
return keyData_;
}
/**
* <pre>
* Cryptographic key data. The key data may be more than the key length
* required for the record protocol, thus the client of the handshaker
* service needs to truncate the key data into the right key length.
* </pre>
*
* <code>bytes key_data = 3;</code>
*/
public Builder setKeyData(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
keyData_ = value;
onChanged();
return this;
}
/**
* <pre>
* Cryptographic key data. The key data may be more than the key length
* required for the record protocol, thus the client of the handshaker
* service needs to truncate the key data into the right key length.
* </pre>
*
* <code>bytes key_data = 3;</code>
*/
public Builder clearKeyData() {
keyData_ = getDefaultInstance().getKeyData();
onChanged();
return this;
}
private io.grpc.alts.internal.Identity peerIdentity_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.Identity, io.grpc.alts.internal.Identity.Builder, io.grpc.alts.internal.IdentityOrBuilder> peerIdentityBuilder_;
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public boolean hasPeerIdentity() {
return peerIdentityBuilder_ != null || peerIdentity_ != null;
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public io.grpc.alts.internal.Identity getPeerIdentity() {
if (peerIdentityBuilder_ == null) {
return peerIdentity_ == null ? io.grpc.alts.internal.Identity.getDefaultInstance() : peerIdentity_;
} else {
return peerIdentityBuilder_.getMessage();
}
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public Builder setPeerIdentity(io.grpc.alts.internal.Identity value) {
if (peerIdentityBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
peerIdentity_ = value;
onChanged();
} else {
peerIdentityBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public Builder setPeerIdentity(
io.grpc.alts.internal.Identity.Builder builderForValue) {
if (peerIdentityBuilder_ == null) {
peerIdentity_ = builderForValue.build();
onChanged();
} else {
peerIdentityBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public Builder mergePeerIdentity(io.grpc.alts.internal.Identity value) {
if (peerIdentityBuilder_ == null) {
if (peerIdentity_ != null) {
peerIdentity_ =
io.grpc.alts.internal.Identity.newBuilder(peerIdentity_).mergeFrom(value).buildPartial();
} else {
peerIdentity_ = value;
}
onChanged();
} else {
peerIdentityBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public Builder clearPeerIdentity() {
if (peerIdentityBuilder_ == null) {
peerIdentity_ = null;
onChanged();
} else {
peerIdentity_ = null;
peerIdentityBuilder_ = null;
}
return this;
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public io.grpc.alts.internal.Identity.Builder getPeerIdentityBuilder() {
onChanged();
return getPeerIdentityFieldBuilder().getBuilder();
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
public io.grpc.alts.internal.IdentityOrBuilder getPeerIdentityOrBuilder() {
if (peerIdentityBuilder_ != null) {
return peerIdentityBuilder_.getMessageOrBuilder();
} else {
return peerIdentity_ == null ?
io.grpc.alts.internal.Identity.getDefaultInstance() : peerIdentity_;
}
}
/**
* <pre>
* The authenticated identity of the peer.
* </pre>
*
* <code>.grpc.gcp.Identity peer_identity = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.Identity, io.grpc.alts.internal.Identity.Builder, io.grpc.alts.internal.IdentityOrBuilder>
getPeerIdentityFieldBuilder() {
if (peerIdentityBuilder_ == null) {
peerIdentityBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.Identity, io.grpc.alts.internal.Identity.Builder, io.grpc.alts.internal.IdentityOrBuilder>(
getPeerIdentity(),
getParentForChildren(),
isClean());
peerIdentity_ = null;
}
return peerIdentityBuilder_;
}
private io.grpc.alts.internal.Identity localIdentity_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.Identity, io.grpc.alts.internal.Identity.Builder, io.grpc.alts.internal.IdentityOrBuilder> localIdentityBuilder_;
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public boolean hasLocalIdentity() {
return localIdentityBuilder_ != null || localIdentity_ != null;
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public io.grpc.alts.internal.Identity getLocalIdentity() {
if (localIdentityBuilder_ == null) {
return localIdentity_ == null ? io.grpc.alts.internal.Identity.getDefaultInstance() : localIdentity_;
} else {
return localIdentityBuilder_.getMessage();
}
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public Builder setLocalIdentity(io.grpc.alts.internal.Identity value) {
if (localIdentityBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
localIdentity_ = value;
onChanged();
} else {
localIdentityBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public Builder setLocalIdentity(
io.grpc.alts.internal.Identity.Builder builderForValue) {
if (localIdentityBuilder_ == null) {
localIdentity_ = builderForValue.build();
onChanged();
} else {
localIdentityBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public Builder mergeLocalIdentity(io.grpc.alts.internal.Identity value) {
if (localIdentityBuilder_ == null) {
if (localIdentity_ != null) {
localIdentity_ =
io.grpc.alts.internal.Identity.newBuilder(localIdentity_).mergeFrom(value).buildPartial();
} else {
localIdentity_ = value;
}
onChanged();
} else {
localIdentityBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public Builder clearLocalIdentity() {
if (localIdentityBuilder_ == null) {
localIdentity_ = null;
onChanged();
} else {
localIdentity_ = null;
localIdentityBuilder_ = null;
}
return this;
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public io.grpc.alts.internal.Identity.Builder getLocalIdentityBuilder() {
onChanged();
return getLocalIdentityFieldBuilder().getBuilder();
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
public io.grpc.alts.internal.IdentityOrBuilder getLocalIdentityOrBuilder() {
if (localIdentityBuilder_ != null) {
return localIdentityBuilder_.getMessageOrBuilder();
} else {
return localIdentity_ == null ?
io.grpc.alts.internal.Identity.getDefaultInstance() : localIdentity_;
}
}
/**
* <pre>
* The local identity used in the handshake.
* </pre>
*
* <code>.grpc.gcp.Identity local_identity = 5;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.Identity, io.grpc.alts.internal.Identity.Builder, io.grpc.alts.internal.IdentityOrBuilder>
getLocalIdentityFieldBuilder() {
if (localIdentityBuilder_ == null) {
localIdentityBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.Identity, io.grpc.alts.internal.Identity.Builder, io.grpc.alts.internal.IdentityOrBuilder>(
getLocalIdentity(),
getParentForChildren(),
isClean());
localIdentity_ = null;
}
return localIdentityBuilder_;
}
private boolean keepChannelOpen_ ;
/**
* <pre>
* Indicate whether the handshaker service client should keep the channel
* between the handshaker service open, e.g., in order to handle
* post-handshake messages in the future.
* </pre>
*
* <code>bool keep_channel_open = 6;</code>
*/
public boolean getKeepChannelOpen() {
return keepChannelOpen_;
}
/**
* <pre>
* Indicate whether the handshaker service client should keep the channel
* between the handshaker service open, e.g., in order to handle
* post-handshake messages in the future.
* </pre>
*
* <code>bool keep_channel_open = 6;</code>
*/
public Builder setKeepChannelOpen(boolean value) {
keepChannelOpen_ = value;
onChanged();
return this;
}
/**
* <pre>
* Indicate whether the handshaker service client should keep the channel
* between the handshaker service open, e.g., in order to handle
* post-handshake messages in the future.
* </pre>
*
* <code>bool keep_channel_open = 6;</code>
*/
public Builder clearKeepChannelOpen() {
keepChannelOpen_ = false;
onChanged();
return this;
}
private io.grpc.alts.internal.RpcProtocolVersions peerRpcVersions_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.RpcProtocolVersions, io.grpc.alts.internal.RpcProtocolVersions.Builder, io.grpc.alts.internal.RpcProtocolVersionsOrBuilder> peerRpcVersionsBuilder_;
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public boolean hasPeerRpcVersions() {
return peerRpcVersionsBuilder_ != null || peerRpcVersions_ != null;
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public io.grpc.alts.internal.RpcProtocolVersions getPeerRpcVersions() {
if (peerRpcVersionsBuilder_ == null) {
return peerRpcVersions_ == null ? io.grpc.alts.internal.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_;
} else {
return peerRpcVersionsBuilder_.getMessage();
}
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public Builder setPeerRpcVersions(io.grpc.alts.internal.RpcProtocolVersions value) {
if (peerRpcVersionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
peerRpcVersions_ = value;
onChanged();
} else {
peerRpcVersionsBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public Builder setPeerRpcVersions(
io.grpc.alts.internal.RpcProtocolVersions.Builder builderForValue) {
if (peerRpcVersionsBuilder_ == null) {
peerRpcVersions_ = builderForValue.build();
onChanged();
} else {
peerRpcVersionsBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public Builder mergePeerRpcVersions(io.grpc.alts.internal.RpcProtocolVersions value) {
if (peerRpcVersionsBuilder_ == null) {
if (peerRpcVersions_ != null) {
peerRpcVersions_ =
io.grpc.alts.internal.RpcProtocolVersions.newBuilder(peerRpcVersions_).mergeFrom(value).buildPartial();
} else {
peerRpcVersions_ = value;
}
onChanged();
} else {
peerRpcVersionsBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public Builder clearPeerRpcVersions() {
if (peerRpcVersionsBuilder_ == null) {
peerRpcVersions_ = null;
onChanged();
} else {
peerRpcVersions_ = null;
peerRpcVersionsBuilder_ = null;
}
return this;
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public io.grpc.alts.internal.RpcProtocolVersions.Builder getPeerRpcVersionsBuilder() {
onChanged();
return getPeerRpcVersionsFieldBuilder().getBuilder();
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
public io.grpc.alts.internal.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder() {
if (peerRpcVersionsBuilder_ != null) {
return peerRpcVersionsBuilder_.getMessageOrBuilder();
} else {
return peerRpcVersions_ == null ?
io.grpc.alts.internal.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_;
}
}
/**
* <pre>
* The RPC protocol versions supported by the peer.
* </pre>
*
* <code>.grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.RpcProtocolVersions, io.grpc.alts.internal.RpcProtocolVersions.Builder, io.grpc.alts.internal.RpcProtocolVersionsOrBuilder>
getPeerRpcVersionsFieldBuilder() {
if (peerRpcVersionsBuilder_ == null) {
peerRpcVersionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.grpc.alts.internal.RpcProtocolVersions, io.grpc.alts.internal.RpcProtocolVersions.Builder, io.grpc.alts.internal.RpcProtocolVersionsOrBuilder>(
getPeerRpcVersions(),
getParentForChildren(),
isClean());
peerRpcVersions_ = null;
}
return peerRpcVersionsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:grpc.gcp.HandshakerResult)
}
// @@protoc_insertion_point(class_scope:grpc.gcp.HandshakerResult)
private static final io.grpc.alts.internal.HandshakerResult DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.grpc.alts.internal.HandshakerResult();
}
public static io.grpc.alts.internal.HandshakerResult getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<HandshakerResult>
PARSER = new com.google.protobuf.AbstractParser<HandshakerResult>() {
@java.lang.Override
public HandshakerResult parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new HandshakerResult(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<HandshakerResult> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<HandshakerResult> getParserForType() {
return PARSER;
}
@java.lang.Override
public io.grpc.alts.internal.HandshakerResult getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| 31.990506
| 178
| 0.645227
|
befcffce2777552108b0b2903833b5efe1e34774
| 12,766
|
package com.mapbox.mapboxsdk.android.testapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.mapbox.mapboxsdk.api.ILatLng;
import com.mapbox.mapboxsdk.geometry.BoundingBox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.Icon;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.overlay.PathOverlay;
import com.mapbox.mapboxsdk.overlay.UserLocationOverlay;
import com.mapbox.mapboxsdk.tileprovider.tilesource.ITileLayer;
import com.mapbox.mapboxsdk.tileprovider.tilesource.MBTilesLayer;
import com.mapbox.mapboxsdk.tileprovider.tilesource.MapboxTileLayer;
import com.mapbox.mapboxsdk.tileprovider.tilesource.TileLayer;
import com.mapbox.mapboxsdk.tileprovider.tilesource.WebSourceTileLayer;
import com.mapbox.mapboxsdk.views.MapView;
import com.mapbox.mapboxsdk.views.util.TilesLoadedListener;
public class MainTestFragment extends Fragment {
private LatLng startingPoint = new LatLng(51f, 0f);
private MapView mv;
private String satellite = "brunosan.map-cyglrrfu";
private String street = "examples.map-i87786ca";
private String terrain = "examples.map-zgrqqx0w";
private final String mbTile = "test.MBTiles";
private String currentLayer = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_maintest, container, false);
mv = (MapView) view.findViewById(R.id.mapview);
// Set Default Map Type
replaceMapView(terrain);
currentLayer = "terrain";
mv.setUserLocationEnabled(true)
.setUserLocationTrackingMode(UserLocationOverlay.TrackingMode.FOLLOW);
// Set a reasonable user location zoom level
mv.setUserLocationRequiredZoom(16);
/*
// Original GeoJSON Test that caus es crash when Hardware Acceleration when enabled in TestApp
mv.loadFromGeoJSONURL("https://gist.githubusercontent.com/tmcw/4a6f5fa40ab9a6b2f163/raw/b1ee1e445225fc0a397e2605feda7da74c36161b/map.geojson");
*/
// Smaller GeoJSON Test
mv.loadFromGeoJSONURL("https://gist.githubusercontent.com/bleege/133920f60eb7a334430f/raw/5392bad4e09015d3995d6153db21869b02f34d27/map.geojson");
Marker m = new Marker(mv, "Edinburgh", "Scotland", new LatLng(55.94629, -3.20777));
m.setIcon(new Icon(getActivity(), Icon.Size.SMALL, "marker-stroked", "FF0000"));
mv.addMarker(m);
m = new Marker(mv, "Stockholm", "Sweden", new LatLng(59.32995, 18.06461));
m.setIcon(new Icon(getActivity(), Icon.Size.MEDIUM, "city", "FFFF00"));
mv.addMarker(m);
m = new Marker(mv, "Prague", "Czech Republic", new LatLng(50.08734, 14.42112));
m.setIcon(new Icon(getActivity(), Icon.Size.LARGE, "land-use", "00FFFF"));
mv.addMarker(m);
m = new Marker(mv, "Athens", "Greece", new LatLng(37.97885, 23.71399));
mv.addMarker(m);
m = new Marker(mv, "Milwaukee", "Wisconsin", new LatLng(43.04506, -87.92217));
m.setIcon(new Icon(getActivity(), Icon.Size.LARGE, "city", "0000FF"));
mv.addMarker(m);
/*
m = new Marker(mv, "Prague2", "Czech Republic", new LatLng(50.0875, 14.42112));
m.setIcon(new Icon(getBaseContext(), Icon.Size.LARGE, "land-use", "00FF00"));
mv.addMarker(m);
*/
// Set Button Listeners
Button satBut = changeButtonTypeface((Button) view.findViewById(R.id.satbut));
satBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!currentLayer.equals("satellite")) {
replaceMapView(satellite);
currentLayer = "satellite";
}
}
});
Button terBut = changeButtonTypeface((Button) view.findViewById(R.id.terbut));
terBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!currentLayer.equals("terrain")) {
replaceMapView(terrain);
currentLayer = "terrain";
}
}
});
Button strBut = changeButtonTypeface((Button) view.findViewById(R.id.strbut));
strBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!currentLayer.equals("street")) {
replaceMapView(street);
currentLayer = "street";
}
}
});
Button mbTileBut = changeButtonTypeface((Button) view.findViewById(R.id.mbTilesBut));
mbTileBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!currentLayer.equals(mbTile)) {
replaceMapView(mbTile);
currentLayer = mbTile;
}
}
});
/*
Button altBut = changeButtonTypeface((Button) view.findViewById(R.id.strAltMap));
altBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent altMapActivity =
new Intent(getActivity(), AlternateMapTestActivity.class);
startActivity(altMapActivity);
}
});
Button pinsButton = changeButtonTypeface((Button) view.findViewById(R.id.markersButton));
pinsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent altMapActivity =
new Intent(getActivity(), MarkersTestActivity.class);
startActivity(altMapActivity);
}
});
*/
Button spinButton = changeButtonTypeface((Button) view.findViewById(R.id.spinButton));
spinButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mv.setMapOrientation(mv.getMapOrientation() + 45f);
}
});
/*
Button selectBut = changeButtonTypeface((Button) view.findViewById(R.id.layerselect));
selectBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
ab.setTitle("Select Layer");
ab.setItems(availableLayers, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int choice) {
replaceMapView(availableLayers[choice]);
}
});
ab.show();
}
});
*/
mv.setOnTilesLoadedListener(new TilesLoadedListener() {
@Override
public boolean onTilesLoaded() {
return false;
}
@Override
public boolean onTilesLoadStarted() {
// TODO Auto-generated method stub
return false;
}
});
mv.setVisibility(View.VISIBLE);
PathOverlay equator = new PathOverlay();
equator.addPoint(0, -89);
equator.addPoint(0, 89);
mv.getOverlays().add(equator);
return view;
}
final String[] availableLayers = {
"OpenStreetMap", "OpenSeaMap", "mapquest", "open-streets-dc.mbtiles", "test.MBTiles"
};
protected void replaceMapView(String layer) {
ITileLayer source;
BoundingBox box;
if (layer.toLowerCase().endsWith("mbtiles")) {
TileLayer mbTileLayer = new MBTilesLayer(getActivity(), layer);
// mv.setTileSource(mbTileLayer);
mv.setTileSource(new ITileLayer[] {
mbTileLayer, new WebSourceTileLayer("mapquest",
"http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png").setName(
"MapQuest Open Aerial")
.setAttribution("Tiles courtesy of MapQuest and OpenStreetMap contributors.")
.setMinimumZoomLevel(1)
.setMaximumZoomLevel(18)
});
box = mbTileLayer.getBoundingBox();
} else {
if (layer.equalsIgnoreCase("OpenStreetMap")) {
source = new WebSourceTileLayer("openstreetmap",
"http://tile.openstreetmap.org/{z}/{x}/{y}.png").setName("OpenStreetMap")
.setAttribution("© OpenStreetMap Contributors")
.setMinimumZoomLevel(1)
.setMaximumZoomLevel(18);
} else if (layer.equalsIgnoreCase("OpenSeaMap")) {
source = new WebSourceTileLayer("openstreetmap",
"http://tile.openstreetmap.org/seamark/{z}/{x}/{y}.png").setName(
"OpenStreetMap")
.setAttribution("© OpenStreetMap Contributors")
.setMinimumZoomLevel(1)
.setMaximumZoomLevel(18);
} else if (layer.equalsIgnoreCase("mapquest")) {
source = new WebSourceTileLayer("mapquest",
"http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png").setName(
"MapQuest Open Aerial")
.setAttribution(
"Tiles courtesy of MapQuest and OpenStreetMap contributors.")
.setMinimumZoomLevel(1)
.setMaximumZoomLevel(18);
} else {
source = new MapboxTileLayer(layer);
}
mv.setTileSource(source);
box = source.getBoundingBox();
}
// mv.setScrollableAreaLimit(mv.getTileProvider().getBoundingBox());
mv.setScrollableAreaLimit(box);
mv.setMinZoomLevel(mv.getTileProvider().getMinimumZoomLevel());
mv.setMaxZoomLevel(mv.getTileProvider().getMaximumZoomLevel());
mv.setCenter(mv.getTileProvider().getCenterCoordinate());
mv.setZoom(0);
Log.d("MainActivity", "zoomToBoundingBox " + box.toString());
// mv.zoomToBoundingBox(box);
}
private void addLine() {
// Configures a line
Paint linePaint = new Paint();
linePaint.setStyle(Paint.Style.STROKE);
linePaint.setColor(Color.BLUE);
linePaint.setStrokeWidth(5);
PathOverlay po = new PathOverlay().setPaint(linePaint);
po.addPoint(startingPoint);
po.addPoint(new LatLng(51.7, 0.3));
po.addPoint(new LatLng(51.2, 0));
// Adds line and marker to the overlay
mv.getOverlays().add(po);
}
private Button changeButtonTypeface(Button button) {
//Typeface tf = Typeface.createFromAsset(this.getAssets(), "fonts/semibold.ttf");
//button.setTypeface(tf);
return button;
}
public LatLng getMapCenter() {
return mv.getCenter();
}
public void setMapCenter(ILatLng center) {
mv.setCenter(center);
}
/**
* Method to show settings in alert dialog
* On pressing Settings button will lauch Settings Options - GPS
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
}
| 40.271293
| 153
| 0.606533
|
b83f8dc108e6a2df8f9b55f7469755fdd4b7aec9
| 1,939
|
package liao.brian.files;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Scanner;
import uw.io.BitInputStream;
import uw.io.BitOutputStream;
public class DataManipulatorText implements DataManipulator {
@Override
public void encode(String inFileName, String outFileName) {
PrintWriter writer = null;
try {
BitInputStream in = new BitInputStream(inFileName);
writer = new PrintWriter(outFileName, "UTF-8");
int a = -1;
int b = -1;
while ((a = in.readBit()) != -1 && (b = in.readBit()) != -1) {
int bits = 10 * a + b;
if (bits == 0) {
writer.write("A");
} else if (bits == 1) {
writer.write("C");
} else if (bits == 10) {
writer.write("G");
} else if (bits == 11) {
writer.write("T");
} else {
throw new IllegalStateException("Missing a bit? Bits recieved:" + bits);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
writer.close();
}
}
@Override
public void decode(String inFileName, String outFileName) {
Scanner fileScanner = null;
try {
BitOutputStream out = new BitOutputStream(new PrintStream(outFileName), false);
fileScanner = new Scanner((new File(inFileName)));
String line = fileScanner.nextLine();
for (Character c : line.toCharArray()) {
if (c.equals('A')) {
out.writeBit(0);
out.writeBit(0);
} else if (c.equals('C')) {
out.writeBit(0);
out.writeBit(1);
} else if (c.equals('G')) {
out.writeBit(1);
out.writeBit(0);
} else if (c.equals('T')) {
out.writeBit(1);
out.writeBit(1);
} else {
throw new IllegalStateException("Incorrect character: use only 'A', 'C', 'G', or 'T.'");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
fileScanner.close();
}
}
}
| 25.853333
| 93
| 0.620939
|
f1caa502bf26796d4b51a50e578f288f57db5025
| 105
|
package services;
import models.Stock;
public interface StoreService {
void save(Stock stock);
}
| 10.5
| 31
| 0.733333
|
0ad268bc511bc93961f36b58e713fd265053a6ee
| 445
|
package kelvin.mite.world;
public class MiteSurfaceConfig {
public enum SurfaceType {
SAND_GRASS,
DIRT_GRASS
}
public final SurfaceType surface;
public final double tree_density;
public final StoneConfiguration stone_config;
public MiteSurfaceConfig(SurfaceType surface, StoneConfiguration stone_config, double tree_density) {
this.surface = surface;
this.tree_density = tree_density;
this.stone_config = stone_config;
}
}
| 23.421053
| 102
| 0.793258
|
17cfc1ebb856e2d08aaef02d1dcd52007684eb95
| 626
|
package com.relationalai;
import java.util.List;
public class ArrowRelation extends Entity {
public String relationId;
public List<Object> table;
public ArrowRelation(String relationId, List<Object> table) {
this.relationId = relationId;
this.table = table;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof ArrowRelation)) {
return false;
}
var that = (ArrowRelation) o;
return this.relationId.equals(that.relationId) && this.table.equals(that.table);
}
}
| 22.357143
| 88
| 0.608626
|
e1d91ea76a98b08bf472a00ce753f2ac97b11d3a
| 2,164
|
/*-
* #%L
* Bobcat
* %%
* Copyright (C) 2019 Cognifide 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.
* #L%
*/
package com.cognifide.qa.bb.appium.webdriver.creators;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cognifide.qa.bb.appium.constants.AppiumConfigKeys;
import com.cognifide.qa.bb.provider.selenium.webdriver.creators.WebDriverCreator;
import com.google.inject.Inject;
import io.appium.java_client.ios.IOSDriver;
/**
* Creates instances of {@link IOSDriver}
*/
public class IosDriverCreator implements WebDriverCreator {
private static final Logger LOG = LoggerFactory.getLogger(IosDriverCreator.class);
private static final String ID = "ios";
@Inject
private Properties properties;
@Override
public WebDriver create(Capabilities capabilities) {
LOG.info("Starting the initialization of '{}' WebDriver instance", ID);
LOG.debug("Initializing WebDriver with following capabilities: {}", capabilities);
return createMobileDriver(capabilities, properties);
}
@Override
public String getId() {
return ID;
}
private WebDriver createMobileDriver(Capabilities capabilities, Properties properties) {
final URL url;
try {
url = new URL(properties.getProperty(AppiumConfigKeys.WEBDRIVER_APPIUM_URL));
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Your Appium URL seems to be malformed", e);
}
return new IOSDriver(url, capabilities);
}
}
| 30.478873
| 90
| 0.749076
|
9b19bd3411b4f81e0631b5c84e8890a32f8fb2c4
| 358
|
package com.robert.jvm.closure;
public class ClosureTest8 {
public static Supplier<Integer> testClosure() {
int i = 1;
return () -> {
return i;
};
}
public interface Supplier<T> {
T get();
}
public static void main(String[] args) {
System.out.println(testClosure().get());
}
}
| 17.047619
| 51
| 0.539106
|
595f3b24c81e9f3b5791f93b5a0a11e1e9790b39
| 12,290
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2009 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.mercurial.remote.ui.clone;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import org.netbeans.modules.remotefs.versioning.api.VCSFileProxySupport;
import org.netbeans.modules.versioning.core.api.VCSFileProxy;
import org.openide.util.NbBundle;
/**
*
*
*/
public class ClonePanel extends javax.swing.JPanel implements ActionListener {
private final VCSFileProxy repository;
/** Creates new form ClonePanel */
public ClonePanel(VCSFileProxy repo, VCSFileProxy to) {
repository = repo;
initComponents();
browseButton.addActionListener(this);
fromTextField.setText(repo.getPath());
toTextField.setText(to.getParentFile().getPath());
toCloneField.setText(to.getName());
}
public VCSFileProxy getTargetDir() {
return VCSFileProxySupport.getResource(repository, toTextField.getText()+"/"+toCloneField.getText());
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
fromLabel = new javax.swing.JLabel();
toLabel = new javax.swing.JLabel();
browseButton = new javax.swing.JButton();
fromTextField = new javax.swing.JTextField();
toNameLabel = new javax.swing.JLabel();
toCloneField = new javax.swing.JTextField();
destinationLabel = new javax.swing.JLabel();
fromLabel.setLabelFor(fromTextField);
org.openide.awt.Mnemonics.setLocalizedText(fromLabel, org.openide.util.NbBundle.getMessage(ClonePanel.class, "ClonePanel.fromLabel.text")); // NOI18N
toLabel.setLabelFor(toTextField);
org.openide.awt.Mnemonics.setLocalizedText(toLabel, org.openide.util.NbBundle.getMessage(ClonePanel.class, "ClonePanel.toLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(browseButton, org.openide.util.NbBundle.getMessage(ClonePanel.class, "ClonePanel.browseButton.text")); // NOI18N
fromTextField.setEditable(false);
toNameLabel.setLabelFor(toCloneField);
org.openide.awt.Mnemonics.setLocalizedText(toNameLabel, org.openide.util.NbBundle.getMessage(ClonePanel.class, "ClonePanel.toName.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(destinationLabel, org.openide.util.NbBundle.getMessage(ClonePanel.class, "destinationLabel.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(destinationLabel)
.addComponent(fromLabel)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(toNameLabel)
.addComponent(toLabel))))
.addGap(94, 94, 94)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(fromTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(toCloneField, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
.addComponent(toTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(browseButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(fromLabel)
.addComponent(fromTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(destinationLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(browseButton)
.addComponent(toTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(toLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(toCloneField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(toNameLabel))
.addGap(31, 31, 31))
);
toTextField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ClonePanel.class, "ACSD_toTextField")); // NOI18N
browseButton.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ClonePanel.class, "ACSD_Browse")); // NOI18N
fromTextField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ClonePanel.class, "ACSD_fromTextField")); // NOI18N
toCloneField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(ClonePanel.class, "ACSD_toCloneField")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == browseButton) {
onBrowseClick();
}
}
private void onBrowseClick() {
VCSFileProxy oldFile = defaultWorkingDirectory();
JFileChooser fileChooser = VCSFileProxySupport.createFileChooser(oldFile);
fileChooser.setDialogTitle(NbBundle.getMessage(ClonePanel.class, "Browse_title")); // NO I18N
fileChooser.setMultiSelectionEnabled(false);
FileFilter[] old = fileChooser.getChoosableFileFilters();
for (int i = 0; i < old.length; i++) {
FileFilter fileFilter = old[i];
fileChooser.removeChoosableFileFilter(fileFilter);
}
fileChooser.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory();
}
@Override
public String getDescription() {
return NbBundle.getMessage(ClonePanel.class, "Folders");// NOI18N
}
});
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.showDialog(this, NbBundle.getMessage(ClonePanel.class, "OK_Button")); // NO I18N
VCSFileProxy f = VCSFileProxySupport.getSelectedFile(fileChooser);
if (f != null) {
toTextField.setText(f.getPath());
}
}
/**
* Returns file to be initally used.
* <ul>
* <li>first is takes text in workTextField
* <li>then recent project folder
* <li>finally <tt>user.home</tt>
* <ul>
*/
private VCSFileProxy defaultWorkingDirectory() {
VCSFileProxy defaultDir = null;
String current = toTextField.getText();
if (current != null && !(current.trim().equals(""))) { // NOI18N
VCSFileProxy currentFile = VCSFileProxySupport.getResource(repository, current);
while (currentFile != null && currentFile.exists() == false) {
currentFile = currentFile.getParentFile();
}
if (currentFile != null) {
if (currentFile.isFile()) {
defaultDir = currentFile.getParentFile();
} else {
defaultDir = currentFile;
}
}
}
//TODO: get last selected project
// if (defaultDir == null) {
// VCSFileProxy projectFolder = ProjectChooser.getProjectsFolder();
// if (projectFolder.exists() && projectFolder.isDirectory()) {
// defaultDir = projectFolder;
// }
//
// }
if (defaultDir == null) {
defaultDir = VCSFileProxySupport.getHome(repository);
}
return defaultDir;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton browseButton;
private javax.swing.JLabel destinationLabel;
private javax.swing.JLabel fromLabel;
private javax.swing.JTextField fromTextField;
private javax.swing.JTextField toCloneField;
private javax.swing.JLabel toLabel;
private javax.swing.JLabel toNameLabel;
final javax.swing.JTextField toTextField = new javax.swing.JTextField();
// End of variables declaration//GEN-END:variables
}
| 49.35743
| 167
| 0.675183
|
384fac3b2d16237f692c8626246231f6ea30cab0
| 2,058
|
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellecteu.catalyst.metadata;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* @author Stephane Nicoll
*/
public class TextCapabilityTests {
@Test
public void mergeValue() {
TextCapability capability = new TextCapability("foo");
capability.setContent("1234");
TextCapability another = new TextCapability("foo");
another.setContent("4567");
capability.merge(another);
assertEquals("foo", capability.getId());
assertEquals(ServiceCapabilityType.TEXT, capability.getType());
assertEquals("4567", capability.getContent());
}
@Test
public void mergeTitle() {
TextCapability capability = new TextCapability("foo", "Foo", "my desc");
capability.merge(new TextCapability("foo", "AnotherFoo", ""));
assertEquals("foo", capability.getId());
assertEquals(ServiceCapabilityType.TEXT, capability.getType());
assertEquals("AnotherFoo", capability.getTitle());
assertEquals("my desc", capability.getDescription());
}
@Test
public void mergeDescription() {
TextCapability capability = new TextCapability("foo", "Foo", "my desc");
capability.merge(new TextCapability("foo", "", "another desc"));
assertEquals("foo", capability.getId());
assertEquals(ServiceCapabilityType.TEXT, capability.getType());
assertEquals("Foo", capability.getTitle());
assertEquals("another desc", capability.getDescription());
}
}
| 33.737705
| 76
| 0.718659
|
d197e7d380f4982d6b57894cba271bfdb0d6e7f3
| 11,341
|
package com.pdsl.transformers;
import com.pdsl.junit.RecognizedBy;
import com.pdsl.logging.AnsiTerminalColorHelper;
import com.pdsl.specifications.FilteredPhrase;
import com.pdsl.specifications.PolymorphicDslTransformationException;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class DefaultPolymorphicDslPhraseFilter
implements PolymorphicDslPhraseFilter {
private static final String BOLD = "\033[1m";
private static final String RESET_ANSI = "\033[0m";
private final Logger logger = LoggerFactory.getLogger(DefaultPolymorphicDslPhraseFilter.class);
private final Constructor<? extends Parser> subgrammarParserConstructor;
private final Constructor<? extends Lexer> subgrammarLexerConstructor;
private final Optional<Class<? extends Parser>> recognizerParser;
private final Optional<Class<? extends Lexer>> recognizerLexer;
private final Method subgrammarActivePhraseRule;
private final Optional<String> syntaxRuleName;
public static String DEFAULT_ALL_RULES_METHOD_NAME = "polymorphicDslAllRules";
public DefaultPolymorphicDslPhraseFilter(Class<? extends Parser> subgrammarParser, Class<? extends Lexer> subgrammarLexer) {
Optional<Method> syntaxRuleOptional1;
try {
this.subgrammarLexerConstructor = subgrammarLexer.getConstructor(CharStream.class);
this.subgrammarParserConstructor = subgrammarParser.getConstructor(TokenStream.class);
this.subgrammarActivePhraseRule = subgrammarParser.getMethod(DEFAULT_ALL_RULES_METHOD_NAME);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
String.format("Trouble creating either the lexer or parser!%nNote the parser MUST Have a rule in the grammar called '%s'", DEFAULT_ALL_RULES_METHOD_NAME), e);
}
recognizerLexer = Optional.empty();
recognizerParser = Optional.empty();
syntaxRuleName = Optional.empty();
}
public DefaultPolymorphicDslPhraseFilter(Class<? extends Parser> subgrammarParser, Class<? extends Lexer> subgrammarLexer, Class<? extends Parser> parserRecognizer, Class<? extends Lexer> lexerRecognizer) {
try {
this.subgrammarLexerConstructor = subgrammarLexer.getConstructor(CharStream.class);
this.subgrammarParserConstructor = subgrammarParser.getConstructor(TokenStream.class);
this.subgrammarActivePhraseRule = subgrammarParser.getMethod(DEFAULT_ALL_RULES_METHOD_NAME);
this.recognizerLexer = Optional.of(lexerRecognizer);
this.recognizerParser = Optional.of(parserRecognizer);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
String.format("Trouble creating either the lexer or parser!%nNote the parser MUST Have a rule in the grammar called '%s'", DEFAULT_ALL_RULES_METHOD_NAME), e);
}
syntaxRuleName = Optional.of(RecognizedBy.DEFAULT_RECOGNIZER_RULE_NAME);
}
public DefaultPolymorphicDslPhraseFilter(Class<? extends Parser> subgrammarParser, Class<? extends Lexer> subgrammarLexer, Class<? extends Parser> parserRecognizer, Class<? extends Lexer> lexerRecognizer, String recognizerRuleName) {
try {
this.subgrammarLexerConstructor = subgrammarLexer.getConstructor(CharStream.class);
this.subgrammarParserConstructor = subgrammarParser.getConstructor(TokenStream.class);
this.subgrammarActivePhraseRule = subgrammarParser.getMethod(DEFAULT_ALL_RULES_METHOD_NAME);
this.recognizerLexer = Optional.of(lexerRecognizer);
this.recognizerParser = Optional.of(parserRecognizer);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
String.format("Trouble creating either the lexer or parser!%nNote the parser MUST Have a rule in the grammar called '%s'", DEFAULT_ALL_RULES_METHOD_NAME), e);
}
syntaxRuleName = Optional.of(recognizerRuleName);
}
@Override
public Optional<List<FilteredPhrase>> filterPhrases(List<InputStream> testContent) {
// Avoid changing the reference of the above variable to the streams we create here
List<InputStream> testContextForfiltering = testContent;
if (recognizerParser.isPresent() && recognizerLexer.isPresent()) {
testContextForfiltering = TestSpecificationHelper.checkGrammarValidity(recognizerParser.get(), recognizerLexer.get(), testContent,
syntaxRuleName.isPresent() ? syntaxRuleName.get() : RecognizedBy.DEFAULT_RECOGNIZER_RULE_NAME);
}
List<FilteredPhrase> filteredPhrases = new ArrayList<>();
int phrasesFilteredOut = 0;
for (InputStream inputStream : testContextForfiltering) {
ByteArrayInputStream bais;
try {
bais = new ByteArrayInputStream(inputStream.readAllBytes());
} catch (IOException e) {
throw new PolymorphicDslTransformationException("Could not read from the stream while filtering phrases!", e);
}
Optional<Parser> parser = subgrammarParserOf(new ByteArrayInputStream(bais.readAllBytes()));
if (parser.isPresent()) {
parser.get().setBuildParseTree(true); // A parse tree creates a child object, causing the tree walker to traverse the rule twice
ParseTree parseTree = subgrammarParseTreeOf(parser.get());
filteredPhrases.add(new FilteredPhrase() {
@Override
public String getPhrase() {
return parseTree.getText();
}
@Override
public Optional<ParseTree> getParseTree() {
return Optional.of(parseTree);
}
});
} else {
filteredPhrases.add(new FilteredPhrase() {
@Override
public String getPhrase() {
return new String(bais.readAllBytes());
}
@Override
public Optional<ParseTree> getParseTree() {
return Optional.empty();
}
});
phrasesFilteredOut++;
}
}
if (filteredPhrases.isEmpty() || filteredPhrases.stream().noneMatch(filteredPhrase -> filteredPhrase.getParseTree().isPresent())) { // Let the user know we couldn't parse
String errorType = phrasesFilteredOut == testContent.size() ? "All phrases were filtered out of a test!" : "A test entirely failed to be parsed!";
StringBuilder errorMessage = new StringBuilder(AnsiTerminalColorHelper.BRIGHT_YELLOW + errorType + RESET_ANSI);
errorMessage.append(BOLD + "\n\tParser Context: " + RESET_ANSI + subgrammarParserConstructor.getName());
String message = errorMessage.toString();
logger.warn(message);
return Optional.empty();
}
return Optional.of(filteredPhrases);
}
private Optional<? extends Lexer> createSublexer(InputStream inputStream) {
try {
// We need to see if the lexer will recognize any of the tokens in the input stream
// However checking this will consume the tokens in the lexer, making it useless for future processing,
// so we create two: one to check if this line is relevant at all and the other to use if it is
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inputStream.transferTo(baos);
CharStream charStream = CharStreams.fromStream(new ByteArrayInputStream(baos.toByteArray()));
Lexer pdslLexer = subgrammarLexerConstructor.newInstance(charStream);
pdslLexer.removeErrorListeners();
PdslErrorListener errorListener = new PdslErrorListener();
pdslLexer.addErrorListener(errorListener);
List<? extends Token> allTokens = pdslLexer.getAllTokens();
if (allTokens.isEmpty()) {
if (logger.isWarnEnabled()) {
logger.warn(String.format("%sFiltering out phrase:%n%s<START>%s%s%s<END>", AnsiTerminalColorHelper.BRIGHT_CYAN, RESET_ANSI, AnsiTerminalColorHelper.BRIGHT_CYAN, baos.toString(), RESET_ANSI));
}
return Optional.empty();
} else if (errorListener.isErrorFound()) { //Stream may have been partially consumed. Only keep if there were no errors
if (logger.isWarnEnabled()) {
logger.warn(String.format("%sA line was partially matched! This may indicate an error in the grammar!", AnsiTerminalColorHelper.BRIGHT_YELLOW));
logger.warn(String.format("The match was:%n\t%s", allTokens));
logger.warn(String.format("%sFiltering out phrase:%n\t%s%s", AnsiTerminalColorHelper.BRIGHT_RED, baos.toString(), RESET_ANSI));
}
return Optional.empty();
} else if (allTokens.get(0).getType() == Token.EOF) { // We know the size of the list is at least 1 from the check above. See if the only token is the end of file
String message = String.format("%sOnly the End of File was left. Treating as though everything has been filtered out of this phrase:%n%s%s", AnsiTerminalColorHelper.YELLOW, pdslLexer.getText(), AnsiTerminalColorHelper.RESET);
logger.warn(message);
return Optional.empty();
}
pdslLexer.reset();
return Optional.of(pdslLexer);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | IOException e) {
throw new PolymorphicDslTransformationException("Could not create lexer from input stream!", e);
}
}
private Optional<Parser> subgrammarParserOf(InputStream inputStream) {
Optional<? extends Lexer> lexer = createSublexer(inputStream);
if (lexer.isEmpty()) {
return Optional.empty();
}
try {
// Create a parser-grammar file
// Convert the grammar file to an actual parser
Parser dslParser = subgrammarParserConstructor.newInstance(new CommonTokenStream(lexer.get()));
return Optional.of(dslParser);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new PolymorphicDslTransformationException("Could not create parser from lexer!", e);
}
}
private ParseTree subgrammarParseTreeOf(Parser parser) {
try {
// Remove error messages. These are provided in check grammar.
parser.removeErrorListeners();
return (ParseTree) subgrammarActivePhraseRule.invoke(parser, null);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new PolymorphicDslTransformationException("Could not make parse tree from phrase!", e);
}
}
}
| 57.862245
| 241
| 0.671369
|
1eafa9ec445d204242f82cfeca642bc1668163bf
| 2,297
|
package com.rakuten.tech.mobile.perf.rewriter.mixins;
import org.gradle.api.logging.Logger;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.MethodNode;
public class MixinMethod {
public static String PREFIX = "com_rakuten_tech_mobile_perf_";
private final Mixin _mixin;
private final MethodNode _mn;
private final Logger _log;
public MixinMethod(Mixin mixin, MethodNode mn, Logger log) {
_mixin = mixin;
_mn = mn;
_log = log;
}
public MethodVisitor rewrite(final String className, ClassVisitor cv, int access, String name,
String desc, String signature, String[] exceptions) {
_log.debug("Mixing method " + className + "." + name + desc);
final String varPrefix = "L" + _mixin.mixinClass;
MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
_mn.accept(new MethodVisitor(Opcodes.ASM5, mv) {
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if (_mixin.mixinClass.equals(owner)) {
owner = className;
if (name.equals(_mn.name)) {
opcode = Opcodes.INVOKESPECIAL;
name = PREFIX + name;
}
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
if (_mixin.mixinClass.equals(owner)) {
owner = className;
}
super.visitFieldInsn(opcode, owner, name, desc);
}
@Override
public void visitLocalVariable(String name, String desc, String signature, Label start,
Label end, int index) {
if ((desc != null) && desc.startsWith(varPrefix)) {
desc = "L" + className + desc.substring(varPrefix.length());
}
if ((signature != null) && signature.startsWith(varPrefix)) {
signature = "L" + className + signature.substring(varPrefix.length());
}
super.visitLocalVariable(name, desc, signature, start, end, index);
}
});
return cv.visitMethod(Opcodes.ACC_PRIVATE, PREFIX + name, desc, signature, exceptions);
}
}
| 32.814286
| 100
| 0.65825
|
6a996eb9a685b398c06f905d56a72104755f1cd0
| 396
|
import org.junit.Test;
public class LauncherTest {
@Test
public void testSomeLibraryMethod() {
TomcatLauncher classUnderTest = new TomcatLauncher();
try {
classUnderTest.launchTomcat(8080);
} catch (Exception e) {
throw new RuntimeException(e);
}
//assertTrue("should return 'true'", classUnderTest.someMethod());
}
}
| 24.75
| 74
| 0.616162
|
5b3aa5dd646f2389a80d686f6b9bd88f55d3d60d
| 3,932
|
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author dongzonglei
* @description
* @date 2020/12/1 上午10:59
*/
public class Test1 {
public static void main(String[] args) {
// OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(120, TimeUnit.SECONDS).build();
// Request.Builder reqBuilder = new Request.Builder();
// FormBody.Builder formBodyBuilder = new FormBody.Builder();
// formBodyBuilder.add("aoData", "[{\"name\":\"sEcho\",\"value\":2},{\"name\":\"iColumns\",\"value\":7},{\"name\":\"sColumns\",\"value\":\",,,,,,\"},{\"name\":\"iDisplayStart\",\"value\":0},{\"name\":\"iDisplayLength\",\"value\":10},{\"name\":\"mDataProp_0\",\"value\":0},{\"name\":\"bSortable_0\",\"value\":false},{\"name\":\"mDataProp_1\",\"value\":1},{\"name\":\"bSortable_1\",\"value\":false},{\"name\":\"mDataProp_2\",\"value\":\"deptNo\"},{\"name\":\"bSortable_2\",\"value\":true},{\"name\":\"mDataProp_3\",\"value\":\"deptName\"},{\"name\":\"bSortable_3\",\"value\":true},{\"name\":\"mDataProp_4\",\"value\":\"sellerNo\"},{\"name\":\"bSortable_4\",\"value\":true},{\"name\":\"mDataProp_5\",\"value\":\"sellerName\"},{\"name\":\"bSortable_5\",\"value\":true},{\"name\":\"mDataProp_6\",\"value\":\"statusStr\"},{\"name\":\"bSortable_6\",\"value\":true},{\"name\":\"iSortCol_0\",\"value\":2},{\"name\":\"sSortDir_0\",\"value\":\"desc\"},{\"name\":\"iSortingCols\",\"value\":1}]");
// reqBuilder.url("https://b.jclps.com/dept/queryDeptList.do?rand=0.0934128687415825");
// Map<String, String> headMap = new HashMap<>();
// headMap.put("cookie", "thor=A7D8FFE6962AEFE2B8674D9752656F0E805064301335FA7E838829760F5134531E5DE221841075B4EC94972A33DF3FF23AF164965D2076DBDC920F615E4E691ABDFDF50191CB9934D39323A680E69DE2477BC88B9A5FB73140DA47EE1AAA4A4344A4C034C135FFA4DC725479C18D612DD6CD77C5EB0E30960AA2AE9D43B6F38FA7DD7437746EFA98A0243C665023484D; pin=dzllikelsw; unick=dzllikelsw");
// headMap.put(":authority", "b.jclps.com");
// headMap.put("Accept", "application/json, text/javascript, */*; q=0.01");
// reqBuilder.headers(Headers.of(headMap));
// Request request = reqBuilder.post(formBodyBuilder.build()).build();
// Response response;
// try {
// response = client.newCall(request).execute();
// System.out.println(new String(response.body().bytes(), "utf-8"));
// } catch (IOException e) {
// e.printStackTrace();
// }
OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(120, TimeUnit.SECONDS).build();
Request.Builder reqBuilder = new Request.Builder();
FormBody.Builder formBodyBuilder = new FormBody.Builder();
reqBuilder.url("http://b.jclps.com/monitor/viewKey/test");
Map<String, String> headMap = new HashMap<>();
headMap.put("cookie", "thor=A7D8FFE6962AEFE2B8674D9752656F0EE7BFFB59DB4ABBDD2C04E269FCC16FE0C64AF3B9D090D7E3553807B64F3C398BE6C178E1FA61522AEC642D25ADA6BBBBCE7AD87C54A4C918A4CBEFF93906420C47ACCB778D439D9FE5317CBB9E5D9B8F0F0DFB9FCC4C5E570E9A3145E09D6A8503D1BCCD1ED14C799A25B54377226EC93ACE7889549F3FD2F8C8A35D12238609; pin=dzllikelsw; unick=dzllikelsw");
headMap.put(":authority", "b.jclps.com");
headMap.put("Accept", "application/json, text/javascript, */*; q=0.01");
reqBuilder.headers(Headers.of(headMap));
Request request = reqBuilder.post(formBodyBuilder.build()).build();
Response response;
try {
response = client.newCall(request).execute();
System.out.println(new String(response.body().bytes(), "UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 66.644068
| 991
| 0.668616
|
33cebc934acaf7b4d5ff8d9d020d83c5713cee2e
| 654
|
package com.byd.admin.modules.masterdata.service;
import java.util.List;
import java.util.Map;
import com.byd.utils.PageUtils;
/**
* 品质检验标准
* @author thw
* @email
* @date 2019-09-03 15:12:08
*/
public interface TestStandardService{
List<Map<String,Object>> getQmsTestStandard(Map<String,Object> params);
public PageUtils getQmsTestStandardListByPage(Map<String, Object> params);
public int insertQmsTestStandard(Map<String, Object> params);
public Map<String, Object> selectById(Map<String, Object> params);
public int updateQmsTestStandard(Map<String, Object> params);
public int delQmsTestStandard(Map<String, Object> params);
}
| 25.153846
| 75
| 0.762997
|
0584f0dc8dc0fdc1390a1325f9a00ffe75b2d09b
| 2,496
|
package org.monet.core.model;
import net.minidev.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.monet.core.serialization.*;
import java.io.*;
/**
* Represents the monetesis block.
*/
public class monetesisBlock {
/**
* Loads the monetesis block from the default project resource.
*
* @param monetesisBlockInfo The monetesis block information.
* @param context The deserialization context to use.
* @return The monetesis block.
*/
public static Block fromResource(final monetesisBlockInfo monetesisBlockInfo, final DeserializationContext context) {
try (final InputStream fin = monetesisBlock.class.getClassLoader().getResourceAsStream(monetesisBlockInfo.getDataFileName())) {
final byte[] buffer = IOUtils.toByteArray(fin);
return fromBlobObject(monetesisBlockInfo, buffer, context);
} catch (final IOException e) {
throw new IllegalStateException("unable to parse monetesis block stream");
}
}
/**
* Loads the monetesis block from a json object.
*
* @param monetesisBlockInfo The monetesis block information.
* @param jsonObject The json object.
* @param context The deserialization context to use.
* @return The monetesis block.
*/
public static Block fromJsonObject(final monetesisBlockInfo monetesisBlockInfo, final JSONObject jsonObject, final DeserializationContext context) {
final Deserializer deserializer = new JsonDeserializer(jsonObject, context);
return deserialize(monetesisBlockInfo, deserializer);
}
/**
* Loads the monetesis block from binary data.
*
* @param monetesisBlockInfo The monetesis block information.
* @param buffer The binary data.
* @param context The deserialization context to use.
* @return The monetesis block.
*/
public static Block fromBlobObject(final monetesisBlockInfo monetesisBlockInfo, final byte[] buffer, final DeserializationContext context) {
final Deserializer deserializer = new BinaryDeserializer(buffer, context);
return deserialize(monetesisBlockInfo, deserializer);
}
private static Block deserialize(final monetesisBlockInfo monetesisBlockInfo, final Deserializer deserializer) {
if (BlockTypes.monetESIS != deserializer.readInt("type")) {
throw new IllegalArgumentException("deserializer does not have correct type set");
}
final Block block = new Block(BlockTypes.monetESIS, VerifiableEntity.DeserializationOptions.VERIFIABLE, deserializer);
block.setGenerationHash(monetesisBlockInfo.getGenerationHash());
return block;
}
}
| 38.4
| 149
| 0.778045
|
84c8fc689b7ba983937deaa98a1336da12462e92
| 830
|
package com.edge.xshtsk.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.edge.xshtsk.entity.ERP_Xshtsk;
import com.edge.xshtsk.entity.ERP_Xshtsk_QueryVo;
public interface XshtskDao {
// 分页展现销售合同收款
public List<ERP_Xshtsk> xshtskList(ERP_Xshtsk_QueryVo vo);
// 查询销售合同收款总记录
public Integer xshtskCount(ERP_Xshtsk_QueryVo vo);
// 新增销售合同收款
public void saveXshtsk(ERP_Xshtsk xshtsk);
// 获取刚新增的销售合同收款主键
public Integer maxXshtdm();
// 根据Id获得销售合同收款对象
public ERP_Xshtsk queryXshtskById(@Param("xshtskdm") Integer xshtskdm);
// 编辑销售合同收款
public void editXshtsk(ERP_Xshtsk xshtsk);
// 计算某一个销售合同下的所有实际收款金额
public Double querySumSjskje(@Param("xsht") Integer xsht);
// 查询当前销售合同下所有的累计开票金额
public Double querySumLjkpje(@Param("xsht") Integer xsht);
}
| 23.055556
| 73
| 0.748193
|
266b28024687cb9b9913afedec61988aa1e28040
| 14,062
|
package org.oskari.control.mvt;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import fi.nls.oskari.control.feature.AbstractWFSFeaturesHandler;
import fi.nls.oskari.control.view.modifier.bundle.BundleHandler;
import fi.nls.oskari.control.view.modifier.bundle.MapfullHandler;
import fi.nls.oskari.view.modifier.ViewModifierManager;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.oskari.service.mvt.SimpleFeaturesMVTEncoder;
import org.oskari.service.mvt.TileCoord;
import org.oskari.service.mvt.WFSTileGrid;
import org.oskari.service.user.UserLayerService;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.Point;
import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.cache.CacheManager;
import fi.nls.oskari.cache.ComputeOnceCache;
import fi.nls.oskari.control.ActionCommonException;
import fi.nls.oskari.control.ActionConstants;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.ActionParamsException;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.util.IOHelper;
import fi.nls.oskari.util.ResponseHelper;
import org.oskari.service.mvt.WFSTileGridProperties;
@OskariActionRoute("GetWFSVectorTile")
public class GetWFSVectorTileHandler extends AbstractWFSFeaturesHandler {
protected static final String MVT_CONTENT_TYPE = "application/vnd.mapbox-vector-tile";
protected static final String PARAM_Z = "z";
protected static final String PARAM_X = "x";
protected static final String PARAM_Y = "y";
// Resolution (metres per px) we are aiming for with the WFS requests
// This value is used to find the zoom level that is closest to the resolution specified here
// For ETRS-TME35FIN TileGrid this translates to z=8
private static final int TARGET_ZOOM_LEVEL_RESOLUTION = 8192 / 256;
private static final int DEFAULT_CACHE_ZOOM_LEVEL = 8;
private static final int MIN_ZOOM_OVER_CACHE_ZOOM = 1;
private static final Map<String, WFSTileGrid> KNOWN_TILE_GRIDS;
static {
KNOWN_TILE_GRIDS = new HashMap<>();
KNOWN_TILE_GRIDS.put("EPSG:3067", new WFSTileGrid(new double[] { -548576, 6291456, -548576 + (8192*256), 6291456 + (8192*256) }, 15));
KNOWN_TILE_GRIDS.put("EPSG:3857", new WFSTileGrid(new double[] { -20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892 }, 18));
}
private static final int TILE_EXTENT = 4096;
private static final int TILE_BUFFER = 256;
private static final int TILE_BUFFER_POINT = 1024;
private static final int CACHE_LIMIT = 256;
private static final long CACHE_EXPIRATION = TimeUnit.MINUTES.toMillis(5);
private ComputeOnceCache<byte[]> tileCache;
private WFSTileGridProperties tileGridProperties;
private Map<String, Integer> cacheZLevels;
@Override
public void init() {
super.init();
tileCache = CacheManager.getCache(getClass().getName(),
() -> new ComputeOnceCache<>(CACHE_LIMIT, CACHE_EXPIRATION));
tileGridProperties = new WFSTileGridProperties();
cacheZLevels = new HashMap<>();
final Map<String, BundleHandler> handlers = ViewModifierManager.getModifiersOfType(BundleHandler.class);
MapfullHandler mapfullHandler = (MapfullHandler)handlers.get("mapfull");
WFSVectorLayerPluginViewModifier pluginHandler = new WFSVectorLayerPluginViewModifier();
mapfullHandler.registerPluginHandler(WFSVectorLayerPluginViewModifier.PLUGIN_NAME, pluginHandler);
Map<String, WFSTileGrid> propTileGrids = tileGridProperties.getTileGridMap();
KNOWN_TILE_GRIDS.entrySet().stream().forEach(set -> setGridToModifiers(pluginHandler, set.getKey(), set.getValue()));
propTileGrids.entrySet().stream().forEach(set -> setGridToModifiers(pluginHandler, set.getKey(), set.getValue()));
}
@Override
public void handleAction(ActionParameters params) throws ActionException {
final String id = params.getRequiredParam(ActionConstants.PARAM_ID);
final String srs = params.getRequiredParam(ActionConstants.PARAM_SRS);
final int z = params.getRequiredParamInt(PARAM_Z);
final int x = params.getRequiredParamInt(PARAM_X);
final int y = params.getRequiredParamInt(PARAM_Y);
final Optional<UserLayerService> contentProcessor = getUserContentProsessor(id);
final OskariLayer layer = findLayer(id, params.getUser(), contentProcessor);
final WFSTileGrid gridFromProps = tileGridProperties.getTileGrid(srs.toUpperCase());
final WFSTileGrid grid = gridFromProps != null ? gridFromProps : KNOWN_TILE_GRIDS.get(srs.toUpperCase());
final int targetZ = cacheZLevels.getOrDefault(srs, DEFAULT_CACHE_ZOOM_LEVEL);
final int minZoom = targetZ - MIN_ZOOM_OVER_CACHE_ZOOM;
validateTile(grid, z, x, y, minZoom);
validateScaleDenominator(layer, grid, z);
final CoordinateReferenceSystem crs;
try {
crs = CRS.decode(srs, true);
} catch (Exception e) {
throw new ActionParamsException("Invalid srs!");
}
final String cacheKey = getCacheKey(id, srs, z, x, y);
final byte[] resp;
try {
if (contentProcessor.isPresent() && contentProcessor.get().isUserContentLayer(id)) {
// Don't cache user content tiles
resp = createTile(id, layer, crs, grid, targetZ, z, x, y, contentProcessor);
} else {
resp = tileCache.get(cacheKey, __ -> createTile(id, layer, crs, grid, targetZ, z, x, y, contentProcessor));
}
} catch (Exception e) {
throw new ActionCommonException(e.getMessage(), e);
}
params.getResponse().addHeader("Access-Control-Allow-Origin", "*");
params.getResponse().addHeader("Content-Encoding", "gzip");
ResponseHelper.writeResponse(params, 200, MVT_CONTENT_TYPE, resp);
}
private void setGridToModifiers (WFSVectorLayerPluginViewModifier handler, String srsName, WFSTileGrid grid) {
int z = grid.getZForResolution(TARGET_ZOOM_LEVEL_RESOLUTION, 0);
cacheZLevels.put(srsName, z);
handler.setMinZoomLevelForSRS(srsName, z - MIN_ZOOM_OVER_CACHE_ZOOM);
handler.setTileGridForSRS(srsName, grid);
}
private void validateTile(WFSTileGrid grid, int z, int x, int y, int minZoom)
throws ActionParamsException {
if (grid == null) {
throw new ActionParamsException("Unknown srs");
}
if (z < 0) {
throw new ActionParamsException("z must be non-negative");
}
if (x < 0) {
throw new ActionParamsException("x must be non-negative");
}
if (y < 0) {
throw new ActionParamsException("y must be non-negative");
}
if (z > grid.getMaxZoom()) {
throw new ActionParamsException("z must be <= " + grid.getMaxZoom());
}
if (z < minZoom) {
// we always request features with cacheZLevel and anything below minZoom will trigger too many requests to services
throw new ActionParamsException("z must be >= " + minZoom);
}
int matrixWidthHeight = WFSTileGrid.getMatrixSize(z);
if (x >= matrixWidthHeight) {
throw new ActionParamsException("x must be < " + matrixWidthHeight + " (z = " + z + ")");
}
if (y >= matrixWidthHeight) {
throw new ActionParamsException("y must be < " + matrixWidthHeight + " (z = " + z + ")");
}
}
private void validateScaleDenominator(OskariLayer layer, WFSTileGrid grid, int z)
throws ActionParamsException {
double scaleDenominator = getScaleDenominator(grid, z);
if (layer.getMinScale() != null && layer.getMinScale() != -1) {
if (scaleDenominator > layer.getMinScale()) {
// Bigger denominator <=> Smaller scale
throw new ActionParamsException("z too low for layer");
}
}
if (layer.getMaxScale() != null && layer.getMaxScale() != -1) {
if (scaleDenominator < layer.getMaxScale()) {
// Smaller denominator <=> Bigger scale
throw new ActionParamsException("z too high for layer");
}
}
}
private double getScaleDenominator(WFSTileGrid grid, int z) {
double resolution = grid.getResolutionForZ(z);
return getScaleDenominator(resolution);
}
private double getScaleDenominator(double resolution) {
return resolution * 1000 / 0.28; // OGC WMTS 0.28 mm/px
}
private String getCacheKey(String id, String srs, int z, int x, int y) {
return "WFS_" + id + "_" + srs + "_" + z + "_" + x + "_" + y;
}
/**
* Creates the actual MVT tile
* @return an MVT tile as a GZipped byte array
* @throws ActionException
*/
private byte[] createTile(String id, OskariLayer layer, CoordinateReferenceSystem crs,
WFSTileGrid grid, int targetZ, int z, int x, int y,
Optional<UserLayerService> contentProcessor) {
List<TileCoord> tilesToLoad = getTilesToLoad(targetZ, z, x, y);
DefaultFeatureCollection sfc = new DefaultFeatureCollection();
for (TileCoord tile : tilesToLoad) {
SimpleFeatureCollection tileFeatures = getFeatures(id, layer, crs, grid, tile, contentProcessor);
sfc.addAll(tileFeatures);
}
String mvtLayer = layer.getName();
double[] bbox = grid.getTileExtent(new TileCoord(z, x, y));
int extent = TILE_EXTENT;
int buffer = isOnlyPointFeatures(sfc) ? TILE_BUFFER_POINT : TILE_BUFFER;
byte[] encoded = SimpleFeaturesMVTEncoder.encodeToByteArray(sfc, mvtLayer, bbox, extent, buffer);
try {
return IOHelper.gzip(encoded).toByteArray();
} catch (IOException e) {
throw new ServiceRuntimeException("Unexpected IOException occured");
}
}
protected static List<TileCoord> getTilesToLoad(int targetZ, int z, int x, int y) {
int x1;
int y1;
int x2;
int y2;
// Always load tiles at zoom level targetZ so that we don't cache same features on multiple zoom levels
// Also we can reduce the amount of requests we make to the background services, for example for
// high zoom levels we can send only one request and use the cached FeatureCollection for multiple tiles
int dz = z - targetZ;
if (dz == 0) {
// this is the sweet spot zoom level wise
// Load the target tile and the tiles next to (around) it (buffer)
x1 = x - 1;
y1 = y - 1;
x2 = x + 1;
y2 = y + 1;
} else if (dz < 0) {
// Calculate all tiles inside our target tile
int d = (int) Math.pow(2, -dz);
x1 = x * d;
y1 = y * d;
x2 = (x+1) * d;
y2 = (y+1) * d;
// And include tiles around them (buffer)
x1--;
y1--;
} else {
// Calculate the tile (of lower zoom level) which contains the target tile
int div = (int) Math.pow(2, dz);
x1 = x / div;
y1 = y / div;
// And include tiles around them (buffer)
x2 = x1 + 1;
y2 = y1 + 1;
x1--;
y1--;
}
int tileZ = targetZ;
List<TileCoord> wfsTiles = new ArrayList<>();
for (int tileX = x1; tileX <= x2; tileX++) {
for (int tileY = y1; tileY <= y2; tileY++) {
wfsTiles.add(new TileCoord(tileZ, tileX, tileY));
}
}
return wfsTiles;
}
private SimpleFeatureCollection getFeatures(String id, OskariLayer layer,
CoordinateReferenceSystem crs, WFSTileGrid grid, TileCoord tile,
Optional<UserLayerService> processor) {
double[] box = grid.getTileExtent(tile);
Envelope envelope = new Envelope(box[0], box[2], box[1], box[3]);
ReferencedEnvelope bbox = new ReferencedEnvelope(envelope, crs);
return featureClient.getFeatures(id, layer, bbox, crs, processor);
}
private boolean isOnlyPointFeatures(SimpleFeatureCollection sfc) {
SimpleFeatureType sft = sfc.getSchema();
if (sft == null) {
return isOnlyPointFeaturesIterate(sfc);
}
GeometryDescriptor geomDesc = sft.getGeometryDescriptor();
if (geomDesc == null) {
return isOnlyPointFeaturesIterate(sfc);
}
GeometryType geomType = geomDesc.getType();
if (geomType == null) {
return isOnlyPointFeaturesIterate(sfc);
}
Class<?> binding = geomType.getBinding();
if (binding == null) {
return isOnlyPointFeaturesIterate(sfc);
}
return binding == Point.class || binding == MultiPoint.class;
}
private boolean isOnlyPointFeaturesIterate(SimpleFeatureCollection sfc) {
SimpleFeatureIterator it = sfc.features();
while (it.hasNext()) {
Geometry g = (Geometry) it.next().getDefaultGeometry();
if (g == null || g instanceof Point || g instanceof MultiPoint) {
continue;
}
return false;
}
return true;
}
}
| 43.134969
| 154
| 0.654174
|
f6708899252771a872b3c7496282bbfb749aa801
| 13,608
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
/**
* <code>Base64</code> provides Base64 encoding/decoding of strings and streams.
*/
public class Base64 {
// charset used for base64 encoded data (7-bit ASCII)
private static final String CHARSET = "US-ASCII";
// encoding table (the 64 valid base64 characters)
private static final char[] BASE64CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
// decoding table (used to lookup original 6-bit with base64 character
// as table index)
private static final byte[] DECODETABLE = new byte[128];
static {
// initialize decoding table
for (int i = 0; i < DECODETABLE.length; i++) {
DECODETABLE[i] = 0x7f;
}
// build decoding table
for (int i = 0; i < BASE64CHARS.length; i++) {
DECODETABLE[BASE64CHARS[i]] = (byte) i;
}
}
// pad character
private static final char BASE64PAD = '=';
/**
* empty private constructor
*/
private Base64() {
}
/**
* Base64-decodes or -encodes (see {@link #decodeOrEncode(String)}
* all the given arguments and prints the results on separate lines
* in standard output.
*
* @since Apache Jackrabbit 2.3
* @param args command line arguments to be decoded or encoded
*/
public static void main(String[] args) {
for (String arg : args) {
System.out.println(decodeOrEncode(arg));
}
}
/**
* Base64-decodes or -encodes the given string, depending on whether
* or not it contains a "{base64}" prefix. If the string gets encoded,
* the "{base64}" prefix is added to it.
*
* @since Apache Jackrabbit 2.3
* @param data string to be decoded or encoded
* @return decoded or encoded string
*/
public static String decodeOrEncode(String data) {
if (data.startsWith("{base64}")) {
return decode(data.substring("{base64}".length()));
} else {
return "{base64}" + encode(data);
}
}
/**
* Decodes a base64-encoded string marked by a "{base64}" prefix.
* If the prefix is not found, then the string is returned as-is.
* If the given string is <code>null</code>, then <code>null</code>
* is returned.
*
* @since Apache Jackrabbit 2.3
* @param data string to be decoded, can be <code>null</code>
* @return the given string, possibly decoded
*/
public static String decodeIfEncoded(String data) {
if (data != null && data.startsWith("{base64}")) {
return decode(data.substring("{base64}".length()));
} else {
return data;
}
}
/**
* Calculates the size (i.e. number of bytes) of the base64 encoded output
* given the length (i.e. number of bytes) of the data to be encoded.
*
* @param dataLength length (i.e. number of bytes) of the data to be encoded
* @return size (i.e. number of bytes) of the base64 encoded output
*/
public static long calcEncodedLength(long dataLength) {
long encLen = dataLength * 4 / 3;
encLen += (encLen + 4) % 4;
return encLen;
}
/**
* Pessimistically guesses the size (i.e. number of bytes) of the decoded
* output given the length (i.e. number of bytes) of the base64 encoded
* data.
*
* @param encLength length (i.e. number of bytes) of the base64 encoded data
* @return size (i.e. number of bytes) of the decoded output
*/
public static long guessDecodedLength(long encLength) {
long decLen = encLength * 3 / 4;
return decLen + 3;
}
/**
* Outputs base64 representation of the specified stream data to a
* <code>Writer</code>.
*
* @param in stream data to be encoded
* @param writer writer to output the encoded data
* @throws java.io.IOException if an i/o error occurs
*/
public static void encode(InputStream in, Writer writer)
throws IOException {
// encode stream data in chunks;
// chunksize must be a multiple of 3 in order
// to avoid padding within output
byte[] buffer = new byte[9 * 1024];
int read;
while ((read = in.read(buffer)) > 0) {
encode(buffer, 0, read, writer);
}
}
/**
* Outputs base64 representation of the specified stream data to an
* <code>OutputStream</code>.
*
* @param in stream data to be encoded
* @param out stream where the encoded data should be written to
* @throws java.io.IOException if an i/o error occurs
*/
public static void encode(InputStream in, OutputStream out)
throws IOException {
Writer writer = new BufferedWriter(new OutputStreamWriter(out, CHARSET));
try {
encode(in, writer);
} finally {
try {
writer.flush();
} catch (IOException ignore) {
}
}
}
/**
* Outputs base64 representation of the specified data to a
* <code>Writer</code>.
*
* @param data data to be encoded
* @param off offset within data at which to start encoding
* @param len length of data to encode
* @param writer writer to output the encoded data
* @throws java.io.IOException if an i/o error occurs
*/
public static void encode(byte[] data, int off, int len, Writer writer)
throws IOException {
if (len == 0) {
return;
}
if (len < 0 || off >= data.length
|| len + off > data.length) {
throw new IllegalArgumentException();
}
char[] enc = new char[4];
while (len >= 3) {
int i = ((data[off] & 0xff) << 16)
+ ((data[off + 1] & 0xff) << 8)
+ (data[off + 2] & 0xff);
enc[0] = BASE64CHARS[i >> 18];
enc[1] = BASE64CHARS[(i >> 12) & 0x3f];
enc[2] = BASE64CHARS[(i >> 6) & 0x3f];
enc[3] = BASE64CHARS[i & 0x3f];
writer.write(enc, 0, 4);
off += 3;
len -= 3;
}
// add padding if necessary
if (len == 1) {
int i = data[off] & 0xff;
enc[0] = BASE64CHARS[i >> 2];
enc[1] = BASE64CHARS[(i << 4) & 0x3f];
enc[2] = BASE64PAD;
enc[3] = BASE64PAD;
writer.write(enc, 0, 4);
} else if (len == 2) {
int i = ((data[off] & 0xff) << 8) + (data[off + 1] & 0xff);
enc[0] = BASE64CHARS[i >> 10];
enc[1] = BASE64CHARS[(i >> 4) & 0x3f];
enc[2] = BASE64CHARS[(i << 2) & 0x3f];
enc[3] = BASE64PAD;
writer.write(enc, 0, 4);
}
}
/**
* Returns the base64 representation of UTF-8 encoded string.
*
* @since Apache Jackrabbit 2.3
* @param data the string to be encoded
* @return base64-encoding of the string
*/
public static String encode(String data) {
try {
StringWriter buffer = new StringWriter();
byte[] b = data.getBytes(StandardCharsets.UTF_8);
encode(b, 0, b.length, buffer);
return buffer.toString();
} catch (IOException e) { // should never happen
throw new RuntimeException(
"Unable to encode base64 data: " + data, e);
}
}
/**
* Decodes a base64-encoded string using the UTF-8 character encoding.
* The given string is returned as-is if it doesn't contain a valid
* base64 encoding.
*
* @since Apache Jackrabbit 2.3
* @param data the base64-encoded data to be decoded
* @return decoded string
*/
public static String decode(String data) {
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
decode(data, buffer);
return new String(buffer.toByteArray(), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
return data;
} catch (IOException e) { // should never happen
throw new RuntimeException(
"Unable to decode base64 data: " + data, e);
}
}
/**
* Decode base64 encoded data.
*
* @param reader reader for the base64 encoded data to be decoded
* @param out stream where the decoded data should be written to
* @throws java.io.IOException if an i/o error occurs
*/
public static void decode(Reader reader, OutputStream out)
throws IOException {
char[] chunk = new char[8192];
int read;
while ((read = reader.read(chunk)) > -1) {
decode(chunk, 0, read, out);
}
}
/**
* Decode base64 encoded data. The data read from the inputstream is
* assumed to be of charset "US-ASCII".
*
* @param in inputstream of the base64 encoded data to be decoded
* @param out stream where the decoded data should be written to
* @throws java.io.IOException if an i/o error occurs
*/
public static void decode(InputStream in, OutputStream out)
throws IOException {
decode(new InputStreamReader(in, CHARSET), out);
}
/**
* Decode base64 encoded data.
*
* @param data the base64 encoded data to be decoded
* @param out stream where the decoded data should be written to
* @throws java.io.IOException if an i/o error occurs
*/
public static void decode(String data, OutputStream out)
throws IOException {
char[] chars = data.toCharArray();
decode(chars, 0, chars.length, out);
}
/**
* Decode base64 encoded data.
*
* @param chars the base64 encoded data to be decoded
* @param out stream where the decoded data should be written to
* @throws java.io.IOException if an i/o error occurs
*/
public static void decode(char[] chars, OutputStream out)
throws IOException {
decode(chars, 0, chars.length, out);
}
/**
* Decode base64 encoded data.
*
* @param chars the base64 encoded data to be decoded
* @param off offset within data at which to start decoding
* @param len length of data to decode
* @param out stream where the decoded data should be written to
* @throws java.io.IOException if an i/o error occurs
*/
public static void decode(char[] chars, int off, int len, OutputStream out)
throws IOException {
if (len == 0) {
return;
}
if (len < 0 || off >= chars.length
|| len + off > chars.length) {
throw new IllegalArgumentException();
}
char[] chunk = new char[4];
byte[] dec = new byte[3];
int posChunk = 0;
// decode in chunks of 4 characters
for (int i = off; i < (off + len); i++) {
char c = chars[i];
if (c < DECODETABLE.length && DECODETABLE[c] != 0x7f
|| c == BASE64PAD) {
chunk[posChunk++] = c;
if (posChunk == chunk.length) {
int b0 = DECODETABLE[chunk[0]];
int b1 = DECODETABLE[chunk[1]];
int b2 = DECODETABLE[chunk[2]];
int b3 = DECODETABLE[chunk[3]];
if (chunk[3] == BASE64PAD && chunk[2] == BASE64PAD) {
dec[0] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
out.write(dec, 0, 1);
} else if (chunk[3] == BASE64PAD) {
dec[0] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
dec[1] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
out.write(dec, 0, 2);
} else {
dec[0] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
dec[1] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
dec[2] = (byte) (b2 << 6 & 0xc0 | b3 & 0x3f);
out.write(dec, 0, 3);
}
posChunk = 0;
}
} else if (!Character.isWhitespace(c)) {
throw new IllegalArgumentException("specified data is not base64 encoded");
}
}
}
}
| 35.716535
| 93
| 0.565991
|
50ca9c6243f03c18a26e16b437fe8b2b26db027c
| 137
|
package se.citerus.cqrs.bookstore.command;
/**
* Marker interface for command handler classes.
*/
public interface CommandHandler {
}
| 17.125
| 48
| 0.759124
|
7dd090a88de49091acbd35910b5de22d08ac03cb
| 4,313
|
/****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.mime4j.message;
import java.util.Collections;
import java.util.List;
import org.apache.james.mime4j.dom.Multipart;
import org.apache.james.mime4j.stream.NameValuePair;
import org.apache.james.mime4j.util.ByteSequence;
import org.apache.james.mime4j.util.ContentUtil;
/**
* Default implementation of {@link Multipart}.
*/
public class MultipartImpl extends AbstractMultipart {
private ByteSequence preamble;
private transient String preambleStrCache;
private transient boolean preambleComputed = false;
private ByteSequence epilogue;
private transient String epilogueStrCache;
private transient boolean epilogueComputed = false;
public MultipartImpl(String subType) {
this(subType, Collections.<NameValuePair>emptyList());
}
/**
* Creates a new empty <code>Multipart</code> instance.
*/
public MultipartImpl(String subType, List<NameValuePair> parameters) {
super(subType, parameters);
preamble = null;
preambleStrCache = null;
preambleComputed = true;
epilogue = null;
epilogueStrCache = null;
epilogueComputed = true;
}
// package private for now; might become public someday
public ByteSequence getPreambleRaw() {
return preamble;
}
public void setPreambleRaw(ByteSequence preamble) {
this.preamble = preamble;
this.preambleStrCache = null;
this.preambleComputed = false;
}
/**
* Gets the preamble.
*
* @return the preamble.
*/
@Override
public String getPreamble() {
if (!preambleComputed) {
preambleStrCache = preamble != null ? ContentUtil.decode(preamble) : null;
preambleComputed = true;
}
return preambleStrCache;
}
/**
* Sets the preamble.
*
* @param preamble
* the preamble.
*/
@Override
public void setPreamble(String preamble) {
this.preamble = preamble != null ? ContentUtil.encode(preamble) : null;
this.preambleStrCache = preamble;
this.preambleComputed = true;
}
// package private for now; might become public someday
public ByteSequence getEpilogueRaw() {
return epilogue;
}
public void setEpilogueRaw(ByteSequence epilogue) {
this.epilogue = epilogue;
this.epilogueStrCache = null;
this.epilogueComputed = false;
}
/**
* Gets the epilogue.
*
* @return the epilogue.
*/
@Override
public String getEpilogue() {
if (!epilogueComputed) {
epilogueStrCache = epilogue != null ? ContentUtil.decode(epilogue) : null;
epilogueComputed = true;
}
return epilogueStrCache;
}
/**
* Sets the epilogue.
*
* @param epilogue
* the epilogue.
*/
@Override
public void setEpilogue(String epilogue) {
this.epilogue = epilogue != null ? ContentUtil.encode(epilogue) : null;
this.epilogueStrCache = epilogue;
this.epilogueComputed = true;
}
}
| 31.713235
| 86
| 0.601438
|
cb284772d58d2cc1294ea7aaff04af8bdf295d4e
| 4,521
|
package mage.cards.r;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.ContinuousEffect;
import mage.abilities.effects.Effect;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.DoIfCostPaid;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.keyword.HasteAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.permanent.Permanent;
import mage.game.permanent.token.ElementalShamanToken;
import mage.players.Player;
import mage.target.targetpointer.FixedTarget;
/**
*
* @author Styxo
*/
public final class RebellionOfTheFlamekin extends CardImpl {
public RebellionOfTheFlamekin(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.TRIBAL,CardType.ENCHANTMENT},"{3}{R}");
this.subtype.add(SubType.ELEMENTAL);
// Whenever you clash, you may pay {1}. If you do create a 3/1 Red Elemental Shaman creature token in play. If you won that token gains haste
this.addAbility(new RebellionOfTheFlamekinTriggeredAbility());
}
public RebellionOfTheFlamekin(final RebellionOfTheFlamekin card) {
super(card);
}
@Override
public RebellionOfTheFlamekin copy() {
return new RebellionOfTheFlamekin(this);
}
}
class RebellionOfTheFlamekinTriggeredAbility extends TriggeredAbilityImpl {
public RebellionOfTheFlamekinTriggeredAbility() {
super(Zone.BATTLEFIELD, new RebellionOfTheFlamekinEffect());
}
public RebellionOfTheFlamekinTriggeredAbility(final RebellionOfTheFlamekinTriggeredAbility ability) {
super(ability);
}
@Override
public RebellionOfTheFlamekinTriggeredAbility copy() {
return new RebellionOfTheFlamekinTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.CLASHED;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
boolean youWonTheClash = false;
if (event.getData().equals("controller") && event.getPlayerId().equals(getControllerId())
|| event.getData().equals("opponent") && event.getTargetId().equals(getControllerId())) {
youWonTheClash = true;
}
for (Effect effect : getEffects()) {
if (effect instanceof RebellionOfTheFlamekinEffect) {
effect.setValue("clash", youWonTheClash);
}
}
return true;
}
@Override
public String getRule() {
return "Whenever you clash, you may pay {1}. If you do create a 3/1 Red Elemental Shaman creature token in play. If you won that token gains haste until end of turn";
}
}
class RebellionOfTheFlamekinEffect extends OneShotEffect {
public RebellionOfTheFlamekinEffect() {
super(Outcome.PutCreatureInPlay);
}
public RebellionOfTheFlamekinEffect(final RebellionOfTheFlamekinEffect effect) {
super(effect);
}
@Override
public RebellionOfTheFlamekinEffect copy() {
return new RebellionOfTheFlamekinEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
if (controller != null) {
CreateTokenEffect createTokenEffect = new CreateTokenEffect(new ElementalShamanToken("LRW"));
DoIfCostPaid doIfCostPaid = new DoIfCostPaid(createTokenEffect, new ManaCostsImpl("{1}"));
doIfCostPaid.apply(game, source);
Permanent token = game.getPermanent(createTokenEffect.getLastAddedTokenId());
if (token != null && (boolean) (this.getValue("clash"))) {
ContinuousEffect continuousEffect = new GainAbilityTargetEffect(HasteAbility.getInstance(), Duration.EndOfTurn);
continuousEffect.setTargetPointer(new FixedTarget(createTokenEffect.getLastAddedTokenId()));
game.addEffect(continuousEffect, source);
}
return true;
}
return false;
}
}
| 35.046512
| 174
| 0.714223
|
584fbdf56c43e561f1ec3d9e9f3a4f63f4178373
| 808
|
package com.login.employee.model;
import com.login.employee.domain.Employee;
import com.login.employee.domain.LoginUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
//LoginResponse necessary for SpringSecurity module
//to hold username, password and authorities
public class LoginResponse extends User {
private LoginUser loginUser;
public LoginResponse(String username,
String password,
Collection<? extends GrantedAuthority> authorities,
LoginUser loginUser) {
super(username, password, authorities);
this.loginUser = loginUser;
}
public LoginUser getLoginUser() {return loginUser;}
}
| 26.064516
| 76
| 0.710396
|
1c76b07338e6f9ce33e350dbc040c62129a2f46b
| 3,578
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hop.core;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.core.xml.IXml;
import java.util.Date;
public interface IEngineMeta {
/**
* Sets the filename.
*
* @param filename
*/
void setFilename(String filename);
/**
* Set the name of the engine metadata object
*
* @param name
*/
void setName(String name);
/**
* Gets the name.
*
* @return name
*/
String getName();
/** Builds a name for this. If no name is yet set, create the name from the filename. */
void nameFromFilename();
/** Clears the changed flag of this. */
void clearChanged();
/**
* Gets the XML representation.
*
* @return the XML representation of this pipeline
* @throws HopException if any errors occur during generation of the XML
* @see IXml#getXml()
* @param variables
*/
String getXml(IVariables variables) throws HopException;
/**
* Gets the date the pipeline was created.
*
* @return the date the pipeline was created
*/
Date getCreatedDate();
/**
* Sets the date the pipeline was created.
*
* @param date The creation date to set
*/
void setCreatedDate(Date date);
/**
* Returns whether or not the this can be saved.
*
* @return
*/
boolean canSave();
/**
* Gets the user by whom this was created.
*
* @return the user by whom this was created
*/
String getCreatedUser();
/**
* Sets the user by whom this was created.
*
* @param createduser The user to set
*/
void setCreatedUser(String createduser);
/**
* Gets the date this was modified.
*
* @return the date this was modified
*/
Date getModifiedDate();
/**
* Sets the date this was modified.
*
* @param date The modified date to set
*/
void setModifiedDate(Date date);
/**
* Sets the user who last modified this.
*
* @param user The user name to set
*/
void setModifiedUser(String user);
/**
* Gets the user who last modified this.
*
* @return the user who last modified this
*/
String getModifiedUser();
/**
* Get the filename (if any).
*
* @return the filename
*/
String getFilename();
/**
* Sets the internal hop variables on the provided IVariables
*
* @param variables the variables to set the internal Hop variables and values on
*/
void setInternalHopVariables(IVariables variables);
/** @return true if the name is derived from the filename */
boolean isNameSynchronizedWithFilename();
/** @param nameSynchronizedWithFilename Set to true if the name is derived from the filename */
void setNameSynchronizedWithFilename(boolean nameSynchronizedWithFilename);
}
| 24.175676
| 97
| 0.67943
|
d6cd5417600f99eea62f8a7ab863a7501dc24ee4
| 350
|
package com.dranawhite.study.springboot.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author dranawhite
* @version : AopConfig.java, v 0.1 2019-08-22 10:41 dranawhite Exp $$
*/
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}
| 21.875
| 70
| 0.791429
|
0c2d14aa1ea637d7ce47355b7f7124db1da08772
| 2,578
|
package lapr2.ClientServicesProvider.aplicationagpsd.Controllers;
import java.net.URL;
import java.util.ResourceBundle;
import lapr2.ClientServicesProvider.aplicationagpsd.Model.Availability;
import lapr2.ClientServicesProvider.aplicationagpsd.Model.Company;
import lapr2.ClientServicesProvider.aplicationagpsd.Utils.Date;
import lapr2.ClientServicesProvider.aplicationagpsd.Utils.Time;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.*;
/**
*
* @author Tiago Ribeiro (1181444)
*/
public class DecideAvailabilityControllerTest {
public DecideAvailabilityControllerTest() {
}
/**
* Test of initialize method, of class DecideAvailabilityController.
*/
@Test
public void testInitialize() {
System.out.println("initialize");
URL url = null;
ResourceBundle rb = null;
DecideAvailabilityController instance = new DecideAvailabilityController();
instance.initialize(url, rb);
}
/**
* Test of getAvailability method, of class DecideAvailabilityController.
*/
@Test
public void testGetAvailability() {
System.out.println("getAvailability");
DecideAvailabilityController instance = new DecideAvailabilityController();
Availability expResult = new Availability();
instance.setAvailability(expResult);
Availability result = instance.getAvailability();
assertEquals(expResult, result);
}
/**
* Test of setAvailability method, of class DecideAvailabilityController.
*/
@Test
public void testSetAvailability() {
System.out.println("setCli");
Availability ava = new Availability();
DecideAvailabilityController instance = new DecideAvailabilityController();
instance.setAvailability(ava);
assertEquals(ava, instance.getAvailability());
}
/**
* Test of newAvailability method, of class DecideAvailabilityController.
*/
@Test
public void testNewAvailability() {
System.out.println("newAvailability");
Company c = new Company();
Date startDate = new Date(2019,8,8);
Date endDate = new Date(2019,8,8);
Time startTime = new Time(15,15);
Time endTime = new Time(16,16);
Availability ava = new Availability(startDate, endDate, startTime, endTime);
DecideAvailabilityController instance = new DecideAvailabilityController();
instance.newAvailability(startDate, endDate, startTime, endTime);
assertEquals(instance.getAvailability(), ava);
}
}
| 34.373333
| 84
| 0.699379
|
3720ee5578b6422e54d3e54d37687f1cf2cdcb03
| 593
|
package Strategy;
import Chocolate.Chocolate;
import Mould.*;
public class ProduceSmallChocolate implements ProduceChocolate{
SmallMould smallMould;
public ProduceSmallChocolate(SmallMould m){
System.out.println("======== 使用策略 Strategy 模式 ========");
smallMould=m;
}
@Override
public void doShape(Chocolate chocolate) {
useSmallChocolate();
chocolate.setSSC(smallMould);
}
public void useSmallChocolate(){
System.out.println("使用小型模具为巧克力塑形...");
System.out.println("塑形后的巧克力:");
smallMould.getInfo();
}
}
| 25.782609
| 65
| 0.652614
|
91b1b0f8e921ce9570c583312b1cfd3d10d29b0e
| 781
|
package cn.yangw.demowebsocketwithspringboot.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* TODO comments
*
* @author Willow
* @date 2020/2/18
*/
//@Configuration
//@ComponentScan
//@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("/");
}
}
| 28.925926
| 81
| 0.809219
|
4f586537d4318b5b16d1a250891b58b18bf03440
| 1,303
|
package com.ethan.and.db.room.entity;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
@Entity(tableName = "ip_message")
public class IpMessage {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
private int id;
@ColumnInfo(name = "ip")
private String ip;
@ColumnInfo(name = "port")
private String port;
public IpMessage(String ip, String port) {
this.ip = ip;
this.port = port;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IpMessage)) return false;
IpMessage ipMessage = (IpMessage) o;
return id == ipMessage.id &&
ip.equals(ipMessage.ip) &&
port.equals(ipMessage.port);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
| 20.68254
| 52
| 0.584804
|
34bbe7a7274905dcd5c3e0e4195b68da49e6d740
| 135
|
public class ThreadBandCpu {
static {
System.loadLibrary("bandCpu");
}
public static native void bandCpu(Runnable r, int cpu);
}
| 16.875
| 56
| 0.725926
|
89587eb38959b3db68b526b36daf0f162b843147
| 853
|
package cn.bootx.payment.param.paymodel.wallet;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author xxm
* @date 2020/12/8
*/
@Data
@Accessors(chain = true)
@ApiModel("钱包日志查询参数")
public class WalletLogQueryParam implements Serializable {
private static final long serialVersionUID = -4046664021959786637L;
@ApiModelProperty("钱包ID (与userId至少存在一个)")
private Long walletId;
@ApiModelProperty("用户ID (钱包至少存在一个)")
private Long userId;
@ApiModelProperty("开始日期")
private LocalDateTime startDate;
@ApiModelProperty("结束日期")
private LocalDateTime endDate;
@ApiModelProperty("日志类型,不传则查询全部")
private List<Integer> type;
}
| 22.447368
| 71
| 0.754982
|
1a64732c711d91edb707cf237adc11ae50dcae09
| 534
|
package com.daigou.sg.rpc.order;
import com.daigou.sg.rpc.BaseModule;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
/**
* This file is auto-generated by tgen
* Don't change manually
*/
public class TOrder extends BaseModule<TOrder> implements Serializable {
public int id;
public String orderNumber;
public String productImage;
public String productName;
public boolean gstFee;
public boolean insured;
public String sellerDiscount;
public int packageId;
}
| 22.25
| 72
| 0.747191
|
904565f55f2b554dd90aeba221324880762b895b
| 246
|
package org.javacore.pattern.mediator;
//文本框类:具体同事类
class TextBox extends Component {
public void update() {
System.out.println("客户信息增加成功后文本框清空。");
}
public void setText() {
System.out.println("文本框显示:小龙女。");
}
}
| 18.923077
| 46
| 0.638211
|
82b5bb299def1ccb372b72d90c0b5fba5fd2feaf
| 161
|
package mannyboidpaperrus.paperthinger.items;
/**
* Armor slots.
*/
public enum LivingEntityArmorSlot {
HELMET,
CHESTPLATE,
LEGGINGS,
BOOTS
}
| 13.416667
| 45
| 0.689441
|
833151e8714abcc7af03cf8a5be47017ebb90adc
| 1,259
|
/**
* ABattle, a xbattle conversion for java, Copyright by Roland Spatzenegger (2011-)
*/
package net.npg.abattle.server;
import net.npg.abattle.common.component.ComponentLookup;
import net.npg.abattle.common.error.BaseException;
import net.npg.abattle.communication.network.impl.NetworkComponentImpl;
/**
* Starts the Server. The main purpose of this class is to initialize all Components and start the Network Server, which
* waits for incoming game requests!
*
* @author spatzenegger
*
*/
public abstract class Server {
/**
* Inits the base components.
*/
protected void initBaseComponents() {
final ComponentLookup componentLookup = ComponentLookup.getInstance();
componentLookup.registerComponent(new NetworkComponentImpl());
}
/**
* Run the server.
*
* @throws ServerException the server exception
*/
public void run() throws BaseException {
initBaseComponents();
startPreGameServer();
}
/**
* Start pre game server.
*
* @throws ServerException the server exception
*/
abstract protected void startPreGameServer() throws BaseException;
public void stop() throws BaseException {
stopGameServer();
}
abstract protected void stopGameServer();
}
| 24.686275
| 121
| 0.713264
|
e60ddf097aa855a2a57f567a4cc56b77d5ffa84f
| 856
|
package seller;
/**
* Created by Administrator on 18/11/2559.
*/
public class SellerData {
public static int reportId = 1;
public static int graphOptionId = 0;
public static int reportOptional = TypeSellerOptional.TYPE_TOP_10;
public static int dataSetNumber = 0;
public static String shopCode = null;
public static String graphUnit = "";
public static final String _PURE_DATA_TRANSFER_PORT_ = "3WEQTSSJ-";
// INNER DATA ------------------------------------------------------------------------------->
private String SHIP_NO;
private int REPORT_NO;
public String getSHIP_NO() { return SHIP_NO; }
public void setSHIP_NO(String SHIP_NO) { this.SHIP_NO = SHIP_NO; }
public int getREPORT_NO() { return REPORT_NO; }
public void setREPORT_NO(int REPORT_NO) { this.REPORT_NO = REPORT_NO; }
}
| 25.176471
| 98
| 0.636682
|
c7765e89157736d0d13f7f717a25b6a21f12751f
| 22,547
|
// Copyright 2004 The Apache Software Foundation
//
// 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.apache.hivemind.impl;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hivemind.ApplicationRuntimeException;
import org.apache.hivemind.ClassResolver;
import org.apache.hivemind.ErrorHandler;
import org.apache.hivemind.HiveMind;
import org.apache.hivemind.Occurances;
import org.apache.hivemind.Registry;
import org.apache.hivemind.Resource;
import org.apache.hivemind.ShutdownCoordinator;
import org.apache.hivemind.internal.Module;
import org.apache.hivemind.parse.ConfigurationPointDescriptor;
import org.apache.hivemind.parse.ContributionDescriptor;
import org.apache.hivemind.parse.DescriptorParser;
import org.apache.hivemind.parse.ImplementationDescriptor;
import org.apache.hivemind.parse.InstanceBuilder;
import org.apache.hivemind.parse.InterceptorDescriptor;
import org.apache.hivemind.parse.ModuleDescriptor;
import org.apache.hivemind.parse.ServicePointDescriptor;
import org.apache.hivemind.util.IdUtils;
import org.apache.hivemind.util.URLResource;
/**
* Class used to build a {@link org.apache.hivemind.Registry} from individual
* {@link org.apache.hivemind.parse.ModuleDescriptor}. The descriptors
* are processed one at a time and the registry is constructed using a single call
* to {@link #constructRegistry(Locale)} at the end.
*
* <p>
* A note about threadsafety: The assumption is that a single thread will access the RegistryBuilder
* at one time (typically, a startup class within some form of server or application). Code
* here and in many of the related classes is divided into construction-time logic
* and runtime logic. Runtime logic is synchronized and threadsafe. Construction-time logic
* is not threadsafe. Methods such as {@link org.apache.hivemind.impl.RegistryImpl#addModule(Module)},
* {@link org.apache.hivemind.impl.ModuleImpl#addConfigurationPoint(ConfigurationPoint)},
* {@link org.apache.hivemind.impl.ConfigurationPointImpl#addContribution(Contribution)}
* and the like are construction-time. Once the registry is fully constructed, it is not
* allowed to invoke those methods (though, at this time, no checks occur).
*
* <p>Runtime methods, such as {@link org.apache.hivemind.impl.ModuleImpl#getService(String, Class)}
* are fully threadsafe.
*
* @author Howard Lewis Ship
*/
public final class RegistryBuilder
{
private static final Log LOG = LogFactory.getLog(RegistryBuilder.class);
static {
if (!LOG.isErrorEnabled())
{
System.err.println(
"********************************************************************************");
System.err.println(
"* L O G G I N G C O N F I G U R A T I O N E R R O R *");
System.err.println(
"* ---------------------------------------------------------------------------- *");
System.err.println(
"* Logging is not enabled for org.apache.hivemind.impl.RegistryBuilder. *");
System.err.println(
"* Errors during HiveMind module descriptor parsing and validation may not be *");
System.err.println(
"* logged. This may result in difficult-to-trace runtime exceptions, if there *");
System.err.println(
"* are errors in any of your module descriptors. You should enable error *");
System.err.println(
"* logging for the org.apache.hivemind and hivemind loggers. *");
System.err.println(
"********************************************************************************");
}
}
/**
* The path, within a JAR or the classpath, to the XML HiveMind module
* deployment descriptor: <code>META-INF/hivemodule.xml</code>.
*/
public static final String HIVE_MODULE_XML = "META-INF/hivemodule.xml";
/**
* List of {@link ModuleDescriptor}.
*/
private List _moduleDescriptors = new ArrayList();
/**
* Map of {@link ModuleImpl} keyed on fully qualified module id.
*/
private Map _modules = new HashMap();
/**
* Map of {@link PrimitiveServiceModel} (or subclass) keyed on fully qualified id.
*/
private Map _servicePoints = new HashMap();
/**
* Map of {@link ConfigurationPointImpl} keyed on fully qualified id.
*/
private Map _configurationPoints = new HashMap();
/**
* Delegate used for handling errors.
*/
private ErrorHandler _errorHandler;
/**
* Parser instance used by all parsing for this builder.
*/
private DescriptorParser _parser;
/**
* Shutdown coordinator shared by all objects.
*/
private ShutdownCoordinator _shutdownCoordinator = new ShutdownCoordinatorImpl();
/**
* RegistryAssembly used by the module descriptor parser(s).
*/
private RegistryAssemblyImpl _registryAssembly;
public RegistryBuilder()
{
this(new DefaultErrorHandler());
}
public RegistryBuilder(ErrorHandler handler)
{
_errorHandler = handler;
_registryAssembly = new RegistryAssemblyImpl(handler);
}
/**
* Processes all modules that can be found using the resolver.
*/
public void processModules(ClassResolver resolver)
{
if (LOG.isDebugEnabled())
LOG.debug("Processing modules visible to " + resolver);
processModulesResources(resolver, HIVE_MODULE_XML);
}
/**
* Locates module deployment descriptors in the "standard" location (META-INF).
*/
private void processModulesResources(ClassResolver resolver, String resourcePath)
{
ClassLoader loader = resolver.getClassLoader();
Enumeration e = null;
try
{
e = loader.getResources(resourcePath);
}
catch (IOException ex)
{
throw new ApplicationRuntimeException(
ImplMessages.unableToFindModules(resolver, ex),
ex);
}
while (e.hasMoreElements())
{
URL descriptorURL = (URL) e.nextElement();
Resource descriptorResource = new URLResource(descriptorURL);
processModule(resolver, descriptorResource);
}
}
/**
* Parses a module and processes its contents. This is often used
* in conjunction with {@link #processModules(ClassResolver)} to
* parse additional modules that are not in the standard location
* (for whatever reason).
*/
public void processModule(ClassResolver resolver, Resource moduleDescriptorResource)
{
if (_parser == null)
_parser = new DescriptorParser(_errorHandler, _registryAssembly);
try
{
ModuleDescriptor md = _parser.parse(moduleDescriptorResource, resolver);
processModule(md);
// After parsing a module, parse any additional modules identified
// within the module (using the <sub-module> element.
while (_registryAssembly.moreQueuedModules())
{
md = _registryAssembly.parseNextQueued(_parser);
processModule(md);
}
}
catch (RuntimeException ex)
{
// An exception may leave the parser in an unknown state, so
// give up on that instance and start with a fresh one.
_parser = null;
_errorHandler.error(LOG, ex.getMessage(), HiveMind.getLocation(ex), ex);
}
}
/**
* Processes a parsed HiveMind module descriptor. This may be called
* repeatedly before invoking {@link #constructRegistry(Locale)}.
*
* @param md the parsed module descriptor
*/
public void processModule(ModuleDescriptor md)
{
String id = md.getModuleId();
if (LOG.isDebugEnabled())
LOG.debug("Processing module " + id);
if (_modules.containsKey(id))
{
Module existing = (Module) _modules.get(id);
_errorHandler.error(LOG, ImplMessages.duplicateModuleId(existing, md), null, null);
// Ignore the duplicate module descriptor.
return;
}
ModuleImpl module = new ModuleImpl();
module.setLocation(md.getLocation());
module.setModuleId(id);
module.setClassResolver(md.getClassResolver());
_modules.put(id, module);
_moduleDescriptors.add(md);
}
private void addServiceAndConfigurationPoints(RegistryImpl registry)
{
int count = _moduleDescriptors.size();
for (int i = 0; i < count; i++)
{
ModuleDescriptor md = (ModuleDescriptor) _moduleDescriptors.get(i);
String id = md.getModuleId();
ModuleImpl module = (ModuleImpl) _modules.get(id);
addServicePoints(registry, module, md);
addConfigurationPoints(registry, module, md);
}
}
private void addServicePoints(RegistryImpl registry, ModuleImpl module, ModuleDescriptor md)
{
String moduleId = md.getModuleId();
List services = md.getServicePoints();
int count = size(services);
for (int i = 0; i < count; i++)
{
ServicePointDescriptor sd = (ServicePointDescriptor) services.get(i);
String pointId = moduleId + "." + sd.getId();
if (LOG.isDebugEnabled())
LOG.debug("Creating service extension point: " + pointId);
// Choose which class to instantiate based on
// whether the service is create-on-first-reference
// or create-on-first-use (deferred).
ServicePointImpl point = new ServicePointImpl();
point.setExtensionPointId(pointId);
point.setLocation(sd.getLocation());
point.setModule(module);
point.setServiceInterfaceName(sd.getInterfaceClassName());
point.setParametersSchema(sd.getParametersSchema());
point.setParametersCount(sd.getParametersCount());
point.setShutdownCoordinator(_shutdownCoordinator);
registry.addServicePoint(point);
// Save this for the second phase, where contributions
// from other modules are applied.
_servicePoints.put(pointId, point);
addInternalImplementations(module, pointId, sd);
}
}
private void addConfigurationPoints(
RegistryImpl registry,
ModuleImpl module,
ModuleDescriptor md)
{
String moduleId = md.getModuleId();
List points = md.getConfigurationPoints();
int count = size(points);
for (int i = 0; i < count; i++)
{
ConfigurationPointDescriptor cpd = (ConfigurationPointDescriptor) points.get(i);
String pointId = moduleId + "." + cpd.getId();
if (LOG.isDebugEnabled())
LOG.debug("Creating extension point " + pointId);
ConfigurationPointImpl point = new ConfigurationPointImpl();
point.setExtensionPointId(pointId);
point.setLocation(cpd.getLocation());
point.setModule(module);
point.setExpectedCount(cpd.getCount());
point.setContributionsSchema(cpd.getContributionsSchema());
point.setShutdownCoordinator(_shutdownCoordinator);
registry.addConfigurationPoint(point);
// Needed later when we reconcile the rest
// of the configuration contributions.
_configurationPoints.put(pointId, point);
}
}
private void addContributionElements(
Module sourceModule,
ConfigurationPointImpl point,
List elements)
{
if (size(elements) == 0)
return;
if (LOG.isDebugEnabled())
LOG.debug("Adding extensions to configuration point " + point.getExtensionPointId());
ContributionImpl c = new ContributionImpl();
c.setContributingModule(sourceModule);
c.addElements(elements);
point.addContribution(c);
}
/**
* Invoked after all modules have been added with
* {@link #processModule(ClassResolver, Resource)}.
* This first resolves all the contributions, then constructs and returns
* the registry.
*/
public Registry constructRegistry(Locale locale)
{
// Process any deferred operations
_registryAssembly.performPostProcessing();
RegistryImpl result = new RegistryImpl(_errorHandler, locale);
addServiceAndConfigurationPoints(result);
addImplementationsAndContributions();
checkForMissingServices();
checkContributionCounts();
result.setShutdownCoordinator(_shutdownCoordinator);
addModulesToRegistry(result);
result.startup();
return result;
}
private void addModulesToRegistry(RegistryImpl registry)
{
// Add each module to the registry.
Iterator i = _modules.values().iterator();
while (i.hasNext())
{
ModuleImpl module = (ModuleImpl) i.next();
if (LOG.isDebugEnabled())
LOG.debug("Adding module " + module.getModuleId() + " to registry");
module.setRegistry(registry);
}
}
private void addImplementationsAndContributions()
{
int count = _moduleDescriptors.size();
for (int i = 0; i < count; i++)
{
ModuleDescriptor md = (ModuleDescriptor) _moduleDescriptors.get(i);
if (LOG.isDebugEnabled())
LOG.debug("Adding contributions from module " + md.getModuleId());
addImplementations(md);
addContributions(md);
}
}
private void addImplementations(ModuleDescriptor md)
{
String moduleId = md.getModuleId();
ModuleImpl sourceModule = (ModuleImpl) _modules.get(moduleId);
List implementations = md.getImplementations();
int count = size(implementations);
for (int i = 0; i < count; i++)
{
ImplementationDescriptor impl = (ImplementationDescriptor) implementations.get(i);
String pointId = impl.getServiceId();
String qualifiedId = qualify(moduleId, pointId);
addImplementations(sourceModule, qualifiedId, impl);
}
}
private void addContributions(ModuleDescriptor md)
{
String moduleId = md.getModuleId();
ModuleImpl sourceModule = (ModuleImpl) _modules.get(moduleId);
List contributions = md.getContributions();
int count = size(contributions);
for (int i = 0; i < count; i++)
{
ContributionDescriptor cd = (ContributionDescriptor) contributions.get(i);
String pointId = cd.getConfigurationId();
String qualifiedId = qualify(moduleId, pointId);
ConfigurationPointImpl point =
(ConfigurationPointImpl) _configurationPoints.get(qualifiedId);
if (point == null)
{
_errorHandler.error(
LOG,
ImplMessages.unknownConfigurationPoint(moduleId, cd),
cd.getLocation(),
null);
continue;
}
addContributionElements(sourceModule, point, cd.getElements());
}
}
/**
* Qualifies the artifact id with the module id, if necessary.
*/
private static String qualify(String moduleId, String artifactId)
{
if (artifactId.indexOf('.') >= 0)
return artifactId;
return moduleId + "." + artifactId;
}
/**
* Adds internal service contributions; the contributions provided inplace
* with the service definition.
*/
private void addInternalImplementations(
ModuleImpl sourceModule,
String pointId,
ServicePointDescriptor spd)
{
InstanceBuilder builder = spd.getInstanceBuilder();
List interceptors = spd.getInterceptors();
if (builder == null && interceptors == null)
return;
if (builder != null)
addServiceInstanceBuilder(sourceModule, pointId, builder);
if (interceptors == null)
return;
int count = size(interceptors);
for (int i = 0; i < count; i++)
{
InterceptorDescriptor id = (InterceptorDescriptor) interceptors.get(i);
addInterceptor(sourceModule, pointId, id);
}
}
/**
* Adds ordinary service contributions.
*/
private void addImplementations(
ModuleImpl sourceModule,
String pointId,
ImplementationDescriptor id)
{
InstanceBuilder builder = id.getInstanceBuilder();
List interceptors = id.getInterceptors();
if (builder != null)
addServiceInstanceBuilder(sourceModule, pointId, builder);
int count = size(interceptors);
for (int i = 0; i < count; i++)
{
InterceptorDescriptor ind = (InterceptorDescriptor) interceptors.get(i);
addInterceptor(sourceModule, pointId, ind);
}
}
/**
* Adds an {@link InstanceBuilder}
* to a service extension point.
*
*
*/
private void addServiceInstanceBuilder(
ModuleImpl sourceModule,
String pointId,
InstanceBuilder builder)
{
if (LOG.isDebugEnabled())
LOG.debug("Adding " + builder + " to service extension point " + pointId);
ServicePointImpl sep = (ServicePointImpl) _servicePoints.get(pointId);
if (sep == null)
{
_errorHandler.error(
LOG,
ImplMessages.unknownServicePoint(sourceModule, pointId),
builder.getLocation(),
null);
return;
}
if (sep.getServiceConstructor() != null)
{
LOG.error(ImplMessages.duplicateFactory(sourceModule, pointId, sep));
return;
}
sep.setServiceModel(builder.getServiceModel());
sep.setServiceConstructor(builder.createConstructor(sep, sourceModule));
}
private void addInterceptor(ModuleImpl sourceModule, String pointId, InterceptorDescriptor id)
{
if (LOG.isDebugEnabled())
LOG.debug("Adding " + id + " to service extension point " + pointId);
ServicePointImpl sep = (ServicePointImpl) _servicePoints.get(pointId);
String sourceModuleId = sourceModule.getModuleId();
if (sep == null)
{
_errorHandler.error(
LOG,
ImplMessages.unknownServicePoint(sourceModule, pointId),
id.getLocation(),
null);
return;
}
ServiceInterceptorContributionImpl sic = new ServiceInterceptorContributionImpl();
// Allow the factory id to be unqualified, to refer to an interceptor factory
// service from within the same module.
sic.setFactoryServiceId(qualify(sourceModuleId, id.getFactoryServiceId()));
sic.setLocation(id.getLocation());
sic.setFollowingInterceptorIds(IdUtils.qualifyList(sourceModuleId, id.getBefore()));
sic.setPrecedingInterceptorIds(IdUtils.qualifyList(sourceModuleId, id.getAfter()));
sic.setContributingModule(sourceModule);
sic.setParameters(id.getParameters());
sep.addInterceptorContribution(sic);
}
/**
* Checks that each service has at service constructor.
*/
private void checkForMissingServices()
{
Iterator i = _servicePoints.values().iterator();
while (i.hasNext())
{
ServicePointImpl point = (ServicePointImpl) i.next();
if (point.getServiceConstructor() != null)
continue;
_errorHandler.error(LOG, ImplMessages.missingService(point), null, null);
}
}
/**
* Checks that each configuration extension point has the right number of contributions.
*/
private void checkContributionCounts()
{
Iterator i = _configurationPoints.values().iterator();
while (i.hasNext())
{
ConfigurationPointImpl point = (ConfigurationPointImpl) i.next();
Occurances expected = point.getExpectedCount();
int actual = point.getContributionCount();
if (expected.inRange(actual))
continue;
_errorHandler.error(
LOG,
ImplMessages.wrongNumberOfContributions(point, actual, expected),
point.getLocation(),
null);
}
}
private static int size(Collection c)
{
return c == null ? 0 : c.size();
}
/**
* Constructs a default registry based on just the modules
* visible to the thread context class loader (this is sufficient
* is the majority of cases), and using the default locale. If you have different
* error handling needs, or wish to pick up HiveMind module deployment
* descriptors for non-standard locations, you must create
* a RegistryBuilder instance yourself.
*/
public static Registry constructDefaultRegistry()
{
ClassResolver resolver = new DefaultClassResolver();
RegistryBuilder builder = new RegistryBuilder();
builder.processModules(resolver);
return builder.constructRegistry(Locale.getDefault());
}
}
| 31.534266
| 103
| 0.622832
|
81949ce2fbaf7fc1fee559791354a9ab3b50a902
| 4,602
|
package org.infinispan;
import net.jcip.annotations.Immutable;
import java.io.ByteArrayOutputStream;
/**
* Contains version information about this release of Infinispan.
*
* @author Bela Ban
* @since 4.0
*/
@Immutable
public class Version {
private static final String MAJOR = "7";
private static final String MINOR = "0";
private static final String MICRO = "0";
private static final String MODIFIER = "SNAPSHOT";
private static final boolean SNAPSHOT = true;
public static final String VERSION = String.format("%s.%s.%s%s%s", MAJOR, MINOR, MICRO, SNAPSHOT ? "-" : ".", MODIFIER);
public static final String CODENAME = "Guinness";
public static final String PROJECT_NAME = "Infinispan";
public static final byte[] VERSION_ID = readVersionBytes();
public static final String MAJOR_MINOR = MAJOR + "." + MINOR;
public static final String MODULE_SLOT = "ispn-" + MAJOR_MINOR;
private static final int MAJOR_SHIFT = 11;
private static final int MINOR_SHIFT = 6;
private static final int MAJOR_MASK = 0x00f800;
private static final int MINOR_MASK = 0x0007c0;
private static final int PATCH_MASK = 0x00003f;
private static byte[] readVersionBytes() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < MAJOR.length(); i++) baos.write(MAJOR.charAt(i));
for (int i = 0; i < MINOR.length(); i++) baos.write(MINOR.charAt(i));
for (int i = 0; i < MICRO.length(); i++) baos.write(MICRO.charAt(i));
if (SNAPSHOT)
baos.write('S');
else
for (int i = 0; i < MODIFIER.length(); i++) baos.write(MODIFIER.charAt(i));
return baos.toByteArray();
}
/**
* Prints version information.
*/
public static void main(String[] args) {
printFullVersionInformation();
}
/**
* Prints full version information to the standard output.
*/
public static void printFullVersionInformation() {
System.out.println(PROJECT_NAME);
System.out.println();
System.out.printf("Version: \t%s%n", VERSION);
System.out.printf("Codename: \t%s%n", CODENAME);
System.out.println("History: \t(see https://jira.jboss.org/jira/browse/ISPN for details)");
System.out.println();
}
/**
* Returns version information as a string.
*/
public static String printVersion() {
return PROJECT_NAME + " '" + CODENAME + "' " + VERSION;
}
public static String printVersionId(byte[] v, int len) {
StringBuilder sb = new StringBuilder();
if (v != null) {
if (len <= 0)
len = v.length;
for (int i = 0; i < len; i++)
sb.append((char) v[i]);
}
return sb.toString();
}
public static boolean compareTo(byte[] v) {
if (v == null)
return false;
if (v.length < VERSION_ID.length)
return false;
for (int i = 0; i < VERSION_ID.length; i++) {
if (VERSION_ID[i] != v[i])
return false;
}
return true;
}
public static int getLength() {
return VERSION_ID.length;
}
public static short getVersionShort() {
return getVersionShort(VERSION);
}
public static short getVersionShort(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
String parts[] = getParts(versionString);
int a = 0;
int b = 0;
int c = 0;
if (parts.length > 0)
a = Integer.parseInt(parts[0]);
if (parts.length > 1)
b = Integer.parseInt(parts[1]);
if (parts.length > 2)
c = Integer.parseInt(parts[2]);
return encodeVersion(a, b, c);
}
public static short encodeVersion(int major, int minor, int patch) {
return (short) ((major << MAJOR_SHIFT)
+ (minor << MINOR_SHIFT)
+ patch);
}
public static String decodeVersion(short version) {
int major = (version & MAJOR_MASK) >> MAJOR_SHIFT;
int minor = (version & MINOR_MASK) >> MINOR_SHIFT;
int patch = (version & PATCH_MASK);
return major + "." + minor + "." + patch;
}
/**
* Serialization only looks at major and minor, not micro or below.
*/
public static String decodeVersionForSerialization(short version) {
int major = (version & MAJOR_MASK) >> MAJOR_SHIFT;
int minor = (version & MINOR_MASK) >> MINOR_SHIFT;
return major + "." + minor;
}
private static String[] getParts(String versionString) {
return versionString.split("[\\.\\-]");
}
}
| 31.306122
| 123
| 0.614515
|
69b706543f3bf8bf3e0e69dd7836763ba16e8d57
| 1,183
|
package shoonye.dbmvc.parser;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shoonye.dbmvc.sample.SampleActionProcessor;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FMTemplateParser implements TemplateParser {
static final Logger logger = LoggerFactory.getLogger(SampleActionProcessor.class);
@Override
public String parse(Parsable template, Map<String, Object> data) {
StringWriter writer = new StringWriter();
try {
Configuration cfg = new Configuration();
StringTemplateLoader stringLoader = new StringTemplateLoader();
String name = template.getName()==null? template.getName(): template.getKey();
stringLoader.putTemplate(name, template.getBody());
cfg.setTemplateLoader(stringLoader);
Template tmplt = new Template(name, new StringReader(template.getBody()),cfg);
tmplt.process(data, writer);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return null;
}
return writer.toString();
}
}
| 30.333333
| 84
| 0.743872
|
8a1d0e374f463860e1ff46530da1e1fdb219f734
| 15,997
|
package io.vertx.armysystem.microservice.account.impl;
import io.vertx.armysystem.business.common.*;
import io.vertx.core.*;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.armysystem.microservice.account.User;
import io.vertx.armysystem.microservice.account.UserService;
import io.vertx.armysystem.microservice.account.common.Functional;
import io.vertx.armysystem.microservice.common.service.MongoRepositoryWrapper;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.JWTAuthOptions;
import io.vertx.ext.jwt.JWTOptions;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Implementation of {@link UserService}. Use MongoDB as the persistence.
*/
public class UserServiceImpl extends MongoRepositoryWrapper implements UserService, ServiceBase {
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
private static final String FILTER_COLUMN_NAME = "organization.parentIds";
private JWTAuth authProvider;
private final CRUDService roleService;
private final Vertx vertx;
public UserServiceImpl(Vertx vertx, JsonObject config, CRUDService roleService) {
super(vertx, config);
this.vertx = vertx;
this.roleService = roleService;
authProvider = JWTAuth.create(vertx, new JWTAuthOptions(config));
}
@Override
public String getServiceName() {
return "account-user-eb-service";
}
@Override
public String getServiceAddress() {
return "service.account.user";
}
@Override
public String getPermission() {
return "User";
}
@Override
public String getCollectionName() {
return "User";
}
@Override
public UserService initializePersistence(Handler<AsyncResult<Void>> resultHandler) {
logger.info("init user collection...");
this.createCollection(getCollectionName())
.otherwise(err -> null)
.compose(o -> this.createIndexWithOptions(getCollectionName(),
new JsonObject().put("username", 1), new JsonObject().put("unique", true)))
.otherwise(err -> null)
.compose(o -> initUserData())
.otherwise(err -> null)
.setHandler(resultHandler);
return this;
}
// Read init user data from user.json config file
private Future<Void> initUserData() {
Future<Void> future = Future.future();
vertx.fileSystem().readFile("user.json",
ar -> {
if (ar.succeeded()) {
JsonObject userData = new JsonObject(ar.result().toString());
logger.info("Read user data: " + userData);
JsonArray users = userData.getJsonArray("users");
if (users != null) {
CompositeFuture.join(users.stream()
.filter(item -> item instanceof JsonObject)
.map(json -> this.insertOne(getCollectionName(), (JsonObject)json))
.collect(Collectors.toList()))
.setHandler(ar2 -> future.complete());
} else {
future.complete();
}
} else {
logger.error("Init user data failed: " + ar.cause());
future.fail(ar.cause());
}
});
return future;
}
@Override
public UserService addOne(JsonObject item, JsonObject principal, Handler<AsyncResult<JsonObject>> resultHandler) {
User user = new User(item);
logger.info("add user " + user.getUsername());
user.setBuildIn(false);
JsonObject query = new JsonObject().put("username", user.getUsername());
ModelUtil.fillOrganization(this, item)
.compose(u -> ModelUtil.validateOrganization(principal, u))
.compose(r -> validatePermissions(principal, user.getRoleName()))
.compose(r -> this.findOne(getCollectionName(), query, new JsonObject()))
.map(option -> option.map(User::new).orElse(null))
.setHandler(ar -> {
if (ar.succeeded()) {
if (ar.result() != null) {
String failureMessage = "User already exists with name " + user.getUsername();
resultHandler.handle(Future.failedFuture(failureMessage));
} else {
fillRoleLevel(user, principal)
.compose(u -> this.insertOne(getCollectionName(), u.toJson()))
.compose(u -> ModelUtil.fillOrganization(this, u))
.map(json -> json.putNull("password"))
.setHandler(resultHandler);
}
} else {
resultHandler.handle(Future.failedFuture(ar.cause()));
}
});
return this;
}
@Override
public UserService retrieveOne(String id, JsonObject principal, Handler<AsyncResult<JsonObject>> resultHandler) {
this.findOne(getCollectionName(), getCondition(id, principal).getQuery(), new JsonObject())
.map(option -> option.map(json -> json.putNull("password")))
.map(option -> option.orElse(null))
.compose(u -> ModelUtil.fillOrganization(this, u))
.setHandler(resultHandler);
return this;
}
@Override
public UserService retrieveAll(JsonObject principal, Handler<AsyncResult<List<JsonObject>>> resultHandler) {
this.retrieveManyByCondition(new JsonObject(), principal, resultHandler);
return this;
}
@Override
public UserService count(JsonObject condition, JsonObject principal, Handler<AsyncResult<Long>> resultHandler) {
QueryCondition qCondition = QueryCondition.parse(condition);
qCondition.filterByUserOrganizationV2(FILTER_COLUMN_NAME, principal);
logger.info("count user condition: " + qCondition);
AggregateBuilder builder = new AggregateBuilder()
.addLookupOrganization()
.addQuery(qCondition.getQuery())
.addCount();
this.aggregateQuery(getCollectionName(), builder.getPipeline(), new JsonObject())
.map(list -> builder.getCount(list))
.setHandler(resultHandler);
return this;
}
@Override
public UserService retrieveManyByCondition(JsonObject condition, JsonObject principal, Handler<AsyncResult<List<JsonObject>>> resultHandler) {
QueryCondition qCondition = QueryCondition.parse(condition);
if (qCondition.getOption().getJsonObject("sort") == null) {
qCondition.getOption().put("sort", new JsonObject().put("organization.orgCode", 1).put("roleLevel", 1));
}
qCondition.filterByUserOrganizationV2(FILTER_COLUMN_NAME, principal);
logger.info("query condition: " + qCondition);
AggregateBuilder builder = new AggregateBuilder()
.addLookupOrganization()
.addQuery(qCondition.getQuery())
.addOption(qCondition.getOption());
this.aggregateQuery(getCollectionName(), builder.getPipeline(), new JsonObject())
.map(list -> builder.fixLookupResults(list))
.setHandler(resultHandler);
return this;
}
@Override
public UserService updateOne(String id, JsonObject item, JsonObject principal, Handler<AsyncResult<JsonObject>> resultHandler) {
item.remove("id");
item.remove("buildIn");
item.remove("password");
item.remove("organization");
User user = new User(item);
this.findOne(getCollectionName(), getCondition(id, principal).getQuery(), new JsonObject())
.map(option -> option.map(User::new).orElse(null))
.setHandler(ar -> {
if (ar.succeeded()) {
if (ar.result() != null) {
List<Future<Void>> futures = new ArrayList<>();
futures.add(validatePermissions(principal, ar.result().getRoleName()));
if (user.getRoleName() != null && !user.getRoleName().equals(ar.result().getRoleName())) {
System.out.println("modify role from " + ar.result().getRoleName() + " to " + user.getRoleName());
futures.add(validatePermissions(principal, user.getRoleName()));
}
io.vertx.armysystem.microservice.common.functional.Functional.allOfFutures(futures)
.compose(r -> fillRoleLevel(user, principal))
.compose(r -> this.update(getCollectionName(), new JsonObject().put("_id", ar.result().getId()), user.toJson()))
.setHandler(ar2 -> {
if (ar2.succeeded()) {
this.retrieveOne(user.getId(), principal, resultHandler);
} else {
resultHandler.handle(Future.failedFuture(ar2.cause()));
}
});
} else {
resultHandler.handle(Future.failedFuture("Not found"));
}
} else {
resultHandler.handle(Future.failedFuture(ar.cause()));
}
});
return this;
}
@Override
public UserService deleteOne(String id, JsonObject principal, Handler<AsyncResult<Void>> resultHandler) {
JsonObject query = getCondition(id, principal).getQuery();
this.findOne(getCollectionName(), query, new JsonObject())
.map(option -> option.map(User::new).orElse(null))
.compose(result -> {
Future<User> future = Future.future();
if (result == null) {
future.fail("The user does not exist");
} else if (result.isBuildIn()) {
future.fail("The build-in user can't be deleted");
} else {
future.complete(result);
}
return future;
})
.compose(r -> validatePermissions(principal, r.getRoleName()))
.compose(r -> this.remove(getCollectionName(), query))
.setHandler(resultHandler);
return this;
}
private Future<JsonObject> fillPermissionsInUser(User user) {
if (user == null) {
return Future.succeededFuture();
}
JsonObject userObj = user.toJson();
return Functional.getPermissitions(user.getRoleName(), roleService)
.map(permissions -> userObj.put("permissions", new JsonArray(permissions)));
}
private Future<User> fillRoleLevel(User user, JsonObject principal) {
if (user.getRoleName() == null) {
return Future.succeededFuture(user);
}
Future<JsonObject> future = Future.future();
roleService.retrieveOne(user.getRoleName(), principal, future);
return future.map(r -> {
if (r != null && r.containsKey("level"))
return user.setRoleLevel(r.getInteger("level"));
else
return user;
});
}
@Override
public UserService loginUser(String username, String password, Handler<AsyncResult<JsonObject>> resultHandler) {
JsonObject query = new JsonObject()
.put("username", username)
.put("password", password);
this.findOne(getCollectionName(), query, new JsonObject())
.map(option -> option.map(json -> json.putNull("password")))
.map(option -> option.map(User::new).orElse(null))
.compose(user -> this.fillPermissionsInUser(user))
.compose(json -> ModelUtil.fillOrganization(this, json))
.setHandler(ar -> {
if (ar.succeeded()) {
if (ar.result() != null) {
JsonObject json = ar.result();
if (json.containsKey("organization") &&
json.getJsonObject("organization").containsKey("deactivated") &&
json.getJsonObject("organization").getBoolean("deactivated")) {
resultHandler.handle(Future.failedFuture("The user is deactivated."));
} else {
String token = generateAuthToken(json);
resultHandler.handle(Future.succeededFuture(new JsonObject()
.put("user", json)
.put("token", token)));
}
} else {
resultHandler.handle(Future.failedFuture("The username or password is invalid."));
}
} else {
resultHandler.handle(Future.failedFuture(ar.cause()));
}
});
return this;
}
@Override
public UserService updatePassword(String username, String oldPassword, String newPassword, Handler<AsyncResult<JsonObject>> resultHandler) {
JsonObject query = new JsonObject()
.put("username", username)
.put("password", oldPassword);
this.findOne(getCollectionName(), query, new JsonObject())
.map(option -> option.map(json -> json.putNull("password")))
.map(option -> option.map(User::new).orElse(null))
.setHandler(ar -> {
if (ar.succeeded()) {
if (ar.result() != null) {
User user = ar.result();
this.update(getCollectionName(), new JsonObject().put("_id", user.getId()), new JsonObject().put("password", newPassword))
.setHandler(ar2 -> {
if (ar2.succeeded())
resultHandler.handle(Future.succeededFuture(user.toJson()));
else
resultHandler.handle(Future.failedFuture(ar2.cause()));
});
} else {
resultHandler.handle(Future.failedFuture("The password is invalid."));
}
} else {
resultHandler.handle(Future.failedFuture(ar.cause()));
}
});
return this;
}
private String generateAuthToken(JsonObject user) {
JsonObject tokenJson = new JsonObject().
put("iss", "CYARMY").
put("exp", System.currentTimeMillis() / 1000L + 24*3600L).
put("iat", System.currentTimeMillis() / 1000L).
put("username", user.getString("username")).
put("roleName", user.getString("roleName"));
if (user.getString("organizationId") != null) {
tokenJson.put("organizationId", user.getString("organizationId"));
tokenJson.put("parentOrgIds", user.getJsonArray("parentOrgIds"));
}
JWTOptions options = new JWTOptions().
setExpiresInSeconds(24*3600).
setAlgorithm("HS256");
JsonArray permissions = user.getJsonArray("permissions");
if (permissions != null) {
options.setPermissions(permissions.getList());
}
return authProvider.generateToken(tokenJson, options);
}
private Future<Void> validatePermissions(JsonObject principal, String roleName) {
Future<Void> future = Future.future();
String currRole = principal.getString("roleName");
List<String> currPermissions = principal.getJsonArray("permissions", new JsonArray()).getList();
if (currRole == roleName) {
future.complete();
} else {
Functional.getPermissitions(roleName, roleService)
.map(permissions -> validatePermissions(currPermissions, permissions))
.setHandler(ar -> {
if (ar.succeeded()) {
if (ar.result())
future.complete();
else
future.fail("Unauthorized");
} else {
future.fail(ar.cause());
}
});
}
return future;
}
// 检查permissions中所有的权限是否都包含在currPermissions中
private Boolean validatePermissions(List<String> currPermissions, List<String> permissions) {
if (currPermissions == null || permissions == null) return false;
return permissions.stream()
.map(perm -> {
if (currPermissions.contains(perm)) {
return true;
} else if (perm.startsWith("*") || perm.indexOf(':') < 0) {
return false;
} else {
String newPerm = "*" + perm.substring(perm.indexOf(':'));
return currPermissions.contains(newPerm);
}
}).filter(r -> !r).count() == 0;
}
private QueryCondition getCondition(String id, JsonObject principal) {
JsonObject query = new JsonObject().put("$or", new JsonArray()
.add(new JsonObject().put("_id", id))
.add(new JsonObject().put("username", id)));
QueryCondition condition = new QueryCondition(query, new JsonObject())
.filterByUserOrganizationV1(FILTER_COLUMN_NAME, principal);
return condition;
}
}
| 36.859447
| 144
| 0.626367
|
313beb83c85ca3e3a1bf6425d0903b0402e8f2dd
| 8,778
|
package uk.ac.ebi.embl.api.validation.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import org.apache.commons.dbutils.DbUtils;
import uk.ac.ebi.embl.api.entry.Entry;
import uk.ac.ebi.embl.api.entry.EntryFactory;
import uk.ac.ebi.embl.api.entry.Text;
import uk.ac.ebi.embl.api.entry.feature.SourceFeature;
import uk.ac.ebi.embl.api.entry.qualifier.Qualifier;
import uk.ac.ebi.embl.api.entry.qualifier.QualifierFactory;
import uk.ac.ebi.embl.api.validation.SequenceEntryUtils;
import uk.ac.ebi.embl.api.validation.helper.taxon.TaxonHelper;
import uk.ac.ebi.embl.api.validation.helper.taxon.TaxonHelperImpl;
public class EntryDAOUtilsImpl implements EntryDAOUtils
{
private final Connection connection;
private static EntryDAOUtilsImpl entryDAOUtils;
public static EntryDAOUtilsImpl getEntryDAOUtilsImpl(Connection connection) {
if(null == entryDAOUtils ) {
entryDAOUtils = new EntryDAOUtilsImpl(connection);
}
return entryDAOUtils;
}
private EntryDAOUtilsImpl(Connection connection)
{
this.connection = connection;
}
@Override
public ArrayList<Qualifier> getChromosomeQualifiers(String analysisId,String submitterAccession, SourceFeature source) throws SQLException
{
String sql = "select chromosome_name, chromosome_location, chromosome_type "
+ "from gcs_chromosome where assembly_id = ? and upper(object_name) = upper(?)";
PreparedStatement stmt = null;
ResultSet rs = null;
boolean virus=false;
if(source!=null)
{
TaxonHelper taxonHelper= new TaxonHelperImpl();
String scientificName=source.getScientificName();
virus=taxonHelper.isChildOf(scientificName, "Viruses");
}
ArrayList<Qualifier> qualifiers = new ArrayList<Qualifier>();
QualifierFactory qualifierFactory = new QualifierFactory();
try
{
stmt = connection.prepareStatement(sql);
stmt.setString(1, analysisId);
stmt.setString(2, submitterAccession); // entry name
rs = stmt.executeQuery();
if (!rs.next())
{
return qualifiers;
}
String chromosomeType = rs.getString(3);
String chromosomeLocation = rs.getString(2);
String chromosomeName = rs.getString(1);
if (chromosomeLocation != null && !chromosomeLocation.isEmpty()&& !virus&&!chromosomeLocation.equalsIgnoreCase("Phage"))
{
String organelleValue = SequenceEntryUtils.getOrganelleValue(chromosomeLocation);
if (organelleValue != null)
{
qualifiers.add(qualifierFactory.createQualifier(Qualifier.ORGANELLE_QUALIFIER_NAME, SequenceEntryUtils.getOrganelleValue(chromosomeLocation)));
}
}
else if (chromosomeName != null && !chromosomeName.isEmpty())
{
if (Qualifier.PLASMID_QUALIFIER_NAME.equals(chromosomeType))
{
qualifiers.add(qualifierFactory.createQualifier(Qualifier.PLASMID_QUALIFIER_NAME, chromosomeName));
}
else if (Qualifier.CHROMOSOME_QUALIFIER_NAME.equals(chromosomeType))
{
qualifiers.add(qualifierFactory.createQualifier(Qualifier.CHROMOSOME_QUALIFIER_NAME, chromosomeName));
}
else if("segmented".equals(chromosomeType)||"multipartite".equals(chromosomeType))
{
qualifiers.add(qualifierFactory.createQualifier(Qualifier.SEGMENT_QUALIFIER_NAME, chromosomeName));
}
else if("monopartite".equals(chromosomeType))
{
qualifiers.add(qualifierFactory.createQualifier(Qualifier.NOTE_QUALIFIER_NAME, chromosomeType));
}
}
}
finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(stmt);
}
return qualifiers;
}
@Override
public boolean isValueExists(String tableName, String constraintKey, String constraintValue) throws SQLException
{
String sqlSearchStringTemp = "select 1 from %s where %s ='%s'";
String sql = String.format(sqlSearchStringTemp, tableName, constraintKey, constraintValue);
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
if (ps.executeQuery(sql).next())
return true;
return false;
} finally
{
DbUtils.closeQuietly(ps);
}
}
@Override
public boolean isEntryExists(String accession) throws SQLException
{
ResultSet rs = null;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement("select 1 from bioseq where sequence_acc=? or seq_accid=?");
ps.setString(1, accession);
ps.setString(2,accession);
rs = ps.executeQuery();
if (rs.next())
{
return true;
}
return false;
} finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
}
}
@Override
public Long getSequenceLength(String accession) throws SQLException
{
ResultSet rs = null;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement("select seqlen from bioseq where sequence_acc=? or seq_accid=?");
ps.setString(1,accession);
ps.setString(2, accession);
rs = ps.executeQuery();
if (rs.next())
{
return rs.getLong(1);
}
return 0L;
} finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
}
}
@Override
public boolean isProjectValid(String project) throws SQLException
{
ResultSet rs = null;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement("select 1 from mv_project where project_id=? or ncbi_project_id=?");
ps.setString(1, project);
ps.setString(2, project);
rs = ps.executeQuery();
if (rs.next())
{
return true;
}
return false;
} finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
}
}
@Override
public HashSet<String> getProjectLocutagPrefix(String project) throws SQLException {
ResultSet rs = null;
PreparedStatement ps = null;
HashSet<String> locusTagPrefixes = new HashSet<String>();
try
{
ps = connection.prepareStatement("select upper(locus_tag) from mv_project where project_id=? or ncbi_project_id=?");
ps.setString(1, project);
ps.setString(2, project);
rs = ps.executeQuery();
while (rs.next())
{
locusTagPrefixes.add(rs.getString(1));
}
return locusTagPrefixes;
} finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
}
}
@Override
public String isEcnumberValid(String ecNumber) throws SQLException
{
ResultSet rs = null;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement("select valid from cv_ec_numbers where ec_number=?");
ps.setString(1, ecNumber);
rs = ps.executeQuery();
if (rs.next())
{
return rs.getString(1);
}
else
return null;
} finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
}
}
@Override
public Entry
getEntryInfo( String primaryAcc) throws SQLException
{
Entry entry =(new EntryFactory()).createEntry();
ResultSet rs = null;
PreparedStatement ps = null;
boolean isValid=false;
try
{
ps = connection.prepareStatement("select entry_name,dataclass,keyword from dbentry "
+ "left outer join keywords on(dbentry.dbentryid=keywords.dbentryid ) where dbentry.primaryacc#=?");
ps.setString(1, primaryAcc);
rs = ps.executeQuery();
while(rs.next())
{
isValid=true;
entry.setSubmitterAccession(rs.getString("entry_name"));
entry.setDataClass(rs.getString("dataclass"));
entry.addKeyword(new Text(rs.getString("keyword")));
}
if(!isValid)
{
return null;
}
}finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
}
return entry;
}
@Override
public String getDbcode(String prefix) throws SQLException {
if(prefix==null)
return null;
String sql= "select dbcode from cv_database_prefix where prefix= ?";
ResultSet rs = null;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
ps.setString(1, prefix);
rs = ps.executeQuery();
if(rs.next())
{
return rs.getString(1);
}
}finally
{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
}
return null;
}
@Override
public boolean isChromosomeValid(String analysisId,String chromosomeName) throws SQLException
{
String sql = "select 1 from gcs_chromosome where assembly_id = ? and chromosome_name = ?";
try(PreparedStatement ps = connection.prepareStatement(sql))
{
ps.setString(1, analysisId);
ps.setString(2, chromosomeName);
ResultSet rs = ps.executeQuery();
if (!rs.next())
{
return false;
}
return true;
}
}
@Override
public String getNewProteinId() throws SQLException {
try (PreparedStatement pstsmt = connection.prepareStatement("select prefix_pkg.get_new_protein_id from dual");
ResultSet rs = pstsmt.executeQuery()) {
if (rs.next()) {
return rs.getString(1);
} else {
return null;
}
}
}
}
| 25.666667
| 148
| 0.708931
|
f40ddc08020fe4008f2ec5cb1c3fa74695966bc3
| 4,175
|
package com.volmit.react.util;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import com.volmit.react.Config;
import primal.bukkit.nms.Catalyst;
import primal.bukkit.nms.CatalystHost;
import primal.lang.collection.GList;
import primal.lang.collection.GMap;
public class TickListSplitter
{
private final World world;
private final Set<Object> master;
private final Set<Object> masterFluid;
private final CatalystHost host;
private final GMap<Object, Integer> withold;
private final GMap<Object, Integer> witholdFluid;
private final GMap<Material, Integer> witholdTypes;
private final GMap<Chunk, Integer> witholdChunks;
private final GMap<Chunk, Integer> witholdTicks;
private final RollingAverage avg;
private int globalThrottle;
public TickListSplitter(World world)
{
this.world = world;
host = Catalyst.host;
master = host.getTickList(world);
masterFluid = host.getTickListFluid(world);
witholdTypes = new GMap<>();
withold = new GMap<>();
witholdFluid = new GMap<>();
witholdChunks = new GMap<>();
witholdTicks = new GMap<>();
setGlobalThrottle(0);
avg = new RollingAverage(50);
}
public void tick()
{
throttleTick(master, withold);
throttleTick(masterFluid, witholdFluid);
computeGlobalTickLimiter();
dropTickChunks();
dumpWitheldTickList();
}
private void dropTickChunks()
{
for(Chunk i : witholdTicks.k())
{
witholdTicks.put(i, witholdTicks.get(i) - 1);
if(witholdTicks.get(i) <= 0)
{
witholdTicks.remove(i);
witholdChunks.remove(i);
}
}
}
public void withold(Chunk c, int cy)
{
if(cy > 0)
{
witholdChunks.put(c, cy);
}
else
{
unregister(c);
}
}
public void register(Material type, int ticks)
{
if(ticks > 0)
{
witholdTypes.put(type, ticks);
}
else
{
unregister(type);
}
}
public void dumpAll()
{
while(getWitheldCount() > 0)
{
dumpWitheldTickList();
}
}
private void throttleTick(Set<Object> master2, GMap<Object, Integer> withold)
{
for(Object i : new GList<>(master2))
{
Block b = host.getBlock(world, i);
Material t = b.getType();
if(witholdChunks.containsKey(b.getChunk()) && witholdTicks.containsKey(b.getChunk()) && witholdTicks.get(b.getChunk()) > 0)
{
withold.put(i, witholdChunks.get(b.getChunk()));
master2.remove(i);
}
else if(witholdTypes.containsKey(t))
{
withold.put(i, witholdTypes.get(t));
master2.remove(i);
}
else if(globalThrottle > 0)
{
withold.put(i, globalThrottle);
master2.remove(i);
}
}
}
private void computeGlobalTickLimiter()
{
avg.put(getTickCount());
if(avg.get() > Config.MAX_TICKS_PER_WORLD)
{
setGlobalThrottle((int) M.clip(globalThrottle + 1, 0, 20));
}
else
{
setGlobalThrottle((int) M.clip(globalThrottle - 1, 0, 20));
}
}
private void dumpWitheldTickList()
{
for(Object i : withold.k())
{
withold.put(i, withold.get(i) - 1);
if(withold.get(i) <= 0)
{
withold.remove(i, withold.get(i));
master.add(i);
}
}
for(Object i : witholdFluid.k())
{
witholdFluid.put(i, witholdFluid.get(i) - 1);
if(witholdFluid.get(i) <= 0)
{
witholdFluid.remove(i);
masterFluid.add(i);
}
}
}
public boolean throttle(Chunk chunk, int tickDelay, long time)
{
withold(chunk, tickDelay);
witholdTicks.put(chunk, (int) (time / 50));
return true;
}
public int getTickCount()
{
return master.size() + masterFluid.size();
}
public int getWitheldCount()
{
return withold.size() + witholdFluid.size();
}
public void setPhysicsSpeed(double d)
{
setGlobalThrottle((int) (M.clip(d, 0, 1D) * 20D));
}
public double getPhysicsSpeed()
{
return 1D - M.clip(globalThrottle, 0, 20D) / 20D;
}
public void unregisterAll()
{
witholdTypes.clear();
}
public void unregister(Material type)
{
witholdTypes.remove(type);
}
public void unregisterAllChunks()
{
witholdChunks.clear();
}
public void unregister(Chunk type)
{
witholdChunks.remove(type);
}
public void setGlobalThrottle(int throttle)
{
this.globalThrottle = throttle;
}
}
| 18.721973
| 126
| 0.674012
|
d11d58fcf6dfe074c77ef5eb4337825d374e048c
| 4,474
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.joshua.decoder.cky;
import static org.apache.joshua.decoder.cky.TestUtil.decodeList;
import static org.apache.joshua.decoder.cky.TestUtil.loadStringsFromFile;
import static org.testng.Assert.assertEquals;
import java.util.List;
import org.apache.joshua.decoder.Decoder;
import org.apache.joshua.decoder.JoshuaConfiguration;
import org.apache.joshua.util.io.KenLmTestUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class BnEnDecodingTest {
private JoshuaConfiguration joshuaConfig;
private Decoder decoder;
@AfterMethod
public void tearDown() throws Exception {
if(decoder != null) {
decoder.cleanUp();
decoder = null;
}
}
@Test
public void givenBnEnInput_whenPhraseDecoding_thenScoreAndTranslationCorrect() throws Exception {
// Given
List<String> inputStrings = loadStringsFromFile("src/test/resources/bn-en/hiero/input.bn");
// When
configureDecoder("src/test/resources/bn-en/hiero/joshua.config");
List<String> decodedStrings = decodeList(inputStrings, decoder, joshuaConfig);
// Then
List<String> goldStrings = loadStringsFromFile("src/test/resources/bn-en/hiero/output.gold");
assertEquals(decodedStrings, goldStrings);
}
@Test
public void givenBnEnInput_whenPhraseDecodingWithBerkeleyLM_thenScoreAndTranslationCorrect() throws Exception {
// Given
List<String> inputStrings = loadStringsFromFile("src/test/resources/bn-en/hiero/input.bn");
// When
configureDecoder("src/test/resources/bn-en/hiero/joshua-berkeleylm.config");
List<String> decodedStrings = decodeList(inputStrings, decoder, joshuaConfig);
// Then
List<String> goldStrings = loadStringsFromFile("src/test/resources/bn-en/hiero/output-berkeleylm.gold");
assertEquals(decodedStrings, goldStrings);
}
@Test
public void givenBnEnInput_whenPhraseDecodingWithClassLM_thenScoreAndTranslationCorrect() throws Exception {
// Given
List<String> inputStrings = loadStringsFromFile("src/test/resources/bn-en/hiero/input.bn");
// When
configureDecoder("src/test/resources/bn-en/hiero/joshua-classlm.config");
List<String> decodedStrings = decodeList(inputStrings, decoder, joshuaConfig);
// Then
List<String> goldStrings = loadStringsFromFile("src/test/resources/bn-en/hiero/output-classlm.gold");
assertEquals(decodedStrings, goldStrings);
}
@Test
public void givenBnEnInput_whenPhraseDecodingWithPackedGrammar_thenScoreAndTranslationCorrect() throws Exception {
// Given
List<String> inputStrings = loadStringsFromFile("src/test/resources/bn-en/packed/input.bn");
// When
configureDecoder("src/test/resources/bn-en/packed/joshua.config");
List<String> decodedStrings = decodeList(inputStrings, decoder, joshuaConfig);
// Then
List<String> goldStrings = loadStringsFromFile("src/test/resources/bn-en/packed/output.gold");
assertEquals(decodedStrings, goldStrings);
}
@Test
public void givenBnEnInput_whenPhraseDecodingWithSAMT_thenScoreAndTranslationCorrect() throws Exception {
// Given
List<String> inputStrings = loadStringsFromFile("src/test/resources/bn-en/samt/input.bn");
// When
configureDecoder("src/test/resources/bn-en/samt/joshua.config");
List<String> decodedStrings = decodeList(inputStrings, decoder, joshuaConfig);
// Then
List<String> goldStrings = loadStringsFromFile("src/test/resources/bn-en/samt/output.gold");
assertEquals(decodedStrings, goldStrings);
}
public void configureDecoder(String pathToConfig) throws Exception {
joshuaConfig = new JoshuaConfiguration();
joshuaConfig.readConfigFile(pathToConfig);
KenLmTestUtil.Guard(() -> decoder = new Decoder(joshuaConfig, ""));
}
}
| 36.672131
| 115
| 0.777604
|
e31c1e2d3a4926d90c17bf55c42c2bd9f4e5858c
| 4,486
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qihoo.qsql.org.apache.calcite.sql.dialect;
import com.qihoo.qsql.org.apache.calcite.config.NullCollation;
import com.qihoo.qsql.org.apache.calcite.sql.*;
import com.qihoo.qsql.org.apache.calcite.sql.fun.HiveSqlOperatorTable;
import com.qihoo.qsql.org.apache.calcite.sql.fun.SqlStdOperatorTable;
import com.qihoo.qsql.org.apache.calcite.sql.fun.SqlTrimFunction;
/**
* A <code>SqlDialect</code> implementation for the Apache Hive database.
*/
public class HiveSqlDialect extends SqlDialect {
public static final SqlDialect DEFAULT =
new HiveSqlDialect(EMPTY_CONTEXT
.withDatabaseProduct(DatabaseProduct.HIVE)
.withNullCollation(NullCollation.LOW));
private final boolean emulateNullDirection;
/** Creates a HiveSqlDialect. */
public HiveSqlDialect(Context context) {
super(context);
// Since 2.1.0, Hive natively supports "NULLS FIRST" and "NULLS LAST".
// See https://issues.apache.org/jira/browse/HIVE-12994.
emulateNullDirection = (context.databaseMajorVersion() < 2)
|| (context.databaseMajorVersion() == 2
&& context.databaseMinorVersion() < 1);
}
@Override protected boolean allowsAs() {
return false;
}
@Override public void unparseOffsetFetch(SqlWriter writer, SqlNode offset,
SqlNode fetch) {
unparseFetchUsingLimit(writer, offset, fetch);
}
@Override public SqlNode emulateNullDirection(SqlNode node,
boolean nullsFirst, boolean desc) {
if (emulateNullDirection) {
return emulateNullDirectionWithIsNull(node, nullsFirst, desc);
}
return null;
}
@Override public void unparseCall(final SqlWriter writer, final SqlCall call,
final int leftPrec, final int rightPrec) {
if (call.getOperator() == SqlStdOperatorTable.CONCAT) {
SqlUtil.unparseFunctionSyntax(HiveSqlOperatorTable.CONCAT, writer, call);
} else {
switch (call.getKind()) {
case POSITION:
final SqlWriter.Frame frame = writer.startFunCall("INSTR");
writer.sep(",");
call.operand(1).unparse(writer, leftPrec, rightPrec);
writer.sep(",");
call.operand(0).unparse(writer, leftPrec, rightPrec);
if (3 == call.operandCount()) {
throw new RuntimeException("3rd operand Not Supported for Function INSTR in Hive");
}
writer.endFunCall(frame);
break;
case MOD:
SqlOperator op = SqlStdOperatorTable.PERCENT_REMAINDER;
SqlSyntax.BINARY.unparse(writer, op, call, leftPrec, rightPrec);
break;
case TRIM:
unparseTrim(writer, call, leftPrec, rightPrec);
break;
default:
super.unparseCall(writer, call, leftPrec, rightPrec);
}
}
}
/**
* For usage of TRIM, LTRIM and RTRIM in Hive, see
* <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF">Hive UDF usage</a>.
*/
private void unparseTrim(SqlWriter writer, SqlCall call, int leftPrec,
int rightPrec) {
assert call.operand(0) instanceof SqlLiteral : call.operand(0);
SqlLiteral flag = call.operand(0);
final String operatorName;
switch (flag.getValueAs(SqlTrimFunction.Flag.class)) {
case LEADING:
operatorName = "LTRIM";
break;
case TRAILING:
operatorName = "RTRIM";
break;
default:
operatorName = call.getOperator().getName();
break;
}
final SqlWriter.Frame frame = writer.startFunCall(operatorName);
call.operand(2).unparse(writer, leftPrec, rightPrec);
writer.endFunCall(frame);
}
@Override public boolean supportsCharSet() {
return false;
}
}
// End HiveSqlDialect.java
| 35.888
| 102
| 0.693714
|
2c7f8d68c6f3abf15d6ecefd4ee1d6eccd4095f7
| 4,988
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** BatchFindAndReplace.java
* When given an input file and a mapping file (in tab separated value format) this program creates a new
* file with all the appropriate find and replace mappings done together in one batch simultaneously.
* If there is a sequence to be found that is a subset of another sequence, the longer sequences takes priority.
* It is particularly helpful when dealing with unicode text.
* <p>
* Warning: this class assumes all Unicode text has the same normalisation e.g. NFC.
* <p>
* Example usage (main method): java BatchFindAndReplace helloWorldInTimitAscii.txt timit2ipa_utf8nfc.txt
*
* @author Timothy Kempton
* @version 0.1
*/
/* in the future, this class may sort out normalisation itself once java 1.6
becomes more widespread */
public class BatchFindAndReplace {
/** Mapping from string keys to string values */
Map<String, String> rMap;
/** Create BatchFindAndReplace object from existing string to string mapping. */
public BatchFindAndReplace(Map<String,String> inMap) {
rMap = inMap;
}
/** Create BatchFindAndReplace object from TSV file. */
public BatchFindAndReplace(String mapFile) throws IOException {
BufferedReader tableFile = new BufferedReader(new FileReader(mapFile));
String thisLine = null;
String[] thisLineArray = null;
rMap = new LinkedHashMap<String, String>();// linked version to keep order and therefore any bugs deterministic
// otherwise could just be HashMap
// load tsv file into map
while ((thisLine = tableFile.readLine()) != null) {
thisLineArray = thisLine.split("\\t",2);
if (thisLineArray.length > 1) {
rMap.put(thisLineArray[0], thisLineArray[1]);
}
}
}
/** Finds the earliest occurring search string (as defined in the objects find/replace table) in the input string.
* If there are more than one match, this method returns the longest string.*/
public String earliestLongestMatch(String in,int fromIndex){
Set<String> findSet = rMap.keySet();
int minStart = in.length();
//search for all words and get initial positions
for(String f:findSet){
if (f.equals(""))
System.err.println("Warning: found empty search string; ignoring a search/replace pair "+rMap.get(f));
else {
int s = in.indexOf(f,fromIndex);
if (s > -1) minStart=Math.min(minStart,s);
//System.out.println("word="+f+" index="+s);
}
}
// find earliest word(s)
// efficiency potential: no need for this second loop if first loop
// was more clever with a Map<Integer,List<String>>
// structure that stored indexes and associated words
List<String> commonStartWords = new LinkedList<String>();
for(String f:findSet){
if (in.indexOf(f,fromIndex)==minStart) commonStartWords.add(f);
}
//System.out.println("earliest word found at "+minStart+":"+commonStartWords);
//now find the longest word (if more than one word with common starting point)
String longestStr = "";
int lengthMax = 0;
for(String c:commonStartWords){
if (c.length()>lengthMax) {
longestStr=c;
lengthMax=c.length();
}
}
//System.out.println("longest word found:"+longestStr);
return longestStr;
}
/** Performs a batch search and replace (all) process on the input string. */
public String processString(String in) {
String out="";
int beginning = 0;
int newBeginning = 0;
int matchStart = 0;
while (beginning<in.length()) {
String match=earliestLongestMatch(in,beginning);
if (match.length()>0) { // if there is a match
//matchStart = in.indexOf(match);
matchStart = in.indexOf(match,beginning);
//System.out.println("before substring: beginning="+beginning+" matchStart="+matchStart);
out=out+in.substring(beginning, matchStart);
out=out+rMap.get(match);
newBeginning=matchStart+match.length();
}
else { // if there are no more matches
out=out+in.substring(beginning);
newBeginning=in.length();
}
//System.out.println("processString: beginning="+beginning+" matchStart="+matchStart+" match="+match+" out="+out+" newBeginning="+newBeginning);
beginning=newBeginning;
}
return out;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "BatchFindAndReplace [rMap=" + rMap + "]";
}
/** First parameter is the text file and the second parameter is the mapping file */
public static void main(String[] args) throws IOException {
String textFile = args[0];
String replaceTsvFile = args[1];
BatchFindAndReplace p = new BatchFindAndReplace(replaceTsvFile);
BufferedReader textReader = new BufferedReader(new FileReader(textFile));
String thisLine = "";
while ((thisLine = textReader.readLine()) != null) {
System.out.println(p.processString(thisLine));
}
}
}
| 37.503759
| 147
| 0.710305
|
8c8ac695a470bca32526af53a42ae1be7c7aa22f
| 1,578
|
package jp.ac.nii.prl.mape.redundancy.service;
import java.util.Collection;
import java.util.Optional;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jp.ac.nii.prl.mape.redundancy.model.Instance;
import jp.ac.nii.prl.mape.redundancy.model.RedundancyView;
import jp.ac.nii.prl.mape.redundancy.repository.InstanceRepository;
@Service("instanceService")
public class InstanceServiceImpl implements InstanceService {
@Autowired
private InstanceRepository instanceRepository;
/* (non-Javadoc)
* @see jp.ac.nii.prl.mape.redundancy.service.InstanceService#save(jp.ac.nii.prl.mape.redundancy.model.Instance)
*/
@Override
public void save(Instance instance) {
instanceRepository.save(instance);
}
/* (non-Javadoc)
* @see jp.ac.nii.prl.mape.redundancy.service.InstanceService#findOne(java.lang.Long)
*/
@Override
public Optional<Instance> findOne(Long instanceId) {
return Optional.ofNullable(instanceRepository.findOne(instanceId));
}
@Override
public Collection<Instance> findByRedundancyViewId(Long redundancyViewId) {
return instanceRepository.findByRedundancyViewId(redundancyViewId);
}
@Override
public Instance createNewInstance(RedundancyView redundancyView) {
Instance instance = new Instance();
instance.setInstID(UUID.randomUUID().toString());
instance.setRedundancyView(redundancyView);
instance.setStatus(1);
return instance;
}
@Override
public Collection<Instance> findAll() {
return instanceRepository.findAll();
}
}
| 27.684211
| 113
| 0.787706
|
1e513f7a86fd72f62e9cb000921e1a8719f0b83b
| 1,532
|
class rMOcK {
}
class iJ0QaWj {
public int[][][][] Zo;
public jBlER g8rWR1z;
public boolean[][][][][] f () throws E3_HcIS7t {
-637.Nk5xo8Z;
--ON55.sgAH_OD1bx();
void T = null.CuFCJqzs7Yl8 = ( ( !true[ new rO5Sx().dYr1Nd46]).dBJ())[ !-this.LyOR()];
if ( null[ !this.KR()]) return;else return;
int[] ZfGmQ;
while ( 68319.I2Jknbk8()) ;
}
public uO1v5tjaG2Z[] nI0ifxK (FdyVikCHF3[][] LfmMygTcKg, nBQysQMNb Mm4LShLlqmb, boolean KaURGNHlLRa, int[][] ku, mlQ4[][][][][][] TT, boolean[] LStyHRK6QlKiI4) throws roasJ {
void y;
btSE[] lv_GoLE;
if ( !( --new jHKPU_5()._ihQ1GLpXkV()).NW0k9dxQab()) while ( false.NXnZ()) !this.Tyn();
void[] Zkqi38 = this[ !-this.Vj9ml];
;
while ( -0.QRZQsPRrbqF()) if ( -new boolean[ b.xlUsydiw4].QZ7sVKSX4DCtw()) if ( -!--true[ -( AVM9hfLHav.fL97xH0ST_WE_).Ao4RB4Ot91Zk]) ;
int[] crld49O2b0o = false.nxX();
return;
-true[ !Ckn1dm6WFc.btYL0c6HK()];
;
}
public static void gYNTSfK (String[] umNdF77yk) {
while ( !!!this.U5L9X) Li5Y().eGUw2RB5r();
cfCWVVT9TE QwUb6FuHtpjNz = ( !--false.jH_zujBQA()).J4v0V = 2011.jB_pt();
void[] YzVvNHQkuM9Nk;
int[] YqWhYMe;
;
;
;
while ( !!( -!ENQhBYV()[ new boolean[ -!!false[ -new nTUQVOUSFe().Aaz()]]._e1SConOEtm()]).zv()) {
f[] xDfkMR;
}
boolean TkqcAwCVCbXDc1 = 0346.YGyCghZERx8;
}
}
class z0Fu5NsV0Wq {
}
| 33.304348
| 178
| 0.541775
|
d0a0f9696773131776924943e09c4e6e0397fe33
| 560
|
package com.jeanboy.app.training.ui.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.jeanboy.app.training.R;
import com.jeanboy.app.training.base.BaseActivity;
public class ScreenConfigActivity extends BaseActivity {
@Override
protected String getTAG() {
return ScreenConfigActivity.class.getSimpleName();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_config);
}
}
| 25.454545
| 58
| 0.753571
|
4b7f71043607d429ee801c17eed8000179fc79be
| 361
|
package ru.job4j.trainee.part002.tracker.actions;
import ru.job4j.trainee.part002.tracker.Input;
import ru.job4j.trainee.part002.tracker.Store;
public class Exit implements UserAction {
@Override
public String name() {
return "Выход";
}
@Override
public boolean execute(Input input, Store tracker) {
return false;
}
}
| 21.235294
| 56
| 0.695291
|
9151f3a781059ac0c88e0c00ddfca53ce62e7835
| 8,022
|
package net.a6te.lazycoder.weatherapp.mvp.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class WeatherData {
@SerializedName("message")
@Expose
private String message;
@SerializedName("cod")
@Expose
private String cod;
@SerializedName("count")
@Expose
private Integer count;
@SerializedName("list")
@Expose
private java.util.List<List> list = null;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCod() {
return cod;
}
public void setCod(String cod) {
this.cod = cod;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public java.util.List<List> getList() {
return list;
}
public void setList(java.util.List<List> list) {
this.list = list;
}
public class Clouds {
@SerializedName("all")
@Expose
private Integer all;
public Integer getAll() {
return all;
}
public void setAll(Integer all) {
this.all = all;
}
}
public class Coord {
@SerializedName("lat")
@Expose
private Double lat;
@SerializedName("lon")
@Expose
private Double lon;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
}
public class List {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("coord")
@Expose
private Coord coord;
@SerializedName("main")
@Expose
private Main main;
@SerializedName("dt")
@Expose
private Integer dt;
@SerializedName("wind")
@Expose
private Wind wind;
@SerializedName("sys")
@Expose
private Sys sys;
@SerializedName("rain")
@Expose
private Object rain;
@SerializedName("snow")
@Expose
private Object snow;
@SerializedName("clouds")
@Expose
private Clouds clouds;
@SerializedName("weather")
@Expose
private java.util.List<Weather> weather = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public Object getRain() {
return rain;
}
public void setRain(Object rain) {
this.rain = rain;
}
public Object getSnow() {
return snow;
}
public void setSnow(Object snow) {
this.snow = snow;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public java.util.List<Weather> getWeather() {
return weather;
}
public void setWeather(java.util.List<Weather> weather) {
this.weather = weather;
}
}
public class Main {
@SerializedName("temp")
@Expose
private Double temp;
@SerializedName("pressure")
@Expose
private Double pressure;
@SerializedName("humidity")
@Expose
private Integer humidity;
@SerializedName("temp_min")
@Expose
private Double tempMin;
@SerializedName("temp_max")
@Expose
private Double tempMax;
@SerializedName("sea_level")
@Expose
private Double seaLevel;
@SerializedName("grnd_level")
@Expose
private Double grndLevel;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getPressure() {
return pressure;
}
public void setPressure(Double pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Double getTempMin() {
return tempMin;
}
public void setTempMin(Double tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
public Double getSeaLevel() {
return seaLevel;
}
public void setSeaLevel(Double seaLevel) {
this.seaLevel = seaLevel;
}
public Double getGrndLevel() {
return grndLevel;
}
public void setGrndLevel(Double grndLevel) {
this.grndLevel = grndLevel;
}
}
public class Sys {
@SerializedName("country")
@Expose
private String country;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
public class Weather {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("main")
@Expose
private String main;
@SerializedName("description")
@Expose
private String description;
@SerializedName("icon")
@Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
public class Wind {
@SerializedName("speed")
@Expose
private Double speed;
@SerializedName("deg")
@Expose
private Double deg;
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public Double getDeg() {
return deg;
}
public void setDeg(Double deg) {
this.deg = deg;
}
}
}
| 20.155779
| 65
| 0.507604
|
308a28372b0c2439691dff3270f9d9df77b3a1c6
| 3,040
|
package au.gov.qld.fire.jms;
import java.util.Hashtable;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.sql.DataSource;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class JndiTest extends TestCase
{
public JndiTest()
{
super();
}
public JndiTest(String name)
{
super(name);
}
//http://www.informit.com/articles/article.aspx?p=384904
//[ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=jdbc/DataSource_jms' to JNDI name 'java:jdbc/DataSource_jms'
public void testJBossJndi() throws Exception
{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
env.put(Context.PROVIDER_URL, "localhost");
//env.put(Context.PROVIDER_URL, "jnp://localhost:1099");
env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
//env.put(Context.SECURITY_AUTHENTICATION, "simple");
//env.put(Context.SECURITY_PRINCIPAL, "cn=Directory Manager");
//env.put(Context.SECURITY_CREDENTIALS, "password");
Context initCtx = new InitialContext(env);
try
{
Context envCtx = (Context) initCtx.lookup("java:"); //:comp/env
NamingEnumeration<Binding> bindings = envCtx.listBindings("");
while (bindings.hasMore())
{
Binding binding = bindings.next();
assertNotNull(binding);
}
Object bean = (Object) envCtx.lookup("jdbc/DataSource_jms");
assertNotNull(bean);
}
finally
{
initCtx.close();
}
}
public void testWeblogicJndi() throws Exception
{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7001");
//env.put(Context.SECURITY_AUTHENTICATION, "simple");
//env.put(Context.SECURITY_PRINCIPAL, "cn=Directory Manager");
//env.put(Context.SECURITY_CREDENTIALS, "password");
Context initCtx = new InitialContext(env);
try
{
DataSource bean = (DataSource) initCtx.lookup("jndi/jms");
assertNotNull(bean);
}
finally
{
initCtx.close();
}
}
/**
* Main test suite.
* @return Test suite.
*/
public static Test suite() throws Exception
{
TestSuite suite = new TestSuite();
suite.addTest(new JndiTest("testJBossJndi"));
//suite.addTest(new JndiTest("testWeblogicJndi"));
return suite;
}
}
| 33.043478
| 167
| 0.611842
|
8760615405545663bac04bb39d35458e80dcc45d
| 5,257
|
///###////////////////////////////////////////////////////////////////////////
//
// Burton Computer Corporation
// http://www.burton-computer.com
//
// Copyright (c) 2021, Burton Computer Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the Burton Computer Corporation nor the names
// of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.javimmutable.collections.common;
import org.javimmutable.collections.IterableStreamable;
import org.javimmutable.collections.JImmutableMap;
import org.javimmutable.collections.MapEntry;
import org.javimmutable.collections.iterators.TransformStreamable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.util.Map;
import java.util.function.BiPredicate;
@Immutable
public abstract class AbstractJImmutableMap<K, V>
implements JImmutableMap<K, V>
{
@Nullable
@Override
public V get(K key)
{
return getValueOr(key, null);
}
/**
* Adds the key/value pair to this map. Any value already existing for the specified key
* is replaced with the new value.
*/
@Override
@Nonnull
public JImmutableMap<K, V> insert(@Nonnull Entry<? extends K, ? extends V> e)
{
return assign(e.getKey(), e.getValue());
}
@Nonnull
@Override
public JImmutableMap<K, V> getInsertableSelf()
{
return this;
}
@Nonnull
@Override
public JImmutableMap<K, V> assignAll(@Nonnull JImmutableMap<? extends K, ? extends V> map)
{
return map.reduce((JImmutableMap<K, V>)this, (m, k, v) -> m = m.assign(k, v));
}
@Nonnull
@Override
public JImmutableMap<K, V> assignAll(@Nonnull Map<? extends K, ? extends V> map)
{
JImmutableMap<K, V> answer = this;
for (Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
answer = answer.assign(e.getKey(), e.getValue());
}
return answer;
}
@Override
public boolean isEmpty()
{
return size() == 0;
}
@Override
public boolean isNonEmpty()
{
return size() != 0;
}
@Nonnull
@Override
public Map<K, V> getMap()
{
return MapAdaptor.of(this);
}
@Nonnull
@Override
public IterableStreamable<K> keys()
{
return TransformStreamable.ofKeys(this);
}
@Nonnull
@Override
public IterableStreamable<V> values()
{
return TransformStreamable.ofValues(this);
}
@Override
public int hashCode()
{
return getMap().hashCode();
}
@Override
public boolean equals(Object o)
{
if (o == this) {
return true;
} else if (o instanceof JImmutableMap) {
return getMap().equals(((JImmutableMap)o).getMap());
} else {
return (o instanceof Map) && getMap().equals(o);
}
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("{");
forEach((k, v) -> {
if (sb.length() > 1) {
sb.append(", ");
}
MapEntry.addToString(sb, k, v);
});
sb.append("}");
return sb.toString();
}
public int getSpliteratorCharacteristics()
{
return StreamConstants.SPLITERATOR_UNORDERED;
}
@Nonnull
@Override
public JImmutableMap<K, V> select(@Nonnull BiPredicate<K, V> predicate)
{
return reduce(deleteAll().mapBuilder(), (b, k, v) -> predicate.test(k, v) ? b.add(k, v) : b).build();
}
@Nonnull
@Override
public JImmutableMap<K, V> reject(@Nonnull BiPredicate<K, V> predicate)
{
return reduce((JImmutableMap<K, V>)this, (m, k, v) -> predicate.test(k, v) ? m.delete(k) : m);
}
}
| 29.044199
| 109
| 0.637055
|
9e02713b0c4837eb68cb95ad93be16f36284605c
| 224
|
package config;
/**
* @Author: zr
* @Description:
* @Date: 14:16 2019/8/27
* @Modified by:
*/
public enum Time {
YEAR,
MONTH,
DAY,
HOUR,
MINUTE,
SECOND,
MILLISECONDS;
Time() {
}
}
| 10.181818
| 25
| 0.513393
|
af4431f8ea2386f51979f841658c214bacc00129
| 1,273
|
package fr.kraiss.scratch.gist;
import java.io.File;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
* @author Pierrick Rassat
* @see https://github.com/kraiss
*/
public class JarManifestPrinter {
public static void printJarManifestAttributes() throws IOException {
// Get jarfile url
String jarUrl = JarManifestPrinter.class.getProtectionDomain().getCodeSource().getLocation().getFile();
// Get the manifest from the jarfile
File file = new File(jarUrl);
JarFile jar = new JarFile(file);
Manifest manifest = jar.getManifest();
Attributes attributes = manifest.getMainAttributes();
// Print manifest 'standard' attributes
System.out.println("Manifest Attributes:");
System.out.println("Vendor : " + attributes.getValue("Implementation-Vendor"));
System.out.println("Title : " + attributes.getValue("Implementation-Title"));
System.out.println("Version : " + attributes.getValue("Implementation-Version"));
System.out.println("Build date : " + attributes.getValue("Built-Date"));
System.out.println("Build by : " + attributes.getValue("Built-By"));
}
}
| 37.441176
| 111
| 0.677926
|
b3f3cedd15ba8bc28a130e57cc00f866c20f81c9
| 26,595
|
package com.goertek.watchface.dataprovider.sportshealth.controller;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.RemoteException;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.goertek.commonlib.provider.data.model.IntRangeValue;
import com.goertek.commonlib.utils.LogUtil;
import com.goertek.watchface.dataprovider.sportshealth.bean.CalorieDataBean;
import com.goertek.watchface.dataprovider.sportshealth.bean.HeartRateDataBean;
import com.goertek.watchface.dataprovider.sportshealth.bean.ParseUtil;
import com.goertek.watchface.dataprovider.sportshealth.bean.SportTimeDataBean;
import com.goertek.watchface.dataprovider.sportshealth.bean.StandDataBean;
import com.goertek.watchface.dataprovider.sportshealth.bean.StepDataBean;
import java.util.Map;
/**
* 功能说明
*
* @author: ww
* @version: 1.0.0
* @since: 2019/07/08
*/
public class SportsHealthController {
private static final String APPLICATION_ID_HEALTH = "com.huawei.health";
private static final int CALORIES_MAX_DEFAULT_VAULE = 334;
private static final int CURR = 3;
private static final int DELAY_REGISTER_TIME = 200;
private static final int HEAT_RATE_NUM = 5;
private static final int MIN_SPORTS_NUM = 0;
private static final String NODATA_STR = "--";
private static final String NO_VALUE_STR = "-1";
private static final int SERVICE_PROAD_TIME = 5000;
private static final String TAG = "SportsHealthController";
private static SportsHealthController instance;
private Handler handler = new Handler();
private boolean isConnectSuccess = false;
private CalorieDataBean mCalorieBean;
private int mCalorieMaxVaule;
private Context mContext;
private HeartRateDataBean mHeartBean;
private SportTimeDataBean mSportTimeBean;
private StandDataBean mStandBean;
private StepDataBean mStepDataBean;
private SportsHealthController() {
}
@NonNull
private String getHeatRateString(String valueType) {
return (!TextUtils.isEmpty(valueType) && !TextUtils.equals("-1", valueType)) ? valueType : "--";
}
public static SportsHealthController getInstance() {
synchronized (SportsHealthController.class) {
if (instance == null) {
instance = new SportsHealthController();
}
return instance;
}
}
private int getIntValue(String valueType) {
try {
int intValue = Integer.parseInt(valueType);
return intValue;
} catch (NumberFormatException var3) {
LogUtil.e("SportsHealthController", "method getIntValue() catch NumberFormatException");
return 0;
}
}
private int getStepValue(int min, int max, int value, int step) {
float steps = (float) (max - min) / (float) step;
StringBuilder var6 = new StringBuilder();
var6.append("step=== ");
var6.append(steps);
LogUtil.d("SportsHealthController", var6.toString());
for (min = 0; min <= step && (float) value > (float) min * steps; ++min) {
}
var6 = new StringBuilder();
var6.append("index ===");
var6.append(min);
LogUtil.d("SportsHealthController", var6.toString());
return min;
}
private String getTestCurrAndTarget() {
return "--/--";
}
private String getTestCurrStr() {
return "50";
}
private int getTestCurrentIntData() {
return 50;
}
private IntRangeValue getTestRangeData() {
return new IntRangeValue(50, 100, 0);
}
private String getValueFromMap(Map var1, String var2) {
if (var1 == null) {
return "0";
} else {
Object var3 = var1.get(var2);
return var3 != null && var3 instanceof String ? (String) var3 : "0";
}
}
private boolean isNnmber(String var1) {
try {
Integer.valueOf(var1);
return true;
} catch (NumberFormatException var2) {
return false;
}
}
private void logExceptionName(String var1, String var2) {
StringBuilder var3 = new StringBuilder();
var3.append(var1);
var3.append(" has catch ");
var3.append(var2);
LogUtil.e("SportsHealthController", var3.toString());
}
private int parseString2Int(String var1) {
if (!TextUtils.isEmpty(var1) && !var1.equals("null")) {
if (TextUtils.equals("-1", var1)) {
return 0;
} else {
try {
int var2 = Integer.parseInt(var1);
return var2;
} catch (NumberFormatException var3) {
this.logExceptionName("parseString2Int", "NumberFormatException");
return 0;
}
}
} else {
return 0;
}
}
private void setCurrentHeartRate(String var1) {
if (this.mHeartBean == null) {
this.mHeartBean = new HeartRateDataBean();
}
this.mHeartBean.setCurrentHeartRate(var1);
if (TextUtils.equals("-1", var1)) {
this.mHeartBean.setMaxHeartRate("--");
this.mHeartBean.setMinHeartRate("--");
this.mHeartBean.setRestHeartRate("--");
this.mHeartBean.setCurrentHeartRate("--");
}
}
private void setHeartRate(String heartRate) {
if (this.mHeartBean == null) {
this.mHeartBean = new HeartRateDataBean();
}
this.mHeartBean.setCurrentHeartRate(heartRate);
this.mHeartBean.setMaxHeartRate(heartRate);
this.mHeartBean.setMinHeartRate(heartRate);
this.mHeartBean.setRestHeartRate(heartRate);
}
public IntRangeValue getCalorieRange() {
IntRangeValue intRangeValue = this.getTestRangeData();
/*CalorieDataBean var3 = this.mCalorieBean;
if (var3 != null) {
return new IntRangeValue(this.parseString2Int(var3.getCurrentCalorie()), this.mCalorieMaxVaule, 0);
} else {
label47: {
label52: {
int var1;
boolean var10001;
try {
var1 = HWWearableClientAPI.getInstance().getCaloriesInfo();
this.mCalorieBean = new CalorieDataBean();
this.mCalorieBean.setCurrentCalorie(String.valueOf(var1));
} catch (NoBinderException var10) {
var10001 = false;
break label47;
} catch (RemoteException var11) {
var10001 = false;
break label52;
}
if (var1 > 334) {
try {
this.mCalorieBean.setTargetCalorie(String.valueOf(var1));
} catch (NoBinderException var8) {
var10001 = false;
break label47;
} catch (RemoteException var9) {
var10001 = false;
break label52;
}
} else {
try {
this.mCalorieBean.setTargetCalorie(String.valueOf(334));
} catch (NoBinderException var6) {
var10001 = false;
break label47;
} catch (RemoteException var7) {
var10001 = false;
break label52;
}
}
try {
IntRangeValue var12 = new IntRangeValue(this.parseString2Int(this.mCalorieBean.getCurrentCalorie()), this.parseString2Int(this.mCalorieBean.getTargetCalorie()), 0);
return var12;
} catch (NoBinderException var4) {
var10001 = false;
break label47;
} catch (RemoteException var5) {
var10001 = false;
}
}
this.logExceptionName("getCalorieRange", "RemoteException");
return var2;
}
this.logExceptionName("getCalorieRange", "NoBinderException");*/
return intRangeValue;
}
public int getCurrentHeatRateStep() {
IntRangeValue intRangeValue = this.getHeatRange();
if (intRangeValue != null) {
int max = intRangeValue.getmMax();
int min = intRangeValue.getmMin();
int value = intRangeValue.getmValue();
if (max != 0) {
return this.getStepValue(min, max, value, 5);
} else {
LogUtil.d("SportsHealthController", "max is 0");
return 0;
}
} else {
LogUtil.d("SportsHealthController", "getHeatRange is null");
return 0;
}
}
public String getHealthCalorieCurrent() {
String testCurrStr = this.getTestCurrStr();
/*CalorieDataBean var3 = this.mCalorieBean;
if (var3 != null) {
return var3.getCurrentCalorie();
} else {
try {
int var1 = HWWearableClientAPI.getInstance().getCaloriesInfo();
this.mCalorieBean = new CalorieDataBean();
this.mCalorieBean.setCurrentCalorie(String.valueOf(var1));
String var6 = this.mCalorieBean.getCurrentCalorie();
return var6;
} catch (NoBinderException var4) {
this.logExceptionName("getHealthCalorieCurrent", "NoBinderException");
return var2;
} catch (RemoteException var5) {
this.logExceptionName("getHealthCalorieCurrent", "RemoteException");
return var2;
}
}*/
return testCurrStr;
}
public int getHealthCalorieCurrentInt() {
int currentIntData = this.getTestCurrentIntData();
/* String var3 = this.getHealthCalorieCurrent();
int var1 = var2;
if (!TextUtils.isEmpty(var3)) {
var1 = var2;
if (!TextUtils.equals("--", var3)) {
var1 = this.getIntValue(var3);
}
}*/
return currentIntData;
}
public String getHealthCalorieCurrentWithUnit() {
String calorieCurrent = this.getHealthCalorieCurrent();
/*if (TextUtils.isEmpty(var1)) {
StringBuilder var3 = new StringBuilder();
var3.append("0");
var3.append(this.mContext.getString(2131755044));
return var3.toString();
} else {
StringBuilder var2 = new StringBuilder();
var2.append(var1);
var2.append(this.mContext.getString(2131755044));
return var2.toString();
}*/
return calorieCurrent;
}
public String getHealthClimCurrent() {
return this.getTestCurrStr();
}
public int getHealthClimCurrentInt() {
return this.getTestCurrentIntData();
}
public IntRangeValue getHealthClimRange() {
return this.getTestRangeData();
}
public String getHealthHeartRateCurrent() {
String currStr = this.getTestCurrStr();
/*HeartRateDataBean var2 = this.mHeartBean;
if (var2 != null) {
var1 = var2.getCurrentHeartRate();
}
*/
return this.getHeatRateString(currStr);
}
public int getHealthHeartRateCurrentInt() {
int currentIntData = this.getTestCurrentIntData();
/*String var3 = this.getHealthHeartRateCurrent();
int var1 = var2;
if (!TextUtils.isEmpty(var3)) {
var1 = var2;
if (!TextUtils.equals("--", var3)) {
var1 = this.getIntValue(var3);
}
}*/
return currentIntData;
}
public String getHealthHeartRateMax() {
String currStr = this.getTestCurrStr();
HeartRateDataBean var2 = this.mHeartBean;
/* if (var2 != null) {
currStr = var2.getMaxHeartRate();
}*/
return this.getHeatRateString(currStr);
}
public String getHealthHeartRateMin() {
String currStr = this.getTestCurrStr();
/* HeartRateDataBean var2 = this.mHeartBean;
if (var2 != null) {
var1 = var2.getMinHeartRate();
}*/
return this.getHeatRateString(currStr);
}
public String getHealthSportTime() {
String currAndTarget = this.getTestCurrAndTarget();
/*if (this.mSportTimeBean != null) {
StringBuilder var5 = new StringBuilder(0);
var5.append(this.mSportTimeBean.getCurrentSportTime());
var5.append("/");
var5.append(this.mSportTimeBean.getTargetSportTime());
return var5.toString();
} else {
try {
this.mSportTimeBean = ParseUtil.parseMapToSportTimeDataBean(HWWearableClientAPI.getInstance().getIntensityInfo());
StringBuilder var2 = new StringBuilder(0);
var2.append(this.mSportTimeBean.getCurrentSportTime());
var2.append("/");
var2.append(this.mSportTimeBean.getTargetSportTime());
String var6 = var2.toString();
return var6;
} catch (NoBinderException var3) {
this.logExceptionName("getHealthSportTime", "NoBinderException");
return var1;
} catch (RemoteException var4) {
this.logExceptionName("getHealthSportTime", "RemoteException");
return var1;
}
}*/
return currAndTarget;
}
public String getHealthSportTimeCurrent() {
String currStr = this.getTestCurrStr();
/*SportTimeDataBean var2 = this.mSportTimeBean;
if (var2 != null) {
return var2.getCurrentSportTime();
} else {
try {
this.mSportTimeBean = ParseUtil.parseMapToSportTimeDataBean(HWWearableClientAPI.getInstance().getIntensityInfo());
String var5 = this.mSportTimeBean.getCurrentSportTime();
return var5;
} catch (NoBinderException var3) {
this.logExceptionName("getHealthSportTimeCurrent", "NoBinderException");
return currStr;
} catch (RemoteException var4) {
this.logExceptionName("getHealthSportTimeCurrent", "RemoteException");
return currStr;
}
}*/
return currStr;
}
public int getHealthSportTimeCurrentInt() {
int currentIntData = this.getTestCurrentIntData();
/*String var3 = this.getHealthSportTimeCurrent();
int var1 = currentIntData;
if (!TextUtils.isEmpty(var3)) {
var1 = currentIntData;
if (!TextUtils.equals("--", var3)) {
var1 = this.getIntValue(var3);
}
}*/
return currentIntData;
}
public String getHealthStandCurrent() {
String currStr = this.getTestCurrStr();
/*StandDataBean var2 = this.mStandBean;
if (var2 != null) {
return var2.getCurrentStand();
} else {
try {
this.mStandBean = ParseUtil.parseMapToStandDataBean(HWWearableClientAPI.getInstance().getStandNumberInfo());
String var5 = this.mStandBean.getCurrentStand();
return var5;
} catch (NoBinderException var3) {
this.logExceptionName("getHealthStandCurrent", "NoBinderException");
return currStr;
} catch (RemoteException var4) {
this.logExceptionName("getHealthStandCurrent", "RemoteException");
return currStr;
}
}*/
return currStr;
}
public int getHealthStandCurrentInt() {
int currentIntData = this.getTestCurrentIntData();
/*String var3 = this.getHealthStandCurrent();
int var1 = currentIntData;
if (!TextUtils.isEmpty(var3)) {
var1 = currentIntData;
if (!TextUtils.equals("--", var3)) {
var1 = this.getIntValue(var3);
}
}*/
return currentIntData;
}
public String getHealthStep() {
String currAndTarget = this.getTestCurrAndTarget();
/*StringBuilder var2 = new StringBuilder(0);
StepDataBean var3 = this.mStepDataBean;
if (var3 != null) {
var2.append(var3.getCurrentStep());
var2.append("/");
var2.append(this.mStepDataBean.getTargetStep());
return var2.toString();
} else {
try {
this.mStepDataBean = ParseUtil.parseMapToStepDataBean(HWWearableClientAPI.getInstance().getStepNumberInfo());
var2.append(this.mStepDataBean.getCurrentStep());
var2.append("/");
var2.append(this.mStepDataBean.getTargetStep());
String var6 = var2.toString();
return var6;
} catch (NoBinderException var4) {
this.logExceptionName("getHealthStep", "NoBinderException");
return currAndTarget;
} catch (RemoteException var5) {
this.logExceptionName("getHealthStep", "RemoteException");
return currAndTarget;
}
}*/
return currAndTarget;
}
public String getHealthStepCurrent() {
String testCurrStr = this.getTestCurrStr();
/*StepDataBean var2 = this.mStepDataBean;
if (var2 != null) {
return var2.getCurrentStep();
} else {
try {
this.mStepDataBean = ParseUtil.parseMapToStepDataBean(HWWearableClientAPI.getInstance().getStepNumberInfo());
String var5 = this.mStepDataBean.getCurrentStep();
return var5;
} catch (NoBinderException var3) {
this.logExceptionName("getHealthStepCurrent", "NoBinderException");
return testCurrStr;
} catch (RemoteException var4) {
this.logExceptionName("getHealthStepCurrent", "RemoteException");
return testCurrStr;
}
}*/
return testCurrStr;
}
public int getHealthStepCurrentInt() {
int currentIntData = this.getTestCurrentIntData();
/*String var3 = this.getHealthStepCurrent();
int var1 = currentIntData;
if (!TextUtils.isEmpty(var3)) {
var1 = currentIntData;
if (!TextUtils.equals("--", var3)) {
var1 = this.getIntValue(var3);
}
}
*/
return currentIntData;
}
public String getHealthStepCurrentWithUnit() {
String healthStepCurrent = this.getHealthStepCurrent();
/*if (TextUtils.isEmpty(healthStepCurrent)) {
StringBuilder var3 = new StringBuilder();
var3.append("0");
var3.append(this.mContext.getString(2131755148));
return var3.toString();
} else {
StringBuilder var2 = new StringBuilder();
var2.append(healthStepCurrent);
var2.append(this.mContext.getString(2131755148));
return var2.toString();
}*/
return healthStepCurrent;
}
public IntRangeValue getHeatRange() {
IntRangeValue rangeData = this.getTestRangeData();
/* HeartRateDataBean var2 = this.mHeartBean;
if (var2 != null) {
rangeData = new IntRangeValue(this.parseString2Int(var2.getCurrentHeartRate()), this.parseString2Int(this.mHeartBean.getMaxHeartRate()), this.parseString2Int(this.mHeartBean.getMinHeartRate()));
}*/
return rangeData;
}
public IntRangeValue getSportTimeRange() {
IntRangeValue rangeData = this.getTestRangeData();
/*SportTimeDataBean var2 = this.mSportTimeBean;
if (var2 != null) {
return new IntRangeValue(this.parseString2Int(var2.getCurrentSportTime()), this.parseString2Int(this.mSportTimeBean.getTargetSportTime()), 0);
} else {
try {
this.mSportTimeBean = ParseUtil.parseMapToSportTimeDataBean(HWWearableClientAPI.getInstance().getIntensityInfo());
IntRangeValue var5 = new IntRangeValue(this.parseString2Int(this.mSportTimeBean.getCurrentSportTime()), this.parseString2Int(this.mSportTimeBean.getTargetSportTime()), 0);
return var5;
} catch (NoBinderException var3) {
this.logExceptionName("getSportTimeRange", "NoBinderException");
return rangeData;
} catch (RemoteException var4) {
this.logExceptionName("getSportTimeRange", "RemoteException");
return rangeData;
}
}*/
return rangeData;
}
public String getStandNumber() {
String currAndTarget = this.getTestCurrAndTarget();
/*if (this.mStandBean != null) {
StringBuilder var5 = new StringBuilder(0);
var5.append(this.mStandBean.getCurrentStand());
var5.append("/");
var5.append(this.mStandBean.getTargetStand());
return var5.toString();
} else {
try {
this.mStandBean = ParseUtil.parseMapToStandDataBean(HWWearableClientAPI.getInstance().getStandNumberInfo());
StringBuilder var2 = new StringBuilder(0);
var2.append(this.mStandBean.getCurrentStand());
var2.append("/");
var2.append(this.mStandBean.getTargetStand());
String var6 = var2.toString();
return var6;
} catch (NoBinderException var3) {
this.logExceptionName("getHealthSportTime", "NoBinderException");
return currAndTarget;
} catch (RemoteException var4) {
this.logExceptionName("getHealthSportTime", "RemoteException");
return currAndTarget;
}
}*/
return currAndTarget;
}
public IntRangeValue getStandRange() {
IntRangeValue testRangeData = this.getTestRangeData();
/* StandDataBean var2 = this.mStandBean;
if (var2 != null) {
return new IntRangeValue(this.parseString2Int(var2.getCurrentStand()), this.parseString2Int(this.mStandBean.getTargetStand()), 0);
} else {
try {
this.mStandBean = ParseUtil.parseMapToStandDataBean(HWWearableClientAPI.getInstance().getStandNumberInfo());
IntRangeValue var5 = new IntRangeValue(this.parseString2Int(this.mStandBean.getCurrentStand()), this.parseString2Int(this.mStandBean.getTargetStand()), 0);
return var5;
} catch (NoBinderException var3) {
this.logExceptionName("getStandRange", "NoBinderException");
return var1;
} catch (RemoteException var4) {
this.logExceptionName("getStandRange", "RemoteException");
return var1;
}
}*/
return testRangeData;
}
public IntRangeValue getStepRange() {
IntRangeValue rangeData = this.getTestRangeData();
/*StepDataBean var2 = this.mStepDataBean;
if (var2 != null) {
return new IntRangeValue(this.parseString2Int(var2.getCurrentStep()), this.parseString2Int(this.mStepDataBean.getTargetStep()), 0);
} else {
try {
this.mStepDataBean = ParseUtil.parseMapToStepDataBean(HWWearableClientAPI.getInstance().getStepNumberInfo());
IntRangeValue var5 = new IntRangeValue(this.parseString2Int(this.mStepDataBean.getCurrentStep()), this.parseString2Int(this.mStepDataBean.getTargetStep()), 0);
return var5;
} catch (NoBinderException var3) {
this.logExceptionName("getStepRange", "NoBinderException");
return rangeData;
} catch (RemoteException var4) {
this.logExceptionName("getStepRange", "RemoteException");
return rangeData;
}
}*/
return rangeData;
}
/* public void gotoHealthApp(String path) {
try {
Intent var2 = new Intent("android.intent.action.MAIN");
var2.addCategory("android.intent.category.LAUNCHER");
var2.setFlags(268435456);
var2.setComponent(new ComponentName("com.huawei.health", path));
this.mContext.startActivity(var2);
} catch (ActivityNotFoundException var3) {
LogUtil.e("SportsHealthController", "gotoHealthApp:ActivityNotFoundException");
}
}*/
/*public void init(Context var1) {
this.mContext = var1;
try {
StringBuilder var2 = new StringBuilder();
var2.append("getPackageName");
var2.append(var1.getPackageName());
HwLogUtil.i("SportsHealthController", var2.toString());
HWWearableClientAPI.getInstance(this.callback).bindHWWearableService(var1, var1.getPackageName());
} catch (NoFoundServiceException var3) {
this.logExceptionName("init", "NoFoundServiceException");
this.handler.postDelayed(this.runnable, 5000L);
}
}
public void registerHeartSensor() {
try {
HWWearableClientAPI.getInstance().registerRealTimeHeartRateSensorCallback(this.iHeartRateRealTimeCallback);
} catch (NoBinderException var2) {
this.logExceptionName("registerHeartSensor", "NoBinderException");
} catch (RemoteException var3) {
this.logExceptionName("registerHeartSensor", "RemoteException");
}
}*/
/*public void unregisterHeartSensor() {
try {
HWWearableClientAPI.getInstance().unregisterRealTimeHeartRateSensorCallback(this.iHeartRateRealTimeCallback);
} catch (NoBinderException var2) {
this.logExceptionName("unregisterHeartSensor", "NoBinderException");
} catch (RemoteException var3) {
this.logExceptionName("unregisterHeartSensor", "RemoteException");
}
}*/
}
| 37.247899
| 206
| 0.585937
|
11845e95d28f11890e18860471368631542b2f67
| 573
|
package tech.peller.mrblackandroidwatch.models.venue;
import io.realm.RealmObject;
public class PromotionCompany extends RealmObject {
private int id;
private String name;
public PromotionCompany() {
}
public PromotionCompany(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 16.371429
| 53
| 0.596859
|
5e33e0a045eb8705e32a4c02046619d1ff8ccdd8
| 1,662
|
/*
* Decompiled with CFR 0.150.
*/
package net.minecraft.util;
import net.minecraft.nbt.NBTTagFloat;
import net.minecraft.nbt.NBTTagList;
public class Rotations {
protected final float field_179419_a;
protected final float field_179417_b;
protected final float field_179418_c;
private static final String __OBFID = "CL_00002316";
public Rotations(float p_i46009_1_, float p_i46009_2_, float p_i46009_3_) {
this.field_179419_a = p_i46009_1_;
this.field_179417_b = p_i46009_2_;
this.field_179418_c = p_i46009_3_;
}
public Rotations(NBTTagList p_i46010_1_) {
this.field_179419_a = p_i46010_1_.getFloat(0);
this.field_179417_b = p_i46010_1_.getFloat(1);
this.field_179418_c = p_i46010_1_.getFloat(2);
}
public NBTTagList func_179414_a() {
NBTTagList var1 = new NBTTagList();
var1.appendTag(new NBTTagFloat(this.field_179419_a));
var1.appendTag(new NBTTagFloat(this.field_179417_b));
var1.appendTag(new NBTTagFloat(this.field_179418_c));
return var1;
}
public boolean equals(Object p_equals_1_) {
if (!(p_equals_1_ instanceof Rotations)) {
return false;
}
Rotations var2 = (Rotations)p_equals_1_;
return this.field_179419_a == var2.field_179419_a && this.field_179417_b == var2.field_179417_b && this.field_179418_c == var2.field_179418_c;
}
public float func_179415_b() {
return this.field_179419_a;
}
public float func_179416_c() {
return this.field_179417_b;
}
public float func_179413_d() {
return this.field_179418_c;
}
}
| 29.678571
| 150
| 0.685319
|
870f618a3723051ce1512d62ff4a184a6d1069e6
| 131
|
package richardludev.utilities.componentmodel;
public interface ComponentSystem {
public void update(double timestep);
}
| 18.714286
| 46
| 0.778626
|
da1496037ffd910002d5370bdbbcb5a3bf1aca62
| 3,240
|
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;
/**
* BQFinancialDocumentHandlingRetrieveOutputModelFinancialDocumentHandlingInstanceReport
*/
public class BQFinancialDocumentHandlingRetrieveOutputModelFinancialDocumentHandlingInstanceReport {
private Object financialDocumentHandlingInstanceReportRecord = null;
private String financialDocumentHandlingInstanceReportType = null;
private String financialDocumentHandlingInstanceReportParameters = null;
private Object financialDocumentHandlingInstanceReport = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The input information used to assemble the report that can be on-going, periodic and actual and projected
* @return financialDocumentHandlingInstanceReportRecord
**/
public Object getFinancialDocumentHandlingInstanceReportRecord() {
return financialDocumentHandlingInstanceReportRecord;
}
public void setFinancialDocumentHandlingInstanceReportRecord(Object financialDocumentHandlingInstanceReportRecord) {
this.financialDocumentHandlingInstanceReportRecord = financialDocumentHandlingInstanceReportRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external report available
* @return financialDocumentHandlingInstanceReportType
**/
public String getFinancialDocumentHandlingInstanceReportType() {
return financialDocumentHandlingInstanceReportType;
}
public void setFinancialDocumentHandlingInstanceReportType(String financialDocumentHandlingInstanceReportType) {
this.financialDocumentHandlingInstanceReportType = financialDocumentHandlingInstanceReportType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the report (e.g. period, content type)
* @return financialDocumentHandlingInstanceReportParameters
**/
public String getFinancialDocumentHandlingInstanceReportParameters() {
return financialDocumentHandlingInstanceReportParameters;
}
public void setFinancialDocumentHandlingInstanceReportParameters(String financialDocumentHandlingInstanceReportParameters) {
this.financialDocumentHandlingInstanceReportParameters = financialDocumentHandlingInstanceReportParameters;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external report in any suitable form including selection filters where appropriate
* @return financialDocumentHandlingInstanceReport
**/
public Object getFinancialDocumentHandlingInstanceReport() {
return financialDocumentHandlingInstanceReport;
}
public void setFinancialDocumentHandlingInstanceReport(Object financialDocumentHandlingInstanceReport) {
this.financialDocumentHandlingInstanceReport = financialDocumentHandlingInstanceReport;
}
}
| 40
| 230
| 0.82963
|
06e44f41f51287061574d44404eaed6ce226f0e6
| 740
|
package com.github.extermania.leetcode;
public class $0566_Reshape_the_Matrix_100 {
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
if(nums.length==0 || nums[0].length==0) return new int[r][c];
if(nums.length==r && nums[0].length==c) return nums;
if(nums.length*nums[0].length!=r*c) return nums;
int[][] arr = new int[r][c];
int k = 0;
int l = 0;
for(int i=0; i<nums.length; i++){
for(int j=0; j<nums[0].length; j++){
arr[k][l]=nums[i][j];
if(++l==c){
k++; l=0;
}
}
}
return arr;
}
}
}
| 29.6
| 71
| 0.436486
|
9c86712f2462f952320a39eed3a49e07dac01bc7
| 29,177
|
package com.mindasoft._03_collection.map;
/**
* Hashtable同样是基于哈希表实现的,同样每个元素是一个key-value对,其内部也是通过单链表解决冲突问题,容量不足(超过了阀值)时,同样会自动增长。
* Hashtable也是JDK1.0引入的类,是线程安全的,能用于多线程环境中。
* Hashtable同样实现了Serializable接口,它支持序列化,实现了Cloneable接口,能被克隆。
*
* 针对Hashtable,我们同样给出几点比较重要的总结,但要结合与HashMap的比较来总结。
* 1、二者的存储结构和解决冲突的方法都是相同的。
* 2、HashTable在不指定容量的情况下的默认容量为11,而HashMap为16,Hashtable不要求底层数组的容量一定要为2的整数次幂,而HashMap则要求一定为2的整数次幂。
* 3、Hashtable中key和value都不允许为null,而HashMap中key和value都允许为null(key只能有一个为null,而value则可以有多个为null)。但是如果在Hashtable中有类似put(null,null)的操作,编译同样可以通过,因为key和value都是Object类型,但运行时会抛出NullPointerException异常,这是JDK的规范规定的。我们来看下ContainsKey方法和ContainsValue的源码:
* // 判断Hashtable是否包含“值(value)”
* public synchronized boolean contains(Object value) {
* //注意,Hashtable中的value不能是null,
* // 若是null的话,抛出异常!
* if (value == null) {
* throw new NullPointerException();
* }
*
* // 从后向前遍历table数组中的元素(Entry)
* // 对于每个Entry(单向链表),逐个遍历,判断节点的值是否等于value
* Entry tab[] = table;
* for (int i = tab.length ; i-- > 0 ;) {
* for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {
* if (e.value.equals(value)) {
* return true;
* }
* }
* }
* return false;
* }
*
* public boolean containsValue(Object value) {
* return contains(value);
* }
*
* // 判断Hashtable是否包含key
* public synchronized boolean containsKey(Object key) {
* Entry tab[] = table;
* /计算hash值,直接用key的hashCode代替
* int hash = key.hashCode();
* // 计算在数组中的索引值
* int index = (hash & 0x7FFFFFFF) % tab.length;
* // 找到“key对应的Entry(链表)”,然后在链表中找出“哈希值”和“键值”与key都相等的元素
* for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
* if ((e.hash == hash) && e.key.equals(key)) {
* return true;
* }
* }
* return false;
* }
*
* 很明显,如果value为null,会直接抛出NullPointerException异常,但源码中并没有对key是否为null判断,有点小不解!
* 不过NullPointerException属于RuntimeException异常,是可以由JVM自动抛出的,也许对key的值在JVM中有所限制吧。
* 4、Hashtable扩容时,将容量变为原来的2倍加1,而HashMap扩容时,将容量变为原来的2倍。
* Company:MGTV
* User: huangmin
* DateTime: 2017/12/7 9:12
*/
public class HashtableLearning {
/**
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java._01_io.Serializable {
// 保存key-value的数组。
// Hashtable同样采用单链表解决冲突,每一个Entry本质上是一个单向链表
private transient Entry[] table;
// Hashtable中键值对的数量
private transient int count;
// 阈值,用于判断是否需要调整Hashtable的容量(threshold = 容量*加载因子)
private int threshold;
// 加载因子
private float loadFactor;
// Hashtable被改变的次数,用于fail-fast机制的实现
private transient int modCount = 0;
// 序列版本号
private static final long serialVersionUID = 1421746759512286392L;
// 指定“容量大小”和“加载因子”的构造函数
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry[initialCapacity];
threshold = (int)(initialCapacity * loadFactor);
}
// 指定“容量大小”的构造函数
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
// 默认构造函数。
public Hashtable() {
// 默认构造函数,指定的容量大小是11;加载因子是0.75
this(11, 0.75f);
}
// 包含“子Map”的构造函数
public Hashtable(Map<? extends K, ? extends V> t) {
this(Math.max(2*t.size(), 11), 0.75f);
// 将“子Map”的全部元素都添加到Hashtable中
putAll(t);
}
public synchronized int size() {
return count;
}
public synchronized boolean isEmpty() {
return count == 0;
}
// 返回“所有key”的枚举对象
public synchronized Enumeration<K> keys() {
return this.<K>getEnumeration(KEYS);
}
// 返回“所有value”的枚举对象
public synchronized Enumeration<V> elements() {
return this.<V>getEnumeration(VALUES);
}
// 判断Hashtable是否包含“值(value)”
public synchronized boolean contains(Object value) {
//注意,Hashtable中的value不能是null,
// 若是null的话,抛出异常!
if (value == null) {
throw new NullPointerException();
}
// 从后向前遍历table数组中的元素(Entry)
// 对于每个Entry(单向链表),逐个遍历,判断节点的值是否等于value
Entry tab[] = table;
for (int i = tab.length ; i-- > 0 ;) {
for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {
if (e.value.equals(value)) {
return true;
}
}
}
return false;
}
public boolean containsValue(Object value) {
return contains(value);
}
// 判断Hashtable是否包含key
public synchronized boolean containsKey(Object key) {
Entry tab[] = table;
//计算hash值,直接用key的hashCode代替
int hash = key.hashCode();
// 计算在数组中的索引值
int index = (hash & 0x7FFFFFFF) % tab.length;
// 找到“key对应的Entry(链表)”,然后在链表中找出“哈希值”和“键值”与key都相等的元素
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return true;
}
}
return false;
}
// 返回key对应的value,没有的话返回null
public synchronized V get(Object key) {
Entry tab[] = table;
int hash = key.hashCode();
// 计算索引值,
int index = (hash & 0x7FFFFFFF) % tab.length;
// 找到“key对应的Entry(链表)”,然后在链表中找出“哈希值”和“键值”与key都相等的元素
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return e.value;
}
}
return null;
}
// 调整Hashtable的长度,将长度变成原来的2倍+1
protected void rehash() {
int oldCapacity = table.length;
Entry[] oldMap = table;
//创建新容量大小的Entry数组
int newCapacity = oldCapacity * 2 + 1;
Entry[] newMap = new Entry[newCapacity];
modCount++;
threshold = (int)(newCapacity * loadFactor);
table = newMap;
//将“旧的Hashtable”中的元素复制到“新的Hashtable”中
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
//重新计算index
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
// 将“key-value”添加到Hashtable中
public synchronized V put(K key, V value) {
// Hashtable中不能插入value为null的元素!!!
if (value == null) {
throw new NullPointerException();
}
// 若“Hashtable中已存在键为key的键值对”,
// 则用“新的value”替换“旧的value”
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
}
}
// 若“Hashtable中不存在键为key的键值对”,
// 将“修改统计数”+1
modCount++;
// 若“Hashtable实际容量” > “阈值”(阈值=总的容量 * 加载因子)
// 则调整Hashtable的大小
if (count >= threshold) {
rehash();
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
//将新的key-value对插入到tab[index]处(即链表的头结点)
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
return null;
}
// 删除Hashtable中键为key的元素
public synchronized V remove(Object key) {
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
//从table[index]链表中找出要删除的节点,并删除该节点。
//因为是单链表,因此要保留带删节点的前一个节点,才能有效地删除节点
for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
// 将“Map(t)”的中全部元素逐一添加到Hashtable中
public synchronized void putAll(Map<? extends K, ? extends V> t) {
for (Map.Entry<? extends K, ? extends V> e : t.entrySet())
put(e.getKey(), e.getValue());
}
// 清空Hashtable
// 将Hashtable的table数组的值全部设为null
public synchronized void clear() {
Entry tab[] = table;
modCount++;
for (int index = tab.length; --index >= 0; )
tab[index] = null;
count = 0;
}
// 克隆一个Hashtable,并以Object的形式返回。
public synchronized Object clone() {
try {
Hashtable<K,V> t = (Hashtable<K,V>) super.clone();
t.table = new Entry[table.length];
for (int i = table.length ; i-- > 0 ; ) {
t.table[i] = (table[i] != null)
? (Entry<K,V>) table[i].clone() : null;
}
t.keySet = null;
t.entrySet = null;
t.values = null;
t.modCount = 0;
return t;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
public synchronized String toString() {
int max = size() - 1;
if (max == -1)
return "{}";
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<K,V>> it = entrySet().iterator();
sb.append('{');
for (int i = 0; ; i++) {
Map.Entry<K,V> e = it.next();
K key = e.getKey();
V value = e.getValue();
sb.append(key == this ? "(this Map)" : key.toString());
sb.append('=');
sb.append(value == this ? "(this Map)" : value.toString());
if (i == max)
return sb.append('}').toString();
sb.append(", ");
}
}
// 获取Hashtable的枚举类对象
// 若Hashtable的实际大小为0,则返回“空枚举类”对象;
// 否则,返回正常的Enumerator的对象。
private <T> Enumeration<T> getEnumeration(int type) {
if (count == 0) {
return (Enumeration<T>)emptyEnumerator;
} else {
return new Enumerator<T>(type, false);
}
}
// 获取Hashtable的迭代器
// 若Hashtable的实际大小为0,则返回“空迭代器”对象;
// 否则,返回正常的Enumerator的对象。(Enumerator实现了迭代器和枚举两个接口)
private <T> Iterator<T> getIterator(int type) {
if (count == 0) {
return (Iterator<T>) emptyIterator;
} else {
return new Enumerator<T>(type, true);
}
}
// Hashtable的“key的集合”。它是一个Set,没有重复元素
private transient volatile Set<K> keySet = null;
// Hashtable的“key-value的集合”。它是一个Set,没有重复元素
private transient volatile Set<Map.Entry<K,V>> entrySet = null;
// Hashtable的“key-value的集合”。它是一个Collection,可以有重复元素
private transient volatile Collection<V> values = null;
// 返回一个被synchronizedSet封装后的KeySet对象
// synchronizedSet封装的目的是对KeySet的所有方法都添加synchronized,实现多线程同步
public Set<K> keySet() {
if (keySet == null)
keySet = Collections.synchronizedSet(new KeySet(), this);
return keySet;
}
// Hashtable的Key的Set集合。
// KeySet继承于AbstractSet,所以,KeySet中的元素没有重复的。
private class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return getIterator(KEYS);
}
public int size() {
return count;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
return Hashtable.this.remove(o) != null;
}
public void clear() {
Hashtable.this.clear();
}
}
// 返回一个被synchronizedSet封装后的EntrySet对象
// synchronizedSet封装的目的是对EntrySet的所有方法都添加synchronized,实现多线程同步
public Set<Map.Entry<K,V>> entrySet() {
if (entrySet==null)
entrySet = Collections.synchronizedSet(new EntrySet(), this);
return entrySet;
}
// Hashtable的Entry的Set集合。
// EntrySet继承于AbstractSet,所以,EntrySet中的元素没有重复的。
private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return getIterator(ENTRIES);
}
public boolean add(Map.Entry<K,V> o) {
return super.add(o);
}
// 查找EntrySet中是否包含Object(0)
// 首先,在table中找到o对应的Entry链表
// 然后,查找Entry链表中是否存在Object
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry[] tab = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
if (e.hash==hash && e.equals(entry))
return true;
return false;
}
// 删除元素Object(0)
// 首先,在table中找到o对应的Entry链表
// 然后,删除链表中的元素Object
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
K key = entry.getKey();
Entry[] tab = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e.hash==hash && e.equals(entry)) {
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
count--;
e.value = null;
return true;
}
}
return false;
}
public int size() {
return count;
}
public void clear() {
Hashtable.this.clear();
}
}
// 返回一个被synchronizedCollection封装后的ValueCollection对象
// synchronizedCollection封装的目的是对ValueCollection的所有方法都添加synchronized,实现多线程同步
public Collection<V> values() {
if (values==null)
values = Collections.synchronizedCollection(new ValueCollection(),
this);
return values;
}
// Hashtable的value的Collection集合。
// ValueCollection继承于AbstractCollection,所以,ValueCollection中的元素可以重复的。
private class ValueCollection extends AbstractCollection<V> {
public Iterator<V> iterator() {
return getIterator(VALUES);
}
public int size() {
return count;
}
public boolean contains(Object o) {
return containsValue(o);
}
public void clear() {
Hashtable.this.clear();
}
}
// 重新equals()函数
// 若两个Hashtable的所有key-value键值对都相等,则判断它们两个相等
public synchronized boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> t = (Map<K,V>) o;
if (t.size() != size())
return false;
try {
// 通过迭代器依次取出当前Hashtable的key-value键值对
// 并判断该键值对,存在于Hashtable中。
// 若不存在,则立即返回false;否则,遍历完“当前Hashtable”并返回true。
Iterator<Map.Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Map.Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(t.get(key)==null && t.containsKey(key)))
return false;
} else {
if (!value.equals(t.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
// 计算Entry的hashCode
// 若 Hashtable的实际大小为0 或者 加载因子<0,则返回0。
// 否则,返回“Hashtable中的每个Entry的key和value的异或值 的总和”。
public synchronized int hashCode() {
int h = 0;
if (count == 0 || loadFactor < 0)
return h; // Returns zero
loadFactor = -loadFactor; // Mark hashCode computation in progress
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
for (Entry e = tab[i]; e != null; e = e.next)
h += e.key.hashCode() ^ e.value.hashCode();
loadFactor = -loadFactor; // Mark hashCode computation complete
return h;
}
// java._01_io.Serializable的写入函数
// 将Hashtable的“总的容量,实际容量,所有的Entry”都写入到输出流中
private synchronized void writeObject(java._01_io.ObjectOutputStream s)
throws IOException
{
// Write out the length, threshold, loadfactor
s.defaultWriteObject();
// Write out length, count of elements and then the key/value objects
s.writeInt(table.length);
s.writeInt(count);
for (int index = table.length-1; index >= 0; index--) {
Entry entry = table[index];
while (entry != null) {
s.writeObject(entry.key);
s.writeObject(entry.value);
entry = entry.next;
}
}
}
// java._01_io.Serializable的读取函数:根据写入方式读出
// 将Hashtable的“总的容量,实际容量,所有的Entry”依次读出
private void readObject(java._01_io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the length, threshold, and loadfactor
s.defaultReadObject();
// Read the original length of the array and number of elements
int origlength = s.readInt();
int elements = s.readInt();
// Compute new size with a bit of room 5% to grow but
// no larger than the original size. Make the length
// odd if it's large enough, this helps distribute the entries.
// Guard against the length ending up zero, that's not valid.
int length = (int)(elements * loadFactor) + (elements / 20) + 3;
if (length > elements && (length & 1) == 0)
length--;
if (origlength > 0 && length > origlength)
length = origlength;
Entry[] table = new Entry[length];
count = 0;
// Read the number of elements and then all the key/value objects
for (; elements > 0; elements--) {
K key = (K)s.readObject();
V value = (V)s.readObject();
// synch could be eliminated for performance
reconstitutionPut(table, key, value);
}
this.table = table;
}
private void reconstitutionPut(Entry[] tab, K key, V value)
throws StreamCorruptedException
{
if (value == null) {
throw new java._01_io.StreamCorruptedException();
}
// Makes sure the key is not already in the hashtable.
// This should not happen in deserialized version.
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
throw new java._01_io.StreamCorruptedException();
}
}
// Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
}
// Hashtable的Entry节点,它本质上是一个单向链表。
// 也因此,我们才能推断出Hashtable是由拉链法实现的散列表
private static class Entry<K,V> implements Map.Entry<K,V> {
// 哈希值
int hash;
K key;
V value;
// 指向的下一个Entry,即链表的下一个节点
Entry<K,V> next;
// 构造函数
protected Entry(int hash, K key, V value, Entry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
protected Object clone() {
return new Entry<K,V>(hash, key, value,
(next==null ? null : (Entry<K,V>) next.clone()));
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
// 设置value。若value是null,则抛出异常。
public V setValue(V value) {
if (value == null)
throw new NullPointerException();
V oldValue = this.value;
this.value = value;
return oldValue;
}
// 覆盖equals()方法,判断两个Entry是否相等。
// 若两个Entry的key和value都相等,则认为它们相等。
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ (value==null ? 0 : value.hashCode());
}
public String toString() {
return key.toString()+"="+value.toString();
}
}
private static final int KEYS = 0;
private static final int VALUES = 1;
private static final int ENTRIES = 2;
// Enumerator的作用是提供了“通过elements()遍历Hashtable的接口” 和 “通过entrySet()遍历Hashtable的接口”。
private class Enumerator<T> implements Enumeration<T>, Iterator<T> {
// 指向Hashtable的table
Entry[] table = Hashtable.this.table;
// Hashtable的总的大小
int index = table.length;
Entry<K,V> entry = null;
Entry<K,V> lastReturned = null;
int type;
// Enumerator是 “迭代器(Iterator)” 还是 “枚举类(Enumeration)”的标志
// iterator为true,表示它是迭代器;否则,是枚举类。
boolean iterator;
// 在将Enumerator当作迭代器使用时会用到,用来实现fail-fast机制。
protected int expectedModCount = modCount;
Enumerator(int type, boolean iterator) {
this.type = type;
this.iterator = iterator;
}
// 从遍历table的数组的末尾向前查找,直到找到不为null的Entry。
public boolean hasMoreElements() {
Entry<K,V> e = entry;
int i = index;
Entry[] t = table;
while (e == null && i > 0) {
e = t[--i];
}
entry = e;
index = i;
return e != null;
}
// 获取下一个元素
// 注意:从hasMoreElements() 和nextElement() 可以看出“Hashtable的elements()遍历方式”
// 首先,从后向前的遍历table数组。table数组的每个节点都是一个单向链表(Entry)。
// 然后,依次向后遍历单向链表Entry。
public T nextElement() {
Entry<K,V> et = entry;
int i = index;
Entry[] t = table;
while (et == null && i > 0) {
et = t[--i];
}
entry = et;
index = i;
if (et != null) {
Entry<K,V> e = lastReturned = entry;
entry = e.next;
return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e);
}
throw new NoSuchElementException("Hashtable Enumerator");
}
// 迭代器Iterator的判断是否存在下一个元素
// 实际上,它是调用的hasMoreElements()
public boolean hasNext() {
return hasMoreElements();
}
// 迭代器获取下一个元素
// 实际上,它是调用的nextElement()
public T next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
return nextElement();
}
// 迭代器的remove()接口。
// 首先,它在table数组中找出要删除元素所在的Entry,
// 然后,删除单向链表Entry中的元素。
public void remove() {
if (!iterator)
throw new UnsupportedOperationException();
if (lastReturned == null)
throw new IllegalStateException("Hashtable Enumerator");
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
synchronized(Hashtable.this) {
Entry[] tab = Hashtable.this.table;
int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e == lastReturned) {
modCount++;
expectedModCount++;
if (prev == null)
tab[index] = e.next;
else
prev.next = e.next;
count--;
lastReturned = null;
return;
}
}
throw new ConcurrentModificationException();
}
}
}
private static Enumeration emptyEnumerator = new EmptyEnumerator();
private static Iterator emptyIterator = new EmptyIterator();
// 空枚举类
// 当Hashtable的实际大小为0;此时,又要通过Enumeration遍历Hashtable时,返回的是“空枚举类”的对象。
private static class EmptyEnumerator implements Enumeration<Object> {
EmptyEnumerator() {
}
// 空枚举类的hasMoreElements() 始终返回false
public boolean hasMoreElements() {
return false;
}
// 空枚举类的nextElement() 抛出异常
public Object nextElement() {
throw new NoSuchElementException("Hashtable Enumerator");
}
}
// 空迭代器
// 当Hashtable的实际大小为0;此时,又要通过迭代器遍历Hashtable时,返回的是“空迭代器”的对象。
private static class EmptyIterator implements Iterator<Object> {
EmptyIterator() {
}
public boolean hasNext() {
return false;
}
public Object next() {
throw new NoSuchElementException("Hashtable Iterator");
}
public void remove() {
throw new IllegalStateException("Hashtable Iterator");
}
}
}
*/
}
| 34.366313
| 241
| 0.482606
|
e9a39ede1a2a73527184a98445ad03d2bf6138ba
| 703
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.maf.cellmissy.analysis;
import be.ugent.maf.cellmissy.exception.TwoOrMoreObservationsException;
import java.util.List;
/**
* Kernel Density Estimator interface
*
* @author Paola Masuzzo
*/
public interface KernelDensityEstimator {
/**
* Estimate Density Function for a dataset data
*
* @param data
* @return a List of double arrays (x and y values of density Function)
* @throws be.ugent.maf.cellmissy.exception.TwoOrMoreObservationsException
*/
List<double[]> estimateDensityFunction(Double[] data) throws TwoOrMoreObservationsException;
}
| 27.038462
| 96
| 0.731152
|
57ad0ce132703c13650ee57fb4717ad3c7d8a634
| 2,641
|
package com.i906.mpt.date;
import com.github.msarhan.ummalqura.calendar.UmmalquraCalendar;
import com.i906.mpt.prefs.CommonPreferences;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class DateTimeHelper {
private final DateProvider mProvider;
private final CommonPreferences mPrefs;
private Calendar mCalendar;
private UmmalquraCalendar mHijriCalendar;
@Inject
public DateTimeHelper(DateProvider provider, CommonPreferences prefs) {
mProvider = provider;
mPrefs = prefs;
refresh();
}
public int getCurrentDate() {
refresh();
return mCalendar.get(Calendar.DATE);
}
public int getNextDate() {
Calendar c = getNow();
c.add(Calendar.DATE, 1);
return c.get(Calendar.DATE);
}
public int getCurrentMonth() {
refresh();
return mCalendar.get(Calendar.MONTH);
}
public int getNextMonth() {
Calendar c = getNow();
c.add(Calendar.MONTH, 1);
return c.get(Calendar.MONTH);
}
public int getCurrentYear() {
refresh();
return mCalendar.get(Calendar.YEAR);
}
public int getNextYear() {
Calendar c = getNow();
c.add(Calendar.YEAR, 1);
return c.get(Calendar.YEAR);
}
public boolean isTommorowNewMonth() {
Calendar tom = getNow();
tom.add(Calendar.DATE, 1);
int tommonth = tom.get(Calendar.MONTH);
return getCurrentMonth() != tommonth;
}
public boolean isNextMonthNewYear() {
Calendar tom = getNow();
tom.add(Calendar.MONTH, 1);
int tomyear = tom.get(Calendar.YEAR);
return getCurrentYear() != tomyear;
}
public List<Integer> getHijriDate(boolean maghribPassed) {
List<Integer> l = new ArrayList<>(3);
refresh();
if (maghribPassed) {
mHijriCalendar.add(Calendar.DATE, 1);
}
mHijriCalendar.add(Calendar.DATE, mPrefs.getHijriOffset());
l.add(mHijriCalendar.get(Calendar.DATE));
l.add(mHijriCalendar.get(Calendar.MONTH));
l.add(mHijriCalendar.get(Calendar.YEAR));
return l;
}
private void refresh() {
mCalendar = mProvider.getNow();
mHijriCalendar = new UmmalquraCalendar();
mHijriCalendar.setTimeInMillis(mProvider.getCurrentTime());
}
public Calendar getNow() {
return mProvider.getNow();
}
public Calendar getCalendarInstance() {
return mProvider.getCalendarInstance();
}
}
| 24.682243
| 75
| 0.631579
|
93b6afcb0b315c616ad05ec2da28f25014251c23
| 2,282
|
package us.ihmc.messager.examples;
import static us.ihmc.messager.examples.EnglishPerson.*;
import static us.ihmc.messager.examples.FrenchPerson.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import us.ihmc.messager.Messager;
import us.ihmc.messager.TopicListener;
public class BilingualPerson
{
private final Map<String, String> englishToFrenchNumbers = new HashMap<>();
private final Map<String, String> frenchToEnglishNumbers = new HashMap<>();
public BilingualPerson(Messager messager)
{
englishToFrenchNumbers.put("one", "un");
englishToFrenchNumbers.put("two", "deux");
englishToFrenchNumbers.put("three", "trois");
englishToFrenchNumbers.put("four", "quatre");
englishToFrenchNumbers.put("five", "cinq");
frenchToEnglishNumbers.put("un", "one");
frenchToEnglishNumbers.put("deux", "two");
frenchToEnglishNumbers.put("trois", "three");
frenchToEnglishNumbers.put("quatre", "four");
frenchToEnglishNumbers.put("cinq", "five");
messager.registerTopicListener(SpeakEnglish, new TopicListener<String>()
{
@Override
public void receivedMessageForTopic(String messageContent)
{
String frenchMessage = "Le bilingue ne sait pas traduire ce qu'a dit l'anglais.";
for (Entry<String, String> entry : englishToFrenchNumbers.entrySet())
{
if (messageContent.toLowerCase().contains(entry.getKey()))
frenchMessage = "l'anglais a dit: " + entry.getValue();
}
messager.submitMessage(ListenFrench, frenchMessage);
}
});
messager.registerTopicListener(SpeakFrench, new TopicListener<String>()
{
@Override
public void receivedMessageForTopic(String messageContent)
{
String englishMessage = "I have no clue what the French said.";
for (Entry<String, String> entry : frenchToEnglishNumbers.entrySet())
{
if (messageContent.toLowerCase().contains(entry.getKey()))
englishMessage = "the French said: " + entry.getValue();
}
messager.submitMessage(ListenEnglish, englishMessage);
}
});
}
}
| 35.65625
| 93
| 0.650745
|
bbc592947dbb993f4ea53750f959597ab2fd60ea
| 1,136
|
package by.andd3dfx.queue;
import java.util.ArrayList;
import java.util.List;
public class Queue {
private Item head;
public Queue(Item head) {
assert head != null;
this.head = head;
}
public Item getHead() {
return head;
}
public void setHead(Item head) {
this.head = head;
}
public Item revertUsingAdditionalArray() {
List<Item> items = new ArrayList<Item>();
Item current = head;
while (current != null) {
items.add(current);
current = current.getNext();
}
for (int i = items.size() - 1; i > 0; i--) {
items.get(i).setNext(items.get(i - 1));
}
items.get(0).setNext(null);
return items.get(items.size() - 1);
}
public Item revertUsingRecursion() {
return swapLinks(null, head);
}
private Item swapLinks(Item item1, Item item2) {
if (item2 == null) return item1;
Item next = item2.getNext();
item2.setNext(item1);
return swapLinks(item2, next);
}
}
| 22.27451
| 53
| 0.527289
|
56fbbd9bd916ff68afd5e3daaf684e52772c6765
| 620
|
package com.moqi.c05;
import com.moqi.bean.Artist;
import com.moqi.bean.SampleData;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class C05P085LongestNameTest {
@Test
public void findsLongestNameByReduce() {
Artist artist = C05P085LongestName.byReduce(SampleData.getThreeArtists());
assertEquals(SampleData.johnColtrane, artist);
}
@Test
public void findsLongestNameByCollecting() {
Artist artist = C05P085LongestName.byCollecting(SampleData.getThreeArtists());
assertEquals(SampleData.johnColtrane, artist);
}
}
| 25.833333
| 86
| 0.741935
|
3aa570b53cf1c69ce5276f41493588f8b652576d
| 3,455
|
package com.thejounezz.demisegame;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import net.md_5.bungee.api.ChatColor;
public class ScoreboardHandler
{
Game plugin;
GameStateHandler gameState;
Scoreboard b;
String objectiveName = Globals.GameName + "Game";
public ScoreboardHandler(Game plugin, GameStateHandler gameState)
{
this.plugin = plugin;
this.gameState = gameState;
ScoreboardManager m = Bukkit.getScoreboardManager();
b = m.getNewScoreboard();
this.CreateTeams();
}
public Scoreboard GetScoreboard()
{
return b;
}
public void GenerateNewScoreboard(Player sender)
{
ScoreboardManager m = Bukkit.getScoreboardManager();
b = m.getNewScoreboard();
@SuppressWarnings("deprecation")
Objective o = b.registerNewObjective(objectiveName, "");
o.setDisplaySlot(DisplaySlot.SIDEBAR);
o.setDisplayName(ChatColor.GOLD + "" + ChatColor.BOLD + Globals.GameName + " Game");
// Bottom up lines
int i = 0;
for(String p : plugin.GetDeadPlayers())
{
Score dead = o.getScore(ChatColor.WHITE + "- " + p);
dead.setScore(i++);
}
Score deadTitle = o.getScore(ChatColor.RED + "Players Dead:");
deadTitle.setScore(i++);
for(String p : plugin.GetAlivePlayers())
{
Score alive = o.getScore(ChatColor.WHITE + "- " + p);
alive.setScore(i++);
}
Score aliveTitle = o.getScore(ChatColor.GREEN + "Players Alive:");
aliveTitle.setScore(i++);
Score empty = o.getScore("");
empty.setScore(i++);
Score gameStateScore;
if(gameState.Get() == GameState.RUNNING)
{
gameStateScore = o.getScore(ChatColor.GOLD + "Game: " + ChatColor.BOLD + "RUNNING");
}
else
{
gameStateScore = o.getScore(ChatColor.GOLD + "Game: Not running");
}
gameStateScore.setScore(i++);
Score empty2 = o.getScore(" ");
empty2.setScore(i++);
// Set Tab List names
for(Player p : Bukkit.getOnlinePlayers()) // reset
{
ResetName(p);
}
for(String s : plugin.GetAlivePlayers())
{
Player p = Bukkit.getPlayer(s);
p.setDisplayName(ChatColor.GREEN + "[Alive] " + ChatColor.RESET + p.getName());
p.setPlayerListName(p.getDisplayName());
}
for(String s : plugin.GetDeadPlayers())
{
Player p = Bukkit.getPlayer(s);
p.setDisplayName(ChatColor.RED + "[Dead] " + ChatColor.RESET + p.getName());
p.setPlayerListName(p.getDisplayName());
}
sender.setScoreboard(b);
}
public void ClearScoreboard(Player sender)
{
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
public void run() {
sender.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
}
}, 20L);
// reset player names
for(Player p : Bukkit.getOnlinePlayers())
{
p.setPlayerListName(p.getName());
}
}
private void CreateTeams()
{
if(this.b.getTeam(Globals.TeamAliveName) == null)
{
this.b.registerNewTeam(Globals.TeamAliveName);
Bukkit.getLogger().info("Team " + Globals.TeamAliveName + " was created");
}
if(b.getTeam(Globals.TeamDeadName) == null)
{
this.b.registerNewTeam(Globals.TeamDeadName);
Bukkit.getLogger().info("Team " + Globals.TeamDeadName + " was created");
}
}
private void ResetName(Player p)
{
p.setPlayerListName(p.getName());
}
}
| 25.404412
| 89
| 0.691462
|
8fe588e0dfd8c6f632db0f9364c14a524e128471
| 588
|
package main.java.Leetcode;
/**
* Solution_1243_Array_Transformation
*/
public class Solution_1243_Array_Transformation {
public List<Integer> transformArray(int[] arr) {
int[] ans = new int[arr.length];
while (!Arrays.equals(ans, arr)) {
ans = arr.clone();
for (int i = 1; i < arr.length - 1; ++i) {
if (ans[i - 1] < ans[i] && ans[i] > ans[i + 1]) {
--arr[i];
} else if (ans[i - 1] > ans[i] && ans[i] < ans[i + 1]) {
++arr[i];
}
}
}
return Arrays.stream(ans).boxed().collect(Collectors.toList());
}
}
| 25.565217
| 67
| 0.535714
|
0cb3d3ab9c932a6bb0126cd1d2c37a478373b5f1
| 4,605
|
package com.udacity.sandwichclub;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.udacity.sandwichclub.model.Sandwich;
import com.udacity.sandwichclub.utils.JsonUtils;
import java.util.List;
public class DetailActivity extends AppCompatActivity {
public static final String EXTRA_POSITION = "extra_position";
private static final int DEFAULT_POSITION = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ImageView ingredientsIv = findViewById(R.id.image_iv);
Intent intent = getIntent();
if (intent == null) {
closeOnError();
}
assert intent != null;
int position = intent.getIntExtra(EXTRA_POSITION, DEFAULT_POSITION);
if (position == DEFAULT_POSITION) {
// EXTRA_POSITION not found in intent
closeOnError();
return;
}
String[] sandwiches = getResources().getStringArray(R.array.sandwich_details);
String json = sandwiches[position];
Sandwich sandwich = JsonUtils.parseSandwichJson(json);
if (sandwich == null) {
// Sandwich data unavailable
closeOnError();
return;
}
populateUI(sandwich);
Picasso.with(this)
.load(sandwich.getImage())
.into(ingredientsIv);
setTitle(sandwich.getMainName());
}
private void closeOnError() {
finish();
Toast.makeText(this, R.string.detail_error_message, Toast.LENGTH_SHORT).show();
}
// Sets the TextViews with the data parsed from JsonUtils via sandwich
private void populateUI(Sandwich sandwich) {
/*
alsoKnownAsTextView
*/
TextView alsoKnownAsTextView = findViewById(R.id.also_known_tv);
String alsoKnownAs;
List<String> alsoKnownAsList = sandwich.getAlsoKnownAs();
if (alsoKnownAsList.isEmpty()) {
alsoKnownAs = getString(R.string.no_aliases);
} else {
// iterates though adding a - dash to each entry
StringBuilder akaBuilder = new StringBuilder();
for (int i = 0; i < alsoKnownAsList.size(); i++) {
akaBuilder
.append("\u2013 ") // - dash
.append(alsoKnownAsList.get(i));
// prevents new line after last entry so it doesn't effect margins
if (i != alsoKnownAsList.size() - 1)
akaBuilder.append('\n');
}
alsoKnownAs = akaBuilder.toString();
}
alsoKnownAsTextView.setText(alsoKnownAs);
/*
Description TextView
*/
TextView descriptionTextView = findViewById(R.id.description_tv);
String description = sandwich.getDescription();
if (description == null || description.equals("")){
description = getString(R.string.no_description);
}
descriptionTextView.setText(description);
/*
Ingredients TextView
*/
TextView ingredientsTextView = findViewById(R.id.ingredients_tv);
String ingredients;
List<String> ingredientsList = sandwich.getIngredients();
if (ingredientsList.isEmpty()){
ingredients = getString(R.string.no_ingredients);
}else{
// iterates though adding a - dash to each entry
StringBuilder ingredientsBuilder = new StringBuilder();
for (int i = 0; i < ingredientsList.size(); i++) {
ingredientsBuilder
.append("\u2013 ") // - dash
.append(ingredientsList.get(i));
// prevents new line after last entry so it doesn't effect margins
if (i != ingredientsList.size() - 1)
ingredientsBuilder.append('\n');
}
ingredients = ingredientsBuilder.toString();
}
ingredientsTextView.setText(ingredients);
TextView placeOfOriginTextView = findViewById(R.id.origin_tv);
String placeOfOrigin = sandwich.getPlaceOfOrigin();
if (placeOfOrigin == null || placeOfOrigin.equals("")) {
placeOfOrigin = getString(R.string.origin_unknown);
}
placeOfOriginTextView.setText(placeOfOrigin);
}
}
| 34.886364
| 87
| 0.611075
|
909c85e107034f48aeae3f6fe0408658520b8c36
| 3,645
|
/***
* Copyright (c) 2015 Oscar Salguero www.oscarsalguero.com
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.oscarsalguero.colorextractor.utils;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Image Utilities.
* <p/>
* Created by RacZo on 9/1/15.
*/
public class ImageUtils {
private static final String LOG_TAG = ImageUtils.class.getName();
public static Bitmap decodeBitmap(Activity activity, Uri selectedImage) throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(selectedImage), null, o);
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(selectedImage), null, o2);
}
public static Bitmap getBitmapWithCorrectOrientation(Bitmap bitmap, Uri uri) {
Bitmap resizedBitmap = null;
try {
resizedBitmap = null;
ExifInterface ei = new ExifInterface(uri.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
if (bitmap.getWidth() >= bitmap.getHeight()) {
resizedBitmap = Bitmap.createBitmap(
bitmap,
bitmap.getWidth() / 2
- bitmap.getHeight() / 2, 0,
bitmap.getHeight(), bitmap.getHeight(),
mat, true);
} else {
resizedBitmap = Bitmap.createBitmap(
bitmap,
0,
bitmap.getHeight() / 2
- bitmap.getWidth() / 2,
bitmap.getWidth(), bitmap.getWidth(),
mat, true);
}
} catch (IOException e) {
Log.e(LOG_TAG, e.getLocalizedMessage());
e.printStackTrace();
}
return resizedBitmap;
}
}
| 38.368421
| 114
| 0.603018
|
463733066511929792a08ad6efc431c0098d857b
| 4,419
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.nullness;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.Matchers.variableType;
import static com.google.errorprone.suppliers.Suppliers.BOOLEAN_TYPE;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.dataflow.nullnesspropagation.Nullness;
import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis;
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.util.ASTHelpers;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.Objects;
/**
* {@link BugChecker} adds a null check to equals() method implementations which don't satisfy the
* null contract of equals() method i.e. Object.equals(null) should return false.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
name = "EqualsBrokenForNull",
summary = "equals() implementation throws NullPointerException when given null",
severity = SeverityLevel.WARNING,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public class EqualsBrokenForNull extends BugChecker implements MethodTreeMatcher {
private static final Matcher<MethodTree> MATCHER =
allOf(
methodIsNamed("equals"),
methodHasParameters(variableType(isSameType("java.lang.Object"))),
methodReturns(BOOLEAN_TYPE));
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
VarSymbol varSymbol = ASTHelpers.getSymbol(getOnlyElement(tree.getParameters()));
NullnessAnalysis analysis = NullnessAnalysis.instance(state.context);
// we run nullness analysis on all the subtrees and match if there is a method invocation on
// the argument to the equals method.
boolean[] crashesWithNull = {false};
new TreePathScanner<Void, Void>() {
@Override
public Void visitMemberSelect(MemberSelectTree node, Void aVoid) {
if (!crashesWithNull[0]) {
if (Objects.equals(varSymbol, ASTHelpers.getSymbol(node.getExpression()))) {
Nullness nullness =
analysis.getNullness(
new TreePath(getCurrentPath(), node.getExpression()), state.context);
if (nullness == Nullness.NULLABLE) {
crashesWithNull[0] = true;
}
}
}
return super.visitMemberSelect(node, aVoid);
}
}.scan(state.getPath(), null);
if (!crashesWithNull[0]) {
return NO_MATCH;
}
String stringAddition =
String.format("if (%s == null) { return false; }\n", varSymbol.name.toString());
Fix fix = SuggestedFix.prefixWith(tree.getBody().getStatements().get(0), stringAddition);
return describeMatch(tree, fix);
}
}
| 42.902913
| 98
| 0.749491
|
16861f6a23132795af13581b86ed7c957ba6ad26
| 7,083
|
package io.github.miroslavpokorny.blog.controller.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.miroslavpokorny.blog.model.dto.ErrorMessageDto;
import io.github.miroslavpokorny.blog.model.dto.LoggedUserDto;
import io.github.miroslavpokorny.blog.testutil.TokenTestHelper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc(secure = false)
@ActiveProfiles("TEST")
public class SignControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void badPasswordSignIn() throws Exception {
mvc.perform(post("/api/sign/in")
.content("{\"email\":\"frantanovak@example.com\",\"password\":\"badpass\"}")
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isUnauthorized());
}
@Test
public void missingPropertyDataSignIn() throws Exception {
mvc.perform(post("/api/sign/in")
.content("{\"email\":\"frantanovak@example.com\"}")
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isBadRequest());
mvc.perform(post("/api/sign/in")
.content("\"password\":\"badpass\"}")
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isBadRequest());
mvc.perform(post("/api/sign/in")
.content("{}")
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isBadRequest());
}
@Test
public void signIn() throws Exception {
MvcResult result = mvc.perform(post("/api/sign/in")
.content("{\"email\":\"frantanovak@example.com\",\"password\":\"abc\"}")
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isOk()).andReturn();
ObjectMapper mapper = new ObjectMapper();
String textJson = result.getResponse().getContentAsString();
LoggedUserDto loggedUser = mapper.readValue(textJson, LoggedUserDto.class);
Assert.assertEquals("frantanovak", loggedUser.getNickname());
Assert.assertEquals(1, loggedUser.getId());
Assert.assertEquals(4, loggedUser.getRole());
Assert.assertTrue(loggedUser.getTokenId().length() > 0);
}
@Test
public void signOutUserTest() throws Exception {
String tokenId = TokenTestHelper.getSignedAdministratorTokenId(mvc);
mvc.perform(post("/api/sign/out")
.param("tokenId", tokenId)
).andExpect(status().isOk());
}
@Test
public void signOutUnauthorizedUser() throws Exception {
String tokenId = "";
mvc.perform(post("/api/sign/out")
.param("tokenId", tokenId)
).andExpect(status().isOk());
mvc.perform(post("/api/sign/out")
).andExpect(status().isUnauthorized());
}
@Test
public void getLoggedUser() throws Exception {
String tokenId = TokenTestHelper.getSignedAdministratorTokenId(mvc);
MvcResult result = mvc.perform(post("/api/getLoggedUser")
.param("tokenId", tokenId)
).andExpect(status().isOk()).andReturn();
ObjectMapper mapper = new ObjectMapper();
String textJson = result.getResponse().getContentAsString();
LoggedUserDto loggedUser = mapper.readValue(textJson, LoggedUserDto.class);
Assert.assertEquals("frantanovak", loggedUser.getNickname());
Assert.assertEquals(1, loggedUser.getId());
Assert.assertEquals(4, loggedUser.getRole());
}
@Test
public void getLoggedUserUnauthorized() throws Exception {
String tokenId = "not existing token";
mvc.perform(post("/api/getLoggedUser")
.param("tokenId", tokenId)
).andExpect(status().isUnauthorized());
mvc.perform(post("/api/getLoggedUser")
).andExpect(status().isUnauthorized());
}
@Test
public void signUpTest() throws Exception {
String signUp = "{\"email\":\"test@test.test\",\"nickname\":\"test\",\"password\":\"password\",\"name\":\"test\",\"surname\":\"test\"}";
MvcResult result = mvc.perform(post("/api/sign/up")
.content(signUp)
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isOk()).andReturn();
ObjectMapper mapper = new ObjectMapper();
String textJson = result.getResponse().getContentAsString();
LoggedUserDto loggedUser = mapper.readValue(textJson, LoggedUserDto.class);
Assert.assertEquals("test", loggedUser.getNickname());
Assert.assertEquals(1, loggedUser.getRole());
}
@Test
public void signUpTestInvalidData() throws Exception {
String signUp = "{\"email\":\"test\",\"nickname\":\"test\",\"password\":\"password\",\"name\":\"test\",\"surname\":\"test\"}";
MvcResult result = mvc.perform(post("/api/sign/up")
.content(signUp)
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isBadRequest()).andReturn();
ObjectMapper mapper = new ObjectMapper();
String textJson = result.getResponse().getContentAsString();
ErrorMessageDto error = mapper.readValue(textJson, ErrorMessageDto.class);
Assert.assertTrue(error.getMessage().toLowerCase().contains("bad data format"));
Assert.assertEquals("ErrorMessageDto", error.getType());
Assert.assertEquals(HttpStatus.BAD_REQUEST.value(), error.getCode());
}
@Test
public void signUpConflictData() throws Exception {
String signUpEmailConflict = "{\"email\":\"frantanovak@example.com\",\"nickname\":\"test\",\"password\":\"password\",\"name\":\"test\",\"surname\":\"test\"}";
mvc.perform(post("/api/sign/up")
.content(signUpEmailConflict)
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isConflict());
String signUpNicknameConflict = "{\"email\":\"some@example.com\",\"nickname\":\"frantanovak\",\"password\":\"password\",\"name\":\"test\",\"surname\":\"test\"}";
mvc.perform(post("/api/sign/up")
.content(signUpNicknameConflict)
.contentType(MediaType.APPLICATION_JSON)
).andExpect(status().isConflict());
}
}
| 45.11465
| 169
| 0.661584
|
50300d06a737b9b48bc6e1c5c2c882fc5de2b74b
| 2,001
|
package com.example.retrofitmarvel;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.list);
//calling a method to display the REST server data
getHeroes();
}
private void getHeroes() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<List<Hero>> call = api.getHeroes();
call.enqueue(new Callback<List<Hero>>() {
@Override
public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
List<Hero> herolist = response.body();
//Creating a string array for the listview
String[] heroes = new String[herolist.size()];
for(int i =0; i < herolist.size(); i++) {
heroes[i] = herolist.get(i).getName();
}
//displaying the string array into listview
lv.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, heroes));
}
@Override
public void onFailure(Call<List<Hero>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
| 29.865672
| 98
| 0.62019
|
81c8b2deafb0ff602bf43b174728f13af61beaa5
| 4,894
|
package me.m1dnightninja.midnightnpcs.fabric.npc;
import me.m1dnightninja.midnightcore.api.config.ConfigSection;
import me.m1dnightninja.midnightcore.api.inventory.MInventoryGUI;
import me.m1dnightninja.midnightcore.api.module.skin.Skin;
import me.m1dnightninja.midnightcore.api.player.Location;
import me.m1dnightninja.midnightcore.api.registry.MIdentifier;
import me.m1dnightninja.midnightcore.api.text.MComponent;
import me.m1dnightninja.midnightcore.fabric.MidnightCore;
import me.m1dnightninja.midnightcore.fabric.util.ConversionUtil;
import me.m1dnightninja.midnightcore.fabric.util.LocationUtil;
import me.m1dnightninja.midnightnpcs.api.MidnightNPCsAPI;
import me.m1dnightninja.midnightnpcs.api.npc.NPCAction;
import me.m1dnightninja.midnightnpcs.api.trait.Trait;
import me.m1dnightninja.midnightnpcs.api.trait.TraitType;
import me.m1dnightninja.midnightnpcs.common.npc.AbstractNPC;
import me.m1dnightninja.midnightnpcs.fabric.entity.NPCEntity;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.Registry;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerLevel;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
public class FabricNPC extends AbstractNPC {
private NPCEntity entity;
public FabricNPC(Location location, MIdentifier entityType, UUID uuid, MComponent name) {
super(location, entityType, uuid, name);
}
public FabricNPC(Location location, MIdentifier entityType, UUID uuid, MComponent name, NPCEntity ent) {
super(location, entityType, uuid, name);
this.entity = ent;
}
@Override
public Skin getSkin() {
return skin;
}
@Override
public void doTeleport() {
LocationUtil.teleport(entity, location);
}
@Override
public void doSkinUpdate() {
entity.setSkin(skin);
}
@Override
public void doNameUpdate() {
entity.displayNameUpdated();
}
@Override
protected ConfigSection getTraitConfig(TraitType id) {
if (entity == null) return new ConfigSection();
CompoundTag tag = entity.saveWithoutId(new CompoundTag());
if (!tag.contains("MidnightNPC", 10)) return new ConfigSection();
CompoundTag mnpc = tag.getCompound("MidnightNPC");
if (!mnpc.contains("traits", 10)) return new ConfigSection();
CompoundTag traits = mnpc.getCompound("traits");
if (!traits.contains(TraitType.TRAIT_REGISTRY.getId(id).toString())) return new ConfigSection();
return ConversionUtil.fromCompoundTag(traits.getCompound(id.toString()));
}
@Override
public void spawn() {
entity = NPCEntity.fromNPC(this);
entity.level.addFreshEntity(entity);
for(Trait t : traits.values()) {
t.onSpawn();
}
}
@Override
public void respawn() {
if(entity == null) {
spawn();
} else {
entity.respawn();
}
}
@Override
public void kill() {
if(entity != null) {
entity.kill();
}
entity = null;
}
@Override
public void runCommand(String value) {
CommandSourceStack stack = entity.createCommandSourceStack();
MidnightCore.getServer().getCommands().performCommand(stack, value);
}
public CompoundTag saveActions() {
if(actions.isEmpty()) return null;
CompoundTag out = new CompoundTag();
for(Map.Entry<MInventoryGUI.ClickType, Collection<NPCAction>> ent : actions.entrySet()) {
ListTag tag = new ListTag();
for(NPCAction act : ent.getValue()) {
tag.add(ConversionUtil.toCompoundTag(act.save()));
}
out.put(ent.getKey().name(), tag);
}
return out;
}
public void loadActions(CompoundTag tag) {
actions.clear();
for(String s : tag.getAllKeys()) {
MInventoryGUI.ClickType type;
try {
type = MInventoryGUI.ClickType.valueOf(s.toUpperCase(Locale.ROOT));
} catch (IllegalStateException ex) {
MidnightNPCsAPI.getLogger().warn("No click type exists with name " + s + "!");
continue;
}
for(Tag t : tag.getList(s, 10)) {
ConfigSection sec = ConversionUtil.fromCompoundTag((CompoundTag) t);
addCommand(type, NPCAction.parse(sec, this));
}
}
}
public NPCEntity getEntity() {
return entity;
}
public ServerLevel getLevel() {
return MidnightCore.getServer().getLevel(ResourceKey.create(Registry.DIMENSION_REGISTRY, ConversionUtil.toResourceLocation(location.getWorld())));
}
}
| 29.130952
| 154
| 0.666122
|
540b9766035769278a0872158ec5896f719bfe48
| 3,687
|
package de.cotto.lndmanagej.controller;
import com.codahale.metrics.annotation.Timed;
import de.cotto.lndmanagej.controller.dto.ChannelWithWarningsDto;
import de.cotto.lndmanagej.controller.dto.NodeWithWarningsDto;
import de.cotto.lndmanagej.controller.dto.NodesAndChannelsWithWarningsDto;
import de.cotto.lndmanagej.controller.dto.ObjectMapperConfiguration;
import de.cotto.lndmanagej.controller.dto.WarningsDto;
import de.cotto.lndmanagej.model.ChannelId;
import de.cotto.lndmanagej.model.LocalOpenChannel;
import de.cotto.lndmanagej.model.Node;
import de.cotto.lndmanagej.model.Pubkey;
import de.cotto.lndmanagej.model.warnings.ChannelWarnings;
import de.cotto.lndmanagej.model.warnings.NodeWarnings;
import de.cotto.lndmanagej.service.ChannelWarningsService;
import de.cotto.lndmanagej.service.NodeWarningsService;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import static java.util.Map.Entry.comparingByKey;
@RestController
@RequestMapping("/api/")
@Import(ObjectMapperConfiguration.class)
public class WarningsController {
private final NodeWarningsService nodeWarningsService;
private final ChannelWarningsService channelWarningsService;
public WarningsController(
NodeWarningsService nodeWarningsService,
ChannelWarningsService channelWarningsService
) {
this.nodeWarningsService = nodeWarningsService;
this.channelWarningsService = channelWarningsService;
}
@Timed
@GetMapping("/node/{pubkey}/warnings")
public WarningsDto getWarningsForNode(@PathVariable Pubkey pubkey) {
return WarningsDto.createFromModel(nodeWarningsService.getNodeWarnings(pubkey));
}
@Timed
@GetMapping("/channel/{channelId}/warnings")
public WarningsDto getWarningsForChannel(@PathVariable ChannelId channelId) {
return WarningsDto.createFromModel(channelWarningsService.getChannelWarnings(channelId));
}
@Timed
@GetMapping("/warnings")
public NodesAndChannelsWithWarningsDto getWarnings() {
Map<Node, NodeWarnings> nodeWarnings = nodeWarningsService.getNodeWarnings();
List<NodeWithWarningsDto> nodeWarningsList = nodeWarnings.entrySet().stream()
.sorted(comparingByKey())
.map(entry -> getNodeWarningsDto(entry.getKey(), entry.getValue()))
.toList();
Map<LocalOpenChannel, ChannelWarnings> channelWarnings = channelWarningsService.getChannelWarnings();
List<ChannelWithWarningsDto> channelWarningsList = channelWarnings.entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey().getId()))
.map(entry -> getChannelWarningsDto(entry.getKey(), entry.getValue()))
.toList();
return new NodesAndChannelsWithWarningsDto(nodeWarningsList, channelWarningsList);
}
private NodeWithWarningsDto getNodeWarningsDto(Node node, NodeWarnings warnings) {
return new NodeWithWarningsDto(
WarningsDto.createFromModel(warnings).warnings(),
node.alias(),
node.pubkey()
);
}
private ChannelWithWarningsDto getChannelWarningsDto(LocalOpenChannel channel, ChannelWarnings warnings) {
return new ChannelWithWarningsDto(
WarningsDto.createFromModel(warnings).warnings(),
channel.getId()
);
}
}
| 42.37931
| 110
| 0.752373
|
eb9d1090d8e4b1b294b96d1708668ae8798e7d5c
| 3,180
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.eventhubs.proxy;
import com.microsoft.azure.eventhubs.ConnectionStringBuilder;
import com.microsoft.azure.eventhubs.EventData;
import com.microsoft.azure.eventhubs.EventHubClient;
import com.microsoft.azure.eventhubs.EventHubException;
import com.microsoft.azure.eventhubs.EventPosition;
import com.microsoft.azure.eventhubs.PartitionReceiver;
import com.microsoft.azure.eventhubs.PartitionSender;
import com.microsoft.azure.eventhubs.ProxyConfiguration;
import com.microsoft.azure.eventhubs.RetryPolicy;
import com.microsoft.azure.eventhubs.TransportType;
import com.microsoft.azure.eventhubs.lib.ApiTestBase;
import com.microsoft.azure.eventhubs.lib.TestContext;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ProxyIntegrationTest extends ApiTestBase {
private static final String PARTITION_ID = "0";
private EventHubClient client;
private PartitionSender sender;
@Before
public void setup() throws IOException, EventHubException {
final ProxyConfiguration proxyConfiguration = getProxyConfiguration();
Assume.assumeTrue("Cannot run proxy integration tests without setting proxy configuration.",
proxyConfiguration != null);
final ConnectionStringBuilder connectionString = TestContext.getConnectionString()
.setTransportType(TransportType.AMQP_WEB_SOCKETS);
client = EventHubClient.createFromConnectionStringSync(connectionString.toString(), RetryPolicy.getNoRetry(),
TestContext.EXECUTOR_SERVICE, proxyConfiguration);
sender = client.createPartitionSenderSync(PARTITION_ID);
}
@After
public void teardown() throws ExecutionException, InterruptedException {
CompletableFuture.allOf(sender.close(), client.close()).get();
}
/**
* Verifies we can send events through the proxy.
*/
@Test
public void send() throws EventHubException {
sender.sendSync(EventData.create("Hello".getBytes(UTF_8)));
}
/**
* Verifies we can receive events through the proxy.
*/
@Test
public void receive() throws EventHubException, ExecutionException, InterruptedException {
// Arrange
final int numberOfEvents = 15;
final PartitionReceiver receiver = client.createReceiverSync(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME,
PARTITION_ID, EventPosition.fromStartOfStream());
pushEventsToPartition(client, PARTITION_ID, numberOfEvents).get();
// Act
final Iterable<EventData> received = receiver.receiveSync(15);
// Assert
Assert.assertNotNull(received);
final ArrayList<EventData> list = new ArrayList<>();
received.forEach(list::add);
Assert.assertEquals(numberOfEvents, list.size());
}
}
| 35.730337
| 117
| 0.750629
|
0b57e8a86ed8261563929f39bbfabf02e6a9c5cd
| 1,276
|
package controller;
import java.io.IOException;
import java.sql.SQLException;
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 util.Delete;
@WebServlet("/DeleteController")
public class DeleteController extends HttpServlet {
private static final long serialVersionUID = 1L;
public DeleteController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
int x=Delete.deleteTalk(Integer.parseInt(request.getParameter("talkid")));
if(x==1)
response.sendRedirect("AdminPannel.jsp");
} catch (NumberFormatException e) {
System.out.println("Wrong talkid entered");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| 26.040816
| 119
| 0.747649
|
41de3fda9c707112db3c9a4ec5a0bd6f7a3506f0
| 13,637
|
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.material.catalog.bottomappbar;
import io.material.catalog.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import androidx.annotation.ColorInt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.bottomappbar.BottomAppBarTopEdgeTreatment;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.shape.CutCornerTreatment;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.ShapeAppearanceModel;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import io.material.catalog.feature.DemoFragment;
import io.material.catalog.feature.OnBackPressedHandler;
import io.material.catalog.themeswitcher.ThemeSwitcherHelper;
/** A fragment that displays the main Bottom App Bar demos for the Catalog app. */
public class BottomAppBarMainDemoFragment extends DemoFragment implements OnBackPressedHandler {
public final String PREFERENCES = "mPREFERENCES";
SharedPreferences sp;
SharedPreferences.Editor spe;
protected BottomAppBar bar;
protected CoordinatorLayout coordinatorLayout;
protected FloatingActionButton fab;
protected MaterialButton applyAlpha;
protected TextInputEditText alphaValue;
protected TextView savedConfigurations;
protected MaterialCardView card1;
protected MaterialCardView card2;
protected MaterialCardView card3;
protected MaterialCardView card4;
protected MaterialCardView card5;
protected MaterialCardView card6;
protected MaterialCardView card7;
protected MaterialCardView card8;
@Nullable private ThemeSwitcherHelper themeSwitcherHelper;
private BottomSheetBehavior<View> bottomDrawerBehavior;
@Override
public void onCreate(@Nullable Bundle bundle) {
super.onCreate(bundle);
setHasOptionsMenu(true);
// The theme switcher helper is used in an adhoc way with the toolbar since the BottomAppBar is
// set as the action bar.
themeSwitcherHelper = new ThemeSwitcherHelper(getParentFragmentManager());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.demo_primary, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
showSnackbar(menuItem.getTitle());
return true;
}
@LayoutRes
public int getBottomAppBarContent() {
return R.layout.cat_bottomappbar_fragment;
}
/**
* <p>Finds the n-th index within a String, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
* <p>Note that matches may overlap<p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th {@code searchStr} to find, overlapping matches are allowed.
* @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()
* @return the n-th index of the search CharSequence,
* {@code -1} if no match or {@code null} string input
*/
private static int ordinalIndexOf(final String str, final String searchStr, final int ordinal, final boolean lastIndex) {
if (str == null || searchStr == null || ordinal <= 0) {
return -1;
}
if (searchStr.length() == 0) {
return lastIndex ? str.length() : 0;
}
int found = 0;
// set the initial index beyond the end of the string
// this is to allow for the initial index decrement/increment
int index = lastIndex ? str.length() : -1;
do {
if (lastIndex) {
index = str.lastIndexOf(searchStr, index - 1); // step backwards thru string
} else {
index = str.indexOf(searchStr, index + 1); // step forwards through string
}
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}
@Override
public View onCreateDemoView(
LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
View view = layoutInflater.inflate(getBottomAppBarContent(), viewGroup, false);
sp = PreferenceManager.getDefaultSharedPreferences(view.getContext());
spe = sp.edit();
Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setTitle(getDefaultDemoTitle());
themeSwitcherHelper.onCreateOptionsMenu(toolbar.getMenu(), getActivity().getMenuInflater());
toolbar.setOnMenuItemClickListener(themeSwitcherHelper::onOptionsItemSelected);
toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed());
coordinatorLayout = view.findViewById(R.id.coordinator_layout);
bar = view.findViewById(R.id.bar);
((AppCompatActivity) getActivity()).setSupportActionBar(bar);
savedConfigurations = view.findViewById(R.id.saved_configurations);
savedConfigurations.setText(sp.getString(PREFERENCES, "No configurations saved yet."));
setUpBottomDrawer(view);
fab = view.findViewById(R.id.fab);
NavigationView navigationView = view.findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(
item -> {
showSnackbar(item.getTitle());
return false;
});
applyAlpha = view.findViewById(R.id.apply_alpha_button);
alphaValue = view.findViewById(R.id.alpha_value);
card1 = view.findViewById(R.id.card1);
card2 = view.findViewById(R.id.card2);
card3 = view.findViewById(R.id.card3);
card4 = view.findViewById(R.id.card4);
card5 = view.findViewById(R.id.card5);
card6 = view.findViewById(R.id.card6);
card7 = view.findViewById(R.id.card7);
card8 = view.findViewById(R.id.card8);
view.<MaterialButton>findViewById(R.id.delete_all).setOnClickListener(view1 -> {
spe.putString(PREFERENCES, "").commit();
savedConfigurations.setText("");
});
view.<MaterialButton>findViewById(R.id.delete_last).setOnClickListener(view1 -> {
String string = sp.getString(PREFERENCES, "");
String substring = string.substring(0, ordinalIndexOf(string, "\n", 2, true) + 1);
spe.putString(PREFERENCES, substring).commit();
savedConfigurations.setText(substring);
});
applyAlpha.setOnClickListener(view1 -> {
Editable text = alphaValue.getText();
if(text != null) {
int value = Integer.parseInt(text.toString());
TypedValue typedValue = new TypedValue();
Resources.Theme theme = view1.getContext().getTheme();
theme.resolveAttribute(R.attr.colorSecondaryVariant, typedValue, true);
@ColorInt int color = typedValue.data;
ColorStateList secondaryVariantColor = ColorStateList.valueOf(color).withAlpha(value);
card1.setCardBackgroundColor(secondaryVariantColor);
card2.setCardBackgroundColor(secondaryVariantColor);
card3.setCardBackgroundColor(secondaryVariantColor);
card4.setCardBackgroundColor(secondaryVariantColor);
card5.setCardBackgroundColor(secondaryVariantColor);
card6.setCardBackgroundColor(secondaryVariantColor);
card7.setCardBackgroundColor(secondaryVariantColor);
card8.setCardBackgroundColor(secondaryVariantColor);
}
});
fab.setOnClickListener(v -> {
Editable text = alphaValue.getText();
int value = 0;
if(text != null) {
String a = text.toString();
if (!a.equals("")) {
value = Integer.parseInt(text.toString());
}
}
Context context = view.getContext();
String result = "primary: " + Integer.toHexString(getColorFromAttr(context, R.attr.colorPrimary)) + ", secondary: " + Integer.toHexString(getColorFromAttr(context, R.attr.colorSecondary)) + ", variant: " + Integer.toHexString(getColorFromAttr(context, R.attr.colorSecondaryVariant)) + ", Alpha: " + value + "\n";
showSnackbar("Configuration saved: " + result);
String previous = sp.getString(PREFERENCES, "");
String newString = previous + result;
spe.putString(PREFERENCES, newString).commit();
savedConfigurations.setText(newString);
});
/*Button centerButton = view.findViewById(R.id.center);
Button endButton = view.findViewById(R.id.end);
ToggleButton attachToggle = view.findViewById(R.id.attach_toggle);
attachToggle.setChecked(fab.getVisibility() == View.VISIBLE);
centerButton.setOnClickListener(
v -> {
bar.setFabAlignmentModeAndReplaceMenu(
BottomAppBar.FAB_ALIGNMENT_MODE_CENTER, R.menu.demo_primary);
});
endButton.setOnClickListener(
v -> {
bar.setFabAlignmentModeAndReplaceMenu(
BottomAppBar.FAB_ALIGNMENT_MODE_END, R.menu.demo_primary_alternate);
});
attachToggle.setOnCheckedChangeListener(
(buttonView, isChecked) -> {
if (isChecked) {
fab.show();
} else {
fab.hide();
}
});
ToggleButton barScrollToggle = view.findViewById(R.id.bar_scroll_toggle);
barScrollToggle.setChecked(bar.getHideOnScroll());
barScrollToggle.setOnCheckedChangeListener(
(buttonView, isChecked) -> bar.setHideOnScroll(isChecked));
ToggleButton fabAnimToggle = view.findViewById(R.id.fab_animation_mode_toggle);
fabAnimToggle.setOnCheckedChangeListener(
(buttonView, isChecked) ->
bar.setFabAnimationMode(
isChecked
? BottomAppBar.FAB_ANIMATION_MODE_SLIDE
: BottomAppBar.FAB_ANIMATION_MODE_SCALE));
*/
setUpBottomAppBarShapeAppearance();
return view;
}
@ColorInt public int getColorFromAttr(Context context, int attr){
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.data;
}
@Override
public boolean onBackPressed() {
if (bottomDrawerBehavior.getState() != BottomSheetBehavior.STATE_HIDDEN) {
bottomDrawerBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
return true;
}
return false;
}
@Override
public boolean shouldShowDefaultDemoActionBar() {
return false;
}
private void setUpBottomAppBarShapeAppearance() {
ShapeAppearanceModel fabShapeAppearanceModel = fab.getShapeAppearanceModel();
boolean cutCornersFab =
fabShapeAppearanceModel.getBottomLeftCorner() instanceof CutCornerTreatment
&& fabShapeAppearanceModel.getBottomRightCorner() instanceof CutCornerTreatment;
BottomAppBarTopEdgeTreatment topEdge =
cutCornersFab
? new BottomAppBarCutCornersTopEdge(
bar.getFabCradleMargin(),
bar.getFabCradleRoundedCornerRadius(),
bar.getCradleVerticalOffset())
: new BottomAppBarTopEdgeTreatment(
bar.getFabCradleMargin(),
bar.getFabCradleRoundedCornerRadius(),
bar.getCradleVerticalOffset());
MaterialShapeDrawable babBackground = (MaterialShapeDrawable) bar.getBackground();
babBackground.setShapeAppearanceModel(
babBackground.getShapeAppearanceModel().toBuilder().setTopEdge(topEdge).build());
}
protected void setUpBottomDrawer(View view) {
View bottomDrawer = coordinatorLayout.findViewById(R.id.bottom_drawer);
bottomDrawerBehavior = BottomSheetBehavior.from(bottomDrawer);
bottomDrawerBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
bar.setNavigationOnClickListener(
v -> bottomDrawerBehavior.setState(BottomSheetBehavior.STATE_HALF_EXPANDED));
bar.setNavigationIcon(R.drawable.ic_drawer_menu_24px);
bar.replaceMenu(R.menu.demo_primary);
}
private void showSnackbar(CharSequence text) {
Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_LONG)
.setAnchorView(fab.getVisibility() == View.VISIBLE ? fab : bar)
.show();
}
}
| 41.075301
| 318
| 0.728166
|
115450b79edf5b3687f394cd3bc9b6b2db72957a
| 1,092
|
public class Entita extends Thread {
private Monitor m;
private int id;
private String tipo;
public Entita(Monitor m, int id, String tipo) {
this.m = m;
this.id = id;
this.tipo = tipo;
}
public int getID() {
return this.id;
}
public String getTipo() {
return this.tipo;
}
public void run() {
try {
// Sostituire il nome dei metodi con i metodi del monitor utilizzati.
// NB FARE QUI TUTTE LE SLEEP NECESSARIE A SIMULARE LA DURATA DI UN'AZIONE.
// NB2 sfruttare i getter di entita
m.entra(this.getID(), this.getTipo());
Thread.sleep(500); // Azione che simula la durata dell'entrata
m.vota(this.getID(), this.getTipo());
Thread.sleep(700); // Azione che simula la durata di voto
m.esce(this.getID(), this.getTipo());
Thread.sleep(200); // Azione che simula la durata dell'uscita
} catch (
InterruptedException e) {
e.printStackTrace();
}
}
}
| 27.3
| 87
| 0.554945
|
c75e25766d364686895bba77b0817b61b55b4f74
| 642
|
package ru.job4j.array;
/**
*Class RatateArray.
*@author edzabarov
*@since 19.07.2017
*/
public class RotateArray {
/**
* rotate.
*@param array - array
*@return array;
*/
public int[][] rotate(int[][] array) {
int[] auxiliary = new int[array.length * array.length];
for (int i = 0, z = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++, z++) {
auxiliary[z] = array[i][j];
}
}
for (int i = 0, z = 0; i < array.length; z = ++i) {
for (int j = 0; j < array.length; j++) {
z = (z + array.length * (array.length - 1)) % auxiliary.length;
array[i][j] = auxiliary[z];
}
}
return array;
}
}
| 22.137931
| 67
| 0.55296
|
f083dac5661dbc0dfccce23ff759304374392d6a
| 1,242
|
package com.sickworm.wechat.graph;
import android.graphics.Canvas;
import android.graphics.Paint;
import java.util.Locale;
public class Point extends Graph {
private static final Paint DEFAULT_PAINT;
static {
DEFAULT_PAINT = new Paint();
DEFAULT_PAINT.setColor(Graph.TYPE_RED);
DEFAULT_PAINT.setStyle(Paint.Style.STROKE);
DEFAULT_PAINT.setStrokeCap(Paint.Cap.ROUND);
DEFAULT_PAINT.setStrokeWidth(16);
}
public int x;
public int y;
/**
* 用于区分点类型,值为颜色
*/
public int type;
public Point(int x, int y) {
this(x, y, Graph.TYPE_RED);
}
public Point(int x, int y, int type) {
this.x = x;
this.y = y;
this.type = type;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Point)) {
return false;
}
Point point = (Point) obj;
return x == point.x && y == point.y;
}
@Override
public void draw(Canvas canvas) {
DEFAULT_PAINT.setColor(type);
canvas.drawPoint(x, y, DEFAULT_PAINT);
}
@Override
public String toString() {
return String.format(Locale.ENGLISH, "(% 4d, % 4d)", x, y);
}
}
| 22.178571
| 67
| 0.586957
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.