Unnamed: 0
int64 0
9.45k
| cwe_id
stringclasses 1
value | source
stringlengths 37
2.53k
| target
stringlengths 19
2.4k
|
---|---|---|---|
100 | public void stopVideo(){
stopSyncSubtitle();
if (mVideoView != null) {
Log.d(TAG, "stopVideo() => Time" + mVideoView.getCurrentPosition());
mUserTask.setTimeWatched(mVideoView.getCurrentPosition());
mVideoView.stopPlayback();
Bundle bundle = new Bundle();
bundle.putString(FIREBASE_KEY_VIDEO_ID, mSelectedTask.video.videoId);
bundle.putString(FIREBASE_KEY_PRIMARY_AUDIO_LANGUAGE, mSelectedTask.video.primaryAudioLanguageCode);
mFirebaseAnalytics.logEvent(FIREBASE_LOG_EVENT_PRESSED_STOP_VIDEO, bundle);
}
} | public void stopVideo(){
stopSyncSubtitle();
if (mVideoView != null) {
Log.d(TAG, "stopVideo() => Time" + mVideoView.getCurrentPosition());
mUserTask.setTimeWatched(mVideoView.getCurrentPosition());
mVideoView.stopPlayback();
firebaseLoginEvents(FIREBASE_LOG_EVENT_PRESSED_VIDEO_STOP);
}
} |
|
101 | public static void removePrimaryQuestions(String[] primarySecurityQuestion, int tenantId) throws IdentityException{
JDBCUserRecoveryDataStore store = new JDBCUserRecoveryDataStore();
UserRecoveryDataDO[] metadata = new UserRecoveryDataDO[primarySecurityQuestion.length];
int i = 0;
for (String secQuestion : primarySecurityQuestion) {
if (!secQuestion.contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI)) {
throw new IdentityException("One or more security questions does not contain the namespace " + UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI);
}
metadata[i++] = new UserRecoveryDataDO("TENANT", tenantId, UserRecoveryDataDO.METADATA_PRIMARAY_SECURITY_QUESTION, secQuestion);
}
} | public static void removePrimaryQuestions(String[] primarySecurityQuestion, int tenantId) throws IdentityException{
UserRecoveryDataDO[] metadata = new UserRecoveryDataDO[primarySecurityQuestion.length];
int i = 0;
for (String secQuestion : primarySecurityQuestion) {
if (!secQuestion.contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI)) {
throw new IdentityException("One or more security questions does not contain the namespace " + UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI);
}
metadata[i++] = new UserRecoveryDataDO("TENANT", tenantId, UserRecoveryDataDO.METADATA_PRIMARAY_SECURITY_QUESTION, secQuestion);
}
} |
|
102 | public ResponseEntity<Player> getPlayer(@PathVariable Long game_id, @PathVariable Long player_id){
HttpStatus status;
Player returnPlayer = null;
Game game = gameRepository.findById(game_id).get();
Set<Player> players = game.getPlayers();
for (Player player : players) {
if (player.getId() == player_id) {
returnPlayer = player;
}
}
if (returnPlayer == null) {
status = HttpStatus.NO_CONTENT;
} else {
status = HttpStatus.OK;
}
return new ResponseEntity<>(returnPlayer, status);
} | public ResponseEntity<Player> getPlayer(@PathVariable Long game_id, @PathVariable Long player_id){
HttpStatus status;
Player player = playerRepository.findById(player_id).get();
if (player == null) {
status = HttpStatus.NO_CONTENT;
} else {
status = HttpStatus.OK;
}
return new ResponseEntity<>(player, status);
} |
|
103 | public void logout(){
if (mGameHelper != null) {
mGameHelper.signOut();
mGameHelper.setmListener(null);
LogD("Signed out");
UserWrapper.onActionResult(mUserGooglePlay, UserWrapper.ACTION_RET_LOGOUT_SUCCEED, "Google Play: logout successful.");
} else {
LogD("Please configure first");
UserWrapper.onActionResult(mUserGooglePlay, UserWrapper.ACTION_RET_LOGOUT_FAILED, "Google Play: not configured yet.");
}
} | public void logout(){
if (mGameHelper != null) {
mGameHelper.signOut();
LogD("Signed out");
UserWrapper.onActionResult(mUserGooglePlay, UserWrapper.ACTION_RET_LOGOUT_SUCCEED, "Google Play: logout successful.");
} else {
LogD("Please configure first");
UserWrapper.onActionResult(mUserGooglePlay, UserWrapper.ACTION_RET_LOGOUT_FAILED, "Google Play: not configured yet.");
}
} |
|
104 | private Node createTree(char[] arr, Node parent, Node current, int i, HashMap<Character, Node> map){
if (i < arr.length) {
Node temp = new Node(arr[i]);
current = temp;
current.setParent(parent);
current.setLeft(this.createTree(arr, current, current.getLeft(), 2 * i + 1, map));
current.setRight(this.createTree(arr, current, current.getRight(), 2 * i + 2, map));
map.put(current.getValue(), current);
}
return current;
} | private Node createTree(char[] arr, Node parent, Node current, int i, HashMap<Character, Node> map){
if (i < arr.length) {
current = new Node(arr[i]);
current.setParent(parent);
current.setLeft(this.createTree(arr, current, current.getLeft(), 2 * i + 1, map));
current.setRight(this.createTree(arr, current, current.getRight(), 2 * i + 2, map));
map.put(current.getValue(), current);
}
return current;
} |
|
105 | public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState){
Log.e("ASD", "newState = " + newState);
} | public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState){
} |
|
106 | public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRetainInstance(true);
if (getArguments() != null)
search = getArguments().getString(SEARCH_PARAM);
isLoadingArticles = new AtomicBoolean(false);
} | public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRetainInstance(true);
if (getArguments() != null)
search = getArguments().getString(SEARCH_PARAM);
} |
|
107 | public static JSONObject networkInfo() throws SigarException, IOException{
JSONObject net = new JSONObject();
URL getPublic = new URL("http://checkip.amazonaws.com");
BufferedReader buffer = new BufferedReader(new InputStreamReader(getPublic.openStream()));
String publicIP = buffer.readLine();
InetAddress localIP = InetAddress.getLocalHost();
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
String local = localIP.getHostAddress().toString();
String address = inetAddress.getHostAddress().toString();
if (local.equalsIgnoreCase(address)) {
String netName = netint.getName();
System.out.println("NETWORK ADAPATER NAME: " + netName);
}
}
}
net.put("ip_address", localIP.getHostAddress());
net.put("hostname", sigar.getNetInfo().getHostName());
net.put("gateway", sigar.getNetInfo().getDefaultGateway());
net.put("public_ip", publicIP);
return net;
} | public static JSONObject networkInfo() throws SigarException, IOException{
JSONObject net = new JSONObject();
URL getPublic = new URL("http://checkip.amazonaws.com");
BufferedReader buffer = new BufferedReader(new InputStreamReader(getPublic.openStream()));
String publicIP = buffer.readLine();
InetAddress localIP = InetAddress.getLocalHost();
net.put("ip_address", localIP.getHostAddress());
net.put("hostname", sigar.getNetInfo().getHostName());
net.put("gateway", sigar.getNetInfo().getDefaultGateway());
net.put("public_ip", publicIP);
return net;
} |
|
108 | public void setup(){
config = getTorbitConfig();
List<String> clouds = getClouds();
assumeTrue(config != null && clouds.size() >= 2);
mtdHandler = new MtdHandler();
mtdHandler.timeOut = "2s";
mtdHandler.retryDelay = "30s";
mtdHandler.interval = "5s";
mtdHandler.failureCountToMarkDown = 3;
mtdHandler.gson = new Gson();
mtdHandler.jsonParser = new JsonParser();
cloud1 = clouds.get(0);
cloud2 = clouds.get(1);
} | public void setup(){
config = getTorbitConfig();
mtdHandler = new MtdHandler();
List<String> clouds = getClouds();
assumeTrue(config != null && clouds.size() >= 2);
cloud1 = clouds.get(0);
cloud2 = clouds.get(1);
} |
|
109 | private void initACTextViews(){
HashMap<String, BusStop[]> busTagsToBusStops = RUDirectApplication.getBusData().getBusTagToBusStops();
if (busTagsToBusStops != null) {
BusStop[] busStopArray = RUDirectApplication.getBusData().getBusStops();
ArrayAdapter<BusStop> busStopArrayAdapter = new ArrayAdapter<>(mainActivity, R.layout.list_autocomplete_textview, busStopArray);
setupACTextView(originACTextView, busStopArrayAdapter);
setupACTextView(destACTextView, busStopArrayAdapter);
setOriginToNearestBusStop();
}
} | private void initACTextViews(){
BusStop[] busStopArray = RUDirectApplication.getBusData().getAllBusStops();
if (busStopArray != null) {
ArrayAdapter<BusStop> busStopArrayAdapter = new ArrayAdapter<>(mainActivity, R.layout.list_autocomplete_textview, busStopArray);
setupACTextView(originACTextView, busStopArrayAdapter);
setupACTextView(destACTextView, busStopArrayAdapter);
setOriginToNearestBusStop();
}
} |
|
110 | public InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException{
SparkInterpreter sparkInterpreter = getSparkInterpreter();
if (sparkInterpreter.isUnsupportedSparkVersion()) {
return new InterpreterResult(Code.ERROR, "Spark " + sparkInterpreter.getSparkVersion().toString() + " is not supported");
}
sparkInterpreter.getZeppelinContext().setInterpreterContext(context);
SQLContext sqlc = sparkInterpreter.getSQLContext();
SparkContext sc = sqlc.sparkContext();
sc.setLocalProperty("spark.scheduler.pool", context.getLocalProperties().get("pool"));
sc.setJobGroup(Utils.buildJobGroupId(context), Utils.buildJobDesc(context), false);
Object rdd = null;
try {
Method sqlMethod = sqlc.getClass().getMethod("sql", String.class);
String effectiveString = Boolean.parseBoolean(getProperty("zeppelin.spark.sql.interpolation")) ? interpolate(st, context.getResourcePool()) : st;
rdd = sqlMethod.invoke(sqlc, effectiveString);
} catch (InvocationTargetException ite) {
if (Boolean.parseBoolean(getProperty("zeppelin.spark.sql.stacktrace"))) {
throw new InterpreterException(ite);
}
logger.error("Invocation target exception", ite);
String msg = ite.getTargetException().getMessage() + "\nset zeppelin.spark.sql.stacktrace = true to see full stacktrace";
return new InterpreterResult(Code.ERROR, msg);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
throw new InterpreterException(e);
}
String msg = sparkInterpreter.getZeppelinContext().showData(rdd);
sc.clearJobGroup();
return new InterpreterResult(Code.SUCCESS, msg);
} | public InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException{
if (sparkInterpreter.isUnsupportedSparkVersion()) {
return new InterpreterResult(Code.ERROR, "Spark " + sparkInterpreter.getSparkVersion().toString() + " is not supported");
}
sparkInterpreter.getZeppelinContext().setInterpreterContext(context);
SQLContext sqlc = sparkInterpreter.getSQLContext();
SparkContext sc = sqlc.sparkContext();
sc.setLocalProperty("spark.scheduler.pool", context.getLocalProperties().get("pool"));
sc.setJobGroup(Utils.buildJobGroupId(context), Utils.buildJobDesc(context), false);
Object rdd = null;
try {
Method sqlMethod = sqlc.getClass().getMethod("sql", String.class);
String effectiveString = Boolean.parseBoolean(getProperty("zeppelin.spark.sql.interpolation")) ? interpolate(st, context.getResourcePool()) : st;
rdd = sqlMethod.invoke(sqlc, effectiveString);
} catch (InvocationTargetException ite) {
if (Boolean.parseBoolean(getProperty("zeppelin.spark.sql.stacktrace"))) {
throw new InterpreterException(ite);
}
logger.error("Invocation target exception", ite);
String msg = ite.getTargetException().getMessage() + "\nset zeppelin.spark.sql.stacktrace = true to see full stacktrace";
return new InterpreterResult(Code.ERROR, msg);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
throw new InterpreterException(e);
}
String msg = sparkInterpreter.getZeppelinContext().showData(rdd);
sc.clearJobGroup();
return new InterpreterResult(Code.SUCCESS, msg);
} |
|
111 | public void testPrime(){
Assert.assertTrue(PrimeGenerator.isPrime(5));
Assert.assertFalse(PrimeGenerator.isPrime(1));
for (int no : PrimeGenerator.getAllPrimes(10)) {
System.out.println(no);
}
Assert.assertArrayEquals(new int[] { 2, 3, 5, 7 }, PrimeGenerator.getAllPrimes(10));
Assert.assertArrayEquals(PrimeGenerator.getAllPrimes(10), PrimeGenerator.getPrimesViaSieve(10));
Assert.assertArrayEquals(PrimeGenerator.getAllPrimes(100), PrimeGenerator.getPrimesViaSieve(100));
} | public void testPrime(){
Assert.assertTrue(PrimeGenerator.isPrime(5));
Assert.assertFalse(PrimeGenerator.isPrime(1));
Assert.assertArrayEquals(new int[] { 2, 3, 5, 7 }, PrimeGenerator.getAllPrimes(10));
Assert.assertArrayEquals(PrimeGenerator.getAllPrimes(10), PrimeGenerator.getPrimesViaSieve(10));
Assert.assertArrayEquals(PrimeGenerator.getAllPrimes(100), PrimeGenerator.getPrimesViaSieve(100));
} |
|
112 | public void connectionAdded(Server server, HostedConnection con){
LOGGER.info("Client id [{}] from [{}] is now connected.", con.getId(), con.getAddress());
Message msg = new ShutdownServerMessage("toto");
server.broadcast(msg);
} | public void connectionAdded(Server server, HostedConnection con){
LOGGER.info("Client id [{}] from [{}] is now connected.", con.getId(), con.getAddress());
server.broadcast(new ShutdownServerMessage("Closing for maintenance in few minutes."));
} |
|
113 | public List<Diff> apply(Object beforeObject, Object afterObject, String description){
List<Diff> diffs = new LinkedList<>();
Collection before = (Collection) beforeObject;
Collection after = (Collection) afterObject;
if (!isNullOrEmpty(before) && isNullOrEmpty(after)) {
for (Object object : before) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description));
}
} else if (isNullOrEmpty(before) && !isNullOrEmpty(after)) {
for (Object object : after) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(null, object, description));
}
} else {
for (Object object : before) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, findCorrespondingObject(object, after), description));
} else {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, getCorrespondingObject(object, after), description));
}
}
List<Diff> temp;
for (Object object : after) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
temp = getDiffComputeEngine().evaluateAndExecute(findCorrespondingObject(object, before), object, description);
} else {
temp = getDiffComputeEngine().evaluateAndExecute(getCorrespondingObject(object, before), object, description);
}
if (temp != null && temp.size() > 0) {
temp.removeIf(delta -> delta.getChangeType().equals(ChangeType.NO_CHANGE) || delta.getChangeType().equals(ChangeType.UPDATED));
diffs.addAll(temp);
}
}
}
return diffs;
} | public List<Diff> apply(Object beforeObject, Object afterObject, String description){
List<Diff> diffs = new LinkedList<>();
Collection before = (Collection) beforeObject;
Collection after = (Collection) afterObject;
if (!isNullOrEmpty(before) && isNullOrEmpty(after)) {
before.forEach(object -> diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description)));
} else if (isNullOrEmpty(before) && !isNullOrEmpty(after)) {
after.forEach(object -> diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description)));
} else {
for (Object object : before) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, findCorrespondingObject(object, after), description));
} else {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, getCorrespondingObject(object, after), description));
}
}
List<Diff> temp = new LinkedList<>();
for (Object object : after) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
temp.addAll(getDiffComputeEngine().evaluateAndExecute(findCorrespondingObject(object, before), object, description));
} else {
temp.addAll(getDiffComputeEngine().evaluateAndExecute(getCorrespondingObject(object, before), object, description));
}
}
if (temp != null && temp.size() > 0) {
temp.removeIf(delta -> delta.getChangeType().equals(ChangeType.NO_CHANGE) || delta.getChangeType().equals(ChangeType.UPDATED));
diffs.addAll(temp);
}
}
return diffs;
} |
|
114 | private void selectAndReveal(final ISelection selection){
IWorkbenchPage page = fSite.getPage();
if (page == null)
return;
List<IWorkbenchPart> parts = new ArrayList<IWorkbenchPart>();
IWorkbenchPartReference[] refs = page.getViewReferences();
for (int i = 0; i < refs.length; i++) {
IWorkbenchPart part = refs[i].getPart(false);
if (part != null)
parts.add(part);
}
refs = page.getEditorReferences();
for (int i = 0; i < refs.length; i++) {
if (refs[i].getPart(false) != null)
parts.add(refs[i].getPart(false));
}
for (IWorkbenchPart part : parts) {
ISetSelectionTarget target = null;
if (part instanceof ISetSelectionTarget)
target = (ISetSelectionTarget) part;
else
target = part.getAdapter(ISetSelectionTarget.class);
if (target != null) {
final ISetSelectionTarget finalTarget = target;
page.getWorkbenchWindow().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
finalTarget.selectReveal(selection);
}
});
}
}
} | private void selectAndReveal(final ISelection selection){
IWorkbenchPage page = fSite.getPage();
if (page == null)
return;
List<IWorkbenchPart> parts = new ArrayList<IWorkbenchPart>();
IWorkbenchPartReference[] refs = page.getViewReferences();
for (int i = 0; i < refs.length; i++) {
IWorkbenchPart part = refs[i].getPart(false);
if (part != null)
parts.add(part);
}
refs = page.getEditorReferences();
for (int i = 0; i < refs.length; i++) {
if (refs[i].getPart(false) != null)
parts.add(refs[i].getPart(false));
}
for (IWorkbenchPart part : parts) {
ISetSelectionTarget target = null;
if (part instanceof ISetSelectionTarget)
target = (ISetSelectionTarget) part;
else
target = part.getAdapter(ISetSelectionTarget.class);
if (target != null) {
final ISetSelectionTarget finalTarget = target;
page.getWorkbenchWindow().getShell().getDisplay().asyncExec(() -> finalTarget.selectReveal(selection));
}
}
} |
|
115 | public boolean hasSameMethod(Invocation candidate){
Method m1 = invocation.getMethod();
Method m2 = candidate.getMethod();
if (m1.getName() != null && m1.getName().equals(m2.getName())) {
Class<?>[] params1 = m1.getParameterTypes();
Class<?>[] params2 = m2.getParameterTypes();
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i])
return false;
}
return true;
}
}
return false;
} | public boolean hasSameMethod(Invocation candidate){
Method m1 = invocation.getMethod();
Method m2 = candidate.getMethod();
if (m1.getName() != null && m1.getName().equals(m2.getName())) {
Class<?>[] params1 = m1.getParameterTypes();
Class<?>[] params2 = m2.getParameterTypes();
return Arrays.equals(params1, params2);
}
return false;
} |
|
116 | public final ASTNode visitExpr(final ExprContext ctx){
if (null != ctx.booleanPrimary()) {
return visit(ctx.booleanPrimary());
}
if (null != ctx.LP_()) {
return visit(ctx.expr(0));
}
if (null != ctx.logicalOperator()) {
BinaryOperationExpression result = new BinaryOperationExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setLeft((ExpressionSegment) visit(ctx.expr(0)));
result.setRight((ExpressionSegment) visit(ctx.expr(1)));
result.setOperator(ctx.logicalOperator().getText());
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
result.setText(text);
return result;
}
NotExpression result = new NotExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setExpression((ExpressionSegment) visit(ctx.expr(0)));
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
result.setText(text);
return result;
} | public final ASTNode visitExpr(final ExprContext ctx){
if (null != ctx.booleanPrimary()) {
return visit(ctx.booleanPrimary());
}
if (null != ctx.LP_()) {
return visit(ctx.expr(0));
}
if (null != ctx.logicalOperator()) {
BinaryOperationExpression result = new BinaryOperationExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setLeft((ExpressionSegment) visit(ctx.expr(0)));
result.setRight((ExpressionSegment) visit(ctx.expr(1)));
result.setOperator(ctx.logicalOperator().getText());
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
result.setText(text);
return result;
}
NotExpression result = new NotExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setExpression((ExpressionSegment) visit(ctx.expr(0)));
return result;
} |
|
117 | public void testDeleteProcessDefinitionById() throws Exception{
String projectName = "test";
int id = 1;
Map<String, Object> result = new HashMap<>();
putMsg(result, Status.SUCCESS);
Mockito.when(processDefinitionService.deleteProcessDefinitionById(user, projectName, id)).thenReturn(result);
Result response = processDefinitionController.deleteProcessDefinitionById(user, projectName, id);
Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue());
} | public void testDeleteProcessDefinitionById() throws Exception{
String projectName = "test";
int id = 1;
Result<Void> result = Result.success(null);
Mockito.when(processDefinitionService.deleteProcessDefinitionById(user, projectName, id)).thenReturn(result);
Result<Void> response = processDefinitionController.deleteProcessDefinitionById(user, projectName, id);
Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue());
} |
|
118 | public Vector4d set(Vector3fc v, double w){
this.x = v.x();
this.y = v.y();
this.z = v.z();
this.w = w;
return this;
} | public Vector4d set(Vector3fc v, double w){
return set(v.x(), v.y(), v.z(), w);
} |
|
119 | protected Module createModule(CConfiguration cConf, Configuration hConf, TwillContext context, ProgramId programId, String runId, String instanceId, @Nullable String principal){
Module module = super.createModule(cConf, hConf, context, programId, runId, instanceId, principal);
return new AbstractModule() {
@Override
protected void configure() {
install(module);
install(new DistributedArtifactManagerModule());
}
};
} | protected Module createModule(CConfiguration cConf, Configuration hConf, ProgramOptions programOptions, ProgramRunId programRunId){
Module module = super.createModule(cConf, hConf, programOptions, programRunId);
return Modules.combine(module, new DistributedArtifactManagerModule());
} |
|
120 | public String jsonRestTagBarcodes(@RequestParam("barcodeStrategy") String barcodeStrategy, @RequestParam("position") String position) throws IOException{
if (!isStringEmptyOrNull(barcodeStrategy)) {
TagBarcodeStrategy tbs = tagBarcodeStrategyResolverService.getTagBarcodeStrategy(barcodeStrategy);
if (tbs != null) {
List<TagBarcode> tagBarcodes = new ArrayList<TagBarcode>(tbs.getApplicableBarcodesForPosition(Integer.parseInt(position)));
List<String> names = new ArrayList<String>();
for (TagBarcode tb : tagBarcodes) {
names.add("\"" + tb.getId() + "\"" + ":" + "\"" + tb.getName() + " (" + tb.getSequence() + ")\"");
}
return "{" + LimsUtils.join(names, ",") + "}";
} else {
return "{}";
}
} else {
return "{}";
}
} | public String jsonRestTagBarcodes(@RequestParam("barcodeStrategy") String barcodeStrategy, @RequestParam("position") String position) throws IOException{
if (!isStringEmptyOrNull(barcodeStrategy)) {
TagBarcodeFamily tbs = tagBarcodeStore.getTagBarcodeFamilyByName(barcodeStrategy);
if (tbs != null) {
List<String> names = new ArrayList<String>();
for (TagBarcode tb : tbs.getBarcodesForPosition(Integer.parseInt(position))) {
names.add("\"" + tb.getId() + "\"" + ":" + "\"" + tb.getName() + " (" + tb.getSequence() + ")\"");
}
return "{" + LimsUtils.join(names, ",") + "}";
} else {
return "{}";
}
} else {
return "{}";
}
} |
|
121 | public Result importProcessDefinition(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("file") MultipartFile file, @RequestParam("projectName") String projectName){
logger.info("import process definition by id, login user:{}, project: {}", loginUser.getUserName(), projectName);
Map<String, Object> result = processDefinitionService.importProcessDefinition(loginUser, file, projectName);
return returnDataList(result);
} | public Result<Void> importProcessDefinition(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("file") MultipartFile file, @RequestParam("projectName") String projectName){
logger.info("import process definition by id, login user:{}, project: {}", loginUser.getUserName(), projectName);
return processDefinitionService.importProcessDefinition(loginUser, file, projectName);
} |
|
122 | public void onMessageReceived(CastDevice castDevice, String namespace, String message){
synchronized (mVideoConsumers) {
for (IVideoCastConsumer consumer : mVideoConsumers) {
try {
consumer.onDataMessageReceived(message);
} catch (Exception e) {
LOGE(TAG, "onMessageReceived(): Failed to inform " + consumer, e);
}
}
}
} | public void onMessageReceived(CastDevice castDevice, String namespace, String message){
for (IVideoCastConsumer consumer : mVideoConsumers) {
try {
consumer.onDataMessageReceived(message);
} catch (Exception e) {
LOGE(TAG, "onMessageReceived(): Failed to inform " + consumer, e);
}
}
} |
|
123 | public void calculateArgument8Test(){
StringBuilder xml_ = new StringBuilder();
xml_.append("$public $class pkg.Ex {\n");
xml_.append(" $public $static String exmeth(){\n");
xml_.append(" $return $staticCall(ExTwo<String>).exmeth(\"string\");\n");
xml_.append(" }\n");
xml_.append("}\n");
xml_.append("$public $class pkg.ExTwo<T> {\n");
xml_.append(" $public $staticCall String exmeth(T t){\n");
xml_.append(" String o=\"\";\n");
xml_.append(" $switch(t){\n");
xml_.append(" $case $null:\n");
xml_.append(" o=\"null\";\n");
xml_.append(" $case T v:\n");
xml_.append(" o=v+\" String\";\n");
xml_.append(" $case StringBuilder v:\n");
xml_.append(" o=v+\" StringBuilder\";\n");
xml_.append(" }\n");
xml_.append(" $return o;\n");
xml_.append(" }\n");
xml_.append("}\n");
StringMap<String> files_ = new StringMap<String>();
ContextEl cont_ = ctx();
files_.put("pkg/Ex", xml_.toString());
Classes.validateAll(files_, cont_);
assertTrue(isEmptyErrors(cont_));
CustList<Argument> args_ = new CustList<Argument>();
MethodId id_ = getMethodId("exmeth");
Argument ret_;
ret_ = calculateNormal("pkg.Ex", id_, args_, cont_);
assertEq("string String", getString(ret_));
} | public void calculateArgument8Test(){
StringBuilder xml_ = new StringBuilder();
xml_.append("$public $class pkg.Ex {\n");
xml_.append(" $public $static String exmeth(){\n");
xml_.append(" $return $staticCall(ExTwo<String>).exmeth(\"string\");\n");
xml_.append(" }\n");
xml_.append("}\n");
xml_.append("$public $class pkg.ExTwo<T> {\n");
xml_.append(" $public $staticCall String exmeth(T t){\n");
xml_.append(" String o=\"\";\n");
xml_.append(" $switch(t){\n");
xml_.append(" $case $null:\n");
xml_.append(" o=\"null\";\n");
xml_.append(" $case T v:\n");
xml_.append(" o=v+\" String\";\n");
xml_.append(" $case StringBuilder v:\n");
xml_.append(" o=v+\" StringBuilder\";\n");
xml_.append(" }\n");
xml_.append(" $return o;\n");
xml_.append(" }\n");
xml_.append("}\n");
StringMap<String> files_ = new StringMap<String>();
files_.put("pkg/Ex", xml_.toString());
ContextEl cont_ = ctxOk(files_);
CustList<Argument> args_ = new CustList<Argument>();
MethodId id_ = getMethodId("exmeth");
Argument ret_;
ret_ = calculateNormal("pkg.Ex", id_, args_, cont_);
assertEq("string String", getString(ret_));
} |
|
124 | public void fetchTweetsFromTwitterSearchTest(long[] idTwitterToFetch){
log.info("-----exampleTest-------------------------------------------");
log.info("Hello, Testing-World.");
log.info("We are waiting for fetchTweetsFromTwitterSearch.");
log.info("number of tweets: " + tweetService.count());
try {
Thread.sleep(millisToWaitForFetchTweetsFromTwitterSearch);
log.info("number of tweets: " + tweetService.count());
if (!fetchTestData) {
for (long id : idTwitterToFetch) {
try {
org.springframework.social.twitter.api.Tweet twitterTweet = twitterApiService.findOneTweetById(id);
this.storeOneTweet(twitterTweet);
} catch (TwitterApiException e) {
log.error("twitterApiService.findOneTweetById: " + e.getMessage());
} catch (EmptyResultDataAccessException ex) {
log.error("storeOneTweet: " + ex.getMessage());
} catch (NoResultException exe) {
log.error("storeOneTweet: " + exe.getMessage());
}
}
}
} catch (InterruptedException e) {
log.warn(e.getMessage());
}
log.info("number of tweets: " + tweetService.count());
log.info("------------------------------------------------");
} | public void fetchTweetsFromTwitterSearchTest(long[] idTwitterToFetch){
log.info("-----exampleTest-------------------------------------------");
log.info("Hello, Testing-World.");
log.info("We are waiting for fetchTweetsFromTwitterSearch.");
log.info("number of tweets: " + tweetService.count());
try {
Thread.sleep(millisToWaitForFetchTweetsFromTwitterSearch);
log.info("number of tweets: " + tweetService.count());
for (long id : idTwitterToFetch) {
try {
org.springframework.social.twitter.api.Tweet twitterTweet = twitterApiService.findOneTweetById(id);
this.storeOneTweet(twitterTweet);
} catch (TwitterApiException e) {
log.error("twitterApiService.findOneTweetById: " + e.getMessage());
} catch (EmptyResultDataAccessException ex) {
log.error("storeOneTweet: " + ex.getMessage());
} catch (NoResultException exe) {
log.error("storeOneTweet: " + exe.getMessage());
}
}
} catch (InterruptedException e) {
log.warn(e.getMessage());
}
log.info("number of tweets: " + tweetService.count());
log.info("------------------------------------------------");
} |
|
125 | public Map<String, Object> unauthorizedUser(User loginUser, Integer alertgroupId){
Map<String, Object> result = new HashMap<>();
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
List<User> userList = userMapper.selectList(null);
List<User> resultUsers = new ArrayList<>();
Set<User> userSet = null;
if (userList != null && !userList.isEmpty()) {
userSet = new HashSet<>(userList);
List<User> authedUserList = userMapper.queryUserListByAlertGroupId(alertgroupId);
Set<User> authedUserSet = null;
if (authedUserList != null && !authedUserList.isEmpty()) {
authedUserSet = new HashSet<>(authedUserList);
userSet.removeAll(authedUserSet);
}
resultUsers = new ArrayList<>(userSet);
}
result.put(Constants.DATA_LIST, resultUsers);
putMsg(result, Status.SUCCESS);
return result;
} | public Result<List<User>> unauthorizedUser(User loginUser, Integer alertgroupId){
if (!isAdmin(loginUser)) {
return Result.error(Status.USER_NO_OPERATION_PERM);
}
List<User> userList = userMapper.selectList(null);
List<User> resultUsers = new ArrayList<>();
Set<User> userSet = null;
if (userList != null && !userList.isEmpty()) {
userSet = new HashSet<>(userList);
List<User> authedUserList = userMapper.queryUserListByAlertGroupId(alertgroupId);
Set<User> authedUserSet = null;
if (authedUserList != null && !authedUserList.isEmpty()) {
authedUserSet = new HashSet<>(authedUserList);
userSet.removeAll(authedUserSet);
}
resultUsers = new ArrayList<>(userSet);
}
return Result.success(resultUsers);
} |
|
126 | public ResponseEntity fetchSpecificMovie(@PathVariable String title){
Movie movie;
movie = movieService.fetchSpecificMovie(title);
if (movie != null) {
return new ResponseEntity(movie, HttpStatus.OK);
} else {
return new ResponseEntity("Movie doesn't exist", HttpStatus.NO_CONTENT);
}
} | public ResponseEntity fetchSpecificMovie(@PathVariable String title){
Movie movie = movieService.fetchSpecificMovie(title);
if (movie != null) {
return new ResponseEntity(movie, HttpStatus.OK);
} else {
return new ResponseEntity(GMDBConstants.ERR_MOVIE_DOES_NOT_EXIST, HttpStatus.NO_CONTENT);
}
} |
|
127 | public int hashCode(){
int prime = 31;
int result = 7;
result = prime * result + Objects.hashCode(parameters);
result = prime * result + super.hashCode();
return result;
} | public int hashCode(){
return 31 * Objects.hashCode(parameters) + super.hashCode();
} |
|
128 | public ResponseEntity<?> fetchAccount(Authentication auth, @Valid @RequestBody FetchAccountReqDto reqDto){
DtoMetadata dtoMetadata;
final Account account;
try {
if (reqDto.getId() != null) {
account = accountServ.fetchAccountById(reqDto.getId());
} else if (reqDto.getUsername() != null && !reqDto.getUsername().isEmpty()) {
account = accountServ.fetchAccountByUsername(reqDto.getUsername());
} else if (reqDto.getNickname() != null && !reqDto.getNickname().isEmpty()) {
account = accountServ.fetchAccountByNickname(reqDto.getNickname());
Account myAccount = accountServ.fetchCurrentAccount(auth);
if (account == myAccount) {
logger.warn("fetched self");
dtoMetadata = new DtoMetadata("fetched self");
return ResponseEntity.status(400).body(new FetchAccountResDto(dtoMetadata));
}
} else {
account = accountServ.fetchCurrentAccount(auth);
}
} catch (Exception e) {
logger.warn(e.toString());
dtoMetadata = new DtoMetadata(e.getMessage(), e.getClass().getName());
return ResponseEntity.status(400).body(new FetchAccountResDto(dtoMetadata));
}
dtoMetadata = new DtoMetadata(msgSrc.getMessage("res.fetch.success", null, Locale.ENGLISH));
return ResponseEntity.ok(new FetchAccountResDto(dtoMetadata, account));
} | public ResponseEntity<?> fetchAccount(Authentication auth, @Valid @RequestBody FetchAccountReqDto reqDto){
DtoMetadata dtoMetadata;
final Account account;
try {
if (reqDto.getId() != null) {
account = accountServ.fetchAccountById(reqDto.getId());
} else if (reqDto.getUsername() != null && !reqDto.getUsername().isEmpty()) {
account = accountServ.fetchAccountByUsername(reqDto.getUsername());
} else if (reqDto.getNickname() != null && !reqDto.getNickname().isEmpty()) {
account = accountServ.fetchAccountByNickname(auth, reqDto.getNickname());
} else {
account = accountServ.fetchCurrentAccount(auth);
}
} catch (Exception e) {
logger.warn(e.toString());
dtoMetadata = new DtoMetadata(e.getMessage(), e.getClass().getName());
return ResponseEntity.status(400).body(new FetchAccountResDto(dtoMetadata));
}
dtoMetadata = new DtoMetadata(msgSrc.getMessage("res.fetch.success", null, Locale.ENGLISH));
return ResponseEntity.ok(new FetchAccountResDto(dtoMetadata, account));
} |
|
129 | public void fail8Test(){
DefaultInitializer di_ = new DefaultInitializer();
KeyWords kw_ = new KeyWords();
LgNames lgName_ = new CustLgNames();
InitializationLgNames.basicStandards(lgName_);
kw_.setKeyWordNbHexEnd("<");
AnalyzedTestContext s_ = getCtx(di_, kw_, lgName_);
StringMap<String> keyWords_ = kw_.allKeyWords();
validateKeyWordContents(kw_, s_, keyWords_);
StringMap<String> escapings_ = kw_.allEscapings();
validateEscapingsContents(kw_, s_, escapings_);
StringMap<String> nbWords_ = kw_.allNbWords(kw_.allNbWordsBasic());
validateNbWordContents(kw_, s_, nbWords_);
assertTrue(s_.getAnalyzing().getMessages().displayStdErrors(), !s_.getAnalyzing().isEmptyStdError());
} | public void fail8Test(){
KeyWords kw_ = new KeyWords();
LgNames lgName_ = new CustLgNames();
InitializationLgNames.basicStandards(lgName_);
kw_.setKeyWordNbHexEnd("<");
AnalyzedTestContext s_ = getCtx(kw_, lgName_);
StringMap<String> keyWords_ = kw_.allKeyWords();
validateKeyWordContents(kw_, s_, keyWords_);
StringMap<String> escapings_ = kw_.allEscapings();
validateEscapingsContents(kw_, s_, escapings_);
StringMap<String> nbWords_ = kw_.allNbWords(kw_.allNbWordsBasic());
validateNbWordContents(kw_, s_, nbWords_);
assertTrue(s_.getAnalyzing().getMessages().displayStdErrors(), !s_.getAnalyzing().isEmptyStdError());
} |
|
130 | public int doStartTag() throws JspException{
JspWriter out = pageContext.getOut();
String language = "en";
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie temp : cookies) {
String name = temp.getName();
String value = temp.getValue();
if (temp.getName().equals("language")) {
language = temp.getValue();
}
}
Properties properties = new Properties();
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("page_" + language + ".properties")) {
properties.load(inputStream);
} catch (IOException e) {
throw new IllegalStateException("Cannot load database property file");
}
String message = properties.getProperty(key);
try {
out.print(message);
} catch (IOException e) {
LOGGER.error("Could not print message! locale {} message {}", language, message, e);
}
}
return EVAL_PAGE;
} | public int doStartTag() throws JspException{
JspWriter out = pageContext.getOut();
String language = "en";
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie temp : cookies) {
if (temp.getName().equals("language")) {
language = temp.getValue();
}
}
Properties properties = new Properties();
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("page_" + language + ".properties")) {
properties.load(inputStream);
} catch (IOException e) {
throw new IllegalStateException("Cannot load database property file");
}
String message = properties.getProperty(key);
try {
out.print(message);
} catch (IOException e) {
LOGGER.error("Could not print message! locale {} message {}", language, message, e);
}
}
return EVAL_PAGE;
} |
|
131 | private List<StatementLine> getStatementLines(List<Transaction> transactions){
AtomicInteger runningBalance = new AtomicInteger(0);
List<StatementLine> statementLines = transactions.stream().map(transaction -> statementLine(transaction, runningBalance)).collect(Collectors.toList());
return statementLines;
} | private List<StatementLine> getStatementLines(List<Transaction> transactions){
AtomicInteger runningBalance = new AtomicInteger(0);
return transactions.stream().map(transaction -> statementLine(transaction, runningBalance)).collect(Collectors.toList());
} |
|
132 | public void process16Test(){
String folder_ = "messages";
String relative_ = "sample/file";
String html_ = "<html><body><c:try><c:throw value='$null'/></c:try>\n<c:catch>Exc</c:catch></body></html>";
Configuration conf_ = contextElFive();
conf_.setMessagesFolder(folder_);
conf_.setProperties(new StringMap<String>());
conf_.getProperties().put("msg_example", relative_);
RendDocumentBlock rendDocumentBlock_ = buildRendWithoutBean(html_, conf_);
assertTrue(conf_.isEmptyErrors());
assertEq("<html><body>Exc</body></html>", RendBlock.getRes(rendDocumentBlock_, conf_));
assertNull(getException(conf_));
} | public void process16Test(){
String folder_ = "messages";
String relative_ = "sample/file";
String html_ = "<html><body><c:try><c:throw value='$null'/></c:try>\n<c:catch>Exc</c:catch></body></html>";
Configuration conf_ = contextElFive();
setup(folder_, relative_, conf_);
RendDocumentBlock rendDocumentBlock_ = buildRendWithoutBean(html_, conf_);
assertTrue(conf_.isEmptyErrors());
assertEq("<html><body>Exc</body></html>", RendBlock.getRes(rendDocumentBlock_, conf_));
assertNull(getException(conf_));
} |
|
133 | public void show(){
if (isShowing()) {
return;
}
setLayoutInDisplayCutout();
mWindow.getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
SystemBarUtils.showSystemBars(mWindow, false);
}
});
super.show();
mRotationObserver = new RotationObserver(mParentWindow.getDecorView().getHandler(), mContext) {
@Override
public void onRotationChange(boolean selfChange, boolean enabled) {
mIsRotationEnabled = enabled;
}
};
mOnOrientationChangeListener = new OnOrientationChangeListener(mContext, mScreenOrientation) {
@Override
public void onOrientationChange(int orientation) {
if (orientation != SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
if (!mIsRotationEnabled && !(orientation != SCREEN_ORIENTATION_PORTRAIT && mScreenOrientation != SCREEN_ORIENTATION_PORTRAIT)) {
setOrientation(mScreenOrientation);
return;
}
mScreenOrientation = orientation;
setRequestedOrientation(orientation);
}
}
};
mRotationObserver.startObserver();
mOnOrientationChangeListener.setEnabled(true);
} | public void show(){
if (isShowing()) {
return;
}
setLayoutInDisplayCutout();
mWindow.getDecorView().setOnSystemUiVisibilityChangeListener(visibility -> {
SystemBarUtils.showSystemBars(mWindow, false);
});
super.show();
mRotationObserver = new RotationObserver(mParentWindow.getDecorView().getHandler(), mContext) {
@Override
public void onRotationChange(boolean selfChange, boolean enabled) {
mIsRotationEnabled = enabled;
}
};
mOnOrientationChangeListener = new OnOrientationChangeListener(mContext, mScreenOrientation) {
@Override
public void onOrientationChange(int orientation) {
if (orientation != SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
if (!mIsRotationEnabled && !(orientation != SCREEN_ORIENTATION_PORTRAIT && mScreenOrientation != SCREEN_ORIENTATION_PORTRAIT)) {
setOrientation(mScreenOrientation);
return;
}
mScreenOrientation = orientation;
setRequestedOrientation(orientation);
}
}
};
mRotationObserver.startObserver();
mOnOrientationChangeListener.setEnabled(true);
} |
|
134 | public TaskGraphBuilder buildTaskGraph(){
List<Integer> taskStages = jobParameters.getTaskStages();
int sourceParallelism = taskStages.get(0);
int sinkParallelism = taskStages.get(1);
String edge = "edge";
BaseWindowSource g = new SourceWindowTask(edge);
ISink d = new DirectReceiveTask();
WindowConfig.Count count1 = new WindowConfig.Count(10);
WindowType windowType1 = WindowType.TUMBLING;
WindowConfig.Count count2 = new WindowConfig.Count(3);
WindowType windowType2 = WindowType.TUMBLING;
WindowConfig.Duration duration1 = new WindowConfig.Duration(10, TimeUnit.MINUTES);
WindowType windowType3 = WindowType.TUMBLING;
WindowingTumblingPolicy windowingTumblingPolicy = new WindowingTumblingPolicy(count1);
BaseWindowSink dw = null;
try {
dw = new DirectWindowedReceivingTask(windowingTumblingPolicy);
} catch (InValidWindowingPolicy inValidWindowingPolicy) {
inValidWindowingPolicy.printStackTrace();
}
taskGraphBuilder.addSource(SOURCE, g, sourceParallelism);
computeConnection = taskGraphBuilder.addSink(SINK, dw, sinkParallelism);
computeConnection.direct(SOURCE, edge, DataType.INTEGER);
return taskGraphBuilder;
} | public TaskGraphBuilder buildTaskGraph(){
List<Integer> taskStages = jobParameters.getTaskStages();
int sourceParallelism = taskStages.get(0);
int sinkParallelism = taskStages.get(1);
String edge = "edge";
BaseWindowSource g = new SourceWindowTask(edge);
ISink d = new DirectReceiveTask();
WindowConfig.Count count1 = new WindowConfig.Count(10);
WindowType windowType1 = WindowType.TUMBLING;
WindowConfig.Count count2 = new WindowConfig.Count(3);
WindowType windowType2 = WindowType.TUMBLING;
WindowConfig.Duration duration1 = new WindowConfig.Duration(10, TimeUnit.MINUTES);
WindowType windowType3 = WindowType.TUMBLING;
WindowingTumblingPolicy windowingTumblingPolicy = new WindowingTumblingPolicy(count1);
BaseWindowSink dw = new DirectWindowedReceivingTask();
taskGraphBuilder.addSource(SOURCE, g, sourceParallelism);
computeConnection = taskGraphBuilder.addSink(SINK, dw, sinkParallelism);
computeConnection.direct(SOURCE, edge, DataType.INTEGER);
return taskGraphBuilder;
} |
|
135 | private void createCatalogFramework(){
catalogFramework = new MockCatalogFramework();
Dictionary properties = new Properties();
bundleContext.registerService(CatalogFramework.class, catalogFramework, properties);
await().atMost(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS).until(() -> bundleContext.getServiceReference(CatalogFramework.class) != null);
} | private void createCatalogFramework(){
catalogFramework = new MockCatalogFramework();
bundleContext.registerService(CatalogFramework.class, catalogFramework, null);
await().atMost(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS).until(() -> bundleContext.getServiceReference(CatalogFramework.class) != null);
} |
|
136 | public Map<String, Object> unauthDatasource(User loginUser, Integer userId){
Map<String, Object> result = new HashMap<>();
if (!isAdmin(loginUser)) {
putMsg(result, Status.USER_NO_OPERATION_PERM);
return result;
}
List<DataSource> resultList = new ArrayList<>();
List<DataSource> datasourceList = dataSourceMapper.queryDatasourceExceptUserId(userId);
Set<DataSource> datasourceSet = null;
if (datasourceList != null && !datasourceList.isEmpty()) {
datasourceSet = new HashSet<>(datasourceList);
List<DataSource> authedDataSourceList = dataSourceMapper.queryAuthedDatasource(userId);
Set<DataSource> authedDataSourceSet = null;
if (authedDataSourceList != null && !authedDataSourceList.isEmpty()) {
authedDataSourceSet = new HashSet<>(authedDataSourceList);
datasourceSet.removeAll(authedDataSourceSet);
}
resultList = new ArrayList<>(datasourceSet);
}
result.put(Constants.DATA_LIST, resultList);
putMsg(result, Status.SUCCESS);
return result;
} | public Result<List<DataSource>> unauthDatasource(User loginUser, Integer userId){
if (!isAdmin(loginUser)) {
return Result.error(Status.USER_NO_OPERATION_PERM);
}
List<DataSource> resultList = new ArrayList<>();
List<DataSource> datasourceList = dataSourceMapper.queryDatasourceExceptUserId(userId);
Set<DataSource> datasourceSet = null;
if (datasourceList != null && !datasourceList.isEmpty()) {
datasourceSet = new HashSet<>(datasourceList);
List<DataSource> authedDataSourceList = dataSourceMapper.queryAuthedDatasource(userId);
Set<DataSource> authedDataSourceSet = null;
if (authedDataSourceList != null && !authedDataSourceList.isEmpty()) {
authedDataSourceSet = new HashSet<>(authedDataSourceList);
datasourceSet.removeAll(authedDataSourceSet);
}
resultList = new ArrayList<>(datasourceSet);
}
return Result.success(resultList);
} |
|
137 | static UserVO fromJson(JsonObject json){
String id = json.getString("id", json.getString("_id"));
String username = json.getString("username");
String password = json.getString("password");
String fullName = json.getString("fullName");
String email = json.getString("email");
Instant lastModifiedDate = null;
Long version = json.getLong("version");
JsonObject lastModifiedDateJson = json.getJsonObject("lastModifiedDate");
if (lastModifiedDateJson != null && !lastModifiedDateJson.isEmpty()) {
lastModifiedDate = lastModifiedDateJson.getInstant("$date");
}
return new UserVO(id, username, password, fullName, email, lastModifiedDate, version);
} | static UserVO fromJson(JsonObject json){
String id = json.getString("id", json.getString("_id"));
String username = json.getString("username");
String password = json.getString("password");
String fullName = json.getString("fullName");
String email = json.getString("email");
Instant lastModifiedDate = CommonUtils.getInstantMongoDate(json, "lastModifiedDate");
Long version = json.getLong("version");
return new UserVO(id, username, password, fullName, email, lastModifiedDate, version);
} |
|
138 | public ResponseEntity updateSupplyPostBikeByUser(@PathVariable int id, @PathVariable int userId, @RequestBody Map<String, String> body){
AccountEntity accountEntity = accountRepository.findById(userId);
SupplyProductEntity supplyProductEntity = supplyProductRepository.findById(id);
if (accountEntity == null || supplyProductEntity == null) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
if (!accountEntity.getStatus().equals(MainConstants.ACCOUNT_ACTIVE) || !accountEntity.getRoleByRoleId().getName().equals(MainConstants.ROLE_USER) || supplyProductEntity.getStatus().equals(MainConstants.SUPPLY_POST_CLOSED) || !supplyProductEntity.getTypeItem().equals(MainConstants.STATUS_BIKE))
return new ResponseEntity(HttpStatus.LOCKED);
if (supplyProductEntity.getCreatorId().equals(userId)) {
int bikeId = supplyProductEntity.getItemId();
BikeEntity bikeEntity = bikeRepository.findById(bikeId);
supplyProductEntity = paramSupplyPostEntityRequest(body, supplyProductEntity, bikeEntity, null, MainConstants.STATUS_BIKE);
supplyProductRepository.save(supplyProductEntity);
frozenAllTransactionBySupplyProductId(id);
return new ResponseEntity(supplyProductEntity, HttpStatus.OK);
}
return new ResponseEntity(HttpStatus.BAD_REQUEST);
} | public ResponseEntity updateSupplyPostBikeByUser(@PathVariable int id, @PathVariable int userId, @RequestBody Map<String, String> body){
AccountEntity accountEntity = accountRepository.findById(userId);
SupplyProductEntity supplyProductEntity = supplyProductRepository.findById(id);
if (accountEntity == null || supplyProductEntity == null)
return new ResponseEntity(HttpStatus.NOT_FOUND);
if (!accountEntity.getStatus().equals(MainConstants.ACCOUNT_ACTIVE) || !accountEntity.getRoleByRoleId().getName().equals(MainConstants.ROLE_USER) || supplyProductEntity.getStatus().equals(MainConstants.SUPPLY_POST_CLOSED) || !supplyProductEntity.getTypeItem().equals(MainConstants.STATUS_BIKE))
return new ResponseEntity(HttpStatus.LOCKED);
if (supplyProductEntity.getCreatorId().equals(userId)) {
int bikeId = supplyProductEntity.getItemId();
BikeEntity bikeEntity = bikeRepository.findById(bikeId);
supplyProductEntity = paramSupplyPostEntityRequest(body, supplyProductEntity, bikeEntity, null, MainConstants.STATUS_BIKE);
supplyProductRepository.save(supplyProductEntity);
frozenAllTransactionBySupplyProductId(id);
return new ResponseEntity(supplyProductEntity, HttpStatus.OK);
}
return new ResponseEntity(HttpStatus.BAD_REQUEST);
} |
|
139 | public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
FragmentGradesBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_grades, container, false);
GraduationsViewModel viewModel = new ViewModelProvider(this).get(GraduationsViewModel.class);
binding.graduationsRecyclerView.setHasFixedSize(true);
GraduationsAdapter adapter = new GraduationsAdapter(getActivity(), getParentFragmentManager(), viewModel);
binding.graduationsRecyclerView.setAdapter(adapter);
viewModel.getUpdateGraduationsEvent().observe(getViewLifecycleOwner(), aVoid -> {
adapter.notifyDataSetChanged();
SoundUtil.play(getContext(), R.raw.yon);
});
FragmentUtils.setSectionTitle(getActivity(), R.string.section_graduations);
AdRequest adRequest = new AdRequest.Builder().build();
binding.adView.loadAd(adRequest);
return binding.getRoot();
} | public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
FragmentGradesBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_grades, container, false);
GraduationsViewModel viewModel = new ViewModelProvider(this).get(GraduationsViewModel.class);
binding.graduationsRecyclerView.setHasFixedSize(true);
GraduationsAdapter adapter = new GraduationsAdapter(getActivity(), getParentFragmentManager(), viewModel);
binding.graduationsRecyclerView.setAdapter(adapter);
viewModel.getUpdateGraduationsEvent().observe(getViewLifecycleOwner(), aVoid -> {
adapter.notifyDataSetChanged();
SoundUtil.play(getContext(), R.raw.yon);
});
FragmentUtils.setSectionTitle(getActivity(), R.string.section_graduations);
binding.adView.loadAd(new AdRequest.Builder().build());
return binding.getRoot();
} |
|
140 | private Map<String, Object> checkProjectAndAuth(User loginUser, String projectName){
Project project = projectMapper.queryByName(projectName);
Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
Status resultStatus = (Status) checkResult.get(Constants.STATUS);
if (resultStatus != Status.SUCCESS) {
return checkResult;
}
return null;
} | private CheckParamResult checkProjectAndAuth(User loginUser, String projectName){
Project project = projectMapper.queryByName(projectName);
return projectService.checkProjectAndAuth(loginUser, project, projectName);
} |
|
141 | public Collection<String> visit(final Function expression, final Object data){
final Collection<String> names;
if (data instanceof Collection)
names = (Collection<String>) data;
else
names = new HashSet<String>();
if (expression.getParameters() != null) {
for (Expression parameter : expression.getParameters()) {
parameter.accept(this, names);
}
}
return names;
} | public Collection<String> visit(final Function expression, final Object data){
final Collection<String> names = dest(data);
if (expression.getParameters() != null) {
for (Expression parameter : expression.getParameters()) {
parameter.accept(this, names);
}
}
return names;
} |
|
142 | public Map<String, Object> queryTaskListByProcessId(User loginUser, String projectName, Integer processId) throws IOException{
Map<String, Object> result = new HashMap<>();
Project project = projectMapper.queryByName(projectName);
Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
Status resultEnum = (Status) checkResult.get(Constants.STATUS);
if (resultEnum != Status.SUCCESS) {
return checkResult;
}
ProcessInstance processInstance = processService.findProcessInstanceDetailById(processId);
List<TaskInstance> taskInstanceList = processService.findValidTaskListByProcessId(processId);
addDependResultForTaskList(taskInstanceList);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put(PROCESS_INSTANCE_STATE, processInstance.getState().toString());
resultMap.put(TASK_LIST, taskInstanceList);
result.put(DATA_LIST, resultMap);
putMsg(result, Status.SUCCESS);
return result;
} | public Result<Map<String, Object>> queryTaskListByProcessId(User loginUser, String projectName, Integer processId) throws IOException{
Project project = projectMapper.queryByName(projectName);
CheckParamResult checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
if (!Status.SUCCESS.equals(checkResult.getStatus())) {
return Result.error(checkResult);
}
ProcessInstance processInstance = processService.findProcessInstanceDetailById(processId);
List<TaskInstance> taskInstanceList = processService.findValidTaskListByProcessId(processId);
addDependResultForTaskList(taskInstanceList);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put(PROCESS_INSTANCE_STATE, processInstance.getState().toString());
resultMap.put(TASK_LIST, taskInstanceList);
return Result.success(resultMap);
} |
|
143 | public void initialize(URL location, ResourceBundle resources){
this.fullname.setText(client.getFullname());
this.firstnameInput.setText(client.getFirstname());
this.lastnameInput.setText(client.getLastname());
this.addressInput.setText(client.getAddress());
this.cardIdInput.setText(client.getCardId());
this.genderInput.setValue(client.getGender());
this.birthdateInput.setValue(new java.sql.Date(client.getBirthdate().getTime()).toLocalDate());
BooleanBinding isValid = new FormValidationBuilder().notEmpty(firstnameInput.textProperty()).notEmpty(lastnameInput.textProperty()).notEmpty(addressInput.textProperty()).notEmpty(cardIdInput.textProperty()).add(Bindings.createBooleanBinding(() -> birthdateInput.getValue() != null && birthdateInput.getValue().isBefore(LocalDate.now()), birthdateInput.valueProperty())).notNull(genderInput.valueProperty()).build();
updateProfileButton.disableProperty().bind(isValid.not());
} | public void initialize(URL location, ResourceBundle resources){
this.firstnameInput.setText(client.getFirstname());
this.lastnameInput.setText(client.getLastname());
this.addressInput.setText(client.getAddress());
this.cardIdInput.setText(client.getCardId());
this.genderInput.setValue(client.getGender());
this.birthdateInput.setValue(client.getBirthdate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
BooleanBinding isValid = new FormValidationBuilder().notEmpty(firstnameInput.textProperty()).notEmpty(lastnameInput.textProperty()).notEmpty(addressInput.textProperty()).notEmpty(cardIdInput.textProperty()).add(Bindings.createBooleanBinding(() -> birthdateInput.getValue() != null && birthdateInput.getValue().isBefore(LocalDate.now()), birthdateInput.valueProperty())).notNull(genderInput.valueProperty()).build();
updateProfileButton.disableProperty().bind(isValid.not());
} |
|
144 | protected final java.io.File getAssetDir(final Manifest mf) throws IOException{
final java.io.File forgeDir = OperatingSystemUtils.getUserForgeDir();
final java.io.File result = new java.io.File(forgeDir, String.format("dynjs/%s", getVersion(mf)));
if (!result.exists()) {
if (!result.mkdirs()) {
throw new IOException(String.format("error creating dynjs asset dir [%s]", result));
}
}
return result;
} | protected final java.io.File getAssetDir(final Manifest mf) throws IOException{
return AddonUtils.getAssetDir(mf);
} |
|
145 | public synchronized void asserOff(){
byte[] out = new byte[1];
bufferBassePriorite.add(new Order(out, SerialProtocol.OutOrder.ASSER_OFF));
notify();
} | public synchronized void asserOff(){
bufferBassePriorite.add(new Order(OutOrder.ASSER_OFF));
notify();
} |
|
146 | private void playAnimation(Spatial model, String name, boolean hardwareSkinning){
if (name != null) {
AnimControl animControl = model.getControl(AnimControl.class);
AnimChannel channel = animControl.createChannel();
channel.setAnim(name);
}
SkeletonControl skControl = model.getControl(SkeletonControl.class);
skControl.setHardwareSkinningPreferred(hardwareSkinning);
} | private void playAnimation(Spatial model, String name, boolean hardwareSkinning){
if (name != null) {
AnimComposer composer = model.getControl(AnimComposer.class);
composer.setCurrentAction(name);
}
SkinningControl skControl = model.getControl(SkinningControl.class);
skControl.setHardwareSkinningPreferred(hardwareSkinning);
} |
|
147 | public void speak(String text){
System.setProperty("mbrola.base", "D:/mbrola");
voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("kevin16");
voice.allocate();
voice.speak(text);
voice.deallocate();
} | public void speak(String text){
} |
|
148 | public void start(Server server) throws IOException{
server.run(new MiddlewareStack() {
{
use(new ApacheCommonLogger(logger));
use(new ServerHeader(NAME));
use(new DateHeader());
use(new ContentLengthHeader());
use(new Failsafe());
use(new FailureMonitor(failureReporter));
use(new HttpMethodOverride());
use(staticAssets());
use(new Cookies());
use(new CookieSessionTracker(createSessionPool(timeout)).expireAfter(timeout));
use(new FilterMap().map("/", Layout.html(new SiteLayout(layoutTemplate()))));
use(new ConnectionScope(dataSource));
run(new Routing(new Pages(pageTemplates())));
}
});
} | public void start(WebServer server) throws IOException{
server.add(new ApacheCommonLogger(logger)).add(new ServerHeader(NAME)).add(new DateHeader()).add(new ContentLengthHeader()).add(new Failsafe()).add(new FailureMonitor(failureReporter)).add(new HttpMethodOverride()).add(staticAssets()).add(new Cookies()).add(new CookieSessionTracker(createSessionPool(timeout)).expireAfter(timeout)).filter("/", Layout.html(new SiteLayout(layoutTemplate()))).add(new ConnectionScope(dataSource)).start(new Routing(new Pages(pageTemplates())));
} |
|
149 | public void process1Test(){
String locale_ = "en";
String folder_ = "messages";
String relative_ = "sample/file";
String content_ = "one=Description one\ntwo=Description two\nthree=desc <{0}>";
String html_ = "<html c:bean='bean_one'><body><ul><c:for var=\"s\" list=\"composite.strings\" className='java.lang.String'><li>{s.length()}</li></c:for></ul></body></html>";
StringMap<String> files_ = new StringMap<String>();
files_.put(EquallableExUtil.formatFile(folder_, locale_, relative_), content_);
BeanOne bean_ = new BeanOne();
bean_.getComposite().getStrings().add("FIRST");
bean_.getComposite().getStrings().add("SECOND");
bean_.getComposite().setInteger(5);
Configuration context_ = contextElSec();
((BeanNatLgNames) context_.getStandards()).setBeans(new StringMap<Bean>());
context_.setMessagesFolder(folder_);
context_.setProperties(new StringMap<String>());
context_.getProperties().put("msg_example", relative_);
RendDocumentBlock rendDocumentBlock_ = buildRendWithOneNativeBean(html_, bean_, context_);
assertTrue(context_.isEmptyErrors());
assertEq("<html><body><ul><li>5</li><li>6</li></ul></body></html>", RendBlock.getRes(rendDocumentBlock_, context_));
assertNull(getException(context_));
} | public void process1Test(){
String locale_ = "en";
String folder_ = "messages";
String relative_ = "sample/file";
String content_ = "one=Description one\ntwo=Description two\nthree=desc <{0}>";
String html_ = "<html c:bean='bean_one'><body><ul><c:for var=\"s\" list=\"composite.strings\" className='java.lang.String'><li>{s.length()}</li></c:for></ul></body></html>";
StringMap<String> files_ = new StringMap<String>();
files_.put(EquallableExUtil.formatFile(folder_, locale_, relative_), content_);
BeanOne bean_ = new BeanOne();
bean_.getComposite().getStrings().add("FIRST");
bean_.getComposite().getStrings().add("SECOND");
bean_.getComposite().setInteger(5);
Configuration context_ = contextElSec();
setupNative(folder_, relative_, context_);
RendDocumentBlock rendDocumentBlock_ = buildRendWithOneNativeBean(html_, bean_, context_);
assertTrue(context_.isEmptyErrors());
assertEq("<html><body><ul><li>5</li><li>6</li></ul></body></html>", RendBlock.getRes(rendDocumentBlock_, context_));
assertNull(getException(context_));
} |
|
150 | private void CheckCloseActivity(){
if (isRecipeEmpty() || !isAdding)
CloseActivity();
else {
AlertDialog verification = new AlertDialog.Builder(this).setMessage(R.string.are_you_sure_discard).setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
CloseActivity();
}
}).setNegativeButton(R.string.dialog_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).create();
verification.show();
}
} | private void CheckCloseActivity(){
if (isRecipeEmpty() || !isAdding)
CloseActivity();
else {
AlertDialog verification = new AlertDialog.Builder(this).setMessage(R.string.are_you_sure_discard).setPositiveButton(R.string.dialog_yes, (dialogInterface, i) -> CloseActivity()).setNegativeButton(R.string.dialog_no, (dialogInterface, i) -> {
}).create();
verification.show();
}
} |
|
151 | private void updateForecastText(String currentForecast, boolean successfulLoad){
mWeatherCurrentText.setText(currentForecast);
showLayout(mWeatherCurrentText);
mDataLoaded = successfulLoad;
} | private void updateForecastText(String currentForecast, boolean successfulLoad){
mWeatherCurrentText.setText(currentForecast);
showLayout(mWeatherCurrentText);
} |
|
152 | public boolean checkForCar(String SN){
try {
ResultSet result = statement.executeQuery("SELECT car_id FROM cars WHERE car_id='" + SN + "';");
return result.next();
} catch (SQLException ex) {
System.out.println("Could not verify user, connection failed?");
ex.printStackTrace();
}
return true;
} | public boolean checkForCar(int SN){
try {
ResultSet result = statement.executeQuery("SELECT car_id FROM cars WHERE car_id='" + SN + "';");
return result.next();
} catch (SQLException ex) {
ex.printStackTrace();
}
return true;
} |
|
153 | Argument getCommonArgument(Configuration _conf){
Argument a_;
setRelativeOffsetPossibleLastPage(getIndexInEl() + off, _conf);
PageEl ip_ = _conf.getPageEl();
if (type == ConstType.CATCH_VAR) {
LocalVariable locVar_ = ip_.getCatchVars().getVal(variableName);
a_ = new Argument();
a_.setStruct(locVar_.getStruct());
return a_;
}
if (type == ConstType.LOOP_INDEX) {
LoopVariable locVar_ = ip_.getVars().getVal(variableName);
a_ = new Argument();
ClassArgumentMatching clArg_ = new ClassArgumentMatching(locVar_.getIndexClassName());
LgNames stds_ = _conf.getStandards();
LongStruct str_ = new LongStruct(locVar_.getIndex());
Struct value_ = PrimitiveTypeUtil.convertStrictObject(clArg_, str_, stds_);
a_.setStruct(value_);
return a_;
}
LoopVariable locVar_ = ip_.getVars().getVal(variableName);
a_ = new Argument();
a_.setStruct(locVar_.getStruct());
return a_;
} | Argument getCommonArgument(Configuration _conf){
Argument a_;
setRelativeOffsetPossibleLastPage(getIndexInEl() + off, _conf);
ImportingPage ip_ = _conf.getLastPage();
if (type == ConstType.LOOP_INDEX) {
return ExecTemplates.getIndexLoop(_conf.getContext(), variableName, ip_.getPageEl());
}
return ExecTemplates.getValue(_conf.getContext(), variableName, ip_.getPageEl());
} |
|
154 | public void onDestroy(){
super.onDestroy();
String rememberLogin = loginPrefs.getString("rememberLogin");
if (rememberLogin.equals("false"))
loginPrefs.clear();
} | public void onDestroy(){
super.onDestroy();
clearAllPreferences();
} |
|
155 | private void requestBookings(String userID){
RetrofitManager.getInstance().getUserBookings(userID, UserDefaultUtil.isBusinessUser() ? "S" : "C", new AbstractCallback() {
@Override
public void onResult(boolean isSuccess, Object result) {
hideLoadingView();
if (isSuccess) {
bookingModels.clear();
bookingModels = ((UserBookingsResponse) result).getUserBookings();
initBookings();
}
}
});
} | private void requestBookings(String userID){
RetrofitManager.getInstance().getUserBookings(userID, UserDefaultUtil.isBusinessUser() ? "S" : "C", (isSuccess, result) -> {
hideLoadingView();
if (isSuccess) {
bookingModels.clear();
bookingModels = ((UserBookingsResponse) result).getUserBookings();
initBookings();
}
});
} |
|
156 | public void testEntryMultipleFormats0() throws Exception{
final OPDSAcquisitionFeedEntryParserType parser = this.getParser();
final OPDSAcquisitionFeedEntry e = parser.parseEntryStream(URI.create("urn:test"), OPDSFeedEntryParserContract.getResource("entry-with-formats-0.xml"));
Assert.assertEquals(2, e.getAcquisitions().size());
{
final OPDSAcquisition acquisition = e.getAcquisitions().get(0);
Assert.assertTrue("application/epub+zip is available", OPDSIndirectAcquisition.Companion.findTypeInOptional(mimeOf("application/epub+zip"), acquisition.getIndirectAcquisitions()).isSome());
final Set<MIMEType> available_content_types = acquisition.availableFinalContentTypes();
Assert.assertEquals(1, available_content_types.size());
Assert.assertTrue("application/epub+zip is available", available_content_types.contains(mimeOf("application/epub+zip")));
}
{
final OPDSAcquisition acquisition = e.getAcquisitions().get(1);
Assert.assertTrue("application/pdf is available", OPDSIndirectAcquisition.Companion.findTypeInOptional(mimeOf("application/pdf"), acquisition.getIndirectAcquisitions()).isSome());
final Set<MIMEType> available_content_types = acquisition.availableFinalContentTypes();
Assert.assertEquals(1, available_content_types.size());
Assert.assertTrue("application/pdf is available", available_content_types.contains(mimeOf("application/pdf")));
}
} | public void testEntryMultipleFormats0() throws Exception{
final OPDSAcquisitionFeedEntryParserType parser = this.getParser();
final OPDSAcquisitionFeedEntry e = parser.parseEntryStream(URI.create("urn:test"), OPDSFeedEntryParserContract.getResource("entry-with-formats-0.xml"));
Assert.assertEquals(3, e.getAcquisitions().size());
{
final OPDSAcquisition acquisition = e.getAcquisitions().get(0);
Assert.assertTrue("application/epub+zip is available", OPDSIndirectAcquisition.Companion.findTypeInOptional(mimeOf("application/epub+zip"), acquisition.getIndirectAcquisitions()).isSome());
}
{
final OPDSAcquisition acquisition = e.getAcquisitions().get(1);
Assert.assertTrue("application/pdf is available", OPDSIndirectAcquisition.Companion.findTypeInOptional(mimeOf("application/pdf"), acquisition.getIndirectAcquisitions()).isSome());
}
{
final OPDSAcquisition acquisition = e.getAcquisitions().get(2);
Assert.assertTrue("text/html is available", OPDSIndirectAcquisition.Companion.findTypeInOptional(mimeOf("text/html"), acquisition.getIndirectAcquisitions()).isSome());
}
} |
|
157 | public void onErrorResponse(VolleyError error){
pDialog.dismiss();
Log.d("error", "Error: " + error.getMessage());
} | public void onErrorResponse(VolleyError error){
pDialog.dismiss();
} |
|
158 | public Result updateProject(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("projectId") Integer projectId, @RequestParam("projectName") String projectName, @RequestParam(value = "description", required = false) String description){
logger.info("login user {} , updateProcessInstance project name: {}, desc: {}", loginUser.getUserName(), projectName, description);
Map<String, Object> result = projectService.update(loginUser, projectId, projectName, description);
return returnDataList(result);
} | public Result<Void> updateProject(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("projectId") Integer projectId, @RequestParam("projectName") String projectName, @RequestParam(value = "description", required = false) String description){
logger.info("login user {} , updateProcessInstance project name: {}, desc: {}", loginUser.getUserName(), projectName, description);
return projectService.update(loginUser, projectId, projectName, description);
} |
|
159 | private void requestPermissions(){
if (mShowTemperature && ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Intent mPermissionRequestIntent = new Intent(getBaseContext(), PermissionRequestActivity.class);
mPermissionRequestIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (mShowWeather && ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mPermissionRequestIntent.putExtra("KEY_PERMISSIONS", new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION });
} else {
mPermissionRequestIntent.putExtra("KEY_PERMISSIONS", Manifest.permission.ACCESS_COARSE_LOCATION);
}
startActivity(mPermissionRequestIntent);
}
} | private void requestPermissions(){
if ((mShowWeather || mShowTemperature) && ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Intent mPermissionRequestIntent = new Intent(getBaseContext(), PermissionRequestActivity.class);
mPermissionRequestIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mPermissionRequestIntent.putExtra("KEY_PERMISSIONS", new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION });
startActivity(mPermissionRequestIntent);
}
} |
|
160 | private Optional<KlvHandler> find(Map<String, KlvHandler> handlers, String name){
return handlers.values().stream().filter(handler -> {
return handler.getAttributeName().equals(name);
}).findFirst();
} | private Optional<KlvHandler> find(Map<String, KlvHandler> handlers, String name){
return handlers.values().stream().filter(handler -> handler.getAttributeName().equals(name)).findFirst();
} |
|
161 | public double getTotalAmount(CurrencyType type){
double totalAmount = 0;
for (Object o : moneySet.entrySet()) {
var mapElement = (Entry) o;
CurrencyType key = (CurrencyType) mapElement.getKey();
if (key == CurrencyType.Rupee) {
totalAmount += (double) mapElement.getValue();
} else {
totalAmount += (double) mapElement.getValue() * CurrencyType.getRupeeValue();
}
}
return type.equals(CurrencyType.Rupee) ? totalAmount : totalAmount / CurrencyType.getRupeeValue();
} | public double getTotalAmount(CurrencyType type){
double totalAmount = 0;
for (Object o : moneySet.entrySet()) {
var mapElement = (Entry) o;
CurrencyType key = (CurrencyType) mapElement.getKey();
totalAmount += key == CurrencyType.Rupee ? (double) mapElement.getValue() : (double) mapElement.getValue() * CurrencyType.getRupeeValue();
}
return type.equals(CurrencyType.Rupee) ? totalAmount : totalAmount / CurrencyType.getRupeeValue();
} |
|
162 | public void execute(Config config, int workerID, AllocatedResources resources, IWorkerController workerController, IPersistentVolume persistentVolume, IVolatileVolume volatileVolume){
TWSNetwork network = new TWSNetwork(config, resources.getWorkerId());
TWSCommunication channel = network.getDataFlowTWSCommunication();
GeneratorCheckpointTask g = new GeneratorCheckpointTask();
RecevingCheckpointTask r = new RecevingCheckpointTask(channel);
GraphBuilder builder = GraphBuilder.newBuilder();
builder.addSource("source", g);
builder.setParallelism("source", 4);
builder.addSink("sink", r);
builder.setParallelism("sink", 4);
builder.connect("source", "sink", "partition-edge", Operations.PARTITION);
builder.addConfiguration("source", "Ram", GraphConstants.taskInstanceRam(config));
builder.addConfiguration("source", "Disk", GraphConstants.taskInstanceDisk(config));
builder.addConfiguration("source", "Cpu", GraphConstants.taskInstanceCpu(config));
List<String> sourceInputDataset = new ArrayList<>();
sourceInputDataset.add("dataset1.txt");
sourceInputDataset.add("dataset2.txt");
builder.addConfiguration("source", "inputdataset", sourceInputDataset);
DataFlowTaskGraph graph = builder.build();
RoundRobinTaskScheduler roundRobinTaskScheduler = new RoundRobinTaskScheduler();
roundRobinTaskScheduler.initialize(config);
WorkerPlan workerPlan = createWorkerPlan(resources);
TaskSchedulePlan taskSchedulePlan = roundRobinTaskScheduler.schedule(graph, workerPlan);
ExecutionPlanBuilder executionPlanBuilder = new ExecutionPlanBuilder(resources, new Communicator(config, network.getChannel()));
ExecutionPlan plan = executionPlanBuilder.build(config, graph, taskSchedulePlan);
Executor executor = new Executor(config, plan, network.getChannel());
executor.execute();
} | public void execute(Config config, int workerID, AllocatedResources resources, IWorkerController workerController, IPersistentVolume persistentVolume, IVolatileVolume volatileVolume){
TWSChannel channel = Network.initializeChannel(config, workerController, resources);
GeneratorCheckpointTask g = new GeneratorCheckpointTask();
RecevingCheckpointTask r = new RecevingCheckpointTask(channel);
GraphBuilder builder = GraphBuilder.newBuilder();
builder.addSource("source", g);
builder.setParallelism("source", 4);
builder.addSink("sink", r);
builder.setParallelism("sink", 4);
builder.connect("source", "sink", "partition-edge", Operations.PARTITION);
builder.addConfiguration("source", "Ram", GraphConstants.taskInstanceRam(config));
builder.addConfiguration("source", "Disk", GraphConstants.taskInstanceDisk(config));
builder.addConfiguration("source", "Cpu", GraphConstants.taskInstanceCpu(config));
List<String> sourceInputDataset = new ArrayList<>();
sourceInputDataset.add("dataset1.txt");
sourceInputDataset.add("dataset2.txt");
builder.addConfiguration("source", "inputdataset", sourceInputDataset);
DataFlowTaskGraph graph = builder.build();
RoundRobinTaskScheduler roundRobinTaskScheduler = new RoundRobinTaskScheduler();
roundRobinTaskScheduler.initialize(config);
WorkerPlan workerPlan = createWorkerPlan(resources);
TaskSchedulePlan taskSchedulePlan = roundRobinTaskScheduler.schedule(graph, workerPlan);
ExecutionPlanBuilder executionPlanBuilder = new ExecutionPlanBuilder(resources, new Communicator(config, channel));
ExecutionPlan plan = executionPlanBuilder.build(config, graph, taskSchedulePlan);
Executor executor = new Executor(config, plan, channel);
executor.execute();
} |
|
163 | public boolean createEditProject(ProjectDetail projectDetail){
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
projectDetail.setTenderSqlDate(getSQLDate(projectDetail.getTenderDate(), formatter));
projectDetail.setAgreementSqlDate(getSQLDate(projectDetail.getAgreementDate(), formatter));
projectDetail.setCommencementSqlDate(getSQLDate(projectDetail.getCommencementDate(), formatter));
projectDetail.setCompletionSqlDate(getSQLDate(projectDetail.getCompletionDate(), formatter));
projectDetail.setEmdStartSqlDate(getSQLDate(projectDetail.getEmdStartDate(), formatter));
projectDetail.setEmdEndSqlDate(getSQLDate(projectDetail.getEmdEndDate(), formatter));
projectDetail.setLastUpdatedBy(projectDetail.getEmployeeId());
projectDetail.setLastUpdatedAt(getCurrentDateTime());
boolean isInsertSuccessful = projectDAO.saveProject(projectDetail);
return isInsertSuccessful;
} | public boolean createEditProject(ProjectDetail projectDetail){
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
projectDetail.setTenderSqlDate(getSQLDate(projectDetail.getTenderDate(), formatter));
projectDetail.setAgreementSqlDate(getSQLDate(projectDetail.getAgreementDate(), formatter));
projectDetail.setCommencementSqlDate(getSQLDate(projectDetail.getCommencementDate(), formatter));
projectDetail.setCompletionSqlDate(getSQLDate(projectDetail.getCompletionDate(), formatter));
projectDetail.setLastUpdatedBy(projectDetail.getEmployeeId());
projectDetail.setLastUpdatedAt(getCurrentDateTime());
boolean isInsertSuccessful = projectDAO.saveProject(projectDetail);
return isInsertSuccessful;
} |
|
164 | protected void updateMongoInfo(JSONArray tmpMongoDetailArray){
try {
JSONObject dataMainObj = new JSONObject();
for (int i = 0; i < tmpMongoDetailArray.size(); i++) {
if (dataMainObj != null) {
dataMainObj.clear();
}
dataMainObj = (JSONObject) tmpMongoDetailArray.get(i);
TeamCollectorItem team = new TeamCollectorItem();
@SuppressWarnings("unused")
boolean deleted = this.removeExistingEntity(tools.sanitizeResponse(dataMainObj.get("id")));
team.setCollectorId(featureCollectorRepository.findByName("Jira").getId());
team.setTeamId(tools.sanitizeResponse(dataMainObj.get("id")));
team.setName(tools.sanitizeResponse(dataMainObj.get("name")));
team.setChangeDate("");
team.setAssetState("Active");
team.setIsDeleted("False");
try {
teamRepo.save(team);
} catch (Exception e) {
logger.error("Unexpected error caused when attempting to save data\nCaused by:\n" + e.getMessage() + " : " + e.getCause() + "\n" + Arrays.toString(e.getStackTrace()));
}
}
} catch (Exception e) {
logger.error("Unexpected error caused while mapping data from source system to local data store:\n" + e.getMessage() + " : " + e.getCause() + "\n" + Arrays.toString(e.getStackTrace()));
}
} | protected void updateMongoInfo(JSONArray tmpMongoDetailArray){
try {
for (int i = 0; i < tmpMongoDetailArray.size(); i++) {
JSONObject dataMainObj = (JSONObject) tmpMongoDetailArray.get(i);
TeamCollectorItem team = new TeamCollectorItem();
@SuppressWarnings("unused")
boolean deleted = this.removeExistingEntity(TOOLS.sanitizeResponse(dataMainObj.get("id")));
team.setCollectorId(featureCollectorRepository.findByName("Jira").getId());
team.setTeamId(TOOLS.sanitizeResponse(dataMainObj.get("id")));
team.setName(TOOLS.sanitizeResponse(dataMainObj.get("name")));
team.setChangeDate("");
team.setAssetState("Active");
team.setIsDeleted("False");
try {
teamRepo.save(team);
} catch (Exception e) {
LOGGER.error("Unexpected error caused when attempting to save data\nCaused by: " + e.getMessage() + " : " + e.getCause(), e);
}
}
} catch (Exception e) {
LOGGER.error("Unexpected error caused while mapping data from source system to local data store:\n" + e.getMessage() + " : " + e.getCause(), e);
}
} |
|
165 | public void onResume(){
super.onResume();
final SearchTimeline searchTimeline = new SearchTimeline.Builder().query(droidconTwitterHashTag).build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(context).setTimeline(searchTimeline).build();
setListAdapter(adapter);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeLayout.setRefreshing(true);
adapter.refresh(new Callback<TimelineResult<Tweet>>() {
@Override
public void success(Result<TimelineResult<Tweet>> result) {
swipeLayout.setRefreshing(false);
}
@Override
public void failure(TwitterException exception) {
Toast.makeText(context, "No Tweets", Toast.LENGTH_SHORT).show();
}
});
}
});
} | public void onResume(){
super.onResume();
final SearchTimeline searchTimeline = new SearchTimeline.Builder().query(droidconTwitterHashTag).build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(context).setTimeline(searchTimeline).build();
setListAdapter(adapter);
swipeLayout.setOnRefreshListener(() -> {
swipeLayout.setRefreshing(true);
adapter.refresh(new Callback<TimelineResult<Tweet>>() {
@Override
public void success(Result<TimelineResult<Tweet>> result) {
swipeLayout.setRefreshing(false);
}
@Override
public void failure(TwitterException exception) {
Toast.makeText(context, "No Tweets", Toast.LENGTH_SHORT).show();
}
});
});
} |
|
166 | public boolean validateModifications(Peptide peptide, SequenceMatchingParameters sequenceMatchingPreferences, SequenceMatchingParameters ptmSequenceMatchingPreferences, ModificationParameters modificationProfile){
ModificationFactory modificationFactory = ModificationFactory.getInstance();
if (unknownPtm) {
ArrayList<ModificationMatch> modificationMatches = peptide.getModificationMatches();
if (modificationMatches != null) {
for (ModificationMatch modMatch : modificationMatches) {
String ptmName = modMatch.getModification();
if (!modificationFactory.containsModification(ptmName)) {
return false;
}
}
}
}
return true;
} | public boolean validateModifications(Peptide peptide, SequenceMatchingParameters sequenceMatchingPreferences, SequenceMatchingParameters modificationSequenceMatchingPreferences, ModificationParameters modificationProfile){
ModificationFactory modificationFactory = ModificationFactory.getInstance();
if (unknownModification) {
ModificationMatch[] modificationMatches = peptide.getModificationMatches();
if (modificationMatches != null) {
if (Arrays.stream(modificationMatches).map(ModificationMatch::getModification).anyMatch(modName -> !modificationFactory.containsModification(modName))) {
return false;
}
}
}
return true;
} |
|
167 | public void init(){
this.localAddress = InetUtils.getSelfIp() + ":" + port;
NotifyManager.registerPublisher(NodeChangeEvent::new, NodeChangeEvent.class);
initSys();
SyncNodeTask task = new SyncNodeTask(servletContext);
taskManager.execute(task);
initAPProtocol();
initCPProtocol();
DistributeIDManager.init(this);
} | public void init(){
this.localAddress = InetUtils.getSelfIp() + ":" + port;
NotifyCenter.registerPublisher(NodeChangeEvent::new, NodeChangeEvent.class);
initSys();
SyncNodeTask task = new SyncNodeTask(servletContext);
taskManager.execute(task);
initAPProtocol();
initCPProtocol();
} |
|
168 | public void calculateArgument16Test(){
StringBuilder xml_ = new StringBuilder();
xml_.append("$public $class pkg.Ex {\n");
xml_.append(" $public $int a;\n");
xml_.append(" $operator+ $int (Ex a, Ex... b){\n");
xml_.append(" $return a.a+b[0].a+b[1].a;\n");
xml_.append(" }\n");
xml_.append(" $public $static $int catching(){\n");
xml_.append(" Ex one = $new Ex();\n");
xml_.append(" one.a=5i;\n");
xml_.append(" Ex two = $new Ex();\n");
xml_.append(" two.a=3i;\n");
xml_.append(" $if ($operator(+,Ex)(one, two,two) != 11i){\n");
xml_.append(" $return 1i;\n");
xml_.append(" }\n");
xml_.append(" $return 2i;\n");
xml_.append(" }\n");
xml_.append("}\n");
StringMap<String> files_ = new StringMap<String>();
ContextEl cont_ = ctx();
files_.put("pkg/Ex", xml_.toString());
Classes.validateAll(files_, cont_);
assertTrue(isEmptyErrors(cont_));
CustList<Argument> args_ = new CustList<Argument>();
MethodId id_ = getMethodId("catching");
Argument ret_;
ret_ = calculateNormal("pkg.Ex", id_, args_, cont_);
assertEq(2, getNumber(ret_));
} | public void calculateArgument16Test(){
StringBuilder xml_ = new StringBuilder();
xml_.append("$public $class pkg.Ex {\n");
xml_.append(" $public $int a;\n");
xml_.append(" $operator+ $int (Ex a, Ex... b){\n");
xml_.append(" $return a.a+b[0].a+b[1].a;\n");
xml_.append(" }\n");
xml_.append(" $public $static $int catching(){\n");
xml_.append(" Ex one = $new Ex();\n");
xml_.append(" one.a=5i;\n");
xml_.append(" Ex two = $new Ex();\n");
xml_.append(" two.a=3i;\n");
xml_.append(" $if ($operator(+,Ex)(one, two,two) != 11i){\n");
xml_.append(" $return 1i;\n");
xml_.append(" }\n");
xml_.append(" $return 2i;\n");
xml_.append(" }\n");
xml_.append("}\n");
StringMap<String> files_ = new StringMap<String>();
files_.put("pkg/Ex", xml_.toString());
ContextEl cont_ = ctxOk(files_);
CustList<Argument> args_ = new CustList<Argument>();
MethodId id_ = getMethodId("catching");
Argument ret_;
ret_ = calculateNormal("pkg.Ex", id_, args_, cont_);
assertEq(2, getNumber(ret_));
} |
|
169 | public ResponseEntity<UserTokenState> refreshAuthenticationToken(HttpServletRequest request){
String token = tokenUtils.getToken(request);
String username = this.tokenUtils.getUsernameFromToken(token);
User user = (User) this.userService.loadUserByUsername(username);
String refreshedToken = tokenUtils.refreshToken(token);
int expiresIn = tokenUtils.getExpiredIn();
return ResponseEntity.ok(new UserTokenState(refreshedToken, expiresIn));
} | public ResponseEntity<UserTokenState> refreshAuthenticationToken(HttpServletRequest request){
String token = tokenUtils.getToken(request);
String refreshedToken = tokenUtils.refreshToken(token);
int expiresIn = tokenUtils.getExpiredIn();
return ResponseEntity.ok(new UserTokenState(refreshedToken, expiresIn));
} |
|
170 | public void onNext(NewsModel countryTopHeadNews){
if (newsModel.getArticles() == null) {
newsModel.setArticles(countryTopHeadNews.getArticles());
} else {
newsModel.getArticles().addAll(countryTopHeadNews.getArticles());
}
viewHolderLayer.setIndiaItem();
} | public void onNext(NewsModel countryTopHeadNews){
viewHolderLayer.setIndiaItem();
} |
|
171 | void testEmptyElements() throws Exception{
String jsonData = TestResourceReader.readFileAsString("xmlEmptyElements.json");
String expectedXml = TestResourceReader.readFileAsString("xmlEmptyElementsNull.xml");
String datasonnet = TestResourceReader.readFileAsString("xmlEmptyElementsNull.ds");
Mapper mapper = new Mapper(datasonnet, Collections.emptyList(), true);
mapper.findAndRegisterPlugins();
String mappedXml = mapper.transform(new StringDocument(jsonData, "application/json"), Collections.emptyMap(), "application/xml").getContentsAsString();
assertThat(mappedXml, CompareMatcher.isSimilarTo(expectedXml).ignoreWhitespace());
expectedXml = TestResourceReader.readFileAsString("xmlEmptyElementsNoNull.xml");
datasonnet = TestResourceReader.readFileAsString("xmlEmptyElementsNoNull.ds");
mapper = new Mapper(datasonnet, Collections.emptyList(), true);
mapper.findAndRegisterPlugins();
mappedXml = mapper.transform(new StringDocument(jsonData, "application/json"), Collections.emptyMap(), "application/xml").getContentsAsString();
assertThat(mappedXml, CompareMatcher.isSimilarTo(expectedXml).ignoreWhitespace());
} | void testEmptyElements() throws Exception{
String jsonData = TestResourceReader.readFileAsString("xmlEmptyElements.json");
String expectedXml = TestResourceReader.readFileAsString("xmlEmptyElementsNull.xml");
String datasonnet = TestResourceReader.readFileAsString("xmlEmptyElementsNull.ds");
Mapper mapper = new Mapper(datasonnet);
String mappedXml = mapper.transform(new StringDocument(jsonData, "application/json"), Collections.emptyMap(), "application/xml").getContentsAsString();
assertThat(mappedXml, CompareMatcher.isSimilarTo(expectedXml).ignoreWhitespace());
expectedXml = TestResourceReader.readFileAsString("xmlEmptyElementsNoNull.xml");
datasonnet = TestResourceReader.readFileAsString("xmlEmptyElementsNoNull.ds");
mapper = new Mapper(datasonnet);
mappedXml = mapper.transform(new StringDocument(jsonData, "application/json"), Collections.emptyMap(), "application/xml").getContentsAsString();
assertThat(mappedXml, CompareMatcher.isSimilarTo(expectedXml).ignoreWhitespace());
} |
|
172 | public static String getSMSBody(String userName, String webUrl, String instanceName, String appName, String setPasswordLink, String verifyEmailLink){
try {
Properties props = new Properties();
URLShortner urlShortner = new URLShortnerImpl();
props.put("resource.loader", "class");
props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine();
ve.init(props);
Map<String, String> params = new HashMap<>();
params.put("userName", StringUtils.isBlank(userName) ? "user_name" : userName);
params.put("webUrl", StringUtils.isBlank(webUrl) ? "web_url" : webUrl);
params.put("instanceName", StringUtils.isBlank(instanceName) ? "instance_name" : instanceName);
if (StringUtils.isNotBlank(appName)) {
params.put("appName", appName);
}
params.put("newline", "\n");
if (StringUtils.isNotBlank(setPasswordLink)) {
params.put(JsonKey.LINK, setPasswordLink);
params.put(JsonKey.SET_PW_LINK, "true");
} else if (StringUtils.isNotBlank(verifyEmailLink)) {
params.put(JsonKey.LINK, setPasswordLink);
params.put(JsonKey.SET_PW_LINK, null);
}
Template t = ve.getTemplate("/welcomeSmsTemplate.vm");
VelocityContext context = new VelocityContext(params);
StringWriter writer = new StringWriter();
t.merge(context, writer);
return writer.toString();
} catch (Exception ex) {
ProjectLogger.log("Exception occurred while formating and sending SMS " + ex);
}
return "";
} | public static String getSMSBody(String userName, String webUrl, String instanceName, String appName, String setPasswordLink, String verifyEmailLink){
try {
Properties props = new Properties();
props.put("resource.loader", "class");
props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine();
ve.init(props);
Map<String, String> params = new HashMap<>();
params.put("userName", StringUtils.isBlank(userName) ? "user_name" : userName);
params.put("webUrl", StringUtils.isBlank(webUrl) ? "web_url" : webUrl);
params.put("instanceName", StringUtils.isBlank(instanceName) ? "instance_name" : instanceName);
if (StringUtils.isNotBlank(appName)) {
params.put("appName", appName);
}
params.put("newline", "\n");
if (StringUtils.isNotBlank(setPasswordLink)) {
params.put(JsonKey.LINK, setPasswordLink);
params.put(JsonKey.SET_PW_LINK, "true");
} else if (StringUtils.isNotBlank(verifyEmailLink)) {
params.put(JsonKey.LINK, setPasswordLink);
params.put(JsonKey.SET_PW_LINK, null);
}
Template t = ve.getTemplate("/welcomeSmsTemplate.vm");
VelocityContext context = new VelocityContext(params);
StringWriter writer = new StringWriter();
t.merge(context, writer);
return writer.toString();
} catch (Exception ex) {
ProjectLogger.log("Exception occurred while formating and sending SMS " + ex);
}
return "";
} |
|
173 | public ResponseEntity findPath(@RequestParam Long startId, @RequestParam Long endId){
PathResponseView response = new PathResponseView(startId, endId, graphService.findPath(startId, endId));
PathResource pathResource = new PathResource(response);
pathResource.add(linkTo(PathController.class).slash("?startId=" + startId + "&endId=" + endId).withSelfRel());
pathResource.add(linkTo(FavoritePathController.class).withRel("favorite-path-create"));
pathResource.add(new Link("/docs/api-guide.html#resource-find-path").withRel("profile"));
return ResponseEntity.ok(pathResource);
} | public ResponseEntity findPath(@RequestParam Long startId, @RequestParam Long endId){
return ResponseEntity.ok(new PathResponseView(startId, endId, graphService.findPath(startId, endId)));
} |
|
174 | void isApproved_should_handle_all_different_review_actions(final String actions, final String title, final String descrition, final boolean result){
final PullRequest pullRequest = mock(PullRequest.class);
when(pullRequest.getTitle()).thenReturn(title);
when(pullRequest.getDescription()).thenReturn(descrition);
when(template.getForObject(anyString(), eq(String.class))).thenReturn(actions);
assertThat(cut.isApproved(pullRequest)).isEqualTo(result);
} | void isApproved_should_handle_all_different_review_actions(final String actions, final boolean allRequested, final boolean result){
final PullRequest pullRequest = mock(PullRequest.class);
when(pullRequest.isReviewByAllReviewersRequested()).thenReturn(allRequested);
when(template.getForObject(anyString(), eq(String.class))).thenReturn(actions);
assertThat(cut.isApproved(pullRequest)).isEqualTo(result);
} |
|
175 | protected void onPause(){
super.onPause();
if (conn != null)
conn.cancel();
if (imageReceiver != null)
imageReceiver.cancel();
} | protected void onPause(){
super.onPause();
if (conn != null)
conn.cancel();
} |
|
176 | public void setupTest(BackendListenerContext arg1){
Util.setLogger(LoggerFactory.getLogger(BackendListener.class));
Util.writeLog("BackendListener initialization", Util.LogLevel.info);
host = arg1.getParameter(ES_HOST);
protocol = arg1.getParameter(ES_PROTOCOL);
port = arg1.getParameter(ES_PORT);
index = arg1.getParameter(ES_INDEX);
document = arg1.getParameter(ES_DOC);
countOfAttempts = arg1.getIntParameter(COUNT_OF_ATTEMPTS);
saveResponseData = Boolean.valueOf(arg1.getParameter(JMETER_RESPONSE));
project = arg1.getParameter(PROJECT);
try {
if (WorkWithServer.doHead(protocol + "://" + host + ":" + port)) {
Util.writeLog("ElasticSearch server is available", Util.LogLevel.info);
} else {
Util.writeLog("BackendListener initialization failed", Util.LogLevel.error);
}
} catch (Exception e) {
Util.writeLog(ExceptionUtils.getStackTrace(e), Util.LogLevel.error);
Util.writeLog("BackendListener initialization failed", Util.LogLevel.info);
}
Util.writeLog("BackendListener initialization successful", Util.LogLevel.info);
} | public void setupTest(BackendListenerContext arg1){
Util.writeLog("BackendListener initialization", Util.LogLevel.info, LOGGER);
host = arg1.getParameter(ES_HOST);
protocol = arg1.getParameter(ES_PROTOCOL);
port = arg1.getParameter(ES_PORT);
index = arg1.getParameter(ES_INDEX);
document = arg1.getParameter(ES_DOC);
countOfAttempts = arg1.getIntParameter(COUNT_OF_ATTEMPTS);
saveResponseData = Boolean.valueOf(arg1.getParameter(JMETER_RESPONSE));
project = arg1.getParameter(PROJECT);
try {
if (WorkWithServer.doHead(protocol + "://" + host + ":" + port)) {
Util.writeLog("ElasticSearch server is available", Util.LogLevel.info, LOGGER);
} else {
Util.writeLog("BackendListener initialization failed", Util.LogLevel.error, LOGGER);
}
} catch (Exception e) {
Util.writeLog(ExceptionUtils.getStackTrace(e), Util.LogLevel.error, LOGGER);
Util.writeLog("BackendListener initialization failed", Util.LogLevel.info, LOGGER);
}
Util.writeLog("BackendListener initialization successful", Util.LogLevel.info, LOGGER);
} |
|
177 | private String getReferenceRDFID(String value, ReferenceNode referenceNode) throws RendererException{
String id = "";
if (referenceNode.hasRDFIDValueEncoding()) {
if (referenceNode.hasExplicitlySpecifiedRDFIDValueEncoding()) {
id = generateReferenceValue(value, referenceNode.getRDFIDValueEncodingNode(), referenceNode);
} else if (referenceNode.hasValueExtractionFunctionNode()) {
id = generateReferenceValue(value, referenceNode.getValueExtractionFunctionNode());
} else {
id = value;
}
}
if (id.isEmpty() && !referenceNode.getActualDefaultRDFID().isEmpty()) {
id = referenceNode.getActualDefaultRDFID();
}
if (id.isEmpty() && referenceNode.getActualEmptyRDFIDDirective() == MM_ERROR_IF_EMPTY_ID) {
throw new RendererException("empty RDF ID in reference " + referenceNode);
}
return id;
} | private String getReferenceRDFID(String value, ReferenceNode referenceNode) throws RendererException{
String id = "";
if (referenceNode.hasRDFIDValueEncoding()) {
if (referenceNode.hasExplicitlySpecifiedRDFIDValueEncoding()) {
id = generateReferenceValue(value, referenceNode.getRDFIDValueEncodingNode(), referenceNode);
} else if (referenceNode.hasValueExtractionFunctionNode()) {
id = generateReferenceValue(value, referenceNode.getValueExtractionFunctionNode());
} else {
id = value;
}
}
if (id.isEmpty() && !referenceNode.getActualDefaultRDFID().isEmpty()) {
id = referenceNode.getActualDefaultRDFID();
}
return id;
} |
|
178 | public void createPatients(Table table) throws Exception{
Patient patient = transformTableToPatient(table);
registrationFirstPage.registerPatient(patient);
waitForAppReady();
String path = driver.getCurrentUrl();
String uuid = path.substring(path.lastIndexOf('/') + 1);
if (!Objects.equals(uuid, "new")) {
patient.setUuid(uuid);
registrationFirstPage.storePatientInSpecStore(patient);
}
} | public void createPatients(Table table) throws Exception{
registrationFirstPage.createPatients(table);
} |
|
179 | public void setAcronym(String acronym){
if (getAcronym() != null && !getAcronym().toUpperCase().equals(acronym.toUpperCase()) || getAcronym() == null) {
if (!acronym.matches("^[A-Za-z0-9\\-]+$")) {
throw new LdoDException("acronym");
}
if (getAcronym() == null || !getAcronym().equals(VirtualEdition.ARCHIVE_EDITION_ACRONYM)) {
TextProvidesInterface textProvidesInterface = new TextProvidesInterface();
if (textProvidesInterface.acronymExists(acronym)) {
throw new LdoDDuplicateAcronymException();
}
for (VirtualEdition edition : VirtualModule.getInstance().getVirtualEditionsSet()) {
if (edition.getAcronym() != null && acronym.toUpperCase().equals(edition.getAcronym().toUpperCase())) {
throw new LdoDDuplicateAcronymException();
}
}
EventInterface eventInterface = new EventInterface();
Event event = new Event(Event.EventType.VIRTUAL_EDITION_UPDATE, this.getAcronym());
event.setNewAcronym(acronym);
eventInterface.publish(event);
super.setAcronym(acronym);
}
}
} | public void setAcronym(String acronym){
if (getAcronym() != null && !getAcronym().toUpperCase().equals(acronym.toUpperCase()) || getAcronym() == null) {
if (!acronym.matches("^[A-Za-z0-9\\-]+$")) {
throw new LdoDException("acronym");
}
if (getAcronym() == null || !getAcronym().equals(VirtualEdition.ARCHIVE_EDITION_ACRONYM)) {
TextProvidesInterface textProvidesInterface = new TextProvidesInterface();
if (textProvidesInterface.acronymExists(acronym)) {
throw new LdoDDuplicateAcronymException();
}
for (VirtualEdition edition : VirtualModule.getInstance().getVirtualEditionsSet()) {
if (edition.getAcronym() != null && acronym.toUpperCase().equals(edition.getAcronym().toUpperCase())) {
throw new LdoDDuplicateAcronymException();
}
}
EventInterface eventInterface = new EventInterface();
Event event = new EventVirtualEditionUpdate(this.getAcronym(), acronym);
eventInterface.publish(event);
super.setAcronym(acronym);
}
}
} |
|
180 | public Collection<Henkilo> findByIdentifications(Collection<IdentificationDto> identifications){
QHenkilo qHenkilo = QHenkilo.henkilo;
QIdentification qIdentification = QIdentification.identification;
List<Predicate> predicates = identifications.stream().map(identification -> {
return qIdentification.idpEntityId.eq(identification.getIdpEntityId()).and(qIdentification.identifier.eq(identification.getIdentifier()));
}).collect(toList());
return jpa().from(qHenkilo).join(qHenkilo.identifications, qIdentification).where(anyOf(predicates)).select(qHenkilo).distinct().fetch();
} | public Collection<Henkilo> findByIdentifications(Collection<IdentificationDto> identifications){
QHenkilo qHenkilo = QHenkilo.henkilo;
QIdentification qIdentification = QIdentification.identification;
List<Predicate> predicates = identifications.stream().map(identification -> qIdentification.idpEntityId.eq(identification.getIdpEntityId()).and(qIdentification.identifier.eq(identification.getIdentifier()))).collect(toList());
return jpa().from(qHenkilo).join(qHenkilo.identifications, qIdentification).where(anyOf(predicates)).select(qHenkilo).distinct().fetch();
} |
|
181 | public ResponseEntity<Vitalsign> updateVitalsignRecord(@RequestBody Vitalsign vitalsign, @PathVariable long id){
Optional<Vitalsign> vitalsignDetails = vitalsignService.updateVitalsignRecord(vitalsign, id);
if (vitalsignDetails.isEmpty()) {
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(vitalsign);
} else {
return ResponseEntity.status(HttpStatus.OK).body(vitalsignDetails.get());
}
} | public VitalsignDto updateVitalsignRecord(@RequestBody VitalsignDto vitalsign, @PathVariable long id){
return vitalsignService.updateVitalsignRecord(vitalsign, id);
} |
|
182 | public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.steps_detail_list, container, false);
if (view instanceof RecyclerView) {
Context context = view.getContext();
mRecyclerView = (RecyclerView) view;
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
}
DetailViewModelFactory factory = InjectorUtils.provideDetailViewModelFactory(Objects.requireNonNull(this.getContext()), mRecipeID);
DetailViewModel mViewModel = ViewModelProviders.of(this, factory).get(DetailViewModel.class);
mViewModel.getOneRecipe().observe(this, oneRecipe -> {
if (view instanceof RecyclerView) {
Logger.d("Setting detail adapter");
if (getArguments() != null) {
if (getArguments().containsKey(DetailActivity.SHOW_STEPS))
mRecyclerView.setAdapter(new StepListItemAdapter(oneRecipe, mListener));
else if (getArguments().containsKey(DetailActivity.SHOW_INGREDIENTS))
mRecyclerView.setAdapter(new IngredientListItemAdapter(oneRecipe));
}
}
});
return view;
} | public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.steps_detail_list, container, false);
if (view instanceof RecyclerView) {
Context context = view.getContext();
mRecyclerView = (RecyclerView) view;
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
}
DetailViewModelFactory factory = InjectorUtils.provideDetailViewModelFactory(Objects.requireNonNull(this.getContext()), mRecipeID);
DetailViewModel mViewModel = ViewModelProviders.of(this, factory).get(DetailViewModel.class);
mViewModel.getOneRecipe().observe(this, oneRecipe -> {
if (view instanceof RecyclerView) {
if (getArguments() != null) {
if (getArguments().containsKey(DetailActivity.STEPS_MODE))
mRecyclerView.setAdapter(new StepListItemAdapter(oneRecipe, mListener));
else if (getArguments().containsKey(DetailActivity.INGREDIENTS_MODE))
mRecyclerView.setAdapter(new IngredientListItemAdapter(oneRecipe));
}
}
});
return view;
} |
|
183 | public void drawKeyboardGUI() throws InvalidMidiDataException, MidiUnavailableException, IOException{
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = (int) screenSize.getWidth();
screenHeight = (int) screenSize.getHeight();
keyboardLayered = new JLayeredPane();
secondFrame = new JFrame("6100COMP: Computer Music Education Application");
secondFrame.setBounds(0, 0, screenWidth, screenHeight);
secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
secondFrame.setContentPane(keyboardLayered);
secondFrame.setVisible(true);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(0, 0, 500, 52);
keyboardLayered.add(tabbedPane, new Integer(0), 0);
} | public void drawKeyboardGUI() throws InvalidMidiDataException, MidiUnavailableException, IOException{
keyboardLayered = new JLayeredPane();
secondFrame = new JFrame("6100COMP: Computer Music Education Application");
secondFrame.setBounds(0, 0, screenWidth, screenHeight);
secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
secondFrame.setContentPane(keyboardLayered);
secondFrame.setVisible(true);
} |
|
184 | public boolean isValid(String email, ConstraintValidatorContext constraintValidatorContext){
if (email == null) {
return false;
}
return email.matches(EMAIL_PATTERN);
} | public boolean isValid(String email, ConstraintValidatorContext constraintValidatorContext){
return email != null && email.matches(EMAIL_PATTERN);
} |
|
185 | public ResponseEntity<?> getRB001(@Valid @NotBlank @RequestParam(value = "orgCd", defaultValue = "") String orgCd, @Valid @NotBlank @RequestParam(value = "bankCd", defaultValue = "") String bankCd, @Valid @NotBlank @RequestParam(value = "bankCoNo", defaultValue = "") String bankCoNo, @Valid @NotBlank @RequestParam(value = "trnxId", defaultValue = "") String trnxId){
logger.info("--------- START ---------- ::" + System.currentTimeMillis());
List<RB001DTO> er001Infos = rb001Service.getRB001(orgCd, bankCd, bankCoNo, trnxId);
logger.info("--------- END ---------- ::" + System.currentTimeMillis());
return new ResponseEntity<>(er001Infos, HttpStatus.OK);
} | public ResponseEntity<?> getRB001(@Valid @NotBlank @RequestParam(value = "orgCd", defaultValue = "") String orgCd, @Valid @NotBlank @RequestParam(value = "bankCd", defaultValue = "") String bankCd, @Valid @NotBlank @RequestParam(value = "bankCoNo", defaultValue = "") String bankCoNo, @Valid @NotBlank @RequestParam(value = "trnxId", defaultValue = "") String trnxId){
List<RB001DTO> er001Infos = rb001Service.getRB001(orgCd, bankCd, bankCoNo, trnxId);
return new ResponseEntity<>(er001Infos, HttpStatus.OK);
} |
|
186 | public ResponseEntity<GetPacakageInformationResponse> getSubmissionPackage(UUID id){
Optional<Submission> fromCacheSubmission = this.submissionStore.getByKey(id);
if (!fromCacheSubmission.isPresent())
return ResponseEntity.notFound().build();
GetPacakageInformationResponse response = new GetPacakageInformationResponse();
ParentApplication parentApplication = new ParentApplication();
parentApplication.setApplicationType(fromCacheSubmission.get().getParentApplication().getApplicationType());
parentApplication.setCourtLocation(fromCacheSubmission.get().getParentApplication().getCourtLocation());
parentApplication.setCourtLevel(fromCacheSubmission.get().getParentApplication().getCourtLevel());
parentApplication.setCourtDivision(fromCacheSubmission.get().getParentApplication().getCourtDivision());
parentApplication.setCourtClass(fromCacheSubmission.get().getParentApplication().getCourtClass());
parentApplication.setParticipationClass(fromCacheSubmission.get().getParentApplication().getParticipationClass());
parentApplication.setIndigenousStatus(fromCacheSubmission.get().getParentApplication().getIndigenousStatus());
parentApplication.setDocumentType(fromCacheSubmission.get().getParentApplication().getDocumentType());
parentApplication.setCourtFileNumber(fromCacheSubmission.get().getParentApplication().getCourtFileNumber());
response.setParentApplication(parentApplication);
return ResponseEntity.ok(response);
} | public ResponseEntity<GetPacakageInformationResponse> getSubmissionPackage(UUID id){
Optional<Submission> fromCacheSubmission = this.submissionStore.getByKey(id);
if (!fromCacheSubmission.isPresent())
return ResponseEntity.notFound().build();
GetPacakageInformationResponse response = new GetPacakageInformationResponse();
response.setParentApplication(fromCacheSubmission.get().getParentApplication());
return ResponseEntity.ok(response);
} |
|
187 | public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connected to GATT server.");
Log.i(TAG, "Discovering services.");
if (!mBluetoothGatt.discoverServices()) {
Log.e(TAG, "Service discovery failed to start.");
}
broadcastUpdate(ACTION_CONNECTING);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(ACTION_DISCONNECTED);
unregisterReceiver(mReceiver);
registerReceiver(mReceiver, mDisconnectedFilter);
}
} | public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connected to GATT server.");
Log.i(TAG, "Discovering services.");
if (!mBluetoothGatt.discoverServices()) {
Log.e(TAG, "Service discovery failed to start.");
}
broadcastUpdate(ACTION_CONNECTING);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mConnected = false;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(ACTION_DISCONNECTED);
}
} |
|
188 | public void sendMarkers(NeighborUpdate.Neighbors neighbors){
System.out.println("SendMarkers");
endpoint.send(neighbors.getRightNeighbor(), new SnapshotMarker());
endpoint.send(neighbors.getLeftNeighbor(), new SnapshotMarker());
} | public void sendMarkers(NeighborUpdate.Neighbors neighbors){
endpoint.send(neighbors.getRightNeighbor(), new SnapshotMarker());
endpoint.send(neighbors.getLeftNeighbor(), new SnapshotMarker());
} |
|
189 | public ResponseEntity<Person> updatePerson(@PathVariable("id") final Long id, @RequestBody Person person){
Optional<Person> p = personService.getPersonById(id);
if (p.isPresent()) {
Person currentPerson = p.get();
String email = person.getEmail();
if (email != null) {
currentPerson.setEmail(email);
}
Integer zip = person.getZip();
if (zip != null) {
currentPerson.setZip(zip);
}
String city = person.getCity();
if (city != null) {
currentPerson.setCity(city);
}
String address = person.getAddress();
if (address != null) {
currentPerson.setAddress(address);
}
String phone = person.getPhone();
if (phone != null) {
currentPerson.setPhone(phone);
}
personService.savePerson(currentPerson);
return ResponseEntity.ok().body(currentPerson);
} else {
return ResponseEntity.notFound().build();
}
} | public ResponseEntity<Person> updatePerson(@PathVariable("id") final Long id, @RequestBody Person person){
Optional<Person> p = personService.updatePerson(id, person);
if (p.isPresent()) {
return ResponseEntity.ok().body(person);
} else {
return ResponseEntity.notFound().build();
}
} |
|
190 | private Handler buildSelectionChangeHandler(){
return new Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
int selectedFlows = countSelectedFlows();
if (autoPreview) {
previewSelected(true, true);
}
if (selectedFlows == 0) {
setUiForNothingSelected();
} else {
refreshReplaceAllButton();
}
}
};
} | private Handler buildSelectionChangeHandler(){
return event -> {
int selectedFlows = countSelectedFlows();
if (autoPreview) {
previewSelected(true, true);
}
if (selectedFlows == 0) {
setUiForNothingSelected();
} else {
refreshReplaceAllButton();
}
};
} |
|
191 | private void initNotificationScheduler(){
ThreadFactory threadFactory = new ThreadFactory() {
private int threadNumber = 0;
public Thread newThread(Runnable r) {
threadNumber += 1;
Thread t = new Thread(r, "HumanTaskServer-" + threadNumber);
t.setDaemon(true);
return t;
}
};
ExecutorService executorService = Executors.newFixedThreadPool(serverConfig.getThreadPoolMaxSize(), threadFactory);
NotificationScheduler notificationScheduler = new NotificationScheduler();
notificationScheduler.setExecutorService(executorService);
taskEngine.setNotificationScheduler(notificationScheduler);
} | private void initNotificationScheduler(){
NotificationScheduler notificationScheduler = new NotificationScheduler();
taskEngine.setNotificationScheduler(notificationScheduler);
} |
|
192 | public void call(final Object... args){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
mUserList.clear();
JSONArray jsonArray = new JSONArray(args);
String aa = jsonArray.getString(0).toString();
Log.e("data:", aa);
JSONArray newArr = new JSONArray(aa);
for (int i = 0; i < newArr.length(); i++) {
JSONObject jsonObject = newArr.getJSONObject(i);
User user = new User();
String name = jsonObject.getString("user_name");
user.setUserName(name);
if (name.equalsIgnoreCase(mUsername)) {
Log.e("user_matched", "I am " + mUsername);
continue;
}
user.setEmail(jsonObject.getString("email"));
user.setStatus("online");
user.setSocket_id(jsonObject.getString("socket_id"));
Log.e("email", jsonObject.getString("email"));
mUserList.add(user);
}
mUsrAdapter.notifyDataSetChanged();
} catch (JSONException e) {
Log.e("user_registration", "JSONException" + e.toString());
} catch (Exception e) {
Log.e("user_registration", "Exception" + e.toString());
}
}
});
} | public void call(final Object... args){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
mUserList.clear();
JSONArray jsonArray = new JSONArray(args);
String aa = jsonArray.getString(0).toString();
Log.e("data:", aa);
JSONArray newArr = new JSONArray(aa);
for (int i = 0; i < newArr.length(); i++) {
JSONObject jsonObject = newArr.getJSONObject(i);
User user = new User();
String name = jsonObject.getString("user_name");
user.setUserName(name);
if (name.equalsIgnoreCase(mUsername)) {
Log.e("user_matched", "I am " + mUsername);
continue;
}
user.setEmail(jsonObject.getString("email"));
user.setSocket_id(jsonObject.getString("socket_id"));
Log.e("email", jsonObject.getString("email"));
mUserList.add(user);
}
mUsrAdapter.notifyDataSetChanged();
} catch (JSONException e) {
Log.e("user_registration", "JSONException" + e.toString());
} catch (Exception e) {
Log.e("user_registration", "Exception" + e.toString());
}
}
});
} |
|
193 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
Log.d(TAG, "onCreateView: starts");
mBoardPresenter = new BoardPresenter(this, getActivity());
setHasOptionsMenu(true);
mBoardPresenter.checkIfAllRecordsAreUpToDate();
mView = inflater.inflate(R.layout.fragment_main, container, false);
mBoardLayout = mView.findViewById(R.id.fragment_main_board);
for (int i = 0; i < 16; i++) {
mBoardLayout.getChildAt(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: CLICK HAPPENS");
if (mBoardEnabled) {
view.setClickable(false);
int position = mBoardLayout.indexOfChild(view);
Card card = mBoardPresenter.onCardSelected(position);
if (card != null) {
final ImageView iv = (ImageView) view;
if (mOneSelected) {
Log.d(TAG, "onClick: starts");
mBoardEnabled = false;
mOneSelected = false;
} else {
mOneSelected = true;
}
startCardShowAnimation(iv, card.getImageResourceId());
}
}
}
});
}
return mView;
} | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_main, container, false);
mBoardLayout = view.findViewById(R.id.fragment_main_board);
setHasOptionsMenu(true);
mBoardEngine = new BoardEngine(this, getActivity());
mBoardEngine.checkIfAllRecordsAreUpToDate();
for (int i = 0; i < 16; i++) {
mBoardLayout.getChildAt(i).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mBoardEnabled) {
view.setClickable(false);
int position = mBoardLayout.indexOfChild(view);
Card card = mBoardEngine.onCardSelected(position);
if (card != null) {
final ImageView iv = (ImageView) view;
if (mOneSelected) {
mBoardEnabled = false;
mOneSelected = false;
} else {
mOneSelected = true;
}
startCardShowAnimation(iv, card.getImageResourceId());
}
}
}
});
}
return view;
} |
|
194 | public Set<Driver> findAll() throws SQLException, NamingException{
Context ctx = new InitialContext();
Context envContext = (Context) ctx.lookup("java:comp/env");
DataSource dataSource = (javax.sql.DataSource) envContext.lookup("jdbc/TestDB");
Connection con = null;
try {
con = dataSource.getConnection();
PreparedStatement findAllDriversStatement = con.prepareStatement("SELECT * FROM drivers ORDER BY id");
ResultSet drivers = findAllDriversStatement.executeQuery();
Set<Driver> driverSet = new HashSet();
while (drivers.next()) {
Driver driver = new Driver();
driver.setId(drivers.getInt("id"));
driver.setName(drivers.getString("name"));
driver.setPassportSerialNumbers(drivers.getString("passport_serial_numbers"));
driver.setPhoneNumber(drivers.getString("phone_number"));
driverSet.add(driver);
}
findAllDriversStatement.close();
drivers.close();
return driverSet;
} finally {
if (con != null)
try {
con.close();
} catch (Exception ignore) {
}
}
} | public Set<Driver> findAll() throws SQLException, NamingException{
Connection con = null;
try {
con = dataSource.getConnection();
PreparedStatement findAllDriversStatement = con.prepareStatement("SELECT * FROM drivers ORDER BY id");
ResultSet drivers = findAllDriversStatement.executeQuery();
Set<Driver> driverSet = new HashSet();
while (drivers.next()) {
Driver driver = new Driver();
driver.setId(drivers.getInt("id"));
driver.setName(drivers.getString("name"));
driver.setPassportSerialNumbers(drivers.getString("passport_serial_numbers"));
driver.setPhoneNumber(drivers.getString("phone_number"));
driverSet.add(driver);
}
findAllDriversStatement.close();
drivers.close();
return driverSet;
} finally {
if (con != null)
try {
con.close();
} catch (Exception ignore) {
}
}
} |
|
195 | public void onBackPressed(){
if (isFirstLaunch == true) {
if (step > 3) {
int locationOption = configurationFragment.getChoosenLocationOption();
if (locationOption == 1 && step == 4)
exitDialog.show();
} else
exitDialog.show();
}
Log.d("step end", "" + step);
} | public void onBackPressed(){
if (isFirstLaunch == true) {
if (step > 3) {
int locationOption = configurationFragment.getChoosenDefeaultLocationOption();
if (locationOption == 1 && step == 4)
exitDialog.show();
} else
exitDialog.show();
}
} |
|
196 | public ResponseEntity<Team> createTeam(@RequestBody Team t){
Logger.getLogger("TeamController.java").log(Logger.Level.INFO, "POST on /team/create -- creating team " + t.toString());
t.setActive(1);
Team created = teamRepository.save(t);
if (created != null) {
Logger.getLogger("TeamController.java").log(Logger.Level.INFO, "Successfully created team " + created.toString());
return new ResponseEntity(created, HttpStatus.OK);
} else {
Logger.getLogger("TeamController.java").log(Logger.Level.INFO, "Failed to create team " + t.toString());
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
} | public ResponseEntity<Team> createTeam(@RequestBody Team t){
Logger.getLogger("TeamController.java").log(Logger.Level.INFO, "POST on /team/create -- creating team " + t.toString());
t.setActive(1);
Team created = teamRepository.save(t);
return (created != null) ? new ResponseEntity(created, HttpStatus.OK) : new ResponseEntity(HttpStatus.BAD_REQUEST);
} |
|
197 | public Page<SubmissionSectionRest> findAll(Context context, Pageable pageable){
List<SubmissionConfig> subConfs = new ArrayList<SubmissionConfig>();
subConfs = submissionConfigReader.getAllSubmissionConfigs(pageable.getPageSize(), pageable.getOffset());
int total = 0;
List<SubmissionStepConfig> stepConfs = new ArrayList<>();
for (SubmissionConfig config : subConfs) {
total = +config.getNumberOfSteps();
for (int i = 0; i < config.getNumberOfSteps(); i++) {
SubmissionStepConfig step = config.getStep(i);
stepConfs.add(step);
}
}
Projection projection = utils.obtainProjection(true);
Page<SubmissionSectionRest> page = new PageImpl<>(stepConfs, pageable, total).map((object) -> converter.toRest(object, projection));
return page;
} | public Page<SubmissionSectionRest> findAll(Context context, Pageable pageable){
List<SubmissionConfig> subConfs = submissionConfigReader.getAllSubmissionConfigs(pageable.getPageSize(), pageable.getOffset());
long total = 0;
List<SubmissionStepConfig> stepConfs = new ArrayList<>();
for (SubmissionConfig config : subConfs) {
total = +config.getNumberOfSteps();
for (int i = 0; i < config.getNumberOfSteps(); i++) {
SubmissionStepConfig step = config.getStep(i);
stepConfs.add(step);
}
}
return converter.toRestPage(stepConfs, pageable, total, utils.obtainProjection(true));
} |
|
198 | private void updateModels(){
if (this.landerModel == null) {
OBJModel model;
try {
model = (OBJModel) ModelLoaderRegistry.getModel(new ResourceLocation(Constants.ASSET_PREFIX, "jupiter_lander.obj"));
model = (OBJModel) model.process(ImmutableMap.of("flip-v", "true"));
Function<ResourceLocation, TextureAtlasSprite> spriteFunction = location -> MCUtilities.getMinecraft().getTextureMapBlocks().getAtlasSprite(location.toString());
this.landerModel = (OBJModel.OBJBakedModel) model.bake(new OBJModel.OBJState(ImmutableList.of("Body", "FirstLeg", "FirstLegPart1", "FirstLegPart2", "TwoLeg", "TwoLegPart1", "TwoLegPart2", "ThirdLeg", "ThirdLegPart1", "ThirdLegPart2", "FourLeg", "FourLegPart1", "FourLegPart2"), false), DefaultVertexFormats.ITEM, spriteFunction);
} catch (Exception e) {
e.printStackTrace();
}
}
} | private void updateModels(){
if (this.landerModel == null) {
try {
landerModel = ModelUtilities.modelFromOBJForge(new ResourceLocation(Constants.ASSET_PREFIX, "jupiter_lander.obj"), ImmutableList.of("Body", "FirstLeg", "FirstLegPart1", "FirstLegPart2", "TwoLeg", "TwoLegPart1", "TwoLegPart2", "ThirdLeg", "ThirdLegPart1", "ThirdLegPart2", "FourLeg", "FourLegPart1", "FourLegPart2"));
} catch (Exception e) {
e.printStackTrace();
}
}
} |
|
199 | public String getCashTransactionDetails(HttpServletRequest request, Model model){
cashTransferService.getUserAccountDetails(request);
List<UserAccountDetails> userAccountDetailsList = (List<UserAccountDetails>) request.getSession().getAttribute("listAllAccount");
List<UserAccountDetails> listAllAccount = cashTransactionManagementService.getUserAccountDetails();
request.getSession().setAttribute("userDetails", listAllAccount);
UserAccountDetails details = (UserAccountDetails) request.getSession().getAttribute("userDetail");
Integer userId = 0;
String loggedInUserId = details.getLoginId();
if (Objects.nonNull(loggedInUserId)) {
UserAccountDetails userAccountDetails = cashTransactionManagementDao.findUserAccountByUserId(loggedInUserId);
userId = userAccountDetails.getAccountNo();
model.addAttribute("accountNo", userAccountDetails.getAccountNo());
model.addAttribute("balanceAmount", userAccountDetails.getBalanceAmount());
}
List<TransactionDetails> tranactionDetails = userAccountDetailsRepository.accountTransactonsForDebit(userId);
List<TransactionDetails> tranactionDetails1 = userAccountDetailsRepository.accountTransactonsForCredit(userId);
request.getSession().setAttribute("tranactionDetails", tranactionDetails);
request.getSession().setAttribute("tranactionDetails1", tranactionDetails1);
return "transactionHistory";
} | public String getCashTransactionDetails(HttpServletRequest request, Model model){
List<UserAccountDetails> listAllAccount = cashTransactionManagementService.getUserAccountDetails();
request.getSession().setAttribute(Constants.USER_DETAILS, listAllAccount);
UserAccountDetails details = (UserAccountDetails) request.getSession().getAttribute(Constants.USER_DETAIL);
Integer userId = 0;
String loggedInUserId = details.getLoginId();
if (Objects.nonNull(loggedInUserId)) {
UserAccountDetails userAccountDetails = cashTransactionManagementDao.findUserAccountByUserId(loggedInUserId);
userId = userAccountDetails.getAccountNo();
model.addAttribute("accountNo", userAccountDetails.getAccountNo());
model.addAttribute("balanceAmount", userAccountDetails.getBalanceAmount());
}
List<TransactionDetails> accountTransactonsForDebit = userAccountDetailsRepository.accountTransactonsForDebit(userId);
List<TransactionDetails> accountTransactonsForCredit = userAccountDetailsRepository.accountTransactonsForCredit(userId);
request.getSession().setAttribute("tranactionDetails", accountTransactonsForDebit);
request.getSession().setAttribute("tranactionDetails1", accountTransactonsForCredit);
return Constants.TRANSACTION_HISTORY;
} |