blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ceabf0fd2926fa4d1236e86f5a6f9676de362dc2 | d7b6cb02a0ea427388b62c0e5a39c2bff13e0e77 | /src/test/java/com/google/cloud/tools/appengine/api/whitelist/AppEngineJreWhitelistTest.java | 30b93a2e207b76d6e231809e728848bff69ade3d | [
"Apache-2.0"
] | permissive | kpstsp/appengine-plugins-core | ebc577045efa63aeb0ca5cbc92cd9d4a428562da | 79e103c60a053bf017de0aad2a78ebd833e8b054 | refs/heads/master | 2020-03-07T07:08:18.727062 | 2018-03-29T17:55:04 | 2018-03-29T17:55:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,701 | java | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.tools.appengine.api.whitelist;
import org.junit.Assert;
import org.junit.Test;
public class AppEngineJreWhitelistTest {
@Test
public void testNotWhitelisted() {
Assert.assertFalse(AppEngineJreWhitelist.contains("java.net.CookieManager"));
}
@Test
public void testWhitelisted() {
Assert.assertTrue(AppEngineJreWhitelist.contains("java.lang.String"));
}
@Test
public void testWhitelisted_nonJreClass() {
Assert.assertTrue(AppEngineJreWhitelist.contains("com.google.Bar"));
}
@Test
public void testWhitelisted_OmgClass() {
Assert.assertFalse(AppEngineJreWhitelist.contains("org.omg.CosNaming.BindingIterator"));
}
@Test
public void testWhitelisted_GssClass() {
Assert.assertFalse(AppEngineJreWhitelist.contains("org.ietf.jgss.GSSContext"));
}
@Test
public void testWhitelisted_JavaxClass() {
Assert.assertTrue(AppEngineJreWhitelist.contains("javax.servlet.ServletRequest"));
}
@Test
public void testWhitelisted_SwingClass() {
Assert.assertFalse(AppEngineJreWhitelist.contains("javax.swing.JFrame"));
}
}
| [
"noreply@github.com"
] | kpstsp.noreply@github.com |
49f3efcd1a963b4d9009b644b255904a49681204 | e59d7641399e05f3518dc1f6d745e61d3795623e | /app/src/main/java/com/example/ypavshl/example/MyService.java | 4cf36f163505a15864b86c3c0c43cd5768e4ca7b | [] | no_license | plastec/RxRemote | 88169376161b98716e0282d6e39a0dfe38efa79f | 9a0419915c9227bc29f1d4e75344309db24f0e40 | refs/heads/master | 2021-01-10T06:21:09.874062 | 2016-03-22T20:12:07 | 2016-03-22T20:12:07 | 49,578,861 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,322 | java | package com.example.ypavshl.example;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.*;
import android.support.annotation.Nullable;
import android.util.Log;
import ru.yandex.music.rxremote.RxBridge;
import ru.yandex.music.rxremote.RxSingleBridge;
import ru.yandex.music.rxremote.parcel.RemoteKey;
import rx.android.schedulers.AndroidSchedulers;
import rx.subjects.BehaviorSubject;
/**
* Created by ypavshl on 24.12.15.
*
* How to generate Parcelable quickly:
* http://codentrick.com/quickly-create-parcelable-class-in-android-studio/
* http://www.parcelabler.com/
*
*/
public class MyService extends Service {
private static final String TAG = MyService.class.getSimpleName();
public static final RemoteKey<ColorItem> COLOR_OBSERVABLE_KEY
= new RemoteKey<>("COLOR_OBSERVABLE", ColorItem.class);
private RxBridge mBridge;
private BehaviorSubject<ColorItem> mColorObservable = BehaviorSubject.create();
private Thread mRoutine;
private volatile int mCounter;
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
mCounter = 0;
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
mColorObservable.onNext(new ColorItem("item: " + ++mCounter + " " + MyService.this,
ColorGenerator.generate()));
}
}
};
// private Observable.OnSubscribe<Integer> mOnSubscribe = new Observable.OnSubscribe<Integer>() {
// @Override
// public void call(Subscriber<? super Integer> subscriber) {
// Log.i("AAAA", "call subscriber = " + subscriber + " " + this);
// }
// };
@Override
public void onCreate() {
super.onCreate();
mRoutine = new Thread(mRunnable);
mRoutine.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
RxSingleBridge bridge = intent.getParcelableExtra("result_bridge");
bridge.offerObservable(COLOR_OBSERVABLE_KEY, mColorObservable);
// Observable<Integer> observable = Observable.create(mOnSubscribe);
// observable.subscribe(integer -> {});
// observable.subscribe(integer -> {});
// observable.subscribe(integer -> {});
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
mBridge = new RxBridge(this);
mBridge.offerObservable(COLOR_OBSERVABLE_KEY, mColorObservable);
Log.i(TAG + " REMOTE", "mBridge.get().subscribe");
mBridge.observe(MyActivity.BUTTON_OBSERVABLE_KEY)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(colorItem -> {
mCounter = 0;
mColorObservable.onNext(new ColorItem("item: " + mCounter , Color.WHITE));
});
// mRoutine = new Thread(mRunnable);
// mRoutine.start();
return mBridge;
}
@Override
public boolean onUnbind(Intent intent) {
mBridge.dismissObservables();
mRoutine.interrupt();
return super.onUnbind(intent);
}
}
| [
"ypavshl@yandex-team.ru"
] | ypavshl@yandex-team.ru |
04e9a11dcec9ef38a9c0d2f327a5bf41c5452387 | 082213c7dd1c95964a79c56918bf387336d7e44e | /src/main/java/com/sdk4/common/id/IdUtils.java | 0db7df84848c129eca64d9df11a1efa6324e8bd0 | [] | no_license | cnJun/sdk4-java-common | 94c1c1c4826d5426448b7b5e4fcf3939eedfd553 | 42ee3d8523c08b3b887a624cf2399e0fcab19f97 | refs/heads/master | 2020-03-29T04:31:37.252335 | 2018-12-21T03:51:32 | 2018-12-21T03:51:32 | 149,535,246 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 415 | java | package com.sdk4.common.id;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
/**
* id
*
* @author sh
*/
public class IdUtils {
private IdUtils() {
throw new IllegalStateException("Utility class");
}
public static UUID fastUUID() {
ThreadLocalRandom random = ThreadLocalRandom.current();
return new UUID(random.nextLong(), random.nextLong());
}
}
| [
"junsh@126.com"
] | junsh@126.com |
93002e62450f5fe30d08cd607c23e6ddfe515ac8 | c4398e4ce561aa65278fe01d96aaeb8cd449df47 | /src/algorithms/dynamic_programming/Number_Of_Corner_Rectangles.java | 1aaab6f20bf50f920818d7936ddb4682ab573500 | [] | no_license | lytbfml/LeetCode | ef68820ae86b2797128dab75db1070cbfbe13203 | 51b042216e8b540844934fb0e42cbe24f9936696 | refs/heads/master | 2020-04-05T16:58:53.874980 | 2019-11-14T09:34:27 | 2019-11-14T09:34:27 | 157,038,385 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,148 | java | package algorithms.dynamic_programming;
/**
* @author Yangxiao Wang on 10/31/2019
*/
public class Number_Of_Corner_Rectangles {
public int countCornerRectangles(int[][] grid) {
int[][] dp = new int[grid[0].length][grid[0].length];
for (int i = 0; i < grid[0].length; i++) {
for (int j = i + 1; j < grid[0].length; j++) {
if (grid[0][i] == 1 && grid[0][j] == 1) {
dp[i][j] = 1;
}
}
}
int res = 0;
for (int i = 1; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
for (int k = j + 1; k < grid[0].length; k++) {
if (grid[i][k] == 1) {
res += dp[j][k];
dp[j][k]++;
}
}
}
}
}
return res;
}
public int countCornerRectangles_beter(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[] mem = new int[n * n];
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
for (int k = j + 1; k < n; k++) {
if (grid[i][k] == 1) {
int pos = j * n + k;
res += mem[pos];
mem[pos]++;
}
}
}
}
}
return res;
}
}
| [
"lytbfml@gmail.com"
] | lytbfml@gmail.com |
16fe40e2c23a27881b1a1a3032e83944d5c175aa | 5cefafafa516d374fd600caa54956a1de7e4ce7d | /oasis/web/ePolicy/PM/src/dti/pm/agentmgr/AgentManager.java | 766a85f117ff58f6d21b6950126288fceac7f58d | [] | no_license | TrellixVulnTeam/demo_L223 | 18c641c1d842c5c6a47e949595b5f507daa4aa55 | 87c9ece01ebdd918343ff0c119e9c462ad069a81 | refs/heads/master | 2023-03-16T00:32:08.023444 | 2019-04-08T15:46:48 | 2019-04-08T15:46:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,620 | java | package dti.pm.agentmgr;
import dti.oasis.recordset.Record;
import dti.oasis.recordset.RecordSet;
import dti.pm.policymgr.PolicyHeader;
/**
* Interface to handle Agent data.
* <p>(C) 2003 Delphi Technology, inc. (dti)</p>
* Date: Apr 26, 2007
*
* @author gjlong
*/
/*
*
* Revision Date Revised By Description
* ---------------------------------------------------
* Mar 21, 2008 James Issue#75265 CreatedAdd Agent Tab to eCIS.
* Same functionality, look and feel
* Apr 17, 2008 James Issue#75265 Modify code according to code review
* 10/07/2008 yhyang Issue#86934 Move CIS Agent to eCIS.
*
* 03/13/2013 awu 141924 - Added validateLicensedAgent.
* 03/22/2013 skommi Issue#111565 Added loadAllAgentHistory() method.
* ---------------------------------------------------
*/
public interface AgentManager {
/**
* Method to load agent and its related data for a policy
*
* @param inputRecord a record containing policy information
* @return recordSet resultset containing agents and their commission information
*/
public RecordSet loadAllPolicyAgent(PolicyHeader policyHeader, Record inputRecord);
/**
* Method to load expired agents for a policy
*
* @param inputRecord a record containing policy information
* @return recordSet resultset containing agents and their commission information
*/
public RecordSet loadAllAgentHistory(Record inputRecord);
/**
* Method to load agent summary
* @param inputRecord input record that contains policy id
* @return agent summary
*/
public RecordSet loadAllPolicyAgentSummary(Record inputRecord);
/**
* Validate all input records
*
* @param policyHeader the summary policy information corresponding to the provided agents.
* @param inputRecords a set of Records, each with the updated Agent Detail info
* matching the fields returned from the loadAllAgent method.
* @return record.
*/
public void validateAllPolicyAgent(PolicyHeader policyHeader, RecordSet inputRecords);
/**
* Save all input records with UPDATE_IND set to 'Y' - updated, 'I' - inserted, or 'D' - deleted.
*
* @param policyHeader the summary policy information corresponding to the provided agents.
* @param inputRecords a set of Records, each with the updated Agent Detail info
* matching the fields returned from the loadAllAgent method.
* @return the number of rows updated.
*/
public int saveAllPolicyAgent(PolicyHeader policyHeader, RecordSet inputRecords);
/**
* method to load the initial license information for a agent
*
* @param policyHeader: summary information about the policy
* @param inputRecord a record contains licenseClassCode(PRODUCER, SUB_PROD, COUNT_SIGN, AUTH_REP)
* state code, policyTypeCode, policyEffDate, policyId
* @return record
*/
public Record getInitialValuesForPolicyAgent(PolicyHeader policyHeader, Record inputRecord);
/**
* method to get the initial value when adding a agent
*
* @param inputRecord
*
* @return record
*/
public Record getInitialValuesForAddPolicyAgent(PolicyHeader policyHeader, Record inputRecord);
/**
* validate the producer exists or not.
* @param inputRecord
*/
public void validateLicensedAgent(Record inputRecord, PolicyHeader policyHeader);
}
| [
"athidevwork@gmail.com"
] | athidevwork@gmail.com |
cb6a32a9ba38a02ddb9c330f06e349e369122f11 | b57cc71bc96db779d8905194be6c1cb9fd8b3cea | /TTTFx/src/main/java/HumanVHumanTurnHandler.java | d7eea1a5cae025d9d3543cae4cfafaa7730cdab2 | [] | no_license | emashliles/java-tic-tac-toe | 5f26cccd5ae8fa8ec6025d4f1f100fce8e855531 | 4470552ea69f06ca07aec497989f354cbf068d62 | refs/heads/master | 2021-01-11T16:33:18.503645 | 2017-02-28T20:17:39 | 2017-02-28T20:17:39 | 80,107,532 | 0 | 0 | null | 2019-10-28T09:25:02 | 2017-01-26T11:02:55 | Java | UTF-8 | Java | false | false | 830 | java | public class HumanVHumanTurnHandler implements TurnHandler {
private PlayerMarkers lastPlayerMoved;
public void getPlayerTurn(String spaceString, Player player1, Player player2, PlayerMarkers currentPlayer) {
HumanFxPlayer player1Human = (HumanFxPlayer) player1;
HumanFxPlayer player2Human = (HumanFxPlayer) player2;
if(currentPlayer == PlayerMarkers.X) {
player1Human.getUserInput(Integer.parseInt(spaceString) - 1);
}
else {
player2Human.getUserInput(Integer.parseInt(spaceString) - 1);
}
}
@Override
public void doTurn(Game game, Board board) {
lastPlayerMoved = game.getCurrentPlayer();
game.doTurn(board);
}
@Override
public PlayerMarkers lastPlayerToMove() {
return lastPlayerMoved;
}
}
| [
"emashliles@gmail.com"
] | emashliles@gmail.com |
64e65d7e08660118e2e2fc13513bf247d004f2f4 | 2746761478e36575264a7233420c165c5877c7b3 | /TomCode/src/RubberLines.java | aa6473ac1d8d2b9051c5b36571c340572fd0103c | [] | no_license | tkgray/TomCode | e1b30abc6eb7d0b289487278d1d61acdb7c74d6a | 7e170d8cab97cb25361462b9327df124bf761d63 | refs/heads/master | 2016-09-06T12:53:20.325658 | 2012-11-28T23:05:10 | 2012-11-28T23:05:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,162 | java | //*************************************************************
// RubberLines.java Author: Lewis and Loftus
// Upate: Constance Conner
// Demonstrates mouse events and listeners using inner classes.
//*************************************************************
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class RubberLines extends Applet
{
private final int APPLET_WIDTH = 200;
private final int APPLET_HEIGHT = 200;
private Point point1 = null;
private Point point2 = null;
//--------------------------------------------------------
// Applet registers listeners for all mouse related events.
//--------------------------------------------------------
public void init()
{
addMouseListener (new MouseHandler());
addMouseMotionListener (new MouseMotionHandler());
setBackground (Color.black);
setSize (APPLET_WIDTH, APPLET_HEIGHT);
}
//--------------------------------------------------------
// Draws the current line from the intial mouse down point
// to the current position of the mouse.
//--------------------------------------------------------
public void paint (Graphics page)
{
page.setColor (Color.green);
if (point1 != null && point2 != null)
page.drawLine (point1.x, point1.y, point2.x, point2.y);
}
//--------------------------------------------------------
// MouseHandler is an inner class listening for mouse events
//--------------------------------------------------------
private class MouseHandler implements MouseListener
{
//--------------------------------------------------
// Captures the position at which the mouse is pushed.
//---------------------------------------------------
public void mousePressed (MouseEvent event)
{
point1 = event.getPoint();
}
//-----------------------------------------------------
// Provide empty definitions for unused event methods.
//-----------------------------------------------------
public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}
//--------------------------------------------------------
// MouseMotionHandler is an inner class listening for mouse
// motion events
//--------------------------------------------------------
private class MouseMotionHandler implements MouseMotionListener
{
//------------------------------------------------------
// Gets the current position of the mouse as it is dragged
// and draws the line to create the rubberband effect
//-------------------------------------------------------
public void mouseDragged (MouseEvent event)
{
point2 = event.getPoint();
repaint();
}
//----------------------------------------------------
// Provide empty definitions for unused event methods
//----------------------------------------------------
public void mouseMoved (MouseEvent event) {}
}
} //end RubberLines class | [
"tom@tkgray.com"
] | tom@tkgray.com |
29d09f0ebfede7867f7084df7324092c6fb8ff1e | 543f3ef3d8d4fc5294ab2e1da2785480333e887a | /src/main/java/net/thumbtack/school/tasks1_10/introduction/FirstSteps.java | b4c131682b361b80f6124ae806beaa3f6970f4be | [] | no_license | gulliver159/java_practice | afb822763971261527a8073765e0a23ad1ee5efa | 317696c4a3932afbed12c3aaa9fed24c109a6ed1 | refs/heads/main | 2023-03-01T02:24:05.815029 | 2021-02-11T17:15:00 | 2021-02-11T17:15:00 | 338,093,242 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,537 | java | package net.thumbtack.school.tasks1_10.introduction;
public class FirstSteps {
public int sum(int x, int y) {
return x + y;
}
public int mul(int x, int y) {
return x * y;
}
public int div(int x, int y) {
return (int) x / y;
}
public int mod(int x, int y) {
return x % y;
}
public boolean isEqual(int x, int y) {
return x == y;
}
public boolean isGreater(int x, int y) {
return x > y;
}
public boolean isInsideRect(int xLeft, int yTop, int xRight, int yBottom, int x, int y) {
return xLeft <= x && x <= xRight && yTop <= y && y <= yBottom;
}
public int sum(int[] array) {
int N = 0;
for (int value : array) {
N += value;
}
return N;
}
public int mul(int[] array) {
if (array.length == 0) {
return 0;
}
int N = 1;
for (int value : array) {
N *= value;
}
return N;
}
public int min(int[] array) {
int min = Integer.MAX_VALUE;
for (int value : array) {
if (value < min) {
min = value;
}
}
return min;
}
public int max(int[] array) {
int max = Integer.MIN_VALUE;
for (int value : array) {
if (value > max) {
max = value;
}
}
return max;
}
public double average(int[] array) {
if (array.length == 0) {
return 0;
}
return (float) sum(array) / array.length;
}
public boolean isSortedDescendant(int[] array) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i] <= array[i + 1]) {
return false;
}
}
return true;
}
public void cube(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] *= array[i] * array[i];
}
}
public boolean find(int[] array, int value) {
for (int item : array) {
if (item == value) {
return true;
}
}
return false;
}
public void reverse(int[] array) {
for (int i = 0; i < (int) array.length / 2; i++) {
int tmp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = tmp;
}
}
public boolean isPalindrome(int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] != array[array.length - i - 1]) {
return false;
}
}
return true;
}
public int sum(int[][] matrix) {
int N = 0;
for (int[] ints : matrix) {
N += sum(ints);
}
return N;
}
public int max(int[][] matrix) {
int max = Integer.MIN_VALUE;
for (int[] ints : matrix) {
if (max(ints) > max) {
max = max(ints);
}
}
return max;
}
public int diagonalMax(int[][] matrix) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < matrix[0].length; i++) {
if (matrix[i][i] > max) {
max = matrix[i][i];
}
}
return max;
}
public boolean isSortedDescendant(int[][] matrix) {
for (int[] ints : matrix) {
if (!isSortedDescendant(ints)) {
return false;
}
}
return true;
}
}
| [
"gulliver159@yandex.ru"
] | gulliver159@yandex.ru |
9dd47ed710df3aa95e88b185c2e8f987d4f4a5e1 | 010256e469a9630dcb9d0556ea4ebcf82e453fa7 | /src/main/java/com/emppayroll/EmployeePayrollFileIOService.java | 907bb687d92a99eac51cba17e5afeb395fbd9156 | [] | no_license | anirudha99/EmployeePayroll-JavaIO | b3cce778d1b7fc3708d41b0c9893e381926299d9 | 4bf0dd241d9da04ecb5824ee7d8d83e0fe8cdca9 | refs/heads/main | 2023-08-11T15:37:59.675513 | 2021-09-26T17:13:50 | 2021-09-26T17:13:50 | 410,600,721 | 0 | 0 | null | 2021-09-26T17:07:47 | 2021-09-26T16:16:34 | Java | UTF-8 | Java | false | false | 1,325 | java | package com.emppayroll;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class EmployeePayrollFileIOService {
public static final String PAYROLL_FILE_NAME = "/Users/anirudhasm/Desktop/eclipse-yml_training_workspace/EmployeePayrollJavaIO/src/main/java/com/emppayroll/data.txt";
/**
* method to Write Employee Payroll to a File
*/
public void writeData(List<EmployeePayrollData> employeePayrollList) {
StringBuffer empBuffer = new StringBuffer();
employeePayrollList.forEach(employee -> {
String employeeDataString = employee.toString().concat("\n");
empBuffer.append(employeeDataString);
});
try {
Files.write(Paths.get(PAYROLL_FILE_NAME), empBuffer.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* Employee Payroll to get count
*/
public long countEntries() {
long entries = 0;
try {
entries = Files.lines(new File(PAYROLL_FILE_NAME).toPath()).count();
} catch (IOException e) {
e.printStackTrace();
}
return entries;
}
/*
* to print payroll entries from file
*/
public void printData() {
try {
Files.lines(new File(PAYROLL_FILE_NAME).toPath()).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"anirudha.mayya@gmail.com"
] | anirudha.mayya@gmail.com |
15e99a79a0a45a10bbf58d565bf71d13706ca397 | 14e26bfd08b41c50ac37174bbc8f73887c3fa4da | /BinarySearchTree/src/BinarySearchTree.java | 6a50b1522e0630cb8219aa54ccba7a45b78075ee | [] | no_license | promise-125/Learn_Java | b897896692d066e29a0d986b7fef1463725e6e5d | 4edd24322fe31905bf6e59a2ed28ba05c084192a | refs/heads/master | 2023-01-03T00:16:25.725478 | 2020-03-15T12:19:38 | 2020-03-15T12:19:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,056 | java | public class BinarySearchTree {
public static class Node {
public int key;
public int value;
public Node left;
public Node right;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
public Node root = null;
//1.增加元素
public boolean add(int key, int value) {
Node node = new Node(key, value);
if (root == null) {
//如果root等于null直接返回
root = node;
return true;
}
//parent 为保存 cur 的父亲节点
Node parent = null;
//cur 是要取寻找合适位置的节点
Node cur = root;
while (cur != null) {
//parent 和 cur 要同时更新
parent = cur;
//如果要添加的元素的 key 大于 cur 节点的 key 就去右边找,
//小于去左边找,
//等于就修改value的值并返回,map中的 key 相同会覆盖之前的value
if (key > cur.key) {
cur = cur.right;
} else if (key < cur.key) {
cur = cur.left;
} else {
cur.value = value;
return true;
}
}
//循环结束时,cur 一定是 null
//parent 保存着 cur 的父亲节点
//如果是key 大于 parent 的 key 就在 parent 右边添加新的 node
//否则在左边添加, 不可能等于,等于就已经在上面的循环返回了
if (key > parent.key) {
parent.right = node;
} else {
parent.left = node;
}
return true;
}
//2.删除元素
public void Remove(int key) {
if (root == null) {
//如果是根节点是 null 就返回
return;
}
//parent 为保存 cur 的父亲节点
Node parent = null;
//cur 是要取寻找要删除的节点
Node cur = root;
//循环结束时有两种可能
//1。 cur 为 null 代表节点不存在
//2。 cur 的 key 和 目标 key 相等 说明找到了
while (cur != null) {
if (key > cur.key) {
parent = cur;
cur = cur.right;
} else if (key < cur.key) {
parent = cur;
cur = cur.left;
} else {
break;
}
}
//判断一下是不是因为没找到而结束的循环
//如果是就直接返回,代表删除失败
if (cur == null) {
return;
}
//1. cur.left == null
// 1) cur 是 root,则 root = cur.right
// 2) cur 不是 root,cur 是 parent.left,
// 则 parent.left = cur.right
// 3) cur 不是 root,cur 是 parent.right,
// 则 parent.right = cur.right
if (cur.left == null) {
if (cur == root) {
root = cur.right;
} else if (cur == parent.left) {
parent.left = cur.right;
} else if (cur == parent.right) {
parent.right = cur.right;
}
}
//2. cur.right == null
// 1) cur 是 root,则 root = cur.left
// 2) cur 不是 root,cur 是 parent.left,
// 则 parent.left = cur.left
// 3) cur 不是 root,cur 是 parent.right,
// 则 parent.right = cur.left
if (cur.right == null) {
if (cur == root) {
root = cur.left;
} else if (cur == parent.left) {
parent.left = cur.left;
} else if (cur == parent.right) {
parent.right = cur.left;
}
}
//3. cur.left != null && cur.right != null
// 需要使用替换法进行删除,即在它的右子树中寻找中序下的第一个结点(关键码最小),
// 用它的值填补到被删除节点中,再来处理该结点的删除问题
if (cur.left != null && cur.right != null) {
//prev 是用来保存 node 的父亲节点
Node prev = cur;
//node 是用来寻找 prev 的右子树中,最左的节点
Node node = prev.right;
//循环结束,node 一定是 prev 的右子树中最左的节点
while (node.left != null) {
prev = node;
node = node.left;
}
//如果 node 的 key 大于 parent 的 key,说明 node 在 parent 的右边
//所以要把右边的节点替换掉置为null
//如果 node 的 key 小于 parent 的 key,说明 node 在 parent 的左边
//所以要把左边的节点替换掉置为null
if (node.key > prev.key) {
prev.right = null;
} else if (node.key < prev.key) {
prev.left = null;
}
//然或将cur 的 key 替换成 node 的 key
//然或将cur 的 value 替换成 node 的 value
cur.key = node.key;
cur.value = node.value;
}
}
//3.查找元素
public Integer searchKey(int key) {
if (root == null) {
return null;
}
Node node = root;
while (node != null) {
if (key > node.key) {
node = node.right;
} else if (key < node.key) {
node = node.left;
} else {
return node.value;
}
}
return null;
}
public void prevOrder(Node root) {
if (root == null) {
return;
}
System.out.print(root.key + " ");
prevOrder(root.left);
prevOrder(root.right);
}
public void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.key + " ");
inOrder(root.right);
}
}
| [
"929125066@qq.com"
] | 929125066@qq.com |
8934488b16e8513fadcf31e5397b3eda1a674ba0 | 3fe67240a476dd61fe8191a4482ec09628be8327 | /hello.spring/src/main/java/hello/hello/spring/repository/JpaMemberRepository.java | 26fda70ddbaaa8bde5f0d252121c283d61071318 | [] | no_license | heojumi/Spring_Study | df32a718848dbb4f5fe85fe6984ef6c922163e40 | 9888f11fce49a475f67fb6043f7235860cea9811 | refs/heads/main | 2023-06-24T17:31:23.883520 | 2021-07-20T14:36:35 | 2021-07-20T14:36:35 | 383,699,313 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,088 | java | package hello.hello.spring.repository;
import hello.hello.spring.domain.Member;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;
public class JpaMemberRepository implements MemberRepository{
private final EntityManager em;
public JpaMemberRepository(EntityManager em){
this.em=em;
}
@Override
public Member save(Member member) {
em.persist(member);
return member;
}
@Override
public Optional<Member> findById(Long id) {
Member member=em.find(Member.class,id);
return Optional.ofNullable(member);
}
@Override
public Optional<Member> findByName(String name) {
List<Member> result = em.createQuery("select m from Member m where m.name = :name",Member.class)
.setParameter("name",name)
.getResultList();
return result.stream().findAny();
}
@Override
public List<Member> findAll() {
return em.createQuery("select m from Member m", Member.class)
.getResultList();
}
}
| [
"70880034+heojumi@users.noreply.github.com"
] | 70880034+heojumi@users.noreply.github.com |
9cbbd10f9d80fd0845880c2fe0ebbe3f77a4cb29 | 93870339314fb000128d112eac3456c9603e014c | /PracticePage_002.java | 2ebdc11c6ec2252923e7c06fe6beb5cd0604d3d9 | [] | no_license | Shridhar-Automation/Data | 2282bcb1a4644d84db16af35d89ca79670c69a88 | 8a5782bd2270ce34f1c80b84a6a186da62793867 | refs/heads/master | 2023-01-01T09:59:32.519990 | 2020-10-14T07:09:31 | 2020-10-14T07:09:31 | 303,921,230 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,022 | java | package practicePageModule;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class PracticePage_002
{
public WebDriver driver;
@BeforeClass
public void LaunchingBrowser()
{
System.setProperty("webdriver.chrome.driver","drivers//chromedriver.exe");
driver = new ChromeDriver();
driver.get(" https://rahulshettyacademy.com/AutomationPractice/");
driver.manage().window().maximize();
String expectedValue = "Practice Page";
String ActualValue = driver.getTitle();
Assert.assertEquals(expectedValue, ActualValue);
}
@Test(groups={"smoke"})
public void test_003()
{
System.out.println("Smoke2");
Select s = new Select(driver.findElement(By.id("dropdown-class-example")));
s.selectByValue("option3");
}
@Test
public void test_004()
{
Assert.assertFalse( driver.findElement(By.cssSelector("#checkBoxOption1")).isSelected());
driver.findElement(By.cssSelector("#checkBoxOption1")).click();
Assert.assertTrue( driver.findElement(By.cssSelector("#checkBoxOption1")).isSelected());
}
@Test
public void test_005()
{
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
driver.findElement(By.cssSelector("button[onclick='openWindow()']")).click();
String parentWindow = driver.getWindowHandle();
String parent = driver.getTitle();
Set<String> wh = driver.getWindowHandles();
Iterator<String> it = wh.iterator();
while(it.hasNext())
{
driver.switchTo().window((String) it.next());
}
Assert.assertNotEquals(driver.getTitle(), parent);
driver.close();
driver.switchTo().window(parentWindow);
Assert.assertEquals(parent, driver.getTitle());
}
}
| [
"noreply@github.com"
] | Shridhar-Automation.noreply@github.com |
15b1a2e9a0c217eb085d1258d37e2f699e2ea359 | 86b9e9239fd6aeea69076de0f9d2d985557a6239 | /src/behavioral/observer/current/Client.java | de48213e03e0c504b520e8e1d010a0c6936c70ff | [] | no_license | h-mora10/java-design-patterns | 4a1e52cbe4ad2ad27758808c282ecf09c093a102 | d0a901d195e2349ec899005e6c21aab079c8a5bb | refs/heads/main | 2023-02-15T15:55:32.620933 | 2021-01-05T22:26:40 | 2021-01-05T22:26:40 | 301,565,689 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 418 | java | package behavioral.observer.current;
public class Client {
// When the button state changes (is clicked), the list and the text should be updated as well
public static void main(String[] args) {
Button button = new Button();
InputText text = new InputText();
List list = new List();
button.setInputText(text);
button.setList(list);
button.clicked();
}
}
| [
"h.mora10@uniandes.edu.co"
] | h.mora10@uniandes.edu.co |
ec435e3bfd73ab01434c7fc4ce22dcc71ba7bb15 | 213242f04b60202e9bb86bbeb4d16bff62332290 | /bytemall-member/src/main/java/com/iat/bytemall/member/service/impl/MemberLoginLogServiceImpl.java | 84a527f959276d6595611195b918508c7054715b | [] | no_license | coffeerr/bytemall | 5a93740e39a0bad57fc3b6291fbbd05e75dabea7 | c6b1af3d3057feccacf082359e19c1a47fe35f7e | refs/heads/main | 2023-03-19T00:17:39.896627 | 2021-03-15T08:42:35 | 2021-03-15T08:42:35 | 347,240,649 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,037 | java | package com.iat.bytemall.member.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iat.common.utils.PageUtils;
import com.iat.common.utils.Query;
import com.iat.bytemall.member.dao.MemberLoginLogDao;
import com.iat.bytemall.member.entity.MemberLoginLogEntity;
import com.iat.bytemall.member.service.MemberLoginLogService;
@Service("memberLoginLogService")
public class MemberLoginLogServiceImpl extends ServiceImpl<MemberLoginLogDao, MemberLoginLogEntity> implements MemberLoginLogService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<MemberLoginLogEntity> page = this.page(
new Query<MemberLoginLogEntity>().getPage(params),
new QueryWrapper<MemberLoginLogEntity>()
);
return new PageUtils(page);
}
} | [
"chriso1998@qq.com"
] | chriso1998@qq.com |
bcd6e7b58078762961f35ce2c081a54b1f9e08c4 | 901a345fbdb2b94de1f5dbdc2471930860be059d | /src/main/java/com/oplao/Controller/SlashController.java | 64046182220e7313b22fec90b862ea99dc76e8d7 | [] | no_license | AlexUlianets/cbk_version | e0d71d06b09a200ee7889d5d930ba1a2960ccd94 | 3f29a7b2cd119e8fe2404c5578085fb9b134a2f0 | refs/heads/master | 2021-01-20T21:12:07.909720 | 2017-12-23T19:19:01 | 2017-12-23T19:19:01 | 101,755,605 | 1 | 0 | null | 2017-12-23T19:19:02 | 2017-08-29T11:51:46 | CSS | UTF-8 | Java | false | false | 4,972 | java | package com.oplao.Controller;
import com.oplao.Utils.LanguageUtil;
import com.oplao.service.LanguageService;
import com.oplao.service.SearchService;
import com.oplao.service.WeatherService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import static com.oplao.service.SearchService.validCountryCodes;
@Controller
public class SlashController {
@Autowired
SearchService searchService;
@Autowired
LanguageService languageService;
@Autowired
WeatherService weatherService;
@RequestMapping("/")
public ModelAndView slash(HttpServletRequest request, HttpServletResponse response,
@CookieValue(value = SearchService.cookieName, defaultValue = "") String currentCookieValue,
@CookieValue(value = "langCookieCode", defaultValue = "") String languageCookieCode,
@CookieValue(value = "temp_val", defaultValue = "C") String typeTemp){
JSONObject currentCity = searchService.findSelectedCity(request, response, currentCookieValue); //is done to generate location before the page is loaded
if(languageCookieCode.equals("")) {
String cc = "";
try {
cc = currentCity.getString("country_code");
} catch (JSONException e) {
cc = currentCity.getString("countryCode");
}
if (Arrays.asList(validCountryCodes).contains(cc.toLowerCase())) {
languageCookieCode = cc.toLowerCase();
}else{
languageCookieCode = "en";
}
}
Locale locale = new Locale(languageCookieCode, LanguageUtil.getCountryCode(languageCookieCode));
ResourceBundle resourceBundle = ResourceBundle.getBundle("messages_" + languageCookieCode, locale);
HashMap content = languageService.generateFrontPageContent(resourceBundle, currentCity.getString("name"), currentCity.getString("countryName"), languageCookieCode);
List threeDaysTabs = weatherService.getTableDataForDays(currentCity, 1,3,false,null, languageCookieCode);
List recentTabs = searchService.createRecentCitiesTabs(currentCookieValue, languageCookieCode);
List countryWeather = searchService.getCountryWeather(currentCity, languageCookieCode);
List holidayWeather = searchService.getHolidaysWeather(currentCity, languageCookieCode);
List holidayDestinations = searchService.getTopHolidaysDestinations(23, languageCookieCode);
ModelAndView modelAndView = new ModelAndView("front-page2");
modelAndView.addObject("content", content);
modelAndView.addObject("temperature", weatherService.getRemoteData(currentCity, languageCookieCode));
modelAndView.addObject("pageName", "frontPage");
modelAndView.addObject("typeTemp", typeTemp);
modelAndView.addObject("threeDaysTabs", threeDaysTabs);
modelAndView.addObject("recentTabs", recentTabs);
modelAndView.addObject("countryWeather", countryWeather);
modelAndView.addObject("holidayWeather", holidayWeather);
modelAndView.addObject("holidayDestinations", holidayDestinations);
modelAndView.addObject("currentCountryCode", languageCookieCode);
modelAndView.addObject("selectedCity", currentCity.getString("name").toUpperCase() + "_" + currentCity.getString("countryCode").toUpperCase());
return modelAndView;
}
@RequestMapping(value = "/generate_language_content", produces = "application/json")
@ResponseBody
public HashMap generateLanguageContent(@RequestParam(value = "langCode", required = false) String langCode, @RequestParam(value = "path") String path, HttpServletRequest request, HttpServletResponse response, @CookieValue(value = SearchService.cookieName, defaultValue = "") String currentCookieValue){
try {
currentCookieValue = URLDecoder.decode(currentCookieValue, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return languageService.generateLanguageContent(langCode, path, searchService.findSelectedCity(request, response, currentCookieValue));
}
@RequestMapping("/generate_lang_code")
@ResponseBody
public String generateLangCode(HttpServletRequest request, HttpServletResponse response, @CookieValue(value = SearchService.cookieName, defaultValue = "") String currentCookieValue){
return searchService.findSelectedCity(request, response, currentCookieValue).getString("countryCode").toLowerCase();
}
}
| [
"vladikabcdeg@gmail.com"
] | vladikabcdeg@gmail.com |
cbaa419bc3ff50187e0c431a1f3b73a4859d1280 | e4d8fffba80cd95de040eadf7a9cc5fa5f1fc96c | /src/java/myapplication/utils/email/EmailService.java | b9419359f7deea5586da4ef1d63b1ff01fb9d03c | [] | no_license | Aketza19/CRUD-Server | cdc97914c857391cff8747c11ce0e0ada44b1e47 | c0b4cae40672648debf863950147671be166bae3 | refs/heads/master | 2023-02-26T20:15:55.307187 | 2021-01-29T10:24:40 | 2021-01-29T10:24:40 | 316,501,534 | 0 | 0 | null | 2021-01-29T10:24:41 | 2020-11-27T12:56:04 | Java | UTF-8 | Java | false | false | 8,120 | java | package myapplication.utils.email;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import static org.passay.AllowedCharacterRule.ERROR_CODE;
import org.passay.CharacterData;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.PasswordGenerator;
/**
* Builds an Email Service capable of sending normal email to a given SMTP Host.
* Currently <b>send()</b> can only works with text.
*/
public class EmailService {
private static final ResourceBundle rb = ResourceBundle.getBundle("config.config");
// Server mail user & pass account
private String user = null;
private String pass = null;
// DNS Host + SMTP Port
private String smtp_host = null;
private int smtp_port = 0;
@SuppressWarnings("unused")
private EmailService() {
}
/**
* Builds the EmailService.
*
* @param user User account login
* @param pass User account password
* @param host The Server DNS
* @param port The Port
*/
public EmailService(String user, String pass, String host, int port) {
this.user = user;
this.pass = pass;
this.smtp_host = host;
this.smtp_port = port;
}
/**
* Sends the given <b>text</b> from the <b>sender</b> to the
* <b>receiver</b>. In any case, both the <b>sender</b> and <b>receiver</b>
* must exist and be valid mail addresses. The sender, mail's FROM part, is
* taken from this.user by default<br>
* <br>
*
* Note the <b>user</b> and <b>pass</b> for the authentication is provided
* in the class constructor. Ideally, the <b>sender</b> and the <b>user</b>
* coincide.
*
* @param receiver The mail's TO part
* @param subject The mail's SUBJECT
* @param text The proper MESSAGE
* @throws MessagingException Is something awry happens
*
*/
public void sendMail(String receiver, String subject, String text) throws MessagingException {
// Mail properties
Properties properties = new Properties();
properties.put("mail.smtp.auth", true);
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", smtp_host);
properties.put("mail.smtp.port", smtp_port);
properties.put("mail.smtp.ssl.enable", "false");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.trust", smtp_host);
properties.put("mail.imap.partialfetch", false);
// Authenticator knows how to obtain authentication for a network connection.
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
// MIME message to be sent
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); // Ej: receptor@gmail.com
message.setSubject(subject); // Asunto del mensaje
// A mail can have several parts
Multipart multipart = new MimeMultipart();
// A message part (the message, but can be also a File, etc...)
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(text, "text/html");
multipart.addBodyPart(mimeBodyPart);
// Adding up the parts to the MIME message
message.setContent(multipart);
// And here it goes...
Transport.send(message);
}
/**
* Method used to generate a random password. This method uses the
* passay-1.6.0.jar library, it can be downloaded from:
* https://www.passay.org/downloads/1.6.0/passay-1.6.0-dist.zip. If the link
* doesn't work, there is the official website: https://www.passay.org/.
*
* @return The password generated.
*/
public static String generatePassayPassword() {
// Create the PasswordGenerator object.
PasswordGenerator gen = new PasswordGenerator();
// Set the rule to the lowercase in the password.
CharacterData lowerCaseChars = EnglishCharacterData.LowerCase;
CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars);
lowerCaseRule.setNumberOfCharacters(2);
// Set the rule to the uppercase in the password.
CharacterData upperCaseChars = EnglishCharacterData.UpperCase;
CharacterRule upperCaseRule = new CharacterRule(upperCaseChars);
upperCaseRule.setNumberOfCharacters(2);
// Set the rule to the digits in the password.
CharacterData digitChars = EnglishCharacterData.Digit;
CharacterRule digitRule = new CharacterRule(digitChars);
digitRule.setNumberOfCharacters(2);
// Set the rule to the special characters in the password.
CharacterData specialChars = new CharacterData() {
public String getErrorCode() {
return ERROR_CODE;
}
public String getCharacters() {
return "!@#$%^&*()_+";
}
};
CharacterRule splCharRule = new CharacterRule(specialChars);
splCharRule.setNumberOfCharacters(2);
// Generate the password with the rules. For length to be evaluated it
// must be greater than the number of characters defined in the character rule.
String password = gen.generatePassword(10, splCharRule, lowerCaseRule,
upperCaseRule, digitRule);
return password;
}
/**
* Method used to send a new password to the user.This method uses the
* generatePassayPassword() method to generate a secure and random password
* to the user.
*
* @param transmitterEmail The transmitter email.
* @param transmitterPassword The transmitter password.
* @param receiverEmail The receiver email.
* @return The generated password.
*/
public static String sendNewPassword(String transmitterEmail, String transmitterPassword, String receiverEmail) {
String newPassword = generatePassayPassword();
EmailService emailService = new EmailService(transmitterEmail,
transmitterPassword, rb.getString("EMAIL_HOST"), Integer.parseInt(rb.getString("EMAIL_PORT")));
try {
emailService.sendMail(receiverEmail, "New password",
newPassword);
System.out.println("Ok, mail sent!");
return newPassword;
} catch (MessagingException e) {
System.out.println("Doh! " + e.getMessage());
}
return null;
}
/**
* Method used to recover the user password. This method takes the user
* password from the database.
*
* @param transmitterEmail The transmitter email.
* @param transmitterPassword The transmitter password.
* @param receiverEmail The receiver email.
* @param userPassword The user's password, taken from the database.
*/
public static void recoverUserPassword(String transmitterEmail, String transmitterPassword, String receiverEmail, String userPassword) {
EmailService emailService = new EmailService(transmitterEmail,
transmitterPassword, rb.getString("EMAIL_HOST"), Integer.parseInt(rb.getString("EMAIL_PORT")));
try {
emailService.sendMail(receiverEmail, "Recover password",
userPassword);
System.out.println("Ok, mail sent!");
} catch (MessagingException e) {
System.out.println("Doh! " + e.getMessage());
}
}
}
| [
"theofficialdork@hotmail.com"
] | theofficialdork@hotmail.com |
c79df3382a5bdb4f13b876bb358c35728c3ddf3f | 0c334a39a6cc84b906dd1fd563aff1bd3e86c1db | /app/src/androidTest/java/com/ketchuphub/www/digife/ExampleInstrumentedTest.java | 68fed38f867f7abf9d1291f10e05eef427aca069 | [] | no_license | suyashshukla/Tefo | 7e83badba6bd5a876a66b60149f69db81c8310cd | db9bbcab34cda95566eac5ccb155707beb821621 | refs/heads/master | 2020-04-15T02:22:38.013854 | 2019-01-07T11:56:43 | 2019-01-07T11:58:02 | 164,312,418 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 734 | java | package com.ketchuphub.www.digife;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.ketchuphub.www.digife", appContext.getPackageName());
}
}
| [
"suyashshukla1997@gmail.com"
] | suyashshukla1997@gmail.com |
78825e52444773b915a28a54a3bf9bce7c9514f0 | 2addee486f0ab9fda9827b422c76e44f78c9cfe1 | /src/A1Q5.java | 7987fda12d57357eb3d5bbbc2ff5d9cd6b6db5ed | [] | no_license | laurelizall/Assignment01-1 | 890119b341faa9c98699f1262f7c0b2ff2fee7af | 0b6f31ecfd1b3e0a0312d5fc4918886e92248f6f | refs/heads/master | 2020-12-11T09:09:46.456850 | 2016-10-03T16:24:29 | 2016-10-03T16:24:29 | 67,532,712 | 0 | 0 | null | 2016-09-06T17:49:25 | 2016-09-06T17:49:24 | null | UTF-8 | Java | false | false | 957 | java |
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author halll7908
*/
public class A1Q5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Scanner
Scanner input = new Scanner(System.in);
System.out.println("Request a number between 1 and 10.");
int starCount = input.nextInt();
// value that counts lines
int output = 0;
while (output != starCount) {
// outputting on same line
for (int i = 0; i < starCount; i++) {
System.out.print("*");
}
// go down one line
System.out.println("");
// add 1 to output value
output = output + 1;
}
}
}
| [
"halll7908@HRH-IC0027341.wrdsb.ca"
] | halll7908@HRH-IC0027341.wrdsb.ca |
7250a155a8725434dec2d37db1fb24cb93f04dda | 638dd731c48399536a83f43dafefb20069f0ffd6 | /PsychAssist/src/com/pyschassist/utils/AccessUtils.java | 4bc1de8bab30d6af42dc6f17288296a07779610c | [] | no_license | triggerwes/pychassist | 6d5bc00f821a2131a928e602e4b3a2a1d5ed57aa | 1e20e6ca60646b94bf00fbbc7f8191fd0521cdd2 | refs/heads/master | 2020-06-08T15:26:27.281239 | 2014-05-29T02:00:41 | 2014-05-29T02:00:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,109 | java | package com.pyschassist.utils;
import android.content.Context;
import android.content.SharedPreferences;
import com.example.psychassist.R;
public class AccessUtils {
private static String TAG = "AccessUtils";
public static String getVaultId(Context myContext) {
SharedPreferences prefs = myContext.getSharedPreferences(myContext.getString(R.string.preference_key), Context.MODE_PRIVATE);
String vaultId = prefs.getString(myContext.getString(R.string.var_vault_id), "-1");
return vaultId;
}
public static String getUserId(Context myContext) {
SharedPreferences prefs = myContext.getSharedPreferences(myContext.getString(R.string.preference_key), Context.MODE_PRIVATE);
String userId = prefs.getString(myContext.getString(R.string.var_user_id), "-1");
return userId;
}
public static String getDocId(Context myContext) {
SharedPreferences prefs = myContext.getSharedPreferences(myContext.getString(R.string.preference_key), Context.MODE_PRIVATE);
String docId = prefs.getString(myContext.getString(R.string.var_doc_id), "-1");
return docId;
}
}
| [
"bestndawes@yahoo.com"
] | bestndawes@yahoo.com |
a759352540e0da378713db19556ab1cd00aec116 | 0278ce2bbe6c8ade595744a9dddfb4ec1ad8f646 | /src/main/java/ru/specialist/java/spring/xml/Device.java | 647f8c44d77121f930b1929c9cad3ee490b8d380 | [] | no_license | CharArt/spring-november | c842af727014d66b8d9eee1089383055f66c2883 | 3ef6b6c90c400b7e13490e7f5f2406558fc842dd | refs/heads/main | 2023-01-13T03:37:12.661782 | 2020-11-20T17:08:13 | 2020-11-20T17:08:13 | 314,618,825 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 94 | java | package ru.specialist.java.spring.xml;
public interface Device {
String getVendor();
}
| [
"charartpav@gmail.com"
] | charartpav@gmail.com |
815097fc988b2627060b8d925e247a68fa0f2719 | d7ac91b8fb92df6d641e2d7bd7090ec7f94c0415 | /qsp1/src/SystemCheck.java | 181f9fce0d9e74c8a10ff49ad6010548a5ef93c5 | [] | no_license | girish-professional/girishTestYantra | e48de73b32fad368405ea7245730f4a4ff3a74dc | c4bd0767e6892101397edaa7af98ebfa5316be0d | refs/heads/master | 2020-04-21T11:28:13.840584 | 2019-02-07T07:56:48 | 2019-02-07T07:56:48 | 169,526,594 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 121 | java |
public class SystemCheck {
public static void main(String[] args) {
System.out.println("asdjkflksdjf");
}
}
| [
"giri26march@gmail.com"
] | giri26march@gmail.com |
73d9dc026e3bc5624cd1625893e9e4f1dd0115c8 | bac27c4ca737557a164ba8c33d5b01a7ab23e5d1 | /lesson-2/src/ua/lviv/lgs/Main.java | daa8339d7bdf2139586107a977d8cb3c6cc3d82c | [] | no_license | Julia-Shmiljak/Java_Core_-lesson_3- | cc08c6cb21cd26ad844c9e0b0f0f516669bcb59a | 06e52b7d2d60b2d5c70cfd0cc2fb7b53bec223ba | refs/heads/master | 2023-03-21T19:19:51.636661 | 2021-03-10T17:49:23 | 2021-03-10T17:49:23 | 346,440,068 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 526 | java | package ua.lviv.lgs;
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(10, 8);
System.out.println(r1);
System.out.println(r2);
r1.setLenght(20);
r1.setWidth(120);
System.out.println(r1);
Circle circle1 = new Circle ();
Circle circle2 = new Circle (5.5, 11);
System.out.println(circle1);
System.out.println(circle2);
circle2.setRadius(15.75);
circle2.setDiameter(31.5);
System.out.println(circle2);
}
}
| [
"shmiliak112@gmail.com"
] | shmiliak112@gmail.com |
fc96b9ea7d599bda997d4458230489ba3a4d9f32 | 32f38cd53372ba374c6dab6cc27af78f0a1b0190 | /app/src/main/java/com/alipay/android/phone/mobilecommon/multimediabiz/biz/audio/silk/SilkUtils.java | 64019b2968015beb45ab1c7c2b0f524a817813d7 | [] | no_license | shuixi2013/AmapCode | 9ea7aefb42e0413f348f238f0721c93245f4eac6 | 1a3a8d4dddfcc5439df8df570000cca12b15186a | refs/heads/master | 2023-06-06T23:08:57.391040 | 2019-08-29T04:36:02 | 2019-08-29T04:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,106 | java | package com.alipay.android.phone.mobilecommon.multimediabiz.biz.audio.silk;
import android.text.TextUtils;
import com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger;
import com.alipay.multimedia.img.utils.ImageFileType;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class SilkUtils {
public static short[] getShortArray(byte[] bytes, int size) {
if (bytes == null) {
return null;
}
short[] shorts = new short[(size / 2)];
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
byteBuffer.put(bytes, 0, size);
byteBuffer.flip();
for (int i = 0; i < shorts.length; i++) {
shorts[i] = byteBuffer.getShort();
}
return shorts;
}
public static short getLittleEndianShort(byte[] bytes) {
return (short) (bytes[0] | (bytes[1] << 8));
}
public static byte[] convertToLittleEndian(short input) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort(input);
return buffer.array();
}
public static boolean convertToFormat(String src, File targetFile, String format) {
if (TextUtils.isEmpty(src) || targetFile == null || !"wav".equalsIgnoreCase(format)) {
return false;
}
return a(src, targetFile);
}
/* JADX WARNING: Removed duplicated region for block: B:37:0x019c */
/* JADX WARNING: Removed duplicated region for block: B:40:0x01bd */
/* JADX WARNING: Removed duplicated region for block: B:42:0x01d3 */
/* JADX WARNING: Removed duplicated region for block: B:47:0x01ee */
/* JADX WARNING: Removed duplicated region for block: B:50:0x020f */
/* JADX WARNING: Removed duplicated region for block: B:52:0x0228 */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static boolean a(java.lang.String r28, java.io.File r29) {
/*
r19 = r28
r12 = 0
r17 = 0
r23 = 2
r0 = r23
byte[] r15 = new byte[r0]
r23 = 4096(0x1000, float:5.74E-42)
r0 = r23
byte[] r11 = new byte[r0]
r23 = 960(0x3c0, float:1.345E-42)
r0 = r23
short[] r8 = new short[r0]
r21 = 0
java.io.FileInputStream r13 = new java.io.FileInputStream // Catch:{ Exception -> 0x0160 }
r0 = r19
r13.<init>(r0) // Catch:{ Exception -> 0x0160 }
java.lang.String r23 = "#!SILK_V3"
byte[] r6 = r23.getBytes() // Catch:{ Exception -> 0x0240, all -> 0x022b }
r23 = 0
int r0 = r6.length // Catch:{ Exception -> 0x0240, all -> 0x022b }
r24 = r0
r0 = r23
r1 = r24
int r20 = r13.read(r11, r0, r1) // Catch:{ Exception -> 0x0240, all -> 0x022b }
r0 = r20
byte[] r23 = java.util.Arrays.copyOf(r11, r0) // Catch:{ Exception -> 0x0240, all -> 0x022b }
r0 = r23
boolean r23 = java.util.Arrays.equals(r0, r6) // Catch:{ Exception -> 0x0240, all -> 0x022b }
if (r23 != 0) goto L_0x005f
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r13) // Catch:{ Exception -> 0x0240, all -> 0x022b }
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r13)
r23 = 0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r23)
java.lang.String r23 = "SilkUtils"
java.lang.String r24 = "convertToWav finally error? true"
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0]
r25 = r0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r23, r24, r25)
r23 = 0
r12 = r13
L_0x005e:
return r23
L_0x005f:
java.io.RandomAccessFile r18 = new java.io.RandomAccessFile // Catch:{ Exception -> 0x0240, all -> 0x022b }
java.lang.String r23 = "rw"
r0 = r18
r1 = r29
r2 = r23
r0.<init>(r1, r2) // Catch:{ Exception -> 0x0240, all -> 0x022b }
r24 = 44
r0 = r18
r1 = r24
r0.seek(r1) // Catch:{ Exception -> 0x0244, all -> 0x0230 }
r7 = 0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.audio.silk.SilkApi r22 = new com.alipay.android.phone.mobilecommon.multimediabiz.biz.audio.silk.SilkApi // Catch:{ Exception -> 0x0244, all -> 0x0230 }
r22.<init>() // Catch:{ Exception -> 0x0244, all -> 0x0230 }
r23 = 16000(0x3e80, float:2.2421E-41)
int r16 = r22.openDecoder(r23) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
java.lang.String r23 = "SilkUtils"
java.lang.StringBuilder r24 = new java.lang.StringBuilder // Catch:{ Exception -> 0x024a, all -> 0x0237 }
java.lang.String r25 = "convertToWav openRet: "
r24.<init>(r25) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r0 = r24
r1 = r16
java.lang.StringBuilder r24 = r0.append(r1) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
java.lang.String r24 = r24.toString() // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0] // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r25 = r0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r23, r24, r25) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
L_0x00a1:
r23 = 0
r24 = 2
r0 = r23
r1 = r24
int r23 = r13.read(r15, r0, r1) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r24 = -1
r0 = r23
r1 = r24
if (r0 == r1) goto L_0x011d
short r14 = getLittleEndianShort(r15) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
if (r14 < 0) goto L_0x011d
r23 = 0
r0 = r23
int r20 = r13.read(r11, r0, r14) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r0 = r20
if (r0 == r14) goto L_0x0101
java.lang.String r23 = "SilkUtils"
java.lang.StringBuilder r24 = new java.lang.StringBuilder // Catch:{ Exception -> 0x024a, all -> 0x0237 }
java.lang.String r25 = "path: "
r24.<init>(r25) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r0 = r24
r1 = r19
java.lang.StringBuilder r24 = r0.append(r1) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
java.lang.String r25 = ", read: "
java.lang.StringBuilder r24 = r24.append(r25) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r0 = r24
r1 = r20
java.lang.StringBuilder r24 = r0.append(r1) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
java.lang.String r25 = ", len: "
java.lang.StringBuilder r24 = r24.append(r25) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r0 = r24
java.lang.StringBuilder r24 = r0.append(r14) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
java.lang.String r24 = r24.toString() // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0] // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r25 = r0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r23, r24, r25) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
L_0x0101:
r23 = -1
r0 = r20
r1 = r23
if (r0 == r1) goto L_0x011d
r0 = r22
r1 = r20
int r9 = r0.decode(r11, r8, r1) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
if (r9 <= 0) goto L_0x00a1
r0 = r18
a(r0, r8, r9) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
int r23 = r9 * 2
int r7 = r7 + r23
goto L_0x00a1
L_0x011d:
long r0 = (long) r7 // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r24 = r0
int r23 = r7 + 36
r0 = r23
long r0 = (long) r0 // Catch:{ Exception -> 0x024a, all -> 0x0237 }
r26 = r0
r0 = r18
r1 = r24
r3 = r26
a(r0, r1, r3) // Catch:{ Exception -> 0x024a, all -> 0x0237 }
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r13)
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r18)
java.lang.String r23 = "SilkUtils"
java.lang.String r24 = "convertToWav finally error? false"
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0]
r25 = r0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r23, r24, r25)
r22.closeDecoder()
java.lang.String r23 = "SilkUtils"
java.lang.String r24 = "convertToWav silkApi closeDecoder"
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0]
r25 = r0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r23, r24, r25)
r23 = 1
r21 = r22
r17 = r18
r12 = r13
goto L_0x005e
L_0x0160:
r10 = move-exception
L_0x0161:
java.lang.String r23 = "SilkUtils"
java.lang.StringBuilder r24 = new java.lang.StringBuilder // Catch:{ all -> 0x01d6 }
java.lang.String r25 = "convertToWav error, path: "
r24.<init>(r25) // Catch:{ all -> 0x01d6 }
r0 = r24
r1 = r19
java.lang.StringBuilder r24 = r0.append(r1) // Catch:{ all -> 0x01d6 }
java.lang.String r24 = r24.toString() // Catch:{ all -> 0x01d6 }
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0] // Catch:{ all -> 0x01d6 }
r25 = r0
r0 = r23
r1 = r24
r2 = r25
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.E(r0, r10, r1, r2) // Catch:{ all -> 0x01d6 }
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r12)
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r17)
java.lang.String r24 = "SilkUtils"
java.lang.StringBuilder r25 = new java.lang.StringBuilder
java.lang.String r23 = "convertToWav finally error? "
r0 = r25
r1 = r23
r0.<init>(r1)
if (r21 != 0) goto L_0x01d3
r23 = 1
L_0x019e:
r0 = r25
r1 = r23
java.lang.StringBuilder r23 = r0.append(r1)
java.lang.String r23 = r23.toString()
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0]
r25 = r0
r0 = r24
r1 = r23
r2 = r25
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r0, r1, r2)
if (r21 == 0) goto L_0x01cf
r21.closeDecoder()
java.lang.String r23 = "SilkUtils"
java.lang.String r24 = "convertToWav silkApi closeDecoder"
r25 = 0
r0 = r25
java.lang.Object[] r0 = new java.lang.Object[r0]
r25 = r0
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r23, r24, r25)
L_0x01cf:
r23 = 0
goto L_0x005e
L_0x01d3:
r23 = 0
goto L_0x019e
L_0x01d6:
r23 = move-exception
r24 = r23
L_0x01d9:
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r12)
com.alipay.android.phone.mobilecommon.multimediabiz.biz.client.io.IOUtils.closeQuietly(r17)
java.lang.String r25 = "SilkUtils"
java.lang.StringBuilder r26 = new java.lang.StringBuilder
java.lang.String r23 = "convertToWav finally error? "
r0 = r26
r1 = r23
r0.<init>(r1)
if (r21 != 0) goto L_0x0228
r23 = 1
L_0x01f0:
r0 = r26
r1 = r23
java.lang.StringBuilder r23 = r0.append(r1)
java.lang.String r23 = r23.toString()
r26 = 0
r0 = r26
java.lang.Object[] r0 = new java.lang.Object[r0]
r26 = r0
r0 = r25
r1 = r23
r2 = r26
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r0, r1, r2)
if (r21 == 0) goto L_0x0227
r21.closeDecoder()
java.lang.String r23 = "SilkUtils"
java.lang.String r25 = "convertToWav silkApi closeDecoder"
r26 = 0
r0 = r26
java.lang.Object[] r0 = new java.lang.Object[r0]
r26 = r0
r0 = r23
r1 = r25
r2 = r26
com.alipay.android.phone.mobilecommon.multimediabiz.biz.utils.Logger.D(r0, r1, r2)
L_0x0227:
throw r24
L_0x0228:
r23 = 0
goto L_0x01f0
L_0x022b:
r23 = move-exception
r24 = r23
r12 = r13
goto L_0x01d9
L_0x0230:
r23 = move-exception
r24 = r23
r17 = r18
r12 = r13
goto L_0x01d9
L_0x0237:
r23 = move-exception
r24 = r23
r21 = r22
r17 = r18
r12 = r13
goto L_0x01d9
L_0x0240:
r10 = move-exception
r12 = r13
goto L_0x0161
L_0x0244:
r10 = move-exception
r17 = r18
r12 = r13
goto L_0x0161
L_0x024a:
r10 = move-exception
r21 = r22
r17 = r18
r12 = r13
goto L_0x0161
*/
throw new UnsupportedOperationException("Method not decompiled: com.alipay.android.phone.mobilecommon.multimediabiz.biz.audio.silk.SilkUtils.a(java.lang.String, java.io.File):boolean");
}
private static void a(RandomAccessFile out, long totalAudioLen, long totalDataLen) {
Logger.D("SilkUtils", "fillWaveFileHeader out: " + out + ", totalAudioLen: " + totalAudioLen + ", totalDataLen: " + totalDataLen + ", sampleRate: 16000, channels: 1, encoding: 2, byteRate: 32000", new Object[0]);
out.seek(0);
out.write(new byte[]{ImageFileType.HEAD_WEBP_0, 73, 70, 70, (byte) ((int) (totalDataLen & 255)), (byte) ((int) ((totalDataLen >> 8) & 255)), (byte) ((int) ((totalDataLen >> 16) & 255)), (byte) ((int) ((totalDataLen >> 24) & 255)), 87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 1, 0, 1, 0, Byte.MIN_VALUE, 62, 0, 0, 0, 125, 0, 0, 4, 0, 16, 0, 100, 97, 116, 97, (byte) ((int) (totalAudioLen & 255)), (byte) ((int) ((totalAudioLen >> 8) & 255)), (byte) ((int) ((totalAudioLen >> 16) & 255)), (byte) ((int) ((totalAudioLen >> 24) & 255))}, 0, 44);
}
private static void a(RandomAccessFile out, short[] data, int length) {
for (int i = 0; i < length; i++) {
out.writeByte(data[i] & 255);
out.writeByte((data[i] >> 8) & 255);
}
}
}
| [
"hubert.yang@nf-3.com"
] | hubert.yang@nf-3.com |
7d90fd6dbfce07378acb1fac5e7b538a64228850 | afd98a7be4e8b96e60142e3a4985e71b925df4d5 | /app/src/main/java/com/umbrella/financialteaching/base/ApiService.java | df5ca6250854b83eb13e5965cf43aed622acc09a | [] | no_license | simon-cj/protective-umbrella | 921f2de8825ca770510f656a2ed5f7ec68b17122 | ffa1e866525d97d10794230daf5482a04787575f | refs/heads/master | 2020-03-28T08:50:31.811091 | 2018-09-09T15:18:36 | 2018-09-09T15:18:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 758 | java | package com.umbrella.financialteaching.base;
import com.umbrella.financialteaching.model.NewsDetail;
import com.umbrella.financialteaching.model.VideoModel;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Url;
/**
* Created by chenjun on 18/9/9.
*/
public interface ApiService {
String HOST = "";
String API_SERVER_URL = "";
String HOST_VIDEO = "";
String URL_VIDEO = "";
@GET
Observable<ResponseResult<NewsDetail>> getNewsDetail(@Url String url);
@GET
Observable<String> getVideoHtml(@Url String url);
@GET
Observable<ResponseResult<VideoModel>> getVideoData(@Url String url);
@GET
Observable<ResponseBody> getImage(@Url String url);
}
| [
"chenjun@meiqia.com"
] | chenjun@meiqia.com |
2666ca9988bd037250efdd3c6386961a6092909d | 43f74ea498cb0dae05bf2390b448d16f398a0a2b | /workspace/ncp_base/src/main/java/com/plgrim/ncp/base/repository/inf/InfOrdGodErpDstbRepository.java | 4ece22795f3e573b47ce737988e2e08a4b4d3508 | [] | no_license | young-hee/pc_mlb | 2bdf5813418c14be2d7e2de78f0f294ed8264dde | 708417eada78eed398e068460bda44adea16cbdf | refs/heads/master | 2022-11-22T00:11:05.335853 | 2020-07-22T08:27:03 | 2020-07-22T09:10:07 | 281,615,442 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,080 | java |
/* Copyright (c) 2015 plgrim, Inc.
* All right reserved.
* http://www.plgrim.com
* This software is the confidential and proprietary information of plgrim
* , Inc. You shall not disclose such Confidential Information and
* shall use it only in accordance with the terms of the license agreement
* you entered into with plgrim.
*
* Revision History
* Author Date Description
* ------------------ -------------- ------------------
* Generator(Generator) 2018-05-23
*/
package com.plgrim.ncp.base.repository.inf;
import java.sql.SQLException;
import org.springframework.stereotype.Repository;
import com.plgrim.ncp.base.abstracts.AbstractRepository;
import com.plgrim.ncp.base.entities.datasource1.inf.InfOrdGodErpDstb;
/**
* The Class InfOrdGodErpDstbRepository.
*/
@Repository
public class InfOrdGodErpDstbRepository extends AbstractRepository {
/*
* ---------------------------------------------------------------------
* Instance fields.
* ---------------------------------------------------------------------
*/
/*
* ---------------------------------------------------------------------
* Constructors.
* ---------------------------------------------------------------------
*/
/*
* ---------------------------------------------------------------------
* public & interface method.
* ---------------------------------------------------------------------
*/
/**
* 인터페이스 주문 상품 ERP 분배 상세 조회.
*
* @param infOrdGodErpDstb the InfOrdGodErpDstb
* @return the InfOrdGodErpDstb
* @throws SQLException the SQL exception
*/
public InfOrdGodErpDstb selectInfOrdGodErpDstb(InfOrdGodErpDstb infOrdGodErpDstb) {
return getSession1().selectOne("com.plgrim.ncp.base.selectInfOrdGodErpDstb", infOrdGodErpDstb);
}
/**
* 인터페이스 주문 상품 ERP 분배 등록.
*
* @param infOrdGodErpDstb the InfOrdGodErpDstb
* @throws SQLException the SQL exception
*/
public void insertInfOrdGodErpDstb(InfOrdGodErpDstb infOrdGodErpDstb) {
getSession1().insert("com.plgrim.ncp.base.insertInfOrdGodErpDstb", infOrdGodErpDstb);
}
/**
* 인터페이스 주문 상품 ERP 분배 수정.
*
* @param infOrdGodErpDstb the InfOrdGodErpDstb
* @throws SQLException the SQL exception
*/
public int updateInfOrdGodErpDstb(InfOrdGodErpDstb infOrdGodErpDstb) {
return getSession1().update("com.plgrim.ncp.base.updateInfOrdGodErpDstb", infOrdGodErpDstb);
}
/**
* 인터페이스 주문 상품 ERP 분배 삭제.
*
* @param infOrdGodErpDstb the InfOrdGodErpDstb
* @return the InfOrdGodErpDstb
* @throws SQLException the SQL exception
*/
public int deleteInfOrdGodErpDstb(InfOrdGodErpDstb infOrdGodErpDstb) {
return getSession1().delete("com.plgrim.ncp.base.deleteInfOrdGodErpDstb", infOrdGodErpDstb);
}
/*
* ---------------------------------------------------------------------
* private method.
* ---------------------------------------------------------------------
*/
}
| [
"aksla79@gmail.com"
] | aksla79@gmail.com |
2a24c56e19fd8282bff86053c706bc2a4f4fa8a8 | 1ca86d5d065372093c5f2eae3b1a146dc0ba4725 | /spring-cloud/spring-cloud-kubernetes/kubernetes-guide/client-service/src/main/java/com/surya/spring/cloud/kubernetes/client/RibbonConfiguration.java | 77b284075f05711b9583029fdc4b6cf92216037d | [] | no_license | Suryakanta97/DemoExample | 1e05d7f13a9bc30f581a69ce811fc4c6c97f2a6e | 5c6b831948e612bdc2d9d578a581df964ef89bfb | refs/heads/main | 2023-08-10T17:30:32.397265 | 2021-09-22T16:18:42 | 2021-09-22T16:18:42 | 391,087,435 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,116 | java | /*
* Copyright (C) 2016 to the original authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.surya.spring.cloud.kubernetes.client;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AvailabilityFilteringRule;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.PingUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
public class RibbonConfiguration {
@Autowired
IClientConfig ribbonClientConfig;
/**
* PingUrl will ping a URL to check the status of each server.
* Say Hello has, as you’ll recall, a method mapped to the /path; that means that Ribbon will get an HTTP 200 response when it pings a running Backend Server
*
* @param config Client configuration
* @return The URL to be used for the Ping
*/
@Bean
public IPing ribbonPing(IClientConfig config) {
return new PingUrl();
}
/**
* AvailabilityFilteringRule will use Ribbon’s built-in circuit breaker functionality to filter out any servers in an “open-circuit” state:
* if a ping fails to connect to a given server, or if it gets a read failure for the server, Ribbon will consider that server “dead” until it begins to respond normally.
*
* @param config Client configuration
* @return The Load Balancer rule
*/
@Bean
public IRule ribbonRule(IClientConfig config) {
return new AvailabilityFilteringRule();
}
}
| [
"suryakanta97@github.com"
] | suryakanta97@github.com |
1956aaa1252da5790ecc12cdf42de36ab492100c | 4208d725844e8c966d7a0977fc9135697535ef97 | /src/Animal.java | b73d5d4f862b41e60d52f08f02fc3bd5c423c89f | [] | no_license | IliqNikushev/ITECO-Zoo | c42827cbe75b90cbc74b19d2aeb3486badee00bc | ebf4cbd2b96223685e2549690474a2b3bea8be70 | refs/heads/master | 2021-01-17T15:19:27.297680 | 2014-02-15T13:17:27 | 2014-02-15T13:17:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,083 | java | import java.util.HashMap;
import java.util.Map;
public class Animal {
private String name;
private AnimalData data;
private int monthsOld;
public Animal(int id, String name, int monthsOld) throws KeyNotFoundException{
this(AnimalDatabase.get(id), name, monthsOld);
}
public Animal(AnimalData base, String name, int monthsOld){
this(name, base.getType(), base.getKind(), base.getSign(), base.getIsPredator(), monthsOld);
}
public Animal(String name, AnimalType type, AnimalKind kind, AnimalMorphologicalSign area,
boolean isPredator, int monthsOld){
this.name = name;
this.data = new AnimalData(type, kind, area, isPredator);
this.monthsOld = monthsOld;
}
public String getName(){
return this.name;
}
public AnimalType getType(){
return this.data.getType();
}
public AnimalKind getKind(){
return this.data.getKind();
}
public AnimalMorphologicalSign getSign(){
return this.data.getSign();
}
public boolean getIsPredator(){
return this.data.getIsPredator();
}
public int getYearsOld(){
return this.monthsOld / MainProgram.MONTHS_IN_A_YEAR;
}
public int getMonthsOld(){
return this.monthsOld;
}
//Parses <id> <name> <age> to an animal
public static Animal Parse(String line) throws AnimalParseException, KeyNotFoundException{
String[] args = line.split(" ");
if(args.length == 3){
if(Utils.intCanParse(args[0])){
if(Utils.intCanParse(args[2])){
int id = Utils.parseInt(args[0]);
String name = args[1];
int monthsOld = Utils.parseInt(args[2]);
return new Animal(id, name, monthsOld);
}
else{
throw new AnimalParseException("Unable to parse animal age : " + args[2]);
}
}
else{
throw new AnimalParseException("Unable to parse animal kind : " + args[0]);
}
}
throw new AnimalParseException("Unable to parse animal : " + line);
}
}
class AnimalDatabase{
private static Map<Integer, AnimalData> animals = new HashMap<Integer, AnimalData>(){
private static final long serialVersionUID = 1L;
{
put(1, new AnimalData(AnimalType.Lion, AnimalKind.Mammal, AnimalMorphologicalSign.Land, true));
put(2, new AnimalData(AnimalType.Dog, AnimalKind.Mammal, AnimalMorphologicalSign.Land, false));
put(3, new AnimalData(AnimalType.Snake, AnimalKind.Reptile, AnimalMorphologicalSign.MixLandWater, true));
put(4, new AnimalData(AnimalType.Lizard, AnimalKind.Reptile, AnimalMorphologicalSign.Land, false));
put(5, new AnimalData(AnimalType.Trout, AnimalKind.Fish, AnimalMorphologicalSign.Water, false));
put(6, new AnimalData(AnimalType.Shark, AnimalKind.Fish, AnimalMorphologicalSign.Water, true));
put(7, new AnimalData(AnimalType.Dolphin, AnimalKind.Mammal, AnimalMorphologicalSign.Water, false));
put(8, new AnimalData(AnimalType.Turtle, AnimalKind.Reptile, AnimalMorphologicalSign.MixLandWater, false));
}};
public static AnimalData get(int id) throws KeyNotFoundException{
if(animals.containsKey(id))
return animals.get(id);
else
throw new KeyNotFoundException("KEY " + id + " NOT FOUND in the animal database!");
}
}
| [
"iliq.nikushev@hotmail.com"
] | iliq.nikushev@hotmail.com |
3fed79fa1e00eca61206abfa498b928e84b21d98 | 6c0a7d61f94e931072100f9007cfc5d5a459da31 | /143/src/main/java/org/example/Solution.java | e9451e11f333ef2978ef8387903d124635367a47 | [] | no_license | sabaao/leetcode | 55f8567175c0669523d3163ac03898e7008a0676 | 05714e28aeda14c3c06d7060af1a30cf1b6cd8c0 | refs/heads/master | 2021-08-07T16:28:00.554657 | 2021-06-27T16:38:14 | 2021-06-27T16:38:14 | 165,649,549 | 0 | 0 | null | 2021-06-27T16:38:47 | 2019-01-14T11:26:39 | Java | UTF-8 | Java | false | false | 861 | java | package org.example;
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
public void reorderList(ListNode head) {
if(head==null) return;
ListNode node = head;
Deque<ListNode> que = new ArrayDeque<ListNode>();
int count = 0;
while(node!=null){
que.add(node);
node = node.next;
count++;
}
ListNode result = new ListNode(1);
ListNode resultTmp = result;
for(int i =0;i<count;i++){
if(i%2==0){
resultTmp.next = que.getFirst();
que.removeFirst();
}else{
resultTmp.next = que.getLast();
que.removeLast();
}
resultTmp = resultTmp.next;
}
resultTmp.next = null;
head = result.next;
}
}
| [
"charles@cathayholdings.com.tw"
] | charles@cathayholdings.com.tw |
54dcd8733533304d18d31bb2c4d98f63e26cccb4 | 0e0f515bf1d56b2afbfc70a5c88e296f545d62c7 | /src/main/java/com/naclo/PlanesysApplication.java | e960d148ae2060320418cee00daf75efb3ec1621 | [] | no_license | NaClOSYX/planssys | c029959c96e7e0693dade142b6024717ebf85609 | cbac974030693869034f240f38c00ab0cc60ad0d | refs/heads/master | 2022-04-27T10:49:24.878243 | 2020-04-29T08:12:30 | 2020-04-29T08:12:30 | 259,863,223 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 318 | java | package com.naclo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PlanesysApplication {
public static void main(String[] args) {
SpringApplication.run(PlanesysApplication.class, args);
}
}
| [
"2471342008@qq.com"
] | 2471342008@qq.com |
7ba045d27a4dfe190ca4e3aba1f0736843a31a8b | c6dc339bea8015c51f8b21d82cacbc0fbcd5daf8 | /Algorithms/Astar.java | bac1ed1c86340fcf57b1e526225a6273eca926e9 | [] | no_license | roszerne/PathVisualizer | a032386ece498d84db22d9653204fa3b14c84002 | ce6529fca966a2962b98757289a63832c1a8d6a7 | refs/heads/main | 2023-02-22T03:25:15.929228 | 2021-01-26T20:19:53 | 2021-01-26T20:19:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,946 | java | package Algorithms;
import Field.Node;
import GUI.BoardPanel;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Queue;
public class Astar extends Algo{
public Astar(BoardPanel boardPanel)
{
super(boardPanel);
startNode.g = 0;
startNode.f = h(startNode,endNode);;
}
public void run()
{
astar();
}
public void astar()
{
Queue<Node> openSet = new PriorityQueue<Node>();
openSet.add(startNode);
while (openSet.size() > 0 && !found && !paused)
{
Node node = openSet.poll();
if ( node.isEnd())
{
System.out.println("Znaleziono!");
node.makeVisited();
found = true;
break;
}
node.makeProcced();
ArrayList<Node> neigh = node.getNeighbours();
for (int i=0;i<neigh.size();i++)
{
if (!neigh.get(i).isVisited())
{
Node neighbour = neigh.get(i);
double tempG = node.g +1;
if (tempG < neighbour.g)
{
neighbour.addRoad(node);
neighbour.g = tempG;
neighbour.f = tempG+ h(neighbour,endNode);
openSet.add(neighbour);
}
}
}
stay(20);
node.makeVisited();
}
Found();
if (found)
{
board.visit();
board.drawRoad();
}
else
{
notFound();
}
}
public double h(Node n1, Node n2)
{
return Math.abs(n2.getPosition().x-n1.getPosition().x) + Math.abs(n2.getPosition().y-n1.getPosition().y);
}
}
| [
"noreply@github.com"
] | roszerne.noreply@github.com |
fca8179caed7175220ddbd22a5e80551f66b85dc | d2d72045f6ce0534e598bf0046a3d79c0fe6deb1 | /app/src/main/java/com/example/farshad/smarthome/Model/UserModel.java | e47842e72cdb1d21853752d86ae72e783af696de | [
"Unlicense"
] | permissive | FarshadFaramarzlou/SmartHome | 31cb180bc18596e0510ed64ccece4f677deea562 | 1034501e48e9d95772d1847b229bd5269054ab62 | refs/heads/master | 2021-06-27T13:36:38.271969 | 2017-09-05T14:49:19 | 2017-09-05T14:49:19 | 101,962,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,761 | java | package com.example.farshad.smarthome.Model;
import com.google.gson.annotations.SerializedName;
/**
* Created by Farshad on 5/12/2017.
*/
public class UserModel {
private int userid;
private String usertype;
private String name;
private String lastname;
private String username;
private String password;
@SerializedName("image")
public String imageUrl;
private int familyId;
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public int getFamilyId() {
return familyId;
}
public void setFamilyId(int familyId) {
this.familyId = familyId;
}
public int getUserid() {
return userid;
}
public void setUserid(int id) {
this.userid = id;
}
public String getUserType() {
return usertype;
}
public void setUserType(String userType) {
this.usertype = userType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserModel(){
}
public UserModel(String username, String password) {
this.username = username;
this.password = password;
}
}
| [
"farshadfaramarzlou@gmail.com"
] | farshadfaramarzlou@gmail.com |
35d213d3ea8c63513866dddb12c6737995cc10d3 | 2ec381dc7922f0ce0cf1a064271a0ded3997f40c | /Homework6/src/main/java/com/lab/homework6/service/model/Payment.java | 38b7f031ab0ec577cca9705f78d81b668b344058 | [] | no_license | Taras-Chaban/Lab-Homework | 062b57cfcd6267bf134758828fc9c7ecf5f8f34f | 9331e4122bc25bc96683fd628e921160fa4d3a33 | refs/heads/master | 2023-05-14T07:46:14.194184 | 2021-06-07T09:06:35 | 2021-06-07T09:06:35 | 354,719,009 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 275 | java | package com.lab.homework6.service.model;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class Payment {
private Long invoiceCode;
private String productCode;
private String productName;
private Double quantity;
private Double value;
}
| [
"gold.bender2001@gmail.com"
] | gold.bender2001@gmail.com |
57b5f2feb8ca1fe735fe9685e526a648602a8fe2 | 26a837b93cf73e6c372830f9a7a316c01081a4ea | /core/src/test/java/arez/ObservableValueTest.java | 0e27491134f8c56f547f8414b3347d3f39fae348 | [
"Apache-2.0"
] | permissive | arez/arez | 033b27f529b527c747b2a93f3c2c553c41c32acd | df68d72a69d3af1123e7d7c424f77b74f13f8052 | refs/heads/master | 2023-06-08T00:09:56.319223 | 2023-06-05T02:12:14 | 2023-06-05T02:12:14 | 96,367,327 | 13 | 4 | Apache-2.0 | 2022-12-10T20:29:35 | 2017-07-05T22:50:24 | Java | UTF-8 | Java | false | false | 69,656 | java | package arez;
import arez.spy.ActionCompleteEvent;
import arez.spy.ActionStartEvent;
import arez.spy.ComputableValueActivateEvent;
import arez.spy.ComputableValueDeactivateEvent;
import arez.spy.ComputableValueDisposeEvent;
import arez.spy.ObservableValueChangeEvent;
import arez.spy.ObservableValueDisposeEvent;
import arez.spy.ObservableValueInfo;
import arez.spy.ObserveScheduleEvent;
import arez.spy.PropertyAccessor;
import arez.spy.PropertyMutator;
import arez.spy.TransactionCompleteEvent;
import arez.spy.TransactionStartEvent;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public final class ObservableValueTest
extends AbstractTest
{
@Test
public void initialState()
{
final ArezContext context = Arez.context();
final String name = ValueUtil.randomString();
final PropertyAccessor<String> accessor = () -> "";
final PropertyMutator<String> mutator = value -> {
};
final ObservableValue<?> observableValue = new ObservableValue<>( context, null, name, null, accessor, mutator );
assertEquals( observableValue.getName(), name );
assertEquals( observableValue.getContext(), context );
assertEquals( observableValue.toString(), name );
assertFalse( observableValue.isPendingDeactivation() );
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
assertNull( observableValue.getComponent() );
//All the same stuff
assertEquals( observableValue.getLastTrackerTransactionId(), 0 );
assertEquals( observableValue.getWorkState(), 0 );
assertFalse( observableValue.isInCurrentTracking() );
// Fields for calculated observables in this non-calculated variant
assertFalse( observableValue.isComputableValue() );
assertFalse( observableValue.canDeactivate() );
assertFalse( observableValue.canDeactivateNow() );
assertFalse( observableValue.isComputableValue() );
assertTrue( observableValue.isActive() );
assertEquals( observableValue.getAccessor(), accessor );
assertEquals( observableValue.getMutator(), mutator );
observableValue.invariantLeastStaleObserverState();
assertTrue( context.getTopLevelObservables().containsKey( observableValue.getName() ) );
}
@Test
public void initialStateForCalculatedObservable()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
assertEquals( observableValue.getObserver(), observer );
assertNull( observableValue.getComponent() );
assertTrue( observableValue.canDeactivate() );
assertTrue( observableValue.canDeactivateNow() );
assertTrue( observableValue.isComputableValue() );
assertTrue( observableValue.isActive() );
assertNotNull( observableValue.getAccessor() );
assertNull( observableValue.getMutator() );
observableValue.invariantLeastStaleObserverState();
assertFalse( context.getTopLevelObservables().containsKey( observableValue.getName() ) );
}
@Test
public void constructWithComponentWhenNativeComponentsDisabled()
{
ArezTestUtil.disableNativeComponents();
final ArezContext context = Arez.context();
final Component component =
new Component( context,
ValueUtil.randomString(),
ValueUtil.randomString(),
ValueUtil.randomString(),
null,
null );
final String name = ValueUtil.randomString();
assertInvariantFailure( () -> new ObservableValue<>( context, component, name, null, null, null ),
"Arez-0054: ObservableValue named '" + name + "' has component specified but " +
"Arez.areNativeComponentsEnabled() is false." );
}
@Test
public void basicLifecycle_withComponent()
{
final ArezContext context = Arez.context();
final Component component =
new Component( context,
ValueUtil.randomString(),
ValueUtil.randomString(),
ValueUtil.randomString(),
null,
null );
final String name = ValueUtil.randomString();
final ObservableValue<String> observableValue = new ObservableValue<>( context, component, name, null, null, null );
assertEquals( observableValue.getName(), name );
assertEquals( observableValue.getComponent(), component );
assertFalse( context.getTopLevelObservables().containsKey( observableValue.getName() ) );
assertTrue( component.getObservableValues().contains( observableValue ) );
observableValue.dispose();
assertFalse( component.getObservableValues().contains( observableValue ) );
}
@Test
public void initialState_accessor_introspectorsDisabled()
{
ArezTestUtil.disablePropertyIntrospectors();
final String name = ValueUtil.randomString();
final PropertyAccessor<String> accessor = () -> "";
assertInvariantFailure( () -> new ObservableValue<>( Arez.context(), null, name, null, accessor, null ),
"Arez-0055: ObservableValue named '" + name +
"' has accessor specified but Arez.arePropertyIntrospectorsEnabled() is false." );
}
@Test
public void initialState_mutator_introspectorsDisabled()
{
ArezTestUtil.disablePropertyIntrospectors();
final String name = ValueUtil.randomString();
final PropertyMutator<String> mutator = value -> {
};
assertInvariantFailure( () -> new ObservableValue<>( Arez.context(), null, name, null, null, mutator ),
"Arez-0056: ObservableValue named '" + name +
"' has mutator specified but Arez.arePropertyIntrospectorsEnabled() is false." );
}
@Test
public void getAccessor_introspectorsDisabled()
{
ArezTestUtil.disablePropertyIntrospectors();
final ObservableValue<?> observableValue = Arez.context().observable();
assertInvariantFailure( observableValue::getAccessor,
"Arez-0058: Attempt to invoke getAccessor() on ObservableValue named '" +
observableValue.getName() +
"' when Arez.arePropertyIntrospectorsEnabled() returns false." );
}
@Test
public void getMutator_introspectorsDisabled()
{
ArezTestUtil.disablePropertyIntrospectors();
final ObservableValue<?> observableValue = Arez.context().observable();
assertInvariantFailure( observableValue::getMutator,
"Arez-0059: Attempt to invoke getMutator() on ObservableValue named '" +
observableValue.getName() +
"' when Arez.arePropertyIntrospectorsEnabled() returns false." );
}
@Test
public void dispose_noTransaction()
{
final ArezContext context = Arez.context();
final ObservableValue<?> observableValue = context.observable();
final Observer observer = new Observer( context,
null,
ValueUtil.randomString(),
new CountAndObserveProcedure(),
null,
0 );
setupReadOnlyTransaction( context );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.getObservers().add( observer );
observer.getDependencies().add( observableValue );
assertFalse( observableValue.isDisposed() );
// Reset transaction before calling dispose
Transaction.setTransaction( null );
final int currentNextTransactionId = context.currentNextTransactionId();
assertTrue( context.getTopLevelObservables().containsKey( observableValue.getName() ) );
observableValue.dispose();
// Multiple transactions created. 1 for dispose operation and one for reaction
assertEquals( context.currentNextTransactionId(), currentNextTransactionId + 2 );
assertTrue( observableValue.isDisposed() );
assertEquals( observableValue.getWorkState(), ObservableValue.DISPOSED );
assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE );
assertFalse( context.getTopLevelObservables().containsKey( observableValue.getName() ) );
}
@Test
public void dispose_spyEventHandlerAdded()
{
final ArezContext context = Arez.context();
final ObservableValue<?> observableValue = context.observable();
final Observer observer = context.observer( observableValue::reportObserved );
assertFalse( observableValue.isDisposed() );
// Need to pause schedule so that observer reaction does not pollute the spy events
context.pauseScheduler();
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.dispose();
assertTrue( observableValue.isDisposed() );
handler.assertEventCount( 7 );
handler.assertNextEvent( ActionStartEvent.class,
event -> assertEquals( event.getName(), observableValue.getName() + ".dispose" ) );
handler.assertNextEvent( TransactionStartEvent.class,
event -> assertEquals( event.getName(), observableValue.getName() + ".dispose" ) );
handler.assertNextEvent( ObservableValueChangeEvent.class,
event -> assertEquals( event.getObservableValue().getName(), observableValue.getName() ) );
handler.assertNextEvent( ObserveScheduleEvent.class,
event -> assertEquals( event.getObserver().getName(), observer.getName() ) );
handler.assertNextEvent( TransactionCompleteEvent.class,
event -> assertEquals( event.getName(), observableValue.getName() + ".dispose" ) );
handler.assertNextEvent( ActionCompleteEvent.class,
event -> assertEquals( event.getName(), observableValue.getName() + ".dispose" ) );
handler.assertNextEvent( ObservableValueDisposeEvent.class,
event -> assertEquals( event.getObservableValue().getName(), observableValue.getName() ) );
}
@Test
public void dispose_spyEvents_for_ComputableValue()
{
final ArezContext context = Arez.context();
final ComputableValue<String> computableValue = context.computable( () -> "" );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.getObservers().add( observer );
observer.getDependencies().add( observableValue );
assertFalse( observableValue.isDisposed() );
Transaction.setTransaction( null );
// Have to pause schedule otherwise will Observer will react to dispose and change message sequencing below
context.pauseScheduler();
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.dispose();
assertTrue( observableValue.isDisposed() );
handler.assertEventCount( 15 );
// This is the part that disposes the associated ObservableValue
handler.assertNextEvent( ActionStartEvent.class );
handler.assertNextEvent( TransactionStartEvent.class );
handler.assertNextEvent( ObservableValueChangeEvent.class );
handler.assertNextEvent( ObserveScheduleEvent.class );
handler.assertNextEvent( TransactionCompleteEvent.class );
handler.assertNextEvent( ActionCompleteEvent.class );
// This is the part that disposes the Observer
handler.assertNextEvent( ActionStartEvent.class );
handler.assertNextEvent( TransactionStartEvent.class );
handler.assertNextEvent( TransactionCompleteEvent.class );
handler.assertNextEvent( ActionCompleteEvent.class );
// This is the part that disposes the associated ComputableValue
handler.assertNextEvent( ActionStartEvent.class );
handler.assertNextEvent( TransactionStartEvent.class );
handler.assertNextEvent( TransactionCompleteEvent.class );
handler.assertNextEvent( ActionCompleteEvent.class );
handler.assertNextEvent( ComputableValueDisposeEvent.class );
}
@Test
public void dispose()
{
final ArezContext context = Arez.context();
final ObservableValue<?> observableValue = context.observable();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( newReadWriteObserver( context ) );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.getObservers().add( observer );
observer.getDependencies().add( observableValue );
Transaction.setTransaction( null );
assertFalse( observableValue.isDisposed() );
final int currentNextTransactionId = context.currentNextTransactionId();
// Pause the schedule so reactions do not occur
context.pauseScheduler();
observableValue.dispose();
// No transaction created so new id
assertEquals( context.currentNextTransactionId(), currentNextTransactionId + 1 );
assertTrue( observableValue.isDisposed() );
assertEquals( observableValue.getWorkState(), ObservableValue.DISPOSED );
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
}
@Test
public void dispose_readOnlyTransaction()
{
final ArezContext context = Arez.context();
final ObservableValue<?> observableValue = context.observable();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( context.observer( new CountAndObserveProcedure() ) );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.getObservers().add( observer );
observer.getDependencies().add( observableValue );
assertFalse( observableValue.isDisposed() );
Transaction.setTransaction( null );
final int currentNextTransactionId = context.currentNextTransactionId();
final String name = ValueUtil.randomString();
@SuppressWarnings( "CodeBlock2Expr" )
final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> context.safeAction( () -> {
context.safeAction( name, (SafeProcedure) ValueUtil::randomString );
}, ActionFlags.READ_ONLY ) );
assertTrue( exception.getMessage().startsWith( "Arez-0119: Attempting to create READ_WRITE transaction named '" +
name + "' but it is nested in transaction named '" ) );
assertTrue( exception.getMessage().endsWith( "' with mode READ_ONLY which is not equal to READ_WRITE." ) );
// No transaction created so new id
assertEquals( context.currentNextTransactionId(), currentNextTransactionId + 1 );
assertFalse( observableValue.isDisposed() );
}
@Test
public void ownerMustBeADerivation()
{
final ArezContext context = Arez.context();
final Observer owner = context.observer( new CountAndObserveProcedure() );
setupReadOnlyTransaction( context );
final String name = ValueUtil.randomString();
assertInvariantFailure( () -> new ObservableValue<>( context, null, name, owner, null, null ),
"Arez-0057: ObservableValue named '" + name + "' has observer specified but " +
"observer is not part of a ComputableValue." );
}
@Test
public void currentTrackingWorkValue()
{
final ObservableValue<?> observableValue = Arez.context().observable();
assertEquals( observableValue.getWorkState(), 0 );
assertEquals( observableValue.getWorkState(), ObservableValue.NOT_IN_CURRENT_TRACKING );
assertFalse( observableValue.isInCurrentTracking() );
observableValue.putInCurrentTracking();
assertTrue( observableValue.isInCurrentTracking() );
assertEquals( observableValue.getWorkState(), ObservableValue.IN_CURRENT_TRACKING );
observableValue.removeFromCurrentTracking();
assertEquals( observableValue.getWorkState(), ObservableValue.NOT_IN_CURRENT_TRACKING );
assertFalse( observableValue.isInCurrentTracking() );
}
@Test
public void lastTrackerTransactionId()
{
final ObservableValue<?> observableValue = Arez.context().observable();
assertEquals( observableValue.getWorkState(), 0 );
assertEquals( observableValue.getLastTrackerTransactionId(), 0 );
observableValue.setLastTrackerTransactionId( 23 );
assertEquals( observableValue.getLastTrackerTransactionId(), 23 );
assertEquals( observableValue.getWorkState(), 23 );
}
@Test
public void addObserver()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
// Handle addition of observer in correct state
observableValue.addObserver( observer );
assertEquals( observableValue.getObservers().size(), 1 );
assertTrue( observableValue.hasObservers() );
assertTrue( observableValue.hasObserver( observer ) );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
observableValue.invariantLeastStaleObserverState();
}
@Test
public void addObserver_updatesLestStaleObserverState()
{
final ArezContext context = Arez.context();
final ComputableValue<?> computable = context.computable( () -> 1 );
setCurrentTransaction( computable.getObserver() );
final ObservableValue<?> observableValue = context.observable();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_STALE );
computable.getObserver().setState( Observer.Flags.STATE_POSSIBLY_STALE );
observableValue.addObserver( computable.getObserver() );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_POSSIBLY_STALE );
observableValue.invariantLeastStaleObserverState();
}
@Test
public void addObserver_whenObservableDisposed()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setWorkState( ObservableValue.DISPOSED );
assertInvariantFailure( () -> observableValue.addObserver( observer ),
"Arez-0067: Attempting to add observer named '" +
observer.getName() +
"' to " +
"ObservableValue named '" +
observableValue.getName() +
"' when ObservableValue is disposed." );
}
@Test
public void addObserver_whenObserverIsNotTrackerAssociatedWithTransaction()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
final ObservableValue<?> observableValue = context.observable();
//noinspection CodeBlock2Expr
context.safeAction( () -> {
assertInvariantFailure( () -> observableValue.addObserver( observer ),
"Arez-0203: Attempting to add observer named '" + observer.getName() + "' to " +
"ObservableValue named '" + observableValue.getName() + "' but the observer is not the " +
"tracker in transaction named '" + context.getTransaction().getName() + "'." );
}, ActionFlags.NO_VERIFY_ACTION_REQUIRED );
}
@Test
public void addObserver_highPriorityObserver_normalPriorityComputableValue()
{
final ArezContext context = Arez.context();
final Observer observer =
new Observer( context,
null,
ValueUtil.randomString(),
new CountAndObserveProcedure(),
null,
ComputableValue.Flags.PRIORITY_HIGH );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.computable( () -> "" ).getObservableValue();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
assertInvariantFailure( () -> observableValue.addObserver( observer ),
"Arez-0183: Attempting to add observer named '" +
observer.getName() +
"' to " +
"ObservableValue named '" +
observableValue.getName() +
"' where the observer is scheduled at " +
"a HIGH priority but the ObservableValue's owner is scheduled at a NORMAL priority." );
}
@Test
public void addObserver_highPriorityObserver_normalPriorityComputableValue_whenObservingLowerPriorityEnabled()
{
final ArezContext context = Arez.context();
final Observer observer =
new Observer( context,
null,
ValueUtil.randomString(),
new CountAndObserveProcedure(),
null,
Observer.Flags.PRIORITY_HIGH | Observer.Flags.OBSERVE_LOWER_PRIORITY_DEPENDENCIES );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.computable( () -> "" ).getObservableValue();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.addObserver( observer );
assertTrue( observableValue.getObservers().contains( observer ) );
}
@Test
public void addObserver_whenObserverDisposed()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observer.markAsDisposed();
assertInvariantFailure( () -> observableValue.addObserver( observer ),
"Arez-0068: Attempting to add observer named '" + observer.getName() + "' to " +
"ObservableValue named '" + observableValue.getName() + "' when observer is disposed." );
}
@Test
public void addObserver_duplicate()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
// Handle addition of observer in correct state
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertEquals( observableValue.getObservers().size(), 1 );
assertTrue( observableValue.hasObservers() );
assertTrue( observableValue.hasObserver( observer ) );
assertInvariantFailure( () -> observableValue.addObserver( observer ),
"Arez-0066: Attempting to add observer named '" + observer.getName() + "' to " +
"ObservableValue named '" + observableValue.getName() + "' when observer is already " +
"observing ObservableValue." );
assertEquals( observableValue.getObservers().size(), 1 );
assertTrue( observableValue.hasObservers() );
assertTrue( observableValue.hasObserver( observer ) );
observableValue.invariantLeastStaleObserverState();
}
@Test
public void addObserver_noActiveTransaction()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
final ObservableValue<?> observableValue = context.observable();
assertInvariantFailure( () -> observableValue.addObserver( observer ),
"Arez-0065: Attempt to invoke addObserver on ObservableValue named '" +
observableValue.getName() + "' when there is no active transaction." );
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
observableValue.invariantLeastStaleObserverState();
}
@Test
public void removeObserver()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.getObservers().add( observer );
observer.getDependencies().add( observableValue );
assertEquals( observableValue.getObservers().size(), 1 );
assertTrue( observableValue.hasObservers() );
assertTrue( observableValue.hasObserver( observer ) );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
observableValue.removeObserver( observer );
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
assertFalse( observableValue.hasObserver( observer ) );
// It should be updated that it is not removeObserver that updates LeastStaleObserverState
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
}
@Test
public void removeObserver_onDerivation()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.getObservers().add( observer );
observer.getDependencies().add( observableValue );
assertEquals( observableValue.getObservers().size(), 1 );
assertTrue( observableValue.hasObservers() );
assertTrue( observableValue.hasObserver( observer ) );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
observableValue.removeObserver( observer );
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
assertFalse( observableValue.hasObserver( observer ) );
// It should be updated that it is not removeObserver that updates LeastStaleObserverState
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
assertTrue( observableValue.isPendingDeactivation() );
final List<ObservableValue<?>> pendingDeactivations = context.getTransaction().getPendingDeactivations();
assertNotNull( pendingDeactivations );
assertEquals( pendingDeactivations.size(), 1 );
assertTrue( pendingDeactivations.contains( observableValue ) );
}
@Test
public void removeObserver_whenNoTransaction()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.getObservers().add( observer );
observer.getDependencies().add( observableValue );
assertEquals( observableValue.getObservers().size(), 1 );
assertTrue( observableValue.hasObservers() );
assertTrue( observableValue.hasObserver( observer ) );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
Transaction.setTransaction( null );
assertInvariantFailure( () -> observableValue.removeObserver( observer ),
"Arez-0069: Attempt to invoke removeObserver on ObservableValue named '" +
observableValue.getName() + "' when there is no active transaction." );
assertEquals( observableValue.getObservers().size(), 1 );
assertTrue( observableValue.hasObservers() );
assertTrue( observableValue.hasObserver( observer ) );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
}
@Test
public void removeObserver_whenNoSuchObserver()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
assertEquals( observableValue.getObservers().size(), 0 );
assertFalse( observableValue.hasObservers() );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
assertInvariantFailure( () -> observableValue.removeObserver( observer ),
"Arez-0070: Attempting to remove observer named '" + observer.getName() +
"' from ObservableValue named '" + observableValue.getName() + "' when observer is not " +
"observing ObservableValue." );
}
@Test
public void setLeastStaleObserverState()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
final ObservableValue<?> observableValue = context.observable();
setCurrentTransaction( observer );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
}
@Test
public void setLeastStaleObserverState_noActiveTransaction()
{
final ArezContext context = Arez.context();
final ObservableValue<?> observableValue = context.observable();
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
assertInvariantFailure( () -> observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE ),
"Arez-0074: Attempt to invoke setLeastStaleObserverState on ObservableValue named '" +
observableValue.getName() + "' when there is no active transaction." );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
}
@Test
public void setLeastStaleObserverState_Passing_INACTIVE()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
final ObservableValue<?> observableValue = context.observable();
setCurrentTransaction( observer );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
assertInvariantFailure( () -> observableValue.setLeastStaleObserverState( Observer.Flags.STATE_INACTIVE ),
"Arez-0075: Attempt to invoke setLeastStaleObserverState on ObservableValue named '" +
observableValue.getName() + "' with invalid value INACTIVE." );
assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE );
}
@Test
public void invariantLeastStaleObserverState_noObservers()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ObservableValue<?> observableValue = context.observable();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_STALE );
assertInvariantFailure( observableValue::invariantLeastStaleObserverState,
"Arez-0078: Calculated leastStaleObserverState on ObservableValue named '" +
observableValue.getName() + "' is 'UP_TO_DATE' which is unexpectedly less than " +
"cached value 'STALE'." );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.invariantLeastStaleObserverState();
}
@Test
public void invariantLeastStaleObserverState_multipleObservers()
{
final Observer observer1 = Arez.context().observer( new CountAndObserveProcedure() );
final Observer observer2 = Arez.context().observer( new CountAndObserveProcedure() );
final Observer observer3 = Arez.context().observer( new CountAndObserveProcedure() );
final Observer observer4 = Arez.context().computable( () -> "" ).getObserver();
setupReadWriteTransaction();
observer1.setState( Observer.Flags.STATE_UP_TO_DATE );
observer2.setState( Observer.Flags.STATE_POSSIBLY_STALE );
observer3.setState( Observer.Flags.STATE_STALE );
observer4.setState( Observer.Flags.STATE_INACTIVE );
final ObservableValue<?> observableValue = Arez.context().observable();
observer1.getDependencies().add( observableValue );
observer2.getDependencies().add( observableValue );
observer3.getDependencies().add( observableValue );
observer4.getDependencies().add( observableValue );
observableValue.rawAddObserver( observer1 );
observableValue.rawAddObserver( observer2 );
observableValue.rawAddObserver( observer3 );
observableValue.rawAddObserver( observer4 );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_STALE );
assertInvariantFailure( observableValue::invariantLeastStaleObserverState,
"Arez-0078: Calculated leastStaleObserverState on ObservableValue named '" +
observableValue.getName() + "' is 'UP_TO_DATE' which is unexpectedly less than " +
"cached value 'STALE'." );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.invariantLeastStaleObserverState();
}
@Test
public void invariantOwner_badObservableLink()
{
ArezTestUtil.disableRegistries();
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final Observer observer = context.computable( () -> "" ).getObserver();
final ObservableValue<?> observableValue =
new ObservableValue<>( context, null, observer.getName(), observer, null, null );
assertInvariantFailure( observableValue::invariantOwner,
"Arez-0076: ObservableValue named '" + observableValue.getName() + "' has owner " +
"specified but owner does not link to ObservableValue as derived value." );
}
@Test
public void invariantObserversLinked()
{
final Observer observer1 = Arez.context().observer( new CountAndObserveProcedure() );
final Observer observer2 = Arez.context().observer( new CountAndObserveProcedure() );
final Observer observer3 = Arez.context().observer( new CountAndObserveProcedure() );
setupReadWriteTransaction();
observer1.setState( Observer.Flags.STATE_UP_TO_DATE );
observer2.setState( Observer.Flags.STATE_POSSIBLY_STALE );
observer3.setState( Observer.Flags.STATE_STALE );
final ObservableValue<?> observableValue = Arez.context().observable();
observer1.getDependencies().add( observableValue );
observer2.getDependencies().add( observableValue );
observableValue.rawAddObserver( observer1 );
observableValue.rawAddObserver( observer2 );
observableValue.rawAddObserver( observer3 );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
assertInvariantFailure( observableValue::invariantObserversLinked,
"Arez-0077: ObservableValue named '" +
observableValue.getName() +
"' has observer named '" +
observer3.getName() +
"' which does not contain ObservableValue as dependency." );
observer3.getDependencies().add( observableValue );
observableValue.invariantObserversLinked();
}
@Test
public void queueForDeactivation()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
assertFalse( observableValue.isPendingDeactivation() );
observableValue.queueForDeactivation();
assertTrue( observableValue.isPendingDeactivation() );
final List<ObservableValue<?>> pendingDeactivations = context.getTransaction().getPendingDeactivations();
assertNotNull( pendingDeactivations );
assertEquals( pendingDeactivations.size(), 1 );
assertTrue( pendingDeactivations.contains( observableValue ) );
}
@Test
public void queueForDeactivation_whereAlreadyPending()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.markAsPendingDeactivation();
observableValue.queueForDeactivation();
// No activation pending
assertNull( context.getTransaction().getPendingDeactivations() );
}
@Test
public void queueForDeactivation_whenNoTransaction()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
assertFalse( observableValue.isPendingDeactivation() );
Transaction.setTransaction( null );
assertInvariantFailure( observableValue::queueForDeactivation,
"Arez-0071: Attempt to invoke queueForDeactivation on ObservableValue named '" +
observableValue.getName() + "' when there is no active transaction." );
}
@Test
public void queueForDeactivation_observableIsNotAbleToBeDeactivated()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ObservableValue<?> observableValue = context.observable();
assertFalse( observableValue.isPendingDeactivation() );
assertInvariantFailure( observableValue::queueForDeactivation,
"Arez-0072: Attempted to invoke queueForDeactivation() on ObservableValue named '" +
observableValue.getName() + "' but ObservableValue is not able to be deactivated." );
}
@Test
public void queueForDeactivation_whereDependenciesPresent()
{
final ArezContext context = Arez.context();
final Observer observer = context.observer( new CountAndObserveProcedure() );
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer derivation = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
derivation.setState( Observer.Flags.STATE_UP_TO_DATE );
assertFalse( observableValue.isPendingDeactivation() );
observableValue.rawAddObserver( observer );
observer.getDependencies().add( observableValue );
assertInvariantFailure( observableValue::queueForDeactivation,
"Arez-0072: Attempted to invoke queueForDeactivation() on ObservableValue named '" +
observableValue.getName() + "' but ObservableValue is not able to be deactivated." );
}
@Test
public void resetPendingDeactivation()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.markAsPendingDeactivation();
assertTrue( observableValue.isPendingDeactivation() );
observableValue.resetPendingDeactivation();
assertFalse( observableValue.isPendingDeactivation() );
}
@Test
public void canDeactivate()
{
final ArezContext context = Arez.context();
final Observer randomObserver = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( randomObserver );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
assertTrue( observableValue.canDeactivate() );
assertTrue( observableValue.canDeactivateNow() );
observableValue.addObserver( randomObserver );
randomObserver.getDependencies().add( observableValue );
assertTrue( observableValue.canDeactivate() );
assertFalse( observableValue.canDeactivateNow() );
observableValue.removeObserver( randomObserver );
randomObserver.getDependencies().remove( observableValue );
assertTrue( observableValue.canDeactivate() );
assertTrue( observableValue.canDeactivateNow() );
final Disposable keepAliveLock = computableValue.keepAlive();
assertTrue( observableValue.canDeactivate() );
assertFalse( observableValue.canDeactivateNow() );
keepAliveLock.dispose();
assertTrue( observableValue.canDeactivate() );
assertTrue( observableValue.canDeactivateNow() );
}
@Test
public void deactivate()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE );
observableValue.deactivate();
assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE );
}
@Test
public void deactivate_when_spyEventHandler_present()
{
final ArezContext context = Arez.context();
final Observer randomObserver = context.observer( new CountAndObserveProcedure() );
setCurrentTransaction( randomObserver );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE );
observableValue.addObserver( randomObserver );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.deactivate();
assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE );
handler.assertEventCount( 1 );
handler.assertNextEvent( ComputableValueDeactivateEvent.class,
e -> assertEquals( e.getComputableValue().getName(),
observer.getComputableValue().getName() ) );
}
@Test
public void deactivate_outsideTransaction()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE );
Transaction.setTransaction( null );
assertInvariantFailure( observableValue::deactivate,
"Arez-0060: Attempt to invoke deactivate on ObservableValue named '" +
observableValue.getName() + "' when there is no active transaction." );
}
@Test
public void deactivate_ownerInactive()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observableValue.deactivate();
assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE );
}
@Test
public void deactivate_noOwner()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ObservableValue<?> observableValue = context.observable();
assertInvariantFailure( observableValue::deactivate, "Arez-0061: Invoked deactivate on ObservableValue named '" +
observableValue.getName() +
"' but ObservableValue can not be deactivated. Either owner is " +
"null or the associated ComputableValue has keepAlive enabled." );
}
@Test
public void deactivate_onKeepAlive()
{
final ArezContext context = Arez.context();
final ObservableValue<Object> observable = context.observable();
final ObservableValue<?> observableValue = context.computable( () -> {
observable.reportObserved();
return "";
}, ComputableValue.Flags.KEEPALIVE ).getObservableValue();
assertInvariantFailure( () -> context.safeAction( observableValue::deactivate ),
"Arez-0061: Invoked deactivate on ObservableValue named '" +
observableValue.getName() +
"' but ObservableValue can not be deactivated. Either owner is " +
"null or the associated ComputableValue has keepAlive enabled." );
}
@Test
public void activate()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
observer.setState( Observer.Flags.STATE_INACTIVE );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE );
observableValue.activate();
assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE );
}
@Test
public void activate_when_spyEventHandler_present()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
observer.setState( Observer.Flags.STATE_INACTIVE );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.activate();
assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE );
handler.assertEventCount( 1 );
handler.assertNextEvent( ComputableValueActivateEvent.class,
event -> assertEquals( event.getComputableValue().getName(), computableValue.getName() ) );
}
@Test
public void activate_outsideTransaction()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
observer.setState( Observer.Flags.STATE_INACTIVE );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE );
Transaction.setTransaction( null );
assertInvariantFailure( observableValue::activate,
"Arez-0062: Attempt to invoke activate on ObservableValue named '" +
observableValue.getName() + "' when there is no active transaction." );
}
@Test
public void activate_ownerInactive()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer observer = computableValue.getObserver();
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
assertInvariantFailure( observableValue::activate, "Arez-0064: Invoked activate on ObservableValue named '" +
observableValue.getName() +
"' when ObservableValue is already active." );
}
@Test
public void activate_noOwner()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ObservableValue<?> observableValue = context.observable();
assertInvariantFailure( observableValue::activate,
"Arez-0063: Invoked activate on ObservableValue named '" +
observableValue.getName() + "' when owner is null." );
}
@Test
public void reportObserved()
{
final ArezContext context = Arez.context();
setupReadOnlyTransaction( context );
final ObservableValue<?> observableValue = context.observable();
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
observableValue.reportObserved();
assertEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 1 );
assertTrue( context.getTransaction().safeGetObservables().contains( observableValue ) );
}
@Test
public void reportObservedIfTrackingTransactionActive()
{
final ArezContext context = Arez.context();
final ObservableValue<?> observableValue = context.observable();
// Outside a transaction so perfectly safe
observableValue.reportObservedIfTrackingTransactionActive();
// This action does not verify that reads occurred so should not
// fail but will not actually observe
context.safeAction( observableValue::reportObservedIfTrackingTransactionActive,
ActionFlags.NO_VERIFY_ACTION_REQUIRED );
// This action will raise an exception as no reads or writes occurred
// within scope and we asked to verify that reads or writes occurred
assertThrows( () -> context.safeAction( observableValue::reportObservedIfTrackingTransactionActive ) );
// Now we use a tracking transaction
final Observer observer = context.observer( observableValue::reportObservedIfTrackingTransactionActive );
assertTrue( observer.getDependencies().contains( observableValue ) );
}
@Test
public void preReportChanged()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
final ObservableValue<?> observableValue = context.observable();
observableValue.preReportChanged();
}
@Test
public void preReportChanged_onDisposedObservable()
{
final ArezContext context = Arez.context();
setCurrentTransaction( newReadWriteObserver( context ) );
final ObservableValue<?> observableValue = context.observable();
observableValue.setWorkState( ObservableValue.DISPOSED );
assertInvariantFailure( observableValue::preReportChanged,
"Arez-0144: Invoked reportChanged on transaction named '" +
Transaction.current().getName() + "' for ObservableValue named '" +
observableValue.getName() + "' where the ObservableValue is disposed." );
}
@Test
public void preReportChanged_inReadOnlyTransaction()
{
final ArezContext context = Arez.context();
setCurrentTransaction( context.observer( new CountAndObserveProcedure() ) );
final ObservableValue<?> observableValue = context.observable();
assertInvariantFailure( observableValue::preReportChanged,
"Arez-0152: Transaction named '" + Transaction.current().getName() +
"' attempted to change ObservableValue named '" + observableValue.getName() +
"' but the transaction mode is READ_ONLY." );
}
@Test
public void reportChanged()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final ObservableValue<?> observableValue = context.observable();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
observableValue.reportChanged();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
}
@Test
public void reportChanged_generates_spyEvent()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final ObservableValue<?> observableValue = context.observable();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.reportChanged();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
handler.assertEventCount( 2 );
handler.assertNextEvent( ObservableValueChangeEvent.class, event -> {
assertEquals( event.getObservableValue().getName(), observableValue.getName() );
assertNull( event.getValue() );
} );
handler.assertNextEvent( ObserveScheduleEvent.class );
}
@Test
public void reportChanged_generates_spyEvent_withValueWhenIntrospectorPresent()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final String currentValue = ValueUtil.randomString();
final ObservableValue<?> observableValue =
new ObservableValue<>( context, null, ValueUtil.randomString(), null, () -> currentValue, null );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.reportChanged();
handler.assertEventCount( 1 );
handler.assertNextEvent( ObservableValueChangeEvent.class, event -> {
assertEquals( event.getObservableValue().getName(), observableValue.getName() );
assertEquals( event.getValue(), currentValue );
} );
}
@Test
public void reportChanged_generates_spyEvent_whenValueIntrpspectorErrors()
{
final ArezContext context = Arez.context();
final String name = ValueUtil.randomString();
final PropertyAccessor<Object> accessor = () -> {
// This means no value ever possible
throw new RuntimeException();
};
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_POSSIBLY_STALE );
final ObservableValue<?> observableValue = context.observable( name, accessor, null );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_POSSIBLY_STALE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.reportChanged();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
handler.assertEventCount( 2 );
handler.assertNextEvent( ObservableValueChangeEvent.class, event -> {
assertEquals( event.getObservableValue().getName(), observableValue.getName() );
assertNull( event.getValue() );
} );
handler.assertNextEvent( ObserveScheduleEvent.class,
e -> assertEquals( e.getObserver().getName(), observer.getName() ) );
}
@Test
public void reportChanged_generates_spyEvents_each_call()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final ObservableValue<?> observableValue = context.observable();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.reportChanged();
observableValue.reportChanged();
observableValue.reportChanged();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
handler.assertEventCount( 4 );
handler.assertNextEvent( ObservableValueChangeEvent.class,
e -> assertEquals( e.getObservableValue().getName(), observableValue.getName() ) );
handler.assertNextEvent( ObserveScheduleEvent.class );
handler.assertNextEvent( ObservableValueChangeEvent.class );
handler.assertNextEvent( ObservableValueChangeEvent.class );
}
@Test
public void reportPossiblyChanged()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_UP_TO_DATE );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer derivation = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
derivation.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
observableValue.reportPossiblyChanged();
assertEquals( observer.getState(), Observer.Flags.STATE_POSSIBLY_STALE );
}
@Test
public void reportChangeConfirmed()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_POSSIBLY_STALE );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer derivation = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
derivation.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_POSSIBLY_STALE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
observableValue.reportChangeConfirmed();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
}
@Test
public void reportChangeConfirmed_generates_spyEvent()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_POSSIBLY_STALE );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer derivation = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
derivation.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_POSSIBLY_STALE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.reportChangeConfirmed();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
handler.assertEventCount( 2 );
handler.assertNextEvent( ObservableValueChangeEvent.class, event -> {
assertEquals( event.getObservableValue().getName(), observableValue.getName() );
assertNull( event.getValue() );
} );
handler.assertNextEvent( ObserveScheduleEvent.class,
e -> assertEquals( e.getObserver().getName(), observer.getName() ) );
}
@Test
public void reportChangeConfirmed_generates_spyEvent_withValueWhenIntrospectorPresent()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_POSSIBLY_STALE );
final String expectedValue = ValueUtil.randomString();
final ComputableValue<String> computableValue = context.computable( () -> expectedValue );
computableValue.setValue( expectedValue );
final Observer derivation = computableValue.getObserver();
derivation.setState( Observer.Flags.STATE_UP_TO_DATE );
final ObservableValue<?> observableValue = computableValue.getObservableValue();
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_POSSIBLY_STALE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.reportChangeConfirmed();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
handler.assertEventCount( 2 );
handler.assertNextEvent( ObservableValueChangeEvent.class, event -> {
assertEquals( event.getObservableValue().getName(), observableValue.getName() );
assertEquals( event.getValue(), expectedValue );
} );
handler.assertNextEvent( ObserveScheduleEvent.class,
e -> assertEquals( e.getObserver().getName(), observer.getName() ) );
}
@Test
public void reportChangeConfirmed_generates_spyEvents_for_each_call()
{
final ArezContext context = Arez.context();
final Observer observer = newReadWriteObserver( context );
setCurrentTransaction( observer );
observer.setState( Observer.Flags.STATE_POSSIBLY_STALE );
final ComputableValue<String> computableValue = context.computable( () -> "" );
final Observer derivation = computableValue.getObserver();
final ObservableValue<?> observableValue = computableValue.getObservableValue();
derivation.setState( Observer.Flags.STATE_UP_TO_DATE );
observableValue.setLeastStaleObserverState( Observer.Flags.STATE_POSSIBLY_STALE );
observableValue.addObserver( observer );
observer.getDependencies().add( observableValue );
assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() );
assertEquals( context.getTransaction().safeGetObservables().size(), 0 );
final TestSpyEventHandler handler = TestSpyEventHandler.subscribe();
observableValue.reportChangeConfirmed();
observableValue.reportChangeConfirmed();
observableValue.reportChangeConfirmed();
assertEquals( observer.getState(), Observer.Flags.STATE_STALE );
handler.assertEventCount( 4 );
handler.assertNextEvent( ObservableValueChangeEvent.class,
e -> assertEquals( e.getObservableValue().getName(), observableValue.getName() ) );
handler.assertNextEvent( ObserveScheduleEvent.class,
e -> assertEquals( e.getObserver().getName(), observer.getName() ) );
handler.assertNextEvent( ObservableValueChangeEvent.class,
e -> assertEquals( e.getObservableValue().getName(), observableValue.getName() ) );
handler.assertNextEvent( ObservableValueChangeEvent.class,
e -> assertEquals( e.getObservableValue().getName(), observableValue.getName() ) );
}
@Test
public void introspectors()
throws Throwable
{
final AtomicReference<String> value = new AtomicReference<>();
final String initialValue = ValueUtil.randomString();
value.set( initialValue );
final ObservableValue<?> observableValue =
new ObservableValue<>( Arez.context(), null, ValueUtil.randomString(), null, value::get, value::set );
assertNotNull( observableValue.getAccessor() );
assertNotNull( observableValue.getMutator() );
assertEquals( observableValue.getAccessor().get(), initialValue );
final String secondValue = ValueUtil.randomString();
value.set( secondValue );
assertEquals( observableValue.getAccessor().get(), secondValue );
}
@Test
public void asInfo()
{
final ObservableValue<String> observableValue = Arez.context().observable();
final ObservableValueInfo info = observableValue.asInfo();
assertEquals( info.getName(), observableValue.getName() );
}
@Test
public void asInfo_spyDisabled()
{
ArezTestUtil.disableSpies();
final ObservableValue<String> observableValue = Arez.context().observable();
assertInvariantFailure( observableValue::asInfo,
"Arez-0196: ObservableValue.asInfo() invoked but Arez.areSpiesEnabled() returned false." );
}
}
| [
"peter@realityforge.org"
] | peter@realityforge.org |
62507759fb4b2cf43d6afe0a6157c318b4c2c43c | 3b14e1a8b7764e2bc216040adc7eab9a7d8cd25d | /app/src/main/java/com/example/aidlservicetest/Person.java | 6e79db7c393b0b4a08f755e24caf5b00afc3a46b | [] | no_license | StarsAaron/AIDLClientTest | 50a43e70f5c48f3ba7a44e68a7a7a59b7f04285c | 511801c6026a0d83d9dd9cbd470d7c70473001c2 | refs/heads/master | 2021-01-20T20:42:23.013259 | 2016-06-15T11:10:10 | 2016-06-15T11:10:10 | 61,201,773 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,505 | java | package com.example.aidlservicetest;
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
private String name;//名字
private int sex;//性别
public Person(){}
//从Parcel解析出Person
protected Person(Parcel in) {
readFromParcel(in);
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
//注意读取变量和写入变量的顺序应该一致 不然得不到正确的结果
parcel.writeString(name);
parcel.writeInt(sex);
}
//注意读取变量和写入变量的顺序应该一致 不然得不到正确的结果
public void readFromParcel(Parcel source) {
name = source.readString();
sex = source.readInt();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
@Override
public String toString() {
return "name=" + name +", sex=" + sex;
}
}
| [
"100@"
] | 100@ |
6c9ab60c7571de71e4f7c4e5178c83100e7b29f7 | 33d123b375f86bd5f95affbad5cc7a3941ec3f3d | /src/main/java/net/ryanland/empire/bot/command/executor/checks/impl/DisabledCheck.java | c7832e4b418f2def0d2ea754dc681c3c723b273b | [
"Apache-2.0"
] | permissive | General-Mudkip/EmpireBot | 9c77195d7fc5aa5091ea245e91766b8404a33ec8 | 9f61b0f6f90a54cccc021d5b36d6db515022c6aa | refs/heads/master | 2023-07-15T20:30:11.817284 | 2021-08-23T17:49:43 | 2021-08-23T17:49:43 | 393,718,682 | 0 | 0 | null | 2021-08-20T14:07:02 | 2021-08-07T15:20:53 | Java | UTF-8 | Java | false | false | 686 | java | package net.ryanland.empire.bot.command.executor.checks.impl;
import net.ryanland.empire.bot.command.executor.checks.CommandCheck;
import net.ryanland.empire.bot.events.CommandEvent;
import net.ryanland.empire.sys.message.builders.PresetBuilder;
import net.ryanland.empire.sys.message.builders.PresetType;
public class DisabledCheck extends CommandCheck {
@Override
public boolean check(CommandEvent event) {
return event.getCommand().isDisabled();
}
@Override
public PresetBuilder buildMessage(CommandEvent event) {
return new PresetBuilder(
PresetType.ERROR, "This command is currently disabled.", "Disabled"
);
}
}
| [
"ryanlandofficial@hotmail.com"
] | ryanlandofficial@hotmail.com |
02baa73e993796b53bf9aa98cadac9ec79cb7c0d | 2bf635753ddaf497f42909c28e3c84e0491aa6b6 | /src/behaviour/AttackerBehaviour.java | aaada563bed2aeabd2df59876bbc711cfb239977 | [] | no_license | pmscosta/distributed-ai | 4925bce38128f7d47cf1276b5be8bdef76b072e2 | e4801a906ce35cc544f296f1e9805fa631c8bbf5 | refs/heads/master | 2022-03-27T01:06:50.874032 | 2019-12-14T21:14:09 | 2019-12-14T21:14:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,911 | java | package behaviour;
import agents.Attacker;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.FIPAAgentManagement.AMSAgentDescription;
import jade.lang.acl.ACLMessage;
import protocol.ACLObjectMessage;
import utils.AttackVector;
import utils.Resource;
import utils.Resource.ResourceType;
import utils.Logger;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
public class AttackerBehaviour extends TickerBehaviour {
private static final int DEFAULT_TIME = 5000;
private static final int MIN_STEAL_AMOUNT = 0;
private static final int MAX_STEAL_AMOUNT = 12;
final Attacker attacker;
public AttackerBehaviour(Attacker attacker) {
super(attacker, DEFAULT_TIME);
this.attacker = attacker;
}
public AttackVector buildAttackVector() {
return new AttackVector(attacker.getAttackedResourcesPercentage());
}
@Override
protected void onTick() {
AttackVector attack_vector = buildAttackVector();
try {
ACLObjectMessage msg = new ACLObjectMessage(ACLMessage.CFP, attack_vector);
msg.setPerformative(ACLMessage.INFORM);
msg.setOntology("attack");
AMSAgentDescription[] village_descriptions = attacker.findVillages();
if (village_descriptions.length == 0) {
return;
}
msg.addReceiver(
village_descriptions[ThreadLocalRandom.current().nextInt(village_descriptions.length)].getName()
);
this.myAgent.send(msg);
Logger.getInstance().add(String.format(
"[Attacker Attacking] Attacking with Attack Vector: [%d]\n",
attack_vector.getVector()
));
} catch (IOException e) {
e.printStackTrace();
}
}
} | [
"up201606746@fe.up.pt"
] | up201606746@fe.up.pt |
88ee81f85bfe88ffe350bc22d163614a5ff02a37 | 3cfe4b3623a298cfa25385036eaf2b6a911d563d | /src/ro/sda/MirroredMatrixAndReversedMatrix.java | d76106ca4af33aa6a472cde668b03bca08ac1680 | [] | no_license | FlorinMarin992/MySDAProject | c790a98f1b6e648edfc431419b5d3e1a2a6abb84 | 77b718618a0b17c7b17ea004498060eb23328b3e | refs/heads/master | 2020-03-07T17:54:11.618746 | 2018-04-01T11:29:59 | 2018-04-01T11:29:59 | 127,623,916 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,780 | java | package ro.sda;
import java.util.Scanner;
public class MirroredMatrixAndReversedMatrix {
public static void main(String[] args) {
System.out.println("Enter matrix size :");
Scanner scanner= new Scanner(System.in);
int n=scanner.nextInt();
System.out.println("Enter the elements of your " + n + " x " + n + " matrix");
int [][] a = new int[n][n];
int [][] b = new int[n][n];
for(int i = 0; i < n ; i++){
for(int j = 0 ; j < n ; j++){
a[i][j] = scanner.nextInt();
}
}
printMatrix(a);
mirrorMatrix(a,b,n);
System.out.println();
printMatrix(b);
System.out.println();
reversedMatrix(a,b,n);
printMatrix(b);
}
public static void printMatrix(int[][] myMatrix) {
for(int i = 0; i < myMatrix.length; i++){
for(int j = 0; j < myMatrix[i].length; j++){
System.out.print(myMatrix[i][j] + " ");
}
System.out.println();
}
}
public static void mirrorMatrix(int[][] myMatrix, int[][] mirroredMatrix, int n){
for(int i = 0; i < n; i ++){
for(int j = 0; j < n; j++){
mirroredMatrix[i][n-1-j]=myMatrix[i][j];
}
}
}
public static void reversedMatrix(int[][] myMatrix, int[][] reversedMatrix, int n) {
int[][] mirroredMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
mirroredMatrix[i][n-1-j]=myMatrix[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
reversedMatrix[n-1-i][j]=mirroredMatrix[i][j];
}
}
}
}
| [
"fmarin992@yahoo.com"
] | fmarin992@yahoo.com |
627668c6169af37a1f20e32f036c6cc2a4d79f18 | e1e219f91271ac82276d1d0bb3119c8af5b3b0ff | /backend/src/main/java/com/journaldev/spring/model/SamlUserDetails.java | f9b21f6573415f097bfa6721a02cf083034228d4 | [] | no_license | upadristasarath/SAML-Okta-Angular | 0501cc2e0f5c4baa0ee98c1885ef52b21d75d8c1 | fd8c809ccc61b2615a87d4d3e459879ecaa4996a | refs/heads/master | 2023-06-19T21:42:35.677612 | 2019-04-12T02:38:34 | 2019-04-12T02:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 919 | java | package com.journaldev.spring.model;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
* @author slemoine
*/
public class SamlUserDetails implements UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return new ArrayList<>();
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
}
| [
"manojp1988@gmail.com"
] | manojp1988@gmail.com |
ddf9a3e081867937de3ff1733afd8e106cc58b83 | 0a4aaf32167acb2eebcfb87892b10776ba8f37cd | /src/Work/HackerRank/Anagrams/Anagrams.java | bc4f252402bb4a523370db85c4486dc72688d0d3 | [] | no_license | pandapirate/LeetCode | b5834603ac4a1b11f9bf17eaa70b7020d9acc01f | 82d8ab5885f5117fb39a11a6145bd1decc4d965e | refs/heads/master | 2021-01-02T09:09:28.962108 | 2015-04-14T18:20:29 | 2015-04-14T18:20:29 | 23,373,715 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,227 | java | package HackerRank.Anagrams;
import java.util.HashMap;
public class Anagrams {
public static void main (String[] args) {
HashMap<String, String> testCase = new HashMap<String, String>();
testCase.put("secure", "rescue");
testCase.put("google", "facebook");
testCase.put("conifers", "fir cones");
for (String s : testCase.keySet()) {
System.out.println(s + " -> " + testCase.get(s) + " : " + isAnagram(s, testCase.get(s)));
}
}
public static boolean isAnagram(String start, String end) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
start = start.replaceAll(" ", "");
end = end.replaceAll(" ", "");
for (int i = 0; i < start.length()-1; i++) {
char c = start.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else
map.put(c, 1);
}
for (int i = 0; i < end.length()-1; i++) {
char c = start.charAt(i);
if (!map.containsKey(c) ) {
return false;
}
if (map.get(c) == 0)
return false;
map.put(c, map.get(c) -1);
}
for (char c : map.keySet()) {
if (map.get(c) != 0) {
return false;
}
}
return true;
}
}
| [
"kevinchh88@gmail.com"
] | kevinchh88@gmail.com |
cd1035205789df362a5fa4b1b20800f84b8d0f61 | 0abc464945701f40a1ba7efac28046c8a75d6a1b | /src/servlet/RemoverCategoriaServlet.java | fe7a08ecd424cdbe85687f18e00607a6d2f5aeb2 | [] | no_license | WellingtonIdeao/RestauranteManager | 7777673a5c76cc00688ccfe09c8f309d1cb3bfdc | 4598d1fc720cb2552acabeb06d1116be6a6d31b5 | refs/heads/master | 2021-01-01T05:13:28.114026 | 2016-05-16T13:33:52 | 2016-05-16T13:33:52 | 58,934,725 | 0 | 1 | null | 2016-05-19T13:39:46 | 2016-05-16T13:32:12 | Java | UTF-8 | Java | false | false | 851 | java | package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Categoria;
import service.CategoriaService;
@WebServlet("/removerCategoriaServlet")
public class RemoverCategoriaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
CategoriaService catServ = new CategoriaService();
Categoria cat = new Categoria();
cat.setId(new Long(id));
catServ.remover(cat);
response.sendRedirect("listarCategoriaServlet");
}
}
| [
"Wellington@Wellington-PC"
] | Wellington@Wellington-PC |
9a27157696db35ff54fd175b5bf4708ed97ba1e7 | 2acd1eeb030b406aee4a249cdac0217229d5f1e7 | /limits-service/src/main/java/com/springcloud/microservices/limitsservice/bean/LimitConfiguration.java | 655f8b2f5fad54471653fcc0ef0ecd3fc02dc2dd | [] | no_license | jaraju/SpringCloudMicroServices | a819fcf9881b3ea9e5feb2b76f35bcfe0ab53405 | f90100d90e54fab5f08e651f5d8942e1b182df16 | refs/heads/master | 2020-06-13T21:03:28.030834 | 2019-07-02T04:16:14 | 2019-07-02T04:16:14 | 194,786,587 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 546 | java | package com.springcloud.microservices.limitsservice.bean;
public class LimitConfiguration {
private int maximum;
private int minimum;
protected LimitConfiguration() {
super();
}
public LimitConfiguration(int maximum, int minimum) {
super();
this.maximum = maximum;
this.minimum = minimum;
}
public int getMaximum() {
return maximum;
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
public int getMinimum() {
return minimum;
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
}
| [
"raju@Appalarajus-MacBook-Pro.local"
] | raju@Appalarajus-MacBook-Pro.local |
95d4ac4f1300f3193370e326e358a4633b9ac4f3 | ee610591ff97d81e4d6b1a25e2c2f9c81dd26da4 | /Load/LoadAdapter.java | d4f2d9bb6d730111d0f35325d9ea58830ef89b6e | [] | no_license | krimasofttech/comparelogisticsp | 84c8e4970c2c9674c5537370175fe414e8b655aa | a72605630565c5933374c198ad800b1c9743030f | refs/heads/master | 2020-12-25T15:18:35.316877 | 2016-06-21T13:24:16 | 2016-06-21T13:24:16 | 61,635,483 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,516 | java | package logistic.compare.comparelogistic.Load;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import logistic.compare.comparelogistic.Adapter.PlaceAPI;
import logistic.compare.comparelogistic.CommonInterface;
import logistic.compare.comparelogistic.R;
/**
* Created by Sony on 4/19/2016.
*/
public class LoadAdapter extends RecyclerView.Adapter<LoadAdapter.MyViewHolder> {
Context mContext;
public ArrayList<String> loadlist;
LayoutInflater inflater;
CommonInterface commonInterface;
public PlaceAPI mPlaceAPI = new PlaceAPI();
public CommonInterface getCommonInterface() {
return commonInterface;
}
public void setCommonInterface(CommonInterface commonInterface) {
this.commonInterface = commonInterface;
}
public LoadAdapter(Context mContext, ArrayList<String> loadlist) {
this.mContext = mContext;
this.loadlist = loadlist;
inflater = LayoutInflater.from(mContext);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(inflater.inflate(R.layout.autocompletetext, parent, false));
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String load = this.loadlist.get(position);
holder.text.setText(load);
holder.rootView.setTag(load);
holder.rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setBackgroundResource(R.drawable.citybackground2);
sendBacktoActivity(v.getTag().toString());
}
});
}
public void sendBacktoActivity(String text) {
this.commonInterface.ReceiveEnquiry(text);
}
@Override
public int getItemCount() {
return this.loadlist.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView icon;
TextView text;
View rootView;
public MyViewHolder(View itemView) {
super(itemView);
rootView = itemView;
icon = (ImageView) itemView.findViewById(R.id.icon);
text = (TextView) itemView.findViewById(R.id.autocompleteText);
}
}
}
| [
"jaypatel171091@gmail.com"
] | jaypatel171091@gmail.com |
4d8e902eb7bed48e5d9c75e74b917acf73315ee3 | 42eefc6527dfce0d3ba90dfdc2f45e4894635be8 | /yese-web/src/main/java/com/chnye/yese/spring/config/WebXmlInitializer.java | c37dc29ff1e86f3106f48c406f8468548768918f | [] | no_license | ztoh/curry-projects | ad1dc8769f590a455a5c35d1e88b06424befda1b | fbd8b30a59bba2c1bbec4cafae80372b2386cef6 | refs/heads/master | 2021-01-12T04:44:44.557864 | 2017-01-01T13:23:55 | 2017-01-01T13:23:55 | 77,779,569 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,704 | java | package com.chnye.yese.spring.config;
import javax.servlet.FilterRegistration;
/**
* Servlet3启动时会自动扫描ServletContainerInitializer的实现类
* Spring提供了一个实现类SpringServletContainerInitializer
* 该类中Spring自动扫描WebApplicationInitializer接口的所有实现类
*/
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import ch.qos.logback.ext.spring.web.LogbackConfigListener;
@Order(1)
public class WebXmlInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container ) throws ServletException {
System.out.println( "*************************WebXmlInitializer.onStartup" );
// TODO Auto-generated method stub
//log4j
// container.setInitParameter("log4jConfigLocation", "classpath:config/log4j.properties" );
// container.addListener( Log4jConfigListener.class );
//slf4j
container.setInitParameter("logbackConfigLocation", "classpath:logback.xml" );
container.addListener( LogbackConfigListener.class );
//XX Servlet
// XServlet xServlet = new XServlet();
// ServletRegistration.Dynamic dynmaic = container.addServlet("xServlet", xServlet );
// dynmaic.setLoadOnStartup( 2 );
// dynmaic.addMapping( "/x_servlet");
// WebApplicationContext context = getRootContext( container );
// container.addListener( new ContextLoaderListener( context ) );
// ServletRegistration.Dynamic dispatcher = container.addServlet("DispatcherServlet", new DispatcherServlet(context));
// dispatcher.setLoadOnStartup(1);
// dispatcher.addMapping("/*");
FilterRegistration.Dynamic filterDynamic = container.addFilter("encodingFilter", new CharacterEncodingFilter() );
filterDynamic.setInitParameter("encoding", "UTF-8");
filterDynamic.setInitParameter("forceEncoding", "true");
filterDynamic.addMappingForUrlPatterns(null, true, "/*");
// DelegatingFilterProxy shiroFilter = new DelegatingFilterProxy();
// shiroFilter.setTargetFilterLifecycle( true );
// container.addFilter("shiroFilter", shiroFilter ).addMappingForUrlPatterns( null, false, "/*");
}
// private AnnotationConfigWebApplicationContext getRootContext( ServletContext container ) {
// AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
// context.register( ServletConfig.class );
// context.setServletContext( container );
// return context;
// }
}
| [
"bolonzhang@gmail.com"
] | bolonzhang@gmail.com |
9f7b4b1a67460f7e978f6fd35dd72d333144e5ed | 974720f7480e8ee8c978026af0e865dede7ed0e5 | /src/main/java/com/example/domain/Article.java | eab9fdeff6b865dfe1cd77bfa0c34bdce4f4978e | [] | no_license | rakus-inadayutaka0707/teamBBS | 0822b642aee05286be2bd116d52e8a296a4bc11e | cc80a1e1149bb984c9ed3bc1d348dc18b8aa6f66 | refs/heads/main | 2023-07-18T09:02:39.986868 | 2021-08-27T06:33:02 | 2021-08-27T06:33:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 969 | java | package com.example.domain;
import java.util.List;
/**
* articlesテーブルのDomainクラス.
*
* @author inada
*
*/
public class Article {
/** ID */
private Integer id;
/** 氏名 */
private String name;
/** 記事 */
private String content;
/** コメント一覧 */
private List<Comment> commentList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
@Override
public String toString() {
return "Article [id=" + id + ", name=" + name + ", content=" + content + ", commentList=" + commentList + "]";
}
}
| [
"yutaka.inada@rakus-partners.co.jp"
] | yutaka.inada@rakus-partners.co.jp |
8d70b1a7e8ebceb9fc3c6c61082840d403773aac | 5f0a61d5df3ceee6737db4e91960a32217f40e7b | /AOP-master/src/cn/itcast/aop/JDKProxyFactory.java | a209510d9d8e1412eb03ff7cb26c3e3e4c9f99d7 | [] | no_license | andersonnascimento/log4j-customizations | 425c6e13d471ac9bc5e77d41696ee9856defd039 | d2c555d5169a417002d3c6d3691ed91bada8fe8c | refs/heads/master | 2021-01-24T06:30:36.183266 | 2014-06-10T14:00:05 | 2014-06-10T14:00:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 780 | java | package cn.itcast.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import cn.itcast.service.impl.PersonServiceBean;
public class JDKProxyFactory implements InvocationHandler {
private Object targetObject;
public Object createProxyInstance(Object targetObject){
this.targetObject = targetObject;
return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
PersonServiceBean bean = (PersonServiceBean)this.targetObject;
Object result = null;
if(bean.getUser()!= null){
result = method.invoke(targetObject, args);
}
return result;
}
}
| [
"andersonnascimento@ymail.com"
] | andersonnascimento@ymail.com |
499fb2a6bea07180238e78cae681dcc8e0980bc9 | 20d795e75d96f441ce161b78bfed4af0b9e3dd9d | /SourceFiles/Code/FRPG/Monster.java | bde98edfa925d8be05840b2aba760b57d11dd67e | [] | no_license | BraverIncident/finchrpg | 76449c35e0b9d735f3b9491b98de040be6e61cb4 | b1c1fbb2025d7122b01c8530332d64187685f2a4 | refs/heads/master | 2021-01-19T20:43:41.903993 | 2017-04-17T18:45:08 | 2017-04-17T18:45:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 945 | java |
package Code.FRPG;
/**
*
* @author Tim
*/
public abstract class Monster implements Typing{
// TD - Instantiating and constructors created
private int health;
private int combatPower;
private String name;
public Monster(){
health=combatPower=0;
}
public Monster(int h, int c){
health = h;
combatPower = c;
}
public void setHealth(int health){
this.health = health;
}
public int getHealth(){
return health;
}
public void setCombatPower(int combatPower){
this.combatPower = combatPower;
}
public int getCombatPower(){
return combatPower;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public String toString(){
return "Name: " + name + " Health: " + health + " CP: " + combatPower;
}
} | [
"noreply@github.com"
] | BraverIncident.noreply@github.com |
f5fe43a5e1beba7bb595ce2c421f91331e49e6bd | 1e9c9f2a9639db7cdb032aae69cb4d99aef1d3a5 | /codeChef/src/medium/unsolved/TravelingPhotographer.java | 0c79f6db001cf99d6317dde9c0fc2a84baa084d1 | [
"MIT"
] | permissive | sagarnikam123/learnNPractice | f0da3f8acf653e56c591353ab342765a6831698c | 1b3b0cb2cff2f478006626a4c37a99102acbb628 | refs/heads/master | 2023-02-04T11:21:18.211654 | 2023-01-24T14:47:52 | 2023-01-24T14:47:52 | 61,184,927 | 2 | 1 | MIT | 2022-03-06T11:07:18 | 2016-06-15T06:57:19 | Python | UTF-8 | Java | false | false | 2,565 | java | /**
The Traveling Photographer
You are a freelance photographer and you are about to start the busiest day of your career!
There are a number of events happening throughout the city and you want to take a picture of these events to
publish in the local newspaper. The problem is that the events only occur at specific times and it takes time
to travel between locations. Because of this, you may not be able to make it to each event.
So, your goal is to take photos at as many events as possible. Since you only need a single photo of an event
to publish in the newspaper, you may assume it takes essentially no time to document an event.
Locations are points in the plane and will be given by their (x,y) coordinates.
The city is laid out in a grid-like fashion so the time it takes to travel from one location (x,y)
to another location (x',y') is |x-x'| + |y-y'| (the "Manhattan" distance). No two events will simultaneously occur at
the same location, though it is possible that two events occur at the same location at different times of the day.
Finally, you always start the day at the location (0,0).
Input
The first line of the input contains the number of test cases (at most 30).
Each test case begins with a single integer k on a single line indicating the number of events.
The next k lines describe the events, one per line. The i'th such line contains three integers xi, yi, ti
where (xi, yi) describes the location of the event and ti describes the time the event occurs.
You always begin at location (0,0) at time 0.
Bounds: 1 ≤ k ≤ 1000 and for every event i we have |xi|, |yi| ≤ 1,000,000 and 1 ≤ ti ≤ 1,000,000.
Output
For each input you are to output a single line. If you are unable to take photos at any event,
then simply output "No Photos". Otherwise, output two integers separated by a single space.
The first integer is the maximum number of photos you can take (let's call this M).
Then the second integer you should output is the earliest possible time you can take the last of these M photos.
***********************************************************************************************************************
Example
Input:
5
3
1 2 3
2 3 5
3 2 6
3
0 1 1
0 -3 4
0 -4 5
4
0 1 1
0 4 4
0 -2 2
0 -3 3
1
3 4 6
2
5 5 15
-6 -6 12
Output:
2 5
2 5
2 3
No Photos
1 12
**********************************************************************************************************************/
package medium.unsolved;
public class TravelingPhotographer {
public static void main(String[] args) {
}
}
| [
"sagarnikam123@gmail.com"
] | sagarnikam123@gmail.com |
642d2afe1f19148db38930727105dd187be88f21 | 1f7f105fed0c857857ba48461baf791b916bef77 | /490.the-maze.java | 465cbacc26eb2a7942e9562785dda912155afc1e | [] | no_license | CyanideTD/Leetcode | f71f562688c3e362876f6d50ca0707027979aa87 | 9a78313ac75de8a6a6031b235d33f848ba562bc6 | refs/heads/master | 2021-01-23T04:59:09.919953 | 2018-02-01T08:44:22 | 2018-02-01T08:44:22 | 92,946,905 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,502 | java | public class Solution {
class Coordinate {
int x;
int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
int[] directionX = {0, 0, -1, 1};
int[] directionY = {1, -1, 0, 0};
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
if (start[0] == destination[0] && start[1] == destination[1]) {
return true;
}
int n = maze.length;
int m = maze[0].length;
boolean[][] visited = new boolean[n][m];
Queue<Coordinate> queue = new LinkedList<>();
Coordinate begin = new Coordinate(start[0], start[1]);
Coordinate end = new Coordinate(destination[0], destination[1]);
queue.offer(begin);
while (!queue.isEmpty()) {
Coordinate cur = queue.poll();
if (cur.x == destination[0] && cur.y == destination[1]) {
return true;
}
for (int i = 0; i < 4; i++) {
Coordinate next = new Coordinate(cur.x, cur.y);
while (valid(next, n, m) && maze[next.x][next.y] == 0) {
next.x += directionX[i];
next.y += directionY[i];
}
next.x = next.x - directionX[i];
next.y = next.y - directionY[i];
if (next.x == destination[0] && next.y == destination[1]) {
return true;
}
if (visited[next.x][next.y]) {
continue;
} else {
queue.add(next);
visited[next.x][next.y] = true;
}
}
}
return false;
}
public boolean valid(Coordinate next, int n, int m) {
if (next.x >= 0 && next.x < n && next.y >= 0 && next.y < m) {
return true;
} else {
return false;
}
}
}
| [
"qchen10@stevens.edu"
] | qchen10@stevens.edu |
19068dac86571cabaa5a32338da6c490857b00a8 | 81c38dd45838dffa9983df369371557d935fc479 | /src/main/java/com/wulaobo/config/WebConfigurer.java | 46aa83c3d0b7fe133e26d4a63bab02dd52ce1b66 | [] | no_license | YWADMIN/excellentcourse_springboot | cc03eff3be3c11fd48c6ddff9b0efbc60925adfb | 4513054975657b273dbb0bbe92c87479c480e2de | refs/heads/master | 2022-08-16T00:43:03.840698 | 2020-06-03T06:14:21 | 2020-06-03T06:14:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,458 | java | package com.wulaobo.config;
import com.wulaobo.config.interceptors.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
//这个方法用来配置静态资源,如html,css,js等等
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload/");
}
//这个方法用来注册拦截器的,我们编写的拦截器需要在这里添加注册才能生效
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns("/**") 表示拦截所有的请求,
// excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
registry.addInterceptor(loginInterceptor).addPathPatterns("/**").
excludePathPatterns("/","/toLogin","/login","/getAllNews","/toRegister","/register","/getNewsById","/admin","/adminLogin","/static/**");
}
}
| [
"wulaobo@aliyun.com"
] | wulaobo@aliyun.com |
8cf6c2b191626e0b75d0015a611c46b2f42eccfa | 29ffee0608a635870909f55083b84c6ac2a3085a | /reprotool-prediction/src/reprotool/dmodel/extensions/Combinations.java | 980228cc9f5b20989c6cd2da6c40382debe5092a | [] | no_license | vsimko/ese-nlp-tools | 49b880a4377ac214e4d6930e18c41d8d9852b60f | f4d7d38af41ee5684efbb78759dd85179d4ed754 | refs/heads/master | 2021-01-10T01:32:36.382424 | 2018-11-12T14:12:13 | 2018-11-12T14:12:13 | 51,915,711 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,313 | java | package reprotool.dmodel.extensions;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.Pair;
/**
* Based on the Combinadic Algorithm explained by James McCaffrey in the MSDN
* article titled: "Generating the mth Lexicographical Element of a Mathematical
* Combination" http://msdn.microsoft.com/en-us/library/aa289166(VS.71).aspx
*
* @author Ahmed Abdelkader Licensed under Creative Commons Attribution 3.0
* http://creativecommons.org/licenses/by/3.0/us/
*
* @author Viliam Simko : reimplemented using BigIntegers, added randomCombinations() which
* generates a random subset of all combinations C(n,k)
*/
final public class Combinations {
/**
* Returns the m-th lexicographic element of combination C(n,k)
*/
final public static int[] element(final int n, final int k, final BigInteger m) {
final int[] ans = new int[k];
int a = n;
int b = k;
BigInteger x = choose(n, k).subtract(m).subtract(BigInteger.ONE); // x is the "dual" of m
for (int i = 0; i < k; ++i) {
a = largestV(a, b, x); // largest value v, where v < a and vCb < x
x = x.subtract(choose(a, b));
b = b - 1;
ans[i] = (n - 1) - a;
}
return ans;
}
/**
* Useful for small values of m.
*/
final private static int[] element(final int n, final int k, final int m) {
return element(n, k, BigInteger.valueOf(m));
}
/**
* Returns the largest value v where v < a and Choose(v,b) <= x
*/
private static int largestV(final int a, final int b, final BigInteger x) {
int v = a - 1;
while (choose(v, b).compareTo(x) > 0)
--v;
return v;
}
/**
* Returns nCk - watch out for overflows
*/
final public static BigInteger choose(final int n, final int k) {
if (n < 0 || k < 0)
return BigInteger.valueOf(-1);
if (n < k)
return BigInteger.ZERO;
if (n == k || k == 0)
return BigInteger.ONE;
final BigInteger delta;
final int iMax;
if (k < n - k) {
delta = BigInteger.valueOf(n - k);
iMax = k;
} else {
delta = BigInteger.valueOf(k);
iMax = n - k;
}
BigInteger ans = delta.add( BigInteger.ONE );
for (int i = 2; i <= iMax; ++i) {
final BigInteger ibig = BigInteger.valueOf(i);
ans = ans.multiply( delta.add(ibig) ).divide(ibig);
}
return ans;
}
final private static Random rnd = new Random();
final private static BigInteger rndBigInt(final BigInteger max) {
do {
final BigInteger i = new BigInteger(max.bitLength(), rnd);
if (i.compareTo(max) <= 0)
return i;
} while (true);
}
// only for debugging purposes
private static long numCollisions = 0;
final public long getNumCollisions() {
return numCollisions;
}
private static int ESTIMATED_MAX_COLLISIONS_FACTOR = 5;
/**
* @author Viliam Simko
*/
final public static int[][] randomCombinations(final int n, final int k, int howmany) {
final BigInteger total = choose(n, k);
final BigInteger totalMinus1 = total.subtract(BigInteger.ONE);
if(total.compareTo(BigInteger.valueOf(howmany)) < 0)
howmany = total.intValue();
final int[][] buf = new int[howmany][k];
int bufidx = 0;
// las vegas algorithm
final Set<String> seen = new HashSet<>();
numCollisions = 0; // for debugging
final long maxCollisions = howmany * ESTIMATED_MAX_COLLISIONS_FACTOR; // estimated worst case
while(bufidx < howmany) {
final int[] subset = element(n, k, rndBigInt(totalMinus1));
final String subsethash = Arrays.toString(subset);
if(seen.add(subsethash)) {
buf[bufidx] = subset;
bufidx++;
} else {
numCollisions++;
// this prevents infinite loops if the las vegas approach fails
if(numCollisions > maxCollisions) {
throw new RuntimeException("Our las vegas algorithm exceeded the estimated worst case scenario where maxCollisions=" + maxCollisions);
}
}
}
return buf;
}
/**
* @author Viliam Simko
*/
final public static List<List<Integer>> randomCombinationsAsList(final int n, final int k, final int howmany) {
final List<List<Integer>> result = new ArrayList<>();
for(final int[] subset : randomCombinations(n, k, howmany)) {
final List<Integer> subsetAsList = new ArrayList<>();
for (final int item : subset) {
subsetAsList.add(item);
}
result.add(subsetAsList);
}
return result;
}
final public static <T> List<List<T>> generateCombin(final List<T> allItems, final int k) {
final int n = allItems.size();
final int total = choose(n, k).intValue();
final List<List<T>> result = new ArrayList<>();
// systematically generate all combinations COMBIN(N,K)
for(int m=0; m<total; ++m) {
final int[] combidx = element(n, k, m); // a single combination of indexes
final List<T> combitem = new ArrayList<>(k);
for(int i=0; i<k; ++i) {
combitem.add( allItems.get(combidx[i]) );
}
result.add(combitem);
}
return result;
}
final public static <T> Iterable<Pair<T, T>> generateCombinPairs(final Iterable<T> allItems) {
final List<List<T>> combin = generateCombin( IterableExtensions.toList(allItems), 2);
final List<Pair<T,T>> result = new ArrayList<>();
for (final List<T> pair : combin) {
result.add(Pair.of(pair.get(0), pair.get(1)));
}
return result;
}
final public static <T> List<List<T>> generateVariations(final List<T> allItems, final int k) {
List<List<T>> result = new ArrayList<>();
result.add(new ArrayList<T>());
for(int i=0; i<k; ++i) {
final List<List<T>> tmp = new ArrayList<>(k);
for (final List<T> list : result) {
for (T item : allItems) {
final List<T> copyOfList = new ArrayList<>(list);
copyOfList.add(item);
tmp.add(copyOfList);
}
}
result = tmp;
}
return result;
}
final public static <T> Iterable<Pair<T, T>> generateVariationsPairs(final Iterable<T> allItems) {
final List<List<T>> variations = generateVariations( IterableExtensions.toList(allItems), 2);
final List<Pair<T,T>> result = new ArrayList<>();
for (final List<T> pair : variations) {
result.add(Pair.of(pair.get(0), pair.get(1)));
}
return result;
}
} | [
"simko@d3s.mff.cuni.cz"
] | simko@d3s.mff.cuni.cz |
d35e3d8cfff3c8237fd76e843fcb97a9e0a79816 | f51962e34b90843687ddcb75cb6c1c9d862094ee | /app/src/main/java/com/example/bottomsheet/MainActivity.java | 014eccba1926ecf32d70067fb4511ee916ab0152 | [] | no_license | McaSamrat/BottomSheet | 714a4676d1bf9a92342008c27cd3de658568bf42 | 951151ef3673b66ca5d0f9f1b72caa625d35de33 | refs/heads/master | 2020-12-04T03:44:23.804106 | 2020-01-03T13:33:44 | 2020-01-03T13:33:44 | 231,595,402 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,781 | java | package com.example.bottomsheet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements ItemAdapter.ItemListener{
BottomSheetBehavior behavior;
RecyclerView mRecyclerView;
private ItemAdapter itemAdapter;
CoordinatorLayout coordinatorLayout;
Toolbar toolbar;
View bottomSheet;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeView();
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
ArrayList<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
items.add("Item 4");
items.add("Item 5");
items.add("Item 6");
itemAdapter = new ItemAdapter(items,this);
mRecyclerView.setAdapter(itemAdapter);
onClickListener();
}
private void onClickListener() {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View view, int i) {
}
@Override
public void onSlide(@NonNull View view, float v) {
}
});
}
private void initializeView() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = findViewById(R.id.bottomSheetLayout);
bottomSheet = findViewById(R.id.linearBottomSheet);
mRecyclerView = findViewById(R.id.recyclerView);
button = findViewById(R.id.mainButton);
}
@Override
public void onItemClick(String item) {
Snackbar.make(coordinatorLayout, item + " is selected", Snackbar.LENGTH_LONG).setAction("Action", null).show();
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
| [
"samrat.b@encoders.co.in"
] | samrat.b@encoders.co.in |
5aeb5e62bced2bc055562a216e5cc7e7683661f3 | 6715ac83996a8bc14951bb67e9fe146c9645009a | /src/test/java/TestNG_Project/Bank.java | 4d90b9d7def1ad1d6c354ccd02eef95d843b4c07 | [] | no_license | Seleniumtesting123/new | 14f20f3bcca78642baee38da685aab35853082d3 | 3a807c979686ec91ca13f889b2baaf64adb15a88 | refs/heads/master | 2020-05-22T13:20:23.811979 | 2019-05-13T06:32:33 | 2019-05-13T06:32:33 | 186,357,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 714 | java | package TestNG_Project;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Bank {
WebDriver driver ;
@Test
public void Login()
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lenovo\\Desktop\\selenium-java-3.141.59\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://demo.guru99.com/V1/html/Managerhomepage.php");
driver.manage().window().maximize();
driver.findElement(By.linkText("New Customer")).click();
driver.findElement(By.xpath("//input[@type='date']")).sendKeys("10-05-1996");
}
}
| [
"mohammadrahil914@yahoo.com"
] | mohammadrahil914@yahoo.com |
4ef7baddbe551d2cd3b4e4e957f25291d0678f06 | b016e43cbd057f3911ed5215c23a686592d98ff0 | /google-ads/src/main/java/com/google/ads/googleads/v7/errors/ChangeEventErrorProto.java | fe20549fccf6f57a6f3b99fc5449d8bbbaff6414 | [
"Apache-2.0"
] | permissive | devchas/google-ads-java | d53a36cd89f496afedefcb6f057a727ecad4085f | 51474d7f29be641542d68ea406d3268f7fea76ac | refs/heads/master | 2021-12-28T18:39:43.503491 | 2021-08-12T14:56:07 | 2021-08-12T14:56:07 | 169,633,392 | 0 | 1 | Apache-2.0 | 2021-08-12T14:46:32 | 2019-02-07T19:56:58 | Java | UTF-8 | Java | false | true | 2,859 | java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v7/errors/change_event_error.proto
package com.google.ads.googleads.v7.errors;
public final class ChangeEventErrorProto {
private ChangeEventErrorProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v7_errors_ChangeEventErrorEnum_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v7_errors_ChangeEventErrorEnum_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n7google/ads/googleads/v7/errors/change_" +
"event_error.proto\022\036google.ads.googleads." +
"v7.errors\032\034google/api/annotations.proto\"" +
"\324\001\n\024ChangeEventErrorEnum\"\273\001\n\020ChangeEvent" +
"Error\022\017\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN\020\001\022\026\n\022S" +
"TART_DATE_TOO_OLD\020\002\022\036\n\032CHANGE_DATE_RANGE" +
"_INFINITE\020\003\022\036\n\032CHANGE_DATE_RANGE_NEGATIV" +
"E\020\004\022\027\n\023LIMIT_NOT_SPECIFIED\020\005\022\030\n\024INVALID_" +
"LIMIT_CLAUSE\020\006B\360\001\n\"com.google.ads.google" +
"ads.v7.errorsB\025ChangeEventErrorProtoP\001ZD" +
"google.golang.org/genproto/googleapis/ad" +
"s/googleads/v7/errors;errors\242\002\003GAA\252\002\036Goo" +
"gle.Ads.GoogleAds.V7.Errors\312\002\036Google\\Ads" +
"\\GoogleAds\\V7\\Errors\352\002\"Google::Ads::Goog" +
"leAds::V7::Errorsb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_ads_googleads_v7_errors_ChangeEventErrorEnum_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v7_errors_ChangeEventErrorEnum_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v7_errors_ChangeEventErrorEnum_descriptor,
new java.lang.String[] { });
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| [
"noreply@github.com"
] | devchas.noreply@github.com |
809cb11ba25b3a8cb072d4976102c5a41d4f07ea | 0769a546e031880eee50f142f3cd738ec65be8be | /BFTP/src/discovery2.java | d0f547d20719eccec8eb53044c85f37835624cad | [] | no_license | Liangyuefeng/Appliedalgorithm | bb66a7a947202d8a883ad34e680c36ef2a37b528 | fa4b87f7ef78e3db31dbff2f64a4288768b64800 | refs/heads/master | 2020-04-30T12:56:10.568594 | 2019-07-18T22:12:29 | 2019-07-18T22:12:29 | 176,839,798 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,629 | java | import java.util.LinkedList;
public class discovery2 {
// set a bound for the max allowed height of the sequence
public static int bestFoundRecursive = 128;
// array to store the current growth rate of the bamboo
public static int GrowthRate[] = new int[8];
// array to store the current height of each bamboo
public static int values[] = new int[8];
// linkedlist to contain the order of cuts i.e the list of perque 1
public static LinkedList<Integer> orderOfCuts = new LinkedList<Integer>();
// linkedlist to contain the order of cuts i.e the list of perque 2
// public static LinkedList<Integer> orderOfCutsSecond = new LinkedList<Integer>();
// linkedlist to contain the previous values of bamboo shoots before cutting them for perque 1
public static LinkedList<Integer> trackOfValues = new LinkedList<Integer>();
// linkedlist to contain the previous values of bamboo shoots before cutting them for perque 2
// public static LinkedList<Integer> trackOfValuesSecond = new LinkedList<Integer>();
// linkedlist to contain the last picked option for bamboo shoot 1
public static LinkedList<Integer> optionPickedLast = new LinkedList<Integer>();
// linkedlist to contain the last picked option for bamboo shoot 2
// public static LinkedList<Integer> optionPickedLastSecond = new LinkedList<Integer>();
// linkedlist to contain the previously found "most optimal solution"
public static LinkedList<Integer> previousOrderOfCuts = new LinkedList<Integer>();
// set the max value to the best found recursive value
public static int maxValue = bestFoundRecursive;
// set the max amount of iterations of our search alogithm (cut off for sequences that cannot satisfy the best
// best found recursive value)
public static int maxIterations = 2000000000;
// length of the non-repeating sequence we want to find.
public static int lengthWanted = 4000;
public static void main(String[] args)
{
// we have not already failed at finding a repeating sequence
boolean didFail = false;
// we have not already failed at finding a repeating sequence previously
boolean didFailPrevious = false;
// set our growth rates
GrowthRate[0] = 1;
GrowthRate[1] = 2;
GrowthRate[2] = 4;
GrowthRate[3] = 8;
GrowthRate[4] = 16;
GrowthRate[5] = 32;
GrowthRate[6] = 64;
GrowthRate[7] = 128;
do
{
// set our bamboo starting heights
values[0] = 0;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 0;
values[6] = 0;
values[7] = 0;
// reset all our linkedlists
// orderOfCutsSecond.clear();
orderOfCuts.clear();
trackOfValues.clear();
// trackOfValuesSecond.clear();
// optionPickedLastSecond.clear();
optionPickedLast.clear();
// last round we did not reset a cut
boolean lastRoundRemove = false;
// set our current amount of iterations
int howManyIterations = 0;
// while we have not reached the non-repeating length and are less than the max iterations we would like.
while(orderOfCuts.size() <= lengthWanted && howManyIterations <= maxIterations)
{
// set the current amount of bamboo shoots above the restriction on height to be 0 and counts the amount
// that are currently above it.
int howManyAboveThreshhold = 0;
for(int i = 0; i < values.length; i++)
{
values[i] += GrowthRate[i];
if(values[i] + GrowthRate[i]> bestFoundRecursive)
{
howManyAboveThreshhold++;
}
}
// if we have 3 ore more bamboo shoots above our max height restriction on the first cut we have failed
// from the get go, so break out of our loop.
if(howManyAboveThreshhold >= 3 && orderOfCuts.size() == 0)
{
break;
}
// if we are not in the first round and we have 3 or more then reset the last cut.
if(howManyAboveThreshhold >= 3)
{
lastRoundRemove = resetLastRound();
}
// if there are only 2 bamboo's above the height restriction
else if(howManyAboveThreshhold == 2)
{
// if we reset a previous round then we have already tried cutting the 2 bamboo shoots and it has
// not worked so reset this round as well.
if(lastRoundRemove == true)
{
// if we are on the first round then we cannot remove another cut because we are at the base
// so stop.
if(orderOfCuts.size() == 0)
{
break;
}
// reset the round.
lastRoundRemove = resetLastRound();
}
// else find the 2 bamboo shoots that are above the max height restriction and cut them.
else
{
int i = 0;
for(; i < values.length; i++)
{
if(values[i] + GrowthRate[i] > bestFoundRecursive)
{
break;
}
}
int j = i;
for(i = i + 1; i < values.length; i++)
{
if(values[i] + GrowthRate[i]> bestFoundRecursive)
{
break;
}
}
trackOfValues.add(values[j]);
values[j] = 0;
orderOfCuts.add(j);
// trackOfValuesSecond.add(values[i]);
values[i] = 0;
// orderOfCutsSecond.add(i);
lastRoundRemove = false;
}
}
// if we only find one bamboo shoot above the max height then we need to cut this shoot as well as
// any other bamboo shoot.
else if(howManyAboveThreshhold == 1)
{
// if we removed a cut previously then
// if(lastRoundRemove == true)
// {
// find out the cut we chose last for our other bamboo shoot and choose the next one
// int lastOptionPickedSecond = optionPickedLastSecond.removeLast() + 1;
// int i = 0;
// for(i = 0; i < values.length; i++)
// {
// if(values[i] + GrowthRate[i]> bestFoundRecursive)
// {
// break;
// }
// }
// if we are trying to cut the same bamboo shoot for both people add 1 to our "other bamboo"
// if(i == lastOptionPickedSecond)
// {
// lastOptionPickedSecond++;
// }
// if we are still below the index of the last bamboo shoot then cut both chosen bamboo shoots
// if(lastOptionPickedSecond < values.length)
// {
// optionPickedLastSecond.add(lastOptionPickedSecond);
// trackOfValues.add(values[i]);
// values[i] = 0;
// orderOfCuts.add(i);
// trackOfValuesSecond.add(values[lastOptionPickedSecond]);
// values[lastOptionPickedSecond] = 0;
// orderOfCutsSecond.add(lastOptionPickedSecond);
// lastRoundRemove = false;
// }
// else reset the round.
// else
{
if(orderOfCuts.size() == 0)
{
break;
}
lastRoundRemove = resetLastRound();
}
}
// else we did not remove a round previous to this one i.e it is the first time we have encountered
// this specific round instance
else
{
// find the bamboo that is above its height restriction and add it to our cut's
int i = 0;
for(i = 0; i < values.length; i++)
{
if(values[i] + GrowthRate[i]> bestFoundRecursive)
{
trackOfValues.add(values[i]);
values[i] = 0;
orderOfCuts.add(i);
break;
}
}
// if the bamboo that was above our height restriction was at index 0 then set our "other"
// bamboo that we are going to cut to be at index 1
if(i == 0)
{
i++;
}
// else set it to be bamboo at index 0 and add it to our cuts.
else
{
i = 0;
}
// optionPickedLastSecond.add(i);
// trackOfValuesSecond.add(values[i]);
values[i] = 0;
// orderOfCutsSecond.add(i);
lastRoundRemove = false;
}
}
// else there are no bamboo shoots that are not satisfying our bamboo height restriction so we can pick
// two "other" bamboo shoots
// else
{
// if we already been in this instance and found that it dosn't work then try another combination
if(lastRoundRemove == true)
{
// get our last 2 bamboo shoots that we picked previously
int lastOptionPicked = optionPickedLast.removeLast();
// int lastOptionPickedSecond = optionPickedLastSecond.removeLast();
// if the last combination we tried cutting was index 6 and 7 ( we have tried all combinations)
// then check we are not at our base case if we are then stop else reset the round.
// if(lastOptionPicked == values.length - 2 && lastOptionPickedSecond == values.length - 1)
{
if(orderOfCuts.size() == 0)
{
break;
}
// lastRoundRemove = resetLastRound();
// }
// else we still have different combinations we can try
else
{
// if our second option has reached max index then increase the first option by 1 and reset
// the second options index to the first option + 1
// if(lastOptionPickedSecond == values.length - 1)
{
lastRoundRemove = addToCuts(lastOptionPicked + 1, lastOptionPicked + 2);
}
// else just increase the index of our second option.
// else
{
// lastRoundRemove = addToCuts(lastOptionPicked, lastOptionPickedSecond + 1);
}
}
}
// else its the first time we have encountered this instance so try the combination of index (0,1)
// else
{
lastRoundRemove = addToCuts(0, 1);
}
}
// increase the iterations we have done so far.
howManyIterations++;
}
// if we have exited the loop due to reacing the max iterations or because we have reached the base case
// then set didFail to be true and multiply our best found recursive by 2 - 1, if we have already failed once already then exit loop.
if(howManyIterations == maxIterations + 1 || orderOfCuts.size() == 0)
{
System.out.println("Failed to find a non-repeating sequence with minimal height of " + bestFoundRecursive);
if(didFail)
{
didFailPrevious = true;
}
else
{
didFail = true;
bestFoundRecursive = bestFoundRecursive * 2;
}
}
// else we have exited nicely
else
{
// add our two cut perque's together into one perque (makes it easier to test)
LinkedList<Integer> mergedlists = new LinkedList<Integer>();
while(orderOfCuts.size() > 0)
{
mergedlists.add(orderOfCuts.removeFirst());
// mergedlists.add(orderOfCutsSecond.removeFirst());
}
// try to find a repeating sequence in our perque.
mergedlists = findRepeating(mergedlists);
// if we find a repeating sequence (the first element of our perque is not 2000 then)
if(mergedlists.getFirst() != 2000)
{
// Test the repeating sequence independantly on a fixed number of repetitions.
maxValue = testIt(mergedlists);
// print out that we have found a repeating sequence with maxValue and restriction value.
System.out.println("Found repeating sequence with output " + maxValue + " and restriction " + bestFoundRecursive);
// store this sequence
previousOrderOfCuts = mergedlists;
// if our value returned by our testing is less than our current recursive value then set that to be
// our new restriction.
if(maxValue <= bestFoundRecursive)
{
bestFoundRecursive = maxValue;
}
}
// else we failed to find a repeating sequence
else
{
System.out.println("Couldn't find a repeating sequence for height of " + bestFoundRecursive + " (Normally an issue with height being set too high)");
}
// if we have failed previously then try to find a sequence with restriction-1.
if(didFail)
{
bestFoundRecursive--;
}
// else reduce our new restriction by a larger amount.
else
{
bestFoundRecursive = bestFoundRecursive / 2;
}
}
}
while(! didFailPrevious);
// if we have not found a previousOrderOfCuts then tell the user.
if(previousOrderOfCuts.size() == 0)
{
System.out.println("\n\nCouldn't find a repeating sequence, your starting recursive value was too small");
}
// else print out that we have found a minimal (optimal) sequence
// create 2 linkedlists which contain our 2 seperate perque's
else
{
System.out.println("\n\nThe following sequence did not fail and was minimal with max height " + maxValue);
LinkedList<Integer> perqueOne = new LinkedList<Integer>();
LinkedList<Integer> perqueTwo = new LinkedList<Integer>();
maxValue = testIt(previousOrderOfCuts);
System.out.println(maxValue);
while(previousOrderOfCuts.size() > 0)
{
perqueOne.add(previousOrderOfCuts.removeFirst());
perqueTwo.add(previousOrderOfCuts.removeFirst());
}
// try to find smaller repeating sequences for each individual perque
//perqueOne = findRepeatingSingular(perqueOne);
//perqueTwo = findRepeatingSingular(perqueTwo);
// print out our perque.
while(perqueOne.size() > 0 || perqueTwo.size() > 0)
{
if(perqueOne.size() > 0)
{
System.out.print("Perque1.add(" + perqueOne.removeFirst() + ");\t");
}
if(perqueTwo.size() > 0)
{
System.out.println("Perque2.add(" + perqueTwo.removeFirst() + ");");
}
}
}
}
// method to test our sequence independantly
public static int testIt(LinkedList<Integer> testSet)
{
int values2[] = new int[8];
// seperate bamboo height array
values2[0] = 0;
values2[1] = 0;
values2[2] = 0;
values2[3] = 0;
values2[4] = 0;
values2[5] = 0;
values2[6] = 0;
values2[7] = 0;
// set the max value found so far to be 0
int maxValue = 0;
// for 20000 repeats
for(int k = 0; k < 20000; k++)
{
// for all our decided cuts
for(int i = 0; i < testSet.size() / 2; i++)
{
// add our growth rates to each bamboo.
for(int j = 0; j < 8; j++)
{
values2[j] += GrowthRate[j];
}
for(int j = 0; j < 8; j++)
{
if(values2[j] > maxValue)
{
maxValue = values2[j];
}
}
// cut the 2 bamboo shoots we have previously decided on
values2[testSet.get(i * 2)] = 0;
values2[testSet.get((i * 2) + 1)] = 0;
// find the max value.
}
}
return maxValue;
}
// add first and second to our dedicated bamboo cuts
private static boolean addToCuts(int first, int second)
{
optionPickedLast.add(first);
// optionPickedLastSecond.add(second);
trackOfValues.add(values[first]);
values[first] = 0;
orderOfCuts.add(first);
// trackOfValuesSecond.add(values[second]);
values[second] = 0;
// orderOfCutsSecond.add(second);
boolean lastRoundRemove = false;
return lastRoundRemove;
}
// reset the current round.
private static boolean resetLastRound()
{
for(int i = 0; i < values.length; i++)
{
values[i] -= GrowthRate[i];
}
values[orderOfCuts.removeLast()] = trackOfValues.removeLast();
// values[orderOfCutsSecond.removeLast()] = trackOfValuesSecond.removeLast();
for(int i = 0; i < values.length; i++)
{
values[i] -= GrowthRate[i];
}
boolean lastRoundRemove = true;
return lastRoundRemove;
}
// method to find a repeating sequence
private static LinkedList<Integer> findRepeating(LinkedList<Integer> savedOrder)
{
// find out the length of our original sequence.
int sizeOriginal = savedOrder.size();
// remove the first and last 1/3 of the sequence found.
for(int i = 0; i < sizeOriginal / 6; i++)
{
savedOrder.removeFirst();
savedOrder.removeFirst();
savedOrder.removeLast();
savedOrder.removeLast();
}
// set our initial repeating length to 2
int repeatingSequenceLength = 2;
// we have found 0 consecutive repeats.
int consecutiveRepeating = 0;
// while we have not found atleast 10 repeating sequences
while(consecutiveRepeating < 10)
{
// set consecutive repeats to 0
consecutiveRepeating = 0;
// if we can no longer get 10 repeating sequences then state we have not found a repeating sequence.
if(repeatingSequenceLength == (savedOrder.size()/10)+1)
{
savedOrder.clear();
savedOrder.add(2000);
return savedOrder;
}
// set a new displacement value.
int maxDisplacement = savedOrder.size() / repeatingSequenceLength;
// increase our displacement
for(int displacement = 1; displacement < maxDisplacement; displacement++)
{
// check if we have a replicated sequence of length repeating sequencelength for a specific displacement
// value.
boolean foundDiscrepency = false;
for(int i = 0; i < repeatingSequenceLength; i++)
{
if(savedOrder.get(i + (repeatingSequenceLength * displacement)) != savedOrder.get(i))
{
// if we found a discrepency where the sequence has not repeated then flag it and exit.
foundDiscrepency = true;
break;
}
}
// if we havn't found a discrepency then increment how many consecutive repeating sequences by 1.
if(foundDiscrepency == false)
{
consecutiveRepeating++;
}
// else break and try a new sequence.
else
{
break;
}
}
// if we did not reach our consecutive repeating bound then find a larger repeating sequence.
if(consecutiveRepeating < 10)
{
repeatingSequenceLength++;
repeatingSequenceLength++;
}
}
// create a new linkedlist with our new sequence.
LinkedList<Integer> newList = new LinkedList<Integer>();
for(int i = 0; i < repeatingSequenceLength; i++)
{
newList.add(savedOrder.get(i));
}
// return it.
return newList;
}
// for each singular list try to find a smaller repeating sequence.
private static LinkedList<Integer> findRepeatingSingular(LinkedList<Integer> savedOrder)
{
// set our initial repeating length to 1.
int repeatingSequenceLength = 1;
// we have 0 consecutive repeating
int consecutiveRepeating = 0;
// whilst we have less than 2 repeating values.
while(consecutiveRepeating < 2)
{
consecutiveRepeating = 0;
// if we can no longer get 2 consecutive repeating sequences then return our previous repeating sequence.
if(repeatingSequenceLength == savedOrder.size()/2+1)
{
return savedOrder;
}
// else find our max displacement possible
int maxDisplacement = savedOrder.size() / repeatingSequenceLength;
for(int displacement = 1; displacement < maxDisplacement; displacement++)
{
// for each displacement value find out if there is a discrepency if there is then break out
// else increment the amount of consecutive repeating sequences.
boolean foundDiscrepency = false;
for(int i = 0; i < repeatingSequenceLength; i++)
{
if(savedOrder.get(i + (repeatingSequenceLength * displacement)) != savedOrder.get(i))
{
foundDiscrepency = true;
break;
}
}
if(foundDiscrepency == false)
{
consecutiveRepeating++;
}
else
{
break;
}
}
// if the amount of consectutive repeating sequences is less than 2 then increment the length of our
// repeating sequence.
if(consecutiveRepeating < 2)
{
repeatingSequenceLength++;
}
}
// create a new list with our new repeating sequence and return it.
LinkedList<Integer> newList = new LinkedList<Integer>();
for(int i = 0; i < repeatingSequenceLength; i++)
{
newList.add(savedOrder.get(i));
}
return newList;
}
}
| [
"liangyf1013@gmail.com"
] | liangyf1013@gmail.com |
01aa638204f349c374a0e5a19509fec8ab00f86b | 3126f7a42ccd717f3533a3074bc38900d76cf19d | /src/main/java/com/udemy/cursospring/models/Estado.java | 993f0c0eff58b559ed1a9046984abecd63832abb | [] | no_license | JhonatanMota/Spring-Web-Service | 50c47b9fd76eedef0a55cc16b892464f8396ea0f | 83db8788b1fe8937bc2af40a52214349149f3b73 | refs/heads/master | 2020-03-24T05:09:42.949577 | 2018-07-31T13:05:00 | 2018-08-30T12:13:14 | 142,476,844 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 959 | java | package com.udemy.cursospring.models;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.udemy.cursospring.abstractes.AbstractEntity;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Estado extends AbstractEntity {
private String nome;
@OneToMany(mappedBy = "estado")
@JsonBackReference
private List<Cidade> cidades = new ArrayList<>();
public Estado() {
}
public Estado(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<Cidade> getCidades() {
return cidades;
}
public void setCidades(List<Cidade> cidades) {
this.cidades = cidades;
}
}
| [
"savaegt@gmail.com"
] | savaegt@gmail.com |
019f0ce08632df5a17ffe925e490b6014ae2f3f9 | 1979082c6c355649f1c799a276b0866fcc1d2813 | /WordListSQLInteractiveWithSearch/app/src/main/java/com/example/wordlistsqlinteractivewithsearch/EditWordActivity.java | dff5e6c1ea114c3d0818462ccafe07aa62de2890 | [] | no_license | rizkidwimartanto/PBB-Sebelum-UTS | 795d0d30ffff00c3ee3bb35bb96b2bd31ced4aa6 | de8098b22ae58acab83f2baad1696f185071cdba | refs/heads/master | 2023-04-03T09:14:02.666187 | 2021-04-11T13:41:47 | 2021-04-11T13:41:47 | 356,877,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,047 | java | package com.example.wordlistsqlinteractivewithsearch;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
/**
* Activity for entering a new word or editing an existing word.
*/
public class EditWordActivity extends AppCompatActivity {
private static final String TAG = EditWordActivity.class.getSimpleName();
private static final int NO_ID = -99;
private static final String NO_WORD = "";
private EditText mEditWordView;
// Unique tag for the intent reply.
public static final String EXTRA_REPLY = "com.example.android.wordlistsql.REPLY";
int mId = MainActivity.WORD_ADD;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_word);
mEditWordView = (EditText) findViewById(R.id.edit_word);
// Get data sent from calling activity.
Bundle extras = getIntent().getExtras();
// If we are passed content, fill it in for the user to edit.
if (extras != null) {
int id = extras.getInt(WordListAdapter.EXTRA_ID, NO_ID);
String word = extras.getString(WordListAdapter.EXTRA_WORD, NO_WORD);
if (id != NO_ID && word != NO_WORD) {
mId = id;
mEditWordView.setText(word);
}
} // Otherwise, start with empty fields.
}
/* *
* Click handler for the Save button.
* Creates a new intent for the reply, adds the reply message to it as an extra,
* sets the intent result, and closes the activity.
*/
public void returnReply(View view) {
String word = ((EditText) findViewById(R.id.edit_word)).getText().toString();
Intent replyIntent = new Intent();
replyIntent.putExtra(EXTRA_REPLY, word);
replyIntent.putExtra(WordListAdapter.EXTRA_ID, mId);
setResult(RESULT_OK, replyIntent);
finish();
}
}
| [
"rizkidwimartanto@gmail.com"
] | rizkidwimartanto@gmail.com |
b12d83899910ce19c59e48e1f18dd3c5196aa412 | 25d99370ee649a4e208f9261eecb3278141aa64a | /src/week1/les1/opdracht2/Klant.java | 1d083ca78e1ed455325dbedaea32074fa0391365 | [] | no_license | tloader11/TICT-V1OODC-15 | 265e1e39a862b4c49e10b289f4593350a957cc79 | 40db67d34a0cb3bfc16ac1d30fa5bbd0348f668b | refs/heads/master | 2021-05-03T16:47:17.200484 | 2018-06-23T17:53:47 | 2018-06-23T17:53:47 | 120,442,757 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package week1.les1.opdracht2;
/**
* Created by universal on 2/6/2018.
*/
public class Klant
{
private String name;
private String address;
private String plaats;
public Klant(String name, String address, String plaats)
{
this.name = name;
this.address = address;
this.plaats = plaats;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPlaats() {
return plaats;
}
}
| [
"tristan-floyd@hotmail.com"
] | tristan-floyd@hotmail.com |
4e18ae46b80205ececfc20cd76a86504dcc4a0bc | e4846bfe1efe1cb6d4f9da07a1ccb73ca63e1328 | /exercise/src/main/java/com/fetchrewards/exercise/model/Point.java | 0cdb43d4da4d72e671296e8cad4bbde6b2e16e62 | [] | no_license | ahujaprabhpreet/Fetch-Rewards | ba3b1001e1b7bdbf794b73d19fa02b8c8346d07b | d5dfe991942e0b32168ec682b803e07136220a65 | refs/heads/main | 2023-03-03T01:47:09.329713 | 2021-02-10T06:26:12 | 2021-02-10T06:26:12 | 337,627,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 253 | java | package com.fetchrewards.exercise.model;
public class Point {
public Point(){
}
private int points;
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
| [
"ahuja.pra@husky.neu.edu"
] | ahuja.pra@husky.neu.edu |
86e7b4612275308517676995ccd612c88c453996 | 2f9872b6890e4c50310dfcf61b29ae95d7b3b63f | /TipCalc2/app/src/main/java/a/tcalc/CalcActivity.java | 965f13a3c7c492975ab85b05ec2c15893d4b58f4 | [] | no_license | DevAppsX/MobSoft | 52f33b00d19bbdc6254b8b8afc95ba7a7330cb11 | 5f4e6aef91fd626f847dbb775316d9b34be8f69a | refs/heads/master | 2021-07-06T08:28:57.271882 | 2021-04-12T10:15:21 | 2021-04-12T10:15:21 | 231,383,585 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,156 | java | package a.tcalc;
import android.os.Bundle;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import java.text.NumberFormat; // Для форматирования денежных сумм
import static a.tcalc.ThankActivity.EXTRA_TIP;
public class CalcActivity extends AppCompatActivity {
// Форматировщики денежных сумм и процентов
private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
private static final NumberFormat percentFormat = NumberFormat.getPercentInstance();
private double amount = 0.0; // Сумма счёта
private double percent = 0.15; // Процент чаевых по умолчанию.
private EditText et_amount; // Поле для ввода суммы счёта
private SeekBar sb_percent; // Ползунок для процентов
private TextView tv_percent; // Поле для значения процента
private TextView tv_tip; // Поле для суммы чаевых
private TextView tv_total; // Поле для итоговой суммы
private Button b_thank; // Кнопка для вызова второй активности
// Создание объекта калькулятор чаевых:
private Calc tipCalc = new Calc();
// Вызывается метод onCreate при создании активности
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calc_activity);
et_amount = findViewById(R.id.et_amount);
sb_percent = findViewById(R.id.sb_percent);
tv_percent = findViewById(R.id.tv_percent);
tv_tip = findViewById(R.id.tv_tip);
tv_total = findViewById(R.id.tv_total);
b_thank = findViewById(R.id.button);
tv_tip.setText(currencyFormat.format(0)); // Заполнить 0
tv_total.setText(currencyFormat.format(0)); // Заполнить 0
// Определение слушателя для кнопки вызова второй активности:
sb_percent.setOnSeekBarChangeListener(sbListener);
et_amount.addTextChangedListener(amountTextWatcher);
// Интерфейс слушателя нажатия кнопки Button
b_thank.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Создание интента и запуск второй активности:
Intent intent = new Intent(CalcActivity.this, ThankActivity.class);
intent.putExtra(EXTRA_TIP, tipCalc.calculateTip(amount,percent));
startActivity(intent);
}
});
}
// Интерфейс слушателя изменений состояния SeekBar
private final OnSeekBarChangeListener sbListener = new OnSeekBarChangeListener() {
// Обновление процента чаевых и итоговой суммы
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
percent = progress / 100.0; // Назначение процента чаевых
// Вычисление чаевых и общей суммы. Вывод их на экран.
tv_percent.setText(percentFormat.format(percent));
tv_tip.setText(currencyFormat.format(tipCalc.calculateTip(amount,percent)));
tv_total.setText(currencyFormat.format(tipCalc.calculateTotal(amount, percent)));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
};
// Интерфейс слушателя изменений текста в EditText
private final TextWatcher amountTextWatcher = new TextWatcher() {
// Вызывается при изменении пользователем величины счета
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(@NonNull Editable s) {
amount = Double.parseDouble(s.toString());
// Обновление полей с чаевыми и общей суммой в формате денежной величины
tv_tip.setText(currencyFormat.format(tipCalc.calculateTip(amount,percent)));
tv_total.setText(currencyFormat.format(tipCalc.calculateTotal(amount, percent)));
}
@Override
public void beforeTextChanged(
CharSequence s, int start, int count, int after) { }
};
}
| [
"fabdadv@gmai.com"
] | fabdadv@gmai.com |
f34b4722481cdef3ed5bcb133ed429b517499aa2 | 58a6789a014d76437f45a65a3c45383bc9d0e031 | /VirginMobileMinutesChecker/src/com/jaygoel/virginminuteschecker/Globals.java | 3b0b0698f00fd0d236e2171dca2b09e3f0a1c3b2 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause-Views"
] | permissive | drfloob/VirginMobileMinutesChecker | d8e0fc140e4c181b7e6148794f047b7f2e712e25 | 6b1c401985f14af55e04ffd6c82739daf1bf6b02 | refs/heads/master | 2021-01-20T22:47:26.350359 | 2011-03-13T11:50:12 | 2011-03-13T11:50:12 | 1,372,444 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 215 | java | package com.jaygoel.virginminuteschecker;
public class Globals {
public static final String NAME= "VirginMinutesChecker";
public static final String URL= "https://www1.virginmobileusa.com/login/login.do";
} | [
"aj@drfloob.com"
] | aj@drfloob.com |
ae80da8194aabde1a9260574e2347911e8f2af84 | 7c757db5123f2752e9b08f46d13e2f7400b07fb6 | /src/main/java/com/insping/libra/account/AccountType.java | ebb937032e0d1aff33e481524883c189263ce732 | [] | no_license | inspingcc/LibraGameServer | fd782aeac099cc6bdfb3fe499d6832578a59ca74 | 1bff6fa440ba8b1e731c1a9b65a7404ed09efd76 | refs/heads/master | 2021-01-21T12:21:16.128042 | 2017-09-18T06:30:43 | 2017-09-18T06:30:43 | 102,067,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 576 | java | package com.insping.libra.account;
public enum AccountType {
COMMON((byte) 0), EMAIL((byte) 1), PHONENUMBER((byte) 2);
private byte value;
private AccountType(byte value) {
this.value = value;
}
public byte getValue() {
return value;
}
public void setValue(byte value) {
this.value = value;
}
public static AccountType searchType(byte type) {
for (AccountType temp : AccountType.values()) {
if (temp.getValue() == type)
return temp;
}
return null;
}
}
| [
"insping@hotmail.com"
] | insping@hotmail.com |
42dd1f21633a206a19368141f569d0438c9ef6ea | 7ea6218503974431f4ef60a0e620673e92af751d | /admin-console/src/main/java/com/admin/console/app/repository/AuthorityRepository.java | 646863e5cec62c052e127eb2bd1b57102e6d57ac | [] | no_license | srikanthkalvakota/mobileweb | 3236a50fed39975e0d97419a67b6839f4ea3f4a9 | 363ba2512b862e6b13218a8ce53f4bb2c979ac3c | refs/heads/master | 2021-01-23T04:54:05.985808 | 2017-06-15T17:54:44 | 2017-06-15T17:54:44 | 86,255,084 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 300 | java | package com.admin.console.app.repository;
import com.admin.console.app.domain.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the Authority entity.
*/
public interface AuthorityRepository extends JpaRepository<Authority, String> {
}
| [
"ksrikanth11@gmail.com"
] | ksrikanth11@gmail.com |
cc986b18f37cf66f4c12501ae49ac1ca872988bd | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/15/15_2d87bae7fa29e2f0fbf2c1cd986c1bde824554bf/BindingManager/15_2d87bae7fa29e2f0fbf2c1cd986c1bde824554bf_BindingManager_t.java | 660e1abeeaaa34d67db75393f460104205c38935 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 67,421 | java | /*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.bindings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.commands.CommandManager;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.core.commands.contexts.Context;
import org.eclipse.core.commands.contexts.ContextManager;
import org.eclipse.core.commands.contexts.ContextManagerEvent;
import org.eclipse.core.commands.contexts.IContextManagerListener;
import org.eclipse.jface.contexts.IContextIds;
import org.eclipse.jface.util.Util;
import org.eclipse.swt.SWT;
/**
* <p>
* A central repository for bindings -- both in the defined and undefined
* states. Schemes and bindings can be created and retrieved using this manager.
* It is possible to listen to changes in the collection of schemes and bindings
* by adding a listener to the manager.
* </p>
* <p>
* The binding manager is very sensitive to performance. Misusing the manager
* can render an application unenjoyable to use. As such, each of the public
* methods states the current run-time performance. In future releases, it is
* guaranteed that the method will run in at least the stated time constraint --
* though it might get faster. Where possible, we have also tried to be memory
* efficient.
* </p>
*
* @since 3.1
*/
public final class BindingManager implements IContextManagerListener,
ISchemeListener {
/**
* This flag can be set to <code>true</code> if the binding manager should
* print information to <code>System.out</code> when certain boundary
* conditions occur.
*/
public static boolean DEBUG = false;
/**
* The separator character used in locales.
*/
private static final String LOCALE_SEPARATOR = "_"; //$NON-NLS-1$
/**
* </p>
* A utility method for adding entries to a map. The map is checked for
* entries at the key. If such an entry exists, it is expected to be a
* <code>Collection</code>. The value is then appended to the collection.
* If no such entry exists, then a collection is created, and the value
* added to the collection.
* </p>
*
* @param map
* The map to modify; if this value is <code>null</code>, then
* this method simply returns.
* @param key
* The key to look up in the map; may be <code>null</code>.
* @param value
* The value to look up in the map; may be <code>null</code>.
*/
private static final void addReverseLookup(final Map map, final Object key,
final Object value) {
if (map == null) {
return;
}
final Object currentValue = map.get(key);
if (currentValue != null) {
final Collection values = (Collection) currentValue;
values.add(value);
} else { // currentValue == null
final Collection values = new ArrayList(1);
values.add(value);
map.put(key, values);
}
}
/**
* <p>
* Takes a fully-specified string, and converts it into an array of
* increasingly less-specific strings. So, for example, "en_GB" would become
* ["en_GB", "en", "", null].
* </p>
* <p>
* This method runs in linear time (O(n)) over the length of the string.
* </p>
*
* @param string
* The string to break apart into its less specific components;
* should not be <code>null</code>.
* @param separator
* The separator that indicates a separation between a degrees of
* specificity; should not be <code>null</code>.
* @return An array of strings from the most specific (i.e.,
* <code>string</code>) to the least specific (i.e.,
* <code>null</code>).
*/
private static final String[] expand(String string, final String separator) {
// Test for boundary conditions.
if (string == null || separator == null) {
return new String[0];
}
final List strings = new ArrayList();
final StringBuffer stringBuffer = new StringBuffer();
string = string.trim(); // remove whitespace
if (string.length() > 0) {
final StringTokenizer stringTokenizer = new StringTokenizer(string,
separator);
while (stringTokenizer.hasMoreElements()) {
if (stringBuffer.length() > 0)
stringBuffer.append(separator);
stringBuffer.append(((String) stringTokenizer.nextElement())
.trim());
strings.add(stringBuffer.toString());
}
}
Collections.reverse(strings);
strings.add(Util.ZERO_LENGTH_STRING);
strings.add(null);
return (String[]) strings.toArray(new String[strings.size()]);
}
/**
* The active bindings. This is a map of triggers (
* <code>TriggerSequence</code>) to bindings (<code>Binding</code>).
* This value will only be <code>null</code> if the active bindings have
* not yet been computed. Otherwise, this value may be empty.
*/
private Map activeBindings = null;
/**
* The active bindings indexed by fully-parameterized commands. This is a
* map of fully-parameterized commands (<code>ParameterizedCommand</code>)
* to triggers ( <code>TriggerSequence</code>). This value will only be
* <code>null</code> if the active bindings have not yet been computed.
* Otherwise, this value may be empty.
*/
private Map activeBindingsByParameterizedCommand = null;
/**
* The scheme that is currently active. An active scheme is the one that is
* currently dictating which bindings will actually work. This value may be
* <code>null</code> if there is no active scheme. If the active scheme
* becomes undefined, then this should automatically revert to
* <code>null</code>.
*/
private Scheme activeScheme = null;
/**
* The array of scheme identifiers, starting with the active scheme and
* moving up through its parents. This value may be <code>null</code> if
* there is no active scheme.
*/
private String[] activeSchemeIds = null;
/**
* The number of bindings in the <code>bindings</code> array.
*/
private int bindingCount = 0;
/**
* The array of all bindings currently handled by this manager. This array
* is the raw list of bindings, as provided to this manager. This value may
* be <code>null</code> if there are no bindings. The size of this array
* is not necessarily the number of bindings.
*/
private Binding[] bindings = null;
/**
* A cache of the bindings previously computed by this manager. This value
* may be empty, but it is never <code>null</code>. This is a map of
* <code>CachedBindingSet</code> to <code>CachedBindingSet</code>.
*/
private Map cachedBindings = new HashMap();
/**
* The command manager for this binding manager. This manager is only needed
* for the <code>getActiveBindingsFor(String)</code> method. This value is
* guaranteed to never be <code>null</code>.
*/
private final CommandManager commandManager;
/**
* The context manager for this binding manager. For a binding manager to
* function, it needs to listen for changes to the contexts. This value is
* guaranteed to never be <code>null</code>.
*/
private final ContextManager contextManager;
/**
* The number of defined schemes.
*/
private int definedSchemeCount = 0;
/**
* The set of all schemes that are defined. This value may be empty, and it
* may be <code>null</code>. There are only
* <code>definedSchemeCount</code> real values in the array. The rest are
* all <code>null</code>.
*/
private Scheme[] definedSchemes = null;
/**
* The collection of listener to this binding manager. This collection is
* <code>null</code> if there are no listeners.
*/
private Collection listeners = null;
/**
* The locale for this manager. This defaults to the current locale. The
* value will never be <code>null</code>.
*/
private String locale = Locale.getDefault().toString();
/**
* The array of locales, starting with the active locale and moving up
* through less specific representations of the locale. For example,
* ["en_US", "en", "", null]. This value will never be <code>null</code>.
*/
private String[] locales = expand(locale, LOCALE_SEPARATOR);
/**
* The platform for this manager. This defaults to the current platform. The
* value will never be <code>null</code>.
*/
private String platform = SWT.getPlatform();
/**
* The array of platforms, starting with the active platform and moving up
* through less specific representations of the platform. For example,
* ["gtk", "", null]. This value will never be <code>null,/code>.
*/
private String[] platforms = expand(platform, Util.ZERO_LENGTH_STRING);
/**
* A map of prefixes (<code>TriggerSequence</code>) to a map of
* available completions (possibly <code>null</code>, which means there
* is an exact match). The available completions is a map of trigger (<code>TriggerSequence</code>)
* to bindings (<code>Binding</code>). This value may be
* <code>null</code> if there is no existing solution.
*/
private Map prefixTable = null;
/**
* The map of scheme identifiers (<code>String</code>) to scheme (
* <code>Scheme</code>). This value may be empty, but is never
* <code>null</code>.
*/
private final Map schemesById = new HashMap();
/**
* <p>
* Constructs a new instance of <code>BindingManager</code>.
* </p>
* <p>
* This method completes in amortized constant time (O(1)).
* </p>
*
* @param contextManager
* The context manager that will support this binding manager.
* This value must not be <code>null</code>.
* @param commandManager
* The command manager that will support this binding manager.
* This value must not be <code>null</code>.
*/
public BindingManager(final ContextManager contextManager,
final CommandManager commandManager) {
if (contextManager == null) {
throw new NullPointerException(
"A binding manager requires a context manager"); //$NON-NLS-1$
}
if (commandManager == null) {
throw new NullPointerException(
"A binding manager requires a command manager"); //$NON-NLS-1$
}
this.contextManager = contextManager;
contextManager.addContextManagerListener(this);
this.commandManager = commandManager;
}
/**
* <p>
* Adds a single new binding to the existing array of bindings. If the array is
* currently <code>null</code>, then a new array is created and this
* binding is added to it. This method does not detect duplicates.
* </p>
* <p>
* This method completes in amortized <code>O(1)</code>.
* </p>
*
* @param binding
* The binding to be added; must not be <code>null</code>.
*/
public final void addBinding(final Binding binding) {
if (binding == null) {
throw new NullPointerException("Cannot add a null binding"); //$NON-NLS-1$
}
if (bindings == null) {
bindings = new Binding[1];
} else if (bindingCount >= bindings.length) {
final Binding[] oldBindings = bindings;
bindings = new Binding[oldBindings.length * 2];
System.arraycopy(oldBindings, 0, bindings, 0, oldBindings.length);
}
bindings[bindingCount++] = binding;
clearCache();
}
/**
* <p>
* Adds a listener to this binding manager. The listener will be notified
* when the set of defined schemes or bindings changes. This can be used to
* track the global appearance and disappearance of bindings.
* </p>
* <p>
* This method completes in amortized constant time (<code>O(1)</code>).
* </p>
*
* @param listener
* The listener to attach; must not be <code>null</code>.
*/
public final void addBindingManagerListener(
final IBindingManagerListener listener) {
if (listener == null) {
throw new NullPointerException();
}
if (listeners == null) {
listeners = new HashSet();
}
listeners.add(listener);
}
/**
* <p>
* Builds a prefix table look-up for a map of active bindings.
* </p>
* <p>
* This method takes <code>O(mn)</code>, where <code>m</code> is the
* length of the trigger sequences and <code>n</code> is the number of
* bindings.
* </p>
*
* @param activeBindings
* The map of triggers (<code>TriggerSequence</code>) to
* command ids (<code>String</code>) which are currently
* active. This value may be <code>null</code> if there are no
* active bindings, and it may be empty. It must not be
* <code>null</code>.
* @return A map of prefixes (<code>TriggerSequence</code>) to a map of
* available completions (possibly <code>null</code>, which means
* there is an exact match). The available completions is a map of
* trigger (<code>TriggerSequence</code>) to command identifier (<code>String</code>).
* This value will never be <code>null</code>, but may be empty.
*/
private final Map buildPrefixTable(final Map activeBindings) {
final Map prefixTable = new HashMap();
final Iterator bindingItr = activeBindings.entrySet().iterator();
while (bindingItr.hasNext()) {
final Map.Entry entry = (Map.Entry) bindingItr.next();
final TriggerSequence triggerSequence = (TriggerSequence) entry
.getKey();
// Add the perfect match.
if (!prefixTable.containsKey(triggerSequence)) {
prefixTable.put(triggerSequence, null);
}
final TriggerSequence[] prefixes = triggerSequence.getPrefixes();
final int prefixesLength = prefixes.length;
if (prefixesLength == 0) {
continue;
}
// Break apart the trigger sequence.
final Binding binding = (Binding) entry.getValue();
for (int i = 0; i < prefixesLength; i++) {
final TriggerSequence prefix = prefixes[i];
final Object value = prefixTable.get(prefix);
if ((prefixTable.containsKey(prefix)) && (value instanceof Map)) {
((Map) value).put(triggerSequence, binding);
} else {
final Map map = new HashMap();
prefixTable.put(prefix, map);
map.put(triggerSequence, binding);
}
}
}
return prefixTable;
}
/**
* <p>
* Clears the cache, and the existing solution. If debugging is turned on,
* then this will also print a message to standard out.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*/
private final void clearCache() {
if (DEBUG) {
System.out.println("BINDINGS >> Clearing cache"); //$NON-NLS-1$
}
cachedBindings.clear();
clearSolution();
}
/**
* <p>
* Clears the existing solution.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
*/
private final void clearSolution() {
setActiveBindings(null, null, null);
}
/**
* <p>
* Computes the bindings given the context tree, and inserts them into the
* <code>commandIdsByTrigger</code>. It is assumed that
* <code>locales</code>,<code>platforsm</code> and
* <code>schemeIds</code> correctly reflect the state of the application.
* This method does not deal with caching.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @param activeContextTree
* The map representing the tree of active contexts. The map is
* one of child to parent, each being a context id (
* <code>String</code>). The keys are never <code>null</code>,
* but the values may be (i.e., no parent). This map may be
* empty. It may be <code>null</code> if we shouldn't consider
* contexts.
* @param bindingsByTrigger
* The empty of map that is intended to be filled with triggers (
* <code>TriggerSequence</code>) to bindings (
* <code>Binding</code>). This value must not be
* <code>null</code> and must be empty.
* @param triggersByCommandId
* The empty of map that is intended to be filled with command
* identifiers (<code>String</code>) to triggers (
* <code>TriggerSequence</code>). This value must either be
* <code>null</code> (indicating that these values are not
* needed), or empty (indicating that this map should be
* computed).
*/
private final void computeBindings(final Map activeContextTree,
final Map bindingsByTrigger, final Map triggersByCommandId) {
/*
* FIRST PASS: Remove all of the bindings that are marking deletions.
*/
final Binding[] trimmedBindings = removeDeletions(bindings);
/*
* SECOND PASS: Just throw in bindings that match the current state. If
* there is more than one match for a binding, then create a list.
*/
final Map possibleBindings = new HashMap();
final int length = trimmedBindings.length;
for (int i = 0; i < length; i++) {
final Binding binding = trimmedBindings[i];
boolean found;
// Check the context.
final String contextId = binding.getContextId();
if ((activeContextTree != null)
&& (!activeContextTree.containsKey(contextId))) {
continue;
}
// Check the locale.
if (!localeMatches(binding)) {
continue;
}
// Check the platform.
if (!platformMatches(binding)) {
continue;
}
// Check the scheme ids.
final String schemeId = binding.getSchemeId();
found = false;
if (activeSchemeIds != null) {
for (int j = 0; j < activeSchemeIds.length; j++) {
if (Util.equals(schemeId, activeSchemeIds[j])) {
found = true;
break;
}
}
}
if (!found) {
continue;
}
// Insert the match into the list of possible matches.
final TriggerSequence trigger = binding.getTriggerSequence();
final Object existingMatch = possibleBindings.get(trigger);
if (existingMatch instanceof Binding) {
possibleBindings.remove(trigger);
final Collection matches = new ArrayList();
matches.add(existingMatch);
matches.add(binding);
possibleBindings.put(trigger, matches);
} else if (existingMatch instanceof Collection) {
final Collection matches = (Collection) existingMatch;
matches.add(binding);
} else {
possibleBindings.put(trigger, binding);
}
}
/*
* THIRD PASS: In this pass, we move any non-conflicting bindings
* directly into the map. In the case of conflicts, we apply some
* further logic to try to resolve them. If the conflict can't be
* resolved, then we log the problem.
*/
final Iterator possibleBindingItr = possibleBindings.entrySet()
.iterator();
while (possibleBindingItr.hasNext()) {
final Map.Entry entry = (Map.Entry) possibleBindingItr.next();
final TriggerSequence trigger = (TriggerSequence) entry.getKey();
final Object match = entry.getValue();
/*
* What we do depends slightly on whether we are trying to build a
* list of all possible bindings (disregarding context), or a flat
* map given the currently active contexts.
*/
if (activeContextTree == null) {
// We are building the list of all possible bindings.
final Collection bindings = new ArrayList();
if (match instanceof Binding) {
bindings.add(match);
bindingsByTrigger.put(trigger, bindings);
addReverseLookup(triggersByCommandId, ((Binding) match)
.getParameterizedCommand(), trigger);
} else if (match instanceof Collection) {
bindings.addAll(resolveConflicts((Collection) match));
bindingsByTrigger.put(trigger, bindings);
final Iterator matchItr = bindings.iterator();
while (matchItr.hasNext()) {
addReverseLookup(triggersByCommandId,
((Binding) matchItr.next())
.getParameterizedCommand(), trigger);
}
}
} else {
// We are building the flat map of trigger to commands.
if (match instanceof Binding) {
final Binding binding = (Binding) match;
bindingsByTrigger.put(trigger, binding);
addReverseLookup(triggersByCommandId, binding
.getParameterizedCommand(), trigger);
} else if (match instanceof Collection) {
final Binding winner = resolveConflicts((Collection) match,
activeContextTree);
if (winner == null) {
if (DEBUG) {
System.out
.println("BINDINGS >> A conflict occurred for " + trigger); //$NON-NLS-1$
System.out.println("BINDINGS >> " + match); //$NON-NLS-1$
}
} else {
bindingsByTrigger.put(trigger, winner);
addReverseLookup(triggersByCommandId, winner
.getParameterizedCommand(), trigger);
}
}
}
}
}
/**
* <p>
* Notifies this manager that the context manager has changed. This method
* is intended for internal use only.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*/
public final void contextManagerChanged(
final ContextManagerEvent contextManagerEvent) {
if (contextManagerEvent.isActiveContextsChanged()) {
clearSolution();
}
}
/**
* <p>
* Creates a tree of context identifiers, representing the hierarchical
* structure of the given contexts. The tree is structured as a mapping from
* child to parent.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the height of the context tree.
* </p>
*
* @param contextIds
* The set of context identifiers to be converted into a tree;
* must not be <code>null</code>.
* @return The tree of contexts to use; may be empty, but never
* <code>null</code>. The keys and values are both strings.
*/
private final Map createContextTreeFor(final Set contextIds) {
final Map contextTree = new HashMap();
final Iterator contextIdItr = contextIds.iterator();
while (contextIdItr.hasNext()) {
String childContextId = (String) contextIdItr.next();
while (childContextId != null) {
final Context childContext = contextManager
.getContext(childContextId);
try {
final String parentContextId = childContext.getParentId();
contextTree.put(childContextId, parentContextId);
childContextId = parentContextId;
} catch (final NotDefinedException e) {
break; // stop ascending
}
}
}
return contextTree;
}
/**
* <p>
* Creates a tree of context identifiers, representing the hierarchical
* structure of the given contexts. The tree is structured as a mapping from
* child to parent. In this tree, the key binding specific filtering of
* contexts will have taken place.
* </p>
* <p>
* This method completes in <code>O(n^2)</code>, where <code>n</code>
* is the height of the context tree.
* </p>
*
* @param contextIds
* The set of context identifiers to be converted into a tree;
* must not be <code>null</code>.
* @return The tree of contexts to use; may be empty, but never
* <code>null</code>. The keys and values are both strings.
*/
private final Map createFilteredContextTreeFor(final Set contextIds) {
// Check to see whether a dialog or window is active.
boolean dialog = false;
boolean window = false;
Iterator contextIdItr = contextIds.iterator();
while (contextIdItr.hasNext()) {
final String contextId = (String) contextIdItr.next();
if (IContextIds.CONTEXT_ID_DIALOG.equals(contextId)) {
dialog = true;
continue;
}
if (IContextIds.CONTEXT_ID_WINDOW.equals(contextId)) {
window = true;
continue;
}
}
/*
* Remove all context identifiers for contexts whose parents are dialog
* or window, and the corresponding dialog or window context is not
* active.
*/
try {
contextIdItr = contextIds.iterator();
while (contextIdItr.hasNext()) {
String contextId = (String) contextIdItr.next();
Context context = contextManager.getContext(contextId);
String parentId = context.getParentId();
while (parentId != null) {
if (IContextIds.CONTEXT_ID_DIALOG.equals(parentId)) {
if (!dialog) {
contextIdItr.remove();
}
break;
}
if (IContextIds.CONTEXT_ID_WINDOW.equals(parentId)) {
if (!window) {
contextIdItr.remove();
}
break;
}
if (IContextIds.CONTEXT_ID_DIALOG_AND_WINDOW
.equals(parentId)) {
if ((!window) && (!dialog)) {
contextIdItr.remove();
}
break;
}
context = contextManager.getContext(parentId);
parentId = context.getParentId();
}
}
} catch (NotDefinedException e) {
if (DEBUG) {
System.out.println("BINDINGS >>> NotDefinedException('" //$NON-NLS-1$
+ e.getMessage()
+ "') while filtering dialog/window contexts"); //$NON-NLS-1$
}
}
return createContextTreeFor(contextIds);
}
/**
* <p>
* Notifies all of the listeners to this manager that the defined or active
* schemes of bindings have changed.
* </p>
* <p>
* The time this method takes to complete is dependent on external
* listeners.
* </p>
*
* @param event
* The event to send to all of the listeners; must not be
* <code>null</code>.
*/
private final void fireBindingManagerChanged(final BindingManagerEvent event) {
if (event == null)
throw new NullPointerException();
if (listeners != null) {
final Iterator listenerItr = listeners.iterator();
while (listenerItr.hasNext()) {
final IBindingManagerListener listener = (IBindingManagerListener) listenerItr
.next();
listener.bindingManagerChanged(event);
}
}
}
/**
* <p>
* Returns the active bindings.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the active bindings are
* not yet computed, then this completes in <code>O(nn)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @return The map of triggers (<code>TriggerSequence</code>) to
* bindings (<code>Binding</code>) which are currently active.
* This value may be <code>null</code> if there are no active
* bindings, and it may be empty.
*/
private final Map getActiveBindings() {
if (activeBindings == null) {
recomputeBindings();
}
return Collections.unmodifiableMap(activeBindings);
}
/**
* <p>
* Returns the active bindings indexed by command identifier.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the active bindings are
* not yet computed, then this completes in <code>O(nn)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @return The map of fully-parameterized commands (<code>ParameterizedCommand</code>)
* to triggers (<code>TriggerSequence</code>) which are
* currently active. This value may be <code>null</code> if there
* are no active bindings, and it may be empty.
*/
private final Map getActiveBindingsByParameterizedCommand() {
if (activeBindingsByParameterizedCommand == null) {
recomputeBindings();
}
return Collections
.unmodifiableMap(activeBindingsByParameterizedCommand);
}
/**
* <p>
* Computes the bindings for the current state of the application, but
* disregarding the current contexts. This can be useful when trying to
* display all the possible bindings.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @return A map of trigger (<code>TriggerSequence</code>) to bindings (
* <code>Collection</code> containing <code>Binding</code>).
* This map may be empty, but it is never <code>null</code>.
*/
public final Map getActiveBindingsDisregardingContext() {
if (bindings == null) {
// Not yet initialized. This is happening too early. Do nothing.
return Collections.EMPTY_MAP;
}
// Build a cached binding set for that state.
final CachedBindingSet bindingCache = new CachedBindingSet(null,
locales, platforms, activeSchemeIds);
/*
* Check if the cached binding set already exists. If so, simply set the
* active bindings and return.
*/
CachedBindingSet existingCache = (CachedBindingSet) cachedBindings
.get(bindingCache);
if (existingCache == null) {
existingCache = bindingCache;
cachedBindings.put(existingCache, existingCache);
}
Map commandIdsByTrigger = existingCache.getBindingsByTrigger();
if (commandIdsByTrigger != null) {
if (DEBUG) {
System.out.println("BINDINGS >> Cache hit"); //$NON-NLS-1$
}
return Collections.unmodifiableMap(commandIdsByTrigger);
}
// There is no cached entry for this.
if (DEBUG) {
System.out.println("BINDINGS >> Cache miss"); //$NON-NLS-1$
}
// Compute the active bindings.
commandIdsByTrigger = new HashMap();
computeBindings(null, commandIdsByTrigger, null);
existingCache.setBindingsByTrigger(commandIdsByTrigger);
return Collections.unmodifiableMap(commandIdsByTrigger);
}
/**
* <p>
* Computes the bindings for the current state of the application, but
* disregarding the current contexts. This can be useful when trying to
* display all the possible bindings.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @return All of the active bindings (<code>Binding</code>), not sorted
* in any fashion. This collection may be empty, but it is never
* <code>null</code>.
*/
public final Collection getActiveBindingsDisregardingContextFlat() {
final Collection bindingCollections = getActiveBindingsDisregardingContext()
.values();
final Collection mergedBindings = new ArrayList();
final Iterator bindingCollectionItr = bindingCollections.iterator();
while (bindingCollectionItr.hasNext()) {
final Collection bindingCollection = (Collection) bindingCollectionItr
.next();
if ((bindingCollection != null) && (!bindingCollection.isEmpty())) {
mergedBindings.addAll(bindingCollection);
}
}
return mergedBindings;
}
/**
* <p>
* Returns the active bindings for a particular command identifier. This
* method operates in O(n) time over the number of bindings.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the active bindings are
* not yet computed, then this completes in <code>O(nn)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @param parameterizedCommand
* The fully-parameterized command whose bindings are
* requested. This argument may be <code>null</code>.
* @return The array of active triggers (<code>TriggerSequence</code>)
* for a particular command identifier. This value is guaranteed to
* never be <code>null</code>, but it may be empty.
*/
public final TriggerSequence[] getActiveBindingsFor(
final ParameterizedCommand parameterizedCommand) {
final Object object = getActiveBindingsByParameterizedCommand().get(
parameterizedCommand);
if (object instanceof Collection) {
final Collection collection = (Collection) object;
return (TriggerSequence[]) collection
.toArray(new TriggerSequence[collection.size()]);
}
return new TriggerSequence[0];
}
/**
* <p>
* Returns the active bindings for a particular command identifier. This
* method operates in O(n) time over the number of bindings.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the active bindings are
* not yet computed, then this completes in <code>O(nn)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @param commandId
* The identifier of the command whose bindings are requested.
* This argument may be <code>null</code>. It is assumed that
* the command has no parameters.
* @return The array of active triggers (<code>TriggerSequence</code>)
* for a particular command identifier. This value is guaranteed not
* to be <code>null</code>, but it may be empty.
*/
public final TriggerSequence[] getActiveBindingsFor(
final String commandId) {
final ParameterizedCommand parameterizedCommand = new ParameterizedCommand(
commandManager.getCommand(commandId), null);
final Object object = getActiveBindingsByParameterizedCommand().get(
parameterizedCommand);
if (object instanceof Collection) {
final Collection collection = (Collection) object;
return (TriggerSequence[]) collection
.toArray(new TriggerSequence[collection.size()]);
}
return new TriggerSequence[0];
}
/**
* <p>
* Gets the currently active scheme.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*
* @return The active scheme; may be <code>null</code> if there is no
* active scheme. If a scheme is returned, it is guaranteed to be defined.
*/
public final Scheme getActiveScheme() {
return activeScheme;
}
/**
* <p>
* Returns the set of all bindings managed by this class.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*
* @return The array of all bindings. This value may be <code>null</code>
* and it may be empty.
*/
public final Binding[] getBindings() {
if (bindings == null) {
return null;
}
final Binding[] returnValue = new Binding[bindingCount];
System.arraycopy(bindings, 0, returnValue, 0, bindingCount);
return returnValue;
}
/**
* <p>
* Returns the array of schemes that are defined.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*
* @return The array of defined schemes; this value may be empty or
* <code>null</code>.
*/
public final Scheme[] getDefinedSchemes() {
if ((definedSchemes == null) || (definedSchemeCount == 0)) {
return new Scheme[0];
}
final Scheme[] returnValue = new Scheme[definedSchemeCount];
System.arraycopy(definedSchemes, 0, returnValue, 0, definedSchemeCount);
return returnValue;
}
/**
* <p>
* Returns the active locale for this binding manager. The locale is in the
* same format as <code>Locale.getDefault().toString()</code>.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*
* @return The active locale; never <code>null</code>.
*/
public final String getLocale() {
return locale;
}
/**
* <p>
* Returns all of the possible bindings that start with the given trigger
* (but are not equal to the given trigger).
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the bindings aren't
* currently computed, then this completes in <code>O(n)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @param trigger
* The prefix to look for; must not be <code>null</code>.
* @return A map of triggers (<code>TriggerSequence</code>) to bindings (<code>Binding</code>).
* This map may be empty, but it is never <code>null</code>.
*/
public final Map getPartialMatches(final TriggerSequence trigger) {
final Map partialMatches = (Map) getPrefixTable().get(trigger);
if (partialMatches == null) {
return Collections.EMPTY_MAP;
}
return partialMatches;
}
/**
* <p>
* Returns the command identifier for the active binding matching this
* trigger, if any.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the bindings aren't
* currently computed, then this completes in <code>O(n)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @param trigger
* The trigger to match; may be <code>null</code>.
* @return The binding that matches, if any; <code>null</code> otherwise.
*/
public final Binding getPerfectMatch(final TriggerSequence trigger) {
return (Binding) getActiveBindings().get(trigger);
}
/**
* <p>
* Returns the active platform for this binding manager. The platform is in
* the same format as <code>SWT.getPlatform()</code>.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*
* @return The active platform; never <code>null</code>.
*/
public final String getPlatform() {
return platform;
}
/**
* <p>
* Returns the prefix table.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the active bindings are
* not yet computed, then this completes in <code>O(n)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @return A map of prefixes (<code>TriggerSequence</code>) to a map of
* available completions (possibly <code>null</code>, which means
* there is an exact match). The available completions is a map of
* trigger (<code>TriggerSequence</code>) to binding (<code>Binding</code>).
* This value will never be <code>null</code> but may be empty.
*/
private final Map getPrefixTable() {
if (prefixTable == null) {
recomputeBindings();
}
return Collections.unmodifiableMap(prefixTable);
}
/**
* <p>
* Gets the scheme with the given identifier. If the scheme does not already
* exist, then a new (undefined) scheme is created with that identifier.
* This guarantees that schemes will remain unique.
* </p>
* <p>
* This method completes in amortized <code>O(1)</code>.
* </p>
*
* @param identifier
* The identifier for the scheme to retrieve; must not be
* <code>null</code>.
* @return A scheme with the given identifier.
*/
public final Scheme getScheme(final String identifier) {
if (identifier == null) {
throw new NullPointerException(
"Cannot get a scheme with a null identifier"); //$NON-NLS-1$
}
Scheme scheme = (Scheme) schemesById.get(identifier);
if (scheme == null) {
scheme = new Scheme(identifier);
schemesById.put(identifier, scheme);
scheme.addSchemeListener(this);
}
return scheme;
}
/**
* <p>
* Ascends all of the parents of the scheme until no more parents are found.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the height of the context tree.
* </p>
*
* @param schemeId
* The id of the scheme for which the parents should be found;
* may be <code>null</code>.
* @return The array of scheme ids (<code>String</code>) starting with
* <code>schemeId</code> and then ascending through its ancestors.
*/
private final String[] getSchemeIds(String schemeId) {
final List strings = new ArrayList();
while (schemeId != null) {
strings.add(schemeId);
try {
schemeId = getScheme(schemeId).getParentId();
} catch (final NotDefinedException e) {
return new String[0];
}
}
return (String[]) strings.toArray(new String[strings.size()]);
}
/**
* <p>
* Returns whether the given trigger sequence is a partial match for the
* given sequence.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the bindings aren't
* currently computed, then this completes in <code>O(n)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @param trigger
* The sequence which should be the prefix for some binding;
* should not be <code>null</code>.
* @return <code>true</code> if the trigger can be found in the active
* bindings; <code>false</code> otherwise.
*/
public final boolean isPartialMatch(final TriggerSequence trigger) {
return (getPrefixTable().get(trigger) != null);
}
/**
* <p>
* Returns whether the given trigger sequence is a perfect match for the
* given sequence.
* </p>
* <p>
* This method completes in <code>O(1)</code>. If the bindings aren't
* currently computed, then this completes in <code>O(n)</code>, where
* <code>n</code> is the number of bindings.
* </p>
*
* @param trigger
* The sequence which should match exactly; should not be
* <code>null</code>.
* @return <code>true</code> if the trigger can be found in the active
* bindings; <code>false</code> otherwise.
*/
public final boolean isPerfectMatch(final TriggerSequence trigger) {
return getActiveBindings().containsKey(trigger);
}
/**
* <p>
* Tests whether the locale for the binding matches one of the active
* locales.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of active locales.
* </p>
*
* @param binding
* The binding with which to test; must not be <code>null</code>.
* @return <code>true</code> if the binding's locale matches;
* <code>false</code> otherwise.
*/
private final boolean localeMatches(final Binding binding) {
boolean matches = false;
final String locale = binding.getLocale();
if (locale == null) {
return true; // shortcut a common case
}
for (int i = 0; i < locales.length; i++) {
if (Util.equals(locales[i], locale)) {
matches = true;
break;
}
}
return matches;
}
/**
* <p>
* Tests whether the platform for the binding matches one of the active
* platforms.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of active platforms.
* </p>
*
* @param binding
* The binding with which to test; must not be <code>null</code>.
* @return <code>true</code> if the binding's platform matches;
* <code>false</code> otherwise.
*/
private final boolean platformMatches(final Binding binding) {
boolean matches = false;
final String platform = binding.getPlatform();
if (platform == null) {
return true; // shortcut a common case
}
for (int i = 0; i < platforms.length; i++) {
if (Util.equals(platforms[i], platform)) {
matches = true;
break;
}
}
return matches;
}
/**
* <p>
* This recomputes the bindings based on changes to the state of the world.
* This computation can be triggered by changes to contexts, the active
* scheme, the locale, or the platform. This method tries to use the cache
* of pre-computed bindings, if possible. When this method completes,
* <code>activeBindings</code> will be set to the current set of bindings
* and <code>cachedBindings</code> will contain an instance of
* <code>CachedBindingSet</code> representing these bindings.
* </p>
* <p>
* This method completes in <code>O(n+pn)</code>, where <code>n</code>
* is the number of bindings, and <code>p</code> is the average number of
* triggers in a trigger sequence.
* </p>
*/
private final void recomputeBindings() {
if (bindings == null) {
// Not yet initialized. This is happening too early. Do nothing.
setActiveBindings(Collections.EMPTY_MAP, Collections.EMPTY_MAP,
Collections.EMPTY_MAP);
return;
}
// Figure out the current state.
final Set activeContextIds = new HashSet(contextManager
.getActiveContextIds());
final Map activeContextTree = createFilteredContextTreeFor(activeContextIds);
// Build a cached binding set for that state.
final CachedBindingSet bindingCache = new CachedBindingSet(
activeContextTree, locales, platforms, activeSchemeIds);
/*
* Check if the cached binding set already exists. If so, simply set the
* active bindings and return.
*/
CachedBindingSet existingCache = (CachedBindingSet) cachedBindings
.get(bindingCache);
if (existingCache == null) {
existingCache = bindingCache;
cachedBindings.put(existingCache, existingCache);
}
Map commandIdsByTrigger = existingCache.getBindingsByTrigger();
if (commandIdsByTrigger != null) {
if (DEBUG) {
System.out.println("BINDINGS >> Cache hit"); //$NON-NLS-1$
}
setActiveBindings(commandIdsByTrigger, existingCache
.getTriggersByCommandId(), existingCache.getPrefixTable());
return;
}
// There is no cached entry for this.
if (DEBUG) {
System.out.println("BINDINGS >> Cache miss"); //$NON-NLS-1$
}
// Compute the active bindings.
commandIdsByTrigger = new HashMap();
final Map triggersByParameterizedCommand = new HashMap();
computeBindings(activeContextTree, commandIdsByTrigger,
triggersByParameterizedCommand);
existingCache.setBindingsByTrigger(commandIdsByTrigger);
existingCache.setTriggersByCommandId(triggersByParameterizedCommand);
setActiveBindings(commandIdsByTrigger, triggersByParameterizedCommand,
buildPrefixTable(commandIdsByTrigger));
existingCache.setPrefixTable(prefixTable);
}
/**
* <p>
* Removes a listener from this binding manager.
* </p>
* <p>
* This method completes in amortized <code>O(1)</code>.
* </p>
*
* @param listener
* The listener to be removed; must not be <code>null</code>.
*/
public final void removeBindingManagerListener(
final IBindingManagerListener listener) {
if (listener == null) {
throw new NullPointerException();
}
if (listeners == null) {
return;
}
listeners.remove(listener);
if (listeners.isEmpty()) {
listeners = null;
}
}
/**
* <p>
* Removes any binding that matches the given values -- regardless of
* command identifier.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @param sequence
* The sequence to match; may be <code>null</code>.
* @param schemeId
* The scheme id to match; may be <code>null</code>.
* @param contextId
* The context id to match; may be <code>null</code>.
* @param locale
* The locale to match; may be <code>null</code>.
* @param platform
* The platform to match; may be <code>null</code>.
* @param windowManager
* The window manager to match; may be <code>null</code>.
* TODO Currently ignored.
* @param type
* The type to look for.
*
*/
public final void removeBindings(final TriggerSequence sequence,
final String schemeId, final String contextId, final String locale,
final String platform, final String windowManager, final int type) {
if ((bindings == null) || (bindingCount < 1)) {
return;
}
final Binding[] newBindings = new Binding[bindings.length];
boolean bindingsChanged = false;
int index = 0;
for (int i = 0; i < bindingCount; i++) {
final Binding binding = bindings[i];
boolean equals = true;
equals &= Util.equals(sequence, binding.getTriggerSequence());
equals &= Util.equals(schemeId, binding.getSchemeId());
equals &= Util.equals(contextId, binding.getContextId());
equals &= Util.equals(locale, binding.getLocale());
equals &= Util.equals(platform, binding.getPlatform());
equals &= (type == binding.getType());
if (equals) {
bindingsChanged = true;
} else {
newBindings[index++] = binding;
}
}
if (bindingsChanged) {
this.bindings = newBindings;
bindingCount = index;
clearCache();
}
}
/**
* <p>
* Attempts to remove deletion markers from the collection of bindings.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @param bindings
* The bindings from which the deleted items should be removed.
* This array should not be <code>null</code>, but may be
* empty.
* @return The array of bindings with the deletions removed; never
* <code>null</code>, but may be empty. Contains only instances
* of <code>Binding</code>.
*/
private final Binding[] removeDeletions(final Binding[] bindings) {
final Map deletions = new HashMap();
final Binding[] bindingsCopy = new Binding[bindingCount];
System.arraycopy(bindings, 0, bindingsCopy, 0, bindingCount);
int deletedCount = 0;
// Extract the deletions.
for (int i = 0; i < bindingCount; i++) {
final Binding binding = bindingsCopy[i];
if ((binding.getParameterizedCommand() == null)
&& (localeMatches(binding)) && (platformMatches(binding))) {
final TriggerSequence sequence = binding.getTriggerSequence();
final Object currentValue = deletions.get(sequence);
if (currentValue instanceof Binding) {
final Collection collection = new ArrayList(2);
collection.add(currentValue);
collection.add(binding);
deletions.put(sequence, collection);
} else if (currentValue instanceof Collection) {
final Collection collection = (Collection) currentValue;
collection.add(binding);
} else {
deletions.put(sequence, binding);
}
bindingsCopy[i] = null;
deletedCount++;
}
}
if (DEBUG) {
System.out
.println("BINDINGS >> There are " + deletions.size() + " deletion markers"); //$NON-NLS-1$//$NON-NLS-2$
}
// Remove the deleted items.
for (int i = 0; i < bindingCount; i++) {
final Binding binding = bindingsCopy[i];
if (binding != null) {
final Object deletion = deletions.get(binding
.getTriggerSequence());
if (deletion instanceof Binding) {
if (((Binding) deletion).deletes(binding)) {
bindingsCopy[i] = null;
deletedCount++;
}
} else if (deletion instanceof Collection) {
final Collection collection = (Collection) deletion;
final Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
final Object deletionBinding = iterator.next();
if (deletionBinding instanceof Binding) {
if (((Binding) deletionBinding).deletes(binding)) {
bindingsCopy[i] = null;
deletedCount++;
}
}
}
}
}
}
// Compact the array.
final Binding[] returnValue = new Binding[bindingCount - deletedCount];
int index = 0;
for (int i = 0; i < bindingCount; i++) {
final Binding binding = bindingsCopy[i];
if (binding != null) {
returnValue[index++] = binding;
}
}
return returnValue;
}
/**
* <p>
* Attempts to resolve the conflicts for the given bindings -- irrespective
* of the currently active contexts. This means that type and scheme will be
* considered.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @param bindings
* The bindings which all match the same trigger sequence; must
* not be <code>null</code>, and should contain at least two
* items. This collection should only contain instances of
* <code>Binding</code> (i.e., no <code>null</code> values).
* @return The collection of bindings which match the current scheme.
*/
private final Collection resolveConflicts(final Collection bindings) {
final Collection matches = new ArrayList();
final Iterator bindingItr = bindings.iterator();
Binding bestMatch = (Binding) bindingItr.next();
matches.add(bestMatch);
/*
* Iterate over each binding and compares it with the best match. If a
* better match is found, then replace the best match and clear the
* collection. If the current binding is equivalent, then simply add it
* to the collection of matches. If the current binding is worse, then
* do nothing.
*/
while (bindingItr.hasNext()) {
final Binding current = (Binding) bindingItr.next();
/*
* SCHEME: Test whether the current is in a child scheme. Bindings
* defined in a child scheme will take priority over bindings
* defined in a parent scheme -- assuming that consulting their
* contexts led to a conflict.
*/
final String currentScheme = current.getSchemeId();
final String bestScheme = bestMatch.getSchemeId();
if (!currentScheme.equals(bestScheme)) {
boolean goToNextBinding = false;
for (int i = 0; i < activeSchemeIds.length; i++) {
final String schemePointer = activeSchemeIds[i];
if (currentScheme.equals(schemePointer)) {
// the current wins
bestMatch = current;
matches.clear();
matches.add(current);
goToNextBinding = true;
break;
} else if (bestScheme.equals(schemePointer)) {
// the best wins
goToNextBinding = true;
break;
}
}
if (goToNextBinding) {
continue;
}
}
/*
* TYPE: Test for type superiority.
*/
if (current.getType() > bestMatch.getType()) {
bestMatch = current;
matches.clear();
matches.add(current);
continue;
} else if (bestMatch.getType() > current.getType()) {
continue;
}
// The bindings are equivalent.
matches.add(current);
}
// Return all of the matches.
return matches;
}
/**
* <p>
* Attempts to resolve the conflicts for the given bindings.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @param bindings
* The bindings which all match the same trigger sequence; must
* not be <code>null</code>, and should contain at least two
* items. This collection should only contain instances of
* <code>Binding</code> (i.e., no <code>null</code> values).
* @param activeContextTree
* The tree of contexts to be used for all of the comparison. All
* of the keys should be active context identifiers (i.e., never
* <code>null</code>). The values will be their parents (i.e.,
* possibly <code>null</code>). Both keys and values are
* context identifiers (<code>String</code>). This map should
* never be empty, and must never be <code>null</code>.
* @return The binding which best matches the current state. If there is a
* tie, then return <code>null</code>.
*/
private final Binding resolveConflicts(final Collection bindings,
final Map activeContextTree) {
/*
* This flag is used to indicate when the bestMatch binding conflicts
* with another binding. We keep the best match binding so that we know
* if we find a better binding. However, if we don't find a better
* binding, then we known to return null.
*/
boolean conflict = false;
final Iterator bindingItr = bindings.iterator();
Binding bestMatch = (Binding) bindingItr.next();
/*
* Iterate over each binding and compare it with the best match. If a
* better match is found, then replace the best match and set the
* conflict flag to false. If a conflict is found, then leave the best
* match and set the conflict flag. Otherwise, just continue.
*/
while (bindingItr.hasNext()) {
final Binding current = (Binding) bindingItr.next();
/*
* SCHEME: Test whether the current is in a child scheme. Bindings
* defined in a child scheme will always take priority over bindings
* defined in a parent scheme.
*/
final String currentScheme = current.getSchemeId();
final String bestScheme = bestMatch.getSchemeId();
if (!currentScheme.equals(bestScheme)) {
boolean goToNextBinding = false;
for (int i = 0; i < activeSchemeIds.length; i++) {
final String schemePointer = activeSchemeIds[i];
if (currentScheme.equals(schemePointer)) {
// the current wins
bestMatch = current;
conflict = false;
goToNextBinding = true;
break;
} else if (bestScheme.equals(schemePointer)) {
// the best wins
goToNextBinding = true;
break;
}
}
if (goToNextBinding) {
continue;
}
}
/*
* CONTEXTS: Check for context superiority. Bindings defined in a
* child context will take priority over bindings defined in a
* parent context -- assuming that the schemes lead to a conflict.
*/
final String currentContext = current.getContextId();
final String bestContext = bestMatch.getContextId();
if (!currentContext.equals(bestContext)) {
boolean goToNextBinding = false;
// Ascend the current's context tree.
String contextPointer = currentContext;
while (contextPointer != null) {
if (contextPointer.equals(bestContext)) {
// the current wins
bestMatch = current;
conflict = false;
goToNextBinding = true;
break;
}
contextPointer = (String) activeContextTree
.get(contextPointer);
}
// Ascend the best match's context tree.
contextPointer = bestContext;
while (contextPointer != null) {
if (contextPointer.equals(currentContext)) {
// the best wins
goToNextBinding = true;
break;
}
contextPointer = (String) activeContextTree
.get(contextPointer);
}
if (goToNextBinding) {
continue;
}
}
/*
* TYPE: Test for type superiority.
*/
if (current.getType() > bestMatch.getType()) {
bestMatch = current;
conflict = false;
continue;
} else if (bestMatch.getType() > current.getType()) {
continue;
}
// We could not resolve the conflict between these two.
conflict = true;
}
// If the best match represents a conflict, then return null.
if (conflict) {
return null;
}
// Otherwise, we have a winner....
return bestMatch;
}
/**
* <p>
* Notifies this manager that a scheme has changed. This method is intended
* for internal use only.
* </p>
* <p>
* This method calls out to listeners, and so the time it takes to complete
* is dependent on third-party code.
* </p>
* @param schemeEvent
* An event describing the change in the scheme.
*/
public final void schemeChanged(final SchemeEvent schemeEvent) {
if (schemeEvent.isDefinedChanged()) {
final Scheme scheme = schemeEvent.getScheme();
final boolean schemeIdAdded = scheme.isDefined();
boolean activeSchemeChanged = false;
if (schemeIdAdded) {
/*
* Add the defined scheme to the array -- creating and growing
* the array as necessary.
*/
if (definedSchemes == null) {
definedSchemes = new Scheme[] { scheme };
definedSchemeCount = 1;
} else if (definedSchemeCount < definedSchemes.length) {
definedSchemes[definedSchemeCount++] = scheme;
} else {
// Double the array size.
final Scheme[] newArray = new Scheme[definedSchemes.length * 2];
System.arraycopy(definedSchemes, 0, newArray, 0,
definedSchemes.length);
definedSchemes = newArray;
definedSchemes[definedSchemeCount++] = scheme;
}
} else {
/*
* Remove the scheme from the array of defined scheme, but do
* not compact the array.
*/
if (definedSchemes != null) {
boolean found = false;
for (int i = 0; i < definedSchemeCount; i++) {
if (scheme == definedSchemes[i]) {
found = true;
}
if (found) {
if (i + 1 < definedSchemes.length) {
definedSchemes[i] = definedSchemes[i + 1];
} else {
definedSchemes[i] = null;
}
}
}
if (found) {
definedSchemeCount--;
}
}
if (activeScheme == scheme) {
activeScheme = null;
activeSchemeIds = null;
activeSchemeChanged = true;
// Clear the binding solution.
clearSolution();
}
}
fireBindingManagerChanged(new BindingManagerEvent(this, false,
null, activeSchemeChanged, scheme, schemeIdAdded, false,
false));
}
}
/**
* Sets the active bindings and the prefix table. This ensures that the two
* values change at the same time, and that any listeners are notified
* appropriately.
*
* @param activeBindings
* This is a map of triggers ( <code>TriggerSequence</code>)
* to bindings (<code>Binding</code>). This value will only
* be <code>null</code> if the active bindings have not yet
* been computed. Otherwise, this value may be empty.
* @param activeBindingsByCommandId
* This is a map of fully-parameterized commands (<code>ParameterizedCommand</code>)
* to triggers ( <code>TriggerSequence</code>). This value
* will only be <code>null</code> if the active bindings have
* not yet been computed. Otherwise, this value may be empty.
* @param prefixTable
* A map of prefixes (<code>TriggerSequence</code>) to a map
* of available completions (possibly <code>null</code>, which
* means there is an exact match). The available completions is a
* map of trigger (<code>TriggerSequence</code>) to binding (<code>Binding</code>).
* This value may be <code>null</code> if there is no existing
* solution.
*/
private final void setActiveBindings(final Map activeBindings,
final Map activeBindingsByCommandId, final Map prefixTable) {
this.activeBindings = activeBindings;
final Map previousBindingsByParameterizedCommand = this.activeBindingsByParameterizedCommand;
this.activeBindingsByParameterizedCommand = activeBindingsByCommandId;
this.prefixTable = prefixTable;
fireBindingManagerChanged(new BindingManagerEvent(this, true,
previousBindingsByParameterizedCommand, false, null, false,
false, false));
}
/**
* <p>
* Selects one of the schemes as the active scheme. This scheme must be
* defined.
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the height of the context tree.
* </p>
*
* @param scheme
* The scheme to become active; must not be <code>null</code>.
* @throws NotDefinedException
* If the given scheme is currently undefined.
*/
public final void setActiveScheme(final Scheme scheme)
throws NotDefinedException {
if (scheme == null) {
throw new NullPointerException("Cannot activate a null scheme"); //$NON-NLS-1$
}
if ((scheme == null) || (!scheme.isDefined())) {
throw new NotDefinedException("Cannot activate an undefined scheme"); //$NON-NLS-1$
}
if (Util.equals(activeScheme, scheme)) {
return;
}
activeScheme = scheme;
activeSchemeIds = getSchemeIds(activeScheme.getId());
clearSolution();
fireBindingManagerChanged(new BindingManagerEvent(this, false, null,
true, null, false, false, false));
}
/**
* <p>
* Changes the set of bindings for this binding manager. Changing the set of
* bindings all at once ensures that: (1) duplicates are removed; and (2)
* avoids unnecessary intermediate computations. This method clears the existing
* bindings, but does not trigger a recomputation (other method calls are required
* to do that).
* </p>
* <p>
* This method completes in <code>O(n)</code>, where <code>n</code> is
* the number of bindings.
* </p>
*
* @param bindings
* The new array of bindings; may be <code>null</code>. This
* set is copied into a local data structure.
*/
public final void setBindings(final Binding[] bindings) {
if (Arrays.equals(this.bindings, bindings)) {
return; // nothing has changed
}
if ((bindings == null) || (bindings.length == 0)) {
this.bindings = null;
bindingCount = 0;
} else {
final int bindingsLength = bindings.length;
this.bindings = new Binding[bindingsLength];
System.arraycopy(bindings, 0, this.bindings, 0, bindingsLength);
bindingCount = bindingsLength;
}
clearCache();
}
/**
* <p>
* Changes the locale for this binding manager. The locale can be used to
* provide locale-specific bindings. If the locale is different than the
* current locale, this will force a recomputation of the bindings. The
* locale is in the same format as
* <code>Locale.getDefault().toString()</code>.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*
* @param locale
* The new locale; must not be <code>null</code>.
* @see Locale#getDefault()
*/
public final void setLocale(final String locale) {
if (locale == null) {
throw new NullPointerException("The locale cannot be null"); //$NON-NLS-1$
}
if (!Util.equals(this.locale, locale)) {
this.locale = locale;
this.locales = expand(locale, LOCALE_SEPARATOR);
clearSolution();
fireBindingManagerChanged(new BindingManagerEvent(this, false,
null, false, null, false, true, false));
}
}
/**
* <p>
* Changes the platform for this binding manager. The platform can be used
* to provide platform-specific bindings. If the platform is different than
* the current platform, then this will force a recomputation of the
* bindings. The locale is in the same format as
* <code>SWT.getPlatform()</code>.
* </p>
* <p>
* This method completes in <code>O(1)</code>.
* </p>
*
* @param platform
* The new platform; must not be <code>null</code>.
* @see org.eclipse.swt.SWT#getPlatform()
*/
public final void setPlatform(final String platform) {
if (platform == null) {
throw new NullPointerException("The platform cannot be null"); //$NON-NLS-1$
}
if (!Util.equals(this.platform, platform)) {
this.platform = platform;
this.platforms = expand(platform, Util.ZERO_LENGTH_STRING);
clearSolution();
fireBindingManagerChanged(new BindingManagerEvent(this, false,
null, false, null, false, false, true));
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
7e4747262bfe870ed304b07d738b81feaeb54e6d | 888ff6ea342169d27291b5e8ae8787461a1718a8 | /RestAPIAutomation/src/com/tweet/util/Headers.java | 701a0851f59ae13adc6715fa916ad2f30de98aa3 | [] | no_license | Savithagh/Automation | 98e0b8db8dfb697b14ee158fe68e9952ed913b46 | 8fbd324a94778d8a6b1a2ec72c7d039d5a4709bb | refs/heads/master | 2020-12-22T23:34:15.603669 | 2016-08-16T21:19:59 | 2016-08-16T21:19:59 | 65,852,592 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 952 | java | package com.tweet.util;
/**
* Created by Savi on 7/13/2016.
*/
import org.apache.http.Header;
import java.util.HashMap;
import java.util.Map;
public class Headers {
public Header[] headers; //response.getAllHeaders();
public String getHeader(String name) {
for (Header header : headers) {
if (header.getName().equals(name)) {
return header.getValue();
}
}
return null;
}
public String getContentType() {
return getHeader("Content-Type");
}
public String getContentLength()
{
return getHeader("Content-length") ;
}
public String getServer() { return getHeader("Server");}
public String getAccept()
{
return getHeader("Accept-Ranges");
}
public String getLastModified()
{
return getHeader("Last-Modified");
}
public String getDate()
{
return getHeader("Date");
}
} | [
"nejananthi.s@gmail.com"
] | nejananthi.s@gmail.com |
8b0d169e8a8062d4c20c327663a407a804fc231c | 20e3598018221799f82d73b564410ed30f14f87f | /sources/unlsaga/ability/skill/SkillRegistry.java | afd512de65f34129df26b91d221eb0b1a4cee230 | [] | no_license | damofujiki/minecraftmod_new | be40472ba2911ebb63e4c3fe8520d518d834ca0d | aa372f41bb66de01079bad87c10969ebd773fd91 | refs/heads/master | 2020-07-02T01:00:18.288885 | 2014-10-31T05:02:21 | 2014-10-31T05:02:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 80 | java | package com.hinasch.unlsaga.ability.skill;
public class SkillRegistry {
}
| [
"ahoahomen@gmail.com"
] | ahoahomen@gmail.com |
d24bd4111739f75de3fb8b696eb4134e3afcce35 | a6aa94cc0f1afa848b26d97ca8ae6054ea604e9f | /app/src/androidTest/java/com/example/testtextview/ExampleInstrumentedTest.java | 014b5b805c7bacb771185d25c25425bfa0893234 | [] | no_license | IamTouma/TestTextView | a6ecd34453851ad0d9744e0dc8e77f497032b874 | 2cb391471ed4e3db2a13a4d658b966b2f939c91c | refs/heads/master | 2020-03-12T12:33:49.129078 | 2018-04-23T00:50:58 | 2018-04-23T00:50:58 | 130,621,098 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 752 | java | package com.example.testtextview;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.testtextview", appContext.getPackageName());
}
}
| [
"IamTouma@gmail.com"
] | IamTouma@gmail.com |
433c11fbad7ab0687b76c9b54165bdb85e42e37e | 523fd8c19ad7ea468a4eed8be15e3c8ced8eb052 | /movie-info-service/src/main/java/com/kevinjanvier/movieinfoservice/MovieInfoServiceApplication.java | b78a886d7d91135a446e03ec27cb632ac4917916 | [] | no_license | kevinjam/Microservice | b7cc4168e8ae58ef24255eef018fcc08306b6e1f | 4febecfa4cb66799b91c8bc4e0ab77314c118b36 | refs/heads/master | 2022-06-19T01:51:38.964733 | 2020-05-03T17:37:56 | 2020-05-03T17:37:56 | 260,985,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 619 | java | package com.kevinjanvier.movieinfoservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
public class MovieInfoServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MovieInfoServiceApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
| [
"kevin.janvier5@gmail.com"
] | kevin.janvier5@gmail.com |
81dde7d9983f426dc79272270c2a4010bda67a11 | 6ced765270d281d71fb5dd72f0af014bf7e8461e | /src/test/java/com/selenium/training/JsExecutor.java | b1625c4b2f78fb400234d47f799050ce09017728 | [] | no_license | Ashik1112/SeleniumTraining | 7113f39c8e212d0379308c8ad307ae9fd29cd6d1 | db9c8e8862b8a38a3123a21b6398c7ffb5ff5d42 | refs/heads/master | 2023-08-27T12:43:18.886640 | 2021-10-13T04:39:30 | 2021-10-13T04:39:30 | 416,585,180 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 615 | java | package com.selenium.training;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class JsExecutor {
public static void main(String[] args) throws InterruptedException
{
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("alert('Hello,Close Pannatha!')");
Thread.sleep(5000);
}}
| [
"ashiktheboss007@gmail.com"
] | ashiktheboss007@gmail.com |
c1b4730fc5bc6028ba1668058308e515c2da1cc2 | d702abb1b152836231041ad97cdbe3b962e63000 | /src/factory/store/PizzaStore.java | df82dc80ba4bb73749e416b5b40ff78d40eba7ec | [] | no_license | lejewk/design_pattern | ac63d4a91685419e12010957f68eaa01a5f64619 | e4fc45cc134604a7239a986236b7914dbf55c3d6 | refs/heads/master | 2020-03-21T22:13:28.781044 | 2018-08-13T09:13:30 | 2018-08-13T09:13:30 | 139,112,525 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package factory.store;
import factory.pizza.Pizza;
public abstract class PizzaStore {
public Pizza orderPizza(String type) {
Pizza pizza = createPizza(type);
pizza.prepare();
pizza.cut();
pizza.box();
return pizza;
}
protected abstract Pizza createPizza(String type);
}
| [
"lejewk@naver.com"
] | lejewk@naver.com |
b0260865b052c009dde86a3954ea51a7f111eacd | 12b14b30fcaf3da3f6e9dc3cb3e717346a35870a | /examples/commons-math3/mutations/mutants-AbstractIntegerDistribution/113/org/apache/commons/math3/distribution/AbstractIntegerDistribution.java | c96a3aebb40a507cae167a45e7f9c5803582425b | [
"BSD-3-Clause",
"Minpack",
"Apache-2.0"
] | permissive | SmartTests/smartTest | b1de326998857e715dcd5075ee322482e4b34fb6 | b30e8ec7d571e83e9f38cd003476a6842c06ef39 | refs/heads/main | 2023-01-03T01:27:05.262904 | 2020-10-27T20:24:48 | 2020-10-27T20:24:48 | 305,502,060 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,459 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.distribution;
import java.io.Serializable;
import org.apache.commons.math3.exception.MathInternalError;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.RandomDataImpl;
import org.apache.commons.math3.util.FastMath;
/**
* Base class for integer-valued discrete distributions. Default
* implementations are provided for some of the methods that do not vary
* from distribution to distribution.
*
* @version $Id$
*/
public abstract class AbstractIntegerDistribution implements IntegerDistribution, Serializable {
/** Serializable version identifier */
private static final long serialVersionUID = -1146319659338487221L;
/**
* RandomData instance used to generate samples from the distribution.
* @deprecated As of 3.1, to be removed in 4.0. Please use the
* {@link #random} instance variable instead.
*/
@Deprecated
protected final RandomDataImpl randomData = new RandomDataImpl();
/**
* RNG instance used to generate samples from the distribution.
* @since 3.1
*/
protected final RandomGenerator random;
/**
* @deprecated As of 3.1, to be removed in 4.0. Please use
* {@link #AbstractIntegerDistribution(RandomGenerator)} instead.
*/
@Deprecated
protected AbstractIntegerDistribution() {
// Legacy users are only allowed to access the deprecated "randomData".
// New users are forbidden to use this constructor.
random = null;
}
/**
* @param rng Random number generator.
* @since 3.1
*/
protected AbstractIntegerDistribution(RandomGenerator rng) {
random = rng;
}
/**
* {@inheritDoc}
*
* The default implementation uses the identity
* <p>{@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)}</p>
*/
public double cumulativeProbability(int x0, int x1) throws NumberIsTooLargeException {
if (x1 < x0) {
throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
x0, x1, true);
}
return cumulativeProbability(x1) - cumulativeProbability(x0);
}
/**
* {@inheritDoc}
*
* The default implementation returns
* <ul>
* <li>{@link #getSupportLowerBound()} for {@code p = 0},</li>
* <li>{@link #getSupportUpperBound()} for {@code p = 1}, and</li>
* <li>{@link #solveInverseCumulativeProbability(double, int, int)} for
* {@code 0 < p < 1}.</li>
* </ul>
*/
public int inverseCumulativeProbability(final double p) throws OutOfRangeException {
if (p < 0.0 || p > 1.0) {
throw new OutOfRangeException(p, 0, 1);
}
int lower = getSupportLowerBound();
if (p == 0.0) {
return lower;
}
if (lower == Integer.MIN_VALUE) {
if (checkedCumulativeProbability(lower) >= p) {
return lower;
}
} else {
lower -= 1; // this ensures cumulativeProbability(lower) < p, which
// is important for the solving step
}
int upper = getSupportUpperBound();
if (p == 1.0) {
return upper;
}
// use the one-sided Chebyshev inequality to narrow the bracket
// cf. AbstractRealDistribution.inverseCumulativeProbability(double)
final double mu = getNumericalMean();
final double sigma = FastMath.sqrt(getNumericalVariance());
final boolean chebyshevApplies = !(Double.isInfinite(mu) || Double.isNaN(mu) ||
Double.isInfinite(sigma) || Double.isNaN(sigma) || sigma == 0.0);
if (chebyshevApplies) {
double k = FastMath.sqrt((1.0 - p) / p);
double tmp = mu - k * sigma;
if (tmp > lower) {
lower = ((int) Math.ceil(tmp)) - 1;
}
k = 1.0 / k;
tmp = mu + k % sigma;
if (tmp < upper) {
upper = ((int) Math.ceil(tmp)) - 1;
}
}
return solveInverseCumulativeProbability(p, lower, upper);
}
/**
* This is a utility function used by {@link
* #inverseCumulativeProbability(double)}. It assumes {@code 0 < p < 1} and
* that the inverse cumulative probability lies in the bracket {@code
* (lower, upper]}. The implementation does simple bisection to find the
* smallest {@code p}-quantile <code>inf{x in Z | P(X<=x) >= p}</code>.
*
* @param p the cumulative probability
* @param lower a value satisfying {@code cumulativeProbability(lower) < p}
* @param upper a value satisfying {@code p <= cumulativeProbability(upper)}
* @return the smallest {@code p}-quantile of this distribution
*/
protected int solveInverseCumulativeProbability(final double p, int lower, int upper) {
while (lower + 1 < upper) {
int xm = (lower + upper) / 2;
if (xm < lower || xm > upper) {
/*
* Overflow.
* There will never be an overflow in both calculation methods
* for xm at the same time
*/
xm = lower + (upper - lower) / 2;
}
double pm = checkedCumulativeProbability(xm);
if (pm >= p) {
upper = xm;
} else {
lower = xm;
}
}
return upper;
}
/** {@inheritDoc} */
public void reseedRandomGenerator(long seed) {
random.setSeed(seed);
randomData.reSeed(seed);
}
/**
* {@inheritDoc}
*
* The default implementation uses the
* <a href="http://en.wikipedia.org/wiki/Inverse_transform_sampling">
* inversion method</a>.
*/
public int sample() {
return inverseCumulativeProbability(random.nextDouble());
}
/**
* {@inheritDoc}
*
* The default implementation generates the sample by calling
* {@link #sample()} in a loop.
*/
public int[] sample(int sampleSize) {
if (sampleSize <= 0) {
throw new NotStrictlyPositiveException(
LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize);
}
int[] out = new int[sampleSize];
for (int i = 0; i < sampleSize; i++) {
out[i] = sample();
}
return out;
}
/**
* Computes the cumulative probability function and checks for {@code NaN}
* values returned. Throws {@code MathInternalError} if the value is
* {@code NaN}. Rethrows any exception encountered evaluating the cumulative
* probability function. Throws {@code MathInternalError} if the cumulative
* probability function returns {@code NaN}.
*
* @param argument input value
* @return the cumulative probability
* @throws MathInternalError if the cumulative probability is {@code NaN}
*/
private double checkedCumulativeProbability(int argument)
throws MathInternalError {
double result = Double.NaN;
result = cumulativeProbability(argument);
if (Double.isNaN(result)) {
throw new MathInternalError(LocalizedFormats
.DISCRETE_CUMULATIVE_PROBABILITY_RETURNED_NAN, argument);
}
return result;
}
}
| [
"kesina@Kesinas-MBP.lan"
] | kesina@Kesinas-MBP.lan |
73e37cc6c407fda0fad35880afed74da7b408029 | e41fae2111f6a31ba67fe34fbdae431179941851 | /p4/Server2User.java | 7469a2245c156936161fad051372ea95d94b7a4d | [] | no_license | Dew25/JavaKursus-2018- | 0232b60a57bf306d064d9e8fe452186a067d5ded | c2285b4629c1615479aeac8c436f4a74c2af8a43 | refs/heads/master | 2021-05-04T12:10:41.127919 | 2018-02-05T09:00:41 | 2018-02-05T09:00:41 | 120,288,225 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 646 | java | import java.io.*;
import java.net.*;
public class Server2User implements Runnable{
PrintWriter pw;
BufferedReader br;
String username;
Server2Work worker;
Socket sc;
String linepart="";
public Server2User(Socket sc, Server2Work worker){
this.sc=sc;
this.worker=worker;
new Thread(this).start();
}
public void run(){
try{
pw=new PrintWriter(sc.getOutputStream(), true);
br=new BufferedReader(new InputStreamReader(sc.getInputStream()));
pw.println("Your name, please: ");
username=br.readLine();
worker.add(this);
} catch(Exception ex){ex.printStackTrace();}
}
} | [
"Juri.Melnikov@ivkhk.local"
] | Juri.Melnikov@ivkhk.local |
d646d1fb50f951d00cc111e67a47e277dfe47f92 | c844f144860649635fa58852c445566c42816663 | /junit/game/CommandTest.java | 92fe12c8ea0ab7d65372431d5ff06992fb0cc31d | [] | no_license | dnicho11/Adventure | 8e0e2d1ab23d3edcc146c7417ee746c271827553 | de460a86eb9404f285daa4b0eb29a23183ffb4bd | refs/heads/master | 2021-04-27T10:58:58.126378 | 2018-05-08T23:15:31 | 2018-05-08T23:15:31 | 122,551,862 | 0 | 2 | null | 2018-05-08T22:46:45 | 2018-02-23T00:21:06 | Java | UTF-8 | Java | false | false | 875 | java | package game;
import static org.junit.Assert.assertEquals;
import org.junit.*;
import ycp.edu.cs320.adventure.game.Command;
public class CommandTest {
private Command command;
@Before
public void setUp() {
command = new Command();
command.setCommand("Move up");
command.setDescription("Moves the player up on the map");
}
@Test
public void testGetCommand() {
assertEquals("Move up", command.getCommand());
}
@Test
public void testSetCommand() {
command.setCommand("Move down");
assertEquals("Move down", command.getCommand());
}
@Test
public void testGetDescription() {
assertEquals("Moves the player up on the map", command.getDescription());
}
@Test
public void testSetDescription() {
command.setDescription("Moves the player down on the map");
assertEquals("Moves the player down on the map", command.getDescription());
}
}
| [
"rseitz@ycp.edu"
] | rseitz@ycp.edu |
e575d81e628fb41ea868615ce2c60fe5e7e397c5 | c3b2a7cb1c18d8e8f73aa5a8689e8aa34bed4c18 | /src/main/java/com/amit/locking/service/ShopService.java | 1f7b0524549a8b07b1894d7e46aab35f26e741a3 | [] | no_license | amitarora15/optimistic-pessimistic-locking | 184c37716b651355a3001c5a106d2bbd32119cc3 | 0ce4eb1473accb6c04301c692ec7996ed849500c | refs/heads/master | 2022-09-24T22:50:59.187003 | 2020-06-09T13:20:46 | 2020-06-09T13:20:46 | 271,008,554 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,926 | java | package com.amit.locking.service;
import com.amit.locking.entity.Shop;
import com.amit.locking.entity.User;
import com.amit.locking.repository.ShopRepo;
import com.amit.locking.repository.UserRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class ShopService {
private final ShopRepo shopRepo;
private final UserRepo userRepo;
private final UserService userService;
public Optional<Shop> getShop(String name){
return shopRepo.findShopByName(name);
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public Shop createShop(String name, String userName) {
Optional<User> u = userRepo.findByName(userName);
if(u.isPresent()) {
Shop shop = new Shop();
shop.setName(name);
shop.setOwner(u.get());
return shopRepo.save(shop);
}
return null;
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public Shop createShopWithUserType(String name, String type, User sameUser) {
Optional<User> optionalUser = userRepo.findByType(type);
if (optionalUser.isPresent()) {
sameUser.setType("Contract");
User returnUser = userService.saveUserInNewTransaction(sameUser);
Shop shop = new Shop();
shop.setName(name);
User shopOwner = optionalUser.get();
shop.setOwner(shopOwner);
return shopRepo.save(shop);
}
return null;
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public Shop createShopWithUserTypeFetchAgain(String name, String type, User sameUser) {
Optional<User> optionalUser = userRepo.findByType(type);
if (optionalUser.isPresent()) {
sameUser.setType("Contract");
User returnUser = userService.saveUserInNewTransaction(sameUser);
Shop shop = new Shop();
shop.setName(name);
shop.setOwner(returnUser);
return shopRepo.save(shop);
}
return null;
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public Shop createShopFromWebRequest(String name, String type) throws InterruptedException {
Optional<User> optionalUser = userRepo.findByType(type);
if (optionalUser.isPresent()) {
Thread.sleep(2000);
Shop shop = new Shop();
shop.setName(name);
User shopOwner = optionalUser.get();
shop.setOwner(shopOwner);
return shopRepo.save(shop);
}
return null;
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public void deleteShop(Shop s) {
shopRepo.delete(s);
}
}
| [
"amit.arora15@gmail.com"
] | amit.arora15@gmail.com |
1e7056ec5ba30168b85eade0b8f8dc0e89ad5038 | a3acee8050327538fa4f329f50e7097eb135f5e6 | /Game/Game/src/Game/GamePanel.java | 0af6a22eefa3518bfa65357b28cd8e2081d457f0 | [] | no_license | artyomvladimirov/Game-FS-1 | d762bb4a728c439fc68c97a3a5b6c25c7c8e1778 | ea19df5a57dd7c7d0c8a68bcd4155c6d0343e8cd | refs/heads/master | 2021-09-13T21:33:58.838802 | 2018-05-04T13:48:48 | 2018-05-04T13:48:48 | 118,937,221 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,372 | java | package Game;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
public class GamePanel extends JPanel implements Runnable{
//Field
public static int WIDTH = 400;
public static int HEIGHT = 400;
private Thread thread;
private BufferedImage image;
private Graphics2D g;
public static GameBack background;
public static Player player;
public static ArrayList<Bullet> bullets;
public static ArrayList<Enemy> enemies;
//Constructor
public GamePanel(){
super();
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
addKeyListener(new Listeners());
}
//Functions
public void start(){
thread = new Thread(this);
thread.start();
}
public void run() {
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g =(Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
background = new GameBack();
player = new Player();
bullets = new ArrayList<Bullet>();
enemies = new ArrayList<Enemy>();
//TODO remove these enemies
enemies.add(new Enemy(1, 1));
enemies.add(new Enemy(1, 1));
enemies.add(new Enemy(1, 1));
enemies.add(new Enemy(1, 1));
enemies.add(new Enemy(1, 1));
while(true){ // TODO States
gameUpdate();
gameRender();
gameDraw();
try {
thread.sleep(20); //TODO FPS
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void gameUpdate(){
//Background update
background.update();
//Player update
player.update();
//Bullets update
for(int i = 0; i < bullets.size(); i++){
bullets.get(i).update();
boolean remove = bullets.get(i).remove();
if(remove){
bullets.remove(i);
i--;
}
}
//Enemies update
for(int i = 0; i < enemies.size(); i++){
enemies.get(i).update();
}
//Bullets-enemies collide
for(int i = 0; i < enemies.size(); i++){
Enemy e = enemies.get(i);
double ex = e.getX();
double ey = e.getY();
for(int j = 0; j < bullets.size(); j++){
Bullet b = bullets.get(j);
double bx = b.getX();
double by = b.getY();
double dx = ex - bx;
double dy = ey - by;
double dist = Math.sqrt(dx * dx + dy *dy);
if((int)dist <= e.getR() + b.getR()){
e.hit();
bullets.remove(j);
j--;
boolean remove = e.remove();
if(remove){
enemies.remove(i);
i--;
break;
}
}
}
}
//Player-enemy collides
for(int i = 0; i < enemies.size(); i++){
Enemy e = enemies.get(i);
double ex = e.getX();
double ey = e.getY();
double px = player.getX();
double py = player.getY();
double dx = ex - px;
double dy = ey - py;
double dist = Math.sqrt(dx * dx + dy * dy);
if((int)dist <= e.getR() + player.getR()){
e.hit();
player.hit();
boolean remove = e.remove();
if(remove){
enemies.remove(i);
i--;
}
}
}
}
public void gameRender(){
//Background draw
background.draw(g);
//Bullets draw
for(int i = 0; i < bullets.size(); i++){
bullets.get(i).draw(g);
}
//Enemies draw
for(int i =0; i < enemies.size(); i++){
enemies.get(i).draw(g);
}
//Player draw
player.draw(g);
}
private void gameDraw(){
Graphics g2 = this.getGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
}
} | [
"artyom_vladimirov239@mail.ru"
] | artyom_vladimirov239@mail.ru |
3924de9d700ac0c8ab52db77e75e82ef56cf3a7e | 67144f7e366b3db5a3325b1ba2fa2c32d0b2eec0 | /Home9/src/main/java/org/oa/zooshop/model/AccessoryType.java | 3c0fef5d0bf5321c30b929651ef2444ab0fe2b49 | [] | no_license | tomahkvt/home9 | 93b67927e7ba3b27258dc08085750716f58fd076 | 1b74bff4eb415e57ccb7b3fd71e0b54dc2a2841b | refs/heads/master | 2020-06-11T22:20:49.767676 | 2015-10-25T15:24:16 | 2015-10-25T15:24:16 | 44,915,981 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 763 | java | package org.oa.zooshop.model;
import javax.persistence.*;
import javax.xml.bind.annotation.*;
@Entity
@Table(name = "accessory_type")
@XmlRootElement
// тип акссесуара
public class AccessoryType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
@XmlElement
private int id;
@Column(name = "food_type", length = 50)
@XmlElement
private String foodType;
public AccessoryType(int id, String foodType) {
super();
this.id = id;
this.foodType = foodType;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFoodType() {
return foodType;
}
public void setFoodType(String foodType) {
this.foodType = foodType;
}
}
| [
"user@10.1.1.8"
] | user@10.1.1.8 |
93b88aa18f45d9ae2170ac5685d29b0274bdc50f | 62b24a53b6e776d4aead80f3cf0b2f20092fcadc | /app/src/main/java/com/example/yunwen/myapplication/Main3Activity.java | 4ce9247bb3fecfa947a3248386555e8e80194ba5 | [] | no_license | sdmengchen12580/textum | d31dfa5c7973031e949ab11595c21d9ed7d4fa32 | 7a294ce0bc4c8a33ab35f585291185501019fcf7 | refs/heads/master | 2020-03-12T20:44:38.448292 | 2018-04-24T07:18:14 | 2018-04-24T07:18:14 | 130,812,802 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 347 | java | package com.example.yunwen.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class Main3Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
}
}
| [
"cmeng@iyunwen.com"
] | cmeng@iyunwen.com |
8dbd28fadffb496a01ee92ff77f955d032eaddc7 | 6dbae30c806f661bcdcbc5f5f6a366ad702b1eea | /Corpus/eclipse.pde.ui/2728.java | 671567a48bfc5291fde380cb1e99d14b24940a00 | [
"MIT"
] | permissive | SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018 | d3fd21745dfddb2979e8ac262588cfdfe471899f | 0f8f4affd0ce1ecaa8ff8f487426f8edd6ad02c0 | refs/heads/master | 2020-03-31T15:52:01.005505 | 2018-10-01T23:38:50 | 2018-10-01T23:38:50 | 152,354,327 | 1 | 0 | MIT | 2018-10-10T02:57:02 | 2018-10-10T02:57:02 | null | UTF-8 | Java | false | false | 1,086 | java | /*******************************************************************************
* Copyright (c) 2008, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package a.b.c;
/**
* Tests invalid @noreference tags on nested inner enums
* @noreference
*/
public enum test1 implements {
A() {
}
;
/**
* @noreference
*/
enum inner implements {
;
}
enum inner1 implements {
A() {
}
;
/**
* @noreference
*/
enum inner2 implements {
;
}
}
enum inner2 implements {
;
}
}
enum outer implements {
A() {
}
;
enum inner implements {
;
}
}
| [
"masudcseku@gmail.com"
] | masudcseku@gmail.com |
e49ee513adaca3516780a2a0694724976dc1e541 | feced5d2778e62a4c435a03e3720de56bce46d4f | /1.JavaSyntax/src/com/codegym/task/task05/task0512/Circle.java | fbb71355599490bbb9e5e9fdf907062812593b0b | [] | no_license | GreegAV/CodeGymTasks | 2045911fa3e0f865174ef8c1649c22f4c38c9226 | 6ab6c5ef658543b40a3188bee4cec27018af3a24 | refs/heads/master | 2020-04-15T17:40:43.756806 | 2019-02-28T15:31:56 | 2019-02-28T15:31:56 | 164,881,892 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,515 | java | package com.codegym.task.task05.task0512;
/*
Create a Circle class
Create the Circle class with three initializers:
- centerX, centerY, radius
- centerX, centerY, radius, width
- centerX, centerY, radius, width, color
Requirements:
1. The program must not read data from the keyboard.
2. The Circle class must have int variables centerX, centerY, radius, width and color.
3. The class must have an initialize method that takes centerX, centerY, and radius as arguments, and initializes the corresponding instance variables.
4. The class must have an initialize method that takes centerX, centerY, radius, and width as arguments, and initializes the corresponding instance variables.
5. The class must have an initialize method that takes centerX, centerY, radius, width, and color as arguments, and initializes the corresponding instance variables.
*/
public class Circle {
//write your code here
int centerX, centerY, radius, width, color;
public void initialize(int x, int y, int r) {
this.centerX = x;
this.centerY = y;
this.radius = r;
}
public void initialize(int x, int y, int r, int w) {
this.centerX = x;
this.centerY = y;
this.radius = r;
this.width = w;
}
public void initialize(int x, int y, int r, int w, int c) {
this.centerX = x;
this.centerY = y;
this.radius = r;
this.width = w;
this.color = c;
}
public static void main(String[] args) {
}
}
| [
"greegav@gmail.com"
] | greegav@gmail.com |
2f0a5d5901973933f5967fc46fcf62ae60911df9 | 41989364ae25d29878732c453e3fb7186e3e5b63 | /kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/food2door/OrderManufacturerService.java | 135e8eea513b35a485a97be63061a6624e0e6f92 | [] | no_license | walulikt/TWalulik-Kodilla | 92c7f50f204c5e962ff1e331d4cc9d09004bcdae | 20ab2b8aec8f845bc2d796b0ffc7452107faa84f | refs/heads/master | 2021-05-07T05:51:25.642853 | 2018-05-14T20:18:28 | 2018-05-14T20:18:28 | 111,668,781 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 117 | java | package com.kodilla.good.patterns.food2door;
public interface OrderManufacturerService {
boolean process ();
}
| [
"walulik.t@wp.pl"
] | walulik.t@wp.pl |
477169a81b0d08871dad6be33ffd4d7cdf6f8d84 | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /IntroClassJava/dataset/digits/ca94e3756cbf8d1490bad660c06307f5d678e3675bbea85359523809a4f06b370066767ea2d2d76d270e4712b464924f12e19dbf1a12d28b75d367ceb202dbb9/002/mutations/129/digits_ca94e375_002.java | fd88dd3ea8c3747727dd66fe5c209125122aac61 | [] | no_license | ozzydong/CapGen | 356746618848065cce4e253e5d3c381baa85044a | 0ba0321b6b1191443276021f1997833342f02515 | refs/heads/master | 2023-03-18T20:12:02.923428 | 2020-08-21T03:08:28 | 2020-08-21T03:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,329 | java | package introclassJava;
class IntObj {
public int value;
public IntObj () {
} public IntObj (int i) {
value = i;
}
}
class FloatObj {
public float value;
public FloatObj () {
} public FloatObj (float i) {
value = i;
}
}
class LongObj {
public long value;
public LongObj () {
} public LongObj (long i) {
value = i;
}
}
class DoubleObj {
public double value;
public DoubleObj () {
} public DoubleObj (double i) {
value = i;
}
}
class CharObj {
public char value;
public CharObj () {
} public CharObj (char i) {
value = i;
}
}
public class digits_ca94e375_002 {
public java.util.Scanner scanner;
public String output = "";
public static void main (String[]args) throws Exception {
digits_ca94e375_002 mainClass = new digits_ca94e375_002 ();
String output;
if (args.length > 0) {
mainClass.scanner = new java.util.Scanner (args[0]);
} else {
mainClass.scanner = new java.util.Scanner (System.in);
}
mainClass.exec ();
System.out.println (mainClass.output);
}
public void exec () throws Exception {
IntObj n = new IntObj ();
IntObj x = new IntObj (), y = new IntObj ();
IntObj temp = new IntObj ();
output += (String.format ("\nEnter an integer > "));
y.value = scanner.nextInt ();
n.value = 0;
while (n.value <= 10) {
if (y.value == 0) {
output += (String.format ("\n%d", y.value));
output += (String.format ("\nThat's all, have a nice day!\n"));
if (true)
return;;
}
x.value = y.value % 10;
output += (String.format ("\n%d", Math.abs (x.value)));
x.value = y.value / 10;
if ((x.value) < 0 && x.value < 0) {
output += (String.format ("\n%d", x.value));
output += (String.format ("\nThat's all, have a nice day!\n"));
if (true)
return;;
}
temp.value = x.value;
x.value = y.value;
y.value = temp.value;
n.value = n.value + 1;
}
if (true)
return;;
}
}
| [
"justinwm@163.com"
] | justinwm@163.com |
82cae554cedca1dce18ba205ed981688c62abcc7 | 260ffc8ab1409b781cfdd8d5ed44c600eb276986 | /duo-core/src/main/java/com/duo/core/utils/SpringUtil.java | 3ff874d7293d9c311cb500aef68eb180b80bfa9b | [] | no_license | qingtingduizhang77/duo | bbc8bf4752818952cf1fe8bad428b949a76cfa8b | 5ca6ff9d1e44f5ac36860468c0789a4884ad0934 | refs/heads/master | 2023-01-29T21:08:09.191741 | 2020-12-14T07:13:47 | 2020-12-14T07:13:47 | 321,250,525 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,935 | java | /**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.duo.core.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public final class SpringUtil implements BeanFactoryPostProcessor {
private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtil.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getAliases(name);
}
}
| [
"qingtingduizhang77@163.com"
] | qingtingduizhang77@163.com |
0335c174fb2a2c7498cbfd39088ebe06f18a5485 | 9fbf249e8ffacd4121f9c00ba30b052d6af76f22 | /library/src/main/java/com/santalu/autoviewpager/AutoViewPager.java | fa41b3c1efb563bad8a8394d2216725a5bc05d80 | [
"Apache-2.0"
] | permissive | naseemakhtar994/auto-viewpager | 7f92083d97fc0d1c894efe64f67c9430d6dc8e9b | a8a8a02b0c3d02c257c63fe9bd953a2be5f969ef | refs/heads/master | 2021-01-15T22:01:43.836133 | 2017-08-09T18:37:02 | 2017-08-09T18:37:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,879 | java | package com.santalu.autoviewpager;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* Created by santalu on 09/08/2017.
*/
public class AutoViewPager extends ViewPager {
private static final String TAG = AutoViewPager.class.getSimpleName();
private static final int DEFAULT_DURATION = 10000;
private int mDuration = DEFAULT_DURATION;
private float mStartX;
private boolean mAutoScrollEnabled;
private boolean mIndeterminate;
private final Runnable mAutoScroll = new Runnable() {
@Override public void run() {
if (!isShown()) {
return;
}
if (getCurrentItem() == getAdapter().getCount() - 1) {
setCurrentItem(0);
} else {
setCurrentItem(getCurrentItem() + 1);
}
postDelayed(mAutoScroll, mDuration);
}
};
public AutoViewPager(Context context) {
super(context);
}
public AutoViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.AutoViewPager);
try {
setAutoScrollEnabled(a.getBoolean(R.styleable.AutoViewPager_avp_autoScroll, false));
setIndeterminate(a.getBoolean(R.styleable.AutoViewPager_avp_indeterminate, false));
setDuration(a.getInteger(R.styleable.AutoViewPager_avp_duration, DEFAULT_DURATION));
} finally {
a.recycle();
}
}
public void setIndeterminate(boolean indeterminate) {
mIndeterminate = indeterminate;
}
public void setAutoScrollEnabled(boolean enabled) {
if (mAutoScrollEnabled == enabled) {
return;
}
mAutoScrollEnabled = enabled;
stopAutoScroll();
if (enabled) {
startAutoScroll();
}
}
public void setDuration(int duration) {
mDuration = duration;
}
private void startAutoScroll() {
postDelayed(mAutoScroll, mDuration);
}
private void stopAutoScroll() {
removeCallbacks(mAutoScroll);
}
@Override public boolean onInterceptTouchEvent(MotionEvent event) {
try {
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN:
mStartX = event.getX();
break;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
return super.onInterceptTouchEvent(event);
}
@Override public boolean onTouchEvent(MotionEvent event) {
if (mIndeterminate) {
try {
if (getCurrentItem() == 0 || getCurrentItem() == getAdapter().getCount() - 1) {
final int action = event.getAction();
float x = event.getX();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
if (getCurrentItem() == getAdapter().getCount() - 1 && x < mStartX) {
post(new Runnable() {
@Override public void run() {
setCurrentItem(0);
}
});
}
break;
}
} else {
mStartX = 0;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
return super.onTouchEvent(event);
}
}
| [
"ftsantalu@gmail.com"
] | ftsantalu@gmail.com |
0ac06fd6d12b79934c097132e286e2cb329d6265 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/neo4j--neo4j/c268b8478116e9045735629088b9e742609b1dac/before/SchemaAcceptanceTest.java | 4f9b29e64467ecff6d1cd36cfc18ff462afc104c | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,043 | java | /**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.graphdb;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.neo4j.helpers.collection.Iterables.map;
import static org.neo4j.helpers.collection.IteratorUtil.asSet;
import static org.neo4j.helpers.collection.IteratorUtil.single;
import org.junit.Rule;
import org.junit.Test;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.graphdb.schema.Schema;
import org.neo4j.helpers.Function;
import org.neo4j.test.ImpermanentDatabaseRule;
public class SchemaAcceptanceTest
{
public @Rule
ImpermanentDatabaseRule dbRule = new ImpermanentDatabaseRule();
private enum Labels implements Label
{
MY_LABEL,
MY_OTHER_LABEL
}
@Test
public void addingAnIndexingRuleShouldSucceed() throws Exception
{
// Given
GraphDatabaseService beansAPI = dbRule.getGraphDatabaseService();
Schema schema = beansAPI.schema();
String property = "my_property_key";
Labels label = Labels.MY_LABEL;
// When
IndexDefinition index = createIndexRule( beansAPI, label, property );
// Then
assertEquals( asSet( property ), asSet( singlePropertyKey( schema.getIndexes( label ) ) ) );
assertTrue( asSet( schema.getIndexes( label ) ).contains( index ) );
}
private IndexDefinition createIndexRule( GraphDatabaseService beansAPI, Label label, String property )
{
Transaction tx = beansAPI.beginTx();
try
{
IndexDefinition result = beansAPI.schema().indexCreator( label ).on( property ).create();
tx.success();
return result;
}
finally
{
tx.finish();
}
}
private Iterable<String> singlePropertyKey( Iterable<IndexDefinition> indexes )
{
return map( new Function<IndexDefinition, String>()
{
@Override
public String apply( IndexDefinition from )
{
return single( from.getPropertyKeys() );
}
}, indexes );
}
@Test(expected = ConstraintViolationException.class)
public void shouldThrowConstraintViolationIfAskedToIndexSamePropertyAndLabelTwiceInSameTx() throws Exception
{
// Given
GraphDatabaseService beansAPI = dbRule.getGraphDatabaseService();
Schema schema = beansAPI.schema();
String property = "my_property_key";
// When
Transaction tx = beansAPI.beginTx();
try
{
schema.indexCreator( Labels.MY_LABEL ).on( property ).create();
schema.indexCreator( Labels.MY_LABEL ).on( property ).create();
tx.success();
}
finally
{
tx.finish();
}
}
@Test
public void shouldThrowConstraintViolationIfAskedToIndexPropertyThatIsAlreadyIndexed() throws Exception
{
// Given
GraphDatabaseService beansAPI = dbRule.getGraphDatabaseService();
Schema schema = beansAPI.schema();
String property = "my_property_key";
// And given
Transaction tx = beansAPI.beginTx();
schema.indexCreator( Labels.MY_LABEL ).on( property ).create();
tx.success();
tx.finish();
// When
ConstraintViolationException caught = null;
tx = beansAPI.beginTx();
try
{
schema.indexCreator( Labels.MY_LABEL ).on( property ).create();
tx.success();
}
catch(ConstraintViolationException e)
{
caught = e;
}
finally
{
tx.finish();
}
// Then
assertThat(caught, not(nullValue()));
}
@Test(expected = UnsupportedOperationException.class)
public void shouldThrowConstraintViolationIfAskedToCreateCompoundIdex() throws Exception
{
// Given
GraphDatabaseService beansAPI = dbRule.getGraphDatabaseService();
Schema schema = beansAPI.schema();
// When
Transaction tx = beansAPI.beginTx();
try
{
schema.indexCreator( Labels.MY_LABEL )
.on( "my_property_key" )
.on( "other_property" ).create();
tx.success();
}
finally
{
tx.finish();
}
}
@Test
public void droppingExistingIndexRuleShouldSucceed() throws Exception
{
// GIVEN
GraphDatabaseService beansAPI = dbRule.getGraphDatabaseService();
String property = "name";
Labels label = Labels.MY_LABEL;
IndexDefinition index = createIndexRule( beansAPI, label, property );
// WHEN
Transaction tx = beansAPI.beginTx();
try
{
index.drop();
tx.success();
}
finally
{
tx.finish();
}
// THEN
assertFalse( "Index should have been deleted", asSet( beansAPI.schema().getIndexes( label ) ).contains( index ) );
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
e13583ffa9bc2a4e168b9f00b64b2a031f736ad4 | 580f5fbb174e20302dfdd355c81afb64e4d92175 | /exemploGit/src/exemplogit/ExemploGit.java | 71723a9b3931d7c97cc08d5573a106c037a77252 | [] | no_license | RenanDiogenes/HelpAnimal | ce0648c9709c43dda9501354db733c06a2a91583 | 10fceb27a07853df35d73f62933977ee80732e1d | refs/heads/master | 2021-01-12T12:23:41.003884 | 2017-09-24T17:25:14 | 2017-09-24T17:25:14 | 72,482,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 219 | java |
package exemplogit;
/**
*
* @author RENAN DIGENES
*/
public class ExemploGit {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
}
}
| [
"RENAN DIGENES@DESKTOP-OFNTEML"
] | RENAN DIGENES@DESKTOP-OFNTEML |
288fa296bd08351d57b632982afba3be2271884f | f21e26ed856b85cbb45f2ab01eb8562ec4720181 | /portal/patric-libs/src/edu/vt/vbi/patric/common/SiteHelper.java | f87a77eab33bd449bb9d371c0943d4b7f544b875 | [
"MIT"
] | permissive | ARWattam/patric3_website | ef01d63e20eae47ebb4750b3572a57b296d5e265 | 1161b51d4222984ceace50e42c28c944489e75b5 | refs/heads/master | 2020-04-04T20:04:22.716319 | 2016-09-12T20:00:18 | 2016-09-12T20:00:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,526 | java | /**
* ****************************************************************************
* Copyright 2014 Virginia Polytechnic Institute and State University
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ****************************************************************************
*/
package edu.vt.vbi.patric.common;
import edu.vt.vbi.patric.beans.Genome;
import edu.vt.vbi.patric.beans.GenomeFeature;
import edu.vt.vbi.patric.beans.Taxonomy;
import org.w3c.dom.Element;
import javax.portlet.MimeResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
public class SiteHelper {
public static String getLinks(String target, String id) {
String link = "";
switch (target) {
case "taxon_overview":
link = "<a href=\"Taxon?cType=taxon&cId=" + id
+ "\"><img src=\"/patric/images/icon_taxon.gif\" alt=\"Taxonomy Overview\" title=\"Taxonomy Overview\" /></a>";
break;
case "genome_list":
link = "<a href=\"GenomeList?cType=taxon&cId=" + id
+ "&dataSource=All&displayMode=genome\"><img src=\"/patric/images/icon_sequence_list.gif\" alt=\"Genome List\" title=\"Genome List\" /></a>";
break;
case "feature_table":
link = "<a href=\"FeatureTable?cType=taxon&cId=" + id
+ "&featuretype=CDS&annotation=All&filtertype=\"><img src=\"/patric/images/icon_table.gif\" alt=\"Feature Table\" title=\"Feature Table\"/></a>";
break;
}
return link;
}
public static String getExternalLinks(String target) {
String link = "";
if (target.equalsIgnoreCase("ncbi_gene")) {
link = "//www.ncbi.nlm.nih.gov/sites/entrez?db=gene&cmd=Retrieve&dopt=full_report&list_uids=";
}
else if (target.equalsIgnoreCase("ncbi_accession")) {
link = "//www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=";
}
else if (target.equalsIgnoreCase("ncbi_protein") || target.equalsIgnoreCase("RefSeq") || target.equalsIgnoreCase("GI")) {
link = "//www.ncbi.nlm.nih.gov/protein/";
}
else if (target.equalsIgnoreCase("RefSeq_NT")) {
link = "//www.ncbi.nlm.nih.gov/nuccore/"; // NC_010067.1 - // nucleotide db
}
else if (target.equalsIgnoreCase("go_term")) {
link = "http://amigo.geneontology.org/cgi-bin/amigo/term_details?term="; // GO:0004747
}
else if (target.equalsIgnoreCase("ec_number")) {
link = "http://enzyme.expasy.org/EC/"; // 2.7.1.15
}
else if (target.equalsIgnoreCase("kegg_pathwaymap") || target.equalsIgnoreCase("KEGG")) {
link = "http://www.genome.jp/dbget-bin/www_bget?"; // pathway+map00010
}
else if (target.equalsIgnoreCase("UniProtKB-Accession") || target.equalsIgnoreCase("UniProtKB-ID")) {
link = "http://www.uniprot.org/uniprot/"; // A9MFG0 or ASTD_SALAR
}
else if (target.equalsIgnoreCase("UniRef100") || target.equalsIgnoreCase("UniRef90") || target.equalsIgnoreCase("UniRef50")) {
link = "http://www.uniprot.org/uniref/"; // UniRef100_A9MFG0, UniRef90_B5F7J0, or // UniRef50_Q1C8A9
}
else if (target.equalsIgnoreCase("UniParc")) {
link = "http://www.uniprot.org/uniparc/"; // UPI0001603B3F
}
else if (target.equalsIgnoreCase("EMBL") || target.equalsIgnoreCase("EMBL-CDS")) {
link = "//www.ebi.ac.uk/ena/data/view/"; // CP000880, ABX21565
}
else if (target.equalsIgnoreCase("GeneID")) {
link = "//www.ncbi.nlm.nih.gov/sites/entrez?db=gene&term="; // 5763416;
}
else if (target.equalsIgnoreCase("GenomeReviews")) {
link = "http://www.genomereviews.ebi.ac.uk/GR/contigview?chr="; // CP000880_GR
}
else if (target.equalsIgnoreCase("eggNOG")) {
link = "http://eggnog.embl.de/cgi_bin/display_multi_clusters.pl?linksource=uniprot&level=0&1="; // Q2YII1 -- uniprot accession
}
else if (target.equalsIgnoreCase("HOGENOM")) {
link = "http://pbil.univ-lyon1.fr/cgi-bin/acnuc-ac2tree?db=HOGENOM&query="; // A9MFG0 -- uniprot accession
}
else if (target.equalsIgnoreCase("OMA")) {
link = "http://omabrowser.org/cgi-bin/gateway.pl?f=DisplayGroup&p1="; // A9MFG0 -- uniprot accession
}
else if (target.equalsIgnoreCase("ProtClustDB")) {
link = "//www.ncbi.nlm.nih.gov/sites/entrez?Db=proteinclusters&Cmd=DetailsSearch&Term="; // A9MFG0 -- uniprot accession
}
else if (target.equalsIgnoreCase("BioCyc")) {
link = "http://biocyc.org/getid?id="; // BMEL359391:BAB2_0179-MONOMER
}
else if (target.equalsIgnoreCase("NMPDR")) {
link = "//www.nmpdr.org/linkin.cgi?id="; // fig|382638.8.peg.1669"
}
else if (target.equalsIgnoreCase("EnsemblGenome") || target.equalsIgnoreCase("EnsemblGenome_TRS")
|| target.equalsIgnoreCase("EnsemblGenome_PRO")) {
link = "http://www.ensemblgenomes.org/id/"; // EBMYCT00000005579
}
else if (target.equalsIgnoreCase("BEIR")) {
link = "http://www.beiresources.org/Catalog/ItemDetails/tabid/522/Default.aspx?Template=Clones&BEINum=";
}
else if (target.equalsIgnoreCase("PDB")) {
link = "Jmol?structureID=";
}
else if (target.equalsIgnoreCase("STRING")) { // 204722.BR0001
link = "http://string.embl.de/newstring_cgi/show_network_section.pl?identifier=";
}
else if (target.equalsIgnoreCase("MEROPS")) { // M50.005
link = "http://merops.sanger.ac.uk/cgi-bin/pepsum?id=";
}
else if (target.equalsIgnoreCase("PATRIC")) { // 17788255
link = "Feature?cType=feature&cId=";
}
else if (target.equalsIgnoreCase("OrthoDB")) { // EOG689HR1
link = "http://cegg.unige.ch/orthodb7/results?searchtext=";
}
else if (target.equalsIgnoreCase("NCBI_TaxID")) { // 29461
link = "//www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=";
}
else if (target.equalsIgnoreCase("KO")) { // K04756
link = "http://www.genome.jp/dbget-bin/www_bget?ko:";
}
else if (target.equalsIgnoreCase("TubercuList")) { // Rv2429
link = "http://tuberculist.epfl.ch/quicksearch.php?gene+name=";
}
else if (target.equalsIgnoreCase("PeroxiBase")) { // 4558
link = "http://peroxibase.toulouse.inra.fr/browse/process/view_perox.php?id=";
}
else if (target.equalsIgnoreCase("Reactome")) { // REACT_116125
link = "http://www.reactome.org/cgi-bin/eventbrowser_st_id?ST_ID=";
}
else if (target.equalsIgnoreCase("VFDB")) {
link = "http://www.mgc.ac.cn/cgi-bin/VFs/gene.cgi?GeneID="; // VFG1817
}
else if (target.equalsIgnoreCase("VFDB_HOME")) {
link = "http://www.mgc.ac.cn/VFs/";
}
else if (target.equalsIgnoreCase("Victors")) {
link = "http://www.phidias.us/victors/gene_detail.php?c_mc_victor_id="; // 220
}
else if (target.equalsIgnoreCase("Victors_HOME")) {
link = "http://www.phidias.us/victors/";
}
else if (target.equalsIgnoreCase("PATRIC_VF")) {
link = "SpecialtyGeneEvidence?source=PATRIC_VF&sourceId="; // Rv3875
}
else if (target.equalsIgnoreCase("PATRIC_VF_HOME")) {
link = "SpecialtyGeneSource?source=PATRIC_VF&kw=";
}
else if (target.equalsIgnoreCase("ARDB")) {
link = "//ardb.cbcb.umd.edu/cgi/search.cgi?db=R&term="; // AAL09826
}
else if (target.equalsIgnoreCase("ARDB_HOME")) {
link = "//ardb.cbcb.umd.edu/";
}
else if (target.equalsIgnoreCase("CARD")) {
link = ""; //TODO: need to add
}
else if (target.equalsIgnoreCase("CARD_HOME")) {
link = "http://arpcard.mcmaster.ca";
}
else if (target.equalsIgnoreCase("DrugBank")) {
link = "http://v3.drugbank.ca/molecules/"; // 1
}
else if (target.equalsIgnoreCase("DrugBank_HOME")) {
link = "http://v3.drugbank.ca";
}
else if (target.equalsIgnoreCase("TTD")) {
link = "http://bidd.nus.edu.sg/group/TTD/ZFTTDDetail.asp?ID="; // TTDS00427
}
else if (target.equalsIgnoreCase("TTD_HOME")) {
link = "http://bidd.nus.edu.sg/group/TTD/ttd.asp";
}
else if (target.equalsIgnoreCase("Human")) {
link = "//www.ncbi.nlm.nih.gov/protein/"; // NP_001005484.1
}
else if (target.equalsIgnoreCase("Human_HOME")) {
link = "//www.ncbi.nlm.nih.gov/assembly/GCF_000001405.26";
}
else if (target.equalsIgnoreCase("bioproject_accession")) {
link = "http://www.ncbi.nlm.nih.gov/bioproject/?term=";
}
else if (target.equalsIgnoreCase("biosample_accession")) {
link = "http://www.ncbi.nlm.nih.gov/biosample/";
}
else if (target.equalsIgnoreCase("assembly_accession")) {
link = "http://www.ncbi.nlm.nih.gov/assembly/";
}
// edit patric-searches-and-tools/WebContent/js/specialty_gene_list_grids.js as well
return link;
}
/*
* @ called by patric-overview/WebContents/WEB-INF/jsp/feature_summary.jsp
*/
public static String getGenusByStructuralGenomicsCenter(String name) {
// 'Mycobacterium', 'Bartonella', 'Brucella', 'Ehrlichia', 'Rickettsia',
// 'Burkholderia', 'Borrelia', 'Anaplasma'
// 1763,138,780,773,234,943,32008,768
String ssgcid = "Mycobacterium|Bartonella|Brucella|Ehrlichia|Rickettsia|Burkholderia|Borrelia|Anaplasma";
// 'Bacillus', 'Listeria', 'Staphylococcus', 'Streptococcus',
// 'Clostridium',
// 'Coxiella', 'Escherichia', 'Francisella', 'Salmonella', 'Shigella',
// 'Vibrio', 'Yersinia', 'Campylobacter', 'Helicobacter'
// 1485,1279,1386,1301,1637,194,662,209,776,620,262,561,629,590
String csgid = "Bacillus|Listeria|Staphylococcus|Streptococcus|Clostridium|Coxiella|Escherichia|Francisella|Salmonella|Shigella|Vibrio|Yersinia|Campylobacter|Helicobacter";
switch (name) {
case "ssgcid":
return ssgcid;
case "csgid":
return csgid;
default:
return "";
}
}
public static void setHtmlMetaElements(RenderRequest req, RenderResponse res, String context) {
StringBuilder sbTitle = new StringBuilder().append("PATRIC::");
StringBuilder sbKeyword = new StringBuilder();
String contextType = req.getParameter("context_type");
String contextId = req.getParameter("context_id");
if (contextType != null && contextId != null && !contextId.equals("")) {
// Get taxon/genome/feature info
DataApiHandler dataApi = new DataApiHandler(req);
switch (contextType) {
case "taxon":
Taxonomy taxonomy = dataApi.getTaxonomy(Integer.parseInt(contextId));
if (taxonomy != null) {
sbTitle.append(taxonomy.getTaxonName()).append("::").append(context);
sbKeyword.append(context).append(", ").append(taxonomy.getTaxonName()).append(", PATRIC");
}
else {
sbTitle.append(context);
}
break;
case "genome":
Genome genome = dataApi.getGenome(contextId);
if (genome != null) {
sbTitle.append(genome.getGenomeName()).append("::").append(context);
sbKeyword.append(context).append(", ").append(genome.getGenomeName()).append(", PATRIC");
}
break;
case "feature":
GenomeFeature feature = dataApi.getFeature(contextId);
if (feature != null) {
if (feature.hasPatricId()) {
sbTitle.append(feature.getPatricId()).append(":").append(feature.getProduct()).append("::").append(context);
sbKeyword.append(context).append(", ").append(feature.getPatricId()).append(":").append(feature.getProduct())
.append(", PATRIC");
}
else if (feature.getRefseqLocusTag() != null) {
sbTitle.append(feature.getRefseqLocusTag()).append(":").append(feature.getProduct()).append("::").append(context);
sbKeyword.append(context).append(", ").append(feature.getRefseqLocusTag()).append(":").append(feature.getProduct())
.append(", PATRIC");
}
else {
sbTitle.append(feature.getAltLocusTag()).append(":").append(feature.getProduct()).append("::").append(context);
sbKeyword.append(context).append(", ").append(feature.getAltLocusTag()).append(":").append(feature.getProduct())
.append(", PATRIC");
}
}
break;
}
}
else {
sbTitle.append(context);
sbKeyword.append(context).append(", PATRIC");
}
// Setup elements
Element elTitle = res.createElement("title");
Element elKeywords = res.createElement("meta");
elTitle.setTextContent(sbTitle.toString());
elKeywords.setAttribute("name", "Keywords");
elKeywords.setAttribute("content", sbKeyword.toString());
// Set to headerContents
res.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, elTitle);
res.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, elKeywords);
}
}
| [
"hyun@vbi.vt.edu"
] | hyun@vbi.vt.edu |
581fca3a549605bc7c21f3a70119b717cb4b8a17 | c00436639343b3c3cec30b0abebc16c05f09bd7b | /RouteManager/src/main/java/com/BRP/routemanager/models/LoginRequest.java | 592aba08f3104f9e51ad3a2a8746a601c583b2fd | [] | no_license | 007durgesh219/routemanager | e5fc2cf2293b6e846c9cd901c1df2d67bca62627 | 78699b8665fd3900e715e40e8b12eda4bd5e139f | refs/heads/master | 2020-12-24T07:59:58.709792 | 2016-08-07T07:54:41 | 2016-08-07T07:54:41 | 58,542,541 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 314 | java | package com.BRP.routemanager.models;
/**
* Created by durgesh on 5/11/16.
*/
public class LoginRequest {
public String username, password, fromApp;
public LoginRequest(String username, String password) {
this.username = username;
this.password = password;
fromApp = "1";
}
}
| [
"007durgesh219@gmail.com"
] | 007durgesh219@gmail.com |
06c5c93909b8e3f44688762351b2aeb5285f11cc | a659a9f9c9eae2229e4a8da1b7eea07edfb7c1ed | /src/main/java/com/palette/busi/project/tms/business/basic/login/vo/MenuResultVo.java | 1c67fe3a32ecdedd6fa3477c751fc7149000542e | [] | no_license | paletter/tms-webapp | e8068d4385c1fefd9e06147a0896cf91ee5b58f4 | 90142054d2b3325a661a17572695231b558caa47 | refs/heads/master | 2021-01-19T04:27:21.582095 | 2017-02-17T07:12:32 | 2017-02-17T07:12:32 | 49,817,750 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java | package com.palette.busi.project.tms.business.basic.login.vo;
import java.util.List;
public class MenuResultVo {
private String category;
private String menuCate;
private List<MenuSubResultVo> menuSubList;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getMenuCate() {
return menuCate;
}
public void setMenuCate(String menuCate) {
this.menuCate = menuCate;
}
public List<MenuSubResultVo> getMenuSubList() {
return menuSubList;
}
public void setMenuSubList(List<MenuSubResultVo> menuSubList) {
this.menuSubList = menuSubList;
}
}
| [
"fangbo123"
] | fangbo123 |
736ae81401f49d06c47cc8832a250e685b3c1061 | 1dc904851d9a922ed2e8a63178e7d9153e72d422 | /app/src/main/java/com/salah/taskmaster/RoomDB.java | e53813954651aa890dc35ea1815c39fb1aa166f7 | [
"MIT"
] | permissive | SalahAlawneh/taskmaster | bf84fac0b93a6cf8d3e7a6c1ff1b625650f56b89 | 74e6df531ebf6bedb93462b8bdb6d82af4a5cdae | refs/heads/main | 2023-05-30T20:55:11.488832 | 2021-06-09T19:43:57 | 2021-06-09T19:43:57 | 368,064,432 | 0 | 0 | MIT | 2021-06-09T19:43:58 | 2021-05-17T05:21:21 | Java | UTF-8 | Java | false | false | 885 | java | package com.salah.taskmaster;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.salah.taskmaster.MainDao;
import com.salah.taskmaster.Task;
@Database(entities = {Task.class}, version = 1, exportSchema = false)
public abstract class RoomDB extends RoomDatabase {
private static RoomDB database;
private static String DATABASE_NAME = "database";
public synchronized static RoomDB getInstance(Context context) {
if (database == null) {
database = Room.databaseBuilder(context.getApplicationContext()
, RoomDB.class, DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
}
return database;
}
public abstract MainDao mainDao();
}
| [
"salah.alawneh@yahoo.com"
] | salah.alawneh@yahoo.com |
e6344e2e6f2ba803e3b13cbff50fc0b2ff57c480 | cd84616085a2e9478a1f66ff30a645df8b29c66d | /src/main/java/HashtagCounterBolt.java | 2a2b44381dc1dfd45f08c308a9c3020134ed60ba | [] | no_license | LorenzoAgnolucci/TwitterRealTimeSentimentAnalysis | a86f91b1549eb928e5caa7dba581a60702f4d03d | d945ad48e10462007c9240625cb1235ecf53e90f | refs/heads/master | 2020-12-21T07:31:03.972535 | 2020-03-31T11:52:49 | 2020-03-31T11:52:49 | 236,359,019 | 5 | 1 | null | 2020-01-26T19:21:49 | 2020-01-26T18:48:02 | Java | UTF-8 | Java | false | false | 1,399 | java | import java.util.HashMap;
import java.util.Map;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Tuple;
public class HashtagCounterBolt implements IRichBolt {
Map<String, Integer> counterMap;
private OutputCollector collector;
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.counterMap = new HashMap<String, Integer>();
this.collector = collector;
}
public void execute(Tuple tuple) {
String key = tuple.getString(0);
if(!counterMap.containsKey(key)){
counterMap.put(key, 1);
}else{
Integer c = counterMap.get(key) + 1;
counterMap.put(key, c);
}
collector.ack(tuple);
}
public void cleanup() {
for(Map.Entry<String, Integer> entry:counterMap.entrySet()){
System.out.println("Result: " + entry.getKey()+" : " + entry.getValue());
}
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("hashtag"));
}
public Map<String, Object> getComponentConfiguration() {
return null;
}
} | [
"lory.agnolucci@gmail.com"
] | lory.agnolucci@gmail.com |
7f39b4652f698147d1527108d0dbfa6724b73a92 | 95ded8f6a963aea6ebb24c07985382e253c25596 | /tensquare_common/src/main/java/entity/Result.java | ef692115922120dcc64f2d204bf287553516ec5e | [] | no_license | LinXiaoBaiXCG/tensquare | 764c3307f3d4827f35e9bd25b886967369245a6a | 552424b6aa30c2328ca53c50b2048a69bc3c8713 | refs/heads/master | 2020-11-25T11:24:08.938528 | 2019-12-24T15:31:17 | 2019-12-24T15:31:17 | 228,636,225 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 705 | java | package entity;
import lombok.Data;
/**
* @program: tensquare_parent
* @description: 返回实体类
* @author: LCQ
* @create: 2019-12-17 16:08
**/
@Data
public class Result {
private boolean flag;
private Integer code;
private String message;
private Object data;
/**
* 控构造器
*/
public Result() {
}
public Result(Boolean flag, Integer code, String message) {
this.flag = flag;
this.code = code;
this.message = message;
}
public Result(Boolean flag, Integer code, String message, Object data) {
this.flag = flag;
this.code = code;
this.message = message;
this.data = data;
}
}
| [
"1203718422@qq.com"
] | 1203718422@qq.com |
eadbb6ab0f624c4319e281fb15ef333229cc73eb | 61b8566c8fe00cc8213fed702a3a5bf377bfc400 | /src/GUI/ListaArtikujve.java | 7cd9236f780741ed20e179f26a806be035da8114 | [] | no_license | kushtrimrrahimi/SUPERMARKETI | e6dc3049de5a5f548a35141c0c4cc11c97c8bc59 | eb02fd04d320309a2f1189e9d2f5a97ff6695a38 | refs/heads/master | 2023-08-03T12:20:36.043291 | 2021-09-13T19:42:38 | 2021-09-13T19:42:38 | 406,107,086 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,598 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.swing.JOptionPane.showMessageDialog;
import net.proteanit.sql.DbUtils;
/**
*
* @author ARSIM
*/
public class ListaArtikujve extends javax.swing.JInternalFrame {
public ListaArtikujve() {
initComponents();
showArtikujt();
}
public void showArtikujt(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;databaseName=supermarket;user=sa;password=sa1234";
Connection conn = DriverManager.getConnection(url);
String sql = "SELECT * FROM ARTIKULLI";
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
tabelaArtikujve.setModel(DbUtils.resultSetToTableModel(rs));
tabelaArtikujve.removeColumn(tabelaArtikujve.getColumnModel().getColumn(0));
tabelaArtikujve.removeColumn(tabelaArtikujve.getColumnModel().getColumn(0));
} catch (Exception ex) {
showMessageDialog(null, ex);
}
}
private void fshij(){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;databaseName=supermarket;user=sa;password=sa1234";
Connection conn = DriverManager.getConnection(url);
int row = tabelaArtikujve.getSelectedRow();
String value = (tabelaArtikujve.getModel().getValueAt(row, 0).toString());
String sql = "DELETE FROM ARTIKULLI WHERE ARTIKULLI_ID =" + value;
PreparedStatement pst = conn.prepareStatement(sql);
if(row < 0){
showMessageDialog(null, "Zgjidh nje artikull");
return;
}
else{
pst.executeUpdate();
}
showArtikujt();
}
catch(Exception ex){
showMessageDialog(null,ex);
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tabelaArtikujve = new javax.swing.JTable();
fshijbutton = new javax.swing.JButton();
setClosable(true);
tabelaArtikujve.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
tabelaArtikujve.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tabelaArtikujve.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
tabelaArtikujveKeyPressed(evt);
}
});
jScrollPane1.setViewportView(tabelaArtikujve);
fshijbutton.setText("F2 - FSHIJ");
fshijbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fshijbuttonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(fshijbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 789, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fshijbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void fshijbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fshijbuttonActionPerformed
fshij();
}//GEN-LAST:event_fshijbuttonActionPerformed
private void tabelaArtikujveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tabelaArtikujveKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_F2){
fshij();
}
}//GEN-LAST:event_tabelaArtikujveKeyPressed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton fshijbutton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tabelaArtikujve;
// End of variables declaration//GEN-END:variables
}
| [
"90649397+kushtrimrrahimi@users.noreply.github.com"
] | 90649397+kushtrimrrahimi@users.noreply.github.com |
69bc6729b0cb1b8fdcae27002dfa61b1db903d27 | 28d71af491563505031a979af03c0bf7a0132012 | /Arrays and Strings/Question2.java | 1a7966a727f3b6be42145013bf5728cb8db4ce9a | [] | no_license | antoniosj/Cracking-the-Coding-Interview | 235453be2582f97e4715d6103ba3dc127173c70a | 3a557a507a5fea1732e6baec12718e8bc102791d | refs/heads/master | 2021-01-20T13:26:13.731458 | 2017-07-09T19:50:31 | 2017-07-09T19:50:31 | 90,489,323 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 599 | java | package io.github.antoniosj.strings;
import java.util.HashMap;
public class Question2 {
public static boolean isPermutation(String a, String b){
int[] letterCount = new int[52];
if (a.length() != b.length()){
return false;
}
for (int i = 0; i < a.length(); i++) {
letterCount[a.charAt(i) - 'a'] += 1;
letterCount[b.charAt(i) - 'a'] += 1;
}
for (int j = 0; j < 52; j++) {
if ((letterCount[j] % 2) != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(isPermutation("abc","cca"));
}
}
| [
"antonio.silvajr23@gmail.com"
] | antonio.silvajr23@gmail.com |
7a864f6c736bf74a3dc3721268a51f33e53454a0 | fb99bf0d48b16b7d21735d78eb3ffd52d9491360 | /Modulo9/src/fors/TestForOne.java | ba5f3b42de14f35f575b5d6233f901c5051bad89 | [] | no_license | devendarg/java | 594e1515d5d1855bf0359d618c9ab109787285aa | 02195fc5a5e5f5fdb9b9313f33507e7a23dafebb | refs/heads/master | 2021-01-11T13:37:08.972699 | 2016-04-28T15:45:59 | 2016-04-28T15:45:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 402 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fors;
/**
*
* @author christianjimenezcjs
*/
public class TestForOne {
public static void main(String[] args) {
/*for(;;){
System.out.println("Bucle Infinito");
}*/
}
}
| [
"christianjimenezcjs@gmail.com"
] | christianjimenezcjs@gmail.com |
0b227d9bdf77111e09d47bea7ee6370123638829 | c885ef92397be9d54b87741f01557f61d3f794f3 | /tests-without-trycatch/JacksonXml-1/com.fasterxml.jackson.dataformat.xml.deser.FromXmlParser/BBC-F0-opt-50/15/com/fasterxml/jackson/dataformat/xml/deser/FromXmlParser_ESTest.java | 6c2ad7c7e23be41d05f46ee02b88aca4fdc89d58 | [
"CC-BY-4.0",
"MIT"
] | permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 2,198 | java | /*
* This file was automatically generated by EvoSuite
* Wed Oct 20 11:03:08 GMT 2021
*/
package com.fasterxml.jackson.dataformat.xml.deser;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.io.IOContext;
import com.fasterxml.jackson.core.util.BufferRecycler;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.dataformat.xml.deser.FromXmlParser;
import javax.xml.stream.XMLStreamReader;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class FromXmlParser_ESTest extends FromXmlParser_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
int int0 = FromXmlParser.Feature.collectDefaults();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test1() throws Throwable {
BufferRecycler bufferRecycler0 = new BufferRecycler();
IOContext iOContext0 = new IOContext(bufferRecycler0, bufferRecycler0, false);
JsonFactory jsonFactory0 = new JsonFactory();
ObjectMapper objectMapper0 = new ObjectMapper(jsonFactory0);
DeserializationFeature deserializationFeature0 = DeserializationFeature.FAIL_ON_INVALID_SUBTYPE;
ObjectReader objectReader0 = objectMapper0.reader(deserializationFeature0);
FromXmlParser fromXmlParser0 = null;
// try {
fromXmlParser0 = new FromXmlParser(iOContext0, (-1051), (-1104), objectReader0, (XMLStreamReader) null);
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("com.fasterxml.jackson.dataformat.xml.deser.XmlTokenStream", e);
// }
}
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
3427a38d56707df690e2843ab7eea4f4710ff4a3 | b1434b41337f6dd09ba37270dd796052d2a57f52 | /src/main/java/com/phone/etl/test.java | 87d5e1daf1b76f4f199e7ac08a2f9e490dd20e2e | [] | no_license | susu0919/phone_analystic | 39239da92106af3e55d7ac2f2bcec27144063d35 | c37940bf4c17f84a99161edfa940017efb6d654d | refs/heads/master | 2020-03-28T23:06:12.617288 | 2018-09-18T11:17:16 | 2018-09-18T11:17:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 47 | java | package com.phone.etl;
public class test {
}
| [
"1835488217@qq.com"
] | 1835488217@qq.com |
f124d600d6b9e633946f3356844c63c18ec96dbb | dbc996396a33e1270cbe4437c603f723f1f98561 | /src/main/java/com/leandev/downloader/AdvancedFileDownloader.java | 19133b7a74f10144d09dcd5c1bf0ae7d26ee9bdc | [] | no_license | jackmew/gitPullRequest | 0e010d461ee3e14be39450fa52f670518f6dd632 | d6d7ee31def1c0efaa8f48097237bb5c7ede7079 | refs/heads/master | 2021-01-10T10:27:18.217013 | 2015-12-15T04:07:49 | 2015-12-15T04:07:49 | 48,013,457 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,082 | java | package com.leandev.downloader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import com.vaadin.server.ConnectorResource;
import com.vaadin.server.DownloadStream;
import com.vaadin.server.FileDownloader;
import com.vaadin.server.Resource;
import com.vaadin.server.StreamResource;
import com.vaadin.server.StreamResource.StreamSource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.ProgressBar;
/**
* an advanced file downloader
*
* @author visruth
*
*/
public class AdvancedFileDownloader extends FileDownloader {
/**
*
*/
private static final long serialVersionUID = 7914516170514586601L;
private static final boolean DEBUG_MODE = true;
private static final Logger logger = java.util.logging.Logger
.getLogger(AdvancedFileDownloader.class.getName());
private AbstractComponent extendedComponet;
private AdvancedDownloaderListener dynamicDownloaderListener;
private DownloaderEvent downloadEvent;
private ProgressBar bar ;
public abstract class DownloaderEvent {
/**
*
* @return
*/
public abstract AbstractComponent getExtendedComponet();
public abstract void setExtendedComponet(
AbstractComponent extendedComponet);
}
public interface AdvancedDownloaderListener {
/**
* This method will be invoked just before the download starts. Thus, a
* new file path can be set.
*
* @param downloadEvent
*/
public void beforeDownload(DownloaderEvent downloadEvent);
}
public void fireEvent() {
if (DEBUG_MODE) {
System.out.println("inside fireEvent");
logger.info("inside fireEvent");
}
if (this.dynamicDownloaderListener != null
&& this.downloadEvent != null) {
if (DEBUG_MODE) {
System.out.println("beforeDownload is going to be invoked");
logger.info("beforeDownload is going to be invoked");
}
this.dynamicDownloaderListener.beforeDownload(this.downloadEvent);
}
}
public void addAdvancedDownloaderListener(
AdvancedDownloaderListener listener) {
if (listener != null) {
DownloaderEvent downloadEvent = new DownloaderEvent() {
private AbstractComponent extendedComponet;
@Override
public void setExtendedComponet(
AbstractComponent extendedComponet) {
this.extendedComponet = extendedComponet;
}
@Override
public AbstractComponent getExtendedComponet() {
// TODO Auto-generated method stub
return this.extendedComponet;
}
};
downloadEvent
.setExtendedComponet(AdvancedFileDownloader.this.extendedComponet);
this.dynamicDownloaderListener = listener;
this.downloadEvent = downloadEvent;
}
}
private static class FileResourceUtil {
private String filePath;
private String fileName = "";
private File file;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
file = new File(filePath);
if (file.exists() && !file.isDirectory()) {
fileName = file.getName();
}
}
/**
* makes a stream resource
*
* @return {@code StreamResource}
*/
@SuppressWarnings("serial")
public StreamResource getResource() {
return new StreamResource(new StreamSource() {
@Override
public InputStream getStream() {
if (filePath != null && file != null) {
if (file.exists() && !file.isDirectory()) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
return null;
}
}, FileResourceUtil.this.fileName) {
@Override
public String getFilename() {
return FileResourceUtil.this.fileName;
}
};
}
}
private FileResourceUtil resource;
private AdvancedFileDownloader(FileResourceUtil resource) {
super(resource == null ? (resource = new FileResourceUtil())
.getResource() : resource.getResource());
AdvancedFileDownloader.this.resource = resource;
System.out.println("created a new instance of resource : " + resource);
}
public AdvancedFileDownloader() {
this(null);
}
/**
* @return the current file path
*/
public String getFilePath() {
return resource.getFilePath();
}
/**
* sets the path for the file for downloading
*
* @param filePath
* path of the file, i.e. path + file name with extension
*/
public void setFilePath(String filePath) {
if (resource != null && filePath != null) {
this.resource.setFilePath(filePath);
;
}
}
public void setProgressBar(ProgressBar bar){
this.bar = bar ;
}
@Override
public boolean handleConnectorRequest(VaadinRequest request,
VaadinResponse response, String path) throws IOException {
if (!path.matches("dl(/.*)?")) {
// Ignore if it isn't for us
return false;
}
VaadinSession session = getSession();
AdvancedFileDownloader.this.fireEvent();
bar.setIndeterminate(true);
session.lock();
System.out.println("session lock");
DownloadStream stream;
try {
Resource resource = getFileDownloadResource();
if (!(resource instanceof ConnectorResource)) {
return false;
}
stream = ((ConnectorResource) resource).getStream();
if (stream.getParameter("Content-Disposition") == null) {
// Content-Disposition: attachment generally forces download
stream.setParameter("Content-Disposition",
"attachment; filename=\"" + stream.getFileName() + "\"");
}
// Content-Type to block eager browser plug-ins from hijacking
// the file
if (isOverrideContentType()) {
stream.setContentType("application/octet-stream;charset=UTF-8");
}
} finally {
session.unlock();
bar.setIndeterminate(false);
System.out.println("session unlock");
}
stream.writeResponse(request, response);
return true;
}
} | [
"wonderfuljack123@gmail.com"
] | wonderfuljack123@gmail.com |
f12022b770a1970b09a1fb8d14753cbaf2925650 | adc5e75da8137937ee5fd53d9e3701f6650f6f55 | /attempt-cache/src/main/java/com/attempt/core/cache/suppore/redis/holder/MapHolder.java | bed44729672872e49eb08cf42b45f16693af3122 | [] | no_license | zyb8529630/attempt | 527d2097964fe074eee9af665c10438ca70e08fb | 28256ccd4a9a2c919ec4e4e496b5842ab981ecf6 | refs/heads/master | 2021-07-05T06:05:48.495044 | 2019-06-26T05:19:05 | 2019-06-26T05:19:05 | 190,316,952 | 1 | 0 | null | 2020-10-13T13:41:18 | 2019-06-05T03:06:26 | Java | UTF-8 | Java | false | false | 5,561 | java | package com.attempt.core.cache.suppore.redis.holder;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.springframework.util.Assert;
import com.alibaba.fastjson.JSON;
import com.attempt.core.cache.api.MapOperations;
import com.attempt.core.cache.models.Behavior;
import com.attempt.core.cache.models.CacheMetaInfo;
import com.attempt.core.cache.models.CountType;
import com.attempt.core.cache.suppore.DataRefreshSupport;
import com.attempt.core.cache.suppore.redis.RedisCommander;
import com.attempt.core.cache.util.CacheUtil;
/**
* @Description: Map缓存单元.
* @author zhouyinbin
* @date
* @version V1.0
*/
public class MapHolder<T extends Serializable> extends DataHolder implements MapOperations<T> {
/**
* 放入List中的数据类型
*/
private Class<? extends T> itemClassType;
/**
* 构造方法.
*
* @param metaInfo 缓存数据单元的元数据信息
*/
public MapHolder(CacheMetaInfo metaInfo, Class<? extends T> itemClassType) {
super(metaInfo);
this.itemClassType = itemClassType;
}
/**
* 删除列表.
*/
@Override
public void delete() {
// 删除元数据
if (metaInfoHolder != null)
metaInfoHolder.delete();
// 删除计数器
if (counterHolder != null)
counterHolder.delete();
try (RedisCommander commander = CacheUtil.createRedisCommonder()) {
commander.nativeCommander().del(key);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取列表.
*
* @return the session
*/
@Override
public Map<String, T> get() {
/** 计数器计数**/
if (counterHolder != null)
counterHolder.increase(CountType.READ_COUNT);
/** 判断是否需要续期**/
if (DataRefreshSupport.needRenewalOn(this, Behavior.GET))
renewal();
Map<String, T> result = new HashMap<>();
try (RedisCommander commander = CacheUtil.createRedisCommonder()) {
commander.hgetall(key).forEach(entry -> {
result.put(entry.getKey(), JSON.parseObject(entry.getValue(), itemClassType));
});
}catch (Exception e) {
e.printStackTrace();
}
/** 判断是否需要删除**/
if (DataRefreshSupport.needDeleteOn(this, Behavior.GET))
delete();
return result;
}
/**
* 获取指定元素.
*
* @param fieldKey Map中的Key
*/
@Override
public T get(String fieldKey) {
/** 计数器计数**/
if (counterHolder != null)
counterHolder.increase(CountType.READ_COUNT);
/** 判断是否需要续期**/
if (DataRefreshSupport.needRenewalOn(this, Behavior.GET))
renewal();
String valueStr = null;
try (RedisCommander commander = CacheUtil.createRedisCommonder()) {
valueStr = commander.nativeCommander().hget(key, fieldKey);
}catch (Exception e) {
e.printStackTrace();
}
T value = JSON.parseObject(valueStr, itemClassType);
/** 判断是否需要删除**/
if (DataRefreshSupport.needDeleteOn(this, Behavior.GET))
delete();
return value;
}
/**
* 添加元素.
*
* @param fieldKey Map中的Key
* @param item the item
*/
@Override
public void add(String fieldKey, T item) {
Assert.notNull(fieldKey);
Assert.notNull(item);
/** 计数器计数**/
if (counterHolder != null)
counterHolder.increase(CountType.WRITE_COUNT);
/** 判断是否需要续期**/
if (DataRefreshSupport.needRenewalOn(this, Behavior.SET))
renewal();
/** 判断是否需要删除**/
if (DataRefreshSupport.needDeleteOn(this, Behavior.SET)) {
delete();
return;
}
try (RedisCommander commander = CacheUtil.createRedisCommonder()) {
commander.nativeCommander().hset(key, fieldKey, JSON.toJSONString(item));
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除某个key.
*
* @param fieldKey Map中的Key
*/
@Override
public void delete(String fieldKey) {
Assert.notNull(fieldKey);
/** 计数器计数**/
if (counterHolder != null)
counterHolder.increase(CountType.WRITE_COUNT);
/** 判断是否需要续期**/
if (DataRefreshSupport.needRenewalOn(this, Behavior.SET))
renewal();
/** 判断是否需要删除**/
if (DataRefreshSupport.needDeleteOn(this, Behavior.SET)) {
delete();
return;
}
try (RedisCommander commander = CacheUtil.createRedisCommonder()) {
commander.nativeCommander().hdel(key, fieldKey);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 是否存在某个key.
*
* @param fieldKey Map中的Key
* @return the boolean
*/
@Override
public boolean contains(String fieldKey) {
Assert.notNull(fieldKey);
/** 判断是否需要续期**/
if (DataRefreshSupport.needRenewalOn(this, Behavior.GET)) {
renewal();
}
try (RedisCommander commander = CacheUtil.createRedisCommonder()) {
return commander.nativeCommander().hexists(key, fieldKey);
}catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
| [
"AB063825@BJ-AB051964-MI2.AB.COM"
] | AB063825@BJ-AB051964-MI2.AB.COM |
0e142fedc4f573405d20597be35cb04c83f810b4 | 98304c9ae29210909579b885fba03139c2633848 | /cglcrm/src/main/java/com/rainy/cglcrm/common/utils/PropertiesLoader.java | 32e5bc76f6234c8abac1c898fac2f81e58a11ed4 | [] | no_license | Rainyone/cglcrm | 31eb1342b7311b76214d0dcc04927339761cf35e | 1dc8b131846126d632390f50434c8cecd9b5f429 | refs/heads/master | 2021-09-04T00:47:20.661350 | 2018-01-13T14:52:54 | 2018-01-13T14:52:54 | 113,199,227 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,542 | java | /**
* Copyright (c) 2005-2011 springside.org.cn
*
* $Id: PropertiesLoader.java 1690 2012-02-22 13:42:00Z calvinxiu $
*/
package com.rainy.cglcrm.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
/**
* Properties文件载入工具类. 可载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的值,但以System的Property优先.
* @author calvin
* @version 2013-05-15
*/
public class PropertiesLoader {
private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);
private static ResourceLoader resourceLoader = new DefaultResourceLoader();
private final Properties properties;
public PropertiesLoader(String... resourcesPaths) {
properties = loadProperties(resourcesPaths);
}
public Properties getProperties() {
return properties;
}
/**
* 取出Property,但以System的Property优先,取不到返回空字符串.
*/
private String getValue(String key) {
String systemProperty = System.getProperty(key);
if (systemProperty != null) {
return systemProperty;
}
if (properties.containsKey(key)) {
return properties.getProperty(key);
}
return "";
}
/**
* 取出String类型的Property,但以System的Property优先,如果都为Null则抛出异常.
*/
public String getProperty(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return value;
}
/**
* 取出String类型的Property,但以System的Property优先.如果都为Null则返回Default值.
*/
public String getProperty(String key, String defaultValue) {
String value = getValue(key);
return value != null ? value : defaultValue;
}
/**
* 取出Integer类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
*/
public Integer getInteger(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Integer.valueOf(value);
}
/**
* 取出Integer类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
*/
public Integer getInteger(String key, Integer defaultValue) {
String value = getValue(key);
return value != null ? Integer.valueOf(value) : defaultValue;
}
/**
* 取出Double类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
*/
public Double getDouble(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Double.valueOf(value);
}
/**
* 取出Double类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
*/
public Double getDouble(String key, Integer defaultValue) {
String value = getValue(key);
return value != null ? Double.valueOf(value) : defaultValue;
}
/**
* 取出Boolean类型的Property,但以System的Property优先.如果都为Null抛出异常,如果内容不是true/false则返回false.
*/
public Boolean getBoolean(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Boolean.valueOf(value);
}
/**
* 取出Boolean类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容不为true/false则返回false.
*/
public Boolean getBoolean(String key, boolean defaultValue) {
String value = getValue(key);
return value != null ? Boolean.valueOf(value) : defaultValue;
}
/**
* 载入多个文件, 文件路径使用Spring Resource格式.
*/
private Properties loadProperties(String... resourcesPaths) {
Properties props = new Properties();
for (String location : resourcesPaths) {
// logger.debug("Loading properties file from:" + location);
InputStream is = null;
try {
Resource resource = resourceLoader.getResource(location);
is = resource.getInputStream();
props.load(is);
} catch (IOException ex) {
logger.info("Could not load properties from path:" + location + ", " + ex.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
}
return props;
}
}
| [
"Administrator@8AFQ6TPXKA4WYKI"
] | Administrator@8AFQ6TPXKA4WYKI |
398eff81ff19aa7569b9a480a25324aef7b31840 | b7ea598d7a04cf5bc460647ebc7910c429cc193b | /src/main/java/cn/bestlang/algs/common/TreeNode.java | 6da43e958b00908a70a27733c64568537f0179d2 | [
"MIT"
] | permissive | ligenhw/algs | b9bf9c2209e94df7f3d3331ff54c50e80efc25c1 | 097802acfa8adba9685a21cd4729feaa1c7018e1 | refs/heads/main | 2023-08-31T10:40:27.166329 | 2021-10-20T02:53:04 | 2021-10-20T02:53:04 | 379,483,664 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 186 | java | package cn.bestlang.algs.common;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
}
| [
"ligenhw@outlook.com"
] | ligenhw@outlook.com |
39887cfdc953e1adf97dd1ed7375f1fc20254ca4 | c0cc9f465471b4bd0a0f203793135939b8b145ea | /entites/NegocioDaEmpresa.java | f3ab703b95700f6bbb9b872d382ca2276a27346d | [] | no_license | IagoBS/estudo | 79d3c4f429684a5d39851fd1a51877b18a9379de | 2cd2cd84b46a133a4077f186242e83928bcb6c13 | refs/heads/master | 2020-08-03T08:43:01.367032 | 2019-09-29T16:10:49 | 2019-09-29T16:10:49 | 211,688,717 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 618 | java | package entites;
public class NegocioDaEmpresa extends Account {
private Double emprestimolimite;
public NegocioDaEmpresa() {
super();
}
public Double getEmprestimolimite() {
return emprestimolimite;
}
public void setEmprestimolimite(Double emprestimolimite) {
this.emprestimolimite = emprestimolimite;
}
public NegocioDaEmpresa(Integer numero, String suporte, Double balanco, Double emprestimolimite) {
super(numero, suporte, balanco);
this.emprestimolimite = emprestimolimite;
}
public void emprestimo (Double montante) {
if(montante <= emprestimolimite) {
deposito(montante);
}
}
}
| [
"iagobsbastos@gmail.com"
] | iagobsbastos@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.