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 |
|---|---|---|---|---|---|
ea6b75d9bc70f4fa0d8c324c336d0febfe44ee6e | 2,502 | /*
* Copyright 2011-2014 Thomas Bouffard (redfish4ktc)
*
* 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.ktc.soapui.maven.extension.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import com.eviware.soapui.SoapUIProTestCaseRunner;
import com.eviware.soapui.model.testsuite.TestAssertion;
import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.tools.SoapUITestCaseRunner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.Test;
public abstract class AbstractTestErrorHandler {
protected SoapUITestCaseRunner runner;
@Test
public void hasFailures_whenEverythingIsOk() {
assertThat(ErrorHandler.hasFailures(runner)).isFalse();
}
@Test
public void hasFailures_whenRunnerHasFailedTests() throws IllegalAccessException {
initializeFailedTests();
assertThat(ErrorHandler.hasFailures(runner)).isTrue();
}
@Test
public void hasFailures_whenRunnerHasFailedAssertions() throws IllegalAccessException {
initializeFailedAssertions();
assertThat(ErrorHandler.hasFailures(runner)).isTrue();
}
private void initializeFailedTests() throws IllegalAccessException {
List<TestCase> failedTests = new ArrayList<TestCase>();
failedTests.add(mock(TestCase.class));
Field field = FieldUtils.getField(SoapUIProTestCaseRunner.class, "failedTests", true);
FieldUtils.writeField(field, runner, failedTests, true);
}
private void initializeFailedAssertions() throws IllegalAccessException {
List<TestAssertion> failedAssertions = new ArrayList<TestAssertion>();
failedAssertions.add(mock(TestAssertion.class));
Field field = FieldUtils.getField(SoapUIProTestCaseRunner.class, "assertions", true);
FieldUtils.writeField(field, runner, failedAssertions, true);
}
}
| 36.26087 | 91 | 0.756595 |
f3cd46eb8c988a26f93ee79ebee4762fef2a5401 | 1,667 | package com.nh.micro.support;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.nh.micro.db.MicroMetaDao;
import com.nh.micro.rule.engine.core.GroovyLoadUtil;
import org.springframework.jdbc.core.JdbcTemplate;
/**
*
* @author ninghao
*
*/
public class GroovyDbLoadTimer {
private static Logger logger=Logger.getLogger(GroovyDbLoadTimer.class);
public static String dbName="default";
public static String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
GroovyInitDbUtil.dbName = dbName;
//add 201806 ning
GroovyDbLoadTimer.dbName=dbName;
}
public void doJob() throws Exception {
MicroMetaDao microDao=MicroMetaDao.getInstance(GroovyDbLoadTimer.dbName);
String sql="select * from nh_micro_groovy_load_list where valid_flag=1 and time_load_flag=1";
List<Map<String, Object>> retList=microDao.getMicroJdbcTemplate().queryForList(sql);
for (Map rowMap : retList) {
String groovyContent=(String) rowMap.get("groovy_content");
String ruleName=(String) rowMap.get("meta_key");
String publishTime=(String) rowMap.get("publish_time");
try{
if(GroovyLoadUtil.canDbLoad(ruleName)==false){
continue;
}
boolean checkFlag=GroovyLoadUtil.checkStamp(ruleName,publishTime);
if(checkFlag==true){
continue;
}
GroovyLoadUtil.loadGroovyStampCheck(ruleName, groovyContent,publishTime);
}catch(Exception e){
logger.error("load db groovy error name="+ruleName+" publishTime="+publishTime, e);
}
}
}
}
| 30.87037 | 96 | 0.685663 |
d536ff678ee1b10b2e002a2e1b0aad5beea91b52 | 294 | package com.iniesta.cuber.manager.puzzles;
import com.iniesta.cuber.manager.CuberException;
import com.iniesta.cuber.manager.Scramble;
import javafx.scene.image.Image;
public interface MyPuzzle {
String type();
String puzzleName();
Scramble getScramble() throws CuberException;
}
| 17.294118 | 48 | 0.778912 |
dc46791af763fbd60f5864bdcb9ed61ca9ba079a | 264 | import cn.zzq.aix.builder.AIXBuilder;
import cn.zzq.aix.builder.utils.Path;
public class Test {
public static void main(String[] args) {
Path pj = new Path().backward().forward("Scene3D","scene3d-main");
AIXBuilder.main(new String[] { pj.toString() });
}
}
| 26.4 | 68 | 0.700758 |
08f787d27d8f7368528b4a4c2a7e66c2d0c6c08b | 6,226 | /*
* 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.jclouds.openstack.v2_0.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.net.URI;
import javax.inject.Named;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
/**
* For convenience, resources contain links to themselves. This allows a api to easily obtain a
* resource URIs rather than to construct them.
*
* @see <a href= "http://docs.openstack.org/api/openstack-compute/1.1/content/LinksReferences.html"
* />
*/
public class Link {
/**
* Relations associated with resources.
*/
public static enum Relation {
/**
* a versioned link to the resource. These links should be used in cases where the link will
* be followed immediately.
*/
SELF,
/**
* a permanent link to a resource that is appropriate for long term storage.
*/
BOOKMARK,
/**
*
*/
DESCRIBEDBY,
/**
* Indicates that the link's context is a part of a series, and that the next in the series is
* the link target.
*/
NEXT,
/**
* Indicates that the link's context is a part of a series, and that the previous in the
* series is the link target.
*/
PREVIOUS,
ALTERNATE,
/**
* the value returned by the OpenStack service was not recognized.
*/
UNRECOGNIZED;
public String value() {
return name().toLowerCase();
}
public static Relation fromValue(String v) {
try {
return valueOf(v.toUpperCase());
} catch (IllegalArgumentException e) {
return UNRECOGNIZED;
}
}
}
public static Link create(Relation relation, URI href) {
return new Link(relation, null, href);
}
public static Link create(Relation relation, String type, URI href) {
return new Link(relation, Optional.fromNullable(type), href);
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return builder().fromLink(this);
}
public static class Builder {
protected Link.Relation relation;
protected Optional<String> type = Optional.absent();
protected URI href;
/**
* @see Link#getRelation()
*/
public Builder relation(Link.Relation relation) {
this.relation = relation;
return this;
}
/**
* @see Link#getType()
*/
public Builder type(String type) {
this.type = Optional.fromNullable(type);
return this;
}
/**
* @see Link#getHref()
*/
public Builder href(URI href) {
this.href = href;
return this;
}
public Link build() {
return new Link(relation, type, href);
}
public Builder fromLink(Link in) {
return this.relation(in.getRelation()).type(in.getType().orNull()).href(in.getHref());
}
}
@Named("rel")
private final Link.Relation relation;
private final Optional<String> type;
private final URI href;
@ConstructorProperties({ "rel", "type", "href" })
protected Link(Link.Relation relation, Optional<String> type, URI href) {
this.href = checkNotNull(href, "href");
this.relation = checkNotNull(relation, "relation of %s", href);
this.type = (type == null) ? Optional.<String> absent() : type;
}
/**
* There are three kinds of link relations associated with resources. A self link contains a
* versioned link to the resource. These links should be used in cases where the link will be
* followed immediately. A bookmark link provides a permanent link to a resource that is
* appropriate for long term storage. An alternate link can contain an alternate representation
* of the resource. For example, an OpenStack Compute image may have an alternate representation
* in the OpenStack Image service. Note that the type attribute here is used to provide a hint as
* to the type of representation to expect when following the link.
*
* @return the relation of the resource in the current OpenStack deployment
*/
public Link.Relation getRelation() {
return this.relation;
}
/**
* @return the type of the resource or null if not specified
*/
public Optional<String> getType() {
return this.type;
}
/**
* @return the href of the resource
*/
public URI getHref() {
return this.href;
}
@Override
public int hashCode() {
return Objects.hashCode(relation, type, href);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Link that = Link.class.cast(obj);
return Objects.equal(this.relation, that.relation) && Objects.equal(this.type, that.type)
&& Objects.equal(this.href, that.href);
}
protected ToStringHelper string() {
return MoreObjects.toStringHelper(this).omitNullValues().add("relation", relation).add("type", type.orNull())
.add("href", href);
}
@Override
public String toString() {
return string().toString();
}
}
| 29.647619 | 115 | 0.644073 |
9cff36a84049d8840e5568837a2ea1041f378b2b | 1,387 | package pt.tqsua.homework.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pt.tqsua.homework.model.Entity;
import pt.tqsua.homework.model.UVIndex;
import pt.tqsua.homework.service.UVIndexService;
import javax.validation.constraints.NotNull;
import java.util.List;
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = {"localhost", "127.0.0.1"})
public class UVIndexController {
private static final Logger log = LoggerFactory.getLogger(UVIndexController.class);
@Autowired
private UVIndexService service;
@GetMapping("/uvindexes")
public Entity<List<UVIndex>> getAllIndexes() {
return service.getAllIndexes();
}
@GetMapping("/uvindexes/{locationId}")
public Entity<List<UVIndex>> getIndexesByLocation(@PathVariable @NotNull int locationId) {
log.debug("GET UVIndex for location {}", locationId);
return service.getLocationIndex(locationId);
}
@GetMapping("/uvindexes/{locationId}/{day}")
public Entity<List<UVIndex>> getIndexesByLocation(@PathVariable @NotNull int locationId, @PathVariable @NotNull int day) {
log.debug("GET UVIndex for location {} and day {}", locationId, day);
return service.getLocationIndexByDay(locationId, day);
}
}
| 33.02381 | 126 | 0.741889 |
b70af4a5ec2ec573e48b142fae042ea11393aef2 | 7,015 | package org.gigbuddy.startup;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.http.HttpServlet;
import org.gigbuddy.events.Event;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
public class EventScraper extends HttpServlet {
private static final long serialVersionUID = -7949675392030436183L;
List<WebElement> events;
List<Event> eventList = new ArrayList<>();
WebElement temp;
Event event;
public void init() {
long repeat = (1000*60)*60*24;
Timer timer = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
eventScraper();
}
};
timer.schedule(tt, 0, repeat);
}
private java.sql.Date normalizeDate(String date) {
//Saturday 22nd October at 7:30 PM
//Desired format Saturday 22nd October
String currentYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
StringBuffer sb = new StringBuffer(date.replaceAll("\n", ""));
int indexOfTH = sb.toString().indexOf("th ");
if (indexOfTH < 0) {
indexOfTH = sb.toString().indexOf("st ");
if (indexOfTH < 0) {
indexOfTH = sb.toString().indexOf("nd ");
if (indexOfTH < 0) {
indexOfTH = sb.toString().indexOf("rd ");
}
}
}
sb.delete(indexOfTH, indexOfTH+2);
//Saturday 22 October at 7:30 PM
//deleting everything after at
sb.delete(sb.indexOf(" at "), sb.length());
//append current year
sb.append(" "+currentYear);
SimpleDateFormat sdf = new SimpleDateFormat("E dd MMM yyyy");
java.sql.Date dateSqlDate = null;
Calendar c = Calendar.getInstance();
try {
Date dateDate = sdf.parse(sb.toString());
c.add(Calendar.MONTH, -1);
if (dateDate.before(c.getTime())) {
c.setTime(dateDate);
c.add(Calendar.YEAR, 1);
dateDate.setTime(c.getTime().getTime());
}
dateSqlDate = new java.sql.Date(dateDate.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dateSqlDate;
}
private void eventScraper() {
eventList.clear();
HtmlUnitDriver driver = new HtmlUnitDriver(false);
driver.get("http://www.gigsandtours.com/search?browseorder=soonest&distance=0&availableonly=False&showfavourites=True&se=True&pageSize=30&pageIndex=1");
//Getting number of pages
String pageNum = driver.findElement(By.xpath(".//*[@id='search-results']/nav/p")).getText().trim();
//The last two number is the actual page number
pageNum = pageNum.substring(pageNum.length()-2).trim();
int pageNumInt = Integer.parseInt(pageNum);
//looping through all the pages
for (int i=2; i<=pageNumInt+1; i++) {
//getting the number of events
temp = driver.findElement(By.id("search-results"));
events = temp.findElements(By.tagName("article"));
//looping through events
for (int k=0; k<events.size(); k++) {
try {
temp = events.get(k).findElement(By.xpath("div[1]"));
event = new Event();
event.setTitle(temp.findElement(By.xpath("h3")).getText());
//double quote to escape it in sql
event.setTitle(event.getTitle().replaceAll("'", "''"));
event.setLocation(temp.findElement(By.xpath("p[1]")).getText());
event.setLocation(event.getLocation().replaceAll("'", "''"));
event.setTime(temp.findElement(By.xpath("p[2]")).getText().trim());
event.setDate(normalizeDate(event.getTime()));
event.setTime(event.getTime().substring(event.getTime().indexOf(" at ")+4, event.getTime().length()));
eventList.add(event);
}
catch (NoSuchElementException nsee) {
System.out.println("Skipped one");
}
}
driver.get("http://www.gigsandtours.com/search?browseorder=soonest&distance=0&availableonly=False&showfavourites=True&se=True&pageSize=30&pageIndex="+i);
}
driver.close();
System.out.println("Starting wrintinh data into database");
Calendar cToday = Calendar.getInstance();
Calendar cSelectedDate = Calendar.getInstance();
java.sql.Date dSelectedDate;
String log = "";
try (Connection c = DriverManager.getConnection(getServletContext().getInitParameter("databaseURL"),getServletContext().getInitParameter("databaseUsername"),getServletContext().getInitParameter("databasePassword"));
Statement s = c.createStatement();
Statement sQuery = c.createStatement();
ResultSet rs = sQuery.executeQuery("SELECT * FROM eventsbyusers")) {
while(rs.next()) {
//Deleting dates from eventsbyusers that are sooner then current date
dSelectedDate = rs.getDate("date");
cSelectedDate.setTime(dSelectedDate);
if (cSelectedDate.before(cToday)) {
s.executeUpdate("DELETE FROM eventsbyusers WHERE date = '"+rs.getString("date")+"'");
}
}
s.executeUpdate("TRUNCATE TABLE events");
for (int i=0; i<eventList.size(); i++) {
try {
s.executeUpdate("INSERT INTO events (title,location,date,time) VALUES ('"+eventList.get(i).getTitle()+"','"+eventList.get(i).getLocation()+"','"+eventList.get(i).getDate()+"','"+eventList.get(i).getTime()+"')");
}
catch (MySQLIntegrityConstraintViolationException micve) {
}
}
ResultSet rsNew = sQuery.executeQuery("SELECT * FROM eventsbyusers");
while(rsNew.next()) {
try {
s.executeUpdate("INSERT INTO events (title,location,date,time) VALUES ('"+rsNew.getString("title")+"','"+rsNew.getString("location")+"','"+rsNew.getString("date")+"','"+rsNew.getString("time")+"')");
}
catch (MySQLIntegrityConstraintViolationException micve) {
System.out.println("Duplicate Entry");
}
}
} catch (SQLException e) {
e.printStackTrace();
log = e.getMessage();
}
System.out.println("Events table updated succesfully");
try {
File eventScraperLog = new File("/home/gigbud5/public_html/eventScraperLog.txt");
eventScraperLog.createNewFile();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date currentDate = new Date();
BufferedWriter bw = new BufferedWriter(new FileWriter(eventScraperLog));
if (log.isEmpty()) bw.write("Events table updated successfully" +dateFormat.format(currentDate));
else bw.write(log);
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 37.116402 | 218 | 0.679971 |
3046127e20a09531de3f4ed69a20a8a58e3a7e23 | 404 | package com.huobi.client.model.event;
import com.huobi.client.model.TradeClearing;
public class TradeClearingEvent {
private String ch;
private TradeClearing data;
public String getCh() {
return ch;
}
public void setCh(String ch) {
this.ch = ch;
}
public TradeClearing getData() {
return data;
}
public void setData(TradeClearing data) {
this.data = data;
}
}
| 14.962963 | 44 | 0.680693 |
4cb4c6f4a110003bf4ed01435ef2b24612627984 | 401 | package org.summarine.demo;
import org.summarine.core.annotation.Inject;
import org.summarine.core.annotation.MyComponent;
import org.summarine.core.annotation.MyQualifier;
@MyComponent
public class Worker {
@Inject
@MyQualifier("bigMachine")
private ITool tool;
public String weed() {
return "I'm using the " + tool.using() + ", the weed is " + tool.weed() + ".";
}
}
| 22.277778 | 86 | 0.688279 |
5f75956491052f4a20beed99d757a34577bac34e | 5,287 | package nl.jpelgrm.retrofit2oauthrefresh.api;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.IOException;
import nl.jpelgrm.retrofit2oauthrefresh.BuildConfig;
import nl.jpelgrm.retrofit2oauthrefresh.api.objects.AccessToken;
import okhttp3.Authenticator;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
public static final String API_BASE_URL = "https://api.example.com";
public static final String API_OAUTH_REDIRECT = "nl.jpelgrm.retrofit2oauthrefresh://oauth";
private static OkHttpClient.Builder httpClient;
private static Retrofit.Builder builder;
private static Context mContext;
private static AccessToken mToken;
public static <S> S createService(Class<S> serviceClass) {
httpClient = new OkHttpClient.Builder();
builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, AccessToken accessToken, Context c) {
httpClient = new OkHttpClient.Builder();
builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
if(accessToken != null) {
mContext = c;
mToken = accessToken;
final AccessToken token = accessToken;
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Accept", "application/json")
.header("Content-type", "application/json")
.header("Authorization",
token.getTokenType() + " " + token.getAccessToken())
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
httpClient.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
if(responseCount(response) >= 2) {
// If both the original call and the call with refreshed token failed,
// it will probably keep failing, so don't try again.
return null;
}
// We need a new client, since we don't want to make another call using our client with access token
APIClient tokenClient = createService(APIClient.class);
Call<AccessToken> call = tokenClient.getRefreshAccessToken(mToken.getRefreshToken(),
mToken.getClientID(), mToken.getClientSecret(), API_OAUTH_REDIRECT,
"refresh_token");
try {
retrofit2.Response<AccessToken> tokenResponse = call.execute();
if(tokenResponse.code() == 200) {
AccessToken newToken = tokenResponse.body();
mToken = newToken;
SharedPreferences prefs = mContext.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);
prefs.edit().putBoolean("oauth.loggedin", true).apply();
prefs.edit().putString("oauth.accesstoken", newToken.getAccessToken()).apply();
prefs.edit().putString("oauth.refreshtoken", newToken.getRefreshToken()).apply();
prefs.edit().putString("oauth.tokentype", newToken.getTokenType()).apply();
return response.request().newBuilder()
.header("Authorization", newToken.getTokenType() + " " + newToken.getAccessToken())
.build();
} else {
return null;
}
} catch(IOException e) {
return null;
}
}
});
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
private static int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
}
| 41.960317 | 134 | 0.578022 |
43cf756863c5e6e116170ee9f316f0a50b5d3c33 | 13,557 | package com.spayker.account.repository;
import com.spayker.account.domain.Account;
import com.spayker.account.domain.Training;
import com.spayker.account.util.factory.AccountFactory;
import com.spayker.account.util.factory.TrainingFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace.NONE;
@DataJpaTest
@AutoConfigureTestDatabase(replace = NONE)
public class TrainingRepositoryTest {
@Autowired
private AccountRepository accountRepository;
@Autowired
private TrainingRepository trainingRepository;
@AfterEach
public void clearRecordsInDb(){
trainingRepository.deleteAll();
accountRepository.deleteAll();
}
private static Stream<Arguments> provideCommonTrainings() {
return Stream.of(
Arguments.of(TrainingFactory.createTraining("miBand3", "v1.0", "jogging", 12000, 3500, new Date(), AccountFactory.createDummyAccount())),
Arguments.of(TrainingFactory.createTraining("miBand4", "v1.2", "cycling", 12000, 5500, new Date(), AccountFactory.createDummyAccount()))
);
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Saves trainings by repository API")
public void shouldSaveAccount(Training training){
// given
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
// then
assertNotNull(savedTraining);
assertEquals(training.getDeviceName(), savedTraining.getDeviceName());
assertEquals(training.getDeviceFirmware(), savedTraining.getDeviceFirmware());
assertEquals(training.getType(), savedTraining.getType());
assertEquals(training.getTime(), savedTraining.getTime());
assertEquals(training.getCalories(), savedTraining.getCalories());
assertEquals(training.getAccount(), savedTraining.getAccount());
assertEquals(training.getCreatedDate(), savedTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved trainings by their ids")
public void shouldFindTrainingById(Training training) {
// given
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
Optional<Training> foundEntity = trainingRepository.findById(savedTraining.getId());
// then
assertNotNull(savedTraining);
assertTrue(foundEntity.isPresent());
Training foundTraining = foundEntity.get();
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved trainings by their device name")
public void shouldFindTrainingByDeviceName(Training training) {
// given
final int expectedFoundTraining = 1;
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
List<Training> foundTrainings = trainingRepository.findByDeviceName(savedTraining.getDeviceName());
// then
assertNotNull(savedTraining);
assertFalse(foundTrainings.isEmpty());
assertEquals(expectedFoundTraining, foundTrainings.size());
Training foundTraining = foundTrainings.get(0);
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved trainings by their device firmware")
public void shouldFindTrainingByDeviceFirmware(Training training) {
// given
final int expectedFoundTraining = 1;
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
List<Training> foundTrainings = trainingRepository.findByDeviceFirmware(savedTraining.getDeviceFirmware());
// then
assertNotNull(savedTraining);
assertFalse(foundTrainings.isEmpty());
assertEquals(expectedFoundTraining, foundTrainings.size());
Training foundTraining = foundTrainings.get(0);
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved trainings by their callories")
public void shouldFindTrainingByCalories(Training training) {
// given
final int expectedFoundTraining = 1;
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
List<Training> foundTrainings = trainingRepository.findByCalories(savedTraining.getCalories());
// then
assertNotNull(savedTraining);
assertFalse(foundTrainings.isEmpty());
assertEquals(expectedFoundTraining, foundTrainings.size());
Training foundTraining = foundTrainings.get(0);
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved training by its created date")
public void shouldFindTrainingByCreatedDate(Training training) {
// given
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
Training foundTraining = trainingRepository.findByCreatedDate(savedTraining.getCreatedDate());
// then
assertNotNull(savedTraining);
assertNotNull(foundTraining);
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved trainings by their time")
public void shouldFindTrainingByTime(Training training) {
// given
final int expectedFoundTraining = 1;
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
List<Training> foundTrainings = trainingRepository.findByTime(savedTraining.getTime());
// then
assertNotNull(savedTraining);
assertFalse(foundTrainings.isEmpty());
assertEquals(expectedFoundTraining, foundTrainings.size());
Training foundTraining = foundTrainings.get(0);
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved trainings by their type")
public void shouldFindTrainingByType(Training training) {
// given
final int expectedFoundTraining = 1;
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
List<Training> foundTrainings = trainingRepository.findByType(savedTraining.getType());
// then
assertNotNull(savedTraining);
assertFalse(foundTrainings.isEmpty());
assertEquals(expectedFoundTraining, foundTrainings.size());
Training foundTraining = foundTrainings.get(0);
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
@ParameterizedTest
@MethodSource("provideCommonTrainings")
@DisplayName("Returns saved trainings by their account")
public void shouldFindTrainingByAccount(Training training) {
// given
final int expectedFoundTraining = 1;
Account account = accountRepository.saveAndFlush(AccountFactory.createDummyAccount());
training.setAccount(account);
// when
Training savedTraining = trainingRepository.save(training);
List<Training> foundTrainings = trainingRepository.findByAccount(savedTraining.getAccount());
// then
assertNotNull(savedTraining);
assertFalse(foundTrainings.isEmpty());
assertEquals(expectedFoundTraining, foundTrainings.size());
Training foundTraining = foundTrainings.get(0);
assertEquals(savedTraining.getDeviceName(), foundTraining.getDeviceName());
assertEquals(savedTraining.getDeviceFirmware(), foundTraining.getDeviceFirmware());
assertEquals(savedTraining.getType(), foundTraining.getType());
assertEquals(savedTraining.getTime(), foundTraining.getTime());
assertEquals(savedTraining.getCalories(), foundTraining.getCalories());
assertEquals(savedTraining.getAccount(), foundTraining.getAccount());
assertEquals(savedTraining.getCreatedDate(), foundTraining.getCreatedDate());
}
}
| 47.072917 | 149 | 0.733643 |
8f5a77e11beb9df9d83d584afb1d3f68774cd8f5 | 2,977 | package com.jesen.paint_colorfilter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.util.AttributeSet;
import android.view.View;
public class ColorFilterView extends View {
private Paint mPaint;
private Bitmap mBitmap;
private ColorMatrixColorFilter mColorMatrixColorFilter;
public ColorFilterView(Context context) {
super(context);
mPaint = new Paint();
mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.kid);
}
public ColorFilterView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorFilterView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* R' = R * mul.R / 0xff + add.R
* G' = G * mul.G / 0xff + add.G
* B' = B * mul.B / 0xff + add.B
*/
//红色去除掉
// LightingColorFilter lighting = new LightingColorFilter(0x00ffff,0x000000);
// mPaint.setColorFilter(lighting);
// canvas.drawBitmap(mBitmap, 0,0, mPaint);
// //原始图片效果
// LightingColorFilter lighting = new LightingColorFilter(0xffffff,0x000000);
// mPaint.setColorFilter(lighting);
// canvas.drawBitmap(mBitmap, 0,0, mPaint);
// //绿色更亮
// LightingColorFilter lighting = new LightingColorFilter(0xffffff,0x003000);
// mPaint.setColorFilter(lighting);
// canvas.drawBitmap(mBitmap, 0,0, mPaint);
// PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.DARKEN);
// mPaint.setColorFilter(porterDuffColorFilter);
// canvas.drawBitmap(mBitmap, 100, 0, mPaint);
float[] colorMatrix = {
2,0,0,0,0, //red
0,1,0,0,0, //green
0,0,1,0,0, //blue
0,0,0,1,0 //alpha
};
ColorMatrix cm = new ColorMatrix();
// //亮度调节
// cm.setScale(1,2,1,1);
// //饱和度调节0-无色彩, 1- 默认效果, >1饱和度加强
// cm.setSaturation(2);
//色调调节
cm.setRotate(0, 45);
mColorMatrixColorFilter = new ColorMatrixColorFilter(cm);
mPaint.setColorFilter(mColorMatrixColorFilter);
canvas.drawBitmap(mBitmap, 100, 0, mPaint);
}
// 胶片
public static final float colormatrix_fanse[] = {
-1.0f, 0.0f, 0.0f, 0.0f, 255.0f,
0.0f, -1.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, -1.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f};
}
| 31.336842 | 117 | 0.632852 |
a497c95f6b4b0f1245cbfee5c59074853ed6530e | 1,401 | /* ###
* IP: GHIDRA
*
* 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 agent.dbgeng.dbgeng;
/**
* Information about a thread.
*
* <p>
* The fields correspond to parameters taken by {@code CreateThread} of
* {@code IDebugEventCallbacks}. They also appear as a subset of parameters taken by
* {@code CreateProcess} of {@code IDebugEventCallbacks}.
*/
public class DebugThreadInfo {
public final long handle;
public final long dataOffset;
public final long startOffset;
public DebugThreadInfo(long handle, long dataOffset, long startOffset) {
this.handle = handle;
this.dataOffset = dataOffset;
this.startOffset = startOffset;
}
@Override
public String toString() {
return String.format("<%s@%08x handle=0x%04x,dataOffset=0x%08x,startOffset=0x%08x>",
getClass().getSimpleName(), System.identityHashCode(this),
handle, dataOffset, startOffset);
}
}
| 31.840909 | 86 | 0.733048 |
bfef454234fd3fb385901e07606ba5dcd960d42b | 853 | package resource;
import java.util.Random;
import com.lac.annotations.Resource;
@Resource
public class Buffer {
int size = 7;
String[] buff = new String[size];
int writeIndex = 0;
int readIndex = 0;
public void escribir(){
String value = Integer.toString((new Random()).nextInt(10000));
System.out.println("writeIndex: " + writeIndex + " written value: "+ value + " Thread id: " + Thread.currentThread().getId());
buff[writeIndex] = value ;
if(writeIndex == size -1 )
writeIndex = 0;
else
writeIndex++;
}
public void leer(){
String value = buff[readIndex];
buff[readIndex] = null;
System.out.println("readIndex = "+ readIndex + " written value: "+ value + " Thread id: " + Thread.currentThread().getId() );
if(readIndex == size -1 )
readIndex = 0;
else
readIndex++;
}
}
| 24.371429 | 129 | 0.629543 |
72cee6948d903c684060649e2b184ef13400abb7 | 822 | package org.opencds.cqf.tooling.visitor;
import org.hl7.elm.r1.Element;
import org.hl7.elm.r1.VersionedIdentifier;
public class ElmRequirement {
private VersionedIdentifier libraryIdentifier;
public VersionedIdentifier getLibraryIdentifier() {
return this.libraryIdentifier;
}
private Element element;
public Element getElement() {
return this.element;
}
public ElmRequirement(VersionedIdentifier libraryIdentifier, Element element) {
if (libraryIdentifier == null) {
throw new IllegalArgumentException("libraryIdentifier is required");
}
if (element == null) {
throw new IllegalArgumentException("element is required");
}
this.libraryIdentifier = libraryIdentifier;
this.element = element;
}
}
| 26.516129 | 83 | 0.687348 |
62895850bc6dea063f2a62f4a0398288051f9a07 | 13,057 | package org.jsmart.zerocode.core.httpclient;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;
import static org.jsmart.zerocode.core.httpclient.utils.FileUploadUtils.*;
import static org.jsmart.zerocode.core.httpclient.utils.HeaderUtils.hasMultiPartHeader;
import static org.jsmart.zerocode.core.httpclient.utils.HeaderUtils.processFrameworkDefault;
import static org.jsmart.zerocode.core.httpclient.utils.UrlQueryParamsUtils.setQueryParams;
import static org.jsmart.zerocode.core.utils.HelperJsonUtils.getContentAsItIsJson;
public class BasicHttpClient {
Logger LOGGER = LoggerFactory.getLogger(BasicHttpClient.class);
public static final String FILES_FIELD = "files";
public static final String BOUNDARY_FIELD = "boundary";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
public static final String CONTENT_TYPE = "Content-Type";
private Object COOKIE_JSESSIONID_VALUE;
private CloseableHttpClient httpclient;
public BasicHttpClient() {
}
public BasicHttpClient(CloseableHttpClient httpclient) {
this.httpclient = httpclient;
}
/**
* Override this method to create your own http or https client or a customized client if needed
* for your project. Framework uses the below client which is the default implementation.
* - org.jsmart.zerocode.core.httpclient.ssl.SslTrustHttpClient#createHttpClient()
* {@code
* See examples:
* - org.jsmart.zerocode.core.httpclient.ssl.SslTrustHttpClient#createHttpClient()
* - org.jsmart.zerocode.core.httpclient.ssl.SslTrustCorporateProxyHttpClient#createHttpClient()
* - org.jsmart.zerocode.core.httpclient.ssl.CorporateProxyNoSslContextHttpClient#createHttpClient()
* }
*
* @return CloseableHttpClient
* @throws Exception
*/
public CloseableHttpClient createHttpClient() throws Exception {
/*
* If your connections are not via SSL or corporate Proxy etc,
* You can simply override this method and return the below default
* client provided by "org.apache.httpcomponents.HttpClients".
*
* - return HttpClients.createDefault();
*/
LOGGER.info("###Creating SSL Enabled Http Client for both http/https/TLS connections");
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CookieStore cookieStore = new BasicCookieStore();
return HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setDefaultCookieStore(cookieStore)
.build();
}
/**
* Override this method in case you want to execute the http call differently via your http client.
* Otherwise the framework falls back to this implementation by default.
*
* @param httpUrl : path to end point
* @param methodName : e.g. GET, PUT etc
* @param headers : headers, cookies etc
* @param queryParams : key-value query params after the '?' in the url
* @param body : json body
*
* @return : Http response consists of status code, entity, headers, cookies etc
* @throws Exception
*/
public Response execute(String httpUrl,
String methodName,
Map<String, Object> headers,
Map<String, Object> queryParams,
Object body) throws Exception {
httpclient = createHttpClient();
// ---------------------------
// Handle request body content
// ---------------------------
String reqBodyAsString = handleRequestBody(body);
// -----------------------------------
// Handle the url and query parameters
// -----------------------------------
httpUrl = handleUrlAndQueryParams(httpUrl, queryParams);
RequestBuilder requestBuilder = createRequestBuilder(httpUrl, methodName, headers, reqBodyAsString);
// ------------------
// Handle the headers
// ------------------
handleHeaders(headers, requestBuilder);
// ------------------
// Handle cookies
// ------------------
addCookieToHeader(requestBuilder);
CloseableHttpResponse httpResponse = httpclient.execute(requestBuilder.build());
// --------------------
// Handle the response
// --------------------
return handleResponse(httpResponse);
}
/**
* Once the client executes the http call, then it receives the http response. This method takes care of handling
* that. In case you need to handle it differently you can override this method.
*
* @param httpResponse : Received Apache http response from the server
*
* @return : Effective response with handled http session.
* @throws IOException
*/
public Response handleResponse(CloseableHttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
Response serverResponse = Response
.status(httpResponse.getStatusLine().getStatusCode())
.entity(entity != null ? IOUtils.toString(entity.getContent()) : null)
.build();
Header[] allHeaders = httpResponse.getAllHeaders();
Response.ResponseBuilder responseBuilder = Response.fromResponse(serverResponse);
for (Header thisHeader : allHeaders) {
String headerKey = thisHeader.getName();
responseBuilder = responseBuilder.header(headerKey, thisHeader.getValue());
handleHttpSession(serverResponse, headerKey);
}
return responseBuilder.build();
}
/**
* If(optionally) query parameters was sent as a JSON in the request below, this gets available to this method
* for processing them with the url.
*<pre>{@code
* e.g.
* "url": "/api/v1/search/people"
* "request": {
* "queryParams": {
* "city":"Lon",
* "lang":"Awesome"
* }
* }
* }</pre>
* will resolve to effective url "/api/v1/search/people?city=Lon{@literal &}lang=Awesome".
*
* In case you need to handle it differently you can override this method to change this behaviour to roll your own
* feature.
*
* @param httpUrl - Url of the target service
* @param queryParams - Query parameters to pass
* @return : Effective url
*/
public String handleUrlAndQueryParams(String httpUrl, Map<String, Object> queryParams) {
if (queryParams != null) {
httpUrl = setQueryParams(httpUrl, queryParams);
}
return httpUrl;
}
/**
* Override this method in case you want to handle the headers differently which were passed from the
* test-case requests. If there are keys with same name e.g. some headers were populated from
* properties file(or via any other way from your java application), then how these should be handled.
* The framework will fall back to this default implementation to handle this.
*
* @param headers
* @param requestBuilder
* @return : An effective Apache http request builder object with processed headers.
*/
public RequestBuilder handleHeaders(Map<String, Object> headers, RequestBuilder requestBuilder) {
processFrameworkDefault(headers, requestBuilder);
return requestBuilder;
}
/**
* Override this method when you want to manipulate the request body passed from your test cases.
* Otherwise the framework falls back to this default implementation.
*
* @param body
* @return
*/
public String handleRequestBody(Object body) {
return getContentAsItIsJson(body);
}
/**
* This is the usual http request builder most widely used using Apache Http Client. In case you want to build
* or prepare the requests differently, you can override this method.
*
* Please see the following request builder to handle file uploads.
* - BasicHttpClient#createFileUploadRequestBuilder(java.lang.String, java.lang.String, java.lang.String)
*
* @param httpUrl
* @param methodName
* @param reqBodyAsString
* @return
*/
public RequestBuilder createDefaultRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) {
RequestBuilder requestBuilder = RequestBuilder
.create(methodName)
.setUri(httpUrl);
if (reqBodyAsString != null) {
HttpEntity httpEntity = EntityBuilder.create()
.setContentType(APPLICATION_JSON)
.setText(reqBodyAsString)
.build();
requestBuilder.setEntity(httpEntity);
}
return requestBuilder;
}
/**
* This is the http request builder for file uploads, using Apache Http Client. In case you want to build
* or prepare the requests differently, you can override this method.
*
* Note-
* With file uploads you can send more headers too from the testcase to the server, except "Content-Type" because
* this is reserved for "multipart/form-data" which the client sends to server during the file uploads. You can
* also send more request-params and "boundary" from the test cases if needed. The boundary defaults to an unique
* string of local-date-time-stamp if not provided in the request.
*
* @param httpUrl
* @param methodName
* @param reqBodyAsString
* @return
* @throws IOException
*/
public RequestBuilder createFileUploadRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) throws IOException {
Map<String, Object> fileFieldNameValueMap = getFileFieldNameValue(reqBodyAsString);
List<String> fileFieldsList = (List<String>) fileFieldNameValueMap.get(FILES_FIELD);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
buildAllFilesToUpload(fileFieldsList, multipartEntityBuilder);
buildOtherRequestParams(fileFieldNameValueMap, multipartEntityBuilder);
buildMultiPartBoundary(fileFieldNameValueMap, multipartEntityBuilder);
return createUploadRequestBuilder(httpUrl, methodName, multipartEntityBuilder);
}
/**
* This method handles the http session to be maintained between the calls.
* In case the session is not needed or to be handled differently, then this
* method can be overridden to do nothing or to roll your own feature.
*
* @param serverResponse
* @param headerKey
*/
public void handleHttpSession(Response serverResponse, String headerKey) {
/** ---------------
* Session handled
* ----------------
*/
if ("Set-Cookie".equals(headerKey)) {
COOKIE_JSESSIONID_VALUE = serverResponse.getMetadata().get(headerKey);
}
}
private void addCookieToHeader(RequestBuilder uploadRequestBuilder) {
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Setting cookies:
// Highly discouraged to use sessions, but in case of any server dependent upon session,
// then it's taken care here.
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
if (COOKIE_JSESSIONID_VALUE != null) {
uploadRequestBuilder.addHeader("Cookie", (String) COOKIE_JSESSIONID_VALUE);
}
}
private RequestBuilder createRequestBuilder(String httpUrl, String methodName, Map<String, Object> headers, String reqBodyAsString) throws IOException {
RequestBuilder requestBuilder;
if (hasMultiPartHeader(headers)) {
requestBuilder = createFileUploadRequestBuilder(httpUrl, methodName, reqBodyAsString);
} else {
requestBuilder = createDefaultRequestBuilder(httpUrl, methodName, reqBodyAsString);
}
return requestBuilder;
}
}
| 40.803125 | 156 | 0.656047 |
1347ee5db34ca5d17f0c8602778de2336f03f7d4 | 207 | package works.hop.javro.gen.plugin;
import org.gradle.api.provider.Property;
import java.io.File;
public interface JavroExtension {
Property<File> getSourceDir();
Property<File> getDestDir();
}
| 15.923077 | 40 | 0.743961 |
ce232175af767a11f355bbc5d0fbcf9726f27d3f | 386 | package com.example.coolweather.gson;
/**
* Created by Machenike on 2017/9/1.
*/
public class Suggestion {
public String iname;
public String ivalue;
public String detail;
public Suggestion() {
}
public Suggestion(String detail, String iname, String ivalue) {
this.detail = detail;
this.iname = iname;
this.ivalue = ivalue;
}
}
| 18.380952 | 67 | 0.634715 |
9d48875c61dbe1a28704603da3305f4d813ae1b7 | 9,621 | /*******************************************************************************
* Copyright (C) 2017, Paul Scerri, Sean R Owens
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*
* File: BeliefsScanner.java
* Generated from: Beliefs.dtd
* Date: 10 July 2002 15:27
*
* @author scerri
* @version generated by NetBeans XML module
*/
package Machinetta.State;
/**
* This is a scanner of DOM tree.
*
* Example:
* <pre>
* javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
* javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder();
* org.w3c.dom.Document document = builder.parse (new org.xml.sax.InputSource (???));
* <font color="blue">BeliefsScanner scanner = new BeliefsScanner (document);</font>
* <font color="blue">scanner.visitDocument();</font>
* </pre>
*
* @see org.w3c.dom.Document
* @see org.w3c.dom.Element
* @see org.w3c.dom.NamedNodeMap
*/
public class BeliefsScanner {
/** org.w3c.dom.Document document */
org.w3c.dom.Document document;
/** Create new BeliefsScanner with org.w3c.dom.Document. */
public BeliefsScanner(org.w3c.dom.Document document) {
this.document = document;
}
/** Scan through org.w3c.dom.Document document. */
public void visitDocument() {
org.w3c.dom.Element element = document.getDocumentElement();
if ((element != null) && element.getTagName().equals("Beliefs")) {
visitElement_Beliefs(element);
}
if ((element != null) && element.getTagName().equals("Belief")) {
visitElement_Belief(element);
}
if ((element != null) && element.getTagName().equals("BooleanBelief")) {
visitElement_BooleanBelief(element);
}
if ((element != null) && element.getTagName().equals("IntegerBelief")) {
visitElement_IntegerBelief(element);
}
if ((element != null) && element.getTagName().equals("Id")) {
visitElement_Id(element);
}
}
/** Scan through org.w3c.dom.Element named Beliefs. */
void visitElement_Beliefs(org.w3c.dom.Element element) { // <Beliefs>
// element.getValue();
org.w3c.dom.NodeList nodes = element.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
org.w3c.dom.Node node = nodes.item(i);
switch (node.getNodeType()) {
case org.w3c.dom.Node.CDATA_SECTION_NODE:
// ((org.w3c.dom.CDATASection)node).getData();
break;
case org.w3c.dom.Node.ELEMENT_NODE:
org.w3c.dom.Element nodeElement = (org.w3c.dom.Element)node;
if (nodeElement.getTagName().equals("Belief")) {
visitElement_Belief(nodeElement);
}
break;
case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
// ((org.w3c.dom.ProcessingInstruction)node).getTarget();
// ((org.w3c.dom.ProcessingInstruction)node).getData();
break;
}
}
}
/** Scan through org.w3c.dom.Element named Belief. */
void visitElement_Belief(org.w3c.dom.Element element) { // <Belief>
// element.getValue();
org.w3c.dom.NodeList nodes = element.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
org.w3c.dom.Node node = nodes.item(i);
switch (node.getNodeType()) {
case org.w3c.dom.Node.CDATA_SECTION_NODE:
// ((org.w3c.dom.CDATASection)node).getData();
break;
case org.w3c.dom.Node.ELEMENT_NODE:
org.w3c.dom.Element nodeElement = (org.w3c.dom.Element)node;
if (nodeElement.getTagName().equals("BooleanBelief")) {
visitElement_BooleanBelief(nodeElement);
}
if (nodeElement.getTagName().equals("IntegerBelief")) {
visitElement_IntegerBelief(nodeElement);
}
break;
case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
// ((org.w3c.dom.ProcessingInstruction)node).getTarget();
// ((org.w3c.dom.ProcessingInstruction)node).getData();
break;
}
}
}
/** Scan through org.w3c.dom.Element named BooleanBelief. */
void visitElement_BooleanBelief(org.w3c.dom.Element element) { // <BooleanBelief>
// element.getValue();
org.w3c.dom.NodeList nodes = element.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
org.w3c.dom.Node node = nodes.item(i);
switch (node.getNodeType()) {
case org.w3c.dom.Node.CDATA_SECTION_NODE:
// ((org.w3c.dom.CDATASection)node).getData();
break;
case org.w3c.dom.Node.ELEMENT_NODE:
org.w3c.dom.Element nodeElement = (org.w3c.dom.Element)node;
if (nodeElement.getTagName().equals("Id")) {
visitElement_Id(nodeElement);
}
break;
case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
// ((org.w3c.dom.ProcessingInstruction)node).getTarget();
// ((org.w3c.dom.ProcessingInstruction)node).getData();
break;
}
}
}
/** Scan through org.w3c.dom.Element named IntegerBelief. */
void visitElement_IntegerBelief(org.w3c.dom.Element element) { // <IntegerBelief>
// element.getValue();
org.w3c.dom.NodeList nodes = element.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
org.w3c.dom.Node node = nodes.item(i);
switch (node.getNodeType()) {
case org.w3c.dom.Node.CDATA_SECTION_NODE:
// ((org.w3c.dom.CDATASection)node).getData();
break;
case org.w3c.dom.Node.ELEMENT_NODE:
org.w3c.dom.Element nodeElement = (org.w3c.dom.Element)node;
if (nodeElement.getTagName().equals("Id")) {
visitElement_Id(nodeElement);
}
break;
case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
// ((org.w3c.dom.ProcessingInstruction)node).getTarget();
// ((org.w3c.dom.ProcessingInstruction)node).getData();
break;
}
}
}
/** Scan through org.w3c.dom.Element named Id. */
void visitElement_Id(org.w3c.dom.Element element) { // <Id>
// element.getValue();
org.w3c.dom.NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
org.w3c.dom.Attr attr = (org.w3c.dom.Attr)attrs.item(i);
if (attr.getName().equals("Name")) { // <Id Name="???">
// attr.getValue();
}
}
org.w3c.dom.NodeList nodes = element.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
org.w3c.dom.Node node = nodes.item(i);
switch (node.getNodeType()) {
case org.w3c.dom.Node.CDATA_SECTION_NODE:
// ((org.w3c.dom.CDATASection)node).getData();
break;
case org.w3c.dom.Node.ELEMENT_NODE:
org.w3c.dom.Element nodeElement = (org.w3c.dom.Element)node;
break;
case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
// ((org.w3c.dom.ProcessingInstruction)node).getTarget();
// ((org.w3c.dom.ProcessingInstruction)node).getData();
break;
}
}
}
}
| 44.748837 | 120 | 0.569587 |
f9b1cec4682465632d6e05e559c3e207fc2d26a0 | 814 | package com.adyen.p081ui.activities;
import android.content.Intent;
import android.support.p000v4.content.C0515e;
import com.adyen.p081ui.p083b.C5596e.C5597a;
import p019d.p135a.p136a.p139c.p140a.C6879a;
/* renamed from: com.adyen.ui.activities.c */
/* compiled from: CheckoutActivity */
class C5584c implements C5597a {
/* renamed from: a */
final /* synthetic */ CheckoutActivity f9411a;
C5584c(CheckoutActivity this$0) {
this.f9411a = this$0;
}
/* renamed from: a */
public void mo17722a(C6879a creditCardPaymentDetails) {
Intent intent = new Intent("com.adyen.core.ui.PaymentDetailsProvided");
intent.putExtra("PaymentDetails", creditCardPaymentDetails);
C0515e.m2597a(this.f9411a.f9402b).mo5314a(intent);
this.f9411a.f9401a = true;
}
}
| 30.148148 | 79 | 0.708845 |
55388747d44f33390be367306d59aa1e46655068 | 1,737 | /*
* 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 DAO;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author digital
*/
public class EnsMat {
private DaoFactory daoFactory;
public EnsMat(DaoFactory dao)
{
this.daoFactory = dao;
}
public boolean create(int id_mat, int id_ens) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
try
{
Connection connexion=daoFactory.getConnection();
Statement stmt=connexion.createStatement();
String sql="insert into enseigner(ID_MAT, ID_ENS) values("+
id_mat+","+
id_ens+")"; ;
stmt.executeUpdate(sql);
return true;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
public boolean update(int id_mat, int id_ens) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Connection connexion=null;
Statement stmt=null;
try
{
connexion=daoFactory.getConnection();
stmt=connexion.createStatement();
String sql="update enseigner set "+
"ID_MAT="+ id_mat +""+
" where ID_ENS = " + id_ens + "";
stmt.executeUpdate(sql);
return true;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
}
| 25.925373 | 137 | 0.600461 |
9ccbc438a561bcf962b775df96a5106ec2fb36a3 | 3,276 | package com.owl.integration.elasticsearch.client.request.query;
import java.util.List;
public class QueryBuilders {
/**
* A Query that matches documents matching boolean combinations of other queries.
*/
public static BoolQuery boolQuery() {
return new BoolQuery();
}
/**
* A query that wraps another query and simply returns a constant score equal to the
* query boost for every document in the query.
*
* @param query The query to wrap in a constant score query
*/
public static ConstantScoreQuery constantScoreQuery(Query query) {
return new ConstantScoreQuery().setQuery(query);
}
/**
* A filter to filter only documents where a field exists in them.
*
* @param name The name of the field
*/
public static ExistsQuery existsQuery(String name) {
return new ExistsQuery().setField(name);
}
/**
* A Query that matches documents containing a term.
*
* @param name The name of the field
* @param value The value of the term
*/
public static MatchQuery matchQuery(String name, Object value) {
return new MatchQuery().setField(name).setQuery(value);
}
/**
* A Query that has prefix match with a specified prefix.
*
* @param name The name of the field
* @param prefix The prefix
*/
public static PrefixQuery prefixQuery(String name, String prefix) {
return new PrefixQuery().setField(name).setPrefix(prefix);
}
/**
* A Query that has wildcard match with a specified wildcard.
* @param name The name of the field
* @param wildcard The wildcard
*/
public static WildcardQuery wildcardQuery(String name, String wildcard) {
return new WildcardQuery().setField(name).setWildcard(wildcard);
}
/**
* A Query that matches documents containing terms with a specified regular expression.
*
* @param name The name of the field
* @param regexp The regular expression
*/
public static RegexpQuery regexpQuery(String name, String regexp) {
return new RegexpQuery().setField(name).setRegexp(regexp);
}
/**
* A Query that matches documents within an range of terms.
*
* @param name The field name
*/
public static RangeQuery rangeQuery(String name) {
return new RangeQuery().setField(name);
}
/**
* A Query that matches documents containing a term.
*
* @param name The name of the field
* @param value The value of the term
*/
public static TermQuery termQuery(String name, Object value) {
return new TermQuery().setField(name).setTerm(value);
}
/**
* A Query that matches documents containing a terms.
*
* @param name The name of the field
* @param value The value of the terms
*/
public static TermsQuery termsQuery(String name, List<Object> value) {
return new TermsQuery().setField(name).setTerms(value);
}
/**
* A Query that matches documents by queryString.
*
* @param value The query string
*/
public static QueryStringQuery queryString(String value) {
return new QueryStringQuery().setQuery(value);
}
}
| 29.781818 | 91 | 0.645604 |
dedbf157ad1a11118eb24f8122a9ff57f1286135 | 1,309 | /*
* Copyright (c) 2010-2017 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.util.exception;
import com.evolveum.midpoint.util.LocalizableMessage;
/**
* Configuration exception indicates that something is mis-configured.
*
* The system or its part is misconfigured and therefore the intended operation
* cannot be executed.
*
* @author Radovan Semancik
*
*/
public class ConfigurationException extends CommonException {
private static final long serialVersionUID = 1L;
public ConfigurationException() {
}
public ConfigurationException(String message) {
super(message);
}
public ConfigurationException(LocalizableMessage userFriendlyMessage) {
super(userFriendlyMessage);
}
public ConfigurationException(Throwable cause) {
super(cause);
}
public ConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public ConfigurationException(LocalizableMessage userFriendlyMessage, Throwable cause) {
super(userFriendlyMessage, cause);
}
@Override
public String getErrorTypeMessage() {
return "Configuration error";
}
}
| 25.173077 | 92 | 0.722689 |
689872c9909b998bf029f6f72dfd8034237fcde1 | 709 | package io.basc.framework.locks;
import io.basc.framework.codec.support.URLCodec;
import io.basc.framework.io.FileUtils;
import io.basc.framework.util.Assert;
import java.io.File;
import java.util.concurrent.locks.Lock;
public class FileLockFactory implements LockFactory {
private final File directory;
public FileLockFactory() {
this(new File(FileUtils.getTempDirectory()));
}
public FileLockFactory(File directory) {
Assert.requiredArgument(directory != null && directory.exists() && directory.isDirectory(), "directory");
this.directory = directory;
}
@Override
public Lock getLock(String name) {
return new FileLock(new File(directory, URLCodec.UTF_8.encode(name) + ".lock"));
}
}
| 25.321429 | 107 | 0.760226 |
b9969a6c406c1a1da0ae24e8848b50a1c2ce72c8 | 791 | // Create a class Area. Define constructors for the class to calculate area of the circle if radius
// is provided as parameter or else calculate the area of rectangle given length and breadth valuec;
class Prob3
{
float r,l,b;
double areac,arear;
public Prob3(float r)
{
this.r=r;
}
public Prob3(float l,float b)
{
this.l=l;
this.b=b;
}
public void areaC()
{
areac= 3.14*r*r;
}
public void areaR()
{
arear=l*b;
}
public void showc()
{
System.out.println("Area of Circle is: "+areac);
}
public void showr()
{
System.out.println("Area of Rectangle is: "+arear);
}
public static void main(String args[])
{
Prob3 circle =new Prob3(12);
Prob3 rac =new Prob3(12,12);
circle.areaC();
rac.areaR();
circle.showc();
rac.showr();
}
} | 19.292683 | 100 | 0.646018 |
cb1625af65c0f331f252fd9a8cfd9bd63f7214f3 | 1,358 | package com.monday.state.branchlogic;
import static com.monday.state.branchlogic.State.*;
public class MarioStateMachine {
private int score;
private State currentState;
public MarioStateMachine() {
this.score = 0;
this.currentState = SMALL;
}
public void obtainMushRoom() {
if (currentState.equals(SMALL)) {
currentState = SUPER;
score += 100;
}
}
public void obtainCape() {
if (currentState.equals(SMALL) || currentState.equals(SUPER)) {
currentState = CAPE;
score += 200;
}
}
public void obtainFireFlower() {
if (currentState.equals(SMALL) || currentState.equals(SUPER)) {
currentState = FIRE;
score += 300;
}
}
public void meetMonster() {
switch (currentState) {
case SUPER:
currentState = SMALL;
score -= 100;
break;
case CAPE:
currentState = SMALL;
score -= 200;
case FIRE:
currentState = SMALL;
score -= 300;
default:
break;
}
}
public int getScore() {
return this.score;
}
public State getCurrentState() {
return this.currentState;
}
}
| 21.555556 | 71 | 0.511782 |
68161aca8f059bd8f3d8a0e06e854c6f3f195f57 | 1,280 | // package com.xuegao.springboot_tool.mvc.exception;
//
// import com.baomidou.mybatisplus.extension.api.R;
// import com.xuegao.springboot_tool.utils.ExceptionUtil;
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;
// import org.springframework.web.bind.annotation.ControllerAdvice;
// import org.springframework.web.bind.annotation.ExceptionHandler;
// import org.springframework.web.bind.annotation.ResponseBody;
//
// /**
// * <br/> @PackageName:com.fff.springbootapiseedtest.exception
// * <br/> @ClassName:BaseExceptionHandler2
// * <br/> @Description:
// * <br/> @author:xuegao
// * <br/> @date:2020/4/5 15:19
// */
// @ControllerAdvice
// public class BaseExceptionHandler2 {
//
// private final Logger log = LoggerFactory.getLogger(getClass());
//
// /**修改统一异常处理器,将异常方法中的直接打印改为日志输入并打印
// * -------- 通用异常处理方法 --------
// * 日志的环境即spring.profiles.acticve,跟随项目启动;
// *
// * 启动后,即可到自定目录查找到生成的日志文件;
// *
// * 本地idea调试时,推荐Grep Console插件可实现控制台的自定义颜色输出
// **/
// @ExceptionHandler(Exception.class)
// @ResponseBody
// public R error(Exception e) {
// // e.printStackTrace();
// log.error(ExceptionUtil.getMessage(e));
// // return R.error();
// return null;
// }
//
// } | 32 | 70 | 0.649219 |
a3a78d54a975fc09ca7e509a70d92277cddc10c1 | 5,828 | package seedu.address.model.itinerary.event;
import static seedu.address.commons.util.AppUtil.checkArgument;
import static seedu.address.commons.util.CollectionUtil.requireAllNonNull;
import java.time.LocalDateTime;
import java.util.Optional;
import seedu.address.model.booking.Booking;
import seedu.address.model.expenditure.Expenditure;
import seedu.address.model.inventory.Inventory;
import seedu.address.model.itinerary.Location;
import seedu.address.model.itinerary.Name;
/**
* Represents a Event in TravelPal.
* Compulsory fields: name, startDate, endDate, destination.
* Optional fields: expenditure, booking, inventory.
*/
public class Event {
public static final String MESSAGE_INVALID_DATETIME = "Start date should be before end date";
// Compulsory fields
private final Name name;
private final LocalDateTime startDate;
private final LocalDateTime endDate;
private final Location destination;
// Optional fields
private final Inventory inventory;
private final Expenditure expenditure;
private final Booking booking;
/**
* Constructs an {@code Event}.
*/
public Event(Name name, LocalDateTime startDate, LocalDateTime endDate, Booking booking,
Expenditure expenditure, Inventory inventory, Location destination) {
requireAllNonNull(name, startDate, endDate);
checkArgument(isValidDuration(startDate, endDate), MESSAGE_INVALID_DATETIME);
this.name = name;
this.startDate = startDate;
this.endDate = endDate;
this.booking = booking;
this.destination = destination;
this.expenditure = expenditure;
this.inventory = inventory;
}
// temporary constructor until we implement booking and inventory, accepts null for now
public Event(Name name, LocalDateTime startDate, LocalDateTime endDate,
Expenditure expenditure, Location destination) {
requireAllNonNull(name, startDate, endDate, expenditure);
checkArgument(isValidDuration(startDate, endDate), MESSAGE_INVALID_DATETIME);
this.name = name;
this.startDate = startDate;
this.endDate = endDate;
this.booking = null;
this.destination = destination;
this.expenditure = expenditure;
this.inventory = null;
}
/**
* Constructs a trip with optional expenditure field.
*/
public Event(Name name, LocalDateTime startDate, LocalDateTime endDate,
Optional<Expenditure> expenditure, Location destination) {
requireAllNonNull(name, startDate, endDate, expenditure);
checkArgument(isValidDuration(startDate, endDate), MESSAGE_INVALID_DATETIME);
this.name = name;
this.startDate = startDate;
this.endDate = endDate;
this.booking = null;
this.destination = destination;
this.expenditure = expenditure.orElse(null);
this.inventory = null;
}
public boolean isValidDuration(LocalDateTime startDate, LocalDateTime endDate) {
return startDate.isBefore(endDate);
}
// Compulsory Field getters
public Name getName() {
return name;
}
public LocalDateTime getStartDate() {
return startDate;
}
public LocalDateTime getEndDate() {
return endDate;
}
public Location getDestination() {
return destination;
}
// Optional field getters
public Optional<Expenditure> getExpenditure() {
return Optional.ofNullable(expenditure);
}
public Optional<Inventory> getInventory() {
return Optional.ofNullable(inventory);
}
public Optional<Booking> getBooking() {
return Optional.ofNullable(booking);
}
/**
* Returns true if both {@link Event} contain the same booking and their endDate and startDate time are the same.
* This defines a weaker notion of equality between two events.
*/
public boolean isSameEvent(Event otherEvent) {
if (otherEvent == this) {
return true;
}
return otherEvent != null
&& otherEvent.getName().equals(getName())
&& (otherEvent.getEndDate().equals(getEndDate()) && otherEvent.getStartDate().equals(getStartDate()));
}
/**
* Checks whether this event is clashing with another.
*
* @param other The other event to check.
* @return Boolean of whether the events clash.
*/
public boolean isClashingWith(Event other) {
return (this.getStartDate().compareTo(other.getStartDate()) >= 0
&& this.getStartDate().compareTo(other.getEndDate()) <= 0)
|| (this.getEndDate().compareTo(other.getStartDate()) >= 0
&& this.getEndDate().compareTo(other.getEndDate()) <= 0);
}
/**
* Checks whether this event is has the same name with another.
*
* @param other The other event to check.
* @return Boolean of whether the events has the same name.
*/
public boolean hasSameName(Event other) {
return this.getName().equals(other.getName());
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Event)) {
return false;
}
Event otherTrip = (Event) other;
return otherTrip.getName().equals(getName())
&& otherTrip.getStartDate().equals(getStartDate())
&& otherTrip.getEndDate().equals(getEndDate())
&& otherTrip.getDestination().equals(getDestination())
&& otherTrip.getBooking().equals(getBooking())
&& otherTrip.getExpenditure().equals(getExpenditure())
&& otherTrip.getInventory().equals(getInventory());
}
}
| 33.494253 | 118 | 0.656486 |
c77d680e00a2ed03d1282b06cb5a218356b3a17d | 413 | package edu.utexas.tacc.tapis.security.secrets;
import com.bettercloud.vault.SslConfig;
/** This class extends the vault driver class to get access to its protected members.
*
* @author rcardone
*/
public final class SkSslConfig
extends SslConfig
{
// Construct all instances with our custom environment loader.
public SkSslConfig()
{
environmentLoader(new VaultNoOpLoader());
}
}
| 22.944444 | 85 | 0.728814 |
76ab3e0b573ddadfa6d81a0f1a83a2ea334f34fb | 6,718 | package com.monri.android.flows;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
import com.monri.android.MonriApi;
import com.monri.android.ResultCallback;
import com.monri.android.logger.MonriLogger;
import com.monri.android.logger.MonriLoggerFactory;
import com.monri.android.model.ConfirmPaymentResponse;
import com.monri.android.model.PaymentResult;
import com.monri.android.model.PaymentStatusParams;
import com.monri.android.model.PaymentStatusResponse;
import com.monri.android.three_ds1.auth.PaymentAuthWebView;
import com.monri.android.three_ds1.auth.PaymentAuthWebViewClient;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by jasminsuljic on 2019-12-09.
* MonriAndroid
*/
public class ActivityActionRequiredFlow implements ActionRequiredFlow, PaymentAuthWebViewClient.Delegate {
private final Activity activity;
private final PaymentAuthWebView webView;
private final ProgressBar progressBar;
private final MonriApi monriApi;
private final AtomicInteger atomicInteger = new AtomicInteger();
private final PaymentAuthWebViewClient client;
private final MonriLogger logger = MonriLoggerFactory.get("ActivityActReqFlow");
private InvokationState invokationState = InvokationState.CALLBACK_NOT_INVOKED;
@SuppressLint("SetJavaScriptEnabled")
public ActivityActionRequiredFlow(Activity activity, PaymentAuthWebView webView, ProgressBar progressBar, MonriApi monriApi) {
this.activity = activity;
this.webView = webView;
this.progressBar = progressBar;
this.monriApi = monriApi;
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowContentAccess(false);
settings.setDomStorageEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
if (consoleMessage != null) {
String message = consoleMessage.message();
if (message != null) {
logger.trace(message);
}
}
return super.onConsoleMessage(consoleMessage);
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
return super.onJsConfirm(view, url, message, result);
}
});
client = new PaymentAuthWebViewClient(this);
webView.setWebViewClient(client);
}
@Override
public void handleResult(ConfirmPaymentResponse confirmPaymentResponse) {
executeIfStatus(InvokationState.CALLBACK_NOT_INVOKED, InvokationState.HANDLE_RESULT, () -> {
final String acsUrl = confirmPaymentResponse.getActionRequired().getAcsUrl();
logger.info(String.format("Handle result invoked with acsUrl = [%s]", acsUrl));
client.setAcsUrl(acsUrl);
executeOnUiThread(() -> {
webView.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
webView.loadUrl(confirmPaymentResponse.getActionRequired().getRedirectTo());
});
});
}
@Override
public void threeDs1Result(String status, String clientSecret) {
logger.info(String.format("ThreeDs1Result, status = %s, clientSecret = %s", status, clientSecret));
atomicInteger.set(0);
executeOnUiThread(() -> {
progressBar.setVisibility(View.INVISIBLE);
webView.setVisibility(View.GONE);
});
checkPaymentStatus(clientSecret, atomicInteger.incrementAndGet());
}
@Override
public void redirectingToAcs() {
executeIfStatus(InvokationState.HANDLE_RESULT, InvokationState.REDIRECTING_TO_ACS, () -> {
logger.info("redirectingToAcs");
executeOnUiThread(() -> {
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
});
});
}
@Override
public void acsAuthenticationFinished() {
logger.info("acsAuthenticationFinished");
executeOnUiThread(() -> {
webView.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
});
}
private void executeIfStatus(InvokationState state, InvokationState newState, Runnable runnable) {
if (invokationState != state) {
logger.warn(String.format("Tried changing to state = [%s] from state [%s], currentState = [%s]", newState.name(), state.name(), invokationState.name()));
} else {
logger.info(String.format("Changing state to state = [%s] from currentState = [%s]", newState.name(), state.name()));
this.invokationState = newState;
runnable.run();
}
}
private void executeOnUiThread(Runnable runnable) {
// Code here will run in UI thread
new Handler(Looper.getMainLooper()).post(runnable);
}
private void checkPaymentStatus(String clientSecret, int count) {
if (count >= 3) {
Intent intent = new Intent();
PaymentResult paymentResult = new PaymentResult("pending");
intent.putExtra(PaymentResult.BUNDLE_NAME, paymentResult);
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
} else {
monriApi.paymentStatus(new PaymentStatusParams(clientSecret), new ResultCallback<PaymentStatusResponse>() {
@Override
public void onSuccess(PaymentStatusResponse result) {
Intent intent = new Intent();
intent.putExtra(PaymentResult.BUNDLE_NAME, result.getPaymentResult());
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
}
@Override
public void onError(Throwable throwable) {
checkPaymentStatus(clientSecret, atomicInteger.incrementAndGet());
}
});
}
}
enum InvokationState {
CALLBACK_NOT_INVOKED,
THREE_DS_RESULT,
REDIRECTING_TO_ACS,
ACS_LOAD_FINISHED,
ACS_AUTHENTICATION_FINISHED,
HANDLE_RESULT
}
}
| 37.322222 | 165 | 0.661655 |
8bcbf281b2d5b1dec5b72acc32f7e8b4a3d4e3f0 | 1,974 | /*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.endpoint;
/**
* An operation on an endpoint.
*
* @author Andy Wilkinson
* @since 2.0.0
*/
public class Operation {
private final OperationType type;
private final OperationInvoker invoker;
private final boolean blocking;
/**
* Creates a new {@code EndpointOperation} for an operation of the given {@code type}.
* The operation can be performed using the given {@code operationInvoker}.
* @param type the type of the operation
* @param operationInvoker used to perform the operation
* @param blocking whether or not this is a blocking operation
*/
public Operation(OperationType type, OperationInvoker operationInvoker,
boolean blocking) {
this.type = type;
this.invoker = operationInvoker;
this.blocking = blocking;
}
/**
* Returns the {@link OperationType type} of the operation.
* @return the type
*/
public OperationType getType() {
return this.type;
}
/**
* Returns the {@code OperationInvoker} that can be used to invoke this endpoint
* operation.
* @return the operation invoker
*/
public OperationInvoker getInvoker() {
return this.invoker;
}
/**
* Whether or not this is a blocking operation.
*
* @return {@code true} if it is a blocking operation, otherwise {@code false}.
*/
public boolean isBlocking() {
return this.blocking;
}
}
| 26.675676 | 87 | 0.719352 |
26dd30a5ca0629ec00781f06118efa5b85f840ce | 4,795 | package com.cyberlink.cosmetic.modules.mail.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.context.ApplicationEventPublisherAware;
import com.cyberlink.cosmetic.modules.mail.model.MailType;
import com.cyberlink.cosmetic.modules.mail.service.MailInappropProdCommentService;
import com.cyberlink.cosmetic.modules.product.dao.ProductCommentDao;
import com.cyberlink.cosmetic.modules.product.model.ProductComment;
import com.cyberlink.cosmetic.modules.user.model.Account;
public class MailInappropProdCommentServiceImpl extends AbstractMailService
implements MailInappropProdCommentService, ApplicationEventPublisherAware{
private ProductCommentDao commentDao;
protected MailInappropProdCommentServiceImpl() {
super(MailType.REPORTBAD_NOTIFY_CREATOR);
}
@Override
public void send(Long bannedCommentId) {
ProductComment bannedComment = commentDao.findById(bannedCommentId);
String email = "" ;
List<Account> emailList = bannedComment.getUser().getAccountList() ;
if( emailList.size() > 0 ){
email = emailList.get(0).getAccount() ;
}
else{ //no email account
return ;
}
String comment = bannedComment.getComment() ;
//String copyright = "© 2015 CyberLink Corp. All Rights Reserved.";
Locale locale = new Locale(bannedComment.getUser().getRegion().substring(0,2),
bannedComment.getUser().getRegion().substring(3,5)) ;
String contentType = getLocalizedProductReview(locale) ;
String subject = getLocalizedMailSubject(locale, contentType) ;
final Map<String, Object> data = new HashMap<String, Object>();
data.put("comment", comment) ;
data.put("contentType", contentType);
data.put("creator", bannedComment.getUser().getDisplayName() );
data.put("copyRight", getCopyRight(locale));
data.put("mailWidth", 700);
final String content = getContent(locale, data);
sendMail(subject, content, email);
}
private String getLocalizedProductReview(Locale locale){
if (locale.getLanguage().equalsIgnoreCase("en")) {
return "Product Review";
} else if (locale.getLanguage().equalsIgnoreCase("de")){
return "Produktbewertung";
} else if (locale.getLanguage().equalsIgnoreCase("es")){
return "reseña de producto";
} else if (locale.getLanguage().equalsIgnoreCase("fr")){
return "avis sur un produit";
} else if (locale.getLanguage().equalsIgnoreCase("it")){
return "articolo su un prodotto";
} else if (locale.getLanguage().equalsIgnoreCase("ja")){
return "製品レビュー";
} else if (locale.getLanguage().equalsIgnoreCase("ko")){
return "제품 리뷰";
} else if (locale.getLanguage().equalsIgnoreCase("ru")){
return "отзыв о продукте";
} else if (locale.getCountry().equalsIgnoreCase("CN")){
return "产品评论";
} else if (locale.getCountry().equalsIgnoreCase("TW")){
return "產品評論";
} else {
return "Product Review";
}
}
private String getLocalizedMailSubject(Locale locale, String contentTypeString){
if (locale.getLanguage().equalsIgnoreCase("en")) {
return "[Beauty Circle] your " + contentTypeString + " has been reported!";
} else if (locale.getLanguage().equalsIgnoreCase("de")){
return "[Beauty Circle] Ihr " + contentTypeString + " wurde als unangemessen gemeldet!";
} else if (locale.getLanguage().equalsIgnoreCase("es")){
return "¡[Beauty Circle] tu " + contentTypeString + " ha sido reportada(o)!";
} else if (locale.getLanguage().equalsIgnoreCase("fr")){
return "[Sphère Beauté] votre " + contentTypeString + " a été signalé!";
} else if (locale.getLanguage().equalsIgnoreCase("it")){
return "[Beauty Circle] il tuo " + contentTypeString + " è stato segnalato!";
} else if (locale.getLanguage().equalsIgnoreCase("ja")){
return "[Beauty サークル] 記載された " + contentTypeString + " が不適切との通報がありました。";
} else if (locale.getLanguage().equalsIgnoreCase("ko")){
return "[Beauty Circle] 고객님의 콘텐츠 " + contentTypeString + " 이(가) 신고 접수되었습니다.";
} else if (locale.getLanguage().equalsIgnoreCase("ru")){
return "[Beauty Circle] Ваш " + contentTypeString + " считается неуместным!";
} else if (locale.getCountry().equalsIgnoreCase("CN")){
return "[玩美圈] 您的" + contentTypeString + "已被玩美圈社群标记为不适宜内容";
} else if (locale.getCountry().equalsIgnoreCase("TW")){
return "[玩美圈] 您的" + contentTypeString + "已被玩美圈社群標記為不適宜內容";
} else {
return "[Beauty Circle] your " + contentTypeString + " has been reported!";
}
}
public ProductCommentDao getCommentDao() {
return commentDao;
}
public void setCommentDao(ProductCommentDao commentDao) {
this.commentDao = commentDao;
}
}
| 42.433628 | 91 | 0.699062 |
90933e246fe2a534bdabf1d4ec8fbdd6ed21d9dd | 872 | /**
* @Auther: cheng.tang
* @Date: 2019/6/12
* @Description:
*/
package com.tangcheng.learning.service.valid.impl;
import com.tangcheng.learning.service.valid.ValidatedService;
import com.tangcheng.learning.web.dto.dto.ValidateResultDTO;
import com.tangcheng.learning.web.dto.req.UserReq;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
/**
* @Auther: cheng.tang
* @Date: 2019/6/12
* @Description:
*/
@Service
@Validated
public class ValidatedServiceImpl implements ValidatedService {
@Override
public ValidateResultDTO testValidateService(@NotNull(message = "userId不能为空") Integer userId, UserReq userReq) {
ValidateResultDTO dto = new ValidateResultDTO();
dto.setAge(userId);
dto.setName("N");
return dto;
}
}
| 25.647059 | 116 | 0.741972 |
ba567baa5a466d8bd42d7f597143a81c15dfbbb1 | 506 | package org.nlp;
import lombok.Data;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* 描述用途
* <p>
* </p>
* DATE 2020/2/21.
*
* @author zhangjunbo.
*/
@Data
public class ACTree {
private String word;
private Boolean end;
private ACTree fail;
private Map<String, ACTree> next;
public ACTree() {
next = new HashMap<>();
end = false;
word = "";
}
@Override
public String toString() {
return word;
}
}
| 14.882353 | 37 | 0.583004 |
3190d15398bcd196738ad51181aa43d0dc1d2fed | 1,306 | package grafioschtrader.entities;
import java.time.LocalDate;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class HoldBase {
@Column(name = "id_tenant")
protected Integer idTenant;
@Column(name = "id_portfolio")
protected Integer idPortfolio;
@Column(name = "to_hold_date")
protected LocalDate toHoldDate;
@Column(name = "valid_timestamp")
protected LocalDateTime validTimestamp;
public HoldBase() {
}
public HoldBase(Integer idTenant, Integer idPortfolio) {
this(idTenant, idPortfolio, null);
}
public HoldBase(Integer idTenant, Integer idPortfolio, LocalDate toHoldDate) {
this.idTenant = idTenant;
this.idPortfolio = idPortfolio;
this.toHoldDate = toHoldDate;
this.validTimestamp = LocalDateTime.now();
}
public LocalDate getToHoldDate() {
return toHoldDate;
}
public void setToHoldDate(LocalDate toHoldDate) {
this.toHoldDate = toHoldDate;
}
public Integer getIdTenant() {
return idTenant;
}
public Integer getIdPortfolio() {
return idPortfolio;
}
@Override
public String toString() {
return "HoldBase [idTenant=" + idTenant + ", idPortfolio=" + idPortfolio + ", toHoldDate=" + toHoldDate + "]";
}
}
| 21.766667 | 114 | 0.721286 |
3851be79cb8b6328b349d50bdacc4caf2ca3e699 | 507 | package cn.hutool.desgin.singleton;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class DataSourceConfigTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void getConfig() {
String result = DataSourceConfig.getInstance().getConfig();
Assert.assertEquals("read data success",result); ;
}
} | 20.28 | 67 | 0.686391 |
690a8871bb222f785170175a3c3f6015dd056132 | 1,966 | package zj;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Lzj Created on 2016/3/23.
*/
public class TestDump {
Object obj1 = new Object();
Object obj2 = new Object();
public void fun1() {
synchronized (obj1) {
fun2();
}
}
public void fun2() {
synchronized (obj2) {
//让线程一直运行以便在控制台打印出堆栈信息 ctrl + break
while (true) {
System.out.print("");
}
}
}
public static void main(String[] args) {
TestDump a = new TestDump();
a.fun1();
}
void a() {
Map<String, Object> map = new HashMap<>();
Object o = new Object();
map.put("o", o);
//还需要从map中删除该引用才可以
o = null;
}
//创建锁
private Lock lock = new ReentrantLock();
//创建关联条件
private Condition isFull = lock.newCondition();
private Condition isEmpty = lock.newCondition();
private int size = 2;
void get() {
//获取锁
lock.lock();
try {
//等待满足条件并接到唤醒通知
while (size == 0) {
isEmpty.await();
}
System.out.println("doGet when size == " + (size--));
isEmpty.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
}
void set() {
//获取锁
lock.lock();
try {
//等待满足条件并接到唤醒通知
while (size == 2) {
isFull.await();
}
System.out.println("doSet when size == " + (size++));
isFull.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
}
}
| 21.844444 | 65 | 0.485758 |
f053203d3194209662c4230269f9120440262700 | 11,271 | /**
*
*/
package org.jbei.auth.hmac;
import com.google.common.net.PercentEscaper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpRequestBase;
import org.jbei.auth.KeyTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.*;
import java.util.*;
/**
* Generates {@link HmacSignature} objects for use in authenticating requests to a REST service. By
* default this class will generate {@link HmacSignature} objects conforming to version 1 of the
* JBEI authentication specification. An HTTP Authorization header is set with the format
* {@code Version:KeyId:UserId:Signature}, with:
* <ul>
* <li>{@code Version = 1},</li>
* <li>{@code KeyId} is a string identifying the key used to sign the request,</li>
* <li>{@code UserId} is a string identifying the user (if any) the request is submitted on behalf
* of,</li>
* <li>{@code Signature} is a Base64-encoded string of the request content signed with the SHA-1
* HMAC algorithm (specified in RFC 2104)</li>
* </ul>
* This class builds objects to generate the {@code Signature} portion of the header, given a
* request object and a {@code UserId}. The {@code Signature} is generated by constructing a string
* containing the following separated by a newline character:
* <ul>
* <li>{@code UserId}</li>
* <li>the HTTP Method (e.g. {@code GET}, {@code POST})</li>
* <li>the HTTP Host</li>
* <li>the request path</li>
* <li>the query string, <i>sorted</i> by natural UTF-8 byte ordering of parameter names</li>
* <li>the content of the request entity body</li>
* </ul>
* This constructed string is then signed with the key used to initialize this object.
*
* @author wcmorrell
* @version 1.0
* @since 1.0
*/
public class HmacSignatureFactory {
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final Comparator<String> QUERY_COMPARATOR = new Comparator<String>() {
@Override
public int compare(final String a, final String b) {
return a.substring(0, a.indexOf("=")).compareTo(b.substring(0, b.indexOf("=")));
}
};
private static final Logger log = LoggerFactory.getLogger(HmacSignatureFactory.class);
private static final PercentEscaper ESCAPER = new PercentEscaper("-_.~", false);
private static final String HMAC = "HmacSHA1";
private static final String NEWLINE = "\n";
private final KeyTable table;
/**
* Convenience method to create a new random key for signing requests.
*
* @return a SecretKey instance
* @throws NoSuchAlgorithmException if the system has no registered security providers able to generate the key
*/
public static Key createKey() throws NoSuchAlgorithmException {
final KeyGenerator keyGenerator = KeyGenerator.getInstance(HMAC);
keyGenerator.init(512, new SecureRandom());
return keyGenerator.generateKey();
}
/**
* Convenience method to decode a key stored in Base64 encoding.
*
* @param encodedKey the encoded key String
* @return a SecretKey object for the decoded key
*/
public static Key decodeKey(final String encodedKey) {
return new SecretKeySpec(Base64.decodeBase64(encodedKey), HMAC);
}
/**
* Convenience method to encode a key to a Base64 String.
*
* @param key the key to encode
* @return a Base64 String representation of the key
*/
public static String encodeKey(final Key key) {
return Base64.encodeBase64String(key.getEncoded());
}
/**
* Constructor initializes factory with the secret used to sign requests.
*
* @param table object used to look up keys for signing
*/
public HmacSignatureFactory(final KeyTable table) {
this.table = table;
}
/**
* @param request a request received via Servlet API
* @param keyId the key identifier signing the request
* @param userId the user creating the request
* @return an {@link HmacSignature} initialized with the request headers; the request stream may
* need to be passed through {@link HmacSignature#filterInput(InputStream)} to calculate
* the correct signature
* @throws SignatureException if there is an error setting up the signature
*/
public HmacSignature buildSignature(final HttpServletRequest request, final String keyId,
final String userId) throws SignatureException {
try {
final Mac mac = Mac.getInstance(HMAC);
final Key key = table.getKey(keyId);
if (key != null) {
mac.init(key);
mac.update((buildRequestString(userId, request)).getBytes(UTF8));
return new DefaultHmacSignature(mac, userId);
}
return null;
} catch (final InvalidKeyException | NoSuchAlgorithmException e) {
throw new SignatureException("Failed to initialize signature");
}
}
/**
* @param request a request to be sent via HttpClient API
* @param keyId the key identifier signing the request
* @param userId the user creating the request
* @return an {@link HmacSignature} initialized with the request headers; the request stream may
* need to be passed through {@link HmacSignature#filterOutput(OutputStream)} to
* calculate the correct signature
* @throws SignatureException if there is an error setting up the signature
*/
public HmacSignature buildSignature(final HttpRequestBase request, final String keyId,
final String userId) throws SignatureException {
try {
final Mac mac = Mac.getInstance(HMAC);
final Key key = table.getKey(keyId);
if (key != null) {
mac.init(key);
mac.update((buildRequestString(userId, request)).getBytes(UTF8));
return new DefaultHmacSignature(mac, userId);
}
return null;
} catch (final InvalidKeyException | NoSuchAlgorithmException e) {
throw new SignatureException("Failed to initialize signature");
}
}
/**
* Builds initial signature object from raw individual components.
*
* @param keyId
* @param userId
* @param method
* @param host
* @param path
* @param params
* @return an {@link HmacSignature} initialized with the request headers; the request stream may
* need to be passed through {@link HmacSignature#filterOutput(OutputStream)} to
* calculate the correct signature
* @throws SignatureException
*/
public HmacSignature buildSignature(final String keyId, final String userId,
final String method, final String host, final String path,
final Map<String, ? extends Iterable<String>> params) throws SignatureException {
try {
final Mac mac = Mac.getInstance(HMAC);
final Key key = table.getKey(keyId);
if (key != null) {
mac.init(key);
mac.update((buildRequestString(userId, method, host, path,
extractAndSortParams(params))).getBytes(UTF8));
return new DefaultHmacSignature(mac, userId);
}
return null;
} catch (final InvalidKeyException | NoSuchAlgorithmException e) {
throw new SignatureException("Failed to initialize signature");
}
}
private List<String> extractAndSortParams(final Map<String, ? extends Iterable<String>> params) {
final List<String> encParams = new ArrayList<String>();
for (final Map.Entry<String, ? extends Iterable<String>> entry : params.entrySet()) {
final String name = ESCAPER.escape(entry.getKey());
for (final String value : entry.getValue()) {
encParams.add(name + "=" + ESCAPER.escape(value));
}
}
Collections.sort(encParams, QUERY_COMPARATOR);
return encParams;
}
private List<String> extractAndSortParams(final HttpServletRequest request) {
final List<String> encParams = new ArrayList<String>();
for (final Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
final String name = ESCAPER.escape(entry.getKey());
for (final String value : entry.getValue()) {
encParams.add(name + "=" + ESCAPER.escape(value));
}
}
Collections.sort(encParams, QUERY_COMPARATOR);
return encParams;
}
private List<String> extractAndSortParams(final HttpRequestBase request) {
final List<String> encParams = new ArrayList<String>();
final String query = request.getURI().getRawQuery();
if (query != null) {
// split on ampersand (&)
for (final String parameter : StringUtils.split(request.getURI().getRawQuery(), "&")) {
encParams.add(parameter);
}
}
Collections.sort(encParams, QUERY_COMPARATOR);
return encParams;
}
private String buildRequestString(final String userId, final String method, final String host,
final String path, final List<String> params) {
final StringBuilder buffer = new StringBuilder();
final String sortedParams = StringUtils.join(params.iterator(), "&");
buffer.append(userId).append(NEWLINE);
buffer.append(method).append(NEWLINE);
buffer.append(host).append(NEWLINE);
buffer.append(path).append(NEWLINE);
buffer.append(sortedParams).append(NEWLINE);
debugRequestString(buffer);
return buffer.toString();
}
private String buildRequestString(final String userId, final HttpServletRequest request) {
return buildRequestString(userId, request.getMethod(), request.getHeader("Host"),
request.getRequestURI(), extractAndSortParams(request));
}
private String buildRequestString(final String userId, final HttpRequestBase request) {
final Header host = request.getFirstHeader("Host");
final URI uri = request.getURI();
return buildRequestString(userId, request.getMethod(), host.getValue(), uri.getRawPath(),
extractAndSortParams(request));
}
private void debugRequestString(final StringBuilder buffer) {
if (log.isDebugEnabled()) {
final StringBuilder debug = new StringBuilder();
debug.append("Constructed request string:").append(NEWLINE);
debug.append("-----BEGIN-----").append(NEWLINE);
debug.append(buffer).append(NEWLINE);
debug.append("----- END -----").append(NEWLINE);
log.debug(debug.toString());
}
}
}
| 41.744444 | 121 | 0.650342 |
c2035a151797c8636eaed08b987565568566c0f7 | 2,256 | package com.capture.packages.controller;
import com.capture.packages.model.NetworkCardInfos;
import com.capture.packages.model.WifiInfos;
import com.capture.packages.service.INetworkCardService;
import org.pcap4j.core.PcapAddress;
import org.pcap4j.core.PcapNetworkInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Benedict Jin on 2016/4/14.
*/
@Controller
@RequestMapping("/network")
public class NetworkCardController {
@Autowired
private INetworkCardService networkCardService;
@RequestMapping(value = "/cards", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public List<NetworkCardInfos> queryCapture(HttpServletRequest request, Model model) {
List<PcapNetworkInterface> pcapNetworkInterfaces = networkCardService.displayAllCards();
List<NetworkCardInfos> networkCardInfosList = new LinkedList<>();
NetworkCardInfos networkCardInfos;
for (PcapNetworkInterface pcapNetworkInterface : pcapNetworkInterfaces) {
networkCardInfos = new NetworkCardInfos();
networkCardInfos.setName(pcapNetworkInterface.getName());
networkCardInfos.setDescription(pcapNetworkInterface.getDescription());
List<PcapAddress> pcapAddresses = pcapNetworkInterface.getAddresses();
networkCardInfos.setAddresses(
pcapAddresses == null || pcapAddresses.size() == 0 ? "" :
pcapAddresses.get(0).getAddress().toString());
networkCardInfosList.add(networkCardInfos);
}
return networkCardInfosList;
}
@RequestMapping(value = "/wifi/ips", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public List<WifiInfos> getDeviceIps(HttpServletRequest request, Model model) {
return networkCardService.getDeviceIps();
}
}
| 40.285714 | 96 | 0.745567 |
bafd2d9442ebde158254ae5ba2e1a6d77d7a7011 | 995 | package com.maxbin.hadoop.Hdfs2Hbase;
import java.io.IOException;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class Hdfs2HbaseReducer extends Reducer<Text, Text, ImmutableBytesWritable, Put>{
@Override
protected void reduce(Text rowKey, Iterable<Text> value, Context context)
throws IOException, InterruptedException {
String k = rowKey.toString();
for(Text val : value) {
Put put = new Put(k.getBytes());
String[] strs = val.toString().split(",");
// put.add(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes(strs[0]));
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes(strs[0]));
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"), Bytes.toBytes(strs[1]));
context.write(new ImmutableBytesWritable(k.getBytes()), put);
}
}
}
| 33.166667 | 88 | 0.730653 |
822bba1d2acbe84c9104b8ef34d16a69a4a533fc | 8,538 | package de.regis24.hackathlon.bam.agent;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import javax.batch.operations.JobOperator;
import lombok.Builder;
import lombok.Getter;
@RestController
@RequestMapping("/bam")
public class BamEndpoint {
@Autowired(required = false)
private List<Job> jobs = new ArrayList<>();
@Autowired
private BamJdbcDao bamJdbcDao;
@Autowired
private JobExplorer jobExplorer;
@Autowired
private JobLauncher jobLauncher;
@Autowired
private ApplicationContext ctx;
@RequestMapping("stats")
public Stats stats() {
return Stats.builder()
.numberOfExecutions(bamJdbcDao.getNumberOfExecutions())
.numberOfProcessedItems(bamJdbcDao.getNumberOfItemsImported())
.totalExecutedTime(bamJdbcDao.getTotalExecutionTime())
.build();
}
@RequestMapping("jobs")
public List<JobStats> jobStats() {
return jobs.stream()
.map(this::lastJobExecution)
.filter(jobExecution -> jobExecution != null)
.map(this::toJobStats)
.collect(Collectors.toList());
}
@RequestMapping("job/{jobName}")
public List<BamJobExecution> singleJob(@PathVariable("jobName") String jobName)
throws NoSuchJobException {
List<JobInstance> jobInstances = jobExplorer.getJobInstances(jobName, 0, 1);
if (!CollectionUtils.isEmpty(jobInstances)) {
List<JobExecution> executions = jobExplorer.getJobExecutions(jobInstances.get(0));
return executions.stream().map(BamJobExecution::fromJobExecution)
.collect(Collectors.toList());
}
return new ArrayList<>();
}
@RequestMapping("job/{jobName}/run")
public void runJob(@PathVariable("jobName") String jobName){
Job job = (Job) ctx.getBean(jobName);
try {
jobLauncher.run(job, new JobParametersBuilder().toJobParameters());
} catch (Exception e) {
}
}
private JobStats toJobStats(JobExecution jobExecution) {
int skippedItems = 0;
int writtenItems = 0;
for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
skippedItems += stepExecution.getReadSkipCount()
+ stepExecution.getProcessSkipCount()
+ stepExecution.getWriteSkipCount();
writtenItems += stepExecution.getWriteCount();
}
return JobStats.builder()
.jobName(jobExecution.getJobInstance().getJobName())
.numberOfSkippedItems(skippedItems)
.numberOfWrittenItems(writtenItems)
.resultOfLastExecution(jobExecution.getExitStatus().getExitCode())
.build();
}
private JobExecution lastJobExecution(Job job) {
List<JobInstance> jobInstances = jobExplorer.getJobInstances(job.getName(), 0, 1);
if (!CollectionUtils.isEmpty(jobInstances)) {
List<JobExecution> jobExecutions = jobExplorer.getJobExecutions(jobInstances.get(0));
if (!CollectionUtils.isEmpty(jobExecutions)) {
return jobExecutions.get(0);
}
}
return null;
}
@Getter
@Builder
public static class Stats {
private int numberOfExecutions;
private int numberOfProcessedItems;
private long totalExecutedTime;
}
@Getter
@Builder
public static class JobStats {
String jobName;
int numberOfWrittenItems;
int numberOfSkippedItems;
String resultOfLastExecution;
}
@Getter
public static class BamJobExecution {
public static final BamJobExecution fromJobExecution(JobExecution jobExecution) {
BamJobExecution execution = new BamJobExecution();
execution.jobParameters = jobExecution.getJobParameters();
execution.jobInstance = jobExecution.getJobInstance();
execution.status = jobExecution.getStatus();
execution.startTime = jobExecution.getStartTime();
execution.endTime = jobExecution.getEndTime();
execution.lastUpdated = jobExecution.getLastUpdated();
execution.exitStatus = jobExecution.getExitStatus();
execution.executionContext = jobExecution.getExecutionContext();
execution.failureExceptions = jobExecution.getFailureExceptions();
execution.jobConfigurationName = jobExecution.getJobConfigurationName();
execution.stepExecutions = jobExecution.getStepExecutions().stream()
.map(BamStepExecution::fromStepExecution)
.collect(Collectors.toSet());
return execution;
}
private JobParameters jobParameters;
private JobInstance jobInstance;
private Collection<BamStepExecution> stepExecutions = new HashSet<>();
private BatchStatus status = BatchStatus.STARTING;
private Date startTime = null;
private Date createTime = new Date(System.currentTimeMillis());
private Date endTime = null;
private Date lastUpdated = null;
private ExitStatus exitStatus = ExitStatus.UNKNOWN;
private ExecutionContext executionContext = new ExecutionContext();
private List<Throwable> failureExceptions = new ArrayList<>();
private String jobConfigurationName;
}
@Getter
public static class BamStepExecution {
public static final BamStepExecution fromStepExecution(StepExecution stepExecution) {
BamStepExecution execution = new BamStepExecution();
execution.stepName = stepExecution.getStepName();
execution.status = stepExecution.getStatus();
execution.readCount = stepExecution.getReadCount();
execution.writeCount = stepExecution.getWriteCount();
execution.commitCount = stepExecution.getCommitCount();
execution.readSkipCount = stepExecution.getReadSkipCount();
execution.rollbackCount = stepExecution.getRollbackCount();
execution.processSkipCount = stepExecution.getProcessSkipCount();
execution.writeSkipCount = stepExecution.getWriteSkipCount();
execution.startTime = stepExecution.getStartTime();
execution.endTime = stepExecution.getEndTime();
execution.lastUpdated = stepExecution.getLastUpdated();
execution.executionContext = stepExecution.getExecutionContext();
execution.exitStatus = stepExecution.getExitStatus();
execution.terminateOnly = stepExecution.isTerminateOnly();
execution.filterCount = stepExecution.getFilterCount();
execution.failureExceptions = stepExecution.getFailureExceptions();
return execution;
}
private String stepName;
private BatchStatus status = BatchStatus.STARTING;
private int readCount = 0;
private int writeCount = 0;
private int commitCount = 0;
private int rollbackCount = 0;
private int readSkipCount = 0;
private int processSkipCount = 0;
private int writeSkipCount = 0;
private Date startTime = new Date(System.currentTimeMillis());
private Date endTime = null;
private Date lastUpdated = null;
private ExecutionContext executionContext = new ExecutionContext();
private ExitStatus exitStatus = ExitStatus.EXECUTING;
private boolean terminateOnly;
private int filterCount;
private List<Throwable> failureExceptions = new CopyOnWriteArrayList<Throwable>();
}
}
| 36.025316 | 91 | 0.75205 |
0c9b98e207e20e18de73fc51836340d5c31f1ecf | 1,087 | package com.csr.csrportal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
@SpringBootApplication
@PropertySources({
@PropertySource(value="classpath:test.properties", ignoreResourceNotFound=true),
@PropertySource(value="classpath:message.properties", ignoreResourceNotFound=true),
@PropertySource(value="file:C:\\Workspaces\\springboot\\src\\main\\java\\test1.properties", ignoreResourceNotFound=true)
})
public class CsrPortalApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CsrPortalApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(CsrPortalApplication.class, args);
}
}
| 41.807692 | 121 | 0.841766 |
0276a9c7611a83d9424372d4ccbfdfed91ebde23 | 5,502 | package de.zentoo.robocupanalytics.uicontroller;
import de.zentoo.robocupanalytics.DefaultContext;
import de.zentoo.robocupanalytics.event.action.ControlAction;
import de.zentoo.robocupanalytics.event.action.ShowAction;
import de.zentoo.robocupanalytics.event.listener.ControlActionListener;
import de.zentoo.robocupanalytics.event.listener.ShowActionListener;
import de.zentoo.robocupanalytics.event.ListenerHandler;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class MonitorControl implements Initializable{
private static final Logger LOGGER = LoggerFactory.getLogger(MonitorControl.class);
private DefaultContext context = DefaultContext.getInstance();
private List<ControlActionListener> listenerList = new ArrayList<>();
private ListenerHandler listenerHandler = null;
private boolean isPlay = false;
@FXML
private Button button_backback;
@FXML
private Button button_back;
@FXML
private Button button_play_stop;
@FXML
private Button button_forward;
@FXML
private Button button_forwardforward;
@FXML
private TextField textField_time;
@FXML
private void stop_click(ActionEvent event) {
if(isPlay){
listenerHandler.setAction(new ControlAction() {
@Override
public Event getEvent() {
return Event.STOP;
}
});
} else {
listenerHandler.setAction(new ControlAction() {
@Override
public Event getEvent() {
return Event.PLAY;
}
});
}
}
@FXML
private void fast_back(ActionEvent event) {
listenerHandler.setAction(new ControlAction() {
@Override
public Event getEvent() {
return Event.FASTBACK;
}
});
}
@FXML
private void fast_forward(ActionEvent event) {
listenerHandler.setAction(new ControlAction() {
@Override
public Event getEvent() {
return Event.FASTFORWARD;
}
});
}
@FXML
private void step_forward(ActionEvent event) {
listenerHandler.setAction(new ControlAction() {
@Override
public Event getEvent() {
return Event.FORWARD;
}
});
}
@FXML
private void step_backward(ActionEvent event) {
listenerHandler.setAction(new ControlAction() {
@Override
public Event getEvent() {
return Event.BACK;
}
});
}
@FXML
private void jumpTo(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
listenerHandler.setAction(new ControlAction() {
@Override
public Event getEvent() {
return Event.JUMPTO;
}
@Override
public int getTime() {
Integer time = Integer.valueOf(textField_time.getText());
if (time == null) time = 0;
return time;
}
});
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
/*InputStream fontStream = Propertieloader.getResourceAsStream("styles/fontawesome-webfont.ttf");
FontAwesome fontAwesome = new FontAwesome(fontStream);
int fontsize = 18;
Glyph glyph = fontAwesome.create('\uf049').size(fontsize); //GEAR
button_backback.setGraphic(glyph);
button_backback.setText("");
glyph = fontAwesome.create('\uf04a').size(fontsize);
button_back.setGraphic(glyph);
button_back.setText("");
glyph = fontAwesome.create('\uf04d').size(fontsize);
button_play_stop.setGraphic(glyph);
button_play_stop.setText("");
glyph = fontAwesome.create('\uf04e').size(fontsize);
button_forward.setGraphic(glyph);
button_forward.setText("");
glyph = fontAwesome.create('\uf050').size(fontsize);
button_forwardforward.setGraphic(glyph);
button_forwardforward.setText("");*/
listenerHandler = context.getListenerHandler();
listenerHandler.addListener(new ShowActionListener() {
@Override
public void onAction(ShowAction action) {
textField_time.setText(String.valueOf(action.getShow().getTime()));
}
});
listenerHandler.addListener(new ControlActionListener() {
@Override
public void onAction(ControlAction action) {
if(action.getEvent() == ControlAction.Event.STOP){
// button_play_stop.setText("[▶]︎");
button_play_stop.setStyle("-fx-text-fill: darkblue");
isPlay = false;
} else if (action.getEvent() == ControlAction.Event.PLAY) {
// button_play_stop.setText("▶︎");
button_play_stop.setStyle("-fx-text-fill: red");
isPlay = true;
}
}
});
}
}
| 32.175439 | 105 | 0.601599 |
b524e08851860a9a6fb9ba6b6c6b9f9613dfd91f | 16,146 | package com.main.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.main.model.*;
import com.main.service.LinkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/Link")
public class LinkController {
private static final Logger logger = LoggerFactory.getLogger(LinkController.class);
@Autowired
private LinkService linkService;
/**
* 将数据合并的逻辑
* @param ids
* @return
*/
@RequestMapping(value = "/getLinkids/id",method = RequestMethod.POST)
public ResponseEntity<ResponseMessage> getLinkid(@RequestBody String ids){
// System.out.println(ids);
JSONObject outJson = JSONObject.parseObject(ids);
JSONArray bounds12 = outJson.getJSONArray("ids");
List<String> list2 = JSONObject.parseArray(bounds12.toJSONString(), String.class);
String[] ids_array=list2.toArray(new String[list2.size()]);
// System.out.println(ids_array);
for (int i = 0; i < ids_array.length; i++) {
ids_array[i]=ids_array[i].replace("[","").replace("]","").trim();
// System.out.println(i+"|||"+ids_array[i]);
}
logger.info("从数据库读取Link集合");
ResponseMessage responseMS= new ResponseMessage();
List<Link> returnLink= linkService.getList(ids_array);
if(returnLink !=null&&returnLink.size()>0){
responseMS.setCode(200);
responseMS.setData(returnLink);
responseMS.setMsg("成功");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else{
responseMS.setCode(422);
responseMS.setMsg("数据不能合并");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.UNPROCESSABLE_ENTITY);
}
}
/**
* 接受bounds数据返回整体数据
* @param bounds
* @return
* @RequestMapping(value = "/getWays/bounds",method = RequestMethod.POST)
* @ResponseBody
* public List<Ways> getLinkOfBound(@RequestBody String bounds){
*/
@RequestMapping(value = "/getLinkid/bounds",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> getLinkOfBound( @RequestBody String bounds){
// System.out.println("LinkController.getLinkOfBound"+bounds);
logger.info("接受到了LinkBounds请求");
JSONObject outJson = JSONObject.parseObject(bounds);
JSONArray bounds12 = outJson.getJSONArray("bounds");
List<String> list2 = JSONObject.parseArray(bounds12.toJSONString(), String.class);
String[] array=list2.toArray(new String[list2.size()]);
// System.out.println(array);
for (int i = 0; i < array.length; i++) {
array[i]=array[i].replace("[","").replace("]","").trim();
// System.out.println(i+"|||"+array[i]);
}
ResponseMessage responseMS= new ResponseMessage();
try{
List<Link_apart> ReturnLink_apart=linkService.getListOfBoundV2(array);
if (array.length!=4){
responseMS.setMsg("参数不满足四个");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.UNPROCESSABLE_ENTITY);
}
else if(ReturnLink_apart!=null){
responseMS.setCode(200);
responseMS.setMsg("成功");
responseMS.setData(ReturnLink_apart);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else{
responseMS.setCode(404);
responseMS.setMsg("报错");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}catch (Exception e){
responseMS.setCode(404);
responseMS.setMsg("报错");
responseMS.setData(e.getMessage());
e.printStackTrace();
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
/**
* 修改整体LINK的名字
* @param links
* @return
*/
@RequestMapping(value = "/updata",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> updataOfId( @RequestBody(required = false) String links){
// // System.out.println("bounds"+bounds);
// if (bounds.split(",").length != 4) {
// return new ResponseEntity<>(ResponseVO.error("新增失败"), HttpStatus.BAD_REQUEST);
// }
// System.out.println("LinkController.updataOfId"+links);
JSONObject jsonObject = JSONObject.parseObject(links);
String Updataname = jsonObject.getString("name");
JSONArray bounds12 = jsonObject.getJSONArray("link_ids");
List<String> list2 = JSONObject.parseArray(bounds12.toJSONString(), String.class);
Updata_LinkName updataname= new Updata_LinkName();
updataname.setName(Updataname);
updataname.setLink_id(list2);
// System.out.println("LinkController.updataOfId"+updataname);
List<Link> ReturnLink=linkService.updataOfId(updataname);
ResponseMessage responseMS= new ResponseMessage();
if (ReturnLink!=null){
responseMS.setCode(200);
responseMS.setMsg("修改成功");
responseMS.setData(ReturnLink);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else{
responseMS.setCode(404);
responseMS.setMsg("修改失败");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
/**
*删除Link数据
* @param link_ids
* @return
*/
@RequestMapping(value = "/deleteLinkid/id",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> deleteOfId(@RequestBody String link_ids){
// System.out.println("link_ids");
JSONObject outJson = JSONObject.parseObject(link_ids);
JSONArray bounds12 = outJson.getJSONArray("link_ids");
List<String> list2 = JSONObject.parseArray(bounds12.toJSONString(), String.class);
String[] ids_array=list2.toArray(new String[list2.size()]);
// System.out.println(ids_array);
for (int i = 0; i < ids_array.length; i++) {
ids_array[i]=ids_array[i].replace("[","").replace("]","").trim();
// System.out.println(i+"|||"+ids_array[i]);
}
List<Link> deleteLink= linkService.deleteOfId(ids_array);
ResponseMessage responseMS= new ResponseMessage();
if (deleteLink!=null){
responseMS.setCode(200);
responseMS.setMsg("删除成功");
responseMS.setData(deleteLink);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else{
responseMS.setCode(404);
responseMS.setMsg("删除失败");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
/**
* 返回回收站的数据
* @return
*/
@RequestMapping(value = "/recover",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<ResponseMessage> recover( ){
List<Link> recoverLink= linkService.recover();
ResponseMessage responseMS= new ResponseMessage();
if(recoverLink.size()==0 ){
responseMS.setCode(200);
responseMS.setMsg("成功");
responseMS.setData(recoverLink);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}
else if (recoverLink!=null){
responseMS.setCode(200);
responseMS.setMsg("成功");
responseMS.setData(recoverLink);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else{
responseMS.setCode(404);
responseMS.setMsg("没有获取到回收站数据");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
/**
* 还原回收站数据到 原始数据表中
* @param link_id
* @return
*/
@RequestMapping(value = "/recover/reduction",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> recoverReduction(@RequestBody String selectIdList ){
// System.out.println("LinkController.recoverReduction"+selectIdList);
String link_id=selectIdList;
JSONObject outJson = JSONObject.parseObject(link_id);
JSONArray bounds12 = outJson.getJSONArray("selectIdList");
List<String> list2 = JSONObject.parseArray(bounds12.toJSONString(), String.class);
String[] ids_array=list2.toArray(new String[list2.size()]);
List<Link> recoverLink= linkService.recoverReduction(ids_array);
ResponseMessage responseMS= new ResponseMessage();
if (recoverLink!=null){
responseMS.setCode(200);
responseMS.setMsg("成功");
responseMS.setData(recoverLink);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else{
responseMS.setCode(404);
responseMS.setMsg("修改失败");
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
//还原数据到原始表中 传过来的数据应该是 新的Link_id
/**
*
* @param link_id
* @return
*/
@RequestMapping(value = "/reduction",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> reductionById(@RequestBody String link_id){
// System.out.println("LinkController.reductionById 111"+link_id);
JSONObject outJson = JSONObject.parseObject(link_id);
String Link_id1 = outJson.getString("link_id");
// System.out.println("LinkController.reductionById 222"+Link_id1);
String[] ids_array={Link_id1};
// System.out.println("ids_array :"+ids_array[0]);
// System.out.println(ids_array);
for (int i = 0; i < ids_array.length; i++) {
ids_array[i]=ids_array[i].replace("[","").replace("]","").trim();
// System.out.println(i+"|||"+ids_array[i]);
}
ResponseMessage responseMS= new ResponseMessage();
//// System.out.println(link_id);
// System.out.println("---------------------------------------");
// linkService.reductionById(ids_array);
List<Original> reductionLink=linkService.reductionById(ids_array);
if(reductionLink!=null){
responseMS.setMsg("还原数据成功");
responseMS.setCode(200);
responseMS.setData(reductionLink);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else {
responseMS.setMsg("还原数据失败");
responseMS.setCode(404);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
// ResponseMessage responseMS= new ResponseMessage();
// if (
// linkService.getListOfBoundV2(array)!=null
// ){
// responseMS.setCode(200);
// responseMS.setMsg("成功");
// responseMS.setData(linkService.getListOfBoundV2(array));
//
// return responseMS;
// }
// else{
// responseMS.setCode(404);
// responseMS.setMsg("参数不对");
// return responseMS;
// }
}
/**
*
* @param link_ids
* @return
* 合并link到道路级别
*/
@RequestMapping(value = "/generate/road",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> LinksToRoad(@RequestBody String link_ids){
JSONObject outJson = JSONObject.parseObject(link_ids);
JSONArray Link_id1 = outJson.getJSONArray("link_ids");
String link_name = outJson.getString("name");
String direction_name = outJson.getString("direction_name");
// List<String> list2 = JSONObject.parseArray(link_ids, String.class);
RoadMerge roadMerge = JSONObject.parseObject(link_ids,RoadMerge.class);
System.out.println(roadMerge);
List<Road> roadlist= linkService.LinktoRoad2(roadMerge);
ResponseMessage responseMS= new ResponseMessage();
if(roadlist!=null){
responseMS.setMsg("合并数据成功");
responseMS.setCode(200);
responseMS.setData(roadlist);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else if(roadlist==null){
responseMS.setMsg("合并数据失败或者主路名字重复");
responseMS.setCode(422);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.UNPROCESSABLE_ENTITY);
}else{
responseMS.setMsg("合并数据失败");
responseMS.setCode(404);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
/**
*将node 节点合并成路口
* @param link_ids
* @return
*/
@RequestMapping(value = "/generate/intersection",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> IntersectionToRoad(@RequestBody String intersection){
// System.out.println("LinkController.reductionById 111"+intersection);
JSONObject outJson = JSONObject.parseObject(intersection);
JSONArray Link_id1 = outJson.getJSONArray("associatedIds");
// String[] ids_array={Link_id1};
List<String> list2 = JSONObject.parseArray(Link_id1.toJSONString(), String.class);
String[] ids_array=list2.toArray(new String[list2.size()]);
// System.out.println(ids_array);
for (int i = 0; i < ids_array.length; i++) {
ids_array[i]=ids_array[i].replace("[","").replace("]","").trim();
// System.out.println(i+"|||"+ids_array[i]);
}
List<Intersection> inter_last=linkService.intersectionToRoad(ids_array);
ResponseMessage responseMS= new ResponseMessage();
if(inter_last.size()>0){
responseMS.setCode(200);
responseMS.setMsg("成功");
responseMS.setData(inter_last);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else{
responseMS.setCode(404);
responseMS.setMsg("失败");
responseMS.setData(inter_last);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
/**
*
* @param link_id
* @return
*/
@RequestMapping(value = "/select/name",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ResponseMessage> selectForName(@RequestBody String name){
JSONObject outJson = JSONObject.parseObject(name);
String name1 = outJson.getString("name");
// System.out.println(name1);
List<LinkOrigin> reductionLink=linkService.selectForName(name1);
// System.out.println("数量为"+reductionLink.size());
for (int i = 0; i < reductionLink.size(); i++) {
// System.out.println("查找数据整体"+reductionLink.get(i).toString());
}
ResponseMessage responseMS= new ResponseMessage();
if(reductionLink!=null&&reductionLink.size()>0){
responseMS.setMsg("搜索数据成功");
responseMS.setCode(200);
responseMS.setData(reductionLink.get(0));
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.OK);
}else if(reductionLink.size()==0){
responseMS.setMsg("搜索数据成功 返回数据为空");
responseMS.setCode(422);
//responseMS.setData(reductionLink.get(0));
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.UNPROCESSABLE_ENTITY);
} else {
responseMS.setMsg("搜索数据失败");
responseMS.setCode(404);
return new ResponseEntity<ResponseMessage>(responseMS,HttpStatus.NOT_FOUND);
}
}
}
| 34.948052 | 103 | 0.625232 |
06b2927a50363fe4f16da7538e3131a22dd89ec0 | 554 | package com.webank.wecross.routine.htlc;
public class HTLCErrorCode {
// WeCrossHTLC
public static final int REQUEST_ERROR = 1001;
public static final int LOCK_ERROR = 1002;
public static final int UNLOCK_ERROR = 1003;
public static final int VERIFY_ERROR = 1004;
public static final int NO_PERMISSION = 1005;
public static final int TRANSACTION_ERROR = 1006;
public static final int GET_TX_INFO_ERROR = 1007;
public static final int NO_COUNTERPARTY_RESOURCE = 1008;
public static final int NONE_RETURN = 1009;
}
| 36.933333 | 60 | 0.747292 |
b94ab1dd1c9647f77c1bbacdd4e9a9291e5a727e | 659 | /*
* 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 com.hellokoding.account.viewModel;
/**
*
* @author kklos
*/
public class BlogView {
private String title;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 19.382353 | 79 | 0.652504 |
ed6ce65eb813a211ebfdcc963a80226ff04bc677 | 1,407 | package entities.reply;
import entities.util.Content;
import entities.util.MessageType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Mauricio on 27/01/2017.
*/
public class ContentExecuteReplyOk extends Content {
private String status;
/**
* This field represents the global kernel counter that increases by one with each request that stores history
*/
private int executionCount;
/**
* This field represents a way to trigger frontend actions from the kernel.
* (Payloads are considered deprecated, though their replacement is not yet implemented.)
*/
@SuppressWarnings("unused")
private List<Map<String, String>> payload;
/**
* This field represents the results for the user_expressions
*/
@SuppressWarnings("unused")
private Map<String, String> userExpressions;
public ContentExecuteReplyOk(int executionCount) {
this.status = "ok";
this.executionCount = executionCount;
this.payload = new ArrayList<Map<String, String>>();
this.userExpressions = new HashMap<String, String>();
}
public String getStatus() {
return status;
}
public int getExecutionCount() {
return executionCount;
}
@Override
public String getMessageType() {
return MessageType.EXECUTE_REPLY;
}
}
| 25.125 | 114 | 0.687278 |
3441ded22460bc2bc9419ebb5d57d2c2f28b874a | 1,333 | package org.trebol.operation.controllers;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.trebol.pojo.DataPagePojo;
import org.trebol.operation.GenericDataController;
import org.trebol.pojo.PersonPojo;
import org.trebol.config.OperationProperties;
import org.trebol.jpa.entities.Person;
import org.trebol.jpa.GenericJpaService;
/**
* API point of entry for Person entities
*
* @author Benjamin La Madrid <bg.lamadrid at gmail.com>
*/
@RestController
@RequestMapping("/data/people")
public class DataPeopleController
extends GenericDataController<PersonPojo, Person> {
@Autowired
public DataPeopleController(OperationProperties globals, GenericJpaService<PersonPojo, Person> crudService) {
super(globals, crudService);
}
@GetMapping({"", "/"})
@PreAuthorize("hasAuthority('people:read')")
public DataPagePojo<PersonPojo> readMany(@RequestParam Map<String, String> allRequestParams) {
return super.readMany(null, null, allRequestParams);
}
}
| 33.325 | 111 | 0.804201 |
90b2b4e84ba43d168e84959baf45292dc0c47253 | 451 | package com.chess.pgn;
public class GameFactory {
public static Game createGame(final PGNGameTags tags,
final String gameText,
final String outcome) {
try {
return new ValidGame(tags, PGNUtilities.processMoveText(gameText), outcome);
} catch(final ParsePGNException e) {
return new InvalidGame(tags, gameText, outcome);
}
}
} | 32.214286 | 88 | 0.569845 |
358b0e017d6c7afaaa359a774cba0ca834b1fe8b | 879 | package pl.itcraft.appstract.core.dto;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class UploadDto {
private String mimeType;
private String base64Content;
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getBase64Content() {
return base64Content;
}
public void setBase64Content(String base64Content) {
this.base64Content = base64Content;
}
@Override
public String toString() {
String content = StringUtils.hasLength(base64Content)
? base64Content.substring(0, Math.min(base64Content.length(), 50)) + " (length: " + base64Content.length() + ")"
: base64Content;
return "UploadDto [mimeType=" + mimeType + ", base64Content=" + content + "]";
}
}
| 26.636364 | 115 | 0.748578 |
f2a626516b84ed3c78eddd5851a45a5a69ff4120 | 1,117 | package com.google.android.gms.internal;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
final class zzbcl implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private /* synthetic */ zzbcc zzaDp;
private zzbcl(zzbcc zzbcc) {
this.zzaDp = zzbcc;
}
/* synthetic */ zzbcl(zzbcc zzbcc, zzbcd zzbcd) {
this(zzbcc);
}
public final void onConnected(Bundle bundle) {
this.zzaDp.zzaDh.zza(new zzbcj(this.zzaDp));
}
public final void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
this.zzaDp.zzaCv.lock();
try {
if (this.zzaDp.zzd(connectionResult)) {
this.zzaDp.zzpZ();
this.zzaDp.zzpX();
} else {
this.zzaDp.zze(connectionResult);
}
} finally {
this.zzaDp.zzaCv.unlock();
}
}
public final void onConnectionSuspended(int i) {
}
}
| 27.925 | 110 | 0.638317 |
c1fa327e3d1676b26a38def1eae743acce80b94b | 101 | public class DNA {
private String rsid;
private String genotype;
public DNA() {
}
}
| 12.625 | 28 | 0.60396 |
5e287e38a14e97ff26c77e7877a82221a01a7406 | 995 | package mchorse.blockbuster.core;
import java.util.Iterator;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
public abstract class ClassMethodTransformer extends ClassTransformer
{
public String mcp = "";
public String mcpSign = "";
public String notch = "";
public String notchSign = "";
@Override
public void process(String name, ClassNode node)
{
Iterator<MethodNode> methods = node.methods.iterator();
while (methods.hasNext())
{
MethodNode method = methods.next();
String methodName = this.checkName(method);
if (methodName != null)
{
this.processMethod(methodName, method);
}
}
}
protected String checkName(MethodNode method)
{
return this.checkName(method, this.notch, this.notchSign, this.mcp, this.mcpSign);
}
public abstract void processMethod(String name, MethodNode method);
} | 26.184211 | 90 | 0.643216 |
6f4688318a54a7cae3540ab22a151078fc11c8a3 | 31,260 | package com.github.sp00m.colalo;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static java.util.Arrays.stream;
import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
// https://www.wikiwand.com/en/ISO_639
// https://www.wikiwand.com/en/List_of_ISO_639-1_codes
public enum Language {
ABKHAZIAN("Abkhazian", Family.NORTHWEST_CAUCASIAN, Alpha2.AB, Alpha3T.ABK, Alpha3B.ABK),
AFAR("Afar", Family.AFRO_ASIATIC, Alpha2.AA, Alpha3T.AAR, Alpha3B.AAR),
AFRIKAANS("Afrikaans", Family.INDO_EUROPEAN, Alpha2.AF, Alpha3T.AFR, Alpha3B.AFR),
AKAN("Akan", Family.NIGER_CONGO, Alpha2.AK, Alpha3T.AKA, Alpha3B.AKA),
ALBANIAN("Albanian", Family.INDO_EUROPEAN, Alpha2.SQ, Alpha3T.SQI, Alpha3B.ALB),
AMHARIC("Amharic", Family.AFRO_ASIATIC, Alpha2.AM, Alpha3T.AMH, Alpha3B.AMH),
ARABIC("Arabic", Family.AFRO_ASIATIC, Alpha2.AR, Alpha3T.ARA, Alpha3B.ARA),
ARAGONESE("Aragonese", Family.INDO_EUROPEAN, Alpha2.AN, Alpha3T.ARG, Alpha3B.ARG),
ARMENIAN("Armenian", Family.INDO_EUROPEAN, Alpha2.HY, Alpha3T.HYE, Alpha3B.ARM),
ASSAMESE("Assamese", Family.INDO_EUROPEAN, Alpha2.AS, Alpha3T.ASM, Alpha3B.ASM),
AVARIC("Avaric", Family.NORTHEAST_CAUCASIAN, Alpha2.AV, Alpha3T.AVA, Alpha3B.AVA),
AVESTAN("Avestan", Family.INDO_EUROPEAN, Alpha2.AE, Alpha3T.AVE, Alpha3B.AVE),
AYMARA("Aymara", Family.AYMARAN, Alpha2.AY, Alpha3T.AYM, Alpha3B.AYM),
AZERBAIJANI("Azerbaijani", Family.TURKIC, Alpha2.AZ, Alpha3T.AZE, Alpha3B.AZE),
BAMBARA("Bambara", Family.NIGER_CONGO, Alpha2.BM, Alpha3T.BAM, Alpha3B.BAM),
BASHKIR("Bashkir", Family.TURKIC, Alpha2.BA, Alpha3T.BAK, Alpha3B.BAK),
BASQUE("Basque", Family.LANGUAGE_ISOLATE, Alpha2.EU, Alpha3T.EUS, Alpha3B.BAQ),
BELARUSIAN("Belarusian", Family.INDO_EUROPEAN, Alpha2.BE, Alpha3T.BEL, Alpha3B.BEL),
BENGALI("Bengali", Family.INDO_EUROPEAN, Alpha2.BN, Alpha3T.BEN, Alpha3B.BEN),
BIHARI_LANGUAGES("Bihari languages", Family.INDO_EUROPEAN, Alpha2.BH, Alpha3T.BIH, Alpha3B.BIH),
BISLAMA("Bislama", Family.CREOLE, Alpha2.BI, Alpha3T.BIS, Alpha3B.BIS),
BOSNIAN("Bosnian", Family.INDO_EUROPEAN, Alpha2.BS, Alpha3T.BOS, Alpha3B.BOS),
BRETON("Breton", Family.INDO_EUROPEAN, Alpha2.BR, Alpha3T.BRE, Alpha3B.BRE),
BULGARIAN("Bulgarian", Family.INDO_EUROPEAN, Alpha2.BG, Alpha3T.BUL, Alpha3B.BUL),
BURMESE("Burmese", Family.SINO_TIBETAN, Alpha2.MY, Alpha3T.MYA, Alpha3B.BUR),
CASTILIAN("Castilian", Family.INDO_EUROPEAN, Alpha2.ES, Alpha3T.SPA, Alpha3B.SPA),
CATALAN("Catalan", Family.INDO_EUROPEAN, Alpha2.CA, Alpha3T.CAT, Alpha3B.CAT),
CENTRAL_KHMER("Central Khmer", Family.AUSTROASIATIC, Alpha2.KM, Alpha3T.KHM, Alpha3B.KHM),
CHAMORRO("Chamorro", Family.AUSTRONESIAN, Alpha2.CH, Alpha3T.CHA, Alpha3B.CHA),
CHECHEN("Chechen", Family.NORTHEAST_CAUCASIAN, Alpha2.CE, Alpha3T.CHE, Alpha3B.CHE),
CHEWA("Chewa", Family.NIGER_CONGO, Alpha2.NY, Alpha3T.NYA, Alpha3B.NYA),
CHICHEWA("Chichewa", Family.NIGER_CONGO, Alpha2.NY, Alpha3T.NYA, Alpha3B.NYA),
CHINESE("Chinese", Family.SINO_TIBETAN, Alpha2.ZH, Alpha3T.ZHO, Alpha3B.CHI),
CHUANG("Chuang", Family.TAI_KADAI, Alpha2.ZA, Alpha3T.ZHA, Alpha3B.ZHA),
CHURCH_SLAVIC("Church Slavic", Family.INDO_EUROPEAN, Alpha2.CU, Alpha3T.CHU, Alpha3B.CHU),
CHURCH_SLAVONIC("Church Slavonic", Family.INDO_EUROPEAN, Alpha2.CU, Alpha3T.CHU, Alpha3B.CHU),
CHUVASH("Chuvash", Family.TURKIC, Alpha2.CV, Alpha3T.CHV, Alpha3B.CHV),
CORNISH("Cornish", Family.INDO_EUROPEAN, Alpha2.KW, Alpha3T.COR, Alpha3B.COR),
CORSICAN("Corsican", Family.INDO_EUROPEAN, Alpha2.CO, Alpha3T.COS, Alpha3B.COS),
CREE("Cree", Family.ALGONQUIAN, Alpha2.CR, Alpha3T.CRE, Alpha3B.CRE),
CROATIAN("Croatian", Family.INDO_EUROPEAN, Alpha2.HR, Alpha3T.HRV, Alpha3B.HRV),
CZECH("Czech", Family.INDO_EUROPEAN, Alpha2.CS, Alpha3T.CES, Alpha3B.CZE),
DANISH("Danish", Family.INDO_EUROPEAN, Alpha2.DA, Alpha3T.DAN, Alpha3B.DAN),
DHIVEHI("Dhivehi", Family.INDO_EUROPEAN, Alpha2.DV, Alpha3T.DIV, Alpha3B.DIV),
DIVEHI("Divehi", Family.INDO_EUROPEAN, Alpha2.DV, Alpha3T.DIV, Alpha3B.DIV),
DUTCH("Dutch", Family.INDO_EUROPEAN, Alpha2.NL, Alpha3T.NLD, Alpha3B.DUT),
DZONGKHA("Dzongkha", Family.SINO_TIBETAN, Alpha2.DZ, Alpha3T.DZO, Alpha3B.DZO),
ENGLISH("English", Family.INDO_EUROPEAN, Alpha2.EN, Alpha3T.ENG, Alpha3B.ENG),
ESPERANTO("Esperanto", Family.CONSTRUCTED, Alpha2.EO, Alpha3T.EPO, Alpha3B.EPO),
ESTONIAN("Estonian", Family.URALIC, Alpha2.ET, Alpha3T.EST, Alpha3B.EST),
EWE("Ewe", Family.NIGER_CONGO, Alpha2.EE, Alpha3T.EWE, Alpha3B.EWE),
FAROESE("Faroese", Family.INDO_EUROPEAN, Alpha2.FO, Alpha3T.FAO, Alpha3B.FAO),
FIJIAN("Fijian", Family.AUSTRONESIAN, Alpha2.FJ, Alpha3T.FIJ, Alpha3B.FIJ),
FINNISH("Finnish", Family.URALIC, Alpha2.FI, Alpha3T.FIN, Alpha3B.FIN),
FLEMISH("Flemish", Family.INDO_EUROPEAN, Alpha2.NL, Alpha3T.NLD, Alpha3B.DUT),
FRENCH("French", Family.INDO_EUROPEAN, Alpha2.FR, Alpha3T.FRA, Alpha3B.FRE),
FULAH("Fulah", Family.NIGER_CONGO, Alpha2.FF, Alpha3T.FUL, Alpha3B.FUL),
GAELIC("Gaelic", Family.INDO_EUROPEAN, Alpha2.GD, Alpha3T.GLA, Alpha3B.GLA),
GALICIAN("Galician", Family.INDO_EUROPEAN, Alpha2.GL, Alpha3T.GLG, Alpha3B.GLG),
GANDA("Ganda", Family.NIGER_CONGO, Alpha2.LG, Alpha3T.LUG, Alpha3B.LUG),
GEORGIAN("Georgian", Family.SOUTH_CAUCASIAN, Alpha2.KA, Alpha3T.KAT, Alpha3B.GEO),
GERMAN("German", Family.INDO_EUROPEAN, Alpha2.DE, Alpha3T.DEU, Alpha3B.GER),
GIKUYU("Gikuyu", Family.NIGER_CONGO, Alpha2.KI, Alpha3T.KIK, Alpha3B.KIK),
GREEK("Greek", Family.INDO_EUROPEAN, Alpha2.EL, Alpha3T.ELL, Alpha3B.GRE),
GREENLANDIC("Greenlandic", Family.ESKIMO_ALEUT, Alpha2.KL, Alpha3T.KAL, Alpha3B.KAL),
GUARANI("Guaraní", Family.TUPIAN, Alpha2.GN, Alpha3T.GRN, Alpha3B.GRN),
GUJARATI("Gujarati", Family.INDO_EUROPEAN, Alpha2.GU, Alpha3T.GUJ, Alpha3B.GUJ),
HAITIAN("Haitian", Family.CREOLE, Alpha2.HT, Alpha3T.HAT, Alpha3B.HAT),
HAITIAN_CREOLE("Haitian Creole", Family.CREOLE, Alpha2.HT, Alpha3T.HAT, Alpha3B.HAT),
HAUSA("Hausa", Family.AFRO_ASIATIC, Alpha2.HA, Alpha3T.HAU, Alpha3B.HAU),
HEBREW("Hebrew", Family.AFRO_ASIATIC, Alpha2.HE, Alpha3T.HEB, Alpha3B.HEB),
HERERO("Herero", Family.NIGER_CONGO, Alpha2.HZ, Alpha3T.HER, Alpha3B.HER),
HINDI("Hindi", Family.INDO_EUROPEAN, Alpha2.HI, Alpha3T.HIN, Alpha3B.HIN),
HIRI_MOTU("Hiri Motu", Family.AUSTRONESIAN, Alpha2.HO, Alpha3T.HMO, Alpha3B.HMO),
HUNGARIAN("Hungarian", Family.URALIC, Alpha2.HU, Alpha3T.HUN, Alpha3B.HUN),
ICELANDIC("Icelandic", Family.INDO_EUROPEAN, Alpha2.IS, Alpha3T.ISL, Alpha3B.ICE),
IDO("Ido", Family.CONSTRUCTED, Alpha2.IO, Alpha3T.IDO, Alpha3B.IDO),
IGBO("Igbo", Family.NIGER_CONGO, Alpha2.IG, Alpha3T.IBO, Alpha3B.IBO),
INDONESIAN("Indonesian", Family.AUSTRONESIAN, Alpha2.ID, Alpha3T.IND, Alpha3B.IND),
INTERLINGUA("Interlingua", Family.CONSTRUCTED, Alpha2.IA, Alpha3T.INA, Alpha3B.INA),
INTERLINGUE("Interlingue", Family.CONSTRUCTED, Alpha2.IE, Alpha3T.ILE, Alpha3B.ILE),
INUKTITUT("Inuktitut", Family.ESKIMO_ALEUT, Alpha2.IU, Alpha3T.IKU, Alpha3B.IKU),
INUPIAQ("Inupiaq", Family.ESKIMO_ALEUT, Alpha2.IK, Alpha3T.IPK, Alpha3B.IPK),
IRISH("Irish", Family.INDO_EUROPEAN, Alpha2.GA, Alpha3T.GLE, Alpha3B.GLE),
ITALIAN("Italian", Family.INDO_EUROPEAN, Alpha2.IT, Alpha3T.ITA, Alpha3B.ITA),
JAPANESE("Japanese", Family.JAPONIC, Alpha2.JA, Alpha3T.JPN, Alpha3B.JPN),
JAVANESE("Javanese", Family.AUSTRONESIAN, Alpha2.JV, Alpha3T.JAV, Alpha3B.JAV),
KALAALLISUT("Kalaallisut", Family.ESKIMO_ALEUT, Alpha2.KL, Alpha3T.KAL, Alpha3B.KAL),
KANNADA("Kannada", Family.DRAVIDIAN, Alpha2.KN, Alpha3T.KAN, Alpha3B.KAN),
KANURI("Kanuri", Family.NILO_SAHARAN, Alpha2.KR, Alpha3T.KAU, Alpha3B.KAU),
KASHMIRI("Kashmiri", Family.INDO_EUROPEAN, Alpha2.KS, Alpha3T.KAS, Alpha3B.KAS),
KAZAKH("Kazakh", Family.TURKIC, Alpha2.KK, Alpha3T.KAZ, Alpha3B.KAZ),
KIKUYU("Kikuyu", Family.NIGER_CONGO, Alpha2.KI, Alpha3T.KIK, Alpha3B.KIK),
KINYARWANDA("Kinyarwanda", Family.NIGER_CONGO, Alpha2.RW, Alpha3T.KIN, Alpha3B.KIN),
KIRGHIZ("Kirghiz", Family.TURKIC, Alpha2.KY, Alpha3T.KIR, Alpha3B.KIR),
KOMI("Komi", Family.URALIC, Alpha2.KV, Alpha3T.KOM, Alpha3B.KOM),
KONGO("Kongo", Family.NIGER_CONGO, Alpha2.KG, Alpha3T.KON, Alpha3B.KON),
KOREAN("Korean", Family.KOREANIC, Alpha2.KO, Alpha3T.KOR, Alpha3B.KOR),
KUANYAMA("Kuanyama", Family.NIGER_CONGO, Alpha2.KJ, Alpha3T.KUA, Alpha3B.KUA),
KURDISH("Kurdish", Family.INDO_EUROPEAN, Alpha2.KU, Alpha3T.KUR, Alpha3B.KUR),
KWANYAMA("Kwanyama", Family.NIGER_CONGO, Alpha2.KJ, Alpha3T.KUA, Alpha3B.KUA),
KYRGYZ("Kyrgyz", Family.TURKIC, Alpha2.KY, Alpha3T.KIR, Alpha3B.KIR),
LAO("Lao", Family.TAI_KADAI, Alpha2.LO, Alpha3T.LAO, Alpha3B.LAO),
LATIN("Latin", Family.INDO_EUROPEAN, Alpha2.LA, Alpha3T.LAT, Alpha3B.LAT),
LATVIAN("Latvian", Family.INDO_EUROPEAN, Alpha2.LV, Alpha3T.LAV, Alpha3B.LAV),
LETZEBURGESCH("Letzeburgesch", Family.INDO_EUROPEAN, Alpha2.LB, Alpha3T.LTZ, Alpha3B.LTZ),
LIMBURGAN("Limburgan", Family.INDO_EUROPEAN, Alpha2.LI, Alpha3T.LIM, Alpha3B.LIM),
LIMBURGER("Limburger", Family.INDO_EUROPEAN, Alpha2.LI, Alpha3T.LIM, Alpha3B.LIM),
LIMBURGISH("Limburgish", Family.INDO_EUROPEAN, Alpha2.LI, Alpha3T.LIM, Alpha3B.LIM),
LINGALA("Lingala", Family.NIGER_CONGO, Alpha2.LN, Alpha3T.LIN, Alpha3B.LIN),
LITHUANIAN("Lithuanian", Family.INDO_EUROPEAN, Alpha2.LT, Alpha3T.LIT, Alpha3B.LIT),
LUBA_KATANGA("Luba-Katanga", Family.NIGER_CONGO, Alpha2.LU, Alpha3T.LUB, Alpha3B.LUB),
LUXEMBOURGISH("Luxembourgish", Family.INDO_EUROPEAN, Alpha2.LB, Alpha3T.LTZ, Alpha3B.LTZ),
MACEDONIAN("Macedonian", Family.INDO_EUROPEAN, Alpha2.MK, Alpha3T.MKD, Alpha3B.MAC),
MALAGASY("Malagasy", Family.AUSTRONESIAN, Alpha2.MG, Alpha3T.MLG, Alpha3B.MLG),
MALAY("Malay", Family.AUSTRONESIAN, Alpha2.MS, Alpha3T.MSA, Alpha3B.MAY),
MALAYALAM("Malayalam", Family.DRAVIDIAN, Alpha2.ML, Alpha3T.MAL, Alpha3B.MAL),
MALDIVIAN("Maldivian", Family.INDO_EUROPEAN, Alpha2.DV, Alpha3T.DIV, Alpha3B.DIV),
MALTESE("Maltese", Family.AFRO_ASIATIC, Alpha2.MT, Alpha3T.MLT, Alpha3B.MLT),
MANX("Manx", Family.INDO_EUROPEAN, Alpha2.GV, Alpha3T.GLV, Alpha3B.GLV),
MAORI("Maori", Family.AUSTRONESIAN, Alpha2.MI, Alpha3T.MRI, Alpha3B.MAO),
MARATHI("Marathi", Family.INDO_EUROPEAN, Alpha2.MR, Alpha3T.MAR, Alpha3B.MAR),
MARSHALLESE("Marshallese", Family.AUSTRONESIAN, Alpha2.MH, Alpha3T.MAH, Alpha3B.MAH),
MOLDAVIAN("Moldavian", Family.INDO_EUROPEAN, Alpha2.RO, Alpha3T.RON, Alpha3B.RUM),
MOLDOVAN("Moldovan", Family.INDO_EUROPEAN, Alpha2.RO, Alpha3T.RON, Alpha3B.RUM),
MONGOLIAN("Mongolian", Family.MONGOLIC, Alpha2.MN, Alpha3T.MON, Alpha3B.MON),
NAURU("Nauru", Family.AUSTRONESIAN, Alpha2.NA, Alpha3T.NAU, Alpha3B.NAU),
NAVAHO("Navaho", Family.DENE_YENISEIAN, Alpha2.NV, Alpha3T.NAV, Alpha3B.NAV),
NAVAJO("Navajo", Family.DENE_YENISEIAN, Alpha2.NV, Alpha3T.NAV, Alpha3B.NAV),
NDONGA("Ndonga", Family.NIGER_CONGO, Alpha2.NG, Alpha3T.NDO, Alpha3B.NDO),
NEPALI("Nepali", Family.INDO_EUROPEAN, Alpha2.NE, Alpha3T.NEP, Alpha3B.NEP),
NORTH_NDEBELE("North Ndebele", Family.NIGER_CONGO, Alpha2.ND, Alpha3T.NDE, Alpha3B.NDE),
NORTHERN_SAMI("Northern Sami", Family.URALIC, Alpha2.SE, Alpha3T.SME, Alpha3B.SME),
NORWEGIAN("Norwegian", Family.INDO_EUROPEAN, Alpha2.NO, Alpha3T.NOR, Alpha3B.NOR),
NORWEGIAN_BOKMAL("Norwegian Bokmål", Family.INDO_EUROPEAN, Alpha2.NB, Alpha3T.NOB, Alpha3B.NOB),
NORWEGIAN_NYNORSK("Norwegian Nynorsk", Family.INDO_EUROPEAN, Alpha2.NN, Alpha3T.NNO, Alpha3B.NNO),
NUOSU("Nuosu", Family.SINO_TIBETAN, Alpha2.II, Alpha3T.III, Alpha3B.III),
NYANJA("Nyanja", Family.NIGER_CONGO, Alpha2.NY, Alpha3T.NYA, Alpha3B.NYA),
OCCITAN("Occitan", Family.INDO_EUROPEAN, Alpha2.OC, Alpha3T.OCI, Alpha3B.OCI),
OJIBWA("Ojibwa", Family.ALGONQUIAN, Alpha2.OJ, Alpha3T.OJI, Alpha3B.OJI),
OLD_BULGARIAN("Old Bulgarian", Family.INDO_EUROPEAN, Alpha2.CU, Alpha3T.CHU, Alpha3B.CHU),
OLD_CHURCH_SLAVONIC("Old Church Slavonic", Family.INDO_EUROPEAN, Alpha2.CU, Alpha3T.CHU, Alpha3B.CHU),
OLD_SLAVONIC("Old Slavonic", Family.INDO_EUROPEAN, Alpha2.CU, Alpha3T.CHU, Alpha3B.CHU),
ORIYA("Oriya", Family.INDO_EUROPEAN, Alpha2.OR, Alpha3T.ORI, Alpha3B.ORI),
OROMO("Oromo", Family.AFRO_ASIATIC, Alpha2.OM, Alpha3T.ORM, Alpha3B.ORM),
OSSETIAN("Ossetian", Family.INDO_EUROPEAN, Alpha2.OS, Alpha3T.OSS, Alpha3B.OSS),
OSSETIC("Ossetic", Family.INDO_EUROPEAN, Alpha2.OS, Alpha3T.OSS, Alpha3B.OSS),
PALI("Pali", Family.INDO_EUROPEAN, Alpha2.PI, Alpha3T.PLI, Alpha3B.PLI),
PANJABI("Panjabi", Family.INDO_EUROPEAN, Alpha2.PA, Alpha3T.PAN, Alpha3B.PAN),
PASHTO("Pashto", Family.INDO_EUROPEAN, Alpha2.PS, Alpha3T.PUS, Alpha3B.PUS),
PERSIAN("Persian", Family.INDO_EUROPEAN, Alpha2.FA, Alpha3T.FAS, Alpha3B.PER),
POLABIAN("Polabian", Family.INDO_EUROPEAN, Alpha2.POX, Alpha3T.SLA, Alpha3B.SLA),
POLISH("Polish", Family.INDO_EUROPEAN, Alpha2.PL, Alpha3T.POL, Alpha3B.POL),
PORTUGUESE("Portuguese", Family.INDO_EUROPEAN, Alpha2.PT, Alpha3T.POR, Alpha3B.POR),
PUNJABI("Punjabi", Family.INDO_EUROPEAN, Alpha2.PA, Alpha3T.PAN, Alpha3B.PAN),
PUSHTO("Pushto", Family.INDO_EUROPEAN, Alpha2.PS, Alpha3T.PUS, Alpha3B.PUS),
QUECHUA("Quechua", Family.QUECHUAN, Alpha2.QU, Alpha3T.QUE, Alpha3B.QUE),
ROMANIAN("Romanian", Family.INDO_EUROPEAN, Alpha2.RO, Alpha3T.RON, Alpha3B.RUM),
ROMANSH("Romansh", Family.INDO_EUROPEAN, Alpha2.RM, Alpha3T.ROH, Alpha3B.ROH),
RUNDI("Rundi", Family.NIGER_CONGO, Alpha2.RN, Alpha3T.RUN, Alpha3B.RUN),
RUSSIAN("Russian", Family.INDO_EUROPEAN, Alpha2.RU, Alpha3T.RUS, Alpha3B.RUS),
SAMOAN("Samoan", Family.AUSTRONESIAN, Alpha2.SM, Alpha3T.SMO, Alpha3B.SMO),
SANGO("Sango", Family.CREOLE, Alpha2.SG, Alpha3T.SAG, Alpha3B.SAG),
SANSKRIT("Sanskrit", Family.INDO_EUROPEAN, Alpha2.SA, Alpha3T.SAN, Alpha3B.SAN),
SARDINIAN("Sardinian", Family.INDO_EUROPEAN, Alpha2.SC, Alpha3T.SRD, Alpha3B.SRD),
SCOTTISH_GAELIC("Scottish Gaelic", Family.INDO_EUROPEAN, Alpha2.GD, Alpha3T.GLA, Alpha3B.GLA),
SERBIAN("Serbian", Family.INDO_EUROPEAN, Alpha2.SR, Alpha3T.SRP, Alpha3B.SRP),
SHONA("Shona", Family.NIGER_CONGO, Alpha2.SN, Alpha3T.SNA, Alpha3B.SNA),
SICHUAN_YI("Sichuan Yi", Family.SINO_TIBETAN, Alpha2.II, Alpha3T.III, Alpha3B.III),
SINDHI("Sindhi", Family.INDO_EUROPEAN, Alpha2.SD, Alpha3T.SND, Alpha3B.SND),
SINHALA("Sinhala", Family.INDO_EUROPEAN, Alpha2.SI, Alpha3T.SIN, Alpha3B.SIN),
SINHALESE("Sinhalese", Family.INDO_EUROPEAN, Alpha2.SI, Alpha3T.SIN, Alpha3B.SIN),
SLOVAK("Slovak", Family.INDO_EUROPEAN, Alpha2.SK, Alpha3T.SLK, Alpha3B.SLO),
SLOVENIAN("Slovenian", Family.INDO_EUROPEAN, Alpha2.SL, Alpha3T.SLV, Alpha3B.SLV),
SOMALI("Somali", Family.AFRO_ASIATIC, Alpha2.SO, Alpha3T.SOM, Alpha3B.SOM),
SOUTH_NDEBELE("South Ndebele", Family.NIGER_CONGO, Alpha2.NR, Alpha3T.NBL, Alpha3B.NBL),
SOUTHERN_SOTHO("Southern Sotho", Family.NIGER_CONGO, Alpha2.ST, Alpha3T.SOT, Alpha3B.SOT),
SPANISH("Spanish", Family.INDO_EUROPEAN, Alpha2.ES, Alpha3T.SPA, Alpha3B.SPA),
SUNDANESE("Sundanese", Family.AUSTRONESIAN, Alpha2.SU, Alpha3T.SUN, Alpha3B.SUN),
SWAHILI("Swahili", Family.NIGER_CONGO, Alpha2.SW, Alpha3T.SWA, Alpha3B.SWA),
SWATI("Swati", Family.NIGER_CONGO, Alpha2.SS, Alpha3T.SSW, Alpha3B.SSW),
SWEDISH("Swedish", Family.INDO_EUROPEAN, Alpha2.SV, Alpha3T.SWE, Alpha3B.SWE),
TAGALOG("Tagalog", Family.AUSTRONESIAN, Alpha2.TL, Alpha3T.TGL, Alpha3B.TGL),
TAHITIAN("Tahitian", Family.AUSTRONESIAN, Alpha2.TY, Alpha3T.TAH, Alpha3B.TAH),
TAJIK("Tajik", Family.INDO_EUROPEAN, Alpha2.TG, Alpha3T.TGK, Alpha3B.TGK),
TAMIL("Tamil", Family.DRAVIDIAN, Alpha2.TA, Alpha3T.TAM, Alpha3B.TAM),
TATAR("Tatar", Family.TURKIC, Alpha2.TT, Alpha3T.TAT, Alpha3B.TAT),
TELUGU("Telugu", Family.DRAVIDIAN, Alpha2.TE, Alpha3T.TEL, Alpha3B.TEL),
THAI("Thai", Family.TAI_KADAI, Alpha2.TH, Alpha3T.THA, Alpha3B.THA),
TIBETAN("Tibetan", Family.SINO_TIBETAN, Alpha2.BO, Alpha3T.BOD, Alpha3B.TIB),
TIGRINYA("Tigrinya", Family.AFRO_ASIATIC, Alpha2.TI, Alpha3T.TIR, Alpha3B.TIR),
TONGA("Tonga", Family.AUSTRONESIAN, Alpha2.TO, Alpha3T.TON, Alpha3B.TON),
TSONGA("Tsonga", Family.NIGER_CONGO, Alpha2.TS, Alpha3T.TSO, Alpha3B.TSO),
TSWANA("Tswana", Family.NIGER_CONGO, Alpha2.TN, Alpha3T.TSN, Alpha3B.TSN),
TURKISH("Turkish", Family.TURKIC, Alpha2.TR, Alpha3T.TUR, Alpha3B.TUR),
TURKMEN("Turkmen", Family.TURKIC, Alpha2.TK, Alpha3T.TUK, Alpha3B.TUK),
TWI("Twi", Family.NIGER_CONGO, Alpha2.TW, Alpha3T.TWI, Alpha3B.TWI),
UIGHUR("Uighur", Family.TURKIC, Alpha2.UG, Alpha3T.UIG, Alpha3B.UIG),
UKRAINIAN("Ukrainian", Family.INDO_EUROPEAN, Alpha2.UK, Alpha3T.UKR, Alpha3B.UKR),
URDU("Urdu", Family.INDO_EUROPEAN, Alpha2.UR, Alpha3T.URD, Alpha3B.URD),
UYGHUR("Uyghur", Family.TURKIC, Alpha2.UG, Alpha3T.UIG, Alpha3B.UIG),
UZBEK("Uzbek", Family.TURKIC, Alpha2.UZ, Alpha3T.UZB, Alpha3B.UZB),
VALENCIAN("Valencian", Family.INDO_EUROPEAN, Alpha2.CA, Alpha3T.CAT, Alpha3B.CAT),
VENDA("Venda", Family.NIGER_CONGO, Alpha2.VE, Alpha3T.VEN, Alpha3B.VEN),
VIETNAMESE("Vietnamese", Family.AUSTROASIATIC, Alpha2.VI, Alpha3T.VIE, Alpha3B.VIE),
VOLAPUK("Volapük", Family.CONSTRUCTED, Alpha2.VO, Alpha3T.VOL, Alpha3B.VOL),
WALLOON("Walloon", Family.INDO_EUROPEAN, Alpha2.WA, Alpha3T.WLN, Alpha3B.WLN),
WELSH("Welsh", Family.INDO_EUROPEAN, Alpha2.CY, Alpha3T.CYM, Alpha3B.WEL),
WESTERN_FRISIAN("Western Frisian", Family.INDO_EUROPEAN, Alpha2.FY, Alpha3T.FRY, Alpha3B.FRY),
WOLOF("Wolof", Family.NIGER_CONGO, Alpha2.WO, Alpha3T.WOL, Alpha3B.WOL),
XHOSA("Xhosa", Family.NIGER_CONGO, Alpha2.XH, Alpha3T.XHO, Alpha3B.XHO),
YIDDISH("Yiddish", Family.INDO_EUROPEAN, Alpha2.YI, Alpha3T.YID, Alpha3B.YID),
YORUBA("Yoruba", Family.NIGER_CONGO, Alpha2.YO, Alpha3T.YOR, Alpha3B.YOR),
ZHUANG("Zhuang", Family.TAI_KADAI, Alpha2.ZA, Alpha3T.ZHA, Alpha3B.ZHA),
ZULU("Zulu", Family.NIGER_CONGO, Alpha2.ZU, Alpha3T.ZUL, Alpha3B.ZUL);
public enum Family {
AFRO_ASIATIC("Afro-Asiatic"),
ALGONQUIAN("Algonquian"),
AUSTROASIATIC("Austroasiatic"),
AUSTRONESIAN("Austronesian"),
AYMARAN("Aymaran"),
CONSTRUCTED("Constructed"),
CREOLE("Creole"),
DENE_YENISEIAN("Dené–Yeniseian"),
DRAVIDIAN("Dravidian"),
ESKIMO_ALEUT("Eskimo–Aleut"),
INDO_EUROPEAN("Indo-European"),
JAPONIC("Japonic"),
KOREANIC("Koreanic"),
LANGUAGE_ISOLATE("Language isolate"),
MONGOLIC("Mongolic"),
NIGER_CONGO("Niger–Congo"),
NILO_SAHARAN("Nilo-Saharan"),
NORTHEAST_CAUCASIAN("Northeast Caucasian"),
NORTHWEST_CAUCASIAN("Northwest Caucasian"),
QUECHUAN("Quechuan"),
SINO_TIBETAN("Sino-Tibetan"),
SOUTH_CAUCASIAN("South Caucasian"),
TAI_KADAI("Tai–Kadai"),
TUPIAN("Tupian"),
TURKIC("Turkic"),
URALIC("Uralic");
private final String name;
Family(String name) {
this.name = name;
}
public final String getName() {
return name;
}
public final Set<Language> getLanguages() {
return Language.getByFamily(this);
}
}
public enum Alpha2 {
AA,
AB,
AE,
AF,
AK,
AM,
AN,
AR,
AS,
AV,
AY,
AZ,
BA,
BE,
BG,
BH,
BI,
BM,
BN,
BO,
BR,
BS,
CA,
CE,
CH,
CO,
CR,
CS,
CU,
CV,
CY,
DA,
DE,
DV,
DZ,
EE,
EL,
EN,
EO,
ES,
ET,
EU,
FA,
FF,
FI,
FJ,
FO,
FR,
FY,
GA,
GD,
GL,
GN,
GU,
GV,
HA,
HE,
HI,
HO,
HR,
HT,
HU,
HY,
HZ,
IA,
ID,
IE,
IG,
II,
IK,
IO,
IS,
IT,
IU,
JA,
JV,
KA,
KG,
KI,
KJ,
KK,
KL,
KM,
KN,
KO,
KR,
KS,
KU,
KV,
KW,
KY,
LA,
LB,
LG,
LI,
LN,
LO,
LT,
LU,
LV,
MG,
MH,
MI,
MK,
ML,
MN,
MR,
MS,
MT,
MY,
NA,
NB,
ND,
NE,
NG,
NL,
NN,
NO,
NR,
NV,
NY,
OC,
OJ,
OM,
OR,
OS,
PA,
PI,
PL,
POX,
PS,
PT,
QU,
RM,
RN,
RO,
RU,
RW,
SA,
SC,
SD,
SE,
SG,
SI,
SK,
SL,
SM,
SN,
SO,
SQ,
SR,
SS,
ST,
SU,
SV,
SW,
TA,
TE,
TG,
TH,
TI,
TK,
TL,
TN,
TO,
TR,
TS,
TT,
TW,
TY,
UG,
UK,
UR,
UZ,
VE,
VI,
VO,
WA,
WO,
XH,
YI,
YO,
ZA,
ZH,
ZU;
private static final Map<String, Alpha2> BY_CODE = stream(values())
.collect(collectingAndThen(toMap(Alpha2::getCode, identity()), Collections::unmodifiableMap));
private final String code;
Alpha2() {
this.code = name().toLowerCase();
}
public final String getCode() {
return code;
}
public final Set<Language> getLanguages() {
return Language.getByAlpha2(this);
}
public static Optional<Alpha2> getByCode(String code) {
return Optional.ofNullable(BY_CODE.get(code.toLowerCase()));
}
}
public enum Alpha3T {
AAR,
ABK,
AFR,
AKA,
AMH,
ARA,
ARG,
ASM,
AVA,
AVE,
AYM,
AZE,
BAK,
BAM,
BEL,
BEN,
BIH,
BIS,
BOD,
BOS,
BRE,
BUL,
CAT,
CES,
CHA,
CHE,
CHU,
CHV,
COR,
COS,
CRE,
CYM,
DAN,
DEU,
DIV,
DZO,
ELL,
ENG,
EPO,
EST,
EUS,
EWE,
FAO,
FAS,
FIJ,
FIN,
FRA,
FRY,
FUL,
GLA,
GLE,
GLG,
GLV,
GRN,
GUJ,
HAT,
HAU,
HEB,
HER,
HIN,
HMO,
HRV,
HUN,
HYE,
IBO,
IDO,
III,
IKU,
ILE,
INA,
IND,
IPK,
ISL,
ITA,
JAV,
JPN,
KAL,
KAN,
KAS,
KAT,
KAU,
KAZ,
KHM,
KIK,
KIN,
KIR,
KOM,
KON,
KOR,
KUA,
KUR,
LAO,
LAT,
LAV,
LIM,
LIN,
LIT,
LTZ,
LUB,
LUG,
MAH,
MAL,
MAR,
MKD,
MLG,
MLT,
MON,
MRI,
MSA,
MYA,
NAU,
NAV,
NBL,
NDE,
NDO,
NEP,
NLD,
NNO,
NOB,
NOR,
NYA,
OCI,
OJI,
ORI,
ORM,
OSS,
PAN,
PLI,
POL,
POR,
PUS,
QUE,
ROH,
RON,
RUN,
RUS,
SAG,
SAN,
SIN,
SLA,
SLK,
SLV,
SME,
SMO,
SNA,
SND,
SOM,
SOT,
SPA,
SQI,
SRD,
SRP,
SSW,
SUN,
SWA,
SWE,
TAH,
TAM,
TAT,
TEL,
TGK,
TGL,
THA,
TIR,
TON,
TSN,
TSO,
TUK,
TUR,
TWI,
UIG,
UKR,
URD,
UZB,
VEN,
VIE,
VOL,
WLN,
WOL,
XHO,
YID,
YOR,
ZHA,
ZHO,
ZUL;
private static final Map<String, Alpha3T> BY_CODE = stream(values())
.collect(collectingAndThen(toMap(Alpha3T::getCode, identity()), Collections::unmodifiableMap));
private final String code;
Alpha3T() {
this.code = name().toLowerCase();
}
public final String getCode() {
return code;
}
public final Set<Language> getLanguages() {
return Language.getByAlpha3T(this);
}
public static Optional<Alpha3T> getByCode(String code) {
return Optional.ofNullable(BY_CODE.get(code.toLowerCase()));
}
}
public enum Alpha3B {
AAR,
ABK,
AFR,
AKA,
ALB,
AMH,
ARA,
ARG,
ARM,
ASM,
AVA,
AVE,
AYM,
AZE,
BAK,
BAM,
BAQ,
BEL,
BEN,
BIH,
BIS,
BOS,
BRE,
BUL,
BUR,
CAT,
CHA,
CHE,
CHI,
CHU,
CHV,
COR,
COS,
CRE,
CZE,
DAN,
DIV,
DUT,
DZO,
ENG,
EPO,
EST,
EWE,
FAO,
FIJ,
FIN,
FRE,
FRY,
FUL,
GEO,
GER,
GLA,
GLE,
GLG,
GLV,
GRE,
GRN,
GUJ,
HAT,
HAU,
HEB,
HER,
HIN,
HMO,
HRV,
HUN,
IBO,
ICE,
IDO,
III,
IKU,
ILE,
INA,
IND,
IPK,
ITA,
JAV,
JPN,
KAL,
KAN,
KAS,
KAU,
KAZ,
KHM,
KIK,
KIN,
KIR,
KOM,
KON,
KOR,
KUA,
KUR,
LAO,
LAT,
LAV,
LIM,
LIN,
LIT,
LTZ,
LUB,
LUG,
MAC,
MAH,
MAL,
MAO,
MAR,
MAY,
MLG,
MLT,
MON,
NAU,
NAV,
NBL,
NDE,
NDO,
NEP,
NNO,
NOB,
NOR,
NYA,
OCI,
OJI,
ORI,
ORM,
OSS,
PAN,
PER,
PLI,
POL,
POR,
PUS,
QUE,
ROH,
RUM,
RUN,
RUS,
SAG,
SAN,
SIN,
SLA,
SLO,
SLV,
SME,
SMO,
SNA,
SND,
SOM,
SOT,
SPA,
SRD,
SRP,
SSW,
SUN,
SWA,
SWE,
TAH,
TAM,
TAT,
TEL,
TGK,
TGL,
THA,
TIB,
TIR,
TON,
TSN,
TSO,
TUK,
TUR,
TWI,
UIG,
UKR,
URD,
UZB,
VEN,
VIE,
VOL,
WEL,
WLN,
WOL,
XHO,
YID,
YOR,
ZHA,
ZUL;
private static final Map<String, Alpha3B> BY_CODE = stream(values())
.collect(collectingAndThen(toMap(Alpha3B::getCode, identity()), Collections::unmodifiableMap));
private final String code;
Alpha3B() {
this.code = name().toLowerCase();
}
public final String getCode() {
return code;
}
public final Set<Language> getLanguages() {
return Language.getByAlpha3B(this);
}
public static Optional<Alpha3B> getByCode(String code) {
return Optional.ofNullable(BY_CODE.get(code.toLowerCase()));
}
}
private static <V extends Enum<V>> Set<V> toImmutableSet(List<V> mutableList) {
return unmodifiableSet(EnumSet.copyOf(mutableList));
}
private static <K extends Enum<K>, V extends Enum<V>> Map<K, Set<V>> freeze(Map<K, List<V>> mutableMap, Class<K> keyType) {
Map<K, Set<V>> outputMap = new EnumMap<>(keyType);
mutableMap.forEach((key, mutableValues) -> outputMap.put(key, toImmutableSet(mutableValues)));
return unmodifiableMap(outputMap);
}
private static final Map<Family, Set<Language>> BY_FAMILY = stream(values())
.collect(collectingAndThen(groupingBy(Language::getFamily), byFamily -> freeze(byFamily, Family.class)));
private static final Map<Alpha2, Set<Language>> BY_ALPHA2 = stream(values())
.collect(collectingAndThen(groupingBy(Language::getAlpha2), byAlpha2 -> freeze(byAlpha2, Alpha2.class)));
private static final Map<Alpha3T, Set<Language>> BY_ALPHA3T = stream(values())
.collect(collectingAndThen(groupingBy(Language::getAlpha3T), byAlpha3T -> freeze(byAlpha3T, Alpha3T.class)));
private static final Map<Alpha3B, Set<Language>> BY_ALPHA3B = stream(values())
.collect(collectingAndThen(groupingBy(Language::getAlpha3B), byAlpha3B -> freeze(byAlpha3B, Alpha3B.class)));
private final String name;
private final Family family;
private final Alpha2 alpha2;
private final Alpha3T alpha3T;
private final Alpha3B alpha3B;
Language(String name, Family family, Alpha2 alpha2, Alpha3T alpha3T, Alpha3B alpha3B) {
this.name = name;
this.family = family;
this.alpha2 = alpha2;
this.alpha3T = alpha3T;
this.alpha3B = alpha3B;
}
public final String getName() {
return name;
}
public final Family getFamily() {
return family;
}
public final Alpha2 getAlpha2() {
return alpha2;
}
public final Alpha3T getAlpha3T() {
return alpha3T;
}
public final Alpha3B getAlpha3B() {
return alpha3B;
}
public static Set<Language> getByFamily(Family family) {
return BY_FAMILY.get(family);
}
public static Set<Language> getByAlpha2(Alpha2 alpha2) {
return BY_ALPHA2.get(alpha2);
}
public static Set<Language> getByAlpha3T(Alpha3T alpha3T) {
return BY_ALPHA3T.get(alpha3T);
}
public static Set<Language> getByAlpha3B(Alpha3B alpha3B) {
return BY_ALPHA3B.get(alpha3B);
}
}
| 31.448692 | 127 | 0.595361 |
01d2f39146c1d9dc2ba1c1bd3442e77e6c75ce80 | 9,010 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.joshua.decoder.ff.lm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import org.apache.joshua.corpus.Vocabulary;
import org.apache.joshua.util.Regex;
import org.apache.joshua.util.io.LineReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class for reading ARPA language model files.
*
* @author Lane Schwartz
*/
public class ArpaFile implements Iterable<ArpaNgram> {
private static final Logger LOG = LoggerFactory.getLogger(ArpaFile.class);
/** Regular expression representing a blank line. */
public static final Regex BLANK_LINE = new Regex("^\\s*$");
/**
* Regular expression representing a line
* starting a new section of n-grams in an ARPA language model file.
*/
public static final Regex NGRAM_HEADER = new Regex("^\\\\\\d-grams:\\s*$");
/**
* Regular expression representing a line
* ending an ARPA language model file.
*/
public static final Regex NGRAM_END = new Regex("^\\\\end\\\\s*$");
/** ARPA file for this object. */
private final File arpaFile;
/** The vocabulary associated with this object. */
private final Vocabulary vocab;
/**
* Constructs an object that represents an ARPA language model file.
*
* @param arpaFileName File name of an ARPA language model file
* @param vocab Symbol table to be used by this object
*/
public ArpaFile(String arpaFileName, Vocabulary vocab) {
this.arpaFile = new File(arpaFileName);
this.vocab = vocab;
}
public ArpaFile(String arpaFileName) throws IOException {
this.arpaFile = new File(arpaFileName);
this.vocab = new Vocabulary();
// final Scanner scanner = new Scanner(arpaFile);
// // Eat initial header lines
// while (scanner.hasNextLine()) {
// String line = scanner.nextLine();
// logger.finest("Discarding line: " + line);
// if (NGRAM_HEADER.matches(line)) {
// break;
// }
// }
// int ngramOrder = 1;
LineReader grammarReader = new LineReader(arpaFileName);
try {
for (String line : grammarReader) {
// while (scanner.hasNext()) {
//
// String line = scanner.nextLine();
String[] parts = Regex.spaces.split(line);
if (parts.length > 1) {
String[] words = Regex.spaces.split(parts[1]);
for (String word : words) {
LOG.debug("Adding to vocab: {}", word);
Vocabulary.addAll(word);
}
} else {
LOG.info(line);
}
}
} finally {
grammarReader.close();
}
//
// boolean lineIsHeader = NGRAM_HEADER.matches(line);
//
// while (lineIsHeader || BLANK_LINE.matches(line)) {
//
// if (lineIsHeader) {
// ngramOrder++;
// }
//
// if (scanner.hasNext()) {
// line = scanner.nextLine().trim();
// lineIsHeader = NGRAM_HEADER.matches(line);
// } else {
// logger.severe("Ran out of lines!");
// return;
// }
// }
//
// // Add word to vocab
// if (logger.isLoggable(Level.FINE)) logger.fine("Adding word to vocab: " + parts[ngramOrder]);
// vocab.addTerminal(parts[ngramOrder]);
//
// // Add context words to vocab
// for (int i=1; i<ngramOrder; i++) {
// if (logger.isLoggable(Level.FINE)) logger.fine("Adding context word to vocab: " + parts[i]);
// vocab.addTerminal(parts[i]);
// }
// }
LOG.info("Done constructing ArpaFile");
}
/**
* Gets the {@link org.apache.joshua.corpus.Vocabulary}
* associated with this object.
*
* @return the symbol table associated with this object
*/
public Vocabulary getVocab() {
return vocab;
}
/**
* Gets the total number of n-grams
* in this ARPA language model file.
*
* @return total number of n-grams
* in this ARPA language model file
*/
@SuppressWarnings("unused")
public int size() {
LOG.debug("Counting n-grams in ARPA file");
int count=0;
for (ArpaNgram ngram : this) {
count++;
}
LOG.debug("Done counting n-grams in ARPA file");
return count;
}
public int getOrder() throws FileNotFoundException {
Pattern pattern = Pattern.compile("^ngram (\\d+)=\\d+$");
LOG.debug("Pattern is {}", pattern);
@SuppressWarnings("resource")
final Scanner scanner = new Scanner(arpaFile);
int order = 0;
// Eat initial header lines
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (NGRAM_HEADER.matches(line)) {
break;
} else {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
LOG.debug("DOES match: '{}'", line);
order = Integer.valueOf(matcher.group(1));
} else {
LOG.debug("Doesn't match: '{}'", line);
}
}
}
return order;
}
/**
* Gets an iterator capable of iterating
* over all n-grams in the ARPA file.
*
* @return an iterator capable of iterating
* over all n-grams in the ARPA file
*/
@SuppressWarnings("resource")
public Iterator<ArpaNgram> iterator() {
try {
final Scanner scanner;
if (arpaFile.getName().endsWith("gz")) {
InputStream in = new GZIPInputStream(
new FileInputStream(arpaFile));
scanner = new Scanner(in);
} else {
scanner = new Scanner(arpaFile);
}
// Eat initial header lines
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
LOG.debug("Discarding line: {}", line);
if (NGRAM_HEADER.matches(line)) {
break;
}
}
return new Iterator<ArpaNgram>() {
String nextLine = null;
int ngramOrder = 1;
// int id = 0;
public boolean hasNext() {
if (scanner.hasNext()) {
String line = scanner.nextLine();
boolean lineIsHeader = NGRAM_HEADER.matches(line) || NGRAM_END.matches(line);
while (lineIsHeader || BLANK_LINE.matches(line)) {
if (lineIsHeader) {
ngramOrder++;
}
if (scanner.hasNext()) {
line = scanner.nextLine().trim();
lineIsHeader = NGRAM_HEADER.matches(line) || NGRAM_END.matches(line);
} else {
nextLine = null;
return false;
}
}
nextLine = line;
return true;
} else {
nextLine = null;
return false;
}
}
public ArpaNgram next() {
if (nextLine!=null) {
String[] parts = Regex.spaces.split(nextLine);
float value = Float.valueOf(parts[0]);
int word = Vocabulary.id(parts[ngramOrder]);
int[] context = new int[ngramOrder-1];
for (int i=1; i<ngramOrder; i++) {
context[i-1] = Vocabulary.id(parts[i]);
}
float backoff;
if (parts.length > ngramOrder+1) {
backoff = Float.valueOf(parts[parts.length-1]);
} else {
backoff = ArpaNgram.DEFAULT_BACKOFF;
}
nextLine = null;
return new ArpaNgram(word, context, value, backoff);
} else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} catch (IOException e) {
LOG.error(e.getMessage(), e);
return null;
}
}
} | 27.469512 | 103 | 0.573807 |
cbd5e5d82ff14bd75ee027df7e58220387f3de60 | 1,682 | package com.honolulu;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.kafka.common.serialization.DoubleDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
public class Consumer {
private static final Logger log = LoggerFactory.getLogger(Consumer.class);
public static void main(String[] args) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "broker-1:9092,broker-2:9093");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, DoubleDeserializer.class.getName());
props.put(ConsumerConfig.GROUP_ID_CONFIG, args[0] + ".consumer");
KafkaConsumer<String, Double> consumer = new KafkaConsumer<>(props);
Thread haltedHook = new Thread(consumer::close);
Runtime.getRuntime().addShutdownHook(haltedHook);
consumer.subscribe(Collections.singletonList(args[0]));
while (true) {
ConsumerRecords<String, Double> records = consumer.poll(Duration.ofMillis(100));
records.forEach(record -> processRecord(record.value()));
}
}
private static void processRecord(Double hurricane) {
log.info("New alert received of intensity: " + hurricane);
}
} | 38.227273 | 102 | 0.741974 |
69f01e446ce9a49a294f09a67a5b043531d81dab | 2,939 | package com.example.jiaqi11_feelbook;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
public class edit extends AppCompatActivity {
//read in file and initialize
public static final String FILE_NAME="example.txt";
Button btnloading;
Button btnedit_edit;
Button edit_2;
TextView Text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
btnloading = (Button) findViewById(R.id.button);
btnedit_edit = (Button) findViewById(R.id.edit_edit);
edit_2 = (Button) findViewById(R.id.edit_2);
//click event handle
Text=findViewById(R.id.editText);
btnedit_edit.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
openedelete();
}
});
edit_2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
openeupdate();
}
});
}
//loading file
public void load(View v){
FileInputStream fis=null;
try {
fis=openFileInput(FILE_NAME);
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
StringBuilder sb= new StringBuilder();
String text;
ArrayList<String> list = new ArrayList<String>();
while((text=br.readLine())!=null) {
sb.append(text);
sb.append("\n");
}
Text.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}//handle all the catch which generate automaticlly
}
}
//function to other activities
public void openedelete(){
Intent intent=new Intent(this, delete.class);
startActivity(intent);
}
public void openeupdate(){
Intent intent=new Intent(this, update.class);
startActivity(intent);
}
}
| 30.614583 | 67 | 0.591017 |
21239aa4c50c458e53b10258903dd7a713301f3a | 901 | package com.github.alex1304.rdi.config;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.List;
class StaticFactoryMethod extends AbstractFactoryMethod {
StaticFactoryMethod(Class<?> owner, String methodName, Class<?> returnType, List<Injectable> params) {
super(owner, methodName, returnType, params);
}
@Override
MethodHandle findMethodHandle(Class<?> owner, String methodName, Class<?> returnType,
List<Class<?>> paramTypes) throws ReflectiveOperationException {
return MethodHandles.publicLookup().findStatic(owner, methodName, MethodType.methodType(returnType,
paramTypes));
}
@Override
String userFriendlyRepresentation(Class<?> owner, String methodName) {
return owner.getName() + "." + methodName;
}
}
| 34.653846 | 107 | 0.703663 |
026491460472d5ae671d65543781f1fa5da8b6b6 | 555 | package fr.nicoPaul.miniHearstone.jeux.carte.paladin;
import fr.nicoPaul.miniHearstone.jeux.Plateau;
import fr.nicoPaul.miniHearstone.jeux.carte.ASort;
/**
* Consécration
*
* @author nicolas paul
* @version 1
* @since 1
*/
public class Consecration extends ASort {
public Consecration() {
super("Consécration", 4, "2 points de degats à tous les adversaires.");
}
@Override
public void use(Plateau plateau) {
plateau.getCartesOfHero(plateau.getHeroCible()).forEach(aServiteur -> aServiteur.takeDamage(2));
}
}
| 23.125 | 104 | 0.704505 |
570c8601399b12f34958bab8377b90419c68a528 | 818 | package com.schematical.chaoscraft.entities;
import com.schematical.chaoscraft.events.CCWorldEvent;
import com.schematical.chaoscraft.fitness.EntityFitnessRule;
import com.schematical.chaosnet.model.ChaosNetException;
/**
* Created by user1a on 1/4/19.
*/
public class EntityFitnessScoreEvent {
public CCWorldEvent worldEvent;
public int score;
public int life;
public EntityFitnessRule fitnessRule;
public EntityFitnessScoreEvent(CCWorldEvent event, int _score, EntityFitnessRule _fitnessRule) {
worldEvent = event;
score = _score;
fitnessRule = _fitnessRule;
if(fitnessRule == null){
throw new ChaosNetException("Missing `fitnessRule`");
}
}
public String toString(){
return worldEvent.toString() + " - " + score;
}
}
| 28.206897 | 100 | 0.705379 |
7112efe5b83d8d09d4ecdd6fca2022b5b87ac0e6 | 3,740 | package com.example.vijaysingh.quotefuel;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Main extends ActionBarActivity {
TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//font path
String fontpath="Oswald-Light_0.ttf";
//Text View label
TextView ourText=(TextView) findViewById(R.id.textView);
//Loading Font Face
Typeface tf=Typeface.createFromAsset(getAssets(),fontpath);
//Applying font
ourText.setTypeface(tf);
StrictMode.enableDefaults();
resultView=(TextView) findViewById(R.id.textView);
Button insert=(Button) findViewById(R.id.button);
insert.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
getData();
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getData() {
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://transcendyourlife.tk");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Couldn't connect to database");
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
resultView.setText(result);
}
catch(Exception e) {
Log.e("log_tag", "Couldn't set text, damnit.");
}
}
}
| 28.549618 | 98 | 0.603209 |
42628164507da5bbea5cf7e085202c56bf4553ca | 1,023 | package com.sixtyfour.templating;
import java.io.File;
/**
* @author EgonOlsen
*
*/
public class TemplateInfo {
private String path;
private String basicCode;
private long modified;
public TemplateInfo(String path) {
this.path = path;
File file = new File(path);
modified = file.lastModified();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getBasicCode() {
return basicCode;
}
public void setBasicCode(String basicCode) {
this.basicCode = basicCode;
}
public boolean hasChanged() {
File file = new File(path);
long modi = file.lastModified();
if (modi != modified) {
modified = modi;
return true;
}
return false;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o instanceof TemplateInfo) {
TemplateInfo ti = (TemplateInfo) o;
return path.equals(ti.path);
}
return false;
}
@Override
public int hashCode() {
return path.hashCode();
}
}
| 16.238095 | 45 | 0.667644 |
acadf5173b3a291dc39bbc3218cbd4df1373e677 | 440 | package com.wupaas.boot.paas.im.thirdservice.weixin.model.result;
import lombok.Data;
/**
* @author by dbinary on 19-6-30.
*/
@Data
public class WeXinBaseResultModel {
/**
* 出错返回码,为0表示成功,非0表示调用失败
*/
private int errcode;
/**
* 返回码提示语
*/
private String errmsg;
public boolean notSuccess() {
return errcode != 0;
}
public boolean isSuccess() {
return errcode == 0;
}
}
| 16.296296 | 65 | 0.595455 |
ee80dca853c385f3bec65e9a3dd8b0f36fd4b544 | 2,805 | /*
* 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.uima.taeconfigurator.editors.ui;
import org.apache.uima.taeconfigurator.editors.Form2Panel;
import org.apache.uima.taeconfigurator.editors.MultiPageEditor;
import org.eclipse.swt.SWT;
import org.eclipse.ui.forms.IManagedForm;
/**
* The Class OverviewPage.
*/
public class OverviewPage extends HeaderPageWithSash {
/** The primitive section. */
private PrimitiveSection primitiveSection;
/** The metadata section. */
// should always exist
private MetaDataSection metadataSection;
/**
* Instantiates a new overview page.
*
* @param aEditor the a editor
*/
public OverviewPage(MultiPageEditor aEditor) {
super(aEditor, "UID_OverviewPage", "Overview");
}
/**
* Called by the 3.0 framework to fill in the contents
*
* @param managedForm the managed form
*/
@Override
protected void createFormContent(IManagedForm managedForm) {
final Form2Panel form = setup2ColumnLayout(managedForm, EQUAL_WIDTH);
managedForm.getForm().setText("Overview");
if (isLocalProcessingDescriptor()) {
managedForm.addPart(new GeneralSection(editor, form.left));
managedForm.addPart(primitiveSection = new PrimitiveSection(editor, form.left));
managedForm.addPart(metadataSection= new MetaDataSection(editor, form.right));
} else {
managedForm.addPart(metadataSection = new MetaDataSection(editor, form.left));
}
createToolBarActions(managedForm);
sashForm.setOrientation(SWT.HORIZONTAL);
vaction.setChecked(false);
haction.setChecked(true);
if (!isLocalProcessingDescriptor()) {
sashForm.setWeights(new int[] { 95, 5 });
}
}
/**
* Gets the primitive section.
*
* @return the primitive section
*/
public PrimitiveSection getPrimitiveSection() {
return primitiveSection;
}
/**
* Gets the meta data section.
*
* @return the meta data section
*/
public MetaDataSection getMetaDataSection() {
return metadataSection;
}
}
| 29.840426 | 86 | 0.721925 |
914863a2f861ed3cf9cfeaffca67476e72abbe52 | 496 | package org.greencheek.web.filter.memcached.domain;
import java.util.concurrent.TimeUnit;
public class Duration {
private final long duration;
private final TimeUnit unit;
public Duration(long duration, TimeUnit unit) {
this.duration = duration;
this.unit = unit;
}
public long toMillis() {
return TimeUnit.MILLISECONDS.convert(duration, unit);
}
public long toSeconds() {
return TimeUnit.SECONDS.convert(duration, unit);
}
}
| 21.565217 | 61 | 0.675403 |
877139d0e14018abd78d74e6d7c0b1ae8262bbc2 | 2,145 | package com.intuit.payment.http;
import com.intuit.payment.data.Errors;
import org.testng.Assert;
import org.testng.annotations.Test;
/*******************************************************************************
* Copyright (c) 2019 Intuit
*
* 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.
* @author praveenadg
*******************************************************************************/
public class ResponseTest {
private static final int STATUS_CODE = 200;
private static final String INTUIT_TID = "intuit_tid";
private static final String ERROR_INTUIT_TID = "error_intuit_tid";
private static final String CONTENT = "content";
@Test
public void testAllGetters() {
Response response = new Response(STATUS_CODE, CONTENT, INTUIT_TID);
Assert.assertEquals(response.getStatusCode(), STATUS_CODE);
Assert.assertEquals(response.getContent(), CONTENT);
Assert.assertEquals(response.getIntuit_tid(), INTUIT_TID);
}
@Test
public void testAllSetters() {
Response response = new Response(STATUS_CODE, CONTENT, INTUIT_TID);
response.setResponseObject(INTUIT_TID);
Errors errors = new Errors();
errors.setIntuit_tid(ERROR_INTUIT_TID);
response.setErrors(errors);
Assert.assertEquals(response.getResponseObject(), INTUIT_TID);
Assert.assertEquals(response.getErrors().getIntuit_tid(), ERROR_INTUIT_TID);
Assert.assertEquals(response.getStatusCode(), STATUS_CODE);
Assert.assertEquals(response.getContent(), CONTENT);
Assert.assertEquals(response.getIntuit_tid(), INTUIT_TID);
}
}
| 40.471698 | 84 | 0.670862 |
a12a6bb2f17dcc670d6910140aa9e1ce80d0d0f8 | 218 | package com.lambdaschool.orders.repos;
import com.lambdaschool.orders.models.Order;
import org.springframework.data.repository.CrudRepository;
public interface OrderRepository extends CrudRepository<Order, Long>
{
}
| 24.222222 | 68 | 0.83945 |
48be83ad79f1f904a37a61df87ad734fc1858f9b | 229 | package com.atsebak.embeddedlinuxjvm.deploy;
import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
public class DeployedLibrary {
private String jarName;
private String size;
private String lastModified;
}
| 16.357143 | 44 | 0.772926 |
f6f2b29a2b7186e1df0dd8acabe92d49ea0ad828 | 8,398 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.base.metric;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import com.alibaba.csp.sentinel.slots.statistic.data.MetricBucket;
import com.alibaba.csp.sentinel.util.TimeUtil;
import com.alibaba.csp.sentinel.slots.statistic.base.WindowWrap;
import com.alibaba.csp.sentinel.slots.statistic.metric.MetricsLeapArray;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Test cases for {@link MetricsLeapArray}.
*
* @author Eric Zhao
*/
public class MetricsLeapArrayTest {
private final int windowLengthInMs = 1000;
private final int intervalInSec = 2;
private final int intervalInMs = intervalInSec * 1000;
private final int sampleCount = intervalInMs / windowLengthInMs;
@Test
public void testNewWindow() {
MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
long time = TimeUtil.currentTimeMillis();
WindowWrap<MetricBucket> window = leapArray.currentWindow(time);
assertEquals(window.windowLength(), windowLengthInMs);
assertEquals(window.windowStart(), time - time % windowLengthInMs);
assertNotNull(window.value());
assertEquals(0L, window.value().pass());
}
@Test
public void testLeapArrayWindowStart() {
MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
long firstTime = TimeUtil.currentTimeMillis();
long previousWindowStart = firstTime - firstTime % windowLengthInMs;
WindowWrap<MetricBucket> window = leapArray.currentWindow(firstTime);
assertEquals(windowLengthInMs, window.windowLength());
assertEquals(previousWindowStart, window.windowStart());
}
@Test
public void testWindowAfterOneInterval() {
MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
long firstTime = TimeUtil.currentTimeMillis();
long previousWindowStart = firstTime - firstTime % windowLengthInMs;
WindowWrap<MetricBucket> window = leapArray.currentWindow(previousWindowStart);
assertEquals(windowLengthInMs, window.windowLength());
assertEquals(previousWindowStart, window.windowStart());
MetricBucket currentWindow = window.value();
assertNotNull(currentWindow);
currentWindow.addPass(1);
currentWindow.addBlock(1);
assertEquals(1L, currentWindow.pass());
assertEquals(1L, currentWindow.block());
long middleTime = previousWindowStart + windowLengthInMs / 2;
window = leapArray.currentWindow(middleTime);
assertEquals(previousWindowStart, window.windowStart());
MetricBucket middleWindow = window.value();
middleWindow.addPass(1);
assertSame(currentWindow, middleWindow);
assertEquals(2L, middleWindow.pass());
assertEquals(1L, middleWindow.block());
long nextTime = middleTime + windowLengthInMs / 2;
window = leapArray.currentWindow(nextTime);
assertEquals(windowLengthInMs, window.windowLength());
assertEquals(windowLengthInMs, window.windowStart() - previousWindowStart);
currentWindow = window.value();
assertNotNull(currentWindow);
assertEquals(0L, currentWindow.pass());
assertEquals(0L, currentWindow.block());
}
@Deprecated
public void testWindowDeprecatedRefresh() {
MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
final int len = sampleCount;
long firstTime = TimeUtil.currentTimeMillis();
List<WindowWrap<MetricBucket>> firstIterWindowList = new ArrayList<WindowWrap<MetricBucket>>(len);
for (int i = 0; i < len; i++) {
WindowWrap<MetricBucket> w = leapArray.currentWindow(firstTime + windowLengthInMs * i);
w.value().addPass(1);
firstIterWindowList.add(i, w);
}
for (int i = len; i < len * 2; i++) {
WindowWrap<MetricBucket> w = leapArray.currentWindow(firstTime + windowLengthInMs * i);
assertNotSame(w, firstIterWindowList.get(i - len));
}
}
@Test
public void testMultiThreadUpdateEmptyWindow() throws Exception {
final long time = TimeUtil.currentTimeMillis();
final int nThreads = 16;
final MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
final CountDownLatch latch = new CountDownLatch(nThreads);
Runnable task = new Runnable() {
@Override
public void run() {
leapArray.currentWindow(time).value().addPass(1);
latch.countDown();
}
};
for (int i = 0; i < nThreads; i++) {
new Thread(task).start();
}
latch.await();
assertEquals(nThreads, leapArray.currentWindow(time).value().pass());
}
@Test
public void testGetPreviousWindow() {
MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
long time = TimeUtil.currentTimeMillis();
WindowWrap<MetricBucket> previousWindow = leapArray.currentWindow(time);
assertNull(leapArray.getPreviousWindow(time));
long nextTime = time + windowLengthInMs;
assertSame(previousWindow, leapArray.getPreviousWindow(nextTime));
long longTime = time + 11 * windowLengthInMs;
assertNull(leapArray.getPreviousWindow(longTime));
}
@Test
public void testListWindowsResetOld() throws Exception {
final int windowLengthInMs = 100;
final int intervalInMs = 1000;
final int sampleCount = intervalInMs / windowLengthInMs;
MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
long time = TimeUtil.currentTimeMillis();
Set<WindowWrap<MetricBucket>> windowWraps = new HashSet<WindowWrap<MetricBucket>>();
windowWraps.add(leapArray.currentWindow(time));
windowWraps.add(leapArray.currentWindow(time + windowLengthInMs));
List<WindowWrap<MetricBucket>> list = leapArray.list();
for (WindowWrap<MetricBucket> wrap : list) {
assertTrue(windowWraps.contains(wrap));
}
Thread.sleep(windowLengthInMs + intervalInMs);
// This will replace the deprecated bucket, so all deprecated buckets will be reset.
leapArray.currentWindow(time + windowLengthInMs + intervalInMs).value().addPass(1);
assertEquals(1, leapArray.list().size());
}
@Test
public void testListWindowsNewBucket() throws Exception {
final int windowLengthInMs = 100;
final int intervalInSec = 1;
final int intervalInMs = intervalInSec * 1000;
final int sampleCount = intervalInMs / windowLengthInMs;
MetricsLeapArray leapArray = new MetricsLeapArray(sampleCount, intervalInMs);
long time = TimeUtil.currentTimeMillis();
Set<WindowWrap<MetricBucket>> windowWraps = new HashSet<WindowWrap<MetricBucket>>();
windowWraps.add(leapArray.currentWindow(time));
windowWraps.add(leapArray.currentWindow(time + windowLengthInMs));
Thread.sleep(intervalInMs + windowLengthInMs * 3);
List<WindowWrap<MetricBucket>> list = leapArray.list();
for (WindowWrap<MetricBucket> wrap : list) {
assertTrue(windowWraps.contains(wrap));
}
// This won't hit deprecated bucket, so no deprecated buckets will be reset.
// But deprecated buckets can be filtered when collecting list.
leapArray.currentWindow(TimeUtil.currentTimeMillis()).value().addPass(1);
assertEquals(1, leapArray.list().size());
}
} | 38.347032 | 106 | 0.688497 |
7eb67757d2c7aa607cc23c139dfe2bb48d1fe0f1 | 3,473 | /*
* Copyright 2012-2013 Sergey Ignatov
*
* 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.
*/
/*
* Adapted from ErlangParserTestBase.java. Downloaded 21 Apr 2014 from:
*
* https://github.com/ignatov/intellij-erlang.
*/
package com.haskforce.parser;
import com.haskforce.parsing.jsonParser.JsonParser;
import com.haskforce.utils.ExecUtil;
import com.intellij.lang.ParserDefinition;
import com.intellij.testFramework.ParsingTestCase;
import com.intellij.psi.PsiFile;
import com.intellij.testFramework.TestDataFile;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.io.IOException;
public abstract class HaskellParserTestBase extends ParsingTestCase {
private JsonParser jsonParser;
public HaskellParserTestBase(String dataPath, String fileExt, ParserDefinition... definitions) {
super(dataPath, fileExt, definitions);
}
@Override
protected String getTestDataPath() {
return "tests" + File.separator + "gold";
}
@Override
protected boolean skipSpaces() {
return true;
}
/**
* Perform a test. Add tests that should work but does not work yet with
* doTest(false, false).
*/
protected void doTest(boolean checkResult, boolean shouldPass) {
doTest(true);
if (shouldPass) {
assertFalse(
"PsiFile contains error elements",
toParseTreeText(myFile, skipSpaces(), includeRanges()).contains("PsiErrorElement")
);
}
}
/*
* Ensure that expected outputs live in some other directory than the test
* inputs.
*
* Additionally this function performs the JSON parser test because this
* is a convenient place to hook into the testing.
*
* Expected outputs go <path>/<component>/expected/, putting the parser
* outputs in tests/gold/parser/expected and jsonParser outputs in
* tests/gold/parser/expectedJson.
*/
@Override
protected void checkResult(@NonNls @TestDataFile String targetDataName,
final PsiFile file) throws IOException {
doCheckResult(myFullDataPath, file, checkAllPsiRoots(),
"expected" + File.separator + targetDataName, skipSpaces(),
includeRanges());
/* TODO: Re-enable if we return to parser-helper.
String phPath = ExecUtil.locateExecutableByGuessing("parser-helper");
if (phPath != null && !phPath.isEmpty()) {
String expectedFile = myFullDataPath + File.separator +
"expectedJson" + File.separator + targetDataName + ".txt";
assertSameLinesWithFile(expectedFile,
jsonParser.getJson(file.getText(), phPath));
} else {
assertEquals(true, false); // Always false.
}
*/
}
@Override
protected void setUp() throws Exception {
super.setUp();
jsonParser = new JsonParser(myProject);
}
}
| 33.718447 | 102 | 0.67089 |
23c419ab08602bc2610ee43293e4b331a3494298 | 10,151 | package com.zoeyoung.audiovideoprimer.task2;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import com.jakewharton.rxbinding2.view.RxView;
import com.zoeyoung.audiovideoprimer.R;
import com.zoeyoung.audiovideoprimer.util.AudioVideoPrimerLog;
import com.zoeyoung.audiovideoprimer.util.IOUtil;
import com.zoeyoung.audiovideoprimer.util.ToastUtil;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import io.reactivex.disposables.CompositeDisposable;
public class AudioRecordActivity extends Activity {
private static final String TAG = "AudioRecordActivity";
// 指定音频源
private static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
// 指定采样率 (MediaRecorder 的采样率通常是 8000Hz AAC 的通常是44100Hz。采样率设置为 44100,目前为常用采样率,官方文档表示这个值可以兼容所有的设置)
private static final int SAMPLE_RATE = 44100;
// 指定捕获音频的声道数目。
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_CONFIGURATION_MONO; // 单声道
// 存放的目录路径名称
private static final String PATH_NAME = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "AudioRecordFile";
// 保存的音频文件名
private static final String FILE_NAME = "audiorecordtest.pcm";
// 指定音频量化位数,在 AudioFormat 类中指定了以下各种可能的常量。通常我们选择ENCODING_PCM_16BIT和ENCODING_PCM_8BIT PCM代表的是脉冲编码调制,它实际上是原始音频样本。
// 因此可以设置每个样本的分辨率为16位或者8位,16位将占用更多的空间和处理能力,表示的音频也更加接近真实。
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
// 指定缓冲区大小。调用 AudioRecord 类的 getMinBufferSize 方法可以获得。
private int mBufferSizeInBytes;
private File mRecordingFile; // 存储 AudioRecord 录下来的文件
private volatile boolean isRecording; // 表示正在录音
private AudioRecord mAudioRecord; // 声明 AudioRecord 对象
private File mFileRoot; // 文件目录
private Thread mThread;
private DataOutputStream mDataOutputStream;
private Button mStartRecordBtn;
private Button mStopRecordBtn;
private Button mStartPlayBtn;
private Button mStopPlayBtn;
private Button mPlayWAVBtn;
private Button mPcm2WAVBtn;
private Button mPlayAACBtn;
private Button mPcm2AACBtn;
private TextView mEncodeProcessTv;
private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_record);
initData();
initView();
initEvent();
}
@Override
protected void onPause() {
super.onPause();
AudioVideoPrimerLog.i(TAG, "onPause, composite clear");
}
@Override
protected void onDestroy() {
super.onDestroy();
mCompositeDisposable.clear();
}
private void initData() {
// 初始化数据
mBufferSizeInBytes = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
// 创建 AudioRecorder 对象
mAudioRecord = new AudioRecord(AUDIO_SOURCE, SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, mBufferSizeInBytes);
// 创建文件夹
mFileRoot = new File(PATH_NAME);
if (!mFileRoot.exists()) {
mFileRoot.mkdirs();
}
}
private void initView() {
mStartRecordBtn = findViewById(R.id.bt_start_record);
mStopRecordBtn = findViewById(R.id.bt_stop_record);
mStartPlayBtn = findViewById(R.id.bt_play_record);
mStopPlayBtn = findViewById(R.id.bt_stop_play_record);
mPcm2WAVBtn = findViewById(R.id.bt_pcm2wav);
mPlayWAVBtn = findViewById(R.id.bt_play_wav);
mPcm2AACBtn = findViewById(R.id.bt_pcm2aac);
mPlayAACBtn = findViewById(R.id.bt_play_aac);
mEncodeProcessTv = findViewById(R.id.tv_encode_process);
}
private void initEvent() {
mCompositeDisposable.add(RxView.clicks(mStartRecordBtn)
.doOnEach(o -> AudioVideoPrimerLog.i(TAG, "start record " + o))
.subscribe(v -> {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) !=
PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
AudioVideoPrimerLog.e(TAG, "check permission fails");
ActivityCompat.requestPermissions(AudioRecordActivity.this,
new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
} else {
startRecord();
}
}));
mCompositeDisposable.add(RxView.clicks(mStopRecordBtn)
.doOnEach(o -> AudioVideoPrimerLog.i(TAG, "stop record " + o))
.subscribe(v -> stopRecord()));
mCompositeDisposable.add(RxView.clicks(mStartPlayBtn)
.subscribe(v -> startPlay()));
// mCompositeDisposable.add(RxView.clicks(mStopPlayBtn).subscribe(v -> stopPlay()));
// mCompositeDisposable.add(RxView.clicks(mPcm2WAVBtn).subscribe(v -> pcm2wav()));
// mCompositeDisposable.add(RxView.clicks(mPlayWAVBtn).subscribe(v -> playWav()));
// mCompositeDisposable.add(RxView.clicks(mPcm2AACBtn).subscribe(v -> pcm2aac()));
// mCompositeDisposable.add(RxView.clicks(mPlayAACBtn).subscribe(v -> playAAC()));
}
/**
* 开始录音
*/
private void startRecord() {
if (AudioRecord.ERROR_BAD_VALUE == mBufferSizeInBytes || AudioRecord.ERROR == mBufferSizeInBytes) {
throw new RuntimeException("Unable to getMinBufferSize");
} else {
destroyThread();
isRecording = true;
if (mThread == null) {
mThread = new Thread(recordTask);
mThread.start();
}
}
}
/**
* 停止录音
*/
private void stopRecord() {
isRecording = false;
// 停止录音,回收 AudioRecord 对象,释放内存
if (mAudioRecord != null) {
// 初始化成功
if (mAudioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
mAudioRecord.stop();
}
mAudioRecord.release();
mAudioRecord = null;
}
}
/**
* 开始播放录音
*/
private void startPlay() {
String path = mFileRoot + File.separator + FILE_NAME;
AudioTrackManager.getInstance().startPlay(path);
}
/**
* 销毁线程方法
*/
private void destroyThread() {
try {
isRecording = false;
if (null != mThread && Thread.State.RUNNABLE == mThread.getState()) {
try {
Thread.sleep(500);
mThread.interrupt();
} catch (Exception e) {
mThread = null;
}
}
mThread = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
mThread = null;
}
}
private Runnable recordTask = () -> {
isRecording = true;
createFile();
// 判断 AudioRecord 未初始化,停止录音的时候释放了,状态就为 STATE_UNINITIALIZED
if (mAudioRecord.getState() == mAudioRecord.STATE_UNINITIALIZED) {
initData();
}
// 最小缓冲区
byte[] buffer = new byte[mBufferSizeInBytes];
// 获取到文件的数据流
try {
mDataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(mRecordingFile)));
// 开始录音
mAudioRecord.startRecording();
AudioVideoPrimerLog.i(TAG, "start recording " + mAudioRecord.getRecordingState());
// getRecordingState 获取当前 AudioRecording 是否正在采集数据的状态
while (isRecording && mAudioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
int bufferReadResult = mAudioRecord.read(buffer, 0, mBufferSizeInBytes);
mDataOutputStream.write(buffer, 0, bufferReadResult);
}
} catch (FileNotFoundException e) {
AudioVideoPrimerLog.e(TAG, "record task " + e);
e.printStackTrace();
} catch (IOException e) {
AudioVideoPrimerLog.e(TAG, "record task " + e);
e.printStackTrace();
} finally {
// stopRecord();
IOUtil.close(mDataOutputStream);
}
};
private void createFile() {
//创建一个流,存放从AudioRecord读取的数据
mRecordingFile = new File(mFileRoot, FILE_NAME);
AudioVideoPrimerLog.i(TAG, "create file " + mRecordingFile);
if (mRecordingFile.exists()) {//音频文件保存过了删除
mRecordingFile.delete();
}
try {
mRecordingFile.createNewFile();//创建新文件
} catch (IOException e) {
e.printStackTrace();
AudioVideoPrimerLog.e(TAG, "create file fail " + e);
}
}
private static final int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_RECORD_AUDIO) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startRecord();
} else {
ToastUtil.show("未授权");
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
| 36.383513 | 141 | 0.639149 |
09d501060b5c8dce672adcbfde42c5cc2c3d5ded | 4,961 | /*
* Copyright 2008-2009 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 net.entropysoft.transmorph.signature.formatter;
import java.util.ArrayList;
import java.util.List;
import net.entropysoft.transmorph.signature.ArrayTypeSignature;
import net.entropysoft.transmorph.signature.ClassTypeSignature;
import net.entropysoft.transmorph.signature.PrimitiveTypeSignature;
import net.entropysoft.transmorph.signature.TypeArgSignature;
import net.entropysoft.transmorph.signature.TypeSignature;
import net.entropysoft.transmorph.signature.TypeVarSignature;
/**
* Format a type signature using internal java type descriptor format
*
* @author Cedric Chabanois (cchabanois at gmail.com)
*
*/
public class ClassFileTypeSignatureFormatter implements ITypeSignatureFormatter {
private char packageSeparator = '/';
private char innerClassPrefix = '.';
public ClassFileTypeSignatureFormatter() {
}
public ClassFileTypeSignatureFormatter(
boolean useInternalFormFullyQualifiedName) {
setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName);
}
/**
* By default we use the Internal Form of Fully Qualified Name where
* identifiers are separated by '/' but you can use the familiar form where
* '.' separates the identifiers
*
* @param packageSeparator
*/
public void setUseInternalFormFullyQualifiedName(boolean value) {
if (value) {
packageSeparator = '/';
innerClassPrefix = '.';
} else {
packageSeparator = '.';
innerClassPrefix = '$';
}
}
public String format(TypeSignature typeSignature) {
if (typeSignature.isPrimitiveType()) {
return formatPrimitiveTypeSignature((PrimitiveTypeSignature) typeSignature);
}
if (typeSignature.isArrayType()) {
return formatArrayTypeSignature((ArrayTypeSignature) typeSignature);
}
if (typeSignature.isClassType()) {
return formatClassTypeSignature((ClassTypeSignature) typeSignature);
}
if (typeSignature.isTypeVar()) {
return formatTypeVarSignature((TypeVarSignature) typeSignature);
}
if (typeSignature.isTypeArgument()) {
return formatTypeArgSignature((TypeArgSignature) typeSignature);
}
return null;
}
private String formatArrayTypeSignature(ArrayTypeSignature typeSignature) {
return '[' + format(typeSignature.getComponentTypeSignature());
}
private String formatPrimitiveTypeSignature(
PrimitiveTypeSignature primitiveTypeSignature) {
return new String(new char[] { primitiveTypeSignature
.getPrimitiveTypeChar() });
}
private ClassTypeSignature[] getClassTypeSignatures(
ClassTypeSignature classTypeSignature) {
List<ClassTypeSignature> list = new ArrayList<ClassTypeSignature>();
while (classTypeSignature != null) {
list.add(0, classTypeSignature);
classTypeSignature = classTypeSignature.getOwnerTypeSignature();
}
return list.toArray(new ClassTypeSignature[list.size()]);
}
private String formatClassTypeSignature(ClassTypeSignature typeSignature) {
ClassTypeSignature[] classTypeSignatures = getClassTypeSignatures(typeSignature);
StringBuilder sb = new StringBuilder();
sb.append('L');
for (int i = 0; i < classTypeSignatures.length; i++) {
ClassTypeSignature classTypeSignature = classTypeSignatures[i];
if (i == 0) {
sb.append(classTypeSignature.getBinaryName().replace('.',
packageSeparator));
} else {
sb.append(innerClassPrefix);
sb.append(classTypeSignature.getBinaryName());
}
if (classTypeSignature.getTypeArgSignatures().length > 0) {
sb.append('<');
for (TypeArgSignature typeArgSignature : classTypeSignature
.getTypeArgSignatures()) {
sb.append(formatTypeArgSignature(typeArgSignature));
}
sb.append('>');
}
}
sb.append(';');
return sb.toString();
}
public String formatTypeVarSignature(TypeVarSignature typeSignature) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('T');
stringBuilder.append(typeSignature.getId());
stringBuilder.append(';');
return stringBuilder.toString();
}
public String formatTypeArgSignature(TypeArgSignature typeArgSignature) {
StringBuilder sb = new StringBuilder();
char wildcard = typeArgSignature.getWildcard();
if (wildcard != TypeArgSignature.NO_WILDCARD) {
sb.append(wildcard);
}
if (typeArgSignature.getFieldTypeSignature() != null) {
sb.append(format(typeArgSignature.getFieldTypeSignature()));
}
return sb.toString();
}
}
| 32.424837 | 83 | 0.757307 |
9be45a9256086c7177bbc731eb58a002782f8e93 | 19,374 | //package com.fbd.admin.common.quartz.action;
//
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.HashMap;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//import javax.annotation.Resource;
//import javax.servlet.ServletException;
//import org.apache.commons.lang3.time.DateUtils;
//import org.quartz.CronTrigger;
//import org.quartz.JobDetail;
//import org.quartz.JobExecutionContext;
//import org.quartz.JobListener;
//import org.quartz.Scheduler;
//import org.quartz.SchedulerException;
//import org.quartz.Trigger;
//import org.quartz.impl.StdScheduler;
//import org.quartz.impl.StdSchedulerFactory;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.context.annotation.Scope;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.ResponseBody;
//import com.fbd.core.common.quartz.helper.TriggerHelper;
//import com.fbd.core.common.quartz.model.ChooseSchedulerForm;
//import com.fbd.core.common.quartz.model.JobDetailForm;
//import com.fbd.core.common.quartz.model.ListenerDTO;
//import com.fbd.core.common.quartz.model.SchedulerDTO;
//import com.fbd.core.common.quartz.model.TriggerForm;
//import com.fbd.core.common.quartz.util.FormatUtil;
//
//@Controller
//@Scope("prototype")
//@RequestMapping("/quartz/job")
//@SuppressWarnings("all")
//public class JobAction {
//
// private static final Logger logger = LoggerFactory.getLogger(JobAction.class);
//
//// @Resource
//// private StdScheduler scheduler;
//
// /**
// * Description: 获取Job列表
// *
// * @param
// * @return List<JobDetail>
// * @throws
// * @Author dongzhongwei Create Date: 2014-12-25 下午2:44:14
// */
// @RequestMapping(value = "/getlist.html", method = RequestMethod.POST)
// public @ResponseBody
// List<JobDetail> getJobsList() {
// List<JobDetail> jobList = null;
// try {
// String[] jobGroups = scheduler.getJobGroupNames();
// List<String> addedJobs = new ArrayList<String>(jobGroups.length);
// jobList = new ArrayList<JobDetail>();
// for (String groupName : jobGroups) {
// String[] jobs = scheduler.getJobNames(groupName);
// for (String job : jobs) {
// JobDetail jobDetail = scheduler
// .getJobDetail(job, groupName);
// String key = job + groupName;
// jobList.add(jobDetail);
// addedJobs.add(key);
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// }
// return jobList;
// }
//
// /**
// * Description: 根据组和名称获取job
// *
// * @param
// * @return Map<String,Object>
// * @throws
// * @Author dongzhongwei Create Date: 2014-12-25 下午2:44:37
// */
// @RequestMapping(value = "/saveJob.html", method = RequestMethod.POST)
// public @ResponseBody Map<String, Object> saveJob(String group,String name, String jobClass,
// Boolean requestsRecovery, Boolean durable,String description,
// String parameterNames[], String parameterValues[]) {
// Map<String, Object> resultMap = new HashMap<String, Object>();
//
// try {
// JobDetail jobDetail = new JobDetail();
// jobDetail.setJobClass(Class.forName(jobClass));
// jobDetail.setGroup(group);
// jobDetail.setName(name);
// jobDetail.setRequestsRecovery(requestsRecovery);
// jobDetail.setDurability(durable);
// jobDetail.setDescription(description);
// if (parameterNames!=null) {
// for (int i = 0; i < parameterNames.length; i++) {
// if (parameterNames[i].trim().length() > 0
// && parameterValues[i].trim().length() > 0) {
// jobDetail.getJobDataMap().put(parameterNames[i].trim(),
// parameterValues[i].trim());
// }
// }
// }
// boolean replace = true;
// scheduler.addJob(jobDetail, replace);
// resultMap.put("success", true);
// }catch (ClassNotFoundException e) {
// resultMap.put("success", false);
// resultMap.put("msg", jobClass+" 类不存在。");
// } catch (SchedulerException e) {
// resultMap.put("success", false);
// resultMap.put("msg", e.getMessage());
// }
// return resultMap;
// }
//
// /**
// * Description: 根据组和名称获取job
// *
// * @param
// * @return Map<String,Object>
// * @throws
// * @Author dongzhongwei Create Date: 2014-12-25 下午2:44:37
// */
// @RequestMapping(value = "/getJob.html", method = RequestMethod.GET)
// public @ResponseBody
// Map<String, Object> getJobByNameAndGroup(String jobName, String jobGroup) {
// JobDetail jobDetail = new JobDetail();
// try {
// jobDetail = scheduler.getJobDetail(jobName, jobGroup);
// } catch (Exception e) {
// }
// Map<String, Object> resultMap = new HashMap<String, Object>();
// resultMap.put("jobDetail", jobDetail);
// resultMap.put("jobDataMapKeys", jobDetail.getJobDataMap().getKeys());
//
// return resultMap;
// }
//
// /**
// * Description: 立即执行
// *
// * @param
// * @return Map<String,Object>
// * @throws
// * @Author dongzhongwei Create Date: 2014-12-25 下午2:44:37
// */
// @RequestMapping(value = "/runNow.html", method = RequestMethod.GET)
// public @ResponseBody
// Map<String, Object> runNow(String jobName, String jobGroup) {
// Map<String, Object> resultMap = new HashMap<String, Object>();
// try {
// scheduler.triggerJob(jobName, jobGroup);
// resultMap.put("success", true);
// } catch (Exception e) {
// resultMap.put("success", false);
// }
// return resultMap;
// }
//
// /**
// * Description: 删除触发器
// *
// * @param
// * @return Map<String,Object>
// * @throws
// * @Author dongzhongwei Create Date: 2014-12-25 下午2:45:44
// */
// @RequestMapping(value = "/unSchedule.html", method = RequestMethod.POST)
// public @ResponseBody
// Map<String, Object> unSchedule(String triggerName, String triggerGroup) {
// Map<String, Object> resultMap = new HashMap<String, Object>();
// try {
// scheduler.unscheduleJob(triggerName, triggerGroup);
// resultMap.put("success", true);
// } catch (Exception e) {
// resultMap.put("success", false);
// }
// return resultMap;
// }
//
// /**
// * Description: 删除job
// *
// * @param
// * @return Map<String,Object>
// * @throws
// * @Author dongzhongwei Create Date: 2014-12-25 下午5:14:22
// */
// @RequestMapping(value = "/removeJob.html", method = RequestMethod.GET)
// public @ResponseBody Map<String, Object> removeJob(String jobName, String jobGroup) {
// Map<String, Object> resultMap = new HashMap<String, Object>();
// try {
// scheduler.deleteJob(jobName, jobGroup);
// resultMap.put("success", true);
// } catch (Exception e) {
// resultMap.put("success", false);
// }
// return resultMap;
// }
//
// /**
// * Description: 添加Cron表达式
// *
// * @param
// * @return Map<String,Object>
// * @throws
// * @Author dongzhongwei
// * Create Date: 2015-3-14 上午12:00:05
// */
// @RequestMapping(value = "/createCronTrigger.html", method = RequestMethod.POST)
// public @ResponseBody
// Map<String, Object> createCronTrigger(String triggerGroup, String triggerName,
// String description, String startTime, String stopTime,
// String cronExpression, String jobName, String jobGroup) {
// Map<String, Object> resultMap = new HashMap<String, Object>();
//
// boolean startTimeHasValue = ((startTime != null) && (startTime.length() > 0));
// boolean stopTimeHasValue = ((stopTime != null) && (stopTime.length() > 0));
// CronTrigger trigger = null;
// try {
// if (cronExpression.length() > 2) {
// trigger = new CronTrigger(triggerName, triggerGroup, jobName,
// jobGroup, cronExpression);
// }
// trigger.setDescription(description);
// String[] pattern = new String[] { "yyyy-MM", "yyyyMM", "yyyy/MM",
// "yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMddHHmmss",
// "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss" };
// if (startTimeHasValue) {
// trigger.setStartTime(DateUtils.parseDate(startTime, pattern));
// }
// if (stopTimeHasValue) {
// trigger.setEndTime(DateUtils.parseDate(stopTime, pattern));
// }
// trigger.setVolatility(false);
// scheduler.scheduleJob(trigger);
// resultMap.put("success", true);
// } catch (SchedulerException e) {
// logger.error("SchedulerException, Could not schedule the trigger " + trigger + " " + e.getLocalizedMessage());
// resultMap.put("success", false);
// resultMap.put("msg", "SchedulerException, Could not schedule the trigger " + trigger + " " + e.getLocalizedMessage());
// } catch (UnsupportedOperationException ue) {
// logger.error("UnsupportedOperation in CronSchedule:" + ue);
// logger.error("Could not schedule the trigger " + trigger + " "+ ue.getLocalizedMessage());
// resultMap.put("success", false);
// resultMap.put("msg", "Could not schedule the trigger " + trigger + " "+ ue.getLocalizedMessage());
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return resultMap;
// }
//
//
// /**
// * Description: 查看Job
// *
// * @param
// * @return Map<String,Object>
// * @throws
// * @Author dongzhongwei Create Date: 2014-12-25 下午2:44:52
// */
// @RequestMapping(value = "/viewJob.html", method = RequestMethod.POST)
// public @ResponseBody
// Map<String, Object> view(String jobName, String jobGroup) throws Exception {
// JobDetail jobDetail = new JobDetail();
// JobDetailForm form = new JobDetailForm();
//
// List<TriggerForm> jobTriggers = new ArrayList<TriggerForm>();
// try {
//
// if (jobDetail.getName() == null) {
// jobDetail = scheduler.getJobDetail(jobName, jobGroup);
// } else {
// jobDetail = scheduler.getJobDetail(jobDetail.getName(),
// jobDetail.getGroup());
// }
// } catch (SchedulerException e) {
// throw new Exception("When reading the jobs", e);
// }
// populateForm(jobDetail, form, scheduler, jobTriggers);
//
// Map<String, Object> resultMap = new HashMap<String, Object>();
// resultMap.put("jobDetail", jobDetail);
// resultMap.put("jobTriggers", jobTriggers);
// resultMap.put("jobDataMapKeys", jobDetail.getJobDataMap().getKeys());
//
// return resultMap;
// }
//
// private void populateForm(JobDetail jobDetail, JobDetailForm form,
// Scheduler scheduler, List<TriggerForm> jobTriggers)
// throws ServletException {
//
// Trigger[] triggers = TriggerHelper.getTriggersFromJob(scheduler,
// jobDetail.getName(), jobDetail.getGroup());
//
// for (Trigger trigger : triggers) {
// TriggerForm tForm = new TriggerForm();
//
// tForm.setDescription(trigger.getDescription());
// tForm.setJobGroup(trigger.getJobGroup());
// tForm.setJobName(trigger.getJobName());
// tForm.setMisFireInstruction(trigger.getMisfireInstruction());
// tForm.setStartTime(FormatUtil.getDateAsString(trigger
// .getStartTime()));
// tForm.setStopTime(FormatUtil.getDateAsString(trigger.getEndTime()));
// tForm.setTriggerGroup(trigger.getGroup());
// tForm.setTriggerName(trigger.getName());
// tForm.setNextFireTime(FormatUtil.getDateAsString(trigger
// .getNextFireTime()));
// tForm.setPreviousFireTime(FormatUtil.getDateAsString(trigger
// .getPreviousFireTime()));
// tForm.setType(TriggerHelper.getTriggerType(trigger));
// if ("cron".equals(tForm.getType())) {
// CronTrigger cronTrigger = (CronTrigger) trigger;
// System.out.println(cronTrigger.getCronExpression());
// }
// jobTriggers.add(tForm);
// }
//
// try {
// String[] jobListenerNames = jobDetail.getJobListenerNames();
// for (Iterator iter = scheduler.getJobListenerNames().iterator(); iter
// .hasNext();) {
// String name = (String) iter.next();
// JobListener jobListener = scheduler.getJobListener(name);
// for (String element : jobListenerNames) {
// if (jobListener.getName().equals(element)) {
// ListenerDTO listenerForm = new ListenerDTO();
// listenerForm.setName(jobListener.getName());
// listenerForm.setListenerClass(jobListener.getClass()
// .getName());
// form.getJobListeners().add(listenerForm);
// }
// }
// }
// } catch (SchedulerException e) {
// }
// }
//
//
// @RequestMapping(value = "/schedule.html", method = RequestMethod.POST)
// public @ResponseBody
// ChooseSchedulerForm ScheduleControler(String command) {
// ChooseSchedulerForm scheduleInfo=new ChooseSchedulerForm();
// try {
// if (command.equals("start")) {
// if (scheduler.isShutdown()) {
// //choosenScheduler = createSchedulerAndUpdateApplicationContext(schedulerName);
// }
// scheduler.start();
// } else if (command.equals("stop")) {
// scheduler.shutdown();
// //choosenScheduler = StdSchedulerFactory.getDefaultScheduler();
// } else if (command.equals("pause")) {
// scheduler.standby();
// } else if (command.equals("waitAndStopScheduler")) {
// scheduler.shutdown(true);
// } else if (command.equals("pauseAll")) {
// scheduler.pauseAll();
// } else if (command.equals("resumeAll")) {
// scheduler.resumeAll();
// }
//
// this.populateSchedulerForm(scheduler, scheduleInfo);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// return scheduleInfo;
// }
//
//
// private void populateSchedulerForm(Scheduler choosenScheduler, ChooseSchedulerForm form)
// throws Exception
// {
//
// Collection scheduleCollection = new StdSchedulerFactory().getAllSchedulers();
// Iterator itr = scheduleCollection.iterator();
//
// form.setSchedulers(new ArrayList<Scheduler>());
// try {
// form.setChoosenSchedulerName(choosenScheduler.getSchedulerName());
//
// while (itr.hasNext()) {
// Scheduler scheduler = (Scheduler) itr.next();
// form.getSchedulers().add(scheduler.getSchedulerName());
// }
//
// } catch (SchedulerException e) {
// throw new Exception(e);
// }
//
//
// SchedulerDTO schedForm = new SchedulerDTO();
// schedForm.setSchedulerName(choosenScheduler.getSchedulerName());
// schedForm.setNumJobsExecuted(String.valueOf(choosenScheduler.getMetaData().getNumberOfJobsExecuted()));
//
// if (choosenScheduler.getMetaData().jobStoreSupportsPersistence()) {
// schedForm.setPersistenceType("database");
// } else {
// schedForm.setPersistenceType("memory"); // mp possible bugfix
// }
// schedForm.setRunningSince(String.valueOf(choosenScheduler.getMetaData().getRunningSince()));
// if (choosenScheduler.isShutdown()) {
// schedForm.setState("stopped");
// } else if (choosenScheduler.isInStandbyMode()) {
// schedForm.setState("paused");
// } else {
// schedForm.setState("started");
// }
//
// schedForm.setThreadPoolSize(String.valueOf(choosenScheduler.getMetaData().getThreadPoolSize()));
// schedForm.setVersion(choosenScheduler.getMetaData().getVersion());
// schedForm.setSummary(choosenScheduler.getMetaData().getSummary());
//
// List jobDetails = choosenScheduler.getCurrentlyExecutingJobs();
// for (Iterator iter = jobDetails.iterator(); iter.hasNext();) {
// JobExecutionContext job = (JobExecutionContext) iter.next();
// JobDetail jobDetail = job.getJobDetail();
//
// JobDetailForm jobForm = new JobDetailForm();
// jobForm.setGroupName(jobDetail.getGroup());
// jobForm.setName(jobDetail.getName());
// jobForm.setDescription(jobDetail.getDescription());
// jobForm.setJobClass(jobDetail.getJobClass().getName());
// form.getExecutingJobs().add(jobForm);
// }
// String calendars[] = choosenScheduler.getCalendarNames();
//
// List jobListeners = choosenScheduler.getGlobalJobListeners();
// for (Iterator iter = jobListeners.iterator(); iter.hasNext();) {
// JobListener jobListener = (JobListener) iter.next();
// ListenerDTO listenerForm = new ListenerDTO();
// listenerForm.setName(jobListener.getName());
// listenerForm.setListenerClass(jobListener.getClass().getName());
// schedForm.getGlobalJobListeners().add(listenerForm);
// }
//
// form.setScheduler(schedForm);
// }
//}
| 42.957871 | 133 | 0.554041 |
200d19431efd37c39de75a7fe860d47e23673d12 | 11,252 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package com.google.maps.android;
public final class R {
public static final class attr {
public static final int ambientEnabled = 0x7f04002f;
public static final int buttonSize = 0x7f04005c;
public static final int cameraBearing = 0x7f040061;
public static final int cameraMaxZoomPreference = 0x7f040062;
public static final int cameraMinZoomPreference = 0x7f040063;
public static final int cameraTargetLat = 0x7f040064;
public static final int cameraTargetLng = 0x7f040065;
public static final int cameraTilt = 0x7f040066;
public static final int cameraZoom = 0x7f040067;
public static final int circleCrop = 0x7f040070;
public static final int colorScheme = 0x7f040081;
public static final int imageAspectRatio = 0x7f0400d5;
public static final int imageAspectRatioAdjust = 0x7f0400d6;
public static final int latLngBoundsNorthEastLatitude = 0x7f0400e2;
public static final int latLngBoundsNorthEastLongitude = 0x7f0400e3;
public static final int latLngBoundsSouthWestLatitude = 0x7f0400e4;
public static final int latLngBoundsSouthWestLongitude = 0x7f0400e5;
public static final int liteMode = 0x7f0400fd;
public static final int mapType = 0x7f040109;
public static final int scopeUris = 0x7f040134;
public static final int uiCompass = 0x7f0401af;
public static final int uiMapToolbar = 0x7f0401b0;
public static final int uiRotateGestures = 0x7f0401b1;
public static final int uiScrollGestures = 0x7f0401b2;
public static final int uiTiltGestures = 0x7f0401b3;
public static final int uiZoomControls = 0x7f0401b4;
public static final int uiZoomGestures = 0x7f0401b5;
public static final int useViewLifecycle = 0x7f0401ba;
public static final int zOrderOnTop = 0x7f0401cb;
}
public static final class color {
public static final int common_google_signin_btn_text_dark = 0x7f060034;
public static final int common_google_signin_btn_text_dark_default = 0x7f060035;
public static final int common_google_signin_btn_text_dark_disabled = 0x7f060036;
public static final int common_google_signin_btn_text_dark_focused = 0x7f060037;
public static final int common_google_signin_btn_text_dark_pressed = 0x7f060038;
public static final int common_google_signin_btn_text_light = 0x7f060039;
public static final int common_google_signin_btn_text_light_default = 0x7f06003a;
public static final int common_google_signin_btn_text_light_disabled = 0x7f06003b;
public static final int common_google_signin_btn_text_light_focused = 0x7f06003c;
public static final int common_google_signin_btn_text_light_pressed = 0x7f06003d;
}
public static final class drawable {
public static final int amu_bubble_mask = 0x7f080059;
public static final int amu_bubble_shadow = 0x7f08005a;
public static final int common_full_open_on_phone = 0x7f08005f;
public static final int common_google_signin_btn_icon_dark = 0x7f080060;
public static final int common_google_signin_btn_icon_dark_focused = 0x7f080061;
public static final int common_google_signin_btn_icon_dark_normal = 0x7f080062;
public static final int common_google_signin_btn_icon_light = 0x7f080065;
public static final int common_google_signin_btn_icon_light_focused = 0x7f080066;
public static final int common_google_signin_btn_icon_light_normal = 0x7f080067;
public static final int common_google_signin_btn_text_dark = 0x7f080069;
public static final int common_google_signin_btn_text_dark_focused = 0x7f08006a;
public static final int common_google_signin_btn_text_dark_normal = 0x7f08006b;
public static final int common_google_signin_btn_text_light = 0x7f08006e;
public static final int common_google_signin_btn_text_light_focused = 0x7f08006f;
public static final int common_google_signin_btn_text_light_normal = 0x7f080070;
}
public static final class id {
public static final int adjust_height = 0x7f090020;
public static final int adjust_width = 0x7f090021;
public static final int amu_text = 0x7f090027;
public static final int auto = 0x7f09002b;
public static final int dark = 0x7f090054;
public static final int hybrid = 0x7f0900a9;
public static final int icon_only = 0x7f0900ac;
public static final int light = 0x7f0900ba;
public static final int none = 0x7f0900e0;
public static final int normal = 0x7f0900e1;
public static final int satellite = 0x7f09012d;
public static final int standard = 0x7f09015d;
public static final int terrain = 0x7f090168;
public static final int webview = 0x7f0901a8;
public static final int wide = 0x7f0901a9;
public static final int window = 0x7f0901aa;
}
public static final class integer {
public static final int google_play_services_version = 0x7f0a0007;
}
public static final class layout {
public static final int amu_info_window = 0x7f0b0030;
public static final int amu_text_bubble = 0x7f0b0031;
public static final int amu_webview = 0x7f0b0032;
}
public static final class raw {
public static final int amu_ballon_gx_prefix = 0x7f0d0000;
public static final int amu_basic_folder = 0x7f0d0001;
public static final int amu_basic_placemark = 0x7f0d0002;
public static final int amu_cdata = 0x7f0d0003;
public static final int amu_default_balloon = 0x7f0d0004;
public static final int amu_document_nest = 0x7f0d0005;
public static final int amu_draw_order_ground_overlay = 0x7f0d0006;
public static final int amu_extended_data = 0x7f0d0007;
public static final int amu_ground_overlay = 0x7f0d0008;
public static final int amu_ground_overlay_color = 0x7f0d0009;
public static final int amu_inline_style = 0x7f0d000a;
public static final int amu_multigeometry_placemarks = 0x7f0d000b;
public static final int amu_multiple_placemarks = 0x7f0d000c;
public static final int amu_nested_folders = 0x7f0d000d;
public static final int amu_nested_multigeometry = 0x7f0d000e;
public static final int amu_poly_style_boolean_alpha = 0x7f0d000f;
public static final int amu_poly_style_boolean_numeric = 0x7f0d0010;
public static final int amu_unknwown_folder = 0x7f0d0011;
public static final int amu_unsupported = 0x7f0d0012;
public static final int amu_visibility_ground_overlay = 0x7f0d0013;
}
public static final class string {
public static final int common_google_play_services_enable_button = 0x7f0e003b;
public static final int common_google_play_services_enable_text = 0x7f0e003c;
public static final int common_google_play_services_enable_title = 0x7f0e003d;
public static final int common_google_play_services_install_button = 0x7f0e003e;
public static final int common_google_play_services_install_title = 0x7f0e0040;
public static final int common_google_play_services_notification_ticker = 0x7f0e0041;
public static final int common_google_play_services_unknown_issue = 0x7f0e0042;
public static final int common_google_play_services_unsupported_text = 0x7f0e0043;
public static final int common_google_play_services_update_button = 0x7f0e0044;
public static final int common_google_play_services_update_text = 0x7f0e0045;
public static final int common_google_play_services_update_title = 0x7f0e0046;
public static final int common_google_play_services_updating_text = 0x7f0e0047;
public static final int common_google_play_services_wear_update_text = 0x7f0e0048;
public static final int common_open_on_phone = 0x7f0e0049;
public static final int common_signin_button_text = 0x7f0e004a;
public static final int common_signin_button_text_long = 0x7f0e004b;
}
public static final class style {
public static final int amu_Bubble_TextAppearance_Dark = 0x7f0f019d;
public static final int amu_Bubble_TextAppearance_Light = 0x7f0f019e;
public static final int amu_ClusterIcon_TextAppearance = 0x7f0f019f;
}
public static final class styleable {
public static final int[] LoadingImageView = { 0x7f040070, 0x7f0400d5, 0x7f0400d6 };
public static final int LoadingImageView_circleCrop = 0;
public static final int LoadingImageView_imageAspectRatio = 1;
public static final int LoadingImageView_imageAspectRatioAdjust = 2;
public static final int[] MapAttrs = { 0x7f04002f, 0x7f040061, 0x7f040062, 0x7f040063, 0x7f040064, 0x7f040065, 0x7f040066, 0x7f040067, 0x7f0400e2, 0x7f0400e3, 0x7f0400e4, 0x7f0400e5, 0x7f0400fd, 0x7f040109, 0x7f0401af, 0x7f0401b0, 0x7f0401b1, 0x7f0401b2, 0x7f0401b3, 0x7f0401b4, 0x7f0401b5, 0x7f0401ba, 0x7f0401cb };
public static final int MapAttrs_ambientEnabled = 0;
public static final int MapAttrs_cameraBearing = 1;
public static final int MapAttrs_cameraMaxZoomPreference = 2;
public static final int MapAttrs_cameraMinZoomPreference = 3;
public static final int MapAttrs_cameraTargetLat = 4;
public static final int MapAttrs_cameraTargetLng = 5;
public static final int MapAttrs_cameraTilt = 6;
public static final int MapAttrs_cameraZoom = 7;
public static final int MapAttrs_latLngBoundsNorthEastLatitude = 8;
public static final int MapAttrs_latLngBoundsNorthEastLongitude = 9;
public static final int MapAttrs_latLngBoundsSouthWestLatitude = 10;
public static final int MapAttrs_latLngBoundsSouthWestLongitude = 11;
public static final int MapAttrs_liteMode = 12;
public static final int MapAttrs_mapType = 13;
public static final int MapAttrs_uiCompass = 14;
public static final int MapAttrs_uiMapToolbar = 15;
public static final int MapAttrs_uiRotateGestures = 16;
public static final int MapAttrs_uiScrollGestures = 17;
public static final int MapAttrs_uiTiltGestures = 18;
public static final int MapAttrs_uiZoomControls = 19;
public static final int MapAttrs_uiZoomGestures = 20;
public static final int MapAttrs_useViewLifecycle = 21;
public static final int MapAttrs_zOrderOnTop = 22;
public static final int[] SignInButton = { 0x7f04005c, 0x7f040081, 0x7f040134 };
public static final int SignInButton_buttonSize = 0;
public static final int SignInButton_colorScheme = 1;
public static final int SignInButton_scopeUris = 2;
}
}
| 63.931818 | 325 | 0.738091 |
fc1dac0db46a1cfb45afd2874def961e509a2bcb | 2,358 | package com.zark.easyframe.common.util.collection;
import java.util.*;
/**
* Created by qiuzhen on 16/3/27.
*/
public class MapUtils {
/**
* 将一个迭代器转换为一个map
* <p>
* value就是迭代器的自身元素
* <p>
* key由mapKeyProvidor指定
*
* @param iterator 迭代器
* @param mapKeyProvidor map的key的提供者
* @return Map<K, V>
*/
public static <K, V> Map<K, V> getMap(Iterator<V> iterator, MapKeyProvidor<K, V> mapKeyProvidor) {
Map<K, V> map = new HashMap<K, V>();
while (iterator.hasNext()) {
V v = iterator.next();
K key = mapKeyProvidor.getKey(v);
if(key != null){
map.put(key, v);
}
}
return map;
}
/**
* 将一个迭代器转换为一个map
* <p>
* value就是迭代器的自身元素
* <p>
* key由mapKeyProvidor指定
*
* @param iterator 迭代器
* @param mapKeyProvidor map的key的提供者
* @return Map<K, List<V>>
*/
public static <K, V> Map<K, List<V>> getListMap(Iterator<V> iterator, MapKeyProvidor<K, V> mapKeyProvidor) {
Map<K, List<V>> map = new HashMap<K, List<V>>();
while (iterator.hasNext()) {
V v = iterator.next();
K key = mapKeyProvidor.getKey(v);
if(key == null){
continue;
}
List<V> value = map.get(key);
if(value == null){
value = new ArrayList<V>();
map.put(key, value);
}
value.add(v);
}
return map;
}
/**
* 将一个迭代器转换为一个map
* <p>
* value就是迭代器的自身元素
* <p>
* key由mapKeyProvidor指定
*
* @param iterator 迭代器
* @param mapKeyProvidor map的key的提供者
* @return Map<K, Set<V>>
*/
public static <K, V> Map<K, Set<V>> getSetMap(Iterator<V> iterator, MapKeyProvidor<K, V> mapKeyProvidor) {
Map<K, Set<V>> map = new HashMap<K, Set<V>>();
while (iterator.hasNext()) {
V v = iterator.next();
K key = mapKeyProvidor.getKey(v);
if(key == null){
continue;
}
Set<V> value = map.get(key);
if(value == null){
value = new HashSet<V>();
map.put(key, value);
}
value.add(v);
}
return map;
}
}
| 24.061224 | 112 | 0.47922 |
2dbe3354d2b7ebc7513ae0fa25348133378dbbb4 | 398 | package org.igor.onlinegames.websocket;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.util.UUID;
@Data
@AllArgsConstructor
@Builder
public class StateInfoDto {
private UUID stateId;
private String stateType;
private String createdAt;
private String lastInMsgAt;
private String lastOutMsgAt;
private Object viewRepresentation;
}
| 19.9 | 39 | 0.781407 |
255eb6cd5df0954ed4b34cae881addefb4196c95 | 5,708 | package com.rabbitmq.rabbittesttool.model;
public class Summary {
String benchmarkId;
long publishedCount;
long consumedCount;
long unconsumedRemainder;
long redeliveredCount;
boolean checkedOrdering;
boolean checkedDataloss;
boolean checkedDuplicates;
boolean checkedConnectivity;
boolean checkedConsumeUptime;
boolean includeRedeliveredInChecks;
boolean safeConfiguration;
long orderingViolations;
long redeliveredOrderingViolations;
long datalossViolations;
long duplicateViolations;
long redeliveredDuplicateViolations;
double connectionAvailability;
int disconnectionPeriods;
int maxDisconnectionMs;
double consumeAvailability;
int noConsumePeriods;
int maxNoconsumeMs;
public Summary() {}
public String getBenchmarkId() {
return benchmarkId;
}
public void setBenchmarkId(String benchmarkId) {
this.benchmarkId = benchmarkId;
}
public long getPublishedCount() {
return publishedCount;
}
public void setPublishedCount(long publishedCount) {
this.publishedCount = publishedCount;
}
public long getConsumedCount() {
return consumedCount;
}
public void setConsumedCount(long consumedCount) {
this.consumedCount = consumedCount;
}
public long getUnconsumedRemainder() {
return unconsumedRemainder;
}
public void setUnconsumedRemainder(long unconsumedRemainder) {
this.unconsumedRemainder = unconsumedRemainder;
}
public long getRedeliveredCount() {
return redeliveredCount;
}
public void setRedeliveredCount(long redeliveredCount) {
this.redeliveredCount = redeliveredCount;
}
public boolean isCheckedOrdering() {
return checkedOrdering;
}
public void setCheckedOrdering(boolean checkedOrdering) {
this.checkedOrdering = checkedOrdering;
}
public boolean isCheckedDataloss() {
return checkedDataloss;
}
public void setCheckedDataloss(boolean checkedDataloss) {
this.checkedDataloss = checkedDataloss;
}
public boolean isCheckedDuplicates() {
return checkedDuplicates;
}
public void setCheckedDuplicates(boolean checkedDuplicates) {
this.checkedDuplicates = checkedDuplicates;
}
public boolean isCheckedConnectivity() {
return checkedConnectivity;
}
public void setCheckedConnectivity(boolean checkedConnectivity) {
this.checkedConnectivity = checkedConnectivity;
}
public boolean isCheckedConsumeUptime() {
return checkedConsumeUptime;
}
public void setCheckedConsumeUptime(boolean checkedConsumeUptime) {
this.checkedConsumeUptime = checkedConsumeUptime;
}
public boolean isIncludeRedeliveredInChecks() {
return includeRedeliveredInChecks;
}
public void setIncludeRedeliveredInChecks(boolean includeRedeliveredInChecks) {
this.includeRedeliveredInChecks = includeRedeliveredInChecks;
}
public boolean isSafeConfiguration() {
return safeConfiguration;
}
public void setSafeConfiguration(boolean safeConfiguration) {
this.safeConfiguration = safeConfiguration;
}
public long getOrderingViolations() {
return orderingViolations;
}
public void setOrderingViolations(long orderingViolations) {
this.orderingViolations = orderingViolations;
}
public long getRedeliveredOrderingViolations() {
return orderingViolations;
}
public void setRedeliveredOrderingViolations(long redeliveredOrderingViolations) {
this.redeliveredOrderingViolations = redeliveredOrderingViolations;
}
public long getDatalossViolations() {
return datalossViolations;
}
public void setDatalossViolations(long datalossViolations) {
this.datalossViolations = datalossViolations;
}
public long getDuplicateViolations() {
return duplicateViolations;
}
public void setDuplicateViolations(long duplicateViolations) {
this.duplicateViolations = duplicateViolations;
}
public long getRedeliveredDuplicateViolations() {
return duplicateViolations;
}
public void setRedeliveredDuplicateViolations(long redeliveredDuplicateViolations) {
this.redeliveredDuplicateViolations = redeliveredDuplicateViolations;
}
public double getConnectionAvailability() {
return connectionAvailability;
}
public void setConnectionAvailability(double connectionAvailability) {
this.connectionAvailability = connectionAvailability;
}
public int getDisconnectionPeriods() {
return disconnectionPeriods;
}
public void setDisconnectionPeriods(int disconnectionPeriods) {
this.disconnectionPeriods = disconnectionPeriods;
}
public int getMaxDisconnectionMs() {
return maxDisconnectionMs;
}
public void setMaxDisconnectionMs(int maxDisconnectionMs) {
this.maxDisconnectionMs = maxDisconnectionMs;
}
public double getConsumeAvailability() {
return consumeAvailability;
}
public void setConsumeAvailability(double consumeAvailability) {
this.consumeAvailability = consumeAvailability;
}
public int getNoConsumePeriods() {
return noConsumePeriods;
}
public void setNoConsumePeriods(int noConsumePeriods) {
this.noConsumePeriods = noConsumePeriods;
}
public int getMaxNoconsumeMs() {
return maxNoconsumeMs;
}
public void setMaxNoconsumeMs(int maxNoconsumeMs) {
this.maxNoconsumeMs = maxNoconsumeMs;
}
}
| 26.672897 | 88 | 0.717414 |
ce27b5bbf9a46f7b9eefd97be4674ea00575e6e0 | 832 | package com.leetcode.algorithm.easy.romantointeger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class SolutionTest {
@Test
public void testIII() {
Solution solution = new Solution();
assertEquals(3, solution.romanToInt("III"));
}
@Test
public void testIV() {
Solution solution = new Solution();
assertEquals(4, solution.romanToInt("IV"));
}
@Test
public void testIX() {
Solution solution = new Solution();
assertEquals(9, solution.romanToInt("IX"));
}
@Test
public void testLVIII() {
Solution solution = new Solution();
assertEquals(58, solution.romanToInt("LVIII"));
}
@Test
public void testMCMXCIV() {
Solution solution = new Solution();
assertEquals(1994, solution.romanToInt("MCMXCIV"));
}
}
| 21.894737 | 60 | 0.685096 |
b0a38299919646680ec2a01f654a76c1131b410f | 1,638 | import java.util.ArrayList;
public class Suitcase {
private ArrayList<Item> items = new ArrayList<>();
private int maximumWeight;
public Suitcase(int maximumWeight) {
this.maximumWeight = maximumWeight;
}
public void addItem(Item item) {
if (this.maximumWeight > item.getWeight()) {
this.maximumWeight -= item.getWeight();
items.add(item);
}
}
public void printItems() {
for (Item item: items) {
System.out.println(item);
}
}
public int totalWeight() {
int totalWeight = 0;
for (Item item: items) {
totalWeight += item.getWeight();
}
return totalWeight;
}
public Item heaviestItem() {
Item heaviestItem = items.get(0);
for (Item item: items) {
if (item.getWeight() > heaviestItem.getWeight()) {
heaviestItem = item;
}
}
return heaviestItem;
}
@Override
public String toString() {
int totalWeight = 0;
for (Item item: items) {
totalWeight += item.getWeight();
}
String noItems = this.items.size() + " items " + "(" + totalWeight + " kg)";
String singleItem = this.items.size() + " item " + "(" + totalWeight + " kg)";
String multipleItems = this.items.size() + " items " + "(" + totalWeight + " kg)";
switch (this.items.size()) {
case 0:
return noItems;
case 1:
return singleItem;
default:
return multipleItems;
}
}
}
| 26 | 90 | 0.518315 |
4fc8d1a4d16d7965cd959621103f3cd3483b0f6b | 569 | package com.spotify.heroic.aggregation.simple;
import com.spotify.heroic.aggregation.Empty;
import com.spotify.heroic.test.ValueSuppliers;
import java.lang.reflect.Type;
import java.util.Optional;
public class OfSupplier implements ValueSuppliers.ValueSupplier {
@Override
public Optional<Object> supply(
final Type type, final boolean secondary, final String name
) {
if ("of".equals(name)) {
return Optional.of(secondary ? Optional.of(Empty.INSTANCE) : Optional.empty());
}
return Optional.empty();
}
}
| 27.095238 | 91 | 0.702988 |
768868d235b5f147f198be02a3da57a0f6fe0ca1 | 679 | package org.kyojo.schemaOrg.m3n3.doma.healthLifesci.physicalActivityCategory;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaOrg.m3n3.healthLifesci.physicalActivityCategory.AEROBIC_ACTIVITY;
import org.kyojo.schemaOrg.m3n3.healthLifesci.PhysicalActivityCategory.AerobicActivity;
@ExternalDomain
public class AerobicActivityConverter implements DomainConverter<AerobicActivity, String> {
@Override
public String fromDomainToValue(AerobicActivity domain) {
return domain.getNativeValue();
}
@Override
public AerobicActivity fromValueToDomain(String value) {
return new AEROBIC_ACTIVITY(value);
}
}
| 29.521739 | 91 | 0.840943 |
6d99249677513cf3d69de97dbe5688686aa83f77 | 1,031 | package me.koply.saniye.data;
import com.eclipsesource.json.JsonObject;
import me.koply.saniye.Main;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import static me.koply.saniye.util.JsonUtil.*;
public class DataHelper {
public static JsonObject getUserVCData(Guild guild, Member member) {
return getUserVCData(Main.DATA.getDataJson(), guild.getId(), member.getId());
}
public static JsonObject getUserVCData(JsonObject data, Guild guild, Member member) {
return getUserVCData(data, guild.getId(), member.getId());
}
public static JsonObject getUserVCData(JsonObject data, String guildID, String userID) {
var guildval = data.get(guildID);
if (isNull(guildval)) return null;
var vcdataval = guildval.asObject().get("vcdata");
if (isNull(vcdataval)) return null;
var userdataval = vcdataval.asObject().get(userID);
if (isNull(userdataval)) return null;
return userdataval.asObject();
}
} | 32.21875 | 92 | 0.704171 |
a78bc74122d6a4645a83de0723949c41e8016e4f | 6,690 | import com.github.mreutegg.laszip4j.LASPoint;
import com.github.mreutegg.laszip4j.LASReader;
import com.github.petvana.liblas.LasWriter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import javax.imageio.ImageIO;
import javax.ws.rs.client.*;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Collection;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
private static final String ARSO_LIDAR_URL = "http://gis.arso.gov.si/lidar/gkot/laz/b_35/D48GK/GK_470_97.laz";
private static final String ARSO_ORTOPHOTO_URL = "http://gis.arso.gov.si/arcgis/rest/services/DOF_2016/MapServer/export";
private static final int ORTO_PHOTO_IMG_SIZE = 1000;//TODO - change so it works with different sizes
public static void main(String[] args){
System.out.println("Started...");
File file = createLidarFile(ARSO_LIDAR_URL);
//File file = new File("C:\\Users\\Matej\\IdeaProjects\\nrg-seminar\\src\\GK_470_97.laz");
String[] fileNameParams = FilenameUtils.removeExtension(file.getName()).split("_"); //GK_470_97
int xThousand = Integer.parseInt(fileNameParams[1]);
int yThousand = Integer.parseInt(fileNameParams[2]);
BufferedImage image = getOrtoPhoto(xThousand,yThousand);//470,97
// BufferedImage image = null;
// try {
// image = ImageIO.read(new File("C:\\Users\\Matej\\IdeaProjects\\nrg-seminar\\src\\saved.png"));
// } catch (Exception e) {
// e.printStackTrace();
// }
DataBufferInt buff = (DataBufferInt) image.getRaster().getDataBuffer();
int[] pixels = buff.getData();
int height = image.getHeight();
int width = image.getWidth();
LASReader lasReader = null;
try {
lasReader = new LASReader(file);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Reading points...");
for (LASPoint p: lasReader.getPoints()) {
int[] pxCoordinates = findClosestPxCoordinates(p.getX(), p.getY(), xThousand, yThousand);
int i = pxCoordinates[0]-(xThousand*1000);
int j = (height-1)-(pxCoordinates[1]-(yThousand*1000));//j index of image goes from top to bottom
int rgb = pixels[(j*width)+i]; //binary int value
Color color = new Color(rgb);
int[] rgbArray = new int[]{color.getRed(), color.getGreen(), color.getBlue()};
//System.out.println(rgbArray[0] + "," + rgbArray[1] + "," + rgbArray[2]);
}
System.out.println("Finished.");
System.exit(0);
}
private static File createLidarFile(String URL){
File f = null;
InputStream inputStream;
try {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(URI.create(URL));
Invocation.Builder request = resource.request();
request.accept(MediaType.APPLICATION_OCTET_STREAM);
System.out.println("Requesting from source [" + resource.getUri() + "]");
Response response = request.get();
System.out.print("Reading response...");
inputStream = response.readEntity(InputStream.class);
//response.close();
String fileName = FilenameUtils.getName(resource.getUri().getPath());
f = new File(fileName);
f.deleteOnExit();
System.out.print("[DONE]\nWriting to file...");
FileUtils.copyInputStreamToFile(inputStream, f);
inputStream.close();
System.out.println("[DONE]");
} catch (IOException e) {
e.printStackTrace();
}
return f;
}
private static BufferedImage getOrtoPhoto(int leftX, int lowerY){
double minX = leftX * 1000;
double minY = lowerY * 1000;
double maxX = minX + (999.999999999);
double maxY = minY + (999.999999999);
Client client = ClientBuilder.newClient();
Form form = new Form()
.param("bbox", minX + ","+minY+","+maxX+","+maxY)
.param("format", "bmp")
.param("transparent", "false")
.param("f", "image")
.param("size", ORTO_PHOTO_IMG_SIZE + "," + ORTO_PHOTO_IMG_SIZE);
System.out.print("Requesting from source: [" + ARSO_ORTOPHOTO_URL + "]");
Response response = client.target(ARSO_ORTOPHOTO_URL).request().post(Entity.form(form));
BufferedImage image = response.readEntity(BufferedImage.class);
response.close();
System.out.println("[DONE]");
return image;
}
private static int[] findClosestPxCoordinates(int x, int y, int minX, int minY){//TODO - find if/why do we need ints? LASreader??
double _x = (double)x/100;//we get x without .00 decimal. why?
double _y = (double)y/100;
return findClosestPxCoordinates(_x, _y, minX, minY);
}
private static int[] findClosestPxCoordinates(double x, double y, int minX, int minY){
double maxX = minX + (ORTO_PHOTO_IMG_SIZE-1);
double maxY = minY + (ORTO_PHOTO_IMG_SIZE-1);
Point2D p = new Point2D.Double(x,y);
Point2D upperLeft = new Point2D.Double((int)x,(int)y+1);
Point2D upperRight = new Point2D.Double((int)x+1,(int)y+1);
Point2D bottomLeft = new Point2D.Double((int)x,(int)y);
Point2D bottomRight = new Point2D.Double((int)x+1,(int)y);
PriorityQueue<Point2D> queue = new PriorityQueue<Point2D>(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Point2D p1 = (Point2D) o1;
Point2D p2 = (Point2D) o2;
if (p.distance(p1) < p.distance(p2)){
return -1;
} else { //no zero needed
return 1;
}
}
});
//if pixel is allowed, add to queue
queue.add(bottomLeft);
if ((int)y+1 <= maxY) queue.add(upperLeft);
if ((int)x+1 <= maxX) queue.add(bottomRight);
if ((int)x+1 <= maxX && (int)y+1 <= maxY) queue.add(upperRight);
Point2D closestPoint = queue.peek();
return new int[]{(int)closestPoint.getX(), (int)closestPoint.getY()};
}
}
| 36.961326 | 133 | 0.610164 |
260ae7c6055d012925ac3c14c06377355703aaa8 | 4,616 | package cn.iocoder.yudao.adminserver.modules.infra.service.file;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.iocoder.yudao.adminserver.BaseDbUnitTest;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.adminserver.modules.infra.framework.file.config.FileProperties;
import cn.iocoder.yudao.adminserver.modules.infra.controller.file.vo.InfFilePageReqVO;
import cn.iocoder.yudao.adminserver.modules.infra.dal.dataobject.file.InfFileDO;
import cn.iocoder.yudao.adminserver.modules.infra.dal.mysql.file.InfFileMapper;
import cn.iocoder.yudao.adminserver.modules.infra.service.file.impl.InfFileServiceImpl;
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.adminserver.modules.infra.enums.InfErrorCodeConstants.FILE_NOT_EXISTS;
import static cn.iocoder.yudao.adminserver.modules.system.enums.SysErrorCodeConstants.FILE_PATH_EXISTS;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomString;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildTime;
import static org.junit.jupiter.api.Assertions.*;
@Import({InfFileServiceImpl.class, FileProperties.class})
public class InfFileServiceTest extends BaseDbUnitTest {
@Resource
private InfFileServiceImpl fileService;
@Resource
private FileProperties fileProperties;
@Resource
private InfFileMapper fileMapper;
@Test
public void testCreateFile_success() {
// 准备参数
String path = randomString();
byte[] content = ResourceUtil.readBytes("file/erweima.jpg");
// 调用
String url = fileService.createFile(path, content);
// 断言
assertEquals(fileProperties.getBasePath() + path, url);
// 校验数据
InfFileDO file = fileMapper.selectById(path);
assertEquals(path, file.getId());
assertEquals("jpg", file.getType());
assertArrayEquals(content, file.getContent());
}
@Test
public void testCreateFile_exists() {
// mock 数据
InfFileDO dbFile = randomPojo(InfFileDO.class);
fileMapper.insert(dbFile);
// 准备参数
String path = dbFile.getId(); // 模拟已存在
byte[] content = ResourceUtil.readBytes("file/erweima.jpg");
// 调用,并断言异常
assertServiceException(() -> fileService.createFile(path, content), FILE_PATH_EXISTS);
}
@Test
public void testDeleteFile_success() {
// mock 数据
InfFileDO dbFile = randomPojo(InfFileDO.class);
fileMapper.insert(dbFile);// @Sql: 先插入出一条存在的数据
// 准备参数
String id = dbFile.getId();
// 调用
fileService.deleteFile(id);
// 校验数据不存在了
assertNull(fileMapper.selectById(id));
}
@Test
public void testDeleteFile_notExists() {
// 准备参数
String id = randomString();
// 调用, 并断言异常
assertServiceException(() -> fileService.deleteFile(id), FILE_NOT_EXISTS);
}
@Test
public void testGetFilePage() {
// mock 数据
InfFileDO dbFile = randomPojo(InfFileDO.class, o -> { // 等会查询到
o.setId("yudao");
o.setType("jpg");
o.setCreateTime(buildTime(2021, 1, 15));
});
fileMapper.insert(dbFile);
// 测试 id 不匹配
fileMapper.insert(ObjectUtils.clone(dbFile, o -> o.setId("tudou")));
// 测试 type 不匹配
fileMapper.insert(ObjectUtils.clone(dbFile, o -> {
o.setId("yudao02");
o.setType("png");
}));
// 测试 createTime 不匹配
fileMapper.insert(ObjectUtils.clone(dbFile, o -> {
o.setId("yudao03");
o.setCreateTime(buildTime(2020, 1, 15));
}));
// 准备参数
InfFilePageReqVO reqVO = new InfFilePageReqVO();
reqVO.setId("yudao");
reqVO.setType("jp");
reqVO.setBeginCreateTime(buildTime(2021, 1, 10));
reqVO.setEndCreateTime(buildTime(2021, 1, 20));
// 调用
PageResult<InfFileDO> pageResult = fileService.getFilePage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbFile, pageResult.getList().get(0), "content");
}
}
| 36.346457 | 103 | 0.679593 |
0d64fc7289b52977f3fc07265c4f5d60d2b94bd0 | 8,366 | package server.web.resources.json;
import static org.junit.Assert.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.TreeMap;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import commons.IdPosizione;
import commons.Posizione;
import commons.Utente;
import server.backend.GestoreDatiPersistenti;
import server.backend.wrapper.UserRegistryAPI;
public class LastPositionAllUsersJSONTest {
static GestoreDatiPersistenti g = GestoreDatiPersistenti.getInstance();
Utente u1= new Utente("pas", "pas", "pas@gmail.com", "Pasquale", "Forgione");
Utente u2= new Utente("lor", "lor", "lor@gmail.com", "Lorenzo", "Goglia");
Utente u3= new Utente("ant", "ant", "ant@gmail.com", "Antonio", "Varone");
Posizione pos1a = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 8, 4, 12, 0, 10)), Math.random(), Math.random()), u1, 20);
Posizione pos1b = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 11, 25, 12, 0, 10)), Math.random(), Math.random()), u1, 20);
Posizione pos1c = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 12, 22, 10, 0, 5)), Math.random(), Math.random()), u1, 20);
Posizione pos2a = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 8, 29, 12, 0, 10)), Math.random(), Math.random()), u2, 20);
Posizione pos2b = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 8, 30, 12, 0, 10)), Math.random(), Math.random()), u2, 20);
Posizione pos2c = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 8, 28, 12, 0, 10)), Math.random(), Math.random()), u2, 20);
Posizione pos3a = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 8, 27, 12, 0, 20)), Math.random(), Math.random()), u3, 20);
Posizione pos3b = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 8, 27, 12, 0, 19)), Math.random(), Math.random()), u3, 20);
Posizione pos3c = new Posizione(new IdPosizione(Timestamp.valueOf(LocalDateTime.of(2017, 8, 27, 12, 0, 18)), Math.random(), Math.random()), u3, 20);
@BeforeClass
public static void setUpBeforeClass() throws Exception {
g.dropDatabase();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
g.dropDatabase();
}
@Before
public void setUp() throws Exception {
g.dropDatabase();
UserRegistryAPI ur = UserRegistryAPI.instance();
TreeMap<String, Utente> temp = new TreeMap<String, Utente>();
temp.putAll(ur.getUtenti());
for(String username : temp.keySet()) {
ur.removeUtente(username);
}
//Aggiunta utenti
try{
ur.addUtente(u1);
}catch(Exception e){
assertTrue("L'utente "+u1.getUsername() +" non esiste e dovrebbe essere aggiunto al database!", false);
}
try{
ur.addUtente(u2);
}catch(Exception e){
assertTrue("L'utente "+u2.getUsername() +" non esiste e dovrebbe essere aggiunto al database!", false);
}
try{
ur.addUtente(u3);
}catch(Exception e){
assertTrue("L'utente "+u3.getUsername() +" non esiste e dovrebbe essere aggiunto al database!", false);
}
//Aggiunta posizioni ad ogni utente u1 (last position is pos1c)
try{
ur.addPosizione(pos1a);
assertTrue("La posizione1a pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos1a.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione1a pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
try{
ur.addPosizione(pos1b);
assertTrue("La posizione1b pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos1b.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione1b pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
try{
ur.addPosizione(pos1c);
assertTrue("La posizione1c pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos1c.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione1c pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
//Aggiunta posizioni ad ogni utente u2 (last position is pos2b)
try{
ur.addPosizione(pos2a);
assertTrue("La posizione2a pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos2a.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione2a pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
try{
ur.addPosizione(pos2b);
assertTrue("La posizione2b pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos2b.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione2b pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
try{
ur.addPosizione(pos2c);
assertTrue("La posizione2c pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos2c.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione2c pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
//Aggiunta posizioni ad ogni utente u3 (last position is pos3a)
try{
ur.addPosizione(pos3a);
assertTrue("La posizione3a pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos3a.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione3a pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
try{
ur.addPosizione(pos3b);
assertTrue("La posizione3b pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos3b.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione3b pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
try{
ur.addPosizione(pos3c);
assertTrue("La posizione3c pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", ur.getPosizioni().containsKey(pos3c.getIdPosizione()));
}catch(Exception e){
assertTrue("La posizione3c pur non essendo presente nel database, non e' stata aggiunta ad un utente esistente!", false);
}
assertTrue("Il database dovrebbe avere 3 utenti, size="+g.getUtenti().size(), g.getUtenti().size()==3);
assertTrue("La mappa dovrebbe contenere 9 posizioni, size="+g.getPosizioni().size(), g.getPosizioni().size()==9);
}
@After
public void tearDown() throws Exception {
g.dropDatabase();
}
@Test
public void test() {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
LastPositionAllUsersJSON lastPositionAllUsersJSON = new LastPositionAllUsersJSON();
String response = lastPositionAllUsersJSON.getUltimaPosizioneOgniUtente();
System.out.println(response);
TreeMap<String,Posizione> mapLastPositionAllUsers = gson.fromJson(response, new TypeToken<TreeMap<String,Posizione>>() {}.getType());
System.out.println(mapLastPositionAllUsers.getClass());
System.out.println(mapLastPositionAllUsers);
assertTrue("La mappa dovrebbe contenere 3 elementi, size="+mapLastPositionAllUsers.size(), mapLastPositionAllUsers.size()==3);
assertTrue("L'ultima posizione dell'utente "+u1.getUsername()+" non e' quella prevista", mapLastPositionAllUsers.containsKey(u1.getUsername()) && mapLastPositionAllUsers.get(u1.getUsername()).equals(pos1c));
assertTrue("L'ultima posizione dell'utente "+u2.getUsername()+" non e' quella prevista", mapLastPositionAllUsers.containsKey(u2.getUsername()) && mapLastPositionAllUsers.get(u2.getUsername()).equals(pos2b));
assertTrue("L'ultima posizione dell'utente "+u3.getUsername()+" non e' quella prevista", mapLastPositionAllUsers.containsKey(u3.getUsername()) && mapLastPositionAllUsers.get(u3.getUsername()).equals(pos3a));
}
}
| 49.502959 | 210 | 0.736433 |
80ff86368eb6752d22576f82f5367f3cf03f4d95 | 1,477 | package com.ecloud.collection.clothes.gson;
import com.ecloud.collection.clothes.app.AppServerConfig;
import com.ecloud.collection.clothes.entity.ErrorBaseBean;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Author: ZhuWenWu
* Version V1.0
* Date: 14-3-15 下午9:50
* Description: 数据请求失败Or成功解析类
* Modification History:
* Date Author Version Discription
* -----------------------------------------------------------------------------------
* 14-3-15 ZhuWenWu 1.0 1.0
* Why & What is modified:
*/
public class GsonErrorParse {
public static ErrorBaseBean mErrorBaseBean;
/**
* 解析HTTP返回数据是否成功
* @param content 返回数据字符串
* @return ErrorBaseBean
*/
public static ErrorBaseBean parse(String content){
mErrorBaseBean = new ErrorBaseBean();
JSONObject json;
try {
json = new JSONObject(content);
if(json.has("code")){
mErrorBaseBean.setCode(json.getInt("status"));
}else{
mErrorBaseBean.setCode(AppServerConfig.CODE_SERVER_ERROR);
}
if(json.has("msg")){
mErrorBaseBean.setMsg(json.getString("msg"));
}else{
mErrorBaseBean.setMsg(AppServerConfig.NET_ERROR_STR);
}
} catch (JSONException e) {
e.printStackTrace();
}
return mErrorBaseBean;
}
}
| 30.142857 | 86 | 0.556534 |
62b4dc2e318225c32b302cac24595c67fdc0931f | 19,464 | package nl.inl.blacklab.server.index;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import nl.inl.blacklab.exceptions.ErrorOpeningIndex;
import nl.inl.blacklab.exceptions.IndexTooOld;
import nl.inl.blacklab.index.IndexListener;
import nl.inl.blacklab.index.Indexer;
import nl.inl.blacklab.search.BlackLab;
import nl.inl.blacklab.search.BlackLabIndex;
import nl.inl.blacklab.search.BlackLabIndexImpl;
import nl.inl.blacklab.search.indexmetadata.IndexMetadata;
import nl.inl.blacklab.server.exceptions.BlsException;
import nl.inl.blacklab.server.exceptions.IllegalIndexName;
import nl.inl.blacklab.server.exceptions.InternalServerError;
import nl.inl.blacklab.server.exceptions.ServiceUnavailable;
import nl.inl.blacklab.server.jobs.User;
import nl.inl.blacklab.server.search.SearchManager;
/**
* A wrapper of sorts around {@link BlackLabIndexImpl}, which is the main blacklab-core
* interface to an index.
*
* This is the main class used to interface with a corpus/index in
* Blacklab-Server. Note the difference between an Index, which is a searchable
* collection of documents, and the _act_ of Indexing, adding new data to an
* Index. Blacklab-Server manages indices centrally using the
* {@link IndexManager}. These handles are managed through this Index class.
*
* References to an Index should not be held for extended amounts of time
* (minutes) (other than by the IndexManager that is), as an Index might
* suddenly be closed, or begin indexing new data, or even be deleted.
*/
public class Index {
//private static final Logger logger = LogManager.getLogger(Index.class);
private static final String SHARE_WITH_USERS_FILENAME = ".shareWithUsers";
public enum IndexStatus {
EMPTY, // index has just been created. can be added to but not searched.
AVAILABLE, // index is available for searching and adding to
INDEXING; // index is busy, files are being added to it
@Override
public String toString() {
return name().toLowerCase();
}
}
/**
* Sort all public indices first, then sort alphabetically within all public and
* private indices.
*/
public static final Comparator<Index> COMPARATOR = new Comparator<Index>() {
@Override
public int compare(Index o1, Index o2) {
// Sort public before private
boolean o1priv = o1.isUserIndex();
boolean o2priv = o2.isUserIndex();
if (o1priv != o2priv)
return o1priv ? 1 : -1;
// Sort rest case-insensitively
return o1.getId().toLowerCase().compareTo(o2.getId().toLowerCase());
}
};
private final String id;
private final File dir;
private SearchManager searchMan;
/**
* Only one of these can be set at a time. The index is closed and cleared
* when an indexer is requested. Running searches are cancelled when this
* happens. The Indexer is cleared the first time a search is started after it
* the Indexer has finished indexing (meaning close() has been called on it). In
* addition, while an index is still running, no new Indexers can be created.
*/
private BlackLabIndex index;
private Indexer indexer;
/** List of users who may access this index (read-only). */
private List<String> shareWithUsers = new ArrayList<>();
/** File where the list of users to share with is stored */
private File shareWithUsersFile;
/**
* NOTE: Index does not support creating a new index from scratch for now,
* instead use {@link IndexManager#createIndex(User, String, String, String)}
*
* @param indexId name of this index, including any username if this is a user
* index
* @param dir directory of this index
* @param searchMan search manager
* @throws IllegalIndexName
* @throws FileNotFoundException
*/
public Index(String indexId, File dir, SearchManager searchMan) throws IllegalIndexName, FileNotFoundException {
if (!isValidIndexName(indexId))
throw new IllegalIndexName(indexId);
if (dir == null || !dir.exists() || !dir.isDirectory())
throw new FileNotFoundException("Cannot find index directory " + dir + ".");
if (!dir.canRead() || !BlackLabIndex.isIndex(dir))
throw new FileNotFoundException("Index directory " + dir + " is not an index or cannot be read.");
this.id = indexId;
this.dir = dir;
this.searchMan = searchMan;
// Opened on-demand
this.index = null;
this.indexer = null;
shareWithUsersFile = new File(dir, SHARE_WITH_USERS_FILENAME);
readShareWithUsersFile();
}
private void readShareWithUsersFile() {
if (shareWithUsersFile.exists()) {
try {
shareWithUsers = FileUtils.readLines(shareWithUsersFile, "utf-8").stream().map(String::trim)
.collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
shareWithUsers = new ArrayList<>();
}
}
private void writeShareWithUsersFile() {
if (shareWithUsers.size() == 0) {
// We don't want to share with anyone. Delete the share file if it exists.
if (shareWithUsersFile.exists()) {
if (!shareWithUsersFile.delete())
throw new RuntimeException("Could not delete share file: " + shareWithUsersFile);
}
} else {
// (Over)write the share file with the current list of users to share with.
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(shareWithUsersFile),
StandardCharsets.UTF_8)) {
writer.write(StringUtils.join(shareWithUsers, "\n"));
} catch (IOException e) {
throw new RuntimeException("Could not write share file", e);
}
}
}
public synchronized void setShareWithUsers(List<String> users) {
shareWithUsers.clear();
shareWithUsers.addAll(users);
writeShareWithUsersFile();
}
public synchronized List<String> getShareWithUsers() {
return Collections.unmodifiableList(shareWithUsers);
}
public String getId() {
return id;
}
public File getDir() {
return dir;
}
/**
* Get the current BlackLabIndex backing this Index. This is not available while this
* index is indexing new data.
*
* @return the currently opened BlackLabIndex
* @throws InternalServerError when there was an error opening this index
* @throws ServiceUnavailable when the index is in use.
*/
// TODO index should not have references to it held for longer times outside of this class
// (references should ideally never leave a synchronized(Index) block... [this might not be possible due to simultaneous searches]
// (this is a large job)
public synchronized BlackLabIndex blIndex() throws InternalServerError, ServiceUnavailable {
try {
openForSearching();
} catch (IndexTooOld e) {
throw BlsException.indexTooOld(e);
}
return index;
}
/**
* Get the IndexMetadata for this Index. This could also be gotten from the
* internal BlackLabIndex or Indexer inside this Index, but this always gets the most
* up-to-date version.
*
* @return the index metadata
* @throws InternalServerError if index couldn't be opened
* @throws IndexTooOld if the index was too old to open by this versio of BlackLab
*/
public synchronized IndexMetadata getIndexMetadata() throws InternalServerError, IndexTooOld {
try {
openForSearching();
} catch (ServiceUnavailable e) {
// swallow, we're apparently still busy indexing something,
// this isn't a problem, we'll just use the Indexer's index to get the structure instead
}
if (this.index != null)
return this.index.metadata();
else if (this.indexer != null)
return this.indexer.indexWriter().metadata();
// This should literally never happen, after openForSearching either index or indexer must be set
throw new RuntimeException(
"Index in invalid state, openForSearching didn't throw unrecoverable error yet there is no BlackLabIndex and no Indexer");
}
public synchronized IndexStatus getStatus() throws BlsException {
if (this.indexer != null && this.indexer.isOpen())
return IndexStatus.INDEXING;
return this.blIndex().isEmpty() ? IndexStatus.EMPTY : IndexStatus.AVAILABLE;
}
/**
* Attempt to open this index in search mode. If this Index currently has an
* open Indexer, checks whether the Indexer has finished (i.e. Indexer.close()
* has been called), and cleans it up if so.
*
* @throws ServiceUnavailable if the index could not be opened due to currently
* ongoing indexing
* @throws InternalServerError if there was some other error opening the index
* @throws IndexTooOld if the index was too old to open by this version of BlackLab
*/
private synchronized void openForSearching() throws ServiceUnavailable, InternalServerError, IndexTooOld {
cleanupClosedIndexerOrThrow();
if (this.index != null)
return;
//logger.debug(" Opening index '" + id + "', dir = " + dir);
try {
index = searchMan.blackLabInstance().open(this.dir);
index.setCache(searchMan.getBlackLabCache());
//logger.debug("Done opening index '" + id + "'");
} catch (IndexTooOld e) {
throw e;
} catch (ErrorOpeningIndex e) {
throw new InternalServerError("Error opening index: " + dir, "INTERR_OPENING_INDEX", e);
}
}
/**
* Get an Indexer that can be used to add new data to this Index. Only one
* indexer may be obtained at a time, meaning until the previous indexer can
* be/has been cleaned up, ServiceUnavailable will be thrown. It is up to the
* user to close the returned Indexer.
*
* Note that this will lock this index for searching until the Indexer has been
* closed again.
*
* @return the indexer
* @throws InternalServerError when the index cannot be opened for some reason
* @throws ServiceUnavailable when there is already an Indexer on this Index
* that's still processing
*/
public synchronized Indexer getIndexer() throws InternalServerError, ServiceUnavailable {
cleanupClosedIndexerOrThrow();
close(); // Close any BlackLabIndex that is still in search mode
try {
this.indexer = Indexer.openIndex(searchMan.blackLabInstance().openForWriting(this.dir, false), null);
indexer.setNumberOfThreadsToUse(BlackLab.config().getIndexing().getNumberOfThreads());
} catch (Exception e) {
throw new InternalServerError("Could not open index '" + id + "'", "INTERR_OPENING_INDEXWRITER", e);
}
return indexer;
}
/**
* Gets the indexListener for the current Indexer. Returns null when this Index
* is not currently Indexing.
*
* @return the listener, or null when there is no ongoing indexing.
* @throws BlsException
*/
public synchronized IndexListener getIndexerListener() throws BlsException {
// Don't return inderListener for an Indexer that has been closed
if (this.getStatus() != IndexStatus.INDEXING)
return null;
return this.indexer.listener();
}
/**
* Close this index if it's currently open. Force closes any current Indexer.
* Has no effect if the index was already closed.
*/
public synchronized void close() {
if (this.index != null) {
// searchMan.getCache().clearCacheForIndex(this.id);
searchMan.getBlackLabCache().removeSearchesForIndex(this.index);
this.index.close();
this.index = null;
}
// if we're currently indexing, force close the indexer
if (this.indexer != null && this.indexer.isOpen()) {
this.indexer.close();
}
this.indexer = null;
}
/**
* Clean up the current Indexer (if any), provided close() has been called on
* the Indexer. NOTE: we do not close the indexer ourselves on purpose (except
* when Index.close() is called), instead we just check if it's been closed when
* a BlackLabIndex or Indexer is requested.
*
* @throws ServiceUnavailable when the current indexer is still indexing
*/
private synchronized void cleanupClosedIndexerOrThrow() throws ServiceUnavailable {
if (this.indexer == null)
return;
if (this.indexer.isOpen())
throw new ServiceUnavailable("Index '" + id + "' is currently indexing a file, please try again later.");
// close() was already called on the indexer externally
this.indexer = null;
}
//---------------------
/**
* three groups: username plus a ':' separator following it, this group is
* non-capturing and optional -- (:?non capturing optional group ending with
* ':')? inside that: the actual capturing of the username -- (:?(capturing):)?
* beyond that, the indexname group, this is not optional so group 1 is always
* the username, and group 2 is always the indexname
*/
private static final Pattern PATT_INDEXID = Pattern.compile("^(?:([\\w\\Q-.!$&'()*+,;=@\\E]+):)?([\\w\\-]+)$");
/**
* Check the index name part (not the user id part, if any) of the specified
* index name. Both indexName and indexIds may be used with this function.
*
* @param indexId the index id, possibly including user id prefix
* @return whether or not the index name part is valid
*/
public static boolean isValidIndexName(String indexId) {
return PATT_INDEXID.matcher(indexId).matches();
}
/**
* Check if this indexId is owned by a user
*
* @param indexId
* @return true if this index is owned by a user
* @throws IllegalIndexName
*/
public static boolean isUserIndex(String indexId) throws IllegalIndexName {
return getUserId(indexId) != null;
}
/**
* Check if this indexId is owned by a user. Convenience version that doesn't
* throw, as the indexId has already been verified as valid on construction.
*
* @return true if this index is owned by a user
*/
public boolean isUserIndex() {
return getUserId() != null;
}
/**
* Get the user that owns this index. Returns null if this is not a user index.
*
* @param indexId
* @return the username, or null if this is not a user index
* @throws IllegalIndexName
*/
public static String getUserId(String indexId) throws IllegalIndexName {
Matcher m = PATT_INDEXID.matcher(indexId);
if (!m.matches())
throw new IllegalIndexName("Index name " + indexId + " contains illegal characters.");
return m.group(1);
}
/**
* A version of {@link Index#getUserId(String)} that doesn't throw, as the id
* cannot be invalid.
*
* @return the username or null if this is not a user index.
*/
public String getUserId() {
Matcher m = PATT_INDEXID.matcher(this.getId());
if (!m.matches())
throw new RuntimeException();
return m.group(1);
}
public boolean userMayRead(User user) {
// Superuser can read anything
if (user.isSuperuser())
return true;
// There are no restrictions on who can read non-user (public) indices
if (!isUserIndex())
return true;
// Owner can always read their own index
if (user.getUserId().equals(getUserId()))
return true;
// Any user the index is explicitly shared with can read it too
return shareWithUsers.contains(user.getUserId());
}
private boolean authorizedForIndex(User user) {
// You are authorized (can add to, can delete) a private index if it's yours or you're the superuser
return isUserIndex() && (getUserId().equals(user.getUserId()) || user.isSuperuser());
}
public boolean userMayAddData(User user) {
return authorizedForIndex(user);
}
public boolean userMayDelete(User user) {
return authorizedForIndex(user);
}
/**
* Get the name portion of the indexId.
*
* @param indexId
* @return the indexname, never null
* @throws IllegalIndexName
*/
public static String getIndexName(String indexId) throws IllegalIndexName {
Matcher m = PATT_INDEXID.matcher(indexId);
if (!m.matches())
throw new IllegalIndexName("Index name " + indexId + " contains illegal characters.");
return m.group(2);
}
/**
* A version of {@link Index#getIndexName(String)} that doesn't throw, as the id
* cannot be invalid.
*
* @return the name of this index, never null.
*/
public String getIndexName() {
Matcher m = PATT_INDEXID.matcher(this.getId());
if (!m.matches())
throw new RuntimeException();
return m.group(2);
}
/**
* Given the base name for an index and a userId, get the corresponding unique
* indexId for the index with that name for that user.
*
* @param indexName base name of the index, will be validated
* @param userId optional user for which this index is being created, wil be
* validated if not null
* @return the id that unique identifies the index with indexName owned by the
* given user
* @throws IllegalIndexName when the result would be an illegal indexId
*/
public static String getIndexId(String indexName, String userId) throws IllegalIndexName {
String indexId = (userId == null) ? indexName : userId + ":" + indexName;
if (!isValidIndexName(indexId))
throw new IllegalIndexName("Index name " + indexId + " contains illegal characters.");
return indexId;
}
//------------------------
@Override
public boolean equals(Object obj) {
if (obj instanceof Index && ((Index) obj).getId().equals(this.getId())) {
if (!((Index) obj).getDir().equals(this.getDir()))
throw new RuntimeException("Index has same id but different directory");
return true;
}
return false;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public String toString() {
return id;
}
}
| 37.358925 | 138 | 0.644369 |
30633c5c746792e6fbc4d033514bb27502285d8b | 2,139 | package com.github.songxzj.wxpay.v2.bean.request.redpack;
import com.github.songxzj.common.annotation.Required;
import com.github.songxzj.common.exception.WxErrorException;
import com.github.songxzj.wxpay.v2.bean.request.BaseWxPayRequest;
import com.github.songxzj.wxpay.v2.bean.result.redpack.WxGetHbInfoResult;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.*;
import lombok.experimental.Accessors;
import java.util.Map;
/**
* 查询红包记录
* 普通商户
* <a href="https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_6&index=5">
* 服务商
* <a href="https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon_sl.php?chapter=13_6&index=5">
*/
@Setter
@Getter
@ToString
@EqualsAndHashCode(callSuper = true)
@Builder(builderMethodName = "newBuilder")
@NoArgsConstructor
@AllArgsConstructor
@XStreamAlias("xml")
@Accessors(chain = true)
public class WxGetHbInfoRequest extends BaseWxPayRequest<WxGetHbInfoResult> {
private static final long serialVersionUID = -6693648543917081768L;
/**
* 商户订单号
* mch_billno
* 是
* 10000098201411111234567890
* String(28)
* 商户订单号(每个订单号必须唯一)
* 组成:mch_id+yyyymmdd+10位一天内不能重复的数字
*/
@Required
@XStreamAlias("mch_billno")
private String mchBillno;
/**
* 订单类型
* bill_type
* 是
* MCHT
* String(32)
* MCHT:通过商户订单号获取红包信息。
*/
@Required
@XStreamAlias("bill_type")
private String billType;
@Override
public String[] getIgnoredParamsForSign() {
return new String[]{"sub_appid", "sub_mch_id", "sign_type"};
}
@Override
public String routing() {
return "/mmpaymkttransfers/gethbinfo";
}
@Override
public Class<WxGetHbInfoResult> getResultClass() {
return WxGetHbInfoResult.class;
}
@Override
public boolean isUseKey() {
return true;
}
@Override
protected void checkConstraints() throws WxErrorException {
}
@Override
protected void storeMap(Map<String, String> map) {
map.put("mch_billno", this.mchBillno);
map.put("bill_type", this.billType);
}
}
| 23.766667 | 98 | 0.690042 |
6b5103f51c2f0230b18d0b34b1da84f7e8be0340 | 2,742 | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdc.webseal.simulator.conf;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.openecomp.sdc.webseal.simulator.User;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Conf {
private static Conf conf= null;
private String feHost;
Map<String,User> users = new HashMap<String,User>();
private Conf(){
initConf();
}
private void initConf() {
try{
String confPath = System.getProperty("config.resource");
if (confPath == null){
System.out.println("config.resource is empty - goint to get it from config.home");
confPath = System.getProperty("config.home") + "/webseal.conf";
}
System.out.println("confPath=" + confPath );
Config confFile = ConfigFactory.parseFileAnySyntax(new File(confPath));
Config resolve = confFile.resolve();
setFeHost(resolve.getString("webseal.fe"));
List<? extends Config> list = resolve.getConfigList("webseal.users");
for (Config conf : list ){
String userId = conf.getString("userId");
String password = conf.getString("password");
String firstName = conf.getString("firstName");
String lastName = conf.getString("lastName");
String email = conf.getString("email");
String role = conf.getString("role");
users.put(userId,new User(firstName,lastName,email,userId,role,password));
}
}catch(Exception e){
e.printStackTrace();
}
}
public static Conf getInstance(){
if (conf == null){
conf = new Conf();
}
return conf;
}
public String getFeHost() {
return feHost;
}
public void setFeHost(String feHost) {
this.feHost = feHost;
}
public Map<String,User> getUsers() {
return users;
}
}
| 30.808989 | 86 | 0.623268 |
8145764843f615347a5ccd2bf1bd22e197e6641a | 1,560 | /*
* Copyright 2018-2020 The Code Department.
*
* 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.tcdng.unify.web.ui.widget.action;
import com.tcdng.unify.core.annotation.Component;
import com.tcdng.unify.core.annotation.UplAttribute;
import com.tcdng.unify.core.annotation.UplAttributes;
import com.tcdng.unify.core.upl.UplElementReferences;
import com.tcdng.unify.web.ui.widget.AbstractPageAction;
/**
* Post action.
*
* @author Lateef Ojulari
* @since 1.0
*/
@Component("ui-post")
@UplAttributes({ @UplAttribute(name = "path", type = String.class, mandatory = true),
@UplAttribute(name = "valueList", type = String[].class),
@UplAttribute(name = "validations", type = UplElementReferences.class),
@UplAttribute(name = "debounce", type = boolean.class, defaultVal = "true") })
public class PostAction extends AbstractPageAction {
public PostAction() {
super("post");
}
protected PostAction(String action) {
super(action);
}
}
| 34.666667 | 87 | 0.698077 |
39bb6ed317f1e8d509a8c9c6d67255dbb35caa2e | 308 | package Sketch.Core.Vectors;
public class Vector1D extends Vector {
public Vector1D() {
super(1);
}
public Double getX() {
return this.get(0);
}
public void setX(Double x) {
this.set(0, x);
}
public void set(Double x) {
this.setX(x);
}
}
| 14 | 38 | 0.535714 |
85cdb6fdf9d511f9b757f0ac72118b45f9be8093 | 1,226 | /*
* Decompiled with CFR 0.150.
*/
package net.minecraft.network.login.server;
import java.io.IOException;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.login.INetHandlerLoginClient;
public class S03PacketEnableCompression
implements Packet {
private int field_179733_a;
private static final String __OBFID = "CL_00002279";
public S03PacketEnableCompression() {
}
public S03PacketEnableCompression(int p_i45929_1_) {
this.field_179733_a = p_i45929_1_;
}
@Override
public void readPacketData(PacketBuffer data) throws IOException {
this.field_179733_a = data.readVarIntFromBuffer();
}
@Override
public void writePacketData(PacketBuffer data) throws IOException {
data.writeVarIntToBuffer(this.field_179733_a);
}
public void func_179732_a(INetHandlerLoginClient p_179732_1_) {
p_179732_1_.func_180464_a(this);
}
public int func_179731_a() {
return this.field_179733_a;
}
@Override
public void processPacket(INetHandler handler) {
this.func_179732_a((INetHandlerLoginClient)handler);
}
}
| 25.541667 | 71 | 0.735726 |
0ce70e3321d93aa9ea5d8115ac9e0486eb25ac2a | 717 | package jingdong;
import java.util.Arrays;
import java.util.Scanner;
/**
* @ClassName Test1
* @Description TODO
* @Author Tsenglying
* @Date 2020/8/6 14:44
* @Version 1.0
**/
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for (int i = 0; i <n ; i++) {
arr[i]=sc.nextInt();
}
System.out.println(Arrays.toString(arr));
int result= protect(arr);
System.out.println(result);
}
private static int protect(int[] arr) {
int n= arr.length;
if (n==1) return 0;
if(n==2) return 1;
return 2*n-3;
}
}
| 21.727273 | 49 | 0.549512 |
f1ba20567135fb980d4f13c5523a303f8a10d903 | 43 | package globalDay;
public class Cell {
}
| 7.166667 | 19 | 0.72093 |
afedeaf2421055fbf0b2f829b6ad971a1b98f234 | 770 | package io.virusafe.domain.document;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class QuestionnaireAnswer {
private Integer questionId;
private String questionTitle;
private String answer;
/**
* All-args constructor for QuestionnaireAnswer.
* Can be used as a Lombok builder.
*
* @param questionId the question's ID
* @param questionTitle the full question title
* @param answer the full question answer
*/
@Builder
public QuestionnaireAnswer(final Integer questionId, final String questionTitle, final String answer) {
this.questionId = questionId;
this.questionTitle = questionTitle;
this.answer = answer;
}
}
| 24.0625 | 107 | 0.706494 |
8d81b24e254e4d7dc05a27f1adba1d98c3795c3a | 788 | package dev.ebullient.micrometer.deployment;
import org.jboss.jandex.ClassInfo;
import io.quarkus.builder.item.MultiBuildItem;
final class MicrometerRegistryProviderBuildItem extends MultiBuildItem {
final Class<?> providedRegistryClass;
public MicrometerRegistryProviderBuildItem(ClassInfo provider) {
this.providedRegistryClass = null;
}
public MicrometerRegistryProviderBuildItem(Class<?> providedRegistryClass) {
this.providedRegistryClass = providedRegistryClass;
}
public Class<?> getProvidedRegistryClass() {
return providedRegistryClass;
}
@Override
public String toString() {
return "MicrometerRegistryProviderBuildItem{"
+ providedRegistryClass.getName()
+ '}';
}
}
| 26.266667 | 80 | 0.715736 |
18b6d0640b7d6a97ebe09f631998f85877852ca2 | 7,340 | package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Strings;
import com.saleem.utils.HTTPSUtils;
import com.saleem.utils.HibernateUtil;
import models.UserProfile;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import javax.persistence.EntityManager;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
public class LoginController extends Controller {
public Result Register(Http.Request request) {
JsonNode node = request.body().asJson();
String email = node.get("email").textValue();
String password = node.get("password").textValue();
String firstname = node.get("firstname").textValue();
String lastname = node.get("lastname").textValue();
SessionFactory sessionFactory = HibernateUtil.getSession();
Session session = sessionFactory.getCurrentSession();
EntityManager em = sessionFactory.createEntityManager();
em.getTransaction().begin();
List<UserProfile> g = em.createQuery("select g from UserProfile g where email = :email", UserProfile.class)
.setParameter("email", email)
.getResultList();
if (g.size() > 0) {
return badRequest("Email is already in use.");
} else {
String hashedPassword = HashPassword(password);
UserProfile userProfile = new UserProfile(firstname, lastname, email, hashedPassword);
session.beginTransaction();
session.save(userProfile);
session.getTransaction().commit();
session.close();
return ok();
}
}
public Result Login(Http.Request request) {
JsonNode node = request.body().asJson();
String bodyPassword = node.get("password").textValue();
String email = node.get("email").textValue();
String hash = HashPassword(bodyPassword);
SessionFactory sessionFactory = HibernateUtil.getSession();
EntityManager em = sessionFactory.createEntityManager();
em.getTransaction().begin();
Long count = em.createQuery("select count(u) from UserProfile u where email = :email", Long.class)
.setParameter("email", email)
.getSingleResult();
if (count > 0) {
String userPassword = em.createQuery("select password from UserProfile g where email = :email", String.class)
.setParameter("email", email)
.getSingleResult();
em.close();
if (userPassword.equals(hash)) {
return ok();
} else {
return status(422); // Input was valid but account does not exist
}
} else {
return status(422);
}
}
public Result validateSession(String token) {
if (HTTPSUtils.IsSessionValid(token)) return ok();
else return forbidden();
}
public Result GetUserInfo(String token) {
String email = HTTPSUtils.GetEmailFromToken(token);
SessionFactory sessionFactory = HibernateUtil.getSession();
EntityManager em = sessionFactory.createEntityManager();
em.getTransaction().begin();
UserProfile profile = em.createQuery("select u from UserProfile u where email = :email", UserProfile.class)
.setParameter("email", email)
.getSingleResult();
em.close();
if (profile != null) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("id", profile.getId());
node.put("firstName", profile.getFirstname());
node.put("lastName", profile.getLastname());
node.put("email", profile.getEmail());
node.put("password", profile.getPassword());
return ok(node);
} else {
return notFound();
}
}
public Result UpdateUserInfo(Http.Request request) {
JsonNode node = request.body().asJson();
Long userId = node.get("id").asLong();
boolean hasPasswordChanged = false;
SessionFactory sessionFactory = HibernateUtil.getSession();
EntityManager em = sessionFactory.createEntityManager();
em.getTransaction().begin();
UserProfile profile = em.createQuery("select u from UserProfile u where id = :id", UserProfile.class)
.setParameter("id", userId)
.getSingleResult();
profile.setFirstname(node.get("firstName").textValue());
profile.setLastname(node.get("lastName").textValue());
em.createQuery("update UserProfile u set u.firstname = :firstName, u.lastname = :lastName where u.id = :userId")
.setParameter("userId", userId)
.setParameter("firstName", node.get("firstName").textValue())
.setParameter("lastName", node.get("lastName").textValue());
if (!Strings.isNullOrEmpty(node.get("oldPassword").textValue())
&& !Strings.isNullOrEmpty(node.get("newPassword").textValue())
&& !Strings.isNullOrEmpty(node.get("newPasswordRepeat").textValue())
) {
String oldPasswordHashed = HashPassword(node.get("oldPassword").textValue());
if (profile.getPassword().equals(oldPasswordHashed)) {
if (node.get("newPassword").textValue().equals(node.get("newPasswordRepeat").textValue())) {
String newHashedPassword = HashPassword(node.get("newPassword").textValue());
profile.setPassword(newHashedPassword);
hasPasswordChanged = true;
em.createQuery("update UserProfile u set u.password = :password where u.id = :userId")
.setParameter("userId", userId)
.setParameter("password", newHashedPassword);
} else {
return badRequest("De nieuwe wachtwoorden komen niet overeen");
}
} else {
return badRequest("Het oude wachtwoord komt niet overeen");
}
}
em.getTransaction().commit();
em.close();
return hasPasswordChanged ? ok("Gegevens opgeslagen") : ok("Gegevens opgeslagen, wachtwoord ongewijzigd");
}
public static String HashPassword(String password) {
String hashedPassword = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(password.getBytes(StandardCharsets.UTF_8));
byte[] bytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte aByte : bytes) {
sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
}
hashedPassword = sb.toString();
} catch (NoSuchAlgorithmException e) {
System.out.println("ERROR: " + e);
e.printStackTrace();
}
return hashedPassword;
}
}
| 37.258883 | 121 | 0.611853 |
007a930f0443f79ab444546a7cf5c92ae045a027 | 1,337 | package fedata.gba.fe7;
import fedata.gba.GBAFEChapterItemData;
public class FE7ChapterTargetedItem implements GBAFEChapterItemData {
private byte[] originalData;
private byte[] data;
private long originalOffset;
private Boolean wasModified = false;
private Boolean hasChanges = false;
public FE7ChapterTargetedItem(byte[] data, long originalOffset) {
super();
this.originalData = data;
this.data = data;
this.originalOffset = originalOffset;
}
@Override
public void resetData() {
wasModified = false;
data = originalData;
}
@Override
public void commitChanges() {
if (wasModified) {
hasChanges = true;
}
wasModified = false;
}
@Override
public byte[] getData() {
return data;
}
@Override
public Boolean hasCommittedChanges() {
return hasChanges;
}
@Override
public Boolean wasModified() {
return wasModified;
}
@Override
public long getAddressOffset() {
return originalOffset;
}
@Override
public Type getRewardType() {
if (data[0] == 0x5C) { return Type.ITGC; }
return data[0] == 0x5B ? Type.ITGV : Type.CHES;
}
public int getTargetID() {
return data[4] & 0xFF;
}
@Override
public int getItemID() {
return data[8] & 0xFF;
}
@Override
public void setItemID(int newItemID) {
data[8] = (byte)(newItemID & 0xFF);
wasModified = true;
}
}
| 16.924051 | 69 | 0.694091 |
24c2ac69637723e31a3cf538ebab513d3b8840fd | 2,951 | import grid.graph.GridGraph;
import grid.logic.LogicStatus;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class BlackConnectedLogicStep implements grid.logic.LogicStep<Board> {
private static class MyReference implements GridGraph.GridReference {
Board b;
Set<Point> blackset = new HashSet<>();
public MyReference(Board b,Point art) { this.b = b; }
@Override public int getWidth() { return b.getWidth(); }
@Override public int getHeight() { return b.getHeight(); }
@Override public boolean edgeExitsEast(int x, int y) { return true; }
@Override public boolean edgeExitsSouth(int x, int y) { return true; }
@Override public boolean isIncludedCell(int x, int y) {
if (!b.onBoard(x,y)) return false;
if (b.getCell(x,y) == CellType.BLACK) blackset.add(new Point(x,y));
return b.getCell(x,y) != CellType.WHITE;
}
}
private static class SecondReference implements GridGraph.GridReference {
Board b;
Set<Point> blackset;
public SecondReference(Board b,Set<Point> blackset) { this.b = b; this.blackset = blackset; }
@Override public int getWidth() { return b.getWidth(); }
@Override public int getHeight() { return b.getHeight(); }
@Override public boolean edgeExitsEast(int x, int y) { return true; }
@Override public boolean edgeExitsSouth(int x, int y) { return true; }
@Override public boolean isIncludedCell(int x,int y) {
return blackset.contains(new Point(x,y));
}
}
@Override public LogicStatus apply(Board thing) {
MyReference myr = new MyReference(thing,null);
GridGraph maingg = new GridGraph(myr);
Set<Point> blackconset = null;
for(Point p : myr.blackset) {
Set<Point> conset = maingg.connectedSetOf(p);
if (blackconset != null && blackconset != conset) return LogicStatus.CONTRADICTION;
blackconset = conset;
}
// if we get here, all black cells are in the same connected set.
LogicStatus result = LogicStatus.STYMIED;
SecondReference sr = new SecondReference(thing,blackconset);
GridGraph artgg = new GridGraph(sr);
for (Point p : artgg.getArticulationPoints()) {
if (thing.getCell(p.x,p.y) == CellType.BLACK) continue;
List<Set<Point>> arts = artgg.getArticulationSet(p);
List<Set<Point>> blackarts = new ArrayList<>();
for (Set<Point> art : arts) {
if (art.stream().anyMatch(sp->thing.getCell(sp.x,sp.y) == CellType.BLACK)) blackarts.add(art);
}
if (blackarts.size() > 1) {
thing.setCell(p.x,p.y,CellType.BLACK);
result = LogicStatus.LOGICED;
}
}
return result;
}
}
| 38.828947 | 110 | 0.620468 |
e9292da73c32a7f6803d132162c7eafb1931159f | 963 | package server;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class ThreadHandler implements Runnable {
private Socket client;
public ThreadHandler(Socket client){
this.client = client;
}
@Override
public void run() {
try {
//Streams
//an den Client
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
//an den Server
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//Nachricht vom Client ausgeben
String s = null;
while((s = reader.readLine())!=null) {
writer.write(s+"\n");
writer.flush();
System.out.println("Vom Client empfangen: "+s);
}
writer.close();
reader.close();
client.close();
}catch (Exception e) {
}
}
}
| 18.882353 | 73 | 0.672897 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.