blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
07264bd1987b4dc3aebd2b97ef2980070ba65fbf
Java
seven-of-zero/FGPtest
/src/main/java/com/soz/service/CommentService.java
UTF-8
191
1.664063
2
[]
no_license
package com.soz.service; import com.soz.pojo.Comment; import java.util.List; public interface CommentService { void add(Comment comment); List<Comment> show(Integer article); }
true
697e1244e66c587e3331fd5be5498768390d5ca1
Java
kokodavid/Foodie
/app/src/main/java/com/koko/foodie/Activities/Search/SearchPresenter.java
UTF-8
1,325
2.03125
2
[]
no_license
package com.koko.foodie.Activities.Search; import androidx.annotation.NonNull; import com.koko.foodie.Models.Food; import com.koko.foodie.Models.Meals; import com.koko.foodie.Utils.Utils; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SearchPresenter { private SearchView view; public SearchPresenter(SearchView view) { this.view = view; } void getSearch(String name){ view.showLoading(); Call<Food> foodCall = Utils.getSearchResults().getSearchedFood(name,"6792adb5e9b544dc990c2499f73befb6","500"); foodCall.enqueue(new Callback<Food>() { @Override public void onResponse(@NonNull Call<Food> call,@NonNull Response<Food> response) { view.hideloading(); if (response.isSuccessful() && response.body() != null){ view.setSearch(response.body().getResults()); }else { view.onErrorLoading(response.message()); } } @Override public void onFailure(@NonNull Call<Food> call,@NonNull Throwable t) { view.showLoading(); t.getLocalizedMessage(); } }); } }
true
4f46916caced263cedf687f09bf0b669c3863d16
Java
brfarlow/Java-Programming-mooc.fi
/2013-OOProgrammingWithJava-PART2/week7-week7_04.ThingSuitcaseAndContainer/src/Container.java
UTF-8
1,046
3.28125
3
[]
no_license
import java.util.ArrayList; /* * 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. */ /** * * @author Xorfos */ public class Container { private int maxWeight; private int totalWeight; private ArrayList<Suitcase> suitcases = new ArrayList(); public Container(int maxWeight){ this.maxWeight = maxWeight; this.totalWeight = 0; } public void addSuitcase(Suitcase suitcase){ if(totalWeight+suitcase.totalWeight() > this.maxWeight){ }else{ this.suitcases.add(suitcase); totalWeight += suitcase.totalWeight(); } } @Override public String toString(){ return this.suitcases.size()+" suitcases ("+this.totalWeight+" kg)"; } public void printThings(){ for(Suitcase suitcase : suitcases){ suitcase.printThings(); } } }
true
9e9260a455c1c4225ec857f543d97ec418c679f7
Java
soranico/spring-learn
/spring-learn/src/main/java/com/soranico/service/impl/MyServiceMapImpl02.java
UTF-8
450
1.695313
2
[ "Apache-2.0" ]
permissive
package com.soranico.service.impl; import com.soranico.service.MyServiceMap; import org.springframework.stereotype.Service; /** * <pre> * @title com.soranico.service.impl.MyServiceMapImpl01 * @description * <pre> * 全都要2 * </pre> * * @author soranico * @version 1.0 * @date 2020/5/10 * * </pre> */ @Service public class MyServiceMapImpl02 implements MyServiceMap { @Override public void testMap() { } }
true
12032bb7f44557ecc1248410c5ea4a3a3234a82e
Java
99550857/employee
/src/com/managesystem/model/Department.java
UTF-8
1,375
2.515625
3
[]
no_license
package com.managesystem.model; /** * @author lihui * Created by 99550 on 2017/12/20. */ public class Department { private Integer id; private String name; private String introduction; private String contactway; public Department(Integer id, String name, String introduction, String contactway) { this.id = id; this.name = name; this.introduction = introduction; this.contactway = contactway; } public Department() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getContactway() { return contactway; } public void setContactway(String contactway) { this.contactway = contactway; } @Override public String toString() { return "Department{" + "id=" + id + ", name='" + name + '\'' + ", introduction='" + introduction + '\'' + ", contactway='" + contactway + '\'' + '}'; } }
true
1cbbf8596cac74033a1e2abf69eacecf8503b31f
Java
popant/uc
/src/main/java/com/channelsoft/usercenter/consumable/controller/ConsumeController.java
UTF-8
2,836
1.921875
2
[]
no_license
package com.channelsoft.usercenter.consumable.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.channelsoft.usercenter.common.controller.BaseController; import com.channelsoft.usercenter.consumable.service.IConsumeService; import com.channelsoft.usercenter.consumable.service.IProductService; import com.channelsoft.usercenter.consumable.service.IPurchaseService; @Controller @RequiresAuthentication @RequestMapping("/consume") public class ConsumeController extends BaseController{ private Logger logger = Logger.getLogger(getClass()); @Autowired private IPurchaseService purchaseService; @Autowired private IProductService productService; @Autowired private IConsumeService consumeService; /** * 前往消费统计页面 * * String * 张辰熇 * 2016年1月18日 */ @RequestMapping("/gotoStatics") public String gotoStatics(HttpServletRequest request,HttpServletResponse response){ logger.info("进入ConsumeController的gotoStatics()方法..."); try { request.setAttribute("statics", purchaseService.getConsumableStatics(getUserInfo().getEnterpriseId())); request.setAttribute("products", productService.getProductsByEntId(getUserInfo().getEnterpriseId())); } catch (Exception e) { logger.error("获取消费统计相关数据失败:" + e.getCause().getMessage()); request.setAttribute("error", e.getCause().getMessage()); return "consumable/consumableError"; } return "consumable/statics"; } /** * 消费统计明细 * * String * 张辰熇 * 2016年1月20日 */ @RequestMapping("/gotoStaticsDetail") public String gotoConsumeDetail(HttpServletRequest request,HttpServletResponse response){ logger.info("进入ConsumeController的gotoConsumeDetail()方法..."); try { request.setAttribute("staticsDetails", consumeService.getConsumableOrders(getUserInfo().getEnterpriseId())); request.setAttribute("statics", purchaseService.getConsumableStatics(getUserInfo().getEnterpriseId())); request.setAttribute("products", productService.getProductsByEntId(getUserInfo().getEnterpriseId())); } catch (Exception e) { logger.error("获取消费明细相关数据失败:" + e.getCause().getMessage()); request.setAttribute("error", e.getCause().getMessage()); return "consumable/consumableError"; } return "consumable/staticsDetail"; } @RequestMapping("/gotoMetronic") public String gotoMetronic(HttpServletRequest request,HttpServletResponse response){ return "/zchShow"; } }
true
3caa30a405d358ceac4a1f9b9281c5e165e92064
Java
JayVae/parking
/停车场项目/parking/.svn/pristine/6a/6af894a7eb9e7e76bf9eb5bac4dfd3ece2cbcd4e.svn-base
UTF-8
1,156
2
2
[]
no_license
package com.hu.parking.entity; import java.io.Serializable; public class Freetimetmp implements Serializable { private Object freetimetmpid; private Object orduserid; private String name; private String isvalid; private String note; private static final long serialVersionUID = 1L; public Object getFreetimetmpid() { return freetimetmpid; } public void setFreetimetmpid(Object freetimetmpid) { this.freetimetmpid = freetimetmpid; } public Object getOrduserid() { return orduserid; } public void setOrduserid(Object orduserid) { this.orduserid = orduserid; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getIsvalid() { return isvalid; } public void setIsvalid(String isvalid) { this.isvalid = isvalid == null ? null : isvalid.trim(); } public String getNote() { return note; } public void setNote(String note) { this.note = note == null ? null : note.trim(); } }
true
a8cd70df838185376b61a6526f8613f24bdfd3bf
Java
Sakue34/CarnivoreHerbivore
/src/main/java/pl/edu/pwr/carnivoreherbivore/simulation/SimulationParameters.java
UTF-8
4,545
2.6875
3
[]
no_license
package pl.edu.pwr.carnivoreherbivore.simulation; /** * Klasa przechowująca parametry symulacji. */ public final class SimulationParameters { public final int mapWidth; public final int mapHeight; public final float speedOfSimulationMultiplier; public final int startingNumberOfPlants; public final int startingNumberOfHerbivores; public final int startingNumberOfCarnivores; public final float herbivoreSpeed; public final float carnivoreSpeed; public final float plantNutritionalValue; public final float herbivoreStartingEnergy; public final float carnivoreStartingEnergy; public final float herbivoreEnergyConsumptionPerSecond; public final float carnivoreEnergyConsumptionPerSecond; public final int plantRadius; public final int herbivoreRadius; public final int carnivoreRadius; public final float herbivoreSightRange; public final float carnivoreSightRange; public final float baseHerbivoreNutritionalValue; public final float timeToSetNewRandomHerbivoreWanderDirection; public final float timeToSetNewRandomCarnivoreWanderDirection; public final String colourStringOfPlant; public final String colourStringOfHerbivore; public final String colourStringOfCarnivore; public final boolean useGUI; public final float timeBetweenProgressOutputInTerminal; public final int numberOfPawnsToEndSimulation; public final boolean endSimulationWhenNoHerbivoresLeft; public final boolean endSimulationWhenNoCarnivoresLeft; public final float collisionRangeMultiplierOfSumOfRadii; public SimulationParameters(int mapWidth, int mapHeight, float speedOfSimulationMultiplier, int startingNumberOfPlants, int startingNumberOfHerbivores, int startingNumberOfCarnivores, float herbivoreSpeed, float carnivoreSpeed, float plantNutritionalValue, float herbivoreStartingEnergy, float carnivoreStartingEnergy, float herbivoreEnergyConsumptionPerSecond, float carnivoreEnergyConsumptionPerSecond, int plantRadius, int herbivoreRadius, int carnivoreRadius, float herbivoreSightRange, float carnivoreSightRange, float baseHerbivoreNutritionalValue, float timeToSetNewRandomHerbivoreWanderDirection, float timeToSetNewRandomCarnivoreWanderDirection, String colourStringOfPlant, String colourStringOfHerbivore, String colourStringOfCarnivore, boolean useGUI, float timeBetweenProgressOutputInTerminal, int numberOfPawnsToEndSimulation, boolean endSimulationWhenNoHerbivoresLeft, boolean endSimulationWhenNoCarnivoresLeft, float collisionRangeMultiplierOfSumOfRadii) { this.mapWidth = mapWidth; this.mapHeight = mapHeight; this.speedOfSimulationMultiplier = speedOfSimulationMultiplier; this.startingNumberOfPlants = startingNumberOfPlants; this.startingNumberOfHerbivores = startingNumberOfHerbivores; this.startingNumberOfCarnivores = startingNumberOfCarnivores; this.herbivoreSpeed = herbivoreSpeed; this.carnivoreSpeed = carnivoreSpeed; this.plantNutritionalValue = plantNutritionalValue; this.herbivoreStartingEnergy = herbivoreStartingEnergy; this.carnivoreStartingEnergy = carnivoreStartingEnergy; this.herbivoreEnergyConsumptionPerSecond = herbivoreEnergyConsumptionPerSecond; this.carnivoreEnergyConsumptionPerSecond = carnivoreEnergyConsumptionPerSecond; this.plantRadius = plantRadius; this.herbivoreRadius = herbivoreRadius; this.carnivoreRadius = carnivoreRadius; this.herbivoreSightRange = herbivoreSightRange; this.carnivoreSightRange = carnivoreSightRange; this.baseHerbivoreNutritionalValue = baseHerbivoreNutritionalValue; this.timeToSetNewRandomHerbivoreWanderDirection = timeToSetNewRandomHerbivoreWanderDirection; this.timeToSetNewRandomCarnivoreWanderDirection = timeToSetNewRandomCarnivoreWanderDirection; this.colourStringOfPlant = colourStringOfPlant; this.colourStringOfHerbivore = colourStringOfHerbivore; this.colourStringOfCarnivore = colourStringOfCarnivore; this.useGUI = useGUI; this.timeBetweenProgressOutputInTerminal = timeBetweenProgressOutputInTerminal; this.numberOfPawnsToEndSimulation = numberOfPawnsToEndSimulation; this.endSimulationWhenNoHerbivoresLeft = endSimulationWhenNoHerbivoresLeft; this.endSimulationWhenNoCarnivoresLeft = endSimulationWhenNoCarnivoresLeft; this.collisionRangeMultiplierOfSumOfRadii = collisionRangeMultiplierOfSumOfRadii; } }
true
48c4890dae4ab63c774084823b69564a70697ae4
Java
folio-org/mod-circulation
/src/main/java/org/folio/circulation/support/http/client/VertxWebClientOkapiHttpClient.java
UTF-8
6,673
2.0625
2
[ "Apache-2.0" ]
permissive
package org.folio.circulation.support.http.client; import static java.time.temporal.ChronoUnit.SECONDS; import static org.folio.circulation.support.results.Result.failed; import static org.folio.circulation.support.results.Result.succeeded; import static org.folio.circulation.support.http.OkapiHeader.OKAPI_URL; import static org.folio.circulation.support.http.OkapiHeader.REQUEST_ID; import static org.folio.circulation.support.http.OkapiHeader.TENANT; import static org.folio.circulation.support.http.OkapiHeader.TOKEN; import static org.folio.circulation.support.http.OkapiHeader.USER_ID; import static org.folio.circulation.support.http.client.Response.responseFrom; import java.net.URL; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; import org.folio.circulation.support.results.Result; import org.folio.circulation.support.ServerErrorFailure; import io.netty.handler.codec.http.HttpHeaderNames; import io.vertx.core.AsyncResult; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.client.HttpRequest; import io.vertx.ext.web.client.HttpResponse; import io.vertx.ext.web.client.WebClient; import io.vertx.core.http.HttpMethod; public class VertxWebClientOkapiHttpClient implements OkapiHttpClient { private static final Duration DEFAULT_TIMEOUT = Duration.of(20, SECONDS); private static final String ACCEPT = HttpHeaderNames.ACCEPT.toString(); private final WebClient webClient; private final URL okapiUrl; private final String tenantId; private final String token; private final String userId; private final String requestId; public static OkapiHttpClient createClientUsing(HttpClient httpClient, URL okapiUrl, String tenantId, String token, String userId, String requestId) { return new VertxWebClientOkapiHttpClient(WebClient.wrap(httpClient), okapiUrl, tenantId, token, userId, requestId); } private VertxWebClientOkapiHttpClient(WebClient webClient, URL okapiUrl, String tenantId, String token, String userId, String requestId) { this.webClient = webClient; this.okapiUrl = okapiUrl; this.tenantId = tenantId; this.token = token; this.userId = userId; this.requestId = requestId; } @Override public CompletableFuture<Result<Response>> post(URL url, JsonObject body) { return post(url.toString(), body, DEFAULT_TIMEOUT); } @Override public CompletableFuture<Result<Response>> post(String url, JsonObject body) { return post(url, body, DEFAULT_TIMEOUT); } @Override public CompletableFuture<Result<Response>> post(String url, JsonObject body, Duration timeout) { final CompletableFuture<AsyncResult<HttpResponse<Buffer>>> futureResponse = new CompletableFuture<>(); final HttpRequest<Buffer> request = withStandardHeaders( webClient.requestAbs(HttpMethod.POST, url)); request .timeout(timeout.toMillis()) .sendJsonObject(body, futureResponse::complete); return futureResponse .thenApply(asyncResult -> mapAsyncResultToResult(url, asyncResult)); } @Override public CompletableFuture<Result<Response>> get(String url, Duration timeout, QueryParameter... queryParameters) { final CompletableFuture<AsyncResult<HttpResponse<Buffer>>> futureResponse = new CompletableFuture<>(); final HttpRequest<Buffer> request = withStandardHeaders( webClient.requestAbs(HttpMethod.GET, url)); Stream.of(queryParameters) .forEach(parameter -> parameter.consume(request::addQueryParam)); request .timeout(timeout.toMillis()) .send(futureResponse::complete); return futureResponse .thenApply(asyncResult -> mapAsyncResultToResult(url, asyncResult)); } @Override public CompletableFuture<Result<Response>> get(URL url, QueryParameter... queryParameters) { return get(url.toString(), queryParameters); } @Override public CompletableFuture<Result<Response>> get(String url, QueryParameter... queryParameters) { return get(url, DEFAULT_TIMEOUT, queryParameters); } @Override public CompletableFuture<Result<Response>> put(URL url, JsonObject body) { return put(url.toString(), body, DEFAULT_TIMEOUT); } @Override public CompletableFuture<Result<Response>> put(String url, JsonObject body) { return put(url, body, DEFAULT_TIMEOUT); } @Override public CompletableFuture<Result<Response>> put(String url, JsonObject body, Duration timeout) { final CompletableFuture<AsyncResult<HttpResponse<Buffer>>> futureResponse = new CompletableFuture<>(); final HttpRequest<Buffer> request = withStandardHeaders( webClient.requestAbs(HttpMethod.PUT, url)); request .timeout(timeout.toMillis()) .sendJsonObject(body, futureResponse::complete); return futureResponse .thenApply(asyncResult -> mapAsyncResultToResult(url, asyncResult)); } @Override public CompletableFuture<Result<Response>> delete(URL url, QueryParameter... queryParameters) { return delete(url.toString(), queryParameters); } @Override public CompletableFuture<Result<Response>> delete(String url, QueryParameter... queryParameters) { return delete(url, DEFAULT_TIMEOUT, queryParameters); } @Override public CompletableFuture<Result<Response>> delete(String url, Duration timeout, QueryParameter... queryParameters) { final CompletableFuture<AsyncResult<HttpResponse<Buffer>>> futureResponse = new CompletableFuture<>(); final HttpRequest<Buffer> request = withStandardHeaders( webClient.requestAbs(HttpMethod.DELETE, url)); Stream.of(queryParameters) .forEach(parameter -> parameter.consume(request::addQueryParam)); request .timeout(timeout.toMillis()) .send(futureResponse::complete); return futureResponse .thenApply(asyncResult -> mapAsyncResultToResult(url, asyncResult)); } private HttpRequest<Buffer> withStandardHeaders(HttpRequest<Buffer> request) { return request .putHeader(ACCEPT, "application/json, text/plain") .putHeader(OKAPI_URL, okapiUrl.toString()) .putHeader(TENANT, this.tenantId) .putHeader(TOKEN, this.token) .putHeader(USER_ID, this.userId) .putHeader(REQUEST_ID, this.requestId); } private static Result<Response> mapAsyncResultToResult(String url, AsyncResult<HttpResponse<Buffer>> asyncResult) { return asyncResult.succeeded() ? succeeded(responseFrom(url, asyncResult.result())) : failed(new ServerErrorFailure(asyncResult.cause())); } }
true
43d87867ed8e33dccb3207e8169ae3c4abb06671
Java
icotting/SETwitter
/Java EE/src/main/java/edu/unl/raikes/se/twitter/service/UserService.java
UTF-8
1,000
2.375
2
[]
no_license
/* * 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 edu.unl.raikes.se.twitter.service; import edu.unl.raikes.se.twitter.entity.UserProfile; /** * * @author iancottingham */ public interface UserService { /* Returns the user profile matching the argument user name */ public UserProfile findUserByName(String userName); /* Returns the user profile for a given ID */ public UserProfile findUserById(long id); /* Persists a new user profile into the backing data store */ public void createUserProfile(UserProfile profile); /* Determines if the provided email address is valid and * unique in the system (i.e. hasn't already been used) */ public boolean isValidEmail(String email); /* Determines if the provided user name is unique in the system */ public boolean isValidUserName(String userName); }
true
9b351372055841d6329eda669cd316039df971b0
Java
z7-x/learning
/jpa/src/main/java/learning/features/lambda/service/impl/NoReturnNoParam.java
UTF-8
259
1.882813
2
[]
no_license
package learning.features.lambda.service.impl; /** * @Classname NoReturnNoParam * @Description TODO * @Date 2020/8/17 9:18 上午 * @Author z7-x */ @FunctionalInterface public interface NoReturnNoParam { /**无参无返回值*/ void method(); }
true
3e81a3d71db6b090a6d4da8ea85053bb3c8b8c38
Java
kevinlowe0x3F7/monopolyjk
/GoToJail.java
UTF-8
822
3.359375
3
[]
no_license
/** Go to jail piece of the Monopoly board. Sets the player's inJail value * to true and sends them to jail. * @author Kevin Lowe */ public class GoToJail implements BoardPiece { /** The name of this piece. */ private final String _name = "Go to Jail"; @Override public boolean effect(Player current) { current.inJail(true); current.jumpPlayer("Jail"); String line = "Player " + current.getID() + " has been sent" + " to jail."; if (current.game().gui() != null) { current.game().gui().panel().status().addLine(line); current.game().nextPlayer(); current.game().gui().panel().buttons().roll().setText("Roll Dice"); } return true; } @Override public String name() { return _name; } }
true
4f43968213758cc51aaf080b57d497046ebd9a7c
Java
HubertYoung/AcFun-Android
/library/component_update/src/main/java/com/hubertyoung/update/AppIncrementalUpdateUtil.java
UTF-8
5,634
2.359375
2
[]
no_license
package com.hubertyoung.update; import android.net.Uri; import android.util.Log; import com.hubertyoung.common.utils.os.AppUtils; import com.hubertyoung.common.utils.ToastUtil; import java.io.File; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; /** * <br> * function:增量更新 * <p> * * @author:HubertYoung * @date:2018/7/30 18:12 * @since:V1.0 * @desc:com.hubertyoung.update */ public class AppIncrementalUpdateUtil { private final String TAG = getClass().getSimpleName(); private static AppIncrementalUpdateUtil mAppUtil; private AppIncrementalUpdateUtil() { } public static AppIncrementalUpdateUtil get() { if ( mAppUtil == null ) { synchronized ( AppIncrementalUpdateUtil.class ) { if ( mAppUtil == null ) { mAppUtil = new AppIncrementalUpdateUtil(); } } } return mAppUtil; } public void incrementalInstall( String oldApk, String newApk, String patch ) { final File newApkFile = new File( newApk ); final File oldApkFile = new File( oldApk ); final File patchFile = new File( patch ); Observable.just( "" )// .map( new Function< String, Boolean >() { @Override public Boolean apply( String s ) throws Exception { //一定要检查补丁文件是否存在 if ( !patchFile.exists() ) { Log.w( TAG, "doBspatch: patch.patch is not exists" ); return false; } if ( !newApkFile.exists() ) { Log.d( TAG, "doBspatch: new.apk is not exists" ); } else { newApkFile.delete(); Log.d( TAG, "doBspatch: new.apk is exists, to del" ); } boolean b = bspatch( oldApkFile.getAbsolutePath(), newApkFile.getAbsolutePath(), patchFile.getAbsolutePath() ); Log.i( TAG, "bspatch: result is " + b ); return b; } } )// .subscribeOn( Schedulers.io() )// .observeOn( AndroidSchedulers.mainThread() )// .subscribe( new Consumer< Boolean >() { @Override public void accept( Boolean aBoolean ) throws Exception { if ( aBoolean ) { if ( newApkFile.exists() ) { install( newApkFile.getAbsolutePath() ); } ToastUtil.showSuccess( "apk生成到" + oldApkFile.getAbsolutePath() ); // mContext.startActivity(new Intent(Intent.ACTION_VIEW).setDataAndType( Uri.fromFile(outApkFile), // "application/vnd.android.package-archive")); } else { ToastUtil.showError( "apk生成失败!你到底放了patch包没有!" ); } } } ); } public void incrementalDiff( String oldApk, String newApk, String patch ) { final File newApkFile = new File( newApk ); final File oldApkFile = new File( oldApk ); final File patchFile = new File( patch ); Observable.just( "" )// .map( new Function< String, Boolean >() { @Override public Boolean apply( String s ) throws Exception { //一定要检查补丁文件是否存在 if ( !patchFile.exists() ) { Log.w( TAG, "doBspatch: patch.patch is not exists" ); } else { patchFile.delete(); Log.d( TAG, "doBspatch: patch.patch is exists, to del" ); } boolean b = diff( oldApkFile.getAbsolutePath(), newApkFile.getAbsolutePath(), patchFile.getAbsolutePath() ); Log.i( TAG, "bspatch: result is " + b ); return b; } } )// .subscribeOn( Schedulers.io() )// .observeOn( AndroidSchedulers.mainThread() )// .subscribe( new Consumer< Boolean >() { @Override public void accept( Boolean aBoolean ) throws Exception { if ( aBoolean ) { if ( patchFile.exists() ) { ToastUtil.showSuccess( "patch生成到" + patchFile.getAbsolutePath() ); // mContext.startActivity( new Intent( Intent.ACTION_VIEW ).setDataAndType( Uri.fromFile( patchFile ), "application/vnd.android.package-archive" ) ); } else { ToastUtil.showError( "apk生成失败" ); } } else { ToastUtil.showError( "apk生成失败" ); } } }, new Consumer< Throwable >() { @Override public void accept( Throwable throwable ) throws Exception { Log.e( "TAG", "" ); } } ); } /** * app安装 * * @param apkPath */ private void install( String apkPath ) { // Intent i = new Intent(Intent.ACTION_VIEW); // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // i.setDataAndType( Uri.fromFile(new File(apkPath)), // "application/vnd.android.package-archive"); // mContext.startActivity(i); AppUtils.installApp( apkPath, "com.hubertyoung.litemallupdate.fileprovider" ); } // /** // * 获取当前程序的版本名 // */ // public String getVersion() { // try { // //获取packagemanager的实例 // PackageManager packageManager = mContext.getPackageManager(); // //getPackageName()是你当前类的包名,0代表是获取版本信息 // PackageInfo packInfo = packageManager.getPackageInfo( mContext.getPackageName(), 0 ); // return packInfo.versionName; // } catch ( Exception e ) { // e.printStackTrace(); // } // return ""; // } /** * 增量更新:Jni库加载 * (module的build.gradle配置ndk {moduleName = 'bsdiff'}) */ static { System.loadLibrary( "update-lib" ); } /** * 增量更新:合并旧apk和补丁 * * @param oldApk * @param newApk * @param patch * @return */ public synchronized static native boolean bspatch( String oldApk, String newApk, String patch ); public synchronized static native boolean diff( String oldApk, String newApk, String patch ); }
true
c0a73c5c869c93d4e46f57007a9e969361bba19c
Java
kiborg007/mapster
/src/main/java/ch/ua/model/Coordinates.java
UTF-8
1,823
2.140625
2
[]
no_license
package ch.ua.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonProperty; @Entity @Table(name="COORDINATES") @XmlRootElement(name = "coordinates") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Coordinates { @Id @Column(name="COORD_ID") @GeneratedValue(strategy=GenerationType.IDENTITY) private int coordID ; private String latitude ; private String longitude ; private Person person ; @JsonProperty @XmlElement public int getCoordID() { return coordID; } public void setCoordID(int coordID) { this.coordID = coordID; } @JsonProperty @XmlElement public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } @JsonProperty @XmlElement public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } @XmlElement //@JsonBackReference //@JsonManagedReference @JsonProperty public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } @Override public String toString() { return "Coordinates [coordID=" + coordID + ", latitude=" + latitude + ", longitude=" + longitude + "]"; } }
true
b91b13304773d81f87783686405f133fcd2de95c
Java
parkjaewon1/JavaClass
/JavaClass/src/ch14/Color1.java
UTF-8
530
3.1875
3
[]
no_license
package ch14; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Color1 extends Frame { public Color1() { int r = (int)(Math.random()*256); int g = (int)(Math.random()*256); int b = (int)(Math.random()*256); setBackground(new Color(r, g, b)); setSize(200, 300); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new Color1(); } }
true
0093b0986297f92800564b2f32de2755bf67bbdb
Java
bronwen-cassidy/talent-evolution
/talent-studio-views/src/main/java/com/zynap/talentstudio/web/analysis/reports/AppraisalReportMultiController.java
UTF-8
3,588
2.046875
2
[]
no_license
/* * Copyright (c) Zynap Ltd. 2006 * All rights reserved. */ package com.zynap.talentstudio.web.analysis.reports; import com.zynap.talentstudio.analysis.reports.AppraisalSummaryReport; import com.zynap.talentstudio.web.utils.controller.ZynapMultiActionController; import com.zynap.talentstudio.web.utils.RequestUtils; import com.zynap.talentstudio.web.utils.mvc.ZynapRedirectView; import com.zynap.talentstudio.web.common.ControllerConstants; import com.zynap.talentstudio.web.common.ParameterConstants; import com.zynap.talentstudio.analysis.reports.IReportService; import com.zynap.talentstudio.analysis.reports.Report; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.Map; import java.util.HashMap; /** * Class or Interface description. * * @author bcassidy * @version 0.1 * @since 21-Sep-2009 15:02:35 */ public class AppraisalReportMultiController extends ZynapMultiActionController { public ModelAndView listAppraisalReports(HttpServletRequest request, HttpServletResponse response) throws Exception { final List<Report> reports = reportService.findAll(Report.APPRAISAL_REPORT); Map myModel = new HashMap(); myModel.put("reports", reports); return new ModelAndView("listappraisalreports", ControllerConstants.MODEL_NAME, myModel); } public ModelAndView viewAppraisalReport(HttpServletRequest request, HttpServletResponse response) throws Exception { final Long reportId = RequestUtils.getRequiredLongParameter(request, ParameterConstants.REPORT_ID); Report report = (Report) reportService.findById(reportId); Map model = new HashMap(); model.put("report", report); return new ModelAndView("viewappraisalreport", ControllerConstants.MODEL_NAME, model); } public ModelAndView deleteAppraisalReport(HttpServletRequest request, HttpServletResponse response) throws Exception { final Long reportId = RequestUtils.getRequiredLongParameter(request, ParameterConstants.REPORT_ID); Report report = (Report) reportService.findById(reportId); reportService.delete(report); return new ModelAndView(new ZynapRedirectView("listappraisalreports.htm")); } public ModelAndView publishAppraisalReport(HttpServletRequest request, HttpServletResponse response) throws Exception { return executeStatus(request, AppraisalSummaryReport.STATUS_PUBLISHED); } public ModelAndView archiveAppraisalReport(HttpServletRequest request, HttpServletResponse response) throws Exception { return executeStatus(request, AppraisalSummaryReport.STATUS_ARCHIVED); } public ModelAndView reopenAppraisalReport(HttpServletRequest request, HttpServletResponse response) throws Exception { return executeStatus(request, AppraisalSummaryReport.STATUS_NEW); } private ModelAndView executeStatus(HttpServletRequest request, String status) throws Exception { final Long reportId = RequestUtils.getRequiredLongParameter(request, ParameterConstants.REPORT_ID); AppraisalSummaryReport report = (AppraisalSummaryReport) reportService.findById(reportId); report.setStatus(status); reportService.update(report); return new ModelAndView(new ZynapRedirectView("listappraisalreports.htm")); } public void setReportService(IReportService reportService) { this.reportService = reportService; } private IReportService reportService; }
true
9c5304b2325e2947125097cd8b2bf985620d9e3b
Java
HongZeBin98/BeanMusic
/app/src/main/java/com/example/hongzebin/beanmusic/main/view/activity/MainActivity.java
UTF-8
5,378
1.664063
2
[ "Apache-2.0" ]
permissive
package com.example.hongzebin.beanmusic.main.view.activity; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.RadioGroup; import com.example.hongzebin.beanmusic.R; import com.example.hongzebin.beanmusic.base.bean.Song; import com.example.hongzebin.beanmusic.base.view.BaseEventBusActivity; import com.example.hongzebin.beanmusic.base.bean.PlayerCondition; import com.example.hongzebin.beanmusic.music.MusicManager; import com.example.hongzebin.beanmusic.music.view.BottomPlayerFragment; import com.example.hongzebin.beanmusic.main.adapter.ViewPagerAdapter; import com.example.hongzebin.beanmusic.locality.view.LocalityMVPFragment; import com.example.hongzebin.beanmusic.main.view.fragment.MusicFragment; import com.example.hongzebin.beanmusic.search.view.activity.SearchActivity; import com.example.hongzebin.beanmusic.util.DimensionUtil; import com.example.hongzebin.beanmusic.util.Permission; import java.util.ArrayList; import java.util.List; public class MainActivity extends BaseEventBusActivity implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, View.OnClickListener { private List<Fragment> mFragments; private ViewPager mViewPager; private RadioGroup mRadioGroup; private RadioButton mRbMusic; private RadioButton mRbLocality; private ImageButton mImageButton; private BottomPlayerFragment mFgBottomPlayer; private FrameLayout mFrameLayout; @Override protected void initView() { //动态获取权限 Permission.requestAllPower(this); setContentView(R.layout.activity_main); mFragments = new ArrayList<>(); mFgBottomPlayer = new BottomPlayerFragment(); mViewPager = findViewById(R.id.main_viewpager); mRadioGroup = findViewById(R.id.main_top_RG); mRbMusic = findViewById(R.id.main_top_music); mRbLocality = findViewById(R.id.main_top_locality); mImageButton = findViewById(R.id.main_top_search); mFrameLayout = findViewById(R.id.main_bottom_player); isBottomPlayerShow(); } @Override protected void initData() { mFragments.add(new MusicFragment()); mFragments.add(new LocalityMVPFragment()); } @Override protected void initEvents() { //动态添加底部播放栏Fragment getSupportFragmentManager().beginTransaction().replace(R.id.main_bottom_player, mFgBottomPlayer).commit(); mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), mFragments)); mViewPager.addOnPageChangeListener(this); mRadioGroup.setOnCheckedChangeListener(this); mImageButton.setOnClickListener(this); mFgBottomPlayer.setBottomPlayerHideCallback(new BottomPlayerFragment.BottomPlayerHideCallback() { @Override public void onFinish() { isBottomPlayerShow(); } }); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position == 0) { mRbMusic.setChecked(true); } else if (position == 1) { mRbLocality.setChecked(true); } } @Override public void onPageScrollStateChanged(int state) { } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == mRbMusic.getId()) { mViewPager.setCurrentItem(0); } else if (checkedId == mRbLocality.getId()) { mViewPager.setCurrentItem(1); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.main_top_search: SearchActivity.startActivity(this); break; default: break; } } @Override protected void setConditionStickEvent(PlayerCondition event) { mFgBottomPlayer.setCondition(event); isBottomPlayerShow(); } @Override protected PlayerCondition getConditionStickEvent() { return mFgBottomPlayer.getPlayerCondition(); } /** * 把本地歌曲歌单传入底部播放栏 * * @param songList 本地歌曲歌单 */ public void getLocalitySongList(List<Song> songList, int position) { mFgBottomPlayer.setSongList(songList, position); isBottomPlayerShow(); } /** * 底部播放栏显示和隐藏 */ private void isBottomPlayerShow() { ViewGroup.LayoutParams lp = mFrameLayout.getLayoutParams(); lp.width = ViewGroup.LayoutParams.MATCH_PARENT; if (mFgBottomPlayer.getSongListSize() != 0) { lp.height = DimensionUtil.dip2px(50); } else { lp.height = 0; } mFrameLayout.setLayoutParams(lp); } @Override protected void onDestroy() { super.onDestroy(); // MusicManager.getInstance().unBindService(); } }
true
0a21f6995f1b3091ffe46e6a2ca6d5a0e0b65433
Java
poshjosh/newsminute
/common/src/main/java/com/looseboxes/idisc/common/notice/PromptWifiOnly.java
UTF-8
822
2.046875
2
[]
no_license
package com.looseboxes.idisc.common.notice; import android.content.DialogInterface; import android.support.annotation.StringRes; import com.looseboxes.idisc.common.util.Pref; /** * Created by Josh on 10/25/2016. */ public class PromptWifiOnly extends AbstractDialogManager { public PromptWifiOnly(@StringRes int dialogTitle, @StringRes int dialogText) { super(dialogTitle, dialogText); } public PromptWifiOnly(@StringRes int dialogTitle, @StringRes int dialogText, float displayFrequency, int launchAttemptsTillPrompt, int daysUntilPrompt) { super(dialogTitle, dialogText, displayFrequency, launchAttemptsTillPrompt, daysUntilPrompt); } @Override public void onOkButtonClicked(DialogInterface dialog, int which) { Pref.setWifiOnly(this.getContext(), true); } }
true
7ce7fe578e00f87b06360b82315d45d770193998
Java
franklinmarcano1970/fermat
/TKY/library/api/fermat-tky-api/src/main/java/com/bitdubai/fermat_tky_api/all_definitions/enums/ArtistAcceptConnectionsType.java
UTF-8
2,338
2.75
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
package com.bitdubai.fermat_tky_api.all_definitions.enums; import com.bitdubai.fermat_api.layer.all_definition.enums.interfaces.FermatEnum; import com.bitdubai.fermat_api.layer.all_definition.exceptions.InvalidParameterException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by Manuel Perez (darkpriestrelative@gmail.com) on 09/03/16. */ public enum ArtistAcceptConnectionsType implements FermatEnum, Serializable { /** * Please for doing the code more readable, keep the elements of the enum ordered. */ AUTOMATIC("AUT"), MANUAL("MAN"), NO_CONNECTIONS("NOC"); String code; ArtistAcceptConnectionsType(String code){ this.code=code; } public static final ArtistAcceptConnectionsType DEFAULT_ARTIST_ACCEPT_CONNECTION_TYPE = ArtistAcceptConnectionsType.AUTOMATIC; //PUBLIC METHODS public static ArtistAcceptConnectionsType getByCode(String code) throws InvalidParameterException { for (ArtistAcceptConnectionsType value : values()) { if (value.getCode().equals(code)) return value; } throw new InvalidParameterException( InvalidParameterException.DEFAULT_MESSAGE, null, "Code Received: " + code, "This Code Is Not Valid for the ArtistAcceptConnectionsType enum."); } @Override public String toString() { return "ArtistAcceptConnectionsType{" + "code='" + code + '\'' + '}'; } //GETTER AND SETTERS @Override public String getCode() { return code; } public static List<String> getArrayItems(){ List<String> platformsNames = new ArrayList<String>(); ArtistAcceptConnectionsType[] externalPlatforms = values(); for (ArtistAcceptConnectionsType externalPlatform : externalPlatforms) { platformsNames.add(externalPlatform.name()); } return platformsNames; } public static ArtistAcceptConnectionsType getArtistAcceptConnectionsTypeByLabel(String label){ for (ArtistAcceptConnectionsType artistAcceptConnectionsType : values()) { if(artistAcceptConnectionsType.name().equals(label.toUpperCase())) return artistAcceptConnectionsType; } return null; } }
true
62b37053a95a18278c7b52cad2c61f873a86036d
Java
Arquisoft/Loader_i2a
/src/test/java/main/asw/parser/ParserTest.java
UTF-8
2,955
2.421875
2
[ "Unlicense" ]
permissive
package main.asw.parser; import main.asw.user.User; import org.junit.Test; import java.io.IOException; import java.text.ParseException; import static junit.framework.TestCase.assertEquals; /** * Created by nicolas on 15/02/17. */ public class ParserTest { private final static String BASE_PATH = "src/test/resources/"; private final static String TEST_OK_FILE_NAME = "pruebaUsuarios.xls"; private final static String TEST_WRONG_AGENT_TYPE = "pruebaUsuarios2.xls"; private final static String TEST_NO_FOUND_FILE = "noExiste"; private static final String TEST_LESS_LINES = "lessLines.xls"; private static final String TEST_MORE_LINES = "moreLines.xls"; private static final String TEST_WITH_ERRORS = "test-errors.xls"; private final static String TEST_CSV_AGENTS = "agentTypes.csv"; private ParserImpl parser; @Test public void testAllOKFile() throws IOException, ParseException { try { parser = ParserFactory.getParser(BASE_PATH + TEST_OK_FILE_NAME, BASE_PATH + TEST_CSV_AGENTS); } catch (IOException e) { e.printStackTrace(); } String baseName = "Prueba"; String baseEmail = "prueba"; int kind = 1; parser.readList(); assertEquals(20, parser.getUsers().size()); for (int i = 0; i < parser.getUsers().size(); i++) { String index = (i + 1 < 10) ? "0" + (i + 1) : (i + 1) + ""; User user = parser.getUsers().get(i); assertEquals(baseName + index, user.getName()); assertEquals(baseEmail + index + "@prueba.es", user.getEmail()); assertEquals(kind, user.getKind()); } } @Test(expected = IllegalArgumentException.class) public void testWrongTypes() throws IOException, ParseException { try { parser = ParserFactory.getParser(BASE_PATH + TEST_WRONG_AGENT_TYPE, BASE_PATH + TEST_CSV_AGENTS); } catch (IOException e) { e.printStackTrace(); } parser.readList(); } @Test(expected = IOException.class) public void testNoFoundFile() throws IOException { parser = ParserFactory.getParser(BASE_PATH + TEST_NO_FOUND_FILE, BASE_PATH + TEST_CSV_AGENTS); } @Test public void testMoreLines() throws IOException, ParseException { parser = ParserFactory.getParser(BASE_PATH + TEST_MORE_LINES, BASE_PATH + TEST_CSV_AGENTS); parser.readList(); assertEquals(0, parser.getUsers().size()); } @Test public void testLessLines() throws IOException, ParseException { parser = ParserFactory.getParser(BASE_PATH + TEST_LESS_LINES, BASE_PATH + TEST_CSV_AGENTS); parser.readList(); assertEquals(0, parser.getUsers().size()); } @Test(expected = NumberFormatException.class) public void testWithParseErrors() throws IOException, ParseException { parser = ParserFactory.getParser(BASE_PATH + TEST_WITH_ERRORS, BASE_PATH + TEST_CSV_AGENTS); parser.readList(); } @Test public void testCSVNotFound() throws IOException, ParseException { parser = ParserFactory.getParser(BASE_PATH + TEST_OK_FILE_NAME, BASE_PATH + TEST_NO_FOUND_FILE); } }
true
d3a948cb3a829eb4def7afa34ea492803bfdfbfd
Java
simplay/JTetris
/src/models/tiles/RevSquigeling.java
UTF-8
369
2.8125
3
[]
no_license
package models.tiles; public class RevSquigeling extends Tile{ public RevSquigeling() { super(5); } @Override public void initShape(){ this.shape.setXAt(0, 7); this.shape.setXAt(1, 8); this.shape.setXAt(2, 6); this.shape.setXAt(3, 7); this.shape.setYAt(0, 0); this.shape.setYAt(1, 1); this.shape.setYAt(2, 0); this.shape.setYAt(3, 1); } }
true
d7d635356af84d18a91400944b9ffcd70cae11c0
Java
agrobost/CocoPanda
/app/src/main/java/agrumlab/cocopanda/scene/game/game_objects/Panda.java
UTF-8
3,307
2.53125
3
[]
no_license
package agrumlab.cocopanda.scene.game.game_objects; import android.graphics.Bitmap; import android.graphics.Canvas; import android.view.MotionEvent; import java.util.Iterator; import agrumlab.cocopanda.ressources.CanvasManager; import agrumlab.cocopanda.ressources.EnumBitmaps; import agrumlab.cocopanda.ressources.PreferenceMemory; import agrumlab.cocopanda.ressources.Screen; import agrumlab.cocopanda.scene.GameObject; import agrumlab.cocopanda.scene.Scene; /** * Created by Alexandre on 30/01/2015. */ public class Panda extends GameObject { //un peu rajouter une animation(par ex pour simuler un leger mouvemen), mais modifier collision et draw public Panda(Scene scene) { super(scene); super.bitmap = EnumBitmaps.OBJECT_PANDA.geBitmap(); float x, y; x = Screen.width - bitmap.getWidth() / 2; y = Screen.height * 1531 / 1920 - bitmap.getHeight(); super.coord = new float[]{x, y}; this.sensitivity = PreferenceMemory.getSensitivity(); } @Override public void draw(Canvas canvas) { canvas.drawBitmap(bitmap, super.getCoordOnScreen()[0], super.getCoordOnScreen()[1], CanvasManager.getPaint(CanvasManager.IMAGE_HD)); } @Override public void animation(Iterator iterator) { //inutile car l'update se fais par le biais du touchevent } public Bitmap getBitmap() { return bitmap; } @Override protected void inCollision(GameObject gameObject, Iterator iterator) { //inutile } //*****************controller event to move panda********************// private float xDown = 0f, xMove = 0f, distanceDowntoMove = 0f; private float[] pandaInitial = {0f, 0f}; private float sensitivity = (float) 1.7; public void actionDown(MotionEvent event) { if (event.getPointerCount() == 1 && event.getPointerId(0) == 0 && scene.getSurface().getLevel().isRunning()) { xDown = event.getX(); pandaInitial = getCoord(); } } public void actionMove(MotionEvent event) { if (event.getPointerCount() == 1 && event.getPointerId(0) == 0 && scene.getSurface().getLevel().isRunning()) { xMove = event.getX(); //pour width screen distanceDowntoMove = xMove - xDown; //pour les ecran dont la largeur nest pas 1080 => produit en crois pour conversion //* ScreenManager.dimScreen[0] / ActivityMain.size.x; if (pandaInitial[0] + distanceDowntoMove * sensitivity > Screen.width /2-getBitmap().getWidth()/2 && pandaInitial[0] + distanceDowntoMove * sensitivity < (3* Screen.width /2)-getBitmap().getWidth()/2) { setCoord(new float[]{pandaInitial[0] + distanceDowntoMove * sensitivity, pandaInitial[1]}); scene.getSurface().getLevel().getCamera().setCoordCamera(new float[]{Screen.width / 2 - Screen.width + getCoord()[0], scene.getSurface().getLevel().getCamera().getCoordCamera()[1]}); }else{ xDown = event.getX(); pandaInitial = getCoord(); } }else{ xDown = event.getX(); pandaInitial = getCoord(); } } public void setSensitivity(float sensitivity) { this.sensitivity = sensitivity; } }
true
515f35ba6c577efec8a2595ec1713bbd1643e680
Java
kimdia200/KH_classTime
/spring_workspace/jdk-api/src/com/kh/jdk8/stream/StreamStudy.java
UTF-8
8,019
3.65625
4
[]
no_license
package com.kh.jdk8.stream; import java.util.ArrayList; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.Stream; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; public class StreamStudy { public static void main(String[] args) { StreamStudy study = new StreamStudy(); // study.test1(); // study.test2(); // study.test3(); // study.test4(); // study.test5(); // study.test6(); // study.test7(); // study.test8(); study.test9(); } /** * reduce * 스트림의 요소로 연산처리후 하나의 결과값을 리턴 * * BinaryOperator : 매개변수와 리턴값의 자료형이 같은 Function * */ public void test9() { int result = Arrays .asList(1,2,3,4,5,6,7,8,9,10) .stream() .reduce(0, (sum, n)->{ System.out.println("sum = " + sum + ", n = "+n); return sum + n; //리턴값은 매개인자 첫번째 값으로 전달됨 // (0, (sum,n) -----> 초기값 0, 리턴값 sum에 지속저장, n = 새로운 파라미터 }); System.out.println("result = " + result); result = Arrays .asList(1,2,30,4,15,67,7,8,9,10) .stream() .reduce(0, (max, n) -> max > n ? max : n); System.out.println("max = " + result); List<Person> list= Arrays.asList( new Person("홍길동", 35), new Person("신사임당", 40), new Person("세종", 45), new Person("홍난파", 80), new Person("전달력", 69) ); Person maxAgePerson = list.stream() .reduce((p1, p2) -> p1.age > p2.age ? p1 : p2) // Optional<Person> .get(); System.out.println(maxAgePerson); Person person=list.stream() .reduce(new Person(), (identity, p)->{ identity.age += p.age; identity.name += p.name; return identity; }); System.out.println(person); } @Data @NoArgsConstructor @AllArgsConstructor static class Person{ private String name; private int age; } /** * 구구단도 가능 */ public void test8() { IntStream .range(2, 10) .forEach(dan->{ IntStream .range(1, 10) .forEach(n-> System.out.println(dan+" * "+n+" = " + (dan*n))); }); } /** * 기본형 stream * - IntStream * - LongStream * - DoubleStream */ public void test7() { int[] arr = {1,2,3}; IntStream intStream = Arrays.stream(arr); DoubleStream doubleStream = DoubleStream.of(1.1,2.3,4.56); doubleStream.forEach(System.out::println); //range | rangeClosed IntStream .range(0, 10) .forEach(System.out::print); System.out.println(); IntStream .rangeClosed(1, 10) .forEach(System.out::print); System.out.println(); int sum = IntStream.rangeClosed(1, 10).sum(); System.out.println("1~10까지 총합 : " + sum); double avg = IntStream.rangeClosed(1, 100).average().getAsDouble(); System.out.println("1~10까지 평균 : " + avg); IntSummaryStatistics summary = IntStream .of(32, 50, 80, 77, 100, 27, 88) .summaryStatistics(); System.out.println(summary); System.out.println(summary.getAverage()); } /** * anyMatch() * * noneMatch() */ public void test6() { //하나라도 true이면 true Boolean bool = Arrays .asList("1", "b2", "c", "d4", "5") .stream() .anyMatch(s->s.startsWith("a")); System.out.println(bool); bool = Arrays .asList("홍길동", "1", "가나다") .stream() .noneMatch(s->Pattern.matches("[0-9]", s)); System.out.println(bool); } /** * collect */ private void test5() { List<Integer> list = Arrays.asList(1,2,3,4,5,4,3,2,1); List<Double> result = list.stream() .map(n->Math.pow(n,2)) .collect(Collectors.toList()); System.out.println(result); Set<Integer> result2 = list.stream() .filter(n->n%2==0) .collect(Collectors.toSet()); System.out.println(result2); Map<Integer, String> result3 = list.stream() .distinct()//stream 에서 collect로 map을생성할때 중복키는 덮어씌어지는게 아니라 에러남 .collect(Collectors.toMap(n->n, n->n+""+n+""+n)); System.out.println(result3); } /** * stream의 처리과정 * 1. collection, array로부터 stream생성 * 2. 중간연산, Intermediate Operations : peek, filter, map.... (요소에 대한 중간작업을 하는것들) * 3. 단말연산, Terminal Operations : forEach, collect * !!!!중간연산, 단말연산 쉽게 구분하는법 : Stream을 리턴을 하는가 하지 않는가 * * 최종단말연산 전까지는 중간연산을 완료하지 않는 특징이있다. * * peek */ private void test4() { Arrays .asList(1,2,3,4,5,6,7,8,9,10) .stream() .peek(n->System.out.println("peek : " + n)) .filter(n->n%2==0) .peek(n->System.out.println("peek : " + n)) .filter(n->n%4==0) .forEach(System.out::println); // p1 p2 p2 p3 p4 p4 4 p5 p6 p6 p7 p8 p8 8 p9 p10 p10 } /** * map * a -> b * * stream은 기본적으로 읽기전용을 생성한다. */ private void test3() { List<Integer> list = Arrays.asList(1,2,3,4,5); list .stream() .map(n-> n*10) .forEach(System.out::println); List<Integer> another =list.stream() .map(n->n*10) .collect(Collectors.toList()); //collect(Collector<T>)인데 Collectors.toList()로 정의된걸 가져다 쓴것 System.out.println("list = " + list); System.out.println("another = "+another); //원본값은 변하지 않은걸 확인 할 수 있다. Stream .of("홍길동", "신사임당", "세종") //String에 대한 stream .map(String::length) //Integer에 대한 Map형식 Stream .forEach(System.out::println); //@실습문제 요소의 공백을 모두 제거하고 List<String>으로 변환 String[] wordArr = {"a b c d", "홍 길동", "hello world"}; List<String> wordList = Arrays.stream(wordArr).map(str->str.replaceAll("[ ]", "")).collect(Collectors.toList()); System.out.println("wordList"+wordList); } /** * distinct * filter(predicate <T>) predicate는 파라미터T를 사용해서 boolean값을 리턴함 */ private void test2() { List<Integer> list = Arrays.asList(5,1,2,3,2,4,3,2,1,2,4,5); Stream<Integer> stream = list.stream(); stream .distinct()//중복제거 .filter(n->n%2!=0) .sorted()//정렬 .forEach(System.out::println); //@실습문제 강씨 성을 가진 사람만 남겨보세요 String[] names = {"강감찬", "강원래", "홍길동", "강형욱"}; Stream<String> nameStream = Arrays.stream(names); nameStream .sorted() .filter(n->n.charAt(0)=='강') .forEach(System.out::println); } /** * stream * 배열이나 컬렉션을 일관되게 제어하려는 추상화 객체 */ private void test1() { int[] arr = {3,1,4,5,2}; //IntStream = int(기본형다루는 스트림) //Arrays.stream()은 배열을 스트림으로 변경해줌 IntStream arrStream = Arrays.stream(arr); //void forEach(IntConsumer action); arrStream .sorted()//정렬 //.forEach(n->System.out.println(n)); .forEach(System.out::println); List<String> list = new ArrayList<>(); list.add("홍현희"); list.add("홍난파"); list.add("홍진호"); list.add("홍진경"); list.add("홍진호"); //Stream<T> 는 T참조형에 대한 스트림 //컬렉션-stream을 메서드를 사용하면 스트림으로 변경해준다. Stream<String> stringStream = list.stream(); //void forEach(Consumer<? super T> action); stringStream .sorted() .forEach(System.out::println); // public static<T> Stream<T> of(T... values) Stream<Double> doubleStream = Stream.of(0.1, 1.2, 3.456); } }
true
cf9d2135dea2a0f05aef6f4d955cc2329e98aca0
Java
tianyakun/abitty
/src/main/java/com/abitty/controller/ViewController.java
UTF-8
1,407
2.21875
2
[]
no_license
package com.abitty.controller; import com.abitty.entity.TblUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * Created by kkk on 17/6/11. */ @Controller public class ViewController { private final static Logger logger = LoggerFactory.getLogger(ViewController.class); // @RequestMapping("/loginIndex") // public String loginIndex(Model model, final HttpServletRequest request) { // // String requestUri = request.getRequestURI(); // logger.info("登录请求 requestUri={}", requestUri); // // model.addAttribute("uid", ""); // return "loginIndex"; // } @RequestMapping("/view/**") public String view(Model model, HttpSession httpSession, final HttpServletRequest request) { String requestUri = request.getRequestURI(); //请求完整路径,可用于登陆后跳转 logger.info("视图请求 requestUri={}", requestUri); TblUser tblUser = (TblUser) httpSession.getAttribute("user"); if (tblUser != null) { model.addAttribute("uid", tblUser.getUid()); } else { model.addAttribute("uid", ""); } return "view"; } }
true
132a9d3308feab561fa2abafb1ac0fcc3d2e312f
Java
sunmaolin/springSecurityStudy
/src/main/java/com/qm/security/controller/IndexController.java
UTF-8
1,862
2.4375
2
[]
no_license
package com.qm.security.controller; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreFilter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class IndexController { @GetMapping("/index") public String index() { return "hello security"; } @PostMapping("/user/login") public String login(String username,String password) { return username + password; } @GetMapping("/admin") public String test() { return "admin"; } @GetMapping("/update") /** * 注解 角色校验,拥有该角色用户才可访问(只能写角色) * 需要开启注解 * @EnableGlobalMethodSecurity(securedEnabled = true) */ //@Secured({"ROLE_boss"}) /** * 注解 权限校验 可以写权限,也可以写角色。 进入方法之前校验 * hasAuthority("admins") * hasAnyAuthority("admins","manager") * hasRole("sale") * hasAnyRole("sale", "boss") * 需要开启注解 * @EnableGlobalMethodSecurity(prePostEnabled = true) */ //@PreAuthorize("hasAnyAuthority('admins')") /** * 与上一个相似,区别在 方法之后进行校验 */ @PostAuthorize("hasAnyAuthority('admins')") // 对传入,返回的数据过滤,不常用 //@PreFilter() //@PostFilter() public String update() { return "hello update"; } }
true
7757947f2e89ff083598dc97f7c7d80e8b680c62
Java
romafilyutitch/web
/src/main/java/by/epam/jwd/web/model/Subscription.java
UTF-8
2,715
3.046875
3
[]
no_license
package by.epam.jwd.web.model; import java.time.LocalDate; import java.util.Objects; /** * Entity represents user's subscription. * @author roma0 * @version 1.0 * @since 1.0 */ public class Subscription implements DbEntity { private final Long id; private final LocalDate startDate; private final LocalDate endDate; /** * Constructor with id generated by database. * Used when it's need to map database table data to instance. * @param id subscription id generated by database. * @param startDate subscription start date. * @param endDate subscription end date. */ public Subscription(Long id, LocalDate startDate, LocalDate endDate) { this.id = id; this.startDate = startDate; this.endDate = endDate; } /** * Constructor without id generated by database. * Used when it's need to save and register subscription in database table. * @param startDate subscription start date. * @param endDate subscription end date. */ public Subscription(LocalDate startDate, LocalDate endDate) { this(null, startDate, endDate); } /** * Returns saved subscription id generated by database. * @return saves subscription id generated by database. */ @Override public Long getId() { return id; } /** * Returns subscription start date. * @return subscription start date. */ public LocalDate getStartDate() { return startDate; } /** * Returns subscription end date. * @return subscription end date. */ public LocalDate getEndDate() { return endDate; } /** * Checks weather two object are equal to each other. * @param o other object. * @return {@code true} if objects are equal or {@code false} otherwise. */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Subscription that = (Subscription) o; return Objects.equals(id, that.id) && Objects.equals(startDate, that.startDate) && Objects.equals(endDate, that.endDate); } /** * Calculates instance hash code. * @return instnace hash code. */ @Override public int hashCode() { return Objects.hash(id, startDate, endDate); } /** * Makes instance string representation. * @return instance string representation. */ @Override public String toString() { return "Subscription{" + "id=" + id + ", startDate=" + startDate + ", endDate=" + endDate + '}'; } }
true
2da170d2b2740917e85923faf924c3fb7eb530a5
Java
Lulb8/AndAction
/src/PostProdBuildingWindow.java
UTF-8
4,684
2.828125
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class PostProdBuildingWindow extends JInternalFrame { protected JInternalFrame internalFrame; private JTextField jTextField = new JTextField(); private JPanel container = new JPanel(); private JButton button; private static int x = 320; private static int y = 100; /** * Constructeur */ public void PostProdBuildingWindow(Movie currentMovie) { if (currentMovie!=null) { internalFrame = new JInternalFrame(); this.setTitle("Bureau de la post-production"); this.setSize(1200, 800); this.setResizable(false); //Interdit la redimensionnement de la fenêtre this.setClosable(true); this.setLocation(x, y); //container.setBackground(Color.white); container.setLayout(new BorderLayout()); Font police = new Font("Arial", Font.BOLD, 14); Font policeTitle = new Font("Arial", Font.BOLD, 22); //Titre du film JPanel panelTitle = new JPanel(); panelTitle.setBackground(Color.WHITE); Dimension panelTitleSize = new Dimension(500, 200); panelTitle.setPreferredSize(panelTitleSize); JLabel labelTitle = new JLabel("Le titre de votre film : "+ currentMovie.getName()); //recuperer le titre du film en cours labelTitle.setFont(policeTitle); panelTitle.add(labelTitle); container.add(panelTitle, BorderLayout.NORTH); //Panel de gauche JPanel panelAd = new JPanel(); Box boxAd = Box.createVerticalBox(); panelAd.setBackground(Color.WHITE); //Choix du budget pub Dimension panelAdSize = new Dimension(500, 200); panelAd.setPreferredSize(panelAdSize); JLabel labelAd = new JLabel("Le budget pub de votre film : "); labelAd.setFont(police); jTextField.setFont(police); jTextField.setPreferredSize(new Dimension(150, 30)); jTextField.setForeground(Color.BLUE); boxAd.add(labelAd); boxAd.add(jTextField); panelAd.add(boxAd); container.add(panelAd, BorderLayout.WEST); //Panel de droite JPanel panelFeature = new JPanel(); Box boxFeature = Box.createVerticalBox(); panelFeature.setBackground(Color.WHITE); //Resumé des caractéristiques du film en cours JLabel labelFeature = new JLabel("Les caractéristiques de votre film : "); labelFeature.setFont(police); boxFeature.add(labelFeature); panelFeature.add(boxFeature); container.add(panelFeature, BorderLayout.EAST); //le genre JLabel labelG = new JLabel("<html> <br>Le genre de votre film : "+currentMovie.getGenre() +"<br>Le scénariste de votre film : "+currentMovie.scriptwriter.getName()+"</html>"); labelG.setFont(police); boxFeature.add(labelG); panelFeature.add(boxFeature); //Logo du building JPanel panelLogo = new JPanel(); panelLogo.setBackground(Color.WHITE); JLabel logo = new JLabel(new ImageIcon("PostProdBuilding.png")); panelLogo.add(logo); container.add(panelLogo, BorderLayout.CENTER); //Bouton pour valider JPanel panelButton = new JPanel(); panelButton.setBackground(Color.WHITE); panelButton.setSize(200, 100); JButton button = new JButton("Sortir le film !"); button.addActionListener(new ButtonListener()); Dimension buttonSize = new Dimension(500, 100); button.setPreferredSize(buttonSize); button.setFont(policeTitle); panelButton.add(button); container.add(panelButton, BorderLayout.SOUTH); button.addActionListener(new ButtonListener()); this.setContentPane(container); this.setVisible(true); } } class ItemState implements ItemListener { public void itemStateChanged(ItemEvent e) { System.out.println("ComboBox événement sur : " + e.getItem()); } } class ItemAction implements ActionListener { JComboBox combo; public ItemAction(JComboBox comboBox) { this.combo = comboBox; } public void actionPerformed(ActionEvent e) { System.out.println("ComboBox action sur " + combo.getSelectedItem()); } } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent action) { setVisible(false); } } }
true
f707f243cb0809d7683595a501014eb0ae811772
Java
bxbxbx/nabaztag-source-code
/server/OS/net/violet/platform/datamodel/ApplicationTempImpl.java
UTF-8
4,631
2.171875
2
[ "MIT" ]
permissive
package net.violet.platform.datamodel; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import net.violet.db.records.AbstractSQLRecord; import net.violet.db.records.ObjectRecord; import net.violet.db.records.SQLKey; import net.violet.db.records.SQLObjectSpecification; import net.violet.db.records.associations.SingleAssociationNotNull; import org.apache.log4j.Logger; public class ApplicationTempImpl extends ObjectRecord<ApplicationTemp, ApplicationTempImpl> implements ApplicationTemp { private static final Logger LOGGER = Logger.getLogger(ApplicationTempImpl.class); public static final SQLObjectSpecification<ApplicationTempImpl> SPECIFICATION = new SQLObjectSpecification<ApplicationTempImpl>("application_temp", ApplicationTempImpl.class, new SQLKey[] { new SQLKey("application_id") }); private static final String[] NEW_COLUMNS = new String[] { "application_id", "application_link", "application_shortcut", "application_image", "application_icone", "application_stream_url", "application_type" }; protected long application_id; protected String application_link; protected String application_shortcut; protected String application_image; protected String application_icone; protected long application_type; private final SingleAssociationNotNull<ApplicationTemp, Application, ApplicationImpl> mApplication; protected ApplicationTempImpl() { this.mApplication = new SingleAssociationNotNull<ApplicationTemp, Application, ApplicationImpl>(this, "application_id", ApplicationImpl.SPECIFICATION); } protected ApplicationTempImpl(long appId) throws NoSuchElementException, SQLException { init(appId); this.mApplication = new SingleAssociationNotNull<ApplicationTemp, Application, ApplicationImpl>(this, "application_id", ApplicationImpl.SPECIFICATION); } public ApplicationTempImpl(Application inApplication, String inLink, String inShortcut, String inImage, String inIcone) throws SQLException { this.application_id = inApplication.getId(); this.application_link = inLink; this.application_shortcut = inShortcut; this.application_image = inImage; this.application_icone = inIcone; this.application_type = 0; ApplicationTempImpl.LOGGER.info("--------->" + this.application_type); init(ApplicationTempImpl.NEW_COLUMNS); this.mApplication = new SingleAssociationNotNull<ApplicationTemp, Application, ApplicationImpl>(this, "application_id", ApplicationImpl.SPECIFICATION); } public static ApplicationTemp findByShortcut(String shortcut) { ApplicationTemp result = null; try { result = AbstractSQLRecord.find(ApplicationTempImpl.SPECIFICATION, "application_shortcut = ?", Arrays.asList(new Object[] { shortcut })); } catch (final SQLException e) { ApplicationTempImpl.LOGGER.fatal(e, e); } return result; } public static ApplicationTemp findByLink(String link) { ApplicationTemp result = null; try { result = AbstractSQLRecord.find(ApplicationTempImpl.SPECIFICATION, "application_link = ?", Arrays.asList(new Object[] { link })); } catch (final SQLException e) { ApplicationTempImpl.LOGGER.fatal(e, e); } return result; } /** * @see net.violet.platform.datamodel.ObjectRecord#getSpecification() */ @Override public SQLObjectSpecification<ApplicationTempImpl> getSpecification() { return ApplicationTempImpl.SPECIFICATION; } public Application getApplication() { return this.mApplication.get(this.application_id); } public String getIcone() { return this.application_icone; } public String getImage() { return this.application_image; } public String getLink() { return this.application_link; } public String getShortcut() { return this.application_shortcut; } public long getType() { return this.application_type; } public void setLink(String link) { final Map<String, Object> theUpdateMap = new HashMap<String, Object>(); setLink(theUpdateMap, link); update(theUpdateMap); } private void setLink(Map<String, Object> theUpdateMap, String link) { if (!this.application_link.equals(link)) { this.application_link = link; theUpdateMap.put("application_link", link); } } public void setShorcut(String shorcut) { final Map<String, Object> theUpdateMap = new HashMap<String, Object>(); setShorcut(theUpdateMap, shorcut); update(theUpdateMap); } private void setShorcut(Map<String, Object> theUpdateMap, String shorcut) { if (!this.application_shortcut.equals(shorcut)) { this.application_shortcut = shorcut; theUpdateMap.put("application_shortcut", shorcut); } } }
true
13b15a247899dfb428c2e4ba9a94ca07f5092872
Java
P79N6A/icse_20_user_study
/methods/Method_13919.java
UTF-8
305
1.9375
2
[]
no_license
@Override public List<Object> getNextRowOfCells() throws IOException { if (_line == null) { _line=_lnReader.readLine(); } if (_line == null) { return null; } if (_dimensions == null) { return parseMetadataPrologueForColumnNames(); } else { return parseForNextDataRow(); } }
true
c5830c1f336d26f38d41abf97c3bf9bc5ea0ac4b
Java
kbuzsaki/FEK
/src/Game/Menus/MenuItemSelection.java
UTF-8
2,096
2.609375
3
[]
no_license
/* * Copyright 2012 Kyle Buzsaki. All Rights Reserved. */ package Game.Menus; import Game.Cursor; import Game.Sound.SoundManager; import Sprites.Panels.GameScreen; import Units.Items.Equipment; import Units.Items.Item; public class MenuItemSelection extends MenuItem { private MenuSelection selectionMenuToOpen; public MenuItemSelection(GameScreen gameScreen, SoundManager soundManager, Cursor cursor, PanelInventoryInfo infoPanel) { super(gameScreen, soundManager, cursor, infoPanel); } @Override // unsupported void openQuietly(Menu parentMenu, CancelListener cancelListener) { throw new UnsupportedOperationException("Cannot open Item Selection Menu without selectionMenuToOpen"); } void openQuietly(MenuSelection selectionMenuToOpen, CancelListener cancelListener) { this.selectionMenuToOpen = selectionMenuToOpen; super.openQuietly(null, cancelListener); } @Override protected void updateIndex(int index) { super.updateIndex(index); if(hasSelectionMenuToOpen()) getSelectionMenuToOpen().updateRanges(getItemAt(index)); } @Override public boolean isTargetable(Item item) { return isUseable(item); } @Override public boolean isUseable(Item item) { return getSelectionMenuToOpen().isUseable(item); } private boolean hasSelectionMenuToOpen() { if(selectionMenuToOpen != null) { return true; } else { return false; } } private MenuSelection getSelectionMenuToOpen() { if(selectionMenuToOpen != null) return selectionMenuToOpen; else { System.err.println("Item Selection Menu has not been properly opened (missing a selection menu)"); return null; } } @Override protected void performAction(int index) { getActor().getInventory().equip((Equipment)getItemAt(index)); getSelectionMenuToOpen().openQuietly(this); close(); } }
true
bef9af5b69820ea8c9026522dc89baedf06a4ccb
Java
MoonSoYoung/SWVProj
/Spring_Customer/src/main/java/com/example/dto/CustomerVO.java
UTF-8
724
2.125
2
[]
no_license
package com.example.dto; public class CustomerVO { private String customer_name; private String carnum; private String carcat; private String phonenum; public String getCustomer_name() { return customer_name; } public void setCustomer_name(String customer_name) { this.customer_name = customer_name; } public String getCarnum() { return carnum; } public void setCarnum(String carnum) { this.carnum = carnum; } public String getCarcat() { return carcat; } public void setCarcat(String carcat) { this.carcat = carcat; } public String getPhonenum() { return phonenum; } public void setPhonenum(String phonenum) { this.phonenum = phonenum; } }
true
342699d18a2b6655f798274bbe6c9cbb440248cc
Java
ylw530788697/zk-distribute-lock
/src/main/java/com/evan/config/ZookeeperConf.java
UTF-8
869
2.140625
2
[]
no_license
package com.evan.config; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author evanYang * @version 1.0 * @date 2020/04/12 21:58 */ @Configuration public class ZookeeperConf { @Value("${zk.url}") private String zkUrl="127.0.0.1:2181"; @Bean public CuratorFramework getCuratorFramework(){ RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3); CuratorFramework client = CuratorFrameworkFactory.newClient(zkUrl, retryPolicy); client.start(); return client; } }
true
5ff861314dff4b9b66887fd0ea412589cb67a77d
Java
karol-dziachan/scheduling-access-to-the-processor
/schedulding-access/RR_implementation/CPU_simulation_RR.java
UTF-8
1,493
3.3125
3
[]
no_license
package RR_implementation; import java.util.ArrayList; public class CPU_simulation_RR { private double time; //q (quantum of process execution time), and k(switching time between processes) private double q, k; private double average; public CPU_simulation_RR(double q, double k) { time=0; this.q=q; this.k=k; } public void executionProcess(ArrayList<Double> array) { System.out.println("Results for the RR algorithm" + "\n"); int size = array.size(); double tmp=0; while(true) { for (int i = 0; i < array.size(); i++) { if (q <= array.get(i)) { tmp=array.get(i); tmp-=q; time+=(q+k); array.add(i, tmp); array.remove(i+1); } else if (q>array.get(i)) { time+=(array.get(i)+k); array.remove(i); } } if(array.size()==0) break; } average = (double) time/size; System.out.println("execution time for all processes " + time + " units time"); System.out.println("average process time "+(double) time/size+" units time" + "\n"); } public double getAverage() { return average; } }
true
c79b49970fdb3bcf0eba55761f8d9a08a4e7f6e6
Java
GrzegorzCagara/AuthorizationService
/security_server_oauth2/src/main/java/com/example/security_server_xxx/services/UserServiceImpl.java
UTF-8
3,098
2.328125
2
[]
no_license
package com.example.security_server_xxx.services; import com.example.security_server_xxx.entity.PasswordResetToken; import com.example.security_server_xxx.entity.Users; import com.example.security_server_xxx.models.request.ResetPasswordRequest; import com.example.security_server_xxx.repositories.AccountRepo; import com.example.security_server_xxx.repositories.PasswordTokenRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import java.util.UUID; @Service public class UserServiceImpl implements UserService { @Autowired private AccountRepo accountRepo; @Autowired private PasswordEncoder passwordEncoder; @Autowired private PasswordTokenRepository passwordTokenRepository; @Override public Users findAccountByUsername(String username) { Optional<Users> account = accountRepo.findByLogin( username ); if ( account.isPresent() ) { return account.get(); } else { throw new UsernameNotFoundException(String.format("Username[%s] not found", username)); } } @Override public Users registerUser(Users account) { account.setPassword(passwordEncoder.encode(account.getPassword())); return accountRepo.save(account); } @Override public String generateResetToken(String login) { Users user = findAccountByUsername(login); String token = UUID.randomUUID().toString(); createPasswordResetTokenForUser(user, token); return token; } @Override public String ifValidTokenChangePassword(ResetPasswordRequest request) { PasswordResetToken passToken = passwordTokenRepository.findByToken(request.getCode()); if (passToken == null) { return "INVALID_TOKEN"; } if (((passToken.getExpiryDate() + PasswordResetToken.getEXPIRATION()) - System.currentTimeMillis()) <= 0) { return "EXPIRED_TOKEN"; } Users user = passToken.getUsers(); if (user == null) { return "NOT_FOUND_USER"; } user.setPassword(request.getNewPassword()); registerUser(user); passwordTokenRepository.delete(passToken); return null; } private void createPasswordResetTokenForUser(Users user, String token) { PasswordResetToken myToken = new PasswordResetToken(token, user); passwordTokenRepository.save(myToken); } @Transactional public boolean removeAuthenticatedAccount() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); Users acct = findAccountByUsername(username); int del = accountRepo.deleteUsersById(acct.getId()); return del > 0; } }
true
63f8085946f2a1453324d0c636a812546e7050ff
Java
azurewer/ArchStudio5
/org.archstudio.myx.java/src/org/archstudio/myx/java/demo/basic/App.java
UTF-8
4,018
2.34375
2
[]
no_license
package org.archstudio.myx.java.demo.basic; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.archstudio.myx.fw.EMyxInterfaceDirection; import org.archstudio.myx.fw.IMyxImplementation; import org.archstudio.myx.fw.IMyxName; import org.archstudio.myx.fw.IMyxRuntime; import org.archstudio.myx.fw.IMyxWeld; import org.archstudio.myx.fw.MyxBasicBrickInitializationData; import org.archstudio.myx.fw.MyxJavaClassInterfaceDescription; import org.archstudio.myx.fw.MyxUtils; import org.archstudio.myx.java.MyxJavaClassBrickDescription; public class App { public static final IMyxName serverName = MyxUtils.createName("Server"); public static final IMyxName clientName = MyxUtils.createName("Client"); public static final IMyxName proxyName = MyxUtils.createName("Proxy"); protected IMyxImplementation myximpl; public static void main(String[] args) { new App(); } public App() { myximpl = MyxUtils.getDefaultImplementation(); doApp1(); System.err.println("---"); doApp2(); } public void doApp1() { IMyxRuntime myx = myximpl.createRuntime(); try { MyxJavaClassBrickDescription serverDesc = new MyxJavaClassBrickDescription( "org.archstudio.myx.demo.basic.ServerComponent"); MyxJavaClassBrickDescription clientDesc = new MyxJavaClassBrickDescription( "org.archstudio.myx.demo.basic.ClientComponent"); myx.addBrick(null, serverName, serverDesc, null); myx.addBrick(null, clientName, clientDesc, null); MyxJavaClassInterfaceDescription imathIfaceDesc = new MyxJavaClassInterfaceDescription( Collections.singleton("org.archstudio.myx.demo.basic.IMath")); myx.addInterface(null, clientName, MyxUtils.createName("math"), imathIfaceDesc, EMyxInterfaceDirection.OUT); myx.addInterface(null, serverName, MyxUtils.createName("math"), imathIfaceDesc, EMyxInterfaceDirection.IN); IMyxWeld s2c = myx.createWeld(null, clientName, MyxUtils.createName("math"), null, serverName, MyxUtils.createName("math")); myx.addWeld(s2c); myx.init(null, null); myx.begin(null, null); } catch (Exception e) { e.printStackTrace(); } } public void doApp2() { IMyxRuntime myx = myximpl.createRuntime(); try { MyxJavaClassBrickDescription serverDesc = new MyxJavaClassBrickDescription( "org.archstudio.myx.demo.basic.ServerComponent"); MyxJavaClassBrickDescription proxyDesc = new MyxJavaClassBrickDescription( "org.archstudio.myx.java.conn.SynchronousProxyConnector"); MyxJavaClassBrickDescription clientDesc = new MyxJavaClassBrickDescription( "org.archstudio.myx.demo.basic.ClientComponent"); myx.addBrick(null, serverName, serverDesc, null); myx.addBrick(null, clientName, clientDesc, null); Map<String, String> proxyProperties = new HashMap<String, String>(); proxyProperties.put("interfaceClassName0", "org.archstudio.myx.demo.basic.IMath"); myx.addBrick(null, proxyName, proxyDesc, new MyxBasicBrickInitializationData(proxyProperties)); MyxJavaClassInterfaceDescription imathIfaceDesc = new MyxJavaClassInterfaceDescription( Collections.singleton("org.archstudio.myx.demo.basic.IMath")); myx.addInterface(null, clientName, MyxUtils.createName("math"), imathIfaceDesc, EMyxInterfaceDirection.OUT); myx.addInterface(null, proxyName, MyxUtils.createName("out"), imathIfaceDesc, EMyxInterfaceDirection.OUT); myx.addInterface(null, proxyName, MyxUtils.createName("in"), imathIfaceDesc, EMyxInterfaceDirection.IN); myx.addInterface(null, serverName, MyxUtils.createName("math"), imathIfaceDesc, EMyxInterfaceDirection.IN); IMyxWeld p2s = myx.createWeld(null, proxyName, MyxUtils.createName("out"), null, serverName, MyxUtils.createName("math")); IMyxWeld c2p = myx.createWeld(null, clientName, MyxUtils.createName("math"), null, proxyName, MyxUtils.createName("in")); myx.addWeld(p2s); myx.addWeld(c2p); myx.init(null, null); myx.begin(null, null); } catch (Exception e) { e.printStackTrace(); } } }
true
04b7ed4e4ba0d35f4af051f8daab836bdd3956ed
Java
app-project/MyAndroidApp
/src/com/app/myapp/activity/CigaretteDetailActivity.java
UTF-8
4,622
2.28125
2
[]
no_license
package com.app.myapp.activity; import java.util.List; import com.app.myapp.R; import com.app.myapp.dao.CartInfoDao; import com.app.myapp.dao.impl.CartInfoDaoImpl; import com.app.myapp.model.CartInfo; import com.app.myapp.model.Cigarette; import com.app.myapp.util.image.ImageManager; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class CigaretteDetailActivity extends Activity { private Cigarette cigaretteDetail; private ImageView img; private TextView txtPrice,txtName; private ImageButton btnback; private Button btnSubtract,btnAdd,btnAddCar; private EditText txtNum; private Integer num; private CartInfoDao cartinfoDao; //TAG private final String TAG = "com.app.myapp.activity.CigaretteDetailActivity"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_cigarettedetail); //实例化DAO cartinfoDao= new CartInfoDaoImpl(this); print(); //查找元素 findsView(); //获取Intent Intent _intent = this.getIntent(); cigaretteDetail = (Cigarette) _intent.getSerializableExtra("cigaretteDetail"); if (cigaretteDetail==null) { Log.e(TAG, "null"); }else { Log.i(TAG,cigaretteDetail.getPic()); Log.i(TAG,cigaretteDetail.getName()); //加载图片 ImageManager.from(this).displayImage(img,cigaretteDetail.getPic(),0,100,100); txtName.setText(cigaretteDetail.getName()); txtPrice.setText(String.valueOf(cigaretteDetail.getPrice())); } setClick(); } //查找元素 private void findsView() { img = (ImageView) this.findViewById(R.id.imageView); txtPrice=(TextView) this.findViewById(R.id.txtPrice); txtName=(TextView) this.findViewById(R.id.txtName); //退回 btnback = (ImageButton) this.findViewById(R.id.btn_back); //减数量 btnSubtract = (Button) this.findViewById(R.id.btnSubtract); //增加数量 btnAdd = (Button) this.findViewById(R.id.btnAdd); //加入购物车 btnAddCar = (Button) this.findViewById(R.id.btnAddCar); //数量 txtNum = (EditText) this.findViewById(R.id.txtNum); } //设置事件 private void setClick() { btnback.setOnClickListener(onclick); btnAdd.setOnClickListener(onclick); btnSubtract.setOnClickListener(onclick); btnAddCar.setOnClickListener(onclick); } //事件处理 private OnClickListener onclick=new OnClickListener () { @Override public void onClick(View v) { switch(v.getId()){ case R.id.btn_back: finish(); break; case R.id.btnAdd: num = Integer.valueOf(txtNum.getText().toString()); Log.e(TAG, "num:"+num); txtNum.setText(String.valueOf(num+1)); break; case R.id.btnSubtract: num = Integer.valueOf(txtNum.getText().toString()); Log.e(TAG,"num:"+num); if(num >1){ txtNum.setText(String.valueOf(num-1)); } break; case R.id.btnAddCar: AddCar(); break; default: break; } } }; //加入购物车 private void AddCar() { String message="成功添加至购物车!"; CartInfo cartInfo; num = Integer.valueOf(txtNum.getText().toString()); if(num>0) { cartInfo = cartinfoDao.checkCartInfo("id", String.valueOf(cigaretteDetail.getId())); if(cartInfo ==null) { cartInfo=new CartInfo(); cartInfo.setId(cigaretteDetail.getId()); cartInfo.setName(cigaretteDetail.getName()); cartInfo.setNum(num); cartInfo.setPic(cigaretteDetail.getPic()); cartInfo.setPrice(cigaretteDetail.getPrice()); //插入 cartinfoDao.insert(cartInfo); }else { message = "购物车中已存在,请到购物车中修改!"; } }else { message = "数量有误,请重新输入!"; } //输出提示 showToast(message); } private void print() { CartInfo cart; List<CartInfo> list=cartinfoDao.getAllCartInfo("id", "1"); for(int i=0;i<list.size();i++) { cart = list.get(i); Log.i(TAG, "id:"+cart.getId()+ " name:"+cart.getName()); } } //提示信息 private void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }
true
84f5082fd047415793d384192af3af6045f24acb
Java
AugustFire/dd-music
/exam_exercise/trunk/src/main/java/com/nercl/music/controller/DirectoryUpdaterController.java
UTF-8
550
1.953125
2
[]
no_license
package com.nercl.music.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.nercl.music.service.MFileService; @Controller public class DirectoryUpdaterController { @Autowired private MFileService mfileService; /** * update * */ @GetMapping("/update") @ResponseBody public void update() { this.mfileService.updatePath(); } }
true
8b71dbe8b84f604b2303949060e9726659df3497
Java
helmutsiegel/profile
/common/src/main/java/org/helmut/profile/common/model/SectionTO.java
UTF-8
826
2.28125
2
[]
no_license
package org.helmut.profile.common.model; import org.helmut.profile.common.validation.groups.Existing; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class SectionTO { @NotNull(groups = Existing.class) private Long id; @NotNull @Size(min = 5) private String title; @NotNull @Size(min = 50) private String description; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
true
feda00b6d294e4144503e6fba4703a7741968def
Java
8secz-johndpope/snapchat-re
/jadx-snap-new/sources/com/snap/core/db/record/CharmsOwnerMetadataRecord$Companion$FACTORY$1.java
UTF-8
959
1.75
2
[]
no_license
package com.snap.core.db.record; import defpackage.akcb; import defpackage.akcq; import defpackage.akde; import defpackage.akej; final class CharmsOwnerMetadataRecord$Companion$FACTORY$1 extends akcq implements akcb<Long, String, byte[], Long, AutoValue_CharmsOwnerMetadataRecord> { public static final CharmsOwnerMetadataRecord$Companion$FACTORY$1 INSTANCE = new CharmsOwnerMetadataRecord$Companion$FACTORY$1(); CharmsOwnerMetadataRecord$Companion$FACTORY$1() { super(4); } public final String getName() { return "<init>"; } public final akej getOwner() { return akde.a(AutoValue_CharmsOwnerMetadataRecord.class); } public final String getSignature() { return "<init>(JLjava/lang/String;[BJ)V"; } public final AutoValue_CharmsOwnerMetadataRecord invoke(long j, String str, byte[] bArr, long j2) { return new AutoValue_CharmsOwnerMetadataRecord(j, str, bArr, j2); } }
true
f70b0e7056ceb0990b4d4792e096c8fc1b4b321c
Java
Gridin/ThinkingInJava
/src/_08_inner_classes_05_using_this_and_new/MyMain.java
UTF-8
200
2.53125
3
[]
no_license
package _08_inner_classes_05_using_this_and_new; public class MyMain { public static void myMain() { Outer out = new Outer(); Separate separate = new Separate(out); } }
true
4f353666049ecec31f91b747eb438565ddbd4863
Java
huhaichao/HuangNiao
/src/main/java/com/sy/huangniao/common/Util/TrainUtil.java
UTF-8
4,486
2.4375
2
[]
no_license
package com.sy.huangniao.common.Util; import java.io.IOException; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import com.alibaba.fastjson.JSONObject; import com.sy.huangniao.common.Util.ProxyUtil.ProxyInfo; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * Created by huchao on 2018/12/15. * 爬取12306车票信息 */ public class TrainUtil { private static String getUrlApi() { StringBuilder buffer = new StringBuilder(); try { buffer.append("https://kyfw.12306.cn/otn/"); String trainDom = httpGet("https://kyfw.12306.cn/otn/leftTicket/init"); String context = trainDom.substring(trainDom.indexOf("/*<![CDATA[*/"), trainDom.indexOf("/*]]>*/")); String ticketUrl = context.substring(context.indexOf(" var CLeftTicketUrl = "), context.indexOf(" var CLeftTicketUrl = ") + 43); ticketUrl = ticketUrl.replaceAll(" ", ""); String aa[] = ticketUrl.split("="); buffer.append(aa[1].substring(aa[1].indexOf("'") + 1, aa[1].indexOf(";") - 1)); buffer.append("?"); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } /** * 通过出发日期-出发站点-到达站点查询车票列表 * * @param departureDate * @param fromSite * @param toSite * @return */ public static JSONObject getTrainList(String departureDate, String fromSite, String toSite) { StringBuilder stringBuilder = new StringBuilder(); String trainUrl = getUrlApi(); String newurl = stringBuilder.append(trainUrl).append("leftTicketDTO.train_date=").append(departureDate).append( "&leftTicketDTO.from_station=") .append(fromSite).append("&leftTicketDTO.to_station=").append(toSite).append("&purpose_codes=ADULT") .toString(); //调用方法,获取两地之间的火车数组 String result = httpGet(newurl); JSONObject jSONObject = JSONObject.parseObject(result); JSONObject listObject = jSONObject.getJSONObject("data"); return listObject; } private static String httpGet(String url) { return httpGet(url, "utf-8", 30000, 30000); } /** * httpGet * * @param url * @param charset * @return */ public static String httpGet(String url, String charset, int connectTimeout, int socketTimeout) { CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig; ThreadLocal<List<ProxyInfo>> threadLocal = ProxyUtil.getLocalProxyInfos(); List<ProxyInfo> list = threadLocal.get(); if (list !=null && list.size() > 0) { try { int i = ThreadLocalRandom.current().nextInt(0, list.size() - 1); ProxyInfo proxyInfo = list.get(i); requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout( socketTimeout).setProxy(new HttpHost(proxyInfo.getIp(), Integer.parseInt(proxyInfo.getPort()))) .build(); } catch (Exception e) { e.printStackTrace(); requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout( socketTimeout).build(); } } else { requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout( socketTimeout).build(); } HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); CloseableHttpResponse response; String result = null; try { response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity, charset); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
true
1f00d6d4c8015b631b1dcc36ec71891ffe5d5e99
Java
openimaj/openimaj
/knowledge/ontologies/sioc/src/main/java/orgrdfs/sioc/ns/Space.java
UTF-8
468
2.125
2
[ "BSD-3-Clause" ]
permissive
package orgrdfs.sioc.ns; import java.util.List; /** * A Space is a place where data resides, e.g. on a website, desktop, fileshare, * etc. */ @SuppressWarnings("javadoc") public interface Space { public List<String> getSpace_of(); public void setSpace_of(final List<String> space_of); public List<orgrdfs.sioc.ns.Usergroup> getHas_usergroup(); public void setHas_usergroup(final List<orgrdfs.sioc.ns.Usergroup> has_usergroup); public String getURI(); }
true
1917acd2f818fc3e549f43ed3c4b9b4bffb8f991
Java
achyutsun/Crossword
/src/main/java/uk/org/downiesoft/crossword/MainActivity.java
UTF-8
19,046
2.078125
2
[ "Apache-2.0" ]
permissive
package uk.org.downiesoft.crossword; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import uk.org.downiesoft.spell.SpellActivity; public class MainActivity extends FragmentActivity implements BluetoothManager.BluetoothListener, ClueListFragment.ClueListListener, WebManager.WebManagerListener { public static final String TAG = MainActivity.class.getName(); public static final String CROSSWORD_DIR = "Crossword"; public static final int REQUEST_CONNECT_DEVICE_SECURE = 1; public static final int REQUEST_ENABLE_BT = 2; public static final int REQUEST_CLUE = 4096; public static final int REQUEST_BROWSER = 4097; public static final int REQUEST_PUZZLE = 4098; public static final int REQUEST_SOLUTION = 4099; private static final int sDebug = 2; private static File sCrosswordRoot; private CrosswordModel mCrossword; private GridFragment mGridFragment; private CluesFragment mCluesFragment; private WebManager mWebManager; private Intent mServerIntent; private BluetoothManager mBluetoothManager; private boolean mCrosswordReceived = false; private boolean mBTServer = false; private boolean mBTEnabled = false; private int mClueDirection = -1; private int mCluePosition = -1; public static void debug(int aLevel, String aTag, String aText) { if (aLevel <= sDebug) { Log.d(aTag, aText); } } private class ImportPuzzleTask extends AsyncTask<String, Void, CrosswordModel> { ProgressDialog mDialog; CrosswordModel mCrossword; @Override protected void onPreExecute() { mDialog = new ProgressDialog(MainActivity.this); mDialog.setMessage("Working..."); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mDialog.setCancelable(false); mDialog.show(); } @Override protected CrosswordModel doInBackground(String... html) { try { DataInputStream is = new DataInputStream(new ByteArrayInputStream(html[0].getBytes())); CrosswordModel crossword = CrosswordModel.importCrossword(is); is.close(); return crossword; } catch (Exception e) { MainActivity.debug(1, TAG, e.toString() + ":" + e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(CrosswordModel aCrossword) { mDialog.dismiss(); if (aCrossword != null) { setCrossword(aCrossword); } } } private class ImportSolutionTask extends AsyncTask<String, Void, CrosswordModel> { ProgressDialog mDialog; @Override protected void onPreExecute() { mDialog = new ProgressDialog(MainActivity.this); mDialog.setMessage("Working..."); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mDialog.setCancelable(false); mDialog.show(); } @Override protected CrosswordModel doInBackground(String... html) { MainActivity.debug(1, TAG, String.format("ImportSolutionTask: %s", html[0])); CrosswordModel solution = null; try { DataInputStream is = new DataInputStream(new ByteArrayInputStream(html[0].getBytes())); solution = CrosswordModel.importCrossword(is); is.close(); } catch (Exception e) { MainActivity.debug(1, TAG, e.toString() + ":" + e.getMessage()); e.printStackTrace(); } return solution; } @Override protected void onPostExecute(CrosswordModel solution) { mDialog.dismiss(); if (solution != null) { if (mCrossword.mapSolution(solution)) { mGridFragment.update(); } } else { Toast.makeText(MainActivity.this, R.string.text_invalid_solution, Toast.LENGTH_SHORT).show(); } } } public static File getCrosswordDirectory() { return sCrosswordRoot; } @Override protected void onCreate(Bundle savedInstanceState) { MainActivity.debug(1, TAG, String.format("onCreate(%s)", mCrossword)); super.onCreate(savedInstanceState); MainActivity.sCrosswordRoot = new File(Environment.getExternalStorageDirectory(),getString(R.string.crossword_app_name)); if (!MainActivity.sCrosswordRoot.exists()) { if (!MainActivity.sCrosswordRoot.mkdir()) { sCrosswordRoot = Environment.getExternalStorageDirectory(); } } setContentView(R.layout.activity_crossword); mCrossword = CrosswordModel.getInstance(); mWebManager = WebManager.getInstance(); restore(); if (mGridFragment == null) mGridFragment = new GridFragment(); if (mCluesFragment == null) { mCluesFragment = new CluesFragment(); } FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction().replace(R.id.fragmentContainer, mGridFragment, GridFragment.TAG).commit(); fm.beginTransaction().replace(R.id.cluesContainer, mCluesFragment, CluesFragment.TAG).commit(); if (fm.findFragmentByTag(WebManager.TAG) == null) { fm.beginTransaction().add(mWebManager,WebManager.TAG).commit(); } } @Override public void onStart() { MainActivity.debug(1, TAG, String.format("onStart(%s)", mCrossword)); super.onStart(); } @Override public void onResume() { MainActivity.debug(1, TAG, String.format("onResume(%s)", mCrossword)); super.onResume(); if (mCrossword.isValid()) setCrosswordTitle(); } @Override public void onPause() { MainActivity.debug(1, TAG, String.format("onPause(%s)", mCrossword)); super.onPause(); if (mCrossword.isValid() && mCrossword.isModified()) { if (!mCrossword.saveCrossword(sCrosswordRoot)) { Toast.makeText(this, R.string.save_failed, Toast.LENGTH_SHORT).show(); } } store(); } @Override public void onDestroy() { super.onDestroy(); if (mBluetoothManager != null) mBluetoothManager.stop(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.crossword, menu); if (mBluetoothManager != null && mBluetoothManager.isActive()) { menu.removeItem(R.id.action_bluetooth_on); } else { menu.removeItem(R.id.action_bluetooth_off); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean on = false; boolean off = false; for (int i = 0; i < menu.size(); i++) { off = off || menu.getItem(i).getItemId() == R.id.action_bluetooth_off; on = on || menu.getItem(i).getItemId() == R.id.action_bluetooth_on; } if (mBluetoothManager != null && mBluetoothManager.isActive()) { if (!off) menu.add(Menu.NONE, R.id.action_bluetooth_off, 100, R.string.action_bluetooth_off); if (on) menu.removeItem(R.id.action_bluetooth_on); } else { if (!on) menu.add(Menu.NONE, R.id.action_bluetooth_on, 101, R.string.action_bluetooth_on); if (off) menu.removeItem(R.id.action_bluetooth_off); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_open: { Intent intent = new Intent(this, BrowserActivity.class); startActivityForResult(intent, REQUEST_BROWSER); return true; } case R.id.action_import: { Intent intent = new Intent(this, WebActivity.class); intent.putExtra(WebViewFragment.ARG_MODE,WebViewFragment.MODE_PUZZLE); startActivityForResult(intent, MainActivity.REQUEST_PUZZLE); return true; } case R.id.action_solution: { Intent intent = new Intent(this, WebActivity.class); intent.putExtra(WebViewFragment.ARG_MODE,WebViewFragment.MODE_SOLUTION); startActivityForResult(intent, MainActivity.REQUEST_SOLUTION); return true; } case R.id.action_clear: { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(R.string.action_clear); builder.setMessage(R.string.text_query_continue); builder.setPositiveButton(R.string.text_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mCrossword.clearAnswers(); mGridFragment.setCrossword(mCrossword); dialog.dismiss(); } }); builder.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); return true; } case R.id.action_bluetooth_on: { startBluetooth(); return true; } case R.id.action_bluetooth_off: { stopBluetooth(); return true; } case R.id.action_spell: { mServerIntent = new Intent(MainActivity.this, SpellActivity.class); mServerIntent.putExtra("uk.org.downiesoft.crossword.wordPattern", mGridFragment.getCluePattern()); mServerIntent.putExtra("uk.org.downiesoft.crossword.clueText", mGridFragment.getClueText()); startActivityForResult(mServerIntent, SpellActivity.REQUEST_CROSSWORD); return true; } } return false; } @Override public void onWebManagerReady(WebManager aWebManager) { setCrosswordTitle(); } void setCrosswordTitle() { String title = getString(R.string.crossword_app_name); String subtitle = null; if (mBluetoothManager != null && mBluetoothManager.isActive() && mBluetoothManager.getStatus() != null) { subtitle = mBluetoothManager.getStatus(); } else if (mCrossword.isValid() && mWebManager != null) { title = Integer.toString(mCrossword.getCrosswordId()); WebInfo info = mWebManager.getCrossword(mCrossword.getCrosswordId()); if (info != null) { subtitle = info.dateString(); } } ActionBar ab = getActionBar(); if (ab != null) { ab.setTitle(title); ab.setSubtitle(subtitle); } } @Override public void setBTStatus(String aSubtitle) { ActionBar ab = getActionBar(); if (ab != null) { ab.setSubtitle(aSubtitle); } else { setCrosswordTitle(); } } public void onFileSelected(final File aFile) { CrosswordModel newCrossword = CrosswordModel.openCrossword(aFile); MainActivity.debug(1, TAG, String.format("onFileSelected(%s):%s", aFile, newCrossword)); if (newCrossword == null) { Toast.makeText(MainActivity.this, R.string.open_failed, Toast.LENGTH_LONG).show(); } else { newCrossword.setModified(false); setCrossword(newCrossword); } } public void setCrossword(CrosswordModel aCrossword) { mCrossword = aCrossword; MainActivity.debug(1,TAG,String.format("setCrossword(%s)",mCrossword.getCrosswordId())); CrosswordModel.setInstance(mCrossword); mCluesFragment.setCrossword(mCrossword); mGridFragment.setCrossword(mCrossword); mGridFragment.resetClue(); setCrosswordTitle(); } public void store() { if (mCrossword.isValid()) { try { DataOutputStream os = new DataOutputStream(openFileOutput("current.xwd", Context.MODE_PRIVATE)); mCrossword.externalize(os); os.flush(); os.close(); mGridFragment.setCrossword(mCrossword); } catch (IOException e) { e.printStackTrace(); } } if (mWebManager != null) { mWebManager.store(this); } } public void restore() { try { DataInputStream is = new DataInputStream(openFileInput("current.xwd")); mCrossword.internalize(is); is.close(); setCrosswordTitle(); } catch (IOException e) { } } public void importPuzzle(String html) { new ImportPuzzleTask().execute(html); } public void importSolution(String html) { new ImportSolutionTask().execute(html); } private void startBluetooth() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(R.string.action_bluetooth_on); builder.setMessage(R.string.text_select_connection); builder.setInverseBackgroundForced(true); builder.setPositiveButton(R.string.text_connect, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mCrosswordReceived = false; mBTServer = false; mBluetoothManager = BluetoothManager.getInstance(MainActivity.this, MainActivity.this); mBluetoothManager.setup(); if (!mBluetoothManager.bluetoothEnabled()) { mBTEnabled = false; Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, MainActivity.REQUEST_ENABLE_BT); } else { mBTEnabled = true; mServerIntent = new Intent(MainActivity.this, DeviceListActivity.class); startActivityForResult(mServerIntent, MainActivity.REQUEST_CONNECT_DEVICE_SECURE); } dialog.dismiss(); } }); builder.setNegativeButton(R.string.text_listen, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mCrosswordReceived = false; mBTServer = true; mBluetoothManager = BluetoothManager.getInstance(MainActivity.this, MainActivity.this); mBluetoothManager.setup(); if (!mBluetoothManager.bluetoothEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, MainActivity.REQUEST_ENABLE_BT); } else { mBluetoothManager.listen(); } dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } private void stopBluetooth() { if (mBluetoothManager != null && mBluetoothManager.isActive()) if (!mBTEnabled) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(R.string.action_bluetooth_off); builder.setMessage(R.string.text_disable_bt); builder.setInverseBackgroundForced(true); builder.setPositiveButton(R.string.text_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mBluetoothManager.stop(true); dialog.dismiss(); } }); builder.setNegativeButton(R.string.text_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mBluetoothManager.stop(false); dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } else mBluetoothManager.stop(false); } @Override public void onCrosswordReceived(final CrosswordModel aCrossword) { MainActivity.debug(1,TAG, String.format(">onCrosswordReceived(%s)->%s", mCrossword.getCrosswordId(), aCrossword.getCrosswordId())); if (mCrossword.isValid()) { if (!mCrossword.saveCrossword(sCrosswordRoot)) { Toast.makeText(this, R.string.save_failed, Toast.LENGTH_SHORT).show(); } } if (mCrossword.getCrosswordId() != aCrossword.getCrosswordId()) { mCrossword = aCrossword; setCrossword(aCrossword); } else { for (int col = 0; col < CrosswordModel.GRID_SIZE; col++) { for (int row = 0; row < CrosswordModel.GRID_SIZE; row++) { if (!mCrossword.isBlank(col, row)) { if (mCrossword.value(col, row) == CrosswordModel.SQUARE_NONBLANK) { mCrossword.setValue(col, row, aCrossword.value(col, row)); } } } } } if (!mCrosswordReceived) { mBluetoothManager.sendCrossword(mCrossword); } mCrosswordReceived = true; if (mGridFragment != null) { mGridFragment.update(); } store(); MainActivity.debug(1,TAG, String.format("<onCrosswordReceived(%s)", mCrossword.getCrosswordId())); } @Override public void onClueClicked(int aDirection, int aNum, int aPosition) { mClueDirection = aDirection; mCluePosition = aPosition; if (mGridFragment != null) { mGridFragment.clueClicked(aDirection, aNum, aPosition); } } @Override public void onClueLongClicked(int aDirection, int aNum, int aPosition) { mClueDirection = aDirection; mCluePosition = aPosition; if (mGridFragment != null) { mGridFragment.clueLongClicked(aDirection, aNum, aPosition); } } @Override public int onClueListCreated(ClueListFragment aClueList, int aDirection) { if (mCluesFragment != null) { mCluesFragment.setClueList(aDirection, aClueList); if (aDirection == mClueDirection) { return mCluePosition; } } return -1; } public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MainActivity.REQUEST_CONNECT_DEVICE_SECURE: // When DeviceListActivity returns with a device to connect if (resultCode == Activity.RESULT_OK) { mBluetoothManager.connectDevice(data); } break; case MainActivity.REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { // Bluetooth is now enabled, so set up a chat session if (!mBTServer) { mServerIntent = new Intent(this, DeviceListActivity.class); startActivityForResult(mServerIntent, MainActivity.REQUEST_CONNECT_DEVICE_SECURE); } else { mBluetoothManager.listen(); } } else { // User did not enable Bluetooth or an error occurred Toast.makeText(this, R.string.bt_not_enabled, Toast.LENGTH_SHORT).show(); } break; case SpellActivity.REQUEST_CROSSWORD: if (resultCode == Activity.RESULT_OK) { String word = data.getExtras().getString("uk.org.downiesoft.spell.wordResult", ""); if (word.length() > 0 && mGridFragment != null) { mGridFragment.enterWord(word.toUpperCase()); store(); BluetoothManager.synch(mCrossword); } } break; case MainActivity.REQUEST_PUZZLE: if (resultCode == Activity.RESULT_OK) { String html = data.getExtras().getString("html", ""); importPuzzle(html); } break; case MainActivity.REQUEST_SOLUTION: if (resultCode == Activity.RESULT_OK) { String html = data.getExtras().getString("html", ""); importSolution(html); } break; case MainActivity.REQUEST_BROWSER: if (resultCode == Activity.RESULT_OK) { File file = new File(sCrosswordRoot,String.format("%s.xwd",data.getExtras().getInt(BrowserDialog.ARG_ID))); MainActivity.debug(1,TAG,String.format("onActivityResult: %s",file)); onFileSelected(file); } break; default: super.onActivityResult(requestCode, resultCode, data); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if (mGridFragment != null) { if (mGridFragment.offerBackKeyEvent()) return true; } } return super.onKeyDown(keyCode, event); } }
true
710afd18df77e754b6d3abcb29c642a2afad8edb
Java
MechaMagpie/JJoy
/src/statements/functions/time/Mktime.java
UTF-8
1,148
2.46875
2
[ "BSD-3-Clause" ]
permissive
package statements.functions.time; import java.util.Calendar; import java.util.ListIterator; import interpreter.NoBracesStack; import statements.AbstractStatement; import statements.functions.MalformedListException; import statements.functions.UnaryFunction; import statements.literals.MutableList; import statements.literals.PushInteger; public class Mktime extends UnaryFunction<MutableList> { @Override public void eval(NoBracesStack stackState, MutableList t) throws MalformedListException { ListIterator<AbstractStatement> iter = t.listIterator(); Calendar cal = Calendar.getInstance(); try { cal.set((int)((PushInteger)iter.next()).longValue(), (int)((PushInteger)iter.next()).longValue() - 1, (int)((PushInteger)iter.next()).longValue(), (int)((PushInteger)iter.next()).longValue(), (int)((PushInteger)iter.next()).longValue(), (int)((PushInteger)iter.next()).longValue()); } catch (ClassCastException e) { throw new MalformedListException(name(), t.toString()); } stackState.push(new PushInteger(cal.getTimeInMillis() / 1000)); } @Override public String name() { return "mktime"; } }
true
a313e23a51b3ca49c50d5d10c8f16f203d34679b
Java
Viitainen/android-stuff
/Harj3_yelp/app/src/main/java/com/example/arto/yelp/MyRecyclerAdapter.java
UTF-8
2,448
2.40625
2
[]
no_license
package com.example.arto.yelp; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.example.arto.yelp.FeedItem; import com.example.arto.yelp.R; import com.squareup.picasso.Picasso; import java.util.List; // RecyclerView requires a customized adapter before the data can be used in it public class MyRecyclerAdapter extends RecyclerView.Adapter<FeedListRowHolder> { // data to be used private List<FeedItem> feedItemList; public FeedItem getSingleItem(int position) { return feedItemList.get(position); } private Context mContext; public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) { this.feedItemList = feedItemList; this.mContext = context; } @Override public FeedListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null); FeedListRowHolder mh = new FeedListRowHolder(v); return mh; } @Override public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) { FeedItem feedItem = feedItemList.get(i); // we're using Picasso to handle picture management. // if thumbnail not found, use placeholder image instead Picasso.with(mContext).load(feedItem.getThumbnail()) .error(R.drawable.placeholder) .placeholder(R.drawable.placeholder) .into(feedListRowHolder.thumbnail); feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle())); feedListRowHolder.address.setText(Html.fromHtml(feedItem.getAddress())); feedListRowHolder.categories.setText(Html.fromHtml(feedItem.getContentCategory())); feedListRowHolder.rating.setRating(feedItem.getRating().floatValue()); String reviews = feedItem.getReviews() + ""; reviews += " review"; if(feedItem.getReviews() != 1) { reviews += "s"; } feedListRowHolder.reviews.setText(reviews); } @Override public int getItemCount() { return (null != feedItemList ? feedItemList.size() : 0); } }
true
c66abb906a989bc56395006fd94badcda7f33ecf
Java
chaitanyabhasme/HackerRank
/src/greedy/PriyankaToys.java
UTF-8
1,345
3.390625
3
[]
no_license
package greedy; import java.util.Scanner; public class PriyankaToys { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int numToys = stdin.nextInt(); int[] weights = new int[numToys]; for(int i = 0;i<numToys; i++){ weights[i] = stdin.nextInt(); } stdin.close(); quicksort(weights,0,numToys - 1); findUnits(weights); } private static void findUnits(int[] arr) { int units = 0; int currWt = 0; for(int i = 0; i<arr.length;i++){ if(units == 0){ units++; currWt = arr[i]; continue; } if(arr[i] > currWt+4){ units++; currWt = arr[i]; } } System.out.println(units); } private static void quicksort(int[] arr, int low, int high) { if(low < high){ int pivot = partition(arr, low, high); quicksort(arr, low, pivot - 1); quicksort(arr, pivot + 1, high); } } private static int partition(int[] arr, int low, int high) { int mid = (low+high)/2; int pivotValue = arr[mid]; //swap pivot value with high int temp = arr[mid]; arr[mid] = arr[high]; arr[high] = temp; int index = low; for(int i = low; i<=high -1;i++){ if(arr[i] < pivotValue){ temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; index++; } } temp = arr[index]; arr[index] = arr[high]; arr[high] = temp; return index; } }
true
11d29e554540ef1fc73d8c64c5d17570e3038366
Java
ctripcorp/x-pipe
/redis/redis-keeper/src/test/java/com/ctrip/xpipe/redis/keeper/store/cmd/GtidSetCommandReaderTest.java
UTF-8
8,491
2
2
[ "Apache-2.0" ]
permissive
package com.ctrip.xpipe.redis.keeper.store.cmd; import com.ctrip.xpipe.api.utils.ControllableFile; import com.ctrip.xpipe.gtid.GtidSet; import com.ctrip.xpipe.redis.core.protocal.protocal.ArrayParser; import com.ctrip.xpipe.redis.core.redis.operation.RedisOp; import com.ctrip.xpipe.redis.core.redis.operation.RedisSingleKeyOp; import com.ctrip.xpipe.redis.core.redis.parser.AbstractRedisOpParserTest; import com.ctrip.xpipe.redis.core.store.CommandFile; import com.ctrip.xpipe.redis.core.store.CommandFileOffsetGtidIndex; import com.ctrip.xpipe.redis.core.store.CommandFileSegment; import com.ctrip.xpipe.redis.core.store.CommandStore; import com.ctrip.xpipe.utils.DefaultControllableFile; import com.ctrip.xpipe.utils.OffsetNotifier; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import static org.mockito.ArgumentMatchers.any; /** * @author lishanglin * date 2022/5/6 */ @RunWith(MockitoJUnitRunner.class) public class GtidSetCommandReaderTest extends AbstractRedisOpParserTest { @Mock private CommandStore commandStore; @Mock private OffsetNotifier notifier; private GtidSet excludedGtidSet = new GtidSet("a1:1-5"); @Before public void setupGtidSetCommandReaderTest() throws Exception { Mockito.when(commandStore.simpleDesc()).thenReturn("test"); } @Test @Ignore // write mock data info local files public void mockData() throws IOException { int cmdIndex = 1; for (int fileIndex = 0; fileIndex < 3; fileIndex++) { ControllableFile controllableFile = null; try { File cmdFile = new File("./src/test/resources/GtidSetCommandReaderTest/cmd_" + fileIndex); controllableFile = new DefaultControllableFile(cmdFile); for (int i = 0; i < 10; i++) { logger.info("[mockData][{}][{}] begin at {}", cmdFile, cmdIndex, controllableFile.getFileChannel().position()); String rawCmd = mockCmdRaw("a1:" + cmdIndex, "k" + cmdIndex, "v" + cmdIndex); controllableFile.getFileChannel().write(ByteBuffer.wrap(rawCmd.getBytes())); logger.info("[mockData][{}][{}] end at {}", cmdFile, cmdIndex, controllableFile.getFileChannel().position()); cmdIndex++; } } finally { if (null != controllableFile) controllableFile.close(); } } } @Test public void testReadCrossFileSegment() throws Exception { CommandFileOffsetGtidIndex startIndex = new CommandFileOffsetGtidIndex(new GtidSet("a1:1-2,b1:1-5"), new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_0"), 0), 112); CommandFileOffsetGtidIndex endIndex = new CommandFileOffsetGtidIndex(new GtidSet("a1:1-15,b1:1-5"), new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_1"), 0), 295); Mockito.when(commandStore.findFirstFileSegment(any())).thenReturn(new CommandFileSegment(startIndex, endIndex)); Mockito.when(commandStore.findNextFile(startIndex.getCommandFile().getFile())).thenReturn(endIndex.getCommandFile()); GtidSetCommandReader reader = new GtidSetCommandReader(commandStore, new GtidSet("a1:1-2"), new ArrayParser(), parser, notifier, 100); Mockito.verify(commandStore).findFirstFileSegment(any()); for (int i = 3; i <= 15;) { RedisOp redisOp = reader.read(); if (null == redisOp) continue; Assert.assertEquals("a1:" + i, redisOp.getOpGtid()); Assert.assertArrayEquals(("k" + i).getBytes(), ((RedisSingleKeyOp) redisOp).getKey().get()); Assert.assertArrayEquals(("v" + i).getBytes(), ((RedisSingleKeyOp) redisOp).getValue()); Mockito.verify(commandStore).findFirstFileSegment(any()); logger.info("[testReadCrossFile] check round {} success", i); i++; } reader.read(); // roll to next segment Mockito.verify(commandStore, Mockito.times(2)).findFirstFileSegment(any()); } @Test public void testReadMultiSegment() throws IOException { CommandFileOffsetGtidIndex startIndex = new CommandFileOffsetGtidIndex(new GtidSet("a1:1-5,b1:1-5"), new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_0"), 0), 280); CommandFileOffsetGtidIndex endIndex = new CommandFileOffsetGtidIndex(new GtidSet("a1:1-9,b1:1-5"), new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_0"), 0), 504); Mockito.when(commandStore.findFirstFileSegment(any())).thenReturn(new CommandFileSegment(startIndex, endIndex)); Mockito.when(commandStore.findNextFile(startIndex.getCommandFile().getFile())) .thenReturn(new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_1"), 0)); GtidSetCommandReader reader = new GtidSetCommandReader(commandStore, new GtidSet("a1:1-5"), new ArrayParser(), parser, notifier, 100); Mockito.verify(commandStore).findFirstFileSegment(any()); startIndex = endIndex; endIndex = new CommandFileOffsetGtidIndex(new GtidSet("a1:1-16,b1:1-5"), new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_1"), 0), 354); Mockito.when(commandStore.findFirstFileSegment(any())).thenReturn(new CommandFileSegment(startIndex, endIndex)); for (int i = 6; i <= 16;) { RedisOp redisOp = reader.read(); if (null == redisOp) continue; Assert.assertEquals("a1:" + i, redisOp.getOpGtid()); Assert.assertArrayEquals(("k" + i).getBytes(), ((RedisSingleKeyOp) redisOp).getKey().get()); Assert.assertArrayEquals(("v" + i).getBytes(), ((RedisSingleKeyOp) redisOp).getValue()); logger.info("[testReadCrossFile] check round {} success", i); i++; } Mockito.verify(commandStore, Mockito.times(2)).findFirstFileSegment(any()); } @Test public void testReadRightBoundOpenSegment() throws IOException { CommandFileOffsetGtidIndex startIndex = new CommandFileOffsetGtidIndex(new GtidSet("a1:1-16,b1:1-5"), new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_1"), 0), 354); Mockito.when(commandStore.findFirstFileSegment(any())).thenReturn(new CommandFileSegment(startIndex)); Mockito.when(commandStore.findNextFile(startIndex.getCommandFile().getFile())) .thenReturn(new CommandFile(new File("./src/test/resources/GtidSetCommandReaderTest/cmd_2"), 0)); GtidSetCommandReader reader = new GtidSetCommandReader(commandStore, new GtidSet("a1:1-16"), new ArrayParser(), parser, notifier, 100); for (int i = 17; i <= 30;) { RedisOp redisOp = reader.read(); if (null == redisOp) continue; Assert.assertEquals("a1:" + i, redisOp.getOpGtid()); Assert.assertArrayEquals(("k" + i).getBytes(), ((RedisSingleKeyOp) redisOp).getKey().get()); Assert.assertArrayEquals(("v" + i).getBytes(), ((RedisSingleKeyOp) redisOp).getValue()); logger.info("[testReadCrossFile] check round {} success", i); i++; } } @Test public void testReadFromHugeFilePosition() throws IOException { } @Test public void testReadSkipCarelessCmdInSegmentHead() { } @Test public void testReadSkipCarelessCmdWithinSegment() { } @Test public void testReadSkipCarelessCmdInSegmentTail() { } private String mockCmdRaw(String gtid, String key, String val) { return "*6\r\n" + "$4\r\n" + "gtid\r\n" + "$" + gtid.length() + "\r\n" + gtid + "\r\n" + "$1\r\n" + "0\r\n" + "$3\r\n" + "SET\r\n" + "$" + key.length() + "\r\n" + key + "\r\n" + "$" + val.length() + "\r\n" + val + "\r\n"; } }
true
9e053ebc40801dda9711491890aeaa084f1418d1
Java
cyrus13/java-abstractions
/src/test/java/net/anastasakis/utl/concurrent/InterruptiblesTest.java
UTF-8
5,287
2.84375
3
[ "MIT" ]
permissive
/** * Copyright 2018 Cyrus13 * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ package net.anastasakis.utl.concurrent; import net.anastasakis.util.concurrent.Interruptibles; import org.junit.jupiter.api.Test; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; /** * Test methods for {@link net.anastasakis.util.concurrent.Interruptibles} class. * * @author Cyrus13 */ public class InterruptiblesTest { @Test public void testCountDownLatchReturns() { final CountDownLatch countDownLatch = new CountDownLatch(1); final CountDownLatchWaiter waiter = new CountDownLatchWaiter(countDownLatch); final Thread thread = new Thread(waiter); thread.start(); countDownLatch.countDown(); // Allow for countDown to be notified mySleep(20); assertTrue(waiter.hasReturnValue()); assertTrue(waiter.getActualReturnValue()); assertFalse(thread.isInterrupted()); } @Test public void testCountDownLatchTimesOut(){ final CountDownLatch countDownLatch = new CountDownLatch(1); final CountDownLatchWaiter waiter = new CountDownLatchWaiter(countDownLatch); final Thread thread = new Thread(waiter); thread.start(); // Wait more than the latch await time mySleep(3_000); assertTrue(waiter.hasReturnValue()); assertFalse(waiter.getActualReturnValue()); assertFalse(thread.isInterrupted()); } @Test public void testCountDownLatchInterrupted() { final CountDownLatch countDownLatch = new CountDownLatch(1); final CountDownLatchWaiter waiter = new CountDownLatchWaiter(countDownLatch); final Thread thread = new Thread(waiter); thread.start(); thread.interrupt(); if (thread.isAlive()) { assertTrue(thread.isInterrupted()); } mySleep(10); assertTrue(waiter.hasReturnValue()); assertFalse(waiter.getActualReturnValue()); } @Test public void testMySleepFinish(){ final Sleeper sleeper = new Sleeper(); final Thread thread = new Thread(sleeper); thread.start(); mySleep(2_100); assertTrue(sleeper.isFinishedSleeping()); assertFalse(thread.isInterrupted()); } @Test public void testMySleepInterrupt(){ final Sleeper sleeper = new Sleeper(); final Thread thread = new Thread(sleeper); thread.start(); mySleep(30); thread.interrupt(); assertFalse(sleeper.isFinishedSleeping()); if (thread.isAlive()) { assertTrue(thread.isInterrupted()); } // Give some time for the thread to be interrupted, // but less than the total sleep time mySleep(30); assertTrue(sleeper.isFinishedSleeping()); } private static void mySleep(long waitInMillis){ try { Thread.sleep(waitInMillis); } catch (InterruptedException e) { // This will never happen as this is the test thread fail("Interrupted exception thrown during test"); } } private static class CountDownLatchWaiter implements Runnable { private final CountDownLatch countDownLatch; private Optional<Boolean> returnValue = Optional.empty(); public CountDownLatchWaiter(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { this.returnValue = Optional.of(Interruptibles.awaitOnLatch(countDownLatch,2,TimeUnit.SECONDS)); } public boolean hasReturnValue() { return returnValue.isPresent(); } public boolean getActualReturnValue(){ return returnValue.get(); } } private static class Sleeper implements Runnable{ private boolean finishedSleeping = false; @Override public void run() { Interruptibles.sleep(2,TimeUnit.SECONDS); this.finishedSleeping = true; } public boolean isFinishedSleeping() { return finishedSleeping; } } }
true
5d045d5e426f5ed4627f02d2375daa651931ff8b
Java
isgrator/MasterListas
/app/src/main/java/org/imgracian/masterlistas/InicioSesionActivity.java
UTF-8
2,435
1.898438
2
[]
no_license
package org.imgracian.masterlistas; import android.app.ActivityOptions; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.ads.MobileAds; import com.google.firebase.analytics.FirebaseAnalytics; public class InicioSesionActivity extends AppCompatActivity { private FirebaseAnalytics analytics; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inicio_sesion); MobileAds.initialize(this,"ca-app-pub-5594373787368665~1826593970"); analytics = FirebaseAnalytics.getInstance(this); } public void loguearCheckbox(View v) { CheckBox recordarme= (CheckBox) findViewById(R.id.recordarme); String s = getResources().getString(R.string.texto_recordar)+": " + (recordarme.isChecked() ? getResources().getString(R.string.si) : getResources().getString(R.string.no)); Toast.makeText(this, s, Toast.LENGTH_LONG).show(); } public void mostrarContraseña(View v) { EditText contraseña = (EditText) findViewById(R.id.contraseña); CheckBox mostrar = (CheckBox) findViewById(R.id.mostrar_contraseña); if (mostrar.isChecked()) { contraseña.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL); } else { contraseña.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } public void acceder (View view){ Bundle param = new Bundle(); param.putString("elemento", "boton inicio sesion MasterListas"); param.putInt("pulsacion_ms",34); analytics.logEvent("butt_acceder", param); Intent intent = new Intent(this, ListasActivity.class); startActivity(intent , ActivityOptions.makeSceneTransitionAnimation(this).toBundle()); } public void borrarCampos(View view){ EditText usuario = (EditText) findViewById(R.id.usuario); EditText contraseña = (EditText) findViewById(R.id.contraseña); usuario.setText(""); contraseña.setText(""); usuario.requestFocus(); } }
true
6363d5f663fb19c6ab86252033c0a74fe1d49ba2
Java
rlaqudrnr810/TopikHelper_Final
/app/src/main/java/com/example/topikhelper/VirtualTestResult.java
UTF-8
1,287
2.578125
3
[]
no_license
package com.example.topikhelper; public class VirtualTestResult { private String questionNum; private String realAnswer; private String myAnswer; private String abcd; public VirtualTestResult(){ } public VirtualTestResult(String questionNum, String realAnswer, String myAnswer) { this.questionNum = questionNum; this.realAnswer = realAnswer; this.myAnswer = myAnswer; } public String getQuestionNum() { return questionNum; } public String getRealAnswer() { return realAnswer; } public String getMyAnswer() { return myAnswer; } public String getText() {return this.abcd;} public void setQuestionNum(String questionNum) { this.questionNum = questionNum; } public void setRealAnswer(String realAnswer) { this.realAnswer = realAnswer; } public void setMyAnswer(String myAnswer) { this.myAnswer = myAnswer; } public void setText(String text){abcd=text;} @Override public String toString() { return "VirtualTestResult{" + "questionNum='" + questionNum + '\'' + ", realAnswer='" + realAnswer + '\'' + ", myAnswer='" + myAnswer + '\'' + '}'; } }
true
a21dc17684374ded53b69072fd0b2a03a9e166cf
Java
KamranMohd/selenium
/src/main/java/com/selenium/pageobjects/AgeCalucationPage.java
UTF-8
1,441
2.703125
3
[]
no_license
package com.selenium.pageobjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class AgeCalucationPage { private WebDriver driver; final private String URL = "https://trainingbypackt.github.io/Beginning-Selenium/lesson_6/exercise_6_1.html"; public AgeCalucationPage(WebDriver driver) { this.driver = driver; } public WebElement getDayOfBirth() { return this.driver.findElement(By.id("dayOfBirth")); } public WebElement getMonthOfBirth() { return this.driver.findElement(By.id("monthOfBirth")); } public WebElement getYearOfBirth() { return this.driver.findElement(By.id("yearOfBirth")); } public WebElement getCalculateBtn() { return this.driver.findElement(By.id("calculate")); } public WebElement getAgeElement() { return this.driver.findElement(By.id("age")); } public WebElement getZodiacSignElement() { return this.driver.findElement(By.id("zodiacSign")); } public void calculate(String day, String month, String year) { this.getDayOfBirth().sendKeys(day); this.getMonthOfBirth().sendKeys(month); this.getYearOfBirth().sendKeys(year); this.getCalculateBtn().click(); } public String getAge() { return getAgeElement().getText(); } public String getZodiacSign() { return getZodiacSignElement().getText(); } public void open() { this.driver.get(URL); } public void close() { this.driver.quit(); } }
true
11a297320410ac9c6c5198d09347f88cd303a8bf
Java
DVRudenko/Restfull-WEB-project
/dao/src/main/java/by/rudenko/imarket/impl/CommentDaoImpl.java
UTF-8
2,968
2.453125
2
[]
no_license
package by.rudenko.imarket.impl; import by.rudenko.imarket.CommentDao; import by.rudenko.imarket.exception.NoSuchIdException; import by.rudenko.imarket.model.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Repository; import javax.persistence.TypedQuery; import javax.persistence.criteria.*; import java.util.List; @Repository public class CommentDaoImpl extends AbstractDao<Comment, Long> implements CommentDao { private static final Logger LOGGER = LogManager.getLogger("imarket"); public CommentDaoImpl() { super(Comment.class); } // список всех Comment без сортировки @Override public List<Comment> getFullComments(int pageNumber, int pageSize) { LOGGER.info("Get full comments list "); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Comment> cq = cb.createQuery(Comment.class); Root<Comment> root = getCommentRoot(cq); CriteriaQuery<Comment> select = cq.select(root); //используем пагинацию TypedQuery<Comment> typedQuery = em.createQuery(select); typedQuery.setFirstResult((pageNumber - 1) * pageSize); typedQuery.setMaxResults(pageSize); return typedQuery.getResultList(); } //внутренний метод сделать Join вложенных полей private Root<Comment> getCommentRoot(CriteriaQuery<Comment> cq) { Root<Comment> root = cq.from(Comment.class); root.fetch(Comment_.user, JoinType.INNER); root.fetch(Comment_.advert, JoinType.INNER); //делаем вложенный fetch 2-го уровня Fetch<Comment, Advert> advRoot = root.fetch(Comment_.advert); Fetch<Advert, User> userRoot = advRoot.fetch(Advert_.user); Fetch<Advert, AdvertTopic> topicRoot = advRoot.fetch(Advert_.advertTopic); Fetch<Advert, AdvertRank> rankRoot = advRoot.fetch(Advert_.advertRank); return root; } //получаем все поля Comment по ID с ленивой инициализацией @Override public Comment getFullCommentByID(final Long id) throws NoSuchIdException { LOGGER.info("Get full comment by Id "); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Comment> cq = cb.createQuery(Comment.class); Root<Comment> root = getCommentRoot(cq); CriteriaQuery<Comment> select = cq.select(root) .where(cb.equal( root.get(Comment_.id), id) ); List<Comment> comment = em.createQuery(select).getResultList(); if (comment.size() > 0) { return comment.get(0); } else { LOGGER.error("No such Comment ID" + id); throw new NoSuchIdException("No such Comment ID" + id); } } }
true
b81002b72a6ced42032ca8cd46bae3bad0c67226
Java
tsuzcx/qq_apk
/com.tencent.mm/classes.jar/com/tencent/mm/protocal/protobuf/cho.java
UTF-8
2,698
1.679688
2
[]
no_license
package com.tencent.mm.protocal.protobuf; import com.tencent.matrix.trace.core.AppMethodBeat; import org.json.JSONObject; public final class cho extends com.tencent.mm.bx.a { public int YYs; public long aanC; public int vhJ; private JSONObject toJSON() { AppMethodBeat.i(259036); JSONObject localJSONObject = new JSONObject(); try { com.tencent.mm.bk.a.a(localJSONObject, "Type", Integer.valueOf(this.vhJ), false); com.tencent.mm.bk.a.a(localJSONObject, "Offset", Integer.valueOf(this.YYs), false); com.tencent.mm.bk.a.a(localJSONObject, "Version", Long.valueOf(this.aanC), false); label55: AppMethodBeat.o(259036); return localJSONObject; } catch (Exception localException) { break label55; } } public final int op(int paramInt, Object... paramVarArgs) { AppMethodBeat.i(117868); if (paramInt == 0) { paramVarArgs = (i.a.a.c.a)paramVarArgs[0]; paramVarArgs.bS(1, this.vhJ); paramVarArgs.bS(2, this.YYs); paramVarArgs.bv(3, this.aanC); AppMethodBeat.o(117868); return 0; } if (paramInt == 1) { paramInt = i.a.a.b.b.a.cJ(1, this.vhJ); int i = i.a.a.b.b.a.cJ(2, this.YYs); int j = i.a.a.b.b.a.q(3, this.aanC); AppMethodBeat.o(117868); return paramInt + 0 + i + j; } if (paramInt == 2) { paramVarArgs = new i.a.a.a.a((byte[])paramVarArgs[0], unknownTagHandler); for (paramInt = com.tencent.mm.bx.a.getNextFieldNumber(paramVarArgs); paramInt > 0; paramInt = com.tencent.mm.bx.a.getNextFieldNumber(paramVarArgs)) { if (!super.populateBuilderWithField(paramVarArgs, this, paramInt)) { paramVarArgs.kFT(); } } AppMethodBeat.o(117868); return 0; } if (paramInt == 3) { i.a.a.a.a locala = (i.a.a.a.a)paramVarArgs[0]; cho localcho = (cho)paramVarArgs[1]; switch (((Integer)paramVarArgs[2]).intValue()) { default: AppMethodBeat.o(117868); return -1; case 1: localcho.vhJ = locala.ajGk.aar(); AppMethodBeat.o(117868); return 0; case 2: localcho.YYs = locala.ajGk.aar(); AppMethodBeat.o(117868); return 0; } localcho.aanC = locala.ajGk.aaw(); AppMethodBeat.o(117868); return 0; } AppMethodBeat.o(117868); return -1; } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes2.jar * Qualified Name: com.tencent.mm.protocal.protobuf.cho * JD-Core Version: 0.7.0.1 */
true
543f1a6fb250589cfe182b69d4fddc03efebd265
Java
jaigupta/java-spring-base
/src/main/java/com/djw/controller/ServicesController.java
UTF-8
503
1.835938
2
[]
no_license
package com.djw.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.djw.web.common.WebResponse; @Controller public class ServicesController { @RequestMapping(value = "/services", method = RequestMethod.GET) public String getService(WebResponse response) { response.setTargetPage("services"); response.getPreparedResponse(); return "landing"; } }
true
f5d798ec8ba0f24bea13a31424a0a6ff470cea94
Java
Lavoiedavidw/Batch-Source
/CoreJavaAssignment/src/main/java/com/revature/question6/Question6.java
UTF-8
695
3.875
4
[]
no_license
package com.revature.question6; import java.util.Scanner; public class Question6 { //Write a program to determine if an integer is even //without using the modulus operator (%) static Scanner input = new Scanner(System.in); static Float number; static int store; public static void even(int a) { number = (float) store; number = number/2; store = store/2; if(number.equals((float) store)) { System.out.println("The integer is even."); }else { System.out.println("The integer is odd."); } } public static void main(String[] args) { System.out.println("Enter number: "); store = input.nextInt(); even(store); } }
true
2fc282b575a33757fab1185bfc51a2264b493730
Java
bolig/huiXiaoBao
/app/src/main/java/com/dhitoshi/xfrs/huixiaobao/Interface/AddClientManage.java
UTF-8
1,396
2.21875
2
[]
no_license
package com.dhitoshi.xfrs.huixiaobao.Interface; import com.dhitoshi.xfrs.huixiaobao.Bean.ClientBean; import com.dhitoshi.xfrs.huixiaobao.Bean.HttpBean; import com.dhitoshi.xfrs.huixiaobao.Bean.InfoAddClientBean; import com.dhitoshi.xfrs.huixiaobao.Dialog.LoadingDialog; import java.util.Map; /** * Created by dxs on 2017/9/8. */ public interface AddClientManage { interface View{ void addClient(HttpBean<ClientBean> httpBean); void editClient(HttpBean<ClientBean> httpBean); void getInfoForAdd(HttpBean<InfoAddClientBean> httpBean); void checkRepeat(String result); } interface Model{ void addClient(Map<String,String> map, LoadingDialog dialog, Callback<HttpBean<ClientBean>> callback); void editClient(Map<String,String> map, LoadingDialog dialog,Callback<HttpBean<ClientBean>> callback); void getInfoForAdd(String token,Callback<HttpBean<InfoAddClientBean>> callback); void checkRepeat(String token,LoadingDialog dialog,String area,String phone,String id,Callback<HttpBean<Object>> callback); } interface Presenter{ void addClient(Map<String,String> map, LoadingDialog dialog); void editClient(Map<String,String> map, LoadingDialog dialog); void getInfoForAdd(String token); void checkRepeat(String token,LoadingDialog dialog,String area,String phone,String id); } }
true
b70c4f588c0a8bf02322f1f299b1ea224510d6f8
Java
djneptulon/frostwire-desktop
/gui/com/limegroup/gnutella/gui/dnd/TorrentFilesTransferHandler.java
UTF-8
2,630
2.1875
2
[]
no_license
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.limegroup.gnutella.gui.dnd; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.File; import java.io.IOException; import javax.swing.JComponent; import com.limegroup.gnutella.gui.GUIMediator; /** * FileTransferHandler that imports drags of local torrent files into frostwire * by starting downloads for them if all files of the drag are torrent files. */ public class TorrentFilesTransferHandler extends LimeTransferHandler { /** * */ private static final long serialVersionUID = 5478003116391589602L; @Override public boolean canImport(JComponent c, DataFlavor[] flavors, DropInfo ddi) { return canImport(c, flavors); } @Override public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { if (DNDUtils.contains(transferFlavors, DataFlavor.javaFileListFlavor) || DNDUtils.contains(transferFlavors, FileTransferable.URIFlavor)) { return true; } return false; } @Override public boolean importData(JComponent c, Transferable t, DropInfo ddi) { return importData(c, t); } @Override public boolean importData(JComponent comp, Transferable t) { if (!canImport(comp, t.getTransferDataFlavors())) return false; try { File[] files = DNDUtils.getFiles(t); if (areAllTorrentFiles(files)) { if (files.length == 1) { GUIMediator.instance().openTorrentFile(files[0], true); } else { for (File file : files) { GUIMediator.instance().openTorrentFile(file, false); } } } } catch (UnsupportedFlavorException e) { } catch (IOException e) { } return false; } // made package private for tests boolean areAllTorrentFiles(File[] files) { for (File file : files) { if (!file.isFile() ||!file.getName().toLowerCase().endsWith(".torrent")) { return false; } } return true; } }
true
90eecf784a05a022c20a060f173c9112b21ee2bc
Java
gurujsprasad/LMSandMore
/src/cs320/finals/EditMeeting.java
UTF-8
3,542
2.359375
2
[]
no_license
package cs320.finals; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/finals/EditMeeting") public class EditMeeting extends HttpServlet { private static final long serialVersionUID = 1L; DBFunctions db = new DBFunctions(); public EditMeeting() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int meetingId = Integer.parseInt(request.getParameter("meetingID")); String query = "select m.meeting_id, d.days, t.time_slot, m.notes from meetings m, timeslots t, days d where m.meeting_id = ? and d.day_id = m.day_id and t.time_slot_id = m.time_slot_id"; ArrayList<FetchMeetingForEditBean> meeting = new ArrayList<FetchMeetingForEditBean>(); try { Class.forName( "com.mysql.jdbc.Driver" ); } catch( ClassNotFoundException e ) { throw new ServletException( e ); } Connection con = db.dbConnection(); ResultSet results; PreparedStatement stmt = null; try { stmt = con.prepareStatement(query); stmt.setInt(1, meetingId); results = stmt.executeQuery(); while (results.next()) { meeting.add(new FetchMeetingForEditBean(results.getInt("meeting_id"), results.getString("days"), results.getString("time_slot"), results.getString("notes"))); } } catch (SQLException e) { e.printStackTrace(); } finally { if(con != null || stmt != null) { try { stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } getServletContext().setAttribute("meeting", meeting); request.getRequestDispatcher("/WEB-INF/jsp/finals/EditMeeting.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int meetingId = Integer.parseInt(request.getParameter("meetingID")); String notes = request.getParameter("notes"); String button = request.getParameter("button"); String query = ""; int flag = 0; if(button.equals("SAVE")) { flag = 1; query = "update meetings set notes = ? where meeting_id = ?"; } if (button.equals("DELETE")) { flag = 2; query = "delete from meetings where meeting_id = ?"; } try { Class.forName( "com.mysql.jdbc.Driver" ); } catch( ClassNotFoundException e ) { throw new ServletException( e ); } Connection con = db.dbConnection(); ResultSet results; PreparedStatement stmt = null; try { stmt = con.prepareStatement(query); if (flag == 1) { stmt.setString(1, notes); stmt.setInt(2, meetingId); } if (flag == 2) { stmt.setInt(1, meetingId); } stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if(con != null || stmt != null) { try { stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } response.sendRedirect("Final"); } }
true
33d17427548c8f99150288b2620e747aaa1ca5aa
Java
afornalik/task1-4
/src/main/java/CardDeck.java
UTF-8
1,987
3.71875
4
[]
no_license
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class CardDeck { public static void main(String[] args) { List<Card> cardList = new ArrayList<>(); for (Color color : Color.values()) { for (Type type : Type.values()) { cardList.add(new Card(color, type)); } } System.out.print("Number of players :"); int numberOfPlayers = new Scanner(System.in).nextInt(); Collections.shuffle(cardList); printPlayersHands(cardList, numberOfPlayers); } private static void printPlayersHands(List<Card> cardList, int numberOfPlayers) { for (int i = 0; i < cardList.size(); i++) { if (i == 0) { for (int j = 1; j <= numberOfPlayers; j++) { System.out.printf("%9s%2s", "player", j); System.out.print(" "); } System.out.println("\n"); } for (int j = 0; j < numberOfPlayers; j++) { if (i + j < cardList.size()) System.out.print(cardList.get(i + j).showCard()); } System.out.println(); i += (numberOfPlayers - 1); } } private static class Card { private final Color color; private final Type type; private Card(Color color, Type type) { this.color = color; this.type = type; } private String showCard() { return String.format("|%4s%10s|", color.mark, type); } } private enum Color { CLUBS("\u2663"), DIAMONDS("\u2666"), HEARTS("\u2665"), SPADES("\u2660"); private String mark; Color(String mark) { this.mark = mark; } } private enum Type { NINE, TEN, JACK, QUEEN, KING, ACE } }
true
d529029ee7f8ae76ae762e9437f6021eeea69cdc
Java
yourvid/syncserver
/src/main/java/com/cmf/domain/CoreBdEquipModel.java
UTF-8
5,778
2.078125
2
[]
no_license
package com.cmf.domain; import javax.persistence.*; import java.sql.Timestamp; import java.util.Objects; @Entity @Table(name = "core_bd_equip_model") public class CoreBdEquipModel { private long ID; private String equipModelId; private String equipModelName; private String equipTypeId; private String equipDigest; private String equipDesc; private String equipImage; private Double equipPrice; private String equipFunc; private String equipScen; private Integer status; private Long factoryId; private Timestamp upTime; private Timestamp downTime; private String downReason; private Integer modelType; @Id @Column(name = "ID", nullable = false) public long getId() { return ID; } public void setId(long ID) { this.ID = ID; } @Basic @Column(name = "EquipModelID", nullable = false, length = 64) public String getEquipModelId() { return equipModelId; } public void setEquipModelId(String equipModelId) { this.equipModelId = equipModelId; } @Basic @Column(name = "EquipModelName", nullable = true, length = 32) public String getEquipModelName() { return equipModelName; } public void setEquipModelName(String equipModelName) { this.equipModelName = equipModelName; } @Basic @Column(name = "EquipTypeID", nullable = true, length = 16) public String getEquipTypeId() { return equipTypeId; } public void setEquipTypeId(String equipTypeId) { this.equipTypeId = equipTypeId; } @Basic @Column(name = "EquipDigest", nullable = true, length = 100) public String getEquipDigest() { return equipDigest; } public void setEquipDigest(String equipDigest) { this.equipDigest = equipDigest; } @Basic @Column(name = "EquipDesc", nullable = true, length = 500) public String getEquipDesc() { return equipDesc; } public void setEquipDesc(String equipDesc) { this.equipDesc = equipDesc; } @Basic @Column(name = "EquipImage", nullable = true, length = 500) public String getEquipImage() { return equipImage; } public void setEquipImage(String equipImage) { this.equipImage = equipImage; } @Basic @Column(name = "EquipPrice", nullable = true, precision = 2) public Double getEquipPrice() { return equipPrice; } public void setEquipPrice(Double equipPrice) { this.equipPrice = equipPrice; } @Basic @Column(name = "EquipFunc", nullable = true, length = 5000) public String getEquipFunc() { return equipFunc; } public void setEquipFunc(String equipFunc) { this.equipFunc = equipFunc; } @Basic @Column(name = "EquipScen", nullable = true, length = 5000) public String getEquipScen() { return equipScen; } public void setEquipScen(String equipScen) { this.equipScen = equipScen; } @Basic @Column(name = "Status", nullable = true) public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Basic @Column(name = "FactoryID", nullable = true) public Long getFactoryId() { return factoryId; } public void setFactoryId(Long factoryId) { this.factoryId = factoryId; } @Basic @Column(name = "UpTime", nullable = true) public Timestamp getUpTime() { return upTime; } public void setUpTime(Timestamp upTime) { this.upTime = upTime; } @Basic @Column(name = "DownTime", nullable = true) public Timestamp getDownTime() { return downTime; } public void setDownTime(Timestamp downTime) { this.downTime = downTime; } @Basic @Column(name = "DownReason", nullable = true, length = 255) public String getDownReason() { return downReason; } public void setDownReason(String downReason) { this.downReason = downReason; } @Basic @Column(name = "ModelType", nullable = true) public Integer getModelType() { return modelType; } public void setModelType(Integer modelType) { this.modelType = modelType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CoreBdEquipModel that = (CoreBdEquipModel) o; return ID == that.ID && Objects.equals(equipModelId, that.equipModelId) && Objects.equals(equipModelName, that.equipModelName) && Objects.equals(equipTypeId, that.equipTypeId) && Objects.equals(equipDigest, that.equipDigest) && Objects.equals(equipDesc, that.equipDesc) && Objects.equals(equipImage, that.equipImage) && Objects.equals(equipPrice, that.equipPrice) && Objects.equals(equipFunc, that.equipFunc) && Objects.equals(equipScen, that.equipScen) && Objects.equals(status, that.status) && Objects.equals(factoryId, that.factoryId) && Objects.equals(upTime, that.upTime) && Objects.equals(downTime, that.downTime) && Objects.equals(downReason, that.downReason) && Objects.equals(modelType, that.modelType); } @Override public int hashCode() { return Objects.hash(ID, equipModelId, equipModelName, equipTypeId, equipDigest, equipDesc, equipImage, equipPrice, equipFunc, equipScen, status, factoryId, upTime, downTime, downReason, modelType); } }
true
38d3ac371021a6bb70641e19dd918215228507f3
Java
LittleLuckYK/SimpleExample
/src/test/java/org/caesar/example/TestCreateSign.java
UTF-8
707
2.15625
2
[]
no_license
package org.caesar.example; import org.springframework.http.ResponseEntity; import org.testng.annotations.Test; import org.caesar.example.utils.CreateSign; import org.springframework.web.client.RestTemplate; public class TestCreateSign { @Test public void testSign() { System.out.println(new CreateSign().sign("hey girl")); } @Test public void testGet() { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://10.130.210.87:8844/system/version", String.class); System.out.println(responseEntity); System.out.println(responseEntity.getStatusCode().value()); } }
true
538691cb225549999815328baeb4c72f123fdc32
Java
samkeeleyong/simple-distributed-server
/src/com/server/Gateway.java
UTF-8
6,776
2.421875
2
[]
no_license
package com.server; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.http.gateway.GatewayRedirectHandler; import com.http.gateway.ListFilesHandler; import com.http.gateway.MainHandler; import com.http.gateway.UploadDoneHandler; import com.http.gateway.UploadPageHandler; import com.http.gateway.UploadToGatewayHandler; import com.sun.net.httpserver.HttpServer; import com.util.Constants; import com.util.SftpChannel; import com.util.SftpService; public class Gateway { private static final long REPLICATOR_DELAY = 5; private static final long REPLICATOR_ITERATION_RATE = 25; private static final ScheduledExecutorService REPLICATOR_EXECUTOR= Executors.newSingleThreadScheduledExecutor(); private static final Executor FILE_WATCHER_EXECUTOR= Executors.newSingleThreadExecutor(); public static void main(String[] args) throws IOException { System.out.println("Gateway is running."); System.out.println("Gateway HTTP server is running"); new Thread(new GatewayHttpServer()).start(); System.out.println("Gateway Replicator is running."); REPLICATOR_EXECUTOR.scheduleAtFixedRate(new Replicator(), REPLICATOR_DELAY, REPLICATOR_ITERATION_RATE, TimeUnit.SECONDS); System.out.println("Gateway New File Watcher is running.\n"); FILE_WATCHER_EXECUTOR.execute(new NewFileWatcher()); try (ServerSocket listener = new ServerSocket(Constants.SERVER_SOCKET_PORT);) { while (true) { new Thread(new NodeChannelThread(listener.accept())).start(); } } } /* * @desc This is the single direct communication * between the gateway and a node. * @message SENDFILE - order a node to send a file to another node. * */ private static class NodeChannelThread implements Runnable { private Socket socket; private BufferedReader in; // to receive messages private PrintWriter printWriter; // to send messages private String nodeName; public NodeChannelThread(Socket socket) { this.socket = socket; } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); printWriter = new PrintWriter(socket.getOutputStream(), true); String[] registerDetails = in.readLine().split(","); System.out.println(registerDetails[1] + " has joined the cluster."); NodeRegistry.register(registerDetails[1], new SftpDetails(registerDetails[2], Long.parseLong(registerDetails[3]), registerDetails[4], registerDetails[5]), printWriter, registerDetails[6], Integer.parseInt(registerDetails[7]), registerDetails[8]); nodeName = registerDetails[1]; while (true) { String input = in.readLine(); if (input.startsWith("CONFIRMTASK")) { String nodeName = input.split(",")[1]; NodeRegistry.confirmFinishTask(nodeName); } } } catch (NullPointerException | SocketException npe) { System.out.println("Gateway:" + nodeName + " just died!"); NodeRegistry.setDead(nodeName); } catch (IOException e) { System.out.println(e); } finally { try { socket.close(); } catch (IOException e) { } } } } private static class GatewayHttpServer implements Runnable{ @Override public void run() { System.out.println("HTTP Gateway is running."); HttpServer server = null; try { server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/mainPage", new MainHandler()); //main page server.createContext("/listFiles", new ListFilesHandler()); //list of files to download server.createContext("/uploadFile", new UploadPageHandler()); //upload Page server.createContext("/upload", new UploadToGatewayHandler()); //upload Page server.createContext("/uploadDone", new UploadDoneHandler()); //upload Page server.createContext("/get", new GatewayRedirectHandler()); //redirect } catch (IOException e) { e.printStackTrace(); } server.setExecutor(Executors.newCachedThreadPool()); // creates a default executor server.start(); } } private static class NewFileWatcher implements Runnable { Path gatewayPath = Paths.get(Constants.GATEWAY_DIRECTORY); WatchService fileWatcher; @Override public void run() { try { fileWatcher = gatewayPath.getFileSystem().newWatchService(); gatewayPath.register(fileWatcher, ENTRY_CREATE); // get the first event before looping WatchKey key = fileWatcher.take(); while(key != null) { // we have a polled event, now we traverse it and // receive all the states from it for (WatchEvent<?> event : key.pollEvents()) { System.out.printf("Received uploaded file: %s\n", event.context() ); // send file to random node if (!NodeRegistry.listEntries().isEmpty()) { NodeRegistry.NodeEntry randomNode = NodeRegistry.getRandomNode(); String filename = ((Path)event.context()).toString(); System.out.println("SFTP Service: sending new file " + filename + " to " + randomNode.nodeName); SftpService.sendFile(randomNode.sftpDetails.host, (int)randomNode.sftpDetails.port, randomNode.sftpDetails.username, randomNode.sftpDetails.password, randomNode.nodeName, filename, SftpChannel.GATEWAY, randomNode.nodeContextPath); randomNode.filenames.add(filename); } } key.reset(); key = fileWatcher.take(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Stop Watching"); } } }
true
bd03b3615c33b9c45b6bd6450591562137907fa5
Java
Zyro9922/Synergy
/app/src/main/java/com/example/alihasan/synergytwo/api/service/Client.java
UTF-8
11,736
1.585938
2
[]
no_license
package com.example.alihasan.synergytwo.api.service; import com.example.alihasan.synergytwo.api.model.Debtor; import java.util.List; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; public interface Client { @POST("authorize.php") @FormUrlEncoded Call<String> getAuth(@Field("USERNAME") String ID, @Field("PASSWORD") String PASS); @POST("logout.php") @FormUrlEncoded Call<String> logout(@Field("USERNAME") String ID); @POST("fetchcases.php") @FormUrlEncoded Call<List<Debtor>> getDebtors(@Field("PDANO") String ID); @POST("deleteimage.php") @FormUrlEncoded Call<String> deleteImage(@Field("NAME") String ID); @POST("addtotable.php") @FormUrlEncoded Call<String> sendBusinessData(@Field("TABLENAME") String TABLENAME, @Field("CASENO") String CASENO, @Field("ADDRESS") String ADDRESS, @Field("EASELOCATE") String EASELOCATE, @Field("OFFICEOWNERSHIP") String OFFICEOWNERSHIP, @Field("APPLCOMPANYNAME") String APPLCOMPANYNAME, @Field("LOCALITYTYPE") String LOCALITYTYPE, @Field("NATUREBUSNIESS") String NATUREBUSNIESS, @Field("APPLDESIGNATION") String APPLDESIGNATION, @Field("WORKINGSINCE") String WORKINGSINCE, @Field("PERSONCONTACTED") String PERSONCONTACTED, @Field("PERSONDESIGNATION") String PERSONDESIGNATION, @Field("NOSEMP") String NOSEMP, @Field("LANDMARK") String LANDMARK, @Field("NOSBRANCHES") String NOSBRANCHES, @Field("BUSINESSSETUP") String BUSINESSSETUP, @Field("BUSINESSBOARD") String BUSINESSBOARD, @Field("NOSYEARSATADDRESS") String NOSYEARSATADDRESS, @Field("VISITINGCARD") String VISITINGCARD, @Field("APPLNAMEVERIFFROM") String APPLNAMEVERIFFROM, @Field("CONTACTVERIF1") String CONTACTVERIF1, @Field("CONTACTVERIF2") String CONTACTVERIF2, @Field("CONTACTFEEDBACK") String CONTACTFEEDBACK, @Field("PROOFDETAILS") String PROOFDETAILS, @Field("POLITICALLINK") String POLITICALLINK, @Field("OVERALLSTATUS") String OVERALLSTATUS, @Field("REASONNEGATIVEFI") String REASONNEGATIVEFI, @Field("LATITUDE") String LATITUDE, @Field("LONGITUDE") String LONGITUDE, @Field("REMARKS") String REMARKS); @POST("addtotable.php") @FormUrlEncoded Call<String> sendPropertyData(@Field("TABLENAME") String TABLENAME, @Field("CASENO") String CASENO, @Field("ADDRESS") String ADDRESS, @Field("EASELOCATE") String EASELOCATE, @Field("PERSONCONTACTED") String PERSONCONTACTED, @Field("RELATIONSHIP") String RELATIONSHIP, @Field("PROPERTYTYPE") String PROPERTYTYPE, @Field("NOSYEARSOWNER") String NOSYEARSOWNER, @Field("AREA") String AREA, @Field("DOCSVERIF") String DOCSVERIF, @Field("NEIGHBOURNAME1") String NEIGHBOURNAME1, @Field("ADDRESS1") String ADDRESS1, @Field("NEIGHBOURNAME2") String NEIGHBOURNAME2, @Field("ADDRESS2") String ADDRESS2, @Field("PROPERTYSOLDTO") String PROPERTYSOLDTO, @Field("PURCHASERDETAILS") String PURCHASERDETAILS, @Field("APPLCOOPERATIVE") String APPLCOOPERATIVE, @Field("NEIGHBOURFEEDBACK") String NEIGHBOURFEEDBACK, @Field("LOCALITYTYPE") String LOCALITYTYPE, @Field("AMBIENCE") String AMBIENCE, @Field("APPLSTAYATADDRESS") String APPLSTAYATADDRESS, @Field("VEHICLESEEN") String VEHICLESEEN, @Field("POLITICALLINK") String POLITICALLINK, @Field("OVERALLSTATUS") String OVERALLSTATUS, @Field("REASONNEGATIVEFI") String REASONNEGATIVEFI, @Field("LATITUDE") String LATITUDE, @Field("LONGITUDE") String LONGITUDE, @Field("REMARKS") String REMARKS); @POST("addtotable.php") @FormUrlEncoded Call<String> sendResidenceData(@Field("TABLENAME") String TABLENAME, @Field("CASENO") String CASENO, @Field("ADDRESS") String ADDRESS, @Field("EASELOCATE") String EASELOCATE, @Field("AGE") String AGE, @Field("LOCALITYTYPE") String LOCALITYTYPE, @Field("HOUSETYPE") String HOUSETYPE, @Field("HOUSECONDITION") String HOUSECONDITION, @Field("OWNERSHIP") String OWNERSHIP, @Field("LIVINGSTANDARD") String LIVINGSTANDARD, @Field("LANDMARK") String LANDMARK, @Field("STAYINGSINCE") String STAYINGSINCE, @Field("APPLSTAYATADDRESS") String APPLSTAYATADDRESS, @Field("PERSONCONTACTED") String PERSONCONTACTED, @Field("RELATIONSHIP") String RELATIONSHIP, @Field("ACCOMODATIONTYPE") String ACCOMODATIONTYPE, @Field("EXTERIOR") String EXTERIOR, @Field("NOOFFAMILY") String NOOFFAMILY, @Field("WORKING") String WORKING, @Field("DEPENDENTADULTS") String DEPENDENTADULTS, @Field("DEPENDENTCHILDREN") String DEPENDENTCHILDREN, @Field("RETIREDMEMBER") String RETIREDMEMBER, @Field("SPOUSEEARNING") String SPOUSEEARNING, @Field("SPOUSEDETAILS") String SPOUSEDETAILS, @Field("MARITALSTATUS") String MARITALSTATUS, @Field("EDUQUAL") String EDUQUAL, @Field("NEIGHBOURNAME1") String NEIGHBOURNAME1, @Field("ADDRESS1") String ADDRESS1, @Field("NEIGHBOURNAME2") String NEIGHBOURNAME2, @Field("ADDRESS2") String ADDRESS2, @Field("NEIGHBOURFEEDBACK") String NEIGHBOURFEEDBACK, @Field("PROOFDETAILS") String PROOFDETAILS, @Field("VEHICLESEEN") String VEHICLESEEN, @Field("POLITICALLINK") String POLITICALLINK, @Field("OVERALLSTATUS") String OVERALLSTATUS, @Field("REASONNEGATIVEFI") String REASONNEGATIVEFI, @Field("LATITUDE") String LATITUDE, @Field("LONGITUDE") String LONGITUDE, @Field("REMARKS") String REMARKS); @POST("addtotable.php") @FormUrlEncoded Call<String> sendEmploymentData(@Field("TABLENAME") String TABLENAME, @Field("CASENO") String CASENO, @Field("ADDRESS") String ADDRESS, @Field("EASELOCATE") String EASELOCATE, @Field("APPLCOMPANYNAME") String APPLCOMPANYNAME, @Field("LOCALITYTYPE") String LOCALITYTYPE, @Field("ADDRESSCONF") String ADDRESSCONF, @Field("LANDMARK") String LANDMARK, @Field("APPLDESIGNATION") String APPLDESIGNATION, @Field("PERSONMET") String PERSONMET, @Field("PERSONDESIGNATION") String PERSONDESIGNATION, @Field("PERSONCONTACT") String PERSONCONTACT, @Field("DOESAPPLWORK") String DOESAPPLWORK, @Field("OFFICETEL") String OFFICETEL, @Field("OFFICEBOARD") String OFFICEBOARD, @Field("ORGANISATIONTYPE") String ORGANISATIONTYPE, @Field("DOJ") String DOJ, @Field("VISITINGCARD") String VISITINGCARD, @Field("NATUREBUSNIESS") String NATUREBUSNIESS, @Field("JOBTYPE") String JOBTYPE, @Field("WORKINGAS") String WORKINGAS, @Field("JOBTRANSFER") String JOBTRANSFER, @Field("NOSEMP") String NOSEMP, @Field("PERSONCONTACTED") String PERSONCONTACTED, @Field("PERSONCONDESIGNATION") String PERSONCONDESIGNATION, @Field("MANAGER") String MANAGER, @Field("MANAGERDESIGNATION") String MANAGERDESIGNATION, @Field("MANAGERCONTACT") String MANAGERCONTACT, @Field("SALARY") String SALARY, @Field("TPCCONFIRM") String TPCCONFIRM, @Field("TPCNAME") String TPCNAME, @Field("OVERALLSTATUS") String OVERALLSTATUS, @Field("REASONNEGATIVEFI") String REASONNEGATIVEFI, @Field("LATITUDE") String LATITUDE, @Field("LONGITUDE") String LONGITUDE, @Field("REMARKS") String REMARKS); @POST("imageupload.php") @FormUrlEncoded Call<String> imageUpload(@Field("IMAGE") String image, @Field("NAME") String imageName, @Field("CASENO") String caseNo, @Field("CASETYPE") String PASS, @Field("PDANO") String pdaNo); @POST("exitcase.php") @FormUrlEncoded Call<String> exit(@Field("CASENO") String ID, @Field("CASETYPE") String PASS); }
true
5db2677036b0075222eae027c4a9ad9313756bab
Java
an1s1a/movies
/app/src/main/java/com/architecture/movies/data/local/entity/PageEntity.java
UTF-8
1,456
2.328125
2
[]
no_license
package com.architecture.movies.data.local.entity; import android.arch.persistence.room.Entity; import android.arch.persistence.room.Ignore; import android.arch.persistence.room.PrimaryKey; import java.util.List; @Entity public class PageEntity { @PrimaryKey(autoGenerate = true) private int id; private int page; private int total_results; private int total_pages; @Ignore private List<MovieEntity> results; @Ignore public PageEntity() { } public PageEntity(int id, int page, int total_results, int total_pages) { this.id = id; this.page = page; this.total_results = total_results; this.total_pages = total_pages; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getTotal_results() { return total_results; } public void setTotal_results(int total_results) { this.total_results = total_results; } public int getTotal_pages() { return total_pages; } public void setTotal_pages(int total_pages) { this.total_pages = total_pages; } public List<MovieEntity> getResults() { return results; } public void setResults(List<MovieEntity> results) { this.results = results; } }
true
e580b5c60a10075248b994f14697085d40ff24fe
Java
jairof/proyecto
/src/main/java/com/proyecto/Tg000008.java
UTF-8
4,128
2.046875
2
[]
no_license
package com.proyecto; import org.hibernate.validator.constraints.*; import java.util.Date; import javax.persistence.*; import javax.validation.constraints.*; /** * @author Zathura Code Generator http://zathuracode.org * www.zathuracode.org * */ @Entity @Table(name = "tg000008", schema = "${schema}") public class Tg000008 implements java.io.Serializable { @NotNull private Tg000008Id id; @NotNull private Tg000001 tg000001; @NotNull private Tg000003 tg000003; private Integer chequeActivo; private Integer chequeUltimo; private Integer chequeprimer; @NotNull @NotEmpty @Size(max = 255) private String consignacionClientes; private Integer ncheques; @NotNull @NotEmpty @Size(max = 100) private String numcuenta; private String tipoCuenta; public Tg000008() { } public Tg000008(Tg000008Id id, Integer chequeActivo, Integer chequeUltimo, Integer chequeprimer, String consignacionClientes, Integer ncheques, String numcuenta, Tg000001 tg000001, Tg000003 tg000003, String tipoCuenta) { this.id = id; this.tg000001 = tg000001; this.tg000003 = tg000003; this.chequeActivo = chequeActivo; this.chequeUltimo = chequeUltimo; this.chequeprimer = chequeprimer; this.consignacionClientes = consignacionClientes; this.ncheques = ncheques; this.numcuenta = numcuenta; this.tipoCuenta = tipoCuenta; } @EmbeddedId @AttributeOverrides({@AttributeOverride(name = "codCuenta",column = @Column(name = "cod_cuenta",nullable = false) ) , @AttributeOverride(name = "codEmpresa",column = @Column(name = "cod_empresa",nullable = false) ) }) public Tg000008Id getId() { return this.id; } public void setId(Tg000008Id id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "cod_banco") public Tg000001 getTg000001() { return this.tg000001; } public void setTg000001(Tg000001 tg000001) { this.tg000001 = tg000001; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "cod_empresa", insertable = false, updatable = false) public Tg000003 getTg000003() { return this.tg000003; } public void setTg000003(Tg000003 tg000003) { this.tg000003 = tg000003; } @Column(name = "cheque_activo") public Integer getChequeActivo() { return this.chequeActivo; } public void setChequeActivo(Integer chequeActivo) { this.chequeActivo = chequeActivo; } @Column(name = "cheque_ultimo") public Integer getChequeUltimo() { return this.chequeUltimo; } public void setChequeUltimo(Integer chequeUltimo) { this.chequeUltimo = chequeUltimo; } @Column(name = "chequeprimer") public Integer getChequeprimer() { return this.chequeprimer; } public void setChequeprimer(Integer chequeprimer) { this.chequeprimer = chequeprimer; } @Column(name = "consignacion_clientes", nullable = false) public String getConsignacionClientes() { return this.consignacionClientes; } public void setConsignacionClientes(String consignacionClientes) { this.consignacionClientes = consignacionClientes; } @Column(name = "ncheques") public Integer getNcheques() { return this.ncheques; } public void setNcheques(Integer ncheques) { this.ncheques = ncheques; } @Column(name = "numcuenta", nullable = false) public String getNumcuenta() { return this.numcuenta; } public void setNumcuenta(String numcuenta) { this.numcuenta = numcuenta; } @Column(name = "tipo_cuenta") public String getTipoCuenta() { return this.tipoCuenta; } public void setTipoCuenta(String tipoCuenta) { this.tipoCuenta = tipoCuenta; } }
true
0bdcc72889087f292faa7e0b9a94b80409eca6d2
Java
Zeejfps/Simple-Javafx-Video-Player
/src/videoplayer/views/VideoGridPane.java
UTF-8
6,854
2.859375
3
[]
no_license
package videoplayer.views; import javafx.animation.ParallelTransition; import javafx.animation.TranslateTransition; import javafx.geometry.Rectangle2D; import javafx.scene.layout.Pane; import javafx.stage.Screen; import javafx.util.Duration; import videoplayer.App; import videoplayer.model.Video; /** * Created by zeejfps on 7/6/2017. */ public class VideoGridPane extends Pane { public static final Duration TRANSITION_DURATION = Duration.millis(500); private Video[] videos; private int rows, columns; private int rowsPadded, columnsPadded; private double cellWidth, cellHeight; private VideoImagePane[][] children; public void showVideos(int rows, int cols, Video[] videos) { this.videos = videos; this.rows = rows; this.columns = cols; rowsPadded = rows+2; columnsPadded = cols+2; calculateCellSize(); children = new VideoImagePane[rowsPadded][columnsPadded]; for (int i = 0; i < rowsPadded; i++) { for (int j = 0; j < columnsPadded; j++) { Video video = videos[App.R.nextInt(videos.length)]; addVideoImagePane(new VideoImagePane(video), i, j); } } requestLayout(); } public void addVideoImagePane(VideoImagePane videoImagePane, int row, int col) { videoImagePane.setMinSize(cellWidth, cellHeight); videoImagePane.setMaxSize(cellWidth, cellHeight); children[row][col] = videoImagePane; getChildren().add(videoImagePane); } public VideoImagePane getChild(int row, int col) { return children[row][col]; } private void calculateCellSize() { // Get the screen bounds Rectangle2D bounds = Screen.getPrimary().getBounds(); // Calculate the width and height of each video pane cellWidth = bounds.getWidth() / columns; cellHeight = bounds.getHeight() / rows; } public void translateRowLeft() { int row = App.R.nextInt(rows) + 1; ParallelTransition pt = new ParallelTransition(); for (int i = 0; i < columnsPadded; i++) { VideoImagePane pane = getChild(row, i); TranslateTransition tt = new TranslateTransition(TRANSITION_DURATION, pane); tt.setToX(-cellWidth); pt.getChildren().add(tt); } pt.setOnFinished(event -> { VideoImagePane[] newRow = new VideoImagePane[columnsPadded]; for (int j = 0; j < columnsPadded; j++) { int x = j - 1; if (x < 0) x = columnsPadded-1; VideoImagePane child = getChild(row, j); child.setTranslateX(0); newRow[x] = child; } for (int j = 0; j < columnsPadded; j++) { if (j == 0 || j == columnsPadded-1) { newRow[j].setVideo(videos[App.R.nextInt(videos.length)]); } children[row][j] = newRow[j]; } requestLayout(); }); pt.play(); } public void translateRowRight() { int row = App.R.nextInt(rows) + 1; ParallelTransition pt = new ParallelTransition(); for (int i = 0; i < columnsPadded; i++) { VideoImagePane pane = getChild(row, i); TranslateTransition tt = new TranslateTransition(TRANSITION_DURATION, pane); tt.setToX(cellWidth); pt.getChildren().add(tt); } pt.setOnFinished(event -> { VideoImagePane[] newRow = new VideoImagePane[columnsPadded]; for (int j = 0; j < columnsPadded; j++) { int x = j + 1; if (x >= columnsPadded) x = 0; VideoImagePane child = getChild(row, j); child.setTranslateX(0); newRow[x] = child; } for (int j = 0; j < columnsPadded; j++) { if (j == 0 || j == columnsPadded-1) { newRow[j].setVideo(videos[App.R.nextInt(videos.length)]); } children[row][j] = newRow[j]; } requestLayout(); }); pt.play(); } public void translateColDown() { int col = App.R.nextInt(columns) + 1; ParallelTransition pt = new ParallelTransition(); for (int i = 0; i < rowsPadded; i++) { VideoImagePane pane = getChild(i, col); TranslateTransition tt = new TranslateTransition(TRANSITION_DURATION, pane); tt.setToY(cellHeight); pt.getChildren().add(tt); } pt.setOnFinished(event -> { VideoImagePane[] newCol = new VideoImagePane[rowsPadded]; for (int j = 0; j < rowsPadded; j++) { int y = j + 1; if (y >= rowsPadded) y = 0; newCol[y] = getChild(j, col);; } for (int j = 0; j < rowsPadded; j++) { if (j == 0 || j == rowsPadded-1) { newCol[j].setVideo(videos[App.R.nextInt(videos.length)]); } newCol[j].setTranslateY(0.0); children[j][col] = newCol[j]; } requestLayout(); }); pt.play(); } public void translateColUp() { int col = App.R.nextInt(columns) + 1; ParallelTransition pt = new ParallelTransition(); for (int i = 0; i < rowsPadded; i++) { VideoImagePane pane = getChild(i, col); TranslateTransition tt = new TranslateTransition(TRANSITION_DURATION, pane); tt.setToY(-cellHeight); pt.getChildren().add(tt); } pt.setOnFinished(event -> { VideoImagePane[] newCol = new VideoImagePane[rowsPadded]; for (int j = 0; j < rowsPadded; j++) { int y = j - 1; if (y < 0) y = rowsPadded-1; newCol[y] = getChild(j, col); } for (int j = 0; j < rowsPadded; j++) { if (j == 0 || j == rowsPadded-1) { newCol[j].setVideo(videos[App.R.nextInt(videos.length)]); } newCol[j].setTranslateY(0.0); children[j][col] = newCol[j]; } requestLayout(); }); pt.play(); } @Override protected void layoutChildren() { if (children == null) return; int y = -1; for (int i = 0; i < rowsPadded; i++, y++) { int x = -1; for (int j = 0; j < columnsPadded; j++, x++) { VideoImagePane child = children[i][j]; child.resizeRelocate(x*cellWidth, y*cellHeight, cellWidth, cellHeight); } } } public VideoImagePane[][] getVideoPanes() { return children; } }
true
e63779c8681c55cfa628ec57867f6e753a404c18
Java
KorvaNikhilKumar13/interviewprogramm
/src/main/java/com/nikhil/interviewprogramm/ReverseString.java
UTF-8
379
3.625
4
[]
no_license
package com.nikhil.interviewprogramm; public class ReverseString { public static void main(String[] args) { String str ="Java World"; reverseString(str); } public static void reverseString(String str) { char [] ch =str.toCharArray(); for (int i=ch.length-1;i>= 0; i--) { System.out.print("The Reverse of the String is " +ch[i]); } } }
true
6cd0582bbe73e8bf50d75037b3a90e424939dade
Java
grozhd/activeSMT3
/src/edu/stanford/nlp/mt/base/PositionIndependentDistance.java
UTF-8
2,613
3.25
3
[]
no_license
package edu.stanford.nlp.mt.base; import java.util.Hashtable; import edu.stanford.nlp.util.Characters; /** Find the (Levenshtein) Position Independent edit distance between two Strings or Character * arrays. * @author Ankush Singla */ public class PositionIndependentDistance { //final boolean allowTranspose;// check what it should do protected double score; public PositionIndependentDistance() { } // CONSTRAINT SEMIRING START protected double unit() { return 1.0; } protected int smaller(int x, int y) { if (x < y) { return x; } return y; } // CONSTRAINT SEMIRING END // COST FUNCTION BEGIN protected double insertCost() { return unit(); } protected double deleteCost() { return unit(); } protected double substituteCost() { return unit(); } double score(Object[] source, int sPos, Object[] target, int tPos) { Hashtable<Object, Integer> hashSource = new Hashtable<Object, Integer>(sPos); int currentPos; int match = 0; int insertions = 0; int deletions = 0; int substitutions = 0; for(currentPos = 0; currentPos < sPos; currentPos++){ int countOfWord = 1; if(hashSource.containsKey(source[currentPos])){ countOfWord = hashSource.get(source[currentPos]) + 1; } hashSource.put(source[currentPos],countOfWord); } for(currentPos = 0; currentPos < tPos; currentPos++){ if(hashSource.containsKey(target[currentPos]) && (hashSource.get(target[currentPos]) > 0)){ hashSource.put(target[currentPos],hashSource.get(target[currentPos]) - 1); match++; } } substitutions = smaller(sPos - match, tPos - match); if(sPos > tPos){ deletions = sPos-tPos; }else{ insertions = tPos -sPos; } score = substitutions * substituteCost() + deletions * deleteCost() + insertions * insertCost(); return score; } public double score(Object[] source, Object[] target) { return score(source, source.length, target, target.length); } public double score(String sourceStr, String targetStr) { Object[] source = Characters.asCharacterArray(sourceStr); Object[] target = Characters.asCharacterArray(targetStr); return score(source, source.length, target, target.length); } public static void main(String[] args) { if (args.length >= 2) { PositionIndependentDistance d = new PositionIndependentDistance(); System.out.println(d.score(args[0], args[1])); } else { System.err.println("usage: java PositionIndependentDistance str1 str2"); } } }
true
2d9c2a36e74b145226689b278b8ad3fe86ada801
Java
AsliUral/search-and-sort-algorithms-java
/java/InsertionSort.java
UTF-8
916
3.921875
4
[]
no_license
import java.util.*; public class InsertionSort{ public void sort(int array[]){ int n = array.length; for (int i = 1; i < n; ++i) { int key = array[i]; int j = i - 1; while (j >= 0 && array[j] > key) { array[j + 1] = array[j]; j = j - 1; } array[j + 1] = key; } } public static void main(String[]args){ InsertionSort example = new InsertionSort(); int array[] = {13,24,9,12}; System.out.println("array before sort: "); for(int i=0;i<array.length;i++) System.out.print(array[i]+" "); System.out.println(); example.sort(array); System.out.println("array after sort: "); for(int i=0;i<array.length;i++) System.out.print(array[i]+" "); System.out.println(); } }
true
cac2fc0d118b45e944285fe6e1a2b910888d87a0
Java
siemen-devos-123/A-Star-pathfinding
/src/main/java/domain/pathfinding/AStarSolver.java
UTF-8
5,077
3.375
3
[]
no_license
package domain.pathfinding; import domain.maze.Cell; import domain.maze.Maze; import domain.maze.Position; import domain.maze.Walls; import java.util.*; import java.util.stream.Collectors; public class AStarSolver { private Maze maze; private Position start; private Position end; private Position current; private Map<Cell, CellScore> cellScores; public AStarSolver(Maze maze, Position start, Position end) { this.maze = maze; this.start = start; this.end = end; this.current = start; this.cellScores = new HashMap<>(); } public Path solve(){ calculateCellScoresToEnd(); return calculatePath(); } private Path calculatePath() { Path path = new Path(); while(!current.equals(start)){ Cell currentCell = maze.getCellByPosition(current); path.addToStart(current); List<Position> possibleSteps = new LinkedList<>(); if(!currentCell.getWalls().contains(Walls.NORTH)){ possibleSteps.add(new Position(current.getX(), current.getY() - 1)); } if(!currentCell.getWalls().contains(Walls.EAST)){ possibleSteps.add(new Position(current.getX() + 1, current.getY())); } if(!currentCell.getWalls().contains(Walls.SOUTH)){ possibleSteps.add(new Position(current.getX(), current.getY() + 1)); } if(!currentCell.getWalls().contains(Walls.WEST)){ possibleSteps.add(new Position(current.getX() - 1, current.getY())); } possibleSteps = possibleSteps.stream().filter((step) -> !path.contains(step)).collect(Collectors.toList()); Cell min = maze.getCellByPosition(possibleSteps.get(0)); for (Position step : possibleSteps){ Cell cell = maze.getCellByPosition(step); if(cellScores.containsKey(cell) && cellScores.containsKey(min) && !path.contains(step)){ if(cellScores.get(min).getGCost() > cellScores.get(cell).getGCost()){ min = cell; } } } current = min.getPosition(); } path.addToStart(start); return path; } private void calculateCellScoresToEnd(){ setStartCellScore(); while(!current.equals(end)){ calculateNeighbors(); calculateNextPosition(); } } private void setStartCellScore(){ Cell startCell = maze.getCellByPosition(start); CellScore startCellScore = getCellScore(startCell); startCellScore.setVisited(true); cellScores.put(startCell, startCellScore); } private CellScore getCellScore(Cell cell){ Position cellPosition = cell.getPosition(); return new CellScore( getDistanceFromEnd(cellPosition), getCurrentCost(cellPosition) ); } private int getDistanceFromEnd(Position position){ return (int) Math.round(pythagoras(end.getX() - position.getX(), end.getY() - position.getY()) * 10 ); } private int getCurrentCost(Position position){ int distanceFromCurrent = (int) Math.round(pythagoras(current.getX() - position.getX(), current.getY() - position.getY()) * 10 ); int currentCost = cellScores.getOrDefault(maze.getCellByPosition(current), new CellScore(0, 0)).getGCost(); return currentCost + distanceFromCurrent; } private void calculateNeighbors(){ Cell cell = maze.getCellByPosition(current); if(!cell.getWalls().contains(Walls.NORTH)){ calculateNextCell(new Position(current.getX(), current.getY() - 1)); } if(!cell.getWalls().contains(Walls.EAST)){ calculateNextCell(new Position(current.getX() + 1, current.getY())); } if(!cell.getWalls().contains(Walls.SOUTH)){ calculateNextCell(new Position(current.getX(), current.getY() + 1)); } if(!cell.getWalls().contains(Walls.WEST)){ calculateNextCell(new Position(current.getX() - 1, current.getY())); } } public void calculateNextCell(Position next){ CellScore cellScore = getCellScore(maze.getCellByPosition(next)); cellScores.put(maze.getCellByPosition(next), cellScore); } private void calculateNextPosition() { List<Map.Entry<Cell, CellScore>> entries = cellScores.entrySet().stream() .filter(entry -> !entry.getValue().isVisited()) .collect(Collectors.toList()); Map.Entry<Cell, CellScore> min = entries.get(0); for(Map.Entry<Cell, CellScore> entry : entries){ if(min.getValue().getFCost() > entry.getValue().getFCost()){ min = entry; } } current = min.getKey().getPosition(); min.getValue().setVisited(true); } private double pythagoras(int a, int b){ return Math.sqrt((a * a) + (b * b)); } }
true
708d0dbb9d0a7f0d6cb903e092459d4ac3c026f2
Java
xenryjake/StageBot
/src/main/java/com/xenry/stagebot/audio/musicquiz/command/MusicQuizAddSongCommand.java
UTF-8
733
2.15625
2
[]
no_license
package com.xenry.stagebot.audio.musicquiz.command; import com.xenry.stagebot.audio.musicquiz.MusicQuizHandler; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.User; /** * StageBot created by Henry Blasingame (Xenry) on 5/24/20 * The content in this file and all related files are * Copyright (C) 2020 Henry Blasingame. * Usage of this content without written consent of Henry Blasingame * is prohibited. */ public class MusicQuizAddSongCommand extends AbstractMusicQuizCommand { public MusicQuizAddSongCommand(MusicQuizHandler musicQuizHandler){ super(musicQuizHandler, "addsong", "as"); botAdminOnly = true; } @Override protected void perform(User user, Message message, String[] args, String label) { } }
true
d3b982e679c18a2f3086b7a990722154e7568a91
Java
JetBrains/intellij-community
/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/jvm/descriptors/GetterDescriptor.java
UTF-8
5,644
1.78125
2
[ "Apache-2.0" ]
permissive
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.dataFlow.jvm.descriptors; import com.intellij.codeInspection.dataFlow.DfaNullability; import com.intellij.codeInspection.dataFlow.DfaPsiUtil; import com.intellij.codeInspection.dataFlow.TypeConstraint; import com.intellij.codeInspection.dataFlow.TypeConstraints; import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState; import com.intellij.codeInspection.dataFlow.types.DfAntiConstantType; import com.intellij.codeInspection.dataFlow.types.DfConstantType; import com.intellij.codeInspection.dataFlow.types.DfPrimitiveType; import com.intellij.codeInspection.dataFlow.types.DfType; import com.intellij.codeInspection.dataFlow.value.DfaValue; import com.intellij.codeInspection.dataFlow.value.DfaValueFactory; import com.intellij.codeInspection.dataFlow.value.DfaVariableValue; import com.intellij.psi.*; import com.intellij.psi.impl.light.LightRecordMethod; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PropertyUtilBase; import com.intellij.psi.util.PsiTypesUtil; import com.intellij.psi.util.PsiUtil; import com.siyeh.ig.callMatcher.CallMatcher; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Objects; /** * A descriptor that represents a getter-like method (without arguments) */ public final class GetterDescriptor extends PsiVarDescriptor { private static final CallMatcher STABLE_METHODS = CallMatcher.anyOf( CallMatcher.instanceCall(CommonClassNames.JAVA_LANG_OBJECT, "getClass").parameterCount(0), CallMatcher.instanceCall("java.lang.reflect.Member", "getName", "getModifiers", "getDeclaringClass", "isSynthetic"), CallMatcher.instanceCall("java.lang.reflect.Executable", "getParameterCount", "isVarArgs"), CallMatcher.instanceCall("java.lang.reflect.Field", "getType"), CallMatcher.instanceCall("java.lang.reflect.Method", "getReturnType"), CallMatcher.instanceCall(CommonClassNames.JAVA_LANG_CLASS, "getName", "isInterface", "isArray", "isPrimitive", "isSynthetic", "isAnonymousClass", "isLocalClass", "isMemberClass", "getDeclaringClass", "getEnclosingClass", "getSimpleName", "getCanonicalName") ); private final @NotNull PsiMethod myGetter; private final boolean myStable; public GetterDescriptor(@NotNull PsiMethod getter) { myGetter = getter; if (STABLE_METHODS.methodMatches(getter) || getter instanceof LightRecordMethod) { myStable = true; } else { PsiField field = PsiUtil.canBeOverridden(getter) ? null : PropertyUtil.getFieldOfGetter(getter); myStable = field != null && field.hasModifierProperty(PsiModifier.FINAL); } } @NotNull @Override public String toString() { return myGetter.getName(); } @Nullable @Override PsiType getType(@Nullable DfaVariableValue qualifier) { return getSubstitutor(myGetter, qualifier).substitute(myGetter.getReturnType()); } @NotNull @Override public PsiMethod getPsiElement() { return myGetter; } @Override public boolean isStable() { return myStable; } @Override public boolean isCall() { return true; } @NotNull @Override public DfaValue createValue(@NotNull DfaValueFactory factory, @Nullable DfaValue qualifier) { if (myGetter.hasModifierProperty(PsiModifier.STATIC)) { return factory.getVarFactory().createVariableValue(this); } return super.createValue(factory, qualifier); } @Override public int hashCode() { return Objects.hashCode(myGetter.getName()); } @Override public boolean equals(Object obj) { return obj == this || (obj instanceof GetterDescriptor && ((GetterDescriptor)obj).myGetter == myGetter); } @Override @NotNull DfaNullability calcCanBeNull(@NotNull DfaVariableValue value, @Nullable PsiElement context) { PsiType type = getType(value.getQualifier()); return DfaNullability.fromNullability(DfaPsiUtil.getElementNullabilityIgnoringParameterInference(type, myGetter)); } @Override public boolean alwaysEqualsToItself(@NotNull DfType type) { if (!super.alwaysEqualsToItself(type)) return false; if (type instanceof DfPrimitiveType || type instanceof DfConstantType) return true; if (PropertyUtilBase.isSimplePropertyGetter(myGetter) || myGetter instanceof LightRecordMethod) return true; return false; } @Override public @NotNull DfType getQualifierConstraintFromValue(@NotNull DfaMemoryState state, @NotNull DfaValue value) { if (!PsiTypesUtil.isGetClass(myGetter)) return DfType.TOP; DfType type = state.getDfType(value); DfType constraint = DfType.TOP; PsiType cls = type.getConstantOfType(PsiType.class); if (cls != null) { constraint = TypeConstraints.exact(cls).asDfType(); } else if (type instanceof DfAntiConstantType) { constraint = StreamEx.of(((DfAntiConstantType<?>)type).getNotValues()).select(PsiType.class) .map(t -> TypeConstraints.exact(t).tryNegate()) .nonNull() .reduce(TypeConstraint::meet).orElse(TypeConstraints.TOP).asDfType(); } if (value instanceof DfaVariableValue && ((DfaVariableValue)value).getDescriptor().equals(this)) { DfaVariableValue qualifier = ((DfaVariableValue)value).getQualifier(); if (qualifier != null) { constraint = constraint.meet(TypeConstraint.fromDfType(state.getDfType(qualifier)).asDfType()); } } return constraint; } }
true
fa33c93370252b3029159488aa3de1e039043f68
Java
ksrubka/cinema-system
/src/main/java/pl/com/bottega/cinemasystem/api/dtos/PaymentDto.java
UTF-8
800
2.15625
2
[]
no_license
package pl.com.bottega.cinemasystem.api.dtos; import pl.com.bottega.cinemasystem.domain.CreditCard; import pl.com.bottega.cinemasystem.domain.Payment; import pl.com.bottega.cinemasystem.domain.PaymentType; public class PaymentDto { private PaymentType type; private Long cashierId; private CreditCard creditCard; public PaymentType getType() { return type; } public void setType(PaymentType type) { this.type = type; } public CreditCard getCreditCard() { return creditCard; } public void setCreditCard(CreditCard creditCard) { this.creditCard = creditCard; } public Long getCashierId() { return cashierId; } public void setCashierId(Long cashierId) { this.cashierId = cashierId; } }
true
0dcfca4f82d81e3287ce0a7a0c0bacff3b6967e4
Java
prasunmax/BootUpSpringAssignment
/gateway/src/main/java/prasun/springboot/gateway/dao/UserDao.java
UTF-8
6,979
2.34375
2
[]
no_license
package prasun.springboot.gateway.dao; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; import java.util.Map; import java.util.Optional; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import org.bson.conversions.Bson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import com.mongodb.ErrorCategory; import com.mongodb.MongoClientSettings; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.Updates; import prasun.springboot.gateway.entity.Session; import prasun.springboot.gateway.entity.User; @Configuration public class UserDao extends AbstractAuthDao { private final MongoCollection<User> usersCollection; // Ticket: User Management - do the necessary changes so that the sessions // collection // returns a Session object private final MongoCollection<Session> sessionsCollection; private final Logger log; @Autowired public UserDao(MongoClient mongoClient, @Value("${spring.mongodb.database}") String databaseName) { super(mongoClient, databaseName); CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build())); usersCollection = db.getCollection("users", User.class).withCodecRegistry(pojoCodecRegistry); log = LoggerFactory.getLogger(this.getClass()); // Ticket: User Management - implement the necessary changes so that the // sessions // collection returns a Session objects instead of Document objects. sessionsCollection = db.getCollection("sessions", Session.class).withCodecRegistry(pojoCodecRegistry); } /** * Inserts the `user` object in the `users` collection. * * @param user - User object to be added * @return True if successful, throw IncorrectDaoOperation otherwise */ public boolean addUser(User user) { // Ticket: Durable Writes - you might want to use a more durable write concern // here! try { usersCollection.withWriteConcern(WriteConcern.MAJORITY).insertOne(user); } catch (MongoException e) { log.error("User could not inserted"); // Ticket: Handling Errors - make sure to only add new users // and not users that already exist. if (ErrorCategory.fromErrorCode(e.getCode()) == ErrorCategory.DUPLICATE_KEY) { throw new IncorrectDaoOperation("User is already in the database."); } return false; } return true; } /** * Creates session using userId and jwt token. * * @param userId - user string identifier * @param jwt - jwt string token * @return true if successful */ public boolean createUserSession(String userId, String jwt) { // Ticket: User Management - implement the method that allows session // information to be // stored in it's designated collection. // Session session = new Session(); // session.setUserId(userId); // session.setJwt(jwt); // UpdateOptions updateOptions = new UpdateOptions(); // updateOptions.upsert(true); // // Ticket: Handling Errors - implement a safeguard against // // creating a session with the same jwt token. // try { // // If the session is present update it, otherwise insert one // if (Optional.ofNullable(sessionsCollection.find( Filters.eq("user_id", userId) ).first()).isPresent()) { // sessionsCollection.updateOne(Filters.eq("user_id", userId), Updates.set("jwt", jwt)); // } else { // sessionsCollection.insertOne(session); // } // } catch (MongoException e) { // log.error("Could not insert/update session"); // return false; // } // return true; Bson updateFilter = new Document("user_id", userId); Bson setUpdate = Updates.set("jwt", jwt); UpdateOptions options = new UpdateOptions().upsert(true); sessionsCollection.updateOne(updateFilter, setUpdate, options); return true; } /** * Returns the User object matching the an email string value. * * @param email - email string to be matched. * @return User object or null. */ public User getUser(String email) { User user = null; // Ticket: User Management - implement the query that returns the first User // object. user = usersCollection.find(Filters.eq("email", email)).first(); return user; } /** * Given the userId, returns a Session object. * * @param userId - user string identifier. * @return Session object or null. */ public Session getUserSession(String userId) { // Ticket: User Management - implement the method that returns Sessions for a // given // userId return sessionsCollection.find(Filters.eq("user_id", userId)).first(); } public boolean deleteUserSessions(String userId) { // Ticket: User Management - implement the delete user sessions method sessionsCollection.deleteMany(Filters.eq("user_id", userId)); return true; } /** * Removes the user document that match the provided email. * * @param email - of the user to be deleted. * @return true if user successfully removed */ public boolean deleteUser(String email) { // remove user sessions // Ticket: User Management - implement the delete user method // Ticket: Handling Errors - make this method more robust by // handling potential exceptions. try { sessionsCollection.deleteMany(Filters.eq("user_id", email)); usersCollection.deleteMany(Filters.eq("email", email)); } catch (MongoException e) { log.error("Error deleting user"); return false; } return true; } /** * Updates the preferences of an user identified by `email` parameter. * * @param email - user to be updated email * @param userPreferences - set of preferences that should be stored and replace * the existing ones. Cannot be set to null value * @return User object that just been updated. */ public boolean updateUserPreferences(String email, Map<String, ?> userPreferences) { // Ticket: User Preferences - implement the method that allows for user // preferences to // be updated. // Ticket: Handling Errors - make this method more robust by // handling potential exceptions when updating an entry. try { usersCollection.updateOne(Filters.eq("email", email), Updates.set("preferences", Optional.ofNullable(userPreferences) .orElseThrow(() -> new IncorrectDaoOperation("user preferences cannot be null")))); } catch (MongoException e) { log.error("An error ocurred while trying to update User preferences."); return false; } return true; } }
true
8e244d6de7ff6b9a251d2d8c6991721a38b72048
Java
altope98/JAVA
/NETBEANS2/TERCER TRIMESTRE/Practica 12/src/Parpadeo.java
UTF-8
8,863
2.578125
3
[]
no_license
import java.awt.Color; import java.awt.Font; import java.util.logging.Level; import java.util.logging.Logger; public class Parpadeo extends javax.swing.JFrame { protected int rojo,verde,azul; protected boolean parpadeo=true; public Parpadeo() { initComponents(); for(int i=0;i<=100;i++){ tamaño.addItem(i+""); } } public void cambiarTexto() throws InterruptedException{ texto.setText(areatexto.getText()); texto.setFont(new Font("",0,Integer.parseInt(tamaño.getSelectedItem()))); for (int i=0;i<100;i++){ if (parpadeo){ texto.setForeground(new Color(rojo,verde,azul)); parpadeo=false; Thread.sleep(100); }else{ texto.setForeground(Color.white); parpadeo=true; Thread.sleep(100); } } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { texto = new java.awt.Label(); areatexto = new java.awt.TextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); tamaño = new java.awt.Choice(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); barrarojo = new javax.swing.JScrollBar(); barraverde = new javax.swing.JScrollBar(); barraazul = new javax.swing.JScrollBar(); salir = new java.awt.Button(); aplicar = new java.awt.Button(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); texto.setAlignment(java.awt.Label.CENTER); texto.setFont(new java.awt.Font("Dialog", 0, 36)); // NOI18N texto.setText("Texto"); getContentPane().add(texto, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 20, 950, 100)); getContentPane().add(areatexto, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 130, 180, -1)); jLabel4.setText("Texto"); getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 130, -1, -1)); jLabel5.setText("Tamaño"); getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 170, -1, -1)); getContentPane().add(tamaño, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 170, 60, -1)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Color")); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setText("Rojo"); jPanel2.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 90, -1, -1)); jLabel2.setText("Verde"); jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 90, -1, -1)); jLabel3.setText("Azul"); jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 80, 30, 20)); barrarojo.setMaximum(256); barrarojo.setOrientation(javax.swing.JScrollBar.HORIZONTAL); barrarojo.addAdjustmentListener(new java.awt.event.AdjustmentListener() { public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) { barrarojoAdjustmentValueChanged(evt); } }); jPanel2.add(barrarojo, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 80, 130, 30)); barraverde.setMaximum(256); barraverde.setOrientation(javax.swing.JScrollBar.HORIZONTAL); barraverde.addAdjustmentListener(new java.awt.event.AdjustmentListener() { public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) { barraverdeAdjustmentValueChanged(evt); } }); jPanel2.add(barraverde, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 80, 130, 30)); barraazul.setMaximum(256); barraazul.setOrientation(javax.swing.JScrollBar.HORIZONTAL); barraazul.addAdjustmentListener(new java.awt.event.AdjustmentListener() { public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) { barraazulAdjustmentValueChanged(evt); } }); jPanel2.add(barraazul, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 80, 130, 30)); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 240, 710, 180)); salir.setLabel("Salir"); salir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { salirActionPerformed(evt); } }); getContentPane().add(salir, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 440, -1, -1)); aplicar.setLabel("Aplicar"); aplicar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aplicarActionPerformed(evt); } }); getContentPane().add(aplicar, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 440, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void barrarojoAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_barrarojoAdjustmentValueChanged rojo=barrarojo.getValue(); }//GEN-LAST:event_barrarojoAdjustmentValueChanged private void barraverdeAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_barraverdeAdjustmentValueChanged verde=barraverde.getValue(); }//GEN-LAST:event_barraverdeAdjustmentValueChanged private void barraazulAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_barraazulAdjustmentValueChanged azul=barraazul.getValue(); }//GEN-LAST:event_barraazulAdjustmentValueChanged private void salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salirActionPerformed System.exit(0); }//GEN-LAST:event_salirActionPerformed private void aplicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aplicarActionPerformed try { cambiarTexto(); } catch (InterruptedException ex) { Logger.getLogger(Parpadeo.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_aplicarActionPerformed public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Parpadeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Parpadeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Parpadeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Parpadeo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Parpadeo().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private java.awt.Button aplicar; private java.awt.TextField areatexto; private javax.swing.JScrollBar barraazul; private javax.swing.JScrollBar barrarojo; private javax.swing.JScrollBar barraverde; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel2; private java.awt.Button salir; private java.awt.Choice tamaño; private java.awt.Label texto; // End of variables declaration//GEN-END:variables }
true
14e6b683b45bfffb1a96936faaaec3bb33ef1b92
Java
Game-Designing/Custom-Football-Game
/sources/p005cm/aptoide/p006pt/view/app/C5300v.java
UTF-8
555
1.585938
2
[ "MIT" ]
permissive
package p005cm.aptoide.p006pt.view.app; import p005cm.aptoide.p006pt.dataprovider.model.p009v7.ListApps; import p026rx.p027b.C0132p; /* renamed from: cm.aptoide.pt.view.app.v */ /* compiled from: lambda */ public final /* synthetic */ class C5300v implements C0132p { /* renamed from: a */ private final /* synthetic */ AppService f9079a; public /* synthetic */ C5300v(AppService appService) { this.f9079a = appService; } public final Object call(Object obj) { return this.f9079a.mo16970b((ListApps) obj); } }
true
2f3082d4a0cd78ee3e202111b1510eb819f652f8
Java
kurogami207176/coloniser
/core/src/com/alaindroid/coloniser/modules/DrawModule.java
UTF-8
1,111
2.0625
2
[]
no_license
package com.alaindroid.coloniser.modules; import com.alaindroid.coloniser.draw.*; import com.alaindroid.coloniser.service.animation.AnimationProcessorService; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; @Module public class DrawModule { @Provides @Singleton public HexGridDrawer hexDrawer() { return new HexGridDrawer(); } @Provides @Singleton public UnitDrawer unitDrawer() { return new UnitDrawer(); } @Provides @Singleton public BuildingDrawer buildingDrawer() { return new BuildingDrawer(); } @Provides @Singleton public SpriteDrawer spriteDrawer(HexGridDrawer hexDrawer, UnitDrawer unitDrawer, BuildingDrawer buildingDrawer) { return new SpriteDrawer(hexDrawer, unitDrawer, buildingDrawer); } @Provides @Singleton public BackgroundDrawer backgroundDrawer() { return new BackgroundDrawer(); } @Provides @Singleton public AnimationProcessorService animationProcessorService() { return new AnimationProcessorService(); } }
true
67a3bf12132a65dc276429487bf07d18535f8237
Java
mogdum/Automation
/src/test/java/com/login/TestLogin.java
UTF-8
1,315
2.4375
2
[]
no_license
package com.login; import java.util.Map; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.Test; import com.util.BaseTestClass; public class TestLogin extends BaseTestClass{ static Logger log = Logger.getLogger(TestLogin.class.getName()); public TestLogin()throws Exception { System.out.println("chiild class"); excelPath=projectPath+"\\src\\test\\resources\\testdata\\login.xlsx"; sheetName="login"; } @Test(dataProvider = "testdata") public void loginPositive(Map<String,String> sample, String Result) { LoginPage page=new LoginPage(driver); page.login(sample.get("uesrname"), sample.get("password")); log.info("method excecution completed"); } @Test(dataProvider = "testdata") public void loginNegative(Map<String,String> sample, String Result) { System.out.println("test method"); LoginPage page = new LoginPage(driver); page.login(sample.get("uesrname"), sample.get("password")); String message=driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); Assert.assertTrue(message.contains("Wrong1!"),"wrong alert message"); //Assert.assertEquals(message.trim(),sample.get("alertMag").trim()); //System.out.println(message); } }
true
dbb525eaecd9207df195f0b8a1c25b8f2dcc1ad5
Java
Heiku/LeetCode
/src/nothing/OverrideOrOverLoad.java
UTF-8
571
3.234375
3
[]
no_license
package nothing; /** * Created by Heiku on 2018/9/20 * * 方法重写:方法名,参数类型,个数,返回类型得相同,同时被重写的方法不能拥有更高的权限 * 方法重载:方法名相同,参数类型,个数,返回类型都可不同, */ public class OverrideOrOverLoad { } class Fruit{ String print(String str){ System.out.println("This is " + str); return str; } } class Apple extends Fruit{ @Override String print(String str) { System.out.println(); return str; } }
true
e2f235b8b0dea8ec83507c45a842f7759d6d1eee
Java
hyong07/semi_
/src/semi/dto/CategoryDTO.java
UTF-8
651
2.59375
3
[]
no_license
package semi.dto; public class CategoryDTO { private String main_category; private String sub_category; public CategoryDTO() { super(); } public CategoryDTO(String main_category, String sub_category) { super(); this.main_category = main_category; this.sub_category = sub_category; } public String getMain_category() { return main_category; } public void setMain_category(String main_category) { this.main_category = main_category; } public String getSub_category() { return sub_category; } public void setSub_category(String sub_category) { this.sub_category = sub_category; } }
true
371cbada4b2bbfd342ddb4c858d4f0a880be3789
Java
superliujian/liquid
/web-console/src/main/java/liquid/api/controller/ApiContainerController.java
UTF-8
1,126
1.960938
2
[ "Apache-2.0" ]
permissive
package liquid.api.controller; import liquid.container.domain.Container; import liquid.container.facade.ContainerFacade; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * Created by redbrick9 on 7/12/14. */ @Controller @RequestMapping("/api/container") public class ApiContainerController { private static final Logger logger = LoggerFactory.getLogger(ApiContainerController.class); @Autowired private ContainerFacade containerFacade; @RequestMapping(method = RequestMethod.GET, params = "bicCode") @ResponseBody public List<Container> findByBicCodeLike(@RequestParam String bicCode) { logger.debug("bicCode: {}", bicCode); return containerFacade.findByBicCodeLike(bicCode); } }
true
7736acb4438b638eac94f81922a3fa959ce68e86
Java
lftechnologyinc/hack_avengers
/doctorsap/mobile/DoctorSap/src/com/doctorsap/task/DoctorsTask.java
UTF-8
777
2.171875
2
[]
no_license
package com.doctorsap.task; import java.util.ArrayList; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import com.doctorsap.madel.Doctors; public class DoctorsTask extends AsyncTask<Void, Integer, Boolean> { private Context context; private ProgressDialog progress; private ArrayList<Doctors> list; public DoctorsTask(Context context) { this.context = context; } @Override protected void onPreExecute() { progress = new ProgressDialog(context); progress.setIndeterminate(true); progress.setCancelable(true); progress.setMessage("Searching Speciality ..."); progress.show(); } @Override protected Boolean doInBackground(Void... params) { // TODO Auto-generated method stub return null; } }
true
4da41a50b7f7411c1648b202bca407e5966bc1cc
Java
wad/fwb
/basic/src/main/java/com/funwithbasic/basic/value/Value.java
UTF-8
636
3.046875
3
[]
no_license
package com.funwithbasic.basic.value; import com.funwithbasic.basic.BasicException; public abstract class Value { public ValueNumber asNumber() throws BasicException { if (!(this instanceof ValueNumber)) { throw new BasicException("Type mismatch, expected a number"); } return (ValueNumber)this; } public ValueString asString() throws BasicException { if (!(this instanceof ValueString)) { throw new BasicException("Type mismatch, expected a string"); } return (ValueString)this; } public abstract String print() throws BasicException; }
true
ab58be794dbc9e131426c2c352d54865e7e51688
Java
HuashengZhao/SONGDUWEB
/src/main/java/com/example/EAS/service/ITFdcCurprojectService.java
UTF-8
375
1.59375
2
[]
no_license
package com.example.EAS.service; import com.example.EAS.model.TFdcCurproject; import com.baomidou.mybatisplus.extension.service.IService; import com.example.EAS.vo.ProjectVO; /** * <p> * 服务类 * </p> * * @author watson * @since 2020-08-30 */ public interface ITFdcCurprojectService extends IService<TFdcCurproject> { ProjectVO getProjects(ProjectVO vo); }
true
64bc22b8b53f70b4744121314aa557b91bcb1b4f
Java
nglou/cargomax-evaluation-dummy
/src/main/java/aero/champ/cargospot/cargomax/dummy/BookingReviewRQProcessor.java
UTF-8
1,119
2.390625
2
[]
no_license
package aero.champ.cargospot.cargomax.dummy; import aero.champ.cargospot.cargomax.dummy.db.InMemoryDB; import aero.champ.cargospot.cargomax.dummy.generated.BookingReviewRQ; import aero.champ.cargospot.cargomax.dummy.generated.BookingReviewRS; import aero.champ.cargospot.cargomax.dummy.generated.SuccessMsg; /** * Processor for BookingReviewRQ. * * @version $Revision$, $Date$ */ public class BookingReviewRQProcessor { //~ Instance fields -------------------------- /** */ private BookingReviewRQ rq; //~ Constructors ----------------------------- /** * Creates a new BookingReviewRQProcessor object. * * @param rq */ public BookingReviewRQProcessor(BookingReviewRQ rq) { this.rq = rq; } //~ Methods ---------------------------------- /** * DOCUMENT ME! * * @return */ public BookingReviewRS process() { InMemoryDB inMemoryDB = InMemoryDB.fromContext(); inMemoryDB.addReviewRequest(rq); BookingReviewRS rs = new BookingReviewRS(); // might need to change default response status rs.setSuccess(SuccessMsg.OK); inMemoryDB.addReviewResponse(rs); return rs; } }
true
45a6831ea0b71f050d4d5f370f657af0c59499e4
Java
Lollala/hitaoapp
/hitaoapp_product/src/main/java/com/hzitxx/hitao/mapper/ShopFrontCategoryMapper.java
UTF-8
1,006
2.03125
2
[]
no_license
package com.hzitxx.hitao.mapper; import com.hzitxx.hitao.entity.ShopFrontCategory; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * <p> * Mapper 接口 * </p> * * @author xianyaoji * @since 2018-08-10 */ public interface ShopFrontCategoryMapper{ /** * 根据父id查询子集 * @param parentId * @return */ List<ShopFrontCategory> ByparentId(Integer parentId); int addShopFrontCategory(ShopFrontCategory obj); int addShopFrontCategorySelective(ShopFrontCategory obj); int deleteById(int frontCatId); int deleteByIds(String[] ids); int updateById(ShopFrontCategory shopFrontCategory); int updateSelectiveById(ShopFrontCategory shopFrontCategory); ShopFrontCategory findOne(Integer frontCatId); List<ShopFrontCategory> searchShopFrontCategory(@Param("map")Map<String,Object> map); }
true
25cc934eae6608ec778b51323ed89b04ec762537
Java
suresh-chaudhari/product-ms
/src/main/java/com/demo/ca/product/model/response/ProductResponse.java
UTF-8
370
1.734375
2
[]
no_license
package com.demo.ca.product.model.response; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class ProductResponse { private String message; }
true
8311d0ecc349e0d6c77f2697311bb7e991028b6b
Java
koreacherry/Java
/DamBae/src/com/ktds/jmj/Market.java
UTF-8
4,224
3.328125
3
[]
no_license
package com.ktds.jmj; import java.util.InputMismatchException; import java.util.Scanner; //하나의 메소드는 하나의 기능을 하게 해야 유지보수가 편해요. public class Market { Scanner input = new Scanner(System.in); Seller DamBaeSell = new Seller (50000, 10, 2000); boolean exit = true; public int inputMessage(int some) { some = input.nextInt(); return some; } public void start() { int age = 0; int totalMoney = 0; int count = 0; int howMuch = 0; //min.setMoney(totalMoney); //min.setDambaeCount(0); while (exit) { System.out.println("몇살이니"); while (true) { try { age = inputMessage(age); break; } catch ( InputMismatchException ime ) { input = new Scanner(System.in); System.out.println("잘못 입력했습니다. 정수만 입력가능"); //System.out.println(ime.getCause().getCause() + "예외가 " + ime.getMessage()); } } System.out.println("재산얼마?"); while (true) { try { totalMoney = inputMessage(totalMoney); break; } catch ( InputMismatchException ime ) { input = new Scanner(System.in); System.out.println("잘못 입력했습니다. 정수만 입력가능"); //System.out.println(ime.getCause().getCause() + "예외가 " + ime.getMessage()); } } Customer min = new Customer(totalMoney, count, age); //나이물어서 어리면 보내기 //exit = min.checkAge(); /*if ( DamBaeSell.getDamBaeCount() == 0 ) { System.out.println("품절."); break; } if (min.getMoney() < DamBaeSell.getDamBaePrice()){ System.out.println("돈이 2000원보다 적네요."); break; }*/ if (!min.checkAge()){ break; } if (!DamBaeSell.checkInven(min)){ break; } // 소비자에게서 돈을 받는다. System.out.println("개당 2천원이야 몇개?"); while (true) { try { count = inputMessage(count); break; } catch ( InputMismatchException ime ) { input = new Scanner(System.in); System.out.println("잘못 입력했습니다. 정수만 입력가능"); //System.out.println(ime.getCause().getCause() + "예외가 " + ime.getMessage()); } } System.out.println("얼마낼거니?"); while (true) { try { howMuch = inputMessage(howMuch); break; } catch ( InputMismatchException ime ) { input = new Scanner(System.in); System.out.println("잘못 입력했습니다. 정수만 입력가능"); //System.out.println(ime.getCause().getCause() + "예외가 " + ime.getMessage()); } } if ( howMuch < DamBaeSell.getDamBaePrice() * count || min.getMoney() < howMuch){ System.out.println("돈 모자르다."); break; } // 내가 달라한 개수보다 있는 담배가 적을 때 if (count > DamBaeSell.getDamBaeCount()){ System.out.println(count + "개의 담배가 없어요."); break; } //min은 돈을 지불하고, seller은 돈을 받는다. //min.pay(howMuch); DamBaeSell.getMoneyFromCustomer(howMuch, min); // DamBaeSell은 사과를 준다. min은 담배를 받는다. DamBaeSell.giveDamBae(count, min); // DamBaeSell은 거스름돈을 남겨준다. min은 받는다. DamBaeSell.giveRemain((howMuch), count, min); // 소비자의 정보를 출력한다. min.printMyInfo(); DamBaeSell.printMyInfo(); System.out.println("========================================="); System.out.println("그만사고 싶으면 exit 입력해.계속살거면 아무거나 눌러"); String exit = input.next(); if (exit.equals("exit")){ System.out.println("잘가"); break; } } } public void printMessage() { System.out.println("========================================="); System.out.println("어서오세요. 담배 팜"); System.out.println("========================================="); System.out.println("안녕?"); } public static void main(String[] args) { Market market = new Market();//자기 자신을 인스턴스로 만들 수 있다. market.printMessage(); market.start(); //System.out.println(Market.appleCount); } }
true
de245ef3a0bc9e167815b28ca7e83b88cb211a26
Java
fagnerpsantos/ADS2M_1
/Estruturas de Dados/src/com/senac/estruturas/interfaces/Container.java
UTF-8
288
2.28125
2
[]
no_license
package com.senac.estruturas.interfaces; import java.util.Enumeration; public interface Container extends Comparable { int getCount(); boolean isEmpty(); boolean isFull(); void purge(); void accept(Visitor visitor); @SuppressWarnings("rawtypes") Enumeration getEnumeration(); }
true
04f1a652ca3bcac6d0f030dae2d442c502cf07ac
Java
meela7/WISE
/WISE/src/main/java/org/cilab/m4/dao/impl/PredictionModelDAOImpl.java
UTF-8
4,682
2.53125
3
[]
no_license
package org.cilab.m4.dao.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.cilab.m4.dao.PredictionModelDAO; import org.cilab.m4.model.PredictionModel; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.persister.entity.AbstractEntityPersister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; public class PredictionModelDAOImpl implements PredictionModelDAO { /** * Class Name: PredictionModelDAOImpl.java * Description: * * @author Meilan Jiang * @since 2016.07.05 * @version 1.2 * * Copyright(c) 2016 by CILAB All right reserved. */ private static final Logger logger = LoggerFactory.getLogger(PredictionModelDAOImpl.class); private SessionFactory sessionFactory; public PredictionModelDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override @Transactional public boolean create(PredictionModel model) { try { sessionFactory.getCurrentSession().save(model); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override @Transactional public PredictionModel read(int modelID) { PredictionModel model = (PredictionModel) sessionFactory.getCurrentSession().get(PredictionModel.class, modelID); return model; } @Override @Transactional public boolean update(PredictionModel model) { try { sessionFactory.getCurrentSession().update(model); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override @Transactional public boolean delete(int modelID) { try { Query query = sessionFactory.getCurrentSession().createQuery("DELETE FROM PredictionModel WHERE MethodID = :modelID"); query.setParameter("modelID", modelID); query.executeUpdate(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override @Transactional public List<PredictionModel> list() { @SuppressWarnings("unchecked") List<PredictionModel> modelList = (List<PredictionModel>) sessionFactory.getCurrentSession().createCriteria(PredictionModel.class).list(); return modelList; } @Override @Transactional public List<PredictionModel> search(Map<String, String> map) { Session session = sessionFactory.getCurrentSession(); String hqlQuery = "FROM PredictionModel WHERE "; // get all the columns of the Instrument // remove the parameters which doesn't match with column in the list AbstractEntityPersister aep=((AbstractEntityPersister)sessionFactory.getClassMetadata(PredictionModel.class)); String[] properties = aep.getPropertyNames(); List<String> columnNames = Arrays.asList(properties); for(String key : map.keySet()){ if(!columnNames.contains(key)) map.remove(key); } // get parameters from map and Uppercase the first letter int index = 0; for(String key : map.keySet()){ if(index == 0 ) hqlQuery = hqlQuery + key + " = :" + key ; else hqlQuery = hqlQuery + " and " + key + " = :" + key ; index++; } // execute HQL Query logger.info("Execute Query: {}", hqlQuery); Query query = session.createQuery(hqlQuery); for(String key : map.keySet()){ query.setParameter(key, map.get(key)); } @SuppressWarnings("unchecked") List<PredictionModel> modelList = (List<PredictionModel>) query.list(); return modelList; } @Override @Transactional public List<PredictionModel> listSearch(Map<String, List<String>> map) { Session session = sessionFactory.getCurrentSession(); String hqlQuery = "FROM PredictionModel WHERE "; // create HQL Statement int index = 0; for(String key : map.keySet()){ if(index == 0 ) hqlQuery = hqlQuery + key + " in :" + key ; else hqlQuery = hqlQuery + " and " + key + " in :" + key ; index++; } // execute HQL Query logger.info("Execute Query: {}", hqlQuery); Query query = session.createQuery(hqlQuery); for(String key : map.keySet()){ if(key.equals("MethodID")){ List<Integer> valueList = new ArrayList<Integer>(); for(String value: map.get(key)){ valueList.add(Integer.parseInt(value)); } query.setParameterList(key, valueList); }else query.setParameterList(key, map.get(key)); } @SuppressWarnings("unchecked") List<PredictionModel> modelList = (List<PredictionModel>) query.list(); return modelList; } }
true
c30c9b6e5bafb03e29a908f8d4aff40081bc7d2c
Java
Pablovsky1/Buscador-ML
/app/src/main/java/com/mercadolibre/products/ui/MainActivity.java
UTF-8
5,560
1.960938
2
[]
no_license
package com.mercadolibre.products.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.widget.NestedScrollView; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.mercadolibre.products.R; import com.mercadolibre.products.adapters.ProductAdapter; import com.mercadolibre.products.util.MyLog; import com.mercadolibre.products.viewmodels.ViewModelMain; public class MainActivity extends AppCompatActivity implements SearchDialog.NoticeSearchDialog { private final String TAG = "MainActivity"; private NestedScrollView scrollView; private ViewModelMain viewModel; private RecyclerView myRecyclerView; private RecyclerView.Adapter myAdapter; private RecyclerView.LayoutManager myLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar(); init(); viewModel.getSearch().observe(this, resource -> { switch (resource.status) { case LOADING: MyLog.i(TAG,"loading search"); findViewById(R.id.containerErros).setVisibility(View.GONE); findViewById(R.id.progress_bar).setVisibility(View.VISIBLE); findViewById(R.id.retry).setVisibility(View.GONE); break; case SUCCESS: MyLog.i(TAG,"search: "+resource.data.toString()); findViewById(R.id.progress_bar).setVisibility(View.GONE); findViewById(R.id.retry).setVisibility(View.GONE); findViewById(R.id.containerErros).setVisibility(View.GONE); break; case ERROR: MyLog.i(TAG,"error search "+resource.message); findViewById(R.id.containerErros).setVisibility(View.VISIBLE); findViewById(R.id.retry).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.textError)).setText(resource.message); findViewById(R.id.progress_bar).setVisibility(View.GONE); break; } }); viewModel.getProducts().observe(this, searchProducts -> { MyLog.i(TAG,"products: "+searchProducts.size()); findViewById(R.id.progressBarLoading).setVisibility(View.GONE); myAdapter = new ProductAdapter(searchProducts, (model, position) -> { Intent intent = new Intent(MainActivity.this, ProductActivity.class); intent.putExtra("id",model.getId()); startActivity(intent); }); myRecyclerView.setItemAnimator(new DefaultItemAnimator()); myRecyclerView.setLayoutManager(myLayoutManager); myRecyclerView.setAdapter(myAdapter); }); scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> { if (scrollY == -(v.getMeasuredHeight() - v.getChildAt(0).getMeasuredHeight())) { findViewById(R.id.progressBarLoading).setVisibility(View.VISIBLE); viewModel.loadProducts(((EditText) findViewById(R.id.search_edittext)).getText().toString()); } }); findViewById(R.id.retry).setOnClickListener(v -> { if(!((EditText)findViewById(R.id.search_edittext)).getText().toString().isEmpty()){ viewModel.startSearch(((EditText)findViewById(R.id.search_edittext)).getText().toString()); } }); } private void init() { this.myRecyclerView = findViewById(R.id.productsRecyclerView); this.myRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); this.myLayoutManager = new LinearLayoutManager(this); this.scrollView = findViewById(R.id.nestedScrollView); this.viewModel = new ViewModelProvider(this).get(ViewModelMain.class); } private void toolbar() { Toolbar myToolbar = findViewById(R.id.toolbar); setSupportActionBar(myToolbar); if (getSupportActionBar() != null) { getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } findViewById(R.id.search_edittext).setOnClickListener(v -> { SearchDialog searchDialog = new SearchDialog(); if (!((EditText) findViewById(R.id.search_edittext)).getText().toString().isEmpty()) { searchDialog.setProductDescription(((EditText) findViewById(R.id.search_edittext)).getText().toString()); } searchDialog.show(getSupportFragmentManager(), "SearchDialog"); }); } @Override public void onDialogSearch(String productDescription) { ((EditText) findViewById(R.id.search_edittext)).setText(productDescription); viewModel.startSearch(productDescription); if (myAdapter != null) { myRecyclerView.removeAllViews(); } } }
true
0857c9d243a43aa1508c5a145ca7d751c4e14633
Java
MichaelLin-TPE/MyPath
/app/src/main/java/com/path/mypath/photo_activity/SelectPhotoActivityPresenter.java
UTF-8
847
1.671875
2
[]
no_license
package com.path.mypath.photo_activity; import java.util.ArrayList; public interface SelectPhotoActivityPresenter { void onCatchUserPhotoByte(ArrayList<byte[]> photoArray); void onCatchUploadPhotoFailListener(String toString, int photoIndex); void onShowFinishInformation(); void onPublicConfirmClickListener(ArrayList<String> photoUrlArray, String articleTitle); void onPrivateConfirmClickListener(ArrayList<String> photoUrlArray, String articleTitle); void onAddButtonClickListener(); void onBackButtonClickListener(); void onBackConfirmClickListener(); void onFinishButtonClickListener(String articleTitle); void onCatchUserDataSuccessful(String json); void onCatchHomeDataSuccessful(String json); void onUpdateSuccessful(); void onCatchSearchPageDataSuccessful(String json); }
true
964643b346ab27ebc82bdf51e7e2c80208d54db8
Java
ahujadipak3/Learning
/TestProject/src/com/sample/programs/A2Authentication.java
UTF-8
236
1.96875
2
[]
no_license
package com.sample.programs; public class A2Authentication implements Authentication { @Override public boolean authenticate() { // TODO Auto-generated method stub System.out.println("A2 Authentication "); return false; } }
true
308d658de560df54fa31f8d1b02f4da4f14cca88
Java
ashtwentyfour/travelling_salesman_optimum_tour_length
/src/test/java/com/ashtwentyfour/algos/AppTest.java
UTF-8
754
2.765625
3
[]
no_license
package com.ashtwentyfour.algos; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Unit test for TSP App */ public class AppTest { /** * TSP Algo Test */ @Test public void shouldCalculateTourLength() { Double [][] C = new Double[4][4]; C[0][0] = 0.0; C[0][1] = 10.0; C[0][2] = 15.0; C[0][3] = 20.0; C[1][0] = 5.0; C[1][1] = 0.0; C[1][2] = 9.0; C[1][3] = 10.0; C[2][0] = 6.0; C[2][1] = 13.0; C[2][2] = 0.0; C[2][3] = 12.0; C[3][0] = 8.0; C[3][1] = 8.0; C[3][2] = 9.0; C[3][3] = 0.0; TSP optimum_tour = new TSP(); assertTrue( optimum_tour.optimum_tour_length(4 , 4 , 1 , C) == 35.0 ); } }
true
48175f40f696a227fdee38e25c818d4565d530e8
Java
ashpjin/TruckStop
/android/src/edu/ucla/cens/truckstop/services/RecordPath.java
UTF-8
3,504
2.28125
2
[]
no_license
package edu.ucla.cens.truckstop.services; import java.util.Timer; import java.util.TimerTask; import android.app.Service; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import edu.ucla.cens.truckstop.survey.CreateRoute; import edu.ucla.cens.truckstop.utils.*; import edu.ucla.cens.truckstop.R; public class RecordPath extends Service { private static final String TAG = "RecordPath"; private SurveyDB sdb; private CreateRoute survey; private Service ctx; private long PATH_PERIOD_MSECS, PATH_DURATION_MSECS; private static final long PATH_DURATION_DEFAULT = 3 * 60 * 60 * 1000; // Default to 3 hours private static final long PATH_PERIOD_DEFAULT = 5 * 60 * 1000; // Default to 5 minute private RequestLocation requestLoc; private Timer endTimer = null; @Override public void onCreate() { Log.d(TAG, "Started"); ctx = this; // Set up the database for the route survey. survey = new CreateRoute(ctx); sdb = new SurveyDB(survey.databaseTable(), survey.uploadURL(), survey.getDBKeys()); // Bind to the location service so we can get location. Log.d(TAG, "LightLocation service started"); requestLoc = new RequestLocation(this, new locationListener()); try { PATH_PERIOD_MSECS = Long.parseLong(getString(R.string.pathRequestPeriod)); } catch (NumberFormatException nfe) { PATH_PERIOD_MSECS = PATH_PERIOD_DEFAULT; } try { PATH_DURATION_MSECS = Long.parseLong(getString(R.string.pathRequestDuration).trim()); } catch (NumberFormatException nfe) { PATH_DURATION_MSECS = PATH_DURATION_DEFAULT; } Log.d(TAG, "Request location every secs: " + PATH_PERIOD_MSECS); requestLoc.startLocation(PATH_PERIOD_MSECS, ""); // Start the timer to kill this service endTimer = new Timer(); endTimer.schedule(endProcess, PATH_DURATION_MSECS, PATH_DURATION_MSECS); } private void saveRow(Location loc) { // Open the database and insert the row DBRow row = new DBRow(ctx, loc); sdb.openWriteable(ctx, survey.databaseTable()); sdb.insertEntry(ctx, row); sdb.close(); } TimerTask endProcess = new TimerTask() { public void run() { Log.d(TAG, "Ending process!"); ctx.stopSelf(); } public boolean cancel() { Log.d(TAG, "Cancelling the endprocess thread"); return true; } }; public class locationListener implements LocationListener { public void onLocationChanged (Location loc) { Log.d(TAG, "Received location: " + loc.toString()); saveRow(loc); } public void onProviderDisabled (String provider) {} public void onProviderEnabled (String provider) {} public void onStatusChanged (String provider, int status, Bundle extras) {} }; @Override public IBinder onBind(Intent arg0) { Log.d(TAG, "Somebody is binding to this service"); return null; } @Override public void onDestroy() { // Cancel the timer, in case it is still running endProcess.cancel(); // Unbind from the location service requestLoc.destroy(); } }
true
5b79966ba76b91ab6a4ca7faff15b7d9b280abfb
Java
manojkumar16/code-time
/src/main/java/etc/two/Test3.java
UTF-8
2,723
3.40625
3
[]
no_license
package etc.two; import java.util.Stack; public class Test3 { public static void main( String[] args ) { //Test3.swapSort( "11000" ); Test3.infixToPostfix( "*+56-78" ); new Test3().method(); } private void method() { } static String infixToPostfix( String s ) { char[] postfix=new char[s.length()]; char ch; Stack<Character> stk = new Stack<Character>(); int j=0; for(int i=0;i<s.length();i++) { ch=s.charAt(i); stk.push( '#'); if(!isOperator(ch)) { postfix[j++]=ch; } else if(isOperator(ch)) { stk.push( ch ); } else if(ch=='#') { char c = stk.pop(); while(c!='#') { postfix[j++]=c; c= stk.pop(); } } } System.out.println(postfix); return null; } /* static String infixToPostfix( String s ) { int j = 0; Stack<Character> stk = new Stack<Character>(); char[] postfix = new char[s.length()]; for ( int i = 0; i < s.length(); i++ ) { if ( isOperator( s.charAt( i ) ) ) { stk.push( s.charAt( i ) ); } else { postfix[j++] = s.charAt( i ); } while ( !stk.empty() && stk.pop() == '#' ) { //stk.pop(); postfix[j++] = stk.pop(); if(stk.size()>0) { stk.pop(); } } stk.push( '#' ); } String s1 = String.copyValueOf( postfix ); System.out.println( s1 ); return s1; }*/ private static boolean isOperator( char c ) { if ( c == '+' || c == '-' || c == '*' || c == '/' ) { return true; } return false; } static int swapSort( String s ) { int[] intArray = new int[s.length()]; for ( int i = 0; i < s.length(); i++ ) { if ( s.charAt( i ) == '0' ) { intArray[i] = 0; } else { intArray[i] = 1; } } int countOne = 0; int swapCount = 0; for ( int i = 0; i < intArray.length; i++ ) { if ( intArray[i] == 1 ) { countOne++; } else { swapCount += countOne; } } System.out.println( swapCount ); return swapCount; } private static void staticmethod() { } }
true
fa6483815bbd9093f95a90da01402c77cc7f6e76
Java
MDhondtRD/redoair
/ReDoAir-jar/src/test/java/com/realdolmen/redoair/persistence/TripRepositoryTest.java
UTF-8
12,678
2.6875
3
[]
no_license
package com.realdolmen.redoair.persistence; import com.realdolmen.redoair.ejb.FlightRepository; import com.realdolmen.redoair.ejb.TripRepository; import com.realdolmen.redoair.entities.Airport; import com.realdolmen.redoair.entities.Flight; import com.realdolmen.redoair.entities.Trip; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Collection; public class TripRepositoryTest extends DataPersistenceTest{ private TripRepository repo; private FlightRepository fRepo; private static boolean populated = false; private static int numberOfFutureTrips = 0; private static int numberOfFutureNoReturnFlightTrips = 0; private int numberOfLocations = 9; private Airport[] locations = new Airport[numberOfLocations]; private int factor1 = 10; private int factor2 = 8; private int factor3 = 6; private int factor4 = 4; private int numberOfCommonTrips = factor1 * numberOfLocations ; private int numberOfFlightOnlyTrips = factor2 * numberOfLocations; private int numberOfCommonTripsWithoutReturnFlight = factor3 * numberOfLocations; private int numberOfFlightOnlyTripsWithoutReturnFlight = factor4 * numberOfLocations; private int numberOfTrips = numberOfCommonTrips + numberOfFlightOnlyTrips + numberOfCommonTripsWithoutReturnFlight + numberOfFlightOnlyTripsWithoutReturnFlight; private int numberOfTripsByLocation = factor1 + factor2 + factor3 + factor4; @Before public void before() { initialiseRepositories(); if (!populated){ populateDatabase(); populated = true; } } @After public void after() { for (Trip t : repo.getAllTrips()) repo.removeTrip(t); repo.getEntityManager().flush(); for (Flight f : fRepo.getAllFlights()) fRepo.removeFlight(f); fRepo.getEntityManager().flush(); populated = false; numberOfFutureTrips = 0; numberOfFutureNoReturnFlightTrips = 0; } public void initialiseRepositories(){ repo = new TripRepository(); repo.setEntityManager(entityManager()); fRepo = new FlightRepository(); fRepo.setEntityManager(entityManager()); Airport a1 = new Airport("London", "abc", "UK", 0.0, 0.0); Airport a2 = new Airport("Paris", "abc", "UK", 0.0, 0.0); Airport a3 = new Airport("New York", "abc", "UK", 0.0, 0.0); Airport a4 = new Airport("Brussels", "abc", "Belgium", 0.0, 0.0); Airport a5 = new Airport("Madrid", "abc", "UK", 0.0, 0.0); Airport a6 = new Airport("Berlin", "abc", "UK", 0.0, 0.0); Airport a7 = new Airport("Rome", "abc", "UK", 0.0, 0.0); Airport a8 = new Airport("Lisbon", "abc", "UK", 0.0, 0.0); Airport a9 = new Airport("Athens", "abc", "UK", 0.0, 0.0); entityManager().persist(a1); entityManager().persist(a2); entityManager().persist(a3); entityManager().persist(a4); entityManager().persist(a5); entityManager().persist(a6); entityManager().persist(a7); entityManager().persist(a8); entityManager().persist(a9); entityManager().flush(); locations[0] = a1; locations[1] = a2; locations[2] = a3; locations[3] = a4; locations[4] = a5; locations[5] = a6; locations[6] = a7; locations[7] = a8; locations[8] = a9; } public void populateDatabase(){ // Generate <numberOfCommonTrips> trips (and twice as much flights) for (int i = 0; i < numberOfCommonTrips*2; i+=2){ LocalDateTime ldt1 = LocalDateTime.of(LocalDate.of(2015, 9 + (i/2 / 30), 1 + ((i/2) % 30)), LocalTime.now()); Flight f1 = new Flight("MD" + (1000 + i), locations[(i/2/factor1)%numberOfLocations], locations[(i/2/factor1+1)%numberOfLocations], ldt1, 15, 399.95); LocalDateTime ldt2 = LocalDateTime.of(LocalDate.of(2015, 9 + (((i/2)+1) / 30), 1 + (((i/2)+1) % 30)), LocalTime.now()); Flight f2 = new Flight("MD" + (1000 + i+1), locations[(i/2/factor1+1)%numberOfLocations], locations[(i/2/factor1)%numberOfLocations], ldt2, 15, 399.95); Trip t = new Trip(ldt1.toLocalDate(), ldt2.toLocalDate(), f1, f2, 49.95, "RD Travel"); fRepo.createFlight(f1); fRepo.createFlight(f2); repo.createTrip(t); if (ldt1.isAfter(LocalDateTime.now())) numberOfFutureTrips++; } // Generate <numberOfFlightOnlyTrips> trips (and twice as much flights) for (int i = 0; i < numberOfFlightOnlyTrips*2; i+=2){ LocalDateTime ldt1 = LocalDateTime.of(LocalDate.of(2015, 9 + (i/2 / 30), 1 + ((i/2) % 30)), LocalTime.now()); Flight f1 = new Flight("MD" + (2000 + i), locations[(i/2/factor2)%numberOfLocations], locations[(i/2/factor2+1)%numberOfLocations], ldt1, 15, 399.95); LocalDateTime ldt2 = LocalDateTime.of(LocalDate.of(2015, 9 + (((i/2)+1) / 30), 1 + (((i/2)+1) % 30)), LocalTime.now()); Flight f2 = new Flight("MD" + (2000 + i+1), locations[(i/2/factor2+1)%numberOfLocations], locations[(i/2/factor2)%numberOfLocations], ldt2, 15, 399.95); Trip t = new Trip(ldt1.toLocalDate(), ldt1.toLocalDate(), f1, f2, 0.0, "RD Travel"); fRepo.createFlight(f1); fRepo.createFlight(f2); repo.createTrip(t); if (ldt1.isAfter(LocalDateTime.now())) numberOfFutureTrips++; } // Generate <numberOfCommonTripsWithoutReturnFlight> trips (and as much flights) for (int i = 0; i < numberOfCommonTripsWithoutReturnFlight; i++){ LocalDateTime ldt1 = LocalDateTime.of(LocalDate.of(2015, 9 + (i / 30), 1 + (i % 30)), LocalTime.now()); Flight f = new Flight("MD" + (3000 + i), locations[(i/factor3)%numberOfLocations], locations[(i/factor3+1)%numberOfLocations], ldt1, 15, 399.95); LocalDateTime ldt2 = LocalDateTime.of(LocalDate.of(2015, 9 + ((i+5) / 30), 1 + ((i+5) % 30)), LocalTime.now()); Trip t = new Trip(ldt1.toLocalDate(), ldt2.toLocalDate(), f, null, 49.95, "RD Travel"); fRepo.createFlight(f); repo.createTrip(t); if (ldt1.isAfter(LocalDateTime.now())) { numberOfFutureTrips++; numberOfFutureNoReturnFlightTrips++; } } // Generate <numberOfFlightOnlyTripsWithoutReturnFlight> trips (and as much flights) for (int i = 0; i < numberOfFlightOnlyTripsWithoutReturnFlight; i++){ LocalDateTime ldt1 = LocalDateTime.of(LocalDate.of(2015, 9 + (i / 30), 1 + (i % 30)), LocalTime.now()); Flight f = new Flight("MD" + (4000 + i), locations[(i/factor4)%numberOfLocations], locations[(i/factor4+1)%numberOfLocations], ldt1, 15, 399.95); Trip t = new Trip(ldt1.toLocalDate(), ldt1.toLocalDate(), f, null, 0.0, "RD Travel"); fRepo.createFlight(f); repo.createTrip(t); if (ldt1.isAfter(LocalDateTime.now())){ numberOfFutureTrips++; numberOfFutureNoReturnFlightTrips++; } } fRepo.getEntityManager().flush(); repo.getEntityManager().flush(); } @Test public void canFindAllTrips(){ assertEquals(numberOfTrips, repo.getAllTrips().size()); } @Test public void canFindAllFutureTrips(){ assertEquals(numberOfFutureTrips, repo.getAllFutureTrips().size()); } @Test public void canFindTripsByID(){ int startIndex = repo.getEntityManager().createQuery("SELECT MIN(t.id) FROM Trip t", Integer.class).getSingleResult(); for (int i = startIndex; i <= numberOfTrips; i++) assertNotNull(repo.getTripById(i)); assertNull(repo.getTripById(startIndex + numberOfTrips)); } @Test public void canFindAllTripsByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals(numberOfTripsByLocation, repo.getAllTripsByDestination(locations[i].getCity()).size()); } @Test public void canFindAllFutureTripsByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals( findTripsByDestination(repo.getAllFutureTrips(), locations[i].getCity()), repo.getAllFutureTripsByDestination(locations[i].getCity()).size()); } @Test public void canFindAllTripsWithoutReturnFlight(){ assertEquals(numberOfCommonTripsWithoutReturnFlight + numberOfFlightOnlyTripsWithoutReturnFlight, repo.getAllTripsWithoutReturnFlight().size()); } @Test public void canFindAllTripsWithoutReturnFlightByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals( findTripsByDestination(repo.getAllTripsWithoutReturnFlight(), locations[i].getCity()), repo.getAllTripsWithoutReturnFlightByDestination(locations[i].getCity()).size()); } @Test public void canFindAllFutureTripsWithoutReturnFlight(){ assertEquals(numberOfFutureNoReturnFlightTrips, repo.getAllFutureTripsWithoutReturnFlight().size()); } @Test public void canFindAllFutureTripsWithoutReturnFlightByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals( findTripsByDestination(repo.getAllFutureTripsWithoutReturnFlight(), locations[i].getCity()), repo.getAllFutureTripsWithoutReturnFlightByDestination(locations[i].getCity()).size()); } @Test public void canFindAllFlightOnlyTrips(){ assertEquals(numberOfFlightOnlyTrips + numberOfFlightOnlyTripsWithoutReturnFlight, repo.getAllFlightOnlyTrips().size()); } @Test public void canFindAllFlightOnlyTripsByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals( findTripsByDestination(repo.getAllFlightOnlyTrips(), locations[i].getCity()), repo.getAllFlightOnlyTripsByDestination(locations[i].getCity()).size()); } @Test public void canFindFutureFlightOnlyTrips(){ assertNotNull(repo.getAllFutureFlightOnlyTrips()); assertTrue(repo.getAllFutureFlightOnlyTrips().size() <= numberOfFutureTrips); assertTrue(repo.getAllFutureFlightOnlyTrips().size() <= numberOfFlightOnlyTrips + numberOfFlightOnlyTripsWithoutReturnFlight); } @Test public void canFindAllFutureFlightOnlyTripsByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals( findTripsByDestination(repo.getAllFutureFlightOnlyTrips(), locations[i].getCity()), repo.getAllFutureFlightOnlyTripsByDestination(locations[i].getCity()).size()); } @Test public void canFindAllFlightOnlyTripsWithoutReturnFlight(){ assertNotNull(repo.getAllFlightOnlyTripsWithoutReturnFlight()); assertTrue(repo.getAllFlightOnlyTripsWithoutReturnFlight().size() <= numberOfFlightOnlyTripsWithoutReturnFlight); } @Test public void canFindAllFlightOnlyTripsWithoutReturnFlightByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals( findTripsByDestination(repo.getAllFlightOnlyTripsWithoutReturnFlight(), locations[i].getCity()), repo.getAllFlightOnlyTripsWithoutReturnFlightByDestination(locations[i].getCity()).size()); } @Test public void canFindAllFutureFlightOnlyTripsWithoutReturnFlight(){ assertNotNull(repo.getAllFutureFlightOnlyTripsWithoutReturnFlight()); assertTrue(repo.getAllFutureFlightOnlyTripsWithoutReturnFlight().size() <= numberOfFutureTrips); assertTrue(repo.getAllFutureFlightOnlyTripsWithoutReturnFlight().size() <= numberOfFlightOnlyTripsWithoutReturnFlight); } @Test public void canFindAllFutureFlightOnlyTripsWithoutReturnFlightByDestination(){ for (int i = 0; i < numberOfLocations; i++) assertEquals( findTripsByDestination(repo.getAllFutureFlightOnlyTripsWithoutReturnFlight(), locations[i].getCity()), repo.getAllFutureFlightOnlyTripsWithoutReturnFlightByDestination(locations[i].getCity()).size()); } private int findTripsByDestination(Collection<Trip> trips, String destination){ int c = 0; for (Trip t : trips) if (t.getOutFlight().getDestinationCity().equals(destination)) c++; return c; } }
true
2f8647dd0c722c28eed531ad8791c7014923bc84
Java
JavaQualitasCorpus/nakedobjects-4.0.0
/core/metamodel/src/main/java/org/nakedobjects/metamodel/facets/SingleClassValueFacetAbstract.java
UTF-8
1,224
2.359375
2
[ "Apache-2.0" ]
permissive
package org.nakedobjects.metamodel.facets; import org.nakedobjects.metamodel.spec.NakedObjectSpecification; import org.nakedobjects.metamodel.specloader.SpecificationLoader; public abstract class SingleClassValueFacetAbstract extends FacetAbstract implements SingleClassValueFacet { private final Class<?> value; private final SpecificationLoader specificationLoader; public SingleClassValueFacetAbstract( final Class<? extends Facet> facetType, final FacetHolder holder, final Class<?> value, final SpecificationLoader specificationLoader) { super(facetType, holder, false); this.value = value; this.specificationLoader = specificationLoader; } public Class<?> value() { return value; } /** * The {@link NakedObjectSpecification} of the {@link #value()}. */ public NakedObjectSpecification valueSpec() { final Class<?> valueType = value(); return valueType != null ? getSpecificationLoader().loadSpecification(valueType) : null; } private SpecificationLoader getSpecificationLoader() { return specificationLoader; } }
true
89e81086cdc7bb89df4297eaa99158a7d6235210
Java
samalprasant123/SpringJSONAndAJAX
/test/com/prasant/spring/mvc/test/tests/OfferDAOTest.java
UTF-8
4,026
2.3125
2
[]
no_license
package com.prasant.spring.mvc.test.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.List; import javax.sql.DataSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.prasant.spring.mvc.dao.OfferDAO; import com.prasant.spring.mvc.dao.UserDAO; import com.prasant.spring.mvc.model.Offer; import com.prasant.spring.mvc.model.User; @ActiveProfiles("test") @ContextConfiguration(locations = { "classpath:com/prasant/spring/mvc/config/dao-context.xml", "classpath:com/prasant/spring/mvc/test/config/dataSource.xml", "classpath:com/prasant/spring/mvc/config/security-context.xml" }) @RunWith(SpringJUnit4ClassRunner.class) public class OfferDAOTest { @Autowired public DataSource dataSource; @Autowired public OfferDAO offerDao; @Autowired public UserDAO userDao; private User user1 = new User("grout", "grout@email.com", "password", true, "ROLE_USER", "Gayatree Rout"); private Offer offer1 = new Offer(user1, "I write awesome contents."); private User user2 = new User("testuser", "testuser@email.com", "password", true, "ROLE_USER", "Test User"); private Offer offer2 = new Offer(user2, "This is a test offer."); @Before public void init() { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("DELETE FROM offer"); jdbcTemplate.execute("DELETE FROM messages"); jdbcTemplate.execute("DELETE FROM users"); } @Test public void create() { userDao.create(user1); offerDao.create(offer1); } @Test public void update() { userDao.create(user1); offerDao.create(offer1); offer1.setText("Updated text"); offerDao.update(offer1); List<Offer> offers1 = offerDao.getOffersByUserName("grout"); assertEquals("Offer retrieved should match offer created", offer1, offers1.get(0)); } @Test public void saveOrUpdate() { userDao.create(user1); offerDao.saveOrUpdate(offer1); offer1.setText("Updated text"); offerDao.saveOrUpdate(offer1); List<Offer> offers1 = offerDao.getOffersByUserName("grout"); assertEquals("Offer retrieved should match offer created", offer1, offers1.get(0)); } @Test public void getOffers() { userDao.create(user1); offerDao.create(offer1); List<Offer> offers1 = offerDao.getOffers(); assertEquals("There should be one offer", 1, offers1.size()); userDao.create(user2); offerDao.create(offer2); List<Offer> offers2 = offerDao.getOffers(); assertEquals("There should be two offers", 2, offers2.size()); } @Test public void getOffersByUserName() { userDao.create(user1); offerDao.create(offer1); List<Offer> offers1 = offerDao.getOffersByUserName("grout"); assertEquals("There should be one offer", 1, offers1.size()); assertEquals("Offer retrieved should match offer created", offer1, offers1.get(0)); } @Test public void getOfferById() { userDao.create(user1); offerDao.create(offer1); List<Offer> offers1 = offerDao.getOffersByUserName("grout"); int id = offers1.get(0).getId(); Offer offer = offerDao.getOfferById(id); assertEquals("Offer retrieved should match offer created", offer1, offer); } @Test public void delete() { userDao.create(user1); offerDao.create(offer1); List<Offer> offers1 = offerDao.getOffersByUserName("grout"); assertEquals("There should be one offer", 1, offers1.size()); assertEquals("Offer retrieved should match offer created", offer1, offers1.get(0)); int id = offers1.get(0).getId(); offerDao.delete(id); Offer offer2 = offerDao.getOfferById(id); assertNull(offer2); } }
true
48643023257dab29b82863d97577ba9c5ddba15c
Java
elliottwang/ESB
/EAB/EABManager/src/eab/deploy/zip/JbiSuBuilder.java
UTF-8
1,080
2.53125
3
[]
no_license
package eab.deploy.zip; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class JbiSuBuilder { public static final String DESCRIPTOR_FILE = "META-INF/jbi.xml"; public static byte[] buildSu(HashMap<String, String> suContent, String jbi) { ByteArrayOutputStream baos = new ByteArrayOutputStream(100000); ZipOutputStream zos = null; try { zos = new ZipOutputStream(baos); // write su content files for (Map.Entry<String, String> entry : suContent.entrySet()) { zos.putNextEntry(new ZipEntry(entry.getKey())); zos.write(entry.getValue().getBytes()); } // write su jbi description zos.putNextEntry(new ZipEntry(DESCRIPTOR_FILE)); zos.write(jbi.getBytes()); zos.flush(); } catch (Exception e) { e.printStackTrace(); } finally{ if(zos != null){ try { zos.close(); } catch (IOException e) { e.printStackTrace(); } } } return baos.toByteArray(); } }
true