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
|
---|---|---|---|---|---|
a8226772b84a42787faf67705c464324dde94670 | 3,898 | /**
* (C) Copyright 2014 Whisper.io.
*
* 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: Maxime ESCOURBIAC
*/
package com.whisperio.data.jpa;
import com.whisperio.data.entity.Project;
import com.whisperio.data.entity.Release;
import com.whisperio.data.entity.Sprint;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test class for SprintController.
*
* @author Maxime ESCOURBIAC
*/
public class SprintControllerTest {
private static Project project;
private static Release release;
private static ProjectController projectController;
private static ReleaseController releaseController;
/**
* Default constructor.
*/
public SprintControllerTest() {
}
/**
* Init the test environment.
*/
@BeforeClass
public static void initContext() {
projectController = new ProjectController();
Date date = new Date();
project = new Project("Test Sprint ", "Project Sprint test.", date);
project = projectController.create(project);
releaseController = new ReleaseController();
release = new Release("Release Test Sprint", 1, date, date, 0, true, project);
release = releaseController.create(release);
}
/**
* Destroy the test environment.
*/
@AfterClass
public static void destroyContext() {
releaseController.destroy(release);
projectController.destroy(project);
}
/**
* Refresh data after each test.
*/
@After
public void refresh() {
project = projectController.refresh(project);
release = releaseController.refresh(release);
}
/**
* Test of create method, of class SprintController.
*/
@Test
public void testCreate() {
System.out.println("SprintController:Create");
SprintController sprintController = new SprintController();
Date startDate = new Date();
Date endDate = new Date();
String name = "Test Create Sprint";
int sprintNumber = 1;
boolean isActive = true;
boolean isClosed = true;
Sprint sprint = new Sprint(name, sprintNumber, startDate, endDate, isActive, isClosed, release);
Sprint sprintResult = sprintController.create(sprint);
//Check Sprint properties.
assertNotNull(sprintResult.getId());
assertEquals(name, sprintResult.getName());
assertEquals(sprintNumber, sprintResult.getSprintNumber());
assertEquals(startDate, sprintResult.getStartDate());
assertEquals(endDate, sprintResult.getEndDate());
assertEquals(isActive, sprintResult.isActive());
assertEquals(isClosed, sprintResult.isClosed());
assertEquals(release, sprintResult.getRelease());
//Check release properties.
release = releaseController.refresh(release);
assertTrue(release.getSprints().contains(sprintResult));
sprintController.destroy(sprint);
}
/**
* Test of destroy method, of class SprintController.
*/
@Test
public void testDestroy() {
System.out.println("SprintController:Destroy");
SprintController sprintController = new SprintController();
Date creationDate = new Date();
Date stopDate = new Date();
Sprint sprint = sprintController.create(new Sprint("Test Destroy Sprint", 1, creationDate, stopDate, true, true, release));
assertTrue(sprintController.destroy(sprint));
}
}
| 31.691057 | 131 | 0.67881 |
0b9b4cff4b77157103a65ab82a895c88fcbd5b4c | 4,425 | package com.example.paypro.gcm;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.example.paypro.GroupListActivity;
import com.example.paypro.R;
import com.example.paypro.data.Group;
import com.example.paypro.data.Transaction;
import com.example.paypro.dbhandler.GroupsHelper;
import com.example.paypro.dbhandler.TransactionHandler;
import com.example.paypro.dbhandler.UserHelper;
import com.example.paypro.manager.JSONHandler;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GCMNotificationIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCMNotificationIntentService";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
System.out.println("GCM Called intent..");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
Log.i(TAG, "Received: " + extras.toString());
Set<String> keys = extras.keySet();
for (String key : keys) {
if (key.equals("transaction")) {
try {
JSONObject json = new JSONObject(
extras.getString("transaction"));
Transaction transaction = (Transaction) JSONHandler
.getInstance().convertToJavaUnderscoreCase(
json.toString(), Transaction.class);
TransactionHandler th = new TransactionHandler(
getApplicationContext());
th.createTransaction(transaction);
th.close();
UserHelper uh = new UserHelper(
getApplicationContext());
String str = uh
.getUserById(transaction.getUserId())
.getDisplayName();
uh.close();
GroupsHelper gh = new GroupsHelper(
getApplicationContext());
String title = gh.getGroupById(
transaction.getGroupId()).getName();
gh.close();
sendNotification(str + ":" + transaction.display(),
title);
} catch (JSONException e) {
e.printStackTrace();
}
} else if (key.equals("group")) {
try {
JSONObject json = new JSONObject(
extras.getString("group"));
Group group = (Group) JSONHandler.getInstance()
.convertToJavaUnderscoreCase(json.toString(),
Group.class);
GroupsHelper gh = new GroupsHelper(
getApplicationContext());
gh.createGroup(group);
gh.close();
sendNotification(
"You have been added to " + group.getName()
+ " by " + group.getGroupAdminId(),
group.getName());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg, String title) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, GroupListActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
private void sendNotification(String msg) {
sendNotification(msg, "GCM Notification");
}
}
| 29.697987 | 71 | 0.709831 |
5c1b2f0f408b4ccf5b56762a7368f1e2d933fbd1 | 2,137 | /**
* File: DebugMenu.java
* Author: William Forte
* Time: 10:09:09 AM
* Date: May 16, 2016
* Project: Survival
* Package: survival.main.debug
*/
package survival.main.debug;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Comparator;
import backbone.engine.main.BackboneVector2f;
/**
* File: DebugMenu.java
* Language: Java
* Author: Will 40
* Data Created: May 16, 2016
* Time Created: 10:09:09 AM
* Project: Survival
* Package: survival.main.debug
*/
public class DebugMenu {
private ArrayList<String> lines;
private ArrayList<String> temp_lines;
// private Font font;
private BackboneVector2f pos;
private Comparator<String> stringSorter = new Comparator<String>() {
public int compare(String a, String b) {
if(a.length() > b.length()) return 1;
if(b.length() > a.length()) return -1;
return 0;
};
};
public DebugMenu(BackboneVector2f pos) {
lines = new ArrayList<String>();
temp_lines = new ArrayList<String>();
// font = new Font("Courier", Font.PLAIN, 24);
this.pos = pos;
}
public void addLine(String message) {
lines.add(message);
}
public String getBiggestLine() {
temp_lines.removeAll(temp_lines);
for(String line: lines) {
temp_lines.add(line);
}
temp_lines.sort(stringSorter);
return temp_lines.get(temp_lines.size() - 1);
}
public void render(Graphics2D g) {
g.setFont(new Font("Courier", Font.PLAIN, 22));
// g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .6f));
// g.setColor(Color.BLACK);
// g.fillRect((int) pos.xpos - 20, (int) pos.ypos - 44, BackboneUtils.stringWidth(getBiggestLine(), new Font("Verdana", Font.PLAIN, 24)) + 40, (lines.size() + 1) * 24);
// g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
g.setColor(Color.BLACK);
for(String line: lines) {
g.drawString(line, pos.xpos, pos.ypos + (lines.indexOf(line) * 22));
}
g.setColor(new Color(0xffffff));
for(String line: lines) {
g.drawString(line, pos.xpos + 1, pos.ypos + (lines.indexOf(line) * 22) + 2);
}
lines.removeAll(lines);
}
}
| 26.382716 | 169 | 0.688348 |
748892332f0e2e6032aae0a57cbcba6e71301053 | 151 | package com.ysu.zyw.tc.openapi.constant;
public abstract class TcSessionKey {
public static final String S_ACCOUNT_ID = "session_account_id";
}
| 18.875 | 67 | 0.774834 |
57d914f445b66ec528576a637eb83021608d3ef0 | 3,787 | package com.webank.wedatasphere.streamis.datasource.appconn.operation;
import com.webank.wedatasphere.dss.standard.app.development.DevelopmentService;
import com.webank.wedatasphere.dss.standard.app.development.publish.RefExportOperation;
import com.webank.wedatasphere.dss.standard.app.sso.builder.SSOUrlBuilderOperation;
import com.webank.wedatasphere.dss.standard.app.sso.origin.request.OriginSSORequestOperation;
import com.webank.wedatasphere.dss.standard.app.sso.request.SSORequestOperation;
import com.webank.wedatasphere.dss.standard.common.desc.AppInstance;
import com.webank.wedatasphere.dss.standard.common.exception.operation.ExternalOperationFailedException;
import com.webank.wedatasphere.linkis.httpclient.request.HttpAction;
import com.webank.wedatasphere.linkis.httpclient.response.HttpResult;
import com.webank.wedatasphere.streamis.datasource.appconn.action.DatasourcePostAction;
import com.webank.wedatasphere.streamis.datasource.appconn.ref.DatasourceExportRequestRef;
import com.webank.wedatasphere.streamis.datasource.appconn.ref.DatasourceExportResponseRef;
import com.webank.wedatasphere.streamis.datasource.appconn.utils.DataSourceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* created by yangzhiyue on 2021/4/13
* Description:
*/
public class DatasourceExportOperation implements RefExportOperation<DatasourceExportRequestRef, DatasourceExportResponseRef> {
private static final Logger LOGGER = LoggerFactory.getLogger(DatasourceExportOperation.class);
private String exportUrl;
private static final String EXPORT_URL = "api/rest_j/v1/streamis/exportDatasource";
private AppInstance appInstance;
private SSORequestOperation<HttpAction, HttpResult> ssoRequestOperation;
private DevelopmentService developmentService;
public DatasourceExportOperation(AppInstance appInstance){
this.appInstance = appInstance;
exportUrl = this.appInstance.getBaseUrl().endsWith("/") ? this.appInstance.getBaseUrl() + EXPORT_URL :
this.appInstance.getBaseUrl() + "/" + EXPORT_URL;
ssoRequestOperation = new OriginSSORequestOperation(DataSourceUtils.DATASOURCE_APP_NAME.getValue());
}
@Override
public DatasourceExportResponseRef exportRef(DatasourceExportRequestRef datasourceExportRequestRef) throws ExternalOperationFailedException {
LOGGER.info("begin to export datasource from streamis, request is {}", datasourceExportRequestRef);
try{
SSOUrlBuilderOperation ssoUrlBuilderOperation = datasourceExportRequestRef.getWorkspace().getSSOUrlBuilderOperation().copy();
ssoUrlBuilderOperation.setAppName(DataSourceUtils.DATASOURCE_APP_NAME.getValue());
ssoUrlBuilderOperation.setReqUrl(this.exportUrl);
ssoUrlBuilderOperation.setWorkspace(datasourceExportRequestRef.getWorkspace().getWorkspaceName());
DatasourcePostAction datasourcePostAction = new DatasourcePostAction(ssoUrlBuilderOperation.getBuiltUrl(), datasourceExportRequestRef.getUser());
datasourcePostAction.addRequestPayload("streamisTableMetaId", datasourceExportRequestRef.getTableMetaId());
HttpResult httpResult = this.ssoRequestOperation.requestWithSSO(ssoUrlBuilderOperation, datasourcePostAction);
LOGGER.info("end to export datasource from streamis, response is {}", httpResult.getResponseBody());
return new DatasourceExportResponseRef(httpResult.getResponseBody());
}catch(final Exception e){
throw new ExternalOperationFailedException(300601, "failed to export ref ", e);
}
}
@Override
public void setDevelopmentService(DevelopmentService developmentService) {
this.developmentService = developmentService;
}
}
| 51.175676 | 157 | 0.796409 |
bb98f35864d025ac38709bb7921d072b86f84420 | 7,002 | package org.springframework.contrib.gae.search.metadata.impl;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.contrib.gae.search.IndexType;
import org.springframework.contrib.gae.search.SearchIndex;
import org.springframework.contrib.gae.search.metadata.IndexTypeRegistry;
import org.springframework.contrib.gae.search.metadata.SearchFieldMetadata;
import java.lang.reflect.Method;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
public class MethodSearchFieldMetadataTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private IndexTypeRegistry indexTypeRegistry;
@Test
public void constructWithSpecificType() throws Exception {
Method member = TestClass.class.getMethod("stringMethod");
SearchFieldMetadata searchFieldMetadata = new MethodSearchFieldMetadata(TestClass.class, member, IndexType.IDENTIFIER);
assertThat(searchFieldMetadata.getEntityType()).isEqualTo(TestClass.class);
assertThat(searchFieldMetadata.getMember()).isEqualTo(member);
assertThat(searchFieldMetadata.getMemberType()).isEqualTo(String.class);
assertThat(searchFieldMetadata.getMemberName()).isEqualTo("stringMethod");
assertThat(searchFieldMetadata.getIndexName()).isEqualTo(new MethodNameCalculator().apply(member));
assertThat(searchFieldMetadata.getEncodedName()).isEqualTo(new FieldNameEncoder().apply(searchFieldMetadata.getMemberName()));
Assertions.assertThat(searchFieldMetadata.getIndexType()).isEqualTo(IndexType.IDENTIFIER);
assertThat(searchFieldMetadata.getValue(new TestClass())).isEqualTo("stringValue");
}
@Test
public void constructWithTypeLookup() throws Exception {
Method member = TestClass.class.getMethod("stringMethod");
when(indexTypeRegistry.apply(String.class)).thenReturn(IndexType.TEXT);
SearchFieldMetadata searchFieldMetadata = new MethodSearchFieldMetadata(TestClass.class, member, indexTypeRegistry);
assertThat(searchFieldMetadata.getEntityType()).isEqualTo(TestClass.class);
assertThat(searchFieldMetadata.getMember()).isEqualTo(member);
assertThat(searchFieldMetadata.getMemberType()).isEqualTo(String.class);
assertThat(searchFieldMetadata.getMemberName()).isEqualTo("stringMethod");
assertThat(searchFieldMetadata.getIndexName()).isEqualTo(new MethodNameCalculator().apply(member));
assertThat(searchFieldMetadata.getEncodedName()).isEqualTo(new FieldNameEncoder().apply(searchFieldMetadata.getMemberName()));
Assertions.assertThat(searchFieldMetadata.getIndexType()).isEqualTo(IndexType.TEXT);
assertThat(searchFieldMetadata.getValue(new TestClass())).isEqualTo("stringValue");
}
@Test
public void constructWithUnannotatedMethod() throws Exception {
Method member = TestClass.class.getMethod("unannotatedMethod");
when(indexTypeRegistry.apply(String.class)).thenReturn(IndexType.TEXT);
SearchFieldMetadata searchFieldMetadata = new MethodSearchFieldMetadata(TestClass.class, member, indexTypeRegistry);
assertThat(searchFieldMetadata.getEntityType()).isEqualTo(TestClass.class);
assertThat(searchFieldMetadata.getMember()).isEqualTo(member);
assertThat(searchFieldMetadata.getMemberType()).isEqualTo(String.class);
assertThat(searchFieldMetadata.getMemberName()).isEqualTo("unannotatedMethod");
assertThat(searchFieldMetadata.getIndexName()).isEqualTo(new MethodNameCalculator().apply(member));
assertThat(searchFieldMetadata.getEncodedName()).isEqualTo(new FieldNameEncoder().apply(searchFieldMetadata.getMemberName()));
Assertions.assertThat(searchFieldMetadata.getIndexType()).isEqualTo(IndexType.TEXT);
assertThat(searchFieldMetadata.getValue(new TestClass())).isEqualTo("unannotatedValue");
}
@Test
public void constructWithAutoType() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Cannot construct an SearchFieldMetadata with index type AUTO. Use an IndexTypeRegistry instead.");
Method member = TestClass.class.getMethod("stringMethod");
new MethodSearchFieldMetadata(TestClass.class, member, IndexType.AUTO);
}
@Test
public void constructWithNamedMember() throws Exception {
Method member = TestClass.class.getMethod("namedMethod");
SearchFieldMetadata searchFieldMetadata = new MethodSearchFieldMetadata(TestClass.class, member, IndexType.IDENTIFIER);
assertThat(searchFieldMetadata.getEntityType()).isEqualTo(TestClass.class);
assertThat(searchFieldMetadata.getMember()).isEqualTo(member);
assertThat(searchFieldMetadata.getMemberType()).isEqualTo(String.class);
assertThat(searchFieldMetadata.getMemberName()).isEqualTo(new MethodNameCalculator().apply(member));
assertThat(searchFieldMetadata.getIndexName()).isEqualTo(new FieldNameEncoder().apply(searchFieldMetadata.getMemberName()));
Assertions.assertThat(searchFieldMetadata.getIndexType()).isEqualTo(IndexType.IDENTIFIER);
assertThat(searchFieldMetadata.getValue(new TestClass())).isEqualTo("namedMethodValue");
}
@Test
public void constructWithTypedMember() throws Exception {
Method member = TestClass.class.getMethod("typedMethod");
SearchFieldMetadata searchFieldMetadata = new MethodSearchFieldMetadata(TestClass.class, member, indexTypeRegistry);
assertThat(searchFieldMetadata.getEntityType()).isEqualTo(TestClass.class);
assertThat(searchFieldMetadata.getMember()).isEqualTo(member);
assertThat(searchFieldMetadata.getMemberType()).isEqualTo(String.class);
assertThat(searchFieldMetadata.getMemberName()).isEqualTo(new MethodNameCalculator().apply(member));
assertThat(searchFieldMetadata.getIndexName()).isEqualTo(new FieldNameEncoder().apply(searchFieldMetadata.getMemberName()));
Assertions.assertThat(searchFieldMetadata.getIndexType()).isEqualTo(IndexType.GEOPOINT);
assertThat(searchFieldMetadata.getValue(new TestClass())).isEqualTo("typedMethodValue");
}
private static class TestClass {
@SearchIndex
public String stringMethod() {
return "stringValue";
}
public String unannotatedMethod() {
return "unannotatedValue";
}
@SearchIndex(name = "myMethod")
public String namedMethod() {
return "namedMethodValue";
}
@SearchIndex(type = IndexType.GEOPOINT)
public String typedMethod() {
return "typedMethodValue";
}
}
} | 49.309859 | 134 | 0.75507 |
46f0c8c8e73a7355697fc7c3dc43b870ccce4278 | 277 | package ru.mail.polis.dao.shkalev;
import org.jetbrains.annotations.NotNull;
import ru.mail.polis.dao.DAO;
import java.io.IOException;
import java.nio.ByteBuffer;
public interface AdvancedDAO extends DAO {
Row getRow(@NotNull final ByteBuffer key) throws IOException;
}
| 23.083333 | 65 | 0.794224 |
a98fb8fe25c7146a63e6557e88d8bd0e70f6e95b | 5,028 | package com.tud.alexw.visualplacerecognition;
import android.content.Context;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;
import com.segway.robot.sdk.locomotion.head.Head;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
/**
* Utility class with static methods for conversion, text colouring, and memory status logging
*/
public class Utils {
public static String TAG = "Utils";
/**
* Log maximum, available and allocated heap memory in MB
*/
public static void logMemory(){
final Runtime runtime = Runtime.getRuntime();
final long used_heap_memory_mb = (runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long max_heap_memory_mb = runtime.maxMemory() / 1048576L;
final long available_heap_memory_mb = max_heap_memory_mb - used_heap_memory_mb;
Log.i(TAG, String.format("%d MB of %d MB of heap memory allocated. %d MB available.", used_heap_memory_mb, max_heap_memory_mb, available_heap_memory_mb));
}
/**
* Checks if storage structure i.e. folders are created. If not creates it. Throws IO exception, if folder couldn't be created
* @param context Application context required for storage location
* @return if storage structure is created after calling this method
* @throws IOException
*/
public static boolean isStorageStructureCreated(Context context) throws IOException {
// Get the directory for the app's private pictures directory.
File file = context.getExternalFilesDir(null);
if(!file.exists()){
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
throw new IOException(TAG + "Couldn't create folder! ");
}
else{
Log.i(TAG ,"Directory created: " + file.getAbsolutePath());
return false;
}
}
else{
Log.i(TAG ,"Exists already!: " + file.getAbsolutePath());
return true;
}
}
/**
* Convert a linked list to an array
* @param linkedList the linked list
* @param <T> type of the elemts within the linked list
* @return
*/
public static <T> Object[] linkedListToArray(LinkedList<T> linkedList){
Object[] array = linkedList.toArray();
return array;
}
/**
* Appends an HTML text in a new line to given textview
* @param textView the text view to write to
* @param msg the message (can be HTML)
*/
public static void addText(TextView textView, String msg){
msg = msg.replace("\n", "<br/>");
textView.append(Html.fromHtml("<br/>" + msg));
}
/**
* Appends an HTML text in a new line to given textview in red
* @param textView the text view to write to
* @param msg the message (can be HTML)
*/
public static void addTextRed(TextView textView, String msg){
msg = msg.replace("\n", "<br/>");
textView.append(Html.fromHtml( "<br/>" + red(msg)));
}
/**
* Appends an HTML text in a new line to given textview; all numbers within message are displayed blue
* @param textView the text view to write to
* @param msg the message (can be HTML)
*/
public static void addTextNumbersBlue(TextView textView, String msg){
msg = msg.replace("\n", "<br/>");
msg = msg.replaceAll("(\\d)", blue("$1"));
textView.append(Html.fromHtml("<br/>" + msg));
}
/**
* Add HTML font colour blue to message
* @param msg message
* @return coloured HTML message
*/
public static String blue(String msg){
return "<font color=#42baff>" + msg +"</font>";
}
/**
* Add HTML font colour red to message
* @param msg message
* @return coloured HTML message
*/
public static String red(String msg){
return "<font color=#ff0000>" + msg +"</font>";
}
/**
* Transforms degrees to radian
* @param degree degree value
* @return corresponding radian value
*/
public static float degreeToRad(int degree){
return (float) (degree * Math.PI/180);
}
/**
* Transforms radian to degree
* @param rad radian value
* @return corresponding degree value
*/
public static int radToDegree(float rad){
return (int) (rad* 180/Math.PI);
}
/**
* Compares two degrees in a soft way (5° deviation allowed). Soft comparison, since robot head measurements "wiggle" a little. High value of 5° set for fast head movement.
* @param deg1 degree value to compare
* @param deg2 degree value to compare
* @return whether the two values are close
*/
public static boolean isClose(int deg1, int deg2){
boolean result = Math.abs(deg1 - deg2) < 5;
if(!result){
Log.v(TAG, String.format("%d° != %d°", deg1, deg2));
}
return result;
}
}
| 33.298013 | 176 | 0.622116 |
243285801533d2680ed6fa8641dc6a2590f75003 | 553 | package com.seudev.simple_posts.module.api.mapper;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.jboss.resteasy.spi.DefaultOptionsMethodException;
@Provider
@ApplicationScoped
public class DefaultOptionsMethodExceptionMapper implements ExceptionMapper<DefaultOptionsMethodException> {
@Override
public Response toResponse(DefaultOptionsMethodException ex) {
return Response.ok()
.build();
}
}
| 26.333333 | 108 | 0.790235 |
b4610243dc9f2efa909be27a2b1076894791f71b | 1,845 | package br.com.abc.javacore.jdbc.test;
import java.util.Scanner;
public class TesteCRUD {
private static Scanner teclado = new Scanner(System.in);
public static void main(String[] args) {
int op;
while (true) {
menu();
op = Integer.parseInt(teclado.nextLine());
if (op == 0) {
System.out.println("saindo do sistema..");
break;
}
if (op == 1) {
menuComprador();
op = Integer.parseInt(teclado.nextLine());
CompradorCRUD.executar(op);
}
if (op == 2) {
menuCarro();
op = Integer.parseInt(teclado.nextLine());
CarroCRUD.executar(op);
}
}
}
private static void menu() {
System.out.println("Selecione uma opcao");
System.out.println("1. Para comprador");
System.out.println("2. Para carro");
System.out.println("0. Para SAIR");
}
private static void menuComprador() {
System.out.println("Digite a opção para comecar");
System.out.println("1. Inserir comprado");
System.out.println("2. Atualizar comprador");
System.out.println("3. Listar todos os compradores");
System.out.println("4. Buscar comprador por nome");
System.out.println("5. Deletar");
System.out.println("9. Voltar");
}
private static void menuCarro() {
System.out.println("Digite a opção para comecar");
System.out.println("1. Inserir carro");
System.out.println("2. Atualizar carro");
System.out.println("3. Listar todos os carros");
System.out.println("4. Buscar carro por nome");
System.out.println("5. Deletar");
System.out.println("9. Voltar");
}
}
| 32.368421 | 61 | 0.55122 |
657e6e8b7587489e8e3f6aae00bd8f84767ba17b | 682 | import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
// Max of two numbers
System.out.print("Enter two numbers to find the max among them -: ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
if (x > y) {
System.out.println("The max number among " + x + " and " + y + " is " + x);
}
if (x < y) {
System.out.println("The max number among " + x + " and " + y + " is " + y);
}
if (x == y) {
System.out.println("Both " + x + " and " + y + " are equal");
}
}
}
| 32.47619 | 87 | 0.489736 |
78cba681e8595409141458c21421a81b18dada5d | 10,492 | package org.sagebionetworks.repo.web.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.sagebionetworks.repo.model.Entity;
import org.sagebionetworks.repo.model.ErrorResponse;
import org.sagebionetworks.repo.util.JSONEntityUtil;
import org.sagebionetworks.schema.adapter.JSONEntity;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.schema.adapter.org.json.EntityFactory;
import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
public class JSONEntityHttpMessageConverter implements HttpMessageConverter<JSONEntity> {
private static final String UTF_8 = "UTF-8";
private static final String CONCRETE_TYPE = "concreteType";
private static final String ENTITY_TYPE = "entityType";
private List<MediaType> supportedMedia;
/**
* When set to true, this message converter will attempt to convert any object to JSON.
*/
boolean convertAnyRequestToJson = false;
/**
* When set to true, this message converter will attempt to convert any object to JSON
* regardless of the requested type.
*
* @param convertAnyRequestToJson
*/
public void setConvertAnyRequestToJson(boolean convertAnyRequestToJson) {
this.convertAnyRequestToJson = convertAnyRequestToJson;
}
public JSONEntityHttpMessageConverter() {
supportedMedia = new ArrayList<MediaType>();
supportedMedia.add(MediaType.APPLICATION_JSON);
supportedMedia.add(MediaType.TEXT_PLAIN);
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
// Does the class implement JSONEntity a JSONEntity?
if(!JSONEntityUtil.isJSONEntity(clazz)) return false;
// Are we converting any request to json?
if(convertAnyRequestToJson) return true;
// Is the requested type a json type?
return isJSONType(mediaType);
}
public static boolean isJSONType(MediaType type){
if(type == null) return false;
if(type.getType() == null) return false;
if(type.getSubtype() == null) return false;
if(!"application".equals(type.getType().toLowerCase())) return false;
if(!"json".equals(type.getSubtype().toLowerCase())) return false;
return true;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return MediaType.TEXT_PLAIN.includes(mediaType) ||
(isJSONType(mediaType) && JSONEntityUtil.isJSONEntity(clazz));
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return supportedMedia;
}
// This is specified by HTTP 1.1
private static final Charset HTTP_1_1_DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
// This is the character set used by Synapse if the client does not specify one
private static final Charset SYNAPSE_DEFAULT_CHARSET = Charset.forName(UTF_8);
@Override
public JSONEntity read(Class<? extends JSONEntity> clazz, HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
// First read the string
Charset charsetForDeSerializingBody = inputMessage.getHeaders().getContentType().getCharset();
if (charsetForDeSerializingBody==null) {
// HTTP 1.1 says that the default is ISO-8859-1
charsetForDeSerializingBody = HTTP_1_1_DEFAULT_CHARSET;
}
String jsonString = JSONEntityHttpMessageConverter.readToString(inputMessage.getBody(), charsetForDeSerializingBody);
try {
return EntityFactory.createEntityFromJSONString(jsonString, clazz);
} catch (JSONObjectAdapterException e) {
// Try to convert entity type to a concrete type and try again. See PLFM-2079.
try {
JSONObject jsonObject = new JSONObject(jsonString);
if(jsonObject.has(ENTITY_TYPE)){
// get the entity type so we can replace it with concrete type
String type = jsonObject.getString(ENTITY_TYPE);
jsonObject.remove(ENTITY_TYPE);
jsonObject.put(CONCRETE_TYPE, type);
jsonString = jsonObject.toString();
// try again
return EntityFactory.createEntityFromJSONString(jsonString, clazz);
}else{
// Something else went wrong
throw new HttpMessageNotReadableException(e.getMessage(), e);
}
} catch (JSONException e1) {
throw new HttpMessageNotReadableException(e1.getMessage(), e);
} catch (JSONObjectAdapterException e2) {
throw new HttpMessageNotReadableException(e2.getMessage(), e);
}
}
}
/**
* Read a string from an input stream
*
* @param in
* @return
* @throws IOException
*/
public static String readToString(InputStream in, Charset charSet)
throws IOException {
if(in == null) throw new IllegalArgumentException("No content to map to Object due to end of input");
try {
if(charSet == null){
charSet = Charset.forName(UTF_8);
}
BufferedInputStream bufferd = new BufferedInputStream(in);
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
int index = -1;
while ((index = bufferd.read(buffer, 0, buffer.length)) > 0) {
builder.append(new String(buffer, 0, index, charSet));
}
return builder.toString();
} finally {
in.close();
}
}
/**
* Read a string from an input stream
*
* @param in
* @return
* @throws IOException
*/
public static String readToString(Reader reader) throws IOException {
if(reader == null) throw new IllegalArgumentException("Reader cannot be null");
try {
char[] buffer = new char[1024];
StringBuilder builder = new StringBuilder();
int index = -1;
while ((index = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, index);
}
return builder.toString();
} finally {
reader.close();
}
}
/**
* Write a string to an oupt stream
* @param toWrite
* @param out
* @param charSet
* @throws IOException
*/
public static long writeToStream(String toWrite, OutputStream out, Charset charSet) throws IOException {
try {
if(charSet == null){
charSet = Charset.forName(UTF_8);
}
BufferedOutputStream bufferd = new BufferedOutputStream(out);
byte[] bytes = toWrite.getBytes(charSet);
bufferd.write(bytes);
bufferd.flush();
return bytes.length;
} finally {
out.close();
}
}
@Override
public void write(JSONEntity entity, final MediaType contentType,
HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
// First write the entity to a JSON string
try {
MediaType contentTypeForResponseHeader = contentType;
if (contentTypeForResponseHeader.isWildcardType() || contentTypeForResponseHeader.isWildcardSubtype()) {
// this will leave the character set unspecified, but we fill that in below
contentTypeForResponseHeader = MediaType.APPLICATION_JSON;
}
Charset charsetForSerializingBody = contentTypeForResponseHeader.getCharset();
if (charsetForSerializingBody==null) {
charsetForSerializingBody = SYNAPSE_DEFAULT_CHARSET;
// Let's make it explicit in the response header
contentTypeForResponseHeader = new MediaType(
contentTypeForResponseHeader.getType(),
contentTypeForResponseHeader.getSubtype(),
charsetForSerializingBody
);
}
HttpHeaders headers = outputMessage.getHeaders();
headers.setContentType(contentTypeForResponseHeader);
String jsonString;
if (contentTypeForResponseHeader.includes(MediaType.TEXT_PLAIN)) {
jsonString = convertEntityToPlainText(entity);
} else {
jsonString = EntityFactory.createJSONStringForEntity(entity);
}
long length = JSONEntityHttpMessageConverter.writeToStream(jsonString, outputMessage.getBody(), charsetForSerializingBody);
if (headers.getContentLength() == -1) {
headers.setContentLength(length);
}
} catch (JSONObjectAdapterException e) {
throw new HttpMessageNotWritableException(e.getMessage(), e);
}
}
public static String convertEntityToPlainText(JSONEntity entity) throws JSONObjectAdapterException {
if (entity instanceof ErrorResponse) {
return ((ErrorResponse)entity).getReason();
} else {
return EntityFactory.createJSONStringForEntity(entity);
}
}
/**
* Read an entity from the reader.
* @param reader
* @return
* @throws IOException
* @throws JSONObjectAdapterException
*/
public static Entity readEntity(Reader reader) throws IOException, JSONObjectAdapterException {
// First read in the string
String jsonString = readToString(reader);
// Read it into an adapter
JSONObjectAdapter adapter = new JSONObjectAdapterImpl(jsonString);
return createEntityFromeAdapter(adapter);
}
/**
* There are many things that can go wrong with this and we want to make sure the error messages
* are always meaningful.
* @param adapter
* @return
* @throws JSONObjectAdapterException
*/
public static Entity createEntityFromeAdapter(JSONObjectAdapter adapter)
throws JSONObjectAdapterException {
// Get the entity type
String typeClassName = adapter.getString("concreteType");
if(typeClassName==null){
throw new IllegalArgumentException("Cannot determine the entity type. The entityType property is null");
}
// Create a new instance using the full class name
Entity newInstance = null;
try {
//
Class<? extends Entity> entityClass = (Class<? extends Entity>) Class.forName(typeClassName);
newInstance = entityClass.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException("Unknown entity type: "+typeClassName+". Message: "+e.getMessage());
}
// Populate the new instance with the JSON.
newInstance.initializeFromJSONObject(adapter);
return newInstance;
}
}
| 35.687075 | 127 | 0.730461 |
2e7ae00133a4bb8d41571888880887c05988f027 | 586 | package io.github.leovr.rtipmidi;
import io.github.leovr.rtipmidi.messages.MidiCommandHeader;
import io.github.leovr.rtipmidi.model.MidiMessage;
public interface AppleMidiMessageListener {
/**
* This method is called when a new MIDI message from the origin server is received
*
* @param midiCommandHeader The MIDI command meta information
* @param message The MIDI message
* @param timestamp Timestamp of this MIDI message
*/
void onMidiMessage(MidiCommandHeader midiCommandHeader, MidiMessage message, final int timestamp);
}
| 34.470588 | 102 | 0.735495 |
7ba76bc731175deee4f0ecc317ce97ef05921105 | 1,716 | /*
* Copyright 2013-2020 Bloomreach Inc. (http://www.bloomreach.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bloomreach.forge.settings.management.config;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.wicket.model.LoadableDetachableModel;
import org.hippoecm.frontend.session.UserSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LoadableDetachableConfigModel
*/
public abstract class LoadableDetachableConfigModel<T> extends LoadableDetachableModel<T> {
private final Logger log = LoggerFactory.getLogger(this.getClass());
public CMSFeatureConfig getConfig() {
return (CMSFeatureConfig)getObject();
}
protected Node getConfigNode(final String path) {
try {
final Session jcrSession = UserSession.get().getJcrSession();
if (jcrSession.nodeExists(path)) {
return jcrSession.getNode(path);
}
} catch (RepositoryException e) {
log.error("Error trying to retrieve configuration node at {}", path);
}
log.info("No configuration found at {}", path);
return null;
}
}
| 31.777778 | 91 | 0.70979 |
ed054f83035a13da1707022fd0fbaa879f09330f | 2,637 | /*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.ballerinalang.net.transport.contract.config;
import org.ballerinalang.net.transport.contract.Constants;
import org.junit.Assert;
import org.testng.annotations.Test;
import java.util.HashMap;
/**
* A unit test class for Transport module ServerBootstrapConfiguration class functions.
*/
public class ServerBootstrapConfigurationTest {
@Test
public void testIsKeepAlive() {
ServerBootstrapConfiguration serverBootstrapConfiguration = new ServerBootstrapConfiguration(new HashMap<>());
Assert.assertTrue(serverBootstrapConfiguration.isKeepAlive());
HashMap<String, Object> properties = new HashMap<>();
properties.put(Constants.SERVER_BOOTSTRAP_KEEPALIVE, false);
serverBootstrapConfiguration = new ServerBootstrapConfiguration(properties);
Assert.assertFalse(serverBootstrapConfiguration.isKeepAlive());
}
@Test
public void testIsSocketReuse() {
ServerBootstrapConfiguration serverBootstrapConfiguration = new ServerBootstrapConfiguration(new HashMap<>());
Assert.assertFalse(serverBootstrapConfiguration.isSocketReuse());
HashMap<String, Object> properties = new HashMap<>();
properties.put(Constants.SERVER_BOOTSTRAP_SO_REUSE, true);
serverBootstrapConfiguration = new ServerBootstrapConfiguration(properties);
Assert.assertTrue(serverBootstrapConfiguration.isSocketReuse());
}
@Test
public void testGetSoTimeout() {
ServerBootstrapConfiguration serverBootstrapConfiguration = new ServerBootstrapConfiguration(new HashMap<>());
Assert.assertEquals(serverBootstrapConfiguration.getSoTimeOut(), 15);
HashMap<String, Object> properties = new HashMap<>();
properties.put(Constants.SERVER_BOOTSTRAP_SO_TIMEOUT, 10);
serverBootstrapConfiguration = new ServerBootstrapConfiguration(properties);
Assert.assertEquals(serverBootstrapConfiguration.getSoTimeOut(), 10);
}
}
| 39.954545 | 118 | 0.751612 |
0bb921cb64e6b7fcf669afed14232f2b9556e00e | 2,605 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fr.service.management.helpers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
/**
*
* @author zouhairhajji
*/
public class ZkHelper {
public static void znode_create(ZooKeeper zooKeeper, String path, byte[] data) throws KeeperException, InterruptedException {
zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
// Method to check existence of znode and its status, if znode is available.
public static Stat znode_exists_stat(ZooKeeper zooKeeper, String path) throws KeeperException, InterruptedException {
return zooKeeper.exists(path, true);
}
public static Boolean znode_exists(ZooKeeper zooKeeper, String path) throws KeeperException, InterruptedException {
return zooKeeper.exists(path, true) != null;
}
// Method to update the data in a znode. Similar to getData but without watcher.
public static void znode_update(ZooKeeper zooKeeper, String path, byte[] data) throws KeeperException, InterruptedException {
zooKeeper.setData(path, data, zooKeeper.exists(path, true).getVersion());
}
public static byte[] znode_getData(ZooKeeper zooKeeper, String path) throws KeeperException, InterruptedException {
byte[] bn = zooKeeper.getData(path, false, null);
return bn;
}
public static List<String> znode_childrens(ZooKeeper zooKeeper, String path) throws KeeperException, InterruptedException {
List<String> childrens = zooKeeper.getChildren(path, false);
return childrens;
}
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
}
| 38.308824 | 129 | 0.742418 |
4c04d31eedd45723d298c9c3762c000e6ce7a4a5 | 751 | package com.webapp.timeline.sns.domain;
import lombok.*;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@Table(name = "newsfeed")
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Newsfeed {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "postId", nullable = false)
private int postId;
@Column(name = "category", nullable = false)
private String category;
@Column(name = "sender")
private String sender;
@Column(name = "receiver", nullable = false)
private String receiver;
@Column(name = "lastUpdate")
private Timestamp lastUpdate;
@Column(name = "commentId", nullable = true)
private long commentId;
}
| 19.25641 | 55 | 0.691079 |
79d1a36ba87b0711c2743b39885625cecfb46525 | 296 | package com.flarebyte.cm.com.order;
import com.flarebyte.cm.com.core.Concept;
import com.flarebyte.cm.com.core.dc.vocabulary.Property;
public interface SalesTaxPolicy extends Concept {
public Float getRateAsFloat(Property property);
public TaxationType getTaxationType(Property property);
}
| 26.909091 | 56 | 0.820946 |
80d8b1ad35d4862864b16d54b866718bded05fa6 | 944 | package org.eugene.mod.collection;
import java.util.List;
public class ListTest {
public static void main(String[] args) {
List<Integer> emptyList = List.of();
List<Integer> luckyNumber = List.of(19);
List<String> vowels = List.of("A", "E", "I", "O", "U");
System.out.println("emptyList = " + emptyList);
System.out.println("singletonList = " + luckyNumber);
System.out.println("vowels = " + vowels);
try {
List<Integer> list = List.of(1, 2, null, 3);
} catch (Exception e) {
System.out.println("Nulls not allowed in List.of().");
}
try {
luckyNumber.add(8);
} catch (Exception e) {
System.out.println("Cannot add an element.");
}
try {
luckyNumber.remove(0);
} catch (Exception e) {
System.out.println("Cannot remove an element.");
}
}
}
| 28.606061 | 66 | 0.536017 |
1158e6bab19ebe98762b2de87d9435578dabe4c5 | 5,001 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package com.google.crypto.tink;
import static com.google.crypto.tink.TestUtil.assertExceptionContains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.crypto.tink.config.TinkConfig;
import com.google.crypto.tink.mac.MacKeyTemplates;
import com.google.crypto.tink.proto.KeyTemplate;
import com.google.crypto.tink.proto.Keyset;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for CleartextKeysetHandle. */
@RunWith(JUnit4.class)
public class CleartextKeysetHandleTest {
@BeforeClass
public static void setUp() throws GeneralSecurityException {
TinkConfig.register();
}
@Test
public void testParse() throws Exception {
// Create a keyset that contains a single HmacKey.
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle = KeysetHandle.generateNew(template);
Keyset keyset = CleartextKeysetHandle.getKeyset(handle);
handle = CleartextKeysetHandle.parseFrom(keyset.toByteArray());
assertEquals(keyset, handle.getKeyset());
handle.getPrimitive(Mac.class);
}
@Test
public void testRead() throws Exception {
// Create a keyset that contains a single HmacKey.
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetManager manager = KeysetManager.withEmptyKeyset().rotate(template);
Keyset keyset1 = manager.getKeysetHandle().getKeyset();
KeysetHandle handle1 =
CleartextKeysetHandle.read(BinaryKeysetReader.withBytes(keyset1.toByteArray()));
assertEquals(keyset1, handle1.getKeyset());
KeysetHandle handle2 = KeysetHandle.generateNew(template);
Keyset keyset2 = handle2.getKeyset();
assertEquals(1, keyset2.getKeyCount());
Keyset.Key key2 = keyset2.getKey(0);
assertEquals(keyset2.getPrimaryKeyId(), key2.getKeyId());
assertEquals(template.getTypeUrl(), key2.getKeyData().getTypeUrl());
Mac unused = handle2.getPrimitive(Mac.class);
}
@Test
public void testWrite() throws Exception {
// Create a keyset that contains a single HmacKey.
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle = KeysetManager.withEmptyKeyset().rotate(template).getKeysetHandle();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
KeysetWriter writer = BinaryKeysetWriter.withOutputStream(outputStream);
CleartextKeysetHandle.write(handle, writer);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
KeysetReader reader = BinaryKeysetReader.withInputStream(inputStream);
KeysetHandle handle2 = CleartextKeysetHandle.read(reader);
assertEquals(handle.getKeyset(), handle2.getKeyset());
}
@Test
public void testReadInvalidKeyset() throws Exception {
// Create a keyset that contains a single HmacKey.
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetManager manager = KeysetManager.withEmptyKeyset().rotate(template);
Keyset keyset = manager.getKeysetHandle().getKeyset();
byte[] proto = keyset.toByteArray();
proto[0] = (byte) ~proto[0];
try {
KeysetHandle unused = CleartextKeysetHandle.read(BinaryKeysetReader.withBytes(proto));
fail("Expected IOException");
} catch (IOException e) {
// expected
}
}
@Test
public void testVoidInputs() throws Exception {
KeysetHandle unused;
try {
unused = CleartextKeysetHandle.read(BinaryKeysetReader.withBytes(new byte[0]));
fail("Expected GeneralSecurityException");
} catch (GeneralSecurityException e) {
assertExceptionContains(e, "empty keyset");
}
try {
unused = CleartextKeysetHandle.read(BinaryKeysetReader.withBytes(new byte[0]));
fail("Expected GeneralSecurityException");
} catch (GeneralSecurityException e) {
assertExceptionContains(e, "empty keyset");
}
try {
unused = CleartextKeysetHandle.parseFrom(new byte[0]);
fail("Expected GeneralSecurityException");
} catch (GeneralSecurityException e) {
assertExceptionContains(e, "empty keyset");
}
}
}
| 37.886364 | 93 | 0.736653 |
2c7d0711ec4bd20f0f808deb3f083b0b582ac29f | 15,920 | package com.github.sparkzxl.workflow.domain.service.driver;
import cn.hutool.core.date.DatePattern;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.sparkzxl.core.utils.DateUtils;
import com.github.sparkzxl.core.utils.ListUtils;
import com.github.sparkzxl.patterns.factory.BusinessStrategyFactory;
import com.github.sparkzxl.patterns.strategy.BusinessHandler;
import com.github.sparkzxl.workflow.application.service.act.IProcessRepositoryService;
import com.github.sparkzxl.workflow.application.service.act.IProcessRuntimeService;
import com.github.sparkzxl.workflow.application.service.act.IProcessTaskService;
import com.github.sparkzxl.workflow.application.service.driver.IProcessDriveService;
import com.github.sparkzxl.workflow.application.service.ext.IExtHiTaskStatusService;
import com.github.sparkzxl.workflow.application.service.ext.IExtProcessStatusService;
import com.github.sparkzxl.workflow.domain.model.DriveProcess;
import com.github.sparkzxl.workflow.domain.repository.IExtProcessUserRepository;
import com.github.sparkzxl.workflow.dto.*;
import com.github.sparkzxl.workflow.infrastructure.constant.WorkflowConstants;
import com.github.sparkzxl.workflow.infrastructure.convert.ActivitiDriverConvert;
import com.github.sparkzxl.workflow.infrastructure.entity.ExtHiTaskStatus;
import com.github.sparkzxl.workflow.infrastructure.entity.ExtProcessStatus;
import com.github.sparkzxl.workflow.infrastructure.enums.ProcessStatusEnum;
import com.github.sparkzxl.workflow.infrastructure.utils.ActivitiUtils;
import com.github.sparkzxl.workflow.interfaces.dto.process.ProcessNextTaskDTO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* description: 流程驱动 服务 实现类
*
* @author charles.zhou
* @date 2020-07-17 16:27:58
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class ProcessDriveServiceImpl implements IProcessDriveService {
private final IExtHiTaskStatusService extHiTaskStatusService;
private final IExtProcessStatusService extProcessStatusService;
private final IProcessRepositoryService processRepositoryService;
private final IProcessRuntimeService processRuntimeService;
private final IProcessTaskService processTaskService;
private final BusinessStrategyFactory businessStrategyFactory;
private final IExtProcessUserRepository processUserRepository;
@Override
public DriverResult driveProcess(DriverProcessParam driverProcessParam) {
int actType = driverProcessParam.getActType();
BusinessHandler<DriverResult, DriveProcess> processBusinessHandler =
this.businessStrategyFactory.getStrategy(WorkflowConstants.BusinessTaskStrategy.BUSINESS_TASK_DRIVER,
String.valueOf(actType));
DriveProcess driveProcess = ActivitiDriverConvert.INSTANCE.convertDriveProcess(driverProcessParam);
return processBusinessHandler.execute(driveProcess);
}
@Override
public UserNextTask getNextUserTask(String processInstanceId, Integer actType) {
Task currentTask = processTaskService.getLatestTaskByProInstId(processInstanceId);
List<UserTask> userTasks = Lists.newArrayList();
//获取BpmnModel对象
BpmnModel bpmnModel = processRepositoryService.getBpmnModel(currentTask.getProcessDefinitionId());
//获取Process对象
Process process = bpmnModel.getProcesses().get(bpmnModel.getProcesses().size() - 1);
//获取所有的FlowElement信息
Collection<FlowElement> flowElements = process.getFlowElements();
//获取当前节点信息
FlowElement flowElement = ActivitiUtils.getFlowElementById(currentTask.getTaskDefinitionKey(), flowElements);
Map<String, Object> variables = Maps.newHashMap();
variables.put("actType", actType == null ? WorkflowConstants.WorkflowAction.SUBMIT : actType);
ActivitiUtils.getNextNode(flowElements, flowElement, variables, userTasks);
log.info("userTasks = {}", userTasks);
List<UserNextTask> userNextTasks = Lists.newArrayList();
if (ListUtils.isNotEmpty(userTasks)) {
userTasks.forEach(item -> {
UserNextTask userNextTask = new UserNextTask();
userNextTask.setAssignee(item.getAssignee());
userNextTask.setOwner(item.getOwner());
userNextTask.setPriority(item.getPriority());
Optional.ofNullable(item.getDueDate()).ifPresent(x -> userNextTask.setDueDate(
DateUtils.formatDate(x, DatePattern.NORM_DATETIME_PATTERN)));
userNextTask.setBusinessCalendarName(item.getBusinessCalendarName());
userNextTask.setCandidateUsers(item.getCandidateUsers());
List<String> candidateGroups = item.getCandidateGroups();
userNextTask.setCandidateGroups(candidateGroups);
List<WorkflowUserInfo> userList = processUserRepository.findUserByRoleIds(candidateGroups);
String candidateUserNames = userList.stream().map(WorkflowUserInfo::getName).collect(Collectors.joining("/"));
userNextTask.setCandidateUserInfos(userList);
userNextTask.setCandidateUserNames(candidateUserNames);
userNextTask.setTaskDefKey(item.getId());
userNextTask.setTaskName(item.getName());
userNextTasks.add(userNextTask);
});
return userNextTasks.stream().sorted(Comparator.comparing(UserNextTask::getTaskDefKey).reversed()).collect(Collectors.toList()).get(0);
}
return null;
}
@Override
public List<UserNextTask> getNextUserTask(ProcessNextTaskDTO processNextTaskDTO) {
Task currentTask = processTaskService.getLatestTaskByProInstId(processNextTaskDTO.getProcessInstanceId());
List<UserTask> userTasks = Lists.newArrayList();
//获取BpmnModel对象
BpmnModel bpmnModel = processRepositoryService.getBpmnModel(currentTask.getProcessDefinitionId());
//获取Process对象
Process process = bpmnModel.getProcesses().get(bpmnModel.getProcesses().size() - 1);
//获取所有的FlowElement信息
Collection<FlowElement> flowElements = process.getFlowElements();
//获取当前节点信息
FlowElement flowElement = ActivitiUtils.getFlowElementById(currentTask.getTaskDefinitionKey(), flowElements);
ActivitiUtils.getNextNode(flowElements, flowElement, processNextTaskDTO.getVariables(), userTasks);
log.info("userTasks = {}", userTasks);
List<UserNextTask> userNextTasks = Lists.newArrayList();
if (ListUtils.isNotEmpty(userTasks)) {
userTasks.forEach(item -> {
UserNextTask userNextTask = new UserNextTask();
userNextTask.setAssignee(item.getAssignee());
userNextTask.setOwner(item.getOwner());
userNextTask.setPriority(item.getPriority());
userNextTask.setDueDate(DateUtils.formatDate(item.getDueDate(), DatePattern.NORM_DATETIME_PATTERN));
userNextTask.setBusinessCalendarName(item.getBusinessCalendarName());
userNextTask.setCandidateUsers(item.getCandidateUsers());
userNextTask.setCandidateGroups(item.getCandidateGroups());
userNextTask.setTaskDefKey(item.getId());
userNextTask.setTaskName(item.getName());
userNextTasks.add(userNextTask);
});
}
return userNextTasks;
}
@Override
public BusTaskInfo busTaskInfo(String businessId, String processDefinitionKey) {
BusTaskInfo busTaskInfo = new BusTaskInfo();
busTaskInfo.setProcessDefinitionKey(processDefinitionKey);
busTaskInfo.setBusinessId(businessId);
ProcessInstance processInstance = processRuntimeService.getProcessInstanceByBusinessId(businessId);
Map<Object, Object> actionMap = Maps.newHashMap();
if (ObjectUtils.isNotEmpty(processInstance)) {
actionMap.put(WorkflowConstants.WorkflowAction.SUBMIT, "提交");
actionMap.put(WorkflowConstants.WorkflowAction.AGREE, "同意");
actionMap.put(WorkflowConstants.WorkflowAction.JUMP, "跳转");
actionMap.put(WorkflowConstants.WorkflowAction.REJECTED, "驳回");
actionMap.put(WorkflowConstants.WorkflowAction.ROLLBACK, "回退");
actionMap.put(WorkflowConstants.WorkflowAction.END, "结束");
Task lastTask = processTaskService.getLatestTaskByProInstId(processInstance.getProcessInstanceId());
List<IdentityLink> identityLinks = processTaskService.getIdentityLinksForTask(lastTask.getId());
List<String> candidateGroupList = Lists.newArrayList();
List<String> assigneeList = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(identityLinks)) {
identityLinks.forEach(identityLink -> {
if (StringUtils.isNoneEmpty(identityLink.getGroupId())) {
candidateGroupList.add(identityLink.getGroupId());
}
if (StringUtils.isNoneEmpty(identityLink.getUserId())) {
assigneeList.add(identityLink.getUserId());
}
});
}
List<WorkflowUserInfo> userList = processUserRepository.findUserByRoleIds(candidateGroupList);
String candidateUserNames = userList.stream().map(WorkflowUserInfo::getName).collect(Collectors.joining("/"));
UserNextTask userNextTask = new UserNextTask();
userNextTask.setTaskId(lastTask.getId());
userNextTask.setAssignee(ListUtils.listToString(assigneeList));
userNextTask.setOwner(lastTask.getOwner());
userNextTask.setPriority(String.valueOf(lastTask.getPriority()));
userNextTask.setDueDate(lastTask.getDueDate());
userNextTask.setCandidateUserInfos(userList);
userNextTask.setCandidateUserNames(candidateUserNames);
userNextTask.setCandidateGroups(candidateGroupList);
userNextTask.setTaskDefKey(lastTask.getTaskDefinitionKey());
userNextTask.setTaskName(lastTask.getName());
busTaskInfo.setCurrentUserTask(userNextTask);
} else {
actionMap.put(WorkflowConstants.WorkflowAction.START, "启动");
}
busTaskInfo.setActTypeMap(actionMap);
return busTaskInfo;
}
@Override
public List<BusTaskInfo> busTaskInfoList(String processDefinitionKey, List<String> businessIds) {
List<BusTaskInfo> busTaskInfoList = Lists.newArrayList();
businessIds.forEach(x -> busTaskInfoList.add(busTaskInfo(x, processDefinitionKey)));
return busTaskInfoList;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean suspendProcess(ModifyProcessDTO modifyProcessDTO) {
LambdaUpdateWrapper<ExtProcessStatus> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
lambdaUpdateWrapper.set(ExtProcessStatus::getStatus, ProcessStatusEnum.SUSPEND.getDesc());
if (modifyProcessDTO.getType().equals(1)) {
lambdaUpdateWrapper.eq(ExtProcessStatus::getBusinessId, modifyProcessDTO.getBusinessId());
processRuntimeService.suspendProcess(modifyProcessDTO.getBusinessId());
} else {
lambdaUpdateWrapper.eq(ExtProcessStatus::getProcessInstanceId, modifyProcessDTO.getProcessInstanceId());
processRuntimeService.suspendProcessInstanceById(modifyProcessDTO.getProcessInstanceId());
}
extProcessStatusService.update(lambdaUpdateWrapper);
return true;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean activateProcessInstance(ModifyProcessDTO modifyProcessDTO) {
LambdaUpdateWrapper<ExtProcessStatus> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
lambdaUpdateWrapper.set(ExtProcessStatus::getStatus, ProcessStatusEnum.RUN_TIME.getDesc());
if (modifyProcessDTO.getType().equals(1)) {
lambdaUpdateWrapper.eq(ExtProcessStatus::getBusinessId, modifyProcessDTO.getBusinessId());
processRuntimeService.activateProcessInstanceByBusinessId(modifyProcessDTO.getBusinessId());
} else {
lambdaUpdateWrapper.eq(ExtProcessStatus::getProcessInstanceId, modifyProcessDTO.getProcessInstanceId());
processRuntimeService.activateProcessInstanceByProcInsId(modifyProcessDTO.getProcessInstanceId());
}
extProcessStatusService.update(lambdaUpdateWrapper);
return true;
}
@Override
public void deleteProcessInstance(String businessId, String deleteReason) {
ProcessInstance processInstance = processRuntimeService.getProcessInstanceByBusinessId(businessId);
if (ObjectUtils.isNotEmpty(processInstance)) {
String processInstanceId = processInstance.getProcessInstanceId();
processRuntimeService.deleteProcessInstance(processInstanceId, deleteReason);
extHiTaskStatusService.remove(new LambdaUpdateWrapper<ExtHiTaskStatus>().eq(ExtHiTaskStatus::getProcessInstanceId,
processInstanceId));
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteProcessInstanceBatch(ProcessInstanceDeleteDTO processInstanceDeleteDTO) {
if (processInstanceDeleteDTO.getType().equals(1)) {
if (CollectionUtils.isNotEmpty(processInstanceDeleteDTO.getBusinessIds())) {
processInstanceDeleteDTO.getBusinessIds().forEach(businessId -> deleteProcessInstance(businessId, processInstanceDeleteDTO.getDeleteReason()));
}
} else {
if (CollectionUtils.isNotEmpty(processInstanceDeleteDTO.getProcessInstanceIds())) {
processInstanceDeleteDTO.getProcessInstanceIds().forEach(processInstanceId -> deleteProcessByProcInsId(processInstanceId, processInstanceDeleteDTO.getDeleteReason()));
}
}
return Boolean.TRUE;
}
@Override
public boolean suspendProcessByProcessInstanceId(String processInstanceId) {
return false;
}
@Override
public void deleteProcessByProcInsId(String processInstanceId, String deleteReason) {
ProcessInstance processInstance = processRuntimeService.getProcessInstance(processInstanceId);
if (ObjectUtils.isNotEmpty(processInstance)) {
processRuntimeService.deleteProcessInstance(processInstanceId, deleteReason);
}
extHiTaskStatusService.remove(new LambdaUpdateWrapper<ExtHiTaskStatus>().eq(ExtHiTaskStatus::getProcessInstanceId,
processInstanceId));
extProcessStatusService.remove(new LambdaUpdateWrapper<ExtProcessStatus>().eq(ExtProcessStatus::getProcessInstanceId,
processInstanceId));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteProcessByProcInsIds(List<String> processInstanceIds) {
if (CollectionUtils.isNotEmpty(processInstanceIds)) {
processInstanceIds.forEach(processInstanceId -> deleteProcessByProcInsId(processInstanceId, "删除流程"));
}
return true;
}
}
| 54.896552 | 183 | 0.730716 |
8533ffc83f896ea43d711fdf4f3a83791f4a3559 | 2,609 | package dev.cheos.armorpointspp.core.render;
import dev.cheos.armorpointspp.core.IRenderComponent;
import dev.cheos.armorpointspp.core.RenderContext;
import dev.cheos.armorpointspp.core.RenderableText;
import dev.cheos.armorpointspp.core.RenderableText.Alignment;
import dev.cheos.armorpointspp.core.adapter.IConfig.BooleanOption;
import dev.cheos.armorpointspp.core.adapter.IConfig.IntegerOption;
public class DebugTextComponent implements IRenderComponent {
private static RenderableText right = new RenderableText("this should be left and red with no shadow").withAlignment(Alignment.LEFT ).withColor(0xff0000).withShadow(false);
private static RenderableText center = new RenderableText("this should be centered and green" ).withAlignment(Alignment.CENTER).withColor(0x00ff00);
private static RenderableText left = new RenderableText("this should be right and blue" ).withAlignment(Alignment.RIGHT ).withColor(0x0000ff);
@Override
public boolean render(RenderContext ctx) {
if (!ctx.shouldRender() || !ctx.config.bool(BooleanOption.DEBUG))
return false;
ctx.profiler.push("appp.debugText");
float maxHp = ctx.data.maxHealth();
float absorb = ctx.data.absorption();
int hpRows = ctx.math.ceil((maxHp + absorb) / 20F);
ctx.renderer.text(ctx.poseStack, "armor should be here (vanilla)", ctx.x, ctx.y, 0xff0000);
ctx.renderer.text(ctx.poseStack, "hp: " + maxHp , 5, 5, 0xffffff);
ctx.renderer.text(ctx.poseStack, "rows: " + hpRows, 5, 15, 0xffffff);
ctx.renderer.text(ctx.poseStack, "armor = 0" , ctx.x, ctx.y - 40, ctx.config.hex(IntegerOption.TEXT_COLOR_ARMOR_0 ));
ctx.renderer.text(ctx.poseStack, "armor < 25", ctx.x, ctx.y - 30, ctx.config.hex(IntegerOption.TEXT_COLOR_ARMOR_LT25));
ctx.renderer.text(ctx.poseStack, "armor = 25", ctx.x, ctx.y - 20, ctx.config.hex(IntegerOption.TEXT_COLOR_ARMOR_EQ25));
ctx.renderer.text(ctx.poseStack, "armor > 25", ctx.x, ctx.y - 10, ctx.config.hex(IntegerOption.TEXT_COLOR_ARMOR_GT25));
right .render(ctx.poseStack, ctx.renderer, ctx.x, ctx.y - 60);
center.render(ctx.poseStack, ctx.renderer, ctx.x, ctx.y - 70);
left .render(ctx.poseStack, ctx.renderer, ctx.x, ctx.y - 80);
new RenderableText("R")
.withColor(0xff0000)
.withAlignment(Alignment.CENTER)
.append(
new RenderableText("G")
.withColor(0x00ff00)
.append(
new RenderableText("B")
.withColor(0x0000ff)))
.append(
new RenderableText("A")
.withColor(0xffffff)
.withShadow(false))
.render(ctx.poseStack, ctx.renderer, ctx.x, ctx.y - 50);
return popReturn(ctx, true);
}
}
| 47.436364 | 175 | 0.730548 |
b5da1a2fbc885fc2b4598148c829dc0aa1cbca66 | 2,898 | package es.us.oauthclient.patches;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
import com.google.api.client.http.HttpResponse;
/**
* @author resinas
*
*/
public class MyAuthCodeInstalledApp extends AuthorizationCodeInstalledApp {
public MyAuthCodeInstalledApp(AuthorizationCodeFlow flow, VerificationCodeReceiver receiver) {
super( flow, receiver );
}
@Override
public Credential authorize(String userId) throws IOException {
try {
Credential credential = getFlow().loadCredential(userId);
if (credential != null
&& (credential.getRefreshToken() != null
|| credential.getExpiresInSeconds() == null || credential
.getExpiresInSeconds() > 60)) {
return credential;
}
// open in browser
String redirectUri = getReceiver().getRedirectUri();
AuthorizationCodeRequestUrl authorizationUrl = getFlow()
.newAuthorizationUrl().setRedirectUri(redirectUri);
onAuthorization(authorizationUrl);
// receive authorization code and exchange it for an access token
String code = getReceiver().waitForCode();
HttpResponse httpresponse = getFlow().newTokenRequest(code)
.setRedirectUri(redirectUri).executeUnparsed();
String resp = httpresponse.parseAsString();
TokenResponse response;
try {
response = getFlow().getJsonFactory().createJsonParser(resp)
.parse(TokenResponse.class);
} catch (Exception e) {
response = tryAltResponseParsing(resp);
}
// store credential and return it
return getFlow().createAndStoreCredential(response, userId);
} finally {
getReceiver().stop();
}
}
private TokenResponse tryAltResponseParsing(String resp) {
TokenResponse tokenResponse = new TokenResponse();
String TOKEN_REGEX = "access_token=([^&]+).*expires=([^&]+)";
String CHARSET = "UTF-8";
Matcher matcher = Pattern.compile(TOKEN_REGEX).matcher(resp);
try {
if (matcher.find()) {
String token;
token = URLDecoder.decode(matcher.group(1), CHARSET);
String expires = URLDecoder.decode(matcher.group(2), CHARSET);
tokenResponse.setAccessToken(token);
tokenResponse.setExpiresInSeconds(Long.parseLong(expires));
} else {
throw new RuntimeException("Invalid response: " + resp);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Invalid response: " + resp, e);
}
return tokenResponse;
}
}
| 32.2 | 95 | 0.745342 |
c36b7a16b947f1ce07458b086b3fc15558d70c37 | 150 | package rosetta;
public class MDC_PRESS_BLD_VEN_UMB_MEAN {
public static final String VALUE = "MDC_PRESS_BLD_VEN_UMB_MEAN";
}
| 16.666667 | 68 | 0.7 |
be0eafa54d214a575091a898e451b6df60bd1f95 | 972 |
package xy.reflect.ui.util;
import java.util.Arrays;
/**
* Simple generic getter/setter class that stores the accessed value in an
* array.
*
* @author olitank
*
* @param <T> The type that is accessed.
*/
public class ArrayAccessor<T> extends Accessor<T> {
protected T[] arrayValue;
public ArrayAccessor(T[] arrayValue) {
super();
this.arrayValue = arrayValue;
}
@Override
public T get() {
return arrayValue[0];
}
@Override
public void set(T t) {
arrayValue[0] = t;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(arrayValue);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ArrayAccessor<?> other = (ArrayAccessor<?>) obj;
if (!Arrays.equals(arrayValue, other.arrayValue))
return false;
return true;
}
}
| 16.758621 | 74 | 0.659465 |
d7b9d2e99a503d8ce12f956692a1f34bc728f649 | 3,073 | /*******************************************************************************
* MIT License
*
* Copyright (c) 2017 CNES
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
package fr.cnes.encoding.binary;
import java.io.InputStream;
import fr.cnes.encoding.base.Reader;
public class InputStreamReader implements Reader {
private InputStream is;
private byte[] buffer;
private int index;
private int size;
public InputStreamReader(InputStream is, byte[] buffer) {
this.is = is;
this.buffer = buffer;
index = 0;
size = 0;
}
public int getUnsignedVarInt() throws Exception {
int value = 0;
int i;
int b;
for (i = 0; ((b = getByte()) & 0x80) != 0; i += 7) {
value |= (b & 0x7f) << i;
}
return value | b << i;
}
private void read(int byteNumber) throws Exception {
size = 0;
int i = 0;
while (i < byteNumber) {
i += is.read(buffer, size, buffer.length - size);
size += i;
}
}
public byte getByte() throws Exception {
if (index == size) {
read(1);
}
return buffer[index++];
}
public String getString(int length) throws Exception {
return new String(getByteArray(length), Binary.utf8);
}
public byte[] getByteArray(int length) throws Exception {
byte[] res = new byte[length];
int remaining = size - index;
int offset = 0;
while (remaining < length) {
System.arraycopy(buffer, index, res, offset, remaining);
index = size;
length -= remaining;
offset += remaining;
if (length > buffer.length) {
read(buffer.length);
} else {
read(length);
}
remaining = size - index;
}
System.arraycopy(buffer, index, res, offset, length);
return res;
}
public boolean getBoolean() throws Exception {
return getByte() == Binary.TRUE;
}
}
| 30.127451 | 83 | 0.607224 |
526319282f77736b08f00691ba180b3fba1223c9 | 1,184 | package com.example.learn.model;
import java.util.ArrayList;
public class WeekClass {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getClassPlace() {
return classPlace;
}
public void setClassPlace(String classPlace) {
this.classPlace = classPlace;
}
public String getClassWeek() {
return classWeek;
}
public void setClassWeek(String classWeek) {
this.classWeek = classWeek;
}
public String getClassNum() {
return classNum;
}
public void setClassNum(String classNum) {
this.classNum = classNum;
}
public String getMatchWeek() {
return matchWeek;
}
public void setMatchWeek(String matchWeek) {
this.matchWeek = matchWeek;
}
public String getTeatherName() {
return teatherName;
}
public void setTeatherName(String teatherName) {
this.teatherName = teatherName;
}
private String className;
private String teatherName;
private String classPlace;
private String classWeek;
private String classNum;
private String matchWeek;
private String id;
}
| 20.77193 | 49 | 0.73902 |
cee1fe4b7263ab5f549bf3dba08d8591b7d1113b | 1,080 | package codetest.LeetCode.BitOperation;
/*
* [461] Hamming Distance
*
* https://leetcode.com/problems/hamming-distance/description/
*
* algorithms
* Easy (69.46%)
* Total Accepted: 197.4K
* Total Submissions: 284K
* Testcase Example: '1\n4'
*
* The Hamming distance between two integers is the number of positions at
* which the corresponding bits are different.
*
* Given two integers x and y, calculate the Hamming distance.
*
* Note:
* 0 ≤ x, y < 231.
*
*
* Example:
*
* Input: x = 1, y = 4
*
* Output: 2
*
* Explanation:
* 1 (0 0 0 1)
* 4 (0 1 0 0)
* ↑ ↑
*
* The above arrows point to positions where the corresponding bits are
* different.
*
*
*/
public class HammingDistance_461 {
public int hammingDistance(int x, int y) {
int cnt = 0;
while (x != 0 || y != 0)
{
int a = x & 0x1;
int b = y & 0x1;
if (a != b)
{
cnt++;
}
x = x >> 1;
y = y >> 1;
}
return cnt;
}
}
| 19.285714 | 74 | 0.517593 |
d007495f5c2e87bd68b966cda52422e798ce0247 | 2,491 | package com.omigost.localaws.budgets.collector.sources;
import com.amazonaws.services.budgets.model.CalculatedSpend;
import com.amazonaws.services.budgets.model.Spend;
import com.omigost.localaws.budgets.aws.BudgetService;
import com.omigost.localaws.budgets.collector.DataCollectorService;
import com.omigost.localaws.budgets.collector.DataSource;
import com.omigost.localaws.budgets.collector.DataSourcePublisher;
import com.omigost.localaws.budgets.collector.model.BudgetCostMeasurement;
import com.omigost.localaws.budgets.model.Budget;
import com.omigost.localaws.budgets.repository.BudgetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.Random;
@Component
public class FakeSource implements DataSource {
private String name;
@Autowired
DataCollectorService dataCollectorService;
@Autowired
BudgetService budgetService;
@Autowired
private BudgetRepository budgets;
private Random random;
public FakeSource() {
random = new Random();
}
@Override
public void onDataFetch(final DataSourcePublisher publisher) {
for(Budget b : budgets.findAllBy()) {
final double spend = random.nextDouble()*2*b.getBudgetLimit().getAmount().doubleValue();
final double forecastedSpend = random.nextDouble()*2*b.getBudgetLimit().getAmount().doubleValue();
publisher.publishPoint(
BudgetCostMeasurement
.builder()
.budgetName(b.getName())
.actualSpend(spend)
.forecastedSpend(forecastedSpend)
.build()
);
b.setCalculatedSpend(
new CalculatedSpend()
.withActualSpend(
new Spend()
.withAmount(BigDecimal.valueOf(spend))
.withUnit("USD")
)
.withForecastedSpend(
new Spend()
.withAmount(BigDecimal.valueOf(forecastedSpend))
.withUnit("USD")
)
);
budgets.save(b);
}
}
@Override
public void setBeanName(final String name) {
this.name = name;
}
}
| 33.662162 | 110 | 0.606182 |
bb9bbd8391a1e95e63991de35266cbb7f5ea4da1 | 621 | package info.kfgodel.diamond.objects;
/**
* This type serves as a test object for field accessors
* Created by kfgodel on 23/10/14.
*/
public class FieldAccessorTestObject {
private int privateField;
int defaultField;
protected int protectedField;
public int publicField;
public int getPrivateField() {
return privateField;
}
public void setPrivateField(int privateField) {
this.privateField = privateField;
}
public int getPublicField() {
return publicField;
}
public int setPublicField(int publicField) {
this.publicField = publicField;
return this.publicField;
}
}
| 20.032258 | 56 | 0.726248 |
4e74fb4143d426496632d5dd95bb94f6364d827b | 12,904 | package Database;
import UDM.api.UDMClient;
import UDM.models.*;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import org.codehaus.jackson.map.ObjectMapper;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.sql.*;
public class DatabaseConnection {
private Statement stmt;
//create a db connection to execute queries
public DatabaseConnection() {
try {
Class.forName("com.mysql.jdbc.Driver") ;
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/udm?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey","root","1") ;
this.stmt = conn.createStatement() ;
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
//returns the registered AMF's info with given UE id
public Response retrieveAmfRegistrationInfo(long ueId){
System.out.println("REQUEST: \nInfo: Retrieve AMF Registration Info");
System.out.println("RESPONSE SENT: \nInfo: ");
try {
if(ueInfoExist(ueId)){
return getServiceInfo(ueId);
}
else{
System.out.println("User with ueId: "+ ueId +" does not exist");
ProblemDetails pd = new ProblemDetails();
pd.setTitle("User with ueId: "+ ueId +" does not exist");
pd.setStatus(404);
pd.addParam("IMSI","There is no UE with imsi: " + ueId +" in UDR");
return Response.status(404)
.entity(pd)
.build();
}
} catch (SQLException e) {
return getResponseSQLException(e);
}
}
//add new AMF registration info
public Response insertAmfRegistrationInfo(Amf3GppAccessRegistration amfInfo, long ueId){
System.out.println("REQUEST: \nInfo: Insert AMF Registration Info");
System.out.println("RESPONSE SENT: \nInfo: ");
try {
boolean amfInfoExist = amfInfoExist(amfInfo.getAmfId());
boolean ueInfoExist = ueInfoExist(ueId);
if(amfInfoExist && ueInfoExist){
Amf3GppAccessRegistration tmpAmfInfo = getAmf3GppAccessRegistrationInfo(ueId);
if(tmpAmfInfo!=null){
if(tmpAmfInfo.getAmfId() != amfInfo.getAmfId())
{
DeregistrationData x = new DeregistrationData("UE_REGISTRATION_AREA_CHANGE");
String deregCallbackUri = tmpAmfInfo.getDeregCallbackUri();
deregistrationNotification(deregCallbackUri,x);
}
return updateServiceInfo(amfInfo,ueId);
}
else{
return createServiceInfo(amfInfo,ueId);
}
}
else{
System.out.println("No entry found with given ID in UDR");
ProblemDetails pd = new ProblemDetails();
pd.setTitle("ID not found");
pd.setStatus(404);
pd.setCause("No entry found with given ID in UDR");
if(!ueInfoExist){
pd.addParam("IMSI","There is no UE with imsi: " + ueId +" in UDR");
}
if (!amfInfoExist) {
pd.addParam("amfId","There is no AMF with amfId: "+ amfInfo.getAmfId() +" in UDR");
}
return Response.status(404)
.entity(pd)
.build();
}
} catch (SQLException e) {
return getResponseSQLException(e);
}
}
//updates the AMf registration info for given UE id
private Response updateServiceInfo(Amf3GppAccessRegistration amfInfo,long ueId) throws SQLException {
System.out.println("REQUEST: \nInfo: Update AMF Registration Info");
System.out.println("RESPONSE SENT: \nInfo: ");
String query = " UPDATE givesservice "+
" SET amfId = " + amfInfo.getAmfId()+","+
" pei = " + amfInfo.getPei() +","+
" deregCallbackUri= '" + amfInfo.getDeregCallbackUri()+
"'WHERE imsi = " + ueId;
System.out.println("Amf Registration Info Updated");
return getResponse(amfInfo, query);
}
private Response createServiceInfo(Amf3GppAccessRegistration amfInfo, long ueId) {
String query = "INSERT INTO givesservice (amfId,imsi,pei,deregCallbackUri)" +
"VALUES ("+amfInfo.getAmfId()+ ","+
ueId +","+
amfInfo.getPei()+",'"+
amfInfo.getDeregCallbackUri()+"')";
try {
stmt.execute(query);
System.out.println("AMF Registration Info Created");
return Response.status(201)
.entity(amfInfo)
.build();
} catch (SQLException e) {
return getResponseSQLException(e);
}
}
private Response getServiceInfo(long ueId) throws SQLException {
Amf3GppAccessRegistration amfInfo = getAmf3GppAccessRegistrationInfo(ueId);
if(amfInfo==null){
System.out.println("There is no service registration info for User Equipment with Imsi: "+ueId);
ProblemDetails pd = new ProblemDetails();
pd.setTitle("There is no service registration info for User Equipment with Imsi: "+ueId);
pd.setStatus(404);
return Response.status(404)
.entity(pd)
.build();
}
else
{
System.out.println("AMF Info Successfully Returned");
return Response.accepted()
.entity(amfInfo)
.build();
}
}
//checks if AMF exists with given id
private boolean amfInfoExist(long amfId) throws SQLException {
String selectquery = "SELECT * FROM amf WHERE amfId = " + amfId;
ResultSet rs = stmt.executeQuery(selectquery);
if(rs.next()){
return true;
}
else{
return false;
}
}
//checks if UE exists with given imsi
private boolean ueInfoExist(long imsi) throws SQLException {
String selectquery = "SELECT * FROM ue WHERE imsi = "+imsi;
ResultSet rs = stmt.executeQuery(selectquery);
if(rs.next()){
return true;
}
else{
return false;
}
}
private Amf3GppAccessRegistration getAmf3GppAccessRegistrationInfo(long ueId) throws SQLException {
String selectquery = "SELECT * FROM givesservice WHERE imsi = " + ueId;
ResultSet rs = stmt.executeQuery(selectquery);
if(rs.next()){
return new Amf3GppAccessRegistration(rs.getLong("amfId"),rs.getLong("pei"),rs.getString("deregCallbackUri"));
}
else{
return null;
}
}
public Response insertSmfRegistrationInfo(SmfRegistration smfRegistrationInfo,long ueId, long pduSessionId){
try {
System.out.println("REQUEST: \nInfo: Insert SMF Registration Info");
System.out.println("RESPONSE SENT: \nInfo: ");
boolean ueInfoExist = ueInfoExist(ueId);
if(ueInfoExist){
SmfRegistration tmpSmfInfo = getSmfRegistrationInfo(ueId, smfRegistrationInfo.getPduSessionId());
if(tmpSmfInfo!=null){
return updateSmfServiceInfo(smfRegistrationInfo,ueId,pduSessionId);
}
else{
return createSmfServiceInfo(smfRegistrationInfo,ueId,pduSessionId);
}
}
else{
System.out.println("User (SUPI) does not exist");
ProblemDetails pd = new ProblemDetails();
pd.setTitle("ID not found");
pd.setStatus(404);
pd.setCause("No entry found with given ID in UDR");
pd.addParam("imsi","User (SUPI) does not exist");
return Response.status(404)
.entity(pd)
.build();
}
} catch (SQLException e) {
return getResponseSQLException(e);
}
}
private Response updateSmfServiceInfo(SmfRegistration smfRegistrationInfo, long ueId, long pduSessionId) throws SQLException {
String query = " UPDATE smfRegistration "+
" SET smfId = " + smfRegistrationInfo.getSmfId()+","+
" pduSessionId = " + pduSessionId +","+
" dnn = '" + smfRegistrationInfo.getDnn()+
"'WHERE imsi = " + ueId + " AND " + " pduSessionId = " + pduSessionId;
System.out.println("Serving SMF UPDATED for PDU Session with id: " + pduSessionId);
return getResponse(smfRegistrationInfo, query);
}
private Response createSmfServiceInfo(SmfRegistration smfRegistrationInfo, long ueId, long pduSessionId) throws SQLException {
String query = "INSERT INTO smfRegistration (smfId,imsi,pduSessionId,dnn)" +
"VALUES ("+ smfRegistrationInfo.getSmfId()+ ","+
ueId +","+
pduSessionId+",'"+
smfRegistrationInfo.getDnn()+"')";
stmt.execute(query);
System.out.println("SMF Registration Info Created");
return Response.status(201)
.entity(smfRegistrationInfo)
.build();
}
private SmfRegistration getSmfRegistrationInfo(long ueId , long pduSessionId) throws SQLException {
String selectquery = "SELECT * FROM smfRegistration WHERE imsi = " + ueId + " AND " + " pduSessionId = " + pduSessionId ;
ResultSet rs = stmt.executeQuery(selectquery);
if(rs.next()){
return new SmfRegistration(rs.getLong("smfId"),rs.getLong("pduSessionId"),rs.getString("dnn"));
}
else{
return null;
}
}
public Response deleteSmfRegistrationInfo(long ueId, long pduSessionId) {
String query = "DELETE FROM smfRegistration WHERE imsi = " + ueId + " AND " + " pduSessionId = " + pduSessionId ;
System.out.println("REQUEST: \nInfo: DELETE SMF Registration Info");
System.out.println("RESPONSE SENT: \nInfo: ");
try {
stmt.execute(query);
} catch (SQLException e) {
return getResponseSQLException(e);
}
System.out.println("SMF DEREGISTERED for PDU Session with Id : "+pduSessionId);
return Response.status(204)
.build();
}
private Response getResponse(Object amfInfo, String query) throws SQLException {
if(stmt.executeUpdate(query)==1) {
System.out.println("Successfull");
return Response.accepted()
.entity(amfInfo)
.build();
}
else{
ProblemDetails pd = new ProblemDetails();
pd.setTitle("Problem occurred while updating serving AMF");
return Response.status(404)
.entity(pd)
.build();
}
}
private Response getResponseSQLException(SQLException e) {
System.out.println("SQL Exception");
e.printStackTrace();
ProblemDetails pd = new ProblemDetails();
pd.setTitle("SQL Exception");
pd.setStatus(404);
return Response.status(404)
.entity(pd.toString())
.build();
}
public void deregistrationNotification(String deregCallbackUri, DeregistrationData deregistrationData){
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
Object mapper = new ObjectMapper();
String json;
try {
OkHttpClient client = UDMClient.getUnsafeOkHttpClient();
json = ((ObjectMapper) mapper).writeValueAsString(deregistrationData);
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(deregCallbackUri)
.post(body)
.build();
com.squareup.okhttp.Response response = client.newCall(request).execute();
System.out.println(response.code());
} catch (IOException e) {
e.printStackTrace();
}
}
public Statement getStmt() {
return stmt;
}
}
| 41.095541 | 166 | 0.557734 |
7b93676b0b224e7d4940b258c27883f24238ee42 | 1,968 | package org.humancellatlas.ingest.query;
import org.humancellatlas.ingest.biomaterial.Biomaterial;
import org.humancellatlas.ingest.project.Project;
import org.humancellatlas.ingest.protocol.Protocol;
import org.humancellatlas.ingest.process.Process;
import org.humancellatlas.ingest.file.File;
import org.humancellatlas.ingest.core.EntityType;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import java.util.List;
/**
* Created by prabhat on 02/11/2020.
*/
@Service
public class MetadataQueryService {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private QueryBuilder queryBuilder;
public Page<?> findByCriteria(EntityType metadataType, List<MetadataCriteria> criteriaList, Boolean andCriteria, Pageable pageable) {
Query query = queryBuilder.build(criteriaList, andCriteria);
List<?> result = mongoTemplate.find(query.with(pageable), getEntityClass(metadataType));
long count = mongoTemplate.count(query, getEntityClass(metadataType));
return new PageImpl<>(result, pageable, count);
};
Class<?> getEntityClass(EntityType metadataType) {
switch (metadataType) {
case BIOMATERIAL:
return Biomaterial.class;
case PROTOCOL:
return Protocol.class;
case PROJECT:
return Project.class;
case PROCESS:
return Process.class;
case FILE:
return File.class;
default:
throw new ResourceNotFoundException();
}
}
}
| 35.142857 | 137 | 0.72002 |
1c0cc64701ff73ac900e0fd9a48334fa32c2e6a0 | 5,393 | package org.hisp.dhis.tracker;
/*
* Copyright (c) 2004-2020, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.dhis.IntegrationTestBase;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundleMode;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundleParams;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundleService;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundleValidationService;
import org.hisp.dhis.dxf2.metadata.objectbundle.feedback.ObjectBundleValidationReport;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.render.RenderFormat;
import org.hisp.dhis.render.RenderService;
import org.hisp.dhis.tracker.converter.TrackerConverterService;
import org.hisp.dhis.tracker.domain.Event;
import org.hisp.dhis.user.UserService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Morten Olav Hansen <[email protected]>
*/
public class EventTrackerConverterServiceTest
extends IntegrationTestBase
{
@Autowired
@Qualifier( "eventTrackerConverterService" )
private TrackerConverterService<Event, ProgramStageInstance> trackerConverterService;
@Autowired
private ObjectBundleService objectBundleService;
@Autowired
private ObjectBundleValidationService objectBundleValidationService;
@Autowired
private RenderService _renderService;
@Autowired
private UserService _userService;
@Override
protected void setUpTest()
throws IOException
{
renderService = _renderService;
userService = _userService;
Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService.fromMetadata(
new ClassPathResource( "tracker/event_metadata.json" ).getInputStream(), RenderFormat.JSON );
ObjectBundleParams objectBundleParams = new ObjectBundleParams();
objectBundleParams.setObjectBundleMode( ObjectBundleMode.COMMIT );
objectBundleParams.setImportStrategy( ImportStrategy.CREATE );
objectBundleParams.setObjects( metadata );
ObjectBundle objectBundle = objectBundleService.create( objectBundleParams );
ObjectBundleValidationReport validationReport = objectBundleValidationService.validate( objectBundle );
assertTrue( validationReport.getErrorReports().isEmpty() );
objectBundleService.commit( objectBundle );
}
@Override
public boolean emptyDatabaseAfterTest()
{
return true;
}
@Test
public void testToProgramStageInstance()
throws IOException
{
Event event = new Event();
event.setProgram( "BFcipDERJne" );
event.setProgramStage( "NpsdDv6kKSO" );
event.setOrgUnit( "PlKwabX2xRW" );
ProgramStageInstance programStageInstance = trackerConverterService.from( event );
assertNotNull( programStageInstance );
assertNotNull( programStageInstance.getProgramStage() );
assertNotNull( programStageInstance.getProgramStage().getProgram() );
assertNotNull( programStageInstance.getOrganisationUnit() );
assertEquals( "BFcipDERJne", programStageInstance.getProgramStage().getProgram().getUid() );
assertEquals( "NpsdDv6kKSO", programStageInstance.getProgramStage().getUid() );
assertEquals( "PlKwabX2xRW", programStageInstance.getOrganisationUnit().getUid() );
}
}
| 41.484615 | 113 | 0.771185 |
7af136836476ab026212a8b86ce88dbcde1c81aa | 3,425 | /*
* Copyright 2019 kiwipeach([email protected]).
*
* 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.kiwipeach.blog.shiro.token;
import cn.kiwipeach.blog.domain.SysUser;
import org.apache.shiro.authc.HostAuthenticationToken;
import org.apache.shiro.authc.RememberMeAuthenticationToken;
/**
* 博客登陆访问token
*
* @author kiwipeach
* @create 2019-01-21
*/
public class AccessToken extends SysUser implements HostAuthenticationToken, RememberMeAuthenticationToken {
/**
* 当前登陆账号的token字符串,一定存在
*/
private String tokenStr;
/**
* 失效时间,不一定有
*/
private String expiresTime;
/**
* 刷新token,不一定有
*/
private String refreshToken;
/**
* 记住我,不一定
*/
private boolean rememberMe;
/**
* 当前登陆的三方平台[qq.github.gitee]
*/
private String host;
/**
* 当前登陆的三方平台[qq.github.gitee]
*/
private String platform;
public AccessToken() {
}
public AccessToken(String tokenStr, String thirdUserId, String userName, String nickName, String headUrl, String platform) {
this.tokenStr = tokenStr;
this.platform = platform;
setThirdUserId(thirdUserId);
setNickName(nickName);
setHeadUrl(headUrl);
setUserName(userName);
}
public AccessToken(String tokenStr, String expiresTime, String refreshToken, boolean rememberMe, String host, String platform) {
this.tokenStr = tokenStr;
this.expiresTime = expiresTime;
this.refreshToken = refreshToken;
this.rememberMe = rememberMe;
this.host = host;
this.platform = platform;
}
public String getTokenStr() {
return tokenStr;
}
public void setTokenStr(String tokenStr) {
this.tokenStr = tokenStr;
}
public String getExpiresTime() {
return expiresTime;
}
public void setExpiresTime(String expiresTime) {
this.expiresTime = expiresTime;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
@Override
public boolean isRememberMe() {
return this.rememberMe;
}
/**
* 获取认证的主体
*
* @return 返回主体信息
*/
@Override
public Object getPrincipal() {
return getUserName();
}
/**
* 获取认证主体的密码
*
* @return 返回密文
*/
@Override
public Object getCredentials() {
return getPassword();
}
@Override
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
}
| 23.458904 | 132 | 0.64292 |
f895eb526a15baaaeb9463d34747da9cad8ce095 | 2,490 | /*
*************************************************************************
*************************************************************************
** **
** V2KPARSE **
** Copyright (C) 2008-2009 Karl W. Pfalzer **
** **
** This program is free software; you can redistribute it and/or **
** modify it under the terms of the GNU General Public License **
** as published by the Free Software Foundation; either version 2 **
** of the License, or (at your option) any later version. **
** **
** This program is distributed in the hope that it will be useful, **
** but WITHOUT ANY WARRANTY; without even the implied warranty of **
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
** GNU General Public License for more details. **
** **
** You should have received a copy of the GNU General Public License **
** along with this program; if not, write to the **
** Free Software Foundation, Inc. **
** 51 Franklin Street, Fifth Floor **
** Boston, MA 02110-1301, USA. **
** **
*************************************************************************
*************************************************************************
*/
package v2k.parser.tree;
public class PortConnection {
public PortConnection(Expression ele) {
m_item = new AExpr(ele);
}
public PortConnection(NamedPortConnection ele) {
m_item = new ANamed(ele);
}
private enum EType {
eExpr,
eNamed
}
private A m_item;
private static abstract class A {
protected A(EType e) {
m_type = e;
}
final EType m_type;
}
private static class AExpr extends A {
private AExpr(Expression ele) {
super(EType.eExpr);
m_ele = ele;
}
private Expression m_ele;
}
private static class ANamed extends A {
private ANamed(NamedPortConnection ele) {
super(EType.eNamed);
m_ele = ele;
}
private NamedPortConnection m_ele;
}
}
| 37.164179 | 73 | 0.428112 |
bdcec6454c4f0e55939e33f3503609a84ee118b6 | 738 | package com.mmit.presentacion.comando.entrenadores;
import com.mmit.negocio.entrenadores.EntrenadorSA;
import com.mmit.negocio.factoriaNegocio.FactoriaNegocio;
import com.mmit.presentacion.Evento;
import com.mmit.presentacion.comando.Comando;
import com.mmit.presentacion.controlador.Contexto;
public class ComandoAbrirListarEntrenadores implements Comando{
@Override
public Contexto execute(Object datos) {
try{
EntrenadorSA entrenadoresSa = FactoriaNegocio.getInstancia().crearEntrenadoresSA();
return new Contexto(Evento.AbrirListarEntrenadores, entrenadoresSa.listarEntrenadores());
} catch (Exception ex){
return new Contexto(Evento.ErrorSQL, null);
}
}
}
| 33.545455 | 101 | 0.752033 |
c2d8469a792acb769d5bf93f5d3d5cb7a37a0433 | 163 | class Outer {
public void withClass(Object <caret>o) {
System.out.println(o.toString());
}
public void foor(Object objct) {
withClass(objct);
}
}
| 16.3 | 42 | 0.644172 |
62c9f5f6028d24a3ff0312bb12e30f55d9f223a9 | 114 | package com.example.recipes.user;
public class UserJsonViews {
public interface RegistrationView {
}
}
| 12.666667 | 39 | 0.72807 |
c5059077193c58c97957ffdeca7825626f0fb9ff | 573 | package com.tencent.bk.codecc.task.vo.scanconfiguration;
import com.tencent.devops.common.api.CommonVO;
import io.swagger.annotations.ApiModel;
import lombok.Data;
/**
* 新告警判定视图
*
* @version V4.0
* @date 2019/11/8
*/
@Data
@ApiModel("新告警判定视图")
public class NewDefectJudgeVO extends CommonVO
{
/**
* 判定方式1:按日期;2:按构建
*/
private Integer judgeBy;
/**
* 新告警开始的日期
*/
private String fromDate;
/**
* 新告警开始的日期时间戳
*/
private Long fromDateTime;
/**
* 最近几次构建产生的告警为新告警
*/
private Integer lastestTimes;
}
| 15.486486 | 56 | 0.633508 |
a7b0540716e23e71ab1cfe2d53b1837d19e43540 | 1,581 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.fuerve.villageelder.actions.results;
/**
* This class represents a single result item in an abstract way.
* @author lparker
*
*/
public abstract class Result<T> {
private T value;
/**
* Initializes a new Result.
*/
public Result() {
}
/**
* Gets this result item value.
* @return The result item's value.
*/
public T getValue() {
return value;
}
/**
* Sets this result item value.
* @param vvalue The result item's value.
*/
public void setValue(final T vvalue) {
value = vvalue;
}
/**
* Called within a subclass to set the result value.
* @param vvalue The value to aggregate into the result.
*/
public abstract void aggregate(final T vvalue);
}
| 27.736842 | 65 | 0.679949 |
306f62873ba0c73e42a23c4cf694bd14c8895207 | 3,643 | package com.amanitadesign.expansion;
import com.adobe.fre.FREObject;
import com.amanitadesign.GoogleExtension;
import com.amanitadesign.GoogleExtensionContext;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;
import com.google.android.vending.expansion.downloader.impl.DownloaderService;
/**
* Created by Oldes on 12/1/2016.
*/
public class ExpansionFunctions {
//private static final byte[] SALT = { 1, 42, -12, -1, 54, 98,
// -100, -12, 43, 2, -8, -4, 9, 5, -106, -107, -33, 45, -1, 84 };
static public class ExpansionFilesStatus implements FREFunction {
@Override
public FREObject call(FREContext ctx, FREObject[] args) {
Log.i(GoogleExtension.TAG, "ExpansionFilesStatusFunction -> call()");
int versionNumber = 1;
int patchNumber = 1;
try {
versionNumber = args[0].getAsInt();
patchNumber = args[1].getAsInt();
} catch (Exception e) {
e.printStackTrace();
}
if (GoogleExtensionContext.getVersionNumber() == 1) {
GoogleExtensionContext.setVersionNumber(versionNumber);
}
if (GoogleExtensionContext.getPatchNumber() == 1) {
GoogleExtensionContext.setPatchNumber(patchNumber);
}
ObbExpansionsManager manager = GoogleExtensionContext.getManager();
manager.getStatus();
return null;
}
}
static public class StartDownload implements FREFunction {
@Override
public FREObject call(FREContext ctx, FREObject[] args) {
try{
ObbDownloaderService.BASE64_PUBLIC_KEY = args[0].getAsString();
Intent notifierIntent = new Intent(ctx.getActivity(), ctx.getActivity().getClass());
notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx.getActivity(), 0, notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int startResult = DownloaderService.startDownloadServiceIfRequired(GoogleExtension.appContext,
pendingIntent, ObbDownloaderService.class);
Log.i(GoogleExtension.TAG, "StartDownload result: " + startResult);
if (startResult != DownloaderService.NO_DOWNLOAD_REQUIRED) {
Downloader dl = new Downloader();
GoogleExtensionContext.setDownloader(dl);
dl.startDownload();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
static public class StopDownload implements FREFunction {
@Override
public FREObject call(FREContext ctx, FREObject[] args) {
Log.i(GoogleExtension.TAG, "StopDownload -> call()");
Downloader dl = GoogleExtensionContext.getDownloader();
if (dl != null) {
dl.stopDownload();
}
return null;
}
}
static public class ResumeDownload implements FREFunction {
@Override
public FREObject call(FREContext ctx, FREObject[] args) {
Log.i(GoogleExtension.TAG, "ResumeDownload -> call()");
Downloader dl = GoogleExtensionContext.getDownloader();
if (dl != null) {
dl.resumeDownload();
}
return null;
}
}
}
| 36.069307 | 145 | 0.603898 |
10146e10f9c17c6beebe8b503d54d000123aa986 | 649 | package Lab_5_Students;
public class Students {
private String firstName;
private String lastName;
private int age;
private String hometown;
public Students(String firstName,String lastName, int age, String hometown){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.hometown = hometown;
}
public String getHometown() {
return this.hometown;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public int getAge() {
return this.age;
}
}
| 20.28125 | 80 | 0.624037 |
34e3a3530e6b02af714b96cdc71b72116c59e077 | 410 | package com.jense.spring.context.demo.impl;
import com.jense.spring.annotation.JAutoWire;
import com.jense.spring.annotation.JService;
import com.jense.spring.context.demo.AService;
import com.jense.spring.context.demo.BService;
@JService
public class AServiceImpl implements AService {
@JAutoWire
BService bService;
@Override
public String hello() {
return bService.hello();
}
}
| 24.117647 | 47 | 0.753659 |
b049cf11f7ca85c98fbe5e16959d15247a1ceff9 | 2,236 | /**
* Copyright (C) 2014-2021 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.jaxb;
import javax.annotation.Nonnull;
import com.helger.commons.error.list.ErrorList;
import com.helger.commons.error.list.IErrorList;
/**
* Interface for validating JAXB documents.
*
* @author Philip Helger
* @param <JAXBTYPE>
* The JAXB type to be written
*/
public interface IJAXBValidator <JAXBTYPE>
{
/**
* Check if the passed JAXB document is valid according to the XSD or not.
*
* @param aJAXBDocument
* The JAXB document to be validated. May not be <code>null</code>.
* @return <code>true</code> if the document is valid, <code>false</code> if
* not.
* @see #validate(Object)
*/
default boolean isValid (@Nonnull final JAXBTYPE aJAXBDocument)
{
return validate (aJAXBDocument).containsNoError ();
}
/**
* Validate the passed JAXB document.
*
* @param aJAXBDocument
* The JAXB document to be validated. May not be <code>null</code>.
* @param aErrorList
* The error list to be filled. May not be <code>null</code>.
* @since v9.3.7
*/
void validate (@Nonnull JAXBTYPE aJAXBDocument, @Nonnull ErrorList aErrorList);
/**
* Validate the passed JAXB document.
*
* @param aJAXBDocument
* The JAXB document to be validated. May not be <code>null</code>.
* @return The validation results. Never <code>null</code>.
*/
@Nonnull
default IErrorList validate (@Nonnull final JAXBTYPE aJAXBDocument)
{
final ErrorList aErrorList = new ErrorList ();
validate (aJAXBDocument, aErrorList);
return aErrorList;
}
}
| 30.630137 | 81 | 0.687388 |
3fd51609b8c9636ade963603a8fbbfa585b8d0b7 | 2,075 | package hkube.communication.streaming;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Flow {
List<Node> nodes = new ArrayList<>();
public List<Node> getNodes() {
return nodes;
}
public void setNodes(List<Node> nodes) {
this.nodes = nodes;
}
public Flow(List mapList) {
((List<Map>) mapList).stream().forEach(
node -> {
nodes.add(new Node((String) node.get("source"), (List) node.get("next")));
}
);
}
public class Node {
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public List<String> getNext() {
return next;
}
public void setNext(List<String> next) {
this.next = next;
}
public Node(String source, List<String> next) {
this.source = source;
this.next = next;
}
String source;
List<String> next;
}
public boolean isNextInFlow(String current, String next) {
Node currentNode = getNode(current);
if (currentNode != null) {
return currentNode.next.contains(next);
} else {
return false;
}
}
private Node getNode(String name) {
if(nodes.stream().anyMatch(node ->
(node.source.equals(name))))
return nodes.stream().filter(node ->
(node.source.equals(name))
).findFirst().get();
else
return null;
}
public Flow getRestOfFlow(String current) {
Flow flow = clone();
flow.nodes.remove(getNode(current));
return flow;
}
public Flow clone() {
Flow flow = new Flow(new ArrayList<>());
List<Node> nodesCopy = new ArrayList<>();
nodesCopy.addAll(nodes);
flow.setNodes(nodesCopy);
return flow;
}
public List asList(){
return nodes;
}
}
| 22.802198 | 94 | 0.528675 |
8aa1762a0f72cef26230951153d1b0589052fc34 | 7,118 | package xyz.monkeytong.hongbao.activities;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
import xyz.monkeytong.hongbao.R;
import xyz.monkeytong.hongbao.adapter.*;
import xyz.monkeytong.hongbao.adapter.BaseAdapter;
import xyz.monkeytong.hongbao.bean.Item;
import xyz.monkeytong.hongbao.fragments.GeneralSettingsFragment;
import xyz.monkeytong.hongbao.utils.ConnectivityUtil;
import xyz.monkeytong.hongbao.utils.UpdateTask;
import xyz.monkeytong.hongbao.widget.CircleImageView;
import com.tencent.bugly.crashreport.CrashReport;
public class MainActivity extends BaseActivity implements AccessibilityManager.AccessibilityStateChangeListener,View.OnClickListener,BaseAdapter.OnItemClickListener {
//开关切换按钮
private CircleImageView iv;
private TextView txt_state;
private RecyclerView recyclerView;
//AccessibilityService 管理
private AccessibilityManager accessibilityManager;
private List<Item> datas=new ArrayList<>();
private RecyclerViewAdapter viewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CrashReport.initCrashReport(getApplicationContext(), "900019352", false);
setContentView(R.layout.activity_main);
iv= (CircleImageView) findViewById(R.id.iv);
txt_state= (TextView) findViewById(R.id.text_state);
recyclerView= (RecyclerView) findViewById(R.id.frist_recyclerview);
initRecycleView();
iv.setBorderWidth(10);
iv.setOnClickListener(this);
// handleMaterialStatusBar();
explicitlyLoadPreferences();
//监听AccessibilityService 变化
accessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
accessibilityManager.addAccessibilityStateChangeListener(this);
updateServiceStatus();
}
private void initRecycleView(){
datas.add(new Item(getString(R.string.settings), R.mipmap.settings));
datas.add(new Item(getString(R.string.study), R.mipmap.jc));
datas.add(new Item(getString(R.string.share),R.mipmap.share));
viewAdapter=new RecyclerViewAdapter(this,datas);
viewAdapter.setOnItemClickListener(this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this,3));
recyclerView.addItemDecoration(new DividerGridItemDecoration());
recyclerView.setAdapter(viewAdapter);
}
private void explicitlyLoadPreferences() {
PreferenceManager.setDefaultValues(this, R.xml.general_preferences, false);
}
/**
* 适配MIUI沉浸状态栏
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void handleMaterialStatusBar() {
// Not supported in APK level lower than 21
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return;
Window window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(0xffE46C62);
}
@Override
protected void onResume() {
super.onResume();
// Check for update when WIFI is connected or on first time.
if (ConnectivityUtil.isWifi(this) || UpdateTask.count == 0)
new UpdateTask(this, false).update();
}
@Override
protected void onDestroy() {
//移除监听服务
accessibilityManager.removeAccessibilityStateChangeListener(this);
super.onDestroy();
}
public void openAccessibility() {
try {
Toast.makeText(this, "点击「微信红包」", Toast.LENGTH_SHORT).show();
Intent accessibleIntent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivity(accessibleIntent);
} catch (Exception e) {
Toast.makeText(this, "遇到一些问题,请手动打开系统设置>无障碍服务>微信红包(ฅ´ω`ฅ)", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public void openGitHub() {
Intent webViewIntent = new Intent(this, WebViewActivity.class);
webViewIntent.putExtra("title", "GitHub 项目主页");
webViewIntent.putExtra("url", "https://github.com/yuzhongrong/WeChatLuckyMoney/blob/master/README.md");
startActivity(webViewIntent);
}
public void openUber() {
Intent webViewIntent = new Intent(this, WebViewActivity.class);
webViewIntent.putExtra("title", "Uber 优惠乘车机会(优惠码rgk2wue)");
webViewIntent.putExtra("url", "https://get.uber.com.cn/invite/rgk2wue");
startActivity(webViewIntent);
}
public void openSettings() {
Intent settingsIntent = new Intent(this, SettingsActivity.class);
settingsIntent.putExtra("title", "偏好设置");
settingsIntent.putExtra("frag_id", "GeneralSettingsFragment");
startActivity(settingsIntent);
}
@Override
public void onAccessibilityStateChanged(boolean enabled) {
updateServiceStatus();
}
/**
* 更新当前 HongbaoService 显示状态
*/
private void updateServiceStatus() {
if (isServiceEnabled()) {
txt_state.setText(R.string.close_service);
} else {
txt_state.setText(R.string.start_service);
}
}
/**
* 获取 HongbaoService 是否启用状态
*
* @return
*/
private boolean isServiceEnabled() {
List<AccessibilityServiceInfo> accessibilityServices =
accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
for (AccessibilityServiceInfo info : accessibilityServices) {
if (info.getId().equals(getPackageName() + "/.services.HongbaoService")) {
return true;
}
}
return false;
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.iv:
openAccessibility();
break;
}
}
@Override
public void onItemClick(View view, int position) {
switch (position){
case 0:
openSettings();
break;
case 1:
openUber();
break;
case 2:
openGitHub();
break;
case 3:
break;
}
}
}
| 29.53527 | 166 | 0.679826 |
4887511b1d18dfce273472d6abecf6dc51f65f8c | 2,608 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.jetbrains.python.documentation.docstrings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Mikhail Golubev
*/
public abstract class SectionBasedDocStringBuilder extends DocStringBuilder<SectionBasedDocStringBuilder> {
protected String mySectionIndent;
protected final String myContinuationIndent;
private String myCurSectionTitle = null;
protected SectionBasedDocStringBuilder(@NotNull String defaultSectionIndent, @NotNull String defaultContinuationIndent) {
mySectionIndent = defaultSectionIndent;
myContinuationIndent = defaultContinuationIndent;
}
@NotNull
public SectionBasedDocStringBuilder startParametersSection() {
// TODO make default section titles configurable
return startSection(getDefaultParametersHeader());
}
@NotNull
public SectionBasedDocStringBuilder startReturnsSection() {
return startSection(getDefaultReturnsHeader());
}
@NotNull
protected SectionBasedDocStringBuilder startSection(@NotNull String title) {
if (myCurSectionTitle != null) {
addEmptyLine();
}
myCurSectionTitle = title;
return this;
}
@NotNull
public SectionBasedDocStringBuilder endSection() {
myCurSectionTitle = null;
return this;
}
@NotNull
protected abstract String getDefaultParametersHeader();
@NotNull
protected abstract String getDefaultReturnsHeader();
@NotNull
public abstract SectionBasedDocStringBuilder addParameter(@NotNull String name, @Nullable String type, @NotNull String description);
@NotNull
public abstract SectionBasedDocStringBuilder addReturnValue(@Nullable String name, @NotNull String type, @NotNull String description);
@NotNull
protected SectionBasedDocStringBuilder addSectionLine(@NotNull String line) {
return addLine(mySectionIndent + line);
}
@NotNull
protected SectionBasedDocStringBuilder withSectionIndent(@NotNull String indent) {
mySectionIndent = indent;
return this;
}
}
| 30.682353 | 136 | 0.773006 |
6f5124b981ba7cee004b196ad39b668770b75c89 | 3,272 | /**
* 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.pinot.core.operator.combine;
import java.util.List;
import org.apache.pinot.core.common.Operator;
import org.apache.pinot.core.operator.ExecutionStatistics;
import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
@SuppressWarnings("rawtypes")
public class CombineOperatorUtils {
private CombineOperatorUtils() {
}
/**
* Use at most 10 or half of the processors threads for each query. If there are less than 2 processors, use 1 thread.
* <p>NOTE: Runtime.getRuntime().availableProcessors() may return value < 2 in container based environment, e.g.
* Kubernetes.
*/
public static final int MAX_NUM_THREADS_PER_QUERY =
Math.max(1, Math.min(10, Runtime.getRuntime().availableProcessors() / 2));
/**
* Returns the number of threads used to execute the query in parallel.
*/
public static int getNumThreadsForQuery(int numOperators) {
return Math.min(numOperators, MAX_NUM_THREADS_PER_QUERY);
}
/**
* Sets the execution statistics into the results block.
*/
public static void setExecutionStatistics(IntermediateResultsBlock resultsBlock, List<Operator> operators,
long threadCpuTimeNs, int numServerThreads) {
int numSegmentsProcessed = operators.size();
int numSegmentsMatched = 0;
long numDocsScanned = 0;
long numEntriesScannedInFilter = 0;
long numEntriesScannedPostFilter = 0;
long numTotalDocs = 0;
for (Operator operator : operators) {
ExecutionStatistics executionStatistics = operator.getExecutionStatistics();
if (executionStatistics.getNumDocsScanned() > 0) {
numSegmentsMatched++;
}
numDocsScanned += executionStatistics.getNumDocsScanned();
numEntriesScannedInFilter += executionStatistics.getNumEntriesScannedInFilter();
numEntriesScannedPostFilter += executionStatistics.getNumEntriesScannedPostFilter();
numTotalDocs += executionStatistics.getNumTotalDocs();
}
resultsBlock.setNumSegmentsProcessed(numSegmentsProcessed);
resultsBlock.setNumSegmentsMatched(numSegmentsMatched);
resultsBlock.setNumDocsScanned(numDocsScanned);
resultsBlock.setNumEntriesScannedInFilter(numEntriesScannedInFilter);
resultsBlock.setNumEntriesScannedPostFilter(numEntriesScannedPostFilter);
resultsBlock.setNumTotalDocs(numTotalDocs);
resultsBlock.setExecutionThreadCpuTimeNs(threadCpuTimeNs);
resultsBlock.setNumServerThreads(numServerThreads);
}
}
| 41.948718 | 120 | 0.761919 |
6e3fb0008cb99edecdc26a75f6b17886ddd72785 | 5,138 | package com.stevezero.game.engine.actor.enemy;
import com.stevezero.game.engine.Engine;
import com.stevezero.game.engine.actor.Actor;
import com.stevezero.game.engine.actor.Role;
import com.stevezero.game.engine.actor.projectile.Projectile;
import com.stevezero.game.engine.graphics.Layers;
import com.stevezero.game.geometry.Vector2;
import com.stevezero.game.statistics.Statistics;
import com.stevezero.game.util.Util;
/**
* Encapsulates common information/methods for enemy actors.
*
* TODO: clean up spriting!!!!
*/
abstract public class Enemy extends Actor {
private static final int MAX_VX = 2;
private static final int MAX_VY = 15;
// Attack power.
protected int power;
// Default speed
protected float speed = 0.1f;
// Default attack speed is ~every second.
protected int attackProb = 2;
// How often to announce themselves.
protected int moveSoundProb = 3;
private final Statistics statistics;
private final Engine engine;
//
// Constructors -------------------->
//
public Enemy(Engine engine, float mass, int x, int y) {
super(mass, x, y, Layers.FOREGROUND, Role.ENEMY);
this.statistics = engine.getStatistics();
this.engine = engine;
}
//
// To Override --------------------->
//
/**
* Called when this enemy attacks.
* Override to provide custom behavior (sounds, sprite changes, etc).
*/
protected void onAttack(Engine engine) {
}
/**
* Called when this enemy makes a velocity update.
* Override to provide custom behavior (sounds, sprite changes, etc).
*/
protected void onMove(Engine engine) {
}
/**
* Called when this enemy is dead.
* Override to provide custom behavior (sounds, sprite changes, etc).
*/
protected void onEnemyDeath(Engine engine) {
}
/**
* @return the ordinal for use when looking up sprites in the atlas.
*/
abstract protected int getAtlasOrdinal();
/**
* @return the number of points this enemy is worth if destroyed.
*/
abstract public int getPoints();
/**
* @return the stat ID to increment.
*/
abstract public int getStat();
/**
* Must be override by subclasses to create a projectile.
*/
protected Projectile createProjectile(Engine engine, Vector2 direction, int startX,
int startY) {
return null;
}
/**
* Create a bullet for this enemy.
*/
protected void createProjectile(Engine engine, Vector2 direction) {
// The spawn location is the edge of the emitter * the direction unit vector.
int startX = (int)(
this.getBox().getCenterX() +
(direction.getX() * (this.getBox().getWidth() / 2)));
int startY = this.getBox().getY() + (this.getBox().getHeight() / 2); // HACK
if (canShoot()) {
Projectile projectile = createProjectile(engine, direction, startX, startY);
if (projectile != null) {
engine.addSimulatable(projectile);
} else {
// TODO: Throw a runtime exception, this should never happen.
}
}
}
//
// Simulation Overrides ------------>
//
@Override
public void update(Engine engine) {
if (isDead()) {
return;
}
if (!canFly()) {
this.applyGravity();
}
// Add a velo cap to avoid instability.
velocity.setY(Util.absCap(velocity.getY(), MAX_VY));
velocity.setX(Util.absCap(velocity.getX(), MAX_VX));
x += Math.round(velocity.getX());
y += Math.round(velocity.getY());
}
/**
* Set the death animation potentially on health change.
*/
@Override
protected void onDeath() {
onEnemyDeath(engine);
statistics.addScore(getPoints());
statistics.increment(getStat());
disableCollisions();
this.zeroVelocity();
}
//
// Public API ----------------->
//
/**
* Override to allow for shooting behavior.
* @return whether this enemy can shoot or not.
*/
public boolean canShoot() {
return false;
}
/**
* Override to allow for jump behavior.
* @return whether this enemy can jump or not.
*/
public boolean canJump() {
return false;
}
/**
* Override to allow for flying behavior.
* @return whether this enemy can fly or not.
*/
public boolean canFly() {
return false;
}
/**
* Move in direction vector.
*/
public void applyVelocity(Vector2 velDelta) {
velocity.addX(velDelta.getX() * speed);
if (canFly()) {
velocity.addX(velDelta.getY() * speed);
}
onMove(engine);
}
/**
* Call this to attack something.
* @param engine
*/
public void attack(Engine engine) {
if (canShoot()) {
if (Math.random() * 100 < attackProb) {
createProjectile(engine, getFacingDirection().getVector2());
onAttack(engine);
}
}
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
}
| 24.235849 | 86 | 0.603153 |
4f1bb8c553c237977bf0d9893374c0f8dde6872d | 12,579 | /*
This file is part of Intake24.
Copyright 2015, 2016 Newcastle University.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file is based on Intake24 v1.0.
© Crown copyright, 2012, 2013, 2014
Licensed under the Open Government Licence 3.0:
http://www.nationalarchives.gov.uk/doc/open-government-licence/
*/
package uk.ac.ncl.openlab.intake24.client.survey.prompts;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.*;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.pcollections.HashTreePMap;
import org.pcollections.HashTreePSet;
import org.pcollections.PVector;
import org.workcraft.gwt.shared.client.Callback1;
import org.workcraft.gwt.shared.client.Function1;
import uk.ac.ncl.openlab.intake24.client.LoadingPanel;
import uk.ac.ncl.openlab.intake24.client.api.foods.AutomaticAssociatedFoods;
import uk.ac.ncl.openlab.intake24.client.api.foods.CategoryHeader;
import uk.ac.ncl.openlab.intake24.client.api.foods.FoodDataService;
import uk.ac.ncl.openlab.intake24.client.api.foods.FoodHeader;
import uk.ac.ncl.openlab.intake24.client.api.uxevents.UxEventsHelper;
import uk.ac.ncl.openlab.intake24.client.api.uxevents.Viewport;
import uk.ac.ncl.openlab.intake24.client.api.uxevents.associatedfoods.AutomaticData;
import uk.ac.ncl.openlab.intake24.client.survey.*;
import uk.ac.ncl.openlab.intake24.client.survey.prompts.messages.HelpMessages;
import uk.ac.ncl.openlab.intake24.client.survey.prompts.messages.PromptMessages;
import uk.ac.ncl.openlab.intake24.client.ui.WidgetFactory;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class AutomaticAssociatedFoodsPrompt implements Prompt<Meal, MealOperation> {
private final static PromptMessages messages = PromptMessages.Util.getInstance();
private final static HelpMessages helpMessages = HelpMessages.Util.getInstance();
private final Meal meal;
private PVector<ShepherdTour.Step> tour;
private FoodBrowser foodBrowser;
private boolean isInBrowserMode = false;
private final String locale;
private final Logger logger = Logger.getLogger("AutomaticAssociatedFoodsPrompt");
public AutomaticAssociatedFoodsPrompt(final String locale, final Meal meal) {
this.locale = locale;
this.meal = meal;
}
@Override
public SurveyStageInterface getInterface(final Callback1<MealOperation> onComplete,
Callback1<Function1<Meal, Meal>> updateIntermediateState) {
final FlowPanel content = new FlowPanel();
PromptUtil.addBackLink(content);
final FlowPanel promptPanel = WidgetFactory.createPromptPanel(SafeHtmlUtils.fromSafeConstant(messages.assocFoods_automaticPrompt(SafeHtmlUtils.htmlEscape(meal.name.toLowerCase()))));
content.add(promptPanel);
final LoadingPanel loading = new LoadingPanel(messages.foodBrowser_loadingMessage());
content.add(loading);
final ArrayList<FoodHeader> encodedFoods = new ArrayList<>();
final ArrayList<String> foodCodes = new ArrayList<>();
for (FoodEntry e : meal.foods) {
if (e.isEncoded()) {
EncodedFood ef = e.asEncoded();
encodedFoods.add(new FoodHeader(ef.data.code, ef.data.localDescription));
foodCodes.add(ef.data.code);
}
}
FoodDataService.INSTANCE.getAutomaticAssociatedFoods(locale, foodCodes, new MethodCallback<AutomaticAssociatedFoods>() {
@Override
public void onFailure(Method method, Throwable exception) {
content.remove(loading);
content.add(WidgetFactory.createDefaultErrorMessage());
}
@Override
public void onSuccess(Method method, AutomaticAssociatedFoods response) {
content.remove(loading);
final List<CheckBox> checkBoxes = new ArrayList<>();
final Map<CheckBox, CategoryHeader> foodMap = new LinkedHashMap<>();
List<CategoryHeader> categories = response.categories.stream()
.filter(c -> milkIsRerevant(c)).collect(Collectors.toList());
List<String> codes = categories.stream().map(c -> c.code).collect(Collectors.toList());
if (!cachedAssociatedFoodsChanged(codes) || codes.size() == 0) {
cacheAssociatedFoods(listToJsArray(new ArrayList<>()));
onComplete.call(MealOperation.update(m -> m.markAssociatedFoodsComplete()));
} else {
cacheAssociatedFoods(listToJsArray(codes));
UxEventsHelper.postAutomaticAssociatedFoodsReceived(new AutomaticData(Viewport.getCurrent(), encodedFoods, response.categories, new ArrayList<>()));
}
for (CategoryHeader category : categories) {
CheckBox cb = new CheckBox(SafeHtmlUtils.fromString(category.description()));
FlowPanel div = new FlowPanel();
div.getElement().getStyle().setPaddingBottom(4, Style.Unit.PX);
div.add(cb);
cb.getElement().getFirstChildElement().getStyle().setMargin(0, Style.Unit.PX);
content.add(div);
checkBoxes.add(cb);
foodMap.put(cb, category);
}
Button continueButton = WidgetFactory.createGreenButton("Continue", "continue-button", new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
ArrayList<String> selectedCategories = new ArrayList<>();
for (CheckBox cb : checkBoxes) {
if (cb.getValue()) {
selectedCategories.add(foodMap.get(cb).code);
}
}
UxEventsHelper.postAutomaticAssociatedFoodsResponse(new AutomaticData(Viewport.getCurrent(), encodedFoods, response.categories, selectedCategories));
onComplete.call(MealOperation.update(
m -> {
List<FoodEntry> newFoodEntries = new ArrayList<>();
for (CheckBox cb : checkBoxes) {
if (cb.getValue()) {
Optional<FoodEntry> assocFood;
CategoryHeader ch = foodMap.get(cb);
switch (ch.code) {
case SpecialData.FOOD_CODE_MILK_ON_CEREAL:
assocFood = meal.foods.stream().filter(f -> isCerealWithMilk(f)).findFirst();
if (assocFood.isPresent()) {
addFood(newFoodEntries, ch, assocFood);
}
break;
case SpecialData.FOOD_CODE_MILK_IN_HOT_DRINK:
assocFood = meal.foods.stream().filter(f -> isHotDrinkWithMilk(f)).findFirst();
if (assocFood.isPresent()) {
addFood(newFoodEntries, ch, assocFood);
}
break;
default:
addFood(newFoodEntries, ch, Optional.empty());
break;
}
}
}
if (newFoodEntries.size() > 0) {
return m.withFoods(m.foods.plusAll(newFoodEntries));
} else {
cacheAssociatedFoods(listToJsArray(new ArrayList<>()));
return m.withFoods(m.foods.plusAll(newFoodEntries)).markAssociatedFoodsComplete();
}
}));
}
});
content.add(WidgetFactory.createButtonsPanel(continueButton));
}
});
return new SurveyStageInterface.Aligned(content, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP,
SurveyStageInterface.DEFAULT_OPTIONS, AutomaticAssociatedFoodsPrompt.class.getSimpleName());
}
public PVector<ShepherdTour.Step> getShepherdTourSteps() {
if (isInBrowserMode)
return foodBrowser.getShepherdTourSteps();
else
return tour;
}
@Override
public String toString() {
return "Food reminder prompt";
}
private void addFood(List<FoodEntry> foodEntries, CategoryHeader ch, Optional<FoodEntry> assocFood) {
FoodLink fl = assocFood.map(f -> FoodLink.newLinked(f.link.id)).orElse(FoodLink.newUnlinked());
foodEntries.add(
new RawFood(fl,
ch.description(),
HashTreePSet.<String>empty().plus(RawFood.FLAG_DISABLE_SPLIT),
HashTreePMap.<String, String>empty().plus(RawFood.KEY_BROWSE_CATEGORY_INSTEAD_OF_LOOKUP,
ch.code)
)
);
}
private boolean isHotDrinkWithMilk(FoodEntry f) {
EncodedFood enc = f.asEncoded();
return enc.data.code.equals(SpecialData.FOOD_CODE_COFFEE) ||
enc.isInCategory(SpecialData.CATEGORY_TEA_CODE);
}
private boolean isCerealWithMilk(FoodEntry f) {
EncodedFood enc = f.asEncoded();
return enc.isInCategory(SpecialData.CATEGORY_BREAKFAST_CEREALS) &&
SpecialData.CATEGORIES_CEREAL_NO_MILK.stream().anyMatch(c -> !enc.isInCategory(c));
}
private boolean hotDrinkIsPresent() {
return meal.foods.stream().filter(f -> f.isEncoded()).anyMatch(this::isHotDrinkWithMilk);
}
private boolean cerealIsPresent() {
return meal.foods.stream().filter(f -> f.isEncoded()).anyMatch(this::isCerealWithMilk);
}
private boolean milkIsRerevant(CategoryHeader categoryHeader) {
return (!categoryHeader.code.equals(SpecialData.FOOD_CODE_MILK_IN_HOT_DRINK) || hotDrinkIsPresent()) &&
(!categoryHeader.code.equals(SpecialData.FOOD_CODE_MILK_ON_CEREAL) || cerealIsPresent());
}
private final native void cacheAssociatedFoods(JsArrayString l)/*-{
return $wnd.lastAssociatedFoods = l;
}-*/;
private final boolean cachedAssociatedFoodsChanged(List<String> l) {
return cachedAssociatedFoodsChangedNative(listToJsArray(l));
}
private final JsArrayString listToJsArray(List<String> l) {
JsArrayString jsArray = (JsArrayString) JsArrayString.createArray();
for (String str : l) {
jsArray.push(str);
}
return jsArray;
}
private final native boolean cachedAssociatedFoodsChangedNative(JsArrayString l)/*-{
var cached = $wnd.lastAssociatedFoods || [];
if (l.length !== cached.length) {
return true;
}
for (var i = 0; i < l.length; i++) {
if (cached.indexOf(l[i]) === -1) {
return true;
}
}
return false;
}-*/;
} | 43.829268 | 190 | 0.593847 |
37b388207ce291a30827567fc79698f5253b6483 | 2,767 | package com.example.thowfeeqrahman.medicalcard;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class
MedicalStoreReg extends AppCompatActivity implements View.OnClickListener {
EditText ed1,ed2,ed3,ed4,ed5,ed6,ed7;
Button bt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medical_store_reg);
ed1=(EditText)findViewById(R.id.editText3);
ed2=(EditText)findViewById(R.id.editText4);
ed3=(EditText)findViewById(R.id.editText5);
ed4=(EditText)findViewById(R.id.editText6);
ed5=(EditText)findViewById(R.id.editText7);
ed6=(EditText)findViewById(R.id.editText8);
ed7=(EditText)findViewById(R.id.editText9);
bt1= (Button)findViewById(R.id.button5);
bt1.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int flg=0;
if(view==bt1) {
if(ed1.getText().length()==0)
{flg++;
ed1.setError("");
}
if(ed2.getText().length()==0)
{flg++;
ed2.setError("");
}
if(ed3.getText().length()==0)
{flg++;
ed3.setError("");
}
if(ed4.getText().length()==0)
{flg++;
ed4.setError("");
}
if(ed5.getText().length()==0)
{flg++;
ed5.setError("");
}
if(ed6.getText().length()==0)
{flg++;
ed6.setError("");
}
if(ed7.getText().length()==0)
{flg++;
ed7.setError("");
}
if (flg==0)
{
SharedPreferences sh = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor ed=sh.edit();
ed.putString("m_name",ed1.getText().toString());
ed.putString("pharmacist_id",ed2.getText().toString());
ed.putString("place",ed5.getText().toString());
ed.putString("state",ed3.getText().toString());
ed.putString("pincode",ed4.getText().toString());
ed.putString("liscence_no",ed6.getText().toString());
ed.putString("phone_no",ed7.getText().toString());
ed.commit();
Intent i=new Intent(getApplicationContext(), MedicalStoreReg2.class);
startActivity(i);
}}
}
}
| 31.804598 | 106 | 0.56704 |
9345e02e8dfb8febee8250268129bd17786dd67d | 3,856 | package org.cboard.filedp;
import org.cboard.dataprovider.DataProvider;
import org.cboard.dataprovider.annotation.DatasourceParameter;
import org.cboard.dataprovider.annotation.ProviderName;
import org.cboard.dataprovider.annotation.QueryParameter;
import org.cboard.exception.CBoardException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
/**
* Created by zyong on 2017/2/4.
*/
@ProviderName(name = "TextFile")
public class FileDataProvider extends DataProvider {
private static final Logger LOG = LoggerFactory.getLogger(FileDataProvider.class);
@Value("${dataprovider.resultLimit:300000}")
private int resultLimit;
@DatasourceParameter(label = "{{'DATAPROVIDER.TEXTFILE.BASE_PATH'|translate}}", type = DatasourceParameter.Type.Input, order = 1)
private String DS_PARAM_BASE_PATH = "basePath";
@QueryParameter(label = "{{'DATAPROVIDER.TEXTFILE.FILE_NAME'|translate}}", type = QueryParameter.Type.Input, order = 1)
private String QUERY_PARAM_FILE_NAME = "fileName";
@QueryParameter(label = "{{'DATAPROVIDER.TEXTFILE.ENCODING'|translate}}", type = QueryParameter.Type.Input, order = 2)
private String QUERY_PARAM_ENCODING = "encoding";
@QueryParameter(label = "{{'DATAPROVIDER.TEXTFILE.SEPRATOR'|translate}}", type = QueryParameter.Type.Input, order = 3)
private String QUERY_PARAM_SEPRATOR = "seprator";
@QueryParameter(label = "{{'DATAPROVIDER.TEXTFILE.ENCLOSURE'|translate}}", type = QueryParameter.Type.Input, order = 4)
private String QUERY_PARAM_ENCLOSURE = "enclosure";
@Override
public boolean doAggregationInDataSource() {
return false;
}
@Override
public String[][] getData() throws Exception {
String basePath = dataSource.get(DS_PARAM_BASE_PATH);
String fileName = query.get(QUERY_PARAM_FILE_NAME);
String encoding = query.get(QUERY_PARAM_ENCODING);
String seprator = query.get(QUERY_PARAM_SEPRATOR);
String enclosure = query.getOrDefault(QUERY_PARAM_ENCLOSURE, "");
encoding = StringUtils.isBlank(encoding) ? "UTF-8" : encoding;
seprator = StringUtils.isBlank(seprator) ? "\t" : seprator;
String fullPath = basePath + fileName;
LOG.info("INFO: Read file from {}", fullPath);
File file = new File(fullPath);
List<String[]> result = null;
try (
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, encoding);
BufferedReader reader = new BufferedReader(isr)
) {
String tempString = null;
result = new LinkedList<>();
int line = 0;
// Read line by line
while ((tempString = reader.readLine()) != null) {
if (StringUtils.isBlank(tempString.trim())) {
continue;
}
if (line++ > resultLimit) {
throw new CBoardException("Cube result count is greater than limit " + resultLimit);
}
List<String> lineList = Arrays.asList(tempString.split(seprator)).stream().map(column -> {
return column.replaceAll(enclosure, "");
}).collect(toList());
result.add(lineList.toArray(new String[lineList.size()]));
}
reader.close();
} catch (Exception e) {
LOG.error("ERROR:" + e.getMessage());
throw new Exception("ERROR:" + e.getMessage(), e);
}
return result.toArray(new String[][]{});
}
}
| 40.589474 | 133 | 0.658454 |
4b8b98e83954993c8cb313de3451a4bd08b287bd | 1,433 | package com.codepath.todoapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by rashmisharma on 8/16/17.
*/
public class ReminderAdaptor extends ArrayAdapter<Reminder> {
public ReminderAdaptor(Context context, List<Reminder> reminders) {
super(context, 0, reminders);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Reminder reminder = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.layout, parent, false);
}
// Lookup view for data population
TextView name = convertView.findViewById(R.id.name);
TextView date = convertView.findViewById(R.id.date);
TextView priority = convertView.findViewById(R.id.priority);
// Populate the data into the template view using the data object
name.setText(reminder.getName());
date.setText(reminder.getDate().toString());
priority.setText(reminder.getPriority());
// Return the completed view to render on screen
return convertView;
}
} | 34.95122 | 100 | 0.695743 |
cc2115951644c28b7a25118b6a57560be0f9b8a4 | 430 | package object;
public class PassFactory {
public static Pass buildPass(Guest guest, Reservation reservation, PartyInstance partyInstance) {
Pass pass = new Pass(guest);
guest.addPass(pass);
pass.setReservation(reservation);
reservation.addPass(pass);
pass.setPartyinstance(partyInstance);
partyInstance.addPass(pass);
return pass;
}
}
| 23.888889 | 98 | 0.632558 |
3695d62e9c0d3ae20a8c88401a1a2e43e1bd7665 | 1,938 | package autoreconnect.config;
import me.shedaniel.clothconfig2.api.AbstractConfigListEntry;
import me.shedaniel.clothconfig2.gui.entries.BaseListEntry;
import me.shedaniel.clothconfig2.gui.entries.IntegerListEntry;
import me.shedaniel.clothconfig2.gui.entries.IntegerListListEntry;
import java.lang.reflect.Field;
import java.util.List;
import static org.apache.logging.log4j.LogManager.getRootLogger;
@SuppressWarnings("rawtypes")
public final class GuiTransformers {
private GuiTransformers() { }
public static List<AbstractConfigListEntry> setMinimum(List<AbstractConfigListEntry> guis, int minimum) {
for (AbstractConfigListEntry gui : guis) {
if (gui instanceof IntegerListEntry) {
((IntegerListEntry) gui).setMinimum(minimum);
}
else if (gui instanceof IntegerListListEntry) {
((IntegerListListEntry) gui).setMinimum(minimum);
}
}
return guis;
}
public static List<AbstractConfigListEntry> disableInsertInFront(List<AbstractConfigListEntry> guis) {
for (AbstractConfigListEntry gui : guis) {
if (gui instanceof BaseListEntry) {
try {
Field insertInFront = BaseListEntry.class.getDeclaredField("insertInFront");
if (insertInFront.canAccess(gui) || insertInFront.trySetAccessible()) {
insertInFront.set(gui, false);
}
} catch (NoSuchFieldException | IllegalAccessException ex) {
getRootLogger().error(ex);
}
}
}
return guis;
}
public static boolean isField(Field field, Class<?> clazz, String fieldName) {
try {
return clazz.getDeclaredField(fieldName).equals(field);
} catch (Exception ex) {
getRootLogger().error(ex);
}
return false;
}
} | 36.566038 | 109 | 0.639319 |
5500e05bee500493fee206b0e48ed79986b618bb | 4,203 | /*
* #%L
* ACS AEM Tools Bundle
* %%
* Copyright (C) 2014 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.wcm.impl;
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
import org.apache.sling.xss.XSSAPI;
import com.day.cq.polling.importer.Importer;
@SlingServlet(paths = "/bin/acs-commons/custom-importers")
public final class CustomPollingImporterListServlet extends SlingSafeMethodsServlet {
private static final long serialVersionUID = -4921197948987912363L;
private transient ServiceTracker tracker;
@Activate
protected void activate(ComponentContext ctx) throws InvalidSyntaxException {
final BundleContext bundleContext = ctx.getBundleContext();
StringBuilder builder = new StringBuilder();
builder.append("(&(");
builder.append(Constants.OBJECTCLASS).append("=").append(Importer.SERVICE_NAME).append(")");
builder.append("(displayName=*))");
Filter filter = bundleContext.createFilter(builder.toString());
this.tracker = new ServiceTracker(bundleContext, filter, null);
this.tracker.open();
}
@Deactivate
protected void deactivate() {
this.tracker.close();
}
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,
IOException {
XSSAPI xssApi = request.adaptTo(XSSAPI.class);
try {
JSONObject result = new JSONObject();
JSONArray list = new JSONArray();
result.put("list", list);
ServiceReference[] services = tracker.getServiceReferences();
if (services != null) {
for (ServiceReference service : services) {
String displayName = PropertiesUtil.toString(service.getProperty("displayName"), null);
String[] schemes = PropertiesUtil.toStringArray(service.getProperty(Importer.SCHEME_PROPERTY));
if (displayName != null && schemes != null) {
for (String scheme : schemes) {
JSONObject obj = new JSONObject();
obj.put("qtip", "");
obj.put("text", displayName);
obj.put("text_xss", xssApi.encodeForJSString(displayName));
obj.put("value", scheme);
list.put(obj);
}
}
}
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
result.write(response.getWriter());
} catch (JSONException e) {
throw new ServletException("Unable to generate importer list", e);
}
}
}
| 39.280374 | 117 | 0.669046 |
7a85546dadc1a20b6dcdcfa985c32db699a70fbe | 4,908 | package com.orbitz.monitoring.lib.timertask;
import com.orbitz.monitoring.api.Monitor;
import com.orbitz.monitoring.api.MonitoringEngine;
import com.orbitz.monitoring.lib.BaseMonitoringEngineManager;
import com.orbitz.monitoring.test.MockDecomposer;
import com.orbitz.monitoring.test.MockMonitorProcessor;
import com.orbitz.monitoring.test.MockMonitorProcessorFactory;
import junit.framework.TestCase;
/**
* Unit tests for the VMStatTimerTask.
*
* <p>(c) 2000-06 Orbitz, LLC. All Rights Reserved.
*
* @author Matt O'Keefe
*/
public class VMStatTimerTaskTest extends TestCase {
private VMStatTimerTask task;
private MockMonitorProcessor processor;
protected void setUp() throws Exception {
super.setUp();
task = new VMStatTimerTask();
processor = new MockMonitorProcessor();
MockMonitorProcessorFactory mockMonitorProcessorFactory =
new MockMonitorProcessorFactory(processor);
MockDecomposer mockDecomposer = new MockDecomposer();
BaseMonitoringEngineManager monitoringEngineManager =
new BaseMonitoringEngineManager(mockMonitorProcessorFactory, mockDecomposer);
monitoringEngineManager.startup();
}
public void testVMStats() {
task.run();
Monitor[] monitors = processor.extractProcessObjects();
boolean garbageCollectorStats = false;
boolean threadStats = false;
boolean heapMemoryStats = false;
boolean nonHeapMemoryStats = false;
boolean finalMemoryStats = false;
boolean heapMemoryPoolStats = false;
boolean nonHeapMemoryPoolStats = false;
for (Monitor monitor: monitors) {
if("JvmStats".equals(monitor.get(Monitor.NAME))) {
if (monitor.getAsString("type").startsWith("GarbageCollector")) {
garbageCollectorStats = true;
assertTrue("Didn't find a count attribute", monitor.hasAttribute("count"));
assertTrue("Didn't find a time attribute", monitor.hasAttribute("time"));
} else if (monitor.getAsString("type").startsWith("Thread")) {
threadStats = true;
assertTrue("Didn't find a count attribute", monitor.hasAttribute("count"));
} else if (monitor.getAsString("type").startsWith("Memory.Heap.memoryUsage")) {
heapMemoryStats = true;
assertTrue("Didn't find a count attribute", monitor.hasAttribute("count"));
assertTrue("Didn't find a percent attribute", monitor.hasAttribute("percent"));
} else if (monitor.getAsString("type").startsWith("Memory.NonHeap.memoryUsage")) {
nonHeapMemoryStats = true;
assertTrue("Didn't find a count attribute", monitor.hasAttribute("count"));
assertTrue("Didn't find a percent attribute", monitor.hasAttribute("percent"));
} else if (monitor.getAsString("type").startsWith("Memory.objectPendingFinalization")) {
finalMemoryStats = true;
assertTrue("Didn't find a count attribute", monitor.hasAttribute("count"));
} else if (monitor.getAsString("type").startsWith("Memory.Heap.Pool")) {
heapMemoryPoolStats = true;
assertTrue("Didn't find a count attribute", monitor.hasAttribute("count"));
if(monitor.getAsString("type").endsWith("memoryUsage")) {
assertTrue("Didn't find a percent attribute", monitor.hasAttribute("percent"));
}
} else if (monitor.getAsString("type").startsWith("Memory.NonHeap.Pool")) {
nonHeapMemoryPoolStats = true;
assertTrue("Didn't find a count attribute", monitor.hasAttribute("count"));
if(monitor.getAsString("type").endsWith("memoryUsage")) {
assertTrue("Didn't find a percent attribute", monitor.hasAttribute("percent"));
}
}
}
}
assertTrue("Didn't find a GarbageCollector Monitor", garbageCollectorStats);
assertTrue("Didn't find a Thread Monitor", threadStats);
assertTrue("Didn't find a Memory.Heap.memoryUsage Monitor", heapMemoryStats);
assertTrue("Didn't find a Memory.NonHeap.memoryUsage Monitor", nonHeapMemoryStats);
assertTrue("Didn't find a Memory.objectPendingFinalization Monitor", finalMemoryStats);
assertTrue("Didn't find a Memory.Heap.Pool Monitor", heapMemoryPoolStats);
assertTrue("Didn't find a Memory.NonHeap.Pool Monitor", nonHeapMemoryPoolStats);
}
protected void tearDown() throws Exception {
MonitoringEngine.getInstance().shutdown();
processor = null;
task = null;
super.tearDown();
}
}
| 50.081633 | 104 | 0.640587 |
22dc7e5cfb5670013ead20ec036d4ef50aaae346 | 3,241 | package frc.robot.util;
public class CommandDetails {
/**
* Enum list of type of commands available
*/
public enum CommandType {
// Runs at a time independent of other commands
PARALLEL,
// Runs after previous command ends
SERIES,
// Runs a parallel command (for now) after a delay specified
TIMEDELAY
}
// Enum instance variable
private CommandType commandType = null;
// Name of command
private String commandName;
// Arguments of the command specified
private String commandArgs = "";
// Time to wait before execution of the command
private double timeDelay;
/**
* Constructor that splits the input and parcels off information
* @param commandInput String input containing the name and arguments for a command
*/
public CommandDetails(String commandInput) {
// Splits commandInput String into an array when spaces are found
String[] commandParts = commandInput.split(" ");
// for (String currentParts : commandParts){
// System.out.print("CURRENT PARTS = " + currentParts + " || ");
// }
// System.out.println();
// Sets commandName as the first string found in the commandInput
this.commandName = commandParts[0];
if (commandParts.length == 1) {
// System.out.println("RETURNING ");
return;
}
switch (commandParts[1]) {
case "-s":
this.commandType = CommandType.SERIES;
if (commandParts.length == 3) {
this.commandArgs = commandParts[2];
}
break;
case "-p":
this.commandType = CommandType.PARALLEL;
if (commandParts.length == 3) {
this.commandArgs = commandParts[2];
}
break;
case "-t":
this.commandType = CommandType.TIMEDELAY;
this.timeDelay = Double.parseDouble(commandParts[2]);
if (commandParts.length == 4) {
this.commandArgs = commandParts[3];
}
break;
default:
System.out.println("U DUN MESSED UP, here's what I saw as commandType = " + commandParts[1]);
break;
}
}
/**
* @return returns the currentTime delay set
*/
public double getDelay() {
return this.timeDelay;
}
/**
* @return Gets command type from enum
*/
public CommandType type() {
return this.commandType;
}
/**
* @return returns command name currently in play
*/
public String name() {
return this.commandName;
}
/**
* @return returns arguemnts for command
*/
public String args() {
return this.commandArgs;
}
/**
* Inbuilt function to return all information on the current state of the class
*/
@Override
public String toString() {
return "Command Name " + this.commandName + " Command Type " + this.commandType + " Command Args "
+ this.commandArgs;
}
} | 27.939655 | 109 | 0.551373 |
f795e9dea23d20af565767fd7a79a674ff38831e | 397 | package payne.framework.pigeon.core.encryption;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
public class MD2WithRSAInvocationSigner extends RSAInvocationSigner implements InvocationSigner {
public MD2WithRSAInvocationSigner() throws NoSuchAlgorithmException, IOException {
super();
}
public String algorithm() {
return "MD2WithRSA";
}
}
| 23.352941 | 98 | 0.780856 |
43ddcd29baca195b86a2b63447c93bc25f51e7ac | 915 | package dev.keva.app;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;
import java.net.ServerSocket;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ApplicationTest {
public static int port = getAvailablePort();
public static final String[] ARGS = {"--p", Integer.toString(port)};
@Test
void testMain() throws Exception {
new Thread(() -> Application.main(ARGS)).start();
TimeUnit.SECONDS.sleep(5);
val jedis = new Jedis("localhost", port);
val pong = jedis.ping();
assertEquals("PONG", pong);
}
@SneakyThrows
public static int getAvailablePort() {
final int port;
try (val serverSocket = new ServerSocket(0)) {
port = serverSocket.getLocalPort();
}
return port;
}
}
| 24.72973 | 72 | 0.655738 |
949d0544ac331365da39d2a901058d955e39e0d9 | 485 | package com.teamwork;
import org.openqa.selenium.WebDriver;
public class TasksPage extends AbstractTeamworkPage {
public TasksPage(WebDriver driver) {
super(driver);
}
public AddNewTaskListModule clickOnAddTaskListBtnAndGoToAddNewTaskListModule() {
return new AddNewTaskListModule(driver);
}
public TaskListPage clickOnTaskListWithNameAndGoToTaskListPage(String taskListName) {
return new TaskListPage(driver);
}
public int getNumberOfTasks() {
return 0;
}
}
| 19.4 | 86 | 0.791753 |
c5865f1644421ccc05ef5795a9fd477878ee8583 | 2,150 | package features.domain.builders;
import features.domain.OneToOneAFoo;
import java.util.List;
import joist.domain.builders.AbstractBuilder;
import joist.domain.builders.DefaultsContext;
import joist.domain.uow.UoW;
@SuppressWarnings("all")
public abstract class OneToOneAFooBuilderCodegen extends AbstractBuilder<OneToOneAFoo> {
public OneToOneAFooBuilderCodegen(OneToOneAFoo instance) {
super(instance);
}
@Override
public OneToOneAFooBuilder defaults() {
return (OneToOneAFooBuilder) super.defaults();
}
@Override
protected void defaults(DefaultsContext c) {
super.defaults(c);
if (name() == null) {
name(defaultName());
}
}
public Long id() {
if (UoW.isOpen() && get().getId() == null) {
UoW.flush();
}
return get().getId();
}
public OneToOneAFooBuilder id(Long id) {
get().setId(id);
return (OneToOneAFooBuilder) this;
}
public String name() {
return get().getName();
}
public OneToOneAFooBuilder name(String name) {
get().setName(name);
return (OneToOneAFooBuilder) this;
}
public OneToOneAFooBuilder with(String name) {
return name(name);
}
protected String defaultName() {
return "name";
}
public OneToOneABarBuilder newOneToOneABar() {
return Builders.aOneToOneABar().oneToOneAFoo((OneToOneAFooBuilder) this);
}
public OneToOneABarBuilder oneToOneABar() {
if (get().getOneToOneABar() == null) {
return null;
}
return Builders.existing(get().getOneToOneABar());
}
public OneToOneAFoo get() {
return (features.domain.OneToOneAFoo) super.get();
}
@Override
public OneToOneAFooBuilder ensureSaved() {
doEnsureSaved();
return (OneToOneAFooBuilder) this;
}
@Override
public OneToOneAFooBuilder use(AbstractBuilder<?> builder) {
return (OneToOneAFooBuilder) super.use(builder);
}
@Override
public void delete() {
OneToOneAFoo.queries.delete(get());
}
public static void deleteAll() {
List<Long> ids = OneToOneAFoo.queries.findAllIds();
for (Long id : ids) {
OneToOneAFoo.queries.delete(OneToOneAFoo.queries.find(id));
}
}
}
| 22.164948 | 88 | 0.686977 |
db78c4554c4a78e6ed0fd9c45f459d5a8a41368b | 1,367 | package io.magnum.antimalware.features;
import java.util.ArrayList;
import android.util.Log;
public class MemoryFeatures extends AbstractFeatures {
private static String TAG = "AntimalwareMemory";
public MemoryFeatures() {
_tags = new String[] { "memActive", "memInactive", "memMapped",
"memFreePages", "memAnonPages", "memFilePages", "memDirtyPages",
"memWritebackPages" };
}
public FeatureValue[] getFeatureVector() {
FileParser fp = new FileParser();
if (!fp.load("/proc/meminfo")) {
Log.w(TAG, "Unable to open /proc/meminfo.");
return null;
}
int active = fp.readInt( 5, 1 );
int inactive = fp.readInt( 6, 1 );
int mapped = fp.readInt( 18, 1 );
fp.close();
if (!fp.load( "/proc/vmstat" )) {
Log.w(TAG, "Unable to open /proc/vmstat.");
return null;
}
int freePages = fp.readInt( 0, 1 );
int anonPages = fp.readInt( 7, 1 );
int filePages = fp.readInt( 9, 1 );
int dirtyPages = fp.readInt( 10, 1 );
int writebackPages = fp.readInt( 11, 1 );
fp.close();
return new FeatureValue[] { new FeatureValue(active),
new FeatureValue(inactive), new FeatureValue(mapped),
new FeatureValue(freePages), new FeatureValue(anonPages),
new FeatureValue(filePages), new FeatureValue(dirtyPages),
new FeatureValue(writebackPages) };
}
}
| 28.479167 | 70 | 0.643745 |
31be33abf350dec2dbcb0f990376b4685613503c | 24,144 | /*
* 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.solr.handler.clustering.carrot2;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.handler.clustering.AbstractClusteringTestCase;
import org.apache.solr.handler.clustering.ClusteringComponent;
import org.apache.solr.handler.clustering.ClusteringEngine;
import org.apache.solr.handler.clustering.SearchClusteringEngine;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.search.DocList;
import org.carrot2.clustering.lingo.LingoClusteringAlgorithm;
import org.carrot2.core.LanguageCode;
import org.carrot2.util.attribute.AttributeUtils;
import org.junit.Test;
/**
*
*/
public class CarrotClusteringEngineTest extends AbstractClusteringTestCase {
@Test
public void testCarrotLingo() throws Exception {
// Note: the expected number of clusters may change after upgrading Carrot2
// due to e.g. internal improvements or tuning of Carrot2 clustering.
final int expectedNumClusters = 10;
checkEngine(getClusteringEngine("default"), expectedNumClusters);
}
@Test
public void testProduceSummary() throws Exception {
// We'll make two queries, one with- and another one without summary
// and assert that documents are shorter when highlighter is in use.
final List<NamedList<Object>> noSummaryClusters = clusterWithHighlighting(false, 80);
final List<NamedList<Object>> summaryClusters = clusterWithHighlighting(true, 80);
assertEquals("Equal number of clusters", noSummaryClusters.size(), summaryClusters.size());
for (int i = 0; i < noSummaryClusters.size(); i++) {
assertTrue("Summary shorter than original document",
getLabels(noSummaryClusters.get(i)).get(1).length() >
getLabels(summaryClusters.get(i)).get(1).length());
}
}
@Test
public void testSummaryFragSize() throws Exception {
// We'll make two queries, one short summaries and another one with longer
// summaries and will check that the results differ.
final List<NamedList<Object>> shortSummaryClusters = clusterWithHighlighting(true, 30);
final List<NamedList<Object>> longSummaryClusters = clusterWithHighlighting(true, 80);
assertEquals("Equal number of clusters", shortSummaryClusters.size(), longSummaryClusters.size());
for (int i = 0; i < shortSummaryClusters.size(); i++) {
assertTrue("Summary shorter than original document",
getLabels(shortSummaryClusters.get(i)).get(1).length() <
getLabels(longSummaryClusters.get(i)).get(1).length());
}
}
private List<NamedList<Object>> clusterWithHighlighting(
boolean enableHighlighting, int fragSize) throws IOException {
// Some documents don't have mining in the snippet
return clusterWithHighlighting(enableHighlighting, fragSize, 1, "mine", numberOfDocs - 7);
}
private List<NamedList<Object>> clusterWithHighlighting(
boolean enableHighlighting, int fragSize, int summarySnippets,
String term, int expectedNumDocuments) throws IOException {
final TermQuery query = new TermQuery(new Term("snippet", term));
final ModifiableSolrParams summaryParams = new ModifiableSolrParams();
summaryParams.add(CarrotParams.SNIPPET_FIELD_NAME, "snippet");
summaryParams.add(CarrotParams.PRODUCE_SUMMARY,
Boolean.toString(enableHighlighting));
summaryParams
.add(CarrotParams.SUMMARY_FRAGSIZE, Integer.toString(fragSize));
summaryParams
.add(CarrotParams.SUMMARY_SNIPPETS, Integer.toString(summarySnippets));
final List<NamedList<Object>> summaryClusters = checkEngine(
getClusteringEngine("echo"), expectedNumDocuments,
expectedNumDocuments, query, summaryParams);
return summaryClusters;
}
@Test
public void testCarrotStc() throws Exception {
checkEngine(getClusteringEngine("stc"), 3);
}
@Test
public void testWithoutSubclusters() throws Exception {
checkClusters(checkEngine(getClusteringEngine("mock"), AbstractClusteringTestCase.numberOfDocs),
1, 1, 0);
}
@Test
public void testExternalXmlAttributesFile() throws Exception {
checkClusters(
checkEngine(getClusteringEngine("mock-external-attrs"), 13),
1, 4, 0);
}
@Test
public void testWithSubclusters() throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(CarrotParams.OUTPUT_SUB_CLUSTERS, true);
checkClusters(checkEngine(getClusteringEngine("mock"), AbstractClusteringTestCase.numberOfDocs), 1, 1, 2);
}
@Test
public void testNumDescriptions() throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(AttributeUtils.getKey(MockClusteringAlgorithm.class, "labels"), 5);
params.set(CarrotParams.NUM_DESCRIPTIONS, 3);
checkClusters(checkEngine(getClusteringEngine("mock"), AbstractClusteringTestCase.numberOfDocs,
params), 1, 3, 0);
}
@Test
public void testClusterScores() throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(AttributeUtils.getKey(MockClusteringAlgorithm.class, "depth"), 1);
List<NamedList<Object>> clusters = checkEngine(getClusteringEngine("mock"),
AbstractClusteringTestCase.numberOfDocs, params);
int i = 1;
for (NamedList<Object> cluster : clusters) {
final Double score = getScore(cluster);
assertNotNull(score);
assertEquals(0.25 * i++, score, 0);
}
}
@Test
public void testOtherTopics() throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(AttributeUtils.getKey(MockClusteringAlgorithm.class, "depth"), 1);
params.set(AttributeUtils.getKey(MockClusteringAlgorithm.class, "otherTopicsModulo"), 2);
List<NamedList<Object>> clusters = checkEngine(getClusteringEngine("mock"),
AbstractClusteringTestCase.numberOfDocs, params);
int i = 1;
for (NamedList<Object> cluster : clusters) {
assertEquals(i++ % 2 == 0 ? true : null, isOtherTopics(cluster));
}
}
@Test
public void testCarrotAttributePassing() throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(AttributeUtils.getKey(MockClusteringAlgorithm.class, "depth"), 1);
params.set(AttributeUtils.getKey(MockClusteringAlgorithm.class, "labels"), 3);
checkClusters(checkEngine(getClusteringEngine("mock"), AbstractClusteringTestCase.numberOfDocs,
params), 1, 3, 0);
}
@Test
public void testLexicalResourcesFromSolrConfigDefaultDir() throws Exception {
checkLexicalResourcesFromSolrConfig("lexical-resource-check",
"online,customsolrstopword,customsolrstoplabel");
}
@Test
public void testLexicalResourcesFromSolrConfigCustomDir() throws Exception {
checkLexicalResourcesFromSolrConfig("lexical-resource-check-custom-resource-dir",
"online,customsolrstopwordcustomdir,customsolrstoplabelcustomdir");
}
private void checkLexicalResourcesFromSolrConfig(String engineName, String wordsToCheck)
throws IOException {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("merge-resources", false);
params.set(AttributeUtils.getKey(
LexicalResourcesCheckClusteringAlgorithm.class, "wordsToCheck"),
wordsToCheck);
// "customsolrstopword" is in stopwords.en, "customsolrstoplabel" is in
// stoplabels.mt, so we're expecting only one cluster with label "online".
final List<NamedList<Object>> clusters = checkEngine(
getClusteringEngine(engineName), 1, params);
assertEquals(getLabels(clusters.get(0)), Collections.singletonList("online"));
}
@Test
public void testSolrStopWordsUsedInCarrot2Clustering() throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("merge-resources", false);
params.set(AttributeUtils.getKey(
LexicalResourcesCheckClusteringAlgorithm.class, "wordsToCheck"),
"online,solrownstopword");
// "solrownstopword" is in stopwords.txt, so we're expecting
// only one cluster with label "online".
final List<NamedList<Object>> clusters = checkEngine(
getClusteringEngine("lexical-resource-check"), 1, params);
assertEquals(getLabels(clusters.get(0)), Collections.singletonList("online"));
}
@Test
public void testSolrStopWordsNotDefinedOnAFieldForClustering() throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams();
// Force string fields to be used for clustering. Does not make sense
// in a real word, but does the job in the test.
params.set(CarrotParams.TITLE_FIELD_NAME, "url");
params.set(CarrotParams.SNIPPET_FIELD_NAME, "url");
params.set("merge-resources", false);
params.set(AttributeUtils.getKey(
LexicalResourcesCheckClusteringAlgorithm.class, "wordsToCheck"),
"online,solrownstopword");
final List<NamedList<Object>> clusters = checkEngine(
getClusteringEngine("lexical-resource-check"), 2, params);
assertEquals(Collections.singletonList("online"), getLabels(clusters.get(0)));
assertEquals(Collections.singletonList("solrownstopword"), getLabels(clusters.get(1)));
}
@Test
public void testHighlightingOfMultiValueField() throws Exception {
final String snippetWithoutSummary = getLabels(clusterWithHighlighting(
false, 30, 3, "multi", 1).get(0)).get(1);
assertTrue("Snippet contains first value", snippetWithoutSummary.contains("First"));
assertTrue("Snippet contains second value", snippetWithoutSummary.contains("Second"));
assertTrue("Snippet contains third value", snippetWithoutSummary.contains("Third"));
final String snippetWithSummary = getLabels(clusterWithHighlighting(
true, 30, 3, "multi", 1).get(0)).get(1);
assertTrue("Snippet with summary shorter than full snippet",
snippetWithoutSummary.length() > snippetWithSummary.length());
assertTrue("Summary covers first value", snippetWithSummary.contains("First"));
assertTrue("Summary covers second value", snippetWithSummary.contains("Second"));
assertTrue("Summary covers third value", snippetWithSummary.contains("Third"));
}
@Test
public void testConcatenatingMultipleFields() throws Exception {
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.TITLE_FIELD_NAME, "title,heading");
params.add(CarrotParams.SNIPPET_FIELD_NAME, "snippet,body");
final List<String> labels = getLabels(checkEngine(
getClusteringEngine("echo"), 1, 1, new TermQuery(new Term("body",
"snippet")), params).get(0));
assertTrue("Snippet contains third value", labels.get(0).contains("Title field"));
assertTrue("Snippet contains third value", labels.get(0).contains("Heading field"));
assertTrue("Snippet contains third value", labels.get(1).contains("Snippet field"));
assertTrue("Snippet contains third value", labels.get(1).contains("Body field"));
}
@Test
public void testHighlightingMultipleFields() throws Exception {
final TermQuery query = new TermQuery(new Term("snippet", "content"));
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.TITLE_FIELD_NAME, "title,heading");
params.add(CarrotParams.SNIPPET_FIELD_NAME, "snippet,body");
params.add(CarrotParams.PRODUCE_SUMMARY, Boolean.toString(false));
final String snippetWithoutSummary = getLabels(checkEngine(
getClusteringEngine("echo"), 1, 1, query, params).get(0)).get(1);
assertTrue("Snippet covers snippet field", snippetWithoutSummary.contains("snippet field"));
assertTrue("Snippet covers body field", snippetWithoutSummary.contains("body field"));
params.set(CarrotParams.PRODUCE_SUMMARY, Boolean.toString(true));
params.add(CarrotParams.SUMMARY_FRAGSIZE, Integer.toString(30));
params.add(CarrotParams.SUMMARY_SNIPPETS, Integer.toString(2));
final String snippetWithSummary = getLabels(checkEngine(
getClusteringEngine("echo"), 1, 1, query, params).get(0)).get(1);
assertTrue("Snippet with summary shorter than full snippet",
snippetWithoutSummary.length() > snippetWithSummary.length());
assertTrue("Snippet covers snippet field", snippetWithSummary.contains("snippet field"));
assertTrue("Snippet covers body field", snippetWithSummary.contains("body field"));
}
@Test
public void testOneCarrot2SupportedLanguage() throws Exception {
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.LANGUAGE_FIELD_NAME, "lang");
final List<String> labels = getLabels(checkEngine(
getClusteringEngine("echo"), 1, 1, new TermQuery(new Term("url",
"one_supported_language")), params).get(0));
assertEquals(3, labels.size());
assertEquals("Correct Carrot2 language", LanguageCode.CHINESE_SIMPLIFIED.name(), labels.get(2));
}
@Test
public void testOneCarrot2SupportedLanguageOfMany() throws Exception {
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.LANGUAGE_FIELD_NAME, "lang");
final List<String> labels = getLabels(checkEngine(
getClusteringEngine("echo"), 1, 1, new TermQuery(new Term("url",
"one_supported_language_of_many")), params).get(0));
assertEquals(3, labels.size());
assertEquals("Correct Carrot2 language", LanguageCode.GERMAN.name(), labels.get(2));
}
@Test
public void testLanguageCodeMapping() throws Exception {
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.LANGUAGE_FIELD_NAME, "lang");
params.add(CarrotParams.LANGUAGE_CODE_MAP, "POLISH:pl");
final List<String> labels = getLabels(checkEngine(
getClusteringEngine("echo"), 1, 1, new TermQuery(new Term("url",
"one_supported_language_of_many")), params).get(0));
assertEquals(3, labels.size());
assertEquals("Correct Carrot2 language", LanguageCode.POLISH.name(), labels.get(2));
}
@Test
public void testPassingOfCustomFields() throws Exception {
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.CUSTOM_FIELD_NAME, "intfield_i:intfield");
params.add(CarrotParams.CUSTOM_FIELD_NAME, "floatfield_f:floatfield");
params.add(CarrotParams.CUSTOM_FIELD_NAME, "heading:multi");
// Let the echo mock clustering algorithm know which custom field to echo
params.add("custom-fields", "intfield,floatfield,multi");
final List<String> labels = getLabels(checkEngine(
getClusteringEngine("echo"), 1, 1, new TermQuery(new Term("url",
"custom_fields")), params).get(0));
assertEquals(5, labels.size());
assertEquals("Integer field", "10", labels.get(2));
assertEquals("Float field", "10.5", labels.get(3));
assertEquals("List field", "[first, second]", labels.get(4));
}
@Test
public void testCustomTokenizer() throws Exception {
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.TITLE_FIELD_NAME, "title");
params.add(CarrotParams.SNIPPET_FIELD_NAME, "snippet");
final List<String> labels = getLabels(checkEngine(
getClusteringEngine("custom-duplicating-tokenizer"), 1, 15, new TermQuery(new Term("title",
"field")), params).get(0));
// The custom test tokenizer duplicates each token's text
assertTrue("First token", labels.get(0).contains("TitleTitle"));
}
@Test
public void testCustomStemmer() throws Exception {
final ModifiableSolrParams params = new ModifiableSolrParams();
params.add(CarrotParams.TITLE_FIELD_NAME, "title");
params.add(CarrotParams.SNIPPET_FIELD_NAME, "snippet");
final List<String> labels = getLabels(checkEngine(
getClusteringEngine("custom-duplicating-stemmer"), 1, 12, new TermQuery(new Term("title",
"field")), params).get(0));
// The custom test stemmer duplicates and lowercases each token's text
assertTrue("First token", labels.get(0).contains("titletitle"));
}
@Test
public void testDefaultEngineOrder() throws Exception {
ClusteringComponent comp = (ClusteringComponent) h.getCore().getSearchComponent("clustering-name-default");
Map<String,SearchClusteringEngine> engines = getSearchClusteringEngines(comp);
assertEquals(
Arrays.asList("stc", "default", "mock"),
new ArrayList<>(engines.keySet()));
assertEquals(
LingoClusteringAlgorithm.class,
((CarrotClusteringEngine) engines.get(ClusteringEngine.DEFAULT_ENGINE_NAME)).getClusteringAlgorithmClass());
}
@Test
public void testDeclarationEngineOrder() throws Exception {
ClusteringComponent comp = (ClusteringComponent) h.getCore().getSearchComponent("clustering-name-decl-order");
Map<String,SearchClusteringEngine> engines = getSearchClusteringEngines(comp);
assertEquals(
Arrays.asList("unavailable", "lingo", "stc", "mock", "default"),
new ArrayList<>(engines.keySet()));
assertEquals(
LingoClusteringAlgorithm.class,
((CarrotClusteringEngine) engines.get(ClusteringEngine.DEFAULT_ENGINE_NAME)).getClusteringAlgorithmClass());
}
@Test
public void testDeclarationNameDuplicates() throws Exception {
ClusteringComponent comp = (ClusteringComponent) h.getCore().getSearchComponent("clustering-name-dups");
Map<String,SearchClusteringEngine> engines = getSearchClusteringEngines(comp);
assertEquals(
Arrays.asList("", "default"),
new ArrayList<>(engines.keySet()));
assertEquals(
MockClusteringAlgorithm.class,
((CarrotClusteringEngine) engines.get(ClusteringEngine.DEFAULT_ENGINE_NAME)).getClusteringAlgorithmClass());
}
private CarrotClusteringEngine getClusteringEngine(String engineName) {
ClusteringComponent comp = (ClusteringComponent) h.getCore()
.getSearchComponent("clustering");
assertNotNull("clustering component should not be null", comp);
CarrotClusteringEngine engine =
(CarrotClusteringEngine) getSearchClusteringEngines(comp).get(engineName);
assertNotNull("clustering engine for name: " + engineName
+ " should not be null", engine);
return engine;
}
private List<NamedList<Object>> checkEngine(CarrotClusteringEngine engine,
int expectedNumClusters) throws IOException {
return checkEngine(engine, numberOfDocs, expectedNumClusters, new MatchAllDocsQuery(), new ModifiableSolrParams());
}
private List<NamedList<Object>> checkEngine(CarrotClusteringEngine engine,
int expectedNumClusters, SolrParams clusteringParams) throws IOException {
return checkEngine(engine, numberOfDocs, expectedNumClusters, new MatchAllDocsQuery(), clusteringParams);
}
private List<NamedList<Object>> checkEngine(CarrotClusteringEngine engine, int expectedNumDocs,
int expectedNumClusters, Query query, SolrParams clusteringParams) throws IOException {
// Get all documents to cluster
return h.getCore().withSearcher(searcher -> {
DocList docList = searcher.getDocList(query, (Query) null, new Sort(), 0,
numberOfDocs);
assertEquals("docList size", expectedNumDocs, docList.matches());
ModifiableSolrParams solrParams = new ModifiableSolrParams();
solrParams.add(clusteringParams);
// Perform clustering
LocalSolrQueryRequest req = new LocalSolrQueryRequest(h.getCore(), solrParams);
Map<SolrDocument,Integer> docIds = new HashMap<>(docList.size());
SolrDocumentList solrDocList = ClusteringComponent.docListToSolrDocumentList( docList, searcher, engine.getFieldsToLoad(req), docIds );
@SuppressWarnings("unchecked")
List<NamedList<Object>> results = (List<NamedList<Object>>) engine.cluster(query, solrDocList, docIds, req);
req.close();
assertEquals("number of clusters: " + results, expectedNumClusters, results.size());
checkClusters(results, false);
return results;
});
}
private void checkClusters(List<NamedList<Object>> results, int expectedDocCount,
int expectedLabelCount, int expectedSubclusterCount) {
for (int i = 0; i < results.size(); i++) {
NamedList<Object> cluster = results.get(i);
checkCluster(cluster, expectedDocCount, expectedLabelCount,
expectedSubclusterCount);
}
}
private void checkClusters(List<NamedList<Object>> results, boolean hasSubclusters) {
for (int i = 0; i < results.size(); i++) {
checkCluster(results.get(i), hasSubclusters);
}
}
private void checkCluster(NamedList<Object> cluster, boolean hasSubclusters) {
List<Object> docs = getDocs(cluster);
assertNotNull("docs is null and it shouldn't be", docs);
for (int j = 0; j < docs.size(); j++) {
Object id = docs.get(j);
assertNotNull("id is null and it shouldn't be", id);
}
List<String> labels = getLabels(cluster);
assertNotNull("labels is null but it shouldn't be", labels);
if (hasSubclusters) {
List<NamedList<Object>> subclusters = getSubclusters(cluster);
assertNotNull("subclusters is null but it shouldn't be", subclusters);
}
}
private void checkCluster(NamedList<Object> cluster, int expectedDocCount,
int expectedLabelCount, int expectedSubclusterCount) {
checkCluster(cluster, expectedSubclusterCount > 0);
assertEquals("number of docs in cluster", expectedDocCount,
getDocs(cluster).size());
assertEquals("number of labels in cluster", expectedLabelCount,
getLabels(cluster).size());
if (expectedSubclusterCount > 0) {
List<NamedList<Object>> subclusters = getSubclusters(cluster);
assertEquals("numClusters", expectedSubclusterCount, subclusters.size());
assertEquals("number of subclusters in cluster",
expectedSubclusterCount, subclusters.size());
}
}
@SuppressWarnings("unchecked")
private List<NamedList<Object>> getSubclusters(NamedList<Object> cluster) {
return (List<NamedList<Object>>) cluster.get("clusters");
}
@SuppressWarnings("unchecked")
private List<String> getLabels(NamedList<Object> cluster) {
return (List<String>) cluster.get("labels");
}
private Double getScore(NamedList<Object> cluster) {
return (Double) cluster.get("score");
}
private Boolean isOtherTopics(NamedList<Object> cluster) {
return (Boolean)cluster.get("other-topics");
}
@SuppressWarnings("unchecked")
private List<Object> getDocs(NamedList<Object> cluster) {
return (List<Object>) cluster.get("docs");
}
}
| 44.464088 | 141 | 0.728587 |
0c8269cd1eba6c9253106e6972077b16d4fcf27b | 7,447 | /*
* 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.aliyuncs.sofa.model.v20190815;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.sofa.transform.v20190815.QueryLinkeBahamutAppcustomcijobbranchlogResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class QueryLinkeBahamutAppcustomcijobbranchlogResponse extends AcsResponse {
private String requestId;
private String resultCode;
private String resultMessage;
private String errorMessage;
private String errorMsgParamsMap;
private String message;
private Long responseStatusCode;
private Boolean success;
private List<ResultItem> result;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getResultCode() {
return this.resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return this.resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public String getErrorMessage() {
return this.errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMsgParamsMap() {
return this.errorMsgParamsMap;
}
public void setErrorMsgParamsMap(String errorMsgParamsMap) {
this.errorMsgParamsMap = errorMsgParamsMap;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getResponseStatusCode() {
return this.responseStatusCode;
}
public void setResponseStatusCode(Long responseStatusCode) {
this.responseStatusCode = responseStatusCode;
}
public Boolean getSuccess() {
return this.success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<ResultItem> getResult() {
return this.result;
}
public void setResult(List<ResultItem> result) {
this.result = result;
}
public static class ResultItem {
private String appId;
private String appName;
private String branch;
private String commitMessage;
private String context;
private Long created;
private String customCIId;
private Boolean deleted;
private Long executionDate;
private Long executionId;
private String id;
private Boolean isLatest;
private String lastCommitId;
private Long lastExecuted;
private Long lastExecuteCost;
private Long lastModified;
private Long pipelineInstanceId;
private Long pipelineTemplateId;
private String pipelineTemplateName;
private String quality;
private String result;
private String status;
private String tenantId;
public String getAppId() {
return this.appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getBranch() {
return this.branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getCommitMessage() {
return this.commitMessage;
}
public void setCommitMessage(String commitMessage) {
this.commitMessage = commitMessage;
}
public String getContext() {
return this.context;
}
public void setContext(String context) {
this.context = context;
}
public Long getCreated() {
return this.created;
}
public void setCreated(Long created) {
this.created = created;
}
public String getCustomCIId() {
return this.customCIId;
}
public void setCustomCIId(String customCIId) {
this.customCIId = customCIId;
}
public Boolean getDeleted() {
return this.deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public Long getExecutionDate() {
return this.executionDate;
}
public void setExecutionDate(Long executionDate) {
this.executionDate = executionDate;
}
public Long getExecutionId() {
return this.executionId;
}
public void setExecutionId(Long executionId) {
this.executionId = executionId;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public Boolean getIsLatest() {
return this.isLatest;
}
public void setIsLatest(Boolean isLatest) {
this.isLatest = isLatest;
}
public String getLastCommitId() {
return this.lastCommitId;
}
public void setLastCommitId(String lastCommitId) {
this.lastCommitId = lastCommitId;
}
public Long getLastExecuted() {
return this.lastExecuted;
}
public void setLastExecuted(Long lastExecuted) {
this.lastExecuted = lastExecuted;
}
public Long getLastExecuteCost() {
return this.lastExecuteCost;
}
public void setLastExecuteCost(Long lastExecuteCost) {
this.lastExecuteCost = lastExecuteCost;
}
public Long getLastModified() {
return this.lastModified;
}
public void setLastModified(Long lastModified) {
this.lastModified = lastModified;
}
public Long getPipelineInstanceId() {
return this.pipelineInstanceId;
}
public void setPipelineInstanceId(Long pipelineInstanceId) {
this.pipelineInstanceId = pipelineInstanceId;
}
public Long getPipelineTemplateId() {
return this.pipelineTemplateId;
}
public void setPipelineTemplateId(Long pipelineTemplateId) {
this.pipelineTemplateId = pipelineTemplateId;
}
public String getPipelineTemplateName() {
return this.pipelineTemplateName;
}
public void setPipelineTemplateName(String pipelineTemplateName) {
this.pipelineTemplateName = pipelineTemplateName;
}
public String getQuality() {
return this.quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public String getResult() {
return this.result;
}
public void setResult(String result) {
this.result = result;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTenantId() {
return this.tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
@Override
public QueryLinkeBahamutAppcustomcijobbranchlogResponse getInstance(UnmarshallerContext context) {
return QueryLinkeBahamutAppcustomcijobbranchlogResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
| 20.628809 | 106 | 0.703908 |
71a42ce21dad19152b048e0457d36b7603b33cda | 11,942 | package com.hck.imagemap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.yoojia.imagemap.ImageMap1;
import net.yoojia.imagemap.core.PrruShape;
import net.yoojia.imagemap.core.RequestShape;
import net.yoojia.imagemap.support.MResource;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.hck.imagemap.Constant.MapConstant;
import com.hck.imagemap.adapter.PrruInfoAdapter;
import com.hck.imagemap.config.GlobalConfig;
import com.hck.imagemap.entity.Floor;
import com.hck.imagemap.entity.PrruInfo;
import com.hck.imagemap.entity.PrruInfoO;
import com.hck.imagemap.utils.Loction;
import com.hck.imagemap.utils.UpLoad;
import com.hck.imagemap.view.CompassViewtran;
public class PrruInfoAcitivity extends Activity {
private ImageMap1 map;
private RelativeLayout layout;
private RelativeLayout layoutTemp;
private Bundle bn;
// private Bitmap bitmap;
private boolean isBack = false;
private TextView tv_prruNum;
private RequestQueue mRequestQueue;
private UpLoad load;
private ListView lv_prru;
private PrruInfoAdapter adapter;
private int num;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
tv_prruNum.setText(getString(R.string.prruNum) + num);
adapter.notifyDataSetChanged();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_prru_info_acitivity);
isBack = false;
initView();
getPrruInfo();
// requestLocationTask();
getCurrentPrruWithRsrpTask();
}
private void initView() {
load = new UpLoad(this);
layout = (RelativeLayout) findViewById(R.id.rl_prru_map);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutTemp = (RelativeLayout) LayoutInflater.from(this).inflate(
R.layout.image_map_item, null);
map = (ImageMap1) layoutTemp.findViewById(R.id.imagemap);
layoutTemp.setLayoutParams(lp);
layout.addView(layoutTemp);
tv_prruNum = (TextView) findViewById(R.id.tv_prruNum);
RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(
10,10);
cv = new CompassViewtran(this);
cv.setId(1);
cv.setImageResource(MResource.getIdByName(getApplication(), "drawable",
"saomiao"));
cv.setLayoutParams(lps);
lv_prru = (ListView) findViewById(R.id.lv_prru);
adapter = new PrruInfoAdapter(this, prruInfos);
lv_prru.setAdapter(adapter);
mRequestQueue = Volley.newRequestQueue(this);
Intent in = this.getIntent();
bn = in.getExtras();
// try {
// bitmap = BitmapFactory.decodeFile(Environment
// .getExternalStorageDirectory() + bn.getString("path"));
// } catch (Exception e) {
// e.printStackTrace();
// }
// if (bitmap == null) {
// finish();
// return;
// }
map.setMapBitmap(MapConstant.bitmap);
}
List<double[]> list = new ArrayList<double[]>();
private ArrayList<PrruInfo> prruInfos = new ArrayList<PrruInfo>();
private ArrayList<String> neCodeArray = new ArrayList<String>();
private ArrayList<PrruInfoO> locationArray = new ArrayList<PrruInfoO>();
private void getPrruInfo() {
Map<String, String> params = new HashMap<String, String>();
params.put("ip", load.getLocaIpOrMac());
params.put("isPush", "2");
JsonObjectRequest newMissRequest = new JsonObjectRequest(
Request.Method.POST, "http://" + GlobalConfig.server_ip
+ "/sva/api/getPrruInfo?floorNo="
+ bn.getInt("floorNo"), new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonobj) {
Log.d("getPrruInfo",
"getPrruInfo:" + jsonobj.toString());
System.out.println("getPrruInfo:" + jsonobj.toString());
JSONArray array = null;
try {
array = jsonobj.getJSONArray("data");
} catch (Exception e) {
Log.e("error", e + "");
}
locationArray.clear();
// tv_prruNum.setText(getString(R.string.prruNum)
// + array.length());
for (int i = 0; i < array.length(); i++) {
try {
JSONObject o = array.getJSONObject(i);
PrruInfoO pinf = new PrruInfoO();
double xSpot = o.getDouble("x");
double ySpot = o.getDouble("y");
Loction loction = new Loction();
double xx = loction
.location(xSpot, ySpot, (Floor) bn
.getSerializable("currFloor"))[0];
double yy = loction
.location(xSpot, ySpot, (Floor) bn
.getSerializable("currFloor"))[1];
pinf.setF(new PointF((float) xx,
(float) yy));
pinf.setNe_code(o.getString("neCode"));
locationArray.add(pinf);
PrruShape prruShape = new PrruShape("prru" + i,
Color.BLACK, null,
PrruInfoAcitivity.this);
prruShape.setValues(String.format(
"%.5f:%.5f:30", xx, yy));
map.addShape(prruShape, false);
// RequestShape requestShape = new RequestShape("fdfd", Color.RED, seismicWaveView, PrruInfoAcitivity.this);
// requestShape.setValues(String.format(
// "%.5f:%.5f:30", xx, yy));
// map.addShape(requestShape, false);
} catch (Exception e) {
Log.e("error", e + "");
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("getPrruInfo", "getPrruInfo:" + error);
Toast.makeText(PrruInfoAcitivity.this,
getString(R.string.prruinfo_norespond),
Toast.LENGTH_SHORT).show();
}
}) {
@Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
mRequestQueue.add(newMissRequest);
}
private CompassViewtran cv;
protected final Handler handlers = new Handler();
private int wrongTag = 0;
private int mDirection;
protected Runnable mCompassViewUpdater = new Runnable()
{
@Override
public void run()
{
if(cv!=null&&f!=null){
mDirection+=4;
cv.updateDirection(mDirection);
RequestShape requestShape = new RequestShape("sdas",
Color.BLUE, cv, PrruInfoAcitivity.this);
requestShape.setValues(String.format("%.5f:%.5f:50",f.x,f.y));
map.addShape(requestShape, false);
}
handlers.postDelayed(mCompassViewUpdater, 20);// 20毫秒后重新执行自己
}
};
private ArrayList<PrruInfo> removeToLengthIsTen(ArrayList<PrruInfo> list) {
Collections.sort(list, new Comparator<PrruInfo>() {
@Override
public int compare(PrruInfo arg0, PrruInfo arg1) {
if (Double.parseDouble(arg0.getRsrp()) < Double
.parseDouble(arg1.getRsrp())) {
return 1;
} else if (Double.parseDouble(arg0.getRsrp()) == Double
.parseDouble(arg1.getRsrp())) {
return 0;
} else {
return -1;
}
}
});// 降序
if (list.size() > 10) {
for (int i = 10; i < list.size(); i++) {
list.remove(10);
}
}
return list;
}
private void getCurrentPrruWithRsrpTask() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getCurrentPrruWithRsrp();
}
}, 1000);
}
// 192.168.0.59:8080
// {"data":[{"timestamp":1476147836900,"id":216096,"gpp":"0_2_2","rsrp":-1100,"userId":"C0A80A6E","enbid":"509146"},
// {"timestamp":1476147836900,"id":216097,"gpp":"0_2_3","rsrp":-900,"userId":"C0A80A6E","enbid":"509146"},
// {"timestamp":1476147836900,"id":216098,"gpp":"0_2_4","rsrp":-1600,"userId":"C0A80A6E","enbid":"509146"},//
// {"timestamp":1476147836900,"id":216099,"gpp":"0_2_5","rsrp":-800,"userId":"C0A80A6E","enbid":"509146"},{"timestamp":1476147836900,"id":216100,"gpp":"0_2_6","rsrp":-1360,"userId":"C0A80A6E","enbid":"509146"},{"timestamp":1476147836900,"id":216101,"gpp":"0_2_7","rsrp":-1100,"userId":"C0A80A6E","enbid":"509146"}]}
PointF f;
private void getCurrentPrruWithRsrp() {
Map<String, String> params = new HashMap<String, String>();
JsonObjectRequest newMissRequest = new JsonObjectRequest(
Request.Method.GET, "http://" + GlobalConfig.server_ip
+ "/sva/api/app/getCurrentPrruWithRsrp?userId="
+ load.getLocaIpOrMac(), new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonobj) {
Log.d("getCurrentPrruWithRsrp", jsonobj.toString());
try {
prruInfos.clear();
JSONArray array = jsonobj.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = (JSONObject) array.get(i);
PrruInfo pi = new PrruInfo();
pi.setGpp(o.getString("gpp"));
pi.setRsrp(o.getString("rsrp"));
prruInfos.add(pi);
}
prruInfos = removeToLengthIsTen(prruInfos);
for (int i = 0; i < locationArray.size(); i++) {
if(prruInfos.get(0).getGpp().equals(locationArray.get(i).getNe_code())){
f = locationArray.get(i).getF();
break;
}
}
num = array.length();
handler.sendEmptyMessage(1);
// tv_prruNum.setText(getString(R.string.prruNum) + num);
// adapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getCurrentPrruWithRsrpTask();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("getCurrentPrruWithRsrperror", error.toString());
getCurrentPrruWithRsrpTask();
Toast.makeText(PrruInfoAcitivity.this,
getString(R.string.prruinfo_norespond),
Toast.LENGTH_SHORT).show();
}
}) {
@Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
mRequestQueue.add(newMissRequest);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.prru_info_acitivity, menu);
return true;
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
isBack = true;
handlers.removeCallbacks(mCompassViewUpdater);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
handlers.postDelayed(mCompassViewUpdater, 20);// 20毫秒后重新执行自己
}
@Override
protected void onDestroy() {
super.onDestroy();
mRequestQueue.cancelAll(this);
isBack = true;
// if (bitmap != null) {
// bitmap.recycle();
// }
// bitmap.recycle();
}
}
| 33.080332 | 316 | 0.674091 |
cd4b9a3772a402b6c2c74393e00ab505ff486529 | 2,593 | package tester;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;
/**
* Created by sazzad on 8/8/17.
*/
public class AESEncryptor extends AESEncryptorBase {
private static final int ITERATION_COUNT = 65536;
private static final int KEY_LENGTH = 128;
private Cipher ecipher;
private Cipher dcipher;
private SecretKey secret;
private byte[] salt = null;
private char[] passPhrase = null;
public AESEncryptor(String passPhrase) {
super(passPhrase);
try {
this.passPhrase = passPhrase.toCharArray();
salt = new byte[8];
SecureRandom rnd = new SecureRandom();
rnd.nextBytes(salt);
SecretKey tmp = getKeyFromPassword(passPhrase);
secret = new SecretKeySpec(tmp.getEncoded(), "AES");
String algorithm = "AES/CBC/PKCS5Padding";
ecipher = Cipher.getInstance(algorithm);
ecipher.init(Cipher.ENCRYPT_MODE, secret);
dcipher = Cipher.getInstance(algorithm);
byte[] iv = ecipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | InvalidParameterSpecException | InvalidKeyException | NoSuchPaddingException e) {
e.printStackTrace();
}
}
public SecretKey getKeyFromPassword(String passPhrase) {
return getKeyFromPassword(passPhrase, salt);
}
public SecretKey getKeyFromPassword(String passPhrase, byte[] salt) {
SecretKeyFactory factory;
SecretKey key = null;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
key = factory.generateSecret(spec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
return key;
}
}
| 34.573333 | 162 | 0.700347 |
554e135874cc1ffbbb1b036bbf06cb640295564e | 15,605 | /*
* Copyright 2014-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.web.http;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.Order;
import org.springframework.session.ExpiringSession;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
/**
* Switches the {@link javax.servlet.http.HttpSession} implementation to be backed by a
* {@link org.springframework.session.Session}.
*
* The {@link SessionRepositoryFilter} wraps the
* {@link javax.servlet.http.HttpServletRequest} and overrides the methods to get an
* {@link javax.servlet.http.HttpSession} to be backed by a
* {@link org.springframework.session.Session} returned by the
* {@link org.springframework.session.SessionRepository}.
*
* The {@link SessionRepositoryFilter} uses a {@link HttpSessionStrategy} (default
* {@link CookieHttpSessionStrategy} to bridge logic between an
* {@link javax.servlet.http.HttpSession} and the
* {@link org.springframework.session.Session} abstraction. Specifically:
*
* <ul>
* <li>The session id is looked up using
* {@link HttpSessionStrategy#getRequestedSessionId(javax.servlet.http.HttpServletRequest)}
* . The default is to look in a cookie named SESSION.</li>
* <li>The session id of newly created {@link org.springframework.session.ExpiringSession}
* is sent to the client using
* <li>The client is notified that the session id is no longer valid with
* {@link HttpSessionStrategy#onInvalidateSession(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}
* </li>
* </ul>
*
* <p>
* The SessionRepositoryFilter must be placed before any Filter that access the
* HttpSession or that might commit the response to ensure the session is overridden and
* persisted properly.
* </p>
*
* @param <S> the {@link ExpiringSession} type.
* @since 1.0
* @author Rob Winch
*/
@Order(SessionRepositoryFilter.DEFAULT_ORDER)
public class SessionRepositoryFilter<S extends ExpiringSession>
extends OncePerRequestFilter {
private static final String SESSION_LOGGER_NAME = SessionRepositoryFilter.class
.getName().concat(".SESSION_LOGGER");
private static final Log SESSION_LOGGER = LogFactory.getLog(SESSION_LOGGER_NAME);
/**
* The session repository request attribute name.
*/
public static final String SESSION_REPOSITORY_ATTR = SessionRepository.class
.getName();
/**
* Invalid session id (not backed by the session repository) request attribute name.
*/
public static final String INVALID_SESSION_ID_ATTR = SESSION_REPOSITORY_ATTR
+ ".invalidSessionId";
private static final String CURRENT_SESSION_ATTR = SESSION_REPOSITORY_ATTR
+ ".CURRENT_SESSION";
/**
* The default filter order.
*/
public static final int DEFAULT_ORDER = Integer.MIN_VALUE + 50;
private final SessionRepository<S> sessionRepository;
private ServletContext servletContext;
private MultiHttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy();
/**
* Creates a new instance.
*
* @param sessionRepository the <code>SessionRepository</code> to use. Cannot be null.
*/
public SessionRepositoryFilter(SessionRepository<S> sessionRepository) {
if (sessionRepository == null) {
throw new IllegalArgumentException("sessionRepository cannot be null");
}
this.sessionRepository = sessionRepository;
}
/**
* Sets the {@link HttpSessionStrategy} to be used. The default is a
* {@link CookieHttpSessionStrategy}.
*
* @param httpSessionStrategy the {@link HttpSessionStrategy} to use. Cannot be null.
*/
public void setHttpSessionStrategy(HttpSessionStrategy httpSessionStrategy) {
if (httpSessionStrategy == null) {
throw new IllegalArgumentException("httpSessionStrategy cannot be null");
}
this.httpSessionStrategy = new MultiHttpSessionStrategyAdapter(
httpSessionStrategy);
}
/**
* Sets the {@link MultiHttpSessionStrategy} to be used. The default is a
* {@link CookieHttpSessionStrategy}.
*
* @param httpSessionStrategy the {@link MultiHttpSessionStrategy} to use. Cannot be
* null.
*/
public void setHttpSessionStrategy(MultiHttpSessionStrategy httpSessionStrategy) {
if (httpSessionStrategy == null) {
throw new IllegalArgumentException("httpSessionStrategy cannot be null");
}
this.httpSessionStrategy = httpSessionStrategy;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(
request, response, this.servletContext);
SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(
wrappedRequest, response);
HttpServletRequest strategyRequest = this.httpSessionStrategy
.wrapRequest(wrappedRequest, wrappedResponse);
HttpServletResponse strategyResponse = this.httpSessionStrategy
.wrapResponse(wrappedRequest, wrappedResponse);
try {
filterChain.doFilter(strategyRequest, strategyResponse);
}
finally {
wrappedRequest.commitSession();
}
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* Allows ensuring that the session is saved if the response is committed.
*
* @author Rob Winch
* @since 1.0
*/
private final class SessionRepositoryResponseWrapper
extends OnCommittedResponseWrapper {
private final SessionRepositoryRequestWrapper request;
/**
* Create a new {@link SessionRepositoryResponseWrapper}.
* @param request the request to be wrapped
* @param response the response to be wrapped
*/
SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request,
HttpServletResponse response) {
super(response);
if (request == null) {
throw new IllegalArgumentException("request cannot be null");
}
this.request = request;
}
@Override
protected void onResponseCommitted() {
this.request.commitSession();
}
}
/**
* A {@link javax.servlet.http.HttpServletRequest} that retrieves the
* {@link javax.servlet.http.HttpSession} using a
* {@link org.springframework.session.SessionRepository}.
*
* @author Rob Winch
* @since 1.0
*/
private final class SessionRepositoryRequestWrapper
extends HttpServletRequestWrapper {
private Boolean requestedSessionIdValid;
private boolean requestedSessionInvalidated;
private final HttpServletResponse response;
private final ServletContext servletContext;
private SessionRepositoryRequestWrapper(HttpServletRequest request,
HttpServletResponse response, ServletContext servletContext) {
super(request);
this.response = response;
this.servletContext = servletContext;
}
/**
* Uses the HttpSessionStrategy to write the session id to the response and
* persist the Session.
*/
private void commitSession() {
HttpSessionWrapper wrappedSession = getCurrentSession();
if (wrappedSession == null) {
if (isInvalidateClientSession()) {
SessionRepositoryFilter.this.httpSessionStrategy
.onInvalidateSession(this, this.response);
}
}
else {
S session = wrappedSession.getSession();
SessionRepositoryFilter.this.sessionRepository.save(session);
if (!isRequestedSessionIdValid()
|| !session.getId().equals(getRequestedSessionId())) {
SessionRepositoryFilter.this.httpSessionStrategy.onNewSession(session,
this, this.response);
}
}
}
@SuppressWarnings("unchecked")
private HttpSessionWrapper getCurrentSession() {
return (HttpSessionWrapper) getAttribute(CURRENT_SESSION_ATTR);
}
private void setCurrentSession(HttpSessionWrapper currentSession) {
if (currentSession == null) {
removeAttribute(CURRENT_SESSION_ATTR);
}
else {
setAttribute(CURRENT_SESSION_ATTR, currentSession);
}
}
@SuppressWarnings("unused")
public String changeSessionId() {
HttpSession session = getSession(false);
if (session == null) {
throw new IllegalStateException(
"Cannot change session ID. There is no session associated with this request.");
}
// eagerly get session attributes in case implementation lazily loads them
Map<String, Object> attrs = new HashMap<String, Object>();
Enumeration<String> iAttrNames = session.getAttributeNames();
while (iAttrNames.hasMoreElements()) {
String attrName = iAttrNames.nextElement();
Object value = session.getAttribute(attrName);
attrs.put(attrName, value);
}
SessionRepositoryFilter.this.sessionRepository.delete(session.getId());
HttpSessionWrapper original = getCurrentSession();
setCurrentSession(null);
HttpSessionWrapper newSession = getSession();
int originalMaxInactiveInterval = session.getMaxInactiveInterval();
original.setSession(newSession.getSession());
newSession.setMaxInactiveInterval(originalMaxInactiveInterval);
for (Map.Entry<String, Object> attr : attrs.entrySet()) {
String attrName = attr.getKey();
Object attrValue = attr.getValue();
newSession.setAttribute(attrName, attrValue);
}
return newSession.getId();
}
@Override
public boolean isRequestedSessionIdValid() {
if (this.requestedSessionIdValid == null) {
String sessionId = getRequestedSessionId();
S session = sessionId == null ? null : getSession(sessionId);
return isRequestedSessionIdValid(session);
}
return this.requestedSessionIdValid;
}
private boolean isRequestedSessionIdValid(S session) {
if (this.requestedSessionIdValid == null) {
this.requestedSessionIdValid = session != null;
}
return this.requestedSessionIdValid;
}
private boolean isInvalidateClientSession() {
return getCurrentSession() == null && this.requestedSessionInvalidated;
}
private S getSession(String sessionId) {
S session = SessionRepositoryFilter.this.sessionRepository
.getSession(sessionId);
if (session == null) {
return null;
}
session.setLastAccessedTime(System.currentTimeMillis());
return session;
}
@Override
public HttpSessionWrapper getSession(boolean create) {
HttpSessionWrapper currentSession = getCurrentSession();
if (currentSession != null) {
return currentSession;
}
String requestedSessionId = getRequestedSessionId();
if (requestedSessionId != null
&& getAttribute(INVALID_SESSION_ID_ATTR) == null) {
S session = getSession(requestedSessionId);
if (session != null) {
this.requestedSessionIdValid = true;
currentSession = new HttpSessionWrapper(session, getServletContext());
currentSession.setNew(false);
setCurrentSession(currentSession);
return currentSession;
}
else {
// This is an invalid session id. No need to ask again if
// request.getSession is invoked for the duration of this request
if (SESSION_LOGGER.isDebugEnabled()) {
SESSION_LOGGER.debug(
"No session found by id: Caching result for getSession(false) for this HttpServletRequest.");
}
setAttribute(INVALID_SESSION_ID_ATTR, "true");
}
}
if (!create) {
return null;
}
if (SESSION_LOGGER.isDebugEnabled()) {
SESSION_LOGGER.debug(
"A new session was created. To help you troubleshoot where the session was created we provided a StackTrace (this is not an error). You can prevent this from appearing by disabling DEBUG logging for "
+ SESSION_LOGGER_NAME,
new RuntimeException(
"For debugging purposes only (not an error)"));
}
S session = SessionRepositoryFilter.this.sessionRepository.createSession();
session.setLastAccessedTime(System.currentTimeMillis());
currentSession = new HttpSessionWrapper(session, getServletContext());
setCurrentSession(currentSession);
return currentSession;
}
// @Override
public ServletContext getServletContext() {
if (this.servletContext != null) {
return this.servletContext;
}
// Servlet 3.0+
// return super.getServletContext();
return null;
}
@Override
public HttpSessionWrapper getSession() {
return getSession(true);
}
@Override
public String getRequestedSessionId() {
return SessionRepositoryFilter.this.httpSessionStrategy
.getRequestedSessionId(this);
}
/**
* Allows creating an HttpSession from a Session instance.
*
* @author Rob Winch
* @since 1.0
*/
private final class HttpSessionWrapper extends ExpiringSessionHttpSession<S> {
HttpSessionWrapper(S session, ServletContext servletContext) {
super(session, servletContext);
}
@Override
public void invalidate() {
super.invalidate();
SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true;
setCurrentSession(null);
SessionRepositoryFilter.this.sessionRepository.delete(getId());
}
}
}
/**
* A delegating implementation of {@link MultiHttpSessionStrategy}.
*/
static class MultiHttpSessionStrategyAdapter implements MultiHttpSessionStrategy {
private HttpSessionStrategy delegate;
/**
* Create a new {@link MultiHttpSessionStrategyAdapter} instance.
* @param delegate the delegate HTTP session strategy
*/
MultiHttpSessionStrategyAdapter(HttpSessionStrategy delegate) {
this.delegate = delegate;
}
public String getRequestedSessionId(HttpServletRequest request) {
return this.delegate.getRequestedSessionId(request);
}
public void onNewSession(Session session, HttpServletRequest request,
HttpServletResponse response) {
this.delegate.onNewSession(session, request, response);
}
public void onInvalidateSession(HttpServletRequest request,
HttpServletResponse response) {
this.delegate.onInvalidateSession(request, response);
}
public HttpServletRequest wrapRequest(HttpServletRequest request,
HttpServletResponse response) {
return request;
}
public HttpServletResponse wrapResponse(HttpServletRequest request,
HttpServletResponse response) {
return response;
}
}
}
| 33.777056 | 207 | 0.730599 |
72006912b95c27c296637fc28e17ec06de459e83 | 1,871 | package Diadoc.Api.httpClient;
import org.jetbrains.annotations.Nullable;
public class DiadocResponseInfo {
@Nullable
private byte[] content;
@Nullable
private Integer retryAfter;
private int statusCode;
@Nullable
private String reason;
@Nullable
private String fileName;
@Nullable
private String contentType;
public DiadocResponseInfo(
@Nullable byte[] content,
@Nullable Integer retryAfter,
int statusCode,
@Nullable String reason,
@Nullable String fileName,
@Nullable String contentType) {
this.content = content;
this.retryAfter = retryAfter;
this.statusCode = statusCode;
this.reason = reason;
this.fileName = fileName;
this.contentType = contentType;
}
public String getFileName() {
return fileName;
}
@Nullable
public byte[] getContent() {
return content;
}
@Nullable
public Integer getRetryAfter() {
return retryAfter;
}
public int getStatusCode() {
return statusCode;
}
@Nullable
public String getReason() {
return reason;
}
public String getContentType() {
return contentType;
}
public static DiadocResponseInfo success(byte[] content, int statusCode) {
return new DiadocResponseInfo(content, null, statusCode, null, null, null);
}
public static DiadocResponseInfo file(byte[] content, int statusCode, String fileName, String contentType){
return new DiadocResponseInfo(content, null, statusCode, null, fileName, contentType);
}
public static DiadocResponseInfo fail(int statusCode, String reason, @Nullable Integer retryAfter) {
return new DiadocResponseInfo(null, retryAfter, statusCode, reason, null, null);
}
}
| 23.987179 | 111 | 0.648851 |
1e3511ac6b295994322b3f76bed4b80c023acdac | 5,579 | /*
* 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.shardingsphere.scaling.mysql.client.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.apache.shardingsphere.db.protocol.mysql.packet.handshake.MySQLAuthMoreDataPacket;
import org.apache.shardingsphere.db.protocol.mysql.packet.handshake.MySQLAuthSwitchRequestPacket;
import org.apache.shardingsphere.db.protocol.mysql.packet.handshake.MySQLHandshakePacket;
import org.apache.shardingsphere.scaling.core.util.ReflectionUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class MySQLNegotiatePackageDecoderTest {
@Mock
private ByteBuf byteBuf;
@Test(expected = IllegalArgumentException.class)
public void assertDecodeUnsupportedProtocolVersion() {
MySQLNegotiatePackageDecoder commandPacketDecoder = new MySQLNegotiatePackageDecoder();
commandPacketDecoder.decode(null, byteBuf, null);
}
@Test
public void assertDecodeHandshakePacket() {
MySQLNegotiatePackageDecoder commandPacketDecoder = new MySQLNegotiatePackageDecoder();
List<Object> actual = new LinkedList<>();
commandPacketDecoder.decode(null, mockHandshakePacket(), actual);
assertHandshakePacket(actual);
}
private ByteBuf mockHandshakePacket() {
String handshakePacket = "000a352e372e32312d6c6f6700090000004a592a1f725a0d0900fff7210200ff8115000000000000000000001a437b30323a4d2b514b5870006d"
+ "7973716c5f6e61746976655f70617373776f72640000000002000000";
byte[] handshakePacketBytes = ByteBufUtil.decodeHexDump(handshakePacket);
ByteBuf result = Unpooled.buffer(handshakePacketBytes.length);
result.writeBytes(handshakePacketBytes);
return result;
}
private void assertHandshakePacket(final List<Object> actual) {
assertThat(actual.size(), is(1));
assertThat(actual.get(0), instanceOf(MySQLHandshakePacket.class));
MySQLHandshakePacket actualPacket = (MySQLHandshakePacket) actual.get(0);
assertThat(actualPacket.getProtocolVersion(), is(0x0a));
assertThat(actualPacket.getServerVersion(), is("5.7.21-log"));
assertThat(actualPacket.getConnectionId(), is(9));
assertThat(actualPacket.getCharacterSet(), is(33));
assertThat(actualPacket.getStatusFlag().getValue(), is(2));
assertThat(actualPacket.getCapabilityFlagsLower(), is(63487));
assertThat(actualPacket.getCapabilityFlagsUpper(), is(33279));
assertThat(actualPacket.getAuthPluginName(), is("mysql_native_password"));
}
@Test
public void assertDecodeAuthSwitchRequestPacket() throws NoSuchFieldException, IllegalAccessException {
MySQLNegotiatePackageDecoder negotiatePackageDecoder = new MySQLNegotiatePackageDecoder();
ReflectionUtil.setFieldValue(negotiatePackageDecoder, "handshakeReceived", true);
List<Object> actual = new LinkedList<>();
negotiatePackageDecoder.decode(null, authSwitchRequestPacket(), actual);
assertPacketByType(actual, MySQLAuthSwitchRequestPacket.class);
}
private ByteBuf authSwitchRequestPacket() {
when(byteBuf.readUnsignedByte()).thenReturn((short) 0, (short) MySQLAuthSwitchRequestPacket.HEADER);
when(byteBuf.getByte(1)).thenReturn((byte) MySQLAuthSwitchRequestPacket.HEADER);
when(byteBuf.bytesBefore((byte) 0)).thenReturn(20);
return byteBuf;
}
@Test
public void assertDecodeAuthMoreDataPacket() throws NoSuchFieldException, IllegalAccessException {
MySQLNegotiatePackageDecoder negotiatePackageDecoder = new MySQLNegotiatePackageDecoder();
ReflectionUtil.setFieldValue(negotiatePackageDecoder, "handshakeReceived", true);
List<Object> actual = new LinkedList<>();
negotiatePackageDecoder.decode(null, authMoreDataPacket(), actual);
assertPacketByType(actual, MySQLAuthMoreDataPacket.class);
}
private ByteBuf authMoreDataPacket() {
when(byteBuf.readUnsignedByte()).thenReturn((short) 0, (short) MySQLAuthMoreDataPacket.HEADER);
when(byteBuf.getByte(1)).thenReturn((byte) MySQLAuthMoreDataPacket.HEADER);
return byteBuf;
}
private void assertPacketByType(final List<Object> actual, final Class<?> clazz) {
assertThat(actual.size(), is(1));
assertThat(actual.get(0), instanceOf(clazz));
}
}
| 46.882353 | 151 | 0.749955 |
828f60bd0a45d418e1f7f2b6e1346842d437a07c | 2,968 | package com.huifer.planar.aset.utils.geo;
import com.huifer.planar.aset.entity.FourBox;
import com.huifer.planar.aset.utils.TmeanLength;
import lombok.extern.slf4j.Slf4j;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import java.util.Arrays;
import java.util.stream.Collectors;
@RunWith(Enclosed.class)
@Slf4j
public class GridUtilTest {
public static class TestCreateGrids {
@Test
public void createGrid() throws Exception {
MapContent map = new MapContent();
map.setTitle("Quickstart");
Polygon polygon = (Polygon) new WKTReader()
.read("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))");
// 单个面的四至
FourBox fourBox = TmeanLength.calcSpaceBetween(
Arrays.stream(polygon.getCoordinates()).collect(Collectors.toList()));
// 输出边框范围
double outLeftX = fourBox.getLeftX() - 1;
double outLeftY = fourBox.getLeftX() - 1;
double outRightX = fourBox.getLeftX() + 1;
double outRightY = fourBox.getLeftX() + 1;
ReferencedEnvelope mapArea = new ReferencedEnvelope(outLeftX, outRightX,
outLeftY, outRightY, null);
ReferencedEnvelope gridArea = new ReferencedEnvelope(outLeftX - 0.001,
outRightX - 0.001,
outLeftY + 0.001, outRightY + 0.001, null);
@SuppressWarnings("rawtypes")
SimpleFeatureSource simpleFeatureByCreateGrids = GridUtil
.getSimpleFeatureByCreateGrids(2, 4, mapArea);
SimpleFeatureCollection features = simpleFeatureByCreateGrids.getFeatures();
SimpleFeatureIterator iterator = features.features();
// 输出每个grid坐标
while (iterator.hasNext()) {
SimpleFeature feature = iterator.next();
// System.out.println( feature.getDefaultGeometry());
log.info("{}", feature.getDefaultGeometry());
}
Style style = GeoStyleUtil.getPolygonStyle(null, "0xff0000", "4",
"0xffffff", "0");
Layer flickrLayer = GeoMapContentUtil.getFlickrLayer();
Layer layer = new FeatureLayer(features, style);
map.addLayer(layer);
map.addLayer(flickrLayer);
JMapFrame.showMap(map);
}
}
}
| 36.641975 | 90 | 0.65027 |
81515f90846cbfe959d169f17ccb4574dc0dd324 | 1,497 | package yandex.cloud.sdk.auth.provider;
public abstract class AbstractCredentialProviderBuilder<BUILDER extends AbstractCredentialProviderBuilder<BUILDER>>
implements CredentialProvider.Builder {
private AuthUpdater updater = null;
private boolean cached = true;
public BUILDER withDefaultBackgroundUpdater() {
this.updater = AuthUpdater.builder().stopOnRuntimeShutdown().build();
//noinspection unchecked
return (BUILDER) this;
}
public BUILDER withBackgroundUpdater(AuthUpdater updater) {
this.updater = updater;
//noinspection unchecked
return (BUILDER) this;
}
public BUILDER withBackgroundUpdater(AuthUpdater.Builder updater) {
this.updater = updater.build();
//noinspection unchecked
return (BUILDER) this;
}
public BUILDER enableCache() {
this.cached = true;
//noinspection unchecked
return (BUILDER) this;
}
public BUILDER disableCache() {
this.cached = false;
//noinspection unchecked
return (BUILDER) this;
}
@Override
public CredentialProvider build() {
CredentialProvider provider = providerBuild();
if (updater != null) {
provider = updater.wrapProvider(provider);
}
if (cached) {
provider = new CachingCredentialProvider(provider);
}
return provider;
}
protected abstract CredentialProvider providerBuild();
}
| 28.245283 | 115 | 0.655311 |
608e3a78106b1755e7457d25760d9848385d2487 | 506 | public class EstimationExample {
public static void main(String[] argv) {
double numTrials = 100000;
double total = 0;
for (int n = 0; n < numTrials; n++) {
// Perform the experiment and observe the value.
double x = Experiment.getValue();
// Record the total so far.
total = total + x;
}
// Compute average at the end.
double avg = total / numTrials;
System.out.println("Mean: " + avg);
}
}
| 28.111111 | 60 | 0.535573 |
ae3e5c669594903a5c8adf51ae1fd75633d3de95 | 2,076 | package se.danielmartensson.CSV2MySQL.components;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.validator.routines.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:mail.properties")
public class SendMail {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
public JavaMailSender emailSender;
@Value("${mail.destination}")
private String destination;
@Value("${mail.subject}")
private String subject;
@Value("${mail.message}")
private String message;
private String sendMailDate;
public void sendAlarmMail() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// Check if we have correct mail
boolean valid = EmailValidator.getInstance().isValid(destination);
if(valid == false)
return;
// Check if we have already send a mail this day
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String currentDate = simpleDateFormat.format(date);
if(currentDate.equals(sendMailDate) == true) {
return;
}else {
sendMailDate = currentDate; // Save
}
logger.info("Sending mail to: " + destination);
// Send mail
simpleMailMessage.setTo(destination);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(message);
emailSender.send(simpleMailMessage);
}
/**
* This is used to reset the send date if we want a new error message by mail for every CSV batch
* @param sendMailDate
*/
public void setSendMailDate(String sendMailDate) {
this.sendMailDate = sendMailDate;
}
}
| 28.833333 | 99 | 0.731696 |
190ec0257f777965a9f8b37bb944683181cb6985 | 990 | package pl.allegro.tech.search.elasticsearch.tools.reindex.query;
import org.assertj.core.api.AbstractAssert;
public class RangeSegmentAssert extends AbstractAssert<RangeSegmentAssert, RangeSegment> {
protected RangeSegmentAssert(RangeSegment actual) {
super(actual, RangeSegmentAssert.class);
}
public static RangeSegmentAssert assertThat(RangeSegment actual) {
return new RangeSegmentAssert(actual);
}
public RangeSegmentAssert hasLowerOpenBound(Double lowerOpenBound) {
isNotNull();
if (!actual.getLowerOpenBound().equals(lowerOpenBound)) {
failWithMessage("Expected lowerOpenBound to be <%f> but was <%f>", lowerOpenBound, actual.getLowerOpenBound());
}
return this;
}
public RangeSegmentAssert hasUpperBound(Double upperBound) {
isNotNull();
if (!actual.getUpperBound().equals(upperBound)) {
failWithMessage("Expected upperBound to be <%f> but was <%f>", upperBound, actual.getUpperBound());
}
return this;
}
} | 31.935484 | 117 | 0.744444 |
3dbdf77b969a9766449b108fd5cfdcf8feed313e | 3,180 | package cn.bearever.mingbase.app.permission.requester;
import android.annotation.SuppressLint;
import android.os.Build;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.GenericLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import java.util.HashMap;
import java.util.Map;
/**
* 管理{@link AsyncPermissionRequester}的单例类
*
* @author : luoming [email protected]
* @date : 2019/8/13
**/
@SuppressLint("RestrictedApi")
public class AsyncPermissionRequesterFactory implements GenericLifecycleObserver {
private static AsyncPermissionRequesterFactory instance;
/**
* 保存Fragment和权限请求Fragment映射关系的map
*/
private Map<LifecycleOwner, AsyncPermissionRequester> mFragmentMap = new HashMap<>();
/**
* 标记权限Fragment的标签
*/
private static final String TAG_FRAGMENT = "AsyncPermissionFragment2019";
public static AsyncPermissionRequesterFactory getInstance() {
if (instance == null) {
synchronized (AsyncPermissionRequesterFactory.class) {
if (instance == null) {
instance = new AsyncPermissionRequesterFactory();
}
}
}
return instance;
}
/**
* 获取当前页面的AsyncPermissionFragment对象
*
* @param fragment 权限请求fragment的宿主
*/
public AsyncPermissionRequester get(Fragment fragment) {
fragment.getLifecycle().addObserver(this);
AsyncPermissionRequester tagFragment = mFragmentMap.get(fragment);
if (tagFragment == null) {
tagFragment = createRequester();
FragmentManager manager = fragment.getChildFragmentManager();
manager.beginTransaction().add(tagFragment, TAG_FRAGMENT).commitNowAllowingStateLoss();
mFragmentMap.put(fragment, tagFragment);
}
return tagFragment;
}
/**
* 获取当前页面的AsyncPermissionFragment对象
*
* @param activity 权限请求activity的宿主
*/
public AsyncPermissionRequester get(FragmentActivity activity) {
activity.getLifecycle().addObserver(this);
AsyncPermissionRequester tagFragment = mFragmentMap.get(activity);
if (tagFragment == null) {
tagFragment = createRequester();
FragmentManager manager = activity.getSupportFragmentManager();
manager.beginTransaction().add(tagFragment, TAG_FRAGMENT).commitNowAllowingStateLoss();
mFragmentMap.put(activity, tagFragment);
}
return tagFragment;
}
/**
* 更新Android版本生成不同的请求器
*
* @return
*/
private AsyncPermissionRequester createRequester() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return new AsyncPermissionRequesterL();
} else {
return new AsyncPermissionRequesterM();
}
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
//移除引用
mFragmentMap.remove(source);
}
}
}
| 31.176471 | 99 | 0.671069 |
480a4c9cf227ad5556848590b14aa22950881bdc | 1,439 | package id.ac.polban.jtk.cursoradapter;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import id.ac.polban.jtk.nearestplace.R;
/**
* Cursor Adapter untuk ListView Place dari cursor database
* Source : https://guides.codepath.com/android/Populating-a-ListView-with-a-CursorAdapter
*
* @editor Mufid Jamaluddin
*/
public class PlaceCursorAdapter extends CursorAdapter
{
/**
* Konstruktor
*
* @param context
* @param cursor
*/
public PlaceCursorAdapter(Context context, Cursor cursor)
{
super(context,cursor,0);
}
/**
* The newView method is used to inflate a new view and return it,
* you don't bind any data to the view at this point.
*
* @param context
* @param cursor
* @param viewGroup
* @return
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
return LayoutInflater.from(context).inflate(R.layout.item_place, parent, false);
}
/**
* The bindView method is used to bind all data to a given view
* such as setting the text on a TextView.
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor)
{
}
}
| 23.983333 | 90 | 0.665045 |
2c778fd1362e3af983369b8680c3c754cb4e808e | 1,116 | package io.github.trashemail.utils;
import io.github.trashemail.Configurations.TrashemailConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.mail.Message;
import java.io.FileWriter;
import java.util.UUID;
@Component
public class SaveMailToHTMLFile {
@Autowired
TrashemailConfig trashemailConfig;
private static final Logger log = LoggerFactory.getLogger(
SaveMailToHTMLFile.class);
public Object saveToFile(String htmlContent){
try {
String filename = UUID.randomUUID().toString() + ".html";
FileWriter myWriter = new FileWriter(
trashemailConfig.getDownloadPath() + filename);
myWriter.write(htmlContent);
myWriter.close();
log.debug("File written to disk: "+ filename);
return filename;
}
catch (Exception e) {
log.error("Unable to save to HTML file. " + e.getMessage());
return null;
}
}
}
| 27.219512 | 72 | 0.666667 |
1a48425dc5619a9aef52f4aab88fcaa025cd4068 | 2,396 | /*
* Copyright (C) 2013 Camptocamp
*
* This file is part of MapFish Print
*
* MapFish Print is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MapFish Print is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MapFish Print. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapfish.print.config.layout;
import org.json.JSONException;
import org.json.JSONWriter;
import org.mapfish.print.InvalidJsonValueException;
import org.mapfish.print.RenderingContext;
import org.mapfish.print.utils.PJsonObject;
import com.itextpdf.text.DocumentException;
/**
* Bean to configure the pages added for each requested maps.
* It's "mainPage" in in the layout definition.
* <p/>
* See http://trac.mapfish.org/trac/mapfish/wiki/PrintModuleServer#ServersideConfiguration
*/
public class MainPage extends Page {
private boolean rotation = false;
public void setRotation(boolean rotation) {
this.rotation = rotation;
}
public void printClientConfig(JSONWriter json) throws JSONException {
MapBlock map = getMap(null);
if (map != null) {
json.key("map");
map.printClientConfig(json);
}
json.key("rotation").value(rotation);
}
/**
* Called for each map requested by the client.
*/
public void render(PJsonObject params, RenderingContext context) throws DocumentException {
//validate the rotation parameter
final float rotation = params.optFloat("rotation", 0.0F);
if (rotation != 0.0F && !this.rotation) {
throw new InvalidJsonValueException(params, "rotation", rotation);
}
super.render(params, context);
}
public MapBlock getMap(String name) {
MapBlock result = null;
for (int i = 0; i < items.size() && result == null; i++) {
Block block = items.get(i);
result = block.getMap(name);
}
return result;
}
}
| 31.946667 | 95 | 0.678214 |
fa221cfd8b9f1eb933e687f2f5386f99f198b629 | 2,292 | package com.github.leecho.spring.cloud.gateway.dubbo.argument.rewirte.variable.render;
import com.github.leecho.spring.cloud.gateway.dubbo.argument.rewirte.variable.VariableRenderContext;
import org.junit.jupiter.api.Test;
import java.util.*;
/**
* @author LIQIU
* @date 2021/7/2 17:18
*/
class SpelVariableRenderTest {
@Test
void render() {
SpelVariableRender variableRender = new SpelVariableRender();
Map<String, Object> arguments = new HashMap<>();
arguments.put("name", "#header['name']");
List<Object> values = new ArrayList<>();
values.add("#query['value']");
values.add("#query['value']");
Map<String, Object> subValues = new HashMap<>();
subValues.put("svalue1", "#query['value']");
subValues.put("svalue2", "#body['text']");
values.add(subValues);
arguments.put("values", values);
arguments.put("value2", "#query['value']");
arguments.put("body", "#body['text']");
arguments.put("array",new String[]{"#query['param']","#body['foo']"});
VariableRenderContext variableRenderContext = new VariableRenderContext(null, null);
Map<String, Object> header = new HashMap<>();
header.put("name", "name1");
variableRenderContext.setVariable("header",header);
Map<String, Object> query = new HashMap<>();
query.put("value", "value1");
query.put("param", "param1");
variableRenderContext.setVariable("query",query);
Map<String, Object> body = new HashMap<>();
body.put("text", "body1");
body.put("foo", "bar");
variableRenderContext.setVariable("body",body);
Map<String, Object> result = variableRender.render(arguments, variableRenderContext);
System.out.println(result);
}
@Test
void renderSample() {
SpelVariableRender variableRender = new SpelVariableRender();
Map<String, Object> template = new HashMap<>();
template.put("name", "#header['name']");
VariableRenderContext variableRenderContext = new VariableRenderContext(null, null);
Map<String, Object> header = new HashMap<>();
header.put("name", "name1");
List<String> query = new ArrayList<>();
query.add("abc");
variableRenderContext.setVariable("header",header);
variableRenderContext.setVariable("query",query);
Map<String, Object> result = variableRender.render(template, variableRenderContext);
System.out.println(result);
}
} | 31.833333 | 100 | 0.704188 |
973e6e8082cf4d001bb36adeace859284deafd8f | 13,718 | package hiteware.com.halfwaythere;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.TextView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity;
import org.robolectric.shadows.ShadowApplication;
import org.robolectric.shadows.ShadowLooper;
import org.robolectric.util.ActivityController;
import java.util.List;
import static junit.framework.Assert.assertNotNull;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
/**
* Created on 5/31/15.
*/
@RunWith(CustomRobolectricRunner.class)
@Config(constants = BuildConfig.class)
public class HalfWayThereFragmentUILogicUnitTest {
private HalfWayThereActivity CreatedActivity;
@Test
public void whenTheAppIsRunningTheServiceWillBeStarted() {
ActivityController controller = Robolectric.buildActivity(HalfWayThereActivity.class).create().start();
HalfWayThereActivity createdActivity = (HalfWayThereActivity) controller.get();
controller.start();
ShadowActivity shadowActivity = shadowOf(createdActivity);
Intent startedIntent = shadowActivity.getNextStartedService();
assertNotNull(startedIntent);
}
@Test
public void whenBroadcastOfStepsIsReceivedThenStepsAreDisplayed() {
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 45);
assertThat(((TextView) CreatedActivity.findViewById(R.id.step_value)).getText().toString(), equalTo("45"));
}
@Test
public void whenBroadcastOfStepsAndGoalAreReceivedThenProgressIsUpdated() {
((TestInjectableApplication) RuntimeEnvironment.application).setMock();
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
int expected = 45;
int expectedGoal = 14000;
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, expected);
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, expectedGoal);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
View expectedCircularProgress = CreatedActivity.findViewById(R.id.circularProgressWithHalfWay);
ProgressUpdateInterface progressUpdate = ((TestInjectableApplication) RuntimeEnvironment.application).testModule.provideProgressUpdate();
verify(progressUpdate, times(1)).SetCircularProgress((CircularProgressWithHalfWay) expectedCircularProgress);
verify(progressUpdate, atLeastOnce()).SetSteps(expected);
verify(progressUpdate, atLeastOnce()).SetGoal(expectedGoal);
}
@Test
public void whenBroadcastOfGoalIsReceivedThenGoalIsDisplayed() {
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 14000);
assertThat(((TextView) CreatedActivity.findViewById(R.id.goal_value)).getText().toString(), equalTo("14000"));
}
@Test
public void whenHalfWayButtonIsClickedThenBroadcastIsSentToService()
{
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 1000);
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 14000);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
StepServiceUnitTestReceiver testReceiver = new StepServiceUnitTestReceiver();
CreatedActivity.registerReceiver(testReceiver, new IntentFilter(StepService.ACTION_HALF_WAY_SET));
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
assertThat(testReceiver.getActualHalfWay(), equalTo(7500));
}
@Test
public void whenHalfWayButtonIsClickedThenProgressUpdateIsUpdated()
{
((TestInjectableApplication) RuntimeEnvironment.application).setMock();
ProgressUpdateInterface progressUpdate = ((TestInjectableApplication) RuntimeEnvironment.application).testModule.provideProgressUpdate();
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 4653);
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 5778);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
verify(progressUpdate, atLeastOnce()).SetHalfWay(5215);
}
@Test
public void whenHalfWayButtonIsClickedThenCountIsUpdatedForHalfWay()
{
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 1333);
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 2000);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
TextView halfWayValue = (TextView) CreatedActivity.findViewById(R.id.HalfWayValue);
assertThat(halfWayValue.getText().toString(), equalTo("1666"));
}
@Test
public void whenHalfWayButtonIsClickedAndIsInvalidBecauseGoalIsZeroThenNoBroadcast()
{
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 0);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
StepServiceUnitTestReceiver testReceiver = new StepServiceUnitTestReceiver();
CreatedActivity.registerReceiver(testReceiver, new IntentFilter(StepService.ACTION_HALF_WAY_SET));
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
assertThat(testReceiver.getActualHalfWay(), equalTo(-1));
}
@Test
public void whenHalfWayButtonIsClickedAndIsInvalidBecauseHalfWayIsGreaterThenTextIsEmptyForHalfWay()
{
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 15000);
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 14000);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
StepServiceUnitTestReceiver testReceiver = new StepServiceUnitTestReceiver();
CreatedActivity.registerReceiver(testReceiver, new IntentFilter(StepService.ACTION_HALF_WAY_SET));
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
TextView halfWayValue = (TextView) CreatedActivity.findViewById(R.id.HalfWayValue);
assertThat(halfWayValue.getText().toString(), equalTo(""));
}
@Test
public void whenHalfWayButtonIsClickedAndIsValidThenItIsClickedWithInvalidThenTextIsEmptyForHalfWay()
{
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 10000);
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 14000);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 15000);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
TextView halfWayValue = (TextView) CreatedActivity.findViewById(R.id.HalfWayValue);
assertThat(halfWayValue.getText().toString(), equalTo(""));
}
@Test
public void whenHalfWayButtonIsClickedAndProgressSaysIsValidThenItIsClickedWithProgressSayingInvalidThenProgressUpdateIsCleared()
{
((TestInjectableApplication) RuntimeEnvironment.application).setMock();
ProgressUpdateInterface progressUpdate = ((TestInjectableApplication) RuntimeEnvironment.application).testModule.provideProgressUpdate();
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
when(progressUpdate.SetHalfWay(anyInt())).thenReturn(true);
View halfWayButton = CreatedActivity.findViewById(R.id.HalfWayToggle);
halfWayButton.performClick();
when(progressUpdate.SetHalfWay(anyInt())).thenReturn(false);
halfWayButton.performClick();
verify(progressUpdate).ClearHalfWay();
}
@Test
public void whenServiceBroadcastsAClearThenTextIsClearedAndProgressUpdateIsCleared()
{
((TestInjectableApplication) RuntimeEnvironment.application).setMock();
ProgressUpdateInterface progressUpdate = ((TestInjectableApplication) RuntimeEnvironment.application).testModule.provideProgressUpdate();
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_CLEAR_HALF_WAY);
verify(progressUpdate).ClearHalfWay();
}
@Test
public void whenServiceBroadcastsAClearThenTextIsCleared()
{
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_STEPS_OCCURRED, StepService.STEPS_OCCURRED, 10000);
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_GOAL_CHANGED, StepService.GOAL_SET, 14000);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
CreatedActivity.findViewById(R.id.HalfWayToggle).performClick();
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_CLEAR_HALF_WAY);
TextView halfWayValue = (TextView) CreatedActivity.findViewById(R.id.HalfWayValue);
assertThat(halfWayValue.getText().toString(), equalTo(""));
}
@Test
public void WhenServiceSendsHalfwaySignalThenTextForHalfWayIsDisplayed()
{
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_HALF_WAY_SET, StepService.HALF_WAY_VALUE, 45);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
TextView halfWayValue = (TextView) CreatedActivity.findViewById(R.id.HalfWayValue);
assertThat(halfWayValue.getText().toString(), equalTo("45"));
}
@Test
public void WhenServiceSendsHalfwaySignalThenProgressIndicatorIsSet()
{
((TestInjectableApplication) RuntimeEnvironment.application).setMock();
ProgressUpdateInterface progressUpdate = ((TestInjectableApplication) RuntimeEnvironment.application).testModule.provideProgressUpdate();
CreatedActivity = Robolectric.buildActivity(HalfWayThereActivity.class).create().start().resume().postResume().get();
BroadcastHelper.sendBroadcast(CreatedActivity, StepService.ACTION_HALF_WAY_SET, StepService.HALF_WAY_VALUE, 100);
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
verify(progressUpdate).SetHalfWay(100);
}
@Test
public void whenActivityIsPausedItUnregistersReceiver() {
ActivityController controller = Robolectric.buildActivity(HalfWayThereActivity.class).create().start();
CreatedActivity = (HalfWayThereActivity) controller.get();
controller.resume();
List<ShadowApplication.Wrapper> registeredReceivers = ShadowApplication.getInstance().getRegisteredReceivers();
assertThat(registeredReceivers.size(), equalTo(1));
controller.pause();
assertThat(ShadowApplication.getInstance().getRegisteredReceivers().size(), equalTo(0));
}
}
| 45.574751 | 145 | 0.772416 |
de372fe7e6d47a23de8698ea5afe94a77e6456ac | 2,324 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.util.xml.reflect;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.GenericDomValue;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author peter
*/
public interface DomGenericInfo {
@Nullable
String getElementName(DomElement element);
@NotNull
List<? extends AbstractDomChildrenDescription> getChildrenDescriptions();
@NotNull
List<? extends DomFixedChildDescription> getFixedChildrenDescriptions();
@NotNull
List<? extends DomCollectionChildDescription> getCollectionChildrenDescriptions();
@NotNull
List<? extends DomAttributeChildDescription> getAttributeChildrenDescriptions();
@Nullable DomFixedChildDescription getFixedChildDescription(@NonNls String tagName);
@Nullable DomFixedChildDescription getFixedChildDescription(@NonNls String tagName, @NonNls String namespaceKey);
@Nullable DomCollectionChildDescription getCollectionChildDescription(@NonNls String tagName);
@Nullable DomCollectionChildDescription getCollectionChildDescription(@NonNls String tagName, @NonNls String namespaceKey);
@Nullable
DomAttributeChildDescription getAttributeChildDescription(@NonNls String attributeName);
@Nullable
DomAttributeChildDescription getAttributeChildDescription(@NonNls String attributeName, @NonNls String namespaceKey);
/**
* @return true, if there's no children in the element, only tag value accessors
*/
boolean isTagValueElement();
@Nullable
GenericDomValue getNameDomElement(DomElement element);
@NotNull
List<? extends CustomDomChildrenDescription> getCustomNameChildrenDescription();
}
| 32.732394 | 125 | 0.796041 |
39e1073c0f67b687ad61d7349cc39ed79ca5c872 | 551 | import java.util.Scanner;
/**
* Created by Atanas on 04/02/2017.
*/
public class p04_SumN_v2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int numbers = Integer.parseInt(s.nextLine());
sum(numbers);
}
static void sum(int n) {
Scanner s1 = new Scanner(System.in);
int b = 0;
for (int i = 0; i < n; i++) {
int a = Integer.parseInt(s1.nextLine());
b += a;
}
System.out.print(b);
}
}
| 20.407407 | 54 | 0.497278 |
071867ec4c1f0403b0706fdfaf500684e3c69ef5 | 381 |
package org.rdv.ui;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
/**
* Interface for panels to implement if they are building popup
* menus dynamically.
*
* @author drewid
*
*/
public interface PopupMenuBuilder {
/// Insert items into menu, return index of next item in menu.
void buildPopupMenu(JPopupMenu menu, MouseEvent e);
}
| 21.166667 | 65 | 0.703412 |
2d92d4f0d65352909036bf0acd0790ff3714c6f4 | 1,245 |
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
public static void main(final String... args) {
int q = scan.nextInt();
while (q-- > 0) {
int n = scan.nextInt();
int[] ints = new int[n];
while (n-- > 0)
ints[ints.length -1-n] = scan.nextInt();
int result = countElements(ints);
System.out.printf("For the array %s the count of elements is: %d\n", Arrays.toString(ints), result);
}
scan.close();
}
static int countElements(int[] ints) {
Map<Integer, CustomInt> mapInts = new HashMap<Integer, CustomInt>();
int cont = 0;
for (int i: ints) {
if (mapInts.get(i) != null) {
mapInts.get(i).increment();
} else {
mapInts.put(i, new CustomInt());
}
}
for (Map.Entry<Integer, CustomInt> entry: mapInts.entrySet()) {
if (mapInts.get(entry.getKey() + 1) != null) cont += entry.getValue().value;
}
return cont;
}
static class CustomInt {
int value = 1;
void increment() { this.value++; }
@Override
public String toString() {
return String.format("%d", this.value);
}
}
}
| 19.153846 | 103 | 0.633735 |
d7773d9b650e6a0105d8b367ec8cfc40fee2c0a0 | 1,052 | package grp.wudi.j2ee.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import grp.wudi.j2ee.dao.NewsDao;
import grp.wudi.j2ee.entity.News;
import grp.wudi.j2ee.service.NewsService;
@Service
public class NewsServiceImpl implements NewsService {
@Autowired
private NewsDao newsDao;
@Override
public News getNewsById(int id) {
return newsDao.findById(id);
}
@Override
public List<News> getNewsByKeyWord(String keyword) {
News news =new News();
news.setTitle(keyword);
return newsDao.findByKeyword(news);
}
@Override
public int addNews(News news) {
return newsDao.addNews(news);
}
@Override
public int updateNews(News news) {
return newsDao.update(news);
}
@Override
public List<News> findall() {
return newsDao.findAll();
}
@Override
public int deleteNews(int id) {
return newsDao.removeNews(id);
}
}
| 20.627451 | 62 | 0.673004 |
b19de62804c301d6d413009de9c740a34586a549 | 7,642 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* 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.slc.sli.domain.utils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slc.sli.common.constants.ParameterConstants;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slc.sli.common.constants.EntityNames;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.Repository;
/**
* Common abstraction to retrieve the EducationOrganization's hierarchy
*
* @author ycao
*
*/
public class EdOrgHierarchyHelper {
private static final Logger LOG = LoggerFactory.getLogger(EdOrgHierarchyHelper.class);
/*
* This class is not spring managed bean because the repo required for
* mongo queries are different depending on the situation, and I don't want to define
* a lot of them in the xml configuration...
*
* The repo must be passed in from the beans managed by spring. This is
* a POJO
*/
static final String SEA_CATEGORIES = "State Education Agency";
private Repository<Entity> repo;
public EdOrgHierarchyHelper(Repository<Entity> repo) {
this.repo = repo;
}
/**
* Determine if this edorg is a SEA
*
* @param entity
* @return boolean
*/
public boolean isSEA(Entity entity) {
return isType(SEA_CATEGORIES, entity);
}
/**
* Determine if this edorg is a LEA
*
* @param entity
* @return boolean
*/
public boolean isLEA(Entity entity) {
return isType("Local Education Agency", entity);
}
/**
* Determine if this edorg is a school
*
* @param entity
* @return boolean
*/
public boolean isSchool(Entity entity) {
return isType("School", entity);
}
@SuppressWarnings("unchecked")
private boolean isType(String type, Entity entity) {
if (entity == null) {
return false;
}
List<String> category = (List<String>) entity.getBody().get("organizationCategories");
if (category != null && category.contains(type)) {
return true;
}
return false;
}
// TODO this logic will need to support multiple parentIds - see us5821
private List<Entity> getParentEdOrg(Entity entity) {
if (entity.getBody().containsKey("parentEducationAgencyReference")) {
@SuppressWarnings("unchecked")
List<String> parentIds = (List<String>) entity.getBody().get("parentEducationAgencyReference");
List<Entity> parents = new ArrayList<Entity>();
if(parentIds!=null) {
for(String parentId: parentIds) {
if(parentId!=null) {
Entity parent = repo.findById(EntityNames.EDUCATION_ORGANIZATION, parentId);
if(parent!=null) {
parents.add(parent);
}
}
}
return parents;
}
}
return null;
}
/**
* Given an school or LEA level entity, returns the top LEA it belongs to
*
* if input is SEA, returns null
*
* @param entity
* @return top level LEA
*/
public List<Entity> getTopLEAOfEdOrg(Entity entity) {
List<Entity> topLEAs = new ArrayList<Entity>();
if (entity.getBody().containsKey("parentEducationAgencyReference")) {
List<Entity> parentEdorgs = getParentEdOrg(entity);
if(parentEdorgs!=null) {
for(Entity parentEdorg: parentEdorgs) {
if (isLEA(parentEdorg)) {
List<Entity> leas = getTopLEAOfEdOrg(parentEdorg);
if(leas!=null) {
topLEAs.addAll(leas);
}
}
}
}
if(!topLEAs.isEmpty()) {
return topLEAs;
}
}
if (isLEA(entity)) {
topLEAs.add(entity);
return topLEAs;
}
return null;
}
/**
* Given an school or LEA level entity, returns all ancestor edOrgs it belongs to (excluding SEAs and including the passed egOrg itself)
*
* If input is SEA, returns null.
*
* @param entity
* @return Ancestors
*/
public Set<Entity> getAncestorsOfEdOrg(Entity entity) {
if (isSEA(entity)) {
return null;
}
// using a set of visited edOrg id's to avoid any issues that might occur with hashCode on Entity
Set<String> visitedIds = new HashSet<String>();
Set<Entity> ancestors = new HashSet<Entity>();
List<Entity> stack = new ArrayList<Entity>(10);
// we are intentionally including the original edOrg -- not doing so breaks the bulk extract in delta mode
ancestors.add(entity);
stack.add(entity);
while (!stack.isEmpty()) {
Entity cur = stack.remove(stack.size() - 1);
// don't let cycles cause us to loop forever
if (visitedIds.contains(cur.getEntityId())) {
continue;
} else {
visitedIds.add(cur.getEntityId());
}
if (cur.getBody().containsKey("parentEducationAgencyReference")) {
List<Entity> parentEdOrgs = getParentEdOrg(cur);
if (parentEdOrgs != null) {
for (Entity parent:parentEdOrgs) {
stack.add(parent);
// do not include SEA in the list of ancestors returned.
if (!isSEA(parent)) {
ancestors.add(parent);
}
}
}
}
}
return ancestors;
}
/**
* Given an edorg entity, returns the SEA it belongs to
*
* @param entity
* @return SEA
*/
public String getSEAOfEdOrg(Entity entity) {
if (isSEA(entity)) {
return entity.getEntityId();
} else {
List<Entity> parentEdorgs = getParentEdOrg(entity);
if(parentEdorgs!=null) {
for(Entity parentEdorg: parentEdorgs) {
String sea = getSEAOfEdOrg(parentEdorg);
if(sea != null) {
return sea;
}
}
}
}
LOG.warn("EdOrg {} is missing parent SEA", entity.getEntityId());
return null;
}
/**
* Get the only SEA from the tenant.
*
* @return SEA entity
*/
public Entity getSEA() {
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria(ParameterConstants.ORGANIZATION_CATEGORIES, NeutralCriteria.OPERATOR_EQUAL, SEA_CATEGORIES));
return repo.findOne(EntityNames.EDUCATION_ORGANIZATION, query);
}
}
| 31.191837 | 140 | 0.573803 |
39f5a45962da4a701015d02a8d6b7d61a59bccb7 | 658 | package cgeo.geocaching;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class cgCacheView {
// layouts & views
public RelativeLayout oneInfo;
public RelativeLayout oneCheckbox;
public CheckBox checkbox;
public ImageView logStatusMark;
public TextView text;
public TextView favourite;
public TextView info;
public RelativeLayout inventory;
public RelativeLayout directionLayout;
public cgDistanceView distance;
public cgCompassMini direction;
public RelativeLayout dirImgLayout;
public ImageView dirImg;
}
| 27.416667 | 42 | 0.775076 |
edf70b42bbca3eaeae3239d1000d8b42aa3f8ea1 | 233 | package com.lambdaschool.starthere.repository;
import com.lambdaschool.starthere.models.Author;
import org.springframework.data.repository.CrudRepository;
public interface AuthorRepository extends CrudRepository<Author, Long>
{
}
| 23.3 | 70 | 0.845494 |
26404a3c69d9253942ecba83af0ee421b6fa7dc0 | 656 | package com.eviltester.gwtshowcase.pageObjects;
import com.thoughtworks.selenium.Selenium;
public class BasicButtonPanel {
private Selenium selenium;
public BasicButtonPanel(Selenium selenium) {
this.selenium = selenium;
}
public boolean isPageTitleCorrect() {
return selenium.getTitle().endsWith("Basic Button");
}
public boolean clickNormalButtonAndExpectPopUp() {
selenium.click("gwt-debug-cwBasicButton-normal");
boolean alert = selenium.isAlertPresent();
boolean ok_so_far = alert;
if(alert){
ok_so_far = selenium.getAlert().contentEquals("Stop poking me!");
}
return ok_so_far;
}
}
| 21.866667 | 69 | 0.716463 |
6ee851218b40ab7183c8d7f4602229308e965c67 | 2,231 | package com.pratapkumar.bakingapplication.utilities;
import android.content.Context;
import android.util.TypedValue;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import static com.pratapkumar.bakingapplication.utilities.Constant.GRID_COLUMN_WIDTH_DEFAULT;
import static com.pratapkumar.bakingapplication.utilities.Constant.GRID_SPAN_COUNT;
public class GridAutofitLayoutManager extends GridLayoutManager {
private int mColumnWidth;
private boolean mColumnWidthChanged = true;
public GridAutofitLayoutManager(Context context, int columnWidth) {
super(context, GRID_SPAN_COUNT);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
public GridAutofitLayoutManager(Context context, int columnWidth,
int orientation, boolean reverseLayout) {
super(context, GRID_SPAN_COUNT, orientation, reverseLayout);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
private int checkedColumnWidth(Context context, int columnWidth) {
if (columnWidth <= 0) {
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
GRID_COLUMN_WIDTH_DEFAULT, context.getResources().getDisplayMetrics());
}
return columnWidth;
}
public void setColumnWidth(int newColumnWidth) {
if (newColumnWidth > 0 && newColumnWidth != mColumnWidth) {
mColumnWidth = newColumnWidth;
mColumnWidthChanged = true;
}
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (mColumnWidthChanged && mColumnWidth > 0) {
int totalSpace;
if (getOrientation() == VERTICAL) {
totalSpace = getWidth() - getPaddingRight() - getPaddingLeft();
} else {
totalSpace = getHeight() - getPaddingTop() - getPaddingBottom();
}
int spanCount = Math.max(1, totalSpace / mColumnWidth);
setSpanCount(spanCount);
mColumnWidthChanged = false;
}
super.onLayoutChildren(recycler, state);
}
}
| 38.465517 | 97 | 0.681309 |
7dad45832bdbac50941547dce3dd02b26999c9ea | 1,125 | package com.chao.wifiscaner.action;
import java.io.File;
import java.util.ArrayList;
import com.chao.wifiscaner.controller.Controller;
import com.chao.wifiscaner.model.PutItem;
import com.chao.wifiscaner.ui.PutActivity;
import com.chao.wifiscaner.utils.FileUtil;
public class GetPutAction extends PutAction {
public GetPutAction(Controller controller) {
super(controller);
}
@Override
public void run(Object... params) {
if(!FileUtil.checkSDcardExist()){
activity.setContentView(controller.nosdcardView);
}else if(getPutItems().size()==0){
activity.setContentView(controller.noputView);
}else{
putItems.clear();
putItems.addAll(getPutItems());
controller.adapter.notifyDataSetChanged();
activity.setContentView(controller.contentView);
}
}
private ArrayList<PutItem> getPutItems(){
File[] files=new File(FileUtil.getBackupPath()).listFiles();
ArrayList<PutItem> trueFiles=new ArrayList<PutItem>();
for(File file:files){
if(file.getName().endsWith(".html")
&&file.getName().startsWith("wsbak")){
trueFiles.add(new PutItem(file));
}
}
return trueFiles;
}
}
| 26.162791 | 62 | 0.738667 |
d3974a149cd6c0fbc4429f5bddfa855387c489d6 | 3,406 | /*
* 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.logging.log4j.perf.jmh;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
/**
* Benchmarks Log4j 2 and Logback ThreadContext/MDC Filter performance.
*/
// HOW TO RUN THIS TEST
// single thread:
// java -jar target/benchmarks.jar ".*MDCFilterBenchmark.*" -f 1 -i 5 -wi 5 -bm sample -tu ns
//
// multiple threads (for example, 4 threads):
// java -jar target/benchmarks.jar ".*MDCFilterBenchmark.*" -f 1 -i 5 -wi 5 -t 4 -si true -bm sample -tu ns
@State(Scope.Benchmark)
public class MDCFilterBenchmark {
// Loggers are Benchmark scope, just like in a real application:
// different threads may use the same logger instance, which may have some lock contention.
Logger log4jLogger;
org.slf4j.Logger slf4jLogger;
@Param({"0", "4"})
public int size;
static int staticSize;
@State(Scope.Thread)
public static class ThreadContextState {
// Thread scope: initialize MDC/ThreadContext here to ensure each thread has some value set
public ThreadContextState() {
for (int i = 0; i < staticSize; i++) {
ThreadContext.put("user" + i, "Apache");
MDC.put("user" + i, "Apache");
}
}
public String message() {
return "This is a test";
}
}
@Setup
public void setUp() {
System.setProperty("log4j.configurationFile", "log4j2-threadContextFilter-perf.xml");
System.setProperty("logback.configurationFile", "logback-mdcFilter-perf.xml");
log4jLogger = LogManager.getLogger(MDCFilterBenchmark.class);
slf4jLogger = LoggerFactory.getLogger(MDCFilterBenchmark.class);
staticSize = size;
}
@TearDown
public void tearDown() {
System.clearProperty("log4j.configurationFile");
System.clearProperty("logback.configurationFile");
}
@Benchmark
public boolean baseline() {
return true;
}
@Benchmark
public void log4jThreadContextFilter(final ThreadContextState state) {
log4jLogger.info(state.message());
}
@Benchmark
public void slf4jMDCFilter(final ThreadContextState state) {
slf4jLogger.info(state.message());
}
}
| 33.392157 | 107 | 0.699354 |
e4d306dc5efdf34431297ec750c20f12efa838d9 | 2,783 |
import java.util.Scanner;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static java.util.stream.Collectors.toCollection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import static java.lang.System.out;
public class SimpleSubsetting {
public static void main(String[] args) throws FileNotFoundException {
// treeSubSetMethod();
// simpleSubSet();
subSetSkipLines();
}
public static void treeSubSetMethod(){
//sub set is not populating - not sure why
//http://www.tutorialspoint.com/java/util/treeset_subset.htm
Integer[] nums = {12,46,52,34,87,123,14,44};
TreeSet <Integer> fullNumsList = new TreeSet<Integer>(new ArrayList<>(Arrays.asList(nums)));
TreeSet <Integer> partNumsList = new TreeSet<Integer>();
out.println("Original List: " + fullNumsList.toString());
partNumsList = (TreeSet<Integer>) fullNumsList.subSet(1,3);
out.println("SubSet of List: " + partNumsList.toString());
out.println(partNumsList.size());
}
public static void simpleSubSet(){
Integer[] nums = {12,46,52,34,87,123,14,44};
ArrayList<Integer> numsList = new ArrayList<>(Arrays.asList(nums));
out.println("Original List: " + numsList.toString());
Set<Integer> fullNumsList = new TreeSet<Integer>(numsList);
Set<Integer> partNumsList = fullNumsList.stream().skip(5).collect(toCollection(TreeSet::new));
out.println("SubSet of List: " + partNumsList.toString());
}
public static void subSetSkipLines() throws FileNotFoundException{
//not behaving as expected
try (BufferedReader br = new BufferedReader(new FileReader("C:\\Jenn Personal\\Packt Data Science\\Chapter 3 Data Cleaning\\stopwords.txt"))) {
br
.lines()
.filter(s -> !s.equals(""))
.forEach(s -> out.println(s));
} catch (IOException ex) {
ex.printStackTrace();
}
//Scanner file = new Scanner(new File("C:\\Jenn Personal\\Packt Data Science\\Chapter 3 Data Cleaning\\stopwords.txt"));
// ArrayList<String> lines = new ArrayList<>();
// while(file.hasNextLine()){
// lines.add(file.nextLine());
// }
// out.println("Original List: " + lines.toString());
// out.println("Original list is " + lines.size() + " elements long");
// Set<String> fullWordsList = new TreeSet<String>(lines);
// Set<String> partWordsList = fullWordsList.stream().skip(2).collect(toCollection(TreeSet::new));
// out.println("SubSet of List: " + partWordsList.toString());
// out.println("Subsetted list is " + partWordsList.size() + " elements long");
//
// file.close();
}
}
| 33.939024 | 146 | 0.681639 |
ebf7548e90bf15fca87215769bc4c2576cd5155e | 1,460 | /*
* Copyright 2019-2020 Elypia CIC and Contributors (https://gitlab.com/Elypia/elypiai/-/graphs/master)
*
* 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.elypia.elypiai.poe.models;
import com.google.gson.annotations.SerializedName;
import java.awt.Color;
/**
* @author [email protected] (Seth Falco)
*/
public enum GemColor {
UNKNOWN(null, null),
@SerializedName("R")
RED("R", Color.RED),
@SerializedName("B")
BLUE("B", Color.BLUE),
@SerializedName("G")
GREEN("G", Color.GREEN),
@SerializedName("W")
WHITE("W", Color.WHITE);
private final String NAME;
private final Color COLOR;
GemColor(String name, Color color) {
NAME = name;
COLOR = color;
}
public String getName() {
return NAME;
}
public Color getColor() {
return COLOR;
}
public static GemColor get(String name) {
for (GemColor color : GemColor.values()) {
if (color.NAME.equals(name))
return color;
}
return UNKNOWN;
}
}
| 21.791045 | 102 | 0.70274 |
ec105bde42945a946e1fae8ba6bb66573aa6f15d | 1,032 | package com.liang.y.daniel.chapter.three;
/* Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise,
display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the
remaining edge. */
import java.util.Scanner;
public class ComputeTrianglePerimeter {
public static void main(String[] args) {
System.out.print("Enter the length of each side of the triangle: ");
Scanner in = new Scanner(System.in);
double firstSide = in.nextDouble();
double secondSide = in.nextDouble();
double thirdSide = in.nextDouble();
boolean isValid = (firstSide + secondSide > thirdSide) && (secondSide + thirdSide > firstSide)
&& (firstSide + thirdSide > secondSide);
if (isValid) {
System.out.println("Triangle Perimeter is: " + (firstSide + secondSide + thirdSide));
} else {
System.out.println("Triangle is invalid.");
}
}
}
| 41.28 | 117 | 0.659884 |
729f321548eb69a3d9e1b53da2dc50c37e3610bc | 1,865 | package uk.gov.ons.ctp.common;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/** Some individual methods for unit tests to reuse */
public class TestHelper {
/**
* Creates an instance of the target class, using its default constructor, and invokes the private
* method, passing the provided params.
*
* @param target the Class owning the provate method
* @param methodName the name of the private method we wish to invoke
* @param params the params we wish to send to the private method
* @return the object that came back from the method!
* @throws Exception Something went wrong with reflection, Get over it.
*/
public static Object callPrivateMethodOfDefaultConstructableClass(
final Class<?> target, final String methodName, final Object... params) throws Exception {
Constructor<?> constructor = target.getConstructor();
Object instance = constructor.newInstance();
Class<?>[] parameterTypes = new Class[params.length];
for (int i = 0; i < params.length; i++) {
parameterTypes[i] = params[i].getClass();
}
Method methodUnderTest = instance.getClass().getDeclaredMethod(methodName, parameterTypes);
methodUnderTest.setAccessible(true);
return methodUnderTest.invoke(instance, params);
}
/**
* Creates and returns Test Date
*
* @param date date to parse
* @return String test date as String
*/
public static String createTestDate(String date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
ZonedDateTime zdt = ZonedDateTime.parse(date, formatter);
ZonedDateTime compareDate = zdt.withZoneSameInstant(ZoneOffset.systemDefault());
return formatter.format(compareDate);
}
}
| 38.854167 | 100 | 0.732976 |
4dae4a72d5d5a024b040615d09da0b4969b4e716 | 3,929 | /*******************************************************************************
* Copyright (C) 2018 Joao Sousa
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package org.rookit.auto.javax;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.rookit.auto.javax.pack.ExtendedPackageElementFactory;
import org.rookit.auto.javax.type.mirror.ExtendedTypeMirrorFactory;
import org.rookit.utils.optional.OptionalFactory;
import org.rookit.utils.primitive.VoidUtils;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementVisitor;
import javax.lang.model.util.Elements;
final class ExtendedElementFactoryImpl implements ExtendedElementFactory {
// due to circular dependency in javax's Element
private final Provider<ExtendedPackageElementFactory> packageFactory;
private final Provider<ElementVisitor<ExtendedElement, Void>> effectiveTypeVisitor;
private final OptionalFactory optionalFactory;
private final ExtendedTypeMirrorFactory mirrorFactory;
private final Elements elements;
private final VoidUtils voidUtils;
@Inject
private ExtendedElementFactoryImpl(
final Provider<ExtendedPackageElementFactory> packageFactory,
final Provider<ElementVisitor<ExtendedElement, Void>> effectiveTypeVisitor,
final OptionalFactory optionalFactory,
final ExtendedTypeMirrorFactory mirrorFactory,
final Elements elements,
final VoidUtils voidUtils) {
this.packageFactory = packageFactory;
this.effectiveTypeVisitor = effectiveTypeVisitor;
this.optionalFactory = optionalFactory;
this.mirrorFactory = mirrorFactory;
this.elements = elements;
this.voidUtils = voidUtils;
}
@Override
public ExtendedElement extend(final Element element) {
return this.optionalFactory.of(element)
.select(ExtendedElement.class)
.orElseGet(() -> createExtendedElement(element));
}
private ExtendedElement createExtendedElement(final Element element) {
return new ExtendedElementImpl(
this.elements,
element,
this.mirrorFactory,
this.effectiveTypeVisitor,
this.voidUtils,
this.packageFactory
);
}
@Override
public String toString() {
return "ExtendedElementFactoryImpl{" +
"packageFactory=" + this.packageFactory +
", effectiveTypeVisitor=" + this.effectiveTypeVisitor +
", optionalFactory=" + this.optionalFactory +
", mirrorFactory=" + this.mirrorFactory +
", elements=" + this.elements +
", voidUtils=" + this.voidUtils +
"}";
}
}
| 42.247312 | 87 | 0.67829 |
69f9a7d282871bf0d5c4fcae69591c7ed0810fd3 | 72 | package com.networknt.oauth.auth;
public interface LightPortalAuth {
}
| 14.4 | 34 | 0.805556 |
4ebc854febdca1b6186345284d51648bea2ea886 | 624 | package com.willian.yunmusic.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.willian.yunmusic.R;
/**
* Created by willian on 2016/7/27.
*/
public class SubNearbyFragment extends Fragment {
private View mView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_nearby, container, false);
initView();
return mView;
}
private void initView() {
}
}
| 20.8 | 103 | 0.727564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.