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
|
---|---|---|---|---|---|
8062309bc93bc050ec35ba11f1ba0aaace828c79 | 445 | class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0, j = 0, k = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
++i;
} else if (nums1[i] > nums2[j]) {
++j;
} else {
nums1[k++] = nums1[i++];
++j;
}
}
return Arrays.copyOfRange(nums1, 0, k);
}
} | 24.722222 | 54 | 0.440449 |
fc3f837a568cb12ffdfaada77673689e94a4b700 | 1,499 | package igao;
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class RotatedDigits {
Set<Integer> good = new HashSet<>() {{
add(2);
add(5);
add(6);
add(9);
}};
Set<Integer> neutral = new HashSet<>() {
{
add(0);
add(1);
add(8);
}
};
public static void main(String[] args) {
RotatedDigits solver = new RotatedDigits();
assert solver.solve(1) == 0;
assert solver.solve(2) == 1;
assert solver.solve(12) == 5;
assert solver.solve(21) == 10;
}
private int solve(int number) {
int total = 0;
for (int i = 1; i <= number; i++) {
if (i < 10 && good.contains(i)) {
total++;
} else if (isGoodNumber(i)) {
total++;
}
}
return total;
}
private boolean isGoodNumber(int i) {
int n = i;
boolean hasGoodNumber = false;
boolean hasBadNumber = false;
while (n > 0) {
int digit = n % 10;
if (good.contains(digit)) {
hasGoodNumber = true;
} else if (!neutral.contains(digit)) {
hasBadNumber = true;
}
n = n / 10;
}
return hasGoodNumber && !hasBadNumber;
}
}
| 23.061538 | 52 | 0.453636 |
b598bafb2b762e55509146070d5e3b536e91a850 | 375 | package com.AIS.Modul.MataKuliah.Repository;
import java.util.List;
import java.util.UUID;
import com.sia.modul.domain.RPMetodePemb;
public interface RPMetodePembRepository {
public List<RPMetodePemb> findByRPPerTemu(UUID idRPPerTemu);
public UUID insert(RPMetodePemb mp);
public RPMetodePemb findById(UUID idRPMetodePemb);
public List<RPMetodePemb> findAll();
}
| 19.736842 | 61 | 0.802667 |
16e51eb73afbbe05388ef78abe97d3fbe57f836c | 1,044 | package de.lemonpie.beddomischer.storage;
import de.lemonpie.beddomischer.BeddoMischerMain;
import de.lemonpie.beddomischer.model.Overlay;
import de.tobias.logger.Logger;
import java.sql.SQLException;
import java.util.List;
public class OverlaySerializer
{
private static final String fileName = BeddoMischerMain.BASE_PATH + "/Overlay.json";
public static synchronized void saveOverlay(Overlay overlay)
{
try
{
BeddoMischerMain.getOverlayDao().update(overlay);
}
catch(SQLException e)
{
Logger.error(e);
}
}
public static Overlay loadOverlay()
{
try
{
final List<Overlay> overlays = BeddoMischerMain.getOverlayDao().queryForAll();
if(overlays.isEmpty())
{
return createOverlay();
}
return overlays.get(0);
}
catch(SQLException e)
{
return createOverlay();
}
}
private static Overlay createOverlay()
{
Overlay overlay = new Overlay();
try
{
BeddoMischerMain.getOverlayDao().create(overlay);
return overlay;
}
catch(SQLException e1)
{
return null;
}
}
}
| 18 | 85 | 0.713602 |
d202bb448dea2bd19280dd25f27da0a6469030ec | 4,120 | package ejercicios.VentanaBloc;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Ventana extends Frame implements ActionListener {
// Variables
TextArea txt_out;
Panel panel_superior, panel_central;
JButton btnColor, btnTamanio, btnGuardar, btnAbrir, btnSalir, btnComillas;
File archivo;
JLabel txt_esta;
/**
*
*/
private static final long serialVersionUID = 1L;
public Ventana() {
initComponents();
}
public void initComponents() {
this.setLayout(new BorderLayout());
btnColor = new JButton("Color");
btnColor.addActionListener(this);
btnTamanio = new JButton("Tamaño");
btnTamanio.addActionListener(this);
btnGuardar = new JButton("Guardar");
btnGuardar.addActionListener(this);
btnAbrir = new JButton("Abrir");
btnAbrir.addActionListener(this);
btnSalir = new JButton("Salir");
btnSalir.addActionListener(this);
btnComillas = new JButton("Comillas");
btnComillas.addActionListener(this);
txt_out = new TextArea();
txt_out.setFont(new Font(null, 1, 12));
panel_superior = new Panel();
panel_superior.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
panel_superior.add(btnColor);
panel_superior.add(btnTamanio);
panel_superior.add(btnGuardar);
panel_superior.add(btnAbrir);
panel_superior.add(btnSalir);
panel_superior.add(btnComillas);
panel_central = new Panel();
panel_central.setLayout(new BorderLayout());
panel_central.add(txt_out, BorderLayout.CENTER);
this.add(panel_central, BorderLayout.CENTER);
this.add(panel_superior, BorderLayout.NORTH);
// Preferencia en la Ventana
this.setSize(600, 500);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
//
if (e.getSource() == btnColor) {
try {
int c = Integer.parseInt(JOptionPane.showInputDialog(null,
"Elija su Color Segun La Lista \n" + "0 - Black\n" + "1 - Blue\n" + "2 - Red\n" + "3 - Cyan\n"
+ "4 - Pink\n" + "5 - Green\n" + "6 - Yellow\n"));
cambiarColor(c);
} catch (Exception exc) {
System.out.println(exc);
}
}
if (e.getSource() == btnTamanio) {
int t = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el Tamaño de Texto"));
txt_out.setFont(new Font(null, 1, t));
}
if (e.getSource() == btnSalir) {
System.exit(0);
}
if (e.getSource() == btnComillas) {
String texto, select;
texto = txt_out.getText();
select = txt_out.getSelectedText();
txt_out.setText(texto.split(select)[0] + "'" + select + "'" + texto.split(select)[1]);
}
}
public void cambiarColor(int c) {
switch (c) {
case 0:
txt_out.setForeground(Color.BLACK);
break;
case 1:
txt_out.setForeground(Color.RED);
break;
case 2:
txt_out.setForeground(Color.PINK);
break;
case 3:
txt_out.setForeground(Color.CYAN);
break;
case 4:
txt_out.setForeground(Color.BLUE);
break;
case 5:
txt_out.setForeground(Color.GREEN);
break;
case 6:
txt_out.setForeground(Color.YELLOW);
break;
default:
txt_out.setForeground(Color.BLACK);
break;
}
}
public static void main(String args[]) {
Ventana v = new Ventana();
v.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
} | 29.640288 | 118 | 0.567961 |
23c0c2585536820c89a0e8eefaa20aa2788125cb | 192 | package com.demo.refletc;
@DiyComponent(name = "1111")
@DiyAnnotation(gg = "gg1")
public class Component1 {
private String myName = "";
public String getMyName() {
return myName;
}
}
| 13.714286 | 28 | 0.6875 |
b580134581a869d7358ff8f276bc30ae3fec443f | 457 | package io.jexxa.application.annotation;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target(TYPE)
@Retention(SOURCE)
@Documented
/*
* Annotation that is not available during runtime. This is for testing purpose only
*/
public @interface UnavailableDuringRuntime
{
}
| 21.761905 | 84 | 0.809628 |
3e896ced799fdfdeb8ec5ab9dbb9938d9577a93d | 19,392 | package com.smile24es.lazy.suite.sample3.student;
import com.smile24es.lazy.beans.enums.AssertionOperationEnum;
import com.smile24es.lazy.beans.enums.DataSourceEnum;
import com.smile24es.lazy.beans.suite.ApiCall;
import com.smile24es.lazy.beans.suite.QueryParam;
import com.smile24es.lazy.beans.suite.assertions.AssertionRule;
import com.smile24es.lazy.beans.suite.assertions.BodyValueAssertion;
import com.smile24es.lazy.exception.LazyCoreException;
import com.smile24es.lazy.suite.sample0.dto.AccountTo;
import com.smile24es.lazy.suite.sample0.dto.ErrorTo;
import com.smile24es.lazy.wrapper.Actions;
import com.smile24es.lazy.wrapper.Assert;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.text.MessageFormat.format;
public class StudentApiCall {
public static ApiCall updateCompleteAccount() {
ApiCall getAccountApiCall = new ApiCall("Update Complete Student");
getAccountApiCall.setUri("service/lazy/test");
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(200));
//Null/Not Null assertions
getAccountApiCall.addAssertionRule(Assert.notNull("$.accountId"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.accountName"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.isActive"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.monthlyCharge"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.phone"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.phone.number"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[0].id"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[0].key"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[0].value"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[0].isActive"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[0].chargeForFeature"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].id"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].key"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].value"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].isActive"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].chargeForFeature"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].supportedMethods"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].supportedMethods[0].type"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].supportedMethods[0].minValue"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].supportedMethods[1].type"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.settings[1].supportedMethods[1].allowed"));
getAccountApiCall.addAssertionRule(Assert.isKeyAvailable("$.accountName"));
getAccountApiCall.addAssertionRule(Assert.isKeyUnavailable("$.invalidKey"));
//Equal assertions
getAccountApiCall.addAssertionRule(Assert.equal("$.accountId", 1));
getAccountApiCall.addAssertionRule(Assert.equal("$.accountName", "Smile24"));
getAccountApiCall.addAssertionRule(Assert.equal("$.isActive", true));
getAccountApiCall.addAssertionRule(Assert.equal("$.monthlyCharge", 10.75));
getAccountApiCall.addAssertionRule(Assert.equal("$.phone.number", "12345678"));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[0].id", 840));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[0].key", "payment.period"));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[0].value", "monthly"));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[0].isActive", true));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[0].chargeForFeature", 11.9));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].id", 841));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].key", "payment.method"));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].value", "direct"));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].isActive", true));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].chargeForFeature", 12.86));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].supportedMethods[0].type", "Card"));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].supportedMethods[0].minValue", 1));
getAccountApiCall.addAssertionRule(Assert.equal("$.settings[1].supportedMethods[1].type", "Cash"));
//String operations
getAccountApiCall.addAssertionRule(Assert.contains("$.accountName", "Smile"));
getAccountApiCall.addAssertionRule(Assert.notContains("$.accountName", "Lazy"));
//Max min - numeric logic
getAccountApiCall.addAssertionRule(Assert.greaterThan("$.monthlyCharge", 10.00));
getAccountApiCall.addAssertionRule(Assert.lessThan("$.monthlyCharge", 11.00));
getAccountApiCall.addAssertionRule(Assert.greaterThanOrEqual("$.monthlyCharge", 10.75));
getAccountApiCall.addAssertionRule(Assert.lessThanOrEqual("$.monthlyCharge", 10.75));
getAccountApiCall.addAssertionRule(Assert.between("$.monthlyCharge", 10.00, 11.00));
//List related logic
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[*].key", Arrays.asList("payment.period", "payment.method")));
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[*].id", Arrays.asList(840, 841)));
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[*].chargeForFeature", Arrays.asList(11.9, 12.86)));
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[*].isActive", Arrays.asList(true, true)));
getAccountApiCall.addAssertionRule(Assert.containsAll("$.settings[*].key", Arrays.asList("payment.period")));
getAccountApiCall.addAssertionRule(Assert.containsAll("$.settings[*].id", Arrays.asList(840)));
getAccountApiCall.addAssertionRule(Assert.containsAll("$.settings[*].chargeForFeature", Arrays.asList(11.9)));
getAccountApiCall.addAssertionRule(Assert.containsAll("$.settings[*].isActive", Arrays.asList(true)));
getAccountApiCall.addAssertionRule(Assert.containsAny("$.settings[*].key", Arrays.asList("payment.period", "INVALID")));
getAccountApiCall.addAssertionRule(Assert.containsAny("$.settings[*].id", Arrays.asList(840, 1000)));
getAccountApiCall.addAssertionRule(Assert.containsAny("$.settings[*].chargeForFeature", Arrays.asList(11.9, 1000)));
getAccountApiCall.addAssertionRule(Assert.containsAny("$.settings[*].isActive", Arrays.asList(true, false)));
//Advanced list related logic
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[?(@.key=='payment.period')].value", Arrays.asList("monthly")));
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[?(@.supportedMethods)].id", Arrays.asList(841)));
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[?(@.supportedMethods)].supportedMethods.[?(@.type == 'Card')].minValue", Arrays.asList(1)));
getAccountApiCall.addAssertionRule(Assert.containsExactly("$.settings[?(@.supportedMethods)].supportedMethods.[?(@.type == 'Cash')].allowed[*]", Arrays.asList("SLR", "USD")));
return getAccountApiCall;
}
public static ApiCall getInvalidAccountApiCall(String accountId, ErrorTo errorTo) {
ApiCall getAccountApiCall = new ApiCall("Get invalid student by Id");
getAccountApiCall.setUri(format("service/accounts/{0}", accountId));
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(404));
getAccountApiCall.addAssertionRule(Assert.notNull("$.code"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.description"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.additionalInfo"));
getAccountApiCall.addAssertionRule(Assert.equal("$.code", errorTo.getCode()));
getAccountApiCall.addAssertionRule(Assert.equal("$.description", errorTo.getDescription()));
getAccountApiCall.addAssertionRule(Assert.equal("$.additionalInfo", errorTo.getAdditionalInfo()));
return getAccountApiCall;
}
//Invalid assertion - invalid data type
public static ApiCall getInvalidRuleApiCall(String accountId, ErrorTo errorTo) {
ApiCall getAccountApiCall = new ApiCall("Get invalid student by Id");
getAccountApiCall.setUri(format("service/accounts/{0}", accountId));
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(404));
getAccountApiCall.addAssertionRule(Assert.notNull("$.codeInvalid"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.description"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.additionalInfo"));
getAccountApiCall.addAssertionRule(Assert.equal("$.code", errorTo.getCode()));
AssertionRule invalidCustomRule = new AssertionRule("Custom invalid meta-rule assertion", DataSourceEnum.BODY, AssertionOperationEnum.TRUE,
new BodyValueAssertion("$.description", "hhhh"));
getAccountApiCall.addAssertionRule(invalidCustomRule);
getAccountApiCall.addAssertionRule(Assert.equal("$.additionalInfo", errorTo.getAdditionalInfo()));
return getAccountApiCall;
}
//Failed assertion - invalid JSON path
public static ApiCall getFailedRuleApiCall(String accountId, ErrorTo errorTo) {
ApiCall getAccountApiCall = new ApiCall("Get invalid student by Id");
getAccountApiCall.setUri(format("service/accounts/{0}", accountId));
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(404));
getAccountApiCall.addAssertionRule(Assert.notNull("$.codeInvalid"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.description"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.additionalInfo"));
getAccountApiCall.addAssertionRule(Assert.equal("$.code", errorTo.getCode()));
getAccountApiCall.addAssertionRule(Assert.equal("$.description", errorTo.getDescription()));
getAccountApiCall.addAssertionRule(Assert.equal("$.additionalInfo", errorTo.getAdditionalInfo()));
return getAccountApiCall;
}
//Skipped assertion - invalid JSON path
public static ApiCall getSkippedRuleApiCall(String accountId, ErrorTo errorTo) {
ApiCall getAccountApiCall = new ApiCall("Get invalid student by Id");
getAccountApiCall.setPort(5050);
getAccountApiCall.setUri(format("service/accounts/{0}", accountId));
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(404));
getAccountApiCall.addAssertionRule(Assert.notNull("$.codeInvalid"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.description"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.additionalInfo"));
getAccountApiCall.addAssertionRule(Assert.equal("$.code", errorTo.getCode()));
getAccountApiCall.addAssertionRule(Assert.equal("$.description", errorTo.getDescription()));
getAccountApiCall.addAssertionRule(Assert.equal("$.additionalInfo", errorTo.getAdditionalInfo()));
return getAccountApiCall;
}
public static ApiCall createInvalidAccountApiCall(String accountId, ErrorTo errorTo) {
ApiCall getAccountApiCall = new ApiCall("Create invalid student by Id");
getAccountApiCall.setUri(format("service/accounts/{0}", accountId));
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(404));
getAccountApiCall.addAssertionRule(Assert.notNull("$.code"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.description"));
getAccountApiCall.addAssertionRule(Assert.notNull("$.additionalInfo"));
getAccountApiCall.addAssertionRule(Assert.equal("$.code", errorTo.getCode()));
getAccountApiCall.addAssertionRule(Assert.equal("$.description", errorTo.getDescription()));
getAccountApiCall.addAssertionRule(Assert.equal("$.additionalInfo", errorTo.getAdditionalInfo()));
return getAccountApiCall;
}
public static ApiCall getValidAccountApiCallWithOutSettings(AccountTo accountTo) {
ApiCall getAccountApiCall = new ApiCall("Get Student by Id without settings");
getAccountApiCall.setUri("service/accounts/{{lazy.global.created.account.id}}");
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(200));
getAccountApiCall.addAssertionRule(Assert.notNull("Student Name not null assertion", "$.accountName"));
getAccountApiCall.addAssertionRule(Assert.equal("$.accountName", accountTo.getAccountName()));
getAccountApiCall.addAssertionRule(Assert.equal("$.status", accountTo.getAccountStatus()));
getAccountApiCall.addAssertionRule(Assert.equal("$.enterpriseId", accountTo.getEnterpriseId()));
getAccountApiCall.addAssertionRule(Assert.equal("$.versionId", accountTo.getVersionId()));
getAccountApiCall.addAssertionRule(Assert.equal("custom", "$.accountName", "{{lazy.global.created.account.accountName}}"));
return getAccountApiCall;
}
public static ApiCall getValidAccountApiCallWithSettings(AccountTo accountTo) {
ApiCall getAccountApiCall = new ApiCall("Get Student by Id with settings");
getAccountApiCall.setUri("service/accounts/{{lazy.global.created.account.id}}");
getAccountApiCall.setQueryParams(new QueryParam("fake", "test"));
getAccountApiCall.setQueryParams(new QueryParam("settings", "true"));
getAccountApiCall.addAssertionRule(Assert.responseCodeEqual(200));
accountDetailAssertion(accountTo, getAccountApiCall);
getAccountApiCall.addAssertionRule(Assert.equal("custom", "$.accountName", "{{lazy.global.created.account.accountName}}"));
return getAccountApiCall;
}
public static ApiCall createSuccessAccount(AccountTo accountTo) throws LazyCoreException {
ApiCall createAccountApiCall = new ApiCall("Create Complete Student");
createAccountApiCall.setUri("service/accounts");
createAccountApiCall.setUri("service/accounts");
createAccountApiCall.setHttpMethod("POST");
Map<String, Object> templateData = new HashMap<>();
templateData.put("accountName", accountTo.getAccountName());
templateData.put("accountStatus", accountTo.getAccountStatus());
templateData.put("enterpriseId", accountTo.getEnterpriseId());
templateData.put("versionId", accountTo.getVersionId());
templateData.put("settings", accountTo.getAccountSettings());
createAccountApiCall.setRequestBodyFromJsonTemplate("request-body/account-api/templates/create-account.ftl", templateData);
accountDetailAssertion(accountTo, createAccountApiCall);
createAccountApiCall.disableAssertion("account.api.max.response.time");
createAccountApiCall.addAssertionRule(Assert.responseTimeLessThan("300"));
createAccountApiCall.getPostActions().add(Actions.createGlobalVariableFromResponseBody("created.account.id", "$.accountId"));
createAccountApiCall.getPostActions().add(Actions.createGlobalVariableFromResponseBody("created.account.accountName", "$.accountName"));
return createAccountApiCall;
}
public static ApiCall createSuccessAccountMinData(AccountTo accountTo) throws LazyCoreException {
ApiCall createAccountApiCall = new ApiCall("Create Student Simple");
createAccountApiCall.setUri("service/accounts");
createAccountApiCall.setUri("service/accounts");
createAccountApiCall.setHttpMethod("POST");
Map<String, Object> templateData = new HashMap<>();
templateData.put("accountName", accountTo.getAccountName());
templateData.put("accountStatus", accountTo.getAccountStatus());
templateData.put("enterpriseId", accountTo.getEnterpriseId());
templateData.put("versionId", accountTo.getVersionId());
createAccountApiCall.setRequestBodyFromJsonTemplate("request-body/account-api/templates/create-account.ftl", templateData);
createAccountApiCall.addAssertionRule(Assert.notNull("Student Name not null assertion", "$.accountName"));
createAccountApiCall.addAssertionRule(Assert.equal("$.accountName", accountTo.getAccountName()));
createAccountApiCall.addAssertionRule(Assert.equal("$.status", accountTo.getAccountStatus()));
createAccountApiCall.addAssertionRule(Assert.equal("$.enterpriseId", accountTo.getEnterpriseId()));
createAccountApiCall.addAssertionRule(Assert.equal("$.versionId", accountTo.getVersionId()));
createAccountApiCall.disableAssertion("account.api.max.response.time");
createAccountApiCall.addAssertionRule(Assert.responseTimeLessThan("300"));
createAccountApiCall.getPostActions().add(Actions.createGlobalVariableFromResponseBody("created.account.id", "$.accountId"));
createAccountApiCall.getPostActions().add(Actions.createGlobalVariableFromResponseBody("created.account.accountName", "$.accountName"));
return createAccountApiCall;
}
private static void accountDetailAssertion(AccountTo accountTo, ApiCall accountApiCall) {
accountApiCall.addAssertionRule(Assert.notNull("Student Name not null assertion", "$.accountName"));
accountApiCall.addAssertionRule(Assert.equal("$.accountName", accountTo.getAccountName()));
accountApiCall.addAssertionRule(Assert.equal("$.status", accountTo.getAccountStatus()));
accountApiCall.addAssertionRule(Assert.equal("$.enterpriseId", accountTo.getEnterpriseId()));
accountApiCall.addAssertionRule(Assert.equal("$.versionId", accountTo.getVersionId()));
accountApiCall.addAssertionRule(Assert.notNull("Settings not null assertion", "$.settings"));
accountApiCall.addAssertionRule(Assert.equal("Student setting length assertion", "$.settings.length()", accountTo.getAccountSettings().size()));
accountApiCall.addAssertionRule(Assert.equal("setting - 1 - key", "$.settings[0].key", accountTo.getAccountSettings().get(0).getKey()));
accountApiCall.addAssertionRule(Assert.equal("setting - 1 - value", "$.settings[0].value", accountTo.getAccountSettings().get(0).getValue()));
accountApiCall.addAssertionRule(Assert.notNull("setting - 1 - id", "$.settings[0].id"));
accountApiCall.addAssertionRule(Assert.equal("setting - 1 - status", "$.settings[0].settingStatus", "ACTIVE"));
accountApiCall.addAssertionRule(Assert.equal("setting - 2 - key", "$.settings[1].key", accountTo.getAccountSettings().get(1).getKey()));
accountApiCall.addAssertionRule(Assert.equal("setting - 2 - value", "$.settings[1].value", accountTo.getAccountSettings().get(1).getValue()));
accountApiCall.addAssertionRule(Assert.notNull("setting - 2 - id", "$.settings[1].id"));
accountApiCall.addAssertionRule(Assert.equal("setting - 2 - status", "$.settings[1].settingStatus", "ACTIVE"));
}
}
| 68.765957 | 183 | 0.737469 |
ee7059865afba6c77694404319ebd4564fa731b2 | 338 | package org.java_websocket.framing;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.framing.Framedata.Opcode;
public abstract class DataFrame extends FramedataImpl1 {
public DataFrame(Opcode opcode) {
super(opcode);
}
public void isValid() throws InvalidDataException {
}
}
| 24.142857 | 58 | 0.766272 |
13648b7888ea20c25b6445e1670c88e5fb221121 | 329 |
public class Birou {
private int l, L, H;
Sertar sertar1 = new Sertar(10, 12, 5);
Sertar sertar2 = new Sertar(8, 10, 5);
public Birou(int l, int l2, int h) {
this.l = l;
L = l2;
H = h;
}
@Override
public String toString() {
return "Birou: [" + l + ", " + L + ", " + H + "]";
}
}
| 14.954545 | 53 | 0.483283 |
db7b7f809efe379fc6630c428aa9e04ec368421b | 130 | package com.akon.kuripaka;
@FunctionalInterface
public interface ThrowsRunnable<X extends Throwable> {
void run() throws X;
}
| 14.444444 | 54 | 0.776923 |
bae9f7ac535267ade899ef73d6d02b920bffda88 | 10,681 | /*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2012 Zhenghong Wang
*
* 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 zumzum.app.zunzuneando.visor.weather;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;
/**
* A wrapper for all weather information provided by Yahoo weather apis.
* @author Zhenghong Wang
*/
public class WeatherInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String mTitle;
String mDescription;
String mLanguage;
String mLastBuildDate;
String mLocationCity;
String mLocationRegion; // region may be null
String mLocationCountry;
String mWindChill;
String mWindDirection;
String mWindSpeed;
String mAtmosphereHumidity;
String mAtmosphereVisibility;
String mAtmospherePressure;
String mAtmosphereRising;
String mAstronomySunrise;
String mAstronomySunset;
String mConditionTitle;
String mConditionLat;
String mConditionLon;
/*
* information in tag "yweather:condition"
*/
int mCurrentCode;
String mCurrentText;
int mCurrentTempC;
int mCurrentTempF;
String mCurrentConditionIconURL;
Bitmap mCurrentConditionIcon;
String mCurrentConditionDate;
/*
* information in the first tag "yweather:forecast"
*/
/*
* information in the second tag "yweather:forecast"
*/
ForecastInfo mForecastInfo1 = new ForecastInfo();
ForecastInfo mForecastInfo2 = new ForecastInfo();
ForecastInfo mForecastInfo3 = new ForecastInfo();
ForecastInfo mForecastInfo4 = new ForecastInfo();
ForecastInfo mForecastInfo5 = new ForecastInfo();
private List<ForecastInfo> mForecastInfoList;
public WeatherInfo() {
mForecastInfoList = new ArrayList<WeatherInfo.ForecastInfo>();
mForecastInfoList.add(mForecastInfo1);
mForecastInfoList.add(mForecastInfo2);
mForecastInfoList.add(mForecastInfo3);
mForecastInfoList.add(mForecastInfo4);
mForecastInfoList.add(mForecastInfo5);
}
public List<ForecastInfo> getForecastInfoList() {
return mForecastInfoList;
}
protected void setForecastInfoList(List<ForecastInfo> forecastInfoList) {
mForecastInfoList = forecastInfoList;
}
public ForecastInfo getForecastInfo1() {
return mForecastInfo1;
}
protected void setForecastInfo1(ForecastInfo forecastInfo1) {
mForecastInfo1 = forecastInfo1;
}
public ForecastInfo getForecastInfo2() {
return mForecastInfo2;
}
protected void setForecastInfo2(ForecastInfo forecastInfo2) {
mForecastInfo2 = forecastInfo2;
}
public ForecastInfo getForecastInfo3() {
return mForecastInfo3;
}
protected void setForecastInfo3(ForecastInfo forecastInfo3) {
mForecastInfo3 = forecastInfo3;
}
public ForecastInfo getForecastInfo4() {
return mForecastInfo4;
}
protected void setForecastInfo4(ForecastInfo forecastInfo4) {
mForecastInfo4 = forecastInfo4;
}
public ForecastInfo getForecastInfo5() {
return mForecastInfo5;
}
protected void setForecastInfo5(ForecastInfo forecastInfo5) {
mForecastInfo5 = forecastInfo5;
}
public String getCurrentConditionDate() {
return mCurrentConditionDate;
}
protected void setCurrentConditionDate(String currentConditionDate) {
mCurrentConditionDate = currentConditionDate;
}
public int getCurrentCode() {
return mCurrentCode;
}
protected void setCurrentCode(int currentCode) {
mCurrentCode = currentCode;
mCurrentConditionIconURL = "http://l.yimg.com/a/i/us/we/52/" + currentCode + ".gif";
}
public int getCurrentTempF() {
return mCurrentTempF;
}
protected void setCurrentTempF(int currentTempF) {
mCurrentTempF = currentTempF;
mCurrentTempC = this.turnFtoC(currentTempF);
}
public int getCurrentTempC() {
return mCurrentTempC;
}
public String getTitle() {
return mTitle;
}
protected void setTitle(String title) {
mTitle = title;
}
public String getDescription() {
return mDescription;
}
protected void setDescription(String description) {
mDescription = description;
}
public String getLanguage() {
return mLanguage;
}
protected void setLanguage(String language) {
mLanguage = language;
}
public String getLastBuildDate() {
return mLastBuildDate;
}
protected void setLastBuildDate(String lastBuildDate) {
mLastBuildDate = lastBuildDate;
}
public String getLocationCity() {
return mLocationCity;
}
protected void setLocationCity(String locationCity) {
mLocationCity = locationCity;
}
public String getLocationRegion() {
return mLocationRegion;
}
protected void setLocationRegion(String locationRegion) {
mLocationRegion = locationRegion;
}
public String getLocationCountry() {
return mLocationCountry;
}
protected void setLocationCountry(String locationCountry) {
mLocationCountry = locationCountry;
}
public String getWindChill() {
return mWindChill;
}
protected void setWindChill(String windChill) {
mWindChill = windChill;
}
public String getWindDirection() {
return mWindDirection;
}
protected void setWindDirection(String windDirection) {
mWindDirection = windDirection;
}
public String getWindSpeed() {
return mWindSpeed;
}
protected void setWindSpeed(String windSpeed) {
mWindSpeed = windSpeed;
}
public String getAtmosphereHumidity() {
return mAtmosphereHumidity;
}
protected void setAtmosphereHumidity(String atmosphereHumidity) {
mAtmosphereHumidity = atmosphereHumidity;
}
public String getAtmosphereVisibility() {
return mAtmosphereVisibility;
}
protected void setAtmosphereVisibility(String atmosphereVisibility) {
mAtmosphereVisibility = atmosphereVisibility;
}
public String getAtmospherePressure() {
return mAtmospherePressure;
}
protected void setAtmospherePressure(String atmospherePressure) {
mAtmospherePressure = atmospherePressure;
}
public String getAtmosphereRising() {
return mAtmosphereRising;
}
protected void setAtmosphereRising(String atmosphereRising) {
mAtmosphereRising = atmosphereRising;
}
public String getAstronomySunrise() {
return mAstronomySunrise;
}
protected void setAstronomySunrise(String astronomySunrise) {
mAstronomySunrise = astronomySunrise;
}
public String getAstronomySunset() {
return mAstronomySunset;
}
protected void setAstronomySunset(String astronomySunset) {
mAstronomySunset = astronomySunset;
}
public String getConditionTitle() {
return mConditionTitle;
}
protected void setConditionTitle(String conditionTitle) {
mConditionTitle = conditionTitle;
}
public String getConditionLat() {
return mConditionLat;
}
protected void setConditionLat(String conditionLat) {
mConditionLat = conditionLat;
}
public String getConditionLon() {
return mConditionLon;
}
protected void setConditionLon(String conditionLon) {
mConditionLon = conditionLon;
}
public String getCurrentText() {
return mCurrentText;
}
protected void setCurrentText(String currentText) {
mCurrentText = currentText;
}
protected void setCurrentTempC(int currentTempC) {
mCurrentTempC = currentTempC;
}
public String getCurrentConditionIconURL() {
return mCurrentConditionIconURL;
}
public Bitmap getCurrentConditionIcon() {
return mCurrentConditionIcon;
}
protected void setCurrentConditionIcon(Bitmap mCurrentConditionIcon) {
this.mCurrentConditionIcon = mCurrentConditionIcon;
}
private int turnFtoC(int tempF) {
return (tempF - 32) * 5 / 9;
}
public class ForecastInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String mForecastDay;
private String mForecastDate;
private int mForecastCode;
private int mForecastTempHighC;
private int mForecastTempLowC;
private int mForecastTempHighF;
private int mForecastTempLowF;
private String mForecastConditionIconURL;
private Bitmap mForecastConditionIcon;
private String mForecastText;
public Bitmap getForecastConditionIcon() {
return mForecastConditionIcon;
}
protected void setForecastConditionIcon(Bitmap mForecastConditionIcon) {
this.mForecastConditionIcon = mForecastConditionIcon;
}
public String getForecastDay() {
return mForecastDay;
}
protected void setForecastDay(String forecastDay) {
mForecastDay = forecastDay;
}
public String getForecastDate() {
return mForecastDate;
}
protected void setForecastDate(String forecastDate) {
mForecastDate = forecastDate;
}
public int getForecastCode() {
return mForecastCode;
}
protected void setForecastCode(int forecastCode) {
mForecastCode = forecastCode;
mForecastConditionIconURL = "http://l.yimg.com/a/i/us/we/52/" + forecastCode + ".gif";
}
public int getForecastTempHighC() {
return mForecastTempHighC;
}
protected void setForecastTempHighC(int forecastTempHighC) {
mForecastTempHighC = forecastTempHighC;
}
public int getForecastTempLowC() {
return mForecastTempLowC;
}
protected void setForecastTempLowC(int forecastTempLowC) {
mForecastTempLowC = forecastTempLowC;
}
public int getForecastTempHighF() {
return mForecastTempHighF;
}
protected void setForecastTempHighF(int forecastTempHighF) {
mForecastTempHighF = forecastTempHighF;
mForecastTempHighC = turnFtoC(forecastTempHighF);
}
public int getForecastTempLowF() {
return mForecastTempLowF;
}
protected void setForecastTempLowF(int forecastTempLowF) {
mForecastTempLowF = forecastTempLowF;
mForecastTempLowC = turnFtoC(forecastTempLowF);
}
public String getForecastConditionIconURL() {
return mForecastConditionIconURL;
}
public String getForecastText() {
return mForecastText;
}
protected void setForecastText(String forecastText) {
mForecastText = forecastText;
}
}
}
| 23.735556 | 90 | 0.735605 |
dfc9173758dff19808fb2eaefbe1d961ad02c610 | 2,330 | package com.course.server.service;
import com.course.server.domain.Chapter;
import com.course.server.domain.ChapterExample;
import com.course.server.dto.ChapterDto;
import com.course.server.dto.ChapterPageDto;
import com.course.server.dto.PageDto;
import com.course.server.mapper.ChapterMapper;
import com.course.server.mapper.TestMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName : TestService
* @Description :
* @Author : cybersa
* @Date: 2020-07-20 20:45
*/
@Service
public class ChapterService {
@Autowired
private ChapterMapper chapterMapper;
public void list(ChapterPageDto chapterPageDto) {
PageHelper.startPage(chapterPageDto.getPage(), chapterPageDto.getSize());
ChapterExample chapterExample = new ChapterExample();
ChapterExample.Criteria criteria = chapterExample.createCriteria();
if (!StringUtils.isEmpty(chapterPageDto.getCourseId())) {
criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
}
List<Chapter> chapters = chapterMapper.selectByExample(chapterExample);
PageInfo<Chapter> chapterPageInfo = new PageInfo<>(chapters);
chapterPageDto.setTotal(chapterPageInfo.getTotal());
List<ChapterDto> chapterDtoList = CopyUtil.copyList(chapters, ChapterDto.class);
chapterPageDto.setList(chapterDtoList);
}
public void save(ChapterDto chapterDto) {
Chapter copy = CopyUtil.copy(chapterDto, Chapter.class);
if (StringUtils.isEmpty(chapterDto.getId())) {
this.insert(copy);
}
else {
this.update(copy);
}
}
protected void insert(Chapter chapter) {
chapter.setId(UuidUtil.getShortUuid());
chapterMapper.insert(chapter);
}
protected void update(Chapter chapter) {
chapterMapper.updateByPrimaryKey(chapter);
}
public void delete(String id) {
chapterMapper.deleteByPrimaryKey(id);
}
}
| 32.361111 | 88 | 0.725322 |
dffcdedcfe059838a947a11f91fdf6c72908b66f | 474 | package com.ziggeo.demos;
import com.ziggeo.Ziggeo;
import org.json.JSONArray;
import org.json.JSONObject;
public class VideoListLimit {
public static void main(String[] args) throws Exception {
Ziggeo ziggeo = new Ziggeo(args[0], args[1], "");
JSONArray videos = ziggeo.videos().index(new JSONObject("{\"skip\":" + Integer.parseInt(args[2]) + ", \"limit\":" + Integer.parseInt(args[3]) + "}"));
System.out.println(videos.length());
}
}
| 27.882353 | 158 | 0.654008 |
c21f6cc0578ac76e705863cbff88cc2d072279fb | 506 | package hicp_client.text;
public interface TextItemAdapterListener {
/**
Implementer should save text item adapter tla,
then call tla.setAdapter(this).
*/
public void setAdapter(TextItemAdapter tia);
/**
Implementer apply text to the displayed component.
Called in GUI thread.
*/
public void setTextInvoked(String text);
/**
Implementer call removeAdapter() on the saved text item adapter.
*/
public void removeAdapter();
}
| 24.095238 | 72 | 0.656126 |
6cf7ebb951eb07205c3af08ac4fae9fc5f907504 | 693 | package ru.job4j.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MatrixIterator implements Iterator {
private final int[][] matrix;
private int x = 0;
private int y = 0;
public MatrixIterator(int[][] matrix) {
this.matrix = matrix;
}
@Override
public boolean hasNext() {
return matrix.length > y && matrix[y].length > x;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int next = matrix[y][x++];
if (matrix[y].length <= x) {
y++;
x = 0;
}
return next;
}
}
| 20.382353 | 57 | 0.551227 |
014623b9ca1c3c96bf0839be83521a92af735d7a | 344 | package com.ringerbell.db;
import android.provider.BaseColumns;
public class OfferGalleryBaseColumns {
public static abstract class OfferGalleryColumns implements BaseColumns {
public static final String COLUMN_OFFER_MESSAGE_ID = "offer_message_id";
public static final String COLUMN_IMAGE_URL = "image_url";
}
}
| 21.5 | 80 | 0.764535 |
36cf9d7dc630c05f13d82b812f76839d097beb1f | 10,727 | package net.ipip.ipdb;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.io.FileUtils;
import sun.net.util.IPAddressUtil;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;
public class FileDecoder {
Map<String, Map<String, CityInfo>> netStates = Maps.newHashMap();
LinkedList<ItemInfo> itemInfos = Lists.newLinkedList();
private int fileSize;
private int nodeCount;
private MetaData meta;
private byte[] data;
private int v4offset;
public FileDecoder(String name) throws IOException, InvalidDatabaseException {
this(new FileInputStream(new File(name)));
}
public FileDecoder(InputStream in) throws IOException, InvalidDatabaseException {
this.init(this.readAllAsStream(in));
}
protected byte[] readAllAsStream(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
in.close();
return out.toByteArray();
}
protected void init(byte[] data) throws InvalidDatabaseException {
this.data = data;
this.fileSize = data.length;
long metaLength = bytesToLong(
this.data[0],
this.data[1],
this.data[2],
this.data[3]
);
// {"build":1547017060,"ip_version":1,"languages":{"CN":0},"node_count":411432,"total_size":3330322,"fields":["country_name","region_name","city_name"]}
byte[] metaBytes = Arrays.copyOfRange(this.data, 4, Long.valueOf(metaLength).intValue() + 4);
MetaData meta = JSONObject.parseObject(new String(metaBytes), MetaData.class);
this.nodeCount = meta.nodeCount;
this.meta = meta;
System.out.println("nodeCount" + this.nodeCount);
if ((meta.totalSize + Long.valueOf(metaLength).intValue() + 4) != this.data.length) {
throw new InvalidDatabaseException("database file size error");
}
this.data = Arrays.copyOfRange(this.data, Long.valueOf(metaLength).intValue() + 4, this.fileSize);
/** for ipv4 */
if (0x01 == (this.meta.IPVersion & 0x01)) {
int node = 0;
for (int i = 0; i < 96 && node < this.nodeCount; i++) {
if (i >= 80) {
node = this.readNode(node, 1);
} else {
node = this.readNode(node, 0);
}
}
this.v4offset = node;
}
}
public String[] find(String addr, String language) throws IPFormatException, InvalidDatabaseException {
int off;
try {
off = this.meta.Languages.get(language);
} catch (NullPointerException e) {
return null;
}
byte[] ipv;
if (addr.indexOf(":") > 0) {
ipv = IPAddressUtil.textToNumericFormatV6(addr);
if (ipv == null) {
throw new IPFormatException("ipv6 format error");
}
if ((this.meta.IPVersion & 0x02) != 0x02) {
throw new IPFormatException("no support ipv6");
}
} else if (addr.indexOf(".") > 0) {
ipv = IPAddressUtil.textToNumericFormatV4(addr);
if (ipv == null) {
throw new IPFormatException("ipv4 format error");
}
if ((this.meta.IPVersion & 0x01) != 0x01) {
throw new IPFormatException("no support ipv4");
}
} else {
throw new IPFormatException("ip format error");
}
int node = 0;
try {
node = this.findNode(ipv);
} catch (NotFoundException nfe) {
return null;
}
final String data = this.resolve(node);
//数据存储格式 language1 data language2 data language3 data
return Arrays.copyOfRange(data.split("\t", this.meta.Fields.length * this.meta.Languages.size()), off, off + this.meta.Fields.length);
}
private int findNode(byte[] binary) throws NotFoundException {
int node = 0;
final int bit = binary.length * 8;
if (bit == 32) {
node = this.v4offset;
}
for (int i = 0; i < bit; i++) {
if (node > this.nodeCount) {
break;
}
node = this.readNode(node, 1 & ((0xFF & binary[i / 8]) >> 7 - (i % 8))); //这里是 7 - (i%8)
}
if (node > this.nodeCount) {
return node;
}
throw new NotFoundException("ip not found");
}
private String resolve(int node) throws InvalidDatabaseException {
final int resoloved = node - this.nodeCount + this.nodeCount * 8;
if (resoloved >= this.fileSize) {
throw new InvalidDatabaseException("database resolve error");
}
byte b = 0;
int size = Long.valueOf(bytesToLong(
b,
b,
this.data[resoloved],
this.data[resoloved + 1]
)).intValue();
if (this.data.length < (resoloved + 2 + size)) {
throw new InvalidDatabaseException("database resolve error");
}
try {
return new String(this.data, resoloved + 2, size, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new InvalidDatabaseException("database resolve error");
}
}
public int readNode(int node, int index) {
int off = node * 8 + index * 4;
//返回第
return Long.valueOf(bytesToLong(
this.data[off],
this.data[off + 1],
this.data[off + 2],
this.data[off + 3]
)).intValue();
}
private static long bytesToLong(byte a, byte b, byte c, byte d) {
return int2long((((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)));
}
private static long int2long(int i) {
long l = i & 0x7fffffffL;
if (i < 0) {
l |= 0x080000000L;
}
return l;
}
public boolean isIPv4() {
return (this.meta.IPVersion & 0x01) == 0x01;
}
public boolean isIPv6() {
return (this.meta.IPVersion & 0x02) == 0x02;
}
public int getBuildUTCTime() {
return this.meta.Build;
}
public String[] getSupportFields() {
return this.meta.Fields;
}
public String getSupportLanguages() {
return this.meta.Languages.keySet().toString();
}
public void dfs() {
LinkedList<Integer> list = new LinkedList<>();
int node = this.v4offset;
System.out.println(node);
list.push(0);
searchNode(node, 0, list);
list.pop();
list.push(1);
searchNode(node, 1, list);
list.pop();
}
private void searchNode(int node, int bt, LinkedList<Integer> list) {
int newnode = readNode(node, bt);
if (list.size() > 32) return;
if (newnode > this.nodeCount) {
String prefix = getPrefix(list);
System.out.println(prefix);
try {
final String nodeData = resolve(newnode);
itemInfos.add(new ItemInfo(prefix, nodeData));
// String[] languagesData = nodeData.split("\t", this.meta.Fields.length * this.meta.Languages.size());
//
//
// Map<String, CityInfo> languageMap = Maps.newHashMap();
// for (Map.Entry<String, Integer> entry : this.meta.Languages.entrySet()) {
// String language = entry.getKey();
// int off = entry.getValue();
// String fields[] = Arrays.copyOfRange(languagesData, off, off + this.meta.Fields.length);
// CityInfo cityInfo = new CityInfo(fields);
//
// languageMap.put(language, cityInfo);
// }
// netStates.put(prefix, languageMap);
} catch (Exception e) {
System.out.println("out of boundary");
return;
} finally {
return;
}
}
list.push(0);
searchNode(newnode, 0, list);
list.pop();
list.push(1);
searchNode(newnode, 1, list);
list.pop();
}
public static String getPrefix(LinkedList<Integer> list) {
int var1 = 0;
int var2 = 0;
int var3 = 0;
int var4 = 0;
int len = list.size();
for (int i = 0; i < 8 && i < len; i++) {
var1 = (var1 << 1) | list.get(i);
}
if (len < 8) var1 <<= 8 - len;
for (int i = 8; i < 16 && i < len; i++) {
var2 = (var2 << 1) | list.get(i);
}
if (len > 8 && len < 16) var2 <<= 16 - len;
for (int i = 16; i < 24 && i < len; i++) {
var3 = (var3 << 1) | list.get(i);
}
if (len > 16 && len < 24) var3 <<= 24 - len;
for (int i = 24; i < 32 && i < len; i++) {
var4 = (var4 << 1) | list.get(i);
}
if (len > 24 && len < 32) var4 <<= 32 - len;
return String.format("%d.%d.%d.%d/%d", var1, var2, var3, var4, len);
}
public void toFile(String outfilename) throws Exception{
System.out.println(this.itemInfos.size());
BufferedWriter bw = null;
FileWriter fw = new FileWriter(outfilename);
bw = new BufferedWriter(fw);
for (ItemInfo itemInfo : itemInfos) {
bw.write(itemInfo.toString());
}
if (bw != null) {
bw.close();
}
fw.close();
}
public static void main(String[] args) throws Exception {
// FileDecoder fileDecoder = new FileDecoder("/Users/linleicheng/Code/ipdb-java/ipv4_pro.ipdb");
// System.out.println(JSONObject.toJSONString(fileDecoder.meta, SerializerFeature.WriteNullStringAsEmpty));
// System.out.println(fileDecoder.v4offset);
// System.out.println(fileDecoder.readNode(fileDecoder.v4offset, 0));
City city = new City("/Users/linleicheng/Code/ipdb-java/ipv4_pro.ipdb");
System.out.println(city.findInfo("123.123.123.123", "CN"));
// String[] data = fileDecoder.find("113.210.98.70", "CN");
// CityInfo info = new CityInfo(data);
// System.out.println(info.toString());
// fileDecoder.dfs();
// fileDecoder.toFile("/Users/linleicheng/Code/ipdb-java/data.txt");
}
}
| 32.904908 | 159 | 0.542649 |
496ae3c14cfe946439ea172313547b62c93092b9 | 933 | package org.yuntu.app.extend.module;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.WXSDKManager;
import com.taobao.weex.common.WXModule;
import com.taobao.weex.common.WXModuleAnno;
import com.umeng.analytics.MobclickAgent;
import java.util.HashMap;
import java.util.Map;
public class TrackModule extends WXModule {
@WXModuleAnno(moduleMethod = true, runOnUIThread = true)
public void sendTrack(String jsonParams, final String callbackId) {
JSONObject job = (JSONObject) JSON.parse(jsonParams);
Map<String,String> map = new HashMap<>();
map.put("pageName", job.getString("pageName"));
MobclickAgent.onEvent(mWXSDKInstance.getContext(), job.getString("path"), map);
Map<String,Object> retMap = new HashMap<String, Object>();
WXSDKManager.getInstance().callback(mWXSDKInstance.getInstanceId(), callbackId, retMap);
}
}
| 35.884615 | 96 | 0.738478 |
153defd1403928fb9f17fc9bf81e8d1b3bb2f792 | 1,307 | import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class MainWindow extends JFrame implements Runnable {
private Field field = new Field();
private Grid grid = new Grid(field);
private Wall wall = new Wall(field, grid);
private UnitController unitController = new UnitController(field, grid);
public static void main(String[] args) {
MainWindow window = new MainWindow();
window.setBounds(0, 0, 800, 600);
window.setDefaultCloseOperation(3);
window.setVisible(true);
Thread thread = new Thread(window);
thread.run();
}
public MainWindow() {
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
unitController.mouseClicked(e);
repaint();
}
});
}
@Override
public void paint(Graphics g) {
this.createBufferStrategy(2);
BufferStrategy bs = this.getBufferStrategy();
g = bs.getDrawGraphics();
super.paint(g);
grid.render(g);
wall.render(g);
unitController.render(g);
bs.show();
}
@Override
public void run() {
while(true){
unitController.tick();
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | 21.783333 | 73 | 0.696251 |
109d29ffc33c8057de129af243b60a8bd4ba5fb9 | 356 | package com.java110.fee.bmo.importFee;
import com.alibaba.fastjson.JSONObject;
import com.java110.dto.importFee.ImportFeeDto;
import org.springframework.http.ResponseEntity;
public interface IFeeSharingBMO {
/**
* 查询费用公摊
* add by wuxw
* @param reqJson
* @return
*/
ResponseEntity<String> share(JSONObject reqJson);
}
| 18.736842 | 53 | 0.707865 |
4d10a4658ce9648f5c06254d0f198939ca7dd32e | 2,390 | /*******************************************************************************
* Copyright 2016 ContainX and OpenStack4j
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package com.huawei.openstack4j.model.network.ext.builder;
import com.huawei.openstack4j.common.Buildable;
import com.huawei.openstack4j.model.network.ext.LoadBalancerV2Update;
/**
* Builder to update a lbaas v2 loadbalancer
* @author emjburns
*/
public interface LoadBalancerV2UpdateBuilder extends Buildable.Builder<LoadBalancerV2UpdateBuilder, LoadBalancerV2Update> {
/**
* Optional
* @param description
* Human-readable description for the load balancer.
* @return LoadBalancerV2UpdateBuilder
*/
public LoadBalancerV2UpdateBuilder description(String description);
/**
* @param name
* Human-readable name for the load balancer.
* @return LoadBalancerV2UpdateBuilder
*/
public LoadBalancerV2UpdateBuilder name(String name);
/**
* Optional
* @param adminStateUp
* The administrative state of the VIP. A valid value is true
* (UP) or false (DOWN).
* @return LoadBalancerV2UpdateBuilder
*/
public LoadBalancerV2UpdateBuilder adminStateUp(boolean adminStateUp);
}
| 46.862745 | 123 | 0.514226 |
21e82838032d3fb1f822cc41eec6d7c4ea168d83 | 605 | /*
* JBoss, Home of Professional Open Source
* This code has been contributed to the public domain by the author.
*/
package gov.nist.javax.sip.header;
import javax.sip.header.Header;
/**
* Extensions to the Header interface supported by the implementation and
* will be included in the next spec release.
*
* @author [email protected]
*
*/
public interface HeaderExt extends Header {
/**
* Gets the header value (i.e. what follows the name:) as a string
* @return the header value (i.e. what follows the name:)
* @since 2.0
*/
public String getValue();
}
| 24.2 | 74 | 0.682645 |
e8d919b8ab24954db7ce308fff6747e8539aebab | 166 | package com.flj.latte.ec.main.personal.address;
/**
* Created by Administrator on 2017/10/18 0018.
*/
public enum AddressItemFields {
PHONE,
ADDRESS
}
| 12.769231 | 47 | 0.686747 |
44123be76b832eb37375624d893e339f5071d074 | 1,285 | package fivemegs;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
/**
* Upvote a single post or comment
*/
@WebServlet("/upvote")
public class UpvoteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpvoteServlet() {
super();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key=request.getParameter(Constants.PARAM_KEY);
HttpSession sss=request.getSession();
if (sss==null || sss.getAttribute(key)==null){
String ctxKey=Post.getCtxKey(key);
Posts ps=(Posts)request.getServletContext().getAttribute(ctxKey);
response.setContentType(Constants.CONTENT_JSON);
if (ps!=null){
Post p=ps.upvote(key);
if (p!=null){
sss.setAttribute(key, p.getPost());
response.getWriter().print(p.getPost().toString());
}
}
}
}
}
| 27.340426 | 119 | 0.726848 |
d538498d19b10ab3a1daa44af0e801e5cf4c5901 | 1,057 | /*
* Copyright (c) 2021 Snowflake Computing Inc. All rights reserved.
*/
package net.snowflake.ingest.streaming.internal;
import java.math.BigInteger;
import java.util.Objects;
class TimestampWrapper {
private long epoch;
private int fraction;
private BigInteger timeInScale;
public TimestampWrapper(long epoch, int fraction, BigInteger timeInScale) {
this.epoch = epoch;
this.fraction = fraction;
this.timeInScale = timeInScale;
}
public long getEpoch() {
return epoch;
}
public int getFraction() {
return fraction;
}
public BigInteger getTimeInScale() {
return timeInScale;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TimestampWrapper that = (TimestampWrapper) o;
return epoch == that.epoch
&& fraction == that.fraction
&& Objects.equals(timeInScale, that.timeInScale);
}
@Override
public int hashCode() {
return Objects.hash(epoch, fraction, timeInScale);
}
}
| 22.020833 | 77 | 0.684011 |
dc6953edca9baa9276074b4ece5bcd7937f50fbe | 4,757 | package thor12022.hardcorewither;
/*
* Check all the classes for (hopefully) detailed descriptions of what it does. There will also be tidbits of comments throughout the codebase.
* If you wish to add a description to a class, or extend/change an existing one, submit a PR with your changes.
*/
//import biomesoplenty.api.content.BOPCBiomes;
import java.io.File;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import thor12022.hardcorewither.blocks.BlockRecipeRegistry;
import thor12022.hardcorewither.blocks.BlockRegistry;
import thor12022.hardcorewither.client.gui.CreativeTabBaseMod;
import thor12022.hardcorewither.client.gui.GuiHandler;
import thor12022.hardcorewither.command.CommandManager;
import thor12022.hardcorewither.config.ConfigManager;
import thor12022.hardcorewither.entity.EntityRegistry;
import thor12022.hardcorewither.items.ItemRecipeRegistry;
import thor12022.hardcorewither.items.ItemRegistry;
import thor12022.hardcorewither.handlers.PlayerHandler;
import thor12022.hardcorewither.handlers.TinkersConstructHandler;
import thor12022.hardcorewither.potions.PotionRegistry;
import thor12022.hardcorewither.powerUps.PowerUpManager;
import thor12022.hardcorewither.proxies.CommonProxy;
import thor12022.hardcorewither.EventHandler;
import thor12022.hardcorewither.util.TextHelper;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.BiomeDictionary;
import net.minecraftforge.common.BiomeManager;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import scala.Array;
@Mod(modid = ModInformation.ID, name = ModInformation.NAME, version = ModInformation.VERSION, dependencies = ModInformation.DEPEND)
public class HardcoreWither
{
@SidedProxy(clientSide = ModInformation.CLIENTPROXY, serverSide = ModInformation.COMMONPROXY)
public static CommonProxy proxy;
public static CreativeTabs tabBaseMod = new CreativeTabBaseMod(ModInformation.ID + ".creativeTab");
public static Logger logger = LogManager.getLogger(ModInformation.NAME);
@Mod.Instance
public static HardcoreWither instance;
private PowerUpManager powerUpManager;
private PlayerHandler playerHandler;
private DataStoreManager dataStore;
private EventHandler eventHandler;
public HardcoreWither()
{
powerUpManager = new PowerUpManager();
playerHandler = new PlayerHandler();
dataStore = DataStoreManager.getInstance();
eventHandler = new EventHandler(playerHandler, powerUpManager);
dataStore.addStorageClass(playerHandler, "PlayerHandler");
dataStore.addStorageClass(powerUpManager, "witherData");
}
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event)
{
logger.info(TextHelper.localize("info." + ModInformation.ID + ".console.load.preInit"));
ConfigManager.getInstance().init(event.getModConfigurationDirectory());
powerUpManager.init();
ItemRegistry.registerItems();
BlockRegistry.registerBlocks();
PotionRegistry.registerPotions();
EntityRegistry.register();
FMLCommonHandler.instance().bus().register(eventHandler);
NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
}
@Mod.EventHandler
public void init(FMLInitializationEvent event)
{
logger.info(TextHelper.localize("info." + ModInformation.ID + ".console.load.init"));
ItemRecipeRegistry.registerItemRecipes();
BlockRecipeRegistry.registerBlockRecipes();
if( Loader.isModLoaded("TConstruct") )
{
TinkersConstructHandler.init(event);
}
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event)
{
logger.info(TextHelper.localize("info." + ModInformation.ID + ".console.load.postInit"));
}
@Mod.EventHandler
public void serverStarting(FMLServerStartingEvent event)
{
CommandManager.serverStarting(event);
}
@Mod.EventHandler
public void onFMLServerStartedEvent(FMLServerStartedEvent event)
{
}
}
| 37.456693 | 143 | 0.781165 |
a28bbdd6ef9c3e7a6799b6ec2dcce2a0ad4659a4 | 1,076 | package com.visitor.shop.service;
import com.visitor.shop.domain.MOrderList;
import java.util.List;
/**
* 订单Service接口
*
* @author visitor
* @date 2019-09-15
*/
public interface IMOrderListService
{
/**
* 查询订单
*
* @param orderListId 订单ID
* @return 订单
*/
public MOrderList selectMOrderListById(String orderListId);
/**
* 查询订单列表
*
* @param mOrderList 订单
* @return 订单集合
*/
public List<MOrderList> selectMOrderListList(MOrderList mOrderList);
/**
* 新增订单
*
* @param mOrderList 订单
* @return 结果
*/
public int insertMOrderList(MOrderList mOrderList);
/**
* 修改订单
*
* @param mOrderList 订单
* @return 结果
*/
public int updateMOrderList(MOrderList mOrderList);
/**
* 批量删除订单
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteMOrderListByIds(String ids);
/**
* 删除订单信息
*
* @param orderListId 订单ID
* @return 结果
*/
public int deleteMOrderListById(String orderListId);
}
| 17.354839 | 72 | 0.582714 |
49412ff4cf3ac8a5ca3b566f6e2688a047b490bd | 393 | package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigurationBean {
@Bean
public Fruit fruit() {
Fruit fruit = new Fruit();
fruit.setName("fruit");
return fruit;
}
@Bean
public User user() {
User user = new User(fruit());
user.setName("tt");
return user;
}
}
| 17.863636 | 60 | 0.720102 |
86528ff0710d58c7057a275869e633147513364a | 742 | package net.famzangl.minecraft.minebot.ai.tools.rate;
import net.famzangl.minecraft.minebot.ai.path.world.BlockFloatMap;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.item.ItemStack;
public class EnchantmentRater extends Rater {
protected final int enchantmentId;
public EnchantmentRater(int enchantmentId, String name,
BlockFloatMap values) {
super(name, values);
this.enchantmentId = enchantmentId;
}
@Override
protected boolean isAppleciable(ItemStack item, int forBlockAndMeta) {
return EnchantmentHelper.getEnchantmentLevel(enchantmentId,
item) > 0;
}
@Override
public String toString() {
return "EnchantmentRater [enchantmentId=" + enchantmentId + ", name="
+ name + "]";
}
} | 27.481481 | 71 | 0.770889 |
8639b1bcedfa175741ee5a93d8cb2a63d32f677a | 1,173 | package org.team2168.commands.tapper;
import org.team2168.RobotMap;
import org.team2168.commands.CommandBase;
/**
* Control the servo ball tappers with a joystick
*/
public class EngageTappers extends CommandBase {
public EngageTappers() {
requires(servoTapper);
}
/**
* Called just before this Command runs the first time
*/
protected void initialize() {
}
/**
* Called repeatedly when this Command is scheduled to run
*/
protected void execute() {
servoTapper.setLeftAngle(RobotMap.ballTapperEngageAngle.getDouble());
servoTapper.setRightAngle(RobotMap.ballTapperEngageAngle.getDouble());
}
/**
* The command has completed when both tappers are at the angle specified.
*/
protected boolean isFinished() {
return true;
// return (servoTapper.getLeftAngle() == RobotMap.ballTapperEngageAngle.getDouble())
// && (servoTapper.getRightAngle() == RobotMap.ballTapperEngageAngle.getDouble());
}
/**
* Called once after isFinished returns true
*/
protected void end() {
}
/**
* Called when another command which requires one or more of the same
* subsystems is scheduled to run.
*/
protected void interrupted() {
}
}
| 23 | 85 | 0.723785 |
ce8db216b7ea46968a4ae16087e9626c9b051378 | 4,129 | /*
* Copyright 2015 Open Networking Laboratory
*
* 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.onosproject.net.config;
import com.google.common.annotations.Beta;
/**
* Base abstract factory for creating configurations for the specified subject type.
*
* @param <S> type of subject
* @param <C> type of configuration
*/
@Beta
public abstract class ConfigFactory<S, C extends Config<S>> {
private final SubjectFactory<S> subjectFactory;
private final Class<C> configClass;
private final String configKey;
private final boolean isList;
/**
* Creates a new configuration factory for the specified class of subjects
* capable of generating the configurations of the specified class. The
* subject and configuration class keys are used merely as keys for use in
* composite JSON trees.
*
* @param subjectFactory subject factory
* @param configClass configuration class
* @param configKey configuration class key
*/
protected ConfigFactory(SubjectFactory<S> subjectFactory,
Class<C> configClass, String configKey) {
this(subjectFactory, configClass, configKey, false);
}
/**
* Creates a new configuration factory for the specified class of subjects
* capable of generating the configurations of the specified class. The
* subject and configuration class keys are used merely as keys for use in
* composite JSON trees.
* <p>
* Note that configurations backed by JSON array are not easily extensible
* at the top-level as they are inherently limited to holding an ordered
* list of items.
* </p>
*
* @param subjectFactory subject factory
* @param configClass configuration class
* @param configKey configuration class key
* @param isList true to indicate backing by JSON array
*/
protected ConfigFactory(SubjectFactory<S> subjectFactory,
Class<C> configClass, String configKey,
boolean isList) {
this.subjectFactory = subjectFactory;
this.configClass = configClass;
this.configKey = configKey;
this.isList = isList;
}
/**
* Returns the class of the subject to which this factory applies.
*
* @return subject type
*/
public SubjectFactory<S> subjectFactory() {
return subjectFactory;
}
/**
* Returns the class of the configuration which this factory generates.
*
* @return configuration type
*/
public Class<C> configClass() {
return configClass;
}
/**
* Returns the unique key (within subject class) of this configuration.
* This is primarily aimed for use in composite JSON trees in external
* representations and has no bearing on the internal behaviours.
*
* @return configuration key
*/
public String configKey() {
return configKey;
}
/**
* Creates a new but uninitialized configuration. Framework will initialize
* the configuration via {@link Config#init} method.
*
* @return new uninitialized configuration
*/
public abstract C createConfig();
/**
* Indicates whether the configuration is a list and should be backed by
* a JSON array rather than JSON object.
*
* @return true if backed by JSON array
*/
public boolean isList() {
return isList;
}
}
| 33.569106 | 85 | 0.647857 |
0d0550ac48e901a8d32a9e6fca697862e28507b1 | 8,399 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chromoting;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.LinkedList;
import java.util.Queue;
/**
* This class receives local touch input events and forwards them to the remote host.
* A queue of MotionEvents is built up and then either transmitted to the remote host if one of its
* remote gesture handler methods is called (such as onScroll) or it is cleared if the current
* stream of events does not represent a remote gesture.
* NOTE: Not all touch gestures are remoted. Touch input and gestures outside the supported ones
* (which includes tapping and 2 finger panning) will either affect the local canvas or
* will be dropped/ignored.
*/
public class TouchInputStrategy implements InputStrategyInterface {
/**
* Contains the maximum number of MotionEvents to store before cancelling the current gesture.
* The size is ~3x the largest number of events seen during any remotable gesture sequence.
*/
private static final int QUEUED_EVENT_THRESHOLD = 50;
/**
* Contains the set of MotionEvents received for the current gesture candidate. If one of the
* gesture handling methods is called, these queued events will be transmitted to the remote
* host for injection. The queue has a maximum size determined by |QUEUED_EVENT_THRESHOLD| to
* prevent a live memory leak where the queue grows unbounded during a local gesture (such as
* someone panning the local canvas continuously for several seconds/minutes).
*/
private Queue<MotionEvent> mQueuedEvents;
/**
* Indicates that the events received should be treated as part of an active remote gesture.
*/
private boolean mInRemoteGesture = false;
/**
* Indicates whether MotionEvents and gestures should be acted upon or ignored. This flag is
* set when we believe that the current sequence of events is not something we should remote.
*/
private boolean mIgnoreTouchEvents = false;
private final RenderData mRenderData;
private final InputEventSender mInjector;
public TouchInputStrategy(RenderData renderData, InputEventSender injector) {
Preconditions.notNull(injector);
mRenderData = renderData;
mInjector = injector;
mQueuedEvents = new LinkedList<MotionEvent>();
mRenderData.drawCursor = false;
}
@Override
public boolean onTap(int button) {
if (mQueuedEvents.isEmpty() || mIgnoreTouchEvents) {
return false;
}
switch (button) {
case InputStub.BUTTON_LEFT:
injectQueuedEvents();
return true;
case InputStub.BUTTON_RIGHT:
// Using the mouse for right-clicking is consistent across all host platforms.
// Right-click gestures are often platform specific and can be tricky to simulate.
// Grab the first queued event which should be the initial ACTION_DOWN event.
MotionEvent downEvent = mQueuedEvents.peek();
assert downEvent.getActionMasked() == MotionEvent.ACTION_DOWN;
mInjector.sendMouseClick(new PointF(downEvent.getX(), downEvent.getY()),
InputStub.BUTTON_RIGHT);
clearQueuedEvents();
return true;
default:
// Tap gestures for > 2 fingers are not supported.
return false;
}
}
@Override
public boolean onPressAndHold(int button) {
if (button != InputStub.BUTTON_LEFT || mQueuedEvents.isEmpty()
|| mIgnoreTouchEvents) {
return false;
}
mInRemoteGesture = true;
injectQueuedEvents();
return true;
}
@Override
public void onScroll(float distanceX, float distanceY) {
if (mIgnoreTouchEvents || mInRemoteGesture) {
return;
}
mInRemoteGesture = true;
injectQueuedEvents();
}
@Override
public void onMotionEvent(MotionEvent event) {
// MotionEvents received are stored in a queue. This queue is added to until one of the
// gesture handling methods is called to indicate that a remote gesture is in progress. At
// that point, each enqueued MotionEvent is dequeued and transmitted to the remote machine
// and the class will now forward all MotionEvents received in real time until the gesture
// has been completed. If we receive too many events without having been notified to start
// a remote gesture, then the queue is cleared and we will wait until the start of the next
// gesture to begin queueing again.
int action = event.getActionMasked();
if (mIgnoreTouchEvents && action != MotionEvent.ACTION_DOWN) {
return;
} else if (mQueuedEvents.size() > QUEUED_EVENT_THRESHOLD) {
// Since we maintain a queue of events to replay once the gesture is known, we need to
// ensure that we do not continue to queue events when we are reasonably sure that the
// user action is not going to be sent to the remote host.
mIgnoreTouchEvents = true;
clearQueuedEvents();
return;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
resetStateData();
mQueuedEvents.add(transformToRemoteCoordinates(event));
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (mInRemoteGesture) {
// Cancel the current gesture if a pointer down action is seen during it.
// We do this because a new pointer down means that we are no longer performing
// the old gesture.
mIgnoreTouchEvents = true;
clearQueuedEvents();
} else {
mQueuedEvents.add(transformToRemoteCoordinates(event));
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
event = transformToRemoteCoordinates(event);
if (mInRemoteGesture) {
mInjector.sendTouchEvent(event);
event.recycle();
} else {
mQueuedEvents.add(event);
}
break;
default:
break;
}
}
@Override
public void injectCursorMoveEvent(int x, int y) {}
@Override
public RenderStub.InputFeedbackType getShortPressFeedbackType() {
return RenderStub.InputFeedbackType.NONE;
}
@Override
public RenderStub.InputFeedbackType getLongPressFeedbackType() {
return RenderStub.InputFeedbackType.LONG_TOUCH_ANIMATION;
}
@Override
public boolean isIndirectInputMode() {
return false;
}
private void injectQueuedEvents() {
while (!mQueuedEvents.isEmpty()) {
MotionEvent event = mQueuedEvents.remove();
mInjector.sendTouchEvent(event);
event.recycle();
}
}
private void clearQueuedEvents() {
while (!mQueuedEvents.isEmpty()) {
mQueuedEvents.remove().recycle();
}
}
// NOTE: MotionEvents generated from this method should be recycled.
private MotionEvent transformToRemoteCoordinates(MotionEvent event) {
// Use a copy of the original event so the original event can be passed to other
// detectors/handlers in an unmodified state.
event = MotionEvent.obtain(event);
// Transform the event coordinates so they represent the remote screen coordinates
// instead of the local touch display.
Matrix inverted = new Matrix();
mRenderData.transform.invert(inverted);
event.transform(inverted);
return event;
}
private void resetStateData() {
clearQueuedEvents();
mInRemoteGesture = false;
mIgnoreTouchEvents = false;
}
}
| 37.495536 | 99 | 0.639957 |
6a89cb6d5e63792dac400c90157118d8daa76f05 | 2,078 | package br.com.zupedu.proposal.cardBlocking;
import br.com.zupedu.proposal.cardsAssociation.entities.Card;
import br.com.zupedu.proposal.cardsAssociation.repositories.CardRepository;
import io.opentracing.Span;
import io.opentracing.Tracer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
@RestController
public class CardBlockingController {
@Autowired
private CardRepository cardRepository;
@Autowired
private BlockadeRepository blockadeRepository;
@Autowired
private SendCardBlocked sendCardBlocked;
@Autowired
private Tracer tracer;
@PostMapping("/cards/{id}/blocking")
public ResponseEntity<Void> createBloking(@PathVariable("id") String cardId,
HttpServletRequest request) {
Span activeSpan = tracer.activeSpan();
activeSpan.setTag("api.name", "proposal");
activeSpan.setBaggageItem("api.name", "proposal");
activeSpan.log("Bloqueio de um cartão");
Optional<Card> checkCardExists = cardRepository.findById(cardId);
if (checkCardExists.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
Card card = checkCardExists.get();
if (card.isBlocked()) {
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY);
}
sendCardBlocked.execute(card);
String ip = request.getRemoteAddr();
String userAgent = request.getHeader("User-Agent");
Blockade blockade = new Blockade(card, ip, userAgent);
blockadeRepository.save(blockade);
return ResponseEntity.ok().build();
}
}
| 31.969231 | 80 | 0.724254 |
dad3e28cbff3edbeb7700cfe01c30376e00eeeec | 1,308 | package br.ufsc.avaliacaomunicipal.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.ufsc.avaliacaomunicipal.model.Questao;
import br.ufsc.avaliacaomunicipal.model.TipoQuestao;
import br.ufsc.avaliacaomunicipal.repository.TipoQuestaoRepository;
@RequestMapping("/api/tipo-questao/")
@RestController
public class TipoQuestaoController {
@Autowired
private TipoQuestaoRepository repository;
@GetMapping(value = "listarTipoQuestao", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<TipoQuestao>> listarTipoQuestoes(){
return ResponseEntity.ok(this.repository.findAll());
}
@PostMapping(value = "inserirTipoQuestao", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity inserirTipoQuestao(@RequestBody TipoQuestao tipoQuestao){
repository.save(tipoQuestao);
return ResponseEntity.ok().build();
}
}
| 34.421053 | 88 | 0.834098 |
3f5ed9889f043c5db89da7137eb2bbadd03c5a57 | 2,854 | package top.inger.JpaDemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.inger.JpaDemo.domain.Order;
import top.inger.JpaDemo.repository.OrderRepository;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
@CrossOrigin
@RestController
@RequestMapping("/api/order")
//@Api(tags="订单API")
public class OrderController {
private final OrderRepository orderRepository;
@Autowired
public OrderController(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
/**
* 创建一个订单 —> POST: /api/order/create
*/
// @ApiOperation(value="创建订单", notes="根据Order对象创建订单")
@PostMapping("/create")
public Order createOrder(@RequestBody @Valid Order order) {
return orderRepository.saveAndFlush(order);
}
/**
* 查询所有的订单 —> GET: /api/order/findAll
*/
// @ApiOperation(value="获取订单列表", notes="")
@GetMapping("/findAll")
public List<Order> findAllOrder() {
return orderRepository.findAll();
}
/**
* 查询某个id的订单 —> GET: /api/order/findById/{orderId}
*/
// @ApiOperation(value="获取订单详细信息", notes="根据url的id来获取订单详细信息")
@GetMapping("/findById/{orderId}")
public Optional<Order> findOrderById(@PathVariable(value = "orderId") int id) {
return orderRepository.findById(id);
}
/**
* 更新某个id的订单 —> GET: /api/order/updateById/{orderId}
*/
// @ApiOperation(value="更新订单详细信息", notes="根据url的id来指定更新对象,并根据传过来的order信息来更新订单详细信息")
@PutMapping("/updateById/{orderId}")
public @Valid Order updateOrderById(
@PathVariable(value = "orderId") int id, @RequestBody @Valid Order uptOrder) {
Optional<Order> order = orderRepository.findById(id);
uptOrder.setOrderId(order.get().getOrderId());
return orderRepository.saveAndFlush(uptOrder);
}
/**
* 删除某个id的订单 —> DELETE: /api/order/deleteById/{orderId}
*/
// @ApiOperation(value="删除订单", notes="根据url的id来指定删除对象")
@DeleteMapping("/deleteById/{orderId}")
public ResponseEntity<?> deleteOrderById(@PathVariable(value = "orderId") int id) {
orderRepository.deleteById(id);
return ResponseEntity.ok().build();
}
/**
* 通过usid和status查询该用户的订单 —> POST: /api/order/findOrderByUsId/{usId}
*/
@PostMapping("/findOrderByUsIdAndStatus/{usId}/{status}")
public List<Order> findOrderByUsIdAndStatus(
@PathVariable(value = "usId") int usId,
@PathVariable(value = "status") byte status) {
List<Order> order = orderRepository.findOrderByUsIdAndStatus(usId, status);
return order;
}
}
| 32.431818 | 91 | 0.653819 |
6c726008362d1dcd5d5da9a924f60afb2207399b | 13,220 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser;
import android.app.Notification;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.chromium.base.Callback;
import org.chromium.base.ContextUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.chrome.browser.banners.AppDetailsDelegate;
import org.chromium.chrome.browser.customtabs.CustomTabsConnection;
import org.chromium.chrome.browser.externalauth.ExternalAuthUtils;
import org.chromium.chrome.browser.feedback.AsyncFeedbackSource;
import org.chromium.chrome.browser.feedback.FeedbackCollector;
import org.chromium.chrome.browser.feedback.FeedbackReporter;
import org.chromium.chrome.browser.feedback.FeedbackSource;
import org.chromium.chrome.browser.feedback.FeedbackSourceProvider;
import org.chromium.chrome.browser.gsa.GSAHelper;
import org.chromium.chrome.browser.help.HelpAndFeedback;
import org.chromium.chrome.browser.historyreport.AppIndexingReporter;
import org.chromium.chrome.browser.init.ProcessInitializationHandler;
import org.chromium.chrome.browser.instantapps.InstantAppsHandler;
import org.chromium.chrome.browser.locale.LocaleManager;
import org.chromium.chrome.browser.metrics.VariationsSession;
import org.chromium.chrome.browser.multiwindow.MultiWindowUtils;
import org.chromium.chrome.browser.offlinepages.CCTRequestStatus;
import org.chromium.chrome.browser.omaha.RequestGenerator;
import org.chromium.chrome.browser.partnerbookmarks.PartnerBookmark;
import org.chromium.chrome.browser.partnerbookmarks.PartnerBookmarksProviderIterator;
import org.chromium.chrome.browser.partnercustomizations.PartnerBrowserCustomizations;
import org.chromium.chrome.browser.password_manager.GooglePasswordManagerUIProvider;
import org.chromium.chrome.browser.policy.PolicyAuditor;
import org.chromium.chrome.browser.preferences.LocationSettings;
import org.chromium.chrome.browser.rlz.RevenueStats;
import org.chromium.chrome.browser.services.AndroidEduOwnerCheckCallback;
import org.chromium.chrome.browser.signin.GoogleActivityController;
import org.chromium.chrome.browser.survey.SurveyController;
import org.chromium.chrome.browser.tab.AuthenticatorNavigationInterceptor;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.webapps.GooglePlayWebApkInstallDelegate;
import org.chromium.chrome.browser.webauth.Fido2ApiHandler;
import org.chromium.chrome.browser.widget.FeatureHighlightProvider;
import org.chromium.components.signin.AccountManagerDelegate;
import org.chromium.components.signin.SystemAccountManagerDelegate;
import org.chromium.policy.AppRestrictionsProvider;
import org.chromium.policy.CombinedPolicyProvider;
import java.util.Collections;
import java.util.List;
/**
* Base class for defining methods where different behavior is required by downstream targets.
* The correct version of {@link AppHooksImpl} will be determined at compile time via build rules.
* See http://crbug/560466.
*/
public abstract class AppHooks {
private static AppHooksImpl sInstance;
/**
* Sets a mocked instance for testing.
*/
@VisibleForTesting
public static void setInstanceForTesting(AppHooksImpl instance) {
sInstance = instance;
}
@CalledByNative
public static AppHooks get() {
if (sInstance == null) sInstance = new AppHooksImpl();
return sInstance;
}
/**
* Initiate AndroidEdu device check.
* @param callback Callback that should receive the results of the AndroidEdu device check.
*/
public void checkIsAndroidEduDevice(final AndroidEduOwnerCheckCallback callback) {
new Handler(Looper.getMainLooper()).post(() -> callback.onSchoolCheckDone(false));
}
/**
* Creates a new {@link AccountManagerDelegate}.
* @return the created {@link AccountManagerDelegate}.
*/
public AccountManagerDelegate createAccountManagerDelegate() {
return new SystemAccountManagerDelegate();
}
/**
* @return An instance of AppDetailsDelegate that can be queried about app information for the
* App Banner feature. Will be null if one is unavailable.
*/
public AppDetailsDelegate createAppDetailsDelegate() {
return null;
}
/**
* Creates a new {@link AppIndexingReporter}.
* @return the created {@link AppIndexingReporter}.
*/
public AppIndexingReporter createAppIndexingReporter() {
return new AppIndexingReporter();
}
/**
* Return a {@link AuthenticatorNavigationInterceptor} for the given {@link Tab}.
* This can be null if there are no applicable interceptor to be built.
*/
public AuthenticatorNavigationInterceptor createAuthenticatorNavigationInterceptor(Tab tab) {
return null;
}
/**
* @return An instance of {@link CustomTabsConnection}. Should not be called
* outside of {@link CustomTabsConnection#getInstance()}.
*/
public CustomTabsConnection createCustomTabsConnection() {
return new CustomTabsConnection();
}
/**
* Creates a new {@link SurveyController}.
* @return The created {@link SurveyController}.
*/
public SurveyController createSurveyController() {
return new SurveyController();
}
/**
* @return An instance of ExternalAuthUtils to be installed as a singleton.
*/
public ExternalAuthUtils createExternalAuthUtils() {
return new ExternalAuthUtils();
}
/**
* @return An instance of {@link FeedbackReporter} to report feedback.
*/
public FeedbackReporter createFeedbackReporter() {
return new FeedbackReporter() {};
}
/**
* @return An instance of GoogleActivityController.
*/
public GoogleActivityController createGoogleActivityController() {
return new GoogleActivityController();
}
/**
* @return An instance of {@link GSAHelper} that handles the start point of chrome's integration
* with GSA.
*/
public GSAHelper createGsaHelper() {
return new GSAHelper();
}
/**
* Returns a new instance of HelpAndFeedback.
*/
public HelpAndFeedback createHelpAndFeedback() {
return new HelpAndFeedback();
}
public InstantAppsHandler createInstantAppsHandler() {
return new InstantAppsHandler();
}
/**
* @return An instance of {@link LocaleManager} that handles customized locale related logic.
*/
public LocaleManager createLocaleManager() {
return new LocaleManager();
}
/**
* @return An instance of {@link GooglePasswordManagerUIProvider}. Will be null if one is not
* available.
*/
public GooglePasswordManagerUIProvider createGooglePasswordManagerUIProvider() {
return null;
}
/**
* Returns an instance of LocationSettings to be installed as a singleton.
*/
public LocationSettings createLocationSettings() {
// Using an anonymous subclass as the constructor is protected.
// This is done to deter instantiation of LocationSettings elsewhere without using the
// getInstance() helper method.
return new LocationSettings() {};
}
/**
* @return An instance of MultiWindowUtils to be installed as a singleton.
*/
public MultiWindowUtils createMultiWindowUtils() {
return new MultiWindowUtils();
}
/**
* @return An instance of RequestGenerator to be used for Omaha XML creation. Will be null if
* a generator is unavailable.
*/
public RequestGenerator createOmahaRequestGenerator() {
return null;
}
/**
* @return a new {@link ProcessInitializationHandler} instance.
*/
public ProcessInitializationHandler createProcessInitializationHandler() {
return new ProcessInitializationHandler();
}
/**
* @return An instance of RevenueStats to be installed as a singleton.
*/
public RevenueStats createRevenueStatsInstance() {
return new RevenueStats();
}
/**
* Returns a new instance of VariationsSession.
*/
public VariationsSession createVariationsSession() {
return new VariationsSession();
}
/** Returns the singleton instance of GooglePlayWebApkInstallDelegate. */
public GooglePlayWebApkInstallDelegate getGooglePlayWebApkInstallDelegate() {
return null;
}
/**
* @return An instance of PolicyAuditor that notifies the policy system of the user's activity.
* Only applicable when the user has a policy active, that is tracking the activity.
*/
public PolicyAuditor getPolicyAuditor() {
// This class has a protected constructor to prevent accidental instantiation.
return new PolicyAuditor() {};
}
public void registerPolicyProviders(CombinedPolicyProvider combinedProvider) {
combinedProvider.registerProvider(
new AppRestrictionsProvider(ContextUtils.getApplicationContext()));
}
/**
* Starts a service from {@code intent} with the expectation that it will make itself a
* foreground service with {@link android.app.Service#startForeground(int, Notification)}.
*
* @param intent The {@link Intent} to fire to start the service.
*/
public void startForegroundService(Intent intent) {
ContextCompat.startForegroundService(ContextUtils.getApplicationContext(), intent);
}
/**
* @return A callback that will be run each time an offline page is saved in the custom tabs
* namespace.
*/
@CalledByNative
public Callback<CCTRequestStatus> getOfflinePagesCCTRequestDoneCallback() {
return null;
}
/**
* @return A list of whitelisted apps that are allowed to receive notification when the
* set of offlined pages downloaded on their behalf has changed. Apps are listed by their
* package name.
*/
public List<String> getOfflinePagesCctWhitelist() {
return Collections.emptyList();
}
/**
* @return A list of whitelisted app package names whose completed notifications
* we should suppress.
*/
public List<String> getOfflinePagesSuppressNotificationPackages() {
return Collections.emptyList();
}
/**
* @return An iterator of partner bookmarks.
*/
@Nullable
public PartnerBookmark.BookmarkIterator getPartnerBookmarkIterator() {
return PartnerBookmarksProviderIterator.createIfAvailable();
}
/**
* @return An instance of PartnerBrowserCustomizations.Provider that provides customizations
* specified by partners.
*/
public PartnerBrowserCustomizations.Provider getCustomizationProvider() {
return new PartnerBrowserCustomizations.ProviderPackage();
}
/**
* @return A {@link FeedbackSourceProvider} that can provide additional {@link FeedbackSource}s
* and {@link AsyncFeedbackSource}s to be used by a {@link FeedbackCollector}.
*/
public FeedbackSourceProvider getAdditionalFeedbackSources() {
return new FeedbackSourceProvider() {};
}
/**
* @return a new {@link Fido2ApiHandler} instance.
*/
public Fido2ApiHandler createFido2ApiHandler() {
return new Fido2ApiHandler();
}
/**
* @return A new {@link FeatureHighlightProvider}.
*/
public FeatureHighlightProvider createFeatureHighlightProvider() {
return new FeatureHighlightProvider();
}
/**
* Checks the Google Play services availability on the this device.
*
* This is a workaround for the
* versioned API of {@link GoogleApiAvailability#isGooglePlayServicesAvailable()}. The current
* Google Play services SDK version doesn't have this API yet.
*
* TODO(zqzhang): Remove this method after the SDK is updated.
*
* @return status code indicating whether there was an error. The possible return values are the
* same as {@link GoogleApiAvailability#isGooglePlayServicesAvailable()}.
*/
public int isGoogleApiAvailableWithMinApkVersion(int minApkVersion) {
try {
PackageInfo gmsPackageInfo =
ContextUtils.getApplicationContext().getPackageManager().getPackageInfo(
GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, /* flags= */ 0);
int apkVersion = gmsPackageInfo.versionCode;
if (apkVersion >= minApkVersion) return ConnectionResult.SUCCESS;
} catch (PackageManager.NameNotFoundException e) {
return ConnectionResult.SERVICE_MISSING;
}
return ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED;
}
}
| 36.620499 | 100 | 0.721785 |
e9f6dde58894107bfa5f1898f3915ed2968e60d9 | 2,882 | //==============================================================================
// This software is part of the Open Standard for Unattended Sensors (OSUS)
// reference implementation (OSUS-R).
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <http://creativecommons.org/publicdomain/zero/1.0/>.
//==============================================================================
package mil.dod.th.core.asset;
import java.util.Set;
import mil.dod.th.core.asset.AssetDirectoryService.ScanResults;
/**
* Optional interface implemented by an asset plug-in if it is capable of finding assets available to the controller,
* such as, performing a port scan. The implementation of this interface must include the {@link
* mil.dod.th.core.factory.ProductType} annotation on the class definition so the scanner will be available for use.
*
* @author dlandoll
*/
public interface AssetScanner
{
/**
* Scan for new assets and update the provided results object as they are found. The set of assets, that currently
* exist in the asset directory, are provided here as a matter convenience (so new assets may be compared with
* existing ones to ensure uniqueness). Do not add found assets to the {@link AssetDirectoryService}, only update
* the provided results object. It is assumed that threading will be handled outside of this method call, do not use
* another thread to perform the scan. It is okay to take a while to scan for assets but this method should return
* in a reasonable amount of time (<10 seconds). The provided results object will be become invalid and will no
* longer accept new assets once this method returns. If the scan fails, throw an {@link AssetException} with
* details.
*
* @param results
* invoke {@link ScanResults#found(java.lang.String, java.util.Map)} for each asset found with properties
* defining the found asset. It is important that the results object is invoked immediately after an
* asset is discovered so that higher level functionality remains responsive (e.g., a user interface).
* @param existing
* an unmodifiable set of assets that currently exist in the {@link AssetDirectoryService}. This
* parameter may be used to compare found assets with existing ones to ensure uniqueness before updating
* the results
* @throws AssetException
* if the scan fails
*/
void scanForNewAssets(ScanResults results, Set<Asset> existing) throws AssetException;
}
| 56.509804 | 120 | 0.681124 |
3030d39128f0962acc2d4381d1e0a092c51ee78e | 3,482 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmlib.testrunner;
/**
* Identifies a parsed instrumentation test.
*/
public class TestIdentifier {
private final String mClassName;
private final String mTestName;
// An index of this test.
// Test suite may have duplicated test cases (the same test case may be run twice). This
// property is used to distinguish them.
private final int mTestIndex;
/**
* Creates a test identifier.
*
* @param className fully qualified class name of the test. Cannot be null.
* @param testName name of the test. Cannot be null.
*/
public TestIdentifier(String className, String testName) {
this(className, testName, /*testIndex=*/ -1);
}
/**
* Creates a test identifier with a test index.
*
* @param className fully qualified class name of the test. Cannot be null.
* @param testName name of the test. Cannot be null.
* @param testIndex an index of this test run.
*/
public TestIdentifier(String className, String testName, int testIndex) {
if (className == null || testName == null) {
throw new IllegalArgumentException("className and testName must " + "be non-null");
}
mClassName = className;
mTestName = testName;
mTestIndex = testIndex;
}
/**
* Returns the fully qualified class name of the test.
*/
public String getClassName() {
return mClassName;
}
/**
* Returns the name of the test.
*/
public String getTestName() {
return mTestName;
}
/** Returns the index of the test. */
public int getTestIndex() {
return mTestIndex;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mClassName == null) ? 0 : mClassName.hashCode());
result = prime * result + ((mTestName == null) ? 0 : mTestName.hashCode());
result = prime * result + mTestIndex;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestIdentifier other = (TestIdentifier) obj;
if (mClassName == null) {
if (other.mClassName != null)
return false;
} else if (!mClassName.equals(other.mClassName))
return false;
if (mTestName == null) {
if (other.mTestName != null)
return false;
} else if (!mTestName.equals(other.mTestName))
return false;
return mTestIndex == other.mTestIndex;
}
@Override
public String toString() {
return String.format("%s#%s", getClassName(), getTestName());
}
}
| 30.54386 | 95 | 0.615164 |
bf6f1b469a94910511662400027c8d045af54c5a | 2,999 | package com.codetaylor.mc.artisanworktables.modules.worktables.tile.workstation;
import com.codetaylor.mc.artisanworktables.api.internal.reference.EnumTier;
import com.codetaylor.mc.artisanworktables.api.internal.reference.EnumType;
import com.codetaylor.mc.artisanworktables.modules.worktables.ModuleWorktables;
import com.codetaylor.mc.artisanworktables.modules.worktables.ModuleWorktablesConfig;
import com.codetaylor.mc.artisanworktables.modules.worktables.gui.AWGuiContainerBase;
import com.codetaylor.mc.artisanworktables.modules.worktables.gui.GuiContainerWorkstation;
import com.codetaylor.mc.artisanworktables.modules.worktables.tile.spi.CraftingMatrixStackHandler;
import com.codetaylor.mc.artisanworktables.modules.worktables.tile.spi.TileEntitySecondaryInputBase;
import com.codetaylor.mc.athenaeum.inventory.ObservableStackHandler;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class TileEntityWorkstation
extends TileEntitySecondaryInputBase {
@SuppressWarnings("unused")
public TileEntityWorkstation() {
// serialization
}
public TileEntityWorkstation(EnumType type) {
super(type);
}
@Override
protected ResourceLocation getGuiBackgroundTexture() {
return new ResourceLocation(
ModuleWorktables.MOD_ID,
String.format(ModuleWorktables.Textures.WORKSTATION_GUI, this.getType().getName())
);
}
@Override
protected String getTableTitleKey() {
return String.format(ModuleWorktables.Lang.WORKSTATION_TITLE, this.getWorktableName());
}
@Override
public EnumTier getTier() {
return EnumTier.WORKSTATION;
}
@Override
protected CraftingMatrixStackHandler createCraftingMatrixHandler() {
return new CraftingMatrixStackHandler(3, 3);
}
@Override
protected ObservableStackHandler createSecondaryOutputHandler() {
return new ObservableStackHandler(3);
}
@Override
protected int getFluidTankCapacity(EnumType type) {
return ModuleWorktablesConfig.FLUID_CAPACITY_WORKSTATION.get(type.getName());
}
@Override
protected ObservableStackHandler createToolHandler() {
return new ObservableStackHandler(2);
}
@Override
protected int getSecondaryInputSlotCount() {
return 9;
}
@Override
@SideOnly(Side.CLIENT)
public AWGuiContainerBase getGuiContainer(
InventoryPlayer inventoryPlayer, World world, IBlockState state, BlockPos pos
) {
return new GuiContainerWorkstation(
this.getContainer(inventoryPlayer, world, state, pos),
this.getGuiBackgroundTexture(),
this.getTableTitleKey(),
this,
176,
189
);
}
@Override
public boolean allowTabs() {
return ModuleWorktablesConfig.ENABLE_TABS_WORKSTATIONS;
}
}
| 28.292453 | 100 | 0.782261 |
fd592e766d71dedde3b3862e644ac3dae4515fb9 | 6,085 | package org.hypertrace.core.documentstore.postgres;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.hypertrace.core.documentstore.Collection;
import org.hypertrace.core.documentstore.Datastore;
import org.hypertrace.core.documentstore.DatastoreProvider;
import org.hypertrace.core.documentstore.Document;
import org.hypertrace.core.documentstore.Filter;
import org.hypertrace.core.documentstore.Key;
import org.hypertrace.core.documentstore.Query;
import org.hypertrace.core.documentstore.SingleValueKey;
import org.hypertrace.core.documentstore.utils.Utils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
@Testcontainers
public class PostgresDocStoreTest {
private static final String COLLECTION_NAME = "mytest";
private static GenericContainer<?> postgres;
private static Datastore datastore;
private static String connectionUrl;
@BeforeAll
public static void init() {
postgres =
new GenericContainer<>(DockerImageName.parse("postgres:13.1"))
.withEnv("POSTGRES_PASSWORD", "postgres")
.withEnv("POSTGRES_USER", "postgres")
.withExposedPorts(5432)
.waitingFor(Wait.forListeningPort());
postgres.start();
connectionUrl = String.format("jdbc:postgresql://localhost:%s/", postgres.getMappedPort(5432));
DatastoreProvider.register("POSTGRES", PostgresDatastore.class);
Map<String, String> postgresConfig = new HashMap<>();
postgresConfig.putIfAbsent("url", connectionUrl);
postgresConfig.putIfAbsent("user", "postgres");
postgresConfig.putIfAbsent("password", "postgres");
Config config = ConfigFactory.parseMap(postgresConfig);
datastore = DatastoreProvider.getDatastore("Postgres", config);
System.out.println(datastore.listCollections());
}
@BeforeEach
public void setUp() {
datastore.deleteCollection(COLLECTION_NAME);
datastore.createCollection(COLLECTION_NAME, null);
}
@AfterAll
public static void shutdown() {
postgres.stop();
}
@Test
public void testInitWithDatabase() {
PostgresDatastore datastore = new PostgresDatastore();
Properties properties = new Properties();
String user = "postgres";
String password = "postgres";
String database = "postgres";
properties.put("url", connectionUrl);
properties.put("user", user);
properties.put("password", password);
properties.put("database", database);
Config config = ConfigFactory.parseProperties(properties);
datastore.init(config);
try {
DatabaseMetaData metaData = datastore.getPostgresClient().getMetaData();
Assertions.assertEquals(metaData.getURL(), connectionUrl + database);
Assertions.assertEquals(metaData.getUserName(), user);
} catch (SQLException e) {
System.out.println("Exception executing init test with user and password");
Assertions.fail();
}
}
@Test
public void testUpsertAndReturn() throws IOException {
Collection collection = datastore.getCollection(COLLECTION_NAME);
Document document = Utils.createDocument("foo1", "bar1");
Document resultDocument =
collection.upsertAndReturn(new SingleValueKey("default", "testKey"), document);
Assertions.assertEquals(document.toJson(), resultDocument.toJson());
}
@Test
public void testBulkUpsertAndReturn() throws IOException {
Collection collection = datastore.getCollection(COLLECTION_NAME);
Map<Key, Document> bulkMap = new HashMap<>();
bulkMap.put(new SingleValueKey("default", "testKey1"), Utils.createDocument("name", "Bob"));
bulkMap.put(new SingleValueKey("default", "testKey2"), Utils.createDocument("name", "Alice"));
bulkMap.put(new SingleValueKey("default", "testKey3"), Utils.createDocument("name", "Alice"));
bulkMap.put(new SingleValueKey("default", "testKey4"), Utils.createDocument("name", "Bob"));
bulkMap.put(new SingleValueKey("default", "testKey5"), Utils.createDocument("name", "Alice"));
bulkMap.put(
new SingleValueKey("default", "testKey6"),
Utils.createDocument("email", "[email protected]"));
Iterator<Document> iterator = collection.bulkUpsertAndReturnOlderDocuments(bulkMap);
// Initially there shouldn't be any documents.
Assertions.assertFalse(iterator.hasNext());
// The operation should be idempotent, so go ahead and try again.
iterator = collection.bulkUpsertAndReturnOlderDocuments(bulkMap);
List<Document> documents = new ArrayList<>();
while (iterator.hasNext()) {
documents.add(iterator.next());
}
Assertions.assertEquals(6, documents.size());
{
// empty query returns all the documents
Query query = new Query();
Assertions.assertEquals(6, collection.total(query));
}
{
Query query = new Query();
query.setFilter(Filter.eq("name", "Bob"));
Assertions.assertEquals(2, collection.total(query));
}
{
// limit should not affect the total
Query query = new Query();
query.setFilter(Filter.eq("name", "Bob"));
query.setLimit(1);
Assertions.assertEquals(2, collection.total(query));
}
}
@Test
public void testDrop() {
Collection collection = datastore.getCollection(COLLECTION_NAME);
Assertions.assertTrue(datastore.listCollections().contains("postgres." + COLLECTION_NAME));
collection.drop();
Assertions.assertFalse(datastore.listCollections().contains("postgres." + COLLECTION_NAME));
}
}
| 36.656627 | 99 | 0.730649 |
b46033c55898a9ed156c7d33f570ca9f544bb103 | 3,339 | package com.ceiba.servicio.entidad;
import com.ceiba.BasePrueba;
import com.ceiba.dominio.excepcion.ExcepcionValorObligatorio;
import com.ceiba.servicio.modelo.entidad.Servicio;
import com.ceiba.servicio.servicio.testdatabuilder.ServicioTestDataBuilder;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ServicioTest {
@Test
@DisplayName("Deberia crear correctamente el servicio")
void deberiaCrearCorrectamenteElServicio() {
// arrange
LocalDateTime fechaServicio = LocalDateTime.parse("2022-03-13T19:30:13.859604100");
//act
Servicio servicio = new ServicioTestDataBuilder().conId(1L).build();
//assert
assertEquals(1, servicio.getId());
assertEquals(null, servicio.getIdConductor());
assertEquals(1, servicio.getIdCliente());
assertEquals("A", servicio.getOrigen());
assertEquals("B", servicio.getDestino());
assertEquals(fechaServicio, servicio.getFechaServicio());
assertEquals(null, servicio.getValor());
assertEquals("ViajeTest", servicio.getDescripcion());
}
@Test
void deberiaFallarSinIdCliente() {
//Arrange
ServicioTestDataBuilder servicioTestDataBuilder = new ServicioTestDataBuilder().conIdCliente(null).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
servicioTestDataBuilder.build();
},
ExcepcionValorObligatorio.class, "Se debe ingresar el idCliente");
}
@Test
void deberiaFallarSinOrigenDeServicio() {
//Arrange
ServicioTestDataBuilder servicioTestDataBuilder = new ServicioTestDataBuilder().conOrigen(null).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
servicioTestDataBuilder.build();
},
ExcepcionValorObligatorio.class, "Se debe ingresar el origen del servicio");
}
@Test
void deberiaFallarSinDestinoDeServicio() {
//Arrange
ServicioTestDataBuilder servicioTestDataBuilder = new ServicioTestDataBuilder().conDestino(null).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
servicioTestDataBuilder.build();
},
ExcepcionValorObligatorio.class, "Se debe ingresar el destino del servicio");
}
@Test
void deberiaFallarSinFechaServicio() {
//Arrange
ServicioTestDataBuilder servicioTestDataBuilder = new ServicioTestDataBuilder().conFechaServicio(null).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
servicioTestDataBuilder.build();
},
ExcepcionValorObligatorio.class, "Se debe ingresar la fechaServicio");
}
@Test
void deberiaFallarSinDescripcion() {
//Arrange
ServicioTestDataBuilder servicioTestDataBuilder = new ServicioTestDataBuilder().conDescripcion(null).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
servicioTestDataBuilder.build();
},
ExcepcionValorObligatorio.class, "Se debe ingresar la descripcion del servicio");
}
}
| 33.727273 | 121 | 0.657382 |
4fdb411626aa5c5d41e379e36d81ffa01308b9b6 | 2,150 | /**
* Copyright 2014 Ryszard Wiśniewski <[email protected]>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package zhao.arsceditor.ResDecoder.data.value;
import android.annotation.SuppressLint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import zhao.arsceditor.ResDecoder.ARSCCallBack;
import zhao.arsceditor.ResDecoder.IO.Duo;
import zhao.arsceditor.ResDecoder.data.ResResource;
/**
* @author Ryszard Wiśniewski <[email protected]>
*/
public class ResEnumAttr extends ResAttr {
private final Duo<ResReferenceValue, ResIntValue>[] mItems;
@SuppressLint("UseSparseArrays")
private final Map<Integer, String> mItemsCache = new HashMap<Integer, String>();
ResEnumAttr(ResReferenceValue parent, int type, Integer min, Integer max, Boolean l10n,
Duo<ResReferenceValue, ResIntValue>[] items) {
super(parent, type, min, max, l10n);
mItems = items;
}
@Override
public String convertToResXmlFormat(ResScalarValue value) throws IOException {
if (value instanceof ResIntValue) {
String ret = String.valueOf(value);
if (ret != null) {
return ret;
}
}
return super.convertToResXmlFormat(value);
}
@Override
protected void serializeBody(ARSCCallBack back, ResResource res) throws IOException, IOException {
for (Duo<ResReferenceValue, ResIntValue> duo : mItems) {
int intVal = duo.m2.getValue();
back.back(res.getConfig().toString(), "enum", res.getResSpec().getName(), String.valueOf(intVal));
}
}
}
| 34.126984 | 110 | 0.695349 |
4b645531f70a0cbdfcba6ab059ee0fee84eb75e5 | 7,001 | package uk.nhs.adaptors.pss.translator.mapper;
import static uk.nhs.adaptors.pss.translator.util.CompoundStatementResourceExtractors.extractAllRequestStatements;
import static uk.nhs.adaptors.pss.translator.util.ResourceUtil.buildIdentifier;
import static uk.nhs.adaptors.pss.translator.util.ResourceUtil.generateMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.dstu3.model.Annotation;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.Encounter;
import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.dstu3.model.ReferralRequest;
import org.hl7.fhir.dstu3.model.ReferralRequest.ReferralCategory;
import org.hl7.fhir.dstu3.model.ReferralRequest.ReferralRequestStatus;
import org.hl7.v3.CD;
import org.hl7.v3.CV;
import org.hl7.v3.IVLTS;
import org.hl7.v3.RCMRMT030101UK04EhrComposition;
import org.hl7.v3.RCMRMT030101UK04EhrExtract;
import org.hl7.v3.RCMRMT030101UK04RequestStatement;
import org.hl7.v3.RCMRMT030101UK04ResponsibleParty3;
import org.hl7.v3.TS;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
import uk.nhs.adaptors.pss.translator.util.DateFormatUtil;
import uk.nhs.adaptors.pss.translator.util.ParticipantReferenceUtil;
@Service
@AllArgsConstructor
public class ReferralRequestMapper extends AbstractMapper<ReferralRequest> {
private static final String META_PROFILE = "ReferralRequest-1";
private static final String PRIORITY_PREFIX = "Priority: ";
private static final String ACTION_DATE_PREFIX = "Action Date: ";
private static final String PRACTITIONER_REFERENCE = "Practitioner/%s";
private static final String RESP_PARTY_TYPE_CODE = "RESP";
private CodeableConceptMapper codeableConceptMapper;
public List<ReferralRequest> mapResources(RCMRMT030101UK04EhrExtract ehrExtract, Patient patient, List<Encounter> encounters,
String practiseCode) {
return mapEhrExtractToFhirResource(ehrExtract, (extract, composition, component) ->
extractAllRequestStatements(component)
.filter(Objects::nonNull)
.map(requestStatement -> mapToReferralRequest(composition, requestStatement, patient, encounters, practiseCode)))
.toList();
}
public ReferralRequest mapToReferralRequest(RCMRMT030101UK04EhrComposition ehrComposition,
RCMRMT030101UK04RequestStatement requestStatement, Patient patient, List<Encounter> encounters, String practiseCode) {
var referralRequest = new ReferralRequest();
var id = requestStatement.getId().get(0).getRoot();
referralRequest.setId(id);
referralRequest.setMeta(generateMeta(META_PROFILE));
referralRequest.getIdentifier().add(buildIdentifier(id, practiseCode));
referralRequest.setStatus(ReferralRequestStatus.UNKNOWN);
referralRequest.setIntent(ReferralCategory.ORDER);
referralRequest.getRequester().setAgent(ParticipantReferenceUtil.getParticipantReference(requestStatement.getParticipant(),
ehrComposition));
referralRequest.setAuthoredOnElement(getAuthoredOn(requestStatement.getAvailabilityTime()));
referralRequest.setNote(getNotes(requestStatement));
referralRequest.setSubject(new Reference(patient));
setReferralRequestContext(referralRequest, ehrComposition, encounters);
setReferralRequestRecipient(referralRequest, requestStatement.getResponsibleParty());
setReferralRequestReasonCode(referralRequest, requestStatement.getCode());
return referralRequest;
}
private void setReferralRequestReasonCode(ReferralRequest referralRequest, CD code) {
if (code != null) {
referralRequest.getReasonCode().add(codeableConceptMapper.mapToCodeableConcept(code));
}
}
private void setReferralRequestRecipient(ReferralRequest referralRequest, RCMRMT030101UK04ResponsibleParty3 responsibleParty) {
if (responsiblePartyAgentRefHasIdValue(responsibleParty)) {
referralRequest.getRecipient().add(new Reference(PRACTITIONER_REFERENCE.formatted(
responsibleParty.getAgentRef().getId().getRoot())));
}
}
private void setReferralRequestContext(ReferralRequest referralRequest, RCMRMT030101UK04EhrComposition ehrComposition,
List<Encounter> encounters) {
encounters
.stream()
.filter(encounter -> encounter.getId().equals(ehrComposition.getId().getRoot()))
.findFirst()
.map(Reference::new)
.ifPresent(referralRequest::setContext);
}
private DateTimeType getAuthoredOn(TS availabilityTime) {
if (availabilityTime != null && availabilityTime.hasValue()) {
return DateFormatUtil.parseToDateTimeType(availabilityTime.getValue());
}
return null;
}
private boolean responsiblePartyAgentRefHasIdValue(RCMRMT030101UK04ResponsibleParty3 responsibleParty) {
return responsibleParty != null
&& responsibleParty.getTypeCode().stream().anyMatch(RESP_PARTY_TYPE_CODE::equals)
&& responsibleParty.getAgentRef() != null
&& responsibleParty.getAgentRef().getId() != null;
}
private List<Annotation> getNotes(RCMRMT030101UK04RequestStatement requestStatement) {
var priority = getPriorityText(requestStatement.getPriorityCode());
var actionDate = getActionDateText(requestStatement.getEffectiveTime());
var text = requestStatement.getText();
var notes = new ArrayList<Annotation>();
if (StringUtils.isNotEmpty(priority)) {
notes.add(new Annotation().setText(priority));
}
if (StringUtils.isNotEmpty(actionDate)) {
notes.add(new Annotation().setText(actionDate));
}
if (StringUtils.isNotEmpty(text)) {
notes.add(new Annotation().setText(text));
}
return notes;
}
private String getPriorityText(CV priorityCode) {
if (priorityCode != null) {
if (StringUtils.isNotEmpty(priorityCode.getOriginalText())) {
return PRIORITY_PREFIX + priorityCode.getOriginalText();
} else if (StringUtils.isNotEmpty(priorityCode.getDisplayName())) {
return PRIORITY_PREFIX + priorityCode.getDisplayName();
}
}
return StringUtils.EMPTY;
}
private String getActionDateText(IVLTS effectiveTime) {
if (hasEffectiveTimeValue(effectiveTime)) {
return ACTION_DATE_PREFIX + DateFormatUtil.parseToDateTimeType(effectiveTime.getCenter().getValue()).asStringValue();
}
return StringUtils.EMPTY;
}
private boolean hasEffectiveTimeValue(IVLTS effectiveTime) {
return effectiveTime != null && effectiveTime.getCenter() != null && effectiveTime.getCenter().getValue() != null;
}
}
| 43.75625 | 131 | 0.732752 |
6f8be131a1f96df51ba2b06c9c6c7634d3a2665e | 328 | package io.github.yexiaoxiaogo.basicexercises;
public class BE1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello world");
System.out.println("yexiaoxiao");
String a = "http://123.com";
String b = "http://234.cn";
a += "+" + b;
System.out.println(a);
}
}
| 20.5 | 46 | 0.658537 |
08b35bb83ad0081a277882dfcff1c92a6681a4e1 | 3,474 | /*******************************************************************************
* Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*******************************************************************************/
package hydrograph.engine.core.component.generator;
import hydrograph.engine.core.component.entity.OutputFileMixedSchemeEntity;
import hydrograph.engine.core.component.entity.utils.OutputEntityUtils;
import hydrograph.engine.core.component.generator.base.OutputComponentGeneratorBase;
import hydrograph.engine.jaxb.commontypes.TrueFalse;
import hydrograph.engine.jaxb.commontypes.TypeBaseComponent;
import hydrograph.engine.jaxb.outputtypes.TextFileMixedScheme;
public class OutputFileMixedSchemeEntityGenerator extends OutputComponentGeneratorBase {
private OutputFileMixedSchemeEntity outputFileMixedSchemeEntity;
private TextFileMixedScheme jaxbTextFileMixedScheme;
public OutputFileMixedSchemeEntityGenerator(TypeBaseComponent baseComponent) {
super(baseComponent);
}
@Override
public void castComponentFromBase(TypeBaseComponent baseComponent) {
jaxbTextFileMixedScheme = (TextFileMixedScheme) baseComponent;
}
@Override
public void createEntity() {
outputFileMixedSchemeEntity = new OutputFileMixedSchemeEntity();
}
@Override
public void initializeEntity() {
outputFileMixedSchemeEntity.setComponentId(jaxbTextFileMixedScheme.getId());
outputFileMixedSchemeEntity.setBatch(jaxbTextFileMixedScheme.getBatch());
outputFileMixedSchemeEntity.setComponentName(jaxbTextFileMixedScheme.getName());
outputFileMixedSchemeEntity.setCharset(jaxbTextFileMixedScheme.getCharset() != null
? jaxbTextFileMixedScheme.getCharset().getValue().value() : "UTF-8");
outputFileMixedSchemeEntity.setPath(jaxbTextFileMixedScheme.getPath().getUri());
outputFileMixedSchemeEntity.setSafe(
jaxbTextFileMixedScheme.getSafe() != null ? jaxbTextFileMixedScheme.getSafe().isValue() : false);
outputFileMixedSchemeEntity.setFieldsList(OutputEntityUtils.extractOutputFields(
jaxbTextFileMixedScheme.getInSocket().get(0).getSchema().getFieldOrRecordOrIncludeExternalSchema()));
outputFileMixedSchemeEntity.setRuntimeProperties(
OutputEntityUtils.extractRuntimeProperties(jaxbTextFileMixedScheme.getRuntimeProperties()));
outputFileMixedSchemeEntity
.setQuote(jaxbTextFileMixedScheme.getQuote() != null ? jaxbTextFileMixedScheme
.getQuote().getValue() : "");
outputFileMixedSchemeEntity.setStrict(
jaxbTextFileMixedScheme.getStrict() != null ? jaxbTextFileMixedScheme.getStrict().isValue() : true);
if (jaxbTextFileMixedScheme.getOverWrite() != null
&& (TrueFalse.FALSE).equals(jaxbTextFileMixedScheme.getOverWrite().getValue()))
outputFileMixedSchemeEntity.setOverWrite(false);
else
outputFileMixedSchemeEntity.setOverWrite(true);
}
@Override
public OutputFileMixedSchemeEntity getEntity() {
return outputFileMixedSchemeEntity;
}
}
| 43.425 | 105 | 0.778641 |
8249f7418cacf282436dabef33ef09b32c9da095 | 3,555 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* This interface defines a contract between the application and GemFire that allows GemFire to
* determine whether an application object contains a delta, allows GemFire to extract the delta
* from an application object, and generate a new application object by applying a delta to an
* existing application object. The difference in object state is contained in the {@link
* DataOutput} and {@link DataInput} parameters.
*
* @since GemFire 6.1
*/
public interface Delta {
/**
* Returns true if this object has pending changes it can write out as a delta. Returns false if
* this object must be transmitted in its entirety.
*/
boolean hasDelta();
/**
* This method is invoked on an application object at the delta sender, if GemFire determines the
* presence of a delta by calling {@link Delta#hasDelta()} on the object. The delta is written to
* the {@link DataOutput} object provided by GemFire.
*
* <p>
* Any delta state should be reset in this method.
*/
void toDelta(DataOutput out) throws IOException;
/**
* This method is invoked on an existing application object when an update is received as a delta.
* This method throws an {@link InvalidDeltaException} when the delta in the {@link DataInput}
* cannot be applied to the object. GemFire automatically handles an {@link InvalidDeltaException}
* by reattempting the update by sending the full application object.
*/
void fromDelta(DataInput in) throws IOException, InvalidDeltaException;
/**
* By default, entry sizes are not recalculated when deltas are applied. This optimizes for the
* case where the size of an entry does not change. However, if an entry size does increase or
* decrease, this default behavior can result in the memory usage statistics becoming inaccurate.
* These are used to monitor the health of Geode instances, and for balancing memory usage across
* partitioned regions.
*
* <p>
* There is a system property, gemfire.DELTAS_RECALCULATE_SIZE, which can be used to cause all
* deltas to trigger entry size recalculation when deltas are applied. By default, this is set
* to 'false' because of potential performance impacts when every delta triggers a recalculation.
*
* <p>
* To allow entry size recalculation on a per-delta basis, classes that extend the Delta interface
* should override this method to return 'true'. This may impact performance of specific delta
* types, but will not globally affect the performance of other Geode delta operations.
*
* @since 1.14
*/
default boolean getForceRecalculateSize() {
return false;
}
}
| 43.888889 | 100 | 0.746273 |
663e4d55a4363a33a5043b937d86126077e01ef7 | 2,330 | package Commands;
import Input.Flat;
import Session.SessionServerClient;
import Utils.Context;
import Utils.FlatCreator;
public class CommandAddIfMax extends Command implements CommandAuthorized {
private Flat flatNew;
@Override
public void preExecute() {
flatNew = getFlatNew();
}
@Override
public void execute(Context context, SessionServerClient session) {
session.append("Новый элемент ").append(flatNew.toString()).append("\n");
if (context.collectionManager.getIsCollectionEmpty()) {
context.collectionManager.addFlatToCollection(flatNew);
session.append("В коллекцию добавлен элемент ").append(flatNew.toString()).append("\n");
} else {
Flat flatMax = getFlatMax(context, session);
addFlatNewToCollectionIfGreaterThatFlatMax(context, session, flatNew, flatMax);
}
}
private Flat getFlatNew() {
return FlatCreator.getCreatedFlatFromTerminal(Context.lineReader);
}
private Flat getFlatMax(Context context, SessionServerClient session) {
Flat flatMax = context.collectionManager.getFlatMax();
session.append("Наибольший элемент коллекции ").append(flatMax.toString()).append("\n");
System.out.println();
return flatMax;
}
private void addFlatNewToCollectionIfGreaterThatFlatMax(Context context, SessionServerClient session, Flat flatNew, Flat flatMax) {
if (flatNew.compareTo(flatMax) > 0)
addFlatNewToCollection(context, session, flatNew);
else
dontAddFlatNewToCollection(session);
}
private void addFlatNewToCollection(Context context, SessionServerClient session, Flat flatNew) {
session.append("Значение нового элемента превышает значение наибольшего элемента коллекции\n");
context.dataBaseManager.addFlat(flatNew, session);
context.collectionManager.addFlatToCollection(flatNew);
session.append("В коллекцию добавлен элемент ").append(flatNew.toString()).append("\n");
}
private void dontAddFlatNewToCollection(SessionServerClient session) {
session.append("Значение нового элемента не превышает значение наибольшего элемента коллекции\n");
session.append("В коллекцию элемент не добавлен");
}
@Override
public String getName() {
return "add_if_max";
}
@Override
public String getDescription() {
return "добавить новый элемент в коллекцию, если его значение превышает значение наибольшего элемента этой коллекции";
}
}
| 34.264706 | 132 | 0.777682 |
72a8ab4796550932a1edc4431908b14b49678b64 | 3,539 | /*******************************************************************************
* Copyright (c) 2001, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.datatools.modelbase.sql.datatypes;
import org.eclipse.datatools.modelbase.sql.schema.ReferentialActionType;
import org.eclipse.datatools.modelbase.sql.schema.TypedElement;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Field</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Reference: 5WD-02-Foundation-2002-12 4.13 Columns, fields, and attributes
*
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.eclipse.datatools.modelbase.sql.datatypes.Field#getScopeCheck <em>Scope Check</em>}</li>
* <li>{@link org.eclipse.datatools.modelbase.sql.datatypes.Field#isScopeChecked <em>Scope Checked</em>}</li>
* </ul>
* </p>
*
* @see org.eclipse.datatools.modelbase.sql.datatypes.SQLDataTypesPackage#getField()
* @model
* @generated
*/
public interface Field extends TypedElement {
/**
* Returns the value of the '<em><b>Scope Check</b></em>' attribute.
* The literals are from the enumeration {@link org.eclipse.datatools.modelbase.sql.schema.ReferentialActionType}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Scope Check</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Scope Check</em>' attribute.
* @see org.eclipse.datatools.modelbase.sql.schema.ReferentialActionType
* @see #setScopeCheck(ReferentialActionType)
* @see org.eclipse.datatools.modelbase.sql.datatypes.SQLDataTypesPackage#getField_ScopeCheck()
* @model
* @generated
*/
ReferentialActionType getScopeCheck();
/**
* Sets the value of the '{@link org.eclipse.datatools.modelbase.sql.datatypes.Field#getScopeCheck <em>Scope Check</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Scope Check</em>' attribute.
* @see org.eclipse.datatools.modelbase.sql.schema.ReferentialActionType
* @see #getScopeCheck()
* @generated
*/
void setScopeCheck(ReferentialActionType value);
/**
* Returns the value of the '<em><b>Scope Checked</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Scope Checked</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Scope Checked</em>' attribute.
* @see #setScopeChecked(boolean)
* @see org.eclipse.datatools.modelbase.sql.datatypes.SQLDataTypesPackage#getField_ScopeChecked()
* @model
* @generated
*/
boolean isScopeChecked();
/**
* Sets the value of the '{@link org.eclipse.datatools.modelbase.sql.datatypes.Field#isScopeChecked <em>Scope Checked</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Scope Checked</em>' attribute.
* @see #isScopeChecked()
* @generated
*/
void setScopeChecked(boolean value);
} // Field
| 36.864583 | 136 | 0.660356 |
d5625f6ee2f19268c66f4343470c5d1a8cc1572f | 161 | package util;
/**
* Represents how a robot can act.
* @author Mitch Parry
* @version Jun 3, 2015
*
*/
public enum Act
{
MOVE, ATTACK, SUICIDE, GUARD
};
| 13.416667 | 34 | 0.63354 |
b17ab249887a0a823bbc05e1102ee6c7741d65c7 | 537 | package com.rendiyu.dao;
import com.github.pagehelper.Page;
import com.rendiyu.pojo.CheckItem;
import java.util.List;
public interface CheckItemDao {
List<CheckItem> findCheckItemByCheckGroupId(Integer id);
List<CheckItem> findAll();
void addCheckItem(CheckItem checkItem);
Page<CheckItem> findByCondition(String queryString);
CheckItem findById(Integer id);
void edit(CheckItem checkItem);
void delete(Integer id);
Integer findByIdFromTCC(Integer id);
void deleteByIdFromTcc(Integer id);
}
| 21.48 | 61 | 0.750466 |
5e0987d9a0d5d6b30be39d65d950e3ae5aaf1edd | 354 | package cz.mg.sql.builder.blocks.rows.create;
import cz.mg.sql.builder.utilities.SqlBlockBuilder;
import cz.mg.sql.builder.utilities.SqlColumnBuilder;
public class SqlInsertIntoBlockBuilder extends SqlBlockBuilder {
public SqlInsertIntoBlockBuilder(String table) {
super("INSERT INTO", table, new SqlColumnBuilder("(", ")", ","));
}
}
| 29.5 | 73 | 0.748588 |
417a5eab8b8f7fcac47432123ba66eed53b78b6a | 3,162 | package org.jchlabs.gharonda.handlers;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.jchlabs.gharonda.domain.model.Favorites;
import org.jchlabs.gharonda.domain.model.NumberSearchCriteria;
import org.jchlabs.gharonda.domain.model.SearchCriteriaIFace;
import org.jchlabs.gharonda.domain.model.Users;
import org.jchlabs.gharonda.domain.pom.dao.iface.FavoritesDAO;
import org.jchlabs.gharonda.search.SearchService;
import org.jchlabs.gharonda.shared.rpc.RemoveFavorite;
import org.jchlabs.gharonda.shared.rpc.RemoveFavoriteResult;
import org.jchlabs.gharonda.shared.rpc.Status;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;
/**
* Handler for handle RemoveFavorite requests
*
*/
public class RemoveFavoriteHandler extends AbstractSessionHandler<RemoveFavorite, RemoveFavoriteResult> {
private Provider<FavoritesDAO> favoritesDAOProvider;
@Inject
public RemoveFavoriteHandler(Log logger, Provider<HttpSession> provider, Provider<FavoritesDAO> favoritesDAOProvider) {
super(logger, provider);
this.favoritesDAOProvider = favoritesDAOProvider;
}
/*
* (non-Javadoc)
*
* @see org.apache.hupa.server.handler.AbstractSessionHandler#executeInternal (org.apache.hupa.shared.rpc.Session,
* net.customware.gwt.dispatch.server.ExecutionContext)
*/
public RemoveFavoriteResult executeInternal(RemoveFavorite action, ExecutionContext arg1) throws ActionException {
Users user = getUser();
RemoveFavoriteResult result = null;
if (user == null) {
result = new RemoveFavoriteResult(Status.FAIL);
} else {
List<Integer> pids = action.getPids();
if (pids != null) {
FavoritesDAO fDAO = favoritesDAOProvider.get();
List<SearchCriteriaIFace> criteriaList = new ArrayList<SearchCriteriaIFace>();
NumberSearchCriteria uidSrchCriteria = new NumberSearchCriteria("UserId", user.getId());
criteriaList.add(uidSrchCriteria);
SearchService service = new SearchService(Favorites.class,
(org.jchlabs.gharonda.domain.pom.dao.FavoritesDAO) fDAO);
List<Object> favorites = service.search(criteriaList);
if (favorites.size() > 0) {
for (Object o : favorites) {
Favorites f = (Favorites) o;
Integer pid = f.getPid();
if (pids.contains(pid)) {
fDAO.delete(f);
}
}
result = new RemoveFavoriteResult(Status.SUCCESS);
} else {
result = new RemoveFavoriteResult(Status.FAIL);
}
} else {
result = new RemoveFavoriteResult(Status.FAIL);
}
}
return result;
}
/*
* (non-Javadoc)
*
* @see net.customware.gwt.dispatch.server.ActionHandler#getActionType()
*/
public Class<RemoveFavorite> getActionType() {
return RemoveFavorite.class;
}
@Override
public void undo(RemoveFavorite action, RemoveFavoriteResult result, ExecutionContext context)
throws ActionException {
// TODO Auto-generated method stub
}
}
| 33.284211 | 121 | 0.734662 |
7273ee145e5d3b41d5219c75fb3590a4321a7c4a | 6,008 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/assuredworkloads/v1beta1/assuredworkloads_v1beta1.proto
package com.google.cloud.assuredworkloads.v1beta1;
public interface CreateWorkloadOperationMetadataOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.assuredworkloads.v1beta1.CreateWorkloadOperationMetadata)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Optional. Time when the operation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the createTime field is set.
*/
boolean hasCreateTime();
/**
*
*
* <pre>
* Optional. Time when the operation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The createTime.
*/
com.google.protobuf.Timestamp getCreateTime();
/**
*
*
* <pre>
* Optional. Time when the operation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder();
/**
*
*
* <pre>
* Optional. The display name of the workload.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The displayName.
*/
java.lang.String getDisplayName();
/**
*
*
* <pre>
* Optional. The display name of the workload.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for displayName.
*/
com.google.protobuf.ByteString getDisplayNameBytes();
/**
*
*
* <pre>
* Optional. The parent of the workload.
* </pre>
*
* <code>string parent = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The parent.
*/
java.lang.String getParent();
/**
*
*
* <pre>
* Optional. The parent of the workload.
* </pre>
*
* <code>string parent = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for parent.
*/
com.google.protobuf.ByteString getParentBytes();
/**
*
*
* <pre>
* Optional. Compliance controls that should be applied to the resources
* managed by the workload.
* </pre>
*
* <code>
* .google.cloud.assuredworkloads.v1beta1.Workload.ComplianceRegime compliance_regime = 4 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for complianceRegime.
*/
int getComplianceRegimeValue();
/**
*
*
* <pre>
* Optional. Compliance controls that should be applied to the resources
* managed by the workload.
* </pre>
*
* <code>
* .google.cloud.assuredworkloads.v1beta1.Workload.ComplianceRegime compliance_regime = 4 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The complianceRegime.
*/
com.google.cloud.assuredworkloads.v1beta1.Workload.ComplianceRegime getComplianceRegime();
/**
*
*
* <pre>
* Optional. Resource properties in the input that are used for
* creating/customizing workload resources.
* </pre>
*
* <code>
* repeated .google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettings resource_settings = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
java.util.List<com.google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettings>
getResourceSettingsList();
/**
*
*
* <pre>
* Optional. Resource properties in the input that are used for
* creating/customizing workload resources.
* </pre>
*
* <code>
* repeated .google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettings resource_settings = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
com.google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettings getResourceSettings(
int index);
/**
*
*
* <pre>
* Optional. Resource properties in the input that are used for
* creating/customizing workload resources.
* </pre>
*
* <code>
* repeated .google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettings resource_settings = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
int getResourceSettingsCount();
/**
*
*
* <pre>
* Optional. Resource properties in the input that are used for
* creating/customizing workload resources.
* </pre>
*
* <code>
* repeated .google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettings resource_settings = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
java.util.List<
? extends com.google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettingsOrBuilder>
getResourceSettingsOrBuilderList();
/**
*
*
* <pre>
* Optional. Resource properties in the input that are used for
* creating/customizing workload resources.
* </pre>
*
* <code>
* repeated .google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettings resource_settings = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
com.google.cloud.assuredworkloads.v1beta1.Workload.ResourceSettingsOrBuilder
getResourceSettingsOrBuilder(int index);
}
| 27.814815 | 143 | 0.668609 |
08acb0bf020aa22db6c4079906f2df6ed1879060 | 11,836 | /*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.ning.http.client.providers.netty;
import static com.ning.http.util.DateUtil.millisTime;
import com.ning.http.client.ConnectionsPool;
import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A simple implementation of {@link com.ning.http.client.ConnectionsPool} based on a {@link java.util.concurrent.ConcurrentHashMap}
*/
public class NettyConnectionsPool implements ConnectionsPool<String, Channel> {
private final static Logger log = LoggerFactory.getLogger(NettyConnectionsPool.class);
private final ConcurrentHashMap<String, ConcurrentLinkedQueue<IdleChannel>> connectionsPool = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IdleChannel>>();
private final ConcurrentHashMap<Channel, IdleChannel> channel2IdleChannel = new ConcurrentHashMap<Channel, IdleChannel>();
private final ConcurrentHashMap<Channel, Long> channel2CreationDate = new ConcurrentHashMap<Channel, Long>();
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final Timer idleConnectionDetector;
private final boolean sslConnectionPoolEnabled;
private final int maxTotalConnections;
private final int maxConnectionPerHost;
private final int maxConnectionLifeTimeInMs;
private final long maxIdleTime;
public NettyConnectionsPool(NettyAsyncHttpProvider provider) {
this(provider.getConfig().getMaxTotalConnections(),//
provider.getConfig().getMaxConnectionPerHost(),//
provider.getConfig().getIdleConnectionInPoolTimeoutInMs(),//
provider.getConfig().getMaxConnectionLifeTimeInMs(),//
provider.getConfig().isSslConnectionPoolEnabled(),//
new Timer(true));
}
public NettyConnectionsPool(int maxTotalConnections, int maxConnectionPerHost, long maxIdleTime, int maxConnectionLifeTimeInMs, boolean sslConnectionPoolEnabled, Timer idleConnectionDetector) {
this.maxTotalConnections = maxTotalConnections;
this.maxConnectionPerHost = maxConnectionPerHost;
this.sslConnectionPoolEnabled = sslConnectionPoolEnabled;
this.maxIdleTime = maxIdleTime;
this.maxConnectionLifeTimeInMs = maxConnectionLifeTimeInMs;
this.idleConnectionDetector = idleConnectionDetector;
this.idleConnectionDetector.schedule(new IdleChannelDetector(), maxIdleTime, maxIdleTime);
}
private static class IdleChannel {
final String uri;
final Channel channel;
final long start;
IdleChannel(String uri, Channel channel) {
this.uri = uri;
this.channel = channel;
this.start = millisTime();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IdleChannel)) return false;
IdleChannel that = (IdleChannel) o;
if (channel != null ? !channel.equals(that.channel) : that.channel != null) return false;
return true;
}
@Override
public int hashCode() {
return channel != null ? channel.hashCode() : 0;
}
}
private class IdleChannelDetector extends TimerTask {
@Override
public void run() {
try {
if (isClosed.get()) return;
if (log.isDebugEnabled()) {
Set<String> keys = connectionsPool.keySet();
for (String s : keys) {
log.debug("Entry count for : {} : {}", s, connectionsPool.get(s).size());
}
}
List<IdleChannel> channelsInTimeout = new ArrayList<IdleChannel>();
long currentTime = millisTime();
for (IdleChannel idleChannel : channel2IdleChannel.values()) {
long age = currentTime - idleChannel.start;
if (age > maxIdleTime) {
log.debug("Adding Candidate Idle Channel {}", idleChannel.channel);
// store in an unsynchronized list to minimize the impact on the ConcurrentHashMap.
channelsInTimeout.add(idleChannel);
}
}
long endConcurrentLoop = millisTime();
for (IdleChannel idleChannel : channelsInTimeout) {
Object attachment = idleChannel.channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
if (attachment instanceof NettyResponseFuture) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) attachment;
if (!future.isDone() && !future.isCancelled()) {
log.debug("Future not in appropriate state %s\n", future);
continue;
}
}
if (remove(idleChannel)) {
log.debug("Closing Idle Channel {}", idleChannel.channel);
close(idleChannel.channel);
}
}
if (log.isTraceEnabled()) {
int openChannels = 0;
for (ConcurrentLinkedQueue<IdleChannel> hostChannels: connectionsPool.values()) {
openChannels += hostChannels.size();
}
log.trace(String.format("%d channel open, %d idle channels closed (times: 1st-loop=%d, 2nd-loop=%d).\n",
openChannels, channelsInTimeout.size(), endConcurrentLoop - currentTime, millisTime() - endConcurrentLoop));
}
} catch (Throwable t) {
log.error("uncaught exception!", t);
}
}
}
/**
* {@inheritDoc}
*/
public boolean offer(String uri, Channel channel) {
if (isClosed.get()) return false;
if (!sslConnectionPoolEnabled && uri.startsWith("https")) {
return false;
}
Long createTime = channel2CreationDate.get(channel);
if (createTime == null) {
channel2CreationDate.putIfAbsent(channel, millisTime());
} else if (maxConnectionLifeTimeInMs != -1 && (createTime + maxConnectionLifeTimeInMs) < millisTime()) {
log.debug("Channel {} expired", channel);
return false;
}
log.debug("Adding uri: {} for channel {}", uri, channel);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(new NettyAsyncHttpProvider.DiscardEvent());
ConcurrentLinkedQueue<IdleChannel> idleConnectionForHost = connectionsPool.get(uri);
if (idleConnectionForHost == null) {
ConcurrentLinkedQueue<IdleChannel> newPool = new ConcurrentLinkedQueue<IdleChannel>();
idleConnectionForHost = connectionsPool.putIfAbsent(uri, newPool);
if (idleConnectionForHost == null) idleConnectionForHost = newPool;
}
boolean added;
int size = idleConnectionForHost.size();
if (maxConnectionPerHost == -1 || size < maxConnectionPerHost) {
IdleChannel idleChannel = new IdleChannel(uri, channel);
synchronized (idleConnectionForHost) {
added = idleConnectionForHost.add(idleChannel);
if (channel2IdleChannel.put(channel, idleChannel) != null) {
log.error("Channel {} already exists in the connections pool!", channel);
}
}
} else {
log.debug("Maximum number of requests per host reached {} for {}", maxConnectionPerHost, uri);
added = false;
}
return added;
}
/**
* {@inheritDoc}
*/
public Channel poll(String uri) {
if (!sslConnectionPoolEnabled && uri.startsWith("https")) {
return null;
}
IdleChannel idleChannel = null;
ConcurrentLinkedQueue<IdleChannel> idleConnectionForHost = connectionsPool.get(uri);
if (idleConnectionForHost != null) {
boolean poolEmpty = false;
while (!poolEmpty && idleChannel == null) {
if (!idleConnectionForHost.isEmpty()) {
synchronized (idleConnectionForHost) {
idleChannel = idleConnectionForHost.poll();
if (idleChannel != null) {
channel2IdleChannel.remove(idleChannel.channel);
}
}
}
if (idleChannel == null) {
poolEmpty = true;
} else if (!idleChannel.channel.isConnected() || !idleChannel.channel.isOpen()) {
idleChannel = null;
log.trace("Channel not connected or not opened!");
}
}
}
return idleChannel != null ? idleChannel.channel : null;
}
private boolean remove(IdleChannel pooledChannel) {
if (pooledChannel == null || isClosed.get()) return false;
boolean isRemoved = false;
ConcurrentLinkedQueue<IdleChannel> pooledConnectionForHost = connectionsPool.get(pooledChannel.uri);
if (pooledConnectionForHost != null) {
isRemoved = pooledConnectionForHost.remove(pooledChannel);
}
isRemoved |= channel2IdleChannel.remove(pooledChannel.channel) != null;
return isRemoved;
}
/**
* {@inheritDoc}
*/
public boolean removeAll(Channel channel) {
channel2CreationDate.remove(channel);
return !isClosed.get() && remove(channel2IdleChannel.get(channel));
}
/**
* {@inheritDoc}
*/
public boolean canCacheConnection() {
if (!isClosed.get() && maxTotalConnections != -1 && channel2IdleChannel.size() >= maxTotalConnections) {
return false;
} else {
return true;
}
}
/**
* {@inheritDoc}
*/
public void destroy() {
if (isClosed.getAndSet(true)) return;
// stop timer
idleConnectionDetector.cancel();
idleConnectionDetector.purge();
for (Channel channel : channel2IdleChannel.keySet()) {
close(channel);
}
connectionsPool.clear();
channel2IdleChannel.clear();
channel2CreationDate.clear();
}
private void close(Channel channel) {
try {
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(new NettyAsyncHttpProvider.DiscardEvent());
channel2CreationDate.remove(channel);
channel.close();
} catch (Throwable t) {
// noop
}
}
public final String toString() {
return String.format("NettyConnectionPool: {pool-size: %d}", channel2IdleChannel.size());
}
}
| 39.585284 | 197 | 0.614988 |
f3f85a4fc958b81de956bcfb149d81afec023c8b | 3,453 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection;
import com.intellij.codeInspection.dataFlow.CommonDataflow;
import com.intellij.codeInspection.dataFlow.TypeConstraint;
import com.intellij.java.JavaBundle;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.callMatcher.CallMatcher;
import com.siyeh.ig.psiutils.CommentTracker;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.TypeUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import static com.siyeh.ig.callMatcher.CallMatcher.instanceCall;
public class SlowAbstractSetRemoveAllInspection extends AbstractBaseJavaLocalInspectionTool {
private static final String FOR_EACH_METHOD = "forEach";
private static final CallMatcher SET_REMOVE_ALL =
instanceCall(CommonClassNames.JAVA_UTIL_SET, "removeAll").parameterTypes(CommonClassNames.JAVA_UTIL_COLLECTION);
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression call) {
super.visitMethodCallExpression(call);
if (!SET_REMOVE_ALL.test(call)) return;
final PsiExpression arg = call.getArgumentList().getExpressions()[0];
if (!TypeUtils.expressionHasTypeOrSubtype(arg, CommonClassNames.JAVA_UTIL_LIST)) return;
final PsiExpression qualifier = call.getMethodExpression().getQualifierExpression();
if (qualifier == null) return;
final String s = arg.getText() + ".forEach(" + qualifier.getText() + "::remove)";
holder.registerProblem(call,
JavaBundle.message("inspection.slow.abstract.set.remove.all.description"),
ProblemHighlightType.WARNING,
new ReplaceWithListForEachFix(s));
}
};
}
private static class ReplaceWithListForEachFix implements LocalQuickFix {
final String myExpressionText;
ReplaceWithListForEachFix(String string) {
myExpressionText = string;
}
@Nls
@NotNull
@Override
public String getName() {
return CommonQuickFixBundle.message("fix.replace.with.x", myExpressionText);
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return JavaBundle.message("inspection.slow.abstract.set.remove.all.fix.family.name");
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiMethodCallExpression call = ObjectUtils.tryCast(descriptor.getPsiElement(), PsiMethodCallExpression.class);
if (call == null) return;
final PsiExpression[] args = call.getArgumentList().getExpressions();
if (args.length != 1) return;
final PsiExpression arg = args[0];
final PsiExpression qualifier = call.getMethodExpression().getQualifierExpression();
if (qualifier == null) return;
ExpressionUtils.bindCallTo(call, FOR_EACH_METHOD);
final CommentTracker ct = new CommentTracker();
final String setRemove = qualifier.getText() + "::remove";
ct.replace(qualifier, arg);
ct.replace(arg, setRemove);
}
}
}
| 40.623529 | 140 | 0.728642 |
ceb5a99a3095a9cdd8a61f2d4b6f0892cfc4e714 | 243 | package com.BusReservation.service;
import java.util.List;
import com.BusReservation.model.AuthorizedUser;
public interface ICustomerService {
List<AuthorizedUser> fetchPassword(String email);
void AddUser(AuthorizedUser authuser);
}
| 16.2 | 49 | 0.8107 |
7677b61263382a2b0c36f4b6ee8fdf65b906b350 | 5,239 | package ch.xcal.serialization.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.junit.Test;
import ch.xcal.serialization.stream.IStreamElement;
import ch.xcal.serialization.stream.SerializationStream;
import ch.xcal.serialization.stream.primitive.IntegerElement;
import ch.xcal.serialization.stream.ref.ClassDescElement;
import ch.xcal.serialization.stream.ref.ObjectElement;
import ch.xcal.serialization.stream.ref.StringElement;
import ch.xcal.serialization.stream.root.NullHandle;
import ch.xcal.serialization.stream.root.handle.ObjectHandle;
import ch.xcal.serialization.stream.root.handle.StringHandle;
public class ParserNewObjectTest {
@Test
public void testIntHolderObject() throws IOException {
final IntHolder intHolder = new IntHolder();
intHolder.value = 10;
final SerializationStream result = parseSingleObject(intHolder);
final ObjectElement obj = assertObjectOfClazz(result, intHolder.getClass());
assertEquals(1, obj.getFields().size());
assertTrue(obj.getFields().get(0) instanceof IntegerElement);
assertEquals(intHolder.value, ((IntegerElement) obj.getFields().get(0)).getValue());
}
@Test
public void testIntHolderHolderObject() throws IOException {
final IntHolderHolder nullHolder = new IntHolderHolder();
final SerializationStream result = parseSingleObject(nullHolder);
final ObjectElement obj = assertObjectOfClazz(result, nullHolder.getClass());
assertEquals(1, obj.getFields().size());
assertTrue(obj.getFields().get(0) instanceof NullHandle);
final IntHolderHolder otherIntHolder = new IntHolderHolder();
otherIntHolder.value = new IntHolder();
otherIntHolder.value.value = -1;
final SerializationStream result2 = parseSingleObject(otherIntHolder);
final ObjectElement obj2 = assertObjectOfClazz(result2, otherIntHolder.getClass());
assertEquals(1, obj2.getFields().size());
assertTrue(obj2.getFields().get(0) instanceof ObjectHandle);
final ObjectElement obj2Value = (ObjectElement) result2.resolveHandle((ObjectHandle) obj2.getFields().get(0));
assertEquals(otherIntHolder.value.getClass().getName(),
((ClassDescElement) result2.resolveHandle(obj2Value.getClassDesc())).getName());
assertEquals(1, obj2Value.getFields().size());
assertTrue(obj2Value.getFields().get(0) instanceof IntegerElement);
assertEquals(otherIntHolder.value.value, ((IntegerElement) obj2Value.getFields().get(0)).getValue());
}
@Test
public void testSubclassObject() throws IOException {
final SubClass subClass = new SubClass();
subClass.value = "subClass";
((SuperClass) subClass).value = "superClass";
final SerializationStream result = parseSingleObject(subClass);
final ObjectElement subClassObj = assertObjectOfClazz(result, subClass.getClass());
final ObjectElement superClassObj = subClassObj.getSuperClassObject();
assertEquals(SuperClass.class.getName(), ((ClassDescElement) result.resolveHandle(superClassObj.getClassDesc())).getName());
assertEquals(1, subClassObj.getFields().size());
assertTrue(subClassObj.getFields().get(0) instanceof StringHandle);
final IStreamElement subClassContent = result.resolveHandle((StringHandle) subClassObj.getFields().get(0));
assertTrue(subClassContent instanceof StringElement);
assertEquals("subClass", ((StringElement) subClassContent).getValue());
assertEquals(1, superClassObj.getFields().size());
assertTrue(superClassObj.getFields().get(0) instanceof StringHandle);
final IStreamElement superClassContent = result.resolveHandle((StringHandle) superClassObj.getFields().get(0));
assertTrue(superClassContent instanceof StringElement);
assertEquals("superClass", ((StringElement) superClassContent).getValue());
}
private ObjectElement assertObjectOfClazz(SerializationStream result, Class<?> clz) {
assertEquals(1, result.getRootElements().size()); // classDesc & object
assertTrue(result.getRootElements().get(0) instanceof ObjectHandle);
final ObjectElement obj = result.resolveHandle((ObjectHandle) result.getRootElements().get(0));
assertEquals(clz.getName(), ((ClassDescElement) result.resolveHandle(obj.getClassDesc())).getName());
return obj;
}
private SerializationStream parseSingleObject(Object clz) throws IOException {
final ByteArrayOutputStream o = new ByteArrayOutputStream();
final ObjectOutputStream out = new ObjectOutputStream(o);
out.writeObject(clz);
out.flush();
final byte[] result = o.toByteArray();
return Parser.parse(new ByteArrayInputStream(result));
}
public static class IntHolder implements Serializable {
private static final long serialVersionUID = 1L;
public int value;
}
public static class IntHolderHolder implements Serializable {
private static final long serialVersionUID = 1L;
public IntHolder value;
}
public static class SuperClass implements Serializable {
private static final long serialVersionUID = 1L;
public String value;
}
public static class SubClass extends SuperClass {
private static final long serialVersionUID = 1L;
public String value;
}
}
| 43.658333 | 126 | 0.789082 |
876a2eb10a632864f7ec4f85fd08e37b2a7e96f3 | 479 | package com.pd.danim.Repository;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import com.pd.danim.DTO.Love;
import com.pd.danim.DTO.Story;
import com.pd.danim.DTO.User;
public interface LoveRepository extends CrudRepository<Love, Long> {
boolean existsByUserAndStory(User user, Story story);
@Transactional
int deleteByUserAndStory(User user,Story story);
@Transactional
void deleteAllByStory(Story story);
}
| 21.772727 | 68 | 0.80167 |
287a378e01407da144faa07e24e1fe5a94644925 | 729 | package com.appdynamics.extensions.docker;
import com.google.common.collect.Maps;
import com.singularity.ee.agent.systemagent.api.exception.TaskExecutionException;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class DockerMonitorTest {
private static final String CONFIG_ARGS = "config-file";
private static final String CONFIG_FILE_PATH = "src/test/resources/conf/config.yml";
@Test
public void testDockerMonitor() throws TaskExecutionException {
DockerMonitor dockerMonitor = new DockerMonitor();
final Map<String, String> taskArgs = new HashMap<>();
taskArgs.put(CONFIG_ARGS,CONFIG_FILE_PATH);
dockerMonitor.execute(taskArgs,null);
}
}
| 30.375 | 88 | 0.751715 |
5bd1f36ddf07d9963e2a4df465e43e79b067d414 | 3,193 | package com.emc.rpsp.fal.commons;
import javax.xml.bind.annotation.*;
@SuppressWarnings("serial")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReplicaFileSystemCreationParam")
public class ReplicaFileSystemCreationParam implements Validateable {
@XmlElement(required = true)
private ConsistencyGroupCopyUID targetCopyUID;
@XmlElement(required = true)
private String defaultDataMover;
@XmlElement(required = true)
private String storagePool;
public ReplicaFileSystemCreationParam() {
}
public ReplicaFileSystemCreationParam(ConsistencyGroupCopyUID targetCopyUID, String defaultDataMover, String storagePool) {
this.targetCopyUID = targetCopyUID;
this.defaultDataMover = defaultDataMover;
this.storagePool = storagePool;
}
public ConsistencyGroupCopyUID getTargetCopyUID() {
return targetCopyUID;
}
public void setTargetCopyUID(ConsistencyGroupCopyUID targetCopyUID) {
this.targetCopyUID = targetCopyUID;
}
public String getDefaultDataMover() {
return defaultDataMover;
}
public void setDefaultDataMover(String defaultDataMover) {
this.defaultDataMover = defaultDataMover;
}
public String getStoragePool() {
return storagePool;
}
public void setStoragePool(String storagePool) {
this.storagePool = storagePool;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((defaultDataMover == null) ? 0 : defaultDataMover.hashCode());
result = prime * result
+ ((storagePool == null) ? 0 : storagePool.hashCode());
result = prime * result
+ ((targetCopyUID == null) ? 0 : targetCopyUID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReplicaFileSystemCreationParam other = (ReplicaFileSystemCreationParam) obj;
if (defaultDataMover == null) {
if (other.defaultDataMover != null)
return false;
} else if (!defaultDataMover.equals(other.defaultDataMover))
return false;
if (storagePool == null) {
if (other.storagePool != null)
return false;
} else if (!storagePool.equals(other.storagePool))
return false;
if (targetCopyUID == null) {
if (other.targetCopyUID != null)
return false;
} else if (!targetCopyUID.equals(other.targetCopyUID))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ReplicaFileSystemCreationParam [targetCopyUID=")
.append(targetCopyUID).append(", defaultDataMover=")
.append(defaultDataMover).append(", storagePool=")
.append(storagePool).append("]");
return builder.toString();
}
}
| 31 | 127 | 0.633887 |
62ff09fd84e2d97cb5139f538c14dbd66c7eb18f | 2,116 | /*
* This is the code written in order to do some tests with the drivetrain.
* This may or may not be rewritten and morphed to be used in the actual competition.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.teamcode.core.Lawnmower;
@TeleOp(name="TeleOp Test", group="Testing")
public final class TeleOpTest extends OpMode {
private static Lawnmower lawnmower;
@Override
public final void init() {
lawnmower = Lawnmower.init(hardwareMap, false, false);
telemetry.addData("Status", "Initialized");
}
@Override
public final void start() {
lawnmower.runtime.reset();
}
@Override
public final void loop() {
telemetry.addData("Status", "Runtime: " + lawnmower.runtime.toString());
// WIP: Proper mechanum driving.
// FIXME: Counteract imperfect strafing.
// This can be done via `leftHorizPos * a`.
// Also, optionally, we could try to preserve the ratios needed.
final double leftVertPos = -gamepad1.left_stick_y;
final double leftHorizPos = gamepad1.left_stick_x;
final double rightHorizPos = gamepad1.right_stick_x;
lawnmower.frontLeft.setPower(leftVertPos + leftHorizPos + rightHorizPos);
lawnmower.backLeft.setPower(leftVertPos - leftHorizPos + rightHorizPos);
lawnmower.frontRight.setPower(leftVertPos - leftHorizPos - rightHorizPos);
lawnmower.backRight.setPower(leftVertPos + leftHorizPos - rightHorizPos);
// FIXME: Remap these to something that makes more sense.
// Again, this is here for testing purposes only.
if (gamepad2.x) {
lawnmower.intake.setPower(1);
lawnmower.revolvingDoor.setPower(0.25);
} else {
lawnmower.intake.setPower(0);
lawnmower.revolvingDoor.setPower(0);
}
if (gamepad2.b)
lawnmower.intake.setPower(-1);
else
lawnmower.intake.setPower(0);
}
}
| 33.587302 | 85 | 0.668242 |
d2a05c7f06bd175c32aa04899958b923d1b099ba | 3,127 | /*
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.googlecompute.compute;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Module;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.internal.BaseComputeServiceLiveTest;
import org.jclouds.oauth.v2.OAuthTestUtils;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.Test;
import java.util.Properties;
import static org.testng.Assert.assertTrue;
/**
* @author David Alves
*/
@Test(groups = "live", singleThreaded = true)
public class GoogleComputeServiceLiveTest extends BaseComputeServiceLiveTest {
public GoogleComputeServiceLiveTest() {
provider = "google-compute";
}
/**
* Nodes may have additional metadata entries (particularly they may have an "sshKeys" entry)
*/
protected void checkUserMetadataInNodeEquals(NodeMetadata node, ImmutableMap<String, String> userMetadata) {
assertTrue(node.getUserMetadata().keySet().containsAll(userMetadata.keySet()));
}
// do not run until the auth exception problem is figured out.
@Test(enabled = false)
@Override
public void testCorrectAuthException() throws Exception {
}
// reboot is not supported by GCE
@Test(enabled = true, dependsOnMethods = "testGet")
public void testReboot() throws Exception {
}
// suspend/Resume is not supported by GCE
@Test(enabled = true, dependsOnMethods = "testReboot")
public void testSuspendResume() throws Exception {
}
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
@Override
public void testGetNodesWithDetails() throws Exception {
super.testGetNodesWithDetails();
}
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
@Override
public void testListNodes() throws Exception {
super.testListNodes();
}
@Test(enabled = true, dependsOnMethods = {"testListNodes", "testGetNodesWithDetails"})
@Override
public void testDestroyNodes() {
super.testDestroyNodes();
}
@Override
protected Module getSshModule() {
return new SshjSshClientModule();
}
@Override
protected Properties setupProperties() {
Properties properties = super.setupProperties();
OAuthTestUtils.setCredentialFromPemFile(properties, "google-compute.credential");
return properties;
}
}
| 32.237113 | 111 | 0.738407 |
e803342aafcea813754689a15a691217879baf55 | 608 | //@@author ShaocongDong
package seedu.address.model;
import javafx.collections.ObservableList;
import seedu.address.model.tag.Tag;
import seedu.address.model.task.ReadOnlyTask;
/**
* Unmodifiable view of an address book
*/
public interface ReadOnlyTaskBook {
/**
* Returns an unmodifiable view of the persons list.
* This list will not contain any duplicate persons.
*/
ObservableList<ReadOnlyTask> getTaskList();
/**
* Returns an unmodifiable view of the tags list.
* This list will not contain any duplicate tags.
*/
ObservableList<Tag> getTagList();
}
| 23.384615 | 56 | 0.708882 |
6b724d33443887374437b012aa69b16245a5d2f5 | 5,203 | package pl.wsiz.rzeszowlocator;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class ActivityMap extends SherlockFragmentActivity implements OnMapClickListener, OnClickListener{
class MyInfoWindowAdapter implements InfoWindowAdapter{
private final View myContentsView;
MyInfoWindowAdapter(){
myContentsView = getLayoutInflater().inflate(R.layout.info_window, null);
}
@Override
public View getInfoContents(Marker marker) {
TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
//TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
//tvSnippet.setText(marker.getSnippet());
ImageView ivIcon = ((ImageView)myContentsView.findViewById(R.id.imgPw));
//ivIcon.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_menu_gallery));
Bitmap bitmap = BitmapFactory.decodeFile(marker.getSnippet());
ivIcon.setImageBitmap(bitmap);
return myContentsView;
}
@Override
public View getInfoWindow(Marker marker) {
return null;
}
}
private GoogleMap mMap;
private String name = "";
private Button btnRet;
private Marker newMarker;
private LatLng RZESZOW = new LatLng(50.03729805668018, 22.004703283309937);
@Override
public void onCreate(Bundle savedInstanceData) {
super.onCreate(savedInstanceData);
setContentView(R.layout.activity_map);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = this.getIntent();
if (intent.hasExtra("name"))
name = intent.getStringExtra("name");
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (!intent.getBooleanExtra("serv", false)) {
mMap.setInfoWindowAdapter(new MyInfoWindowAdapter());
addMarkers();
} else {
btnRet = (Button) findViewById(R.id.btnRetCoords);
btnRet.setOnClickListener(this);
btnRet.setVisibility(View.VISIBLE);
mMap.setOnMapClickListener(this);
btnRet = (Button) findViewById(R.id.btnRetCoords);
newMarker = mMap.addMarker(new MarkerOptions().position(RZESZOW));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(RZESZOW, 13));
}
//mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
@Override
public void onMapClick(LatLng arg0) {
/*
Marker newMarker = mMap.addMarker(new MarkerOptions()
.position(arg0));*/
newMarker.setPosition(arg0);
/*
newMarker.setTitle(newMarker.getId());*/
}
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("lat", newMarker.getPosition().latitude);
intent.putExtra("lon", newMarker.getPosition().longitude);
setResult(RESULT_OK, intent);
finish();
}
void addMarkers() {
DBHelper dbHelper = null;
SQLiteDatabase db = null;
Cursor c = null;
try {
dbHelper = new DBHelper(this, "itemStore");
db = dbHelper.getWritableDatabase();
if (name.equals("")) { // all
c = db.query("itemStore", null, null, null, null, null, null);
Log.i("TAG", "Count" + c.getCount());
} else {
String[] selectionArgs = new String[] { name };
c = db.query("itemStore", null, "name = ?", selectionArgs, null, null, null);
}
if (c == null || !c.moveToFirst()) {
Toast.makeText(ActivityMap.this, "DB error",
Toast.LENGTH_LONG).show();
return;
}
LatLng RZESZOW;
do {
RZESZOW = new LatLng(Double.parseDouble(c.getString(c.getColumnIndex("lat"))),
Double.parseDouble(c.getString(c.getColumnIndex("lon"))));
mMap.addMarker(new MarkerOptions().position(RZESZOW).snippet(ActivityMain.locations + "_" + c.getString(c.getColumnIndex("img")))).
setTitle(c.getString(c.getColumnIndex("name")));
} while (c.moveToNext());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(RZESZOW, 13));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dbHelper != null)
dbHelper.close();
if (db != null)
db.close();
if (c != null)
c.close();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
} | 31.343373 | 135 | 0.714396 |
8bee57a1fc0c1d45946aa40f4270192fee5c0f04 | 11,746 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package ai.djl.mxnet.engine;
import ai.djl.Device;
import ai.djl.Model;
import ai.djl.TrainingDivergedException;
import ai.djl.metric.Metrics;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDArrays;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.Shape;
import ai.djl.nn.Parameter;
import ai.djl.training.GradientCollector;
import ai.djl.training.LocalParameterServer;
import ai.djl.training.ParameterServer;
import ai.djl.training.ParameterStore;
import ai.djl.training.Trainer;
import ai.djl.training.TrainingConfig;
import ai.djl.training.TrainingListener;
import ai.djl.training.dataset.Batch;
import ai.djl.training.loss.Loss;
import ai.djl.training.metrics.TrainingMetric;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** {@code MxTrainer} is the MXNet implementation of the {@link Trainer}. */
public class MxTrainer implements Trainer {
private static final Logger logger = LoggerFactory.getLogger(MxTrainer.class);
private MxModel model;
private MxNDManager manager;
private Metrics metrics;
private TrainingListener listener;
private Device[] devices;
private ParameterStore parameterStore;
private List<TrainingMetric> trainingMetrics;
private List<TrainingMetric> validateMetrics;
private Loss trainingLoss;
private Loss validationLoss;
long batchBeginTime;
private boolean gradientsChecked;
/**
* Creates an instance of {@code MxTrainer} with the given {@link MxModel} and {@link
* TrainingConfig}.
*
* @param model the model the trainer will train on
* @param trainingConfig the configuration used by the trainer
*/
MxTrainer(MxModel model, TrainingConfig trainingConfig) {
this.model = model;
manager = (MxNDManager) model.getNDManager().newSubManager();
devices = trainingConfig.getDevices();
trainingLoss = trainingConfig.getLossFunction();
if (trainingLoss == null) {
throw new IllegalArgumentException("You must specify a loss for the trainer");
}
validationLoss = trainingLoss.duplicate();
trainingMetrics = new ArrayList<>(trainingConfig.getTrainingMetrics());
validateMetrics = new ArrayList<>();
trainingMetrics.forEach(i -> validateMetrics.add(i.duplicate()));
// track loss as training metric by default
trainingMetrics.add(trainingLoss);
// add from duplication of trainingLoss
// do not mess up with duplication of training metrics
validateMetrics.add(validationLoss);
// ParameterServer parameterServer = new MxParameterServer(trainingConfig.getOptimizer());
ParameterServer parameterServer = new LocalParameterServer(trainingConfig.getOptimizer());
parameterStore = new ParameterStore(manager, false);
parameterStore.setParameterServer(parameterServer, devices);
}
/** {@inheritDoc} */
@Override
public void initialize(Shape... shapes) {
model.getBlock().initialize(model.getNDManager(), model.getDataType(), shapes);
// call getValue on all params to initialize on all devices
model.getBlock()
.getParameters()
.forEach(
pair -> {
for (Device device : devices) {
parameterStore.getValue(pair.getValue(), device);
}
});
}
/** {@inheritDoc} */
@Override
public GradientCollector newGradientCollector() {
return new MxGradientCollector();
}
/** {@inheritDoc} */
@Override
public void trainBatch(Batch batch) {
Batch[] splits = batch.split(devices, false);
try (GradientCollector collector = new MxGradientCollector()) {
for (Batch split : splits) {
NDList data = split.getData();
NDList labels = split.getLabels();
NDList preds = forward(data);
long time = System.nanoTime();
NDArray loss = trainingLoss.getLoss(labels, preds);
collector.backward(loss);
addMetric("backward", time);
time = System.nanoTime();
updateTrainingMetrics(labels, preds);
addMetric("training-metrics", time);
}
}
addMetric("train", batchBeginTime);
// count batch begin time at end of batch to include batch loading time
batchBeginTime = System.nanoTime();
if (listener != null) {
listener.onTrainingBatch();
}
}
/** {@inheritDoc} */
@Override
public NDList forward(NDList input) {
long begin = System.nanoTime();
try {
return model.getBlock().forward(parameterStore, input);
} finally {
addMetric("forward", begin);
}
}
/** {@inheritDoc} */
@Override
public void validateBatch(Batch batch) {
long begin = System.nanoTime();
Batch[] splits = batch.split(devices, false);
for (Batch split : splits) {
NDList data = split.getData();
NDList labels = split.getLabels();
NDList preds = forward(data);
updateValidationMetrics(labels, preds);
}
addMetric("validate", begin);
if (listener != null) {
listener.onValidationBatch();
}
}
/** {@inheritDoc} */
@Override
public void step() {
if (!gradientsChecked) {
checkGradients();
}
long begin = System.nanoTime();
parameterStore.updateAllParameters();
addMetric("step", begin);
}
/** {@inheritDoc} */
@Override
public void setMetrics(Metrics metrics) {
this.metrics = metrics;
}
/** {@inheritDoc} */
@Override
public void setTrainingListener(TrainingListener listener) {
this.listener = listener;
}
private void updateTrainingMetrics(NDList labels, NDList preds) {
// stop recording as this is end of computation graph
// any metric calculation or update operation should not be recorded
MxGradientCollector.setRecording(false);
MxGradientCollector.setTraining(false);
// this step is synchronized, should be done at end of batch
trainingMetrics.forEach(metrics -> metrics.update(labels, preds));
// TODO: this can be done during onBatch listener
addMetric("train", trainingLoss);
if (Float.isNaN(trainingLoss.getValue())) {
throw new TrainingDivergedException(
"The Loss became NaN, try reduce learning rate,"
+ "add clipGradient option to your optimizer, check input data and loss calculation.");
}
trainingMetrics.forEach(metric -> addMetric("train", metric));
// turn gradient recording back on
MxGradientCollector.setRecording(true);
MxGradientCollector.setTraining(true);
}
private void updateValidationMetrics(NDList labels, NDList preds) {
validateMetrics.forEach(metrics -> metrics.update(labels, preds));
validateMetrics.forEach(metric -> addMetric("validate", metric));
}
/** {@inheritDoc} */
@Override
public void resetTrainingMetrics() {
trainingMetrics.forEach(TrainingMetric::reset);
validateMetrics.forEach(TrainingMetric::reset);
if (listener != null) {
listener.onEpoch();
}
}
/** {@inheritDoc} */
@Override
public Loss getLoss() {
return trainingLoss;
}
/** {@inheritDoc} */
@Override
public Loss getValidationLoss() {
return validationLoss;
}
/** {@inheritDoc} */
@Override
public Model getModel() {
return model;
}
/**
* Gets the {@link ai.djl.metric.Metrics} associated with this {@code Trainer}.
*
* @return the {@link ai.djl.metric.Metrics} associated with this {@code Trainer}
*/
public Metrics getMetrics() {
return metrics;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public final <T extends TrainingMetric> T getTrainingMetric(Class<T> clazz) {
for (TrainingMetric metric : trainingMetrics) {
if (clazz.isInstance(metric)) {
return (T) metric;
}
}
return null;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public <T extends TrainingMetric> T getValidationMetric(Class<T> clazz) {
for (TrainingMetric metric : validateMetrics) {
if (clazz.isInstance(metric)) {
return (T) metric;
}
}
return null;
}
/** {@inheritDoc} */
@Override
public NDManager getManager() {
return manager;
}
/**
* Checks if all gradients are zeros. This prevent users from calling step() without running
* {@code backward}.
*/
private void checkGradients() {
List<NDArray> grads = new ArrayList<>();
model.getBlock()
.getParameters()
.values()
.stream()
.filter(Parameter::requireGradient)
.forEach(
param ->
grads.add(
parameterStore.getValue(param, devices[0]).getGradient()));
NDList list = new NDList(grads.stream().map(NDArray::sum).toArray(NDArray[]::new));
NDArray gradSum = NDArrays.stack(list);
list.close();
NDArray array = gradSum.sum();
float[] sums = array.toFloatArray();
array.close();
gradSum.close();
float sum = 0f;
for (float num : sums) {
sum += num;
}
if (sum == 0f) {
throw new IllegalStateException(
"Gradient values are all zeros, please call gradientCollector.backward() on"
+ "your target NDArray (usually loss), before calling step() ");
}
gradientsChecked = true;
}
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
@Override
protected void finalize() throws Throwable {
if (manager.isOpen()) {
if (logger.isDebugEnabled()) {
logger.warn("Model was not closed explicitly: {}", getClass().getSimpleName());
}
close();
}
super.finalize();
}
/** {@inheritDoc} */
@Override
public void close() {
parameterStore.sync();
manager.close();
}
private void addMetric(String metricName, long begin) {
if (metrics != null && begin > 0L) {
metrics.addMetric(metricName, System.nanoTime() - begin);
}
}
private void addMetric(String stage, TrainingMetric metric) {
if (metrics != null) {
metrics.addMetric(stage + '_' + metric.getName(), metric.getValue());
}
}
}
| 32.358127 | 120 | 0.608548 |
94bcbb282f147bcd151daf40602b597e5c1032be | 1,607 | package com.godbearing.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class EnquiryDto {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private int id;
private String name,email,contact,enquiryFor,qty;
@Column(columnDefinition="text")
private String comment;
private boolean read;
private boolean subscriber;
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getEnquiryFor() {
return enquiryFor;
}
public void setEnquiryFor(String enquiryFor) {
this.enquiryFor = enquiryFor;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public boolean isSubscriber() {
return subscriber;
}
public void setSubscriber(boolean subscriber) {
this.subscriber = subscriber;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
}
| 19.130952 | 51 | 0.678283 |
d0b9ca15e5827ef13fc7ca37c46fbd150884111e | 1,286 | package account_credentials;
public class AccountTableDataModel {
private String web_name, web_address, web_user_email, web_password, data_id_col;
public AccountTableDataModel(String web_name, String web_address, String web_user_email,
String web_password, String data_id_col) {
this.web_name = web_name;
this.web_address = web_address;
this.web_user_email = web_user_email;
this.web_password = web_password;
this.data_id_col = data_id_col;
}
public String getWeb_name() { return web_name; }
public void setWeb_name(String web_name) {
this.web_name = web_name;
}
public String getWeb_address() {
return web_address;
}
public void setWeb_address(String web_address) {
this.web_address = web_address;
}
public String getWeb_user_email() {
return web_user_email;
}
public void setWeb_user_email(String web_user_email) {
this.web_user_email = web_user_email;
}
public String getWeb_password() {
return web_password;
}
public void setWeb_password(String web_password) {
this.web_password = web_password;
}
public String getData_id_col() {
return data_id_col;
}
}
| 26.244898 | 92 | 0.669518 |
9e36a1cf3c925bab9e074deb6988dcc05625760e | 562 | package com.wavesplatform.wavesj.info;
import com.wavesplatform.transactions.DataTransaction;
import com.wavesplatform.wavesj.ApplicationStatus;
public class DataTransactionInfo extends TransactionInfo {
public DataTransactionInfo(DataTransaction tx, ApplicationStatus applicationStatus, int height) {
super(tx, applicationStatus, height);
}
public DataTransaction tx() {
return (DataTransaction) super.tx();
}
@Override
public String toString() {
return "DataTransactionInfo{} " + super.toString();
}
}
| 25.545455 | 101 | 0.731317 |
2652c571e5827d234325041e92c10e0fa4ce620d | 306 | package com.xinlin.app.service;
import java.util.List;
import com.xinlin.app.base.BaseService;
import com.xinlin.app.entity.pojo.Role;
import com.xinlin.app.entity.pojo.User;
/**
* 框架demo演示
*
*
* @author jxq
* @date 2013-09-29
*
*/
public interface UserService extends BaseService<User>{
}
| 13.909091 | 55 | 0.712418 |
c955dff1594e102747336a493bee0594958bc523 | 130 | package abstractfactory;
/**
* @author tonyc
*/
public interface Color {
/**
*
* fill
*/
void fill();
}
| 10 | 24 | 0.5 |
52e84bff5adac5bd38b0c463c9396ccec3d73546 | 7,749 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.shrinkwrap.impl.base.importer.tar;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.asset.ByteArrayAsset;
import org.jboss.shrinkwrap.api.importer.ArchiveImportException;
import org.jboss.shrinkwrap.api.importer.StreamImporter;
import org.jboss.shrinkwrap.impl.base.AssignableBase;
import org.jboss.shrinkwrap.impl.base.Validate;
import org.jboss.shrinkwrap.impl.base.io.tar.TarEntry;
import org.jboss.shrinkwrap.impl.base.io.tar.TarInputStream;
/**
* Base of implementations used to import existing TAR files/streams into the given {@link Archive}
*
* @author <a href="mailto:[email protected]">ALR</a>
*/
abstract class TarImporterBase<S extends TarInputStream, I extends StreamImporter<I>> extends
AssignableBase<Archive<?>> implements StreamImporter<I> {
// -------------------------------------------------------------------------------------||
// Class Members ----------------------------------------------------------------------||
// -------------------------------------------------------------------------------------||
/**
* Logger
*/
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(TarImporterBase.class.getName());
// -------------------------------------------------------------------------------------||
// Constructor ------------------------------------------------------------------------||
// -------------------------------------------------------------------------------------||
public TarImporterBase(final Archive<?> archive) {
super(archive);
}
// -------------------------------------------------------------------------------------||
// Contracts --------------------------------------------------------------------------||
// -------------------------------------------------------------------------------------||
/**
* Returns the actual class for this implementation
*/
abstract Class<I> getActualClass();
/**
* Obtains the correct {@link InputStream} wrapper type for the specified raw data input
*
* @param in
* @return
* @throws IOException
*/
abstract S getInputStreamForRawStream(InputStream in) throws IOException;
// -------------------------------------------------------------------------------------||
// Functional Methods -----------------------------------------------------------------||
// -------------------------------------------------------------------------------------||
/**
* Provides covarient return
*/
private I covarientReturn() {
return this.getActualClass().cast(this);
}
// -------------------------------------------------------------------------------------||
// Required Implementations -----------------------------------------------------------||
// -------------------------------------------------------------------------------------||
/**
* {@inheritDoc}
*
* @see org.jboss.shrinkwrap.api.importer.StreamImporter#importFrom(java.io.InputStream)
*/
@Override
public I importFrom(final InputStream stream) throws ArchiveImportException {
Validate.notNull(stream, "Stream must be specified");
final S tarStream;
try {
tarStream = this.getInputStreamForRawStream(stream);
} catch (final RuntimeException re) {
throw new ArchiveImportException("Could not wrap raw input with TAR stream", re);
} catch (final IOException e) {
throw new ArchiveImportException("Could not wrap raw input with TAR stream", e);
}
return this.importFrom(tarStream);
}
/**
* {@inheritDoc}
*
* @see org.jboss.shrinkwrap.api.importer.StreamImporter#importFrom(java.io.InputStream)
*/
private I importFrom(final S stream) throws ArchiveImportException {
Validate.notNull(stream, "Stream must be specified");
try {
TarEntry entry;
while ((entry = stream.getNextEntry()) != null) {
// Get the name
String entryName = entry.getName();
final Archive<?> archive = this.getArchive();
// Handle directories separately
if (entry.isDirectory()) {
archive.addAsDirectory(entryName);
continue;
}
ByteArrayOutputStream output = new ByteArrayOutputStream(8192);
byte[] content = new byte[4096];
int readBytes;
while ((readBytes = stream.read(content, 0, content.length)) != -1) {
output.write(content, 0, readBytes);
}
archive.add(new ByteArrayAsset(output.toByteArray()), entryName);
}
} catch (final RuntimeException re) {
throw new ArchiveImportException("Could not import stream", re);
} catch (IOException e) {
throw new ArchiveImportException("Could not import stream", e);
}
return this.covarientReturn();
}
/**
* {@inheritDoc}
*
* @see org.jboss.shrinkwrap.api.importer.StreamImporter#importFrom(java.lang.Object)
*/
@Override
public I importFrom(final File file) throws ArchiveImportException {
Validate.notNull(file, "File must be specified");
if (!file.exists()) {
throw new IllegalArgumentException("Specified file for import does not exist: " + file);
}
if (file.isDirectory()) {
throw new IllegalArgumentException("Specified file for import is a directory: " + file);
}
final S archive;
try {
archive = this.getInputStreamForFile(file);
} catch (final IOException e) {
throw new ArchiveImportException("Could not read archive file " + file, e);
}
return this.importFrom(archive);
}
// -------------------------------------------------------------------------------------||
// Internal Helper Methods ------------------------------------------------------------||
// -------------------------------------------------------------------------------------||
/**
* Obtains an implementation-specific stream to the specified {@link File}
*
* @param file
* To open a stream to, must be specified
* @return
* @throws IOException
* If there was a problem getting an instream to the file
*/
private S getInputStreamForFile(File file) throws IOException {
assert file != null : "File must be specified";
return this.getInputStreamForRawStream(new FileInputStream(file));
}
} | 40.150259 | 100 | 0.519422 |
b2d3d6349cc4f1c87cc24984b5bd26a44ec916e0 | 280 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.implementation.serializer.jsonwrapper.api;
public enum Config {
FAIL_ON_UNKNOWN_PROPERTIES,
FAIL_ON_NULL_FOR_PRIMITIVES,
FAIL_ON_NUMBERS_FOR_ENUM
}
| 28 | 65 | 0.796429 |
852150e5891cd66a2aaf5fc008cb0c759c44c234 | 10,052 | /*
* Copyright 2019-2022 Jörg Steffen, Bernd Kiefer
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package de.dfki.lt.loot.fsa.algo;
import java.util.BitSet;
import java.util.Comparator;
import java.util.TreeSet;
import de.dfki.lt.loot.digraph.Edge;
import de.dfki.lt.loot.fsa.AbstractAutomaton;
import de.dfki.lt.loot.digraph.Graph;
public class MinimizationBrzowski {
/**
* This propagates a non-equivalence between two nodes (identified by their
* given indices in the given array) in the given matrix.
*
* @param nodes an array of <code>Vertex</code>s
* @param i an <code>int</code> with the index of the first node
* @param j an <code>int</code> with the index of the second node
* @param equivalent a <code>boolean</code> matrix that contains a
* <code>false</code> at matrix[i][j] (if i > j; vice versa otherwise)
*/
private static <EdgeInfo> void propagate(AbstractAutomaton<EdgeInfo> graph,
Graph<EdgeInfo> converse,
Comparator<EdgeInfo> comp, int i, int j, BitSet notEquivalent) {
int nodesLength = graph.getNumberOfVertices();
if (converse.getOutEdges(i) == null || converse.getOutEdges(j) == null) return;
// iterate over incoming edges of node i
for (Edge<EdgeInfo> iEdge : converse.getOutEdges(i)) {
// get transition char
EdgeInfo iTrans = iEdge.getInfo();
// get start node
int iStartVertex = iEdge.getSource();
// search for incoming edges of node j with the same transition char
for (Edge<EdgeInfo> jEdge : converse.getOutEdges(j)) {
// get transition char
EdgeInfo jTrans = jEdge.getInfo();
// we can skip the incoming edges with smaller edge info
int compResult = comp.compare(jTrans, iTrans);
// if (compResult < 0) { continue; }
if (compResult == 0) {
// get start node
int jStartVertex = jEdge.getSource();
// switch start node indices, so that iStartVertex always contains the
// larger index; required because we use a LOWER triangular matrix
if (iStartVertex < jStartVertex) {
int temp = iStartVertex;
iStartVertex = jStartVertex;
jStartVertex = temp;
}
// check if the start nodes are marked as equivalen; if yes, mark them
// as non-equivalent and propagate the change
int index = jStartVertex * nodesLength + iStartVertex;
if (! notEquivalent.get(index)) {
notEquivalent.set(index);
propagate(graph, converse, comp,
iStartVertex, jStartVertex, notEquivalent);
}
continue;
}
// when we're here, this means that jTrans > iTrans; we can then stop
// searching since the edges are sorted
// break;
}
}
}
/**
* This checks if two edge lists are "equal", i.e., have the same length and
* the same defined/undefined transitions.
*
* Since the lists are sorted, we only have to traverse them in parallel.
*
* @param edgeList1 a <code>List</code> with edges
* @param edgeList2 a <code>List</code> with edges
* @return a <code>boolean</code> indicating if the edge lists are equals
*/
private static <EdgeInfo> boolean equalEdgesByLabel(
Comparator<EdgeInfo> comp,
Iterable<Edge<EdgeInfo>> edgeList1,
Iterable<Edge<EdgeInfo>> edgeList2) {
TreeSet<EdgeInfo> edges1 = new TreeSet<EdgeInfo>(comp);
for (Edge<EdgeInfo> edge : edgeList1) {
edges1.add(edge.getInfo());
}
for (Edge<EdgeInfo> edge : edgeList2) {
if (! edges1.remove(edge.getInfo())) return false;
}
// no mismatch found, so the lists are equal
return edges1.isEmpty();
}
/**
* This computes the equvalent classes from the given nodes.
*
* @param nodes an array of <code>Vertex</code>s
* @return an array of <code>int</code>s that contains the node number of the
* equivalence class representative for each node; if representative[i] == i,
* node i is one of the representatives; if representative[i] == j, then node
* j is the representative of the equivalence class i belongs to
*/
private static <EdgeInfo> int[] computeEquivalentVertices(
AbstractAutomaton<EdgeInfo> graph, Comparator<EdgeInfo> comp) {
int nodesLength = graph.getNumberOfVertices();
BitSet notEquivalent = new BitSet(nodesLength * nodesLength);
Graph<EdgeInfo> converse = graph.converseLazy();
// check pairs of nodes for equivalence: they are not equivalent if:
// - one of them is a final node and the other is not
// - they have different outgoing edges
for (int i = 0; i < nodesLength; i++) {
if (graph.isVertex(i)) {
// we can skip the case j == i since each node is obviously equivalent
// with itself
for (int j = 0; j < i; j++) {
if (graph.isVertex(j)) {
if (graph.isFinalState(i) != graph.isFinalState(j) ||
! equalEdgesByLabel(comp, graph.getOutEdges(i), graph.getOutEdges(j))){
// nodes are not equivalent
notEquivalent.set(j * nodesLength + i);
// propagate the new found states difference through the rest of the
// graph
propagate(graph, converse, comp, i, j, notEquivalent);
}
}
}
}
}
/*
// print matrix
System.out.print(" ");
for (int i = 0; i < nodes.length; i++) {
System.out.format("%-3d", i);
}
System.out.println();
for (int i = 0; i < nodes.length; i++) {
System.out.format("%-3d", i);
for (int j = 0; j <= i ; j++) {
System.out.print(! notEquivalent.get(j * nodes.length + i) ? "X ": "O ");
}
System.out.println();
}
*/
// from the matrix, compute the representatives for each node:
// this is the minimal node with which it is equivalent
int[] representative = new int[nodesLength];
representative[0] = 0;
for (int i = 0; i < nodesLength; i++) {
if (graph.isVertex(i)) {
int j = 0;
while (j <= i
&& graph.isVertex(j)
&& notEquivalent.get(j * nodesLength + i)) {
j++ ;
}
representative[i] = j;
}
}
/*
// print representatives
System.out.println();
for (int i = 0; i< nodes.length; i++) {
System.out.print(representative[i] + " ");
}
System.out.println();
*/
return representative;
}
/**
* This checks if two edge lists are "equal", i.e., have the same length and
* the same defined/undefined transitions.
*
* Since the lists are sorted, we only have to traverse them in parallel.
*
* @param edgeList1 a <code>List</code> with edges
* @param edgeList2 a <code>List</code> with edges
* @return a <code>boolean</code> indicating if the edge lists are equals
*
* requires edge list sorting, which is why it is not used at the moment.
private boolean
equalEdges(List<Edge<EdgeInfo>> edgeList1, List<Edge<EdgeInfo>> edgeList2) {
// if the lists differ in size, we are already finished
if (edgeList1 == null || edgeList2 == null) {
return (edgeList1 == edgeList2);
} else {
if (edgeList1.size() != edgeList2.size()) {
return false;
}
}
// iterate in parallel over both lists
Iterator<Edge<EdgeInfo>> edgeIter2 = edgeList2.iterator();
for (Edge<EdgeInfo> edge1 : edgeList1) {
// return false when the first mismatch is found
if (edge1.getEdgeInfo() != edgeIter2.next().getEdgeInfo()){
return false;
}
}
// no mismatch found, so the lists are equal
return true;
}
*/
/**
* This sorts the node's edges according to their transition character
* requires edge containers to be lists, which is why it is not used
* currently.
private static <EdgeInfo> void sortEdges(final AbstractAutomaton<EdgeInfo> graph) {
// renumber nodes and sort all edge lists according to the transition
// character
Comparator<Edge<EdgeInfo>> edgeComp = new Comparator<Edge<EdgeInfo>>() {
public int compare(Edge<EdgeInfo> edge1, Edge<EdgeInfo> edge2) {
return graph.compare(edge1.getInfo(), edge2.getInfo());
}
};
for (int i = 0, iMax = graph.getNumberOfVertices(); i < iMax; ++i) {
if (graph.isVertex(i)) {
// sort the edge lists
if (! graph.getInEdges(i).isEmpty()) {
Collections.sort(graph.getInEdges(i), edgeComp);
}
if (! graph.getOutEdges(i).isEmpty()) {
Collections.sort(graph.getOutEdges(i), edgeComp);
}
}
}
}
*/
/**
* This computes the minimal automaton equivalent to this one.
*
* The current automaton is turned destructively into its minimal
* counterpart. Only use this method on a determinized automaton, which can
* be created with {@link #determinize()}.
*/
public static <EdgeInfo> void minimize(
AbstractAutomaton<EdgeInfo> graph, Comparator<EdgeInfo> comp) {
// sort edges
//sortEdges(graph);
// this array will hold the node number of the equivalence class
// representative for each node; if representative[i] == i, node i is one
// of the representatives; if representative[i] == j, then node j is the
// representative of the equivalence class i belongs to
int[] representative = computeEquivalentVertices(graph, comp);
Minimization.reduceAutomaton(graph, representative, comp);
}
}
| 34.542955 | 87 | 0.633804 |
32dd19678eb460bfd2d9073e16d7e3d977263801 | 1,860 | /*
* $Id: TestUtil.java,v 1.1 2000/05/06 00:00:53 boisvert Exp $
*
* Unit test utilities.
*
* Simple db toolkit.
* Copyright (C) 1999, 2000 Cees de Groot <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
package jdbm.recman;
/**
* This class contains some test utilities.
*/
public class TestUtil {
/**
* Creates a "record" containing "length" repetitions of the
* indicated byte.
*/
public static byte[] makeRecord(int length, byte b) {
byte[] retval = new byte[length];
for (int i = 0; i < length; i++)
retval[i] = b;
return retval;
}
/**
* Checks whether the record has the indicated length and data
*/
public static boolean checkRecord(byte[] data, int length, byte b) {
if (data.length != length) {
System.err.println("length doesn't match: expected "
+ length + ", got " + data.length);
return false;
}
for (int i = 0; i < length; i++)
if (data[i] != b) {
System.err.println("byte " + i + " wrong: expected "
+ b + ", got " + data[i]);
return false;
}
return true;
}
}
| 30.491803 | 78 | 0.635484 |
046b2bb4d1c332620d93ac5744eef02817295685 | 360 | package android.support.p000v4.widget;
import android.view.animation.Interpolator;
/* renamed from: android.support.v4.widget.F */
/* compiled from: ViewDragHelper */
class C0675F implements Interpolator {
C0675F() {
}
public float getInterpolation(float t) {
float t2 = t - 1.0f;
return (t2 * t2 * t2 * t2 * t2) + 1.0f;
}
}
| 22.5 | 47 | 0.647222 |
760e964bf1740e8c2cd5f996620770869e6dd2d3 | 8,650 | /*
Copyright 2014 Paul LeBeau, Cave Rock Software Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.scwang.smartrefreshlayout.internal.pathview;
/**
* Parse a SVG 'number' or a CSS 'number' from a String.
*
* We use our own parser because the one in Android (from Harmony I think) is slow.
*
* An SVG 'number' is defined as
* integer ([Ee] integer)?
* | [+-]? [0-9]* "." [0-9]+ ([Ee] integer)?
* Where 'integer' is
* [+-]? [0-9]+
* CSS numbers were different, but have now been updated to a compatible definition (see 2.1 Errata)
* [+-]?([0-9]+|[0-9]*\.[0-9]+)(e[+-]?[0-9]+)?
*
*/
public class NumberParser
{
int pos;
static long TOO_BIG = Long.MAX_VALUE / 10;
/*
* Return the value of pos after the parse.
*/
public int getEndPos()
{
return this.pos;
}
/*
* Scan the string for an SVG number.
*/
public float parseNumber(String str)
{
return parseNumber(str, 0, str.length());
}
/*
* Scan the string for an SVG number.
* Assumes maxPos will not be greater than str.length().
*/
public float parseNumber(String input, int startpos, int len)
{
boolean isNegative = false;
long significand = 0;
int numDigits = 0;
int numLeadingZeroes = 0;
int numTrailingZeroes = 0;
boolean decimalSeen = false;
int sigStart = 0;
int decimalPos = 0;
int exponent = 0;
pos = startpos;
if (pos >= len)
return Float.NaN; // String is empty - no number found
char ch = input.charAt(pos);
switch (ch) {
case '-': isNegative = true;
// fall through
case '+': pos++;
}
sigStart = pos;
while (pos < len)
{
ch = input.charAt(pos);
if (ch == '0')
{
if (numDigits == 0) {
numLeadingZeroes++;
} else {
// We potentially skip trailing zeroes. Keep count for now.
numTrailingZeroes++;
}
}
else if (ch >= '1' && ch <= '9')
{
// Multiply any skipped zeroes into buffer
numDigits += numTrailingZeroes;
while (numTrailingZeroes > 0) {
if (significand > TOO_BIG) {
//Log.e("Number is too large");
return Float.NaN;
}
significand *= 10;
numTrailingZeroes--;
}
if (significand > TOO_BIG) {
// We will overflow if we continue...
//Log.e("Number is too large");
return Float.NaN;
}
significand = significand * 10 + ((int)ch - (int)'0');
numDigits++;
if (significand < 0)
return Float.NaN; // overflowed from +ve to -ve
}
else if (ch == '.')
{
if (decimalSeen) {
// Stop parsing here. We may be looking at a new number.
break;
}
decimalPos = pos - sigStart;
decimalSeen = true;
}
else
break;
pos++;
}
if (decimalSeen && pos == (decimalPos + 1)) {
// No digits following decimal point (eg. "1.")
//Log.e("Missing fraction part of number");
return Float.NaN;
}
// Have we seen anything number-ish at all so far?
if (numDigits == 0) {
if (numLeadingZeroes == 0) {
//Log.e("Number not found");
return Float.NaN;
}
// Leading zeroes have been seen though, so we
// treat that as a '0'.
numDigits = 1;
}
if (decimalSeen) {
exponent = decimalPos - numLeadingZeroes - numDigits;
} else {
exponent = numTrailingZeroes;
}
// Now look for exponent
if (pos < len)
{
ch = input.charAt(pos);
if (ch == 'E' || ch == 'e')
{
boolean expIsNegative = false;
int expVal = 0;
boolean abortExponent = false;
pos++;
if (pos == len) {
// Incomplete exponent.
//Log.e("Incomplete exponent of number");
return Float.NaN;
}
switch (input.charAt(pos)) {
case '-': expIsNegative = true;
// fall through
case '+': pos++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break; // acceptable next char
default:
// any other character is a failure, ie no exponent.
// Could be something legal like "em" though.
abortExponent = true;
pos--; // reset pos to position of 'E'/'e'
}
if (!abortExponent)
{
int expStart = pos;
while (pos < len)
{
ch = input.charAt(pos);
if (ch >= '0' && ch <= '9')
{
if (expVal > TOO_BIG) {
// We will overflow if we continue...
//Log.e("Exponent of number is too large");
return Float.NaN;
}
expVal = expVal * 10 + ((int)ch - (int)'0');
pos++;
}
else
break;
}
// Check that at least some exponent digits were read
if (pos == expStart) {
//Log.e(""Incomplete exponent of number"");
return Float.NaN;
}
if (expIsNegative)
exponent -= expVal;
else
exponent += expVal;
}
}
}
// Quick check to eliminate huge exponents.
// Biggest float is (2 - 2^23) . 2^127 ~== 3.4e38
// Biggest negative float is 2^-149 ~== 1.4e-45
// Some numbers that will overflow will get through the scan
// and be returned as 'valid', yet fail when value() is called.
// However they will be very rare and not worth slowing down
// the parse for.
if ((exponent + numDigits) > 39 || (exponent + numDigits) < -44)
return Float.NaN;
float f = (float) significand;
if (significand != 0)
{
// Do exponents > 0
if (exponent > 0)
{
f *= positivePowersOf10[exponent];
}
else if (exponent < 0)
{
// Some valid numbers can have an exponent greater than the max (ie. < -38)
// for a float. For example, significand=123, exponent=-40
// If that's the case, we need to apply the exponent in two steps.
if (exponent < -38) {
// Long.MAX_VALUE is 19 digits, so taking 20 off the exponent should be enough.
f *= 1e-20;
exponent += 20;
}
// Do exponents < 0
f *= negativePowersOf10[-exponent];
}
}
return (isNegative) ? -f : f;
}
private static final float positivePowersOf10[] = {
1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f, 1e8f, 1e9f,
1e10f, 1e11f, 1e12f, 1e13f, 1e14f, 1e15f, 1e16f, 1e17f, 1e18f, 1e19f,
1e20f, 1e21f, 1e22f, 1e23f, 1e24f, 1e25f, 1e26f, 1e27f, 1e28f, 1e29f,
1e30f, 1e31f, 1e32f, 1e33f, 1e34f, 1e35f, 1e36f, 1e37f, 1e38f
};
private static final float negativePowersOf10[] = {
1e0f, 1e-1f, 1e-2f, 1e-3f, 1e-4f, 1e-5f, 1e-6f, 1e-7f, 1e-8f, 1e-9f,
1e-10f, 1e-11f, 1e-12f, 1e-13f, 1e-14f, 1e-15f, 1e-16f, 1e-17f, 1e-18f, 1e-19f,
1e-20f, 1e-21f, 1e-22f, 1e-23f, 1e-24f, 1e-25f, 1e-26f, 1e-27f, 1e-28f, 1e-29f,
1e-30f, 1e-31f, 1e-32f, 1e-33f, 1e-34f, 1e-35f, 1e-36f, 1e-37f, 1e-38f
};
}
| 30.782918 | 100 | 0.488786 |
3ec4298f0d4ca9636904b41ccfbe83c5f29a7e4c | 1,369 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.tcp;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.geode.internal.Version;
/**
* A message reader which reads from the socket using the old io.
*
*/
public class OioMsgReader extends MsgReader {
public OioMsgReader(Connection conn, Version version) {
super(conn, version);
}
@Override
public ByteBuffer readAtLeast(int bytes) throws IOException {
byte[] buffer = new byte[bytes];
conn.readFully(conn.getSocket().getInputStream(), buffer, bytes);
return ByteBuffer.wrap(buffer);
}
}
| 34.225 | 100 | 0.752374 |
0db15c7fca3578d1b7d602103981e7ebab3f8110 | 4,205 | package org.enguage.objects;
import java.util.ListIterator;
import org.enguage.objects.space.Overlay;
import org.enguage.objects.space.Value;
import org.enguage.util.Audit;
import org.enguage.util.Strings;
import org.enguage.util.attr.Attribute;
import org.enguage.util.sys.Fs;
import org.enguage.util.sys.Shell;
import org.enguage.vehicle.number.Number;
public class Numeric extends Value {
public static final String NAME = "numeric";
static public final int id = 176168105; //Strings.hash( NAME );
static private Audit audit = new Audit( "Numeric" );
public Numeric( String e, String a ) { super( e, a ); }
public void set( Float val ) {
Fs.stringToFile(
name( ent, attr, Overlay.MODE_WRITE ),
Float.toString( val ));
}
public Float get( Float def ) {
Float val = def;
try {
val = Float.valueOf(
Fs.stringFromFile( name( ent, attr, Overlay.MODE_READ ))
);
} catch (Exception e) {
set( def ); // set a default
}
return val;
}
public boolean increase( String value ) {
boolean rc = true;
Float v = get( 0f );
if (Float.isNaN( v )) {
rc = false;
audit.ERROR("Numeric.increase(): NaN found in "+ ent +"/"+ attr );
} else {
v += Float.valueOf( value );
set( v );
}
return rc;
}
public boolean decrease( String value ) {
boolean rc = true;
Float v = get( 0f );
if (Float.isNaN( v )) {
rc = false;
audit.ERROR("Numeric.decrease(): NaN found in "+ ent +"/"+ attr );
} else {
v -= Float.valueOf( value );
set( v );
}
return rc;
}
static private String deref( String s ){
try {
s = Number.floatToString( Float.parseFloat( s ));
} catch ( Exception e ) {
if (s.equals( "-" )) s = "minus";
else if (s.equals( "+" )) s = "plus";
else if (s.equals( "*" )) s = "times";
else if (s.equals( "/" )) s = "divided by";
} // otherwise fail silently!
return s;
}
static public Strings deref( Strings sa ){
ListIterator<String> i = sa.listIterator();
while (i.hasNext())
i.set( deref( i.next()));
return sa;
}
static private String usage( Strings a ) {
System.out.println(
"Usage: numeric [set|get|remove|increase|decrease|exists|equals|delete] <ent> <attr>[ / <attr> ...] [<values>...]\n"+
"given: "+ a.toString( Strings.CSV ));
return Shell.FAIL;
}
static public Strings interpret( Strings a ) {
// interpret( ["increase", "device", "textSize", "4"] )
audit.in( "interpret", a.toString( Strings.DQCSV ));
String rc = Shell.SUCCESS;
if (a.size() > 1) {
String cmd = a.get( 0 );
if (cmd.equals("isAbs")) { // => Numeric.java?
char firstChar = a.get( 1 ).charAt( 0 );
rc = firstChar == '-' || firstChar == '+' ? Shell.FAIL : Shell.SUCCESS;
} else if (cmd.equals( "evaluate" )) {
// parameters no longer expanded in sofa...!
int i = 0;
for (String s : a) {
if (Attribute.isAttribute( s ))
a.set( i, new Attribute( s ).value()) ;
i++;
}
ListIterator<String> ai = a.normalise().listIterator();
if (ai.hasNext()) {
ai.next(); // read over command
Number number = new Number( ai );
rc = number.valueOf() + a.copyAfter( 1 + number.representamen().size()).toString();
} else
rc = Shell.FAIL;
} else if (a.size() > 2) {
int i = 2;
String entity = a.get( 1 ), attribute = null;
if (i<a.size()) { // components? martin car / body / paint / colour red
attribute = a.get( i );
while (++i < a.size() && a.get( i ).equals( "/" ))
attribute += ( "/"+ a.get( i ));
}
Numeric n = new Numeric( entity, attribute );
// [ "4", "+", "3" ] => [ "7" ] ???? at some point!
ListIterator<String> ai = a.listIterator();
String value = new Number( ai ).valueOf().toString(); /* <<<< this could
* have "another", coz it has context. In practice, this is a single figure for
* increase or decrease.
*/
if (cmd.equals( "increase" ))
rc = n.increase( value ) ? Shell.SUCCESS : Shell.FAIL;
else if (cmd.equals( "decrease" ))
rc = n.decrease( value ) ? Shell.SUCCESS : Shell.FAIL;
else
rc = usage( a );
}
} else
rc = usage( a );
audit.out( rc );
return new Strings( rc );
} } | 30.251799 | 121 | 0.59025 |
8811a27173683032fb2fa16a66a44be6fb2fca31 | 470 | package tech.yiyehu.framework.common.annotation;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
/**
* 标记要统计的被调用方法
*
* @author yiyehu
* @version 创建时间:2018/8/1 13:52
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CountApi {
/**
* @return name 统计的名称
*/
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
}
| 16.785714 | 52 | 0.676596 |
8840893531e5daa83b142ed486ce71d2cf19199a | 40,625 | /*
* Copyright (c) 2009-2011, 2014 AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package org.alljoyn.bus;
import org.alljoyn.bus.BusException;
import org.alljoyn.bus.Variant;
import org.alljoyn.bus.annotation.BusInterface;
import org.alljoyn.bus.annotation.BusMethod;
import org.alljoyn.bus.annotation.BusProperty;
import org.alljoyn.bus.annotation.Signature;
import org.alljoyn.bus.annotation.Position;
import java.util.Map;
import java.util.TreeMap;
import java.util.Arrays;
@BusInterface
public interface AnnotatedTypesInterface {
public class InnerStruct {
@Position(0)
@Signature("i")
public int i;
public InnerStruct() { i = 0; }
public InnerStruct(int i) { this.i = i; }
public boolean equals(Object obj) { return i == ((InnerStruct)obj).i; }
}
public class Struct {
@Position(0)
@Signature("y")
public byte y;
@Position(1)
@Signature("b")
public boolean b;
@Position(2)
@Signature("n")
public short n;
@Position(3)
@Signature("q")
public short q;
@Position(4)
@Signature("i")
public int i;
@Position(5)
@Signature("u")
public int u;
@Position(6)
@Signature("x")
public long x;
@Position(7)
@Signature("t")
public long t;
@Position(8)
@Signature("d")
public double d;
@Position(9)
@Signature("s")
public String s;
@Position(10)
@Signature("o")
public String o;
@Position(11)
@Signature("g")
public String g;
@Position(12)
@Signature("ay")
public byte[] ay;
@Position(13)
@Signature("ab")
public boolean[] ab;
@Position(14)
@Signature("an")
public short[] an;
@Position(15)
@Signature("aq")
public short[] aq;
@Position(16)
@Signature("ai")
public int[] ai;
@Position(17)
@Signature("au")
public int[] au;
@Position(18)
@Signature("ax")
public long[] ax;
@Position(19)
@Signature("at")
public long[] at;
@Position(20)
@Signature("ad")
public double[] ad;
@Position(21)
@Signature("as")
public String[] as;
@Position(22)
@Signature("ao")
public String[] ao;
@Position(23)
@Signature("ag")
public String[] ag;
@Position(24)
@Signature("r")
public InnerStruct r;
@Position(25)
@Signature("a{ss}")
public TreeMap<String, String> ae;
@Position(26)
@Signature("v")
public Variant v;
public Struct() {}
public Struct(byte y, boolean b, short n, short q, int i, int u, long x, long t, double d,
String s, String o, String g, byte[] ay, boolean[] ab, short[] an, short[] aq,
int[] ai, int[] au, long[] ax, long[] at, double[] ad, String[] as, String[] ao,
String[] ag, InnerStruct r, Variant v, TreeMap<String, String> ae) {
this.y = y;
this.b = b;
this.n = n;
this.q = q;
this.i = i;
this.u = u;
this.x = x;
this.t = t;
this.d = d;
this.s = s;
this.o = o;
this.g = g;
this.ay = ay;
this.ab = ab;
this.an = an;
this.aq = aq;
this.ai = ai;
this.au = au;
this.ax = ax;
this.at = at;
this.ad = ad;
this.as = as;
this.ao = ao;
this.ag = ag;
this.r = r;
this.v = v;
this.ae = ae;
}
public boolean equals(Object obj) {
Struct struct = (Struct)obj;
return
y == struct.y &&
b == struct.b &&
n == struct.n &&
q == struct.q &&
i == struct.i &&
u == struct.u &&
x == struct.x &&
t == struct.t &&
d == struct.d &&
s.equals(struct.s) &&
o.equals(struct.o) &&
g.equals(struct.g) &&
Arrays.equals(ay, struct.ay) &&
Arrays.equals(ab, struct.ab) &&
Arrays.equals(an, struct.an) &&
Arrays.equals(aq, struct.aq) &&
Arrays.equals(ai, struct.ai) &&
Arrays.equals(au, struct.au) &&
Arrays.equals(ax, struct.ax) &&
Arrays.equals(at, struct.at) &&
Arrays.equals(ad, struct.ad) &&
Arrays.equals(as, struct.as) &&
Arrays.equals(ao, struct.ao) &&
Arrays.equals(ag, struct.ag) &&
r.equals(struct.r) &&
v.equals(struct.v) &&
ae.equals(struct.ae);
}
}
@BusMethod(signature="", replySignature="")
public void Void() throws BusException;
@BusMethod(signature="y", replySignature="y")
public byte Byte(byte y) throws BusException;
@BusMethod(signature="b", replySignature="b")
public boolean Boolean(boolean b) throws BusException;
@BusMethod(signature="n", replySignature="n")
public short Int16(short n) throws BusException;
@BusMethod(signature="q", replySignature="q")
public short Uint16(short q) throws BusException;
@BusMethod(signature="i", replySignature="i")
public int Int32(int i) throws BusException;
@BusMethod(signature="u", replySignature="u")
public int Uint32(int u) throws BusException;
@BusMethod(signature="x", replySignature="x")
public long Int64(long x) throws BusException;
@BusMethod(signature="t", replySignature="t")
public long Uint64(long t) throws BusException;
@BusMethod(signature="d", replySignature="d")
public double Double(double d) throws BusException;
@BusMethod(signature="s", replySignature="s")
public String String(String s) throws BusException;
@BusMethod(signature="o", replySignature="o")
public String ObjectPath(String o) throws BusException;
@BusMethod(signature="g", replySignature="g")
public String Signature(String g) throws BusException;
@BusMethod(signature="aa{ss}", replySignature="aa{ss}")
public Map<String, String>[] DictionaryArray(Map<String, String>[] aaess) throws BusException;
@BusMethod(name="StructArray", signature="ar", replySignature="ar")
public InnerStruct[] AnnotatedStructArray(InnerStruct[] ar) throws BusException;
@BusMethod(signature="ad", replySignature="ad")
public double[] DoubleArray(double[] ad) throws BusException;
@BusMethod(signature="ax", replySignature="ax")
public long[] Int64Array(long[] ax) throws BusException;
@BusMethod(signature="ay", replySignature="ay")
public byte[] ByteArray(byte[] ay) throws BusException;
@BusMethod(signature="au", replySignature="au")
public int[] Uint32Array(int[] au) throws BusException;
@BusMethod(signature="ag", replySignature="ag")
public String[] SignatureArray(String[] ag) throws BusException;
@BusMethod(signature="ai", replySignature="ai")
public int[] Int32Array(int[] ai) throws BusException;
@BusMethod(signature="at", replySignature="at")
public long[] Uint64Array(long[] at) throws BusException;
@BusMethod(signature="an", replySignature="an")
public short[] Int16Array(short[] an) throws BusException;
@BusMethod(signature="av", replySignature="av")
public Variant[] VariantArray(Variant[] av) throws BusException;
@BusMethod(signature="as", replySignature="as")
public String[] StringArray(String[] as) throws BusException;
@BusMethod(signature="aay", replySignature="aay")
public byte[][] ArrayArray(byte[][] aay) throws BusException;
@BusMethod(signature="aq", replySignature="aq")
public short[] Uint16Array(short[] aq) throws BusException;
@BusMethod(signature="ab", replySignature="ab")
public boolean[] BooleanArray(boolean[] ab) throws BusException;
@BusMethod(signature="ab", replySignature="ab")
public Boolean[] CapitalBooleanArray(Boolean[] aB) throws BusException;
@BusMethod(signature="ao", replySignature="ao")
public String[] ObjectPathArray(String[] ao) throws BusException;
@BusMethod(name="Struct", signature="r", replySignature="r")
public Struct AnnotatedStruct(Struct r) throws BusException;
@BusMethod(signature="v", replySignature="v")
public Variant Variant(Variant v) throws BusException;
@BusMethod(signature="a{na{ss}}", replySignature="a{na{ss}}")
public Map<Short, Map<String, String>> DictionaryNAESS(Map<Short, Map<String, String>> aenaess) throws BusException;
@BusMethod(name="DictionaryNR", signature="a{nr}", replySignature="a{nr}")
public Map<Short, AnnotatedTypesInterface.InnerStruct> AnnotatedDictionaryNR(Map<Short, AnnotatedTypesInterface.InnerStruct> aenr) throws BusException;
@BusMethod(signature="a{nd}", replySignature="a{nd}")
public Map<Short, Double> DictionaryND(Map<Short, Double> aend) throws BusException;
@BusMethod(signature="a{nx}", replySignature="a{nx}")
public Map<Short, Long> DictionaryNX(Map<Short, Long> aenx) throws BusException;
@BusMethod(signature="a{ny}", replySignature="a{ny}")
public Map<Short, Byte> DictionaryNY(Map<Short, Byte> aeny) throws BusException;
@BusMethod(signature="a{nu}", replySignature="a{nu}")
public Map<Short, Integer> DictionaryNU(Map<Short, Integer> aenu) throws BusException;
@BusMethod(signature="a{ng}", replySignature="a{ng}")
public Map<Short, String> DictionaryNG(Map<Short, String> aeng) throws BusException;
@BusMethod(signature="a{ni}", replySignature="a{ni}")
public Map<Short, Integer> DictionaryNI(Map<Short, Integer> aeni) throws BusException;
@BusMethod(signature="a{nt}", replySignature="a{nt}")
public Map<Short, Long> DictionaryNT(Map<Short, Long> aent) throws BusException;
@BusMethod(signature="a{nn}", replySignature="a{nn}")
public Map<Short, Short> DictionaryNN(Map<Short, Short> aenn) throws BusException;
@BusMethod(signature="a{nv}", replySignature="a{nv}")
public Map<Short, Variant> DictionaryNV(Map<Short, Variant> aenv) throws BusException;
@BusMethod(signature="a{ns}", replySignature="a{ns}")
public Map<Short, String> DictionaryNS(Map<Short, String> aens) throws BusException;
@BusMethod(signature="a{nay}", replySignature="a{nay}")
public Map<Short, byte[]> DictionaryNAY(Map<Short, byte[]> aenay) throws BusException;
@BusMethod(signature="a{nq}", replySignature="a{nq}")
public Map<Short, Short> DictionaryNQ(Map<Short, Short> aenq) throws BusException;
@BusMethod(signature="a{nb}", replySignature="a{nb}")
public Map<Short, Boolean> DictionaryNB(Map<Short, Boolean> aenb) throws BusException;
@BusMethod(signature="a{no}", replySignature="a{no}")
public Map<Short, String> DictionaryNO(Map<Short, String> aeno) throws BusException;
@BusMethod(signature="a{da{ss}}", replySignature="a{da{ss}}")
public Map<Double, Map<String, String>> DictionaryDAESS(Map<Double, Map<String, String>> aedaess) throws BusException;
@BusMethod(name="DictionaryDR", signature="a{dr}", replySignature="a{dr}")
public Map<Double, AnnotatedTypesInterface.InnerStruct> AnnotatedDictionaryDR(Map<Double, AnnotatedTypesInterface.InnerStruct> aedr) throws BusException;
@BusMethod(signature="a{dd}", replySignature="a{dd}")
public Map<Double, Double> DictionaryDD(Map<Double, Double> aedd) throws BusException;
@BusMethod(signature="a{dx}", replySignature="a{dx}")
public Map<Double, Long> DictionaryDX(Map<Double, Long> aedx) throws BusException;
@BusMethod(signature="a{dy}", replySignature="a{dy}")
public Map<Double, Byte> DictionaryDY(Map<Double, Byte> aedy) throws BusException;
@BusMethod(signature="a{du}", replySignature="a{du}")
public Map<Double, Integer> DictionaryDU(Map<Double, Integer> aedu) throws BusException;
@BusMethod(signature="a{dg}", replySignature="a{dg}")
public Map<Double, String> DictionaryDG(Map<Double, String> aedg) throws BusException;
@BusMethod(signature="a{di}", replySignature="a{di}")
public Map<Double, Integer> DictionaryDI(Map<Double, Integer> aedi) throws BusException;
@BusMethod(signature="a{dt}", replySignature="a{dt}")
public Map<Double, Long> DictionaryDT(Map<Double, Long> aedt) throws BusException;
@BusMethod(signature="a{dn}", replySignature="a{dn}")
public Map<Double, Short> DictionaryDN(Map<Double, Short> aedn) throws BusException;
@BusMethod(signature="a{dv}", replySignature="a{dv}")
public Map<Double, Variant> DictionaryDV(Map<Double, Variant> aedv) throws BusException;
@BusMethod(signature="a{ds}", replySignature="a{ds}")
public Map<Double, String> DictionaryDS(Map<Double, String> aeds) throws BusException;
@BusMethod(signature="a{day}", replySignature="a{day}")
public Map<Double, byte[]> DictionaryDAY(Map<Double, byte[]> aeday) throws BusException;
@BusMethod(signature="a{dq}", replySignature="a{dq}")
public Map<Double, Short> DictionaryDQ(Map<Double, Short> aedq) throws BusException;
@BusMethod(signature="a{db}", replySignature="a{db}")
public Map<Double, Boolean> DictionaryDB(Map<Double, Boolean> aedb) throws BusException;
@BusMethod(signature="a{do}", replySignature="a{do}")
public Map<Double, String> DictionaryDO(Map<Double, String> aedo) throws BusException;
@BusMethod(signature="a{xa{ss}}", replySignature="a{xa{ss}}")
public Map<Long, Map<String, String>> DictionaryXAESS(Map<Long, Map<String, String>> aexaess) throws BusException;
@BusMethod(name="DictionaryXR", signature="a{xr}", replySignature="a{xr}")
public Map<Long, AnnotatedTypesInterface.InnerStruct> AnnotatedDictionaryXR(Map<Long, AnnotatedTypesInterface.InnerStruct> aexr) throws BusException;
@BusMethod(signature="a{xd}", replySignature="a{xd}")
public Map<Long, Double> DictionaryXD(Map<Long, Double> aexd) throws BusException;
@BusMethod(signature="a{xx}", replySignature="a{xx}")
public Map<Long, Long> DictionaryXX(Map<Long, Long> aexx) throws BusException;
@BusMethod(signature="a{xy}", replySignature="a{xy}")
public Map<Long, Byte> DictionaryXY(Map<Long, Byte> aexy) throws BusException;
@BusMethod(signature="a{xu}", replySignature="a{xu}")
public Map<Long, Integer> DictionaryXU(Map<Long, Integer> aexu) throws BusException;
@BusMethod(signature="a{xg}", replySignature="a{xg}")
public Map<Long, String> DictionaryXG(Map<Long, String> aexg) throws BusException;
@BusMethod(signature="a{xi}", replySignature="a{xi}")
public Map<Long, Integer> DictionaryXI(Map<Long, Integer> aexi) throws BusException;
@BusMethod(signature="a{xt}", replySignature="a{xt}")
public Map<Long, Long> DictionaryXT(Map<Long, Long> aext) throws BusException;
@BusMethod(signature="a{xn}", replySignature="a{xn}")
public Map<Long, Short> DictionaryXN(Map<Long, Short> aexn) throws BusException;
@BusMethod(signature="a{xv}", replySignature="a{xv}")
public Map<Long, Variant> DictionaryXV(Map<Long, Variant> aexv) throws BusException;
@BusMethod(signature="a{xs}", replySignature="a{xs}")
public Map<Long, String> DictionaryXS(Map<Long, String> aexs) throws BusException;
@BusMethod(signature="a{xay}", replySignature="a{xay}")
public Map<Long, byte[]> DictionaryXAY(Map<Long, byte[]> aexay) throws BusException;
@BusMethod(signature="a{xq}", replySignature="a{xq}")
public Map<Long, Short> DictionaryXQ(Map<Long, Short> aexq) throws BusException;
@BusMethod(signature="a{xb}", replySignature="a{xb}")
public Map<Long, Boolean> DictionaryXB(Map<Long, Boolean> aexb) throws BusException;
@BusMethod(signature="a{xo}", replySignature="a{xo}")
public Map<Long, String> DictionaryXO(Map<Long, String> aexo) throws BusException;
@BusMethod(signature="a{sa{ss}}", replySignature="a{sa{ss}}")
public Map<String, Map<String, String>> DictionarySAESS(Map<String, Map<String, String>> aesaess) throws BusException;
@BusMethod(name="DictionarySR", signature="a{sr}", replySignature="a{sr}")
public Map<String, AnnotatedTypesInterface.InnerStruct> AnnotatedDictionarySR(Map<String, AnnotatedTypesInterface.InnerStruct> aesr) throws BusException;
@BusMethod(signature="a{sd}", replySignature="a{sd}")
public Map<String, Double> DictionarySD(Map<String, Double> aesd) throws BusException;
@BusMethod(signature="a{sx}", replySignature="a{sx}")
public Map<String, Long> DictionarySX(Map<String, Long> aesx) throws BusException;
@BusMethod(signature="a{sy}", replySignature="a{sy}")
public Map<String, Byte> DictionarySY(Map<String, Byte> aesy) throws BusException;
@BusMethod(signature="a{su}", replySignature="a{su}")
public Map<String, Integer> DictionarySU(Map<String, Integer> aesu) throws BusException;
@BusMethod(signature="a{sg}", replySignature="a{sg}")
public Map<String, String> DictionarySG(Map<String, String> aesg) throws BusException;
@BusMethod(signature="a{si}", replySignature="a{si}")
public Map<String, Integer> DictionarySI(Map<String, Integer> aesi) throws BusException;
@BusMethod(signature="a{st}", replySignature="a{st}")
public Map<String, Long> DictionaryST(Map<String, Long> aest) throws BusException;
@BusMethod(signature="a{sn}", replySignature="a{sn}")
public Map<String, Short> DictionarySN(Map<String, Short> aesn) throws BusException;
@BusMethod(signature="a{sv}", replySignature="a{sv}")
public Map<String, Variant> DictionarySV(Map<String, Variant> aesv) throws BusException;
@BusMethod(signature="a{ss}", replySignature="a{ss}")
public Map<String, String> DictionarySS(Map<String, String> aess) throws BusException;
@BusMethod(signature="a{say}", replySignature="a{say}")
public Map<String, byte[]> DictionarySAY(Map<String, byte[]> aesay) throws BusException;
@BusMethod(signature="a{sq}", replySignature="a{sq}")
public Map<String, Short> DictionarySQ(Map<String, Short> aesq) throws BusException;
@BusMethod(signature="a{sb}", replySignature="a{sb}")
public Map<String, Boolean> DictionarySB(Map<String, Boolean> aesb) throws BusException;
@BusMethod(signature="a{so}", replySignature="a{so}")
public Map<String, String> DictionarySO(Map<String, String> aeso) throws BusException;
@BusMethod(signature="a{ya{ss}}", replySignature="a{ya{ss}}")
public Map<Byte, Map<String, String>> DictionaryYAESS(Map<Byte, Map<String, String>> aeyaess) throws BusException;
@BusMethod(name="DictionaryYR", signature="a{yr}", replySignature="a{yr}")
public Map<Byte, AnnotatedTypesInterface.InnerStruct> AnnotatedDictionaryYR(Map<Byte, AnnotatedTypesInterface.InnerStruct> aeyr) throws BusException;
@BusMethod(signature="a{yd}", replySignature="a{yd}")
public Map<Byte, Double> DictionaryYD(Map<Byte, Double> aeyd) throws BusException;
@BusMethod(signature="a{yx}", replySignature="a{yx}")
public Map<Byte, Long> DictionaryYX(Map<Byte, Long> aeyx) throws BusException;
@BusMethod(signature="a{yy}", replySignature="a{yy}")
public Map<Byte, Byte> DictionaryYY(Map<Byte, Byte> aeyy) throws BusException;
@BusMethod(signature="a{yu}", replySignature="a{yu}")
public Map<Byte, Integer> DictionaryYU(Map<Byte, Integer> aeyu) throws BusException;
@BusMethod(signature="a{yg}", replySignature="a{yg}")
public Map<Byte, String> DictionaryYG(Map<Byte, String> aeyg) throws BusException;
@BusMethod(signature="a{yi}", replySignature="a{yi}")
public Map<Byte, Integer> DictionaryYI(Map<Byte, Integer> aeyi) throws BusException;
@BusMethod(signature="a{yt}", replySignature="a{yt}")
public Map<Byte, Long> DictionaryYT(Map<Byte, Long> aeyt) throws BusException;
@BusMethod(signature="a{yn}", replySignature="a{yn}")
public Map<Byte, Short> DictionaryYN(Map<Byte, Short> aeyn) throws BusException;
@BusMethod(signature="a{yv}", replySignature="a{yv}")
public Map<Byte, Variant> DictionaryYV(Map<Byte, Variant> aeyv) throws BusException;
@BusMethod(signature="a{ys}", replySignature="a{ys}")
public Map<Byte, String> DictionaryYS(Map<Byte, String> aeys) throws BusException;
@BusMethod(signature="a{yay}", replySignature="a{yay}")
public Map<Byte, byte[]> DictionaryYAY(Map<Byte, byte[]> aeyay) throws BusException;
@BusMethod(signature="a{yq}", replySignature="a{yq}")
public Map<Byte, Short> DictionaryYQ(Map<Byte, Short> aeyq) throws BusException;
@BusMethod(signature="a{yb}", replySignature="a{yb}")
public Map<Byte, Boolean> DictionaryYB(Map<Byte, Boolean> aeyb) throws BusException;
@BusMethod(signature="a{yo}", replySignature="a{yo}")
public Map<Byte, String> DictionaryYO(Map<Byte, String> aeyo) throws BusException;
@BusMethod(signature="a{ua{ss}}", replySignature="a{ua{ss}}")
public Map<Integer, Map<String, String>> DictionaryUAESS(Map<Integer, Map<String, String>> aeuaess) throws BusException;
@BusMethod(signature="a{ur}", replySignature="a{ur}")
public Map<Integer, AnnotatedTypesInterface.InnerStruct> DictionaryUR(Map<Integer, AnnotatedTypesInterface.InnerStruct> aeur) throws BusException;
@BusMethod(signature="a{ud}", replySignature="a{ud}")
public Map<Integer, Double> DictionaryUD(Map<Integer, Double> aeud) throws BusException;
@BusMethod(signature="a{ux}", replySignature="a{ux}")
public Map<Integer, Long> DictionaryUX(Map<Integer, Long> aeux) throws BusException;
@BusMethod(signature="a{uy}", replySignature="a{uy}")
public Map<Integer, Byte> DictionaryUY(Map<Integer, Byte> aeuy) throws BusException;
@BusMethod(signature="a{uu}", replySignature="a{uu}")
public Map<Integer, Integer> DictionaryUU(Map<Integer, Integer> aeuu) throws BusException;
@BusMethod(signature="a{ug}", replySignature="a{ug}")
public Map<Integer, String> DictionaryUG(Map<Integer, String> aeug) throws BusException;
@BusMethod(signature="a{ui}", replySignature="a{ui}")
public Map<Integer, Integer> DictionaryUI(Map<Integer, Integer> aeui) throws BusException;
@BusMethod(signature="a{ut}", replySignature="a{ut}")
public Map<Integer, Long> DictionaryUT(Map<Integer, Long> aeut) throws BusException;
@BusMethod(signature="a{un}", replySignature="a{un}")
public Map<Integer, Short> DictionaryUN(Map<Integer, Short> aeun) throws BusException;
@BusMethod(signature="a{uv}", replySignature="a{uv}")
public Map<Integer, Variant> DictionaryUV(Map<Integer, Variant> aeuv) throws BusException;
@BusMethod(signature="a{us}", replySignature="a{us}")
public Map<Integer, String> DictionaryUS(Map<Integer, String> aeus) throws BusException;
@BusMethod(signature="a{uay}", replySignature="a{uay}")
public Map<Integer, byte[]> DictionaryUAY(Map<Integer, byte[]> aeuay) throws BusException;
@BusMethod(signature="a{uq}", replySignature="a{uq}")
public Map<Integer, Short> DictionaryUQ(Map<Integer, Short> aeuq) throws BusException;
@BusMethod(signature="a{ub}", replySignature="a{ub}")
public Map<Integer, Boolean> DictionaryUB(Map<Integer, Boolean> aeub) throws BusException;
@BusMethod(signature="a{uo}", replySignature="a{uo}")
public Map<Integer, String> DictionaryUO(Map<Integer, String> aeuo) throws BusException;
@BusMethod(signature="a{ga{ss}}", replySignature="a{ga{ss}}")
public Map<String, Map<String, String>> DictionaryGAESS(Map<String, Map<String, String>> aegaess) throws BusException;
@BusMethod(signature="a{gr}", replySignature="a{gr}")
public Map<String, AnnotatedTypesInterface.InnerStruct> DictionaryGR(Map<String, AnnotatedTypesInterface.InnerStruct> aegr) throws BusException;
@BusMethod(signature="a{gd}", replySignature="a{gd}")
public Map<String, Double> DictionaryGD(Map<String, Double> aegd) throws BusException;
@BusMethod(signature="a{gx}", replySignature="a{gx}")
public Map<String, Long> DictionaryGX(Map<String, Long> aegx) throws BusException;
@BusMethod(signature="a{gy}", replySignature="a{gy}")
public Map<String, Byte> DictionaryGY(Map<String, Byte> aegy) throws BusException;
@BusMethod(signature="a{gu}", replySignature="a{gu}")
public Map<String, Integer> DictionaryGU(Map<String, Integer> aegu) throws BusException;
@BusMethod(signature="a{gg}", replySignature="a{gg}")
public Map<String, String> DictionaryGG(Map<String, String> aegg) throws BusException;
@BusMethod(signature="a{gi}", replySignature="a{gi}")
public Map<String, Integer> DictionaryGI(Map<String, Integer> aegi) throws BusException;
@BusMethod(signature="a{gt}", replySignature="a{gt}")
public Map<String, Long> DictionaryGT(Map<String, Long> aegt) throws BusException;
@BusMethod(signature="a{gn}", replySignature="a{gn}")
public Map<String, Short> DictionaryGN(Map<String, Short> aegn) throws BusException;
@BusMethod(signature="a{gv}", replySignature="a{gv}")
public Map<String, Variant> DictionaryGV(Map<String, Variant> aegv) throws BusException;
@BusMethod(signature="a{gs}", replySignature="a{gs}")
public Map<String, String> DictionaryGS(Map<String, String> aegs) throws BusException;
@BusMethod(signature="a{gay}", replySignature="a{gay}")
public Map<String, byte[]> DictionaryGAY(Map<String, byte[]> aegay) throws BusException;
@BusMethod(signature="a{gq}", replySignature="a{gq}")
public Map<String, Short> DictionaryGQ(Map<String, Short> aegq) throws BusException;
@BusMethod(signature="a{gb}", replySignature="a{gb}")
public Map<String, Boolean> DictionaryGB(Map<String, Boolean> aegb) throws BusException;
@BusMethod(signature="a{go}", replySignature="a{go}")
public Map<String, String> DictionaryGO(Map<String, String> aego) throws BusException;
@BusMethod(signature="a{ba{ss}}", replySignature="a{ba{ss}}")
public Map<Boolean, Map<String, String>> DictionaryBAESS(Map<Boolean, Map<String, String>> aebaess) throws BusException;
@BusMethod(name="DictionaryBR", signature="a{br}", replySignature="a{br}")
public Map<Boolean, AnnotatedTypesInterface.InnerStruct> AnnotatedDictionaryBR(Map<Boolean, AnnotatedTypesInterface.InnerStruct> aebr) throws BusException;
@BusMethod(signature="a{bd}", replySignature="a{bd}")
public Map<Boolean, Double> DictionaryBD(Map<Boolean, Double> aebd) throws BusException;
@BusMethod(signature="a{bx}", replySignature="a{bx}")
public Map<Boolean, Long> DictionaryBX(Map<Boolean, Long> aebx) throws BusException;
@BusMethod(signature="a{by}", replySignature="a{by}")
public Map<Boolean, Byte> DictionaryBY(Map<Boolean, Byte> aeby) throws BusException;
@BusMethod(signature="a{bu}", replySignature="a{bu}")
public Map<Boolean, Integer> DictionaryBU(Map<Boolean, Integer> aebu) throws BusException;
@BusMethod(signature="a{bg}", replySignature="a{bg}")
public Map<Boolean, String> DictionaryBG(Map<Boolean, String> aebg) throws BusException;
@BusMethod(signature="a{bi}", replySignature="a{bi}")
public Map<Boolean, Integer> DictionaryBI(Map<Boolean, Integer> aebi) throws BusException;
@BusMethod(signature="a{bt}", replySignature="a{bt}")
public Map<Boolean, Long> DictionaryBT(Map<Boolean, Long> aebt) throws BusException;
@BusMethod(signature="a{bn}", replySignature="a{bn}")
public Map<Boolean, Short> DictionaryBN(Map<Boolean, Short> aebn) throws BusException;
@BusMethod(signature="a{bv}", replySignature="a{bv}")
public Map<Boolean, Variant> DictionaryBV(Map<Boolean, Variant> aebv) throws BusException;
@BusMethod(signature="a{bs}", replySignature="a{bs}")
public Map<Boolean, String> DictionaryBS(Map<Boolean, String> aebs) throws BusException;
@BusMethod(signature="a{bay}", replySignature="a{bay}")
public Map<Boolean, byte[]> DictionaryBAY(Map<Boolean, byte[]> aebay) throws BusException;
@BusMethod(signature="a{bq}", replySignature="a{bq}")
public Map<Boolean, Short> DictionaryBQ(Map<Boolean, Short> aebq) throws BusException;
@BusMethod(signature="a{bb}", replySignature="a{bb}")
public Map<Boolean, Boolean> DictionaryBB(Map<Boolean, Boolean> aebb) throws BusException;
@BusMethod(signature="a{bo}", replySignature="a{bo}")
public Map<Boolean, String> DictionaryBO(Map<Boolean, String> aebo) throws BusException;
@BusMethod(signature="a{qa{ss}}", replySignature="a{qa{ss}}")
public Map<Short, Map<String, String>> DictionaryQAESS(Map<Short, Map<String, String>> aeqaess) throws BusException;
@BusMethod(signature="a{qr}", replySignature="a{qr}")
public Map<Short, AnnotatedTypesInterface.InnerStruct> DictionaryQR(Map<Short, AnnotatedTypesInterface.InnerStruct> aeqr) throws BusException;
@BusMethod(signature="a{qd}", replySignature="a{qd}")
public Map<Short, Double> DictionaryQD(Map<Short, Double> aeqd) throws BusException;
@BusMethod(signature="a{qx}", replySignature="a{qx}")
public Map<Short, Long> DictionaryQX(Map<Short, Long> aeqx) throws BusException;
@BusMethod(signature="a{qy}", replySignature="a{qy}")
public Map<Short, Byte> DictionaryQY(Map<Short, Byte> aeqy) throws BusException;
@BusMethod(signature="a{qu}", replySignature="a{qu}")
public Map<Short, Integer> DictionaryQU(Map<Short, Integer> aequ) throws BusException;
@BusMethod(signature="a{qg}", replySignature="a{qg}")
public Map<Short, String> DictionaryQG(Map<Short, String> aeqg) throws BusException;
@BusMethod(signature="a{qi}", replySignature="a{qi}")
public Map<Short, Integer> DictionaryQI(Map<Short, Integer> aeqi) throws BusException;
@BusMethod(signature="a{qt}", replySignature="a{qt}")
public Map<Short, Long> DictionaryQT(Map<Short, Long> aeqt) throws BusException;
@BusMethod(signature="a{qn}", replySignature="a{qn}")
public Map<Short, Short> DictionaryQN(Map<Short, Short> aeqn) throws BusException;
@BusMethod(signature="a{qv}", replySignature="a{qv}")
public Map<Short, Variant> DictionaryQV(Map<Short, Variant> aeqv) throws BusException;
@BusMethod(signature="a{qs}", replySignature="a{qs}")
public Map<Short, String> DictionaryQS(Map<Short, String> aeqs) throws BusException;
@BusMethod(signature="a{qay}", replySignature="a{qay}")
public Map<Short, byte[]> DictionaryQAY(Map<Short, byte[]> aeqay) throws BusException;
@BusMethod(signature="a{qq}", replySignature="a{qq}")
public Map<Short, Short> DictionaryQQ(Map<Short, Short> aeqq) throws BusException;
@BusMethod(signature="a{qb}", replySignature="a{qb}")
public Map<Short, Boolean> DictionaryQB(Map<Short, Boolean> aeqb) throws BusException;
@BusMethod(signature="a{qo}", replySignature="a{qo}")
public Map<Short, String> DictionaryQO(Map<Short, String> aeqo) throws BusException;
@BusMethod(signature="a{oa{ss}}", replySignature="a{oa{ss}}")
public Map<String, Map<String, String>> DictionaryOAESS(Map<String, Map<String, String>> aeoaess) throws BusException;
@BusMethod(signature="a{or}", replySignature="a{or}")
public Map<String, AnnotatedTypesInterface.InnerStruct> DictionaryOR(Map<String, AnnotatedTypesInterface.InnerStruct> aeor) throws BusException;
@BusMethod(signature="a{od}", replySignature="a{od}")
public Map<String, Double> DictionaryOD(Map<String, Double> aeod) throws BusException;
@BusMethod(signature="a{ox}", replySignature="a{ox}")
public Map<String, Long> DictionaryOX(Map<String, Long> aeox) throws BusException;
@BusMethod(signature="a{oy}", replySignature="a{oy}")
public Map<String, Byte> DictionaryOY(Map<String, Byte> aeoy) throws BusException;
@BusMethod(signature="a{ou}", replySignature="a{ou}")
public Map<String, Integer> DictionaryOU(Map<String, Integer> aeou) throws BusException;
@BusMethod(signature="a{og}", replySignature="a{og}")
public Map<String, String> DictionaryOG(Map<String, String> aeog) throws BusException;
@BusMethod(signature="a{oi}", replySignature="a{oi}")
public Map<String, Integer> DictionaryOI(Map<String, Integer> aeoi) throws BusException;
@BusMethod(signature="a{ot}", replySignature="a{ot}")
public Map<String, Long> DictionaryOT(Map<String, Long> aeot) throws BusException;
@BusMethod(signature="a{on}", replySignature="a{on}")
public Map<String, Short> DictionaryON(Map<String, Short> aeon) throws BusException;
@BusMethod(signature="a{ov}", replySignature="a{ov}")
public Map<String, Variant> DictionaryOV(Map<String, Variant> aeov) throws BusException;
@BusMethod(signature="a{os}", replySignature="a{os}")
public Map<String, String> DictionaryOS(Map<String, String> aeos) throws BusException;
@BusMethod(signature="a{oay}", replySignature="a{oay}")
public Map<String, byte[]> DictionaryOAY(Map<String, byte[]> aeoay) throws BusException;
@BusMethod(signature="a{oq}", replySignature="a{oq}")
public Map<String, Short> DictionaryOQ(Map<String, Short> aeoq) throws BusException;
@BusMethod(signature="a{ob}", replySignature="a{ob}")
public Map<String, Boolean> DictionaryOB(Map<String, Boolean> aeob) throws BusException;
@BusMethod(signature="a{oo}", replySignature="a{oo}")
public Map<String, String> DictionaryOO(Map<String, String> aeoo) throws BusException;
@BusMethod(signature="a{ia{ss}}", replySignature="a{ia{ss}}")
public Map<Integer, Map<String, String>> DictionaryIAESS(Map<Integer, Map<String, String>> aeiaess) throws BusException;
@BusMethod(name="DictionaryIR", signature="a{ir}", replySignature="a{ir}")
public Map<Integer, AnnotatedTypesInterface.InnerStruct> AnnotatedDictionaryIR(Map<Integer, AnnotatedTypesInterface.InnerStruct> aeir) throws BusException;
@BusMethod(signature="a{id}", replySignature="a{id}")
public Map<Integer, Double> DictionaryID(Map<Integer, Double> aeid) throws BusException;
@BusMethod(signature="a{ix}", replySignature="a{ix}")
public Map<Integer, Long> DictionaryIX(Map<Integer, Long> aeix) throws BusException;
@BusMethod(signature="a{iy}", replySignature="a{iy}")
public Map<Integer, Byte> DictionaryIY(Map<Integer, Byte> aeiy) throws BusException;
@BusMethod(signature="a{iu}", replySignature="a{iu}")
public Map<Integer, Integer> DictionaryIU(Map<Integer, Integer> aeiu) throws BusException;
@BusMethod(signature="a{ig}", replySignature="a{ig}")
public Map<Integer, String> DictionaryIG(Map<Integer, String> aeig) throws BusException;
@BusMethod(signature="a{ii}", replySignature="a{ii}")
public Map<Integer, Integer> DictionaryII(Map<Integer, Integer> aeii) throws BusException;
@BusMethod(signature="a{it}", replySignature="a{it}")
public Map<Integer, Long> DictionaryIT(Map<Integer, Long> aeit) throws BusException;
@BusMethod(signature="a{in}", replySignature="a{in}")
public Map<Integer, Short> DictionaryIN(Map<Integer, Short> aein) throws BusException;
@BusMethod(signature="a{iv}", replySignature="a{iv}")
public Map<Integer, Variant> DictionaryIV(Map<Integer, Variant> aeiv) throws BusException;
@BusMethod(signature="a{is}", replySignature="a{is}")
public Map<Integer, String> DictionaryIS(Map<Integer, String> aeis) throws BusException;
@BusMethod(signature="a{iay}", replySignature="a{iay}")
public Map<Integer, byte[]> DictionaryIAY(Map<Integer, byte[]> aeiay) throws BusException;
@BusMethod(signature="a{iq}", replySignature="a{iq}")
public Map<Integer, Short> DictionaryIQ(Map<Integer, Short> aeiq) throws BusException;
@BusMethod(signature="a{ib}", replySignature="a{ib}")
public Map<Integer, Boolean> DictionaryIB(Map<Integer, Boolean> aeib) throws BusException;
@BusMethod(signature="a{io}", replySignature="a{io}")
public Map<Integer, String> DictionaryIO(Map<Integer, String> aeio) throws BusException;
@BusMethod(signature="a{ta{ss}}", replySignature="a{ta{ss}}")
public Map<Long, Map<String, String>> DictionaryTAESS(Map<Long, Map<String, String>> aetaess) throws BusException;
@BusMethod(signature="a{tr}", replySignature="a{tr}")
public Map<Long, AnnotatedTypesInterface.InnerStruct> DictionaryTR(Map<Long, AnnotatedTypesInterface.InnerStruct> aetr) throws BusException;
@BusMethod(signature="a{td}", replySignature="a{td}")
public Map<Long, Double> DictionaryTD(Map<Long, Double> aetd) throws BusException;
@BusMethod(signature="a{tx}", replySignature="a{tx}")
public Map<Long, Long> DictionaryTX(Map<Long, Long> aetx) throws BusException;
@BusMethod(signature="a{ty}", replySignature="a{ty}")
public Map<Long, Byte> DictionaryTY(Map<Long, Byte> aety) throws BusException;
@BusMethod(signature="a{tu}", replySignature="a{tu}")
public Map<Long, Integer> DictionaryTU(Map<Long, Integer> aetu) throws BusException;
@BusMethod(signature="a{tg}", replySignature="a{tg}")
public Map<Long, String> DictionaryTG(Map<Long, String> aetg) throws BusException;
@BusMethod(signature="a{ti}", replySignature="a{ti}")
public Map<Long, Integer> DictionaryTI(Map<Long, Integer> aeti) throws BusException;
@BusMethod(signature="a{tt}", replySignature="a{tt}")
public Map<Long, Long> DictionaryTT(Map<Long, Long> aett) throws BusException;
@BusMethod(signature="a{tn}", replySignature="a{tn}")
public Map<Long, Short> DictionaryTN(Map<Long, Short> aetn) throws BusException;
@BusMethod(signature="a{tv}", replySignature="a{tv}")
public Map<Long, Variant> DictionaryTV(Map<Long, Variant> aetv) throws BusException;
@BusMethod(signature="a{ts}", replySignature="a{ts}")
public Map<Long, String> DictionaryTS(Map<Long, String> aets) throws BusException;
@BusMethod(signature="a{tay}", replySignature="a{tay}")
public Map<Long, byte[]> DictionaryTAY(Map<Long, byte[]> aetay) throws BusException;
@BusMethod(signature="a{tq}", replySignature="a{tq}")
public Map<Long, Short> DictionaryTQ(Map<Long, Short> aetq) throws BusException;
@BusMethod(signature="a{tb}", replySignature="a{tb}")
public Map<Long, Boolean> DictionaryTB(Map<Long, Boolean> aetb) throws BusException;
@BusMethod(signature="a{to}", replySignature="a{to}")
public Map<Long, String> DictionaryTO(Map<Long, String> aeto) throws BusException;
@BusProperty(signature="a{ss}")
public Map<String, String> getDictionarySS() throws BusException;
@BusProperty(signature="a{ss}")
public void setDictionarySS(Map<String, String> aess) throws BusException;
public enum EnumType {
Enum0;
};
@BusMethod(signature="y", replySignature="y")
public EnumType EnumY(EnumType y) throws BusException;
@BusMethod(signature="n", replySignature="n")
public EnumType EnumN(EnumType n) throws BusException;
@BusMethod(signature="q", replySignature="q")
public EnumType EnumQ(EnumType q) throws BusException;
@BusMethod(signature="i", replySignature="i")
public EnumType EnumI(EnumType i) throws BusException;
@BusMethod(signature="u", replySignature="u")
public EnumType EnumU(EnumType u) throws BusException;
@BusMethod(signature="x", replySignature="x")
public EnumType EnumX(EnumType x) throws BusException;
@BusMethod(signature="t", replySignature="t")
public EnumType EnumT(EnumType t) throws BusException;
}
| 44.014085 | 159 | 0.689108 |
7bfe96d4f049849f9df33f80c3a92fb622f7699c | 1,293 | /*
* Copyright 2021-2022 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
*
* https://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 icu.easyj.poi.excel.hook;
import java.util.Map;
import icu.easyj.poi.excel.model.ExcelMapping;
import org.apache.poi.ss.usermodel.Sheet;
/**
* 列表转Excel时提供的勾子接口
*
* @author wangliang181230
*/
public interface IListToExcelHook {
/**
* “创建头行之前” 触发的事件
*
* @param context 表格所需上下文
* @param sheet 表格
* @param mapping 表格映射
*/
default void onBeforeCreateHeadRow(Map<Object, Object> context, Sheet sheet, ExcelMapping mapping) {
}
/**
* “创建所有数据行之后” 触发的事件
*
* @param context 表格所需上下文
* @param sheet 表格
* @param mapping 表格映射
*/
default void onAfterCreateDataRows(Map<Object, Object> context, Sheet sheet, ExcelMapping mapping) {
}
}
| 25.86 | 101 | 0.719258 |
a4b1591a9e3c7b46c0110b8186967bf985a7c352 | 1,863 | /**
* 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.qpid.proton.hawtdispatch.impl;
import org.fusesource.hawtdispatch.Dispatch;
import org.fusesource.hawtdispatch.Task;
import java.util.LinkedList;
/**
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
abstract public class WatchBase {
private LinkedList<Watch> watches = new LinkedList<Watch>();
protected void addWatch(final Watch task) {
watches.add(task);
fireWatches();
}
protected void fireWatches() {
if( !this.watches.isEmpty() ) {
Dispatch.getCurrentQueue().execute(new Task(){
@Override
public void run() {
// Lets see if any of the watches are triggered.
LinkedList<Watch> tmp = watches;
watches = new LinkedList<Watch>();
for (Watch task : tmp) {
if( !task.execute() ) {
watches.add(task);
}
}
}
});
}
}
}
| 33.872727 | 75 | 0.619968 |
0faebed0a70d99dd33699366a4d194f56cf974b2 | 3,189 | package com.freedom.lauzy.ticktockmusic.presenter;
import com.freedom.lauzy.interactor.GetLocalSongUseCase;
import com.freedom.lauzy.interactor.GetQueueUseCase;
import com.freedom.lauzy.model.LocalSongBean;
import com.freedom.lauzy.ticktockmusic.base.BaseRxPresenter;
import com.freedom.lauzy.ticktockmusic.contract.LocalMusicContract;
import com.freedom.lauzy.ticktockmusic.model.SongEntity;
import com.freedom.lauzy.ticktockmusic.model.mapper.LocalSongMapper;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
/**
* Desc : Local Music Presenter
* Author : Lauzy
* Date : 2017/8/2
* Blog : http://www.jianshu.com/u/e76853f863a9
* Email : [email protected]
*/
public class LocalMusicPresenter extends BaseRxPresenter<LocalMusicContract.View>
implements LocalMusicContract.SongPresenter {
private GetLocalSongUseCase mGetLocalSongUseCase;
private GetQueueUseCase mGetQueueUseCase;
private LocalSongMapper mLocalSongMapper;
private long mId;//专辑ID
@Inject
LocalMusicPresenter(GetLocalSongUseCase getLocalSongUseCase, GetQueueUseCase getQueueUseCase,
LocalSongMapper localSongMapper) {
mGetLocalSongUseCase = getLocalSongUseCase;
mGetQueueUseCase = getQueueUseCase;
mLocalSongMapper = localSongMapper;
}
public void setId(long id) {
mId = id;
}
@Override
public void loadLocalSong() {
mGetLocalSongUseCase.execute(new DisposableObserver<List<LocalSongBean>>() {
@Override
public void onNext(@NonNull List<LocalSongBean> localSongBeen) {
if (getView() == null) {
return;
}
if (localSongBeen != null && localSongBeen.size() != 0) {
List<SongEntity> songEntities = mLocalSongMapper.transform(localSongBeen);
getView().loadLocalMusic(songEntities);
} else {
getView().setEmptyView();
}
}
@Override
public void onError(@NonNull Throwable e) {
e.printStackTrace();
if (getView() == null) {
return;
}
getView().loadFailed(e);
}
@Override
public void onComplete() {
}
}, mId);
}
@Override
public void deleteSong(int position, SongEntity songEntity) {
mGetLocalSongUseCase.deleteSong(songEntity.id)
.flatMap(integer -> {
if (integer < 0) {
return Observable.error(new RuntimeException("delete failed"));
}
return mGetQueueUseCase.deleteQueueObservable(new String[]{String.valueOf(songEntity.id)});
})
.subscribe(integer -> {
if (getView() == null) {
return;
}
getView().deleteSongSuccess(position, songEntity);
});
}
}
| 33.568421 | 111 | 0.61085 |
1d1d3818db6a64ddfa33ec6dddc37e038cae2500 | 4,521 | package com.haxademic.core.hardware.shared;
import com.haxademic.core.app.P;
import com.haxademic.core.hardware.gamepad.GamepadState;
import com.haxademic.core.hardware.http.HttpInputState;
import com.haxademic.core.hardware.keyboard.KeyCodes;
import com.haxademic.core.hardware.keyboard.KeyboardState;
import com.haxademic.core.hardware.midi.MidiState;
import com.haxademic.core.hardware.osc.OscState;
public class InputTrigger {
public enum InputState {
TRIGGER,
ON,
OFF
}
protected Integer[] keyCodes = new Integer[] {};
protected String[] oscMessages = new String[] {};
protected String[] httpRequests = new String[] {};
protected String[] gamepadControls = new String[] {};
protected Integer[] midiNotes = new Integer[] {};
protected Integer[] midiCC = new Integer[] {};
protected float curValue = 0;
protected String broadcastKey;
public InputTrigger() {
}
// chainable setters
public InputTrigger addKeyCodes(char[] charList) {
keyCodes = new Integer[charList.length];
for (int i = 0; i < charList.length; i++) keyCodes[i] = KeyCodes.keyCodeFromChar(charList[i]);
return this;
}
public InputTrigger addMidiNotes(Integer[] midiNotes) {
this.midiNotes = midiNotes;
return this;
}
public InputTrigger addMidiCCNotes(Integer[] midiCCNotes) {
this.midiCC = midiCCNotes;
return this;
}
public InputTrigger addOscMessages(String[] oscMessages) {
this.oscMessages = oscMessages;
return this;
}
public InputTrigger addGamepadControls(String[] gamepadControls) {
this.gamepadControls = gamepadControls;
return this;
}
public InputTrigger addHttpRequests(String[] webControls) {
this.httpRequests = webControls;
return this;
}
public InputTrigger setBroadcastKey(String broadcastKey) {
this.broadcastKey = broadcastKey;
return this;
}
// getters
public float value() {
return curValue;
}
public boolean triggered() {
boolean foundTrigger = false;
// if triggered, also store the latest value
if(foundTrigger == false) for( int i=0; i < keyCodes.length; i++ ) {
if(KeyboardState.instance().isKeyTriggered(keyCodes[i])) {
curValue = 1;
foundTrigger = true;
}
}
if(foundTrigger == false) for( int i=0; i < oscMessages.length; i++ ) {
if(OscState.instance().isValueTriggered(oscMessages[i])) {
curValue = OscState.instance().getValue(oscMessages[i]);
foundTrigger = true;
}
}
if(foundTrigger == false) for( int i=0; i < httpRequests.length; i++ ) {
if(HttpInputState.instance().isValueTriggered(httpRequests[i])) {
curValue = HttpInputState.instance().getValue(httpRequests[i]);
foundTrigger = true;
}
}
if(foundTrigger == false) for( int i=0; i < midiNotes.length; i++ ) {
if(MidiState.instance().isMidiNoteTriggered(midiNotes[i])) {
curValue = MidiState.instance().midiNoteValue(midiNotes[i]);
foundTrigger = true;
}
}
if(foundTrigger == false) for( int i=0; i < midiCC.length; i++ ) {
if(MidiState.instance().isMidiCCTriggered(midiCC[i])) {
curValue = MidiState.instance().midiCCNormalized(0, midiCC[i]);
foundTrigger = true;
}
}
if(foundTrigger == false) for( int i=0; i < gamepadControls.length; i++ ) {
if(GamepadState.instance().isValueTriggered(gamepadControls[i])) {
curValue = GamepadState.instance().getValue(gamepadControls[i]);
foundTrigger = true;
}
}
// return state
if(foundTrigger) {
// send it out to AppStore if needed
if(broadcastKey != null) P.store.setNumber(broadcastKey, curValue);
// return triggered state!
return true;
}
return false;
}
public boolean on() {
for( int i=0; i < keyCodes.length; i++ ) {
if(KeyboardState.instance().isKeyOn(keyCodes[i])) return true;
}
for( int i=0; i < oscMessages.length; i++ ) {
if(OscState.instance().isValueOn(oscMessages[i])) return true;
}
for( int i=0; i < midiNotes.length; i++ ) {
if(MidiState.instance().isMidiNoteOn(midiNotes[i])) return true;
}
for( int i=0; i < midiCC.length; i++ ) {
if(MidiState.instance().isMidiCCOn(midiCC[i])) return true;
}
for( int i=0; i < httpRequests.length; i++ ) {
if(HttpInputState.instance().isValueOn(httpRequests[i])) return true;
}
for( int i=0; i < gamepadControls.length; i++ ) {
if(GamepadState.instance().isValueOn(gamepadControls[i])) return true;
}
// switched to no longer being active
if(curValue > 0) {
curValue = 0;
if(broadcastKey != null) P.store.setNumber(broadcastKey, curValue);
}
return false;
}
}
| 28.980769 | 96 | 0.69144 |
4c6111fa821876e5ed08f7bb998cc1ae60148e7b | 5,019 | /*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.sql.impl.operation;
import com.hazelcast.internal.util.collection.PartitionIdSet;
import com.hazelcast.sql.impl.QueryId;
import com.hazelcast.sql.impl.QueryParameterMetadata;
import com.hazelcast.sql.impl.plan.Plan;
import com.hazelcast.sql.impl.plan.PlanFragmentMapping;
import com.hazelcast.sql.impl.plan.node.MockPlanNode;
import com.hazelcast.sql.impl.plan.node.PlanNode;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static com.hazelcast.sql.impl.operation.QueryExecuteOperationFragmentMapping.DATA_MEMBERS;
import static com.hazelcast.sql.impl.operation.QueryExecuteOperationFragmentMapping.EXPLICIT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class QueryExecuteOperationFactoryTest {
@Test
public void testExecuteOperationFactory() {
UUID member1 = UUID.randomUUID();
UUID member2 = UUID.randomUUID();
Map<UUID, PartitionIdSet> partitionMap = new HashMap<>();
partitionMap.put(member1, new PartitionIdSet(2, Collections.singletonList(1)));
partitionMap.put(member2, new PartitionIdSet(2, Collections.singletonList(2)));
PlanNode node1 = MockPlanNode.create(1);
PlanNode node2 = MockPlanNode.create(2);
List<PlanNode> fragments = Arrays.asList(node1, node2);
PlanFragmentMapping mapping1 = new PlanFragmentMapping(null, true);
PlanFragmentMapping mapping2 = new PlanFragmentMapping(Collections.singletonList(member2), false);
List<PlanFragmentMapping> fragmentMappings = Arrays.asList(mapping1, mapping2);
Map<Integer, Integer> outboundEdgeMap = Collections.singletonMap(1, 0);
Map<Integer, Integer> inboundEdgeMap = Collections.singletonMap(1, 1);
Map<Integer, Integer> inboundEdgeMemberCountMap = Collections.singletonMap(1, 2);
Plan plan = new Plan(
partitionMap,
fragments,
fragmentMappings,
outboundEdgeMap,
inboundEdgeMap,
inboundEdgeMemberCountMap,
null,
QueryParameterMetadata.EMPTY,
null,
Collections.emptySet(),
Collections.emptyList()
);
QueryId queryId = QueryId.create(UUID.randomUUID());
List<Object> args = Collections.singletonList(1);
Map<Integer, Long> edgeInitialMemoryMap = Collections.singletonMap(1, 1000L);
QueryExecuteOperationFactory factory = new QueryExecuteOperationFactory(plan, args, edgeInitialMemoryMap);
QueryExecuteOperation operation1 = factory.create(queryId, member1);
QueryExecuteOperation operation2 = factory.create(queryId, member2);
// Check common port.
for (QueryExecuteOperation operation : Arrays.asList(operation1, operation2)) {
assertEquals(queryId, operation.getQueryId());
assertSame(partitionMap, operation.getPartitionMap());
assertEquals(2, operation.getFragments().size());
assertSame(outboundEdgeMap, operation.getOutboundEdgeMap());
assertSame(inboundEdgeMap, operation.getInboundEdgeMap());
assertSame(edgeInitialMemoryMap, operation.getEdgeInitialMemoryMap());
assertSame(args, operation.getArguments());
}
// Check fragments.
assertEquals(operation1.getFragments().get(0), new QueryExecuteOperationFragment(node1, DATA_MEMBERS, null));
assertEquals(operation2.getFragments().get(0), new QueryExecuteOperationFragment(node1, DATA_MEMBERS, null));
Collection<UUID> expectedMemberIds = Collections.singletonList(member2);
assertEquals(operation1.getFragments().get(1), new QueryExecuteOperationFragment(null, EXPLICIT, expectedMemberIds));
assertEquals(operation2.getFragments().get(1), new QueryExecuteOperationFragment(node2, EXPLICIT, expectedMemberIds));
}
}
| 44.415929 | 126 | 0.735206 |
905eb29d9d3844c718b0d82feb6ab2f2acf08c86 | 292 | package com.qcloud.cos.exception;
// 未知异常
public class UnknownException extends AbstractCosException {
private static final long serialVersionUID = 4303770859616883146L;
public UnknownException(String message) {
super(CosExceptionType.UNKNOWN_EXCEPTION, message);
}
}
| 22.461538 | 70 | 0.767123 |
2632a82f45e9eefd4916023301d3ebbabb79c891 | 929 | /*
Copyright © 2019 Pasqual K. | All rights reserved
*/
package systems.reformcloud.network.in;
import com.google.gson.reflect.TypeToken;
import systems.reformcloud.ReformCloudAPIBungee;
import systems.reformcloud.configurations.Configuration;
import systems.reformcloud.meta.proxy.settings.ProxySettings;
import systems.reformcloud.network.interfaces.NetworkInboundHandler;
import java.io.Serializable;
import java.util.Optional;
/**
* @author _Klaro | Pasqual K. / created on 06.04.2019
*/
public final class PacketInUpdateProxySettings implements Serializable, NetworkInboundHandler {
@Override
public void handle(Configuration configuration) {
Optional<ProxySettings> proxySettings = configuration
.getValue("settings", new TypeToken<Optional<ProxySettings>>() {
}.getType());
ReformCloudAPIBungee.getInstance().setProxySettings(proxySettings.orElse(null));
}
}
| 30.966667 | 95 | 0.764263 |
a4cdc58e58ff6df7a5da42625a64f798ad10724c | 365 | package com.icepoint.framework.generator.entity;
/**
* @author Jiawei Zhao
*/
public enum AssociationType {
ONE_TO_ONE("1"),
ONE_TO_MANY("2"),
MANY_TO_ONE("3"),
MANY_TO_MANY("4")
;
private final String code;
AssociationType(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
| 15.208333 | 48 | 0.6 |
761c93afe1a0b497186d2b683f7611910753d15b | 898 | package TP7;
public class Application {
public static void main(String[] args) {
Thread thread1 = new Thread(new Talkative(0));
Thread thread2 = new Thread(new Talkative(1));
Thread thread3 = new Thread(new Talkative(2));
Thread thread4 = new Thread(new Talkative(3));
Thread thread5 = new Thread(new Talkative(4));
Thread thread6 = new Thread(new Talkative(5));
Thread thread7 = new Thread(new Talkative(6));
Thread thread8 = new Thread(new Talkative(7));
Thread thread9 = new Thread(new Talkative(8));
Thread thread10 = new Thread(new Talkative(9));
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread7.start();
thread8.start();
thread9.start();
thread10.start();
}
}
| 30.965517 | 55 | 0.594655 |
32cec2a3f530da734deb8b4c254b6e9b2b73e38a | 1,280 | package io.hackages.hackflix.springboot.controller;
import io.hackages.hackflix.backend.java.moviemanager.api.model.Movie;
import io.hackages.hackflix.backend.java.moviemanager.core.MovieServiceImpl;
import io.hackages.hackflix.springboot.repository.MovieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("movies")
public class MovieController {
private MovieRepository movieRepository;
@Bean
private MovieServiceImpl getMovieService() {
return new MovieServiceImpl(movieRepository);
}
@Autowired
public MovieController(MovieRepository movieRepository) {
this.movieRepository = movieRepository;
}
@GetMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
List<Movie> getMovies(@RequestParam Map<String,String> params) {
return getMovieService().getMovies(params);
}
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
Movie getMovieById(@PathVariable Long id) {
return getMovieService().getMovieById(id);
}
}
| 31.219512 | 82 | 0.772656 |
4b66cc902cc3312a60be43cad6e21f574bfa0241 | 2,697 | package graph;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import static sun.misc.Version.println;
public class My {
static class Node {
HashSet<Integer> neighbours;
int id;
Node(int id) {
this.neighbours = new HashSet<>();
this.id = id;
}
void addNeighbour(int id) {
neighbours.add(id);
}
}
public static class Graph {
Node[] nodes;
Graph(int size) {
nodes = new Node[size];
}
Node getNode(int id) {
Node node = nodes[id];
if (node == null) {
node = new Node(id);
nodes[id] = node;
}
return node;
}
void addEdge(int first, int second) {
getNode(first).addNeighbour(second);
// The graph is undirected?
// getNode(second).addNeighbour(first);
}
Boolean bfs(Node source, Node destination) {
HashSet<Integer> visited = new HashSet<>();
LinkedList<Integer> toVisit = new LinkedList<>();
toVisit.add(source.id);
while (!toVisit.isEmpty()) {
Integer nodeId = toVisit.remove();
if (destination.id == nodeId) return true;
if (visited.contains(nodeId)) continue;
visited.add(nodeId);
toVisit.addAll(getNode(nodeId).neighbours);
}
return false;
}
Boolean dfs(Node source, Node destination, HashSet<Integer> visited) {
if (visited.contains(source.id)) return false;
visited.add(source.id);
if (destination == source) return true;
for (Integer neighbour : source.neighbours) {
if (dfs(getNode(neighbour), destination, visited)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 5);
if (graph.dfs(graph.getNode(1), graph.getNode(2), new HashSet<>())) {
System.out.println("DFS YES");
} else {
System.out.println("DFS NO");
}
if (graph.bfs(graph.getNode(1), graph.getNode(2))) {
System.out.println("BFS YES");
} else {
System.out.println("BFS NO");
}
}
}
} | 25.443396 | 81 | 0.487208 |
6c2d5101f07b27d56bfc1213b8c313ab283fcc93 | 19,243 | /*
* Copyright (c) 2007-2015 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading 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 cascading.pipe.assembly;
import java.beans.ConstructorProperties;
import java.lang.reflect.Type;
import cascading.flow.FlowProcess;
import cascading.operation.Aggregator;
import cascading.operation.AggregatorCall;
import cascading.operation.BaseOperation;
import cascading.operation.OperationCall;
import cascading.pipe.Pipe;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import cascading.tuple.coerce.Coercions;
import cascading.tuple.type.CoercibleType;
/**
* Class AverageBy is used to average values associated with duplicate keys in a tuple stream.
* <p/>
* Typically finding the average value in a tuple stream relies on a {@link cascading.pipe.GroupBy} and a {@link cascading.operation.aggregator.Average}
* {@link cascading.operation.Aggregator} operation.
* <p/>
* If the given {@code averageFields} has an associated type, this type will be used to coerce the resulting average value,
* otherwise the result will be a {@link Double}.
* <p/>
* If {@code include} is {@link Include#NO_NULLS}, {@code null} values will not be included in the average (converted to zero).
* By default (and for backwards compatibility) {@code null} values are included, {@link Include#ALL}.
* <p/>
* This SubAssembly uses the {@link cascading.pipe.assembly.AverageBy.AveragePartials} {@link cascading.pipe.assembly.AggregateBy.Functor}
* and private {@link AverageFinal} Aggregator to count and sum as many field values before the GroupBy operator to reduce IO over the network.
* <p/>
* This strategy is similar to using {@code combiners}, except no sorting or serialization is invoked and results
* in a much simpler mechanism.
* <p/>
* The {@code threshold} value tells the underlying AveragePartials functions how many unique key sums and counts to accumulate
* in the LRU cache, before emitting the least recently used entry. This accumulation happens map-side, and thus is
* bounded by the size of your map task JVM and the typical size of each group key.
* <p/>
* By default, either the value of {@link cascading.pipe.assembly.AggregateByProps#AGGREGATE_BY_CAPACITY} System property
* or {@link cascading.pipe.assembly.AggregateByProps#AGGREGATE_BY_DEFAULT_CAPACITY} will be used.
*
* @see cascading.pipe.assembly.AggregateBy
*/
public class AverageBy extends AggregateBy
{
/** DEFAULT_THRESHOLD */
@Deprecated
public static final int DEFAULT_THRESHOLD = 10000;
public enum Include
{
ALL,
NO_NULLS
}
/**
* Class AveragePartials is a {@link cascading.pipe.assembly.AggregateBy.Functor} that is used to count and sum observed duplicates from the tuple stream.
*
* @see cascading.pipe.assembly.AverageBy
*/
public static class AveragePartials implements Functor
{
private final Fields declaredFields;
private final Include include;
/**
* Constructor AveragePartials creates a new AveragePartials instance.
*
* @param declaredFields of type Fields
*/
public AveragePartials( Fields declaredFields )
{
this.declaredFields = declaredFields;
this.include = Include.ALL;
}
public AveragePartials( Fields declaredFields, Include include )
{
this.declaredFields = declaredFields;
this.include = include;
}
@Override
public Fields getDeclaredFields()
{
Fields sumName = new Fields( AverageBy.class.getPackage().getName() + "." + declaredFields.get( 0 ) + ".sum", Double.class );
Fields countName = new Fields( AverageBy.class.getPackage().getName() + "." + declaredFields.get( 0 ) + ".count", Long.class );
return sumName.append( countName );
}
@Override
public Tuple aggregate( FlowProcess flowProcess, TupleEntry args, Tuple context )
{
if( context == null )
context = Tuple.size( 2 );
if( include == Include.NO_NULLS && args.getObject( 0 ) == null )
return context;
context.set( 0, context.getDouble( 0 ) + args.getDouble( 0 ) );
context.set( 1, context.getLong( 1 ) + 1 );
return context;
}
@Override
public Tuple complete( FlowProcess flowProcess, Tuple context )
{
return context;
}
}
/**
* Class AverageFinal is used to finalize the average operation on the Reduce side of the process. It must be used
* in tandem with a {@link AveragePartials} Functor.
*/
public static class AverageFinal extends BaseOperation<AverageFinal.Context> implements Aggregator<AverageFinal.Context>
{
/** Class Context is used to hold intermediate values. */
protected static class Context
{
long nulls = 0L;
double sum = 0.0D;
long count = 0L;
Type type = Double.class;
CoercibleType canonical;
Tuple tuple = Tuple.size( 1 );
public Context( Fields fieldDeclaration )
{
if( fieldDeclaration.hasTypes() )
this.type = fieldDeclaration.getType( 0 );
this.canonical = Coercions.coercibleTypeFor( this.type );
}
public Context reset()
{
nulls = 0L;
sum = 0.0D;
count = 0L;
tuple.set( 0, null );
return this;
}
public Tuple result()
{
// we only saw null from upstream, so return null
if( count == 0 && nulls != 0 )
return tuple;
tuple.set( 0, canonical.canonical( sum / count ) );
return tuple;
}
}
/**
* Constructs a new instance that returns the average of the values encountered in the given fieldDeclaration field name.
*
* @param fieldDeclaration of type Fields
*/
public AverageFinal( Fields fieldDeclaration )
{
super( 2, makeFieldDeclaration( fieldDeclaration ) );
if( !fieldDeclaration.isSubstitution() && fieldDeclaration.size() != 1 )
throw new IllegalArgumentException( "fieldDeclaration may only declare 1 field, got: " + fieldDeclaration.size() );
}
private static Fields makeFieldDeclaration( Fields fieldDeclaration )
{
if( fieldDeclaration.hasTypes() )
return fieldDeclaration;
return fieldDeclaration.applyTypes( Double.class );
}
@Override
public void prepare( FlowProcess flowProcess, OperationCall<Context> operationCall )
{
operationCall.setContext( new Context( getFieldDeclaration() ) );
}
@Override
public void start( FlowProcess flowProcess, AggregatorCall<Context> aggregatorCall )
{
aggregatorCall.getContext().reset();
}
@Override
public void aggregate( FlowProcess flowProcess, AggregatorCall<Context> aggregatorCall )
{
Context context = aggregatorCall.getContext();
TupleEntry arguments = aggregatorCall.getArguments();
if( arguments.getObject( 0 ) == null )
{
context.nulls++;
return;
}
context.sum += arguments.getDouble( 0 );
context.count += arguments.getLong( 1 );
}
@Override
public void complete( FlowProcess flowProcess, AggregatorCall<Context> aggregatorCall )
{
aggregatorCall.getOutputCollector().add( aggregatorCall.getContext().result() );
}
}
/////////
/**
* Constructor AverageBy creates a new AverageBy instance. Use this constructor when used with a {@link cascading.pipe.assembly.AggregateBy}
* instance.
*
* @param valueField of type Fields
* @param averageField of type Fields
*/
@ConstructorProperties({"valueField", "averageField"})
public AverageBy( Fields valueField, Fields averageField )
{
super( valueField, new AveragePartials( averageField ), new AverageFinal( averageField ) );
}
/**
* Constructor AverageBy creates a new AverageBy instance. Use this constructor when used with a {@link cascading.pipe.assembly.AggregateBy}
* instance.
*
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
*/
@ConstructorProperties({"valueField", "averageField", "include"})
public AverageBy( Fields valueField, Fields averageField, Include include )
{
super( valueField, new AveragePartials( averageField, include ), new AverageFinal( averageField ) );
}
//////////////
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
*/
@ConstructorProperties({"pipe", "groupingFields", "valueField", "averageField"})
public AverageBy( Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField )
{
this( null, pipe, groupingFields, valueField, averageField, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param threshold of type int
*/
@ConstructorProperties({"pipe", "groupingFields", "valueField", "averageField", "threshold"})
public AverageBy( Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField, int threshold )
{
this( null, pipe, groupingFields, valueField, averageField, threshold );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
*/
@ConstructorProperties({"name", "pipe", "groupingFields", "valueField", "averageField"})
public AverageBy( String name, Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField )
{
this( name, pipe, groupingFields, valueField, averageField, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param threshold of type int
*/
@ConstructorProperties({"name", "pipe", "groupingFields", "valueField", "averageField", "threshold"})
public AverageBy( String name, Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField, int threshold )
{
this( name, Pipe.pipes( pipe ), groupingFields, valueField, averageField, threshold );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
*/
@ConstructorProperties({"pipes", "groupingFields", "valueField", "averageField"})
public AverageBy( Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField )
{
this( null, pipes, groupingFields, valueField, averageField, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param threshold of type int
*/
@ConstructorProperties({"pipes", "groupingFields", "valueField", "averageField", "threshold"})
public AverageBy( Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField, int threshold )
{
this( null, pipes, groupingFields, valueField, averageField, threshold );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
*/
@ConstructorProperties({"name", "pipes", "groupingFields", "valueField", "averageField"})
public AverageBy( String name, Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField )
{
this( name, pipes, groupingFields, valueField, averageField, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param threshold of type int
*/
@ConstructorProperties({"name", "pipes", "groupingFields", "valueField", "averageField", "threshold"})
public AverageBy( String name, Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField, int threshold )
{
super( name, pipes, groupingFields, valueField, new AveragePartials( averageField ), new AverageFinal( averageField ), threshold );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
*/
@ConstructorProperties({"pipe", "groupingFields", "valueField", "averageField", "include"})
public AverageBy( Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField, Include include )
{
this( null, pipe, groupingFields, valueField, averageField, include, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
* @param threshold of type int
*/
@ConstructorProperties({"pipe", "groupingFields", "valueField", "averageField", "include", "threshold"})
public AverageBy( Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField, Include include, int threshold )
{
this( null, pipe, groupingFields, valueField, averageField, include, threshold );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
*/
@ConstructorProperties({"name", "pipe", "groupingFields", "valueField", "averageField", "include"})
public AverageBy( String name, Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField, Include include )
{
this( name, pipe, groupingFields, valueField, averageField, include, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipe of type Pipe
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
* @param threshold of type int
*/
@ConstructorProperties({"name", "pipe", "groupingFields", "valueField", "averageField", "include", "threshold"})
public AverageBy( String name, Pipe pipe, Fields groupingFields, Fields valueField, Fields averageField, Include include, int threshold )
{
this( name, Pipe.pipes( pipe ), groupingFields, valueField, averageField, include, threshold );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
*/
@ConstructorProperties({"pipes", "groupingFields", "valueField", "averageField", "include"})
public AverageBy( Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField, Include include )
{
this( null, pipes, groupingFields, valueField, averageField, include, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
* @param threshold of type int
*/
@ConstructorProperties({"pipes", "groupingFields", "valueField", "averageField", "include", "threshold"})
public AverageBy( Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField, Include include, int threshold )
{
this( null, pipes, groupingFields, valueField, averageField, include, threshold );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
*/
@ConstructorProperties({"name", "pipes", "groupingFields", "valueField", "averageField", "include"})
public AverageBy( String name, Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField, Include include )
{
this( name, pipes, groupingFields, valueField, averageField, include, USE_DEFAULT_THRESHOLD );
}
/**
* Constructor AverageBy creates a new AverageBy instance.
*
* @param name of type String
* @param pipes of type Pipe[]
* @param groupingFields of type Fields
* @param valueField of type Fields
* @param averageField of type Fields
* @param include of type boolean
* @param threshold of type int
*/
@ConstructorProperties({"name", "pipes", "groupingFields", "valueField", "averageField", "include", "threshold"})
public AverageBy( String name, Pipe[] pipes, Fields groupingFields, Fields valueField, Fields averageField, Include include, int threshold )
{
super( name, pipes, groupingFields, valueField, new AveragePartials( averageField, include ), new AverageFinal( averageField ), threshold );
}
}
| 37.220503 | 156 | 0.680923 |
66edc1536d340afaf2f86bd6c6ddcfbd1bcf72eb | 4,463 | /*
* This file is generated by jOOQ.
*/
package net.stumpwiz.mrradb.model.tables;
import net.stumpwiz.mrradb.model.Keys;
import net.stumpwiz.mrradb.model.Raj;
import net.stumpwiz.mrradb.model.tables.records.BodyRecord;
import org.jooq.Record;
import org.jooq.*;
import org.jooq.impl.DSL;
import org.jooq.impl.SQLDataType;
import org.jooq.impl.TableImpl;
/**
* An organizational unit at Mercy Ridge.
*/
@SuppressWarnings({"all", "unchecked", "rawtypes"})
public class Body extends TableImpl<BodyRecord>
{
private static final long serialVersionUID = 1L;
/**
* The reference instance of <code>raj.body</code>
*/
public static final Body BODY = new Body();
/**
* The column <code>raj.body.bodyid</code>.
*/
public final TableField<BodyRecord, Long> BODYID =
createField(DSL.name("bodyid"), SQLDataType.BIGINT.nullable(false).identity(true), this, "");
/**
* The column <code>raj.body.bodyimage</code>. Name of the graphic file that represents the body in reports and web
* pages.
*/
public final TableField<BodyRecord, String> BODYIMAGE =
createField(DSL.name("bodyimage"), SQLDataType.VARCHAR(45), this,
"Name of the graphic file that represents the body in reports and web pages.");
/**
* The column <code>raj.body.name</code>.
*/
public final TableField<BodyRecord, String> NAME =
createField(DSL.name("name"), SQLDataType.VARCHAR(45).nullable(false), this, "");
/**
* The column <code>raj.body.mission</code>.
*/
public final TableField<BodyRecord, String> MISSION =
createField(DSL.name("mission"), SQLDataType.VARCHAR(512), this, "");
/**
* The column <code>raj.body.bodyprecedence</code>. Field for ordering in reports and web pages. Stored as double
* to allow insertions of new bodies.
*/
public final TableField<BodyRecord, Double> BODYPRECEDENCE =
createField(DSL.name("bodyprecedence"), SQLDataType.DOUBLE.nullable(false), this,
"Field for ordering in reports and web pages. Stored as double to allow insertions of new bodies" +
".");
/**
* Create an aliased <code>raj.body</code> table reference
*/
public Body(String alias)
{
this(DSL.name(alias), BODY);
}
private Body(Name alias, Table<BodyRecord> aliased)
{
this(alias, aliased, null);
}
private Body(Name alias, Table<BodyRecord> aliased, Field<?>[] parameters)
{
super(alias, null, aliased, parameters, DSL.comment("An organizational unit at Mercy Ridge."),
TableOptions.table());
}
/**
* Create an aliased <code>raj.body</code> table reference
*/
public Body(Name alias)
{
this(alias, BODY);
}
/**
* Create a <code>raj.body</code> table reference
*/
public Body()
{
this(DSL.name("body"), null);
}
public <O extends Record> Body(Table<O> child, ForeignKey<O, BodyRecord> key)
{
super(child, key, BODY);
}
@Override
public Body as(String alias)
{
return new Body(DSL.name(alias), this);
}
@Override
public Schema getSchema()
{
return aliased() ? null : Raj.RAJ;
}
@Override
public Identity<BodyRecord, Long> getIdentity()
{
return (Identity<BodyRecord, Long>) super.getIdentity();
}
@Override
public UniqueKey<BodyRecord> getPrimaryKey()
{
return Keys.KEY_BODY_PRIMARY;
}
@Override
public Row5<Long, String, String, String, Double> fieldsRow()
{
return (Row5) super.fieldsRow();
}
@Override
public Body as(Name alias)
{
return new Body(alias, this);
}
/**
* Rename this table
*/
@Override
public Body rename(String name)
{
return new Body(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Body rename(Name name)
{
return new Body(name, null);
}
// -------------------------------------------------------------------------
// Row5 type methods
// -------------------------------------------------------------------------
/**
* The class holding records for this type
*/
@Override
public Class<BodyRecord> getRecordType()
{
return BodyRecord.class;
}
}
| 26.408284 | 120 | 0.588618 |
79fa1b6c20801268d387564f6ce2b823e80b160b | 338 | package com.serenegiant.view;
import android.view.View;
import java.lang.annotation.Retention;
import androidx.annotation.IntDef;
import static java.lang.annotation.RetentionPolicy.SOURCE;
public class ViewUtils {
@IntDef({
View.VISIBLE,
View.INVISIBLE,
View.GONE,
})
@Retention(SOURCE)
public @interface Visibility {}
}
| 15.363636 | 58 | 0.763314 |
77cf2c7860c083dd0a8f59f43397a804901f70ed | 806 | package com.spinyowl.spinygui.core.system.event;
import com.spinyowl.spinygui.core.node.Frame;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
/** Will be generated when the specified window moves. */
@Getter
@ToString
@EqualsAndHashCode
public class SystemWindowPosEvent extends SystemEvent {
/**
* The new x-coordinate, in screen coordinates, of the upper-left corner of the content area of
* the window.
*/
private final int posX;
/**
* The new y-coordinate, in screen coordinates, of the upper-left corner of the content area of
* the window.
*/
private final int posY;
@Builder
protected SystemWindowPosEvent(Frame frame, int posX, int posY) {
super(frame);
this.posX = posX;
this.posY = posY;
}
}
| 23.705882 | 97 | 0.725806 |
522307cd6bff27ac750c2edf130ef4324b1bf3d3 | 3,349 | /**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.categorydetail.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.categorydetail.entity.CategoryDetailsEntity;
import com.thinkgem.jeesite.modules.categorydetail.service.CategoryDetailsService;
/**
* 核查项详细信息Controller
* @author wcy
* @version 2016-08-11
*/
@Controller
@RequestMapping(value = "${adminPath}/categorydetail/examineItemCategory")
public class CategoryDetailsController extends BaseController {
@Autowired
private CategoryDetailsService examineItemCategoryService;
@ModelAttribute
public CategoryDetailsEntity get(@RequestParam(required=false) String id) {
CategoryDetailsEntity entity = null;
if (StringUtils.isNotBlank(id)){
entity = examineItemCategoryService.get(id);
}
if (entity == null){
entity = new CategoryDetailsEntity();
}
return entity;
}
@RequestMapping(value = {"list", ""})
public String list(CategoryDetailsEntity categoryDetailsEntity, HttpServletRequest request, HttpServletResponse response, Model model) {
String catid = request.getParameter("catid");
if (null==catid){
catid = categoryDetailsEntity.getCategoryId();
}else {
categoryDetailsEntity.setCategoryId(catid);
}
Page<CategoryDetailsEntity> page = examineItemCategoryService.findPage(new Page<CategoryDetailsEntity>(request, response), categoryDetailsEntity);
model.addAttribute("page", page);
model.addAttribute("categoryid", catid);
return "modules/categorydetail/examineItemCategoryList";
}
@RequestMapping(value = "form")
public String form(CategoryDetailsEntity categoryDetailsEntity, Model model) {
model.addAttribute("categoryDetailsEntity", categoryDetailsEntity);
return "modules/categorydetail/examineItemCategoryForm";
}
@RequestMapping(value = "save")
public String save(CategoryDetailsEntity categoryDetailsEntity, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, categoryDetailsEntity)){
return form(categoryDetailsEntity, model);
}
examineItemCategoryService.save(categoryDetailsEntity);
addMessage(redirectAttributes, "保存核查详情成功");
return "redirect:"+Global.getAdminPath()+"/categorydetail/examineItemCategory/?repage";
}
@RequestMapping(value = "delete")
public String delete(CategoryDetailsEntity categoryDetailsEntity, RedirectAttributes redirectAttributes) {
examineItemCategoryService.delete(categoryDetailsEntity);
addMessage(redirectAttributes, "删除核查详情成功");
return "redirect:"+Global.getAdminPath()+"/categorydetail/examineItemCategory/?repage";
}
} | 39.4 | 148 | 0.805016 |
04b66f979a5c305afd054d96b9bec2abc5cfed8d | 1,387 | package src;
import java.util.LinkedList;
import java.util.Queue;
/**
* FileName: BalancedBinaryTree
* Description: 平衡二叉树
* Author: @VirtualChen
* Date: 2018/12/24 0024 下午 3:24
*/
public class BalancedBinaryTree {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return isBalancedOdRoot(root) && isBalancedOdRoot(root.left) && isBalancedOdRoot(root.right);
}
private boolean isBalancedOdRoot(TreeNode p) {
if (p == null) {
return true;
}
int leftH = TreeHeight(p.left);
int rightH = TreeHeight(p.right);
if (Math.abs(leftH - rightH) <= 1) {
return true;
}
return false;
}
private int TreeHeight(TreeNode p) {
if (p == null) {
return 0;
}
return Integer.max(TreeHeight(p.right), TreeHeight(p.left)) + 1;
}
/**
* 后序遍历+剪枝
* @param root
* @return
*/
public boolean isBalanced1(TreeNode root) {
return recur(root) != -1;
}
private int recur(TreeNode root) {
if (root == null) return 0;
int left = recur(root.left);
if(left == -1) return -1;
int right = recur(root.right);
if(right == -1) return -1;
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
}
}
| 23.116667 | 101 | 0.546503 |
d0120305d6fa42fb5d230562c5b3b26159982376 | 2,663 | /**
* Copyright (C) 2013-2019 Helical IT Solutions (http://www.helicalinsight.com) - All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helicalinsight.datasource.managed.jaxb;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Rajesh
* Created by author on 4/17/2019.
*/
@Component
@Scope("prototype")
@XmlRootElement(name = "EFWD")
@XmlAccessorType(XmlAccessType.FIELD)
public class EfwdForCe {
@XmlElement(name = "DataSources", required = false)
private DataSourcesForCe dataSources;
@XmlElement(name = "DataMaps", required = false)
private DataMaps dataMaps;
public DataSourcesForCe getDataSources() {
return dataSources;
}
public void setDataSources(DataSourcesForCe dataSources) {
this.dataSources = dataSources;
}
public DataMaps getDataMaps() {
return dataMaps;
}
public void setDataMaps(DataMaps dataMaps) {
this.dataMaps = dataMaps;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EfwdForCe efwdForCe = (EfwdForCe) o;
if (dataMaps != null ? !dataMaps.equals(efwdForCe.dataMaps) : efwdForCe.dataMaps != null) return false;
if (dataSources != null ? !dataSources.equals(efwdForCe.dataSources) : efwdForCe.dataSources != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = dataSources != null ? dataSources.hashCode() : 0;
result = 31 * result + (dataMaps != null ? dataMaps.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "EfwdForCe{" +
"dataSources=" + dataSources +
", dataMaps=" + dataMaps +
'}';
}
}
| 30.261364 | 111 | 0.666917 |
cb8d1a1f45d2cc899791605dec99b98035822235 | 3,199 | package com.trampcr.pkgnamedemo.ui.fragment;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.trampcr.pkgnamedemo.R;
import com.trampcr.pkgnamedemo.base.ui.fragment.BaseFragment;
import com.trampcr.pkgnamedemo.bean.PkgInfoBean;
import com.trampcr.pkgnamedemo.ui.adapter.ViewerListAdapter;
import com.trampcr.pkgnamedemo.util.PackageManagerWrapper;
import com.trampcr.pkgnamedemo.util.PackageUtils;
import com.trampcr.pkgnamedemo.util.VersionUtils;
import com.trampcr.pkgnamedemo.widget.dialog.PkgViewerDialog;
import java.util.ArrayList;
import java.util.List;
/**
* Created by trampcr on 2018/3/28.
* system app fragment
*/
public class SystemAppFragment extends BaseFragment implements AdapterView.OnItemClickListener {
private ListView mListView;
private ViewerListAdapter mViewerListAdapter;
private List<PkgInfoBean> mSystemPkgInfoList;
@Override
public int getContentViewResId() {
return R.layout.fragment_pkgname_viewer;
}
@Override
public void init() {
initPkgNameList();
}
@Override
public void initView() {
mListView = findViewById(R.id.list_view);
mViewerListAdapter = new ViewerListAdapter(mContext, mSystemPkgInfoList);
}
@Override
public void initListener() {
mListView.setOnItemClickListener(this);
}
@Override
public void setViewsValue() {
mListView.setAdapter(mViewerListAdapter);
}
@Override
public void onClickDispatch(View v) {
}
@Override
protected void lazyLoad() {
}
private void initPkgNameList() {
PackageManagerWrapper.init(getContext());
List<String> installedUserPkgNameList = PackageManagerWrapper.getInstalledSystemPkgNameList();
if (null == installedUserPkgNameList || installedUserPkgNameList.size() == 0) {
return;
}
mSystemPkgInfoList = new ArrayList<>();
for (String pkgName : installedUserPkgNameList) {
PkgInfoBean pkgInfoBean = new PkgInfoBean();
String appName = PackageUtils.getAppName(mContext, pkgName);
Drawable appIcon = PackageUtils.getAppIcon(mContext, pkgName);
int versionCode = VersionUtils.getVersionCode(mContext, pkgName);
String versionName = VersionUtils.getVersionName(mContext, pkgName);
pkgInfoBean.setPkgName(pkgName);
pkgInfoBean.setAppName(appName);
pkgInfoBean.setAppIcon(appIcon);
pkgInfoBean.setVersionCode(versionCode);
pkgInfoBean.setVersionName(versionName);
pkgInfoBean.setType(mContext.getString(R.string.system_app_type));
mSystemPkgInfoList.add(pkgInfoBean);
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
PkgInfoBean pkgInfoBean = (PkgInfoBean) mViewerListAdapter.getItem(i);
if (null == pkgInfoBean) {
return;
}
PkgViewerDialog pkgViewerDialog = new PkgViewerDialog(mContext);
pkgViewerDialog.showViewerDialog(pkgInfoBean);
}
}
| 30.179245 | 102 | 0.704283 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.