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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a35f6da1474c0bce92a339166f4e717f6c39188b | eb64ad2bc1cf6a4093edf3df31da04451595e2cb | /CultureGlass/app/src/main/java/cam/cl/kilo/ui/ResultsCardScrollAdapter.java | 62c2e88ff5450f023730d345dbeb45f0aa333a4c | [
"Apache-2.0"
] | permissive | raahilshah/ProjectKilo | fdafd3022c09281d7915e91d3d22ae4468e49884 | 7dff04c88d8c0459ddff42a496d881c3d0442331 | refs/heads/master | 2020-04-01T16:31:23.391110 | 2015-03-02T11:48:44 | 2015-03-02T11:48:44 | 29,470,714 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,323 | java | /*
* Copyright (C) 2014 The Android Open Source Project
* Copyright (C) 2015 Group Kilo (Cambridge Computer Lab)
*
* 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 cam.cl.kilo.ui;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import com.google.android.glass.widget.CardBuilder;
import com.google.android.glass.widget.CardScrollAdapter;
import java.util.List;
/**
* Populates views in a {@code CardScrollView} with cards built from summarised sentences
*
* @author groupKilo
* @author rh572
*/
public class ResultsCardScrollAdapter extends CardScrollAdapter {
private final Context mContext;
private final List<String> mItems;
private final String mTitle;
private final String mAuthor;
/**
* Initializes a new adapter with the specified context and list of items.
*/
public ResultsCardScrollAdapter(Context context, List<String> items, String title, String author) {
mContext = context;
mItems = items;
mTitle = title;
mAuthor = author;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public int getItemViewType(int position) {
return 0;
}
@Override
public int getCount() {
return mItems.size() + 1;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public int getPosition(Object item) {
return AdapterView.INVALID_POSITION;
}
/**
* Returns the view for the relevant position
* If it is 0 then it is the title card
* Otherwise it is one of the results
* If the string for the results is our constant BEGIN_REVIEWS
* then display the REVIEWS title card
*
* @param position position of the View to return in the CardScrollView
* @param convertView
* @param parent
* @return the View to display
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CardBuilder card;
if (position == 0) {
card = new CardBuilder(mContext, CardBuilder.Layout.MENU)
.setText(mTitle)
.setFootnote("by " + mAuthor);
} else if (mItems.get(position - 1).equals("BEGIN_REVIEWS")) {
card = new CardBuilder(mContext, CardBuilder.Layout.MENU)
.setText("REVIEWS");
} else {
card = new CardBuilder(mContext, CardBuilder.Layout.TEXT)
.setText(mItems.get(position - 1))
.setFootnote(mTitle)
.setTimestamp(mAuthor);
}
View view = card.getView(convertView, parent);
return view;
}
}
| [
"[email protected]"
] | |
94e225725dd8ce670ad5884ae3fce27f8eab863e | 98d313cf373073d65f14b4870032e16e7d5466f0 | /gradle-open-labs/example/src/main/java/se/molybden/Class28865.java | 4ebe7c3f1961275c349d4bf0787666b66a0f3c10 | [] | no_license | Molybden/gradle-in-practice | 30ac1477cc248a90c50949791028bc1cb7104b28 | d7dcdecbb6d13d5b8f0ff4488740b64c3bbed5f3 | refs/heads/master | 2021-06-26T16:45:54.018388 | 2016-03-06T20:19:43 | 2016-03-06T20:19:43 | 24,554,562 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 110 | java |
public class Class28865{
public void callMe(){
System.out.println("called");
}
}
| [
"[email protected]"
] | |
59b9b9f4a37fb2079c6c24884b5b386efae919ad | 302f071ff3197065c74092a4ccf791dde589caa6 | /MWDBPhase1/src/edu/asu/mwdb/util/Constants.java | 13ff55b86110fa988301b76110dc8d9c3ea140af | [] | no_license | kirankumarbatna/MWDBP1 | 09213ce2425766f0426da138452750634c33ac89 | 76f37d77a72a012d644c2b00a6d6228cde5950a0 | refs/heads/master | 2021-01-17T14:12:59.021563 | 2013-10-15T01:46:28 | 2013-10-15T01:46:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,277 | java | package edu.asu.mwdb.util;
import java.awt.Color;
public class Constants {
public static int NUMBER_OF_SENSORS = 20;
public static int NUMBER_OF_DOCS;
public static float HIGHEST_IDF;
public static int TOP_COUNT = 10;
public static int GRAYSCALE_VALS = 255;
public static float MAX = 1.0f;
public static float MIN = -1.0f;
public static int WINDOW_LENGTH;
public static int SHIFT_LENGTH;
public static int RESOLUTION;
public static float MEAN;
public static float STD;
public static String[] DIMENSIONS = { "W", "X", "Y", "Z" };
public static void setRESOLUTION(int rESOLUTION) {
RESOLUTION = rESOLUTION;
}
public static void setMEAN(float mEAN) {
MEAN = mEAN;
}
public static void setSTD(float sTD) {
STD = sTD;
}
// Heatmap Constants
public static String HEATMAP_SAVE_LOC="/Users/kishanmaddula/Desktop/heatmap.png";
public static int HEATMAP_BEGIN_VALUE=280;
public static int HEATMAP_INCREMENT_VALUE=5;
public static Color HEATMAP_HIGH_COLOR=Color.WHITE;
public static Color HEATMAP_LOW_COLOR=Color.BLACK;
public static String MATLAB_SCRIPTS_PATH="cd(\'matlabScripts\')";
public static void setNumberOfDocs(int count){
NUMBER_OF_DOCS = count;
}
public static void setHighestIDF(float value){
HIGHEST_IDF = value;
}
}
| [
"[email protected]"
] | |
6d34b78a05df37d57ff206ec8655ae35ca7f0a09 | d0bf33b888309701f4ee62de7db01c0686ec0145 | /Helloworld.java | ec3bfe7f09a55694c716a344446e54836f5bd07f | [] | no_license | annasimha/JavaProgram | 1a96579872e6fadc890a2e1219228764e2b2fb85 | d03da6339594c7e29aee3b613e81239662cee239 | refs/heads/master | 2020-05-23T14:12:40.510724 | 2019-05-15T10:55:46 | 2019-05-15T10:55:46 | 186,797,448 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19 | java | Hi
This narasimha
| [
"[email protected]"
] | |
dafb655779939c79a25f28571321d608111de22a | 71e733646f66b53f64988cdb0f85a846fcfc4900 | /GameOfLife/GameOfLife.java | cf71bdcec389f5b3896baa0a827361b3623179ff | [] | no_license | ogunoksuz-developer/Java | 202c84a77019f18c72b8363f05bc7fe0e01b9f29 | f6fc1029e408fba8facd5da4db67061ddaf74711 | refs/heads/master | 2022-09-22T19:06:33.090576 | 2020-05-31T12:44:17 | 2020-05-31T12:44:17 | 268,277,693 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 999 | java |
import java.util.Scanner;
public class GameOfLife {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int dizi[][];
System.out.println("Please enter number of cow :");
int cow = input.nextInt();
System.out.println("Please enter number of column :");
int column = input.nextInt();
dizi = new int [cow][column];
if (5<=cow && cow<=50){
if(5<=column && column <=50){
for(int i =0; i<cow;i++)
{ for(int j=0; j<column; j++)
{
dizi[i][j] = (int)(Math.random() *4);
System.out.print(dizi[i][j]);
}
System.out.println(""); }}
for(int i=0; i<=cow; i++){
for (int j =0; i<=column; j++){
}
}
}
else
System.out.println("Please rerun this program and enter numbers which are from 5 to 50 ");
}
}
| [
"[email protected]"
] | |
4d0cfb1ecd8982e1ecab7add6bf850199e830763 | 2af70244427b4034b683512a60b17c9373e90773 | /app/src/main/java/com/doandstevensen/lifecollage/ui/featured_collage/FeaturedCollagePresenter.java | e04ff621352203db465a598f568f675c3c572485 | [] | no_license | sheenanick/life-collage | 6418fa4678d7c3149471ee1439ec7acee706b603 | 001c889c9a16499a2c99747f015dc67ae3fb2b67 | refs/heads/master | 2021-01-11T15:58:00.362571 | 2017-02-27T18:23:15 | 2017-02-27T18:23:15 | 80,446,331 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,535 | java | package com.doandstevensen.lifecollage.ui.featured_collage;
import android.content.Context;
import android.view.View;
import com.doandstevensen.lifecollage.data.model.PictureResponse;
import com.doandstevensen.lifecollage.data.remote.DataManager;
import com.doandstevensen.lifecollage.data.remote.LifeCollageApiService;
import java.util.ArrayList;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
/**
* Created by Sheena on 2/19/17.
*/
public class FeaturedCollagePresenter implements FeaturedCollageContract.Presenter {
private FeaturedCollageContract.MvpView mView;
private Context mContext;
private DataManager mDataManager;
private LifeCollageApiService mService;
private Subscription mSubscription;
public FeaturedCollagePresenter(FeaturedCollageContract.MvpView view, Context context) {
mView = view;
mContext = context;
mDataManager = new DataManager(context);
mService = LifeCollageApiService.ServiceCreator.newService();
}
@Override
public void loadCollage(int collageId) {
mView.displayLoadingAnimation();
mDataManager.setApiService(mService);
mSubscription = mDataManager.getAllPictures(collageId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
mSubscription = null;
}
})
.subscribe(new Subscriber<ArrayList<PictureResponse>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
mView.hideLoadingAnimation();
}
@Override
public void onNext(ArrayList<PictureResponse> response) {
mView.hideLoadingAnimation();
mView.setRecyclerViewPictures(response);
mView.setEmptyViewVisibility(View.GONE);
}
});
}
@Override
public void detach() {
mView = null;
mContext = null;
mDataManager = null;
mService = null;
mSubscription = null;
}
}
| [
"[email protected]"
] | |
da4dce18bf74a8cd393df5c5193b91873d8483d9 | 12d58f9a036cb639bdf5e50758dd05090bbf289d | /MathematicalCalculations/HowManyDigitInNumberAreDivisableBy3.java | a3673a6eca22a9140adeecddeffbe7f96668805a | [] | no_license | katarinatodorovic/Java | a4d19ec4485818cb431d280af820f8be986fe01a | 9b3446c05232ff7a4596b538a072380776cd755c | refs/heads/master | 2022-12-24T15:47:02.626841 | 2020-09-20T14:49:19 | 2020-09-20T14:49:19 | 293,961,112 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,943 | java | import java.util.Scanner;
public class HowManyDigitInNumberAreDivisableBy3 {
public static void main(String[] args) {
/*Učitati jedan broj i ispisati koliko on sadrži cifara koje su deljive sa 3.
B) Modifikovati program tako da se postupak pod a) ponavlja i to tako da pre svakog unosa korisnik vidi
pitanje da li želi da unese još jedan broj. Ako je odgovor 'da' treba izbrojati cifre deljive sa 3, a ukoliko je 'ne'
treba završiti program.
C) Omogućiti da unos reči 'da' i 'ne' ne bude caseSensitive.*/
Scanner sc = new Scanner(System.in);
Scanner ns = new Scanner(System.in);
String processContinue;
int number;
int remainder;
int count = 0;
int sum = 0;
while (true) {
System.out.println("Enter a number:");
number = sc.nextInt();
while (number != 0) {
remainder = number % 10;
number = number / 10;
if (remainder % 3 == 0) {
count++;
sum++;
}
}
String singular = count == 1 ? "is" : "are";
String plural = count == 1 ? "number" : "numbers";
System.out.printf("There %s %d %s divisible by 3.%n", singular, sum, plural);
System.out.println("Do you want to enter a new number? Write Yes/No.");
processContinue = ns.nextLine().toLowerCase();
if (processContinue.equals("yes")) {
sum = 0;
continue;
}
if (processContinue.equals("no")) {
System.out.println("You are exited from the program.");
break;
}
}
String singular = count == 1 ? "is" : "are";
String plural = count == 1 ? "number" : "numbers";
System.out.printf("There %s %d %s divisible by 3 in total.%n", singular, count, plural);
}
}
| [
"[email protected]"
] | |
da0b51e4a4b27006adaaf3e7b8c701c59c392d36 | 5245085c230929cdb91db049672f8f276646560c | /mula-base/src/main/java/org/mula/finance/core/ui/screens/habits/list/HabitCardListCache.java | 00532015588bf5849a87dbec4fa9f3b6f8a86ebb | [] | no_license | katrinaannhadi/MULAFinanceApp | 9e7371778d2fe2fbcc61e94cd6d3832409cd6115 | 3130dbd1dfc7438268621cf0320c0856e836e00e | refs/heads/master | 2022-04-25T04:50:36.130679 | 2020-04-30T03:51:17 | 2020-04-30T03:51:17 | 258,404,445 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,278 | java | /* Mula */
package org.mula.finance.core.ui.screens.habits.list;
import androidx.annotation.*;
import org.mula.finance.core.AppScope;
import org.mula.finance.core.commands.Command;
import org.mula.finance.core.commands.CommandRunner;
import org.mula.finance.core.models.Habit;
import org.mula.finance.core.models.HabitList;
import org.mula.finance.core.models.HabitMatcher;
import org.mula.finance.core.models.Timestamp;
import org.mula.finance.core.tasks.Task;
import org.mula.finance.core.tasks.TaskRunner;
import org.mula.finance.core.utils.DateUtils;
import java.util.*;
import javax.inject.*;
/**
* A HabitCardListCache fetches and keeps a cache of all the data necessary to
* render a HabitCardListView.
* <p>
* This is needed since performing database lookups during scrolling can make
* the ListView very slow. It also registers itself as an observer of the
* models, in order to update itself automatically.
* <p>
* Note that this class is singleton-scoped, therefore it is shared among all
* activities.
*/
@AppScope
public class HabitCardListCache implements CommandRunner.Listener
{
private int checkmarkCount;
@Nullable
private Task currentFetchTask;
@NonNull
private Listener listener;
@NonNull
private CacheData data;
@NonNull
private final HabitList allHabits;
@NonNull
private HabitList filteredHabits;
@NonNull
private final TaskRunner taskRunner;
@NonNull
private final CommandRunner commandRunner;
@Inject
public HabitCardListCache(@NonNull HabitList allHabits,
@NonNull CommandRunner commandRunner,
@NonNull TaskRunner taskRunner)
{
if (allHabits == null) throw new NullPointerException();
if (commandRunner == null) throw new NullPointerException();
if (taskRunner == null) throw new NullPointerException();
this.allHabits = allHabits;
this.commandRunner = commandRunner;
this.filteredHabits = allHabits;
this.taskRunner = taskRunner;
this.listener = new Listener()
{
};
data = new CacheData();
}
public synchronized void cancelTasks()
{
if (currentFetchTask != null) currentFetchTask.cancel();
}
public synchronized int[] getCheckmarks(long habitId)
{
return data.checkmarks.get(habitId);
}
/**
* Returns the habits that occupies a certain position on the list.
*
* @param position the position of the habit
* @return the habit at given position or null if position is invalid
*/
@Nullable
public synchronized Habit getHabitByPosition(int position)
{
if (position < 0 || position >= data.habits.size()) return null;
return data.habits.get(position);
}
public synchronized int getHabitCount()
{
return data.habits.size();
}
public synchronized HabitList.Order getOrder()
{
return filteredHabits.getOrder();
}
public synchronized double getScore(long habitId)
{
return data.scores.get(habitId);
}
public synchronized void onAttached()
{
refreshAllHabits();
commandRunner.addListener(this);
}
@Override
public synchronized void onCommandExecuted(@Nullable Command command,
@Nullable Long refreshKey)
{
if (refreshKey == null) refreshAllHabits();
else refreshHabit(refreshKey);
}
public synchronized void onDetached()
{
commandRunner.removeListener(this);
}
public synchronized void refreshAllHabits()
{
if (currentFetchTask != null) currentFetchTask.cancel();
currentFetchTask = new RefreshTask();
taskRunner.execute(currentFetchTask);
}
public synchronized void refreshHabit(long id)
{
taskRunner.execute(new RefreshTask(id));
}
public synchronized void remove(long id)
{
Habit h = data.id_to_habit.get(id);
if (h == null) return;
int position = data.habits.indexOf(h);
data.habits.remove(position);
data.id_to_habit.remove(id);
data.checkmarks.remove(id);
data.scores.remove(id);
listener.onItemRemoved(position);
}
public synchronized void reorder(int from, int to)
{
Habit fromHabit = data.habits.get(from);
data.habits.remove(from);
data.habits.add(to, fromHabit);
listener.onItemMoved(from, to);
}
public synchronized void setCheckmarkCount(int checkmarkCount)
{
this.checkmarkCount = checkmarkCount;
}
public synchronized void setFilter(@NonNull HabitMatcher matcher)
{
if (matcher == null) throw new NullPointerException();
filteredHabits = allHabits.getFiltered(matcher);
}
public synchronized void setListener(@NonNull Listener listener)
{
if (listener == null) throw new NullPointerException();
this.listener = listener;
}
public synchronized void setOrder(@NonNull HabitList.Order order)
{
if (order == null) throw new NullPointerException();
allHabits.setOrder(order);
filteredHabits.setOrder(order);
refreshAllHabits();
}
/**
* Interface definition for a callback to be invoked when the data on the
* cache has been modified.
*/
public interface Listener
{
default void onItemChanged(int position)
{
}
default void onItemInserted(int position)
{
}
default void onItemMoved(int oldPosition, int newPosition)
{
}
default void onItemRemoved(int position)
{
}
default void onRefreshFinished()
{
}
}
private class CacheData
{
@NonNull
public final HashMap<Long, Habit> id_to_habit;
@NonNull
public final List<Habit> habits;
@NonNull
public final HashMap<Long, int[]> checkmarks;
@NonNull
public final HashMap<Long, Double> scores;
/**
* Creates a new CacheData without any content.
*/
public CacheData()
{
id_to_habit = new HashMap<>();
habits = new LinkedList<>();
checkmarks = new HashMap<>();
scores = new HashMap<>();
}
public synchronized void copyCheckmarksFrom(@NonNull CacheData oldData)
{
if (oldData == null) throw new NullPointerException();
int[] empty = new int[checkmarkCount];
for (Long id : id_to_habit.keySet())
{
if (oldData.checkmarks.containsKey(id))
checkmarks.put(id, oldData.checkmarks.get(id));
else checkmarks.put(id, empty);
}
}
public synchronized void copyScoresFrom(@NonNull CacheData oldData)
{
if (oldData == null) throw new NullPointerException();
for (Long id : id_to_habit.keySet())
{
if (oldData.scores.containsKey(id))
scores.put(id, oldData.scores.get(id));
else scores.put(id, 0.0);
}
}
public synchronized void fetchHabits()
{
for (Habit h : filteredHabits)
{
if (h.getId() == null) continue;
habits.add(h);
id_to_habit.put(h.getId(), h);
}
}
}
private class RefreshTask implements Task
{
@NonNull
private final CacheData newData;
@Nullable
private final Long targetId;
private boolean isCancelled;
@Nullable
private TaskRunner runner;
public RefreshTask()
{
newData = new CacheData();
targetId = null;
isCancelled = false;
}
public RefreshTask(long targetId)
{
newData = new CacheData();
this.targetId = targetId;
}
@Override
public synchronized void cancel()
{
isCancelled = true;
}
@Override
public synchronized void doInBackground()
{
newData.fetchHabits();
newData.copyScoresFrom(data);
newData.copyCheckmarksFrom(data);
Timestamp dateTo = DateUtils.getToday();
Timestamp dateFrom = dateTo.minus(checkmarkCount - 1);
if (runner != null) runner.publishProgress(this, -1);
for (int position = 0; position < newData.habits.size(); position++)
{
if (isCancelled) return;
Habit habit = newData.habits.get(position);
Long id = habit.getId();
if (targetId != null && !targetId.equals(id)) continue;
newData.scores.put(id, habit.getScores().getTodayValue());
newData.checkmarks.put(
id,
habit.getCheckmarks().getValues(dateFrom, dateTo));
runner.publishProgress(this, position);
}
}
@Override
public synchronized void onAttached(@NonNull TaskRunner runner)
{
if (runner == null) throw new NullPointerException();
this.runner = runner;
}
@Override
public synchronized void onPostExecute()
{
currentFetchTask = null;
listener.onRefreshFinished();
}
@Override
public synchronized void onProgressUpdate(int currentPosition)
{
if (currentPosition < 0) processRemovedHabits();
else processPosition(currentPosition);
}
private synchronized void performInsert(Habit habit, int position)
{
Long id = habit.getId();
data.habits.add(position, habit);
data.id_to_habit.put(id, habit);
data.scores.put(id, newData.scores.get(id));
data.checkmarks.put(id, newData.checkmarks.get(id));
listener.onItemInserted(position);
}
private synchronized void performMove(@NonNull Habit habit,
int fromPosition,
int toPosition)
{
if(habit == null) throw new NullPointerException();
data.habits.remove(fromPosition);
data.habits.add(toPosition, habit);
listener.onItemMoved(fromPosition, toPosition);
}
private synchronized void performUpdate(long id, int position)
{
double oldScore = data.scores.get(id);
int[] oldCheckmarks = data.checkmarks.get(id);
double newScore = newData.scores.get(id);
int[] newCheckmarks = newData.checkmarks.get(id);
boolean unchanged = true;
if (oldScore != newScore) unchanged = false;
if (!Arrays.equals(oldCheckmarks, newCheckmarks)) unchanged = false;
if (unchanged) return;
data.scores.put(id, newScore);
data.checkmarks.put(id, newCheckmarks);
listener.onItemChanged(position);
}
private synchronized void processPosition(int currentPosition)
{
Habit habit = newData.habits.get(currentPosition);
Long id = habit.getId();
int prevPosition = data.habits.indexOf(habit);
if (prevPosition < 0)
{
performInsert(habit, currentPosition);
}
else
{
if (prevPosition != currentPosition)
performMove(habit, prevPosition, currentPosition);
performUpdate(id, currentPosition);
}
}
private synchronized void processRemovedHabits()
{
Set<Long> before = data.id_to_habit.keySet();
Set<Long> after = newData.id_to_habit.keySet();
Set<Long> removed = new TreeSet<>(before);
removed.removeAll(after);
for (Long id : removed) remove(id);
}
}
}
| [
"[email protected]"
] | |
7c78f05abdafe74e42b8b42034c9b9997b9924e5 | 30033d4c8991bc4d2c08196728eb517be098c8dc | /micrometer-core/src/test/java/io/micrometer/core/instrument/composite/CompositeMeterRegistryTest.java | 30172e884add651ba1fd196601fce2fdfba823b5 | [
"Apache-2.0"
] | permissive | samaitra/micrometer | ac98d3948607c55dd2bab720c4a995f59365e28b | 2b709cd914f5f7c927ddd13e6b7bd7d2f29f22ed | refs/heads/master | 2021-09-01T21:16:51.225991 | 2017-12-27T21:10:54 | 2017-12-28T15:09:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,594 | java | /**
* Copyright 2017 Pivotal Software, Inc.
* <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 io.micrometer.core.instrument.composite;
import io.micrometer.core.Issue;
import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.micrometer.core.instrument.Statistic.Count;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jon Schneider
*/
class CompositeMeterRegistryTest {
private CompositeMeterRegistry composite = new CompositeMeterRegistry();
private SimpleMeterRegistry simple = new SimpleMeterRegistry();
@Test
void metricsAreInitiallyNoop() {
// doesn't blow up
composite.counter("counter").increment();
}
@DisplayName("base units on meters that support them are passed through underlying registries")
@Test
void baseUnitsPreserved() {
composite.add(simple);
Counter.builder("counter").baseUnit("bytes").register(composite);
DistributionSummary.builder("summary").baseUnit("bytes").register(composite);
Gauge.builder("gauge", new AtomicInteger(0), AtomicInteger::get).baseUnit("bytes").register(composite);
assertThat(simple.find("counter").counter())
.hasValueSatisfying(c -> assertThat(c.getId().getBaseUnit()).isEqualTo("bytes"));
assertThat(simple.find("summary").summary())
.hasValueSatisfying(s -> assertThat(s.getId().getBaseUnit()).isEqualTo("bytes"));
assertThat(simple.find("gauge").gauge())
.hasValueSatisfying(g -> assertThat(g.getId().getBaseUnit()).isEqualTo("bytes"));
}
@DisplayName("metrics stop receiving updates when their registry parent is removed from a composite")
@Test
void metricAfterRegistryRemove() {
composite.add(simple);
Counter compositeCounter = composite.counter("counter");
compositeCounter.increment();
Optional<Counter> simpleCounter = simple.find("counter").counter();
assertThat(simpleCounter).hasValueSatisfying(c -> assertThat(c.count()).isEqualTo(1));
composite.remove(simple);
compositeCounter.increment();
// simple counter doesn't receive the increment after simple is removed from the composite
assertThat(simpleCounter).hasValueSatisfying(c -> assertThat(c.count()).isEqualTo(1));
composite.add(simple);
compositeCounter.increment();
// now it receives updates again
assertThat(simpleCounter).hasValueSatisfying(c -> assertThat(c.count()).isEqualTo(2));
}
@DisplayName("metrics that are created before a registry is added are later added to that registry")
@Test
void metricBeforeRegistryAdd() {
Counter compositeCounter = composite.counter("counter");
compositeCounter.increment();
// increments are being NOOPd until there is a registry in the composite
assertThat(compositeCounter.count()).isEqualTo(0);
composite.add(simple);
compositeCounter.increment();
assertThat(compositeCounter.count()).isEqualTo(1);
// only the increment AFTER simple is added to the composite is counted to it
assertThat(simple.find("counter").value(Count, 1.0).counter()).isPresent();
}
@DisplayName("metrics that are created after a registry is added to that registry")
@Test
void registryBeforeMetricAdd() {
composite.add(simple);
composite.counter("counter").increment();
assertThat(simple.find("counter").value(Count, 1.0).counter()).isPresent();
}
@DisplayName("metrics follow the naming convention of each registry in the composite")
@Test
void namingConventions() {
simple.config().namingConvention(NamingConvention.camelCase);
composite.add(simple);
composite.counter("my.counter").increment();
assertThat(simple.find("my.counter").value(Count, 1.0).counter()).isPresent();
}
@DisplayName("common tags added to the composite affect meters registered with registries in the composite")
@Test
void commonTags() {
simple.config().commonTags("instance", "local"); // added alongside other common tags in the composite
simple.config().commonTags("region", "us-west-1"); // overriden by the composite
composite.config().commonTags("region", "us-east-1");
composite.add(simple);
composite.config().commonTags("stack", "test");
composite.counter("counter").increment();
assertThat(simple.find("counter").tags("region", "us-east-1", "stack", "test",
"instance", "local").counter()).isPresent();
}
@DisplayName("function timer base units are delegated to registries in the composite")
@Test
void functionTimerUnits() {
composite.add(simple);
Object o = new Object();
composite.more().timer("function.timer", emptyList(),
o, o2 -> 1, o2 -> 1, TimeUnit.MILLISECONDS);
assertThat(simple.find("function.timer").meter().map(Meter::measure))
.hasValueSatisfying(measurements ->
assertThat(measurements)
.anySatisfy(ms -> {
assertThat(ms.getStatistic()).isEqualTo(Statistic.TotalTime);
assertThat(ms.getValue()).isEqualTo(1e-3);
})
);
}
@Issue("#255")
@Test
void castingFunctionCounter() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
CompositeMeterRegistry compositeMeterRegistry = new CompositeMeterRegistry();
FunctionCounter.builder("foo", 1L, x -> x)
.register(compositeMeterRegistry);
compositeMeterRegistry.add(registry);
}
}
| [
"[email protected]"
] | |
9e7ba6d1c932a5c28ef8ee2f983374906372deff | 84dfd5d702457c93c9db32a4fc956a360980326c | /Week_02/src/test/java/Solution1021Test.java | 31cbccf989d561ae0c0695685d94bfa8213188e8 | [] | no_license | stockcode/algorithm009-class02 | 202017f8dbae4fdb71796722fc500d371fa15ab6 | e1337fb563aa71dd468012c3ec078316eceaa797 | refs/heads/master | 2022-11-25T14:25:07.142634 | 2020-07-27T05:59:32 | 2020-07-27T05:59:32 | 264,673,627 | 0 | 0 | null | 2020-05-17T13:31:30 | 2020-05-17T13:31:29 | null | UTF-8 | Java | false | false | 509 | java | import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class Solution1021Test {
@Test
public void removeOuterParentheses1() {
Solution1021 solution1021 = new Solution1021();
Assert.assertEquals("()()()", solution1021.removeOuterParentheses1("(()())(())"));
Assert.assertEquals("()()()()(())", solution1021.removeOuterParentheses1("(()())(())(()(()))"));
Assert.assertEquals("", solution1021.removeOuterParentheses1("()()"));
}
} | [
"[email protected]"
] | |
3346de8a153c095f31c9da7b7f4c268105379ee3 | 461b4c60a28375ab296f16ed4bb33caf60e33f1e | /Tubes/src/Controller/ControllerKonfirmasiPinjam.java | 2c6570fe02e7a3fba1724c0d539ae2e21ea79da9 | [] | no_license | wafasa/Koperasi-1 | 548afb7c2b3e85c76a2c3c9fc9c5c5627a6f0a12 | c6a47ebbb9f49c8ec4f9ceec47cf2843259c72bf | refs/heads/master | 2020-12-30T12:23:27.337633 | 2016-12-09T02:40:47 | 2016-12-09T02:40:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,596 | 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 Controller;
import Database.Database;
import View.KonfirmasiHapus;
import View.KonfirmasiPinjam;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author reza
*/
public class ControllerKonfirmasiPinjam implements ActionListener {
private KonfirmasiPinjam konfirmasi = new KonfirmasiPinjam();
private Database db = new Database();
private String id = "";
private int amount = 0;
public ControllerKonfirmasiPinjam(String id,int amount) {
this.id = id;
this.amount = amount;
konfirmasi.setVisible(true);
konfirmasi.addListener(this);
db.connect();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(konfirmasi.getconfirmbutton())){
try {
db.konfirmasipeminjaman(this.id,this.amount);
System.out.println(id);
} catch (SQLException ex) {
Logger.getLogger(ControllerKonfirmasiPinjam.class.getName()).log(Level.SEVERE, null, ex);
}
}
konfirmasi.setVisible(false);
try {
db.close();
} catch (SQLException ex) {
Logger.getLogger(ControllerKonfirmasiPinjam.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| [
"[email protected]"
] | |
9be3b9246bbe46f21f607667c6381caef3db9d4a | 03484229f7264b5d5aab9042e6867ba3622ff198 | /src/main/java/com/psp/service/ProjectService.java | 1b6385871080e8e6f9ece8ff6f517be9f715bebe | [] | no_license | VLiamZhao/Project-Sharing-Platform | 26bb7bb52edcd1d0ff14197f1b0c154b779f46af | bc83c67c8e62498d71a6525cdadee3104976ef2f | refs/heads/master | 2022-12-21T10:43:14.234510 | 2020-09-25T07:27:34 | 2020-09-25T07:27:34 | 271,102,866 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,005 | java | package com.psp.service;
import com.psp.model.Project;
import com.psp.repository.ProjectDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProjectService {
@Autowired
ProjectDao projectDao;
public Project saveProject(Project project){
return projectDao.saveProject(project);
}
public boolean deleteProjectById(long id){
return projectDao.deleteProjectById(id);
}
public List<Project> getProjectList(){
return projectDao.getProjectList();
}
public Project updateProject(Project project){
return projectDao.updateProject(project);
}
public Project getProjectById(long id){
return projectDao.getProjectById(id);
}
public List<Project> getProjectsAndInfo(){return projectDao.getProjectsAndInfo();}
public List<Project> getProjectsAndInfoById(long id){return projectDao.getProjectsAndInfoById(id);}
}
| [
"[email protected]"
] | |
6d098e01632e7b1006154d6ff1ecf37ab5bfa948 | 3c238dc9e39a7cbec68305cbe914f46362cd3eaa | /youzan-ad-service/youzan-ad-sponsor/src/main/java/com/youzan/ad/entity/unit_condition/AdUnitDistrict.java | f1931870ed079e388b0e5388898c029c89ef8920 | [] | no_license | java-baimugudu/1607C | b0e022f872f0395a5dccbffeb2667cdac9acf996 | e849cde60881fa63792f857629b6ef67978f3ea5 | refs/heads/master | 2020-05-16T01:53:33.243437 | 2019-05-22T01:12:45 | 2019-05-22T01:12:45 | 182,610,191 | 11 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,165 | java | package com.youzan.ad.entity.unit_condition;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Created by baimugudu on 2019/3/26
* 地域限制
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "ad_unit_district")
public class AdUnitDistrict {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Basic
@Column(name = "unit_id", nullable = false)
private Long unitId;
/**
* 省
*/
@Basic
@Column(name = "province", nullable = false)
private String province;
/**
* 市
*/
@Basic
@Column(name = "city", nullable = false)
private String city;
public AdUnitDistrict(Long unitId, String province, String city) {
this.unitId = unitId;
this.province = province;
this.city = city;
}
}
| [
"[email protected]"
] | |
baf35735f94f977653f31bbb69b5f1f0badacd9e | ac6709b0f9d24f604e0f808b976c1635752286e0 | /src/com/vinay/designpatterns/strategy/scoreboarsystem/model/SquareBalloon.java | 215a26795384635df4f8b2a44c059da38276103c | [] | no_license | VinayagamD/JavaDesignPatterns | 6fcee95fd635a334e4814fe092e216448cbd55cf | b004c9a76932337d30da7ea47fb5ddb459741fd2 | refs/heads/master | 2020-07-03T17:40:24.118913 | 2019-10-02T15:53:58 | 2019-10-02T15:53:58 | 201,990,015 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 337 | java | package com.vinay.designpatterns.strategy.scoreboarsystem.model;
import com.vinay.designpatterns.strategy.scoreboarsystem.controller.ScoreAlgorithmBase;
public class SquareBalloon implements ScoreAlgorithmBase {
@Override
public int calculateScore(int taps, int multiplier) {
return (taps * multiplier) + 40;
}
}
| [
"[email protected]"
] | |
df68f4f61ce0fc373f18763ca0ab07ea8a7fb986 | 6bd1c798616947561e91c032a87c2dff7ab95bf3 | /Book.java | 5f3e52199082aec24e0aff9cff02f9ff549d565c | [] | no_license | AshiPal/pheonixrepo | 388edd0a462a92c030717b6141b192aa866f8eb7 | 297990075347125ec1d72fbaebaa367f5affbc64 | refs/heads/master | 2022-02-11T19:03:54.552451 | 2019-07-20T10:44:27 | 2019-07-20T10:44:27 | 197,891,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 367 | java | public class Book
{
public int bookId;
private String title;
private String author;
private float price;
public void setBookId(int bookId){
this.bookId=bookId;
}
public int getBookId(){
return bookId;
}
public void setTitle(String title){
this.title=title;
}
public void setTitle(String author){
this.author=author;
}
public void test();
} | [
"[email protected]"
] | |
10476027b13da26ddf8a837537a544cdb6a48139 | 95560053663d4b32dc437754860e0d7b1e4ac372 | /src/main/java/com/yelp/scraper/dto/gvisionapi/Request.java | 2836f442ee69e85540a9322c566a978ceedeb56b | [] | no_license | tuty-fruity/yelpscraper | 8b2e4b5b58238a76c044fb773fea7ec3513e0175 | 1699b53618e95fc730a028f484c71540adb71de8 | refs/heads/master | 2023-02-02T04:41:43.570403 | 2020-12-16T12:01:37 | 2020-12-16T12:01:37 | 321,962,823 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 247 | java | package com.yelp.scraper.dto.gvisionapi;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Request {
@JsonProperty(value = "image")
private ImageAttr image;
}
| [
"[email protected]"
] | |
132596f534225b3e22cc2b84df4e2e3ce1514e28 | 006c500a6ee933a9a55a8ebd13e6a0114fc661e7 | /src/main/java/br/ufc/hpc/frontend/webservice/CoreServicesParserConfigurationException.java | ce7f29b4e42a7372fa322a503265142e3d49360e | [] | no_license | alyssongomes/HPC-Shelf-FrontEnd | fcfe10ea5f550036f6cc33e3a06d25d02aaa3757 | 74b762ed6ea0b3fb89a0afa00d7fd0bc9c3817ef | refs/heads/master | 2021-04-22T06:35:47.450556 | 2017-12-19T23:27:40 | 2017-12-19T23:27:40 | 41,442,103 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,997 | java |
package br.ufc.hpc.frontend.webservice;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ParserConfigurationException" type="{http://www.w3.org/2001/XMLSchema}anyType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"parserConfigurationException"
})
@XmlRootElement(name = "CoreServicesParserConfigurationException")
public class CoreServicesParserConfigurationException {
@XmlElementRef(name = "ParserConfigurationException", namespace = "http://webservices.storm.ufc.br", type = JAXBElement.class, required = false)
protected JAXBElement<Object> parserConfigurationException;
/**
* Gets the value of the parserConfigurationException property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public JAXBElement<Object> getParserConfigurationException() {
return parserConfigurationException;
}
/**
* Sets the value of the parserConfigurationException property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public void setParserConfigurationException(JAXBElement<Object> value) {
this.parserConfigurationException = value;
}
}
| [
"[email protected]"
] | |
eb1a7bb5450b0f132166a52ff51199c956efff00 | 0051b6c25978ca8cf710b6839598c90d17cb4809 | /ex06_2/src/main/java/org/zerock/service/BoardService.java | fc80c3d1cbdcdec3a405d60c5891cc84c4c630c3 | [] | no_license | unisung/springQuickEclipse01 | 009e81301a275c753f003f03f77e799d82c22fb8 | 3ff09468c374060209f68a96b028c952c58d0053 | refs/heads/master | 2023-04-05T19:18:37.215717 | 2021-04-23T08:59:39 | 2021-04-23T08:59:39 | 351,041,296 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 523 | java | package org.zerock.service;
import java.util.List;
import org.zerock.domain.BoardAttachVO;
import org.zerock.domain.BoardVO;
import org.zerock.domain.Criteria;
public interface BoardService {
public void register(BoardVO board);
public BoardVO get(Long bno);
public boolean modify(BoardVO board);
public boolean remove(Long bno);
//public List<BoardVO> getList();
public List<BoardVO> getList(Criteria cri);
public int getTotal(Criteria cri);
public List<BoardAttachVO> getAttachList(Long bno);
}
| [
"[email protected]"
] | |
db7cc6d0e413eb8f96e3543dc22d784a5704180f | ccbf385aa34eab82295350bcca33b7904a180ce7 | /client/src/main/java/edu/sjsu/cmpe/cache/client/DistributedCacheService.java | e7e9a3744c9444355eebde6af403c71476089c7a | [] | no_license | Ashutosh-Chandane/cmpe273-lab3 | 35d4f90fe5588d257ec9768cdaf88111ec3e8c58 | 4db30443842cfd721c08387b66aa8d834ef322c7 | refs/heads/master | 2020-05-09T16:12:24.584747 | 2015-05-17T07:55:16 | 2015-05-17T07:55:16 | 35,752,244 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,777 | java | package edu.sjsu.cmpe.cache.client;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONArray;
/**
* Distributed cache service
*
*/
public class DistributedCacheService implements CacheServiceInterface {
private final String cacheServerUrl;
public DistributedCacheService(String serverUrl) {
this.cacheServerUrl = serverUrl;
}
/**
* @see edu.sjsu.cmpe.cache.client.CacheServiceInterface#get(long)
*/
@Override
public String get(long key) {
HttpResponse<JsonNode> response = null;
try {
response = Unirest.get(this.cacheServerUrl + "/cache/{key}")
.header("accept", "application/json")
.routeParam("key", Long.toString(key)).asJson();
} catch (UnirestException e) {
System.err.println(e);
}
String value = response.getBody().getObject().getString("value");
return value;
}
/**
* @see edu.sjsu.cmpe.cache.client.CacheServiceInterface#put(long,
* java.lang.String)
*/
@Override
public void put(long key, String value) {
HttpResponse<JsonNode> response = null;
try {
response = Unirest
.put(this.cacheServerUrl + "/cache/{key}/{value}")
.header("accept", "application/json")
.routeParam("key", Long.toString(key))
.routeParam("value", value).asJson();
} catch (UnirestException e) {
System.err.println(e);
}
if (response.getCode() != 200) {
System.out.println("Failed to add to the cache.");
}
}
@Override
public String getAllValues() {
HttpResponse<JsonNode> response = null;
try {
response = Unirest.get(this.cacheServerUrl + "/cache")
.header("accept", "application/json").asJson();
} catch (UnirestException e) {
System.err.println(e);
}
JSONArray array = response.getBody().getArray();
StringBuilder valuesBuilder = new StringBuilder().append("Values:");
StringBuilder keyBuilder = new StringBuilder().append("Keys:");
for(int length = 0;length < array.length();length++){
valuesBuilder.append(" "+array.getJSONObject(length).getString("value"));
keyBuilder.append(" "+ array.getJSONObject(length).getInt("key"));
}
return new StringBuilder().append(valuesBuilder.toString()+"\n"+ keyBuilder.toString()).toString();
}
public String getUrl() {
return cacheServerUrl;
}
}
| [
"[email protected]"
] | |
f2c0fbd7ee04aeaed4e0fb9d453d9ef68ac4a2e2 | 2c0cec95fe46e9d2234859f7cc0f83aed92e5aba | /insti_ciclos_taller/src/insti_ciclos_taller/CrearBase.java | a3e771ed48b24badc2a19d1c90b89db3eb261d72 | [] | no_license | VILABOA0008/programacion-cosas | 4ef528abb49e31371d57b602995d286f79352318 | d99b1be4871f9dcbc7392661a4a4d8d4077b8130 | refs/heads/master | 2020-05-04T18:29:12.363764 | 2019-04-03T19:46:09 | 2019-04-03T19:46:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,639 | 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 insti_ciclos_taller;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author a16pablovc
*/
public class CrearBase {
public static void crear(Statement sentencia){
try{
Connection conexion=DriverManager.getConnection("jdbc:mysql://localhost:3307/?user=root&password=usbw");
sentencia=conexion.createStatement();
sentencia.execute("CREATE DATABASE IF NOT EXISTS institutos_ciclos_talleres");
sentencia.execute("USE institutos_ciclos_talleres");
/* sentencia.execute("DROP TABLE Libros");
sentencia.execute("DROP TABLE Telefonos");
sentencia.execute("DROP TABLE Autores");
*/
sentencia.execute("CREATE TABLE IF NOT EXISTS ciclos ( "
+ "codciclo int(4) UNSIGNED ZEROFILL NOT NULL, "
+ "nombre VARCHAR(30) NOT NULL, "
+ "PRIMARY KEY (codciclo)) "
+ ";");
System.out.println("1");
sentencia.execute("CREATE TABLE IF NOT EXISTS institutos ( "
+ "codinsti int(4) UNSIGNED ZEROFILL NOT NULL, "
+ "telefono VARCHAR(30) NOT NULL, "
+ "PRIMARY KEY (codinsti))"
+ ";");
System.out.println("22");
sentencia.execute("CREATE TABLE IF NOT EXISTS ciclos_institutos ( "
+ "codinsti int(4) UNSIGNED ZEROFILL NOT NULL, "
+ "codciclo int(4) UNSIGNED ZEROFILL NOT NULL, "
+"FOREIGN KEY (codciclo) REFERENCES CICLOS(codciclo)"
+ "ON DELETE CASCADE "
+ "ON UPDATE CASCADE,"
+"FOREIGN KEY (codinsti) REFERENCES institutos(codinsti)"
+ "ON DELETE CASCADE "
+ "ON UPDATE CASCADE,"
+ "PRIMARY KEY (codinsti,codciclo))"
+ ";");
System.out.println("333");
sentencia.execute("CREATE TABLE IF NOT EXISTS talleres ( "
+ "codtaller int(4) UNSIGNED ZEROFILL NOT NULL, "
+ "nombre VARCHAR(30) NOT NULL, "
+ "PRIMARY KEY (codtaller))"
+ ";");
System.out.println("4444");
sentencia.execute("CREATE TABLE IF NOT EXISTS usos ( "
+ "codciclo int(4) UNSIGNED ZEROFILL NOT NULL, "
+ "codtaller int(4) UNSIGNED ZEROFILL NOT NULL, "
+ "fecha DATE NOT NULL, "
+ "hora TIME NOT NULL, "
+ "FOREIGN KEY (codciclo) REFERENCES CICLOS(codciclo)"
+ "ON DELETE CASCADE "
+ "ON UPDATE CASCADE,"
+ "FOREIGN KEY (codtaller) REFERENCES talleres(codtaller)"
+ "ON DELETE CASCADE "
+ "ON UPDATE CASCADE,"
+ "PRIMARY KEY (codciclo,codtaller,fecha,hora))"
+ ";");
}catch(SQLException e){System.out.println(e);}
}
}
| [
"[email protected]"
] | |
386d87d4388c399fdb328790dfeffa45a3c2084c | bb9fb15b60d96c58d20ff5a7335b947f83ccf1da | /app/src/main/java/com/googlecode/flickrjandroid/groups/members/MembersList.java | dff64bab317e72e3046cee71791d79defd9337b2 | [
"MIT"
] | permissive | rehansheta/Yahoo-Identify | 44f012b5beef67c58e1ca29cc99966382cb1f97c | e07c3fa3403b9c3f875ff4a53438f1bd6022f1b8 | refs/heads/master | 2021-05-04T06:30:48.501971 | 2016-10-10T11:16:15 | 2016-10-10T11:16:15 | 70,480,316 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 376 | java | package com.googlecode.flickrjandroid.groups.members;
import com.googlecode.flickrjandroid.SearchResultList;
/**
* List of Group-members.
*
* @author mago
* @version $Id: MembersList.java,v 1.1 2009/06/21 19:55:15 x-mago Exp $
*/
public class MembersList extends SearchResultList<Member> {
private static final long serialVersionUID = 617037681128L;
}
| [
"[email protected]"
] | |
a313da942e1d6c1c33d1a7a881a979b0a91d7bce | 6045518db77c6104b4f081381f61c26e0d19d5db | /datasets/file_version_per_commit_backup/jruby/4b16ae8975b3da52b4b2bac273ed452f358011c3.java | cd9ba5f5491716b0a8bdcaab4e19f685e1035948 | [] | no_license | edisutoyo/msr16_td_removal | 6e039da7fed166b81ede9b33dcc26ca49ba9259c | 41b07293c134496ba1072837e1411e05ed43eb75 | refs/heads/master | 2023-03-22T21:40:42.993910 | 2017-09-22T09:19:51 | 2017-09-22T09:19:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 50,611 | java | /***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.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.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <[email protected]>
* Copyright (C) 2001-2004 Jan Arne Petersen <[email protected]>
* Copyright (C) 2002 Benoit Cerrina <[email protected]>
* Copyright (C) 2002-2004 Anders Bengtsson <[email protected]>
* Copyright (C) 2004 Joey Gibson <[email protected]>
* Copyright (C) 2004 Charles O Nutter <[email protected]>
* Copyright (C) 2004 Stefan Matthias Aust <[email protected]>
* Copyright (C) 2006 Thomas E Enebo <[email protected]>
* Copyright (C) 2006 Ola Bini <[email protected]>
* Copyright (C) 2006 Miguel Covarrubias <[email protected]>
* Copyright (C) 2009 Joseph LaFata <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import static org.jruby.runtime.Visibility.PRIVATE;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.RubyDateFormatter;
import org.jruby.runtime.Helpers;
import static org.jruby.RubyComparable.invcmp;
import static org.jruby.runtime.Helpers.invokedynamic;
import static org.jruby.runtime.invokedynamic.MethodNames.OP_CMP;
/** The Time class.
*
* @author chadfowler, jpetersen
*/
@JRubyClass(name="Time", include="Comparable")
public class RubyTime extends RubyObject {
public static final String UTC = "UTC";
private DateTime dt;
private long nsec;
private final static DateTimeFormatter ONE_DAY_CTIME_FORMATTER = DateTimeFormat.forPattern("EEE MMM d HH:mm:ss yyyy").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TWO_DAY_CTIME_FORMATTER = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss yyyy").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TO_S_FORMATTER = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TO_S_UTC_FORMATTER = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss 'UTC' yyyy").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TO_S_FORMATTER_19 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss Z").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TO_S_UTC_FORMATTER_19 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withLocale(Locale.ENGLISH);
// There are two different popular TZ formats: legacy (AST+3:00:00, GMT-3), and
// newer one (US/Pacific, America/Los_Angeles). This pattern is to detect
// the legacy TZ format in order to convert it to the newer format
// understood by Java API.
private static final Pattern TZ_PATTERN
= Pattern.compile("([^-\\+\\d]+)?([\\+-]?)(\\d+)(?::(\\d+))?(?::\\d+)?");
private static final Pattern TIME_OFFSET_PATTERN
= Pattern.compile("([\\+-])(\\d\\d):(\\d\\d)");
private static final ByteList TZ_STRING = ByteList.create("TZ");
private boolean isTzRelative = false; // true if and only if #new is called with a numeric offset (e.g., "+03:00")
/* JRUBY-3560
* joda-time disallows use of three-letter time zone IDs.
* Since MRI accepts these values, we need to translate them.
*/
private static final Map<String, String> LONG_TZNAME = Helpers.map(
"MET", "CET", // JRUBY-2759
"ROC", "Asia/Taipei", // Republic of China
"WET", "Europe/Lisbon" // Western European Time
);
/* github-215
* Some non-JVM timezone names are recognized by MRI.
* This map translate those to JVM-friendly names.
*/
private static final Map<String, String> NON_JVM_TZNAME = Helpers.map(
"EDT", "EST",
"CDT", "CST",
"MDT", "MST",
"PDT", "PST"
);
/* Some TZ values need to be overriden for Time#zone
*/
private static final Map<String, String> SHORT_STD_TZNAME = Helpers.map(
"Etc/UCT", "UCT",
"MET", "MET", // needs to be overriden
"UCT", "UCT"
);
private static final Map<String, String> SHORT_DL_TZNAME = Helpers.map(
"Etc/UCT", "UCT",
"MET", "MEST", // needs to be overriden
"UCT", "UCT"
);
private void setIsTzRelative(boolean tzRelative) {
isTzRelative = tzRelative;
}
@Override
public ClassIndex getNativeClassIndex() {
return ClassIndex.TIME;
}
private static IRubyObject getEnvTimeZone(Ruby runtime) {
RubyString tzVar = runtime.newString(TZ_STRING);
RubyHash h = ((RubyHash)runtime.getObject().getConstant("ENV"));
IRubyObject tz = h.op_aref(runtime.getCurrentContext(), tzVar);
return tz;
}
public static DateTimeZone getLocalTimeZone(Ruby runtime) {
IRubyObject tz = getEnvTimeZone(runtime);
if (tz == null || ! (tz instanceof RubyString)) {
return DateTimeZone.getDefault();
} else {
return getTimeZone(runtime, tz.toString());
}
}
public static DateTimeZone getTimeZone(Ruby runtime, long seconds) {
if (seconds >= 60*60*24 || seconds <= -60*60*24) {
throw runtime.newArgumentError("utc_offset out of range");
}
// append "s" to the offset when looking up the cache
String zone = seconds + "s";
DateTimeZone cachedZone = runtime.getTimezoneCache().get(zone);
if (cachedZone != null) return cachedZone;
DateTimeZone dtz = DateTimeZone.forOffsetMillis((int) (seconds * 1000));
runtime.getTimezoneCache().put(zone, dtz);
return dtz;
}
public static DateTimeZone getTimeZone(Ruby runtime, String zone) {
DateTimeZone cachedZone = runtime.getTimezoneCache().get(zone);
if (cachedZone != null) return cachedZone;
String originalZone = zone;
if (NON_JVM_TZNAME.containsKey(zone.toUpperCase())) {
zone = NON_JVM_TZNAME.get(zone.toUpperCase());
}
TimeZone tz = TimeZone.getTimeZone(zone);
// Value of "TZ" property is of a bit different format,
// which confuses the Java's TimeZone.getTimeZone(id) method,
// and so, we need to convert it.
Matcher tzMatcher = TZ_PATTERN.matcher(zone);
if (tzMatcher.matches()) {
String sign = tzMatcher.group(2);
String hours = tzMatcher.group(3);
String minutes = tzMatcher.group(4);
if (Integer.parseInt(hours) > 23 ||
(minutes != null && Integer.parseInt(minutes) > 59)) {
throw runtime.newArgumentError("utc_offset out of range");
}
// GMT+00:00 --> Etc/GMT, see "MRI behavior"
// comment below.
if (("00".equals(hours) || "0".equals(hours)) &&
(minutes == null || "00".equals(minutes) || "0".equals(minutes))) {
zone = "Etc/GMT";
} else {
// Invert the sign, since TZ format and Java format
// use opposite signs, sigh... Also, Java API requires
// the sign to be always present, be it "+" or "-".
sign = ("-".equals(sign)? "+" : "-");
// Always use "GMT" since that's required by Java API.
zone = "GMT" + sign + hours;
if (minutes != null) {
zone += minutes;
}
}
tz = TimeZone.getTimeZone(zone);
} else {
if (LONG_TZNAME.containsKey(zone)) tz.setID(LONG_TZNAME.get(zone.toUpperCase()));
}
// MRI behavior: With TZ equal to "GMT" or "UTC", Time.now
// is *NOT* considered as a proper GMT/UTC time:
// ENV['TZ']="GMT"
// Time.now.gmt? ==> false
// ENV['TZ']="UTC"
// Time.now.utc? ==> false
// Hence, we need to adjust for that.
if ("GMT".equalsIgnoreCase(zone) || "UTC".equalsIgnoreCase(zone)) {
zone = "Etc/" + zone;
tz = TimeZone.getTimeZone(zone);
}
DateTimeZone dtz = DateTimeZone.forTimeZone(tz);
runtime.getTimezoneCache().put(originalZone, dtz);
return dtz;
}
public static DateTimeZone getTimeZoneFromUtcOffset(Ruby runtime, String utcOffset) {
DateTimeZone cachedZone = runtime.getTimezoneCache().get(utcOffset);
if (cachedZone != null) return cachedZone;
Matcher offsetMatcher = TIME_OFFSET_PATTERN.matcher(utcOffset);
if (offsetMatcher.matches()) {
String sign = offsetMatcher.group(1);
String hours = offsetMatcher.group(2);
String minutes = offsetMatcher.group(3);
if (Integer.parseInt(hours) > 23 ||
(minutes != null && Integer.parseInt(minutes) > 59)) {
throw runtime.newArgumentError("utc_offset out of range");
}
long seconds = Integer.parseInt(hours) * 3600 + Integer.parseInt(minutes) * 60;
seconds = "-".equals(sign) ? (-1) * seconds : seconds;
DateTimeZone dtz = DateTimeZone.forOffsetMillis((int) (seconds * 1000));
//DateTimeZone dtz = DateTimeZone.forTimeZone(tz);
runtime.getTimezoneCache().put(utcOffset, dtz);
return dtz;
} else {
throw runtime.newArgumentError("\"+HH:MM\" or \"-HH:MM\" expected for utc_offset");
}
}
public RubyTime(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass);
}
public RubyTime(Ruby runtime, RubyClass rubyClass, DateTime dt) {
super(runtime, rubyClass);
this.dt = dt;
}
private static ObjectAllocator TIME_ALLOCATOR = new ObjectAllocator() {
@Override
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
DateTimeZone dtz = getLocalTimeZone(runtime);
DateTime dt = new DateTime(dtz);
RubyTime rt = new RubyTime(runtime, klass, dt);
rt.setNSec(0);
return rt;
}
};
public static RubyClass createTimeClass(Ruby runtime) {
RubyClass timeClass = runtime.defineClass("Time", runtime.getObject(), TIME_ALLOCATOR);
timeClass.setClassIndex(ClassIndex.TIME);
timeClass.setReifiedClass(RubyTime.class);
runtime.setTime(timeClass);
timeClass.includeModule(runtime.getComparable());
timeClass.defineAnnotatedMethods(RubyTime.class);
return timeClass;
}
public void setNSec(long nsec) {
this.nsec = nsec;
}
public long getNSec() {
return nsec;
}
public void setUSec(long usec) {
this.nsec = 1000 * usec;
}
public long getUSec() {
return nsec / 1000;
}
public void updateCal(DateTime dt) {
this.dt = dt;
}
protected long getTimeInMillis() {
return dt.getMillis();
}
public static RubyTime newTime(Ruby runtime, long milliseconds) {
return newTime(runtime, new DateTime(milliseconds));
}
public static RubyTime newTime(Ruby runtime, DateTime dt) {
return new RubyTime(runtime, runtime.getTime(), dt);
}
public static RubyTime newTime(Ruby runtime, DateTime dt, long nsec) {
RubyTime t = new RubyTime(runtime, runtime.getTime(), dt);
t.setNSec(nsec);
return t;
}
@Override
public Class<?> getJavaClass() {
return Date.class;
}
@JRubyMethod(required = 1, visibility = Visibility.PRIVATE)
@Override
public IRubyObject initialize_copy(IRubyObject original) {
if (!(original instanceof RubyTime)) {
throw getRuntime().newTypeError("Expecting an instance of class Time");
}
RubyTime originalTime = (RubyTime) original;
// We can just use dt, since it is immutable
dt = originalTime.dt;
nsec = originalTime.nsec;
return this;
}
@JRubyMethod
public RubyTime succ() {
return newTime(getRuntime(),dt.plusSeconds(1));
}
@JRubyMethod(name = {"gmtime", "utc"})
public RubyTime gmtime() {
dt = dt.withZone(DateTimeZone.UTC);
return this;
}
public RubyTime localtime() {
return localtime19(getRuntime().getCurrentContext(), NULL_ARRAY);
}
@JRubyMethod(name = "localtime", optional = 1)
public RubyTime localtime19(ThreadContext context, IRubyObject[] args) {
if (args.length == 0) {
dt = dt.withZone(getLocalTimeZone(getRuntime()));
return this;
}
String offset = args[0].asJavaString();
Matcher offsetMatcher = TIME_OFFSET_PATTERN.matcher(offset);
if (! offsetMatcher.matches()) {
throw context.runtime.newArgumentError("\"+HH:MM\" or \"-HH:MM\" expected for utc_offset");
}
String sign = offsetMatcher.group(1);
String hours = offsetMatcher.group(2);
String minutes = offsetMatcher.group(3);
String zone;
if ("00".equals(hours) && "00".equals(minutes)) {
zone = "Etc/GMT";
} else {
// Java needs the sign inverted
String sgn = "+".equals(sign) ? "-" : "+";
zone = "GMT" + sgn + hours + ":" + minutes;
}
DateTimeZone dtz = getTimeZone(context.runtime, zone);
return newTime(context.runtime, dt.withZone(dtz), nsec);
}
@JRubyMethod(name = {"gmt?", "utc?", "gmtime?"})
public RubyBoolean gmt() {
return getRuntime().newBoolean(dt.getZone().getID().equals("UTC"));
}
@JRubyMethod(name = {"getgm", "getutc"})
public RubyTime getgm() {
return newTime(getRuntime(), dt.withZone(DateTimeZone.UTC), nsec);
}
public RubyTime getlocal() {
return getlocal19(getRuntime().getCurrentContext(), NULL_ARRAY);
}
@JRubyMethod(name = "getlocal", optional = 1)
public RubyTime getlocal19(ThreadContext context, IRubyObject[] args) {
if (args.length == 0) {
return newTime(getRuntime(), dt.withZone(getLocalTimeZone(getRuntime())), nsec);
} else {
Matcher tzMatcher = TIME_OFFSET_PATTERN.matcher(args[0].toString());
int hours, minutes, millis = 0;
if (tzMatcher.matches()) {
hours = Integer.parseInt(tzMatcher.group(2));
minutes = Integer.parseInt(tzMatcher.group(3));
millis = (hours * 60 + minutes) * 60 * 1000;
if (tzMatcher.group(1).equals("-"))
millis = -millis;
} else {
throw getRuntime().newArgumentError("\"+HH:MM\" or \"-HH:MM\" expected for utc_offset");
}
return newTime(getRuntime(), dt.withZone(DateTimeZone.forOffsetMillis(millis)), nsec);
}
}
@JRubyMethod(required = 1)
public RubyString strftime(IRubyObject format) {
final RubyDateFormatter rdf = getRuntime().getCurrentContext().getRubyDateFormatter();
return rdf.compileAndFormat(format.convertToString(), false, dt, nsec, null);
}
@JRubyMethod(name = "==", required = 1)
@Override
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
if (other.isNil()) {
return RubyBoolean.newBoolean(getRuntime(), false);
} else if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) == 0);
}
return RubyComparable.op_equal19(context, this, other);
}
@JRubyMethod(name = ">=", required = 1)
public IRubyObject op_ge(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) >= 0);
}
return RubyComparable.op_ge(context, this, other);
}
@JRubyMethod(name = ">", required = 1)
public IRubyObject op_gt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) > 0);
}
return RubyComparable.op_gt(context, this, other);
}
@JRubyMethod(name = "<=", required = 1)
public IRubyObject op_le(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) <= 0);
}
return RubyComparable.op_le(context, this, other);
}
@JRubyMethod(name = "<", required = 1)
public IRubyObject op_lt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) < 0);
}
return RubyComparable.op_lt(context, this, other);
}
private int cmp(RubyTime other) {
Ruby runtime = getRuntime();
long millis = getTimeInMillis();
long millis_other = other.getTimeInMillis();
// ignore < usec on 1.8
long nanosec = this.nsec;
long nsec_other = other.nsec;
if (millis > millis_other || (millis == millis_other && nanosec > nsec_other)) {
return 1;
} else if (millis < millis_other || (millis == millis_other && nanosec < nsec_other)) {
return -1;
}
return 0;
}
public IRubyObject op_plus(IRubyObject other) {
return op_plus19(getRuntime().getCurrentContext(), other);
}
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus19(ThreadContext context, IRubyObject other) {
checkOpCoercion(context, other);
if (other instanceof RubyTime) {
throw getRuntime().newTypeError("time + time ?");
}
other = other.callMethod(context, "to_r");
long adjustNanos = (long)(RubyNumeric.num2dbl(other) * 1000000000);
return opPlusNanos(adjustNanos);
}
private IRubyObject opPlusNanos(long adjustNanos) {
long currentMillis = getTimeInMillis();
long adjustMillis = adjustNanos/1000000;
long adjustNanosLeft = adjustNanos - (adjustMillis*1000000);
long newMillisPart = currentMillis + adjustMillis;
long newNanosPart = nsec + adjustNanosLeft;
if (newNanosPart >= 1000000) {
newNanosPart -= 1000000;
newMillisPart++;
}
RubyTime newTime = new RubyTime(getRuntime(), getMetaClass());
newTime.dt = new DateTime(newMillisPart).withZone(dt.getZone());
newTime.setNSec(newNanosPart);
return newTime;
}
private void checkOpCoercion(ThreadContext context, IRubyObject other) {
if (other instanceof RubyString) {
throw context.runtime.newTypeError("no implicit conversion to rational from string");
} else if (other.isNil()) {
throw context.runtime.newTypeError("no implicit conversion to rational from nil");
} else if (!other.respondsTo("to_r")){
throw context.runtime.newTypeError("can't convert " + other.getMetaClass().getBaseName() + " into Rational");
}
}
private IRubyObject opMinus(RubyTime other) {
long timeInMillis = (getTimeInMillis() - other.getTimeInMillis());
double timeInSeconds = timeInMillis/1000.0 + (getNSec() - other.getNSec())/1000000000.0;
return RubyFloat.newFloat(getRuntime(), timeInSeconds); // float number of seconds
}
public IRubyObject op_minus(IRubyObject other) {
return op_minus19(getRuntime().getCurrentContext(), other);
}
@JRubyMethod(name = "-", required = 1)
public IRubyObject op_minus19(ThreadContext context, IRubyObject other) {
checkOpCoercion(context, other);
if (other instanceof RubyTime) return opMinus((RubyTime) other);
return opMinusCommon(other.callMethod(context, "to_r"));
}
private IRubyObject opMinusCommon(IRubyObject other) {
long adjustmentInNanos = (long)(RubyNumeric.num2dbl(other)*1000000000);
long adjustmentInMillis = adjustmentInNanos/1000000;
long adjustmentInNanosLeft = adjustmentInNanos%1000000;
long time = getTimeInMillis() - adjustmentInMillis;
long nano;
if (nsec < adjustmentInNanosLeft) {
time--;
nano = 1000000 - (adjustmentInNanosLeft - nsec);
} else {
nano = nsec - adjustmentInNanosLeft;
}
RubyTime newTime = new RubyTime(getRuntime(), getMetaClass());
newTime.dt = new DateTime(time).withZone(dt.getZone());
newTime.setNSec(nano);
return newTime;
}
@JRubyMethod(name = "===", required = 1)
@Override
public IRubyObject op_eqq(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return context.runtime.newBoolean(RubyNumeric.fix2int(invokedynamic(context, this, OP_CMP, other)) == 0);
}
return context.getRuntime().getFalse();
}
@JRubyMethod(name = "<=>", required = 1)
@Override
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return context.runtime.newFixnum(cmp((RubyTime) other));
}
return invcmp(context, this, other);
}
@JRubyMethod(name = "eql?", required = 1)
@Override
public IRubyObject eql_p(IRubyObject other) {
if (other instanceof RubyTime) {
RubyTime otherTime = (RubyTime)other;
return (nsec == otherTime.nsec && getTimeInMillis() == otherTime.getTimeInMillis()) ? getRuntime().getTrue() : getRuntime().getFalse();
}
return getRuntime().getFalse();
}
@JRubyMethod(name = {"asctime", "ctime"})
public RubyString asctime() {
DateTimeFormatter simpleDateFormat;
if (dt.getDayOfMonth() < 10) {
simpleDateFormat = ONE_DAY_CTIME_FORMATTER;
} else {
simpleDateFormat = TWO_DAY_CTIME_FORMATTER;
}
String result = simpleDateFormat.print(dt);
return getRuntime().newString(result);
}
@Override
public IRubyObject to_s() {
return to_s19();
}
@JRubyMethod(name = {"to_s", "inspect"})
public IRubyObject to_s19() {
return inspectCommon(TO_S_FORMATTER_19, TO_S_UTC_FORMATTER_19);
}
private IRubyObject inspectCommon(DateTimeFormatter formatter, DateTimeFormatter utcFormatter) {
DateTimeFormatter simpleDateFormat;
if (dt.getZone() == DateTimeZone.UTC) {
simpleDateFormat = utcFormatter;
} else {
simpleDateFormat = formatter;
}
String result = simpleDateFormat.print(dt);
if (isTzRelative) {
// display format needs to invert the UTC offset if this object was
// created with a specific offset in the 7-arg form of #new
DateTimeZone dtz = dt.getZone();
int offset = dtz.toTimeZone().getOffset(dt.getMillis());
DateTimeZone invertedDTZ = DateTimeZone.forOffsetMillis(offset);
DateTime invertedDT = dt.withZone(invertedDTZ);
result = simpleDateFormat.print(invertedDT);
}
return getRuntime().newString(result);
}
@JRubyMethod
@Override
public RubyArray to_a() {
return getRuntime().newArrayNoCopy(new IRubyObject[] { sec(), min(), hour(), mday(), month(),
year(), wday(), yday(), isdst(), zone() });
}
@JRubyMethod
public RubyFloat to_f() {
long millis = getTimeInMillis();
long nanos = nsec;
double secs = 0;
if (millis != 0) secs += (millis / 1000.0);
if (nanos != 0) secs += (nanos / 1000000000.0);
return RubyFloat.newFloat(getRuntime(), secs);
}
@JRubyMethod(name = {"to_i", "tv_sec"})
public RubyInteger to_i() {
return getRuntime().newFixnum(getTimeInMillis() / 1000);
}
@JRubyMethod(name = {"nsec", "tv_nsec"})
public RubyInteger nsec() {
return getRuntime().newFixnum((getTimeInMillis() % 1000) * 1000000 + nsec);
}
@JRubyMethod
public IRubyObject to_r(ThreadContext context) {
IRubyObject rational = to_f().to_r(context);
return rational;
}
@JRubyMethod(name = {"usec", "tv_usec"})
public RubyInteger usec() {
return getRuntime().newFixnum(dt.getMillisOfSecond() * 1000 + getUSec());
}
public void setMicroseconds(long mic) {
long millis = getTimeInMillis() % 1000;
long withoutMillis = getTimeInMillis() - millis;
withoutMillis += (mic / 1000);
dt = dt.withMillis(withoutMillis);
nsec = (mic % 1000) * 1000;
}
public long microseconds() {
return getTimeInMillis() % 1000 * 1000 + getUSec();
}
@JRubyMethod
public RubyInteger sec() {
return getRuntime().newFixnum(dt.getSecondOfMinute());
}
@JRubyMethod
public RubyInteger min() {
return getRuntime().newFixnum(dt.getMinuteOfHour());
}
@JRubyMethod
public RubyInteger hour() {
return getRuntime().newFixnum(dt.getHourOfDay());
}
@JRubyMethod(name = {"mday", "day"})
public RubyInteger mday() {
return getRuntime().newFixnum(dt.getDayOfMonth());
}
@JRubyMethod(name = {"month", "mon"})
public RubyInteger month() {
return getRuntime().newFixnum(dt.getMonthOfYear());
}
@JRubyMethod
public RubyInteger year() {
return getRuntime().newFixnum(dt.getYear());
}
@JRubyMethod
public RubyInteger wday() {
return getRuntime().newFixnum((dt.getDayOfWeek()%7));
}
@JRubyMethod
public RubyInteger yday() {
return getRuntime().newFixnum(dt.getDayOfYear());
}
@JRubyMethod
public IRubyObject subsec() {
Ruby runtime = getRuntime();
long nanosec = dt.getMillisOfSecond() * 1000000 + this.nsec;
if (nanosec % 1000000000 == 0) return RubyFixnum.zero(runtime);
return runtime.newRationalReduced(
nanosec, 1000000000);
}
@JRubyMethod(name = {"gmt_offset", "gmtoff", "utc_offset"})
public RubyInteger gmt_offset() {
int offset = dt.getZone().getOffset(dt.getMillis());
return getRuntime().newFixnum((int)(offset/1000));
}
@JRubyMethod(name = {"isdst", "dst?"})
public RubyBoolean isdst() {
return getRuntime().newBoolean(!dt.getZone().isStandardOffset(dt.getMillis()));
}
@JRubyMethod
public IRubyObject zone() {
Ruby runtime = getRuntime();
if (isTzRelative) return runtime.getNil();
String envTZ = getEnvTimeZone(runtime).toString();
// see declaration of SHORT_TZNAME
if (SHORT_STD_TZNAME.containsKey(envTZ) && ! dt.getZone().toTimeZone().inDaylightTime(dt.toDate())) {
return runtime.newString(SHORT_STD_TZNAME.get(envTZ));
}
if (SHORT_DL_TZNAME.containsKey(envTZ) && dt.getZone().toTimeZone().inDaylightTime(dt.toDate())) {
return runtime.newString(SHORT_DL_TZNAME.get(envTZ));
}
String zone = dt.getZone().getShortName(dt.getMillis());
Matcher offsetMatcher = TIME_OFFSET_PATTERN.matcher(zone);
if (offsetMatcher.matches()) {
boolean minus_p = offsetMatcher.group(1).toString().equals("-");
int hourOffset = Integer.valueOf(offsetMatcher.group(2));
if (zone.equals("+00:00")) {
zone = "GMT";
} else {
// try non-localized time zone name
zone = dt.getZone().getNameKey(dt.getMillis());
if (zone == null) {
char sign = minus_p ? '+' : '-';
zone = "GMT" + sign + hourOffset;
}
}
}
return runtime.newString(zone);
}
public void setDateTime(DateTime dt) {
this.dt = dt;
}
public DateTime getDateTime() {
return this.dt;
}
public Date getJavaDate() {
return this.dt.toDate();
}
@JRubyMethod
@Override
public RubyFixnum hash() {
// modified to match how hash is calculated in 1.8.2
return getRuntime().newFixnum((int)(((dt.getMillis() / 1000) ^ microseconds()) << 1) >> 1);
}
@JRubyMethod(name = "_dump", optional = 1)
public RubyString dump(IRubyObject[] args, Block unusedBlock) {
RubyString str = (RubyString) mdump();
str.syncVariables(this);
return str;
}
public RubyObject mdump() {
Ruby runtime = getRuntime();
RubyTime obj = this;
DateTime dateTime = obj.dt.toDateTime(DateTimeZone.UTC);
byte dumpValue[] = new byte[8];
long nanos = this.nsec;
long usec = this.nsec / 1000;
long nanosec = this.nsec % 1000;
int pe =
0x1 << 31 |
((obj.gmt().isTrue())? 0x1 : 0x0) << 30 |
(dateTime.getYear()-1900) << 14 |
(dateTime.getMonthOfYear()-1) << 10 |
dateTime.getDayOfMonth() << 5 |
dateTime.getHourOfDay();
int se =
dateTime.getMinuteOfHour() << 26 |
dateTime.getSecondOfMinute() << 20 |
(dateTime.getMillisOfSecond() * 1000 + (int)usec); // dump usec, not msec
for(int i = 0; i < 4; i++) {
dumpValue[i] = (byte)(pe & 0xFF);
pe >>>= 8;
}
for(int i = 4; i < 8 ;i++) {
dumpValue[i] = (byte)(se & 0xFF);
se >>>= 8;
}
RubyString string = RubyString.newString(obj.getRuntime(), new ByteList(dumpValue));
// 1.9 includes more nsecs
copyInstanceVariablesInto(string);
// nanos in numerator/denominator form
if (nanosec != 0) {
string.setInternalVariable("nano_num", runtime.newFixnum(nanosec));
string.setInternalVariable("nano_den", runtime.newFixnum(1));
}
// submicro for 1.9.1 compat
byte[] submicro = new byte[2];
int len = 2;
submicro[1] = (byte)((nanosec % 10) << 4);
nanosec /= 10;
submicro[0] = (byte)(nanosec % 10);
nanosec /= 10;
submicro[0] |= (byte)((nanosec % 10) << 4);
if (submicro[1] == 0) len = 1;
string.setInternalVariable("submicro", RubyString.newString(runtime, submicro, 0, len));
// time zone
if (dt.getZone() != DateTimeZone.UTC) {
long offset = dt.getZone().getOffset(dt.getMillis());
string.setInternalVariable("offset", runtime.newFixnum(offset / 1000));
}
return string;
}
@JRubyMethod(visibility = PRIVATE)
public IRubyObject initialize(Block block) {
return this;
}
@JRubyMethod(optional = 1)
public RubyTime round(ThreadContext context, IRubyObject[] args) {
int ndigits = args.length == 0 ? 0 : RubyNumeric.num2int(args[0]);
// There are only 1_000_000_000 nanoseconds in 1 second,
// so there is no need to keep more than 9 digits
if (ndigits > 9) {
ndigits = 9;
} else if (ndigits < 0) {
throw context.getRuntime().newArgumentError("negative ndigits given");
}
int _nsec = this.dt.getMillisOfSecond() * 1000000 + (int) (this.nsec);
int pow = (int) Math.pow(10, 9 - ndigits);
int rounded = ((_nsec + pow/2) / pow) * pow;
DateTime _dt = this.dt.withMillisOfSecond(0).plusMillis(rounded / 1000000);
return newTime(context.runtime, _dt, rounded % 1000000);
}
/* Time class methods */
public static IRubyObject s_new(IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = recv.getRuntime();
RubyTime time = new RubyTime(runtime, (RubyClass) recv, new DateTime(getLocalTimeZone(runtime)));
time.callInit(args,block);
return time;
}
/**
* @deprecated Use {@link #newInstance(ThreadContext, IRubyObject)}
*/
@Deprecated
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return newInstance(context, recv);
}
@JRubyMethod(name = "now", meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv) {
IRubyObject obj = ((RubyClass) recv).allocate();
obj.getMetaClass().getBaseCallSite(RubyClass.CS_IDX_INITIALIZE).call(context, recv, obj);
return obj;
}
@JRubyMethod(meta = true)
public static IRubyObject at(ThreadContext context, IRubyObject recv, IRubyObject arg) {
Ruby runtime = context.runtime;
final RubyTime time;
if (arg instanceof RubyTime) {
RubyTime other = (RubyTime) arg;
time = new RubyTime(runtime, (RubyClass) recv, other.dt);
time.setNSec(other.getNSec());
} else {
time = new RubyTime(runtime, (RubyClass) recv,
new DateTime(0L, getLocalTimeZone(runtime)));
long seconds = RubyNumeric.num2long(arg);
long millisecs = 0;
long nanosecs = 0;
// In the case of two arguments, MRI will discard the portion of
// the first argument after a decimal point (i.e., "floor").
// However in the case of a single argument, any portion after
// the decimal point is honored.
if (arg instanceof RubyFloat || arg instanceof RubyRational) {
double dbl = RubyNumeric.num2dbl(arg);
long nano;
nano = Math.round((dbl - seconds) * 1000000000);
if (dbl < 0 && nano != 0) {
nano += 1000000000;
}
millisecs = nano / 1000000;
nanosecs = nano % 1000000;
}
time.setNSec(nanosecs);
time.dt = time.dt.withMillis(seconds * 1000 + millisecs);
}
time.getMetaClass().getBaseCallSite(RubyClass.CS_IDX_INITIALIZE).call(context, recv, time);
return time;
}
@JRubyMethod(meta = true)
public static IRubyObject at(ThreadContext context, IRubyObject recv, IRubyObject arg1, IRubyObject arg2) {
Ruby runtime = context.runtime;
RubyTime time = new RubyTime(runtime, (RubyClass) recv, new DateTime(0L, getLocalTimeZone(runtime)));
long millisecs;
long nanosecs = 0;
if (arg1 instanceof RubyFloat || arg1 instanceof RubyRational) {
double dbl = RubyNumeric.num2dbl(arg1);
millisecs = (long) (dbl * 1000);
nanosecs = ((long) (dbl * 1000000000)) % 1000000;
} else {
millisecs = RubyNumeric.num2long(arg1) * 1000;
}
if (arg2 instanceof RubyFloat || arg2 instanceof RubyRational) {
double micros = RubyNumeric.num2dbl(arg2);
double nanos = micros * 1000;
millisecs += (long) (nanos / 1000000);
nanosecs += (long) (nanos % 1000000);
} else {
long micros = RubyNumeric.num2long(arg2);
long nanos = micros * 1000;
millisecs += nanos / 1000000;
nanosecs += nanos % 1000000;
}
long nanosecOverflow = (nanosecs / 1000000);
time.setNSec(nanosecs % 1000000);
time.dt = time.dt.withMillis(millisecs + nanosecOverflow);
time.getMetaClass().getBaseCallSite(RubyClass.CS_IDX_INITIALIZE).call(context, recv, time);
return time;
}
@JRubyMethod(name = {"local", "mktime"}, required = 1, optional = 9, meta = true)
public static RubyTime new_local(IRubyObject recv, IRubyObject[] args) {
return createTime(recv, args, false, false);
}
@JRubyMethod(name = "new", optional = 7, meta = true)
public static IRubyObject new19(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length == 0) return newInstance(context, recv);
if (args.length == 7) {
Ruby runtime = context.getRuntime();
// 7th argument can be the symbol :dst instead of an offset, so needs to be special cased
final RubySymbol dstSymbol = RubySymbol.newSymbol(runtime, "dst");
boolean receivedDstSymbolAsArgument = (args[6].op_equal(context, dstSymbol)).isTrue();
final RubyBoolean isDst = RubyBoolean.newBoolean(runtime, receivedDstSymbolAsArgument);
// Convert the 7-argument form of Time.new into the 10-argument form of Time.local:
args = new IRubyObject[] { args[5], // seconds
args[4], // minutes
args[3], // hours
args[2], // day
args[1], // month
args[0], // year
runtime.getNil(), // weekday
runtime.getNil(), // day of year
isDst, // is DST?
args[6] }; // UTC offset
}
return createTime(recv, args, false, true);
}
@JRubyMethod(name = {"utc", "gm"}, required = 1, optional = 9, meta = true)
public static RubyTime new_utc(IRubyObject recv, IRubyObject[] args) {
return createTime(recv, args, true, false);
}
@JRubyMethod(name = "_load", meta = true)
public static RubyTime load(IRubyObject recv, IRubyObject from, Block block) {
return s_mload(recv, (RubyTime)(((RubyClass)recv).allocate()), from);
}
@Override
public Object toJava(Class target) {
if (target.equals(Date.class)) {
return getJavaDate();
} else if (target.equals(Calendar.class)) {
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(getJavaDate());
return cal;
} else if (target.equals(DateTime.class)) {
return this.dt;
} else if (target.equals(java.sql.Date.class)) {
return new java.sql.Date(dt.getMillis());
} else if (target.equals(java.sql.Time.class)) {
return new java.sql.Time(dt.getMillis());
} else if (target.equals(java.sql.Timestamp.class)) {
return new java.sql.Timestamp(dt.getMillis());
} else if (target.isAssignableFrom(Date.class)) {
return getJavaDate();
} else {
return super.toJava(target);
}
}
protected static RubyTime s_mload(IRubyObject recv, RubyTime time, IRubyObject from) {
Ruby runtime = recv.getRuntime();
DateTime dt = new DateTime(DateTimeZone.UTC);
byte[] fromAsBytes;
fromAsBytes = from.convertToString().getBytes();
if(fromAsBytes.length != 8) {
throw runtime.newTypeError("marshaled time format differ");
}
int p=0;
int s=0;
for (int i = 0; i < 4; i++) {
p |= ((int)fromAsBytes[i] & 0xFF) << (8 * i);
}
for (int i = 4; i < 8; i++) {
s |= ((int)fromAsBytes[i] & 0xFF) << (8 * (i - 4));
}
boolean utc = false;
if ((p & (1<<31)) == 0) {
dt = dt.withMillis(p * 1000L);
time.setUSec((s & 0xFFFFF) % 1000);
} else {
p &= ~(1<<31);
utc = ((p >>> 30 & 0x1) == 0x1);
dt = dt.withYear(((p >>> 14) & 0xFFFF) + 1900);
dt = dt.withMonthOfYear(((p >>> 10) & 0xF) + 1);
dt = dt.withDayOfMonth(((p >>> 5) & 0x1F));
dt = dt.withHourOfDay((p & 0x1F));
dt = dt.withMinuteOfHour(((s >>> 26) & 0x3F));
dt = dt.withSecondOfMinute(((s >>> 20) & 0x3F));
// marsaling dumps usec, not msec
dt = dt.withMillisOfSecond((s & 0xFFFFF) / 1000);
time.setUSec((s & 0xFFFFF) % 1000);
}
time.setDateTime(dt);
if (!utc) time.localtime();
from.getInstanceVariables().copyInstanceVariablesInto(time);
// pull out nanos, offset
IRubyObject nano_num = (IRubyObject) from.getInternalVariables().getInternalVariable("nano_num");
IRubyObject nano_den = (IRubyObject) from.getInternalVariables().getInternalVariable("nano_den");
IRubyObject offset = (IRubyObject) from.getInternalVariables().getInternalVariable("offset");
if (nano_num != null && nano_den != null) {
long nanos = nano_num.convertToInteger().getLongValue() / nano_den.convertToInteger().getLongValue();
time.nsec += nanos;
}
if (offset != null) {
long tz = offset.convertToInteger().getLongValue();
time.dt = dt.withZone(DateTimeZone.forOffsetMillis((int)(tz * 1000)));
}
return time;
}
private static final String[] MONTHS = {"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"};
private static final Map<String, Integer> MONTHS_MAP = new HashMap<String, Integer>();
static {
for (int i = 0; i < MONTHS.length; i++) {
MONTHS_MAP.put(MONTHS[i], i + 1);
}
}
private static final int ARG_SIZE = 7;
private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt, boolean utcOffset) {
Ruby runtime = recv.getRuntime();
int len = ARG_SIZE;
boolean isDst = false;
boolean setTzRelative = false;
long nanos = 0;
DateTimeZone dtz;
if (gmt) {
dtz = DateTimeZone.UTC;
} else if (args.length == 10 && args[9] instanceof RubyString) {
if (utcOffset) {
dtz = getTimeZoneFromUtcOffset(runtime, ((RubyString) args[9]).toString());
setTzRelative = true;
} else {
dtz = getTimeZone(runtime, ((RubyString) args[9]).toString());
}
} else if (args.length == 10 && args[9].respondsTo("to_int")) {
IRubyObject offsetInt = args[9].callMethod(runtime.getCurrentContext(), "to_int");
dtz = getTimeZone(runtime, ((RubyNumeric) offsetInt).getLongValue());
} else {
dtz = getLocalTimeZone(runtime);
}
if (args.length == 10) {
if (args[8] instanceof RubyBoolean) isDst = ((RubyBoolean) args[8]).isTrue();
args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil() };
} else {
// MRI accepts additional wday argument which appears to be ignored.
len = args.length;
if (len < ARG_SIZE) {
IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
System.arraycopy(args, 0, newArgs, 0, args.length);
for (int i = len; i < ARG_SIZE; i++) {
newArgs[i] = runtime.getNil();
}
args = newArgs;
len = ARG_SIZE;
}
}
if (args[0] instanceof RubyString) {
args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
}
int year = (int) RubyNumeric.num2long(args[0]);
int month = 1;
if (len > 1) {
if (!args[1].isNil()) {
IRubyObject tmp = args[1].checkStringType();
if (!tmp.isNil()) {
String monthString = tmp.toString().toLowerCase();
Integer monthInt = MONTHS_MAP.get(monthString);
if (monthInt != null) {
month = monthInt;
} else {
try {
month = Integer.parseInt(monthString);
} catch (NumberFormatException nfExcptn) {
throw runtime.newArgumentError("Argument out of range.");
}
}
} else {
month = (int) RubyNumeric.num2long(args[1]);
}
}
if (1 > month || month > 12) {
throw runtime.newArgumentError("Argument out of range: for month: " + month);
}
}
int[] int_args = { 1, 0, 0, 0, 0, 0 };
for (int i = 0; int_args.length >= i + 2; i++) {
if (!args[i + 2].isNil()) {
if (!(args[i + 2] instanceof RubyNumeric)) {
if (args[i + 2].respondsTo("to_int")) {
args[i + 2] = args[i + 2].callMethod(
runtime.getCurrentContext(), "to_int");
} else {
args[i + 2] = args[i + 2].callMethod(
runtime.getCurrentContext(), "to_i");
}
}
int_args[i] = RubyNumeric.num2int(args[i + 2]);
}
}
// Validate the times
// Complying with MRI behavior makes it a little bit complicated. Logic copied from:
// https://github.com/ruby/ruby/blob/trunk/time.c#L2609
if ( (int_args[0] < 1 || int_args[0] > 31)
|| (int_args[1] < 0 || int_args[1] > 24)
|| (int_args[1] == 24 && (int_args[2] > 0 || int_args[3] > 0))
|| (int_args[2] < 0 || int_args[2] > 59)
|| (int_args[3] < 0 || int_args[3] > 60)) {
throw runtime.newArgumentError("argument out of range.");
}
DateTime dt;
// set up with min values and then add to allow rolling over
try {
dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
dt = dt.plusMonths(month - 1)
.plusDays(int_args[0] - 1)
.plusHours(int_args[1])
.plusMinutes(int_args[2])
.plusSeconds(int_args[3]);
// 1.9 will observe fractional seconds *if* not given usec
if (!args[5].isNil()
&& args[6].isNil()) {
double secs = RubyFloat.num2dbl(args[5]);
int int_millis = (int) (secs * 1000) % 1000;
dt = dt.plusMillis(int_millis);
nanos = ((long) (secs * 1000000000) % 1000000);
}
dt = dt.withZoneRetainFields(dtz);
// If we're at a DST boundary, we need to choose the correct side of the boundary
if (isDst) {
final DateTime beforeDstBoundary = dt.withEarlierOffsetAtOverlap();
final DateTime afterDstBoundary = dt.withLaterOffsetAtOverlap();
final int offsetBeforeBoundary = dtz.getOffset(beforeDstBoundary);
final int offsetAfterBoundary = dtz.getOffset(afterDstBoundary);
// If the time is during DST, we need to pick the time with the highest offset
dt = offsetBeforeBoundary > offsetAfterBoundary ? beforeDstBoundary : afterDstBoundary;
}
} catch (org.joda.time.IllegalFieldValueException e) {
throw runtime.newArgumentError("time out of range");
}
RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
// Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
if (args.length != 8 && !args[6].isNil()) {
boolean fractionalUSecGiven = args[6] instanceof RubyFloat || args[6] instanceof RubyRational;
if (fractionalUSecGiven) {
double micros = RubyNumeric.num2dbl(args[6]);
time.dt = dt.withMillis(dt.getMillis() + (long) (micros / 1000));
nanos = ((long) (micros * 1000) % 1000000);
} else {
int usec = int_args[4] % 1000;
int msec = int_args[4] / 1000;
if (int_args[4] < 0) {
msec -= 1;
usec += 1000;
}
time.dt = dt.withMillis(dt.getMillis() + msec);
time.setUSec(usec);
}
}
if (nanos != 0)
time.setNSec(nanos);
time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
time.setIsTzRelative(setTzRelative);
return time;
}
}
| [
"[email protected]"
] | |
4d7ea298a1d1b84a85d930e807cb0cfcd5d048c2 | 3c86b2a273abaf935683862f048f346f09d5bb0a | /app/src/main/java/com/example/mimalabo/MainActivity.java | 4560e2f1873e342da37199a2440af0087ae0d836 | [] | no_license | francisco50/Mimalabo | ab92055a2d9087285b6c7081ccac1f68715dd449 | 6c6c4925118cff9c9aa0eda1cddfdd5af7dc98a1 | refs/heads/master | 2023-03-21T20:14:32.306344 | 2020-12-08T05:58:52 | 2020-12-08T05:58:52 | 262,709,560 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,942 | java | package com.example.mimalabo;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity
{
private Button know;
private ImageView iconimage;
private LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
know = findViewById(R.id.know_malabo);
iconimage = findViewById(R.id.icon_image);
linearLayout = findViewById(R.id.linear_layout);
linearLayout.animate().alpha(0f).setDuration(100000);
TranslateAnimation animation = new TranslateAnimation(0,0,0,-1000);
animation.setDuration(1000);
animation.setFillAfter(false);
animation.setAnimationListener(new MyAnimationListener());
iconimage.setAnimation(animation);
}
private class MyAnimationListener implements Animation.AnimationListener {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
iconimage.clearAnimation();
iconimage.setVisibility(View.INVISIBLE);
linearLayout.animate().alpha(1f).setDuration(1000);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
public void KnowMalabo(View v)
{
Intent intent = new Intent(this,PlacesActivity.class);
startActivity(intent);
}
}
| [
"[email protected]"
] | |
0e0e4021323db257ab9c13cc3df4e32cca202296 | f49f57809f81d65bec18691b07ef36e1816a7352 | /src/main/java/com/masterdevskills/cha3/ext4/JdbcConnectionPool.java | e301407b719d207487f8f3450eca578ef71c1d29 | [] | no_license | MTcodeE/advancejava-exercise | 9698e25f9ba830461dacf74ae34b2c7255af3fa5 | dd7185ead23e67fc89811c1d144af20ce1e813e5 | refs/heads/master | 2022-12-08T14:56:48.261659 | 2020-08-31T16:49:30 | 2020-08-31T16:49:30 | 287,548,943 | 0 | 0 | null | 2020-08-14T14:14:40 | 2020-08-14T14:14:39 | null | UTF-8 | Java | false | false | 1,339 | java | package com.masterdevskills.cha3.ext4;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
//TODO
// Hints: use BlockingQueue
// Use delegate pattern, create a new ProxyConnection
public class JdbcConnectionPool {
private final JdbcConfig config;
private BlockingQueue<ProxyConnection> connections;
public JdbcConnectionPool(JdbcConfig config) {
this.config = config;
initializeConnectionPool();
}
//hints: initialize connection pool with min poolSize
private void initializeConnectionPool() {
connections = new LinkedBlockingQueue<>();
for (int i = 0; i < config.getMinPoolSize(); i++) {
connections.add(createConnection());
}
}
private ProxyConnection createConnection() {
try {
Connection connection = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
return new ProxyConnection(connection, this);
} catch (SQLException throwables) {
//throw new new Unche
}
return null;
}
public int getTotalConnection() {
return connections.size();
}
public Connection getConnectionFromPool() {
return connections.poll();
}
public void returnConnectionToPool(ProxyConnection connection) {
connections.add(connection);
}
}
| [
"[email protected]"
] | |
9fb48e11df58d9aa341e412cf2bef8bb49603ce1 | b958bb8d20cb8fcfebf3be6c1089c624093dd685 | /app/src/androidTest/java/com/rescreation/trematrik/ExampleInstrumentedTest.java | 414c6d4a717d08ccdd571d3fd15f625223f05569 | [] | no_license | sindhu-nir/Trematrik | 0ea677fb54e96f609cefb6657983d1bb5ecb74b5 | fe5333dd8bd1730cf592e911beb299b57a52a759 | refs/heads/master | 2022-04-15T22:32:27.499308 | 2020-04-17T15:06:06 | 2020-04-17T15:06:06 | 256,532,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 766 | java | package com.rescreation.trematrik;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.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.getInstrumentation().getTargetContext();
assertEquals("com.rescreation.trematrik", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
32d0bce418e0cf4ed9f31341f6d9a63b0431fbd2 | 286eb82451484edfb21154c128c97c43c68cfa9d | /src/main/java/com/hanj/blog/web/admin/UserController.java | 3dca98b8a1e6ab0b10d8a6214439e4a015af086a | [] | no_license | hanj123/blog | e59c74f8a939d182ff587817f1fff03d4d7cadf5 | 83b513395e11db0bfa8eac22d9ed61122bb1731c | refs/heads/master | 2020-08-30T07:18:51.392741 | 2019-10-29T14:25:51 | 2019-10-29T14:25:51 | 217,969,117 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,479 | java | package com.hanj.blog.web.admin;
import com.hanj.blog.po.User;
import com.hanj.blog.service.UserService;
import com.hanj.blog.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/admin")
@SessionAttributes("user")
public class UserController {
@Autowired
private UserService userService;
//不写路径,默认访问admin就会到这里
@GetMapping
public String login(){
return "admin/login";
}
@RequestMapping("/login")
public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password,Model model){
User user = userService.checkUser(username, password);
ModelAndView mv = new ModelAndView();
if(user!=null){
user.setPassword(null);
model.addAttribute("user",user);
mv.setViewName("admin/index");
return mv;
}else {
mv.addObject("message","用户名和密码错误");
mv.setViewName("admin/login.html");
return mv;
}
}
@GetMapping("/logout")
public String logout(HttpSession httpSession){
httpSession.invalidate();
return "admin/login";
}
}
| [
"[email protected]"
] | |
7baf465e1ba6012a559c2d533407c3c551889670 | 1a87a30cdc95d50136ff9d354c2aa8824ceb76bb | /src/main/java/com/nats/design/patterns/factory/Language.java | 9850a8bb39f6ff6d56d61c6a351575b758678d90 | [] | no_license | nataraja-maruthi/JavaCodies | a9df176b419c51f2c59a3996748ccce79765e3e5 | fb232d0dc01054fb4275466df9ba617083bd5607 | refs/heads/master | 2018-12-20T05:58:23.107274 | 2018-09-17T11:43:20 | 2018-09-17T11:43:20 | 102,103,048 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 87 | java | package com.nats.design.patterns.factory;
public enum Language {
KANNADA,
ENGLISH
}
| [
"[email protected]"
] | |
c92b24a22e255fb0d7629b40e2e9deae0a1fd692 | 7c6d378747e068c454e5c9d8cbf58180fa25f1aa | /mnis-oracle/src/com/his/mnis/entities/VwBqbrZy.java | 97a1b1de07c2077128d436df2ed902e34bd43f98 | [] | no_license | shawncn123/MNIS | 8410730af875b62f9ca1001dab7b4cd8f48fd682 | 4475858279a5afb9bce02ab88d73893e5e9349d4 | refs/heads/master | 2021-01-10T04:19:34.388882 | 2016-12-12T01:44:03 | 2016-12-12T01:44:03 | 51,803,482 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,805 | java | package com.his.mnis.entities;
/**
* VwBqbrZy entity. @author MyEclipse Persistence Tools
*/
public class VwBqbrZy implements java.io.Serializable {
// Fields
private String rowkey;
private Long key1;
private Integer key2;
private String bq;
private String chw;
private String bah;
private String xm;
private String xb;
private String nl;
private String ksid;
private String ksmc;
private String ysxm;
private String hsxm;
private String hldj;
private String fylb;
private String ryrq;
private String jcflag;
private String fylbBoxcolor;
private String dqbkzt;
private String ryzd;
private String gmls;
private String shanshi;
private String ssms;
private String yems;
private String zytsms;
private String aqtx;
// Constructors
/** default constructor */
public VwBqbrZy() {
}
/** minimal constructor */
public VwBqbrZy(Long key1, Integer key2) {
this.key1 = key1;
this.key2 = key2;
}
/** full constructor */
public VwBqbrZy(Long key1, Integer key2, String bq, String chw, String bah,
String xm, String xb, String nl, String ksid, String ksmc,
String ysxm, String hsxm, String hldj, String fylb, String ryrq,
String jcflag, String fylbBoxcolor, String dqbkzt, String ryzd,
String gmls, String shanshi, String ssms, String yems,
String zytsms, String aqtx) {
this.key1 = key1;
this.key2 = key2;
this.bq = bq;
this.chw = chw;
this.bah = bah;
this.xm = xm;
this.xb = xb;
this.nl = nl;
this.ksid = ksid;
this.ksmc = ksmc;
this.ysxm = ysxm;
this.hsxm = hsxm;
this.hldj = hldj;
this.fylb = fylb;
this.ryrq = ryrq;
this.jcflag = jcflag;
this.fylbBoxcolor = fylbBoxcolor;
this.dqbkzt = dqbkzt;
this.ryzd = ryzd;
this.gmls = gmls;
this.shanshi = shanshi;
this.ssms = ssms;
this.yems = yems;
this.zytsms = zytsms;
this.aqtx = aqtx;
}
// Property accessors
public String getRowkey() {
return this.rowkey;
}
public void setRowkey(String rowkey) {
this.rowkey = rowkey;
}
public Long getKey1() {
return this.key1;
}
public void setKey1(Long key1) {
this.key1 = key1;
}
public Integer getKey2() {
return this.key2;
}
public void setKey2(Integer key2) {
this.key2 = key2;
}
public String getBq() {
return this.bq;
}
public void setBq(String bq) {
this.bq = bq;
}
public String getChw() {
return this.chw;
}
public void setChw(String chw) {
this.chw = chw;
}
public String getBah() {
return this.bah;
}
public void setBah(String bah) {
this.bah = bah;
}
public String getXm() {
return this.xm;
}
public void setXm(String xm) {
this.xm = xm;
}
public String getXb() {
return this.xb;
}
public void setXb(String xb) {
this.xb = xb;
}
public String getNl() {
return this.nl;
}
public void setNl(String nl) {
this.nl = nl;
}
public String getKsid() {
return this.ksid;
}
public void setKsid(String ksid) {
this.ksid = ksid;
}
public String getKsmc() {
return this.ksmc;
}
public void setKsmc(String ksmc) {
this.ksmc = ksmc;
}
public String getYsxm() {
return this.ysxm;
}
public void setYsxm(String ysxm) {
this.ysxm = ysxm;
}
public String getHsxm() {
return this.hsxm;
}
public void setHsxm(String hsxm) {
this.hsxm = hsxm;
}
public String getHldj() {
return this.hldj;
}
public void setHldj(String hldj) {
this.hldj = hldj;
}
public String getFylb() {
return this.fylb;
}
public void setFylb(String fylb) {
this.fylb = fylb;
}
public String getRyrq() {
return this.ryrq;
}
public void setRyrq(String ryrq) {
this.ryrq = ryrq;
}
public String getJcflag() {
return this.jcflag;
}
public void setJcflag(String jcflag) {
this.jcflag = jcflag;
}
public String getFylbBoxcolor() {
return this.fylbBoxcolor;
}
public void setFylbBoxcolor(String fylbBoxcolor) {
this.fylbBoxcolor = fylbBoxcolor;
}
public String getDqbkzt() {
return this.dqbkzt;
}
public void setDqbkzt(String dqbkzt) {
this.dqbkzt = dqbkzt;
}
public String getRyzd() {
return this.ryzd;
}
public void setRyzd(String ryzd) {
this.ryzd = ryzd;
}
public String getGmls() {
return this.gmls;
}
public void setGmls(String gmls) {
this.gmls = gmls;
}
public String getShanshi() {
return this.shanshi;
}
public void setShanshi(String shanshi) {
this.shanshi = shanshi;
}
public String getSsms() {
return this.ssms;
}
public void setSsms(String ssms) {
this.ssms = ssms;
}
public String getYems() {
return this.yems;
}
public void setYems(String yems) {
this.yems = yems;
}
public String getZytsms() {
return this.zytsms;
}
public void setZytsms(String zytsms) {
this.zytsms = zytsms;
}
public String getAqtx() {
return this.aqtx;
}
public void setAqtx(String aqtx) {
this.aqtx = aqtx;
}
} | [
"[email protected]"
] | |
a437e038a9edcb35a7fab82e028eb2bce54ddb49 | c196d0e77c2c0926354a0892877c36dbce4311df | /pac4j-oauth/src/test/java/org/pac4j/oauth/profile/converter/JsonConverterTests.java | 226bf9ce77181a307cb19c7c730078bde4c2fb39 | [
"Apache-2.0"
] | permissive | odin1314/pac4j | ba2480d3bf89dda020d14f8cc885809de1eeedac | e37de32016aff9b344a56c07bd1520eca1a77f8d | refs/heads/master | 2020-12-24T17:26:50.201593 | 2016-02-16T18:36:33 | 2016-02-16T18:36:33 | 52,078,026 | 1 | 0 | null | 2016-02-19T09:47:52 | 2016-02-19T09:47:52 | null | UTF-8 | Java | false | false | 1,972 | java | /*
Copyright 2012 - 2015 pac4j organization
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.pac4j.oauth.profile.converter;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Test;
import org.pac4j.core.util.TestsConstants;
import org.pac4j.oauth.profile.JsonHelper;
import org.pac4j.oauth.profile.facebook.FacebookObject;
import static org.junit.Assert.*;
/**
* Tests the {@link JsonConverter}.
*
* @author Jerome Leleu
* @since 1.9.0
*/
public final class JsonConverterTests implements TestsConstants {
private final JsonConverter converter = new JsonConverter(FacebookObject.class);
private final static String JSON = "{ \"id\": \"x\", \"name\": \"y\" }";
@Test
public void testNull() {
assertNull(this.converter.convert(null));
}
@Test
public void testBadType() {
assertNull(this.converter.convert(1));
}
@Test
public void testString() {
final FacebookObject object = (FacebookObject) converter.convert(JSON);
assertNotNull(object);
assertEquals("x", object.getId());
assertEquals("y", object.getName());
}
@Test
public void testJsonNode() {
final JsonNode node = JsonHelper.getFirstNode(JSON);
final FacebookObject object = (FacebookObject) converter.convert(node);
assertNotNull(object);
assertEquals("x", object.getId());
assertEquals("y", object.getName());
}
}
| [
"[email protected]"
] | |
f17ccd3a9e1aaa893a6798a8e14ad4651172bda8 | 82428498091f5b253a789f9b4caad1d58fbf8e78 | /src/Homework/_AssessmentTest14CalorieBurnedCalculator.java | 3431ca161bb9f2b2511c61c4c6491ea4ad4abf17 | [] | no_license | Huri123/Spring2020B18_Java | c7136b967f4c45fe0b950ea744d457a6c5a1bdc2 | 424d3733cc9ecfd3bc288d96634e2b041a5cbdb8 | refs/heads/master | 2022-11-27T18:53:34.570757 | 2020-08-10T02:59:55 | 2020-08-10T02:59:55 | 286,362,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,771 | java | package Homework;
import java.util.Scanner;
/*
Instructions from your teacher:
One way to measure the amount of energy that is expended during exercise is to use metabolic equivalents (MET).
Here are some METS for various activities:
- Running 6 MPH: 10 METS
- Basketball: 8 METS
- Sleeping: 1 MET
METS are given per minute.
The number of calories burned per minute may be estimated using the following formula:
cal = 0.0175 * MET * Weight in kilograms
Write a program that asks user to enter his weight in pounds, and then calculates and outputs the total number of calories
burned for a person who runs 6 MPH for 30 minutes, plays basketball for 30 minutes, and then sleeps for 6 hours.
One kilogram is equal to 2.2 pounds.
use (int)cal to round a double value.
Example:
output: Enter weight in pounds:
input: 150
output: Calories Burned: 1073
*/
public class _AssessmentTest14CalorieBurnedCalculator {
public static void main(String[] args) {
double weight = 0;
double cal = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter weight in pounds:");
weight=scan.nextDouble();
double run=30*10;
double basket=30*8;
double sleep=360;
double weight2=weight/2.2;
double MET=run+basket+sleep;
double burnedCal = 0.0175 * MET * weight2;
System.out.println("Calories Burned: "+(int)burnedCal);
/*
Assessment test #2. 1- Print odd numbers
Instructions from your teacher:
Write a for loop that prints the odd integers 11 through 121 inclusive, separated by spaces.
*/
for (int i=11;i<=121;i++){
if(i%2!=0){
System.out.println(i+" ");
}
}
}
}
| [
"[email protected]"
] | |
8b60aea04b074a35564221fbc9d89033586bdcb9 | 27267c6198b7e4149b741c55e26a5d990ed40c24 | /TestDiseases.java | 5b05423254aadd7b1a40346766fc871acfebe34f | [] | no_license | rounakbonbon/digi-doc | fa6b275af19b4a38657824b712787ecc534495ad | ec32d2a767539a70441f50de449b0a1bd6c1f448 | refs/heads/master | 2022-12-14T10:49:08.869235 | 2020-09-10T01:21:15 | 2020-09-10T01:21:15 | 294,268,632 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,975 | java | class TestDiseases
{
static void setValues(String diseaseNames[], int diseaseScore [])
{
//////////////////////////////////////////SETTING NAME VALUES//////////////////////////////////////////
diseaseNames[0]="Hypertension";
diseaseNames[1]="Diabetes";
diseaseNames[2]="Hypothyroidism";
diseaseNames[3]="Lethargy";
diseaseNames[4]="Hyperthyroidism";
diseaseNames[5]="Diarrhoea";
diseaseNames[6]="Tuberculosis";
diseaseNames[7]="Chronic Bowel Disease";
diseaseNames[8]="HIV";
diseaseNames[9]="Cerebro-Vascular Accident";
diseaseNames[10]="Coronary Heart Disease";
diseaseNames[11]="Renal Disease";
diseaseNames[12]="Dehydration";
diseaseNames[13]="Syncope";
diseaseNames[14]="Haemorrhage";
diseaseNames[15]="Shock";
diseaseNames[16]="Malaria";
diseaseNames[17]="Dengue";
diseaseNames[18]="Typhoid";
diseaseNames[19]="Meningitis";
diseaseNames[20]="Flu";
diseaseNames[21]="Pneumonia";
diseaseNames[22]="Hypothermia";
diseaseNames[23]="Epilepsy";
diseaseNames[24]="Asthma";
diseaseNames[25]="Anaemia";
diseaseNames[26]="Urinary Tract Infection";
diseaseNames[27]="Hepatitis";
diseaseNames[28]="Leukaemia";
diseaseNames[29]="Cancer";
diseaseNames[30]="Gall Bladder Stone";
diseaseNames[31]="Liver Cirrhosis";
diseaseNames[32]="Kwashiorkor";
diseaseNames[33]="Marasmus";
diseaseNames[34]="Alcoholism";
///////////////////////////////////////SETTING INITIAL SCORES////////////////////////////////////////////
for(int i=0; i<35;i++)
diseaseScore[i]=0;
/////////////////////////////////////////////////////////////////////////////////////////////////////////
}
} | [
"[email protected]"
] | |
139a53d631466824f5413643726a772375bdcd65 | 32de09768dc9eef8ea2588596d8fcc91eb718e3a | /src/main/java/com/hcl/RetailApplication/Service/ProductService.java | 4ed62f732e9397fd31de966132ce5c0add011a85 | [] | no_license | sai555977charan/RetailApplication | 392a66b7bf72e43c6e6a1290877b130e6cf9b540 | d2a574cfa930d5f48ab7efc95e759352f11f200d | refs/heads/master | 2020-06-28T10:16:18.289976 | 2019-08-05T07:11:11 | 2019-08-05T07:11:11 | 200,207,739 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 536 | java | package com.hcl.RetailApplication.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hcl.RetailApplication.Entity.ProductDisplay;
import com.hcl.RetailApplication.Repository.ProductDisplayRepository;
@Service
public class ProductService {
@Autowired
ProductDisplayRepository productDisplayRepository;
public List<ProductDisplay> getall(int categoryId){
return productDisplayRepository.findByCategoryId(categoryId);
}
}
| [
"[email protected]"
] | |
ec9faa4818455f44360e983d8f572dbff92412b3 | ed5984e23302dc1f8d2742d3d9239d985a19841c | /gae/Lima1Sync/src-amber/oauth2-common/src/main/java/org/apache/amber/oauth2/common/error/OAuthError.java | 19c95e61ce5edf16ce83a74221068e39915c0846 | [] | no_license | jie-pan/Lima1 | 4e56f635650ea9163ccd5f350dcd17209febeccc | 2a34530dfb52245346c94e36cb0c6fb91a9a60a3 | refs/heads/master | 2020-05-07T05:45:17.406442 | 2014-03-18T13:29:41 | 2014-03-18T13:29:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,797 | java | /**
* Copyright 2010 Newcastle University
*
* http://research.ncl.ac.uk/smart/
*
* 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.amber.oauth2.common.error;
/**
* @author Maciej Machulak ([email protected])
* @author Lukasz Moren ([email protected])
* @author Aad van Moorsel ([email protected])
*/
public abstract class OAuthError {
//error response params
public static final String OAUTH_ERROR = "error";
public static final String OAUTH_ERROR_DESCRIPTION = "error_description";
public static final String OAUTH_ERROR_URI = "error_uri";
public static final class CodeResponse {
public static final String INVALID_REQUEST = "invalid_request";
public static final String INVALID_CLIENT = "invalid_client";
public static final String UNAUTHORIZED_CLIENT = "unauthorized_client";
public static final String REDIRECT_URI_MISMATCH = "redirect_uri_mismatch";
public static final String ACCESS_DENIED = "access_denied";
public static final String UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
public static final String INVALID_SCOPE = "invalid_scope";
}
public static final class TokenResponse {
public static final String INVALID_REQUEST = "invalid_request";
public static final String INVALID_CLIENT = "invalid_client";
public static final String UNAUTHORIZED_CLIENT = "unauthorized_client";
public static final String INVALID_GRANT = "invalid_grant";
public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
public static final String INVALID_SCOPE = "invalid_scope";
}
public static final class ResourceResponse {
public static final String INVALID_REQUEST = "invalid_request";
public static final String EXPIRED_TOKEN = "expired_token";
public static final String INSUFFICIENT_SCOPE = "insufficient_scope";
public static final String INVALID_TOKEN = "invalid_token";
}
}
| [
"[email protected]"
] | |
e70fa6eaf81cd2e1cbd52baf7c923ed87de00dcb | 73cad2d5c46e6260f5bbe6bfe1a5de3c9ff1685a | /src/test/java/com/automaton/cell/ElementaryNeighbourhoodTest.java | bddc9ad64878a72b30808f67ea8a87d3b261f524 | [] | no_license | OatmealLick/cellular-automata | 878a22273a3581ffa1ee6c1b2d6085b95da9190c | 62e803642fd16dddb093d51af4c8b8813738274e | refs/heads/master | 2020-01-23T21:45:51.120346 | 2016-12-13T12:48:31 | 2016-12-13T12:48:31 | 74,681,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,941 | java | package com.automaton.cell;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Created by lick on 11/25/16.
*/
public class ElementaryNeighbourhoodTest {
@Test
public void neighboursNumberWithNeighbourhoodWidth3() {
CellNeighbourhood neighbourhood = new ElementaryNeighbourhood(3);
Set<CellCoordinates> generatedNeighboursOfCell2 = neighbourhood.cellNeighbours(new Coords1D(2));
Set<CellCoordinates> generatedNeighboursOfCell0 = neighbourhood.cellNeighbours(new Coords1D(0));
Set<CellCoordinates> generatedNeighboursOfCell1 = neighbourhood.cellNeighbours(new Coords1D(1));
Set<CellCoordinates> correctSetOfNeighboursForCell2 = new LinkedHashSet<>(Arrays.asList(
new Coords1D(1),
new Coords1D(2)
));
Set<CellCoordinates> correctSetOfNeighboursForCell0 = new LinkedHashSet<>(Arrays.asList(
new Coords1D(0),
new Coords1D(1)
));
Set<CellCoordinates> correctSetOfNeighboursForCell1 = new LinkedHashSet<>(Arrays.asList(
new Coords1D(0),
new Coords1D(1),
new Coords1D(2)
));
Assert.assertEquals("neighbours width: 3, checking number and order of neighbours generated for cell 0",
generatedNeighboursOfCell0, correctSetOfNeighboursForCell0);
Assert.assertEquals("neighbours width: 3, checking number and order of neighbours generated for cell 1",
generatedNeighboursOfCell1, correctSetOfNeighboursForCell1);
Assert.assertEquals("neighbours width: 3, checking number and order of neighbours generated for cell 2",
generatedNeighboursOfCell2, correctSetOfNeighboursForCell2);
}
@Test
public void neighboursNumberWithNeighbourhoodWidth5() {
CellNeighbourhood neighbourhood = new ElementaryNeighbourhood(5);
Set<CellCoordinates> generatedNeighboursOfCell3 = neighbourhood.cellNeighbours(new Coords1D(3));
Set<CellCoordinates> generatedNeighboursOfCell0 = neighbourhood.cellNeighbours(new Coords1D(0));
Set<CellCoordinates> generatedNeighboursOfCell4 = neighbourhood.cellNeighbours(new Coords1D(4));
Set<CellCoordinates> generatedNeighboursOfCell1 = neighbourhood.cellNeighbours(new Coords1D(1));
Set<CellCoordinates> correctSetOfNeighboursForCell3 = new LinkedHashSet<>(Arrays.asList(
new Coords1D(2),
new Coords1D(3),
new Coords1D(4)
));
Set<CellCoordinates> correctSetOfNeighboursForCell0 = new LinkedHashSet<>(Arrays.asList(
new Coords1D(0),
new Coords1D(1)
));
Set<CellCoordinates> correctSetOfNeighboursForCell4 = new LinkedHashSet<>(Arrays.asList(
new Coords1D(3),
new Coords1D(4)
));
Set<CellCoordinates> correctSetOfNeighboursForCell1 = new LinkedHashSet<>(Arrays.asList(
new Coords1D(0),
new Coords1D(1),
new Coords1D(2)
));
Assert.assertEquals("neighbours width: 5, checking number and order of neighbours generated for cell 3",
generatedNeighboursOfCell3, correctSetOfNeighboursForCell3);
Assert.assertEquals("neighbours width: 5, checking number and order of neighbours generated for cell 4",
generatedNeighboursOfCell4, correctSetOfNeighboursForCell4);
Assert.assertEquals("neighbours width: 5, checking number and order of neighbours generated for cell 0",
generatedNeighboursOfCell0, correctSetOfNeighboursForCell0);
Assert.assertEquals("neighbours width: 5, checking number and order of neighbours generated for cell 1",
generatedNeighboursOfCell1, correctSetOfNeighboursForCell1);
}
}
| [
"[email protected]"
] | |
1aa33d5c62334c750cf6592316fee87017731822 | e8bf550d5d220232e47fe710bc923c0c7de590f0 | /Assignment3/src/a3/Printer.java | 82b81057a575bf0fbc20496a7ed393da07a65cff | [] | no_license | nmjsbl/CSCB07 | debd98cce89214732ce8c509c1d613b3ac4e3ecd | c635b31e8ca011a248bfb52f1607da5726ffb266 | refs/heads/master | 2020-05-05T06:26:47.579169 | 2019-04-06T04:31:19 | 2019-04-06T04:31:19 | 179,787,152 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,943 | java | // **********************************************************
// Assignment0:
// UTORID: sibalnao
// UT Student #: 1003939786
// Author: Naomi Joy Sibal
//
//
// Honor Code: I pledge that this program represents my own
// program code and that I have coded on my own. I received
// help from no one in designing and debugging my program.
// I have also read the plagiarism section in the course info
// sheet of CSC B07 and understand the consequences. In this semester
// we will select any three of your assignments from total of 5 and run it
// for plagiarism check.
// *********************************************************
package a3;
import java.util.ArrayList;
/**
* Represents a printer which prints the user user matrix and the pair of
* users with their corresponding similarity and dissimilarity scores.
*
*/
public class Printer {
/**
* Constructor.
*/
public Printer() {
}
/**
* Prints the pair of users with their corresponding
* similarity and dissimilarity scores.
*
* @param finder is the Finder object
*/
public void printPairOfUsers(Finder finder) {
String line1 = "";
String line3 = "";
String result = "";
ArrayList<String> listOfUsers = finder.getUserPairs();
if(finder instanceof SimilarFinder) {
line1 += "\n\nThe most similar pairs of users"
+ " from above userUserMatrix are:\n";
line3 += "with similarity score of " + String.format("%.4f", finder.getScore());
} else {
line1 += "\n\nThe most dissimilar pairs of users"
+ " from above userUserMatrix are:\n";
line3 += "with dissimilarity score of " + String.format("%.4f", finder.getScore());
}
result = line1 + printUsers(listOfUsers) + line3;
System.out.println(result);
}
/**
* A helper function the prints the pair of users.
*
* @param listOfUsers is the list of users
* @return the string representation of the user pairs
*/
private String printUsers(ArrayList<String> listOfUsers){
String result = "";
// printing the most dis/similar users
for(int i = 0; i < listOfUsers.size(); i++) {
// get all the user number in the dissimilarUser array
String allUsers[] = listOfUsers.get(i).split(" ");
result += "User" + allUsers[0] + " and User" + allUsers[1];
// check if it's the last user pair to avoid printing extra comma
if(i != listOfUsers.size()-1)
result += ",\n";
else
result += "\n";
}
return result;
}
/**
* Prints the UserUserMatrix
*
* @param userUserMatrix is instance of the UserUserMatrix
*/
public void printerMatrix(UserUserMatrix userUserMatrix) {
// prints an extra line for formatting
System.out.println("\n");
// iterate through the userUserMatrix
for(Object output: userUserMatrix) {
System.out.print(output);
}
}
}
| [
"[email protected]"
] | |
134331cfa1e9bebd19a483a9e6c469b11dd15833 | f7e3cd8455a5b6722ec18fa1158951802f57f642 | /program-logic/program-logic-master/src/shuo/laoma/concurrent/c65/VisibilityDemo.java | 10e4742be6912de606d62ec86e5f11d9accdff7a | [] | no_license | oneflyingsun/MyBooks | 75a413aca309ebc6c5caeb37c7f8795ccd6694f5 | 77f583528f52d1e525b554835d734c18e976115d | refs/heads/master | 2020-03-25T13:12:31.848520 | 2018-09-03T01:13:55 | 2018-09-03T01:13:55 | 143,813,343 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 554 | java | package shuo.laoma.concurrent.c65;
public class VisibilityDemo {
private static boolean shutdown = false;
static class HelloThread extends Thread {
@Override
public void run() {
while(!shutdown){
// do nothing
}
System.out.println("exit hello");
}
}
public static void main(String[] args) throws InterruptedException {
new HelloThread().start();
Thread.sleep(1000);
shutdown = true;
System.out.println("exit main");
}
} | [
"[email protected]"
] | |
abb784dba8708a4e777ff378d2d186c74c7eda3c | 71dc527e1e70e9376973968c2f6f732ef1d77cdf | /backend/src/main/java/com/michaelmartins/dsdelivery/repository/ProductRepository.java | 6d41d680059f4e4b343053ed6cbe94bd0ae0c376 | [
"MIT"
] | permissive | DenisonMartins/dsdelivery | a71a95a1038daa94947daeed12f96fa6c3f709c5 | 301662e19b660c351bf61c5ccd36afede48cc712 | refs/heads/main | 2023-02-11T05:14:09.463019 | 2021-01-12T15:38:34 | 2021-01-12T15:38:34 | 326,775,719 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 313 | java | package com.michaelmartins.dsdelivery.repository;
import com.michaelmartins.dsdelivery.domain.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findAllByOrderByNameAsc();
}
| [
"[email protected]"
] | |
ebe882899691a1c91e4c566f56ee3b876912edbf | 29f3758354b9528fd27e407e6ee168a4d8680845 | /src/main/java/com/jpm/iris/service/adapter/LocalDateTimeAdapter.java | 77f53ca2ef4f8a2d0ea8bad63eccc077686bbc01 | [] | no_license | jitendrasagoriya/iris-batch | ad242cf4748a5a1dc74982660157acefb54bf636 | 2d7efbf91afea8c8c1ed48313dd52f3a1acae751 | refs/heads/master | 2022-12-20T18:43:30.375425 | 2020-09-25T10:21:52 | 2020-09-25T10:21:52 | 293,699,222 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 622 | java | package com.jpm.iris.service.adapter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.xml.sax.helpers.XMLReaderAdapter;
public class LocalDateTimeAdapter {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT);
public LocalDateTime unmarshal(String v) throws Exception {
return LocalDateTime.parse(v, DATE_TIME_FORMATTER);
}
public String marshal(LocalDateTime v) throws Exception {
return DATE_TIME_FORMATTER.format(v);
}
} | [
"[email protected]"
] | |
e14e230fed6826ed7a8cf04f9b3bfbd51c215af1 | 47a39c7e8e5edb44c29398dd5ab3f4dbd37ca3aa | /cube-android/src/android/support/v4/app/ActivityCompat.java | e3a3e5418043c9e40bddc0a38f5cb97dfb0a4192 | [] | no_license | Lucaziki/bsl_impc_android | 02840689dd5beb8e3c426a952b22870923380351 | ed94bc13cf04a642a31378109b722c2b8cb89929 | refs/heads/master | 2021-01-17T22:46:41.999425 | 2014-03-05T01:26:37 | 2014-03-05T01:26:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,322 | java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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 android.support.v4.app;
import android.app.Activity;
import android.os.Build;
import android.support.v4.content.ContextCompat;
/**
* Helper for accessing features in {@link android.app.Activity}
* introduced after API level 4 in a backwards compatible fashion.
*/
public class ActivityCompat extends ContextCompat {
/**
* Invalidate the activity's options menu, if able.
*
* <p>Before API level 11 (Android 3.0/Honeycomb) the lifecycle of the
* options menu was controlled primarily by the user's operation of
* the hardware menu key. When the user presses down on the menu key
* for the first time the menu was created and prepared by calls
* to {@link Activity#onCreateOptionsMenu(android.view.Menu)} and
* {@link Activity#onPrepareOptionsMenu(android.view.Menu)} respectively.
* Subsequent presses of the menu key kept the existing instance of the
* Menu itself and called {@link Activity#onPrepareOptionsMenu(android.view.Menu)}
* to give the activity an opportunity to contextually alter the menu
* before the menu panel was shown.</p>
*
* <p>In Android 3.0+ the Action Bar forces the options menu to be built early
* so that items chosen to show as actions may be displayed when the activity
* first becomes visible. The Activity method invalidateOptionsMenu forces
* the entire menu to be destroyed and recreated from
* {@link Activity#onCreateOptionsMenu(android.view.Menu)}, offering a similar
* though heavier-weight opportunity to change the menu's contents. Normally
* this functionality is used to support a changing configuration of Fragments.</p>
*
* <p>Applications may use this support helper to signal a significant change in
* activity state that should cause the options menu to be rebuilt. If the app
* is running on an older platform version that does not support menu invalidation
* the app will still receive {@link Activity#onPrepareOptionsMenu(android.view.Menu)}
* the next time the user presses the menu key and this method will return false.
* If this method returns true the options menu was successfully invalidated.</p>
*
* @param activity Invalidate the options menu of this activity
* @return true if this operation was supported and it completed; false if it was not available.
*/
public static boolean invalidateOptionsMenu(Activity activity) {
if (Build.VERSION.SDK_INT >= 11) {
ActivityCompatHoneycomb.invalidateOptionsMenu(activity);
return true;
}
return false;
}
}
| [
"[email protected]"
] | |
8505f881b6d221fcf7d9f3b292a2ca5a67fe81aa | 01e7076c3f4435fbf623196a07ba2ffae2652255 | /src/ec/edu/ups/DAO/AgendaCitaMedicaDAO.java | 29fff15df14eb6fe2fc110fa888cfd2f9c6dc32d | [] | no_license | Juancarlos56/ProyectoIngSoftware-CitasMedicas | eee959ebc9e07148b6a66ab76e4f660fa9a66d53 | 2f7df6e752879d40f4de332c71c020c77e2972e7 | refs/heads/master | 2023-02-27T07:13:56.973966 | 2021-02-05T07:20:48 | 2021-02-05T07:20:48 | 336,152,362 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 159 | java | package ec.edu.ups.DAO;
import ec.edu.ups.entidades.AgendaCitaMedica;
public interface AgendaCitaMedicaDAO extends GenericDAO<AgendaCitaMedica, Integer>{
}
| [
"[email protected]"
] | |
66b077f09aaf198bfdf2e94ae28ac9c6deb2be21 | 949d4a8b88375b2a72c4e339afdf9f9a54f157d6 | /v2/musicGenerator/src/main/java/com/john-bernier/musicGenerator/voiceLeadingProfile.java | e273fe6aa5140b9202023eae3d33566a8fa62986 | [] | no_license | jbernie2/musicGenerator | ffe840fe751948055223d57b01e7e3a9db16d9e9 | 4142701f29ee79508505f4e4bab9a790f0f100c0 | refs/heads/master | 2021-03-12T19:35:47.180679 | 2013-03-20T05:49:25 | 2013-03-20T05:49:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,684 | java | /*
*Author: John Bernier 2/13
*voiceLeadingProfile.java:
* A customized set of voiceLeading rules, I will hardcode them for now,
* but in the future the user will be able to pass in the rules they want to use
* most likely through some sort of graphical interface or config file
*/
package com.john.bernier.musicGenerator;
class voiceLeadingProfile extends voiceLeadingPrimitives{
chordProgression progression;
voiceLeadingProfile(chordProgression progression, note[][] harmonization, voicingConstants voices){
super(progression.chords, harmonization, voices);
this.progression = progression;
}
boolean checkNote(note currentNote, int voice, int position){
boolean[] rules = new boolean[9];
int[] emptyArray = new int[0];
//forbids leaps of sevenths
rules[0] = forbidden(new int[]{10,11}, new int[]{10,11},new int[] {0},
currentNote,voice,position);
//forbids parallel fifths
rules[1] = parallel(new int[]{7},2,currentNote,voice,position);
//forbids parallel octaves
rules[2] = parallel(new int[]{12},2,currentNote,voice,position);
//allows for leaps of fifths, sixths, and octaves, if followed by
//opposite motion by a second or third
rules[3] = leap(new int[] {7,8,9,12}, new int[]{7,8,9,12},emptyArray,
new int[] {1,2,3,4},new int[] {1,2,3,4}, emptyArray,
currentNote,voice,position);
//restricts largest leap to an octave
rules[4] = maxLeap(12,currentNote,voice,position);
//disallow voice crossing
rules[5] = !voiceCrossing(currentNote,voice,position);
//disallow fifths as the root note on triads
if(checkChordType(position,new String[] {"triad"})){
if(voice == 0 && checkInterval(currentNote, new int[] {7})){
rules[6] = false;
}
else{
rules[6] = true;
}
}
else{
rules[6] = true;
}
//require triads to have root and fifth
if(checkChordType(position,new String[] {"triad"})){
rules[7] = requiredNotes(new int[][] {{0},{3,4}}, currentNote, position);
}else if(checkChordType(position,new String[] {"seventhChord"})){
rules[7] = requiredNotes(new int[][] {{0},{3,4},{10,11}}, currentNote, position);
}
else{
rules[7] = true;
}
//leading tone resolution
rules[8] = noteResolution(new int[]{11},new int[]{1,2}, new int[]{1,2},
currentNote, position, voice);
return allTrue(rules);
}
//checks if the note provided is one of the specified intervals
//this allows for rules like: dont use fifths in root notes
boolean checkInterval(note currentNote, int[] intervals){
for(int i = 0; i < intervals.length; i++){
if(intervals[i] == currentNote.interval){
return true;
}
}
return false;
}
//checks if a note is of a certain scale degree
boolean checkSetClass(note currentNote, int[] setClasses){
for(int i = 0; i < setClasses.length; i++){
if(setClasses[i] == currentNote.setClass){
return true;
}
}
return false;
}
//checks if a chord is of a certain type ie. triad or seventh chord
boolean checkChordType(int position, String[] types)
{
for(int i = 0; i < types.length; i++){
if(chords[position].getType().equals(types[i])){
return true;
}
}
return false;
}
//checks a chords name against a list
//allows for rules like: if V chord do _______
boolean checkChordName(int position, String[] names){
for(int i = 0; i < names.length; i++){
if(chords[position].getName().equals(names[i])){
return true;
}
}
return false;
}
//checks if the inputted note satified all the constraints
boolean allTrue(boolean[] rules){
for(int i = 0; i < rules.length; i++){
if(!rules[i]){
return false;
}
}
return true;
}
}
| [
"[email protected]"
] | |
1c77b45c94779299d77f9de385aa9d3976de0309 | 7d922679835e8b621764e569d90b0759bdf9a11d | /app/src/main/java/app/nahehuo/com/ui/fragment/EventFragment.java | 32230c5b1b9716e5863e860be6052376df03a7af | [] | no_license | wyb20151010/Nahehuo | f4fe334cb276432bdeadd5a20b859ed8615528a4 | cf99489b67425637d61facdb6876fabfae19e286 | refs/heads/master | 2021-01-09T21:51:28.462778 | 2016-03-21T12:02:45 | 2016-03-21T12:02:45 | 53,285,388 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,471 | java | package app.nahehuo.com.ui.fragment;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import app.nahehuo.com.R;
import app.nahehuo.com.adapter.EventListAdapter;
import app.nahehuo.com.base.GlobalVariables;
import app.nahehuo.com.bean.EventListDict;
import app.nahehuo.com.bean.NetEventList;
import app.nahehuo.com.network.GsonCallBack;
import app.nahehuo.com.ui.MainActivity;
import app.nahehuo.com.ui.event.EventDetailActivity;
import app.nahehuo.com.ui.event.EventPubActivity;
import app.nahehuo.com.ui.event.EventSearchActivity;
import app.nahehuo.com.util.MyToast;
import app.nahehuo.com.util.VeDate;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhy.http.okhttp.OkHttpUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by WYB on 2015/12/24.
*/
public class EventFragment extends Fragment implements View.OnClickListener,
PullToRefreshBase.OnRefreshListener {
private Context mContext;
private MainActivity mainActivity;
private RelativeLayout rl_event_recom, rl_event_time, rl_event_distance;
private TextView tv_event_recom, tv_event_time, tv_event_distance;
private TextView temp;
private LinearLayout ll_cursor;
private int width;
private PullToRefreshListView plv_event_list;
private EventListAdapter mEventListAdapter;
private List<EventListDict> mListDicts = new ArrayList<>();
private final static int FIND_EVENT_LIST = 0;
private int pageindex;
//推荐 0 不推荐,1推荐默认 1
private int recommend=1;
private long time;
private String distance;
private Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case FIND_EVENT_LIST:
findEventList();
break;
}
super.handleMessage(msg);
}
};
private void findEventList() {
plv_event_list.onRefreshComplete();
if(pageindex==1){
mListDicts.clear();
}
OkHttpUtils.get()
.url(GlobalVariables.EVENT_LIST)
.addParams("access_token", GlobalVariables.access_token)
.addParams("device", GlobalVariables.device)
.addParams("recommend", recommend + "")
.addParams("time", time + "")
/* .addParams("distance", distance)*/
.addParams("pageindex", pageindex + "")
.addParams("pagesize", GlobalVariables.pagesize)
.build()
.execute(new GsonCallBack<NetEventList>(NetEventList.class) {
@Override public void onResponse(NetEventList response) {
if (response.getCode() == 200) {
for (int i = 0;
i < response.getData().size();
i++) {
EventListDict event = new EventListDict();
event.setIv_per_avater(response.getData()
.get(i)
.getAvatar());
event.setTv_event_title(response.getData()
.get(i)
.getTitle());
event.setTv_per_name(response.getData()
.get(i)
.getUsername());
StringBuffer sb = new StringBuffer();
sb.append(
response.getData().get(i).getJob());
sb.append("-");
sb.append(response.getData()
.get(i)
.getCompany());
event.setTv_per_pos(sb.toString());
StringBuffer sb1 = new StringBuffer();
sb1.append(VeDate.formatEventTime(
response.getData()
.get(i)
.getStarted()));
sb1.append(" 至 ");
sb1.append(VeDate.formatEventTime(
response.getData()
.get(i)
.getEnded()));
event.setTv_event_time(sb1.toString());
event.setTv_event_number(response.getData()
.get(i)
.getEventnum() +
"");
event.setType(response.getData()
.get(i)
.getEventprice());
event.setEvent_price(response.getData()
.get(i)
.getPrice());
StringBuffer buffer = new StringBuffer();
buffer.append(
response.getData().get(i).getProv());
buffer.append(
response.getData().get(i).getCity());
buffer.append(response.getData()
.get(i)
.getAddress());
event.setTv_event_location(
buffer.toString());
event.setTv_event_watch_num(
response.getData()
.get(i)
.getViewnum() + "");
event.setTv_event_com_num(response.getData()
.get(i)
.getComnum() +
"");
event.setTv_event_per_num(response.getData()
.get(i)
.getFollownum() +
"");
mListDicts.add(event);
}
mEventListAdapter.notifyDataSetChanged();
}
else {
MyToast.showToast(mContext,
response.getMessage());
}
super.onResponse(response);
}
});
}
@Override public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof MainActivity) {
mainActivity = (MainActivity) activity;
}
else {
throw new IllegalArgumentException(
"The activity must be a MainActivity !");
}
}
@Nullable @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_event, null);
mContext = getActivity();
pageindex = 1;
temp = new TextView(mContext);
ll_cursor = (LinearLayout) v.findViewById(R.id.ll_cursor);
WindowManager wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
width = wm.getDefaultDisplay().getWidth();
initView(v);
initFLv(v);
mHandler.sendEmptyMessage(FIND_EVENT_LIST);
return v;
}
private void initFLv(View v) {
mEventListAdapter = new EventListAdapter(mListDicts, mContext);
plv_event_list = (PullToRefreshListView) v.findViewById(
R.id.plv_event_list);
plv_event_list.setMode(PullToRefreshBase.Mode.BOTH);
plv_event_list.setAdapter(mEventListAdapter);
plv_event_list.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(mContext,
EventDetailActivity.class));
mainActivity.overridePendingTransition(
R.anim.push_left_in, R.anim.push_left_out);
}
});
plv_event_list.setOnRefreshListener(this);
}
private void initView(View v) {
rl_event_recom = (RelativeLayout) v.findViewById(R.id.rl_event_recom);
rl_event_recom.setOnClickListener(this);
rl_event_time = (RelativeLayout) v.findViewById(R.id.rl_event_time);
rl_event_time.setOnClickListener(this);
rl_event_distance = (RelativeLayout) v.findViewById(
R.id.rl_event_distance);
rl_event_distance.setOnClickListener(this);
tv_event_recom = (TextView) v.findViewById(R.id.tv_event_recom);
tv_event_time = (TextView) v.findViewById(R.id.tv_event_time);
tv_event_distance = (TextView) v.findViewById(R.id.tv_event_distance);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.start_event:
startActivity(new Intent(mContext, EventPubActivity.class));
mainActivity.overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
break;
case R.id.search_event:
startActivity(new Intent(mContext, EventSearchActivity.class));
mainActivity.overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
break;
case R.id.my_event:
break;
}
return super.onOptionsItemSelected(item);
}
@Override public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_event_recom:
fromStateTo(temp, tv_event_recom, 0);
break;
case R.id.rl_event_time:
fromStateTo(temp, tv_event_time, width / 3);
break;
case R.id.rl_event_distance:
fromStateTo(temp, tv_event_distance, width * 2 / 3);
break;
}
}
private void fromStateTo(TextView from, TextView to, int i) {
TextView tv_to = (TextView) to;
if (temp != tv_to) {
temp = tv_to;
from.setTextColor(getResources().getColor(R.color.textcolorgray));
tv_to.setTextColor(getResources().getColor(R.color.colorPrimary));
startAnim(i);
}
}
private void startAnim(int i) {
ObjectAnimator animator = ObjectAnimator.ofFloat(ll_cursor,
"translationX", i);
animator.setDuration(300);
animator.start();
}
@Override public void onRefresh(PullToRefreshBase refreshView) {
if(refreshView.isHeaderShown()){
pageindex=1;
mListDicts.clear();
mHandler.sendEmptyMessage(FIND_EVENT_LIST);
}else if(refreshView.isFooterShown()){
pageindex++;
mHandler.sendEmptyMessage(FIND_EVENT_LIST);
}
}
}
| [
"[email protected]"
] | |
c28334f2bc73ab44cc9da1b38fc796fb8daa4964 | b3f6f9e0f0bd686bebb818a54be06670f715eda4 | /src/main/java/JAVA_ADVANCED/LESSON_1/Main.java | ca9928c8f2ccab03bff35154ab037c101f2b0d0c | [] | no_license | grenaderplus/GEEK_JAVA_LESSONS | 5396dace9455c1450aa24bd39e223fca78d6958a | 6b7203bef5532296e508b6a616e8bae09c4310b7 | refs/heads/master | 2022-12-24T21:28:08.069910 | 2020-10-12T12:27:13 | 2020-10-12T12:27:13 | 295,972,029 | 0 | 0 | null | 2020-10-12T12:27:14 | 2020-09-16T08:31:00 | Java | UTF-8 | Java | false | false | 994 | java | package JAVA_ADVANCED.LESSON_1;
import java.io.Serializable;
public class Main {
public static void main(String[] args) {
// JumpAble[] jumpAbles = {
// new Cat(),
// new Kangoo(),
// new Cat()
// };
//
// for (JumpAble j : jumpAbles) {
// j.jump();
// }
// testJump(new Cat());
// Cat cat = new Cat();
// cat.run(6);
// JumpAble catj = new Cat();
// catj.jump();
// ((Cat) catj).run();
Cat cat = new Cat();
// cat.run(5);
//
// System.out.println(cat instanceof JumpAble);
//
// testJump(()->{
// System.out.println("somebody jump...");
// });
//
// testRun((n)->{
// System.out.println("run "+n+" meter");
// });
// testRun(cat);
cat.superJump(3,5);
}
static void testJump(JumpAble j) {
j.jump();
}
static void testRun(RunAble r) {
r.run();
r.run(5);
}
}
| [
"[email protected]"
] | |
3f4a8872b8695fc078ece62c43a14e2b13173e3f | 52c8a17d5f2e16157749eb45d081bd90de3585c6 | /app/src/androidTest/java/com/github/uiautomator/stub/DeviceInfo.java | 13b07c3e02e831b0b0e130e52e4f7a3c64ef18d7 | [
"MIT"
] | permissive | skytiger0419/android-uiautomator-server | 9c483ae9d2b6da78eae237eed8244ba88dc93075 | d3cc34925a88dddaceb2e6086a31dd284a31f5c8 | refs/heads/master | 2020-04-02T12:51:41.026545 | 2019-02-27T05:49:15 | 2019-02-27T05:49:15 | 154,083,420 | 0 | 0 | MIT | 2018-10-22T03:35:47 | 2018-10-22T03:35:39 | null | UTF-8 | Java | false | false | 4,097 | java | /*
* The MIT License (MIT)
* Copyright (c) 2015 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.github.uiautomator.stub;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiDevice;
public class DeviceInfo {
private String _currentPackageName;
private int _displayWidth;
private int _displayHeight;
private int _displayRotation;
private int _displaySizeDpX;
private int _displaySizeDpY;
private String _productName;
private boolean _naturalOrientation;
private boolean _screenOn;
private int _sdkInt;
public static DeviceInfo getDeviceInfo() {
return new DeviceInfo();
}
private DeviceInfo() {
this._sdkInt = android.os.Build.VERSION.SDK_INT;
UiDevice ud = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
this._currentPackageName = ud.getCurrentPackageName();
this._displayWidth = ud.getDisplayWidth();
this._displayHeight = ud.getDisplayHeight();
this._displayRotation = ud.getDisplayRotation();
this._productName = ud.getProductName();
this._naturalOrientation = ud.isNaturalOrientation();
this._displaySizeDpX = ud.getDisplaySizeDp().x;
this._displaySizeDpY = ud.getDisplaySizeDp().y;
try {
this._screenOn = ud.isScreenOn();
} catch (RemoteException e) {
e.printStackTrace();
Log.e(e.getMessage());
}
}
public String getCurrentPackageName() {
return _currentPackageName;
}
public void setCurrentPackageName(String currentPackageName) {
this._currentPackageName = currentPackageName;
}
public int getDisplayWidth() {
return _displayWidth;
}
public void setDisplayWidth(int displayWidth) {
this._displayWidth = displayWidth;
}
public int getDisplayHeight() {
return _displayHeight;
}
public void setDisplayHeight(int displayHeight) {
this._displayHeight = displayHeight;
}
public int getDisplayRotation() {
return _displayRotation;
}
public void setDisplayRotation(int displayRotation) {
this._displayRotation = displayRotation;
}
public int getDisplaySizeDpX() {
return _displaySizeDpX;
}
public void setDisplaySizeDpX(int displaySizeDpX) {
this._displaySizeDpX = displaySizeDpX;
}
public int getDisplaySizeDpY() {
return _displaySizeDpY;
}
public void setDisplaySizeDpY(int displaySizeDpY) {
this._displaySizeDpY = displaySizeDpY;
}
public String getProductName() {
return _productName;
}
public void setProductName(String productName) {
this._productName = productName;
}
public boolean isNaturalOrientation() {
return _naturalOrientation;
}
public void setNaturalOrientation(boolean naturalOrientation) {
this._naturalOrientation = naturalOrientation;
}
public int getSdkInt() {
return _sdkInt;
}
public void setSdkInt(int sdkInt) {
this._sdkInt = sdkInt;
}
public boolean getScreenOn() {
return _screenOn;
}
public void setScreenOn(boolean screenOn) {
this._screenOn = screenOn;
}
}
| [
"[email protected]"
] | |
ca427b8d6ee5efd5ca083dd4a5c628c7b1693793 | f8542487f2e0f16d68ad61397c4f52f4cf3fe2d4 | /AppProgrammingSource/2.4.3/app/src/main/java/com/youngheart/engine/RemoteService.java | 663f0befa53dcce253b8eac38f4c27526311f233 | [
"MIT"
] | permissive | feixiao/Android | 3b6a138e309ae42bd2886e7d92d89d53d58c2df8 | cb50f1513b09d55324f46aeef8302ebf5faae5ad | refs/heads/master | 2023-07-23T07:16:23.959782 | 2023-07-13T01:43:20 | 2023-07-13T01:43:20 | 101,454,091 | 4 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,887 | java | package com.youngheart.engine;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.infrastructure.activity.BaseActivity;
import com.infrastructure.net.DefaultThreadPool;
import com.infrastructure.net.HttpRequest;
import com.infrastructure.net.RequestCallback;
import com.infrastructure.net.RequestParameter;
import com.infrastructure.net.Response;
import com.infrastructure.net.URLData;
import com.infrastructure.net.UrlConfigManager;
import com.youngheart.mockdata.MockService;
public class RemoteService {
private static RemoteService service = null;
private RemoteService() {
}
public static synchronized RemoteService getInstance() {
if (RemoteService.service == null) {
RemoteService.service = new RemoteService();
}
return RemoteService.service;
}
public void invoke(final BaseActivity activity,
final String apiKey,
final List<RequestParameter> params,
final RequestCallback callBack) {
final URLData urlData = UrlConfigManager.findURL(activity, apiKey);
if (urlData.getMockClass() != null) {
try {
MockService mockService = (MockService) Class.forName(
urlData.getMockClass()).newInstance();
String strResponse = mockService.getJsonData();
final Response responseInJson = JSON.parseObject(strResponse,
Response.class);
if (callBack != null) {
if (responseInJson.hasError()) {
callBack.onFail(responseInJson.getErrorMessage());
} else {
callBack.onSuccess(responseInJson.getResult());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
HttpRequest request = activity.getRequestManager().createRequest(
urlData, params, callBack);
DefaultThreadPool.getInstance().execute(request);
}
}
} | [
"[email protected]"
] | |
f5ecf1bbf4f6c6c7937d0170e834cd126eb17f27 | e64129d42002840ae21c915eea771f7e13bb1f35 | /pet-clinic-data/src/main/java/springFramework/petClinic/model/Owner.java | b6e8aaa40209f2584b19e4f84b2a36072bfab9b7 | [] | no_license | alexander8buga/Pet-clinic-Nov | d3c93fe8be0ca905ede6673e019575a48413e6e8 | 839db3574432257fe68f91092e57848a6d8c55a3 | refs/heads/master | 2020-04-09T20:04:48.635975 | 2019-01-09T22:20:09 | 2019-01-09T22:20:09 | 160,563,192 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 962 | java | package springFramework.petClinic.model;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* Created by ab on 12/21/2018
*/
@Setter
@Getter
@NoArgsConstructor
@Entity
@Table(name="owners")
public class Owner extends Person {
@Builder
public Owner(Long id, String firstName, String lastName, String address,
String city, String cellphone, Set<Pet> pets) {
super(id, firstName, lastName);
this.address = address;
this.city = city;
this.cellphone = cellphone;
this.pets = pets;
}
@Column(name="address")
private String address;
@Column(name="city")
private String city;
@Column(name="cellphone")
private String cellphone;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private Set<Pet> pets = new HashSet<>();
}
| [
"[email protected]"
] | |
e6e88a573067f8948b67927fe45dc0ce944d6dcf | 4397c2da139471d723149b1835005ff7f249ef13 | /src/Person.java | 9a87d0106d6ac236a62f7f22881f76554cedfa19 | [] | no_license | carlosmunozus03/java-exercises | f5ca4d3afb21e8575fe004b6c95b0eaf1f2cc5ec | a5820facecaf3b8fbeb150d25be933ce55d36a6c | refs/heads/main | 2023-09-02T22:13:57.448531 | 2021-11-23T18:16:17 | 2021-11-23T18:16:17 | 408,608,214 | 0 | 0 | null | 2021-11-23T18:16:18 | 2021-09-20T21:40:25 | Java | UTF-8 | Java | false | false | 921 | java | public class Person {
//Instance variables
public String firstName;
public String lastName;
//Instance Method
public String sayHello() {
return String.format("Hello, my name is %s %s", firstName, lastName);
}
//Call function
public static void main(String[] args) {
Person person = new Person(); //instantiated
person.firstName = "Carlos";
person.lastName = "Munoz";
System.out.println(person.sayHello()); // call the persona.function
//Example 1
Person ada = new Person();
ada.firstName = "Ada";
ada.lastName = "Lovelace";
//Example2
Person grace = new Person();
grace.firstName = "Grace";
grace.lastName = "Hopper";
System.out.println(ada.sayHello()); // "Hello from Ada Lovelace!"
System.out.println(grace.sayHello()); // "Hello from Grace Hopper!"
}
} | [
"[email protected]"
] | |
d8f1d806565eca515c602fc5d5db87a06488c998 | 71bcbb92d936aec7fb98331e87ee1f27405a2027 | /app/src/main/java/com/example/covid_19tracker/Adapter.java | 1b97a2ffc530a3407914fb144fee0a8da4427e93 | [] | no_license | aakasky/COVID-19_Tracker_App | 0da5d09d278933eeb93004db940b33c8c798dbe6 | 1e61c2bf48f135009bf1d57a86c09ae20a0edc6d | refs/heads/main | 2023-07-28T21:11:51.407008 | 2021-09-28T16:29:55 | 2021-09-28T16:29:55 | 411,359,180 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,397 | java | package com.example.covid_19tracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private Context mContext;
private List<Model> data;
public Adapter(Context mContext, List<Model> data) {
this.mContext = mContext;
this.data = data;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v;
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.data_layout, parent, false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.district.setText(data.get(position).getDistrictName());
holder.active.setText(data.get(position).getActive());
holder.recovered.setText(data.get(position).getRecovered());
holder.deceased.setText(data.get(position).getDeceased());
holder.total.setText(data.get(position).getConfirmed());
holder.nActive.setText(data.get(position).getnActive());
holder.nRecovered.setText(data.get(position).getnDead());
holder.nDeceased.setText(data.get(position).getnRecovered());
}
@Override
public int getItemCount() {
return data.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView district,active,recovered,deceased,total,nActive,nRecovered,nDeceased;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
district = itemView.findViewById(R.id.textDistrictName);
active = itemView.findViewById(R.id.activeCaseNumber);
recovered = itemView.findViewById(R.id.curedCaseNumber);
deceased = itemView.findViewById(R.id.deathCaseNumber);
total = itemView.findViewById(R.id.totalCaseNumber);
nActive = itemView.findViewById(R.id.activeIncreased);
nRecovered = itemView.findViewById(R.id.curedIncreased);
nDeceased = itemView.findViewById(R.id.deathIncreased);
}
}
}
| [
"[email protected]"
] | |
a046a1f0179152d4ef0cc724cc83cc7d81bfcd1b | 5cbc09e180372e26aea2fdf762f0e2e94b9b3e2d | /lgc_design_mode/src/main/java/com/linguochao/design/creation/singleton/LazySingle.java | 52e39c490cd0ccd107dafae8618ac6061b92d3f2 | [] | no_license | linguochao1024/itdan | 478beda7bd7536e44b561fb4e7e8ebb7ba14b272 | 3480b4e8595d598d3788bd71d1ba85b345828bad | refs/heads/master | 2022-11-10T01:19:56.816001 | 2020-05-02T14:33:43 | 2020-05-02T14:33:43 | 194,394,179 | 0 | 0 | null | 2022-10-12T20:43:30 | 2019-06-29T10:39:50 | Java | UTF-8 | Java | false | false | 478 | java | package com.linguochao.design.creation.singleton;
/**
* description
*
* @author linguochao
* @date 2020\4\11 0011
*/
public class LazySingle {
private static LazySingle s=null ;
private LazySingle(){ }
public static LazySingle getInstance() {
if (s == null) {
synchronized (LazySingle.class) {
if (s == null){
s = new LazySingle();
}
}
}
return s;
}
}
| [
"[email protected]"
] | |
afc9d4a0afb96436e5ea044d35c9004ecda5b363 | e09b548dd204038924bba2a94fc05fc959f5a696 | /sources/gnu/mapping/SymbolRef.java | d0e8693f7e02370032f3a90098c5fd1368bbdd64 | [
"Unlicense"
] | permissive | Li-amK/School-Chemie-App | 9472ac787be3658d0dc3a32a2787b98c34711c18 | 0b747e08e46d43e44849d6c59fd254f9466a4003 | refs/heads/main | 2022-07-29T13:51:33.064078 | 2022-02-06T18:21:34 | 2022-02-06T18:21:34 | 456,215,965 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 628 | java | package gnu.mapping;
import java.lang.ref.WeakReference;
/* JADX INFO: Access modifiers changed from: package-private */
/* compiled from: Namespace.java */
/* loaded from: classes.dex */
public class SymbolRef extends WeakReference {
SymbolRef next;
/* JADX INFO: Access modifiers changed from: package-private */
public SymbolRef(Symbol sym, Namespace ns) {
super(sym);
}
/* JADX INFO: Access modifiers changed from: package-private */
public Symbol getSymbol() {
return (Symbol) get();
}
public String toString() {
return "SymbolRef[" + getSymbol() + "]";
}
}
| [
"[email protected]"
] | |
2264570c40e3cbf54169b4a9289e413fea536120 | 17912b2922fb6f03ec1ca836ff87b18d14a0f1ca | /ConstrainedWidget/src/com/marvinlabs/widget/aspectratio/ConstrainedFrameLayout.java | bf4a80fe1b4a7a003a770a87ea66d802f064e7fa | [] | no_license | ProgrammerYuan/PKUEater | 5d884e18ee1e79a3c87bcf662c467b66a0c0de9c | dff8d01655668273560f421b9d43b63ce9e2f02c | refs/heads/master | 2020-03-30T06:06:50.448618 | 2015-06-16T12:49:00 | 2015-06-16T12:49:00 | 36,392,882 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,405 | java | package com.marvinlabs.widget.aspectratio;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
/**
* A frame layout with a constrained aspect ratio.
*
* @author Vincent Mimoun-Prat @ MarvinLabs (www.marvinlabs.com)
*/
public class ConstrainedFrameLayout extends FrameLayout implements AspectRatioDelegate.ConstrainedView {
public ConstrainedFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
aspectRatioDelegate = new AspectRatioDelegate(this, attrs);
}
public ConstrainedFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
aspectRatioDelegate = new AspectRatioDelegate(this, attrs);
}
public ConstrainedFrameLayout(Context context) {
super(context);
aspectRatioDelegate = new AspectRatioDelegate(this);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
aspectRatioDelegate.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@SuppressLint("WrongCall")
@Override
public void callParentOnMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private AspectRatioDelegate aspectRatioDelegate;
}
| [
"[email protected]"
] | |
127b68d2b82f616958c19f6e3945c5ce68759b95 | 894927bf0fc36549955be6fb781974c12bb449eb | /unisa-tools/unisa-tpustudentplacement/src/java/za/ac/unisa/lms/tools/tpustudentplacement/model/modelImpl/studentPlacementImpl/StuPlacementEditWinBuilder.java | 3367f5fd0ea37a5451fc63553318911606773e52 | [
"LicenseRef-scancode-generic-cla",
"ECL-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | sadupally/Dev | cd32fa3b753e8d20dd80e794618a8e97d1ff1c79 | ead9de3993b7a805199ac254c6fa99d3dda48adf | refs/heads/master | 2020-03-24T08:15:12.732481 | 2018-07-27T12:54:29 | 2018-07-27T12:54:29 | 142,589,852 | 0 | 0 | ECL-2.0 | 2018-07-27T14:49:51 | 2018-07-27T14:49:50 | null | UTF-8 | Java | false | false | 3,142 | java | package za.ac.unisa.lms.tools.tpustudentplacement.model.modelImpl.studentPlacementImpl;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts.action.ActionMessages;
import za.ac.unisa.lms.tools.tpustudentplacement.dao.databaseUtils;
import za.ac.unisa.lms.tools.tpustudentplacement.forms.Student;
import za.ac.unisa.lms.tools.tpustudentplacement.forms.StudentPlacement;
import za.ac.unisa.lms.tools.tpustudentplacement.forms.StudentPlacementForm;
import za.ac.unisa.lms.tools.tpustudentplacement.forms.StudentPlacementListRecord;
import za.ac.unisa.lms.tools.tpustudentplacement.utils.DateUtil;
import za.ac.unisa.lms.tools.tpustudentplacement.utils.StuEditWinValidator;;
public class StuPlacementEditWinBuilder {
public void buildEditWin(StudentPlacementForm studentPlacementForm,ActionMessages messages ){
StuEditWinValidator stuEditWinValidator=new StuEditWinValidator();
String[] indexArr=studentPlacementForm.getIndexNrPlacementSelected();
stuEditWinValidator.validateSelectedPlacement(messages, indexArr);
if(!messages.isEmpty()){
return;
}
StudentPlacementListRecordImpl spImpl=new StudentPlacementListRecordImpl();
StudentPlacementListRecord studentPlacementListRecord =spImpl.getStuPlacementListRecord(studentPlacementForm);
StuPlacementReader stuPlacementReader=new StuPlacementReader();
StudentPlacement studentPlacement =stuPlacementReader.getStudentPlacement(studentPlacementForm, studentPlacementListRecord);
studentPlacementForm.setStudentPlacement(studentPlacement);
String module=studentPlacement.getModule();
if((studentPlacement==null)||(module==null)||(module.equals(""))){
return;
}
setModulesForPrevYear(studentPlacementForm,module);
studentPlacementForm.setSupervisorCode(studentPlacement.getSupervisorCode());
studentPlacementForm.setStudentPlacement(studentPlacement);
studentPlacementForm.setStudentPlacementAction("edit");
studentPlacementForm.setPreviousPage(studentPlacementForm.getCurrentPage());
studentPlacementForm.setCurrentPage("editStudentPlacement");
StudentPlacementImage imageBuilder=new StudentPlacementImage(studentPlacement);
studentPlacementForm.setPlacementImage(imageBuilder.getPlacementImage());
}
private void setModulesForPrevYear(StudentPlacementForm studentPlacementForm,String module){
DateUtil dateUtil=new DateUtil();
if(Integer.parseInt(studentPlacementForm.getAcadYear())<dateUtil.yearInt()){
Student student=studentPlacementForm.getStudent();
List listPracticalModules=new ArrayList();
listPracticalModules.add(module);
student.setListPracticalModules(listPracticalModules);
}
}
}
| [
"[email protected]"
] | |
001e9ff901201047696a695943288cdc2ed87654 | 3bd8f99de86dc7eeb7ce80bb9a7dcd9c96f0e19c | /src/main/java/br/com/cvc/hotelbff/exceptions/ObjectNotFoundException.java | a6e28fc0c37523d247108e5bab622b95d62b4bf4 | [] | no_license | silvermind86/hotel-stay-cost | 9244938dc28ed89d1bbd9c3708652fa3125fba78 | e9e76d49158b1efb49502fc405be65266a21ab13 | refs/heads/main | 2023-06-10T18:17:49.315352 | 2021-07-05T01:29:07 | 2021-07-05T01:29:07 | 382,965,868 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 274 | java | package br.com.cvc.hotelbff.exceptions;
public class ObjectNotFoundException extends RuntimeException {
public ObjectNotFoundException(String msg) {
super(msg);
}
public ObjectNotFoundException(String msg, Throwable e) {
super(msg, e);
}
}
| [
"[email protected]"
] | |
1e2929899aff8aa8e69fe27cc302d039a2b8d690 | d656ba67e977a7cba86d5b5b2209a8f8fe559c01 | /src/main/java/cn/weforward/common/io/OutputStreamObserve.java | 4cb9ec089a0d523fba384d0cf18fb76cfb8e936e | [
"MIT"
] | permissive | garfieid/weforward-common | caa7adfddaa6f81b848a996cd11d828394fbef82 | b090e2213c6848dbf44478c8cde9aa243a211c6e | refs/heads/main | 2022-12-28T08:02:16.773860 | 2020-10-12T02:18:34 | 2020-10-12T02:18:34 | 303,260,039 | 0 | 1 | MIT | 2020-10-12T02:45:07 | 2020-10-12T02:45:06 | null | UTF-8 | Java | false | false | 1,525 | java | /**
* Copyright (c) 2019,2020 honintech
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package cn.weforward.common.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* 用于支持置入导流到观察的流通道
*
* @author liangyi
*
*/
public interface OutputStreamObserve {
/**
* 指定观察者
*
* @param observer
* 观察者
* @return 之前的观察者
* @throws IOException
*/
public OutputStream setObserver(OutputStream observer) throws IOException;
}
| [
"[email protected]"
] | |
f0beb5c6950f4a25c08a18faff2b09158fba54b9 | e6995b9b5dd33b96da457cc790c5882cd3d0e0b7 | /src/main/java/com/satyy/fb/controller/CovidTrackerController.java | 75ba1eb5e2b0fc599deee68199bb3ea720b17afd | [] | no_license | swagatamaiti/facebook-graph-api | f3be4e66c650991f830970ca80c1ae3d020677ad | 5a3d4e458fd2b705211d7f01c4d110b87f8dcedc | refs/heads/master | 2022-09-10T01:09:21.916809 | 2020-05-26T08:36:57 | 2020-05-26T08:36:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,036 | java | package com.satyy.fb.controller;
import com.satyy.fb.exception.ServerException;
import com.satyy.fb.facade.CovidTrackerFacade;
import com.satyy.fb.model.CovidStateData;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/covid/tracker/v1", produces = MediaType.APPLICATION_JSON_VALUE)
public class CovidTrackerController {
@Autowired
private CovidTrackerFacade facade;
@GetMapping(value = "/india", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<CovidStateData>> getStateWiseData() throws ServerException {
final List<CovidStateData> stateData = facade.getStateData();
return ResponseEntity.ok().body(stateData);
}
}
| [
"[email protected]"
] | |
e757bc36bfbbdb38bf9c5ac70c763cd65f34a184 | f2da40d9073673d460f0e1c645337082bf651b93 | /src/prj31/interpreter/GunInterpreter.java | 834a684aa99e41e3403ae86aae20bb20bf4d6fad | [] | no_license | kaszuster/LegoMindstorms | ca779a76a0d1c3fd9c4984eea0df69504df034a5 | b604a969655fe03d9e483634b037a60d1d6d0b55 | refs/heads/master | 2016-09-06T17:27:29.989317 | 2013-10-17T10:13:40 | 2013-10-17T10:13:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 509 | java | package prj31.interpreter;
import prj31.components.Gun;
import prj31.debug.RemoteConsole;
public class GunInterpreter implements Interpreter {
public ActionCode interpret(ActionCode actionCode) {
int code = actionCode.getCode();
if (code == ActionCode.GUN_SHOOT.getCode()) {
shoot();
return ActionCode.FINISHED;
}
return ActionCode.UNKNOWN_COMMAND;
}
private void shoot() {
RemoteConsole.getInstance().print("do: shoot");
Gun.getInstance().shoot();
}
}
| [
"[email protected]"
] | |
23a7cec495a1f8ae71d78cce7a3e7e58f3b62483 | 4a5fc5cc03f565773d47a3ab3161a9a8f1f06edd | /client/src/com/melonbear/ampup/LoginTask.java | e3a3677f0ae6151c5bb509190cb8616a1b8749f7 | [] | no_license | Magicjarvis/AMPup | f0e0611bb8ee170631c4bc4ecf4b2498d2c5a0d6 | cca3a54b5e5aaa6be567a20c1c07b32bbad89fdd | refs/heads/master | 2020-12-25T11:31:07.242706 | 2012-11-21T07:54:20 | 2012-11-21T07:54:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,033 | java | package com.melonbear.ampup;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
public class LoginTask extends AsyncTask<Object, Integer, Void> {
private static final String ROUTE = "/sessions";
private Context mContext;
private String mUsername;
private SharedPreferences mPrefs;
@Override
protected Void doInBackground(Object... params) {
mContext = (Context) params[0];
mUsername = (String) params[1];
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(String.format("http://192.168.43.85:3000%s",
ROUTE));
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("user", mUsername));
try {
post.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse res = client.execute(post);
StatusLine statusLine = res.getStatusLine();
int status = statusLine.getStatusCode();
if (status == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
res.getEntity().writeTo(out);
out.close(); String response = out.toString();
JSONObject dekel = new JSONObject(response);
if (dekel.has("sid")) {
if (!mPrefs.contains("session")) {
Editor editor = mPrefs.edit();
editor.putString("user_name", mUsername);
editor.putString("session", dekel.getString("sid"));
editor.commit();
}
if (!mPrefs.contains("user_name")) {
throw new RuntimeException("This should never happen");
}
}
} else {
res.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void v) {
if (mPrefs.contains("session")) {
Intent i = new Intent(mContext, AMPActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(i);
}
}
}
| [
"[email protected]"
] | |
41e4e2dc5e9df3afba306b5d6fdf76ae23f4bd1e | b5e07c6236b52da4fcd83af8949b71cec54e3ffa | /Week6Lecture/Week6Lecture/src/MathClassMethods/MathMethodTester.java | 58b7ee717c18e0c9b8eeaadb9dcd7fc5d40b56c1 | [] | no_license | lasteagleknight/StrComProg1Get | a72d79f762ae27452736322d3d1af930393e2be5 | 6ada06129ed180298c21fbe8928cbbed6b65a4b6 | refs/heads/master | 2021-01-10T09:14:16.966964 | 2015-06-01T01:44:19 | 2015-06-01T01:44:19 | 36,631,226 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,056 | java | package MathClassMethods;
public class MathMethodTester {
/**
* @param args
*/
public static void main(String[] args) {
//get the absolute value
System.out.printf("The absolute value of -134 is: %d\n", Math.abs(-134));
//round up!
System.out.printf("Round up from 1.098 with Math.ceil() %,.2f\n", Math.ceil(1.098));
//round down!
System.out.printf("Round down from 1.098 with Math.floor() %,.2f\n", Math.floor(1.098));
//Find max and min
System.out.printf("The larger of the two numbers 6 and 3 is %d\n", Math.max(6, 3));
System.out.printf("The smaller of the two numbers 6 and 3 is %d\n", Math.min(6, 3));
//pass arithmetic expressions as parameters.
System.out.printf("The larger of the two numbers (3*4)/9 and (5-6*22)/3is %d\n", Math.max((3*4)/9, (5-6*22)/3));
//make exponential calculations.
System.out.printf("2 raised to the 10th power is %,.2f\n", Math.pow(2, 10));
//calculate square roots
System.out.printf("The square root of the max int value is %,.2f", Math.sqrt(Integer.MAX_VALUE));
}
}
| [
"[email protected]"
] | |
8c52a5d92533fbaa1c13d957904a18b8ddccf585 | c37836a5a5269a0ed7b99dfc9874bf31addfe39f | /Data/weka-commit-1/weka-1f3a355b99df97da3d8dfebca2774e5839d83f77/weka/classifiers/meta/Stacking.java | fde7cba4cf432e539de7b8b139be481fb9823d5d | [] | no_license | lijunyou/AST_Similarity_Detector | bef8621cb7282e09f5839341e2ab5a219a060cd6 | f21f51874d4c4fd8018fdf9010bc5d24c9e5442e | refs/heads/master | 2020-04-13T05:15:24.150922 | 2018-12-24T12:11:34 | 2018-12-24T12:11:34 | 162,986,170 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,637 | java | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Stacking.java
* Copyright (C) 1999 Eibe Frank
*
*/
package weka.classifiers.meta;
import weka.classifiers.*;
import weka.classifiers.rules.ZeroR;
import java.io.*;
import java.util.*;
import weka.core.*;
/**
* Implements stacking. For more information, see<p>
*
* David H. Wolpert (1992). <i>Stacked
* generalization</i>. Neural Networks, 5:241-259, Pergamon Press. <p>
*
* Valid options are:<p>
*
* -X num_folds <br>
* The number of folds for the cross-validation (default 10).<p>
*
* -S seed <br>
* Random number seed (default 1).<p>
*
* -B classifierstring <br>
* Classifierstring should contain the full class name of a base scheme
* followed by options to the classifier.
* (required, option should be used once for each classifier).<p>
*
* -M classifierstring <br>
* Classifierstring for the meta classifier. Same format as for base
* classifiers. (required) <p>
*
* @author Eibe Frank ([email protected])
* @version $Revision: 1.22 $
*/
public class Stacking extends RandomizableMultipleClassifiersCombiner {
/** The meta classifier */
protected Classifier m_MetaClassifier = new ZeroR();
/** Format for meta data */
protected Instances m_MetaFormat = null;
/** Format for base data */
protected Instances m_BaseFormat = null;
/** Set the number of folds for the cross-validation */
protected int m_NumFolds = 10;
/**
* Returns a string describing classifier
* @return a description suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Combines several classifiers using the stacking method. "
+ "Can do classification or regression. "
+ "For more information, see\n\n"
+ "David H. Wolpert (1992). \"Stacked "
+ "generalization\". Neural Networks, 5:241-259, Pergamon Press.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector(2);
newVector.addElement(new Option(
metaOption(),
"M", 0, "-M <scheme specification>"));
newVector.addElement(new Option(
"\tSets the number of cross-validation folds.",
"X", 1, "-X <number of folds>"));
Enumeration enum = super.listOptions();
while (enum.hasMoreElements()) {
newVector.addElement(enum.nextElement());
}
return newVector.elements();
}
/**
* String describing option for setting meta classifier
*/
protected String metaOption() {
return "\tFull name of meta classifier, followed by options.\n" +
"\t(default: \"weka.classifiers.rules.Zero\")";
}
/**
* Parses a given list of options. Valid options are:<p>
*
* -X num_folds <br>
* The number of folds for the cross-validation (default 10).<p>
*
* -S seed <br>
* Random number seed (default 1).<p>
*
* -B classifierstring <br>
* Classifierstring should contain the full class name of a base scheme
* followed by options to the classifier.
* (required, option should be used once for each classifier).<p>
*
* -M classifierstring <br>
* Classifierstring for the meta classifier. Same format as for base
* classifiers. (default: weka.classifiers.rules.ZeroR) <p>
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
String numFoldsString = Utils.getOption('X', options);
if (numFoldsString.length() != 0) {
setNumFolds(Integer.parseInt(numFoldsString));
} else {
setNumFolds(10);
}
processMetaOptions(options);
super.setOptions(options);
}
/**
* Process options setting meta classifier.
*/
protected void processMetaOptions(String[] options) throws Exception {
String classifierString = Utils.getOption('M', options);
String [] classifierSpec = Utils.splitOptions(classifierString);
String classifierName;
if (classifierSpec.length == 0) {
classifierName = "weka.classifiers.rules.ZeroR";
} else {
classifierName = classifierSpec[0];
classifierSpec[0] = "";
}
setMetaClassifier(Classifier.forName(classifierName, classifierSpec));
}
/**
* Gets the current settings of the Classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
public String [] getOptions() {
String [] superOptions = super.getOptions();
String [] options = new String [superOptions.length + 4];
int current = 0;
options[current++] = "-X"; options[current++] = "" + getNumFolds();
options[current++] = "-M";
options[current++] = getMetaClassifier().getClass().getName() + " "
+ Utils.joinOptions(((OptionHandler)getMetaClassifier()).getOptions());
System.arraycopy(superOptions, 0, options, current,
superOptions.length);
return options;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String numFoldsTipText() {
return "The number of folds used for cross-validation.";
}
/**
* Gets the number of folds for the cross-validation.
*
* @return the number of folds for the cross-validation
*/
public int getNumFolds() {
return m_NumFolds;
}
/**
* Sets the number of folds for the cross-validation.
*
* @param numFolds the number of folds for the cross-validation
* @exception Exception if parameter illegal
*/
public void setNumFolds(int numFolds) throws Exception {
if (numFolds < 0) {
throw new IllegalArgumentException("Stacking: Number of cross-validation " +
"folds must be positive.");
}
m_NumFolds = numFolds;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String metaClassifierTipText() {
return "The meta classifiers to be used.";
}
/**
* Adds meta classifier
*
* @param classifier the classifier with all options set.
*/
public void setMetaClassifier(Classifier classifier) {
m_MetaClassifier = classifier;
}
/**
* Gets the meta classifier.
*
* @return the meta classifier
*/
public Classifier getMetaClassifier() {
return m_MetaClassifier;
}
/**
* Buildclassifier selects a classifier from the set of classifiers
* by minimising error on the training data.
*
* @param data the training data to be used for generating the
* boosted classifier.
* @exception Exception if the classifier could not be built successfully
*/
public void buildClassifier(Instances data) throws Exception {
if (m_MetaClassifier == null) {
throw new IllegalArgumentException("No meta classifier has been set");
}
if (!(data.classAttribute().isNominal() ||
data.classAttribute().isNumeric())) {
throw new UnsupportedClassTypeException("Class attribute has to be nominal " +
"or numeric!");
}
Instances newData = new Instances(data);
m_BaseFormat = new Instances(data, 0);
newData.deleteWithMissingClass();
if (newData.numInstances() == 0) {
throw new IllegalArgumentException("No training instances without missing " +
"class!");
}
Random random = new Random(m_Seed);
newData.randomize(random);
if (newData.classAttribute().isNominal()) {
newData.stratify(m_NumFolds);
}
// Create meta level
generateMetaLevel(newData, random);
// Rebuilt all the base classifiers on the full training data
for (int i = 0; i < m_Classifiers.length; i++) {
getClassifier(i).buildClassifier(newData);
}
}
/**
* Generates the meta data
*/
protected void generateMetaLevel(Instances newData, Random random)
throws Exception {
Instances metaData = metaFormat(newData);
m_MetaFormat = new Instances(metaData, 0);
for (int j = 0; j < m_NumFolds; j++) {
Instances train = newData.trainCV(m_NumFolds, j, random);
// Build base classifiers
for (int i = 0; i < m_Classifiers.length; i++) {
getClassifier(i).buildClassifier(train);
}
// Classify test instances and add to meta data
Instances test = newData.testCV(m_NumFolds, j);
for (int i = 0; i < test.numInstances(); i++) {
metaData.add(metaInstance(test.instance(i)));
}
}
m_MetaClassifier.buildClassifier(metaData);
}
/**
* Returns class probabilities.
*
* @param instance the instance to be classified
* @exception Exception if instance could not be classified
* successfully
*/
public double[] distributionForInstance(Instance instance) throws Exception {
return m_MetaClassifier.distributionForInstance(metaInstance(instance));
}
/**
* Output a representation of this classifier
*/
public String toString() {
if (m_Classifiers.length == 0) {
return "Stacking: No base schemes entered.";
}
if (m_MetaClassifier == null) {
return "Stacking: No meta scheme selected.";
}
if (m_MetaFormat == null) {
return "Stacking: No model built yet.";
}
String result = "Stacking\n\nBase classifiers\n\n";
for (int i = 0; i < m_Classifiers.length; i++) {
result += getClassifier(i).toString() +"\n\n";
}
result += "\n\nMeta classifier\n\n";
result += m_MetaClassifier.toString();
return result;
}
/**
* Makes the format for the level-1 data.
*
* @param instances the level-0 format
* @return the format for the meta data
*/
protected Instances metaFormat(Instances instances) throws Exception {
FastVector attributes = new FastVector();
Instances metaFormat;
Attribute attribute;
int i = 0;
for (int k = 0; k < m_Classifiers.length; k++) {
Classifier classifier = (Classifier) getClassifier(k);
String name = classifier.getClass().getName();
if (m_BaseFormat.classAttribute().isNumeric()) {
attributes.addElement(new Attribute(name));
} else {
for (int j = 0; j < m_BaseFormat.classAttribute().numValues(); j++) {
attributes.addElement(new Attribute(name + ":" +
m_BaseFormat
.classAttribute().value(j)));
}
}
}
attributes.addElement(m_BaseFormat.classAttribute());
metaFormat = new Instances("Meta format", attributes, 0);
metaFormat.setClassIndex(metaFormat.numAttributes() - 1);
return metaFormat;
}
/**
* Makes a level-1 instance from the given instance.
*
* @param instance the instance to be transformed
* @return the level-1 instance
*/
protected Instance metaInstance(Instance instance) throws Exception {
double[] values = new double[m_MetaFormat.numAttributes()];
Instance metaInstance;
int i = 0;
for (int k = 0; k < m_Classifiers.length; k++) {
Classifier classifier = getClassifier(k);
if (m_BaseFormat.classAttribute().isNumeric()) {
values[i++] = classifier.classifyInstance(instance);
} else {
double[] dist = classifier.distributionForInstance(instance);
for (int j = 0; j < dist.length; j++) {
values[i++] = dist[j];
}
}
}
values[i] = instance.classValue();
metaInstance = new Instance(1, values);
metaInstance.setDataset(m_MetaFormat);
return metaInstance;
}
/**
* Main method for testing this class.
*
* @param argv should contain the following arguments:
* -t training file [-T test file] [-c class index]
*/
public static void main(String [] argv) {
try {
System.out.println(Evaluation.evaluateModel(new Stacking(), argv));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
| [
"[email protected]"
] | |
e0cd33a84aae56d9c09be3fbd7578eaea5301259 | dafa81d203d9083eda00fe877cba7b0b8afe03e8 | /src/main/java/adapter/Goose.java | 88182eb43b49e4d377484f1afabedfaf4c09f241 | [] | no_license | ChotikaLuangorachorn/MoreDesignPatterns | 82dfb590bf8b5c0a6e7f5b30313486fddc34c5f9 | ae36fa9843bdff6277ad25f6d6d07053c675c95e | refs/heads/master | 2021-05-07T08:32:08.680961 | 2017-11-08T06:34:29 | 2017-11-08T06:34:29 | 109,364,215 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 148 | java | package adapter;
/**
* Created by 708 on 11/3/2017.
*/
public class Goose {
public void honk() {
System.out.println("Honk");
}
}
| [
"[email protected]"
] | |
4c143f398b3c6ff9433c935d3da3f66f00c2d71f | d70a85ce8ad5f8979efe5c5ac0a7787f6db6e643 | /server/src/main/java/socket/ChatServer.java | 954faccc8fd7757d29cc5093225bbb31c56c0329 | [] | no_license | MacMargo/CodeTest | 894a5f10fe43535cdbd1f8276a571a516e4318ed | 8941d177975e6bf766166c707850a7c657db66ff | refs/heads/master | 2022-06-21T23:42:58.325313 | 2019-12-01T11:48:54 | 2019-12-01T11:48:54 | 99,217,216 | 0 | 0 | null | 2022-06-17T02:05:00 | 2017-08-03T09:46:37 | Java | UTF-8 | Java | false | false | 2,207 | java | package socket;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;
import java.net.InetSocketAddress;
/**
* @author maniansheng
* @date 2019/2/23
* @description TODO
**/
public class ChatServer {
private final ChannelGroup channelGroup =
new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
private final EventLoopGroup group = new NioEventLoopGroup();
private Channel channel;
public ChannelFuture start(InetSocketAddress address) {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(createInitializer(channelGroup));
ChannelFuture future = bootstrap.bind(address);
future.syncUninterruptibly();
channel = future.channel();
return future;
}
protected ChannelInitializer<Channel> createInitializer(
ChannelGroup group) {
return new ChatServerInitializer(group);
}
public void destroy() {
if (channel != null) {
channel.close();
}
channelGroup.close();
group.shutdownGracefully();
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Please give port as argument");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
final ChatServer endpoint = new ChatServer();
ChannelFuture future = endpoint.start(
new InetSocketAddress(port));
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
endpoint.destroy();
}
});
future.channel().closeFuture().syncUninterruptibly();
}
}
| [
"[email protected]"
] | |
493a366c2da5df45a7f415552ebb6a4b7b5e3829 | 0cea7c467cd1230f91376c1e53ecaafa3703816c | /src/main/java/com/leandrolara/cursomc/domain/PagamentoComBoleto.java | 6f2037b1094fd90d1aec855a4aeeebc274bfd8d1 | [] | no_license | LeandroSilvaLara/cursomc | 88f4beaeb140072c23aad7aa95245a01ceb460a1 | fd96daaa7157473a6cde9e0b86a33d3da86fc479 | refs/heads/master | 2022-04-07T14:21:30.050476 | 2020-03-16T02:07:01 | 2020-03-16T02:07:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,051 | java | package com.leandrolara.cursomc.domain;
import java.util.Date;
import javax.persistence.Entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.leandrolara.cursomc.domain.enums.EstadoPagamento;
@Entity
public class PagamentoComBoleto extends Pagamento {
private static final long serialVersionUID = 1L;
@JsonFormat(pattern="dd/MM/yyyy")
private Date dataVencimento;
@JsonFormat(pattern="dd/MM/yyyy")
private Date dataPagamento;
public PagamentoComBoleto() {
}
public PagamentoComBoleto(Integer id, EstadoPagamento estado, Pedido pedido, Date dataVencimento, Date dataPagamento) {
super(id, estado, pedido);
this.dataPagamento = dataPagamento;
this.dataVencimento = dataVencimento;
}
public Date getDataVencimento() {
return dataVencimento;
}
public void setDataVencimento(Date dataVencimento) {
this.dataVencimento = dataVencimento;
}
public Date getDataPagamento() {
return dataPagamento;
}
public void setDataPagamento(Date dataPagamento) {
this.dataPagamento = dataPagamento;
}
}
| [
"[email protected]"
] | |
e8e33c49c1aa7435d8a0b4416ded1020ab02f3ab | f1a4f0a9b6ceea2a96c55d8e2d204caa90a49252 | /src/main/java/org/xh/xs/lucene_42/XhAnalyzer.java | 4504621d11acda0bae3caff4045762d6f0acd3f3 | [] | no_license | kevindragon/xh_seg | af285ec48b010152ca447e7713b0b1b0a6abdb78 | aadfbeeb00ca2142d61c12acdd8d25a5b166c40f | refs/heads/master | 2022-12-28T20:40:30.559525 | 2022-12-11T04:24:49 | 2022-12-11T04:24:49 | 19,017,901 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 516 | java | package org.xh.xs.lucene_42;
import java.io.IOException;
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
public class XhAnalyzer extends Analyzer {
@Override
protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
final XhTokenizer src=new XhTokenizer(reader);
return new TokenStreamComponents(src) {
@Override
protected void setReader(final Reader reader) throws IOException {
super.setReader(reader);
}
};
}
}
| [
"[email protected]"
] | |
8ebfe453c584f76798c58c7f30cb9804df48efcf | e985a4f161a6976b307727f5ee74e77367f899d0 | /src/com/mycompany/bsh/FileSearch.java | d9d6db0b7fc569b2f5341d351bc63efc4fc1f91d | [] | no_license | simka5293/Baksmali | 68540e1fe2b83faf0740f2b3845fe4a075fe49f6 | 00e953e0e0727208110df5407cabd7d3e1832990 | refs/heads/master | 2021-01-10T03:51:34.365161 | 2015-12-17T17:05:22 | 2015-12-17T17:05:22 | 48,184,426 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 571 | java | package com.mycompany.bsh;
import java.io.*;
public class FileSearch
{
public FileSearch()
{}
String s="";
String path="";
String endsWith="";
public String[] main(String[] args)
{
this.path = args[0];
this.endsWith = args[1];
dir(path);
return s.split("\n");
}
public void dir(String dir)
{
File[] files=new File(dir).listFiles();
for (File f:files)
{
if (f.isFile())
{
if (f.toString().endsWith(endsWith))
{
this.s += dir + "/" + f.getName() + "\n";
}
}
else
{
dir(dir + "/" + f.getName());
}
}
}
}
| [
"[email protected]"
] | |
2544fd6c7ec00f3b7e0fcb966bc3791e189bf3d4 | 4c3bfd6d3e71e8b1d07a168e1e8b93bb7401e1af | /src/main/java/com/nju/oawork/services/address/AddressService.java | 8df6a1c5e370efe66793e3cbe4c7eb7d97bddbd5 | [
"MIT"
] | permissive | MODmaxM/OAwork | 04e83760b63ef48733eba9b141639750577e766d | ec488311c1fecf02ad3e6aee5d5b71c3f3bad3ac | refs/heads/master | 2022-06-21T04:40:21.340667 | 2020-02-14T14:10:56 | 2020-02-14T14:10:56 | 240,513,693 | 0 | 0 | MIT | 2022-06-21T02:48:04 | 2020-02-14T13:24:37 | JavaScript | UTF-8 | Java | false | false | 1,969 | java | package com.nju.oawork.services.address;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nju.oawork.model.dao.address.AddressDao;
import com.nju.oawork.model.dao.notedao.AttachmentDao;
import com.nju.oawork.model.entity.note.Director;
@Service
@Transactional
public class AddressService {
@Autowired
private AddressDao addressDao;
@Autowired
AttachmentDao atDao;
public Director sava(Director director){
return addressDao.save(director);
}
public void deleteDirector(Director director){
addressDao.delete(director);
System.out.println("删除一个外部联系人");
}
public List<Map<String, Object>> fengzhaung(List<Map<String, Object>> addressList){
List<Map<String, Object>> adds=new ArrayList<>();
for (int i = 0; i < addressList.size(); i++) {
Map<String, Object> result=new HashMap<>();
result.put("director_users_id", addressList.get(i).get("director_users_id"));
result.put("director_id", addressList.get(i).get("director_id"));
result.put("user_id", addressList.get(i).get("user_id"));
result.put("catelog_name", addressList.get(i).get("catelog_name"));
result.put("companyname", addressList.get(i).get("companyname"));
result.put("user_name", addressList.get(i).get("user_name"));
result.put("sex", addressList.get(i).get("sex"));
result.put("phone_number", addressList.get(i).get("phone_number"));
result.put("email", addressList.get(i).get("email"));
// !Objects.isNull(atDao.findOne(d.getAttachment()))
if(addressList.get(i).get("image_path")!=null){
result.put("image_path", atDao.findOne(Long.parseLong((addressList.get(i).get("image_path")+""))).getAttachmentPath());
}else{
result.put("image_path", "timg.jpg");
}
adds.add(result);
}
return adds;
}
}
| [
"[email protected]"
] | |
c5be456e9c416f50959d709cad2cdde318be4349 | 2875ff3836352cadfeafe0a14636a783d224bf5c | /src/com/kolakcc/loljclient/controller/CustomGameLobbyController.java | 41f6adcd2f2bb016bb8e60655cf59e308edb6d02 | [
"Apache-2.0"
] | permissive | devbridie/lol-jclient | 7202865e4d8ee2f4cf1bf48ba0a48e3314a88ae2 | 1e47804de46bf593d18aeb83ea0f0eeafe87320b | refs/heads/master | 2020-04-10T19:06:05.679674 | 2013-11-21T18:29:42 | 2017-12-11T00:45:48 | 12,573,050 | 8 | 5 | null | 2017-12-11T00:45:22 | 2013-09-03T19:40:03 | Java | UTF-8 | Java | false | false | 5,901 | java | package com.kolakcc.loljclient.controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
import com.gvaneyck.rtmp.encoding.TypedObject;
import com.kolakcc.loljclient.StartupClass;
import com.kolakcc.loljclient.model.CustomGameDetailed;
import com.kolakcc.loljclient.model.CustomGameListItem;
import com.kolakcc.loljclient.model.swing.TeamListModel;
import com.kolakcc.loljclient.model.swing.TeamListModel.TEAM;
import com.kolakcc.loljclient.view.CustomGameLobbyView;
public class CustomGameLobbyController extends KolaController implements
ActionListener, WindowListener {
CustomGameLobbyView view;
SwingWorker<TypedObject, Void> joinGameWorker;
int gameID;
CustomGameDetailed gameDetailed;
ChampionSelectController selectController;
TeamListModel team1Model;
TeamListModel team2Model;
//TODO: data with a higher optimistcLock has a higher priority.
private CustomGameLobbyController() {
this.view = new CustomGameLobbyView();
this.view.quitGameButton.addActionListener(this);
this.view.addBotOnTeam1Button.addActionListener(this);
this.view.addBotOnTeam2Button.addActionListener(this);
this.view.swapTeamButton.addActionListener(this);
this.view.startGameButton.addActionListener(this);
this.view.addWindowListener(this);
this.setView(this.view);
}
public CustomGameLobbyController(CustomGameListItem game) {
this(game.getID());
}
public CustomGameLobbyController(int gameID) {
this();
this.gameID = gameID;
this.initializeWorkers();
this.joinGameWorker.execute();
}
public CustomGameLobbyController(TypedObject result) {
this();
this.receivePacket(result);
this.gameID = gameDetailed.getID();
}
public void actionPerformed(ActionEvent event) {
try {
if (event.getSource() == view.quitGameButton) {
closeLobby();
} else if (event.getSource() == view.swapTeamButton) {
int id = StartupClass.Client.invoke("gameService", "switchTeams", new Object[] { gameID });
System.out.println(StartupClass.Client.getResult(id));
} else if (event.getSource() == view.startGameButton) {
System.out.println("gameID: " + gameID);
int id = StartupClass.Client.invoke("gameService", "startChampionSelection", new Object[] { gameID, 1 }); //TODO: what is this 1?
TypedObject result = StartupClass.Client.getResult(id).getTO("data");
System.out.println(result.toPrettyString());
}
} catch (Exception e) { e.printStackTrace(); }
}
protected void initializeWorkers() {
this.joinGameWorker = new SwingWorker<TypedObject, Void>() {
protected TypedObject doInBackground() throws Exception {
int id = StartupClass.Client
.invoke("gameService", "joinGame",
new Object[] { new Double(CustomGameLobbyController.this.gameID), null });
return StartupClass.Client.getResult(id);
}
protected void done() {
try {
TypedObject result = this.get();
if (result.get("result").equals("_error")) {
TypedObject error = result.getTO("data").getTO(
"rootCause");
if (error.getString("rootCauseClassname")
.equals("com.riotgames.platform.game.UserBannedException")) {
CustomGameLobbyController.this.HandleException("You're banned from this game.","The game creator has banned you from this game.\r\n" + error.toString());
System.out.println("You're banned from this game.");
} else {
System.out.println(error.getString("message"));
}
}
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
};
}
public void receivePacket(TypedObject to) {
this.gameDetailed = new CustomGameDetailed(to);
this.updateGameLobby();
System.out.println("game state: "+gameDetailed.getGameState());
view.setTitle(gameDetailed.getName());
if (gameDetailed.getGameState().equals("CHAMP_SELECT")) {
team1Model.addChampionData(gameDetailed.getPlayerChampionSelections());
team2Model.addChampionData(gameDetailed.getPlayerChampionSelections());
if (selectController == null) {
selectController = new ChampionSelectController(team1Model,team2Model);
try {
StartupClass.Client.invoke("gameService", "setClientReceivedGameMessage", new Object[] { new Double(gameID), "CHAMP_SELECT_CLIENT" });
} catch (Exception e) {
e.printStackTrace();
}
}
}
//TODO: move this to championselectcontroller
if (gameDetailed.getGameState().equals("POST_CHAMP_SELECT")) {
selectController.countDown(10);
}
if (gameDetailed.getGameState().equals("START_REQUESTED")) {
//TODO: start requested
}
}
public void updateGameLobby() {
team1Model = new TeamListModel(this.gameDetailed, TEAM.TEAM1);
team2Model = new TeamListModel(this.gameDetailed, TEAM.TEAM2);
this.view.team1List.setModel(team1Model);
this.view.team2List.setModel(team2Model);
if (this.selectController != null) {
this.selectController.view.team1List.setModel(team1Model);
this.selectController.view.team2List.setModel(team2Model);
}
this.view.revalidate();
this.view.repaint();
}
public void closeLobby() {
try {
StartupClass.Client.invoke("gameService", "quitGame",new Object[] {});
} catch (IOException e1) {
e1.printStackTrace();
}
this.view.dispose();
}
@Override
public void windowClosing(WindowEvent e) {
closeLobby();
}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}
| [
"[email protected]"
] | |
5379425e373cda653f537994f05afa7de8c60e4e | ed16250cd6813289b9686d8c506f5369e95dc5f9 | /android/src/main/java/com/matejdr/googleonetap/GoogleOneTapPackage.java | 2ea698c29c2d617ce15de48ff7561ab29c81c009 | [
"MIT"
] | permissive | NZME/react-native-google-one-tap | b19692aac0341496dc0818ea81aeed235fcec408 | 1be9a04939b5ea0c9b3a76424527af9acf469da9 | refs/heads/master | 2023-07-29T08:53:59.873356 | 2021-09-12T16:00:56 | 2021-09-12T16:00:56 | 405,687,020 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 852 | java | package com.matejdr.googleonetap;
import androidx.annotation.NonNull;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GoogleOneTapPackage implements ReactPackage {
@NonNull
@Override
public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new GoogleOneTapModule(reactContext));
return modules;
}
@NonNull
@Override
public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
| [
"[email protected]"
] | |
cb10d13890aeff0d6fe9cff69008ae4b1f6c061e | 2bf30c31677494a379831352befde4a5e3d8ed19 | /vipr-portal/com.iwave.isa.content/src/java/com/emc/sa/asset/providers/ComputeImageProvider.java | 842de26d471b1e210a893e1adc8cc09c1cac3fb6 | [] | no_license | dennywangdengyu/coprhd-controller | fed783054a4970c5f891e83d696a4e1e8364c424 | 116c905ae2728131e19631844eecf49566e46db9 | refs/heads/master | 2020-12-30T22:43:41.462865 | 2015-07-23T18:09:30 | 2015-07-23T18:09:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,667 | java | /*
* Copyright 2012-2015 iWave Software LLC
* All Rights Reserved
*/
package com.emc.sa.asset.providers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.emc.vipr.model.catalog.AssetOption;
import com.emc.sa.asset.AssetOptionsContext;
import com.emc.sa.asset.BaseAssetOptionsProvider;
import com.emc.sa.asset.annotation.Asset;
import com.emc.sa.asset.annotation.AssetNamespace;
import com.emc.storageos.db.client.model.ComputeImage;
import com.emc.storageos.db.client.model.ComputeImage.ComputeImageStatus;
import com.emc.storageos.model.compute.ComputeImageRestRep;
@Component
@AssetNamespace("vipr")
public class ComputeImageProvider extends BaseAssetOptionsProvider {
protected List<ComputeImageRestRep> getComputeImages(AssetOptionsContext context) {
debug("getting compute images");
return api(context).computeImages().getAll();
}
@Asset("computeImage")
public List<AssetOption> getComputeImageOptions(AssetOptionsContext ctx) {
debug("getting compute images");
List<ComputeImageRestRep> availCis = new ArrayList<ComputeImageRestRep>();
for (ComputeImageRestRep ci : getComputeImages(ctx)) {
if (ComputeImage.ComputeImageStatus.AVAILABLE.name().equals(ci.getComputeImageStatus())) {
availCis.add(ci);
}
}
return createBaseResourceOptions(availCis);
}
protected AssetOption createComputeImageOption(AssetOptionsContext ctx, ComputeImageRestRep value) {
String label = value.getName();
return new AssetOption(value.getId(), label);
}
}
| [
"[email protected]"
] | |
1152b05428016422f083470aa9f7ab7ca0da5106 | b9de3ab2a382fe74eec35d5505f76c0b27bd505b | /src/test/java/de/hhu/propra/link/archtests/ServiceArchTests.java | a3122a7f9d198a70d073874921de1a1cc221dac7 | [
"MIT"
] | permissive | n2o/url-shortener | c0a199cac985a437dd26f35be10f2912e006c38b | bd21515ff156406e6f55e6223031e471460e4dbb | refs/heads/master | 2023-08-07T12:28:22.119464 | 2023-07-20T09:48:00 | 2023-07-20T09:48:00 | 223,239,259 | 15 | 27 | MIT | 2023-07-20T09:48:02 | 2019-11-21T18:34:30 | Java | UTF-8 | Java | false | false | 1,182 | java | package de.hhu.propra.link.archtests;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import de.hhu.propra.link.LinkApplication;
import org.springframework.stereotype.Service;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
@AnalyzeClasses(packagesOf = LinkApplication.class,
importOptions = ImportOption.DoNotIncludeTests.class)
public class ServiceArchTests {
@ArchTest
public ArchRule serviceClassNames =
classes()
.that()
.areAnnotatedWith(Service.class)
.or()
.haveSimpleNameEndingWith("Service")
.should()
.beAnnotatedWith(Service.class)
.andShould()
.haveSimpleNameEndingWith("Service");
@ArchTest
public ArchRule serviceClassLocation =
classes()
.that()
.areAnnotatedWith(Service.class)
.or()
.haveSimpleNameEndingWith("Service")
.should()
.resideInAPackage("de.hhu.propra.link.services");
}
| [
"[email protected]"
] | |
8aad27f042a8cce2f7940b957b81a09d0e09f524 | cfac36b752c40d8fef2c34e155df14e4dbacc204 | /mooc-2013-OOProgrammingWithJava-PART1/week6-102.GradeDistribution/src/Exam.java | 36bb727a1c9158d5f1c1f3214fdf9da499f908d9 | [] | no_license | dustincheung/mooc_java_part1 | 0e20f5fd26d521a0b81f9a65d3a3825424b8109e | 2e600019e736c23e63cdbcf47e49eb473814140d | refs/heads/master | 2020-07-28T13:15:32.639405 | 2019-11-16T18:17:39 | 2019-11-16T18:17:39 | 209,422,026 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,442 | java | import java.util.ArrayList;
public class Exam {
private ArrayList<Integer> scores;
private int fiveCount;
private int fourCount;
private int threeCount;
private int twoCount;
private int oneCount;
private int zeroCount;
private int totalCount;
public Exam(){
this.scores = new ArrayList<Integer>();
this.fiveCount = 0;
this.fourCount = 0;
this.threeCount = 0;
this.twoCount = 0;
this.oneCount = 0;
this.zeroCount = 0;
}
public void addScore(int score){
scores.add(score);
if (score >= 0 && score <= 29) {
this.zeroCount++;
this.totalCount++;
} else if (score >= 30 && score <= 34) {
this.oneCount++;
this.totalCount++;
} else if (score >= 35 && score <= 39) {
this.twoCount++;
this.totalCount++;
} else if (score >= 40 && score <= 44) {
this.threeCount++;
this.totalCount++;
} else if (score >= 45 && score <= 49) {
this.fourCount++;
this.totalCount++;
} else if (score >= 50 && score <= 60) {
this.fiveCount++;
this.totalCount++;
} else {
return;
}
}
public void printDistribution(){
System.out.println("Grade Distribution:");
System.out.print("5: ");
for(int i =0; i < this.fiveCount; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("4: ");
for(int i =0; i < this.fourCount; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("3: ");
for(int i =0; i < this.threeCount; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("2: ");
for(int i =0; i < this.twoCount; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("1: ");
for(int i =0; i < this.oneCount; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("0: ");
for(int i =0; i < this.zeroCount; i++){
System.out.print("*");
}
System.out.println("");
System.out.println("Acceptance percentage: " + (double)100*(totalCount - zeroCount)/totalCount);
}
}
| [
"[email protected]"
] | |
bb80a197572c024453b34edaecd041f2f39f95d1 | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /IntroClassJava/dataset/digits/d6364e6e98a5c96387950d5b3e6206ba9d57628ab2ad0f2cd05ea7af3b818ed03e514157fe4c64e264a0ac9df0840028e0c5a8fd3d096f5ab93bffba61f23812/000/mutations/31/digits_d6364e6e_000.java | 4884a0c4597f6b20cc1c8ee306f4bb9cad34c9a2 | [] | 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,252 | 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_d6364e6e_000 {
public java.util.Scanner scanner;
public String output = "";
public static void main (String[]args) throws Exception {
digits_d6364e6e_000 mainClass = new digits_d6364e6e_000 ();
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 input = new IntObj (), display = new IntObj ();
output += (String.format ("Enter an integer > "));
input.value = scanner.nextInt ();
output += (String.format ("\n"));
if (input.value < 0) {
input.value = input.value * (-1);
while ((input.value / 10) >= 1) {
display.value = input.value % 10;
output += (String.format ("%d\n", display.value));
input.value = input.value / 10;
}
output += (String.format ("-%d\n", input.value % 10));
output += (String.format ("That's all, have a nice day!\n"));
if (true)
return;;
}
while ((input.value % 10) >= 1) {
display.value = (input.value) / 10;
output += (String.format ("%d\n", display.value));
input.value = input.value / 10;
}
output += (String.format ("That's all, have a nice day!\n"));
if (true)
return;;
}
}
| [
"[email protected]"
] | |
f25fbfb973c01e1d9343a18f681a24d5b0715487 | 7894522cc24247e1b7e17a11c8d551e09fc3e74b | /app/src/test/java/android/ua/testapp/ExampleUnitTest.java | 9a0237bbaaa19445d48d20d76a116a0ef3958717 | [
"MIT"
] | permissive | gkiryaziev/android-test-work | 85e546d69befe404d0f36888a1457af0fbf29a7b | 884d2f30c61b07fc8489eb369a1ccba58bc6f027 | refs/heads/master | 2016-09-14T07:55:45.620134 | 2016-05-17T17:15:29 | 2016-05-17T17:15:29 | 59,042,238 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 311 | java | package android.ua.testapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
9c8159ceb51a8d085e808b9fcda60d5eeac4a768 | 8d3fb66b32b9520c3d8af8c0b1907d39c46d99c3 | /src/com/javaex/problem03/MusicPhone.java | 2ca4df48335fac8c907202719ca45f813f5e5e02 | [] | no_license | moonhjhj/javapractice04 | a91fe76b2f51c90cd77577496d24bffed287fb12 | 30713f9b6f1dd4125bc4b0db2767b70360886e83 | refs/heads/master | 2020-03-09T11:50:04.227182 | 2018-04-09T12:48:51 | 2018-04-09T12:48:51 | 128,770,661 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 310 | java | package com.javaex.problem03;
public class MusicPhone extends Phone {
public void execute(String str) {
if ("음악".equals(str)) {
playMusic();
} else {
super.execute(str);
}
}
protected void playMusic() {
System.out.println("Mp3플레이어에서 음악재생");
}
}
| [
"USER@HJ-AlldayGram"
] | USER@HJ-AlldayGram |
3f86fda79c7814945b8955c5f6373aee2f43b649 | 92aaba1637d8400b53a9e757077820f946cefaf7 | /src/main/java/Controller/ProfileController.java | f7881a13188a791c4a024562b7ffcb15b4e472fa | [] | no_license | anchit1501/ap2 | d75d92dad8c3d45fdd9d8e5b949d67a9e982478d | 22f17a92c1eb51a158c4e4c955e84d9f426631a2 | refs/heads/master | 2023-08-22T07:39:26.665671 | 2021-10-25T11:23:13 | 2021-10-25T11:23:13 | 419,165,403 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,892 | java | package Controller;
import DAO.ProfileDao;
import Model.ProfileModel;
import Utils.DatabaseUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class ProfileController implements Initializable {
@FXML
public Button saveButton;
@FXML
public Button cancelButton;
@FXML
public TextField firstName;
@FXML
public TextField lastName;
@Override
public void initialize(URL location, ResourceBundle resources) {
ProfileModel userProfile = null;
Integer userId = 1;
try {
userProfile = ProfileDao.getProfileData("1");
} catch (SQLException e) {
e.printStackTrace();
}
if (userProfile != null) {
firstName.setText(userProfile.getFirstName());
lastName.setText(userProfile.getLastName());
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Something went wrong");
alert.show();
}
saveButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
ProfileDao.updateProfile(firstName.getText(), lastName.getText(), userId);
DatabaseUtils.changeScene(event, "/view/dashboard.fxml", "Welcome", null);
}
});
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DatabaseUtils.changeScene(event, "/view/dashboard.fxml", "Login", null);
}
});
}
}
| [
"[email protected]"
] | |
61cc7fadf49574cea001a24fe812fabb2b8d813c | b31c10f45e69500c7a56c5c9ff18ad97d8058506 | /test4j.core/src/main/java/org/test4j/json/decoder/base/BaseDecoder.java | 4e326947cd56a7c8ddc1e0fc96169d29270c53f8 | [] | no_license | gegena/test4j | 2f02efa860f32564d6d16da0058067dfa87c99ae | bd8bc90a6efcf86ff47e4ce24b2916bf94958cf2 | refs/heads/master | 2021-01-15T12:03:16.093348 | 2013-10-09T02:27:26 | 2013-10-09T02:27:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,855 | java | package org.test4j.json.decoder.base;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.test4j.json.decoder.IDecoder;
import org.test4j.tools.commons.ClazzHelper;
/**
* json串解码器基类<br>
* 解码:从json字符串反序列为java对象<br>
* 加码:将java对象序列化为json字符串<br>
*
* @author darui.wudr
*
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class BaseDecoder implements IDecoder {
protected DecoderException getError(String value, String to) {
String msg = String.format("couldn't convert \"%s\" to %s", value, to);
return new DecoderException(msg);
}
protected DecoderException getError(String value, String to, Throwable e) {
String msg = String.format("couldn't convert \"%s\" to %s", value, to);
return new DecoderException(msg, e);
}
/**
* 获取第n个泛型变量,n从0开始
*
* @param type
* @param index
* @return
*/
protected Type getArgType(ParameterizedType type, int index) {
if (type == null || index < 0) {
return null;
}
Type[] types = type.getActualTypeArguments();
if (types == null || index >= types.length) {
return null;
}
return types[index];
}
protected Class getRawType(Type type, Class _default) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
Type raw = ((ParameterizedType) type).getRawType();
return this.getRawType(raw, _default);
} else {
return _default == null ? Object.class : _default;
}
}
protected boolean isInterfaceOrAbstract(Type type) {
Class raw = this.getRawType(type, null);
return ClazzHelper.isInterfaceOrAbstract(raw);
}
protected <T> T newInstance(Type type) {
Class claz = this.getRawType(type, null);
Object o = ClazzHelper.newInstance(claz);
return (T) o;
}
}
| [
"[email protected]"
] | |
986eda93ad33b2ced06985eae94d0b7bdd6caf83 | 84402562543bb23b931eec54bf78bc4067f7430d | /app/src/main/java/com/mahang/weather/common/Constants.java | 9714bf34d3ea577e541d26fcd7c27af27498b149 | [] | no_license | Justwen/MahangWeather | 24b10683d26698586881be33aeb04cc58dd4aa2c | 507eae88611135a12bf0920cfe15a51de11efe98 | refs/heads/master | 2020-12-30T13:45:59.388350 | 2018-02-04T08:46:51 | 2018-02-04T08:46:51 | 91,249,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 993 | java | package com.mahang.weather.common;
import android.net.Uri;
public interface Constants {
String DB_WEATHER = "weather";
String DB_CITY = "city";
String DB_AUTHORITY = "com.mahang.weather";
Uri DB_WEATHER_CONTENT_URL = Uri.parse("content://"
+ DB_AUTHORITY + "/" + DB_WEATHER);
Uri DB_CITY_CONTENT_URL = Uri.parse("content://"
+ DB_AUTHORITY + "/" + DB_CITY);
String DB_WEATHER_NAME = "weather.db";
String DB_CITY_LIST_DB = "citylist.db";
public static final String DEGREE_SIGN = "℃";
int REQUEST_CODE_CITY_LIST = 1;
int REQUEST_CODE_SETTINGS = 2;
int REQUEST_CODE_QUERY_CITY = 3;
int MSG_QUERY_WEATHER_SUCCESS = 2;
int MSG_QUERY_WEATHER_FAILURE = 3;
int MSG_UPDATE_WEATHER_SUCCESS = 5;
int MSG_UPDATE_WEATHER_FAILURE = 6;
int MSG_REQUEST_LOCATION_SUCCESS = 8;
int MSG_REQUEST_LOCATION_FAILURE = 9;
int MSG_QEQUEST_LOCATION = 7;
int MSG_GET_WEATHER = 1;
int MSG_FLAG_SUCCESS = 10;
int MSG_FLAG_FAILURE = 11;
}
| [
"[email protected]"
] | |
0ebca5ea7cfec4ba9c6800ee0008b49654cc50e3 | 37d921910abc93f80b856c2c715c7f75728497f3 | /languagebasics/CaseConvert.java | 53be901319692bf1954af772da13dd54b3383dcc | [] | no_license | vedashree7/WTN3 | ace74c0beb13a168c263b631e19a4eecf280eab2 | 0ae3caa0e7fb8e89e20e06824dc897e68910cc9c | refs/heads/master | 2022-11-11T12:14:57.469233 | 2020-07-04T02:10:29 | 2020-07-04T02:10:29 | 271,693,925 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | package com.wipro.languagebasics;
public class CaseConvert {
public static void main(String[] args) {
char alphabet='C';
char converted;
if (alphabet>='a'&&alphabet<='z')
{
converted=(char) (alphabet-32);
System.out.println(converted);
}
if (alphabet>='A'&&alphabet<='Z')
{
converted=(char) (alphabet+32);
System.out.println(converted);
}
}
}
| [
"[email protected]"
] | |
2b7c382efbb9c0b8ffc3c3b47dfa582eae424ee0 | 3e7954715a32ed187cff38e1eeafd7e938e72cfc | /captura/src/main/java/camiwilliams/captura/controller/CapturaController.java | 8aa43b6ade70b4ef4f500ab5a41c529fa0722e50 | [] | no_license | CamiWilliams/captura | 13e31cfd7ea64d8b20731d4e2b6b21fab8566fb3 | 8b6d5fc4c5d295aef3ee00220a4747fc12b34e27 | refs/heads/master | 2020-04-12T06:53:55.320404 | 2015-10-24T19:07:22 | 2015-10-24T19:07:22 | 41,968,102 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,263 | java | package camiwilliams.captura.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.clarifai.api.ClarifaiClient;
import com.clarifai.api.RecognitionRequest;
import com.clarifai.api.RecognitionResult;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
import camiwilliams.captura.Authenticator;
import camiwilliams.captura.objects.LanguageDictionary;
import camiwilliams.captura.objects.User;
import camiwilliams.captura.objects.Word;
@Controller
public class CapturaController {
private static String APP_ID = "EOMWfJk7qN516eOnS4K11J-PCiCGYf1qQ1B5U-up";
private static String APP_SECRET = "vTRZoqMudBHKobLHzYNxGlQjVv2j8LlYJ1514vcs";
private static Authenticator authenticator = new Authenticator();
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView handleIndex(Model map) {
authenticator.removeCurrentUser();
String message = "";
return new ModelAndView("index", "message", message);
}
@RequestMapping(value = "/login_error", method = RequestMethod.POST)
public ModelAndView handleLoginError(Model map) {
String message = "";
return new ModelAndView("login_error", "message", message);
}
@RequestMapping(value = "/new_user", method = RequestMethod.GET)
public ModelAndView handleNewUser(Model map) {
String message = "";
return new ModelAndView("new_user", "message", message);
}
@RequestMapping(value = "/home", method = RequestMethod.POST)
public ModelAndView handleHomePOST(Model map) {
return handleHomeGET(map);
}
@RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView handleHomeGET(Model map) {
try {
User user = authenticator.getCurrentUser();
String message = user.getName();
return new ModelAndView("home", "message", message);
} catch (NullPointerException e) {
return new ModelAndView("home", "message", "Guest");
}
}
@RequestMapping(value = "/settings", method = RequestMethod.GET)
public ModelAndView handleSettings(Model map) {
try {
User user = authenticator.getCurrentUser();
List<LanguageDictionary> dictionaries = user.getDictionaries();
String removeLanguages = "";
if(dictionaries.size() == 0) {
removeLanguages = "No dictionaries to remove!";
} else {
for(LanguageDictionary ld : dictionaries) {
removeLanguages += "<option value='" + ld.getLanguage() + "'>" + ld.getLanguage() + "</option>";
}
}
return new ModelAndView("settings", "removeLanguages", removeLanguages);
} catch (NullPointerException e) {
return new ModelAndView("settings", "message", "You are a guest, please login to view this feature<br>");
}
}
@RequestMapping(value = "/settings", method = RequestMethod.POST)
public ModelAndView handleRemoveLanguage(@RequestParam("removeDictionary") String removeLang, Model map) {
try {
User user = authenticator.getCurrentUser();
LanguageDictionary dict = new LanguageDictionary(removeLang);
user.removeDictionary(dict); //TODO DB fix
return handleSettings(map);
} catch (NullPointerException e) {
return new ModelAndView("settings", "message", "You are a guest, please login to view this feature<br>");
}
}
@RequestMapping(value = "/dictionary", method = RequestMethod.GET)
public ModelAndView handleDictionary(Model map) {
try {
User user = authenticator.getCurrentUser();
Map<String, String> langs = new HashMap<String, String>(authenticator.getSupportedLanguages());
String addLanguages = "";
String message = "";
List<LanguageDictionary> dictionaries = user.getDictionaries();
for(LanguageDictionary ld : dictionaries) {
if(langs.containsKey((ld.getLanguage()))) {
langs.remove(ld.getLanguage());
}
}
for(String str : langs.keySet()) {
addLanguages += "<option value='" + str + "'>" + str + "</option>";
}
if(dictionaries.size() == 0) {
message = "<h4>No words in your dictionary!</h4>";
} else {
message = "<div class='list-group'>";
for(int i = dictionaries.size() - 1; i >= 0; i--) {
LanguageDictionary ld = dictionaries.get(i);
message += "<button type='submit' class='list-group-item' "
+ "name='langSelect' value='"+ i +"'>"
+ ld.getLanguage() + "</button>";
}
message += "</div>";
}
Map<String, String> model = new HashMap<String, String>();
model.put("addLanguages", addLanguages);
model.put("message", message);
return new ModelAndView("dictionary", "model", model);
} catch (NullPointerException e) {
return new ModelAndView("dictionary", "message", "You are a guest, please login to view this feature<br>");
}
}
@RequestMapping(value = "/dictionary", method = RequestMethod.POST)
public ModelAndView handleAddLangDictionary(@RequestParam("newDictionary") String newLang, Model map) {
try {
User user = authenticator.getCurrentUser();
LanguageDictionary dict = new LanguageDictionary(newLang);
user.addDictionary(dict);
authenticator.updateUser(user, user.getUsername());
return handleDictionary(map);
} catch (NullPointerException e) {
return new ModelAndView("dictionary", "message", "You are a guest, please login to view this feature<br>");
}
}
@RequestMapping(value = "/lang_dictionary", method = RequestMethod.POST)
public ModelAndView handleBranchDictionary(@RequestParam("langSelect") String lang_num, Model map) {
try {
System.out.println("Button clicked: " + lang_num);
User user = authenticator.getCurrentUser();
int index = Integer.parseInt(lang_num);
LanguageDictionary ld = user.getDictionaries().get(index);
Map<String, String> model = new HashMap<String, String>();
model.put("lang", ld.getLanguage());
model.put("message", prepDictionary(ld));
return new ModelAndView("lang_dictionary", "model", model);
} catch (NullPointerException e) {
return new ModelAndView("lang_dictionary", "message", "You are a guest, please login to view this feature<br>");
}
}
private String prepDictionary(LanguageDictionary ld) {
List<Word> dictionary = ld.getWords();
String lang = ld.getLanguage();
String country_code = authenticator.getSupportedLanguages().get(lang);
if(dictionary.size() == 0) {
return "<h4>No words in your dictionary!</h4>";
}
String message = "<ul class='list-group'>";
for(int i = dictionary.size() - 1; i >= 0; i--) {
Word w = dictionary.get(i);
message += "<li class='list-group-item'><div style='display:-webkit-box'>"
+ "<div id=\"lang\" style=\"display:none\">"
+ country_code + "</div><img width='100' src='" + w.getImage() + "'/> "
+ "<div id='word' class='word'>" + w.getString() + "</div>"
+ "<button type='button' class='form-control play'"
+ " onclick='play(\""+ w.getString() +"\",\""
+ country_code +"\")'><span class=\"glyphicon glyphicon-play\" "
+ "aria-hidden=\"true\"></button></div></li>";
}
message += "</ul>";
return message;
}
@RequestMapping(value = "/camera", method = RequestMethod.GET)
public ModelAndView handleCamera(Model map) {
try {
User user = authenticator.getCurrentUser();
List<LanguageDictionary> dictionaries = user.getDictionaries();
String work = "";
for(LanguageDictionary ld : dictionaries) {
work += "<option value='" + ld.getLanguage() + "'>" + ld.getLanguage() + "</option>";
}
final String message = work;
System.out.println(message);
return new ModelAndView("camera", "message", message);
} catch(NullPointerException e) {
return new ModelAndView("camera", "notwork", "You are a guest, please login to view this feature<br>");
}
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView handleFormUpload(@RequestParam("pic") MultipartFile file, @RequestParam("langSelect") String langDict, Model map) throws Exception{
try {
if (!file.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(file.getBytes(), false)));
ClarifaiClient clarifai = new ClarifaiClient(APP_ID, APP_SECRET);
List<RecognitionResult> results = clarifai.recognize(new RecognitionRequest(file.getBytes()));
authenticator.setCurrentImage(sb.toString());
authenticator.setCurrentLanguageDictionary(langDict);
authenticator.setCurrentWord(translate(results.get(0).getTags().get(0).getName(), langDict));
String curr_word = authenticator.getCurrentWord();
String curr_img = authenticator.getCurrentImage();
String message = "<img width='250' src='" + curr_img + "'>";
User user = authenticator.getCurrentUser();
LanguageDictionary curr_ld = getLangDict(user, langDict);
if(curr_ld == null) {
message = "<br><div style='text-align:center;'>"
+ "<h3>This branch did not work... Try again!</h3> </div><br><br>";
return new ModelAndView("home", "notwork", message);
}
String decide = "";
for(Word word : curr_ld.getWords()) {
if(word.getString().equals(curr_word)) {
decide += "<div id=\"lang\" style=\"display:none\">"
+ authenticator.getSupportedLanguages().get(curr_ld.getLanguage())
+ "</div><br>Your " + curr_ld.getLanguage() + " dictionary already contains this word!"
+ "<br> Would you like to update the picture to this one?<br><br><br><button type='button'"
+ "class='form-control' onclick='window.location.href=\"updateWord.html\"' "
+ "style='display: inline-block'>Update</button>";
Map<String, String> model = new HashMap<String, String>();
model.put("word", curr_word);
model.put("message", message);
model.put("decide", decide);
return new ModelAndView("upload", "model", model);
}
}
decide += "<div id=\"lang\" style=\"display:none\">"
+ authenticator.getSupportedLanguages().get(curr_ld.getLanguage())
+ "</div><br>Your " + curr_ld.getLanguage() + " dictionary does not contain this word!"
+ "<br>Would you like to add this word to your " + curr_ld.getLanguage()
+ " dictionary?<br><br><br><button type='button' class='form-control' "
+ "onclick='window.location.href=\"addWord.html\"' style='display: inline-block'>Add</button>";
Map<String, String> model = new HashMap<String, String>();
model.put("word", curr_word);
model.put("message", message);
model.put("decide", decide);
return new ModelAndView("upload", "model", model);
}
String message = "<br><div style='text-align:center;'>"
+ "<h3>This image did not work... Try again!</h3> </div><br><br>";
return new ModelAndView("home", "notwork", message);
} catch (NullPointerException e) {
return new ModelAndView("upload", "message", "You are a guest, please login to view this feature<br>");
}
}
private LanguageDictionary getLangDict(User user, String langDict) {
List<LanguageDictionary> branches = user.getDictionaries();
LanguageDictionary curr_dict = null;
for(LanguageDictionary ld : branches) {
if(ld.getLanguage().equals(langDict)) {
curr_dict = ld;
break;
}
}
return curr_dict;
}
@RequestMapping(value = "/addWord", method = RequestMethod.GET)
public ModelAndView handleAddWord(Model map) {
try {
User user = authenticator.getCurrentUser();
String curr_word = authenticator.getCurrentWord();
String curr_img = authenticator.getCurrentImage();
LanguageDictionary curr_ld = getLangDict(user, authenticator.getCurrentLanguageDictionary());
Word dic = new Word(curr_word, curr_img);
curr_ld.addWord(dic);
Map<String, String> model = new HashMap<String, String>();
model.put("lang", curr_ld.getLanguage());
model.put("message", prepDictionary(curr_ld));
return new ModelAndView("addWord", "model", model);
} catch (NullPointerException e) {
return new ModelAndView("addWord", "message", "You are a guest, please login to view this feature<br>");
}
}
@RequestMapping(value = "/updateWord", method = RequestMethod.GET)
public ModelAndView handleUpdateWord(Model map) {
try {
User user = authenticator.getCurrentUser();
String curr_word = authenticator.getCurrentWord();
String curr_img = authenticator.getCurrentImage();
LanguageDictionary curr_ld = getLangDict(user, authenticator.getCurrentLanguageDictionary());
Word word = new Word(curr_word, curr_img);
curr_ld.removeWord(word);
curr_ld.addWord(word);
Map<String, String> model = new HashMap<String, String>();
model.put("lang", curr_ld.getLanguage());
model.put("message", prepDictionary(curr_ld));
return new ModelAndView("updateWord", "model", model);
} catch (NullPointerException e) {
return new ModelAndView("updateWord", "message", "You are a guest, please login to view this feature<br>");
}
}
public String translate(String word, String lang) throws Exception {
Translate.setClientId("captura");
Translate.setClientSecret("9AnUiVone9beKHlpardalpp2qcIWSzFtdvPamXgVN28=");
//String OAuth = Translate.getToken("captura", "9AnUiVone9beKHlpardalpp2qcIWSzFtdvPamXgVN28");
String translation = word;
if(lang.equals("Spanish")) {
translation = Translate.execute(word, Language.ENGLISH, Language.SPANISH);
} else if(lang.equals("French")) {
translation = Translate.execute(word, Language.ENGLISH, Language.FRENCH);
} else if(lang.equals("German")) {
translation = Translate.execute(word, Language.ENGLISH, Language.GERMAN);
}
return translation;
}
}
| [
"[email protected]"
] | |
8b693c33ca9b618ce9564798bb8384380b019c11 | bf1e3f790a5dda54a0655f5153ab1c838068b0a7 | /src/main/java/com/luizfelipe/cursomc/repositories/EnderecoRepository.java | a286405fd8feeab28f4f8de46be57b3b4504a321 | [] | no_license | luizfelipew/cursomc | ba8fbb0eab0efaea5aa6ea8869784ca7a1096fce | d5e0e692c8ddc25fddaaed408011822d14209fae | refs/heads/master | 2021-04-29T16:45:51.085122 | 2018-03-20T14:49:03 | 2018-03-20T14:49:03 | 121,655,821 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 298 | java | package com.luizfelipe.cursomc.repositories;
import com.luizfelipe.cursomc.domain.Endereco;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EnderecoRepository extends JpaRepository<Endereco, Integer>{
}
| [
"[email protected]"
] | |
d24af090e094e3a4dc5db4aae842b403a2477351 | 3ff2a9e3f8a2dc476efdd602c76140c79c4a72ac | /SNS/src/main/java/com/qinqiang/model/Feed.java | 7641d9690fd96ffab40b4c904fab840a0e3275a4 | [] | no_license | 7-function/SNS | bb651377f62196b77ebfbc93764467e2e3aef514 | cabb2f2a63206e2431f3b91c469542f9cbb01b95 | refs/heads/master | 2020-11-28T23:41:28.270701 | 2019-09-03T12:56:15 | 2019-09-03T12:56:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,216 | java | package com.nowcoder.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
import java.util.Map;
public class Feed {
private int id;
private int type;
private int userId;
private Date createdDate;
private String data;
private JSONObject dataJSON = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getData() {
return data;
}
//方便前端直接读取vo.username等data中的属性
public void setData(String data) {
this.data = data;
dataJSON = JSONObject.parseObject(data);
}
public String get(String key) {
return dataJSON == null ? null : dataJSON.getString(key);
}
}
| [
"[email protected]"
] | |
5a0ef358ece97e1091db3b57e08bfb152511ffe7 | cdde2b8592b7b38e87d5c2ea7626e27bfa2db71a | /src/main/java/enums/Suit.java | d3eaa20ca7cabb1f6845eb32a8f7653cbdc62d7d | [] | no_license | abazlinton/BlackJack | d2686d0f9b021f4a5fcf88b19cef83ac92b07d1a | 38007df49ed11a2056aac87ed480e50f322fa862 | refs/heads/master | 2021-01-04T11:51:34.129717 | 2020-02-17T23:03:28 | 2020-02-17T23:03:28 | 240,534,591 | 0 | 0 | null | 2020-10-13T19:33:00 | 2020-02-14T15:06:28 | Java | UTF-8 | Java | false | false | 85 | java | package enums;
public enum Suit {
HEARTS,
CLUBS,
DIAMONDS,
SPADES
}
| [
"[email protected]"
] | |
e79833f5a7ac7dc40ef3f47a7dc92c6a8216fefb | 21dc5d0ec5407e388c57f9657f571996c8ea665e | /jt-dubbo-web/target/tomcat/work/Tomcat/localhost/_/org/apache/jsp/WEB_002dINF/views/success_jsp.java | 655ff191a48930dcd459b3acf9a0fb06facf073d | [] | no_license | yangrenjie00/1807 | c1f8bc8e50e2ed9a728743d9ca48f56172f3366b | 465ae309ad960cda1f0c61734572a296b964cc6d | refs/heads/master | 2020-04-10T15:28:19.724196 | 2018-12-21T07:21:55 | 2018-12-21T07:21:55 | 161,110,782 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,271 | java | /*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.47
* Generated at: 2018-11-19 07:09:05 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp.WEB_002dINF.views;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class success_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
out.write(" <head>\r\n");
out.write(" <meta http-equiv=\"pragma\" content=\"no-cache\" />\r\n");
out.write(" <meta http-equiv=\"cache-control\" content=\"no-cache\" />\r\n");
out.write(" <meta http-equiv=\"expires\" content=\"0\" /> \r\n");
out.write(" <meta name=\"format-detection\" content=\"telephone=no\" /> \r\n");
out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\" /> \r\n");
out.write(" <meta name=\"format-detection\" content=\"telephone=no\" />\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n");
out.write(" <link type=\"text/css\" rel=\"stylesheet\" href=\"/css/base.css\" />\r\n");
out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/css/purchase.base.2012.css\" />\r\n");
out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/css/purchase.sop.css\" />\r\n");
out.write(" <title>订单成功页面 - 京淘商城</title>\r\n");
out.write(" <script type=\"text/javascript\" src=\"/js/jquery-1.2.6.min.js\"></script>\r\n");
out.write(" <script type=\"text/javascript\" src=\"/js/base-2011.js\" charset=\"utf-8\"></script>\r\n");
out.write(" <script type=\"text/javascript\" src=\"/js/jquery.cookie.js\" charset=\"utf-8\"></script>\r\n");
out.write(" <script type=\"text/javascript\" src=\"/js/jt.js\" charset=\"utf-8\"></script>\r\n");
out.write("</head> <body id=\"mainframe\">\r\n");
out.write("<!--shortcut start-->\r\n");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "../commons/shortcut.jsp", out, false);
out.write("<!--shortcut end-->\r\n");
out.write("<div class=\"w\" id=\"headers\">\r\n");
out.write("\t\t<div id=\"logo\"><a href=\"http://www.jd.com/\"><img alt=\"京淘商城\" src=\"/images/jt-logo.png\"></a></div>\r\n");
out.write("\t\t<ul class=\"step\" id=\"step3\">\r\n");
out.write("\t\t\t<li class=\"fore1\">1.我的购物车<b></b></li>\r\n");
out.write("\t\t\t<li class=\"fore2\">2.填写核对订单信息<b></b></li>\r\n");
out.write("\t\t\t<li class=\"fore3\">3.成功提交订单</li>\r\n");
out.write("\t\t</ul>\r\n");
out.write("\t\t<div class=\"clr\"></div>\r\n");
out.write("</div>\r\n");
out.write("<div class=\"w\" id=\"safeinfo\"></div><!--父订单的ID-->\r\n");
out.write("<div class=\"w main\">\r\n");
out.write("\t<div class=\"m m3 msop\">\r\n");
out.write(" <div class=\"mt\" id=\"success_tittle\"><s class=\"icon-succ02\"></s><h3 class=\"ftx-02\">感谢您,订单提交成功!</h3>\r\n");
out.write("\t\t</div>\r\n");
out.write("\t\t<div class=\"mc\" id=\"success_detail\">\t\r\n");
out.write("\t\t <ul class=\"list-order\">\r\n");
out.write("\t\t\t <li class=\"li-st\">\r\n");
out.write("\t\t\t\t\t<div class=\"fore1\">订单号:<a href=\"javascript:void(0)\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${order.orderId }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
out.write("</a></div>\r\n");
out.write("\t\t\t\t\t<!-- 货到付款 -->\r\n");
out.write("\t\t\t\t\t<div class=\"fore2\">货到付款:<strong class=\"ftx-01\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${order.payment}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
out.write("元</strong></div>\r\n");
out.write("\t\t\t\t\t<div class=\"fore3\">\r\n");
out.write("\t\t\t\t\t \t京淘快递 送货时间: 预计 ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${date}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
out.write(" 送达 \r\n");
out.write("\t\t\t\t\t</div>\r\n");
out.write("\t\t\t\t</li>\r\n");
out.write("\t\t\t</ul>\r\n");
out.write("\t\t<!-- 在线支付按钮 -->\r\n");
out.write("\t\t\t\t<div id=\"bookDiv\"></div>\r\n");
out.write(" \t\t\t\t\t<p class=\"i-tips01\">\r\n");
out.write("\t\t\t\t \t您的订单已经在处理中,发货后订单内容会显示承运人联系方式,如有必要您可以联系对方\r\n");
out.write(" \t\t</p>\r\n");
out.write("\t\t </div>\r\n");
out.write("\t</div>\r\n");
out.write("</div>\r\n");
out.write(" <div class=\"w\">\r\n");
out.write("\t<!-- links start -->\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "../commons/footer-links.jsp", out, false);
out.write("<!-- links end -->\r\n");
out.write("</div><!-- footer end -->\r\n");
out.write(" </body> \r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| [
"[email protected]"
] | |
75b7d135bd368b4ae9c609253eb9f83da55799be | 0c1d5547a78bc4f05c4b1ccc2a63164c8005f178 | /src/main/java/xyz/phanta/rosjay/transport/srv/package-info.java | 662775dd1c2e43c86aa56392e495fb6ef827b14d | [
"JSON"
] | permissive | phantamanta44/RosJay | 9e7e56606b4399fd522e430a97971e3edf45b24f | 3e7bbcc3459abd866ba05a78808f7b1ae8d11326 | refs/heads/master | 2020-09-11T20:22:32.776577 | 2019-11-18T23:08:46 | 2019-11-18T23:08:46 | 222,180,344 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 93 | java | @NothingNull
package xyz.phanta.rosjay.transport.srv;
import xyz.phanta.jsr305.NothingNull;
| [
"[email protected]"
] | |
d40fb6c83bab0f5ddafe6041b26f4ed2c2a0e2a9 | 6851a24f564a425b2212dfd246e0461777069338 | /platform-java/src/main/java/com/zhongtongnev/modules/sys/service/SysRoleMenuService.java | 67fe073c564d6da1105995fda5ba19701fe209cf | [] | no_license | DreamofbecomingIronMan/SnatchRedEnvelopes | 65e9f7801246ec270f2ce7c768fb7127605d4a77 | 4225464f4ec09ab6884cc0c776cc05454c3671d1 | refs/heads/master | 2022-11-26T02:50:12.428716 | 2019-07-27T06:10:58 | 2019-07-27T06:10:58 | 199,123,694 | 0 | 0 | null | 2022-11-16T09:58:06 | 2019-07-27T06:04:14 | Java | UTF-8 | Java | false | false | 575 | java | package com.zhongtongnev.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zhongtongnev.modules.sys.entity.SysRoleMenuEntity;
import java.util.List;
/**
* 角色与菜单对应关系
*/
public interface SysRoleMenuService extends IService<SysRoleMenuEntity> {
void saveOrUpdate(Long roleId, List<Long> menuIdList);
/**
* 根据角色ID,获取菜单ID列表
*/
List<Long> queryMenuIdList(Long roleId);
/**
* 根据角色ID数组,批量删除
*/
int deleteBatch(Long[] roleIds);
}
| [
"[email protected]"
] | |
18ed0500579fbdbd3764e72daf0648d7a664683b | 02183ceb7fcf19e59bd1a041343013c68b50a6b8 | /src/com/yuanneng/book/register/action/WeChatPayStatusConfirmActon.java | ea715c3cfbf1847debf70702f5d5d670511678c8 | [] | no_license | flyqxf/book | 7f63dc9081874f6ecb36933222f636d523dd181c | ef1aa37a72aa8bbeb11d5e2f51f1a829ed014086 | refs/heads/master | 2020-04-28T09:02:19.900596 | 2019-03-12T06:53:02 | 2019-03-12T06:53:02 | 175,151,798 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,386 | java | /*
* @(#)InitTaskAction.java
*/
package com.yuanneng.book.register.action;
import java.io.BufferedOutputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import com.demo.WxPayResult;
import com.yuanneng.book.common.action.CommonAction;
public class WeChatPayStatusConfirmActon extends CommonAction {
/**
* 序列化
*/
private static final long serialVersionUID = 1L;
public static Logger logger = Logger.getLogger(WeChatPayStatusConfirmActon.class);
//private static Log log = LogFactory.getLog(WeChatPayAction.class);
private String resJson = null;
private String orderno = null;
private String msg = null;
@Override
public String doMain() throws Exception{
// HttpSession session = this.getSession();
// UserBean userBean = (UserBean) session.getAttribute("registerUserBean");
HttpServletRequest request = this.getRequest();
HttpServletResponse response = this.getResponse();
//示例报文
// String xml = "<xml><appid><![CDATA[wxb4dc385f953b356e]]></appid><bank_type><![CDATA[CCB_CREDIT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1228442802]]></mch_id><nonce_str><![CDATA[1002477130]]></nonce_str><openid><![CDATA[o-HREuJzRr3moMvv990VdfnQ8x4k]]></openid><out_trade_no><![CDATA[1000000000051249]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[1269E03E43F2B8C388A414EDAE185CEE]]></sign><time_end><![CDATA[20150324100405]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1009530574201503240036299496]]></transaction_id></xml>";
String inputLine;
String notityXml = "";
String resXml = "";
try {
while ((inputLine = request.getReader().readLine()) != null) {
notityXml += inputLine;
}
request.getReader().close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("接收到的报文:" + notityXml);
Map m = parseXmlToList2(notityXml);
WxPayResult wpr = new WxPayResult();
wpr.setAppid(m.get("appid").toString());
wpr.setBankType(m.get("bank_type").toString());
wpr.setCashFee(m.get("cash_fee").toString());
wpr.setFeeType(m.get("fee_type").toString());
wpr.setIsSubscribe(m.get("is_subscribe").toString());
wpr.setMchId(m.get("mch_id").toString());
wpr.setNonceStr(m.get("nonce_str").toString());
wpr.setOpenid(m.get("openid").toString());
wpr.setOutTradeNo(m.get("out_trade_no").toString());
wpr.setResultCode(m.get("result_code").toString());
wpr.setReturnCode(m.get("return_code").toString());
wpr.setSign(m.get("sign").toString());
wpr.setTimeEnd(m.get("time_end").toString());
wpr.setTotalFee(m.get("total_fee").toString());
wpr.setTradeType(m.get("trade_type").toString());
wpr.setTransactionId(m.get("transaction_id").toString());
//WeChatPayRes weChatPayRes = WeChatPayRes.getSingle();
if("SUCCESS".equals(wpr.getResultCode())){
//支付成功
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
logger.debug(resXml);
logger.debug("支付成功");
response.setContentType("text/xml");
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
// UserBean userBean = new UserBean();
// userBean.setOrderId(wpr.getOutTradeNo());
// userBean.setDel_flg("0");
// registerService.updateUserSts(userBean);
//weChatPayRes.setSts(wpr.getOutTradeNo(), "1");
msg = "注册成功!";
return SUCCESS;
}else{
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
logger.debug(resXml);
logger.debug("支付失败:"+m.get("err_code").toString()+"----订单号:"+m.get("out_trade_no").toString()+"----支付失败时间::"
+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
response.setContentType("text/xml");
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
//weChatPayRes.setSts(wpr.getOutTradeNo(), "2");
//该页面可做页面美工编辑
msg = "缴费失败,请重新操作!";
return SUCCESS;
}
}
/**
* description: 解析微信通知xml
*
* @param xml
* @return
* @author ex_yangxiaoyi
* @see
*/
@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
private static Map parseXmlToList2(String xml) {
Map retMap = new HashMap();
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
// 通过输入源构造一个Document
Document doc = (Document) sb.build(source);
Element root = doc.getRootElement();// 指向根节点
List<Element> es = root.getChildren();
if (es != null && es.size() != 0) {
for (Element element : es) {
retMap.put(element.getName(), element.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retMap;
}
/**
* @return the resJson
*/
public String getResJson() {
return resJson;
}
/**
* @param resJson the resJson to set
*/
public void setResJson(String resJson) {
this.resJson = resJson;
}
/**
* @return the orderno
*/
public String getOrderno() {
return orderno;
}
/**
* @param orderno the orderno to set
*/
public void setOrderno(String orderno) {
this.orderno = orderno;
}
/**
* @return the msg
*/
public String getMsg() {
return msg;
}
/**
* @param msg the msg to set
*/
public void setMsg(String msg) {
this.msg = msg;
}
}
| [
"[email protected]"
] | |
01898a4765b69ecc3fa905457b73ec0657c303a9 | f01e0bac7663f1e9435e74ec96327cb1ee8b65d8 | /zkw-fed-web-master/src/main/java/com/zkw/fedweb/controller/VideoController.java | 6ba7c3371d17999a78836c99085bfceea4cf7cb4 | [] | no_license | pijunqi/wyx | 3f424b337a19dd1e121d55e371ff2e674a87fb48 | b5cd1a726476d365121d9ce5a1d99fcc04327180 | refs/heads/master | 2022-07-27T01:44:27.116463 | 2019-08-05T02:20:40 | 2019-08-05T02:20:40 | 200,566,246 | 0 | 0 | null | 2022-06-21T01:36:12 | 2019-08-05T02:11:00 | Java | UTF-8 | Java | false | false | 768 | java | package com.zkw.fedweb.controller;
import com.zkw.fedweb.dao.po.Video;
import com.zkw.fedweb.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/videos")
public class VideoController {
@Resource
private VideoService videoService;
//单视频链接表
@GetMapping("/video")
public List<Video> videos(@Param("id")Integer id) {
List<Video> videos = videoService.video(id);
return videos;
}
}
| [
"[email protected]"
] | |
6605244b46613abf76836ffe9610c87dd01c0105 | 6f150c212f0849afbaaa226b1d722b0ea03c13d9 | /Problems/Check burgs/src/Main.java | 4dbf9bfc4e92655a24a210638337df300da808a2 | [] | no_license | chsvbomi/Simple-Chatty-Bot | b03af4664231519ef9fcee6320765180414fb750 | 1a53786544db4d2618996473d057ea9836a1675e | refs/heads/main | 2023-01-10T14:24:18.621781 | 2020-11-10T07:52:12 | 2020-11-10T07:52:12 | 311,584,351 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 222 | java | import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String city=scanner.nextLine();
System.out.println(city.endsWith("burg"));
}
} | [
"[email protected]"
] | |
4a20e32617b3b40ce46ccdaa9a795a5f09b0c0d0 | 776bf09be5157b847bb9295186ce109a001bc613 | /bundle/src/main/java/com/adobe/acs/commons/mcp/impl/processes/ReferenceFinder.java | af0158359d2d40d7be7eca33f128c9ad22e7e2e3 | [
"Apache-2.0"
] | permissive | YentlFrickx/acs-aem-commons | 8ec23f9a0bbbcde12dc5713f9ffb13bcabe34c33 | c43098092ab0845ecf02167f0cb033f12ab1a28b | refs/heads/master | 2023-04-02T19:21:40.514048 | 2021-02-22T15:38:41 | 2021-02-22T15:38:41 | 220,208,382 | 0 | 0 | Apache-2.0 | 2023-03-31T16:19:27 | 2019-11-07T10:17:16 | Java | UTF-8 | Java | false | false | 4,922 | java | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2019 Adobe
* %%
* 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.
* #L%
*/
package com.adobe.acs.commons.mcp.impl.processes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.jcr.query.Query;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adobe.acs.commons.mcp.impl.processes.renovator.Util;
import com.day.cq.dam.api.DamConstants;
import com.day.cq.wcm.api.NameConstants;
/**
* Class for finding references to content.
*/
public class ReferenceFinder {
private static final Logger log = LoggerFactory.getLogger(ReferenceFinder.class);
private static Resource getClosestPublishableType(Resource resource) {
if (NameConstants.NT_PAGE.equals(resource.getResourceType())
|| DamConstants.NT_DAM_ASSET.equals(resource.getResourceType())) {
return resource;
} else if (resource.getParent() != null) {
return getClosestPublishableType(resource.getParent());
} else {
return null;
}
}
private final List<Pair<String, String>> allReferences = new ArrayList<>();
private final boolean exact;
private final List<String> publishedReferences = new ArrayList<>();
private final String reference;
public ReferenceFinder(ResourceResolver resolver, String reference, String searchRoot, boolean exact) {
this.exact = exact;
this.reference = reference;
Set<String> paths = new HashSet<>();
findReferences(resolver, reference, searchRoot).forEach(r -> {
if (!paths.contains(r.getPath())) {
checkReferences(r);
paths.add(r.getPath());
}
});
}
private void addReference(Resource resource, String key) {
Resource parent = getClosestPublishableType(resource);
if (parent != null && Util.isActivated(resource.getResourceResolver(), parent.getPath())) {
this.publishedReferences.add(parent.getPath());
this.allReferences.add(new ImmutablePair<String, String>(resource.getPath(), key));
} else {
this.allReferences.add(new ImmutablePair<String, String>(resource.getPath(), key));
}
}
private void checkReferences(Resource resource) {
log.trace("Checking for references in resource {}", resource);
ValueMap properties = resource.getValueMap();
properties.keySet().forEach(k -> {
if (properties.get(k) instanceof String) {
checkStringReference(resource, properties, k);
} else if (properties.get(k) instanceof String[]) {
checkStringArrayReference(resource, properties, k);
}
});
}
private void checkStringArrayReference(Resource resource, ValueMap properties, String k) {
for (String v : properties.get(k, String[].class)) {
if (reference.equals(v) || (!exact && v != null && v.contains(reference))) {
log.trace("Found reference in property {}@{}", resource.getPath(), k);
addReference(resource, k);
break;
}
}
}
private void checkStringReference(Resource resource, ValueMap properties, String k) {
String value = properties.get(k, "");
if (reference.equals(value) || (!exact && value.contains(reference))) {
log.trace("Found reference in property {}@{}", resource.getPath(), k);
addReference(resource, k);
}
}
protected Stream<Resource> findReferences(ResourceResolver resolver, String reference, String searchRoot) {
log.trace("Finding references to {}", reference);
String query = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([" + searchRoot + "]) AND CONTAINS(s.*, '"
+ Text.escapeIllegalXpathSearchChars(reference) + "')";
log.trace("Checking for references with: {}", query);
Iterable<Resource> resources = () -> resolver.findResources(query, Query.JCR_SQL2);
return StreamSupport.stream(resources.spliterator(), false);
}
public List<Pair<String, String>> getAllReferences() {
return allReferences;
}
public List<String> getPublishedReferences() {
return publishedReferences;
}
} | [
"[email protected]"
] | |
7cc7b1876cc155dde1f587a054f5bc05b9c009b2 | f2c45b82f682e10e9578c6a6f01fcca221037835 | /src/main/java/tpavels/patterns/creational/singleton/App.java | 3e7fcdeb4749c8128e88fc67219eae63e02e3475 | [
"MIT"
] | permissive | tpavels/design-patterns-practice | 3cc2b9360b7d287edfe39129d2b6d97119bc8389 | f729a6c47fe553a1d1fb5dfd770a512097406208 | refs/heads/master | 2020-04-26T14:56:35.650096 | 2019-05-09T05:36:28 | 2019-05-09T05:36:28 | 173,631,439 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,133 | java | package tpavels.patterns.creational.singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class App {
public static void main(String[] args) {
ServiceSingleton service1 = ServiceSingleton.getInstance();
service1.setName("Test1");
System.out.println("service1: " + service1.getName());
ServiceSingleton service2 = ServiceSingleton.getInstance();
System.out.println("service2: " + service2.getName());
try {
Constructor<?> c = ServiceSingleton.class.getDeclaredConstructor();
if (!c.isAccessible()) {
c.setAccessible(true);
Object o = c.newInstance();
}
} catch (InvocationTargetException |
InstantiationException |
IllegalAccessException |
NoSuchMethodException e) {
e.printStackTrace();
}
try {
ServiceSingleton.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
9f93d4be322f51987fde5a701b9ba53ace2c5984 | ef4bdb9dfd6c7ffb6a865104059112a510d78e13 | /android/app/src/debug/java/com/boticarioblog/ReactNativeFlipper.java | 72165813ac668420f9deffb18b0cdfda328bcc86 | [] | no_license | Fmendescn/microblogging-boticario | a99280d40d659c0e66571af665584f3e66fb187d | 5343bad38924cebbe60c9a9a532b8c7a8022e0d9 | refs/heads/main | 2023-05-07T16:44:00.227747 | 2021-05-25T15:09:23 | 2021-05-25T15:09:23 | 365,513,593 | 0 | 0 | null | 2021-05-11T13:16:41 | 2021-05-08T12:52:00 | TypeScript | UTF-8 | Java | false | false | 3,268 | java | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.boticarioblog;
import android.content.Context;
import com.facebook.flipper.android.AndroidFlipperClient;
import com.facebook.flipper.android.utils.FlipperUtils;
import com.facebook.flipper.core.FlipperClient;
import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
import com.facebook.flipper.plugins.inspector.DescriptorMapping;
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.network.NetworkingModule;
import okhttp3.OkHttpClient;
public class ReactNativeFlipper {
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (FlipperUtils.shouldEnableFlipper(context)) {
final FlipperClient client = AndroidFlipperClient.getInstance(context);
client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
client.addPlugin(new ReactFlipperPlugin());
client.addPlugin(new DatabasesFlipperPlugin(context));
client.addPlugin(new SharedPreferencesFlipperPlugin(context));
client.addPlugin(CrashReporterPlugin.getInstance());
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
new NetworkingModule.CustomClientBuilder() {
@Override
public void apply(OkHttpClient.Builder builder) {
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
}
});
client.addPlugin(networkFlipperPlugin);
client.start();
// Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
// Hence we run if after all native modules have been initialized
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
if (reactContext == null) {
reactInstanceManager.addReactInstanceEventListener(
new ReactInstanceManager.ReactInstanceEventListener() {
@Override
public void onReactContextInitialized(ReactContext reactContext) {
reactInstanceManager.removeReactInstanceEventListener(this);
reactContext.runOnNativeModulesQueueThread(
new Runnable() {
@Override
public void run() {
client.addPlugin(new FrescoFlipperPlugin());
}
});
}
});
} else {
client.addPlugin(new FrescoFlipperPlugin());
}
}
}
}
| [
"[email protected]"
] | |
f7373d8e767f36f11aaa1022de3326a43dec1035 | 6a50e83e25ce8c571151b335400a4ddf1858e23d | /src/main/java/tech/saltyfish/ptcart/model/entity/ChannelEntity.java | 0c3748d0b3a2b0faf7e9237ca99381273a45d09f | [] | no_license | skaimid/pt-cart | 4a0497eb9328bff69a368917e699314fb0851fae | 42e43127dba915b0c529ac6de781e3411fb5a673 | refs/heads/main | 2023-02-28T00:44:11.508148 | 2021-02-05T02:36:00 | 2021-02-05T02:36:00 | 327,794,735 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,125 | java | package tech.saltyfish.ptcart.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
@Entity
public class ChannelEntity {
private @Id
@GeneratedValue
Long channelId;
private String channelName;
@ManyToOne()
private User ownedUser;
@OneToMany(mappedBy = "ownedChannelEntity", cascade = CascadeType.REMOVE)
private List<Link> linkSet;
public ChannelEntity() {
}
public ChannelEntity(String channelName) {
this.channelName = channelName;
}
public ChannelEntity(String channelName, User ownedUser) {
this.channelName = channelName;
this.ownedUser = ownedUser;
}
public Long getChannelId() {
return channelId;
}
public void setChannelId(Long id) {
this.channelId = id;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
@JsonIgnore
public User getOwnedUser() {
return ownedUser;
}
public void setOwnedUser(User ownedUser) {
this.ownedUser = ownedUser;
}
public List<Link> getLinkSet() {
return linkSet;
}
public void setLinkSet(List<Link> linkSet) {
this.linkSet = linkSet;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ChannelEntity)) return false;
ChannelEntity channelEntity = (ChannelEntity) o;
return channelId.equals(channelEntity.channelId) &&
channelName.equals(channelEntity.channelName) &&
ownedUser.equals(channelEntity.ownedUser);
}
@Override
public int hashCode() {
return Objects.hash(channelId, channelName, ownedUser);
}
@Override
public String toString() {
return "Channel{" +
"id=" + channelId +
", channelName='" + channelName + '\'' +
", user=" + ownedUser +
'}';
}
}
| [
"[email protected]"
] | |
220776dcbaf1a280a0431383ae96dfc11a11818a | a0a1ff168ed27e5ea7b8a96203ec1d93613d95fd | /src/com/csl/globalpay/ipm/msgptdfreply/msgptdf/TermId.java | 7b9d69a84fc086f5fccda9fd20625a7c55f157d7 | [] | no_license | taherkhalil/PracWebservice | 77046f70d3ce48176384bf25f979d4d155b33d03 | 363313b5b264ce70bd8d5d9b959eebd4e9b2e512 | refs/heads/master | 2021-01-18T17:00:17.403367 | 2017-03-31T04:59:17 | 2017-03-31T04:59:17 | 86,779,390 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,690 | java | /*
* @(#)TermId.java
* Created by CSL Studio (definition-schema) on 11/11/2016 01:06:52 PM
*/
package com.csl.globalpay.ipm.msgptdfreply.msgptdf;
import java.io.IOException;
import com.comforte.csl.cslapi.CSLInputStream;
import com.comforte.csl.cslapi.CSLOutputStream;
import com.comforte.csl.xmlutils.CSLTypes;
/** <code>TermId</code>
*
*/
public class TermId implements com.comforte.csl.cslapi.CSLStreamable
{
/* Members */
protected String id;
/** <code>TermId</code>
* Constructor
* @param characterEncoding this is for setting strings with CSLBaseData
* here we do not use it!
*/
public TermId(String characterEncoding)
{
setId(new String());
}
/** <code>TermId</code>
* Constructor
*/
public TermId()
{
this(null);
}
/* getter and setter */
/**
* <code>
* Id is a text String of16 bytes.
* </code>
*/
public String getId()
{
return id;
}
/**
* <code>
* Id is a text String of16 bytes.
* </code>
*/
public void setId(String theId)
{
id = theId;
}
/** <code>write</code>
* @param out
* @throws java.io.IOException,
*/
public void write(CSLOutputStream out) throws IOException
{
/* write all attribute values into out */
String help1 = null;
String help2 = null;
out.writeString(getId(),16, CSLTypes.PICX);
}
/** <code>read</code>
* @param in
* @throws java.io.IOException
*/
public void read(CSLInputStream in) throws IOException
{
/* read all attribute values*/
String help1 = null;
String help2 = null;
setId(in.readString(16));
}
}
| [
"[email protected]"
] | |
8e7aa37135e75604b2a9a42e05b095944cd66e07 | 0f23e31dc7a366a6951dfb277037da84d8d3107f | /src/dataModel/Edition.java | 0c1f79093c87ed76823549c1e8b6348d583dcd46 | [] | no_license | japius/Library | e6eade9ea81a026a82e70513fb2a312f8c101e71 | 73e18a7c0d0caa4894441162b63fce3ecc485551 | refs/heads/master | 2023-01-05T17:15:37.680776 | 2020-11-09T11:09:19 | 2020-11-09T11:09:19 | 308,346,111 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,300 | java | import java.sql.*;
import java.util.ArrayList;
public class Edition extends DataTable{
private long isbn;
private String editor;
private int year;
private long id_oeuvre;
private Oeuvre oeuvre;
private static final String basicSelect = "Select * from edition";
private Edition(ResultSet rs){
try{
isbn = rs.getLong("ISBN");
editor = rs.getString("editeur");
year = rs.getInt("annee");
id_oeuvre = rs.getLong("id_oeuvre");
}catch(SQLException e ){
e.printStackTrace();
// XXX a revoir
}
}
public Edition(){}
public void initFields(SqlRequest sqlRequest)throws SQLException{
oeuvre = Oeuvre.getOeuvreById(id_oeuvre,sqlRequest);
}
//Getters
public long getIsbn(){return isbn;}
public String getEditor(){return editor;}
public int getYear(){return year;}
public Oeuvre getOeuvre(){return oeuvre;}
public long getIdoeuvre(){return id_oeuvre;}
public String getAuthors(){return oeuvre != null ? oeuvre.getAuthors() : "";}
//Setters
public void setEdition(long isbn,String editor, int year, Oeuvre oeuvre){
this.isbn = isbn;
this.editor = editor;
this.year = year;
this.oeuvre = oeuvre;
this.id_oeuvre = oeuvre.getId();
}
//Récupération de la liste complete des editions
public static ArrayList<Edition> getListEdition(SqlRequest sqlRequest){
ArrayList<Edition> res = new ArrayList<Edition>();
String query = basicSelect;
try{
ResultSet rs = sqlRequest.executeQuery(query);
while(rs.next()){
Edition tmp = new Edition(rs);
tmp.initFields(sqlRequest);
res.add(tmp);
}
}catch(SQLException e){
e.printStackTrace();
}
return res;
}
//Recupération d'une edition
//Via ID
public static Edition getEditionById(long id, SqlRequest sqlRequest)throws SQLException{
ResultSet rs = getById(id,sqlRequest);
if(!rs.next())
return null;
Edition tmp = new Edition(rs);
tmp.initFields(sqlRequest);
return tmp;
}
private static ResultSet getById(long id, SqlRequest sqlRequest){
String query = basicSelect+" where ISBN ="+id;
return sqlRequest.executeQuery(query);
}
//Ajouter une edition
public int insertValue(SqlRequest sqlRequest){
int tmp = isValideIsbn(sqlRequest, isbn);
if(tmp<0) return tmp;
String query = String.format("Insert into edition(ISBN, editeur, annee, id_oeuvre) values ('%d', '%s', '%d', '%d')",
isbn, editor, year, id_oeuvre);
int res = sqlRequest.executeUpdate(query);
if(res < 0 ) return -999;
return res;
}
//Modifier une edition
public int updateValue(SqlRequest sqlRequest){
String query = String.format("UPDATE edition SET editeur = '%s', annee = '%d', id_oeuvre = '%d' where isbn = %d",
editor, year,id_oeuvre, isbn);
int res = sqlRequest.executeUpdate(query);
if(res < 0 ) return -999;
return res;
}
public static int isValideIsbn(SqlRequest sqlRequest, long isbn){
try{
if(getEditionById(isbn,sqlRequest) != null)
return -11;
}catch(SQLException e){
return -999;
}
return 0;
}
public String toString(){
return String.format("%s, %s, %s",editor, oeuvre.toString(), getAuthors());
}
public boolean equals(Edition item){
return item.isbn==isbn;
}
} | [
"[email protected]"
] | |
ea680487f3871ba200d33ce2bc1c9c30f28a119f | 4d6c00789d5eb8118e6df6fc5bcd0f671bbcdd2d | /src/main/java/com/alipay/api/domain/InteligentItemInfo.java | 1b3997191c66485de68b406515add746ba12a844 | [
"Apache-2.0"
] | permissive | weizai118/payment-alipay | 042898e172ce7f1162a69c1dc445e69e53a1899c | e3c1ad17d96524e5f1c4ba6d0af5b9e8fce97ac1 | refs/heads/master | 2020-04-05T06:29:57.113650 | 2018-11-06T11:03:05 | 2018-11-06T11:03:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,613 | java | package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 智能营销券的单品信息
*
* @author auto create
* @since 1.0, 2018-01-22 16:20:14
*/
public class InteligentItemInfo extends AlipayObject {
private static final long serialVersionUID = 7249985664265962341L;
/**
* 券适用的单品码列表
最少配置1个单品码
最多配置500个单品码
*/
@ApiListField("item_ids")
@ApiField("string")
private List<String> itemIds;
/**
* 单品图片列表
单品图片不能超过3张
*/
@ApiListField("item_imgs")
@ApiField("string")
private List<String> itemImgs;
/**
* 单品券详细介绍跳转链接
*/
@ApiField("item_link")
private String itemLink;
/**
* 单品名称
*/
@ApiField("item_name")
private String itemName;
/**
* 单品券说明
*/
@ApiField("item_text")
private String itemText;
/**
* 单品券适用的商品列表中,每一个商品最高可享受优惠的件数;
如:券适用于A,B两种商品,该字段设置为1,则用券A,B两种商品每种最多只有一件可享受优惠;
*/
@ApiField("max_discount_num")
private String maxDiscountNum;
/**
* 单品券适用商品列表中,每种商品享受优惠最低购买件数的门槛;
如:券适用于A,B两种商品,该字段设置为3,则A,B两种商品每种最少需要购买3件才可享受优惠;
*/
@ApiField("min_consume_num")
private String minConsumeNum;
/**
* 单品的原价,单位元
必须为合法金额类型字符串,如9.99
*/
@ApiField("original_price")
private String originalPrice;
/**
* 券适用SKU的最低消费金额门槛
如券适用A,B两个SKU,该字段设置的值为100,则订单中购买A,B两个SKU的合计金额需大于100元才可用券
*/
@ApiField("sku_min_consume")
private String skuMinConsume;
/**
* 如果一个单品券适用A,B,C三个单品,若设置了该字段为2,则在一笔交易中,A,B,C三个单品加起来最多只有俩件能够享受优惠
*/
@ApiField("total_max_discount_num")
private String totalMaxDiscountNum;
/**
* Gets item ids.
*
* @return the item ids
*/
public List<String> getItemIds() {
return this.itemIds;
}
/**
* Sets item ids.
*
* @param itemIds the item ids
*/
public void setItemIds(List<String> itemIds) {
this.itemIds = itemIds;
}
/**
* Gets item imgs.
*
* @return the item imgs
*/
public List<String> getItemImgs() {
return this.itemImgs;
}
/**
* Sets item imgs.
*
* @param itemImgs the item imgs
*/
public void setItemImgs(List<String> itemImgs) {
this.itemImgs = itemImgs;
}
/**
* Gets item link.
*
* @return the item link
*/
public String getItemLink() {
return this.itemLink;
}
/**
* Sets item link.
*
* @param itemLink the item link
*/
public void setItemLink(String itemLink) {
this.itemLink = itemLink;
}
/**
* Gets item name.
*
* @return the item name
*/
public String getItemName() {
return this.itemName;
}
/**
* Sets item name.
*
* @param itemName the item name
*/
public void setItemName(String itemName) {
this.itemName = itemName;
}
/**
* Gets item text.
*
* @return the item text
*/
public String getItemText() {
return this.itemText;
}
/**
* Sets item text.
*
* @param itemText the item text
*/
public void setItemText(String itemText) {
this.itemText = itemText;
}
/**
* Gets max discount num.
*
* @return the max discount num
*/
public String getMaxDiscountNum() {
return this.maxDiscountNum;
}
/**
* Sets max discount num.
*
* @param maxDiscountNum the max discount num
*/
public void setMaxDiscountNum(String maxDiscountNum) {
this.maxDiscountNum = maxDiscountNum;
}
/**
* Gets min consume num.
*
* @return the min consume num
*/
public String getMinConsumeNum() {
return this.minConsumeNum;
}
/**
* Sets min consume num.
*
* @param minConsumeNum the min consume num
*/
public void setMinConsumeNum(String minConsumeNum) {
this.minConsumeNum = minConsumeNum;
}
/**
* Gets original price.
*
* @return the original price
*/
public String getOriginalPrice() {
return this.originalPrice;
}
/**
* Sets original price.
*
* @param originalPrice the original price
*/
public void setOriginalPrice(String originalPrice) {
this.originalPrice = originalPrice;
}
/**
* Gets sku min consume.
*
* @return the sku min consume
*/
public String getSkuMinConsume() {
return this.skuMinConsume;
}
/**
* Sets sku min consume.
*
* @param skuMinConsume the sku min consume
*/
public void setSkuMinConsume(String skuMinConsume) {
this.skuMinConsume = skuMinConsume;
}
/**
* Gets total max discount num.
*
* @return the total max discount num
*/
public String getTotalMaxDiscountNum() {
return this.totalMaxDiscountNum;
}
/**
* Sets total max discount num.
*
* @param totalMaxDiscountNum the total max discount num
*/
public void setTotalMaxDiscountNum(String totalMaxDiscountNum) {
this.totalMaxDiscountNum = totalMaxDiscountNum;
}
}
| [
"[email protected]"
] | |
a022b41f07b34b31b5450dca207bf462d4b1dae4 | b2f07f3e27b2162b5ee6896814f96c59c2c17405 | /javax/swing/plaf/synth/SynthToolTipUI.java | 4bc564ea6e090540480c0ff004e5d7c866cbc30d | [] | no_license | weiju-xi/RT-JAR-CODE | e33d4ccd9306d9e63029ddb0c145e620921d2dbd | d5b2590518ffb83596a3aa3849249cf871ab6d4e | refs/heads/master | 2021-09-08T02:36:06.675911 | 2018-03-06T05:27:49 | 2018-03-06T05:27:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,630 | java | /* */ package javax.swing.plaf.synth;
/* */
/* */ import java.awt.Dimension;
/* */ import java.awt.Font;
/* */ import java.awt.FontMetrics;
/* */ import java.awt.Graphics;
/* */ import java.awt.Insets;
/* */ import java.awt.Rectangle;
/* */ import java.beans.PropertyChangeEvent;
/* */ import java.beans.PropertyChangeListener;
/* */ import javax.swing.JComponent;
/* */ import javax.swing.JToolTip;
/* */ import javax.swing.plaf.ComponentUI;
/* */ import javax.swing.plaf.basic.BasicHTML;
/* */ import javax.swing.plaf.basic.BasicToolTipUI;
/* */ import javax.swing.text.View;
/* */
/* */ public class SynthToolTipUI extends BasicToolTipUI
/* */ implements PropertyChangeListener, SynthUI
/* */ {
/* */ private SynthStyle style;
/* */
/* */ public static ComponentUI createUI(JComponent paramJComponent)
/* */ {
/* 57 */ return new SynthToolTipUI();
/* */ }
/* */
/* */ protected void installDefaults(JComponent paramJComponent)
/* */ {
/* 65 */ updateStyle(paramJComponent);
/* */ }
/* */
/* */ private void updateStyle(JComponent paramJComponent) {
/* 69 */ SynthContext localSynthContext = getContext(paramJComponent, 1);
/* 70 */ this.style = SynthLookAndFeel.updateStyle(localSynthContext, this);
/* 71 */ localSynthContext.dispose();
/* */ }
/* */
/* */ protected void uninstallDefaults(JComponent paramJComponent)
/* */ {
/* 79 */ SynthContext localSynthContext = getContext(paramJComponent, 1);
/* 80 */ this.style.uninstallDefaults(localSynthContext);
/* 81 */ localSynthContext.dispose();
/* 82 */ this.style = null;
/* */ }
/* */
/* */ protected void installListeners(JComponent paramJComponent)
/* */ {
/* 90 */ paramJComponent.addPropertyChangeListener(this);
/* */ }
/* */
/* */ protected void uninstallListeners(JComponent paramJComponent)
/* */ {
/* 98 */ paramJComponent.removePropertyChangeListener(this);
/* */ }
/* */
/* */ public SynthContext getContext(JComponent paramJComponent)
/* */ {
/* 106 */ return getContext(paramJComponent, getComponentState(paramJComponent));
/* */ }
/* */
/* */ private SynthContext getContext(JComponent paramJComponent, int paramInt) {
/* 110 */ return SynthContext.getContext(SynthContext.class, paramJComponent, SynthLookAndFeel.getRegion(paramJComponent), this.style, paramInt);
/* */ }
/* */
/* */ private int getComponentState(JComponent paramJComponent)
/* */ {
/* 115 */ JComponent localJComponent = ((JToolTip)paramJComponent).getComponent();
/* */
/* 117 */ if ((localJComponent != null) && (!localJComponent.isEnabled())) {
/* 118 */ return 8;
/* */ }
/* 120 */ return SynthLookAndFeel.getComponentState(paramJComponent);
/* */ }
/* */
/* */ public void update(Graphics paramGraphics, JComponent paramJComponent)
/* */ {
/* 137 */ SynthContext localSynthContext = getContext(paramJComponent);
/* */
/* 139 */ SynthLookAndFeel.update(localSynthContext, paramGraphics);
/* 140 */ localSynthContext.getPainter().paintToolTipBackground(localSynthContext, paramGraphics, 0, 0, paramJComponent.getWidth(), paramJComponent.getHeight());
/* */
/* 142 */ paint(localSynthContext, paramGraphics);
/* 143 */ localSynthContext.dispose();
/* */ }
/* */
/* */ public void paintBorder(SynthContext paramSynthContext, Graphics paramGraphics, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
/* */ {
/* 152 */ paramSynthContext.getPainter().paintToolTipBorder(paramSynthContext, paramGraphics, paramInt1, paramInt2, paramInt3, paramInt4);
/* */ }
/* */
/* */ public void paint(Graphics paramGraphics, JComponent paramJComponent)
/* */ {
/* 166 */ SynthContext localSynthContext = getContext(paramJComponent);
/* */
/* 168 */ paint(localSynthContext, paramGraphics);
/* 169 */ localSynthContext.dispose();
/* */ }
/* */
/* */ protected void paint(SynthContext paramSynthContext, Graphics paramGraphics)
/* */ {
/* 180 */ JToolTip localJToolTip = (JToolTip)paramSynthContext.getComponent();
/* */
/* 182 */ Insets localInsets = localJToolTip.getInsets();
/* 183 */ View localView = (View)localJToolTip.getClientProperty("html");
/* 184 */ if (localView != null) {
/* 185 */ Rectangle localRectangle = new Rectangle(localInsets.left, localInsets.top, localJToolTip.getWidth() - (localInsets.left + localInsets.right), localJToolTip.getHeight() - (localInsets.top + localInsets.bottom));
/* */
/* 188 */ localView.paint(paramGraphics, localRectangle);
/* */ } else {
/* 190 */ paramGraphics.setColor(paramSynthContext.getStyle().getColor(paramSynthContext, ColorType.TEXT_FOREGROUND));
/* */
/* 192 */ paramGraphics.setFont(this.style.getFont(paramSynthContext));
/* 193 */ paramSynthContext.getStyle().getGraphicsUtils(paramSynthContext).paintText(paramSynthContext, paramGraphics, localJToolTip.getTipText(), localInsets.left, localInsets.top, -1);
/* */ }
/* */ }
/* */
/* */ public Dimension getPreferredSize(JComponent paramJComponent)
/* */ {
/* 203 */ SynthContext localSynthContext = getContext(paramJComponent);
/* 204 */ Insets localInsets = paramJComponent.getInsets();
/* 205 */ Dimension localDimension = new Dimension(localInsets.left + localInsets.right, localInsets.top + localInsets.bottom);
/* */
/* 207 */ String str = ((JToolTip)paramJComponent).getTipText();
/* */
/* 209 */ if (str != null) {
/* 210 */ Object localObject = paramJComponent != null ? (View)paramJComponent.getClientProperty("html") : null;
/* 211 */ if (localObject != null) {
/* 212 */ localDimension.width += (int)localObject.getPreferredSpan(0);
/* 213 */ localDimension.height += (int)localObject.getPreferredSpan(1);
/* */ } else {
/* 215 */ Font localFont = localSynthContext.getStyle().getFont(localSynthContext);
/* 216 */ FontMetrics localFontMetrics = paramJComponent.getFontMetrics(localFont);
/* 217 */ localDimension.width += localSynthContext.getStyle().getGraphicsUtils(localSynthContext).computeStringWidth(localSynthContext, localFont, localFontMetrics, str);
/* */
/* 219 */ localDimension.height += localFontMetrics.getHeight();
/* */ }
/* */ }
/* 222 */ localSynthContext.dispose();
/* 223 */ return localDimension;
/* */ }
/* */
/* */ public void propertyChange(PropertyChangeEvent paramPropertyChangeEvent)
/* */ {
/* 231 */ if (SynthLookAndFeel.shouldUpdateStyle(paramPropertyChangeEvent)) {
/* 232 */ updateStyle((JToolTip)paramPropertyChangeEvent.getSource());
/* */ }
/* 234 */ String str1 = paramPropertyChangeEvent.getPropertyName();
/* 235 */ if ((str1.equals("tiptext")) || ("font".equals(str1)) || ("foreground".equals(str1)))
/* */ {
/* 240 */ JToolTip localJToolTip = (JToolTip)paramPropertyChangeEvent.getSource();
/* 241 */ String str2 = localJToolTip.getTipText();
/* 242 */ BasicHTML.updateRenderer(localJToolTip, str2);
/* */ }
/* */ }
/* */ }
/* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar
* Qualified Name: javax.swing.plaf.synth.SynthToolTipUI
* JD-Core Version: 0.6.2
*/ | [
"[email protected]"
] | |
a91d9bf5480af395e9f84e9ccd7c1b410341deca | b077868c9ff0f0fd10e282a042ff9b5f28ca06b7 | /src/main/java/ValidNumber.java | b32b525bc17bf6f7bdb94fd6749c398a744328dd | [] | no_license | mariacruz4/U1-M1-Summative-Cruz-Maria | 5ba9b87ed3a00b2007db69a8ce233c57139ebec3 | 0e005aa96034a3cae284060f33efda6986fad3ae | refs/heads/master | 2020-06-14T04:21:24.833605 | 2019-07-02T17:02:52 | 2019-07-02T17:02:52 | 194,791,719 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 633 | java | import java.util.*;
public class ValidNumber {
public static void main(String[] args){
//Prompt the user to enter a number
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = scanner.nextInt();
//while loop that decides whether the number inputted is in the range
while(num < 1 || num > 10){
System.out.println("You must enter a number between 1 and 10, please try again.");
System.out.println("Enter number: ");
num = scanner.nextInt();
}
System.out.println(num);
}
}
| [
"[email protected]"
] | |
5de6aa957a6161e14e7627cb1695b438cee442de | 8bdc8e18cf00d86d15e7b41edce49033cb5cc4bf | /src/main/java/com/item/eshop/util/websocket/TransJson.java | cec4d27a53272b44586ffe02db362b8024cd9226 | [] | no_license | 838375536/eshop_new | 840af1033d79af8d3c347361adc297ab68ed53f4 | 995aec9f4d8b2156f030c32ed9115eddd86612ed | refs/heads/master | 2020-03-27T20:36:28.426017 | 2018-09-02T11:57:53 | 2018-09-02T11:57:53 | 147,080,513 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 463 | java | package com.item.eshop.util.websocket;
public class TransJson {
private Integer code;
private Object msg;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
public TransJson(Integer code, Object msg) {
super();
this.code = code;
this.msg = msg;
}
public TransJson() {
super();
}
}
| [
"[email protected]"
] | |
c3653b11ac12bf88db68ec810643fb0e2a130b5e | e7b3cdffb8c5810ee9a9438f8c381cfb8e3d7138 | /src/main/java/cn/liuzhengwei/ebook/entity/Book.java | ce28165bd2cbc714924e8311611ac5c74fa8d4d5 | [] | no_license | xianfish/E-book-Server | 7c656404103390f7bb3123fb25ac29f8f4a84dd3 | 614fbb57196041439e5eb501596974feec5c2ed8 | refs/heads/master | 2022-11-15T21:39:24.087896 | 2019-06-30T13:29:35 | 2019-06-30T13:29:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 491 | java | package cn.liuzhengwei.ebook.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
//Book实体定义
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Book {
private String name;
private String author;
private String ISBN;
private String newisbn;
private String outline;
private Integer stock;
private Float price;
private String cover;
private String press;
private String year;
private Integer pages;
}
| [
"[email protected]"
] | |
cfe23d65b4fb10614e4304f0d8839b572b53bdc6 | a5108ca821cdbae0c372179e621f008113505f29 | /src/localsearch/domainspecific/vehiclerouting/vrp/online/NodeWeightsManagerOnline.java | 1ecb2956e53fe8e6b2c42c5418d5685f6a13fa58 | [
"BSD-2-Clause"
] | permissive | anhtu-phan/cblsvr | 1a57a126b9ad00da8dbf74280c17e2e3089dac57 | f1d078451b9758615b49bf8507b3d4c3cb9c4860 | refs/heads/master | 2022-04-30T17:39:33.239243 | 2017-11-09T03:08:48 | 2017-11-09T03:08:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 841 | java | package localsearch.domainspecific.vehiclerouting.vrp.online;
import localsearch.domainspecific.vehiclerouting.vrp.entities.NodeWeightsManager;
import localsearch.domainspecific.vehiclerouting.vrp.entities.Point;
import java.util.ArrayList;
public class NodeWeightsManagerOnline extends NodeWeightsManager {
public NodeWeightsManagerOnline(VarRoutesVROnline XR){
super(new ArrayList<Point>());
XR.getVRManagerOnline().setNodeWeightsManager(this);
}
private void scaleUp(){
double[] t_w = new double[2*weights.length];
System.arraycopy(weights, 0, t_w, 0, weights.length);
weights = t_w;
}
public void addPoint(Point p){
if(weights.length == points.size()) scaleUp();
points.add(p);
map.put(p, points.size()-1);
}
public String name(){
return "NodeWeightsManagerOnline";
}
}
| [
"[email protected]"
] | |
6742613219eb629f3ee3f67dbcd050a9027e016c | 6f36fc4a0f9c680553f8dd64c5df55c403f8f2ed | /src/main/java/it/csi/siac/siacbilser/integration/dao/cespiti/CategoriaCespitiDaoImpl.java | 522dcb505b8462eb9e52d405ad10428afad71186 | [] | no_license | unica-open/siacbilser | b46b19fd382f119ec19e4e842c6a46f9a97254e2 | 7de24065c365564b71378ce9da320b0546474130 | refs/heads/master | 2021-01-06T13:25:34.712460 | 2020-03-04T08:44:26 | 2020-03-04T08:44:26 | 241,339,144 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,821 | java | /*
*SPDX-FileCopyrightText: Copyright 2020 | CSI Piemonte
*SPDX-License-Identifier: EUPL-1.2
*/
package it.csi.siac.siacbilser.integration.dao.cespiti;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import it.csi.siac.siacbilser.business.utility.Utility;
import it.csi.siac.siacbilser.integration.entity.SiacDCespitiCategoria;
import it.csi.siac.siaccommonser.integration.dao.base.JpaDao;
import it.csi.siac.siaccommonser.integration.entity.SiacTBase;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class CategoriaCespitiDaoImpl extends JpaDao<SiacDCespitiCategoria, Integer> implements CategoriaCespitiDao {
public SiacDCespitiCategoria create(SiacDCespitiCategoria e){
Date now = new Date();
Date dataInizioValidita = e.getDataInizioValidita();
e.setDataModificaInserimento(now, dataInizioValidita);
setDataModificaInserimento(e, now, dataInizioValidita);
e.setUid(null);
super.save(e);
return e;
}
public SiacDCespitiCategoria update(SiacDCespitiCategoria e){
SiacDCespitiCategoria eAttuale = this.findById(e.getUid());
Date now = new Date();
Date dataInizioValidita = e.getDataInizioValidita();
e.setDataModifica(now);
//SIAC-6393
e.setDataFineValidita(eAttuale.getDataFineValidita());
setDataFineValiditaEDataCancellazioneSeNelPeriodoDiValidita(eAttuale, now, dataInizioValidita);
e.setDataModifica(now);
setDataModificaInserimento(e, now, dataInizioValidita);
entityManager.flush();
super.update(e);
return e;
}
@Override
public SiacDCespitiCategoria delete(int uidCategoriaCespiti, String loginOperazione) {
SiacDCespitiCategoria eAttuale = this.findById(uidCategoriaCespiti);
Date now = new Date();
eAttuale.setDataCancellazioneIfNotSet(now);
eAttuale.setLoginOperazione(loginOperazione);
super.update(eAttuale);
return eAttuale;
}
@Override
public Page<SiacDCespitiCategoria> ricercaSinteticaCategoriaCespiti(int enteProprietarioId, String cescatCode, String cescatDesc, BigDecimal aliquotaAnnua, Integer cescatCalcoloTipoId, Boolean escludiAnnullati, String ambitoCode, Date dataValidita, Pageable pageable) {
final String methodName = "ricercaSinteticaCategoriaCespiti";
StringBuilder jpql = new StringBuilder();
Map<String, Object> param = new HashMap<String, Object>();
componiQueryRicercaSinteticaCategoriaCespiti( jpql, param, enteProprietarioId, cescatCode, cescatDesc, aliquotaAnnua, cescatCalcoloTipoId, escludiAnnullati, ambitoCode, dataValidita);
jpql.append(" ORDER BY d.cescatCode ");
log.debug(methodName, "JPQL to execute: " + jpql.toString());
return getPagedList(jpql.toString(), param, pageable);
}
private void componiQueryRicercaSinteticaCategoriaCespiti(StringBuilder jpql, Map<String, Object> param,
int enteProprietarioId, String cescatCode, String cescatDesc, BigDecimal aliquotaAnnua,
Integer cescatCalcoloTipoId, Boolean escludiAnnullati, String ambitoCode, Date dataValidita) {
jpql.append(" FROM SiacDCespitiCategoria d ");
jpql.append(" WHERE ");
jpql.append(" d.dataCancellazione IS NULL ");
jpql.append(" AND d.siacTEnteProprietario.enteProprietarioId = :enteProprietarioId ");
jpql.append(" AND d.siacDAmbito.ambitoCode = :ambitoCode ");
jpql.append(" AND d.dataInizioValidita <= :dataInizioValidita ");
param.put("enteProprietarioId", enteProprietarioId);
param.put("ambitoCode", ambitoCode);
param.put("dataInizioValidita", dataValidita);
if(Boolean.TRUE.equals(escludiAnnullati)) {
jpql.append(" AND d.dataFineValidita IS NULL ");
}
if(StringUtils.isNotBlank(cescatCode)){
jpql.append(" AND " + Utility.toJpqlSearchLike("d.cescatCode", "CONCAT('%', :cescatCode, '%')") + " ");
param.put("cescatCode", cescatCode);
}
if(StringUtils.isNotBlank(cescatDesc)){
jpql.append(" AND " + Utility.toJpqlSearchLike("d.cescatDesc", "CONCAT('%', :cescatDesc, '%')") + " ");
param.put("cescatDesc", cescatDesc);
}
if(aliquotaAnnua!= null){
jpql.append(" AND EXISTS ( ");
jpql.append(" FROM SiacRCespitiCategoriaAliquotaCalcoloTipo r ");
jpql.append(" WHERE r.siacDCespitiCategoria.cescatId = d.cescatId ");
jpql.append(" AND r.dataCancellazione IS NULL ");
jpql.append(" AND r.dataCancellazione IS NULL ");
jpql.append(" AND (r.dataFineValidita IS NULL OR :dataInputAliquota <= r.dataFineValidita) ");
jpql.append(" AND (r.dataInizioValidita <= :dataInputAliquota) ");
jpql.append(" AND (r.aliquotaAnnua = :aliquotaAnnua) ");
jpql.append(" ) ");
param.put("aliquotaAnnua", aliquotaAnnua);
param.put("dataInputAliquota", dataValidita);
}
if(cescatCalcoloTipoId!= null){
jpql.append(" AND EXISTS ( ");
jpql.append(" FROM SiacRCespitiCategoriaAliquotaCalcoloTipo r ");
jpql.append(" WHERE r.siacDCespitiCategoria.cescatId = d.cescatId ");
jpql.append(" AND r.dataCancellazione IS NULL ");
jpql.append(" AND r.dataCancellazione IS NULL ");
jpql.append(" AND (r.dataFineValidita IS NULL OR :dataInputTipoCalcolo <= r.dataFineValidita) ");
jpql.append(" AND (r.dataInizioValidita <= :dataInputTipoCalcolo) ");
jpql.append(" AND (r.siacDCespitiCategoriaCalcoloTipo.cescatCalcoloTipoId = :cescatCalcoloTipoId) ");
jpql.append(" ) ");
param.put("cescatCalcoloTipoId", cescatCalcoloTipoId);
param.put("dataInputTipoCalcolo", dataValidita);
}
}
/**
* Sets the data modifica inserimento.
*
* @param e the e
* @param now the now
* @param dataInizioValidita
*/
private void setDataModificaInserimento(SiacDCespitiCategoria e, Date now, Date dataInizioValidita) {
int annoInizioValidita = Utility.getAnno(dataInizioValidita);
Date ultimoGiornoDellAnno = Utility.ultimoGiornoDellAnno(dataInizioValidita);
// SIAC-6011
setDataFineValiditaNewRecordByAnnoBilancio(e, now, dataInizioValidita, annoInizioValidita, ultimoGiornoDellAnno, e.getSiacRCategoriaCespitiAliquotaCalcoloTipos(), "SiacRCespitiCategoriaAliquotaCalcoloTipo");
}
/**
* @param e
* @param now
* @param dataInizioValidita
* @param annoInizioValidita
* @param ultimoGiornoDellAnno
*/
private <E extends SiacTBase> void setDataFineValiditaNewRecordByAnnoBilancio(SiacDCespitiCategoria e, Date now, Date dataInizioValidita,
int annoInizioValidita, Date ultimoGiornoDellAnno, List<E> entitas, String entitaName) {
if(entitas != null){
//SIAC-6106
Date validitaInizioMinima = ottieniMinValiditaInizioByNomeEntitaCollegamento(e.getUid(), dataInizioValidita, entitaName);
for(E entita : entitas){
entita.setDataModificaInserimento(now, dataInizioValidita);
entita.setUid(null);
Date validitaFine = ottieniValiditaInizioDaImpostareInBaseAlRecordSuccessivo(validitaInizioMinima, ultimoGiornoDellAnno, annoInizioValidita);
if(validitaFine != null) {
entita.setDataFineValiditaIfNotSet(validitaFine);
}
}
}
}
/**
* @param uid
* @param aliasR
*/
private Date ottieniMinValiditaInizioByNomeEntitaCollegamento(Integer uid, Date dataDiPartenza, String aliasR) {
final String methodName = "ottieniMinValiditaInizioByNomeEntitaCollegamento";
if(uid == null || uid == 0 || StringUtils.isEmpty(aliasR)) {
return null;
}
StringBuilder jpql = new StringBuilder();
Map<String, Object> param = new HashMap<String, Object>();
jpql.append(" SELECT MIN( rcoll.dataInizioValidita ) ")
.append(" FROM " + aliasR + " rcoll ")
.append(" WHERE rcoll.siacDCespitiCategoria.cescatId = :cescatId ")
.append(" AND rcoll.dataCancellazione IS NULL ")
.append(" AND rcoll.dataInizioValidita > :dataInizioValidita ");
param.put("cescatId", uid);
param.put("dataInizioValidita", dataDiPartenza);
log.debug(methodName, "JPQL to execute: " + jpql.toString());
Query query = createQuery(jpql.toString(), param);
return (Date) query.getSingleResult();
}
//SIAC-6106
private Date ottieniValiditaInizioDaImpostareInBaseAlRecordSuccessivo(Date validitaInizioMinima, Date ultimoGiornoDellAnno, int annoInizioValidita){
if(validitaInizioMinima == null) {
return null;
}
int annoValiditaInizioMinima = Utility.getAnno(validitaInizioMinima);
Date validitaFineDaImpostare = Utility.ultimoGiornoDellAnnoPrecedente(validitaInizioMinima);
return annoValiditaInizioMinima > annoInizioValidita ? Utility.dataPiuRecente(validitaFineDaImpostare, ultimoGiornoDellAnno) : null;
}
private void setDataFineValiditaEDataCancellazioneSeNelPeriodoDiValidita(SiacDCespitiCategoria eAttuale, Date dataCancellazioneDaImpostare, Date primoGiornoAnnoBilancio) {
Date ultimoGiornoAnnoBilancioPrecedente = Utility.ultimoGiornoDellAnnoPrecedente(primoGiornoAnnoBilancio);
int annoBilancioDellaModifica = Utility.getAnno(primoGiornoAnnoBilancio);
setDataFineValiditaOldRecordsByAnnoBilancio(dataCancellazioneDaImpostare, primoGiornoAnnoBilancio,
ultimoGiornoAnnoBilancioPrecedente, annoBilancioDellaModifica, eAttuale.getSiacRCategoriaCespitiAliquotaCalcoloTipos());
}
/**
* @param dataCancellazioneDaImpostare
* @param primoGiornoAnnoBilancio
* @param ultimoGiornoAnnoBilancioPrecedente
* @param annoBilancioDellaModifica
* @param entita
*/
private <E extends SiacTBase> void setDataFineValiditaOldRecordsByAnnoBilancio(Date dataCancellazioneDaImpostare,
Date primoGiornoAnnoBilancio, Date ultimoGiornoAnnoBilancioPrecedente, int annoBilancioDellaModifica,
List<E> entitas) {
final String methodName ="setDataFineValiditaOldRecordsByAnnoBilancio";
if(entitas != null){
for(E entita: entitas) {
// SIAC-6106
if(entita.getDataCancellazione() == null) {
Date ultimoGiornoDellannoDellaValiditaInizioDellEntityAttuale = Utility.ultimoGiornoDellAnno(entita.getDataInizioValidita());
//SIAC-6106
int annoInizioValidita = Utility.getAnno(entita.getDataInizioValidita());
Date dataFineValiditaDaImpostare = annoInizioValidita <= annoBilancioDellaModifica ?
//ho inserito/aggiornato una relazione nel 2017 ma ho relazioni nel 2018, non modifico successiva
Utility.dataPiuRecente(ultimoGiornoDellannoDellaValiditaInizioDellEntityAttuale, ultimoGiornoAnnoBilancioPrecedente) :
//ho inserito/aggiornato una relazione nel 2019 e sto aggiornando una relazione nel 2018
entita.getDataFineValidita();
log.info(methodName,
" dataFineValiditaDaImpostare: " + dataFineValiditaDaImpostare
+ " A partire dall' ultimoGiornoDellannoDellaValiditaInizioDellEntityAttuale: "
+ (ultimoGiornoDellannoDellaValiditaInizioDellEntityAttuale != null ? ultimoGiornoDellannoDellaValiditaInizioDellEntityAttuale : "null")
+ "e ultimoGiornoAnnoBilancioPrecedente: "
+ (ultimoGiornoAnnoBilancioPrecedente != null? ultimoGiornoAnnoBilancioPrecedente : "null")
+ "la data piu' recente e': "
+ (Utility.dataPiuRecente(ultimoGiornoDellannoDellaValiditaInizioDellEntityAttuale, ultimoGiornoAnnoBilancioPrecedente) != null ? Utility.dataPiuRecente(ultimoGiornoDellannoDellaValiditaInizioDellEntityAttuale, ultimoGiornoAnnoBilancioPrecedente) : "null" )
+ "e la data validita fine pregressa e' "
+ (entita.getDataFineValidita()!= null? entita.getDataFineValidita() : "null")
);
entita.sovrascriviDataFineValiditaESetDataCancellazioneSeNelPeriodoDiValidita(dataCancellazioneDaImpostare, primoGiornoAnnoBilancio, dataFineValiditaDaImpostare);
}
}
}
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.