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
|
---|---|---|---|---|---|
1c081bce13191a4a385e96bf8daa5fa5575bbed0 | 490 | package cb.test;
public class User {
private String userName;
private String userPass;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
@Override
public String toString() {
return "User [userName=" + userName + ", userPass=" + userPass + "]";
}
}
| 19.6 | 72 | 0.661224 |
d9bf3fccc23b27855995aa512b27d264d2c0f3e9 | 1,875 | package com.croquis.crary.restclient.gson;
import android.test.AndroidTestCase;
import com.google.gson.JsonArray;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import java.util.Date;
public class BuilderTest extends AndroidTestCase {
public void testObjectBuilder() {
JsonObject json = new JsonObjectBuilder()
.add("a", 1)
.add("b", "str")
.add("c", true)
.add("d", JsonNull.INSTANCE)
.add("e", new Date(Date.UTC(114, 10, 25, 14, 10, 15)))
.build();
assertEquals(1, json.get("a").getAsInt());
assertEquals("str", json.get("b").getAsString());
assertEquals(true, json.get("c").getAsBoolean());
assertTrue(json.get("d").isJsonNull());
assertEquals("2014-11-25T14:10:15.000Z", json.get("e").getAsString());
}
public void testArrayBuilder() {
JsonArray json = new JsonArrayBuilder()
.add(1)
.add("str")
.add(true)
.add(JsonNull.INSTANCE)
.add(new Date(Date.UTC(114, 10, 25, 14, 10, 15)))
.build();
assertEquals(1, json.get(0).getAsInt());
assertEquals("str", json.get(1).getAsString());
assertEquals(true, json.get(2).getAsBoolean());
assertTrue(json.get(3).isJsonNull());
assertEquals("2014-11-25T14:10:15.000Z", json.get(4).getAsString());
}
public void testMix() {
JsonObject json = new JsonObjectBuilder()
.add("names", new JsonArrayBuilder()
.add("croquis")
.add("hello")
.add("world")
.build())
.build();
assertEquals("{\"names\":[\"croquis\",\"hello\",\"world\"]}", json.toString());
}
}
| 35.377358 | 87 | 0.530133 |
0418ec0c37f3d5e7ed9310dab257fbb8df6b10e1 | 3,792 | package de.sambalmueslie.wot_api_lib.strongholds_api.response;
import java.util.Map;
import de.sambalmueslie.wot_api_lib.common.BaseWotResponse;
public class StrongholdInfoResponse extends BaseWotResponse {
public class StrongholdBuilding {
public String getDirectionName() {
return direction_name;
}
public long getLevel() {
return level;
}
public long getType() {
return type;
}
private String direction_name;
private long level;
private long type;
}
public class StrongholdDefense {
public int getAttacksCount() {
return attacks_count;
}
public int getAttacksEfficiency() {
return attacks_efficiency;
}
public int getAttacksWins() {
return attacks_wins;
}
public int getBattlesCount() {
return battles_count;
}
public int getBattlesWinPercentage() {
return battles_win_percentage;
}
public int getBattlesWins() {
return battles_wins;
}
public int getCaptureBasesCount() {
return capture_bases_count;
}
public int getCaptureBuildingsCount() {
return capture_buildings_count;
}
public int getCaptureResourcesCount() {
return capture_resources_count;
}
public int getClashesCount() {
return clashes_count;
}
public int getClashesWinPercentage() {
return clashes_win_percentage;
}
public int getClashesWins() {
return clashes_wins;
}
public int getDefensesCount() {
return defenses_count;
}
public int getDefensesEfficiency() {
return defenses_efficiency;
}
public int getDefensesWins() {
return defenses_wins;
}
public int getLossBasesCount() {
return loss_bases_count;
}
public int getLossBuildingsCount() {
return loss_buildings_count;
}
public int getLossResourcesCount() {
return loss_resources_count;
}
private int attacks_count;
private int attacks_efficiency;
private int attacks_wins;
private int battles_count;
private int battles_win_percentage;
private int battles_wins;
private int capture_bases_count;
private int capture_buildings_count;
private int capture_resources_count;
private int clashes_count;
private int clashes_win_percentage;
private int clashes_wins;
private int defenses_count;
private int defenses_efficiency;
private int defenses_wins;
private int loss_bases_count;
private int loss_buildings_count;
private int loss_resources_count;
}
public class StrongholdInfoEntry {
public Map<String, StrongholdBuilding> getBuildings() {
return buildings;
}
public long getClanId() {
return clan_id;
}
public StrongholdDefense getDefense() {
return defense;
}
public int getDirectionsCount() {
return directions_count;
}
public int getLevel() {
return level;
}
public StrongholdSkirmish getSkirmish() {
return skirmish;
}
public boolean isDefenseModeActivated() {
return defense_mode_is_activated;
}
private Map<String, StrongholdBuilding> buildings;
private long clan_id;
private StrongholdDefense defense;
private boolean defense_mode_is_activated;
private int directions_count;
private int level;
private StrongholdSkirmish skirmish;
}
public class StrongholdSkirmish {
public int getBattlesCount() {
return battles_count;
}
public int getBattlesWinPercentage() {
return battles_win_percentage;
}
public int getBattlesWins() {
return battles_wins;
}
private int battles_count;
private int battles_win_percentage;
private int battles_wins;
}
public Map<String, StrongholdInfoEntry> getData() {
return data;
}
private Map<String, StrongholdInfoEntry> data;
}
| 20.835165 | 63 | 0.710707 |
a746243686032a3104a46c9ae348bcd2ec04356d | 459 | package cn.ts.rpc.upms.api;
import cn.ts.core.mybatis.BaseService;
import cn.ts.rpc.upms.model.UpmsUser;
import cn.ts.rpc.upms.model.UpmsUserExample;
/**
* UpmsUserService接口
*
* @author Created by YL on 2017/4/27.
*/
public interface UpmsUserService extends BaseService<UpmsUser, UpmsUserExample> {
/**
* 根据 userName 获取 UpmsUser
*
* @param userName 用户帐号
* @return
*/
UpmsUser selectUpmsUserByUsername(String userName);
} | 22.95 | 81 | 0.703704 |
ee41e293142e8259911b5732b3cb59e7b6432044 | 334 | package com.mohammedatif.medium.lombok.builder;
import com.mohammedatif.medium.lombok.data.HumanName;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class UserInfo {
private HumanName humanName;
private int age;
private Gender gender;
@Builder.Default
private boolean isActive = true;
}
| 17.578947 | 53 | 0.757485 |
9201b60df5cb21c4b1bd49f7da55ed85d07066cf | 4,729 | package ru.moneyshar.site.config;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import ru.moneyshar.site.auth.UserAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;
/**
* Security
* Created with IntelliJ IDEA.
* User: rfk
* Date: 16.07.14
* Time: 21:29
* To change this template use File | Settings | File Templates.
*/
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// @Autowired
// private UserAuthenticationProvider userAuthenticationProvider;
/* @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(userAuthenticationProvider);
}*/
@Bean(name = "ocuAuthenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/*@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("t@t").password("t").roles("USER", "ADMIN");
auth.inMemoryAuthentication()
.withUser("t@t").password("t").roles("USER", "ADMIN");
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// HttpSessionCsrfTokenRepository csrfTokenRepository = new HttpSessionCsrfTokenRepository();
http
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**", "/webjars/**")
.permitAll()
.anyRequest()
.authenticated()
.and().logout().logoutSuccessUrl("/").permitAll();
/* http.formLogin().permitAll().loginPage("/login").failureUrl("/login?error")
.usernameParameter("email").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout");*/
http.csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
private AntPathRequestMatcher apiMatcher = new AntPathRequestMatcher("/api*//**");
@Override
public boolean matches(HttpServletRequest request) {
// No CSRF due to allowedMethod
if (allowedMethods.matcher(request.getMethod()).matches()) {
return false;
}
// No CSRF due to api call
if (apiMatcher.matches(request)) {
return false;
}
// CSRF for everything else that is not an API call or an allowedMethod
return true;
}
});
/*http.csrf().requireCsrfProtectionMatcher(new NegatedRequestMatcher(
new AntPathRequestMatcher("/api*//**")
));*/
// .and().csrf().csrfTokenRepository(csrfTokenRepository);
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setForceEncoding(true);
filter.setEncoding("UTF-8");
http.addFilterBefore(filter, CsrfFilter.class);
http.logout().deleteCookies("JSESSIONID");
http.exceptionHandling().accessDeniedPage("/errors/403");
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
// Spring Security should completely ignore URLs starting with /resources/
.antMatchers("/resources/**")
.antMatchers("/static/**")
;
}
} | 37.531746 | 107 | 0.675619 |
b30d888dc5b8c4e457f0d77aae3ce15fc97f24f3 | 2,176 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.persistence;
import java.io.File;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.DiskWriteAttributesFactory;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.Scope;
import org.apache.geode.test.junit.categories.PersistenceTest;
@Category(PersistenceTest.class)
@SuppressWarnings("serial")
public class PersistentRecoveryOrderOldConfigDUnitTest extends PersistentRecoveryOrderDUnitTest {
/**
* Override to use deprecated APIs for the creation of disk and region. This test class can
* probably be deleted.
*/
@Override
@SuppressWarnings("deprecation")
protected void createReplicateRegion(String regionName, File[] diskDirs,
boolean diskSynchronous) {
getCache();
DiskWriteAttributesFactory diskWriteAttributesFactory = new DiskWriteAttributesFactory();
diskWriteAttributesFactory.setMaxOplogSize(1);
diskWriteAttributesFactory.setSynchronous(diskSynchronous);
RegionFactory regionFactory = new RegionFactory();
regionFactory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
regionFactory.setScope(Scope.DISTRIBUTED_ACK);
regionFactory.setDiskDirs(diskDirs);
regionFactory.setDiskWriteAttributes(diskWriteAttributesFactory.create());
regionFactory.create(regionName);
}
}
| 39.563636 | 100 | 0.79136 |
c5efaab9b3a23901ec38a2e31d96be8f54d409a0 | 1,444 | package com.luv2code.java14.elearning.controller.user;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.luv2code.java14.elearning.dto.UpdateUserDTO;
import com.luv2code.java14.elearning.dto.UserDTO;
public interface UserController {
@GetMapping(value="/user")
public ResponseEntity<Object> findAllUser();
@GetMapping(value="/user/{userId}")
public ResponseEntity<Object> getUser(
@PathVariable("userId") int id
);
@PostMapping(value="/user")
// @PostMapping(value="/sign-up")
public ResponseEntity<Object> createUser(
@Valid @RequestBody UserDTO userDTO,
BindingResult bindingResult
);
@PutMapping(value="/user/{userId}")
public ResponseEntity<Object> updateUser(
@PathVariable("userId") int id,
@Valid @RequestBody UpdateUserDTO updateUserDTO,
BindingResult bindingResult
);
@DeleteMapping(value="/user/{userId}")
public ResponseEntity<Object> deleteUser(
@PathVariable("userId") int id
);
}
| 30.723404 | 61 | 0.786011 |
0ff577411cd25aaf9fec7c95f077f844c7e5c609 | 13,289 | package edu.rutgers.css.Rutgers.api.bus;
import android.location.Location;
import android.support.annotation.NonNull;
import com.google.gson.JsonSyntaxException;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import edu.rutgers.css.Rutgers.Config;
import edu.rutgers.css.Rutgers.api.ApiRequest;
import edu.rutgers.css.Rutgers.api.ParseException;
import edu.rutgers.css.Rutgers.api.bus.model.ActiveStops;
import edu.rutgers.css.Rutgers.api.bus.model.AgencyConfig;
import edu.rutgers.css.Rutgers.api.bus.model.Prediction;
import edu.rutgers.css.Rutgers.api.bus.model.Predictions;
import edu.rutgers.css.Rutgers.api.bus.model.route.Route;
import edu.rutgers.css.Rutgers.api.bus.model.route.RouteStub;
import edu.rutgers.css.Rutgers.api.bus.model.stop.Stop;
import edu.rutgers.css.Rutgers.api.bus.model.stop.StopGroup;
import edu.rutgers.css.Rutgers.api.bus.model.stop.StopStub;
import edu.rutgers.css.Rutgers.api.bus.parsers.AgencyConfigDeserializer;
import edu.rutgers.css.Rutgers.api.bus.parsers.PredictionXmlParser;
import static edu.rutgers.css.Rutgers.utils.LogUtils.LOGV;
import static edu.rutgers.css.Rutgers.utils.LogUtils.LOGW;
/**
* Provides static methods for access to the Nextbus API.
* Uses nextbusjs data to create requests against the official Nextbus API.
*/
public final class NextbusAPI {
private static final String TAG = "NextbusAPI";
private static AgencyConfig sNBConf;
private static AgencyConfig sNWKConf;
private static ActiveStops sNBActive;
private static ActiveStops sNWKActive;
private static final String BASE_URL = "http://webservices.nextbus.com/service/publicXMLFeed?command=";
private static final int activeExpireTime = 10; // active bus data cached ten minutes
private static final TimeUnit activeTimeUnit = TimeUnit.MINUTES;
private static final int configExpireTime = 1; // config data cached one hour
private static final TimeUnit configTimeUnit = TimeUnit.HOURS;
public static final String AGENCY_NB = "nb";
public static final String AGENCY_NWK = "nwk";
/** This class only contains static utility methods. */
private NextbusAPI() {}
/**
* Load agency configurations and lists of active routes/stops for each campus.
*/
private static synchronized void setup () throws JsonSyntaxException, IOException {
sNBActive = ApiRequest.api("nbactivestops.txt", activeExpireTime, activeTimeUnit, ActiveStops.class);
sNBActive.setAgencyTag(AGENCY_NB);
sNWKActive = ApiRequest.api("nwkactivestops.txt", activeExpireTime, activeTimeUnit, ActiveStops.class);
sNWKActive.setAgencyTag(AGENCY_NWK);
sNBConf = ApiRequest.api("rutgersrouteconfig.txt", configExpireTime, configTimeUnit, AgencyConfig.class,
new AgencyConfigDeserializer(AGENCY_NB));
sNWKConf = ApiRequest.api("rutgers-newarkrouteconfig.txt", configExpireTime, configTimeUnit, AgencyConfig.class,
new AgencyConfigDeserializer(AGENCY_NWK));
}
public static synchronized boolean validRoute(@NonNull final String agency, @NonNull final String routeKey) {
try {
setup();
AgencyConfig conf = AGENCY_NB.equals(agency) ? sNBConf : sNWKConf;
final Route route = conf.getRoutes().get(routeKey);
return route != null;
} catch (JsonSyntaxException | IOException ignored) {
return false;
}
}
public static synchronized boolean validStop(@NonNull final String agency, @NonNull final String routeKey) {
try {
setup();
AgencyConfig conf = AGENCY_NB.equals(agency) ? sNBConf : sNWKConf;
final Stop stop = conf.getStops().get(routeKey);
return stop != null;
} catch (JsonSyntaxException | IOException ignored) {
return false;
}
}
/**
* Get arrival time predictions for every stop on a route.
* @param agency Agency (campus) that the route belongs to.
* @param routeKey Route to get predictions for.
* @return Promise for list of arrival time predictions.
*/
public static synchronized Predictions routePredict(@NonNull final String agency, @NonNull final String routeKey) throws JsonSyntaxException, ParseException, IOException {
setup();
LOGV(TAG, "routePredict: " + agency + ", " + routeKey);
// Get agency configuration
AgencyConfig conf = AGENCY_NB.equals(agency) ? sNBConf : sNWKConf;
// Start building Nextbus query with predictionsForMultiStops command
// Returns predictions for a set of route/stop combinations. Direction is optional and can be null.
StringBuilder queryBuilder = new StringBuilder(BASE_URL + "predictionsForMultiStops&a=rutgers");
// Find route in agency config, and get its stop tags
final Route route = conf.getRoutes().get(routeKey);
if (route == null) {
throw new IllegalArgumentException("Invalid route tag \""+routeKey+"\"");
}
for (String stopTag: route.getStopTags()) {
// multiple 'stops' parameters, these are: routeTag|dirTag|stopId
queryBuilder.append("&stops=").append(routeKey).append("%7Cnull%7C").append(stopTag);
}
// Run the query we built and sort the prediction results
Predictions predictions = ApiRequest.xml(queryBuilder.toString(), new PredictionXmlParser(PredictionXmlParser.PredictionType.ROUTE));
Collections.sort(predictions.getPredictions(), new Comparator<Prediction>() {
@Override
public int compare(@NonNull Prediction p1, @NonNull Prediction p2) {
return route.getStopTags().indexOf(p1.getTag()) - route.getStopTags().indexOf(p2.getTag());
}
});
return predictions;
}
/**
* Get arrival time predictions for every route going through a stop.
* @param agency Agency (campus) that the stop belongs to.
* @param stopTitleKey Full title of the stop to get predictions for.
* @return Promise for list of arrival time predictions.
*/
public static synchronized Predictions stopPredict(@NonNull final String agency, @NonNull final String stopTitleKey) throws JsonSyntaxException, ParseException, IOException {
setup();
LOGV(TAG, "stopPredict: " + agency + ", " + stopTitleKey);
// Get agency configuration
AgencyConfig conf = AGENCY_NB.equals(agency) ? sNBConf : sNWKConf;
StringBuilder queryBuilder = new StringBuilder(BASE_URL + "predictionsForMultiStops&a=rutgers");
// Get group of stop IDs by stop title
StopGroup stopsByTitle = conf.getStopsByTitle().get(stopTitleKey);
if (stopsByTitle == null) {
throw new IllegalArgumentException("Invalid stop tag \""+stopTitleKey+"\"");
}
// For every stop tag with the given stop title, get all its routes
for (String stopTag: stopsByTitle.getStopTags()) {
Stop stop = conf.getStops().get(stopTag);
if (stop == null) {
throw new IllegalArgumentException("Stop tag \""+stopTag+"\" in stopsByTitle but not stops");
}
// Then use the route tags to build the query
for (String routeTag: stop.getRouteTags()) {
// multiple 'stops' parameters, these are: routeTag|dirTag|stopId
queryBuilder.append("&stops=").append(routeTag).append("%7Cnull%7C").append(stopTag);
}
}
// Run the query we built and sort the prediction results
Predictions predictions = ApiRequest.xml(queryBuilder.toString(), new PredictionXmlParser(PredictionXmlParser.PredictionType.STOP));
Collections.sort(predictions.getPredictions(), new Comparator<Prediction>() {
@Override
public int compare(@NonNull Prediction p1, @NonNull Prediction p2) {
int res = p1.getTitle().compareTo(p2.getTitle());
if (res == 0) {
return p1.getDirection().compareTo(p2.getDirection());
}
return res;
}
});
return predictions;
}
/**
* Get active routes for an agency.
* @param agency Agency (campus) to get active routes for.
* @return Promise for list of route stubs (tags and titles).
*/
public static synchronized List<RouteStub> getActiveRoutes(@NonNull final String agency) throws JsonSyntaxException, IOException {
setup();
ActiveStops active = AGENCY_NB.equals(agency) ? sNBActive : sNWKActive;
return active.getRoutes();
}
/**
* Get all routes from an agency's configuration.
* @param agency Agency (campus) to get all routes for.
* @return Promise for list of route stubs (tags and titles).
*/
public static synchronized List<RouteStub> getAllRoutes(@NonNull final String agency) throws JsonSyntaxException, IOException {
setup();
AgencyConfig conf = AGENCY_NB.equals(agency) ? sNBConf : sNWKConf;
return conf.getSortedRoutes();
}
/**
* Get active stops for an agency.
* @param agency Agency (campus) to active stops for.
* @return Promise for list of stop stubs (titles and geohashes).
*/
public static synchronized List<StopStub> getActiveStops(@NonNull final String agency) throws JsonSyntaxException, IOException {
setup();
ActiveStops active = AGENCY_NB.equals(agency) ? sNBActive : sNWKActive;
return active.getStops();
}
/**
* Get all stops from an agency's configuration.
* @param agency Agency (campus) to get all stops for.
* @return Promise for list of stop stubs (titles and geohashes).
*/
public static synchronized List<StopStub> getAllStops(@NonNull final String agency) throws JsonSyntaxException, IOException {
setup();
AgencyConfig conf = AGENCY_NB.equals(agency) ? sNBConf : sNWKConf;
return conf.getSortedStops();
}
/**
* Get all bus stops (grouped by title) near a specific location.
* @param agency Agency (campus) to get stops for.
* @param sourceLat Latitude
* @param sourceLon Longitude
* @return Promise for list of stop groups (unique stops grouped by title).
*/
public static synchronized List<StopGroup> getStopsByTitleNear(@NonNull final String agency, final double sourceLat, final double sourceLon) throws JsonSyntaxException, IOException {
setup();
AgencyConfig conf = AGENCY_NB.equals(agency) ? sNBConf : sNWKConf;
HashMap<String, StopGroup> stopsByTitle = conf.getStopsByTitle();
List<StopGroup> nearStops = new ArrayList<>();
// Loop through stop groups
for (StopGroup stopGroup: stopsByTitle.values()) {
// TODO Decode the geohash into long/lat and just compare with that
// Get stop data for each stop tag and check the distance.
for (String stopTag: stopGroup.getStopTags()) {
Stop stop = conf.getStops().get(stopTag);
if (stop == null) {
LOGW(TAG, "Stop tag \""+stopTag+"\" found in stopsByTitle not in stops");
continue; // Check next tag
}
// Calculate distance to stop
double stopLat = Double.parseDouble(stop.getLatitude());
double stopLon = Double.parseDouble(stop.getLongitude());
float[] results = new float[1];
Location.distanceBetween(sourceLat, sourceLon, stopLat, stopLon, results);
if (results[0] < Config.NEARBY_RANGE) {
nearStops.add(stopGroup);
break; // Skip to next group
}
}
}
return nearStops;
}
/**
* Get all active bus stops (grouped by title) near a specific location.
* @param agency Agency (campus) to get stops for.
* @param sourceLat Latitude
* @param sourceLon Longitude
* @return Promise for list of stop groups (unique stops grouped by title).
*/
public static synchronized List<StopGroup> getActiveStopsByTitleNear(final String agency, final float sourceLat, final float sourceLon) throws JsonSyntaxException, IOException {
setup();
final List<StopGroup> nearbyStops = getStopsByTitleNear(agency, sourceLat, sourceLon);
final ActiveStops active = AGENCY_NB.equals(agency) ? sNBActive : sNWKActive;
List<StopGroup> results = new ArrayList<>();
for (StopGroup stopGroup : nearbyStops) {
String stopTitle = stopGroup.getTitle();
// Try to find this stop in list of active stops
for (StopStub activeStopStub : active.getStops()) {
if (StringUtils.equals(stopTitle, activeStopStub.getTitle())) {
results.add(stopGroup); // Found: it's active
}
}
}
return results;
}
}
| 43.006472 | 186 | 0.665513 |
5abb28892e05fab130b9ef214ac1185d39dd46f8 | 7,180 | package services;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public final class ParameterService {
private static final Logger LOGGER = LogManager.getLogger();
private static Map<String, String> scDictionary = new HashMap<>();
private static final String ENCRYPT_KEY = "KeyGeneratedByJesusLNV";
private ParameterService() {
}
/**
* @param parameterName Is the name of the parameter to be stored
* @param parameterValue Is the value of the parameter to be stored
*/
public static void setParameter(String parameterName, String parameterValue) {
scDictionary.put(parameterName, parameterValue);
}
/**
* @param parameterName Is the name of the parameter to be retrieved
* @return Returns the value of the parameter
*/
public static String getParameter(String parameterName) {
return scDictionary.get(parameterName);
}
/**
* @param stringToEncrypt Is the name of the String to be encrypted
* @return Returns the String encrypted
*/
public static String encryptString(String stringToEncrypt) {
String stringEncrypted = null;
try {
SecretKeySpec secretKeySpec = createCustomSecretKeySpec();
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(stringToEncrypt.getBytes(StandardCharsets.UTF_8));
stringEncrypted = Base64.getEncoder().encodeToString(encrypted);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
LOGGER.error("Error while encrypting: {}", ex.getMessage());
}
return stringEncrypted;
}
/**
* @param stringToDecrypt Is the name of the String to be decrypted
* @return Returns the String decrypted
*/
public static String decryptString(String stringToDecrypt) {
String stringDecrypted = null;
try {
SecretKeySpec secretKeySpec = createCustomSecretKeySpec();
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = Base64.getDecoder().decode(stringToDecrypt);
stringDecrypted = new String(cipher.doFinal(decrypted));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
LOGGER.error("Error while decrypting: {}", ex.getMessage());
}
return stringDecrypted;
}
private static SecretKeySpec createCustomSecretKeySpec() {
SecretKeySpec secretKeySpec = null;
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] tmpKey = messageDigest.digest(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8));
tmpKey = Arrays.copyOf(tmpKey, 16);
secretKeySpec = new SecretKeySpec(tmpKey, "AES");
} catch (NoSuchAlgorithmException ex) {
LOGGER.error("Error creating Custom Key Spec: {}", ex.getMessage());
}
return secretKeySpec;
}
/**
* @param url Is the URL from the API to be tested
* @param headers Are the Headers from the API to be tested
* @return Returns the response from requested Service
*/
public static HttpResponse requestGetService(String url, Map<String, String> headers) {
HttpGet httpGet = new HttpGet(url);
for (Map.Entry<String, String> header : headers.entrySet()) {
httpGet.addHeader(header.getKey(), header.getValue());
}
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
LOGGER.info("Starting HttpGet Service Test for API: " + url);
return httpClient.execute(httpGet);
} catch (IOException e) {
LOGGER.error(e.getMessage());
return null;
}
}
/**
* @param url Is the URL from the API to be tested
* @param headers Are the Headers from the API to be tested
* @param bodyFileLocation Is the Body File location to use
* @return Returns the response from requested Service
*/
public static HttpResponse requestPostService(String url, Map<String, String> headers, String bodyFileLocation) {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, String> header : headers.entrySet()) {
httpPost.addHeader(header.getKey(), header.getValue());
}
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String body = new String(Files.readAllBytes(Paths.get(bodyFileLocation)));
StringEntity stringEntity = new StringEntity(body);
httpPost.setEntity(stringEntity);
LOGGER.info("Starting HttpPost Service Test for API: " + url);
return httpClient.execute(httpPost);
} catch (IOException e) {
LOGGER.error(e.getMessage());
return null;
}
}
/**
* @param url Is the URL from the API to be tested
* @param headers Are the Headers from the API to be tested
* @param bodyFileLocation Is the Body File location to use
* @return Returns the response from requested Service
*/
public static HttpResponse requestPutService(String url, Map<String, String> headers, String bodyFileLocation) {
HttpPut httpPut = new HttpPut(url);
for (Map.Entry<String, String> header : headers.entrySet()) {
httpPut.addHeader(header.getKey(), header.getValue());
}
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String body = new String(Files.readAllBytes(Paths.get(bodyFileLocation)));
StringEntity stringEntity = new StringEntity(body);
httpPut.setEntity(stringEntity);
LOGGER.info("Starting HttpPut Service Test for API: " + url);
return httpClient.execute(httpPut);
} catch (IOException e) {
LOGGER.error(e.getMessage());
return null;
}
}
} | 42.994012 | 144 | 0.676045 |
c39d05f20b2ef7985f9cf3150b4950b592bd5b8e | 792 | package bg.galaxy.nuggetsconsumer.service;
import bg.galaxy.nuggetsconsumer.repository.NuggetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by George-Lenovo on 28/03/2018.
*/
@Service
@Transactional
public class NuggetService implements INuggetService{
private final NuggetRepository nuggetRepository;
@Autowired
public NuggetService(NuggetRepository nuggetRepository) {
this.nuggetRepository = nuggetRepository;
}
@Override
public List<String> findByName(String username) {
return this.nuggetRepository.
findByName(username.replace(",", "|"));
}
}
| 26.4 | 64 | 0.760101 |
83ff0cea1b179eeec680aa2c520255b18e1166c4 | 1,478 | package com.github.mubbo.core;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
public class Presetter {
private static final String presetDirectory = "./presets";
static void exportPreset(Symbol[][][] preset, String path) {
GsonBuilder builder;
builder = new GsonBuilder();
builder.setPrettyPrinting().serializeNulls();
File dir = new File(presetDirectory);
File presetPath = new File(dir, path);
try (Writer writer = new FileWriter(presetPath)) {
Gson gson = new GsonBuilder().create();
gson.toJson(preset, writer);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
public static Symbol[][][] importPreset(String path) {
Symbol[][][] fromJSON = null;
Gson gson = new Gson();
File dir = new File(presetDirectory);
File presetPath = new File(dir, path);
try (Reader reader = new FileReader(presetPath)) {
JsonReader jreader = new JsonReader(reader);
fromJSON = gson.fromJson(jreader, Symbol[][][].class);
} catch (Exception e) {
System.err.println("Couldn't open preset.");
System.exit(1);
}
return fromJSON;
}
}
| 27.886792 | 66 | 0.61502 |
9079966ff99b3b351692cc2fb4c0d991d9eecdbd | 2,121 | /*
* 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 TCPThread;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
/**
*
* @author felipesoares
*/
public class Conexao extends Thread{
private final int cli;
private final Socket cliente;
private final JTextArea serverTextArea;
public Conexao(Socket cliente, int cli, JTextArea serverTextArea){
this.cliente = cliente;
this.cli = cli;
this.serverTextArea = serverTextArea;
}
@Override
public void run() {
Scanner resposta;
String string;
PrintStream ps;
try {
serverTextArea.setText(serverTextArea.getText()+"Client accepted\n");
serverTextArea.setText(serverTextArea.getText()+"IP: "+ cliente.getInetAddress()+"\n");
if(cliente.isClosed()){
serverTextArea.setText(serverTextArea.getText()+"Conexão fechada\n");
return;
}
resposta = new Scanner(cliente.getInputStream());
ps = new PrintStream(cliente.getOutputStream());
while(resposta.hasNextLine()){
string = resposta.nextLine();
serverTextArea.setText(serverTextArea.getText()+"Cliente "+cli+":\n"+string+"\n");
ps.println("Cliente "+cli+":\n"+string.toUpperCase());
}
} catch (IOException ex) {
serverTextArea.setText(serverTextArea.getText()+"Erro no processamento da mensagem\n");
} finally {
try{
cliente.close();
serverTextArea.setText(serverTextArea.getText()+"Conexão fechada com o cliente"+ cli+"\n");
} catch(Exception e) {
serverTextArea.setText(serverTextArea.getText()+"Erro ao fechar a conexão com o cliente "+ cli+"\n");
}
}
}
}
| 26.848101 | 117 | 0.610561 |
0eab3a63e4f4a38618e9152d42e1802e55825b35 | 966 | package com.example.share.model;
import java.io.Serializable;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
public class Response implements Serializable {
/**
* 回复的作者名字
*/
private String mUserName;
/**
* 回复的作者头像
*/
private String mUserLogoUrl;
/**
* 回复内容
*/
private String mResponse;
/**
* 回复时间
*/
private String mDate;
public String getmUserName() {
return mUserName;
}
public void setmUserName(String mUserName) {
this.mUserName = mUserName;
}
public String getmUserLogoUrl() {
return mUserLogoUrl;
}
public void setmUserLogoUrl(String mUserLogoUrl) {
this.mUserLogoUrl = mUserLogoUrl;
}
public String getmResponse() {
return mResponse;
}
public void setmResponse(String mResponse) {
this.mResponse = mResponse;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
}
| 14.41791 | 51 | 0.707039 |
f9159d1ce75dbed91b9e185e8fa7e2089c4fca64 | 230 | package heli.htweener.ease.impl.cubic;
import heli.htweener.ease.IEaseFunction;
public class CubicIn implements IEaseFunction {
@Override
public double transform(double ratio) {
return ratio*ratio*ratio;
}
}
| 20.909091 | 47 | 0.734783 |
e2fb87752e873269a93c6598568297628368e950 | 260 | package com.example.demo.exception;
public class GeneralError extends RuntimeException{
public GeneralError(String message) {
super(message);
}
public GeneralError(String message, Exception e) {
super(message,e);
}
}
| 23.636364 | 55 | 0.665385 |
1a22db8f0e61cf2838fb83727d78602194953950 | 150 | package com.kgc.service;
import com.kgc.pojo.User;
/**
* @author shkstart
*/
public interface UserService {
User selectByName(String name);
}
| 13.636364 | 35 | 0.706667 |
0ed5ead4c3c53694a11c2a6a5afdfe9afdd6a259 | 2,051 | package de.fau.fuzzing.logparser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Properties;
public class ApplicationProperties
{
private static final String PROPERTIES_PATH = Paths.get(ApplicationProperties.class.getProtectionDomain()
.getCodeSource().getLocation().getPath()).getParent().resolve("application.properties").toString();
private static ApplicationProperties instance = null;
private final Properties properties;
private final String databaseUrl;
private final String databaseUserName;
private ApplicationProperties()
{
try
{
properties = new Properties();
properties.load(new FileInputStream(new File(PROPERTIES_PATH)));
databaseUrl = properties.getProperty("database.url");
databaseUserName = properties.getProperty("database.user");
}
catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
public static ApplicationProperties getInstance()
{
if (instance == null)
instance = new ApplicationProperties();
return instance;
}
public void setDatabaseUrl(final String databaseUrl)
{
storeProperty("database.url", databaseUrl);
}
public String getDatabaseUrl()
{
return databaseUrl;
}
public void setDatabaseUserName(final String databaseUserName)
{
storeProperty("database.user", databaseUserName);
}
public String getDatabaseUserName()
{
return databaseUserName;
}
private void storeProperty(final String key, final String value)
{
try(final FileOutputStream stream = new FileOutputStream(new File(PROPERTIES_PATH)))
{
properties.setProperty(key, value);
properties.store(stream, null);
}
catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
}
| 26.986842 | 111 | 0.660166 |
3369f891448d4987e6257fecbd1cd3588bb7d547 | 193 | package tester;
import org.openqa.selenium.WebElement;
import elementRepository.ElementFactory;
import utility.Log;
import pages.*;
public class SampleTestPage_tester extends SampleTestPage{
} | 24.125 | 58 | 0.84456 |
dc90937b8fd42040ec70b7311604d373f89bf55c | 525 | package dataforms.devtool.field.common;
import dataforms.field.sqltype.VarcharField;
/**
* パッケージ名フィールドクラス。
*
*/
public class PackageNameField extends VarcharField {
/**
* フィールドコメント。
*/
private static final String COMMENT = "パッケージ名";
/**
* コンストラクタ。
*/
public PackageNameField() {
super(null, 256);
this.setComment(COMMENT);
}
/**
* コンストラクタ。
* @param id パッケージID。
*/
public PackageNameField(final String id) {
super(id, 256);
this.setComment(COMMENT);
}
}
| 15.441176 | 53 | 0.624762 |
10aa64fec791e6a9f1d05cc631330b96097ab477 | 5,969 | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.designer.rowgenerator.shadow;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.emf.common.util.EList;
import org.talend.core.model.process.IContext;
import org.talend.core.model.process.IContextListener;
import org.talend.core.model.process.IContextManager;
import org.talend.core.model.process.IContextParameter;
/**
* qzhang class global comment. Detailled comment <br/>
*
* $Id: RowGenContextManager.java,v 1.1 2007/02/02 07:47:01 pub Exp $
*
*/
public class RowGenContextManager implements IContextManager, Cloneable {
private IContext defaultContext = new EmptyContext();
/*
* (non-Java)
*
* @see
* org.talend.core.model.process.IContextManager#addContextListener(org.talend.core.model.process.IContextListener)
*/
public void addContextListener(IContextListener listener) {
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContextManager#fireContextsChangedEvent()
*/
public void fireContextsChangedEvent() {
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContextManager#getDefaultContext()
*/
public IContext getDefaultContext() {
return this.defaultContext;
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContextManager#getListContext()
*/
public List<IContext> getListContext() {
return Arrays.asList(new IContext[] { getDefaultContext() });
}
/*
* (non-Java)
*
* @see
* org.talend.core.model.process.IContextManager#removeContextListener(org.talend.core.model.process.IContextListener
* )
*/
public void removeContextListener(IContextListener listener) {
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContextManager#setDefaultContext(org.talend.core.model.process.IContext)
*/
public void setDefaultContext(IContext context) {
if (context != null) {
for (IContextParameter param : context.getContextParameterList()) {
this.defaultContext.getContextParameterList().add(param.clone());
}
}
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContextManager#setListContext(java.util.List)
*/
public void setListContext(List<IContext> listContext) {
// Read-only
}
public IContext getContext(String name) {
return null;
}
/**
* qzhang RowGenContextManager class global comment. Detailled comment <br/>
*
* $Id: RowGenContextManager.java,v 1.1 2007/02/02 07:47:01 pub Exp $
*
*/
private class EmptyContext implements IContext, Cloneable {
List<IContextParameter> contextParameterList = new ArrayList<IContextParameter>();
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContext#getContextParameterList()
*/
public List<IContextParameter> getContextParameterList() {
return this.contextParameterList;
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContext#getName()
*/
public String getName() {
return RowGenProcessMain.PREVIEW;
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContext#isConfirmationNeeded()
*/
public boolean isConfirmationNeeded() {
return false;
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContext#setConfirmationNeeded(boolean)
*/
public void setConfirmationNeeded(boolean confirmationNeeded) {
// Read-only
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContext#setContextParameterList(java.util.List)
*/
public void setContextParameterList(List<IContextParameter> contextParameterList) {
// Read-only
}
/*
* (non-Java)
*
* @see org.talend.core.model.process.IContext#setName(java.lang.String)
*/
public void setName(String name) {
// Read-only
}
@Override
public IContext clone() {
return this;
}
public boolean sameAs(IContext context) {
// TODO Auto-generated method stub
return false;
}
public IContextParameter getContextParameter(String parameterName) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see org.talend.core.model.process.IContext#getContextParameter(java.lang.String, java.lang.String)
*/
@Override
public IContextParameter getContextParameter(String sourceId, String paraName) {
// TODO Auto-generated method stub
return null;
}
}
public void saveToEmf(EList contextTypeList) {
}
public void loadFromEmf(EList contextTypeList, String defaultContextName) {
}
public boolean sameAs(IContextManager contextManager) {
return false;
}
public boolean checkValidParameterName(String oldParameterName, String newParameterName) {
// TODO Auto-generated method stub
return false;
}
}
| 28.15566 | 121 | 0.602614 |
351b5f603ee5a35ab4a2eee17f003d726d3a3ddc | 1,347 | /*
* 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 it.terrinoni.gdgtorino.hashcode.model;
/**
*
* @author Marco Terrinoni <[email protected]>
*/
public class Endpoint {
public int id;
public int latencyDataCenter;
public Endpoint (int id, int latencyDataCenter) {
this.id = id;
this.latencyDataCenter = latencyDataCenter;
}
@Override
public int hashCode () {
int hash = 5;
hash = 11 * hash + this.id;
hash = 11 * hash + this.latencyDataCenter;
return hash;
}
@Override
public boolean equals (Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Endpoint other = (Endpoint) obj;
if (this.id != other.id) {
return false;
}
if (this.latencyDataCenter != other.latencyDataCenter) {
return false;
}
return true;
}
@Override
public String toString () {
return "Endpoint{" + "id=" + id + ", latencyDataCenter=" + latencyDataCenter + '}';
}
}
| 23.631579 | 91 | 0.562732 |
9c2b3cc2aa88cfae0222fc4019f862f35fcaa179 | 579 | package com.rideaustin.repo.jpa;
import javax.persistence.LockModeType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import com.rideaustin.model.ride.Ride;
public interface RideRepository extends JpaRepository<Ride, Long>,
QueryDslPredicateExecutor<Ride> {
@Query("SELECT r FROM Ride r WHERE r.id=?1")
@Lock(LockModeType.PESSIMISTIC_WRITE)
Ride findOneForUpdate(long id);
}
| 30.473684 | 67 | 0.818653 |
a0000bf71ccef639701cb68e0c454ff46d930c04 | 1,567 | package org.optsol.jdecor_pojo_template.model;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
import java.util.List;
import org.optsol.jdecor.core.AbstractVariableManager;
import org.optsol.jdecor.core.IConstraintManager;
import org.optsol.jdecor.core.IObjectiveManager;
import org.optsol.jdecor.ortools.AbstractOrtoolsModelFactory;
import org.optsol.jdecor.ortools.OrtoolsVariableManager;
import org.optsol.jdecor.ortools.SolverEngine;
import org.optsol.jdecor_pojo_template.model.constants.Constants;
import org.optsol.jdecor_pojo_template.model.constraints.AvailableMetalQuantity;
import org.optsol.jdecor_pojo_template.model.objective.MaximizeProfit;
import org.optsol.jdecor_pojo_template.model.variables.Variables;
public class Model extends AbstractOrtoolsModelFactory<Constants> {
public Model(SolverEngine solverEngine) {
super(solverEngine);
}
@Override
protected AbstractVariableManager<MPSolver, MPVariable> generateVarManager() {
return
new OrtoolsVariableManager.Builder()
// x : int+
.addIntVar(Variables.x)
.addLowerBound(Variables.x, 0.)
.build();
}
@Override
protected IObjectiveManager<
? super Constants, MPVariable, MPSolver> generateObjective() {
return new MaximizeProfit();
}
@Override
protected List<
IConstraintManager<
? super Constants,
MPVariable,
MPSolver>> generateConstraints() {
return List.of(
new AvailableMetalQuantity());
}
}
| 31.34 | 80 | 0.756222 |
b2bbb0335c1d70e433505ad05ddd5961ebda707e | 314 | package net.minidev.ovh.api.dbaas.queue;
/**
* Region
*/
public class OvhRegion {
/**
* Region name
*
* canBeNull && readOnly
*/
public String name;
/**
* Region ID
*
* canBeNull && readOnly
*/
public String id;
/**
* Region URL
*
* canBeNull && readOnly
*/
public String url;
}
| 11.214286 | 40 | 0.579618 |
332bb88fd2e12a72a84a0c01c87d33f7c727b0bc | 265 | package uk.ac.belfastmet.constituencies.domain;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class AllMembersList {
@JsonProperty("Member")
ArrayList<Member> members;
}
| 16.5625 | 54 | 0.739623 |
c5c9988b04b5a256e78a3313fd94c5c60f03d568 | 160 | package algochess.engine.interfaces.casillero;
import algochess.engine.entidades.Entidad;
public interface ColocarHandler {
void colocar(Entidad other);
} | 22.857143 | 46 | 0.8125 |
b31f975729f3ac31dadbe8d27760b6fca20ba103 | 1,967 | /* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.engedu.continentaldivide;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
ContinentMap continentMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout container = (LinearLayout) findViewById(R.id.vertical_layout);
// Create the map and insert it into the view.
continentMap = new ContinentMap(this);
continentMap.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
container.addView(continentMap, 0);
}
public boolean onGenerateTerrain(View view) {
continentMap.generateTerrain(3);
return true;
}
public boolean onFindContinentalDivideDown(View view) {
continentMap.buildDownContinentalDivide(false);
return true;
}
public boolean onFindContinentalDivideUp(View view) {
continentMap.buildUpContinentalDivide(false);
return true;
}
public boolean onClearContinentalDivide(View view) {
continentMap.clearContinentalDivide();
return true;
}
}
| 32.783333 | 97 | 0.72547 |
474fee995e96429cafa5d8e9c4e3242dd999bd1e | 6,891 | package com.gaoyehau.watchdog;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by gaoyehua on 2016/7/23.
*/
public class DragViewActivity extends Activity {
private LinearLayout ll_dragview_toast;
private SharedPreferences sp;
private TextView tv_draview_buttom;
private TextView tv_draview_top;
private int width;
private int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dragview);
sp= getSharedPreferences("comfig",MODE_PRIVATE);
ll_dragview_toast = (LinearLayout) findViewById(R.id.ll_dragview_toast);
tv_draview_buttom =(TextView) findViewById(R.id.tv_dragview_buttom);
tv_draview_top =(TextView) findViewById(R.id.tv_dragview_top);
//设置回显操作
//获取保存的坐标
int x=sp.getInt("x",0);
int y=sp.getInt("y",0);
Log.i("DragViewActivity","X:"+x+"Y:"+y);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ll_dragview_toast.getLayoutParams();
//RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ll_dragview_toast.getLayoutParams();
//2.2设置相应的属性
//leftMargin : 距离父控件左边的距离,根据布局文件中控件中layout_marginLeft属性效果相似
params.leftMargin = x;
params.topMargin = y;
//2.3给控件设置属性
ll_dragview_toast.setLayoutParams(params);
//获取屏幕的宽度
WindowManager windowManager=(WindowManager) getSystemService(WINDOW_SERVICE);
DisplayMetrics outMetrics =new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(outMetrics);
width=outMetrics.widthPixels;
height=outMetrics.heightPixels;
if(y>=height/2){
tv_draview_buttom.setVisibility(View.INVISIBLE);
tv_draview_top.setVisibility(View.VISIBLE);
}else {
tv_draview_buttom.setVisibility(View.VISIBLE);
tv_draview_top.setVisibility(View.INVISIBLE);
}
setTouch();
setDoubleClinck();
}
long[] mHits= new long[2];
private void setDoubleClinck() {
ll_dragview_toast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.arraycopy(mHits,1,mHits,0,mHits.length-1);
mHits[mHits.length-1]= SystemClock.uptimeMillis();
if(mHits[0]>= (SystemClock.uptimeMillis()-500)){
//双击居中
int l= (width - ll_dragview_toast.getWidth())/2;
int t = (height -25- ll_dragview_toast.getHeight())/2;
ll_dragview_toast.layout(l, t, l+ll_dragview_toast.getWidth(), t+ll_dragview_toast.getHeight());
//保存控件的坐标
SharedPreferences.Editor edit = sp.edit();
edit.putInt("x", l);
edit.putInt("y", t);
edit.commit();
}
}
});
}
/**
* 设置触摸监听
*/
private void setTouch() {
ll_dragview_toast.setOnTouchListener(new View.OnTouchListener() {
private int startX;
private int startY;
//v : 当前的控件
//event : 控件执行的事件
@Override
public boolean onTouch(View v, MotionEvent event) {
//event.getAction() : 获取控制的执行的事件
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//按下的事件
System.out.println("按下了....");
//1.按下控件,记录开始的x和y的坐标
startX = (int) event.getRawX();
startY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
//移动的事件
System.out.println("移动了....");
//2.移动到新的位置记录新的位置的x和y的坐标
int newX = (int) event.getRawX();
int newY = (int) event.getRawY();
//3.计算移动的偏移量
int dX = newX-startX;
int dY = newY-startY;
//4.移动相应的偏移量,重新绘制控件
//获取的时候原控件距离父控件左边和顶部的距离
int l = ll_dragview_toast.getLeft();
int t = ll_dragview_toast.getTop();
//获取新的控件的距离父控件左边和顶部的距离
l+=dX;
t+=dY;
int r = l+ll_dragview_toast.getWidth();
int b = t+ll_dragview_toast.getHeight();
////在绘制控件之前,判断ltrb的值是否超出屏幕的大小,如果是就不在进行绘制控件的操作
if(l < 0 || r > width || t < 0 || b > height - 25) {
break;
}
ll_dragview_toast.layout(l, t, r, b);//重新绘制控件
//隐藏显示提示栏
int top =ll_dragview_toast.getTop();
if(top>=height/2){
tv_draview_buttom.setVisibility(View.INVISIBLE);
tv_draview_top.setVisibility(View.VISIBLE);
}else {
tv_draview_buttom.setVisibility(View.VISIBLE);
tv_draview_top.setVisibility(View.INVISIBLE);
}
//5.更新开始的坐标
startX=newX;
startY=newY;
break;
case MotionEvent.ACTION_UP:
//抬起的事件
System.out.println("抬起了....");
//保存到新移动的坐标
int x=ll_dragview_toast.getLeft();
int y=ll_dragview_toast.getTop();
SharedPreferences.Editor edit=sp.edit();
edit.putInt("x",x);
edit.putInt("y",y);
edit.commit();
break;
}
//True if the listener has consumed the event, false otherwise.
//true:事件消费了,执行了,false:表示事件被拦截了
return false;
}
});
}
}
| 36.654255 | 117 | 0.508925 |
9fa01fdd1207fe6fd7a66acb67bea2a8a51f9049 | 538 | module net.pincette.jes.util {
requires java.json;
requires net.pincette.json;
requires net.pincette.mongo;
requires net.pincette.common;
requires org.mongodb.driver.reactivestreams;
requires org.mongodb.bson;
requires org.mongodb.driver.core;
requires net.pincette.rs;
requires com.fasterxml.jackson.dataformat.cbor;
requires kafka.clients;
requires java.logging;
requires async.http.client;
requires kafka.streams;
requires typesafe.config;
requires org.reactivestreams;
exports net.pincette.jes.util;
}
| 28.315789 | 49 | 0.776952 |
1b720798600f05e2c2b889933eac9a328df3a712 | 10,825 | /*
* Copyright 2018-2021 Prebid.org, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.prebid.mobile.rendering.views.webview;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.FrameLayout;
import org.prebid.mobile.rendering.listeners.WebViewDelegate;
import org.prebid.mobile.rendering.models.HTMLCreative;
import org.prebid.mobile.rendering.sdk.ManagersResolver;
import org.prebid.mobile.rendering.sdk.deviceData.managers.DeviceInfoManager;
import org.prebid.mobile.rendering.utils.exposure.ViewExposure;
import org.prebid.mobile.rendering.utils.helpers.Utils;
import org.prebid.mobile.rendering.utils.logger.LogUtil;
import org.prebid.mobile.rendering.views.interstitial.InterstitialManager;
import org.prebid.mobile.rendering.views.webview.mraid.Views;
import java.lang.ref.WeakReference;
//Equivalent of adBase
public class PrebidWebViewBase extends FrameLayout
implements PreloadManager.PreloadedListener, MraidEventsManager.MraidListener {
private final String TAG = PrebidWebViewBase.class.getSimpleName();
public static final int WEBVIEW_DESTROY_DELAY_MS = 1000;
protected Context mContext;
private final Handler mHandler;
protected WebViewBase mOldWebViewBase;
protected WebViewDelegate mWebViewDelegate;
protected HTMLCreative mCreative;
protected WebViewBase mWebView;
protected WebViewBanner mMraidWebView;
protected int mWidth, mHeight, mDefinedWidthForExpand, mDefinedHeightForExpand;
protected InterstitialManager mInterstitialManager;
private int mScreenVisibility;
protected WebViewBase mCurrentWebViewBase;
protected Animation mFadeInAnimation;
protected Animation mFadeOutAnimation;
public PrebidWebViewBase(Context context, InterstitialManager interstitialManager) {
//a null context to super(), a framelayout, could crash. So, catch this exception
super(context);
mContext = context;
mInterstitialManager = interstitialManager;
mScreenVisibility = getVisibility();
mHandler = new Handler(Looper.getMainLooper());
}
public void initTwoPartAndLoad(String url) {
//do it in banner child class
}
public void loadHTML(String html, int width, int height) {
//call child's
}
public void destroy() {
Views.removeFromParent(this);
removeAllViews();
WebView currentWebView = (mWebView != null) ? mWebView : mMraidWebView;
// IMPORTANT: Delayed execution was implemented due to this issue: jira/browse/MOBILE-5380
// We need to give OMID time to finish method execution inside the webview
mHandler.removeCallbacksAndMessages(null);
mHandler.postDelayed(new WebViewCleanupRunnable(currentWebView), WEBVIEW_DESTROY_DELAY_MS);
}
public void initMraidExpanded() {
runOnUiThread(() -> {
try {
readyForMraidExpanded();
}
catch (Exception e) {
LogUtil.error(TAG, "initMraidExpanded failed: " + Log.getStackTraceString(e));
}
});
}
private void readyForMraidExpanded() {
if (mMraidWebView != null && mMraidWebView.getMRAIDInterface() != null) {
mMraidWebView.getMRAIDInterface().onReadyExpanded();
}
}
@Override
public void preloaded(WebViewBase adBaseView) {
//do it in child
}
public void handleOpen(String url) {
if (mCurrentWebViewBase != null && mCurrentWebViewBase.getMRAIDInterface() != null) {
mCurrentWebViewBase.getMRAIDInterface().open(url);
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
int visibility = (!hasWindowFocus ? View.INVISIBLE : View.VISIBLE);
if (Utils.hasScreenVisibilityChanged(mScreenVisibility, visibility)) {
//visibility has changed. Send the changed value for mraid update for banners
mScreenVisibility = visibility;
if (mCurrentWebViewBase != null && mCurrentWebViewBase.getMRAIDInterface() != null) {
mCurrentWebViewBase.getMRAIDInterface().handleScreenViewabilityChange(Utils.isScreenVisible(mScreenVisibility));
}
}
}
@Override
public void openExternalLink(String url) {
//No need to separate the apis for mraid & non-mraid as they all go to the same methods.
if (mWebViewDelegate != null) {
mWebViewDelegate.webViewShouldOpenExternalLink(url);
}
}
@Override
public void openMraidExternalLink(String url) {
if (mWebViewDelegate != null) {
mWebViewDelegate.webViewShouldOpenMRAIDLink(url);
}
}
@Override
public void onAdWebViewWindowFocusChanged(boolean hasFocus) {
if (mCreative != null) {
mCreative.changeVisibilityTrackerState(hasFocus);
}
}
public void onViewExposureChange(ViewExposure viewExposure) {
if (mCurrentWebViewBase != null && mCurrentWebViewBase.getMRAIDInterface() != null) {
mCurrentWebViewBase.getMRAIDInterface().getJsExecutor().executeExposureChange(viewExposure);
}
}
public WebViewBase getOldWebView() {
return mOldWebViewBase;
}
public void setOldWebView(WebViewBase oldWebView) {
mOldWebViewBase = oldWebView;
}
public void setWebViewDelegate(WebViewDelegate delegate) {
mWebViewDelegate = delegate;
}
public HTMLCreative getCreative() {
return mCreative;
}
public void setCreative(HTMLCreative creative) {
mCreative = creative;
}
public WebViewBase getWebView() {
return mWebView;
}
public WebViewBanner getMraidWebView() {
return mMraidWebView;
}
//gets expand properties & also a close view(irrespective of usecustomclose is false)
public void loadMraidExpandProperties() {
//do it in child classs
}
protected void renderAdView(WebViewBase webViewBase) {
if (webViewBase == null) {
LogUtil.warn(TAG, "WebviewBase is null");
return;
}
if (getContext() != null) {
mFadeInAnimation = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);
}
if (webViewBase.isMRAID() && webViewBase.getMRAIDInterface() != null) {
webViewBase.getMRAIDInterface().getJsExecutor().executeOnViewableChange(true);
}
webViewBase.startAnimation(mFadeInAnimation);
webViewBase.setVisibility(View.VISIBLE);
displayAdViewPlacement(webViewBase);
}
protected void displayAdViewPlacement(WebViewBase webViewBase) {
renderPlacement(webViewBase, mWidth, mHeight);
if (webViewBase.getAdWidth() != 0) {
getLayoutParams().width = webViewBase.getAdWidth();
}
if (webViewBase.getAdHeight() != 0) {
getLayoutParams().height = webViewBase.getAdHeight();
}
invalidate();
}
private void renderPlacement(WebViewBase webViewBase, int width, int height) {
if (mContext == null) {
LogUtil.warn(TAG, "Context is null");
return;
}
if (webViewBase == null) {
LogUtil.warn(TAG, "WebviewBase is null");
return;
}
int orientation = Configuration.ORIENTATION_UNDEFINED;
WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
int screenWidth = Utils.getScreenWidth(windowManager);
int screenHeight = Utils.getScreenHeight(windowManager);
int deviceWidth = Math.min(screenWidth, screenHeight);
int deviceHeight = Math.max(screenWidth, screenHeight);
DeviceInfoManager deviceManager = ManagersResolver.getInstance().getDeviceManager();
if (deviceManager != null) {
orientation = deviceManager.getDeviceOrientation();
}
float factor = getScaleFactor(webViewBase, orientation, deviceWidth, deviceHeight);
webViewBase.setAdWidth(Math.round((width * factor)));
webViewBase.setAdHeight(Math.round((height * factor)));
}
private float getScaleFactor(WebViewBase webViewBase, int orientation, int deviceWidth, int deviceHeight) {
float factor = 1.0f;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (mWidth < deviceHeight) {
factor = factor * deviceWidth / mWidth;
}
else {
factor = factor * deviceHeight / mWidth;
}
}
else {
if (mWidth < deviceWidth) {
factor = factor * deviceWidth / mWidth;
}
else {
factor = factor * deviceWidth / mWidth;
}
}
if (factor > webViewBase.densityScalingFactor()) {
factor = (float) (1.0f * webViewBase.densityScalingFactor());
}
return factor;
}
protected void runOnUiThread(Runnable runnable) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(runnable);
}
private static final class WebViewCleanupRunnable implements Runnable {
private static final String TAG = WebViewCleanupRunnable.class.getSimpleName();
private final WeakReference<WebView> mWeakWebView;
WebViewCleanupRunnable(WebView webViewBase) {
mWeakWebView = new WeakReference<>(webViewBase);
}
@Override
public void run() {
WebView webViewBase = mWeakWebView.get();
if (webViewBase == null) {
Log.d(TAG, "Unable to execute destroy on WebView. WebView is null.");
return;
}
//MOBILE-2950 ARKAI3 - Inline Video of the webview is not stopped on back key press
webViewBase.destroy();
}
}
}
| 33.934169 | 128 | 0.669284 |
c0a95561a65ab6f33a4aaaab4860f7a3abc30638 | 2,511 | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.streamnative.pulsar.handlers.kop.utils;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
/**
* Utils for ZooKeeper.
*/
@Slf4j
public class ZooKeeperUtils {
public static void createPath(ZooKeeper zooKeeper, String zkPath, String subPath, byte[] data) {
try {
if (zooKeeper.exists(zkPath, false) == null) {
zooKeeper.create(zkPath,
new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
String addSubPath = zkPath + subPath;
if (zooKeeper.exists(addSubPath, false) == null) {
zooKeeper.create(addSubPath,
data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} else {
zooKeeper.setData(addSubPath, data, -1);
}
log.debug("create zk path, addSubPath:{} data:{}.",
addSubPath, new String(data, StandardCharsets.UTF_8));
} catch (Exception e) {
log.error("create zookeeper path error", e);
}
}
public static String getData(ZooKeeper zooKeeper, String zkPath, String subPath) {
String data = null;
try {
String addSubPath = zkPath + subPath;
Stat zkStat = zooKeeper.exists(addSubPath, true);
if (zkStat != null) {
data = new String(zooKeeper.getData(addSubPath, false, zkStat), StandardCharsets.UTF_8);
}
} catch (Exception e) {
log.error("get zookeeper path data error", e);
}
return data;
}
public static String groupIdPathFormat(String clientHost, String clientId) {
String path = clientHost.split(":")[0] + "-" + clientId;
return path;
}
} | 37.477612 | 104 | 0.633214 |
dd9761ce052f0b42d421f5861eee5bab85658855 | 1,079 | package com.yore.medium;
import com.yore.base.TreeNode;
import java.util.*;
/**
* @author jia bing wen
* @date 2021/4/26 9:30
* @description
*/
public class Number102 {
public static List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
Queue<TreeNode> nodeQueue = new LinkedList<>();
TreeNode node = root;
nodeQueue.offer(node);
int count = 0;
List<List<Integer>> result = new ArrayList<>();
while (!nodeQueue.isEmpty()) {
List<Integer> list = new ArrayList<>();
count = nodeQueue.size();
while (count > 0) {
node = nodeQueue.poll();
list.add(node.val);
if (node.left != null) {
nodeQueue.offer(node.left);
}
if (node.right != null) {
nodeQueue.offer(node.right);
}
count--;
}
result.add(list);
}
return result;
}
}
| 25.690476 | 65 | 0.481928 |
15f7e91b232b1b6f84639c435e7a5a3980bea7ed | 1,412 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.linkface.transform.v20180720;
import com.aliyuncs.linkface.model.v20180720.DeleteDeviceAllGroupResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class DeleteDeviceAllGroupResponseUnmarshaller {
public static DeleteDeviceAllGroupResponse unmarshall(DeleteDeviceAllGroupResponse deleteDeviceAllGroupResponse, UnmarshallerContext context) {
deleteDeviceAllGroupResponse.setRequestId(context.stringValue("DeleteDeviceAllGroupResponse.RequestId"));
deleteDeviceAllGroupResponse.setCode(context.integerValue("DeleteDeviceAllGroupResponse.Code"));
deleteDeviceAllGroupResponse.setMessage(context.stringValue("DeleteDeviceAllGroupResponse.Message"));
deleteDeviceAllGroupResponse.setSuccess(context.booleanValue("DeleteDeviceAllGroupResponse.Success"));
return deleteDeviceAllGroupResponse;
}
} | 44.125 | 144 | 0.816572 |
67e893c6b3145a4aa99e58892aae9bb1a53b0b11 | 384 | package io.renren.modules.app.v1.dao;
import io.renren.modules.app.v1.entity.AppFpsProdDataEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
*
*
* @author wangkang
* @email [email protected]
* @date 2021-07-14 15:12:44
*/
@Mapper
public interface AppFpsProdDataDao extends BaseMapper<AppFpsProdDataEntity> {
}
| 21.333333 | 77 | 0.765625 |
e7eb7a239a50779fd5507bdf500129844d947c78 | 1,497 | package com.industrial.domin;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author zhu
* @date 2022年01月28日 15:27
*/
/**
* 活动日志表
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "app_activity_log")
public class AppActivityLog {
/**
* 序号
*/
@TableId(value = "id", type = IdType.INPUT)
private Integer id;
/**
* 活动ID
*/
@TableField(value = "activity_id")
private Integer activityId;
/**
* 日志内容
*/
@TableField(value = "log_contents")
private String logContents;
/**
* 创建ID
*/
@TableField(value = "create_id")
private Integer createId;
/**
* 创建人
*/
@TableField(value = "create_name")
private String createName;
/**
* 创建时间
*/
@TableField(value = "create_time")
private Date createTime;
public static final String COL_ID = "id";
public static final String COL_ACTIVITY_ID = "activity_id";
public static final String COL_LOG_CONTENTS = "log_contents";
public static final String COL_CREATE_ID = "create_id";
public static final String COL_CREATE_NAME = "create_name";
public static final String COL_CREATE_TIME = "create_time";
} | 20.791667 | 65 | 0.676019 |
a16719344e4eaccb6e53b7538d631ae48bd28eec | 973 | package com.marverenic.music.view;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
public class InsetDecoration extends RecyclerView.ItemDecoration {
private Drawable mInset;
private int mHeight;
private int mGravity;
public InsetDecoration(Drawable inset, int height, int gravity) {
mInset = inset;
mHeight = height;
mGravity = gravity;
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
int top = 0;
int left = 0;
int right = parent.getWidth();
int bottom = parent.getHeight();
if (mGravity == Gravity.TOP) {
mInset.setBounds(left, top, right, mHeight);
} else if (mGravity == Gravity.BOTTOM) {
mInset.setBounds(left, bottom - mHeight, right, bottom);
}
mInset.draw(c);
}
}
| 27.027778 | 85 | 0.652621 |
7c44b9898858b1d7e8dbc363779452c7fda91118 | 2,292 | package com.wrapper.spotify.model_objects.miscellaneous;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.gson.JsonObject;
import com.wrapper.spotify.model_objects.AbstractModelObject;
/**
* Retrieve information about Restriction objects by building instances from this class. <br><br>
* <p>
* Part of the response when <a href="https://developer.spotify.com/web-api/track-relinking-guide/">Track Relinking</a>
* is applied, the original track is not available in the given market, and Spotify did not have any tracks to relink it
* with. The track response will still contain metadata for the original track, and a restrictions object containing the
* reason why the track is not available
*/
@JsonDeserialize(builder = Restrictions.Builder.class)
public class Restrictions extends AbstractModelObject {
private final String reason;
private Restrictions(final Builder builder) {
super(builder);
this.reason = builder.reason;
}
/**
* Get the reason why the track is not available.
*
* @return The track restriction reason.
*/
public String getReason() {
return reason;
}
@Override
public Builder builder() {
return new Builder();
}
/**
* Builder class for building {@link Restrictions} instances.
*/
public static final class Builder extends AbstractModelObject.Builder {
private String reason;
/**
* The restriction reason setter.
*
* @param reason The track restriction reason.
* @return A {@link Restrictions.Builder}.
*/
public Builder setReason(String reason) {
this.reason = reason;
return this;
}
@Override
public Restrictions build() {
return new Restrictions(this);
}
}
/**
* JSonUtil class for building {@link Restrictions} instances.
*/
public static final class JsonUtil extends AbstractModelObject.JsonUtil<Restrictions> {
public Restrictions createModelObject(JsonObject jsonObject) {
if (jsonObject == null || jsonObject.isJsonNull()) {
return null;
}
return new Restrictions.Builder()
.setReason(
hasAndNotNull(jsonObject, "reason")
? jsonObject.get("reason").getAsString()
: null)
.build();
}
}
}
| 28.65 | 120 | 0.693281 |
68fe890ba0a88f37430452919ad3798ba4f6ba36 | 500 | import java.util.*;
class prime {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int i = 0;
int c = 0;
for (i = 2; i < a; i++) {
if (a % i == 0) {
c = c + 1;
}
}
if (c == 0) {
System.out.println("Prime");
}
else{
System.out.println("Composite");
}
sc.close();
}
} | 21.73913 | 45 | 0.362 |
47ed14ab4f6505acdd84adfd29c328d5bb1c984b | 2,486 | package net.golikov.springdddexample.ddd.model.filesystem.basic;
import net.golikov.springdddexample.ddd.model.Grade;
import net.golikov.springdddexample.ddd.model.Student;
import net.golikov.springdddexample.ddd.model.filesystem.StudentFs;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static java.nio.file.Files.newDirectoryStream;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
@Component
@Scope(SCOPE_PROTOTYPE)
public class BasicStudentFs implements StudentFs<BasicGradeFs> {
private final Path path;
public BasicStudentFs(Path path) {
this.path = path;
}
@Override
public String getName() {
return path.getFileName().toString();
}
@Override
public List<BasicGradeFs> getGrades() throws IOException {
List<BasicGradeFs> result = new ArrayList<>();
try (DirectoryStream<Path> paths = newDirectoryStream(getPath(), Files::isRegularFile)) {
for (Path path : paths) {
result.add(createGradeFs(path));
}
}
return result;
}
public Path getPath() {
return path;
}
@Lookup
public BasicGradeFs createGradeFs(Path path) {
return null;
}
@Component
public static class Factory implements StudentFs.Factory<BasicStudyGroupFs, BasicStudentFs> {
private final BasicGradeFs.Factory basicGradeFsFactory;
public Factory(BasicGradeFs.Factory basicGradeFsFactory) {
this.basicGradeFsFactory = basicGradeFsFactory;
}
@Override
public BasicStudentFs saveStudentFs(BasicStudyGroupFs studyGroup, Student<?> student) throws Exception {
Path studentPath = studyGroup.getPath()
.resolve(student.getName());
Files.createDirectories(studentPath);
BasicStudentFs result = getStudentFs(studentPath);
for (Grade grade : student.getGrades()) {
basicGradeFsFactory.saveGradeFs(result, grade);
}
return result;
}
@Lookup
public BasicStudentFs getStudentFs(Path path) {
return null;
}
}
}
| 29.951807 | 112 | 0.685438 |
8c54c03b3e264ee3e52f7769e5612708cd51e10b | 6,442 | /*
* 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 CMS;
import java.awt.event.ItemEvent;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/**
*
* @author panha
*/
public class Java2sAutoTextField1 extends JTextField {
class AutoDocument extends PlainDocument {
public void replace(int i, int j, String s, AttributeSet attributeset)
throws BadLocationException {
super.remove(i, j);
insertString(i, s, attributeset);
}
public void insertString(int i, String s, AttributeSet attributeset)
throws BadLocationException {
if (s == null || "".equals(s))
return;
String s1 = getText(0, i);
String s2 = getMatch(s1 + s);
int j = (i + s.length()) - 1;
if (isStrict && s2 == null) {
s2 = getMatch(s1);
j--;
} else if (!isStrict && s2 == null) {
super.insertString(i, s, attributeset);
return;
}
if (autoComboBox != null && s2 != null)
autoComboBox.setSelectedValue(s2);
super.remove(0, getLength());
super.insertString(0, s2, attributeset);
setSelectionStart(j + 1);
setSelectionEnd(getLength());
}
public void remove(int i, int j) throws BadLocationException {
int k = getSelectionStart();
if (k > 0)
k--;
String s = getMatch(getText(0, k));
if (!isStrict && s == null) {
super.remove(i, j);
} else {
super.remove(0, getLength());
super.insertString(0, s, null);
}
if (autoComboBox != null && s != null)
autoComboBox.setSelectedValue(s);
try {
setSelectionStart(k);
setSelectionEnd(getLength());
} catch (Exception exception) {
}
}
}
public Java2sAutoTextField1(List list) {
isCaseSensitive = false;
isStrict = true;
autoComboBox = null;
if (list == null) {
throw new IllegalArgumentException("values can not be null");
} else {
dataList = list;
init();
return;
}
}
Java2sAutoTextField1(List list, Java2sAutoComboBox b) {
isCaseSensitive = false;
isStrict = true;
autoComboBox = null;
if (list == null) {
throw new IllegalArgumentException("values can not be null");
} else {
dataList = list;
autoComboBox = b;
init();
return;
}
}
private void init() {
setDocument(new AutoDocument());
if (isStrict && dataList.size() > 0)
setText(dataList.get(0).toString());
}
private String getMatch(String s) {
for (int i = 0; i < dataList.size(); i++) {
String s1 = dataList.get(i).toString();
if (s1 != null) {
if (!isCaseSensitive && s1.toLowerCase().startsWith(s.toLowerCase()))
return s1;
if (isCaseSensitive && s1.startsWith(s))
return s1;
}
}
return null;
}
public void replaceSelection(String s) {
AutoDocument _lb = (AutoDocument) getDocument();
if (_lb != null)
try {
int i = Math.min(getCaret().getDot(), getCaret().getMark());
int j = Math.max(getCaret().getDot(), getCaret().getMark());
_lb.replace(i, j - i, s, null);
} catch (Exception exception) {
}
}
public boolean isCaseSensitive() {
return isCaseSensitive;
}
public void setCaseSensitive(boolean flag) {
isCaseSensitive = flag;
}
public boolean isStrict() {
return isStrict;
}
public void setStrict(boolean flag) {
isStrict = flag;
}
public List getDataList() {
return dataList;
}
public void setDataList(List list) {
if (list == null) {
throw new IllegalArgumentException("values can not be null");
} else {
dataList = list;
return;
}
}
private List dataList;
private boolean isCaseSensitive;
private boolean isStrict;
private Java2sAutoComboBox autoComboBox;
}
class Java2sAutoComboBox extends JComboBox {
private class AutoTextFieldEditor extends BasicComboBoxEditor {
private Java2sAutoTextField1 getAutoTextFieldEditor() {
return (Java2sAutoTextField1) editor;
}
AutoTextFieldEditor(java.util.List list) {
editor = new Java2sAutoTextField1(list, Java2sAutoComboBox.this);
}
}
public Java2sAutoComboBox(java.util.List list) {
isFired = false;
autoTextFieldEditor = new AutoTextFieldEditor(list);
setEditable(true);
setModel(new DefaultComboBoxModel(list.toArray()) {
protected void fireContentsChanged(Object obj, int i, int j) {
if (!isFired)
super.fireContentsChanged(obj, i, j);
}
});
setEditor(autoTextFieldEditor);
}
public boolean isCaseSensitive() {
return autoTextFieldEditor.getAutoTextFieldEditor().isCaseSensitive();
}
public void setCaseSensitive(boolean flag) {
autoTextFieldEditor.getAutoTextFieldEditor().setCaseSensitive(flag);
}
public boolean isStrict() {
return autoTextFieldEditor.getAutoTextFieldEditor().isStrict();
}
public void setStrict(boolean flag) {
autoTextFieldEditor.getAutoTextFieldEditor().setStrict(flag);
}
public java.util.List getDataList() {
return autoTextFieldEditor.getAutoTextFieldEditor().getDataList();
}
public void setDataList(java.util.List list) {
autoTextFieldEditor.getAutoTextFieldEditor().setDataList(list);
setModel(new DefaultComboBoxModel(list.toArray()));
}
void setSelectedValue(Object obj) {
if (isFired) {
return;
} else {
isFired = true;
setSelectedItem(obj);
fireItemStateChanged(new ItemEvent(this, 701, selectedItemReminder, 1));
isFired = false;
return;
}
}
protected void fireActionEvent() {
if (!isFired)
super.fireActionEvent();
}
private AutoTextFieldEditor autoTextFieldEditor;
private boolean isFired;
}
| 26.401639 | 80 | 0.62077 |
5b3cc055460b2f298b22b3ae69ac70dacd92cb72 | 1,768 | package shipmaker.knobs;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import physics.XYTSource;
import render.MouseEventType;
import render.XYTRenderNode;
public abstract class Knob extends XYTRenderNode implements XYTSource {
float x, y;
public Knob() {
super(null);
src = this;
}
public float position_x() {
return x;
}
public float position_y() {
return y;
}
public abstract float offset_rotation();
public float alignment_theta() {
return -offset_rotation();
}
Point2D last = null;
boolean dragging = false;
public boolean interacted(AffineTransform root, MouseEvent e,
MouseEventType t) {
Point2D.Float src = new Point2D.Float();
src.setLocation(e.getX(), e.getY());
try {
root.invert();
} catch (NoninvertibleTransformException e1) {
e1.printStackTrace();
}
Point2D pt = root.transform(src, null);
if (t == MouseEventType.MOUSE_PRESS && Math.abs(pt.getX()) < 10
&& Math.abs(pt.getY()) < 10) {
dragging = true;
last = pt;
pt.setLocation(pt.getX() + worldx(), pt.getY() + worldy());
} else if (dragging && t == MouseEventType.MOUSE_DRAG) {
pt.setLocation(pt.getX() + worldx(), pt.getY() + worldy());
tweak((float) (pt.getX() - last.getX()),
(float) (pt.getY() - last.getY()), (float) pt.getX(),
(float) pt.getY());
last = pt;
} else if (dragging && t == MouseEventType.MOUSE_RELEASE) {
dragging = false;
last = null;
} else {
return false;
}
return true;
}
public abstract void tweak(float dx, float dy, float worldx, float worldy);
public abstract float worldx();
public abstract float worldy();
public int layer() {
return 2;
}
} | 22.379747 | 76 | 0.673077 |
7848878ec64f5ccd2cda73ac76eebc3dc866be62 | 103 | package alexmog.rulemastersworld.packets.skills;
public enum SkillType {
PASSIVE,
ACTIVABLE
}
| 14.714286 | 48 | 0.757282 |
9c87f5ebd40efa49685e65ee8dfe5e33fa98433f | 1,080 | package net.blog.controller.portal;
import net.blog.response.ResponseResult;
import net.blog.services.ISolrService;
import org.springframework.beans.factory.annotation.Autowired;
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;
@RestController
@RequestMapping("/portal/search")
public class SearchPortalApi {
@Autowired
private ISolrService solrService;
@GetMapping
public ResponseResult doSearch(@RequestParam("keyword") String keyword,
@RequestParam("page") int page,
@RequestParam("size") int size,
@RequestParam(value = "categoryId", required = false) String categoryId,
@RequestParam(value = "sort", required = false) Integer sort) {
return solrService.doSearch(keyword, page, size, categoryId, sort);
}
}
| 40 | 107 | 0.687963 |
ed19c28f14b7404162e9326afcfd4773c5e8aa67 | 1,707 | /*
* Licensed to GraphHopper and Peter Karich under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.examples.sfr;
/**
* @author Peter Karich
*/
public class NumHelper
{
private final static double DEFAULT_PRECISION = 1e-6;
public static boolean equalsEps( double d1, double d2 )
{
return equalsEps(d1, d2, DEFAULT_PRECISION);
}
public static boolean equalsEps( double d1, double d2, double epsilon )
{
return Math.abs(d1 - d2) < epsilon;
}
public static boolean equals( double d1, double d2 )
{
return Double.compare(d1, d2) == 0;
}
public static int compare( double d1, double d2 )
{
return Double.compare(d1, d2);
}
public static boolean equalsEps( float d1, float d2 )
{
return equalsEps(d1, d2, DEFAULT_PRECISION);
}
public static boolean equalsEps( float d1, float d2, float epsilon )
{
return Math.abs(d1 - d2) < epsilon;
}
}
| 29.947368 | 76 | 0.681312 |
02d6104f7aa347d2fc8a980e322c8004fd37ebc5 | 112 | package com.github.seckillsystem.common;
public interface Code {
String getMessage();
int getCode();
}
| 16 | 40 | 0.714286 |
65b0a90865e55257778aebdfba9b6a777e18d525 | 4,639 | package io.woleet.idserver.api;
import io.woleet.idserver.ApiClient;
import io.woleet.idserver.ApiException;
import io.woleet.idserver.Config;
import io.woleet.idserver.api.model.*;
import org.apache.http.HttpStatus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
public class DiscoveryApiTest {
private static String WOLEET_ID_SERVER_SIGNATURE_BASEPATH = System.getenv("WOLEET_ID_SERVER_SIGNATURE_BASEPATH");
static {
if (WOLEET_ID_SERVER_SIGNATURE_BASEPATH == null)
WOLEET_ID_SERVER_SIGNATURE_BASEPATH = "https://localhost:3000";
}
private UserGet user;
private DiscoveryApi discoveryApi;
private ApiTokenApi apiTokenApi;
private APITokenGet apiToken;
private KeyApi keyApi;
@Before
public void setUp() throws Exception {
// Start from a clean state
tearDown();
// Create test user
user = Config.createTestUser();
// Create kep API
keyApi = new KeyApi(Config.getAdminAuthApiClient().setBasePath(Config.WOLEET_ID_SERVER_API_BASEPATH));
// Create an helper API with API token authentication
apiTokenApi = new ApiTokenApi(Config.getAdminAuthApiClient());
apiToken = apiTokenApi.createAPIToken((APITokenPost) new APITokenPost().name("test"));
ApiClient apiClient = Config.getNoAuthApiClient();
apiClient.setBasePath(WOLEET_ID_SERVER_SIGNATURE_BASEPATH);
apiClient.addDefaultHeader("Authorization", "Bearer " + apiToken.getValue());
discoveryApi = new DiscoveryApi(apiClient);
}
@After
public void tearDown() throws Exception {
Config.deleteAllTestUsers();
// This code is called before setUp() is called, so API token can be null
if (apiToken != null)
apiTokenApi.deleteAPIToken(apiToken.getId());
}
@Test
public void discoverUserByPubKeyTest() throws ApiException {
// Try to discover a user using an invalid key
try {
discoveryApi.discoverUserByPubKey("invalid pubKey");
fail("Should not be able to discover a user using an invalid key");
}
catch (ApiException e) {
assertEquals("Invalid return code", HttpStatus.SC_BAD_REQUEST, e.getCode());
return;
}
// Try to discover a user using a non existing key
try {
discoveryApi.discoverUserByPubKey("3Beer3irc1vgs76ENA4coqsEQpGZeM5CTd");
fail("Should not be able to discover a user using a non existing key");
}
catch (ApiException e) {
assertEquals("Invalid return code", HttpStatus.SC_NOT_FOUND, e.getCode());
return;
}
// Discover test user from his public key
String key = keyApi.getKeyById(user.getDefaultKeyId()).getPubKey();
UserDisco response = discoveryApi.discoverUserByPubKey(key);
assertEquals(user.getId(), response.getId());
}
@Test
public void discoverUserKeysTest() throws ApiException {
// Try to discover user's keys using a non existing user identifier
try {
discoveryApi.discoverUserKeys(Config.randomUUID());
fail("Should not be able to discover user's key using a non existing user identifier");
}
catch (ApiException e) {
assertEquals("Invalid return code", HttpStatus.SC_NOT_FOUND, e.getCode());
return;
}
// Discover test user's keys
List<KeyDisco> response = discoveryApi.discoverUserKeys(user.getId());
// Check that test user's default key is part of his keys
String pubKey = keyApi.getKeyById(user.getDefaultKeyId()).getPubKey();
for (KeyDisco key : response)
if (key.getPubKey().equals(pubKey))
return;
fail("Test user's public key not found in key list");
}
@Test
public void discoverUsersTest() throws ApiException {
List<UserDisco> response = discoveryApi.discoverUsers("test");
for (UserDisco u : response)
if (u.getId().equals(user.getId()))
return;
fail("Test user not found in user list");
}
@Test
public void discoverUserTest() throws ApiException {
// TODO: The API token created has a userId set to null, so it is not possible to discover the current user.
}
@Test
public void discoverConfigTest() throws ApiException {
ConfigDisco response = discoveryApi.discoverConfig();
assertNotNull(response.getIdentityURL());
}
}
| 33.861314 | 117 | 0.659194 |
18dc50dc79bc7b876ad427af3f56f52755f25ac4 | 1,106 | package ru.job4j.profession;
/**
* Diploma.
*/
class Diploma { }
/**
* Date.
*/
class Date { }
/**
* Profession.
* @author Aleksandr Shigin
* @version $Id$
* @since 0.1
*/
public class Profession {
/**
* Name.
*/
private String name;
/**
* Diploma.
*/
private Diploma diploma;
/**
* Date of birth.
*/
private Date dateOfBirth;
/**
* Constructor with parameters.
* @param name - name
* @param diploma - diploma
* @param dateOfBirth - date of birth
*/
Profession(String name, Diploma diploma, Date dateOfBirth) {
this.name = name;
this.diploma = diploma;
this.dateOfBirth = dateOfBirth;
}
/**
* Get name.
* @return - name
*/
public String getName() {
return this.name;
}
/**
* Get diploma.
* @return - diploma
*/
public Diploma getDiploma() {
return this.diploma;
}
/**
* Get date of birth.
* @return date of birth
*/
public Date getDateOfBirth() {
return this.dateOfBirth;
}
}
| 17.555556 | 64 | 0.528029 |
92c35b5d56774220b6aad2a58ec87bc799a6b743 | 371 | package fr.ubordeaux.jmetrics.project;
/**
* Service that traverses directories to generate a Project Structure containing bytecode class files.
*/
public class BytecodeFileSystemExplorer extends SimpleFileSystemExplorer {
private static final String CLASS_EXTENSION = ".class";
public BytecodeFileSystemExplorer() {
super(CLASS_EXTENSION);
}
}
| 24.733333 | 102 | 0.762803 |
fcd2ac2325b086a803df77b076afbedef6a5642b | 315 | package io.github.syst3ms.skriptparser.parsing;
/**
* An exception thrown whenever something goes wrong at parse time.
*/
public class SkriptParserException extends RuntimeException {
private static final long serialVersionUID = 0L;
public SkriptParserException(String msg) {
super(msg);
}
} | 26.25 | 67 | 0.742857 |
2ae34ee1f83a840f31e8eda56c9ec06d6b56d0c3 | 1,841 | /*
* 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.eagerlogic.cubee.client.properties.ext;
import com.eagerlogic.cubee.client.components.AComponent;
import com.eagerlogic.cubee.client.properties.AExpression;
import com.eagerlogic.cubee.client.properties.IntegerProperty;
/**
*
* @author dipacs
*/
public class AlignMiddleExp extends AExpression<Integer> {
private final AComponent parent;
private final AComponent child;
private final int translateY;
private final IntegerProperty translateYProperty;
public AlignMiddleExp(AComponent parent, AComponent child) {
this(parent, child, 0);
}
public AlignMiddleExp(AComponent parent, AComponent child, int translateY) {
this.parent = parent;
this.child = child;
this.translateY = translateY;
this.translateYProperty = null;
this.bind(parent.clientHeightProperty(), child.boundsHeightProperty());
}
public AlignMiddleExp(AComponent parent, AComponent child, IntegerProperty translateYProperty) {
this.parent = parent;
this.child = child;
this.translateY = 0;
this.translateYProperty = translateYProperty;
this.bind(parent.clientHeightProperty(), child.boundsHeightProperty(), translateYProperty);
}
@Override
public Integer calculate() {
int ty = translateY;
if (translateYProperty != null) {
if (translateYProperty.get() == null) {
ty = 0;
} else {
ty = translateYProperty.get();
}
}
return ((parent.clientHeightProperty().get() - child.boundsHeightProperty().get()) / 2) + ty;
}
}
| 31.741379 | 101 | 0.669202 |
d8af4b799f5d1e2f08810a7a1b8056b7b9745419 | 1,597 | package com.gluk.z2j.app;
import java.io.File;
import java.io.InputStream;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import com.gluk.z2j.model.AbstractDoc;
public class Transformer extends AbstractDoc {
private String name;
private String template;
public Transformer(String dir, String name, String template, String ext) {
this.template = template;
StringBuffer sb = new StringBuffer();
sb.append(dir);
sb.append("/");
int ix = name.lastIndexOf('.');
if (ix > 0) {
sb.append(name.substring(0, ix));
} else {
sb.append(name);
}
sb.append(ext);
this.name = sb.toString();
}
public TransformerHandler getHandler() throws Exception {
init();
return handler;
}
protected void init() throws Exception {
TransformerFactory tf = TransformerFactory.newInstance();
if (tf.getFeature(SAXSource.FEATURE) && tf.getFeature(SAXResult.FEATURE)) {
SAXTransformerFactory stf = (SAXTransformerFactory)tf;
InputStream t = Serializer.class.getResourceAsStream("/xslt/" + template);
handler = stf.newTransformerHandler(new StreamSource(t));
Result result = new StreamResult(new File(name));
handler.setResult(result);
} else {
throw new Exception("Feature unsupported");
}
}
}
| 29.036364 | 84 | 0.725736 |
05cffa24f843ecef7ebb4d202b6820ea776703a3 | 1,003 | package com.bazaarvoice.emodb.blob.client;
import com.bazaarvoice.emodb.blob.api.AuthBlobStore;
import com.bazaarvoice.emodb.blob.api.BlobStore;
import com.bazaarvoice.ostrich.dropwizard.healthcheck.ContainsHealthyEndPointCheck;
import com.bazaarvoice.ostrich.pool.ServicePoolProxies;
/**
* Dropwizard health check.
*/
public class BlobStoreHealthCheck {
public static ContainsHealthyEndPointCheck create(BlobStore blobStore) {
return ContainsHealthyEndPointCheck.forPool(ServicePoolProxies.getPool(toServicePoolProxy(blobStore)));
}
public static ContainsHealthyEndPointCheck create(AuthBlobStore authBlobStore) {
return ContainsHealthyEndPointCheck.forPool(ServicePoolProxies.getPool(authBlobStore));
}
private static Object toServicePoolProxy(BlobStore blobStore) {
if (blobStore instanceof BlobStoreAuthenticatorProxy) {
return ((BlobStoreAuthenticatorProxy) blobStore).getProxiedInstance();
}
return blobStore;
}
}
| 37.148148 | 111 | 0.782652 |
efaee4ade7694670f84cd780b3eb6f3c02a7f217 | 1,959 | package it.besil.jweb.server.conf;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
/**
* Created by besil on 19/07/2016.
*/
public class JWebConfiguration extends Properties {
public JWebConfiguration() throws IOException {
this.load(getClass().getClassLoader().getResourceAsStream("jwebserver.properties"));
}
public JWebConfiguration(String path) throws IOException {
this.load(new FileInputStream(path));
}
public int getServerPort() {
return Integer.parseInt(getProperty(ConfKeys.port.getName()));
}
@Override
public synchronized String toString() {
List<String> keys = this.keySet().stream().map(o -> o.toString()).collect(Collectors.toList());
Collections.sort(keys);
return keys
.stream()
.map(key -> key + ": " + getProperty(key))
.collect(Collectors.joining("\n"));
}
public String getKeystorePath() {
return getProperty(ConfKeys.keystorepath.getName());
}
public String getKeystorePassword() {
return getProperty(ConfKeys.keystorepassword.getName());
}
public String getDatabaseUrl() {
return getProperty(ConfKeys.sessiondburl.getName());
}
public String getDatabaseUser() {
return getProperty(ConfKeys.sessiondbuser.getName());
}
public String getDatabasePassword() {
return getProperty(ConfKeys.sessiondbpassword.getName());
}
public int getSessionTimeout() {
return Integer.parseInt(getProperty(ConfKeys.sessiontimeoutduration.getName()));
}
public String getCookieName() {
return getProperty(ConfKeys.sessioncookiename.getName());
}
public String getStaticFileLocation() {
return getProperty(ConfKeys.staticfilelocation.getName());
}
}
| 27.208333 | 103 | 0.673303 |
04fbe7d38d1b491d794aed8d7f4fa39a83e3e4c3 | 3,278 | package com.theteam.bpmn.engine;
import java.util.*;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.reactivex.Single;
public class Monitor
{
public HubConnection hubConnection;
public Monitor() {
Logger logger = LoggerFactory.getLogger(Monitor.class);
logger.info("Monitor Begin");
//create the connection with token validation don't worry the token expiration date is after 100 years
hubConnection = HubConnectionBuilder.create("http://localhost:5001/DeployWorkflowHub")
/*.withAccessTokenProvider(Single.defer(() -> {
// TODO request Token the put it
return Single.just(/*put your token here"CfDJ8ILPBX-GLhFAhs0mV7u-2ypYX2yGxTouybnBkwFd_gWViN2xmlp9kMedp_ZBCmOBJwU4JBRpD_HKQ7Yz56STlIpcSLaf5Yeq_8hohzoZV7dGJb2opQJ2UCwv40xV5Ty4RkmVy19IxAUFRfG4DKvf2ApsoWKKs1iBet9u_4klmNqHdZe58b8ii5gFbEmCVFV1yg");
})*/.build();
logger.info("Monitor Build");
hubConnection.start();
logger.info("Monitor Started");
//wait for the connection to be established
logger.info("Monitor send add to group");
if(hubConnection.getConnectionState().name() == "CONNECTED")
{
hubConnection.send("AddToGroup","Engine");
logger.info("Monitor send add to group - done");
}
delay(50);
//hubConnection.send("GetCurrentDeployed");
///initialize the deployed list
logger.info("Monitor send InitializeDeployList");
if(hubConnection.getConnectionState().name() == "CONNECTED")
{
hubConnection.send("InitializeDeployList"); // when the engine starts
logger.info("Monitor send InitializeDeployList - done");
}
//String workFlowName = "aa";
//String InstanceId = "aa";
//int runningInstances = 5;
// LA LA LA
//hubConnection.send("updateDeployList" , workFlowName, runningInstances); //when a new workFlow Deployed
/* this should be invoked when the engine starts and you should make an api to
get Running instance for a specific workflow and return {"instance1","instance2",,,}*/
//hubConnection.send("InitializeRuningInstances");
//Add running instance in the client this should be invoked when the A new Instance Created
// hubConnection.send("AddRunningInstance", workFlowName, InstanceId);
// ArrayList<String> nodes = new ArrayList<String>(); //the executed nodes for the instance in the workflow
// this should be invoked At every update in a execution
logger.info("Monitor wait InitializeExecution");
///this a listener
hubConnection.on("InitializeExecution",(workflowID, Instance_Id) ->
{
ArrayList<String> nodes = Workflow.processesRun.get(Instance_Id);
hubConnection.send("UpdateExecution", workflowID, Instance_Id, nodes);
},String.class, String.class);
logger.info("Monitor finished");
}
public void delay(int delay)
{
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public HubConnection getHubConnection()
{
return hubConnection;
}
}
| 31.219048 | 258 | 0.694631 |
7d3a36e31a88316046179a60d845d0fb5d656292 | 1,715 | package com.belonk.net;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by sun on 2021/12/24.
*
* @author [email protected]
* @since 1.0
*/
public class JabberClient {
//~ Static fields/constants/initializer
//~ Instance fields
//~ Constructors
//~ Methods
public static void main(String[] args) throws IOException {
// Passing null to getByName() produces the special "Local Loopback" IP address, for testing on one machine w/o a
// network:
InetAddress addr = InetAddress.getByName(null);
// Alternatively, you can use the address or name:
// InetAddress addr = InetAddress.getByName("127.0.0.1");
// InetAddress addr = InetAddress.getByName("localhost");
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, JabberServer.PORT);
// Guard everything in a try-finally to make sure that the socket is closed:
try {
System.out.println("socket = " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Output is automatically flushed by PrintWriter:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
for (int i = 0; i < 10; i++) {
out.println("howdy " + i);
String str = in.readLine();
System.out.println(str);
}
out.println("END");
} finally {
System.out.println("closing...");
socket.close();
}
/*
addr = localhost/127.0.0.1
// 客户端用本地的端口48981与服务器127.0.0.1的8080端口建立了连接
socket = Socket[addr=localhost/127.0.0.1,port=8080,localport=49891]
howdy 0
howdy 1
howdy 2
howdy 3
howdy 4
howdy 5
howdy 6
howdy 7
howdy 8
howdy 9
closing...
*/
}
} | 25.220588 | 115 | 0.683965 |
a1388c83f4766d8dc2bb24d45d1fd2618de2291c | 2,386 | /*
* Copyright 2009-2020 Tilmann Zaeschke
*
* 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.zoodb.tools.impl;
import org.zoodb.jdo.ZooJdoProperties;
/**
* This interface provides functionality to perform database management operations, such as
* creating and removing database.
*
* By default databases are create in %USER_HOME%/zoodb on Windows or ~/zoodb on Linux/UNIX.
*
* @author ztilmann
*/
public interface DataStoreManager {
/**
* Create a database file.
*
* If only a file name is given, the database will create in %USER_HOME%/zoodb on Windows
* or ~/zoodb on Linux/UNIX.
*
* If a full path is given, the full path will be used instead.
*
* Any necessary parent folders are created automatically.
* It is recommended to use <code>.zdb</code> as file extension, for example
* <code>myDatabase.zdb</code>.
*
* @param dbName The database file name or path
* @see ZooJdoProperties#ZooJdoProperties(String)
*/
void createDb(String dbName);
/**
* Check if a database exists. This checks only whether the file exists, not whether it is a
* valid database file.
*
* @param dbName The database file name or path
* @return <code>true</code> if the database exists.
*/
boolean dbExists(String dbName);
/**
* Delete a database(-file).
* @param dbName The database file name or path
* @return {@code true} if the database could be removed, otherwise false
*/
boolean removeDb(String dbName);
/**
*
* @return The default database folder.
*/
String getDefaultDbFolder();
/**
* Calculates the full path for the given database name, whether the database exists or not.
* @param dbName The database file name or path
* @return The full path of the database given by <code>dbName</code>.
*/
String getDbPath(String dbName);
}
| 30.589744 | 94 | 0.698659 |
d488881e7b1791b86d4f7dfd75bd0943b75175da | 1,200 | package com.testflow.apitest.business;
import com.testflow.apitest.stepdefinations.FileExecutor;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.support.AnnotationConsumer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
public class RangeArgumentsProvider implements ArgumentsProvider, AnnotationConsumer<TestFlowTest> {
private String path;
RangeArgumentsProvider() {
}
@Override
public void accept(TestFlowTest t)
{
path = t.path();
}
@Override
public Stream provideArguments(ExtensionContext context) {
FileExecutor fileExecutor= new FileExecutor();
List<Arguments> list = new ArrayList<>();
try {
List<Map<String, String>> listMap = fileExecutor.loadFile(path);
for (Map<String, String> map : listMap) {
list.add(Arguments.of(map));
}
}
catch (Exception ex)
{
}
return list.stream();
}
}
| 27.272727 | 100 | 0.685 |
4124e9944fad3e9308968ef797fe76392b2b769b | 5,839 | package com.unascribed.yttr.content.block.big;
import java.util.Random;
import com.unascribed.yttr.Yttr;
import com.unascribed.yttr.init.YSounds;
import com.unascribed.yttr.inventory.HighStackGenericContainerScreenHandler;
import com.google.common.base.Ascii;
import net.minecraft.block.Block;
import net.minecraft.block.BlockEntityProvider;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.NamedScreenHandlerFactory;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.state.StateManager.Builder;
import net.minecraft.state.property.DirectionProperty;
import net.minecraft.state.property.EnumProperty;
import net.minecraft.state.property.IntProperty;
import net.minecraft.state.property.Properties;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.ItemScatterer;
import net.minecraft.util.StringIdentifiable;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
public class DSUBlock extends BigBlock implements BlockEntityProvider {
public enum OpenState implements StringIdentifiable {
FALSE,
TRUE,
FORCED,
;
public boolean isFalse() {
return this == FALSE;
}
public boolean isTrue() {
return this != FALSE;
}
public boolean isForced() {
return this == FORCED;
}
@Override
public String asString() {
return Ascii.toLowerCase(name());
}
}
public static final EnumProperty<OpenState> OPEN = EnumProperty.of("open", OpenState.class);
public static final DirectionProperty FACING = Properties.HORIZONTAL_FACING;
public static final IntProperty X = IntProperty.of("x", 0, 1);
public static final IntProperty Y = IntProperty.of("y", 0, 1);
public static final IntProperty Z = IntProperty.of("z", 0, 1);
public DSUBlock(Settings s) {
super(X, Y, Z, s);
setDefaultState(getDefaultState().with(OPEN, OpenState.FALSE));
}
@Override
protected void appendProperties(Builder<Block, BlockState> builder) {
super.appendProperties(builder);
builder.add(OPEN, FACING, X, Y, Z);
}
@Override
public BlockState getPlacementState(ItemPlacementContext ctx) {
return super.getPlacementState(ctx).with(FACING, ctx.getPlayerFacing().getOpposite());
}
@Override
protected BlockState copyState(BlockState us, BlockState neighbor) {
return us.with(OPEN, neighbor.get(OPEN));
}
@Override
public void neighborUpdate(BlockState state, World world, BlockPos pos, Block block, BlockPos fromPos, boolean notify) {
if (!world.isClient) {
boolean cur = state.get(OPEN).isForced();
if (cur != isReceivingRedstonePower(world, pos, state)) {
if (cur) {
world.getBlockTickScheduler().schedule(pos, this, 4);
} else {
if (!state.get(OPEN).isTrue() && !anyNeighborsMatch(world, pos, state, bs -> bs.get(OPEN).isForced())) {
playSound(world, null, pos, state, YSounds.DSU_OPEN, SoundCategory.BLOCKS, 1, 1);
}
world.setBlockState(pos, state.with(OPEN, OpenState.FORCED));
}
}
}
}
@Override
public void scheduledTick(BlockState state, ServerWorld world, BlockPos pos, Random random) {
super.scheduledTick(state, world, pos, random);
if (!isReceivingRedstonePower(world, pos, state)) {
BlockEntity be = world.getBlockEntity(pos);
boolean open = false;
if (be instanceof DSUBlockEntity) {
DSUBlockEntity con = ((DSUBlockEntity)be).getController();
open = con.viewers > 0;
}
if (!open && state.get(OPEN).isTrue()) {
playSound(world, null, pos, state, YSounds.DSU_CLOSE, SoundCategory.BLOCKS, 1, 1);
}
world.setBlockState(pos, state.with(OPEN, open ? OpenState.TRUE : OpenState.FALSE), 2);
}
}
@Override
public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
if (hit.getSide() == state.get(FACING)) {
BlockEntity be = world.getBlockEntity(pos);
if (be instanceof DSUBlockEntity) {
player.openHandledScreen(new NamedScreenHandlerFactory() {
@Override
public ScreenHandler createMenu(int syncId, PlayerInventory inv, PlayerEntity player) {
return HighStackGenericContainerScreenHandler.createGeneric9x5(syncId, inv, (DSUBlockEntity)be);
}
@Override
public Text getDisplayName() {
return new TranslatableText("block.yttr.dsu");
}
});
}
return ActionResult.SUCCESS;
}
return ActionResult.PASS;
}
@Override
public BlockEntity createBlockEntity(BlockView world) {
return new DSUBlockEntity();
}
@Override
public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) {
if (!state.isOf(newState.getBlock()) && state.get(X) == 0 && state.get(Y) == 0 && state.get(Z) == 0) {
BlockEntity be = world.getBlockEntity(pos);
if (be instanceof DSUBlockEntity) {
double x = pos.getX()+(xSize/2D);
double y = pos.getY()+(ySize/2D);
double z = pos.getZ()+(zSize/2D);
for (ItemStack is : Yttr.asList((DSUBlockEntity)be)) {
double xO = (world.random.nextDouble()-world.random.nextDouble())*0.5;
double yO = (world.random.nextDouble()-world.random.nextDouble())*0.5;
double zO = (world.random.nextDouble()-world.random.nextDouble())*0.5;
ItemScatterer.spawn(world, x+xO, y+yO, z+zO, is);
}
}
}
super.onStateReplaced(state, world, pos, newState, moved);
}
}
| 33.176136 | 125 | 0.731975 |
9f61eec54ee06a984371ca1f63e06bcdab399ca3 | 6,289 | // This file was generated by the TNO Bean Generator.
// Any modifications to this file will be lost upon re-generation.
// Generated on: 2020/03/27 12:19:05
package nl.tno.rpr.interactions;
import nl.tno.rpr.datatypes.EntityTypeStruct;
import nl.tno.rpr.datatypes.MinefieldSensorTypeEnum32;
import nl.tno.rpr.datatypes.PerimeterPointStruct;
import nl.tno.rpr.datatypes.RPRboolean;
/**
* Provides the means by which a federate shall query a minefield simulation for information on the
* individual mines within the minefield operating in QRP mode.
*/
public class MinefieldQuery {
/** Identifies the minefield to which this query is addressed */
String MinefieldIdentifier;
/**
* Specifies the location of each perimeter point in the requested area relative to the minefield
* location
*/
PerimeterPointStruct[] PerimeterPoints;
/** Specifies whether or not fusing is requested */
RPRboolean QueryFusing;
/** Specifies whether or not orientation is requested */
RPRboolean QueryMineOrientation;
/** Specifies whether or not ground burial depth offset is requested */
RPRboolean QueryGroundBurialDepthOffset;
/** Specifies whether or not emplacement age is requested */
RPRboolean QueryMineEmplacementAge;
/** Specifies whether or not paint scheme is requested */
RPRboolean QueryPaintScheme;
/** Specifies whether or not reflectance is requested */
RPRboolean QueryReflectance;
/** Specifies whether or not scalar detection coefficient is requested */
RPRboolean QueryScalarDetectionCoefficient;
/** Specifies whether or not snow burial depth offset is requested */
RPRboolean QuerySnowBurialDepthOffset;
/** Specifies whether or not thermal contrast is requested */
RPRboolean QueryThermalContrast;
/** Specifies whether or not trip detonation wire is requested */
RPRboolean QueryTripDetonationWire;
/** Specifies whether or not water burial depth offset is requested */
RPRboolean QueryWaterBurialDepthOffset;
/** Identifies the entity that requests the information from the minefield simulation */
String RequestingEntityIdentifier;
/** Identifies the minefield query request */
byte RequestIdentifier;
/** Identifies the type of mine being queried by the requesting federate */
EntityTypeStruct RequestedMineType;
/** Specifies the types of sensors requesting the data */
MinefieldSensorTypeEnum32[] SensorTypes;
public String getMinefieldIdentifier() {
return this.MinefieldIdentifier;
}
public void setMinefieldIdentifier(String MinefieldIdentifier) {
this.MinefieldIdentifier = MinefieldIdentifier;
}
public PerimeterPointStruct[] getPerimeterPoints() {
return this.PerimeterPoints;
}
public void setPerimeterPoints(PerimeterPointStruct[] PerimeterPoints) {
this.PerimeterPoints = PerimeterPoints;
}
public RPRboolean getQueryFusing() {
return this.QueryFusing;
}
public void setQueryFusing(RPRboolean QueryFusing) {
this.QueryFusing = QueryFusing;
}
public RPRboolean getQueryMineOrientation() {
return this.QueryMineOrientation;
}
public void setQueryMineOrientation(RPRboolean QueryMineOrientation) {
this.QueryMineOrientation = QueryMineOrientation;
}
public RPRboolean getQueryGroundBurialDepthOffset() {
return this.QueryGroundBurialDepthOffset;
}
public void setQueryGroundBurialDepthOffset(RPRboolean QueryGroundBurialDepthOffset) {
this.QueryGroundBurialDepthOffset = QueryGroundBurialDepthOffset;
}
public RPRboolean getQueryMineEmplacementAge() {
return this.QueryMineEmplacementAge;
}
public void setQueryMineEmplacementAge(RPRboolean QueryMineEmplacementAge) {
this.QueryMineEmplacementAge = QueryMineEmplacementAge;
}
public RPRboolean getQueryPaintScheme() {
return this.QueryPaintScheme;
}
public void setQueryPaintScheme(RPRboolean QueryPaintScheme) {
this.QueryPaintScheme = QueryPaintScheme;
}
public RPRboolean getQueryReflectance() {
return this.QueryReflectance;
}
public void setQueryReflectance(RPRboolean QueryReflectance) {
this.QueryReflectance = QueryReflectance;
}
public RPRboolean getQueryScalarDetectionCoefficient() {
return this.QueryScalarDetectionCoefficient;
}
public void setQueryScalarDetectionCoefficient(RPRboolean QueryScalarDetectionCoefficient) {
this.QueryScalarDetectionCoefficient = QueryScalarDetectionCoefficient;
}
public RPRboolean getQuerySnowBurialDepthOffset() {
return this.QuerySnowBurialDepthOffset;
}
public void setQuerySnowBurialDepthOffset(RPRboolean QuerySnowBurialDepthOffset) {
this.QuerySnowBurialDepthOffset = QuerySnowBurialDepthOffset;
}
public RPRboolean getQueryThermalContrast() {
return this.QueryThermalContrast;
}
public void setQueryThermalContrast(RPRboolean QueryThermalContrast) {
this.QueryThermalContrast = QueryThermalContrast;
}
public RPRboolean getQueryTripDetonationWire() {
return this.QueryTripDetonationWire;
}
public void setQueryTripDetonationWire(RPRboolean QueryTripDetonationWire) {
this.QueryTripDetonationWire = QueryTripDetonationWire;
}
public RPRboolean getQueryWaterBurialDepthOffset() {
return this.QueryWaterBurialDepthOffset;
}
public void setQueryWaterBurialDepthOffset(RPRboolean QueryWaterBurialDepthOffset) {
this.QueryWaterBurialDepthOffset = QueryWaterBurialDepthOffset;
}
public String getRequestingEntityIdentifier() {
return this.RequestingEntityIdentifier;
}
public void setRequestingEntityIdentifier(String RequestingEntityIdentifier) {
this.RequestingEntityIdentifier = RequestingEntityIdentifier;
}
public byte getRequestIdentifier() {
return this.RequestIdentifier;
}
public void setRequestIdentifier(byte RequestIdentifier) {
this.RequestIdentifier = RequestIdentifier;
}
public EntityTypeStruct getRequestedMineType() {
return this.RequestedMineType;
}
public void setRequestedMineType(EntityTypeStruct RequestedMineType) {
this.RequestedMineType = RequestedMineType;
}
public MinefieldSensorTypeEnum32[] getSensorTypes() {
return this.SensorTypes;
}
public void setSensorTypes(MinefieldSensorTypeEnum32[] SensorTypes) {
this.SensorTypes = SensorTypes;
}
}
| 30.235577 | 99 | 0.784385 |
ed0bf34d53226e02434c818c1f802e9d4c830909 | 358 | package de.saxsys.workshop_cdi.exercise_01;
import javax.inject.Inject;
public class MethodInjection {
private CDIGreeting greeting;
public CDIGreeting getGreeting() {
return greeting;
}
@Inject
protected void setCDIGreeting(CDIGreeting greeting) {
this.greeting = greeting;
}
public String greet() {
return greeting.sayHello();
}
}
| 15.565217 | 54 | 0.743017 |
38376c19d148e6d919ec2d23388afdab65f4f0e9 | 276 | package scaffold.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ScaffoldPluginTests {
@Test
void livingInModuleScaffold() {
assertEquals("scaffold", ScaffoldPluginTests.class.getModule().getName());
}
}
| 21.230769 | 78 | 0.768116 |
b69e938ad6218048527d90594865221d3544fb42 | 1,358 | package com.divitbui.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import com.fasterxml.jackson.module.blackbird.BlackbirdModule;
import lombok.Getter;
@Getter
public class JacksonConfig {
private ObjectMapper defaultJacksonObjectMapper = new ObjectMapper().registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
private ObjectMapper afterbunerJacksonObjectMapper = new ObjectMapper().registerModule(new JavaTimeModule())
.registerModules(new AfterburnerModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
private ObjectMapper blackbirdJacksonObjectMapper = new ObjectMapper().registerModule(new JavaTimeModule())
.registerModules(new BlackbirdModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
| 59.043478 | 132 | 0.61782 |
60602bd7ca8ae8a0510d22680347f53e01e61df8 | 2,521 | package com.ss.editor.extension.util;
import com.jme3.bullet.control.PhysicsControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.light.Light;
import com.jme3.light.LightList;
import com.jme3.scene.SceneGraphVisitor;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import org.jetbrains.annotations.NotNull;
/**
* The utility methods from jMB extension library.
*
* @author JavaSaBr
*/
public class JmbExtUtils {
@NotNull
public static final SceneGraphVisitor RESET_PHYSICS_VISITOR = new SceneGraphVisitor() {
@Override
public void visit(@NotNull Spatial spatial) {
int numControls = spatial.getNumControls();
for (int i = 0; i < numControls; i++) {
Control control = spatial.getControl(i);
if (!(control instanceof PhysicsControl) || !((PhysicsControl) control).isEnabled()) {
continue;
}
if (control instanceof RigidBodyControl) {
RigidBodyControl bodyControl = (RigidBodyControl) control;
boolean kinematic = bodyControl.isKinematic();
boolean kinematicSpatial = bodyControl.isKinematicSpatial();
bodyControl.setKinematic(true);
bodyControl.setKinematicSpatial(true);
bodyControl.clearForces();
bodyControl.update(0);
bodyControl.setKinematic(kinematic);
bodyControl.setKinematicSpatial(kinematicSpatial);
}
}
}
};
/**
* Reset physics control's positions in the spatial.
*
* @param spatial the spatial.
*/
public static void resetPhysicsControlPositions(@NotNull Spatial spatial) {
spatial.depthFirstTraversal(RESET_PHYSICS_VISITOR);
}
/**
* Check of existing the light in the local light list of the spatial.
*
* @param spatial the spatial.
* @param light the light.
* @return true if the light is already in the local light list.
*/
public static boolean contains(@NotNull Spatial spatial, @NotNull Light light) {
LightList lightList = spatial.getLocalLightList();
if (lightList.size() == 0) {
return false;
}
for (int i = 0; i < lightList.size(); i++) {
if (lightList.get(i) == light) {
return true;
}
}
return false;
}
}
| 31.5125 | 102 | 0.603332 |
15b767432fcc36ef2a48e1ae513ce5bd6028dae8 | 2,108 | package com.xqbase.bn.schema;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class TestRecordSchema extends SchemaTestBase {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[]{"{\"type\":\"record\",\"name\":\"LongList\"," +
"\"fields\":[{\"name\":\"f1\",\"type\":\"long\"}," +
"{\"name\":\"f2\",\"type\": \"int\"}]}",
new String[]{"f1", "long", "100", "f2", "int", "10"}},
new Object[]{"{\"type\":\"record\",\"name\":\"LongList\"," +
"\"fields\":[{\"name\":\"f1\",\"type\":\"long\", \"default\": \"100\"}," +
"{\"name\":\"f2\",\"type\": \"int\"}]}",
new String[]{"f1", "long", "100", "f2", "int", "10"}},
new Object[]{"{\"type\":\"record\",\"name\":\"LongList\"," +
"\"fields\":[{\"name\":\"value\",\"type\":\"long\", \"default\": \"100\"}," +
"{\"name\":\"next\",\"type\":[\"LongList\",\"null\"]}]}",
new String[]{"value", "long", "100", "next", "union", null}});
}
private final String schema;
private final String[] fields;
public TestRecordSchema(String schema, String[] fields) {
this.schema = schema;
this.fields = fields;
}
@Test
public void testRecord() {
Schema sc = Schema.parse(schema);
Assert.assertEquals(SchemaType.RECORD, sc.getType());
Assert.assertTrue(sc instanceof RecordSchema);
RecordSchema record = (RecordSchema) sc;
Assert.assertEquals(fields.length / 3, record.getFieldsSize());
for (int i = 0; i < fields.length; i += 3) {
Field f = record.getField(fields[i]);
Assert.assertEquals(fields[i + 1], f.getSchema().getName());
}
testEquality(schema, sc);
testToString(sc);
}
}
| 39.037037 | 101 | 0.517078 |
2ef3a8850363828ea69bd02dd5b0f23a99c390bb | 74 | package com.migration.refactoring_rules.model;
public class Function {
}
| 14.8 | 46 | 0.810811 |
42c98fa19531d9ea21c6aa71912bc92638dd3e85 | 422 | package tech.taoq.web.mvc.result;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 如不希望被 ResultResponseBodyAdvice 代理时,可在方法上增加此注解
*
* @author keqi
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface NoAdvice {
}
| 21.1 | 59 | 0.796209 |
1c97e833ded1d8666b5a0c354e35d698d6126615 | 874 | package jscast.ui;
import javafx.fxml.FXML;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class FrameSamplerController {
// the FXML area for showing the current frame
@FXML
private ImageView originalFrame;
/**
* Init the controller, at start time
*/
public void init() {
// set a fixed width for the frame
originalFrame.setFitWidth(600);
// preserve image ratio
originalFrame.setPreserveRatio(true);
}
/**
* On application close, stop the acquisition from the camera
*/
public void setClosed() {
System.exit(0);
}
/**
* Update the {@link ImageView} in the JavaFX main thread
*
* @param image the {@link Image} to show
*/
public void updateImageView(Image image) {
originalFrame.setImage(image);
}
}
| 21.85 | 65 | 0.630435 |
6b0d0f110d94d9e9ea236db8b283c32bead937ee | 14,632 | package com.zhongjh.albumcamerarecorder.preview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zhongjh.albumcamerarecorder.R;
import gaode.zhongjh.com.common.entity.IncapableCause;
import gaode.zhongjh.com.common.entity.MultiMedia;
import gaode.zhongjh.com.common.widget.IncapableDialog;
import com.zhongjh.albumcamerarecorder.album.utils.PhotoMetadataUtils;
import com.zhongjh.albumcamerarecorder.preview.adapter.PreviewPagerAdapter;
import com.zhongjh.albumcamerarecorder.preview.previewitem.PreviewItemFragment;
import com.zhongjh.albumcamerarecorder.settings.AlbumSpec;
import com.zhongjh.albumcamerarecorder.settings.GlobalSpec;
import com.zhongjh.albumcamerarecorder.album.model.SelectedItemCollection;
import com.zhongjh.albumcamerarecorder.album.widget.CheckRadioView;
import com.zhongjh.albumcamerarecorder.album.widget.CheckView;
import com.zhongjh.albumcamerarecorder.album.widget.PreviewViewPager;
import com.zhongjh.albumcamerarecorder.utils.VersionUtils;
/**
* 预览的基类
*/
public class BasePreviewActivity extends AppCompatActivity implements View.OnClickListener,
ViewPager.OnPageChangeListener {
public static final String EXTRA_IS_ALLOW_REPEAT = "extra_is_allow_repeat";
public static final String EXTRA_DEFAULT_BUNDLE = "extra_default_bundle";
public static final String EXTRA_RESULT_BUNDLE = "extra_result_bundle";
public static final String EXTRA_RESULT_APPLY = "extra_result_apply";
public static final String EXTRA_RESULT_ORIGINAL_ENABLE = "extra_result_original_enable";
public static final String CHECK_STATE = "checkState";
public static final String ENABLE_OPERATION = "enable_operation";
public static final String IS_SELECTED_LISTENER = "is_selected_listener";
public static final String IS_SELECTED_CHECK = "is_selected_check";
protected final SelectedItemCollection mSelectedCollection = new SelectedItemCollection(this);
protected GlobalSpec mGlobalSpec;
protected AlbumSpec mAlbumSpec;
protected PreviewPagerAdapter mAdapter;
protected boolean mOriginalEnable; // 是否原图
protected int mPreviousPos = -1; // 当前预览的图片的索引
protected boolean mEnableOperation = true; // 启用操作,默认true,也不启动右上角的选择框自定义触发事件
protected boolean mIsSelectedListener = true; // 是否触发选择事件,目前除了相册功能没问题之外,别的触发都会闪退,原因是uri不是通过数据库而获得的
protected boolean mIsSelectedCheck = true; // 设置右上角是否检测类型
protected ViewHolder mViewHolder;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
setTheme(GlobalSpec.getInstance().themeId); // 获取样式
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_preview_zjh);
if (VersionUtils.hasKitKat()) {
// 使用沉倾状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
mGlobalSpec = GlobalSpec.getInstance();
mAlbumSpec = AlbumSpec.getInstance();
boolean isAllowRepeat = getIntent().getBooleanExtra(EXTRA_IS_ALLOW_REPEAT, false);
mEnableOperation = getIntent().getBooleanExtra(ENABLE_OPERATION, true);
mIsSelectedListener = getIntent().getBooleanExtra(IS_SELECTED_LISTENER,true);
mIsSelectedCheck = getIntent().getBooleanExtra(IS_SELECTED_CHECK,true);
if (savedInstanceState == null) {
// 初始化别的界面传递过来的数据
mSelectedCollection.onCreate(getIntent().getBundleExtra(EXTRA_DEFAULT_BUNDLE), isAllowRepeat);
mOriginalEnable = getIntent().getBooleanExtra(EXTRA_RESULT_ORIGINAL_ENABLE, false);
} else {
// 初始化缓存的数据
mSelectedCollection.onCreate(savedInstanceState, isAllowRepeat);
mOriginalEnable = savedInstanceState.getBoolean(CHECK_STATE);
}
mViewHolder = new ViewHolder(this);
mAdapter = new PreviewPagerAdapter(getSupportFragmentManager(), null);
mViewHolder.pager.setAdapter(mAdapter);
mViewHolder.check_view.setCountable(mAlbumSpec.countable);
initListener();
}
/**
* 所有事件
*/
private void initListener() {
// 返回
mViewHolder.button_back.setOnClickListener(this);
// 确认
mViewHolder.button_apply.setOnClickListener(this);
// 多图时滑动事件
mViewHolder.pager.addOnPageChangeListener(this);
// 右上角选择事件
mViewHolder.check_view.setOnClickListener(v -> {
MultiMedia item = mAdapter.getMediaItem(mViewHolder.pager.getCurrentItem());
if (mSelectedCollection.isSelected(item)) {
mSelectedCollection.remove(item);
if (mAlbumSpec.countable) {
mViewHolder.check_view.setCheckedNum(CheckView.UNCHECKED);
} else {
mViewHolder.check_view.setChecked(false);
}
} else {
boolean isTrue = true;
if (mIsSelectedCheck)
isTrue = assertAddSelection(item);
if (isTrue) {
mSelectedCollection.add(item);
if (mAlbumSpec.countable) {
mViewHolder.check_view.setCheckedNum(mSelectedCollection.checkedNumOf(item));
} else {
mViewHolder.check_view.setChecked(true);
}
}
}
updateApplyButton();
if (mAlbumSpec.onSelectedListener != null && mIsSelectedListener) {
// 触发选择的接口事件
mAlbumSpec.onSelectedListener.onSelected(
mSelectedCollection.asListOfUri(), mSelectedCollection.asListOfString());
}
});
// 点击原图事件
mViewHolder.originalLayout.setOnClickListener(v -> {
int count = countOverMaxSize();
if (count > 0) {
IncapableDialog incapableDialog = IncapableDialog.newInstance("",
getString(R.string.error_over_original_count, count, mAlbumSpec.originalMaxSize));
incapableDialog.show(getSupportFragmentManager(),
IncapableDialog.class.getName());
return;
}
mOriginalEnable = !mOriginalEnable;
mViewHolder.original.setChecked(mOriginalEnable);
if (!mOriginalEnable) {
mViewHolder.original.setColor(Color.WHITE);
}
if (mAlbumSpec.onCheckedListener != null) {
mAlbumSpec.onCheckedListener.onCheck(mOriginalEnable);
}
});
updateApplyButton();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
mSelectedCollection.onSaveInstanceState(outState);
outState.putBoolean("checkState", mOriginalEnable);
super.onSaveInstanceState(outState);
}
@Override
public void onBackPressed() {
sendBackResult(false);
super.onBackPressed();
}
@Override
public void finish() {
super.finish();
if (mGlobalSpec.isCutscenes)
//关闭窗体动画显示
this.overridePendingTransition(0, R.anim.activity_close);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.button_back) {
onBackPressed();
} else if (v.getId() == R.id.button_apply) {
sendBackResult(true);
finish();
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
/**
* 滑动事件
*
* @param position 索引
*/
@Override
public void onPageSelected(int position) {
PreviewPagerAdapter adapter = (PreviewPagerAdapter) mViewHolder.pager.getAdapter();
if (mPreviousPos != -1 && mPreviousPos != position) {
((PreviewItemFragment) adapter.instantiateItem(mViewHolder.pager, mPreviousPos)).resetView();
MultiMedia item = adapter.getMediaItem(position);
if (mAlbumSpec.countable) {
int checkedNum = mSelectedCollection.checkedNumOf(item);
mViewHolder.check_view.setCheckedNum(checkedNum);
if (checkedNum > 0) {
mViewHolder.check_view.setEnabled(true);
} else {
mViewHolder.check_view.setEnabled(!mSelectedCollection.maxSelectableReached());
}
} else {
boolean checked = mSelectedCollection.isSelected(item);
mViewHolder.check_view.setChecked(checked);
if (checked) {
mViewHolder.check_view.setEnabled(true);
} else {
mViewHolder.check_view.setEnabled(!mSelectedCollection.maxSelectableReached());
}
}
updateSize(item);
}
mPreviousPos = position;
}
@Override
public void onPageScrollStateChanged(int i) {
}
/**
* 更新确定按钮状态
*/
private void updateApplyButton() {
// 获取已选的图片
int selectedCount = mSelectedCollection.count();
if (selectedCount == 0) {
// 禁用
mViewHolder.button_apply.setText(R.string.button_sure_default);
mViewHolder.button_apply.setEnabled(false);
} else if (selectedCount == 1 && mAlbumSpec.singleSelectionModeEnabled()) {
// 如果只选择一张或者配置只能选一张,或者不显示数字的时候。启用,不显示数字
mViewHolder.button_apply.setText(R.string.button_sure_default);
mViewHolder.button_apply.setEnabled(true);
} else {
// 启用,显示数字
mViewHolder.button_apply.setEnabled(true);
mViewHolder.button_apply.setText(getString(R.string.button_sure, selectedCount));
}
// 判断是否开启原图
if (mAlbumSpec.originalable) {
// 显示
mViewHolder.originalLayout.setVisibility(View.VISIBLE);
updateOriginalState();
} else {
// 隐藏
mViewHolder.originalLayout.setVisibility(View.GONE);
}
// 判断是否启动操作
if (!mEnableOperation){
mViewHolder.button_apply.setVisibility(View.GONE);
mViewHolder.check_view.setVisibility(View.GONE);
}else{
mViewHolder.button_apply.setVisibility(View.VISIBLE);
mViewHolder.check_view.setVisibility(View.VISIBLE);
}
}
/**
* 更新原图按钮状态
*/
private void updateOriginalState() {
// 设置原图按钮根据配置来
mViewHolder.original.setChecked(mOriginalEnable);
if (!mOriginalEnable) {
mViewHolder.original.setColor(Color.WHITE);
}
if (countOverMaxSize() > 0) {
// 如果开启了原图功能
if (mOriginalEnable) {
// 弹框提示取消原图
IncapableDialog incapableDialog = IncapableDialog.newInstance("",
getString(R.string.error_over_original_size, mAlbumSpec.originalMaxSize));
incapableDialog.show(getSupportFragmentManager(),
IncapableDialog.class.getName());
// 去掉原图按钮的选择状态
mViewHolder.original.setChecked(false);
mViewHolder.original.setColor(Color.WHITE);
mOriginalEnable = false;
}
}
}
/**
* 获取当前超过限制原图大小的数量
*
* @return 数量
*/
private int countOverMaxSize() {
int count = 0;
int selectedCount = mSelectedCollection.count();
for (int i = 0; i < selectedCount; i++) {
MultiMedia item = mSelectedCollection.asList().get(i);
if (item.isImage()) {
float size = PhotoMetadataUtils.getSizeInMB(item.size);
if (size > mAlbumSpec.originalMaxSize) {
count++;
}
}
}
return count;
}
/**
* 如果当前item是gif就显示多少M的文本
* 如果当前item是video就显示播放按钮
*
* @param item 当前图片
*/
@SuppressLint("SetTextI18n")
protected void updateSize(MultiMedia item) {
if (item.isGif()) {
mViewHolder.size.setVisibility(View.VISIBLE);
mViewHolder.size.setText(PhotoMetadataUtils.getSizeInMB(item.size) + "M");
} else {
mViewHolder.size.setVisibility(View.GONE);
}
if (item.isVideo()) {
mViewHolder.originalLayout.setVisibility(View.GONE);
} else if (mAlbumSpec.originalable) {
mViewHolder.originalLayout.setVisibility(View.VISIBLE);
}
}
/**
* 设置返回值
*
* @param apply 是否同意
*/
protected void sendBackResult(boolean apply) {
Intent intent = new Intent();
intent.putExtra(EXTRA_RESULT_BUNDLE, mSelectedCollection.getDataWithBundle());
intent.putExtra(EXTRA_RESULT_APPLY, apply);
intent.putExtra(EXTRA_RESULT_ORIGINAL_ENABLE, mOriginalEnable);
setResult(Activity.RESULT_OK, intent);
}
/**
* 处理窗口
*
* @param item 当前图片
* @return 为true则代表符合规则
*/
private boolean assertAddSelection(MultiMedia item) {
IncapableCause cause = mSelectedCollection.isAcceptable(item);
IncapableCause.handleCause(this, cause);
return cause == null;
}
public static class ViewHolder {
public Activity activity;
public PreviewViewPager pager;
TextView button_back;
public CheckRadioView original;
public LinearLayout originalLayout;
public TextView size;
public TextView button_apply;
public FrameLayout bottom_toolbar;
public CheckView check_view;
ViewHolder(Activity activity) {
this.activity = activity;
this.pager = activity.findViewById(R.id.pager);
this.button_back = activity.findViewById(R.id.button_back);
this.original = activity.findViewById(R.id.original);
this.originalLayout = activity.findViewById(R.id.originalLayout);
this.size = activity.findViewById(R.id.size);
this.button_apply = activity.findViewById(R.id.button_apply);
this.bottom_toolbar = activity.findViewById(R.id.bottom_toolbar);
this.check_view = activity.findViewById(R.id.check_view);
}
}
}
| 36.671679 | 106 | 0.638464 |
60c9113c524821da748269386a4aa2f48d9a80d0 | 4,937 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.portal.rest.resource;
import io.gravitee.common.http.MediaType;
import io.gravitee.rest.api.model.api.ApiQuery;
import io.gravitee.rest.api.model.documentation.PageQuery;
import io.gravitee.rest.api.portal.rest.mapper.PageMapper;
import io.gravitee.rest.api.portal.rest.model.Page;
import io.gravitee.rest.api.portal.rest.resource.param.PaginationParam;
import io.gravitee.rest.api.portal.rest.security.RequirePortalAuth;
import io.gravitee.rest.api.portal.rest.utils.HttpHeadersUtil;
import io.gravitee.rest.api.portal.rest.utils.PortalApiLinkHelper;
import io.gravitee.rest.api.service.AccessControlService;
import io.gravitee.rest.api.service.PageService;
import io.gravitee.rest.api.service.exceptions.ApiNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
/**
* @author Florent CHAMFROY (florent.chamfroy at graviteesource.com)
* @author GraviteeSource Team
*/
public class ApiPagesResource extends AbstractResource {
@Inject
private PageMapper pageMapper;
@Inject
private PageService pageService;
@Context
private ResourceContext resourceContext;
@Inject
private AccessControlService accessControlService;
@GET
@Produces(MediaType.APPLICATION_JSON)
@RequirePortalAuth
public Response getPagesByApiId(
@HeaderParam("Accept-Language") String acceptLang,
@PathParam("apiId") String apiId,
@BeanParam PaginationParam paginationParam,
@QueryParam("homepage") Boolean homepage,
@QueryParam("parent") String parent
) {
final ApiQuery apiQuery = new ApiQuery();
apiQuery.setIds(Collections.singletonList(apiId));
if (accessControlService.canAccessApiFromPortal(apiId)) {
final String acceptedLocale = HttpHeadersUtil.getFirstAcceptedLocaleName(acceptLang);
Stream<Page> pageStream = pageService
.search(new PageQuery.Builder().api(apiId).homepage(homepage).published(true).build(), acceptedLocale)
.stream()
.filter(accessControlService::canAccessPageFromPortal)
.map(pageMapper::convert)
.map(page -> this.addPageLink(apiId, page));
List<Page> pages;
if (parent != null) {
pages = new ArrayList<>();
Map<String, Page> pagesMap = pageStream.collect(Collectors.toMap(Page::getId, page -> page));
pagesMap
.values()
.forEach(
page -> {
List<String> ancestors = this.getAncestors(pagesMap, page);
if (ancestors.contains(parent)) {
pages.add(page);
}
}
);
} else {
pages = pageStream.collect(Collectors.toList());
}
return createListResponse(pages, paginationParam);
}
throw new ApiNotFoundException(apiId);
}
private List<String> getAncestors(Map<String, Page> pages, Page page) {
List<String> ancestors = new ArrayList<>();
String parentId = page.getParent();
if (parentId == null) {
return ancestors;
}
ancestors.add(parentId);
Page parentPage = pages.get(parentId);
if (parentPage != null) {
ancestors.addAll(getAncestors(pages, parentPage));
}
return ancestors;
}
@Path("{pageId}")
public ApiPageResource getApiPageResource() {
return resourceContext.getResource(ApiPageResource.class);
}
private Page addPageLink(String apiId, Page page) {
return page.links(
pageMapper.computePageLinks(
PortalApiLinkHelper.apiPagesURL(uriInfo.getBaseUriBuilder(), apiId, page.getId()),
PortalApiLinkHelper.apiPagesURL(uriInfo.getBaseUriBuilder(), apiId, page.getParent())
)
);
}
}
| 36.57037 | 118 | 0.658902 |
ac890560a818d7b96273b780465c40f5969a1c43 | 1,358 |
public class DifferentEquals
{
/**
A demonstration to see how == and an equalArrays method are different.
*/
public static void main(String[] args)
{
int[] c = new int[10];
int[] d = new int[10];
int i;
for (i = 0; i < c.length; i++)
c[i] = i;
for (i = 0; i < d.length; i++)
d[i] = i;
if (c == d)
System.out.println("c and d are equal by ==.");
else
System.out.println("c and d are not equal by ==.");
System.out.println("== only tests memory addresses.");
if (equalArrays(c, d))
System.out.println(
"c and d are equal by the equalArrays method.");
else
System.out.println(
"c and d are not equal by the equalArrays method.");
System.out.println(
"An equalArrays method is usually a more useful test.");
}
public static boolean equalArrays(int[] a, int[] b)
{
if (a.length != b.length)
return false;
else
{
int i = 0;
while (i < a.length)
{
if (a[i] != b[i])
return false;
i++;
}
}
return true;
}
}
| 23.824561 | 76 | 0.430781 |
7e15cfc697365cf47e95f2e392485ea20f67fd01 | 880 | package uk.co.idv.otp.adapter.delivery;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import uk.co.idv.otp.entities.delivery.DeliveryRequest;
import uk.co.idv.otp.usecases.send.deliver.DeliverOtpByMethod;
@Builder
@Slf4j
public class SesDeliverOtp implements DeliverOtpByMethod {
private final SesDeliveryRequestConverter requestConverter;
private final AmazonSimpleEmailService client;
@Override
public String getDeliveryMethodName() {
return "email";
}
@Override
public String deliver(DeliveryRequest request) {
var sendEmailRequest = requestConverter.toSendEmailRequest(request);
log.debug("sending email request {}", sendEmailRequest);
var result = client.sendEmail(sendEmailRequest);
return result.getMessageId();
}
}
| 29.333333 | 76 | 0.760227 |
4a9295731c9ab9e7a782c9d2e1ac0a92637a099f | 17,480 | package edu.internet2.middleware.grouperMessagingRabbitmq;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP.Basic.RecoverOk;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.Confirm.SelectOk;
import com.rabbitmq.client.AMQP.Exchange.BindOk;
import com.rabbitmq.client.AMQP.Exchange.DeclareOk;
import com.rabbitmq.client.AMQP.Exchange.DeleteOk;
import com.rabbitmq.client.AMQP.Exchange.UnbindOk;
import com.rabbitmq.client.AMQP.Queue.PurgeOk;
import com.rabbitmq.client.AMQP.Tx.CommitOk;
import com.rabbitmq.client.AMQP.Tx.RollbackOk;
import com.rabbitmq.client.BlockedListener;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Command;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.ExceptionHandler;
import com.rabbitmq.client.FlowListener;
import com.rabbitmq.client.GetResponse;
import com.rabbitmq.client.Method;
import com.rabbitmq.client.ReturnListener;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
public enum RabbitMQConnectionFactoryFake implements RabbitMQConnectionFactory {
INSTANACE {
@Override
public Connection getConnection(String messagingSystemName) {
return new FakeConnection();
}
@Override
public void closeConnection(String messagingSystemName) {
}
};
}
class FakeConnection implements com.rabbitmq.client.Connection {
public static final Map<String, List<? extends Object>> recordedValues = new HashMap<String, List<? extends Object>>();
@Override
public void addShutdownListener(ShutdownListener arg0) {
// TODO Auto-generated method stub
}
@Override
public ShutdownSignalException getCloseReason() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isOpen() {
// TODO Auto-generated method stub
return false;
}
@Override
public void notifyListeners() {
// TODO Auto-generated method stub
}
@Override
public void removeShutdownListener(ShutdownListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void abort() {
// TODO Auto-generated method stub
}
@Override
public void abort(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void abort(int arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
public void abort(int arg0, String arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void addBlockedListener(BlockedListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void clearBlockedListeners() {
// TODO Auto-generated method stub
}
@Override
public void close() throws IOException {
// TODO Auto-generated method stub
}
@Override
public void close(int arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void close(int arg0, String arg1) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void close(int arg0, String arg1, int arg2) throws IOException {
// TODO Auto-generated method stub
}
@Override
public Channel createChannel() throws IOException {
return new FakeChannel();
}
@Override
public Channel createChannel(int arg0) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public InetAddress getAddress() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getChannelMax() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Map<String, Object> getClientProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getClientProvidedName() {
// TODO Auto-generated method stub
return null;
}
@Override
public ExceptionHandler getExceptionHandler() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getFrameMax() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getHeartbeat() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getId() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Map<String, Object> getServerProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean removeBlockedListener(BlockedListener arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setId(String arg0) {
// TODO Auto-generated method stub
}
}
class FakeChannel implements Channel {
@Override
public void addShutdownListener(ShutdownListener arg0) {
// TODO Auto-generated method stub
}
@Override
public ShutdownSignalException getCloseReason() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isOpen() {
// TODO Auto-generated method stub
return false;
}
@Override
public void notifyListeners() {
// TODO Auto-generated method stub
}
@Override
public void removeShutdownListener(ShutdownListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void abort() throws IOException {
// TODO Auto-generated method stub
}
@Override
public void abort(int arg0, String arg1) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void addConfirmListener(ConfirmListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void addFlowListener(FlowListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void addReturnListener(ReturnListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void asyncRpc(Method arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void basicAck(long arg0, boolean arg1) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void basicCancel(String arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
public String basicConsume(String arg0, Consumer arg1) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String basicConsume(String arg0, boolean arg1, Consumer arg2) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String basicConsume(String arg0, boolean arg1, Map<String, Object> arg2, Consumer arg3) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String basicConsume(String arg0, boolean arg1, String arg2, Consumer arg3) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String basicConsume(String arg0, boolean arg1, String arg2, boolean arg3, boolean arg4,
Map<String, Object> arg5, Consumer arg6) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public GetResponse basicGet(String arg0, boolean arg1) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void basicNack(long arg0, boolean arg1, boolean arg2) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void basicPublish(String arg0, String arg1, BasicProperties arg2, byte[] arg3) throws IOException {
// TODO Auto-generated method stub
FakeConnection.recordedValues.put("basicPublish", Arrays.asList(arg0, arg1, arg2, arg3));
}
@Override
public void basicPublish(String arg0, String arg1, boolean arg2, BasicProperties arg3, byte[] arg4)
throws IOException {
// TODO Auto-generated method stub
}
@Override
public void basicPublish(String arg0, String arg1, boolean arg2, boolean arg3, BasicProperties arg4, byte[] arg5)
throws IOException {
// TODO Auto-generated method stub
}
@Override
public void basicQos(int arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void basicQos(int arg0, boolean arg1) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void basicQos(int arg0, int arg1, boolean arg2) throws IOException {
// TODO Auto-generated method stub
}
@Override
public RecoverOk basicRecover() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public RecoverOk basicRecover(boolean arg0) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void basicReject(long arg0, boolean arg1) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void clearConfirmListeners() {
// TODO Auto-generated method stub
}
@Override
public void clearFlowListeners() {
// TODO Auto-generated method stub
}
@Override
public void clearReturnListeners() {
// TODO Auto-generated method stub
}
@Override
public void close() throws IOException, TimeoutException {
FakeConnection.recordedValues.put("close", Arrays.asList());
}
@Override
public void close(int arg0, String arg1) throws IOException, TimeoutException {
// TODO Auto-generated method stub
}
@Override
public SelectOk confirmSelect() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public long consumerCount(String arg0) throws IOException {
// TODO Auto-generated method stub
return 0;
}
@Override
public BindOk exchangeBind(String arg0, String arg1, String arg2) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public BindOk exchangeBind(String arg0, String arg1, String arg2, Map<String, Object> arg3) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void exchangeBindNoWait(String arg0, String arg1, String arg2, Map<String, Object> arg3) throws IOException {
// TODO Auto-generated method stub
}
@Override
public DeclareOk exchangeDeclare(String arg0, String arg1) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public DeclareOk exchangeDeclare(String arg0, BuiltinExchangeType arg1) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public DeclareOk exchangeDeclare(String arg0, String arg1, boolean arg2) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public DeclareOk exchangeDeclare(String arg0, BuiltinExchangeType arg1, boolean arg2) throws IOException {
FakeConnection.recordedValues.put("exchangeDeclare", Arrays.asList(arg0, arg1, arg2));
return null;
}
@Override
public DeclareOk exchangeDeclare(String arg0, String arg1, boolean arg2, boolean arg3, Map<String, Object> arg4)
throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public DeclareOk exchangeDeclare(String arg0, BuiltinExchangeType arg1, boolean arg2, boolean arg3,
Map<String, Object> arg4) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public DeclareOk exchangeDeclare(String arg0, String arg1, boolean arg2, boolean arg3, boolean arg4,
Map<String, Object> arg5) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public DeclareOk exchangeDeclare(String arg0, BuiltinExchangeType arg1, boolean arg2, boolean arg3, boolean arg4,
Map<String, Object> arg5) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void exchangeDeclareNoWait(String arg0, String arg1, boolean arg2, boolean arg3, boolean arg4,
Map<String, Object> arg5) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void exchangeDeclareNoWait(String arg0, BuiltinExchangeType arg1, boolean arg2, boolean arg3, boolean arg4,
Map<String, Object> arg5) throws IOException {
// TODO Auto-generated method stub
}
@Override
public DeclareOk exchangeDeclarePassive(String arg0) throws IOException {
FakeConnection.recordedValues.put("exchangeDeclarePassive", Arrays.asList(arg0));
return null;
}
@Override
public DeleteOk exchangeDelete(String arg0) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public DeleteOk exchangeDelete(String arg0, boolean arg1) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void exchangeDeleteNoWait(String arg0, boolean arg1) throws IOException {
}
@Override
public UnbindOk exchangeUnbind(String arg0, String arg1, String arg2) throws IOException {
return null;
}
@Override
public UnbindOk exchangeUnbind(String arg0, String arg1, String arg2, Map<String, Object> arg3) throws IOException {
return null;
}
@Override
public void exchangeUnbindNoWait(String arg0, String arg1, String arg2, Map<String, Object> arg3) throws IOException {
}
@Override
public boolean flowBlocked() {
return false;
}
@Override
public int getChannelNumber() {
return 0;
}
@Override
public Connection getConnection() {
return null;
}
@Override
public Consumer getDefaultConsumer() {
return null;
}
@Override
public long getNextPublishSeqNo() {
return 0;
}
@Override
public long messageCount(String arg0) throws IOException {
return 0;
}
@Override
public com.rabbitmq.client.AMQP.Queue.BindOk queueBind(String arg0, String arg1, String arg2) throws IOException {
return null;
}
@Override
public com.rabbitmq.client.AMQP.Queue.BindOk queueBind(String arg0, String arg1, String arg2,
Map<String, Object> arg3) throws IOException {
return null;
}
@Override
public void queueBindNoWait(String arg0, String arg1, String arg2, Map<String, Object> arg3) throws IOException {}
@Override
public com.rabbitmq.client.AMQP.Queue.DeclareOk queueDeclare() throws IOException {
return null;
}
@Override
public com.rabbitmq.client.AMQP.Queue.DeclareOk queueDeclare(String arg0, boolean arg1, boolean arg2, boolean arg3,
Map<String, Object> arg4) throws IOException {
FakeConnection.recordedValues.put("queueDeclare", Arrays.asList(arg0, arg1, arg2, arg3, arg4));
return null;
}
@Override
public void queueDeclareNoWait(String arg0, boolean arg1, boolean arg2, boolean arg3, Map<String, Object> arg4)
throws IOException {
}
@Override
public com.rabbitmq.client.AMQP.Queue.DeclareOk queueDeclarePassive(String arg0) throws IOException {
FakeConnection.recordedValues.put("queueDeclarePassive", Arrays.asList(arg0));
return null;
}
@Override
public com.rabbitmq.client.AMQP.Queue.DeleteOk queueDelete(String arg0) throws IOException {
return null;
}
@Override
public com.rabbitmq.client.AMQP.Queue.DeleteOk queueDelete(String arg0, boolean arg1, boolean arg2)
throws IOException {
return null;
}
@Override
public void queueDeleteNoWait(String arg0, boolean arg1, boolean arg2) throws IOException {
}
@Override
public PurgeOk queuePurge(String arg0) throws IOException {
return null;
}
@Override
public com.rabbitmq.client.AMQP.Queue.UnbindOk queueUnbind(String arg0, String arg1, String arg2) throws IOException {
return null;
}
@Override
public com.rabbitmq.client.AMQP.Queue.UnbindOk queueUnbind(String arg0, String arg1, String arg2,
Map<String, Object> arg3) throws IOException {
return null;
}
@Override
public boolean removeConfirmListener(ConfirmListener arg0) {
return false;
}
@Override
public boolean removeFlowListener(FlowListener arg0) {
return false;
}
@Override
public boolean removeReturnListener(ReturnListener arg0) {
return false;
}
@Override
public Command rpc(Method arg0) throws IOException {
return null;
}
@Override
public void setDefaultConsumer(Consumer arg0) {}
@Override
public CommitOk txCommit() throws IOException {
return null;
}
@Override
public RollbackOk txRollback() throws IOException {
return null;
}
@Override
public com.rabbitmq.client.AMQP.Tx.SelectOk txSelect() throws IOException {
return null;
}
@Override
public boolean waitForConfirms() throws InterruptedException {
return false;
}
@Override
public boolean waitForConfirms(long arg0) throws InterruptedException, TimeoutException {
return false;
}
@Override
public void waitForConfirmsOrDie() throws IOException, InterruptedException {}
@Override
public void waitForConfirmsOrDie(long arg0) throws IOException, InterruptedException, TimeoutException {}
}
| 24.077135 | 121 | 0.715561 |
bf17cab66edc5a264c710acbba77c29ce9f9df7c | 5,055 | package org.apache.fop.events;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.IOUtils;
import org.apache.fop.events.model.EventMethodModel;
import org.apache.fop.events.model.EventModel;
import org.apache.fop.events.model.EventModelParser;
import org.apache.fop.events.model.EventProducerModel;
import org.apache.fop.events.model.EventSeverity;
public class DefaultEventBroadcaster implements EventBroadcaster {
protected CompositeEventListener listeners = new CompositeEventListener();
private static List eventModels = new ArrayList();
private Map proxies = new HashMap();
public void addEventListener(EventListener listener) {
this.listeners.addEventListener(listener);
}
public void removeEventListener(EventListener listener) {
this.listeners.removeEventListener(listener);
}
public boolean hasEventListeners() {
return this.listeners.hasEventListeners();
}
public void broadcastEvent(Event event) {
this.listeners.processEvent(event);
}
private static EventModel loadModel(Class resourceBaseClass) {
String resourceName = "event-model.xml";
InputStream in = resourceBaseClass.getResourceAsStream(resourceName);
if (in == null) {
throw new MissingResourceException("File " + resourceName + " not found", DefaultEventBroadcaster.class.getName(), "");
} else {
EventModel var3;
try {
var3 = EventModelParser.parse(new StreamSource(in));
} catch (TransformerException var7) {
throw new MissingResourceException("Error reading " + resourceName + ": " + var7.getMessage(), DefaultEventBroadcaster.class.getName(), "");
} finally {
IOUtils.closeQuietly(in);
}
return var3;
}
}
public static synchronized void addEventModel(EventModel eventModel) {
eventModels.add(eventModel);
}
private static synchronized EventProducerModel getEventProducerModel(Class clazz) {
int i = 0;
for(int c = eventModels.size(); i < c; ++i) {
EventModel eventModel = (EventModel)eventModels.get(i);
EventProducerModel producerModel = eventModel.getProducer(clazz);
if (producerModel != null) {
return producerModel;
}
}
EventModel model = loadModel(clazz);
addEventModel(model);
return model.getProducer(clazz);
}
public EventProducer getEventProducerFor(Class clazz) {
if (!EventProducer.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException("Class must be an implementation of the EventProducer interface: " + clazz.getName());
} else {
EventProducer producer = (EventProducer)this.proxies.get(clazz);
if (producer == null) {
producer = this.createProxyFor(clazz);
this.proxies.put(clazz, producer);
}
return producer;
}
}
protected EventProducer createProxyFor(Class clazz) {
final EventProducerModel producerModel = getEventProducerModel(clazz);
if (producerModel == null) {
throw new IllegalStateException("Event model doesn't contain the definition for " + clazz.getName());
} else {
return (EventProducer)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
EventMethodModel methodModel = producerModel.getMethod(methodName);
String eventID = producerModel.getInterfaceName() + "." + methodName;
if (methodModel == null) {
throw new IllegalStateException("Event model isn't consistent with the EventProducer interface. Please rebuild FOP! Affected method: " + eventID);
} else {
Map params = new HashMap();
int i = 1;
for(Iterator iter = methodModel.getParameters().iterator(); iter.hasNext(); ++i) {
EventMethodModel.Parameter param = (EventMethodModel.Parameter)iter.next();
params.put(param.getName(), args[i]);
}
Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params);
DefaultEventBroadcaster.this.broadcastEvent(ev);
if (ev.getSeverity() == EventSeverity.FATAL) {
EventExceptionManager.throwException(ev, methodModel.getExceptionClass());
}
return null;
}
}
});
}
}
}
| 38.884615 | 164 | 0.662117 |
74924e8b2f82e3be5ef7f74042126b99621eecbd | 2,907 | /*
* Copyright 2021 Sonu Kumar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*
*/
package com.github.sonus21.rqueue.spring.boot.application;
import com.github.sonus21.rqueue.core.RqueueMessageTemplate;
import com.github.sonus21.rqueue.core.impl.RqueueMessageTemplateImpl;
import com.github.sonus21.rqueue.listener.RqueueMessageHandler;
import com.github.sonus21.rqueue.listener.RqueueMessageListenerContainer;
import com.github.sonus21.rqueue.models.enums.PriorityMode;
import com.github.sonus21.rqueue.test.application.BaseApplication;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@PropertySource("classpath:application.properties")
@SpringBootApplication(scanBasePackages = {"com.github.sonus21.rqueue.test"})
@EnableJpaRepositories(basePackages = {"com.github.sonus21.rqueue.test.repository"})
@EnableTransactionManagement
public class ApplicationWithCustomConfiguration extends BaseApplication {
@Value("${max.workers.count:6}")
private int maxWorkers;
@Value("${priority.mode:}")
private PriorityMode priorityMode;
public static void main(String[] args) {
SpringApplication.run(ApplicationWithCustomConfiguration.class, args);
}
@Bean
public RqueueMessageTemplate rqueueMessageTemplate(
RedisConnectionFactory redisConnectionFactory) {
return new RqueueMessageTemplateImpl(redisConnectionFactory, null);
}
@Bean
public RqueueMessageListenerContainer rqueueMessageListenerContainer(
RqueueMessageHandler rqueueMessageHandler, RqueueMessageTemplate rqueueMessageTemplate) {
RqueueMessageListenerContainer rqueueMessageListenerContainer =
new RqueueMessageListenerContainer(rqueueMessageHandler, rqueueMessageTemplate);
rqueueMessageListenerContainer.setMaxNumWorkers(maxWorkers);
if (priorityMode != null) {
rqueueMessageListenerContainer.setPriorityMode(priorityMode);
}
return rqueueMessageListenerContainer;
}
}
| 43.38806 | 102 | 0.811146 |
4c6d50a84689a3df0619c190506c8c46e8c30a33 | 2,531 | /**
* Copyright 2016-present Open Networking Laboratory
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.kafkaintegration.api;
import java.util.List;
import org.onosproject.kafkaintegration.api.dto.EventSubscriber;
import org.onosproject.kafkaintegration.api.dto.OnosEvent.Type;
import org.onosproject.kafkaintegration.api.dto.RegistrationResponse;
import org.onosproject.kafkaintegration.errors.InvalidApplicationException;
import org.onosproject.kafkaintegration.errors.InvalidGroupIdException;
import com.google.common.annotations.Beta;
/**
* APIs for subscribing to Onos Event Messages.
*/
@Beta
public interface EventSubscriptionService {
/**
* Registers the external application to receive events generated in ONOS.
*
* @param appName Application Name
* @return Registration Response DTO.
*/
RegistrationResponse registerListener(String appName);
/**
* Removes the Registered Listener.
*
* @param appName Application Name
*/
void unregisterListener(String appName);
/**
* Allows registered listener to subscribe for a specific event type.
*
* @param subscriber Subscription data containing the event type
* @throws InvalidGroupIdException
* @throws InvalidApplicationException
*/
void subscribe(EventSubscriber subscriber)
throws InvalidGroupIdException, InvalidApplicationException;
/**
* Allows the registered listener to unsubscribe for a specific event.
*
* @param subscriber Subscription data containing the event type
* @throws InvalidGroupIdException
* @throws InvalidApplicationException
*/
void unsubscribe(EventSubscriber subscriber)
throws InvalidGroupIdException, InvalidApplicationException;
/**
* Returns the event subscriber for various event types.
*
* @param type ONOS event type.
* @return List of event subscribers
*/
List<EventSubscriber> getEventSubscribers(Type type);
}
| 33.302632 | 78 | 0.739629 |
de9af9b3eca66c28b79e9f9159503325d2afddaa | 3,535 | package ca.marklauman.dominionpicker;
import java.util.Arrays;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import ca.marklauman.dominionpicker.database.TableCard;
import ca.marklauman.dominionpicker.database.TableSupply;
/** Contains all information about a supply set.
* @author Mark Lauman */
public class Supply implements Parcelable {
/** The timestamp of this supply (maps to its database id) */
public final long time;
/** The name of this supply (optional, may be null) */
public String name;
/** The cards in the supply. */
public final long[] cards;
/** {@code true} if colonies + platinum are in use. */
public final boolean high_cost;
/** {@code true} if shelters are in use. */
public final boolean shelters;
/** {@code true} if this is from the sample database. */
public boolean sample;
/** The id of the bane card, or -1 if there isn't one. */
final long bane;
public Supply(Cursor c) {
time = c.getLong( c.getColumnIndex(TableSupply._ID));
name = c.getString(c.getColumnIndex(TableSupply._NAME));
bane = c.getLong(c.getColumnIndex(TableSupply._BANE));
high_cost = c.getInt(c.getColumnIndex(TableSupply._HIGH_COST)) != 0;
shelters = c.getInt(c.getColumnIndex(TableSupply._SHELTERS)) != 0;
String[] cardList = c.getString(c.getColumnIndex(TableSupply._CARDS))
.split(",");
cards = new long[cardList.length];
for(int i=0; i<cardList.length; i++)
cards[i] = Long.parseLong(cardList[i]);
}
/** Constructor for unpacking a parcel into a {@code Supply} */
private Supply(Parcel in) {
time = in.readLong();
cards = in.createLongArray();
boolean[] booleans = in.createBooleanArray();
high_cost = booleans[0];
shelters = booleans[1];
sample = booleans[2];
bane = in.readLong();
}
/** String for debugging */
@Override
public String toString (){
String res = "Supply {";
if(high_cost) res += "high cost, ";
else res += "low cost, ";
if(shelters) res += "shelters, ";
else res += "no shelters, ";
if(sample) res += "sample, ";
else res += "history, ";
res += "bane=" + bane + ", ";
res += Arrays.toString(cards);
return res + "}";
}
/** Returns {@code true} if a Black Market is in the supply. */
public boolean blackMarket() {
if(cards == null) return false;
for(long card : cards)
if(card == TableCard.ID_BLACK_MARKET) return true;
return false;
}
@Override
public int describeContents() {
/* As far as I can tell, this method has no function. */
return 0;
}
/** Flatten this Supply in to a Parcel.
* @param out The Parcel in which the Supply
* should be written.
* @param flags Parameter is ignored */
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeLong(time);
out.writeLongArray(cards);
out.writeBooleanArray(new boolean[]{high_cost, shelters, sample});
out.writeLong(bane);
}
public static final Parcelable.Creator<Supply> CREATOR
= new Parcelable.Creator<Supply>() {
public Supply createFromParcel(Parcel in) {
return new Supply(in);
}
public Supply[] newArray(int size) {
return new Supply[size];
}
};
} | 31.283186 | 77 | 0.608204 |
5f0035dfc7fc72e93c8eba57a028409068a3014f | 508 | package com.example.coolweather.android.dto.gsonDto;
import com.google.gson.annotations.SerializedName;
/**
* Created by angel beat on 2017/8/9.
*/
public class Basic {
@SerializedName("city")
public String cityName;
public String cnty;
public String id;
@SerializedName("lat")
public String latitude;
@SerializedName("lon")
public String longtitude;
public Update update;
public class Update{
public String loc;
public String utc;
}
}
| 18.814815 | 52 | 0.669291 |
19b75d801df1261d858e4d7577263f8665ccd295 | 3,357 | /*
* Copyright 2016, Stuart Douglas, and individual contributors as indicated
* by the @authors tag.
*
* 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.fakereplace.integration.wildfly.hibernate5;
import java.util.Map;
import javax.persistence.Cache;
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.Query;
import javax.persistence.SynchronizationType;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import org.jipijapa.plugin.spi.PersistenceUnitService;
/**
* @author Stuart Douglas
*/
public class WildflyEntityManagerFactoryProxy implements EntityManagerFactory {
private final PersistenceUnitService persistenceUnitService;
public WildflyEntityManagerFactoryProxy(PersistenceUnitService persistenceUnitService) {
this.persistenceUnitService = persistenceUnitService;
}
@Override
public EntityManager createEntityManager() {
return unwrap().createEntityManager();
}
private EntityManagerFactory unwrap() {
return ((HackPersistenceUnitService)persistenceUnitService).emf();
}
@Override
public EntityManager createEntityManager(Map map) {
return unwrap().createEntityManager(map);
}
@Override
public EntityManager createEntityManager(SynchronizationType synchronizationType) {
return unwrap().createEntityManager(synchronizationType);
}
@Override
public EntityManager createEntityManager(SynchronizationType synchronizationType, Map map) {
return unwrap().createEntityManager(synchronizationType, map);
}
@Override
public CriteriaBuilder getCriteriaBuilder() {
return unwrap().getCriteriaBuilder();
}
@Override
public Metamodel getMetamodel() {
return unwrap().getMetamodel();
}
@Override
public boolean isOpen() {
return unwrap().isOpen();
}
@Override
public void close() {
unwrap().close();
}
@Override
public Map<String, Object> getProperties() {
return unwrap().getProperties();
}
@Override
public Cache getCache() {
return unwrap().getCache();
}
@Override
public PersistenceUnitUtil getPersistenceUnitUtil() {
return unwrap().getPersistenceUnitUtil();
}
@Override
public void addNamedQuery(String name, Query query) {
unwrap().addNamedQuery(name, query);
}
@Override
public <T> T unwrap(Class<T> cls) {
return unwrap().unwrap(cls);
}
@Override
public <T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph) {
unwrap().addNamedEntityGraph(graphName, entityGraph);
}
}
| 28.449153 | 96 | 0.71969 |
d8f6cad1b82a3d3f0f5aceb3987ac457529ec2a9 | 11,578 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.openal;
import org.lwjgl.system.*;
import java.util.Set;
import org.lwjgl.*;
import java.util.function.IntFunction;
import static org.lwjgl.system.Checks.*;
/** Defines the capabilities of the OpenAL Context API. */
public final class ALCCapabilities {
// ALC10
public final long
alcOpenDevice,
alcCloseDevice,
alcCreateContext,
alcMakeContextCurrent,
alcProcessContext,
alcSuspendContext,
alcDestroyContext,
alcGetCurrentContext,
alcGetContextsDevice,
alcIsExtensionPresent,
alcGetProcAddress,
alcGetEnumValue,
alcGetError,
alcGetString,
alcGetIntegerv;
// ALC11
public final long
alcCaptureOpenDevice,
alcCaptureCloseDevice,
alcCaptureStart,
alcCaptureStop,
alcCaptureSamples;
// EXT_thread_local_context
public final long
alcSetThreadContext,
alcGetThreadContext;
// SOFT_device_clock
public final long
alcGetInteger64vSOFT;
// SOFT_HRTF
public final long
alcGetStringiSOFT,
alcResetDeviceSOFT;
// SOFT_loopback
public final long
alcLoopbackOpenDeviceSOFT,
alcIsRenderFormatSupportedSOFT,
alcRenderSamplesSOFT;
// SOFT_pause_device
public final long
alcDevicePauseSOFT,
alcDeviceResumeSOFT;
// SOFT_reopen_device
public final long
alcReopenDeviceSOFT;
/** When true, {@link ALC10} is supported. */
public final boolean OpenALC10;
/** When true, {@link ALC11} is supported. */
public final boolean OpenALC11;
/** When true, {@link EnumerateAllExt} is supported. */
public final boolean ALC_ENUMERATE_ALL_EXT;
/**
* An OpenAL 1.1 implementation will always support the {@code ALC_ENUMERATION_EXT} extension. This extension provides for enumeration of the available OpenAL devices
* through {@link ALC10#alcGetString GetString}. An {@link ALC10#alcGetString GetString} query of {@link ALC10#ALC_DEVICE_SPECIFIER DEVICE_SPECIFIER} with a {@code NULL} device passed in will return a list of devices. Each
* device name will be separated by a single {@code NULL} character and the list will be terminated with two {@code NULL} characters.
*/
public final boolean ALC_ENUMERATION_EXT;
/** When true, {@link EXTCapture} is supported. */
public final boolean ALC_EXT_CAPTURE;
/** When true, {@link EXTDedicated} is supported. */
public final boolean ALC_EXT_DEDICATED;
/** When true, {@link EXTDefaultFilterOrder} is supported. */
public final boolean ALC_EXT_DEFAULT_FILTER_ORDER;
/** When true, {@link EXTDisconnect} is supported. */
public final boolean ALC_EXT_disconnect;
/** When true, {@link EXTEfx} is supported. */
public final boolean ALC_EXT_EFX;
/** When true, {@link EXTThreadLocalContext} is supported. */
public final boolean ALC_EXT_thread_local_context;
/** When true, {@link LOKIAudioChannel} is supported. */
public final boolean ALC_LOKI_audio_channel;
/** When true, {@link SOFTDeviceClock} is supported. */
public final boolean ALC_SOFT_device_clock;
/** When true, {@link SOFTHRTF} is supported. */
public final boolean ALC_SOFT_HRTF;
/** When true, {@link SOFTLoopback} is supported. */
public final boolean ALC_SOFT_loopback;
/** When true, {@link SOFTOutputLimiter} is supported. */
public final boolean ALC_SOFT_output_limiter;
/** When true, {@link SOFTOutputMode} is supported. */
public final boolean ALC_SOFT_output_mode;
/** When true, {@link SOFTPauseDevice} is supported. */
public final boolean ALC_SOFT_pause_device;
/** When true, {@link SOFTReopenDevice} is supported. */
public final boolean ALC_SOFT_reopen_device;
/** Device handle. */
final long device;
/** Off-heap array of the above function addresses. */
final PointerBuffer addresses;
ALCCapabilities(FunctionProviderLocal provider, long device, Set<String> ext, IntFunction<PointerBuffer> bufferFactory) {
this.device = device;
PointerBuffer caps = bufferFactory.apply(31);
OpenALC10 = check_ALC10(provider, device, caps, ext);
OpenALC11 = check_ALC11(provider, device, caps, ext);
ALC_ENUMERATE_ALL_EXT = ext.contains("ALC_ENUMERATE_ALL_EXT");
ALC_ENUMERATION_EXT = ext.contains("ALC_ENUMERATION_EXT");
ALC_EXT_CAPTURE = check_EXT_CAPTURE(provider, device, caps, ext);
ALC_EXT_DEDICATED = ext.contains("ALC_EXT_DEDICATED");
ALC_EXT_DEFAULT_FILTER_ORDER = ext.contains("ALC_EXT_DEFAULT_FILTER_ORDER");
ALC_EXT_disconnect = ext.contains("ALC_EXT_disconnect");
ALC_EXT_EFX = ext.contains("ALC_EXT_EFX");
ALC_EXT_thread_local_context = check_EXT_thread_local_context(provider, device, caps, ext);
ALC_LOKI_audio_channel = ext.contains("ALC_LOKI_audio_channel");
ALC_SOFT_device_clock = check_SOFT_device_clock(provider, device, caps, ext);
ALC_SOFT_HRTF = check_SOFT_HRTF(provider, device, caps, ext);
ALC_SOFT_loopback = check_SOFT_loopback(provider, device, caps, ext);
ALC_SOFT_output_limiter = ext.contains("ALC_SOFT_output_limiter");
ALC_SOFT_output_mode = ext.contains("ALC_SOFT_output_mode");
ALC_SOFT_pause_device = check_SOFT_pause_device(provider, device, caps, ext);
ALC_SOFT_reopen_device = check_SOFT_reopen_device(provider, device, caps, ext);
alcOpenDevice = caps.get(0);
alcCloseDevice = caps.get(1);
alcCreateContext = caps.get(2);
alcMakeContextCurrent = caps.get(3);
alcProcessContext = caps.get(4);
alcSuspendContext = caps.get(5);
alcDestroyContext = caps.get(6);
alcGetCurrentContext = caps.get(7);
alcGetContextsDevice = caps.get(8);
alcIsExtensionPresent = caps.get(9);
alcGetProcAddress = caps.get(10);
alcGetEnumValue = caps.get(11);
alcGetError = caps.get(12);
alcGetString = caps.get(13);
alcGetIntegerv = caps.get(14);
alcCaptureOpenDevice = caps.get(15);
alcCaptureCloseDevice = caps.get(16);
alcCaptureStart = caps.get(17);
alcCaptureStop = caps.get(18);
alcCaptureSamples = caps.get(19);
alcSetThreadContext = caps.get(20);
alcGetThreadContext = caps.get(21);
alcGetInteger64vSOFT = caps.get(22);
alcGetStringiSOFT = caps.get(23);
alcResetDeviceSOFT = caps.get(24);
alcLoopbackOpenDeviceSOFT = caps.get(25);
alcIsRenderFormatSupportedSOFT = caps.get(26);
alcRenderSamplesSOFT = caps.get(27);
alcDevicePauseSOFT = caps.get(28);
alcDeviceResumeSOFT = caps.get(29);
alcReopenDeviceSOFT = caps.get(30);
addresses = ThreadLocalUtil.setupAddressBuffer(caps);
}
/** Returns the buffer of OpenAL function pointers. */
public PointerBuffer getAddressBuffer() {
return addresses;
}
private static boolean check_ALC10(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("OpenALC10")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
},
"alcOpenDevice", "alcCloseDevice", "alcCreateContext", "alcMakeContextCurrent", "alcProcessContext", "alcSuspendContext", "alcDestroyContext",
"alcGetCurrentContext", "alcGetContextsDevice", "alcIsExtensionPresent", "alcGetProcAddress", "alcGetEnumValue", "alcGetError", "alcGetString",
"alcGetIntegerv"
) || reportMissing("ALC", "OpenALC10");
}
private static boolean check_ALC11(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("OpenALC11")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
15, 16, 17, 18, 19
},
"alcCaptureOpenDevice", "alcCaptureCloseDevice", "alcCaptureStart", "alcCaptureStop", "alcCaptureSamples"
) || reportMissing("ALC", "OpenALC11");
}
private static boolean check_EXT_CAPTURE(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("ALC_EXT_CAPTURE")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
15, 16, 17, 18, 19
},
"alcCaptureOpenDevice", "alcCaptureCloseDevice", "alcCaptureStart", "alcCaptureStop", "alcCaptureSamples"
) || reportMissing("ALC", "ALC_EXT_CAPTURE");
}
private static boolean check_EXT_thread_local_context(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("ALC_EXT_thread_local_context")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
20, 21
},
"alcSetThreadContext", "alcGetThreadContext"
) || reportMissing("ALC", "ALC_EXT_thread_local_context");
}
private static boolean check_SOFT_device_clock(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("ALC_SOFT_device_clock")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
22
},
"alcGetInteger64vSOFT"
) || reportMissing("ALC", "ALC_SOFT_device_clock");
}
private static boolean check_SOFT_HRTF(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("ALC_SOFT_HRTF")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
23, 24
},
"alcGetStringiSOFT", "alcResetDeviceSOFT"
) || reportMissing("ALC", "ALC_SOFT_HRTF");
}
private static boolean check_SOFT_loopback(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("ALC_SOFT_loopback")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
25, 26, 27
},
"alcLoopbackOpenDeviceSOFT", "alcIsRenderFormatSupportedSOFT", "alcRenderSamplesSOFT"
) || reportMissing("ALC", "ALC_SOFT_loopback");
}
private static boolean check_SOFT_pause_device(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("ALC_SOFT_pause_device")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
28, 29
},
"alcDevicePauseSOFT", "alcDeviceResumeSOFT"
) || reportMissing("ALC", "ALC_SOFT_pause_device");
}
private static boolean check_SOFT_reopen_device(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("ALC_SOFT_reopen_device")) {
return false;
}
return checkFunctions(provider, device, caps, new int[] {
30
},
"alcReopenDeviceSOFT"
) || reportMissing("ALC", "ALC_SOFT_reopen_device");
}
}
| 39.247458 | 226 | 0.664709 |
89261d544a4f6327c20d5aa508bf1684b55accab | 4,045 | package func.nn.backprop;
import func.nn.Link;
/**
*
* @author Andrew Guillory [email protected]
* @version 1.0
*/
public class BackPropagationLink extends Link {
/**
* The derivative of the error function
* in respect to this node, or in the case
* of batch training possibly the sum
* of derivative of the error functions for
* many patterns.
*/
private double error;
/**
* The last derivative of the error function
* in respect to this node, sometimes
* used in training algorithms that use
* momentum type terms.
*/
private double lastError;
/**
* The last change made to this link (last delta),
* sometimes used in algorithms with momentum
* type terms.
*/
private double lastChange;
/**
* A learning rate term which is used in
* some algorithms that have weight specific
* learning rates.
*/
private double learningRate;
/**
* A time step term which is used in
* some algorithms that use a time step.
*/
private double timeStep;
/**
* Constructor - initiate timeStep (ADAM).
*/
public BackPropagationLink(){
timeStep=0;
}
/**
* @see func.nn.Link#changeWeight(double)
*/
public void changeWeight(double delta) {
super.changeWeight(delta);
lastChange = delta;
}
/**
* Backpropagate error values into this link
*/
public void backpropagate() {
addError(getInValue() * getOutError());
}
/**
* Add error to this link
* @param error the error to add
*/
public void addError(double error) {
this.error += error;
}
/**
* Clear out the error and
* set the current error to be the last error
*/
public void clearError() {
lastError = error;
error = 0;
}
/**
* Get the error derivative with respect to this weight
* @return the error derivative value
*/
public double getError() {
return error;
}
/**
* Set the error
* @param error the error to set
*/
public void setError(double error) {
this.error = error;
}
/**
* Get the last change in the weight
* @return the last change in weight
*/
public double getLastChange() {
return lastChange;
}
/**
* Get the last error value
* @return the last error value
*/
public double getLastError() {
return lastError;
}
/**
* Set the learning rate
* @param learningRate the learning rate
*/
public void setLearningRate(double learningRate) {
this.learningRate = learningRate;
}
/**
* Get the learning rate
* @return the learning rate
*/
public double getLearningRate() {
return learningRate;
}
/**
* Set the time step
* @param timeStep the timeStep
*/
public void setTimeStep(double timeStep) {
this.timeStep = timeStep;
}
/**
* Get the time step
* @return the time step
*/
public double getTimeStep() {
return timeStep;
}
/**
* Get the output error
* @return the output error
*/
public double getOutError() {
return ((BackPropagationNode) getOutNode()).getInputError();
}
/**
* Get the weighted output error
* @return the output error times the weigh tof the link
*/
public double getWeightedOutError() {
return ((BackPropagationNode) getOutNode()).getInputError()
* getWeight();
}
/**
* Get the input error
* @return the input error
*/
public double getInError() {
return ((BackPropagationNode) getInNode()).getInputError();
}
/**
* Get the weighted input error
* @return the weighted error
*/
public double getWeightedInError() {
return ((BackPropagationNode) getInNode()).getInputError()
* getWeight();
}
}
| 21.515957 | 68 | 0.5822 |
5a6844e969ca08ba7b33896407dd458b9521de52 | 402 | package ru.mihkopylov.operation;
import javax.annotation.Nullable;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Action {
@NonNull
private String actor;
@Nullable
private String input;
@Nullable
private String output;
}
| 18.272727 | 33 | 0.778607 |
1fe8d2c5b66c7d3019e9df5370a78ee95946f6cb | 187 | package ru.stqa.pft.sandbox;
public class Point {
public double p1;
public double p2;
public Point( double p1, double p2) {
this.p1=p1;
this.p2=p2;
}
}
| 14.384615 | 41 | 0.588235 |
6cfbc39f896f408b74a1260a90c468d9c2686356 | 5,902 | /*
* 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.hadoop.metrics2.util;
import com.google.common.collect.Maps;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.metrics2.AbstractMetric;
import org.apache.hadoop.metrics2.MetricsRecord;
import org.apache.hadoop.metrics2.MetricsTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
/**
* A metrics cache for sinks that don't support sparse updates.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class MetricsCache {
static final Logger LOG = LoggerFactory.getLogger(MetricsCache.class);
static final int MAX_RECS_PER_NAME_DEFAULT = 1000;
private final Map<String, RecordCache> map = Maps.newHashMap();
private final int maxRecsPerName;
class RecordCache
extends LinkedHashMap<Collection<MetricsTag>, Record> {
private static final long serialVersionUID = 1L;
private boolean gotOverflow = false;
@Override
protected boolean removeEldestEntry(Map.Entry<Collection<MetricsTag>,
Record> eldest) {
boolean overflow = size() > maxRecsPerName;
if (overflow && !gotOverflow) {
LOG.warn("Metrics cache overflow at "+ size() +" for "+ eldest);
gotOverflow = true;
}
return overflow;
}
}
/**
* Cached record
*/
public static class Record {
final Map<String, String> tags = Maps.newHashMap();
final Map<String, AbstractMetric> metrics = Maps.newHashMap();
/**
* Lookup a tag value
* @param key name of the tag
* @return the tag value
*/
public String getTag(String key) {
return tags.get(key);
}
/**
* Lookup a metric value
* @param key name of the metric
* @return the metric value
*/
public Number getMetric(String key) {
AbstractMetric metric = metrics.get(key);
return metric != null ? metric.value() : null;
}
/**
* Lookup a metric instance
* @param key name of the metric
* @return the metric instance
*/
public AbstractMetric getMetricInstance(String key) {
return metrics.get(key);
}
/**
* @return the entry set of the tags of the record
*/
public Set<Map.Entry<String, String>> tags() {
return tags.entrySet();
}
/**
* @deprecated use metricsEntrySet() instead
* @return entry set of metrics
*/
@Deprecated
public Set<Map.Entry<String, Number>> metrics() {
Map<String, Number> map = new LinkedHashMap<String, Number>(
metrics.size());
for (Map.Entry<String, AbstractMetric> mapEntry : metrics.entrySet()) {
map.put(mapEntry.getKey(), mapEntry.getValue().value());
}
return map.entrySet();
}
/**
* @return entry set of metrics
*/
public Set<Map.Entry<String, AbstractMetric>> metricsEntrySet() {
return metrics.entrySet();
}
@Override public String toString() {
return new StringJoiner(", ", this.getClass().getSimpleName() + "{", "}")
.add("tags=" + tags)
.add("metrics=" + metrics)
.toString();
}
}
public MetricsCache() {
this(MAX_RECS_PER_NAME_DEFAULT);
}
/**
* Construct a metrics cache
* @param maxRecsPerName limit of the number records per record name
*/
public MetricsCache(int maxRecsPerName) {
this.maxRecsPerName = maxRecsPerName;
}
/**
* Update the cache and return the current cached record
* @param mr the update record
* @param includingTags cache tag values (for later lookup by name) if true
* @return the updated cache record
*/
public Record update(MetricsRecord mr, boolean includingTags) {
String name = mr.name();
RecordCache recordCache = map.get(name);
if (recordCache == null) {
recordCache = new RecordCache();
map.put(name, recordCache);
}
Collection<MetricsTag> tags = mr.tags();
Record record = recordCache.get(tags);
if (record == null) {
record = new Record();
recordCache.put(tags, record);
}
for (AbstractMetric m : mr.metrics()) {
record.metrics.put(m.name(), m);
}
if (includingTags) {
// mostly for some sinks that include tags as part of a dense schema
for (MetricsTag t : mr.tags()) {
record.tags.put(t.name(), t.value());
}
}
return record;
}
/**
* Update the cache and return the current cache record
* @param mr the update record
* @return the updated cache record
*/
public Record update(MetricsRecord mr) {
return update(mr, false);
}
/**
* Get the cached record
* @param name of the record
* @param tags of the record
* @return the cached record or null
*/
public Record get(String name, Collection<MetricsTag> tags) {
RecordCache rc = map.get(name);
if (rc == null) return null;
return rc.get(tags);
}
}
| 29.51 | 79 | 0.660115 |
a481c41bcef4c2d01af56ceebd726e93871c4e65 | 568 | package com.projeto.backend.helpdesk.enums;
public enum StatusEnum {
New,
Assigned,
Resolved,
Approved,
Disapproved,
Closed;
public static StatusEnum getStatus(String status) {
switch(status) {
case "New":return New;
case "Assigned":return Assigned;
case "Resolved":return Resolved;
case "Approved":return Approved;
case "Disapproved":return Disapproved;
case "Closed":return Closed;
default: return New;
}
}
} | 21.037037 | 55 | 0.56338 |
caa65db5594a0e8a32281b6d56c999331f12a2bc | 1,111 | import java.util.Random;
public class Program {
public static void main(String[] s) {
Restaurant restaurant = new Restaurant(10, 15, 5);
OutputClass show = new OutputClass(restaurant);
for (int i = 1; i <= 8; i+=2) {
restaurant.addDish(new Drink("Drink " + (i), Math.abs(new Random().nextInt() % 20)));
restaurant.addDish(new Drink("Drink " + (i+1), Math.abs(new Random().nextInt() % 20)));
restaurant.addDish(new Dish("Dish " + (i), Math.abs(new Random().nextInt() % 20)));
restaurant.addDish(new Dish("Dish " + (i+1), Math.abs(new Random().nextInt() % 20)));
}
//show.showMenu();
///del some dishes
//restaurant.removeDish(1);
restaurant.removeDish(6);
restaurant.removeDish(7);
show.showMenu();
//add 5 cooks
for(int i = 0; i<5;i++) {
restaurant.addCook(new Cook("Cook " + (i+1)));
}
//show.showCooks();
restaurant.removeCook(4);
restaurant.removeCook(0);
//show.showCooks();
restaurant.createNewOrder(1,new int[] {1,5,6});
show.showCooks();
show.showCookWithOrder(1);
restaurant.removeOrder(1);
show.showCooks();
}
}
| 25.837209 | 90 | 0.628263 |
5926e660c74999a2fbb3a14e232f65ad95897d8d | 14,215 | /**
* This project is licensed under the Apache License, Version 2.0
* if the following condition is met:
* (otherwise it cannot be used by anyone but the author, Kevin, only)
*
* The original JSON Statham project is owned by Lee, Seong Hyun (Kevin).
*
* -What does it mean to you?
* Nothing, unless you want to take the ownership of
* "the original project" (not yours or forked & modified one).
* You are free to use it for both non-commercial and commercial projects
* and free to modify it as the Apache License allows.
*
* -So why is this condition necessary?
* It is only to protect the original project (See the case of Java).
*
*
* Copyright 2009 Lee, Seong Hyun (Kevin)
*
* 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.elixirian.jsonstatham.core;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import org.elixirian.jsonstatham.annotation.Json;
import org.elixirian.jsonstatham.annotation.JsonField;
import org.elixirian.jsonstatham.annotation.ValueAccessor;
import org.elixirian.jsonstatham.core.convertible.JsonArray;
import org.elixirian.jsonstatham.core.convertible.JsonConvertible;
import org.elixirian.jsonstatham.core.convertible.JsonObject;
import org.elixirian.jsonstatham.core.convertible.JsonObjectCreator;
import org.elixirian.jsonstatham.exception.JsonStathamException;
import org.elixirian.kommonlee.io.CharAndStringWritable;
import org.elixirian.kommonlee.io.CharAndStringWritableToOutputStream;
import org.elixirian.kommonlee.io.CharAndStringWritableToWriter;
import org.elixirian.kommonlee.io.CharReadable;
import org.elixirian.kommonlee.io.CharReadableFromInputStream;
import org.elixirian.kommonlee.io.CharReadableFromReader;
import org.elixirian.kommonlee.io.util.IoUtil;
import org.elixirian.kommonlee.reflect.TypeHolder;
/**
* <pre>
* ___ _____ _____
* / \/ /_________ ___ ____ __ ______ / / ______ ______
* / / / ___ \ \/ //___// // / / / / ___ \/ ___ \
* / \ / _____/\ // // __ / / /___/ _____/ _____/
* /____/\____\\_____/ \__//___//___/ /__/ /________/\_____/ \_____/
* </pre>
*
* @author Lee, SeongHyun (Kevin)
* @version 0.0.1 (2009-11-21)
* @version 0.0.2 (2009-12-07) It is refactored.
* @version 0.0.3 (2009-12-07) It is redesigned.
* @version 0.0.4 (2009-12-12) It can handle array, List and Map.
* @version 0.0.5 (2009-12-20)
* <p>
* It can handle duplicate {@link JsonField} names. => It throws an exception.
* </p>
* <p>
* It can also handle {@link java.util.Date} type value annotated with {@link JsonField}. => It uses the
* toString() method of the value object, or if the field is also annotated with {@link ValueAccessor}
* annotation, it uses the method specified with the {@link ValueAccessor} annotation in order to get the
* value.
* </p>
* @version 0.0.6 (2010-02-03) {@link JsonObjectCreator} is added to create a new {@link org.json.JSONObject} .
* @version 0.0.7 (2010-02-12) The name is changed from NonIndentedJsonStatham to JsonStathamInAction. When the Json is
* converted into JSON, if any fields annotated with @JsonField without the 'name' element explicitly set, it
* will use the actual field names as the JsonField names.
* @version 0.0.8 (2010-03-02) refactoring...
* @version 0.0.9 (2010-03-06)
* <ul>
* <li>It can process {@link java.util.Iterator}, {@link java.lang.Iterable} and {@link java.util.Map.Entry}.</li>
* <li>If there is no explicit @ValueAccessor name, it uses the getter name that is get + the field name (e.g.
* field name: name => getName / field name: id => getId).</li>
* <li>It can handle proxied objects created by javassist.</li>
* <li>It ignores any super classes of the given JSON object if the classes are not annotated with the
* {@link Json} annotation.</li>
* </ul>
* @version 0.0.10 (2010-03-07) It does not throw an exception when the given JSON object has a proxied object created
* by javassist as a field value. Instead it tries to find any JSON objects from its super classes.
* @version 0.0.11 (2010-03-14) If the {@link ValueAccessor} without its name explicitly set is used on a field and the
* field type is <code>boolean</code> or {@link Boolean}, it tries to get the value by calling isField() method
* that is "is" + the field name instead of "get" + the field name.
* @version 0.0.12 (2010-04-20) refactoring...
* @version 0.0.13 (2010-05-10) It can handle enum type fields (it uses enumType.toString() method to use the returned
* String as the value of the field).
* @version 0.0.14 (2010-06-02) The following types are not used anymore.
* <p>
* {@link org.json.JSONObject} and {@link org.json.JSONArray}
* <p>
* These are replaced by {@link JsonObject} and {@link JsonArray} respectively.
* @version 0.0.15 (2010-06-10) known types are injectable (more extensible design).
* @version 0.0.16 (2010-06-14) refactoring...
* @version 0.1.0 (2010-09-08) {@link #convertFromJson(Class, String)} is added.
* @version 0.1.0 (2010-10-09) {@link #convertFromJson(TypeHolder, String)} is added.
*/
public class JsonStathamInAction implements JsonStatham
{
private final JavaToJsonConverter javaToJsonConverter;
private final JsonToJavaConverter jsonToJavaConverter;
public JsonStathamInAction(final JavaToJsonConverter javaToJsonConverter, final JsonToJavaConverter jsonToJavaConverter)
{
this.javaToJsonConverter = javaToJsonConverter;
this.jsonToJavaConverter = jsonToJavaConverter;
}
public JavaToJsonConverter getJavaToJsonConverter()
{
return javaToJsonConverter;
}
public JsonToJavaConverter getJsonToJavaConverter()
{
return jsonToJavaConverter;
}
@Override
public String convertIntoJson(final Object source) throws JsonStathamException
{
try
{
return javaToJsonConverter.convertIntoJson(source);
}
catch (final IllegalArgumentException e)
{
// throw new JsonStathamException(format(
// "Wrong object [object: %s] is passed or it has illegal fields with the @JsonField annotation",
// source), e);
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
}
@Override
public <T extends JsonConvertible> T convertIntoJsonConvertible(final Object source) throws JsonStathamException
{
try
{
return javaToJsonConverter.convertIntoJsonConvertible(source);
}
catch (final IllegalArgumentException e)
{
// throw new JsonStathamException(format(
// "Wrong object [object: %s] is passed or it has illegal fields with the @JsonField annotation",
// source), e);
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
}
@Override
public CharAndStringWritable convertIntoJsonWriteAndGetWriter(final Object source, final CharAndStringWritable charAndStringWritable)
throws JsonStathamException
{
try
{
javaToJsonConverter.convertIntoJsonAndWrite(source, charAndStringWritable);
return charAndStringWritable;
}
catch (final IllegalArgumentException e)
{
// throw new JsonStathamException(format(
// "Wrong object [object: %s] is passed or it has illegal fields with the @JsonField annotation",
// source), e);
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
}
@Override
public CharAndStringWritable convertIntoJsonWriteAndGetWriter(final Object source, final Writer writer) throws JsonStathamException
{
return convertIntoJsonWriteAndGetWriter(source, new CharAndStringWritableToWriter(writer));
}
@Override
public CharAndStringWritable convertIntoJsonWriteAndGetWriter(final Object source, final OutputStream outputStream)
throws JsonStathamException
{
return convertIntoJsonWriteAndGetWriter(source, new CharAndStringWritableToOutputStream(outputStream));
}
@Override
public void convertIntoJsonAndWrite(final Object source, final CharAndStringWritable charAndStringWritable) throws JsonStathamException
{
try
{
convertIntoJsonWriteAndGetWriter(source, charAndStringWritable)
.flush();
}
catch (final IllegalArgumentException e)
{
// throw new JsonStathamException(format(
// "Wrong object [object: %s] is passed or it has illegal fields with the @JsonField annotation",
// source), e);
throw new JsonStathamException(e);
}
finally
{
IoUtil.closeQuietly(charAndStringWritable);
}
}
@Override
public void convertIntoJsonAndWrite(final Object source, final Writer writer) throws JsonStathamException
{
convertIntoJsonAndWrite(source, new CharAndStringWritableToWriter(writer));
}
@Override
public void convertIntoJsonAndWrite(final Object source, final OutputStream outputStream)
{
convertIntoJsonAndWrite(source, new CharAndStringWritableToOutputStream(outputStream));
}
@Override
public JsonConvertible convertJsonStringIntoJsonConvertible(final String json) throws JsonStathamException
{
return jsonToJavaConverter.convertJsonStringIntoJsonConvertible(json);
}
@Override
public <T> T convertFromJson(final Class<T> type, final String json) throws JsonStathamException
{
try
{
return jsonToJavaConverter.convertFromJson(type, json);
}
catch (final IllegalArgumentException e)
{
throw new JsonStathamException(e);
}
catch (final InstantiationException e)
{
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final InvocationTargetException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
}
@Override
public <T> T convertFromJson(final TypeHolder<T> typeHolder, final String jsonString) throws JsonStathamException
{
try
{
return jsonToJavaConverter.convertFromJson(typeHolder, jsonString);
}
catch (final IllegalArgumentException e)
{
throw new JsonStathamException(e);
}
catch (final InstantiationException e)
{
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final InvocationTargetException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
}
@Override
public <T> T convertFromJsonConvertible(final Class<T> type, final JsonConvertible jsonConvertible) throws JsonStathamException
{
try
{
return jsonToJavaConverter.convertFromJsonConvertible(type, jsonConvertible);
}
catch (final IllegalArgumentException e)
{
throw new JsonStathamException(e);
}
catch (final InstantiationException e)
{
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final InvocationTargetException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
}
@Override
public <T> T convertFromJsonConvertible(final TypeHolder<T> typeHolder, final JsonConvertible jsonConvertible)
throws JsonStathamException
{
try
{
return jsonToJavaConverter.convertFromJsonConvertible(typeHolder, jsonConvertible);
}
catch (final IllegalArgumentException e)
{
throw new JsonStathamException(e);
}
catch (final InstantiationException e)
{
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final InvocationTargetException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
}
@Override
public <T> T convertFromJson(final Class<T> type, final CharReadable charReadable)
{
try
{
return jsonToJavaConverter.convertFromJson(type, charReadable);
}
catch (final IllegalArgumentException e)
{
throw new JsonStathamException(e);
}
catch (final InstantiationException e)
{
throw new JsonStathamException(e);
}
catch (final IllegalAccessException e)
{
throw new JsonStathamException(e);
}
catch (final InvocationTargetException e)
{
throw new JsonStathamException(e);
}
catch (final JsonStathamException e)
{
throw e;
}
finally
{
IoUtil.closeQuietly(charReadable);
}
}
@Override
public <T> T convertFromJson(final Class<T> type, final Reader reader)
{
return convertFromJson(type, new CharReadableFromReader(reader));
}
@Override
public <T> T convertFromJson(final Class<T> type, final InputStream inputStream)
{
return convertFromJson(type, new CharReadableFromInputStream(inputStream));
}
} | 33.684834 | 137 | 0.697432 |
5455e18fdf45290f0fbe7b6f05de7a8d41d7c738 | 39,325 | /*
* Copyright (C) 2020 Alberto Irurueta Carro ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irurueta.navigation.inertial.estimators;
import com.irurueta.navigation.frames.CoordinateTransformation;
import com.irurueta.navigation.frames.FrameType;
import com.irurueta.navigation.inertial.BodyKinematics;
import com.irurueta.units.Acceleration;
import com.irurueta.units.AccelerationConverter;
import com.irurueta.units.AccelerationUnit;
import com.irurueta.units.Angle;
import com.irurueta.units.AngleConverter;
import com.irurueta.units.AngleUnit;
import com.irurueta.units.AngularSpeed;
import com.irurueta.units.AngularSpeedConverter;
import com.irurueta.units.AngularSpeedUnit;
/**
* Leveling is the process of attitude initialization of a body.
* When the INS is stationary, self-alignment can be used to initialize
* the roll and pitch with all but the poorest inertial sensors.
* However, accurate self-alignment of the heading requires
* aviation-grade gyros or better. Heading is often initialized using
* a magnetic compass.
* When the INS is initialized in motion, another navigation system
* must provide an attitude reference.
* This class is based on Paul D. Groves. Principles of GNSS Inertial
* and multi-sensor integrated navigation systemd. 2nd ed. p. 196.
* <p>
* Because this implementation neglects effects of Earth rotation on sensed
* specific force, and also neglects the north component of gravity in a local
* navigation frame (which is not zero because Earth is not fully spherical),
* the expected results should be accurate up to about 1e-3 radians
* (about 0.05 degrees).
*/
public class LevelingEstimator {
/**
* Private constructor to prevent instantiation.
*/
private LevelingEstimator() {
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @return roll angle expressed in radians.
*/
public static double getRoll(final double fy, final double fz) {
return Math.atan2(-fy, -fz);
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @return pitch angle expressed in radians.
*/
public static double getPitch(
final double fx, final double fy, final double fz) {
final double fy2 = fy * fy;
final double fz2 = fz * fz;
return Math.atan(fx / Math.sqrt(fy2 + fz2));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method requires previously computed roll and pitch angles
* along with gyroscope measurements.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param roll previously computed roll angle expressed in radians.
* @param pitch previously computed pitch angle expressed in radians.
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @return yaw angle expressed in radians.
*/
@SuppressWarnings("DuplicatedCode")
public static double getYaw(
final double roll, final double pitch,
final double angularRateX, final double angularRateY,
final double angularRateZ) {
final double sinRoll = Math.sin(roll);
final double cosRoll = Math.cos(roll);
final double sinPitch = Math.sin(pitch);
final double cosPitch = Math.cos(pitch);
final double sinYaw = -angularRateY * cosRoll
+ angularRateZ * sinRoll;
final double cosYaw = angularRateX * cosPitch
+ (angularRateY * sinRoll + angularRateZ * cosRoll)
* sinPitch;
return Math.atan2(sinYaw, cosYaw);
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @return yaw angle expressed in radians.
*/
public static double getYaw(
final double fx, final double fy, final double fz,
final double angularRateX, final double angularRateY,
final double angularRateZ) {
final double roll = getRoll(fy, fz);
final double pitch = getPitch(fx, fy, fz);
return getYaw(roll, pitch, angularRateX,
angularRateY, angularRateZ);
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param kinematics body kinematics containing measured
* body specific force.
* @return roll angle expressed in radians.
*/
public static double getRoll(final BodyKinematics kinematics) {
return getRoll(kinematics.getFy(), kinematics.getFz());
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param kinematics body kinematics containing measured
* body specific force.
* @return pitch angle expressed in radians.
*/
public static double getPitch(final BodyKinematics kinematics) {
return getPitch(kinematics.getFx(), kinematics.getFy(),
kinematics.getFz());
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes.
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param kinematics body kinematics containing measured
* body specific force ang angular rates.
* @return yaw angle expressed in radians.
*/
public static double getYaw(final BodyKinematics kinematics) {
return getYaw(kinematics.getFx(), kinematics.getFy(),
kinematics.getFz(), kinematics.getAngularRateX(),
kinematics.getAngularRateY(), kinematics.getAngularRateZ());
}
/**
* Gets body attitude expressed in the local navigation frame.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param result instance where attitude will be stored.
*/
public static void getAttitude(
final double fx, final double fy, final double fz,
final double angularRateX, final double angularRateY,
final double angularRateZ, final CoordinateTransformation result) {
result.setSourceType(FrameType.LOCAL_NAVIGATION_FRAME);
result.setDestinationType(FrameType.BODY_FRAME);
final double roll = getRoll(fy, fz);
final double pitch = getPitch(fx, fy, fz);
final double yaw = getYaw(roll, pitch,
angularRateX, angularRateY, angularRateZ);
result.setEulerAngles(roll, pitch, yaw);
}
/**
* Gets body attitude expressed in the local navigation frame.
*
* @param kinematics body kinematics containing measured
* body specific force and angular rate.
* @param result instance where attitude will be stored.
*/
public static void getAttitude(
final BodyKinematics kinematics,
final CoordinateTransformation result) {
getAttitude(kinematics.getFx(), kinematics.getFy(), kinematics.getFz(),
kinematics.getAngularRateX(), kinematics.getAngularRateY(),
kinematics.getAngularRateZ(), result);
}
/**
* Gets body attitude expressed in the local navigation frame.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @return a coordinate transformation containing body attitude.
*/
public static CoordinateTransformation getAttitude(
final double fx, final double fy, final double fz,
final double angularRateX, final double angularRateY,
final double angularRateZ) {
final double roll = getRoll(fy, fz);
final double pitch = getPitch(fx, fy, fz);
final double yaw = getYaw(roll, pitch,
angularRateX, angularRateY, angularRateZ);
return new CoordinateTransformation(roll, pitch, yaw,
FrameType.LOCAL_NAVIGATION_FRAME, FrameType.BODY_FRAME);
}
/**
* Gets body attitude expressed in the local navigation frame.
*
* @param kinematics body kinematics containing measured body
* specific force and angular rate.
* @return a coordinate transformation containing body attitude.
*/
public static CoordinateTransformation getAttitude(
final BodyKinematics kinematics) {
return getAttitude(kinematics.getFx(), kinematics.getFy(),
kinematics.getFz(), kinematics.getAngularRateX(),
kinematics.getAngularRateY(), kinematics.getAngularRateZ());
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @return roll angle expressed in radians.
*/
public static double getRoll(
final Acceleration fy, final Acceleration fz) {
return getRoll(convertAcceleration(fy), convertAcceleration(fz));
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @return pitch angle expressed in radians.
*/
public static double getPitch(
final Acceleration fx, final Acceleration fy,
final Acceleration fz) {
return getPitch(convertAcceleration(fx), convertAcceleration(fy),
convertAcceleration(fz));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method requires previously computed roll and pitch angles
* along with gyroscope measurements.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param roll previously computed roll angle.
* @param pitch previously computed pitch angle.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @return yaw angle expressed in radians.
*/
public static double getYaw(
final Angle roll, final Angle pitch, final AngularSpeed angularRateX,
final AngularSpeed angularRateY, final AngularSpeed angularRateZ) {
return getYaw(convertAngle(roll), convertAngle(pitch),
convertAngularSpeed(angularRateX),
convertAngularSpeed(angularRateY),
convertAngularSpeed(angularRateZ));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @return yaw angle expressed in radians.
*/
public static double getYaw(
final Acceleration fx, final Acceleration fy, final Acceleration fz,
final AngularSpeed angularRateX, final AngularSpeed angularRateY,
final AngularSpeed angularRateZ) {
return getYaw(convertAcceleration(fx), convertAcceleration(fy),
convertAcceleration(fz), convertAngularSpeed(angularRateX),
convertAngularSpeed(angularRateY),
convertAngularSpeed(angularRateZ));
}
/**
* Gets body attitude expressed in the local navigation frame.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @param result instance where attitude will be stored.
*/
public static void getAttitude(
final Acceleration fx, final Acceleration fy, final Acceleration fz,
final AngularSpeed angularRateX, final AngularSpeed angularRateY,
final AngularSpeed angularRateZ,
final CoordinateTransformation result) {
getAttitude(convertAcceleration(fx), convertAcceleration(fy),
convertAcceleration(fz), convertAngularSpeed(angularRateX),
convertAngularSpeed(angularRateY),
convertAngularSpeed(angularRateZ), result);
}
/**
* Gets body attitude expressed in the local navigation frame.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @return a coordinate transformation containing body attitude.
*/
public static CoordinateTransformation getAttitude(
final Acceleration fx, final Acceleration fy, final Acceleration fz,
final AngularSpeed angularRateX, final AngularSpeed angularRateY,
final AngularSpeed angularRateZ) {
return getAttitude(convertAcceleration(fx), convertAcceleration(fy),
convertAcceleration(fz), convertAngularSpeed(angularRateX),
convertAngularSpeed(angularRateY),
convertAngularSpeed(angularRateZ));
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param result instance where roll angle will be stored.
*/
public static void getRollAsAngle(
final double fy, final double fz, final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getRoll(fy, fz));
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @return roll angle.
*/
public static Angle getRollAsAngle(final double fy, final double fz) {
return new Angle(getRoll(fy, fz), AngleUnit.RADIANS);
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param result instance where pitch angle will be stored.
*/
public static void getPitchAsAngle(
final double fx, final double fy, final double fz,
final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getPitch(fx, fy, fz));
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @return pitch angle.
*/
public static Angle getPitchAsAngle(
final double fx, final double fy, final double fz) {
return new Angle(getPitch(fx, fy, fz), AngleUnit.RADIANS);
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method requires previously computed roll and pitch angles
* along with gyroscope measurements.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param roll previously computed roll angle expressed in radians.
* @param pitch previously computed pitch angle expressed in radians.
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param result instance where yaw angle will be stored.
*/
public static void getYawAsAngle(
final double roll, final double pitch, final double angularRateX,
final double angularRateY, final double angularRateZ,
final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getYaw(roll, pitch, angularRateX, angularRateY,
angularRateZ));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method requires previously computed roll and pitch angles
* along with gyroscope measurements.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param roll previously computed roll angle expressed in radians.
* @param pitch previously computed pitch angle expressed in radians.
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @return yaw angle.
*/
public static Angle getYawAsAngle(
final double roll, final double pitch, final double angularRateX,
final double angularRateY, final double angularRateZ) {
return new Angle(getYaw(roll, pitch, angularRateX, angularRateY,
angularRateZ), AngleUnit.RADIANS);
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param result instance where yaw angle will be stored.
*/
public static void getYawAsAngle(
final double fx, final double fy, final double fz,
final double angularRateX, final double angularRateY,
final double angularRateZ, final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getYaw(fx, fy, fz, angularRateX, angularRateY,
angularRateZ));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param fx x-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fy y-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param fz z-coordinate of measured body specific force
* expressed in meters per squared second (m/s^2).
* @param angularRateX x-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateY y-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @param angularRateZ z-coordinate of body angular rate expressed in
* radians per second (rad/s).
* @return yaw angle.
*/
public static Angle getYawAsAngle(
final double fx, final double fy, final double fz,
final double angularRateX, final double angularRateY,
final double angularRateZ) {
return new Angle(getYaw(fx, fy, fz, angularRateX, angularRateY,
angularRateZ), AngleUnit.RADIANS);
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param kinematics body kinematics containing measured
* body specific force.
* @param result instance where roll angle will be stored.
*/
public static void getRollAsAngle(
final BodyKinematics kinematics, final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getRoll(kinematics));
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param kinematics body kinematics containing measured
* body specific force.
* @return roll angle.
*/
public static Angle getRollAsAngle(final BodyKinematics kinematics) {
return new Angle(getRoll(kinematics), AngleUnit.RADIANS);
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param kinematics body kinematics containing measured
* body specific force.
* @param result instance where pitch angle will be stored.
*/
public static void getPitchAsAngle(
final BodyKinematics kinematics, final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getPitch(kinematics));
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param kinematics body kinematics containing measured
* body specific force.
* @return pitch angle.
*/
public static Angle getPitchAsAngle(final BodyKinematics kinematics) {
return new Angle(getPitch(kinematics), AngleUnit.RADIANS);
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes.
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param kinematics body kinematics containing measured
* body specific force ang angular rates.
* @param result instance where yaw angle will be stored.
*/
public static void getYawAsAngle(
final BodyKinematics kinematics, final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getYaw(kinematics));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes.
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param kinematics body kinematics containing measured
* body specific force ang angular rates.
* @return yaw angle.
*/
public static Angle getYawAsAngle(final BodyKinematics kinematics) {
return new Angle(getYaw(kinematics), AngleUnit.RADIANS);
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @param result instance where roll angle will be stored.
*/
public static void getRollAsAngle(
final Acceleration fy, final Acceleration fz, final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getRoll(fy, fz));
}
/**
* Gets roll angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @return roll angle.
*/
public static Angle getRollAsAngle(
final Acceleration fy, final Acceleration fz) {
return new Angle(getRoll(fy, fz), AngleUnit.RADIANS);
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @param result instance where pitch angle will be stored.
*/
public static void getPitchAsAngle(
final Acceleration fx, final Acceleration fy, final Acceleration fz,
final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getPitch(fx, fy, fz));
}
/**
* Gets pitch angle of body attitude expressed in radians.
* This is based on expression (5.101) of Paul D. Groves.
* Principles of GNSS Inertial and multi-sensor integrated
* navigation systemd. 2nd ed.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @return pitch angle.
*/
public static Angle getPitchAsAngle(
final Acceleration fx, final Acceleration fy, final Acceleration fz) {
return new Angle(getPitch(fx, fy, fz), AngleUnit.RADIANS);
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method requires previously computed roll and pitch angles
* along with gyroscope measurements.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param roll previously computed roll angle.
* @param pitch previously computed pitch angle.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @param result instance where yaw angle will be stored.
*/
public static void getYawAsAngle(
final Angle roll, final Angle pitch, final AngularSpeed angularRateX,
final AngularSpeed angularRateY, final AngularSpeed angularRateZ,
final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getYaw(roll, pitch, angularRateX, angularRateY,
angularRateZ));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method requires previously computed roll and pitch angles
* along with gyroscope measurements.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param roll previously computed roll angle.
* @param pitch previously computed pitch angle.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @return yaw angle.
*/
public static Angle getYawAsAngle(
final Angle roll, final Angle pitch, final AngularSpeed angularRateX,
final AngularSpeed angularRateY, final AngularSpeed angularRateZ) {
return new Angle(getYaw(roll, pitch, angularRateX, angularRateY,
angularRateZ), AngleUnit.RADIANS);
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @param result instance where yaw angle will be stored.
*/
public static void getYawAsAngle(
final Acceleration fx, final Acceleration fy, final Acceleration fz,
final AngularSpeed angularRateX, final AngularSpeed angularRateY,
final AngularSpeed angularRateZ, final Angle result) {
result.setUnit(AngleUnit.RADIANS);
result.setValue(getYaw(fx, fy, fz, angularRateX, angularRateY,
angularRateZ));
}
/**
* Gets yaw angle of body attitude expressed in radians.
* This method can only be used for high-accuracy gyroscopes,
* otherwise, yaw angle must be measured using a magnetometer.
*
* @param fx x-coordinate of measured body specific force.
* @param fy y-coordinate of measured body specific force.
* @param fz z-coordinate of measured body specific force.
* @param angularRateX x-coordinate of body angular rate.
* @param angularRateY y-coordinate of body angular rate.
* @param angularRateZ z-coordinate of body angular rate.
* @return yaw angle.
*/
public static Angle getYawAsAngle(
final Acceleration fx, final Acceleration fy, final Acceleration fz,
final AngularSpeed angularRateX, final AngularSpeed angularRateY,
final AngularSpeed angularRateZ) {
return new Angle(getYaw(fx, fy, fz, angularRateX, angularRateY,
angularRateZ), AngleUnit.RADIANS);
}
/**
* Converts an instance of acceleration to meters per squared second (m/s^2).
*
* @param acceleration acceleration instance to be converted.
* @return converted acceleration value.
*/
private static double convertAcceleration(final Acceleration acceleration) {
return AccelerationConverter.convert(
acceleration.getValue().doubleValue(),
acceleration.getUnit(),
AccelerationUnit.METERS_PER_SQUARED_SECOND);
}
/**
* Converts an instance of angular speed to radians per second (rad/s).
*
* @param angularSpeed angular speed instance to be converted.
* @return converted angular speed value.
*/
private static double convertAngularSpeed(final AngularSpeed angularSpeed) {
return AngularSpeedConverter.convert(
angularSpeed.getValue().doubleValue(),
angularSpeed.getUnit(),
AngularSpeedUnit.RADIANS_PER_SECOND);
}
/**
* Converts an instance of an angle to radians (rad).
*
* @param angle angle to be converted.
* @return converted angle value.
*/
private static double convertAngle(final Angle angle) {
return AngleConverter.convert(angle.getValue().doubleValue(),
angle.getUnit(), AngleUnit.RADIANS);
}
}
| 44.942857 | 82 | 0.649053 |
d54934e507078f6028292064b96f592f3440ee7f | 726 |
public final class realMoneyUser extends User {
public realMoneyUser(String userName, String passWord, double balance) {
super(userName, passWord, balance);
}
public realMoneyUser(String userName, String passWord, double balance, double profit) {
super(userName, passWord, balance, profit);
}
@Override
public void Login() {
System.out.println("Real Money Account. Authorized users only!");
String password = inputString("Enter the password");
while (!(password.equals(getPassword()))){
System.out.println("Enter the correct details");
password = inputString("Enter the password");
}
}
}
| 25.928571 | 91 | 0.62259 |
b4f25e8e2d21494dcb78747c37642f3cb3988c4e | 1,606 | package cn.conque.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 发布订阅模式
*/
@Configuration
public class RabbitmqFanoutConfig {
public static final String FANOUT_QUEUE_A = "fanout_queue_a";
public static final String FANOUT_QUEUE_B = "fanout_queue_b";
public static final String FANOUT_QUEUE_C = "fanout_queue_c";
public static final String FANOUT_EXCHANGE = "fanout_exchange";
@Bean
public Queue fanoutQueueA() {
return new Queue(FANOUT_QUEUE_A);
}
@Bean
public Queue fanoutQueueB() {
return new Queue(FANOUT_QUEUE_B);
}
@Bean
public Queue fanoutQueueC() {
return new Queue(FANOUT_QUEUE_C);
}
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange(FANOUT_EXCHANGE);
}
@Bean
public Binding queueABindingExchange(Queue fanoutQueueA, FanoutExchange fanoutExchange){
return BindingBuilder.bind(fanoutQueueA).to(fanoutExchange);
}
@Bean
public Binding queueBBindingExchange(Queue fanoutQueueB, FanoutExchange fanoutExchange){
return BindingBuilder.bind(fanoutQueueB).to(fanoutExchange);
}
@Bean
public Binding queueCBindingExchange(Queue fanoutQueueC, FanoutExchange fanoutExchange){
return BindingBuilder.bind(fanoutQueueC).to(fanoutExchange);
}
}
| 28.175439 | 92 | 0.740971 |
1a37c3c931f740e26053810d852e0e874feeff9e | 3,008 | package com.nuc.menu.child;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class XMLChildStorage implements ChildStorage {
private static final Logger LOGGER = LogManager.getLogger(XMLChildStorage.class);
private static final String NAME = "name";
private static final String CALORIES = "calories";
public static final String AGE = "age";
public static final String GENDER = "gender";
private final String filePath;
public XMLChildStorage(String filePath) {
this.filePath = filePath;
}
@Override
public Set<Child> getChildren() {
if (!new File(filePath).exists()) {
saveChildren(Collections.emptySet());
return Collections.emptySet();
}
try {
final SAXBuilder saxBuilder = new SAXBuilder();
final Document document = saxBuilder.build(new File(filePath));
final Element rootElement = document.getRootElement();
return rootElement.getChildren().stream().map(this::getChildFromElement).collect(Collectors.toCollection(TreeSet::new));
} catch (Exception e) {
LOGGER.error("Failed to get children", e);
return Collections.emptySet();
}
}
@Override
public void saveChildren(Set<Child> children) {
final Document document = new Document(new Element("children"));
children.stream().map(this::getElementFromChild).forEach(element -> document.getRootElement().addContent(element));
final XMLOutputter xmlOutputter = new XMLOutputter();
xmlOutputter.setFormat(Format.getPrettyFormat());
try {
xmlOutputter.output(document, new FileWriter(filePath));
} catch (IOException e) {
LOGGER.error("Failed to write children", e);
}
}
private Child getChildFromElement(Element element) {
final String name = element.getAttribute(NAME).getValue();
final String age = element.getAttribute(AGE).getValue();
final String gender = element.getAttribute(GENDER).getValue();
final String caloriesRequirement = element.getAttribute(CALORIES).getValue();
return new Child(name, age, gender, caloriesRequirement);
}
private Element getElementFromChild(Child foodItem) {
final Element element = new Element("child");
element.setAttribute(NAME, foodItem.getName());
element.setAttribute(AGE, foodItem.getAge());
element.setAttribute(GENDER, foodItem.getGender());
element.setAttribute(CALORIES, foodItem.getCaloriesRequirement());
return element;
}
}
| 35.388235 | 132 | 0.686835 |
6680ef0f316a0b610a07ef73b8ff221fbc1213fa | 1,913 | package dialight.observable.map;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class ObservableMapWrapper<K, V> extends ObservableMap<K, V> {
protected final Map<K, V> map;
public ObservableMapWrapper(Map<K, V> map) {
this.map = map;
}
public ObservableMapWrapper() {
this(new HashMap<>());
}
@Override public int size() { return map.size(); }
@Override public boolean containsKey(Object key) { return map.containsKey(key); }
@Override public boolean containsValue(Object value) { return map.containsValue(value); }
@Override public V get(Object key) { return map.get(key); }
@Override public boolean isEmpty() { return map.isEmpty(); }
@NotNull @Override public Set<Entry<K, V>> entrySet() { return map.entrySet(); }
@NotNull @Override public Set<K> keySet() { return map.keySet(); }
@NotNull @Override public Collection<V> values() { return map.values(); }
@Override public void clear() {
for (Entry<K, V> entry : map.entrySet()) {
fireRemove(entry.getKey(), entry.getValue());
}
map.clear();
}
@Override public V put(K key, V value) {
V old = map.put(key, value);
if(old != null) {
fireReplace(key, old, value);
} else {
firePut(key, value);
}
return old;
}
@Override public void putAll(Map<? extends K, ? extends V> from) {
for(Entry<? extends K, ? extends V> entry : from.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override public V remove(Object key) {
V rem = map.remove(key);
if(rem != null) {
fireRemove((K) key, rem);
}
return rem;
}
}
| 29.430769 | 94 | 0.578672 |
c106fbb39473a7d01fbfecdad24e643b6d35dd78 | 3,233 | // Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.managedtenants.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.GenericError;
import com.microsoft.graph.managedtenants.models.WorkloadActionStatus;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Workload Action Deployment Status.
*/
public class WorkloadActionDeploymentStatus implements IJsonBackedObject {
/** the OData type of the object as returned by the service */
@SerializedName("@odata.type")
@Expose
@Nullable
public String oDataType;
private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);
@Override
@Nonnull
public final AdditionalDataManager additionalDataManager() {
return additionalDataManager;
}
/**
* The Action Id.
* The unique identifier for the workload action. Required. Read-only.
*/
@SerializedName(value = "actionId", alternate = {"ActionId"})
@Expose
@Nullable
public String actionId;
/**
* The Deployed Policy Id.
* The identifier of any policy that was created by applying the workload action. Optional. Read-only.
*/
@SerializedName(value = "deployedPolicyId", alternate = {"DeployedPolicyId"})
@Expose
@Nullable
public String deployedPolicyId;
/**
* The Error.
* The detailed information for exceptions that occur when deploying the workload action. Optional. Required.
*/
@SerializedName(value = "error", alternate = {"Error"})
@Expose
@Nullable
public GenericError error;
/**
* The Last Deployment Date Time.
* The date and time the workload action was last deployed. Optional.
*/
@SerializedName(value = "lastDeploymentDateTime", alternate = {"LastDeploymentDateTime"})
@Expose
@Nullable
public java.time.OffsetDateTime lastDeploymentDateTime;
/**
* The Status.
* The status of the workload action deployment. Possible values are: toAddress, completed, error, timeOut, inProgress, unknownFutureValue. Required. Read-only.
*/
@SerializedName(value = "status", alternate = {"Status"})
@Expose
@Nullable
public WorkloadActionStatus status;
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
}
}
| 32.989796 | 164 | 0.685431 |
06b269d36d22059006d23d5c51856f784a891586 | 112 | package net.denwilliams.homenet.domain;
public interface Switch {
String getId();
String getValue();
}
| 16 | 39 | 0.714286 |
dd210280f6e302f255a19ed43288bfcb96436b84 | 381 | package com.neusoft;
public class Phone {
//品牌
String brand;
//价格
int price;
//颜色
String color;//成员变量
//方法
//给name 打电话
public void call(String name) {
int a = 45; //局部变量
System.out.println("给"+name+"打电话");
}
//发短信
public void sendMessage() {
System.out.println("发短信");
}
}
| 13.607143 | 43 | 0.48294 |
6febcd70a0de9aa84d1de635a039db41f722f29d | 265 | package gov.cms.mat.fhir.rest.dto.spreadsheet;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class DataType {
private String dataType;
private String validValues;
private String regex;
private String type;
}
| 18.928571 | 46 | 0.766038 |
c1df7763d44e018979f4268e41827715d2128172 | 5,616 | package com.winterwell.es.client;
import java.util.List;
import java.util.Map;
import com.winterwell.gson.RawJson;
import com.winterwell.utils.containers.ArrayMap;
import com.winterwell.utils.io.FileUtils;
import com.winterwell.utils.time.Dt;
/**
* Update a document based on a script provided.
* https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html#_literal_doc_as_upsert_literal
*
* @see UpdateByQueryRequest
* @see org.UpdateRequest.action.update.UpdateRequestBuilder
* @author daniel
* @testedby UpdateRequestBuilderTest
*/
public class UpdateRequest extends ESHttpRequest<UpdateRequest,IESResponse> {
private boolean docAsUpsert;
@Override
protected void get2_safetyCheck() {
if (indices==null || indices.size()==0) throw new IllegalStateException("No index specified for update: "+this);
// typeless ESv7 if (type==null) throw new IllegalStateException("No type specified for update: "+this);
if (id==null) throw new IllegalStateException("No id specified for update: "+this);
}
public UpdateRequest(ESHttpClient esHttpClient) {
super(esHttpClient,"_update");
method = "POST";
bulkOpName = "update";
setType("_doc"); // the new ESv7 omni-type
}
/**
* The language of the script to execute.
* Valid options are: mvel, js, groovy, python, expression, and native (Java)<br>
* Default: groovy (v1.3; was mvel before, but mvel is now deprecated).<br>
* There are security settings which affect scripts! See the link below for details.
* <p>
* Ref: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html
*/
public UpdateRequest setScriptLang(String scriptLang) {
Map script = script();
script.put("lang", scriptLang);
return this;
}
private Map script() {
Map script = (Map) body().get("script");
if (script==null) {
script = new ArrayMap();
body().put("script", script);
}
return script;
}
public UpdateRequest setDoc(Map doc) {
body().put("doc", doc);
return this;
}
/**
* @deprecated Use {@link #setDoc(Map)} or {@link #setScript(String)}
*/
@Override
public UpdateRequest setBodyJson(String json) {
return super.setBodyJson(json);
}
/**
* @deprecated Use {@link #setDoc(Map)} or {@link #setScript(String)}
*/
@Override
public UpdateRequest setBodyMap(Map msrc) {
// TODO Auto-generated method stub
return super.setBodyMap(msrc);
}
/**
* Ref: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-update.html#_literal_doc_as_upsert_literal
* @param b
* @return
*/
public UpdateRequest setDocAsUpsert(boolean b) {
if (b==docAsUpsert) return this;
docAsUpsert = b;
body().put("doc_as_upsert", docAsUpsert);
// // move the doc/upsert data if it was set already
// if (docAsUpsert) {
// Object doc = body.get("doc");
// body.put("upsert", doc);
// } else {
// Object doc = body.get("upsert");
// body.put("doc", doc);
// }
return this;
}
/**
* WARNING: Whether or not this works will depend on your script settings!
*
* Convenience method (not a part of the base API) for removing fields.
* ??Can this combine with upsert??
* @param removeTheseFields
* @param optionalResultField
* @return
*/
public UpdateRequest setRemovedFields(List<String> removeTheseFields, String optionalResultField) {
if (removeTheseFields.isEmpty()) {
// Probably a no-op!
return this;
}
assert getScript()==null;
String script;
// is there a tag to remove? Set OP_RESULT
// "already = ctx._source.jobid2output[job]; "
// +"if (already==empty) { ctx._source."+ESStorage._ESresult+" = false; } "
// +"else { ctx._source."+ESStorage._ESresult+" = true; }"
script = FileUtils.read(UpdateRequest.class.getResourceAsStream("remove_fields.groovy"));
setScript(script);
setScriptParams(new ArrayMap("removals", removeTheseFields, "resultField", optionalResultField));
// Return what we did
if (optionalResultField!=null) setFields(optionalResultField);
return this;
}
/**
* If the doc does not exist -- set to initialJson and don't run the script.
* If it does exist -- this has no effect: just run the script.
*
* ref: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html#upserts
* @param initialJson
*/
public UpdateRequest setUpsert(Map<String, Object> initialJson) {
// jetty JSON is slightly more readable
// String _sjson = hClient.gson.toJson(json);
// String sjson = WebUtils2.generateJSON(initialJson);
body().put("upsert", initialJson); //sjson);
if (docAsUpsert) {
throw new IllegalStateException("doc-as-upsert does not go with upsert + script");
}
return this;
}
public UpdateRequest setScript(String script) {
Map s = script();
s.put("inline", script);
return this;
}
/**
* @deprecated
* @return Can be null
*/
public Object getScript() {
return body==null? null : body.get("script");
}
public UpdateRequest setScriptParams(Map params) {
script().put("params", params);
return this;
}
/**
*
* @param ttl Can be null.
*/
public void setTimeToLive(Dt ttl) {
if (ttl==null) params.remove("_ttl");
else params.put("_ttl", ttl.getMillisecs());
}
public void setDoc(String docJson) {
// HACK - poke the doc json into a wrapping doc property
body().put("doc", new RawJson(docJson));
// setBodyJson("{\"doc\":"+docJson+"}");
}
public void setScript(PainlessScriptBuilder psb) {
setScript(psb.getScript());
setScriptLang(psb.getLang());
setScriptParams(psb.getParams());
}
}
| 28.653061 | 116 | 0.688568 |
74574d97e5a587e7935d4e2720f4746c14da74e6 | 6,368 | package com.Simone.Giuseppe.Help_Smart;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.util.Calendar;
public class MyPhoneStateListener extends PhoneStateListener {
public Context ctx;
public static Boolean phoneRinging = false;
private SharedPreferences Settings, mapTrack;
private String message;
Calendar calendar;
public MyPhoneStateListener(Context context){
ctx=context;
calendar = Calendar.getInstance();
Settings = ctx.getSharedPreferences("Settings", Context.MODE_PRIVATE);
mapTrack = ctx.getSharedPreferences("track" + calendar.get(Calendar.DAY_OF_WEEK), Context.MODE_PRIVATE);
message="Messaggio automatico di emergenza: ho bisogno del tuo aiuto la mia posizione è:\n " ;
}
public static double startTime=0,elapsedTime=0, endTime=0;
private boolean autorizeSms=false;
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.e("elapsedIDLE",Double.toString(elapsedTime/1000));
if(PlayerService.SecondCall) {
if(endTime==0)
endTime=System.currentTimeMillis();
elapsedTime=endTime-startTime;
Log.e("Start",Double.toString(startTime));
Log.e("End",Double.toString(endTime));
Log.e("elapsed",Double.toString(elapsedTime/1000));
if(elapsedTime/1000>=10) {
Log.d("DEBUG", "IDLE");
if (Settings.getString("NumeroEmergenza2", "") != "") {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + Settings.getString("NumeroEmergenza2", "")));
PlayerService.SecondCall = false;
autorizeSms=true;
endTime=0;
startTime=0;
elapsedTime=0;
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
ctx.startActivity(callIntent);
}else {
Log.e("else","1");
autorizeSms=false;
endTime = 0;
startTime=0;
elapsedTime=0;
PlayerService.sms=false;
PlayerService.SecondCall = false;
if(!PlayerService.keyEmergency) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(Settings.getString("NumeroEmergenza", ""), null, message +"\n"+ "http://maps.google.com/maps?f=q&q=" + mapTrack.getFloat("lat" + (mapTrack.getInt("cnt", 0) - 1), 0) + "," + mapTrack.getFloat("lon" + (mapTrack.getInt("cnt", 0) - 1), 0) + "&z=16", null, null);
Log.e("Send", "SMS1");
PlayerService.keyEmergency=false;
}
}
}else{
Log.e("else","2");
PlayerService.sms=false;
PlayerService.SecondCall = false;
startTime=0;
elapsedTime=0;
endTime=0;
Log.e("StartIDLE",Double.toString(startTime));
}
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.e("StartOFFHOOK",Double.toString(startTime));
Log.e("endOFFHOOK",Double.toString(endTime));
Log.e("elapsedOFFHOOK",Double.toString(elapsedTime/1000));
if(PlayerService.sms) {
Log.e("offhook","offhooksms");
if(startTime==0)
startTime=System.currentTimeMillis();
/* try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}*/
Log.e("autorizeSms",Boolean.toString(autorizeSms));
Log.e("keyemergency",Boolean.toString(PlayerService.keyEmergency));
if(autorizeSms && !PlayerService.keyEmergency) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(Settings.getString("NumeroEmergenza", ""), null, message +"\n"+ "http://maps.google.com/maps?f=q&q=" + mapTrack.getFloat("lat" + (mapTrack.getInt("cnt", 0) - 1), 0) + "," + mapTrack.getFloat("lon" + (mapTrack.getInt("cnt", 0) - 1), 0) + "&z=16", null, null);
Log.e("Send","SMS1");
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
if (Settings.getString("NumeroEmergenza2", "") != "")
smsManager.sendTextMessage(Settings.getString("NumeroEmergenza2", ""), null, message +"\n"+ "http://maps.google.com/maps?f=q&q=" + mapTrack.getFloat("lat" + (mapTrack.getInt("cnt", 0) - 1), 0) + "," + mapTrack.getFloat("lon" + (mapTrack.getInt("cnt", 0) - 1), 0) + "&z=16", null, null);
Log.d("Send","SMS2");
PlayerService.sms = false;
autorizeSms=false;
startTime=0;
endTime=0;
elapsedTime=0;
PlayerService.keyEmergency=false;
PlayerService.SecondCall = false;
Log.d("DEBUG", "SMSEND");
}
}
Log.d("DEBUG", "OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d("DEBUG", "RINGING");
break;
}
}
} | 47.879699 | 317 | 0.504868 |
49498620836693a59fff951cd46265d68a9f1173 | 1,678 |
/**
* Write a description of Part1 here.
*
* @author (your name)
* @version (a version number or a date)
*/
import edu.duke.*;
import java.io.*;
public class Part1 {
public StorageResource getAllGenes(String dna){
StorageResource sr = new StorageResource();
int startIndex = dna.indexOf("ATG", 0);
if(startIndex == -1) return sr;
int currIndex = 0;
while(currIndex != -1){
int taaIndex = findStopCodon(dna, startIndex, "TAA");
int tagIndex = findStopCodon(dna, startIndex, "TAG");
int tgaIndex = findStopCodon(dna, startIndex, "TGA");
currIndex = Math.min(taaIndex, Math.min(tagIndex, tgaIndex));
if(currIndex == dna.length()) break;
String gene = dna.substring(startIndex, currIndex+3);
sr.add(gene);
startIndex = dna.indexOf("ATG", currIndex+1);
}
return sr;
}
public int findStopCodon(String dna, int startIndex, String stopCodon){
int currIndex = dna.indexOf(stopCodon, startIndex+3);
// Doesn't Find anything
if(currIndex == -1) return dna.length();
int diffIndex = currIndex - startIndex;
while(true){
if(diffIndex % 3 == 0) return currIndex;
currIndex = dna.indexOf(stopCodon, startIndex+currIndex+1);
if(currIndex == -1) break;
}
return dna.length();
}
public void testGene(){
String dna = "ATGTTTGTAAGATTAATGAGGTAGATGAAG";
StorageResource genes = getAllGenes(dna);
for(String gene: genes.data()){
System.out.println(gene);
}
}
}
| 32.269231 | 75 | 0.580453 |
424896d6f0016b7c4dc7a519d780592a91ddccda | 2,428 | package org.ldlood.controller;
import org.ldlood.VO.EventInfoVO;
import org.ldlood.VO.EventVO;
import org.ldlood.VO.ResultVO;
import org.ldlood.dataobject.EventCategory;
import org.ldlood.dataobject.EventInfo;
import org.ldlood.service.CategoryService;
import org.ldlood.service.EventService;
import org.ldlood.utils.ResultVOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by Ldlood on 2017/7/20.
*/
@RestController
@RequestMapping("/buyer/Event")
@CrossOrigin
public class BuyerEventController {
private Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private EventService EventService;
@Autowired
private CategoryService categoryService;
@GetMapping("/list")
// @Cacheable(cacheNames = "Event", key = "#sellerid", condition = "#sellerid.length()>10", unless = "#result.getCode() !=0")
public ResultVO list(@RequestParam(value = "sellerid", required = false) String sellerid) {
//查询上架的商品
List<EventInfo> EventInfoList = EventService.findUpAll();
List<Integer> categoryTypeList = EventInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
List<EventCategory> EventCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
List<EventVO> EventVOList = new ArrayList<>();
for (EventCategory EventCategory : EventCategoryList) {
EventVO EventVO = new EventVO();
EventVO.setCategoryType(EventCategory.getCategoryType());
EventVO.setCategoryName(EventCategory.getCategoryName());
List<EventInfoVO> EventInfoVOList = new ArrayList<>();
for (EventInfo EventInfo : EventInfoList) {
if (EventInfo.getCategoryType().equals(EventCategory.getCategoryType())) {
EventInfoVO EventInfoVO = new EventInfoVO();
BeanUtils.copyProperties(EventInfo, EventInfoVO);
EventInfoVOList.add(EventInfoVO);
}
}
EventVO.setEventInfoVOList(EventInfoVOList);
EventVOList.add(EventVO);
}
return ResultVOUtil.success(EventVOList);
}
}
| 33.722222 | 128 | 0.7014 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.