blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
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
684M
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
132 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
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
7667fea7664ebd0b0ddf65c51c69866f340b254c
2821fdfb8ac1509350f8d676cd61f32211d08dc9
/src/com/leetcode/oj/RemoveDuplicatesFromSortedList.java
8edd831758f10cf06e1cbafd8630cf76e386bff8
[]
no_license
michaelliudl/CodingInterviewJava
43db1ee56e4d62dc9633d15169b68cdf3eef73ff
ece97039e06bd7efe772aecd402c51e1d8bf7de5
refs/heads/master
2021-01-16T18:43:52.872260
2015-03-06T17:56:12
2015-03-06T17:56:12
22,960,815
1
0
null
null
null
null
UTF-8
Java
false
false
422
java
package com.leetcode.oj; import beans.ListNode; /** * Created by doliu on 8/24/14. */ public class RemoveDuplicatesFromSortedList { public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; ListNode cur = head, next = head.next; while (next != null) { if (next.val != cur.val) { cur.next = next; cur = next; } next = next.next; } cur.next = null; return head; } }
[ "michael.liudl@gmail.com" ]
michael.liudl@gmail.com
1375ce27b1436cc6afb3c49f6defa0655ddf25a5
dc97ffc79dc1ef8150852bbc08a3e07d0c5b59b0
/jdroid-android-sample/src/main/java/com/jdroid/android/sample/ui/notifications/NotificationsFragment.java
a517c5fd53044e60049167362f5feb811ff91839
[ "Apache-2.0" ]
permissive
irfanirawansukirman/jdroid
7349480810aba53aedcb5ae046d5c832f6d85374
31b3294db1241185749e8566df161db864c14977
refs/heads/master
2021-07-20T05:57:47.273315
2017-10-30T02:55:18
2017-10-30T02:55:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,780
java
package com.jdroid.android.sample.ui.notifications; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.EditText; import com.jdroid.android.application.AbstractApplication; import com.jdroid.android.fragment.AbstractFragment; import com.jdroid.android.notification.NotificationBuilder; import com.jdroid.android.notification.NotificationUtils; import com.jdroid.android.sample.R; import com.jdroid.android.sample.application.AndroidNotificationChannelType; import com.jdroid.android.uil.UilBitmapLoader; import com.jdroid.java.concurrent.ExecutorUtils; import com.jdroid.java.date.DateUtils; import com.jdroid.java.utils.IdGenerator; import com.jdroid.java.utils.StringUtils; public class NotificationsFragment extends AbstractFragment { private EditText notificationName; private EditText notificationChannel; private EditText contentTitle; private EditText contentText; private EditText largeIconUrlEditText; private CheckBox largeIconDrawable; private EditText urlEditText; @Override public Integer getContentFragmentLayout() { return R.layout.notifications_fragment; } @SuppressLint("SetTextI18n") @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); notificationName = findView(R.id.notificationName); notificationName.setText("myNotification"); notificationChannel = findView(R.id.notificationChannel); notificationChannel.setText(AndroidNotificationChannelType.DEFAULT_IMPORTANCE.getChannelId()); contentTitle = findView(R.id.contentTitle); contentTitle.setText(R.string.contentTitleSample); contentText = findView(R.id.contentText); contentText.setText(R.string.contextTextSample); largeIconUrlEditText = findView(R.id.largeIconUrl); largeIconUrlEditText.setText("http://jdroidframework.com/images/gradle.png"); urlEditText = findView(R.id.url); urlEditText.setText("http://jdroidframework.com/uri"); largeIconDrawable = findView(R.id.largeIconDrawable); largeIconDrawable.setChecked(false); findView(R.id.sendNotification).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ExecutorUtils.execute(new Runnable() { @Override public void run() { NotificationBuilder builder = new NotificationBuilder(notificationName.getText().toString(), notificationChannel.getText().toString()); builder.setSmallIcon(AbstractApplication.get().getNotificationIconResId()); if (largeIconDrawable.isChecked()) { builder.setLargeIcon(R.drawable.marker); } else { String largeIconUrl = largeIconUrlEditText.getText().toString(); if (StringUtils.isNotEmpty(largeIconUrl)) { builder.setLargeIcon(new UilBitmapLoader(largeIconUrl)); } } builder.setContentTitle(contentTitle.getText().toString()); builder.setContentText(contentText.getText().toString()); String url = urlEditText.getText().toString(); if (StringUtils.isNotBlank(url)) { builder.setSingleTopUrl(url); } else { Intent intent = new Intent(getActivity(), AbstractApplication.get().getHomeActivityClass()); builder.setContentIntent(intent); } builder.setWhen(DateUtils.nowMillis()); builder.setBlueLight(); builder.setDefaultSound(); NotificationUtils.sendNotification(IdGenerator.getIntId(), builder); } }); } }); findView(R.id.cancelNotifications).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { NotificationUtils.cancelAllNotifications(); } }); } }
[ "maxirosson@gmail.com" ]
maxirosson@gmail.com
e029bd7320891f33154246dffcf00c7a58979354
e3c38acaa9105863d6181afa68c15ef61122bc56
/src/android/support/v4/app/TaskStackBuilder.java
d4d9a36613cc51d596393044af82f69e10970ed4
[]
no_license
Neio/iMessageChatDecompile
2d3349d848c25478e2bbbbaaf15006e9566b2f26
f0b32c44a6e7ba6bb6952adf73fa8529b70db59c
refs/heads/master
2021-01-18T06:52:36.066331
2013-09-24T17:29:28
2013-09-24T17:29:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,421
java
package android.support.v4.app; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build.VERSION; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.util.Log; import java.util.ArrayList; import java.util.Iterator; public class TaskStackBuilder implements Iterable { private static final TaskStackBuilder.TaskStackBuilderImpl IMPL = new TaskStackBuilder.TaskStackBuilderImplBase(); private static final String TAG = "TaskStackBuilder"; private final ArrayList mIntents = new ArrayList(); private final Context mSourceContext; static { if (Build.VERSION.SDK_INT >= 11) { IMPL = new TaskStackBuilder.TaskStackBuilderImplHoneycomb(); return; } } private TaskStackBuilder(Context paramContext) { this.mSourceContext = paramContext; } public static TaskStackBuilder create(Context paramContext) { return new TaskStackBuilder(paramContext); } public static TaskStackBuilder from(Context paramContext) { return create(paramContext); } public TaskStackBuilder addNextIntent(Intent paramIntent) { this.mIntents.add(paramIntent); return this; } public TaskStackBuilder addNextIntentWithParentStack(Intent paramIntent) { ComponentName localComponentName = paramIntent.getComponent(); if (localComponentName == null) localComponentName = paramIntent.resolveActivity(this.mSourceContext.getPackageManager()); if (localComponentName != null) addParentStack(localComponentName); addNextIntent(paramIntent); return this; } public TaskStackBuilder addParentStack(Activity paramActivity) { Intent localIntent = NavUtils.getParentActivityIntent(paramActivity); if (localIntent != null) { ComponentName localComponentName = localIntent.getComponent(); if (localComponentName == null) localComponentName = localIntent.resolveActivity(this.mSourceContext.getPackageManager()); addParentStack(localComponentName); addNextIntent(localIntent); } return this; } public TaskStackBuilder addParentStack(ComponentName paramComponentName) { int i = this.mIntents.size(); try { Intent localIntent; for (Object localObject = NavUtils.getParentActivityIntent(this.mSourceContext, paramComponentName); localObject != null; localObject = localIntent) { this.mIntents.add(i, localObject); localIntent = NavUtils.getParentActivityIntent(this.mSourceContext, ((Intent)localObject).getComponent()); } } catch (PackageManager.NameNotFoundException localNameNotFoundException) { Log.e("TaskStackBuilder", "Bad ComponentName while traversing activity parent metadata"); throw new IllegalArgumentException(localNameNotFoundException); } return this; } public TaskStackBuilder addParentStack(Class paramClass) { return addParentStack(new ComponentName(this.mSourceContext, paramClass)); } public Intent editIntentAt(int paramInt) { return (Intent)this.mIntents.get(paramInt); } public Intent getIntent(int paramInt) { return editIntentAt(paramInt); } public int getIntentCount() { return this.mIntents.size(); } public Intent[] getIntents() { Intent[] arrayOfIntent = new Intent[this.mIntents.size()]; if (arrayOfIntent.length == 0) return arrayOfIntent; arrayOfIntent[0] = new Intent((Intent)this.mIntents.get(0)).addFlags(268484608); for (int i = 1; i < arrayOfIntent.length; i++) arrayOfIntent[i] = new Intent((Intent)this.mIntents.get(i)); return arrayOfIntent; } public PendingIntent getPendingIntent(int paramInt1, int paramInt2) { return getPendingIntent(paramInt1, paramInt2, null); } public PendingIntent getPendingIntent(int paramInt1, int paramInt2, Bundle paramBundle) { if (this.mIntents.isEmpty()) throw new IllegalStateException("No intents added to TaskStackBuilder; cannot getPendingIntent"); Intent[] arrayOfIntent = (Intent[])this.mIntents.toArray(new Intent[this.mIntents.size()]); arrayOfIntent[0] = new Intent(arrayOfIntent[0]).addFlags(268484608); return IMPL.getPendingIntent(this.mSourceContext, arrayOfIntent, paramInt1, paramInt2, paramBundle); } public Iterator iterator() { return this.mIntents.iterator(); } public void startActivities() { startActivities(null); } public void startActivities(Bundle paramBundle) { if (this.mIntents.isEmpty()) throw new IllegalStateException("No intents added to TaskStackBuilder; cannot startActivities"); Intent[] arrayOfIntent = (Intent[])this.mIntents.toArray(new Intent[this.mIntents.size()]); arrayOfIntent[0] = new Intent(arrayOfIntent[0]).addFlags(268484608); if (!ContextCompat.startActivities(this.mSourceContext, arrayOfIntent, paramBundle)) { Intent localIntent = new Intent(arrayOfIntent[(-1 + arrayOfIntent.length)]); localIntent.addFlags(268435456); this.mSourceContext.startActivity(localIntent); } } } /* Location: /Users/mdp/Downloads/iMessage/classes-dex2jar.jar * Qualified Name: android.support.v4.app.TaskStackBuilder * JD-Core Version: 0.6.2 */
[ "mdp@yahoo-inc.com" ]
mdp@yahoo-inc.com
80ce229b73c5fdc6f636527f705e014fe4f6c711
74362b77c26687456e436767534ffeb01b14cfc9
/src/dev/hkor/vcprogram/algorithm/LF.java
b24899ecc9cf1ca73c0da17518a872bb8d23af9a
[]
no_license
thePLManHubert/Vertex-Coloring
7fa63beff36099ace55ef801b7e8ed0f4a00b2c3
f0d9c3c1210df99bfa9577310d20506347a98220
refs/heads/master
2020-03-19T09:57:01.495780
2018-06-06T13:10:43
2018-06-06T13:10:43
136,330,081
0
0
null
null
null
null
WINDOWS-1250
Java
false
false
1,873
java
package dev.hkor.vcprogram.algorithm; import java.awt.Color; import dev.hkor.vcprogram.mathobjects.Graph; import dev.hkor.vcprogram.mathobjects.NeighbourListElement; import dev.hkor.vcprogram.mechanisms.ColorTranslator; public class LF extends Algorithm { ColorTranslator ct = new ColorTranslator(); private Color[] colorPalette = ct.getColorPalette(); @Override public Graph method(Graph graph) { sortVertices(graph); boolean[] C = new boolean[colorPalette.length]; int[] CT = new int[graph.getSize()]; NeighbourListElement temp = null; int i, v; for(i = 0; i < graph.getSize(); i++){ CT[i] = -1; // Oznaczenie braku przypisania koloru } graph.getList()[0].getVertex().setColor(colorPalette[0]); // Wierzchołek startowy CT[0] = 0; // Przydzielamy kolor do wierzchołka startowego w pomocniczej tabeli for(v = 1; v < graph.getSize(); v++) // Przeglądamy resztę grafu { for(i = 0; i < colorPalette.length; i++) C[i] = false; while((temp = graph.getList()[v].getNext()) != null){ // Sprawdzamy sąsiadów obecnego wierzchołka if(temp.getVertex().hasColor()){ // Jeśli ma przypisany kolor for(i = 0; i < graph.getSize(); i++) //sprawdź który to element if(temp.getVertex().getLabel().compareTo(graph.getList()[i].getVertex().getLabel()) == 0){ C[CT[i]] = true; // Oznacz kolor jako niedostępny break; } } } graph.getList()[v].resetViewing(); for(i = 0; i < colorPalette.length; i++){ // Szukamy wolnego koloru if(!C[i]) { graph.getList()[v].getVertex().setColor(colorPalette[i]); // Przypisujemy go bieżącemu wierzchołkowi CT[v] = i; break; } } } graph.setColored(true); return graph; } private void sortVertices(Graph graph){ graph.sortVertices(); } }
[ "hubi92@wp.pl" ]
hubi92@wp.pl
3f995364cb56b289ebd00b4c9e60fa742938c728
1829841d6722d3bba533b752042be4d88a3c772a
/app/src/main/java/com/ilian/tictactoe/frontend/PlayActivity.java
aa56323e4c857f74a760c5c21413939906a1fc66
[]
no_license
annihilator01/tic-tac-toe
4f8d9cd03bea27cb010e8c5a3f47e950a4f2f18f
9c65756c2561ec38d4b4d021616048abf0809f20
refs/heads/master
2021-02-07T18:30:34.043311
2020-04-06T10:07:16
2020-04-06T10:07:16
244,062,216
0
0
null
2020-04-06T09:35:16
2020-03-01T00:24:23
Java
UTF-8
Java
false
false
9,838
java
package com.ilian.tictactoe.frontend; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.drawable.AnimatedVectorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.util.Pair; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import com.ilian.tictactoe.R; import com.ilian.tictactoe.backend.GameManager; import com.ilian.tictactoe.backend.WinnerInfo; import com.ilian.tictactoe.backend.guiconnectors.Figure; import com.ilian.tictactoe.frontend.customviews.PathView; import java.util.HashMap; import java.util.Objects; /** * Play screen activity. */ public class PlayActivity extends AppCompatActivity { private ConstraintLayout backgroundLayout; private GameManager gameManager; private ImageView[][] gridImageView; private HashMap<ImageView, Pair<Integer, Integer>> imageToPos; private boolean isGameOver; private LinearLayout gridLayout; /** * Hide all system UI and locate dynamically created elements on the activity on create. * @param savedInstanceState */ @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_activity); InterfaceManager.hideSystemUI(this); int gridSize = getIntent().getIntExtra("GridSize", 3); backgroundLayout = findViewById(R.id.play_background_layout); gridLayout = findViewById(R.id.grid); gameManager = new GameManager(gridSize); setGrid(); setFieldsActionsOnClick(); } /** * Dynamically create grid with size given from the start activity. */ @RequiresApi(api = Build.VERSION_CODES.N) private void setGrid() { gridImageView = new ImageView[gameManager.getGridSize()][gameManager.getGridSize()]; imageToPos = new HashMap<>(); for (int i = 0; i < 2 * gameManager.getGridSize() - 1; i++) { if (i % 2 == 0) { LinearLayout horizontalLL = getNewHorizontalLinearLayout(); gridLayout.addView(horizontalLL); for (int j = 0; j < 2 * gameManager.getGridSize() - 1; j++) { if (j % 2 == 0) { ImageView field = getNewField(); imageToPos.put(field, new Pair<>(i / 2, j / 2)); gridImageView[i / 2][j / 2] = field; horizontalLL.addView(field); } else { horizontalLL.addView(getNewGridSide(0, LinearLayout.LayoutParams.MATCH_PARENT)); } } } else { gridLayout.addView(getNewGridSide(LinearLayout.LayoutParams.MATCH_PARENT, 0)); } } } /** * Get new horizontal linear layout for line of figure on the play grid. * @return horizontalLL - horizontal linear layout */ private LinearLayout getNewHorizontalLinearLayout() { LinearLayout horizontalLL = new LinearLayout(this); horizontalLL.setOrientation(LinearLayout.HORIZONTAL); horizontalLL.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)); return horizontalLL; } /** * Get new play field. * @return field - image view */ @RequiresApi(api = Build.VERSION_CODES.N) private ImageView getNewField() { ImageView field = new ImageView(this); field.setLayoutParams(new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)); return field; } /** * Get new grid side. * @param width - width of grid side * @param height - heigth of grid side * @return gridSide - view that compatible either with horizontal ll or vertical ll */ @SuppressLint("ResourceAsColor") private View getNewGridSide(int width, int height) { View gridSide = new View(this); gridSide.setBackgroundResource(R.color.gridSideColor); gridSide.setLayoutParams(new LinearLayout.LayoutParams( width, height, 0.1f)); return gridSide; } /** * Set action on click for all fields. */ @RequiresApi(api = Build.VERSION_CODES.N) private void setFieldsActionsOnClick() { for (ImageView[] fields : gridImageView) { for (ImageView field : fields) { setFieldActionOnClick(field); } } } /** * Set action on click for specified field. * @param field - image view */ @RequiresApi(api = Build.VERSION_CODES.N) private void setFieldActionOnClick(ImageView field) { field.setOnClickListener(v -> gameEventsHandler(field)); } @RequiresApi(api = Build.VERSION_CODES.N) private void gameEventsHandler(ImageView field) { if (isGameOver) { return; } int i = Objects.requireNonNull(imageToPos.get(field)).first; int j = Objects.requireNonNull(imageToPos.get(field)).second; Figure turn = gameManager.getTurn(); if (!gameManager.markSpace(turn, i, j)) { return; } field.setImageResource(turn.getDrawableID()); startAnimation(field); // drawing win-line WinnerInfo winnerInfo = gameManager.getWinnerInfo(); if (winnerInfo != null) { isGameOver = true; int[] leftFieldLocation = new int[2]; i = winnerInfo.getLeftFieldPos().getY(); j = winnerInfo.getLeftFieldPos().getX(); ImageView leftField = gridImageView[i][j]; leftField.getLocationOnScreen(leftFieldLocation); int[] rightFieldLocation = new int[2]; i = winnerInfo.getRightFieldPos().getY(); j = winnerInfo.getRightFieldPos().getX(); ImageView rightField = gridImageView[i][j]; rightField.getLocationOnScreen(rightFieldLocation); PathView pathView = new PathView(this); backgroundLayout.addView(pathView); int startX = leftFieldLocation[0] + winnerInfo.getRow().getOffsetX(field.getWidth()); int startY = leftFieldLocation[1] + winnerInfo.getRow().getOffsetY(field.getHeight()); int endX = rightFieldLocation[0] + field.getWidth() - winnerInfo.getRow().getOffsetX(field.getWidth()); int endY = rightFieldLocation[1] + field.getHeight() - winnerInfo.getRow().getOffsetY(field.getHeight()); int strokeWidth = ((LinearLayout) gridLayout.getChildAt(0)).getChildAt(1).getWidth(); pathView.init(this, getResources().getColor(winnerInfo.getFigure().getColorID()), startX, startY, endX, endY, strokeWidth); setInfo(winnerInfo.getFigure().getDrawableID(), R.string.winLabel); } else if (gameManager.isDraw()) { isGameOver = true; setInfo(R.string.drawLabel); } else { setInfo(gameManager.getTurn().getDrawableID(), R.string.turnLabel); } } /** * Set info without image view. * @param textInfo - id of string info */ @SuppressLint("ResourceType") private void setInfo(int textInfo) { ImageView imageView = findViewById(R.id.imageInfo); imageView.setVisibility(View.GONE); TextView textView = findViewById(R.id.textInfo); textView.setGravity(Gravity.CENTER); textView.setText(textInfo); } /** * Set info with image view. * @param drawableID - id of drawable for image view * @param textInfo - id of string info */ @SuppressLint("ResourceType") private void setInfo(int drawableID, int textInfo) { ImageView imageView = findViewById(R.id.imageInfo); imageView.setImageResource(drawableID); imageView.setVisibility(View.VISIBLE); TextView textView = findViewById(R.id.textInfo); textView.setText(textInfo); textView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); textView.setVisibility(View.VISIBLE); } /** * Stat figure animation. * * @param imageView - figure field to be animated */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void startAnimation(ImageView imageView) { Drawable drawable = imageView.getDrawable(); if (drawable instanceof AnimatedVectorDrawable) { AnimatedVectorDrawable avd = (AnimatedVectorDrawable) drawable; avd.start(); } } /** * Move to start activity on restart button click. * * @param v the v */ public void onRestartButtonClick(View v) { Intent intent = new Intent(this, StartActivity.class); intent.putExtra("GridSize", gameManager.getGridSize()); startActivity(intent); } /** * Hide all system UI on resume. */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected void onResume() { super.onResume(); InterfaceManager.hideSystemUI(this); } /** * Deactivate actions when back button pressed */ @Override public void onBackPressed() {} }
[ "ghrom07@yandex.ru" ]
ghrom07@yandex.ru
d0f154bd9896234a3039cd7505730de104173a6a
ea4f35442857244320b9013246b491771bca8f15
/1.JavaSyntax/src/com/codegym/task/task04/task0415/Solution.java
22631a83a3ecd3ea96b3e52927d4bbbe762530a9
[]
no_license
stal-janybekuulu/CodeGymTasks
4f2363e4f6c101ec0582f4209efee8942239d1e3
ba62d4f60ce777ab100008a53f896b4a4c672177
refs/heads/master
2021-06-29T01:29:50.964588
2020-10-28T10:22:24
2020-10-28T10:22:24
171,511,247
0
0
null
null
null
null
UTF-8
Java
false
false
585
java
package com.codegym.task.task04.task0415; /* Rule of the triangle */ import java.io.*; import java.util.Scanner; public class Solution { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); int c = scanner.nextInt(); if ((a + b) > c && (b + c) > a && (a + c) > b) { System.out.println("The triangle is possible."); } else { System.out.println("The triangle is not possible."); } } }
[ "stal.janybekuulu@gmail.com" ]
stal.janybekuulu@gmail.com
d5b48ff16f9da29cba43883d3851bbae9896d1e0
07ae59a61f1f34c091c5af575c656f3e26c12945
/src/main/java/org/bpz/rabbitmq/management/web/controller/TestController.java
d47af33ec4b46f1675f43339ea3242a2b8427749
[]
no_license
lovercoder/rabbitmq-management
c90379b99bc62d4e056aaacc38b343da6de05874
9dc632c12d3624fa369c199908b67247a9687a16
refs/heads/master
2020-04-12T14:32:40.886800
2018-11-29T13:45:07
2018-11-29T13:45:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
782
java
package org.bpz.rabbitmq.management.web.controller; import com.google.gson.Gson; import org.apache.commons.codec.digest.DigestUtils; import org.bpz.rabbitmq.management.common.dto.User; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @PostMapping("/test") public void test(@RequestBody User user) { Gson gson = new Gson(); System.out.println(gson.toJson(user)); System.out.println(DigestUtils.sha1Hex(gson.toJson(user))); String ddd= "{\"name\":\"bob\",\"age\":11}"; System.out.println(ddd); System.out.println(DigestUtils.sha1Hex(ddd)); } }
[ "baopeizhou@126.com" ]
baopeizhou@126.com
091eacadeaee770979c8366e8a7c9b3fe6420dee
f8980bd081ad01c3b18d4fce523516f9fc0897bb
/src/etiquetas/visao/FormConectaBanco.java
37719fcc43dea2b6a0e0d6078c1cbc34a087c00c
[]
no_license
Eudes-batista/Etiquetas-de-Gondola
7f2a42f7b5ae8e16cd0b2e9d081cf59d2e89314c
7dd4f5dc636e5c0d9ab5bd7078736979d2d0158c
refs/heads/master
2021-07-05T23:51:35.988484
2021-01-30T16:30:38
2021-01-30T16:30:38
224,517,538
0
0
null
null
null
null
UTF-8
Java
false
false
7,669
java
package etiquetas.visao; import etiquetas.controle.ArquivoControle; import etiquetas.controle.ConectaBanco; import etiquetas.modelo.Configuracao; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.filechooser.FileNameExtensionFilter; public class FormConectaBanco extends javax.swing.JFrame { public FormConectaBanco() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); editHost = new javax.swing.JTextField(); editCaminho = new javax.swing.JTextField(); btnConectar = new javax.swing.JButton(); btnPesquisar = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("Conexão com Banco de dados"); editHost.setText("localhost"); btnConectar.setText("Conectar"); btnConectar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnConectarActionPerformed(evt); } }); btnPesquisar.setText("..."); btnPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPesquisarActionPerformed(evt); } }); jLabel2.setText("Host"); jLabel3.setText("Caminho"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editHost) .addComponent(editCaminho)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(167, 167, 167) .addComponent(btnConectar))) .addContainerGap(41, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(editHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(editCaminho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnPesquisar) .addComponent(jLabel3)) .addGap(18, 18, 18) .addComponent(btnConectar) .addContainerGap(20, Short.MAX_VALUE)) ); setSize(new java.awt.Dimension(430, 221)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnConectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConectarActionPerformed ConectaBanco conectaBanco = new ConectaBanco(); boolean conexao = conectaBanco.conexao(editHost.getText(), editCaminho.getText()); if (conexao) { try { ArquivoControle arquivoControle = new ArquivoControle(); Configuracao configuracao = new Configuracao(); configuracao.setHost(this.editHost.getText()); configuracao.setCaminho(this.editCaminho.getText()); arquivoControle.escreverNoArquivo(configuracao); conectaBanco.desconecta(); FormCriarEtiquetas formCriarEtiquetas = new FormCriarEtiquetas(); formCriarEtiquetas.setVisible(true); dispose(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Erro ao escrever no arquivo."); } return; } JOptionPane.showMessageDialog(null, "Não conseguiu conexão com o banco."); }//GEN-LAST:event_btnConectarActionPerformed private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed JFileChooser chooser = new JFileChooser("C:\\omega\\dba\\"); chooser.setFileFilter(new FileNameExtensionFilter("*.gdb", "gdb")); int retorno = chooser.showOpenDialog(new JDialog()); if (retorno == JFileChooser.APPROVE_OPTION) { editCaminho.setText(chooser.getSelectedFile().getAbsolutePath()); } }//GEN-LAST:event_btnPesquisarActionPerformed public static void main(String args[]) { Arrays.asList(javax.swing.UIManager.getInstalledLookAndFeels()).stream() .filter(name -> "Nimbus".equals(name.getName())) .forEach(info -> { try { javax.swing.UIManager.setLookAndFeel(info.getClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(FormConectaBanco.class.getName()).log(Level.SEVERE, null, ex); } }); java.awt.EventQueue.invokeLater(() -> new FormConectaBanco().setVisible(true)); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnConectar; private javax.swing.JButton btnPesquisar; private javax.swing.JTextField editCaminho; private javax.swing.JTextField editHost; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration//GEN-END:variables }
[ "Administrador@PC-PC" ]
Administrador@PC-PC
10edb35a51e75b09ea39b96336a1e08e21ba98e4
91a6918b7e0e44e72576921485ed231b293e7d59
/src/com/xintong/code/factory2/simple/Product.java
7eeb018e50a230e3fb4e2f7498ac584ff0bf7dee
[]
no_license
githubzsk/DesignModel
af143ad1822f6243d2a467fce5393b3570427310
38f5eeaba518fd5c5adc4106849914a2b69d52d4
refs/heads/master
2021-04-01T05:23:53.411551
2020-09-24T16:00:34
2020-09-24T16:00:34
255,204,514
1
0
null
null
null
null
UTF-8
Java
false
false
213
java
package com.xintong.code.factory2.simple; /** * @ClassName Product * @Description TODO * @Author zsk * @Date 2019/12/30 16:01 * @Version 1.0 */ public abstract class Product { abstract void intro(); }
[ "zzzsk163@163.com" ]
zzzsk163@163.com
d8cf2c43afa8e2f11c5802dd841c75c6e381d16e
5e2cab8845e635b75f699631e64480225c1cf34d
/modules/core/org.jowidgets.impl/src/main/java/org/jowidgets/impl/widgets/composed/blueprint/defaults/QuestionDialogDefaults.java
70907d71e0b6867c1306ac6aeba680256e6e9e99
[ "BSD-3-Clause" ]
permissive
alec-liu/jo-widgets
2277374f059500dfbdb376333743d5507d3c57f4
a1dde3daf1d534cb28828795d1b722f83654933a
refs/heads/master
2022-04-18T02:36:54.239029
2018-06-08T13:08:26
2018-06-08T13:08:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,445
java
/* * Copyright (c) 2010, Michael Grossmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the jo-widgets.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.jowidgets.impl.widgets.composed.blueprint.defaults; import org.jowidgets.api.image.Icons; import org.jowidgets.api.widgets.blueprint.builder.IQuestionDialogSetupBuilder; import org.jowidgets.api.widgets.blueprint.defaults.IDefaultInitializer; import org.jowidgets.impl.widgets.composed.blueprint.BluePrintFactory; public class QuestionDialogDefaults implements IDefaultInitializer<IQuestionDialogSetupBuilder<?>> { @Override public void initialize(final IQuestionDialogSetupBuilder<?> builder) { final BluePrintFactory bpF = new BluePrintFactory(); builder.setYesButton(bpF.button(Messages.getString("QuestionDialogDefaults.yes"))); //$NON-NLS-1$ builder.setNoButton(bpF.button(Messages.getString("QuestionDialogDefaults.no"))); //$NON-NLS-1$ builder.setIcon(Icons.QUESTION); } }
[ "herrgrossmann@users.noreply.github.com" ]
herrgrossmann@users.noreply.github.com
af3ab4164f3c67b8c2d2cb5d958f74902941dcbc
7f4966afc7e238498e79e6226a19327aaeccf93c
/app/src/main/java/com/adex11/android/sastaGoldari/utils/ConstCode.java
49953648783782c75ffd99fa76690a45127c2ebe
[]
no_license
anubhab-d/sastagoldari
b3098be1c6f4b3b7bbbd52c95f7af27baf3f4dd7
be73bce398047ac49682f75f0101b26f1aa320cc
refs/heads/master
2023-06-24T03:18:37.572635
2021-07-22T14:31:33
2021-07-22T14:31:33
376,084,139
0
0
null
null
null
null
UTF-8
Java
false
false
272
java
package com.adex11.android.sastaGoldari.utils; import android.content.Context; import android.widget.Toast; public class ConstCode { public static void showToast(Context context, String txt) { Toast.makeText(context, txt, Toast.LENGTH_SHORT).show(); } }
[ "76570320+sitamadex11@users.noreply.github.com" ]
76570320+sitamadex11@users.noreply.github.com
4242a59bcbb10cbcee032af92edaa2cc16cf9ba6
440129ba5acb1166570b13a97653ae9c95c9387c
/src/caceresenzo/libs/boxplay/culture/searchngo/content/text/INovelContentProvider.java
f24bbe2016349747636075b07ff1bf111dbdd9a7
[]
no_license
Caceresenzo/boxplay3-library
b8bd923d0431e84b342b7016c71a202a70bdf77b
5d65333a323d77e457962060120fbdf03d64cd20
refs/heads/master
2022-02-21T03:45:53.090540
2019-09-18T20:46:38
2019-09-18T20:46:38
137,792,287
0
0
null
null
null
null
UTF-8
Java
false
false
139
java
package caceresenzo.libs.boxplay.culture.searchngo.content.text; public interface INovelContentProvider extends ITextContentProvider { }
[ "caceresenzo1502@gmail.com" ]
caceresenzo1502@gmail.com
7675124c5aa773a246b530d59f2bcdc70128b735
d31a4fc19d6ad777b04d2894b78af5169e9c0cf0
/java/swim-jaxb/swim-jaxb-tmfdata/target/generated-sources/xjc/us/gov/dot/faa/atm/tfm/tfmrequestreplytypes/RerouteDynamicExceptionResponseType.java
8db3d6565eed42f4424870dc11246c018c44116b
[]
no_license
am1985/swim
71120c281f56a4e1962ae3cc822fc579822e8489
44a9295b62520560c61a0c1e7b982e23f886ea60
refs/heads/master
2021-05-21T19:00:20.206445
2020-04-03T17:17:31
2020-04-03T17:17:31
252,761,369
0
0
null
2020-10-13T20:53:13
2020-04-03T14:49:41
Java
UTF-8
Java
false
false
2,920
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.04.03 at 10:08:32 AM EDT // package us.gov.dot.faa.atm.tfm.tfmrequestreplytypes; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for rerouteDynamicExceptionResponseType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="rerouteDynamicExceptionResponseType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="keyword"&gt; * &lt;simpleType&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="DYN_EXC_CONFIRM"/&gt; * &lt;enumeration value="DYN_EXC_ERROR"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * &lt;/element&gt; * &lt;element name="text" minOccurs="0"&gt; * &lt;simpleType&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * &lt;/element&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "rerouteDynamicExceptionResponseType", propOrder = { "keyword", "text" }) public class RerouteDynamicExceptionResponseType { @XmlElement(required = true) protected String keyword; protected String text; /** * Gets the value of the keyword property. * * @return * possible object is * {@link String } * */ public String getKeyword() { return keyword; } /** * Sets the value of the keyword property. * * @param value * allowed object is * {@link String } * */ public void setKeyword(String value) { this.keyword = value; } /** * Gets the value of the text property. * * @return * possible object is * {@link String } * */ public String getText() { return text; } /** * Sets the value of the text property. * * @param value * allowed object is * {@link String } * */ public void setText(String value) { this.text = value; } }
[ "Alexander.Murray@noblis.org" ]
Alexander.Murray@noblis.org
509428e87d6b9097a4ec4487c3d9dd0e5259facf
f6c2b29f29b7d354a9ca829c0eb7b1b0a6589e9e
/Java/AULAS/src/Lista_III/T4_IdividuosRegiao.java
1d9ad8820f0bcc33c583a14a3063ee67ec753885
[]
no_license
LukyAguiar/turma30java
28a652393c9ae82e9d6f1b6a862925a4905d09f3
6e07a4a341aaff47d595b1705567b233881cd430
refs/heads/main
2023-07-03T23:53:17.231774
2021-08-12T19:22:50
2021-08-12T19:22:50
391,053,489
0
0
null
null
null
null
UTF-8
Java
false
false
1,581
java
package Lista_III; import java.util.Scanner; public class T4_IdividuosRegiao { public static void main(String[] args) { //Variaveis Scanner leia = new Scanner(System.in); int idade; char sexo; //(1- woman / 2-man / 3- Others) char opcoes; char op = 'S'; int contadorPessoas = 0; final int LIMITE_PESSOAS_ENTREVISTADAS=3; int numeroPessoasCalma = 0; int numeroMulheresNervosas = 0; int numeroHomemAgressivos = 0; int numeroOutrosCalmos = 0; int numeroPessoasNervosas40 = 0; int numeroPessoasCalmas18 = 0; //Entradas while(contadorPessoas <= LIMITE_PESSOAS_ENTREVISTADAS && op=='S' && op=='s' ){ System.out.println("Digite a idade: "); idade = leia.nextInt(); System.out.println("Digite |- 1 - Feminino |- 2 - Masculino | - 3 - Outros"); sexo = leia.next().charAt(0); System.out.println("Digite |- 1 - Pessoa CALMA | - 2 - Pessoa Nervosa | - 3 - Agressivos "); opcoes = leia.next().charAt(0); contadorPessoas ++; System.out.println("Continua S/N: "); op = leia.next().toUpperCase().charAt(0); //Processamentos if(opcoes == '1') { numeroPessoasCalma++; } if(sexo == '1' && opcoes =='2') { numeroMulheresNervosas++; } if(sexo == '2' && opcoes == '3') { numeroHomemAgressivos++; } if(sexo == '3' && opcoes == '1') { numeroOutrosCalmos++; } if(opcoes == '2' && idade == 40) { numeroPessoasNervosas40++; } if(opcoes == '1' && idade == 18) { numeroPessoasCalmas18++; } } //Saidas } }
[ "lucas.nune@outlook.com.br" ]
lucas.nune@outlook.com.br
a4cb356a10305b3c5c721bef903b142bcc7c8c2a
f093834bae67ab4fa901d93e991fa4f9996c74ba
/src/main/java/com/lexx7/servicemessages/web/model/UserRowModel.java
f5cf842c4e2c2f1b464dfad794dd9bbdd4bcf7ca
[]
no_license
lexx7/service-messages
591649e0b19c866d56affa6deacf3e18c80d97a8
b370bb4ab96302ca8fbd2537ba481bde73eb2c66
refs/heads/master
2020-12-31T05:55:24.253156
2017-02-21T19:00:43
2017-02-21T19:00:43
80,651,446
0
0
null
null
null
null
UTF-8
Java
false
false
850
java
package com.lexx7.servicemessages.web.model; public class UserRowModel { private String id; private String fio; private String email; private String login; private String role; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFio() { return fio; } public void setFio(String fio) { this.fio = fio; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
[ "lexx7@list.ru" ]
lexx7@list.ru
b60f6b75e9fd975c7c1d6bc558eea9016a1e8449
856920a3cc35bc3cecaf1fba628b06c7d614c9ec
/app/src/main/java/com/example/nurseryschool/PostActivity.java
6d7bae471eb89ecbd231663a5150baa5e7dcf974
[]
no_license
nhatthy24/DoAnCNPM
8b6d54ce149d9be0ab21b2606ce4a387225be3c8
4a85c674199d7c15918447c373f0072707523595
refs/heads/master
2023-05-14T15:08:18.244914
2021-06-08T12:58:57
2021-06-08T12:58:57
369,531,509
0
0
null
null
null
null
UTF-8
Java
false
false
4,855
java
package com.example.nurseryschool; import android.os.Bundle; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.os.Bundle; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.IOException; import androidx.appcompat.app.AppCompatActivity; public class PostActivity extends AppCompatActivity { Button btnbrowse, btnupload; EditText txtdata; ImageView imgview; Uri FilePathUri; StorageReference storageReference; DatabaseReference databaseReference; int Image_Request_Code = 7; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post); storageReference = FirebaseStorage.getInstance().getReference("Images"); databaseReference = FirebaseDatabase.getInstance().getReference("Images"); btnbrowse = findViewById(R.id.btnbrowse); btnupload = findViewById(R.id.btnupload); txtdata = findViewById(R.id.txtdata); imgview = findViewById(R.id.image_view); progressDialog = new ProgressDialog(PostActivity.this);// context name as per your project name btnbrowse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image"), Image_Request_Code); } }); btnupload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { UploadImage(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Image_Request_Code && resultCode == RESULT_OK && data != null && data.getData() != null) { FilePathUri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri); imgview.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } public String GetFileExtension(Uri uri) { ContentResolver contentResolver = getContentResolver(); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)); } public void UploadImage() { if (FilePathUri != null) { progressDialog.setTitle("Image is Uploading..."); progressDialog.show(); StorageReference storageReference2 = storageReference.child(System.currentTimeMillis() + "." + GetFileExtension(FilePathUri)); storageReference2.putFile(FilePathUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { String TempImageName = txtdata.getText().toString().trim(); progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show(); @SuppressWarnings("VisibleForTests") UpLoadInfo imageUploadInfo = new UpLoadInfo(TempImageName, taskSnapshot.getUploadSessionUri().toString()); String ImageUploadId = databaseReference.push().getKey(); databaseReference.child(ImageUploadId).setValue(imageUploadInfo); } }); } else { Toast.makeText(PostActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show(); } } }
[ "73516408+nhatthy24@users.noreply.github.com" ]
73516408+nhatthy24@users.noreply.github.com
2764c69f63e056a01bcc52b253e3acc00b3fc524
bf433954e66bfdad4aa4b9bec0574793f12541f3
/src/main/java/com/tild/desafio/blog/data/CommentRepository.java
f10b4de82029763230bd59bd7befed2c62726c1f
[]
no_license
lucasns/desafio-tild
524eec075147452e4eeddb0a1b5c228f62b56837
65e5adbf43a9616b1ced53d0830189447bb80d86
refs/heads/master
2021-05-15T18:27:55.062106
2017-10-23T12:08:04
2017-10-23T12:16:09
107,635,603
0
0
null
2017-10-24T01:41:36
2017-10-20T05:27:54
Java
UTF-8
Java
false
false
222
java
package com.tild.desafio.blog.data; import org.springframework.data.jpa.repository.JpaRepository; import com.tild.desafio.blog.model.Comment; public interface CommentRepository extends JpaRepository<Comment, Long> { }
[ "lucas.n15@outlook.com" ]
lucas.n15@outlook.com
d325a7afe7863485f0c3e5019ec8f3111a673bac
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/alibaba--fastjson/0018fa655339128cce68486bf11b1fe7f20b1eab/before/ASMDeserializerFactory.java
afd918c9f408640ec32e116e5427eecfa3f4ec97
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
67,476
java
package com.alibaba.fastjson.parser.deserializer; import static com.alibaba.fastjson.util.ASMUtils.getDesc; import static com.alibaba.fastjson.util.ASMUtils.getType; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.asm.ASMException; import com.alibaba.fastjson.asm.ClassWriter; import com.alibaba.fastjson.asm.FieldVisitor; import com.alibaba.fastjson.asm.Label; import com.alibaba.fastjson.asm.MethodVisitor; import com.alibaba.fastjson.asm.Opcodes; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONLexerBase; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.ParseContext; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.SymbolTable; import com.alibaba.fastjson.parser.deserializer.ASMJavaBeanDeserializer.InnerJavaBeanDeserializer; import com.alibaba.fastjson.util.ASMClassLoader; import com.alibaba.fastjson.util.ASMUtils; import com.alibaba.fastjson.util.DeserializeBeanInfo; import com.alibaba.fastjson.util.FieldInfo; public class ASMDeserializerFactory implements Opcodes { private static final ASMDeserializerFactory instance = new ASMDeserializerFactory(); private final ASMClassLoader classLoader; private final AtomicLong seed = new AtomicLong(); public String getGenClassName(Class<?> clazz) { return "Fastjson_ASM_" + clazz.getSimpleName() + "_" + seed.incrementAndGet(); } public String getGenFieldDeserializer(Class<?> clazz, FieldInfo fieldInfo) { String name = "Fastjson_ASM__Field_" + clazz.getSimpleName(); name += "_" + fieldInfo.getName() + "_" + seed.incrementAndGet(); return name; } public ASMDeserializerFactory(){ classLoader = new ASMClassLoader(); } public ASMDeserializerFactory(ClassLoader parentClassLoader){ classLoader = new ASMClassLoader(parentClassLoader); } public final static ASMDeserializerFactory getInstance() { return instance; } public boolean isExternalClass(Class<?> clazz) { return classLoader.isExternalClass(clazz); } public ObjectDeserializer createJavaBeanDeserializer(ParserConfig config, Class<?> clazz, Type type) throws Exception { if (clazz.isPrimitive()) { throw new IllegalArgumentException("not support type :" + clazz.getName()); } String className = getGenClassName(clazz); ClassWriter cw = new ClassWriter(); cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, getType(ASMJavaBeanDeserializer.class), null); DeserializeBeanInfo beanInfo = DeserializeBeanInfo.computeSetters(clazz, type); _init(cw, new Context(className, config, beanInfo, 3)); _createInstance(cw, new Context(className, config, beanInfo, 3)); _deserialze(cw, new Context(className, config, beanInfo, 4)); _deserialzeArrayMapping(cw, new Context(className, config, beanInfo, 4)); byte[] code = cw.toByteArray(); if(JSON.DUMP_CLASS != null){ FileOutputStream fos=null; try { fos=new FileOutputStream(JSON.DUMP_CLASS+ File.separator + className + ".class"); fos.write(code); }catch (Exception ex){ System.err.println("FASTJSON dump class:"+className+"失败:"+ex.getMessage()); }finally { if(fos!=null){ fos.close(); } } } Class<?> exampleClass = classLoader.defineClassPublic(className, code, 0, code.length); Constructor<?> constructor = exampleClass.getConstructor(ParserConfig.class, Class.class); Object instance = constructor.newInstance(config, clazz); return (ObjectDeserializer) instance; } void _setFlag(MethodVisitor mw, Context context, int i) { String varName = "_asm_flag_" + (i / 32); mw.visitVarInsn(ILOAD, context.var(varName)); mw.visitLdcInsn(1 << i); mw.visitInsn(IOR); mw.visitVarInsn(ISTORE, context.var(varName)); } void _isFlag(MethodVisitor mw, Context context, int i, Label label) { mw.visitVarInsn(ILOAD, context.var("_asm_flag_" + (i / 32))); mw.visitLdcInsn(1 << i); mw.visitInsn(IAND); mw.visitJumpInsn(IFEQ, label); } void _deserialzeArrayMapping(ClassWriter cw, Context context) { MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "deserialzeArrayMapping", "(" + getDesc(DefaultJSONParser.class) + getDesc(Type.class) + "Ljava/lang/Object;)Ljava/lang/Object;", null, null); defineVarLexer(context, mw); _createInstance(context, mw); List<FieldInfo> sortedFieldInfoList = context.getBeanInfo().getSortedFieldList(); int fieldListSize = sortedFieldInfoList.size(); for (int i = 0; i < fieldListSize; ++i) { final boolean last = (i == fieldListSize - 1); final char seperator = last ? ']' : ','; FieldInfo fieldInfo = sortedFieldInfoList.get(i); Class<?> fieldClass = fieldInfo.getFieldClass(); Type fieldType = fieldInfo.getFieldType(); if (fieldClass == byte.class // || fieldClass == short.class // || fieldClass == int.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanInt", "(C)I"); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == long.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanLong", "(C)J"); mw.visitVarInsn(LSTORE, context.var(fieldInfo.getName() + "_asm", 2)); } else if (fieldClass == boolean.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanBoolean", "(C)Z"); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == float.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFloat", "(C)F"); mw.visitVarInsn(FSTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == double.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanDouble", "(C)D"); mw.visitVarInsn(DSTORE, context.var(fieldInfo.getName() + "_asm", 2)); } else if (fieldClass == char.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanString", "(C)Ljava/lang/String;"); mw.visitInsn(ICONST_0); mw.visitMethodInsn(INVOKEVIRTUAL, getType(String.class), "charAt", "(I)C"); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == String.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanString", "(C)Ljava/lang/String;"); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(fieldClass))); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getSymbolTable", "()" + getDesc(SymbolTable.class)); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanEnum", "(Ljava/lang/Class;" + getDesc(SymbolTable.class) + "C)Ljava/lang/Enum;"); mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); } else if (Collection.class.isAssignableFrom(fieldClass)) { Class<?> itemClass = getCollectionItemClass(fieldType); if (itemClass == String.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(fieldClass))); mw.visitVarInsn(BIPUSH, seperator); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanStringArray", "(Ljava/lang/Class;C)Ljava/util/Collection;"); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); } else { mw.visitVarInsn(ALOAD, 1); if (i == 0) { mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); } else { mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); } mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "accept", "(II)V"); _newCollection(mw, fieldClass); mw.visitInsn(DUP); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); _getCollectionFieldItemDeser(context, mw, fieldInfo, itemClass); mw.visitVarInsn(ALOAD, 1); mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(itemClass))); mw.visitVarInsn(ALOAD, 3); mw.visitMethodInsn(INVOKESTATIC, getType(ASMUtils.class), "parseArray", "(Ljava/util/Collection;" // + getDesc(ObjectDeserializer.class) // + getDesc(DefaultJSONParser.class) // + "Ljava/lang/reflect/Type;Ljava/lang/Object;)V"); } } else { mw.visitVarInsn(ALOAD, 1); if (i == 0) { mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); } else { mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); } mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "accept", "(II)V"); _deserObject(context, mw, fieldInfo, fieldClass); mw.visitVarInsn(ALOAD, 1); if (!last) { mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); } else { mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "RBRACKET", "I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "EOF", "I"); } mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "accept", "(II)V"); continue; } } _batchSet(context, mw, false); // lexer.nextToken(JSONToken.COMMA); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "nextToken", "(I)V"); mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitInsn(ARETURN); mw.visitMaxs(5, context.getVariantCount()); mw.visitEnd(); } void _deserialze(ClassWriter cw, Context context) { if (context.getFieldInfoList().size() == 0) { return; } for (FieldInfo fieldInfo : context.getFieldInfoList()) { Class<?> fieldClass = fieldInfo.getFieldClass(); Type fieldType = fieldInfo.getFieldType(); if (fieldClass == char.class) { return; } if (Collection.class.isAssignableFrom(fieldClass)) { if (fieldType instanceof ParameterizedType) { Type itemType = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; if (itemType instanceof Class) { continue; } else { return; } } else { return; } } } Collections.sort(context.getFieldInfoList()); MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "deserialze", "(" + getDesc(DefaultJSONParser.class) + getDesc(Type.class) + "Ljava/lang/Object;)Ljava/lang/Object;", null, null); Label reset_ = new Label(); Label super_ = new Label(); Label return_ = new Label(); Label end_ = new Label(); defineVarLexer(context, mw); _isEnable(context, mw, Feature.SortFeidFastMatch); mw.visitJumpInsn(IFEQ, super_); { Label next_ = new Label(); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKESPECIAL, getType(ASMJavaBeanDeserializer.class), "isSupportArrayToBean", "(Lcom/alibaba/fastjson/parser/JSONLexer;)Z"); mw.visitJumpInsn(IFEQ, next_); //isSupportArrayToBean mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); mw.visitJumpInsn(IF_ICMPNE, next_); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, 2); mw.visitVarInsn(ALOAD, 3); mw.visitMethodInsn(INVOKESPECIAL, context.getClassName(), "deserialzeArrayMapping", "(" + getDesc(DefaultJSONParser.class) + getDesc(Type.class) + "Ljava/lang/Object;)Ljava/lang/Object;"); mw.visitInsn(ARETURN); mw.visitLabel(next_); // deserialzeArrayMapping } mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitLdcInsn(context.getClazz().getName()); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanType", "(Ljava/lang/String;)I"); mw.visitFieldInsn(GETSTATIC, getType(JSONLexerBase.class), "NOT_MATCH", "I"); mw.visitJumpInsn(IF_ICMPEQ, super_); mw.visitVarInsn(ALOAD, 1); // parser mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getContext", "()Lcom/alibaba/fastjson/parser/ParseContext;"); mw.visitVarInsn(ASTORE, context.var("mark_context")); // ParseContext context = parser.getContext(); mw.visitInsn(ICONST_0); mw.visitVarInsn(ISTORE, context.var("matchedCount")); _createInstance(context, mw); { mw.visitVarInsn(ALOAD, 1); // parser mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getContext", "()" + ASMUtils.getDesc(ParseContext.class)); mw.visitVarInsn(ASTORE, context.var("context")); mw.visitVarInsn(ALOAD, 1); // parser mw.visitVarInsn(ALOAD, context.var("context")); mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ALOAD, 3); // fieldName mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "setContext", "(" + ASMUtils.getDesc(ParseContext.class) + "Ljava/lang/Object;Ljava/lang/Object;)" + ASMUtils.getDesc(ParseContext.class)); mw.visitVarInsn(ASTORE, context.var("childContext")); } mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETFIELD, getType(JSONLexerBase.class), "matchStat", "I"); mw.visitFieldInsn(GETSTATIC, getType(JSONLexerBase.class), "END", "I"); mw.visitJumpInsn(IF_ICMPEQ, return_); mw.visitInsn(ICONST_0); // UNKOWN mw.visitIntInsn(ISTORE, context.var("matchStat")); int fieldListSize = context.getFieldInfoList().size(); for (int i = 0; i < fieldListSize; i += 32) { mw.visitInsn(ICONST_0); mw.visitVarInsn(ISTORE, context.var("_asm_flag_" + (i / 32))); } // declare and init for (int i = 0; i < fieldListSize; ++i) { FieldInfo fieldInfo = context.getFieldInfoList().get(i); Class<?> fieldClass = fieldInfo.getFieldClass(); if (fieldClass == boolean.class // || fieldClass == byte.class // || fieldClass == short.class // || fieldClass == int.class) { mw.visitInsn(ICONST_0); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == long.class) { mw.visitInsn(LCONST_0); mw.visitVarInsn(LSTORE, context.var(fieldInfo.getName() + "_asm", 2)); } else if (fieldClass == float.class) { mw.visitInsn(FCONST_0); mw.visitVarInsn(FSTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == double.class) { mw.visitInsn(DCONST_0); mw.visitVarInsn(DSTORE, context.var(fieldInfo.getName() + "_asm", 2)); } else { if (fieldClass == String.class) { Label flagEnd_ = new Label(); _isEnable(context, mw, Feature.InitStringFieldAsEmpty); mw.visitJumpInsn(IFEQ, flagEnd_); _setFlag(mw, context, i); mw.visitLabel(flagEnd_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "stringDefaultValue", "()Ljava/lang/String;"); } else { mw.visitInsn(ACONST_NULL); } mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); } } for (int i = 0; i < fieldListSize; ++i) { FieldInfo fieldInfo = context.getFieldInfoList().get(i); Class<?> fieldClass = fieldInfo.getFieldClass(); Type fieldType = fieldInfo.getFieldType(); Label notMatch_ = new Label(); if (fieldClass == boolean.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldBoolean", "([C)Z"); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == byte.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldInt", "([C)I"); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == short.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldInt", "([C)I"); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == int.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldInt", "([C)I"); mw.visitVarInsn(ISTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == long.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldLong", "([C)J"); mw.visitVarInsn(LSTORE, context.var(fieldInfo.getName() + "_asm", 2)); } else if (fieldClass == float.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldFloat", "([C)F"); mw.visitVarInsn(FSTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass == double.class) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldDouble", "([C)D"); mw.visitVarInsn(DSTORE, context.var(fieldInfo.getName() + "_asm", 2)); } else if (fieldClass == String.class) { Label notEnd_ = new Label(); mw.visitIntInsn(ILOAD, context.var("matchStat")); mw.visitInsn(ICONST_4); // END mw.visitJumpInsn(IF_ICMPNE, notEnd_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "stringDefaultValue", "()Ljava/lang/String;"); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); mw.visitJumpInsn(GOTO, notMatch_); mw.visitLabel(notEnd_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldString", "([C)Ljava/lang/String;"); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); } else if (fieldClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); Label enumNull_ = new Label(); mw.visitInsn(ACONST_NULL); mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getSymbolTable", "()" + getDesc(SymbolTable.class)); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldSymbol", "([C" + getDesc(SymbolTable.class) + ")Ljava/lang/String;"); mw.visitInsn(DUP); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm_enumName")); mw.visitJumpInsn(IFNULL, enumNull_); mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm_enumName")); mw.visitMethodInsn(INVOKESTATIC, getType(fieldClass), "valueOf", "(Ljava/lang/String;)" + getDesc(fieldClass)); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); mw.visitLabel(enumNull_); } else if (Collection.class.isAssignableFrom(fieldClass)) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); Class<?> itemClass = getCollectionItemClass(fieldType); if (itemClass == String.class) { mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(fieldClass))); // cast mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "scanFieldStringArray", "([CLjava/lang/Class;)" + getDesc(Collection.class)); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); } else { _deserialze_list_obj(context, mw, reset_, fieldInfo, fieldClass, itemClass, i); if (i == fieldListSize - 1) { _deserialize_endCheck(context, mw, reset_); } continue; } } else { _deserialze_obj(context, mw, reset_, fieldInfo, fieldClass, i); if (i == fieldListSize - 1) { _deserialize_endCheck(context, mw, reset_); } continue; } mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETFIELD, getType(JSONLexerBase.class), "matchStat", "I"); Label flag_ = new Label(); // mw.visitInsn(DUP); mw.visitJumpInsn(IFLE, flag_); _setFlag(mw, context, i); mw.visitLabel(flag_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETFIELD, getType(JSONLexerBase.class), "matchStat", "I"); mw.visitInsn(DUP); mw.visitVarInsn(ISTORE, context.var("matchStat")); mw.visitFieldInsn(GETSTATIC, getType(JSONLexerBase.class), "NOT_MATCH", "I"); mw.visitJumpInsn(IF_ICMPEQ, reset_); // mw.visitFieldInsn(GETSTATIC, getType(System.class), "out", "Ljava/io/PrintStream;"); // mw.visitVarInsn(ALOAD, context.var("lexer")); // mw.visitFieldInsn(GETFIELD, getType(JSONLexerBase.class), "matchStat", "I"); // mw.visitMethodInsn(INVOKEVIRTUAL, getType(java.io.PrintStream.class), "println", "(I)V"); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETFIELD, getType(JSONLexerBase.class), "matchStat", "I"); mw.visitJumpInsn(IFLE, notMatch_); // increment matchedCount mw.visitVarInsn(ILOAD, context.var("matchedCount")); mw.visitInsn(ICONST_1); mw.visitInsn(IADD); mw.visitVarInsn(ISTORE, context.var("matchedCount")); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETFIELD, getType(JSONLexerBase.class), "matchStat", "I"); mw.visitFieldInsn(GETSTATIC, getType(JSONLexerBase.class), "END", "I"); mw.visitJumpInsn(IF_ICMPEQ, end_); // mw.visitFieldInsn(GETSTATIC, getType(System.class), "out", "Ljava/io/PrintStream;"); // mw.visitVarInsn(ILOAD, context.var("matchedCount")); // mw.visitMethodInsn(INVOKEVIRTUAL, getType(java.io.PrintStream.class), "println", "(I)V"); mw.visitLabel(notMatch_); if (i == fieldListSize - 1) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETFIELD, getType(JSONLexerBase.class), "matchStat", "I"); mw.visitFieldInsn(GETSTATIC, getType(JSONLexerBase.class), "END", "I"); mw.visitJumpInsn(IF_ICMPNE, reset_); } } // endFor mw.visitLabel(end_); if (!context.getClazz().isInterface() && !Modifier.isAbstract(context.getClazz().getModifiers())) { _batchSet(context, mw); } mw.visitLabel(return_); _setContext(context, mw); mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitInsn(ARETURN); mw.visitLabel(reset_); _batchSet(context, mw); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, 2); mw.visitVarInsn(ALOAD, 3); mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ASMJavaBeanDeserializer.class), "parseRest", "(" + getDesc(DefaultJSONParser.class) + getDesc(Type.class) + "Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); mw.visitTypeInsn(CHECKCAST, getType(context.getClazz())); // cast mw.visitInsn(ARETURN); mw.visitLabel(super_); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, 2); mw.visitVarInsn(ALOAD, 3); mw.visitMethodInsn(INVOKESPECIAL, getType(ASMJavaBeanDeserializer.class), "deserialze", "(" + getDesc(DefaultJSONParser.class) + getDesc(Type.class) + "Ljava/lang/Object;)Ljava/lang/Object;"); mw.visitInsn(ARETURN); mw.visitMaxs(5, context.getVariantCount()); mw.visitEnd(); } private Class<?> getCollectionItemClass(Type fieldType) { if (fieldType instanceof ParameterizedType) { Class<?> itemClass; Type actualTypeArgument = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; if (actualTypeArgument instanceof Class) { itemClass = (Class<?>) actualTypeArgument; if (!Modifier.isPublic(itemClass.getModifiers())) { throw new ASMException("can not create ASMParser"); } } else { throw new ASMException("can not create ASMParser"); } return itemClass; } return Object.class; } private void _isEnable(Context context, MethodVisitor mw, Feature feature) { mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETSTATIC, getType(Feature.class), feature.name(), "L" + getType(Feature.class) + ";"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "isEnabled", "(" + "L" + getType(Feature.class) + ";" + ")Z"); } private void defineVarLexer(Context context, MethodVisitor mw) { mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getLexer", "()" + getDesc(JSONLexer.class)); mw.visitTypeInsn(CHECKCAST, getType(JSONLexerBase.class)); // cast mw.visitVarInsn(ASTORE, context.var("lexer")); } private void _createInstance(Context context, MethodVisitor mw) { Constructor<?> defaultConstructor = context.getBeanInfo().getDefaultConstructor(); if (Modifier.isPublic(defaultConstructor.getModifiers())) { mw.visitTypeInsn(NEW, getType(context.getClazz())); mw.visitInsn(DUP); mw.visitMethodInsn(INVOKESPECIAL, getType(context.getClazz()), "<init>", "()V"); mw.visitVarInsn(ASTORE, context.var("instance")); } else { mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKESPECIAL, getType(ASMJavaBeanDeserializer.class), "createInstance", "(" + getDesc(DefaultJSONParser.class) + ")Ljava/lang/Object;"); mw.visitTypeInsn(CHECKCAST, getType(context.getClazz())); // cast mw.visitVarInsn(ASTORE, context.var("instance")); } } private void _batchSet(Context context, MethodVisitor mw) { _batchSet(context, mw, true); } private void _batchSet(Context context, MethodVisitor mw, boolean flag) { for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { Label notSet_ = new Label(); if (flag) { _isFlag(mw, context, i, notSet_); } FieldInfo fieldInfo = context.getFieldInfoList().get(i); _loadAndSet(context, mw, fieldInfo); if (flag) { mw.visitLabel(notSet_); } } } private void _loadAndSet(Context context, MethodVisitor mw, FieldInfo fieldInfo) { Class<?> fieldClass = fieldInfo.getFieldClass(); Type fieldType = fieldInfo.getFieldType(); if (fieldClass == boolean.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ILOAD, context.var(fieldInfo.getName() + "_asm")); _set(context, mw, fieldInfo); } else if (fieldClass == byte.class // || fieldClass == short.class // || fieldClass == int.class // || fieldClass == char.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ILOAD, context.var(fieldInfo.getName() + "_asm")); _set(context, mw, fieldInfo); } else if (fieldClass == long.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(LLOAD, context.var(fieldInfo.getName() + "_asm", 2)); if (fieldInfo.getMethod() != null) { mw.visitMethodInsn(INVOKEVIRTUAL, getType(context.getClazz()), fieldInfo.getMethod().getName(), getDesc(fieldInfo.getMethod())); if (!fieldInfo.getMethod().getReturnType().equals(Void.TYPE)) { mw.visitInsn(POP); } } else { mw.visitFieldInsn(PUTFIELD, getType(fieldInfo.getDeclaringClass()), fieldInfo.getField().getName(), getDesc(fieldInfo.getFieldClass())); } } else if (fieldClass == float.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(FLOAD, context.var(fieldInfo.getName() + "_asm")); _set(context, mw, fieldInfo); } else if (fieldClass == double.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(DLOAD, context.var(fieldInfo.getName() + "_asm", 2)); _set(context, mw, fieldInfo); } else if (fieldClass == String.class) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); _set(context, mw, fieldInfo); } else if (fieldClass.isEnum()) { mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); _set(context, mw, fieldInfo); } else if (Collection.class.isAssignableFrom(fieldClass)) { mw.visitVarInsn(ALOAD, context.var("instance")); Type itemType = getCollectionItemClass(fieldType); if (itemType == String.class) { mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast } else { mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); } _set(context, mw, fieldInfo); } else { // mw.visitFieldInsn(GETSTATIC, getType(System.class), "out", "Ljava/io/PrintStream;"); // mw.visitIntInsn(ILOAD, context.var(fieldInfo.getName() + "_asm_flag")); // mw.visitMethodInsn(INVOKEVIRTUAL, getType(java.io.PrintStream.class), "println", "(I)V"); // _isFlag(mw, context, i, notSet_); mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); _set(context, mw, fieldInfo); } } private void _set(Context context, MethodVisitor mw, FieldInfo fieldInfo) { if (fieldInfo.getMethod() != null) { mw.visitMethodInsn(INVOKEVIRTUAL, getType(fieldInfo.getDeclaringClass()), fieldInfo.getMethod().getName(), getDesc(fieldInfo.getMethod())); if (!fieldInfo.getMethod().getReturnType().equals(Void.TYPE)) { mw.visitInsn(POP); } } else { mw.visitFieldInsn(PUTFIELD, getType(fieldInfo.getDeclaringClass()), fieldInfo.getField().getName(), getDesc(fieldInfo.getFieldClass())); } } private void _setContext(Context context, MethodVisitor mw) { mw.visitVarInsn(ALOAD, 1); // parser mw.visitVarInsn(ALOAD, context.var("context")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "setContext", "(" + ASMUtils.getDesc(ParseContext.class) + ")V"); Label endIf_ = new Label(); mw.visitVarInsn(ALOAD, context.var("childContext")); mw.visitJumpInsn(IFNULL, endIf_); mw.visitVarInsn(ALOAD, context.var("childContext")); mw.visitVarInsn(ALOAD, context.var("instance")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ParseContext.class), "setObject", "(Ljava/lang/Object;)V"); mw.visitLabel(endIf_); } private void _deserialize_endCheck(Context context, MethodVisitor mw, Label reset_) { Label _end_if = new Label(); // Label nextToken_ = new Label(); // mw.visitFieldInsn(GETSTATIC, getType(System.class), "out", "Ljava/io/PrintStream;"); // mw.visitIntInsn(ILOAD, context.var("matchedCount")); // mw.visitMethodInsn(INVOKEVIRTUAL, getType(java.io.PrintStream.class), "println", "(I)V"); mw.visitIntInsn(ILOAD, context.var("matchedCount")); mw.visitJumpInsn(IFLE, reset_); // mw.visitFieldInsn(GETSTATIC, getType(System.class), "out", "Ljava/io/PrintStream;"); // mw.visitVarInsn(ALOAD, context.var("lexer")); // mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); // mw.visitMethodInsn(INVOKEVIRTUAL, getType(java.io.PrintStream.class), "println", "(I)V"); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "RBRACE", "I"); mw.visitJumpInsn(IF_ICMPNE, reset_); // mw.visitLabel(nextToken_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "nextToken", "(I)V"); mw.visitLabel(_end_if); } private void _deserialze_list_obj(Context context, MethodVisitor mw, Label reset_, FieldInfo fieldInfo, Class<?> fieldClass, Class<?> itemType, int i) { Label matched_ = new Label(); Label _end_if = new Label(); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "matchField", "([C)Z"); mw.visitJumpInsn(IFNE, matched_); mw.visitInsn(ACONST_NULL); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); mw.visitJumpInsn(GOTO, _end_if); mw.visitLabel(matched_); _setFlag(mw, context, i); Label valueNotNull_ = new Label(); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "NULL", "I"); mw.visitJumpInsn(IF_ICMPNE, valueNotNull_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "nextToken", "(I)V"); mw.visitInsn(ACONST_NULL); mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); // loop_end_ mw.visitLabel(valueNotNull_); // if (lexer.token() != JSONToken.LBRACKET) reset mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "LBRACKET", "I"); mw.visitJumpInsn(IF_ICMPNE, reset_); _getCollectionFieldItemDeser(context, mw, fieldInfo, itemType); mw.visitMethodInsn(INVOKEINTERFACE, getType(ObjectDeserializer.class), "getFastMatchToken", "()I"); mw.visitVarInsn(ISTORE, context.var("fastMatchToken")); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ILOAD, context.var("fastMatchToken")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "nextToken", "(I)V"); _newCollection(mw, fieldClass); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); { // setContext mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getContext", "()" + ASMUtils.getDesc(ParseContext.class)); mw.visitVarInsn(ASTORE, context.var("listContext")); mw.visitVarInsn(ALOAD, 1); // parser mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); mw.visitLdcInsn(fieldInfo.getName()); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "setContext", "(Ljava/lang/Object;Ljava/lang/Object;)" + ASMUtils.getDesc(ParseContext.class)); mw.visitInsn(POP); } Label loop_ = new Label(); Label loop_end_ = new Label(); // for (;;) { mw.visitInsn(ICONST_0); mw.visitVarInsn(ISTORE, context.var("i")); mw.visitLabel(loop_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "RBRACKET", "I"); mw.visitJumpInsn(IF_ICMPEQ, loop_end_); // Object value = itemDeserializer.deserialze(parser, null); // array.add(value); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", getDesc(ObjectDeserializer.class)); mw.visitVarInsn(ALOAD, 1); mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(itemType))); mw.visitVarInsn(ILOAD, context.var("i")); mw.visitMethodInsn(INVOKESTATIC, getType(Integer.class), "valueOf", "(I)Ljava/lang/Integer;"); mw.visitMethodInsn(INVOKEINTERFACE, getType(ObjectDeserializer.class), "deserialze", "(" + ASMUtils.getDesc(DefaultJSONParser.class) + "Ljava/lang/reflect/Type;Ljava/lang/Object;)Ljava/lang/Object;"); mw.visitVarInsn(ASTORE, context.var("list_item_value")); mw.visitIincInsn(context.var("i"), 1); mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); mw.visitVarInsn(ALOAD, context.var("list_item_value")); if (fieldClass.isInterface()) { mw.visitMethodInsn(INVOKEINTERFACE, getType(fieldClass), "add", "(Ljava/lang/Object;)Z"); } else { mw.visitMethodInsn(INVOKEVIRTUAL, getType(fieldClass), "add", "(Ljava/lang/Object;)Z"); } mw.visitInsn(POP); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, context.var(fieldInfo.getName() + "_asm")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "checkListResolve", "(Ljava/util/Collection;)V"); // if (lexer.token() == JSONToken.COMMA) { // lexer.nextToken(itemDeserializer.getFastMatchToken()); // continue; // } mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); mw.visitJumpInsn(IF_ICMPNE, loop_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ILOAD, context.var("fastMatchToken")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "nextToken", "(I)V"); mw.visitJumpInsn(GOTO, loop_); mw.visitLabel(loop_end_); // mw.visitVarInsn(ASTORE, context.var("context")); // parser.setContext(context); { // setContext mw.visitVarInsn(ALOAD, 1); // parser mw.visitVarInsn(ALOAD, context.var("listContext")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "setContext", "(" + ASMUtils.getDesc(ParseContext.class) + ")V"); } mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "token", "()I"); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "RBRACKET", "I"); mw.visitJumpInsn(IF_ICMPNE, reset_); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitFieldInsn(GETSTATIC, getType(JSONToken.class), "COMMA", "I"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "nextToken", "(I)V"); // lexer.nextToken(JSONToken.COMMA); mw.visitLabel(_end_if); } private void _getCollectionFieldItemDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo, Class<?> itemType) { Label notNull_ = new Label(); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", getDesc(ObjectDeserializer.class)); mw.visitJumpInsn(IFNONNULL, notNull_); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getConfig", "()" + getDesc(ParserConfig.class)); mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(itemType))); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ParserConfig.class), "getDeserializer", "(" + getDesc(Type.class) + ")" + getDesc(ObjectDeserializer.class)); mw.visitFieldInsn(PUTFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", getDesc(ObjectDeserializer.class)); mw.visitLabel(notNull_); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_list_item_deser__", getDesc(ObjectDeserializer.class)); } private void _newCollection(MethodVisitor mw, Class<?> fieldClass) { if (fieldClass.isAssignableFrom(ArrayList.class)) { mw.visitTypeInsn(NEW, getType(ArrayList.class)); mw.visitInsn(DUP); mw.visitMethodInsn(INVOKESPECIAL, getType(ArrayList.class), "<init>", "()V"); } else if (fieldClass.isAssignableFrom(LinkedList.class)) { mw.visitTypeInsn(NEW, getType(LinkedList.class)); mw.visitInsn(DUP); mw.visitMethodInsn(INVOKESPECIAL, getType(LinkedList.class), "<init>", "()V"); } else if (fieldClass.isAssignableFrom(HashSet.class)) { mw.visitTypeInsn(NEW, getType(HashSet.class)); mw.visitInsn(DUP); mw.visitMethodInsn(INVOKESPECIAL, getType(HashSet.class), "<init>", "()V"); } else if (fieldClass.isAssignableFrom(TreeSet.class)) { mw.visitTypeInsn(NEW, getType(TreeSet.class)); mw.visitInsn(DUP); mw.visitMethodInsn(INVOKESPECIAL, getType(TreeSet.class), "<init>", "()V"); } else { mw.visitTypeInsn(NEW, getType(fieldClass)); mw.visitInsn(DUP); mw.visitMethodInsn(INVOKESPECIAL, getType(fieldClass), "<init>", "()V"); } mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast } private void _deserialze_obj(Context context, MethodVisitor mw, Label reset_, FieldInfo fieldInfo, Class<?> fieldClass, int i) { Label matched_ = new Label(); Label _end_if = new Label(); mw.visitVarInsn(ALOAD, context.var("lexer")); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JSONLexerBase.class), "matchField", "([C)Z"); mw.visitJumpInsn(IFNE, matched_); mw.visitInsn(ACONST_NULL); mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); mw.visitJumpInsn(GOTO, _end_if); mw.visitLabel(matched_); _setFlag(mw, context, i); // increment matchedCount mw.visitVarInsn(ILOAD, context.var("matchedCount")); mw.visitInsn(ICONST_1); mw.visitInsn(IADD); mw.visitVarInsn(ISTORE, context.var("matchedCount")); _deserObject(context, mw, fieldInfo, fieldClass); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getResolveStatus", "()I"); mw.visitFieldInsn(GETSTATIC, getType(DefaultJSONParser.class), "NeedToResolve", "I"); mw.visitJumpInsn(IF_ICMPNE, _end_if); // ResolveTask task = parser.getLastResolveTask(); // task.setFieldDeserializer(this); // task.setOwnerContext(parser.getContext()); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getLastResolveTask", "()" + getDesc(ResolveTask.class)); mw.visitVarInsn(ASTORE, context.var("resolveTask")); mw.visitVarInsn(ALOAD, context.var("resolveTask")); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getContext", "()" + getDesc(ParseContext.class)); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ResolveTask.class), "setOwnerContext", "(" + getDesc(ParseContext.class) + ")V"); mw.visitVarInsn(ALOAD, context.var("resolveTask")); mw.visitVarInsn(ALOAD, 0); mw.visitLdcInsn(fieldInfo.getName()); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ASMJavaBeanDeserializer.class), "getFieldDeserializer", "(Ljava/lang/String;)" + getDesc(FieldDeserializer.class)); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ResolveTask.class), "setFieldDeserializer", "(" + getDesc(FieldDeserializer.class) + ")V"); mw.visitVarInsn(ALOAD, 1); mw.visitFieldInsn(GETSTATIC, getType(DefaultJSONParser.class), "NONE", "I"); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "setResolveStatus", "(I)V"); mw.visitLabel(_end_if); } private void _deserObject(Context context, MethodVisitor mw, FieldInfo fieldInfo, Class<?> fieldClass) { _getFieldDeser(context, mw, fieldInfo); mw.visitVarInsn(ALOAD, 1); if (fieldInfo.getFieldType() instanceof Class) { mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(fieldInfo.getFieldClass()))); } else { mw.visitVarInsn(ALOAD, 0); mw.visitLdcInsn(fieldInfo.getName()); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ASMJavaBeanDeserializer.class), "getFieldType", "(Ljava/lang/String;)Ljava/lang/reflect/Type;"); } mw.visitLdcInsn(fieldInfo.getName()); mw.visitMethodInsn(INVOKEINTERFACE, getType(ObjectDeserializer.class), "deserialze", "(" + getDesc(DefaultJSONParser.class) + getDesc(Type.class) + "Ljava/lang/Object;)Ljava/lang/Object;"); mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast mw.visitVarInsn(ASTORE, context.var(fieldInfo.getName() + "_asm")); } private void _getFieldDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo) { Label notNull_ = new Label(); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_deser__", getDesc(ObjectDeserializer.class)); mw.visitJumpInsn(IFNONNULL, notNull_); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitMethodInsn(INVOKEVIRTUAL, getType(DefaultJSONParser.class), "getConfig", "()" + getDesc(ParserConfig.class)); mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(getDesc(fieldInfo.getFieldClass()))); mw.visitMethodInsn(INVOKEVIRTUAL, getType(ParserConfig.class), "getDeserializer", "(" + getDesc(Type.class) + ")" + getDesc(ObjectDeserializer.class)); mw.visitFieldInsn(PUTFIELD, context.getClassName(), fieldInfo.getName() + "_asm_deser__", getDesc(ObjectDeserializer.class)); mw.visitLabel(notNull_); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, context.getClassName(), fieldInfo.getName() + "_asm_deser__", getDesc(ObjectDeserializer.class)); } public FieldDeserializer createFieldDeserializer(ParserConfig mapping, Class<?> clazz, FieldInfo fieldInfo) throws Exception { Class<?> fieldClass = fieldInfo.getFieldClass(); if (fieldClass == int.class || fieldClass == long.class || fieldClass == String.class) { return createStringFieldDeserializer(mapping, clazz, fieldInfo); } FieldDeserializer fieldDeserializer = mapping.createFieldDeserializerWithoutASM(mapping, clazz, fieldInfo); return fieldDeserializer; } public FieldDeserializer createStringFieldDeserializer(ParserConfig mapping, Class<?> clazz, FieldInfo fieldInfo) throws Exception { Class<?> fieldClass = fieldInfo.getFieldClass(); Method method = fieldInfo.getMethod(); String className = getGenFieldDeserializer(clazz, fieldInfo); ClassWriter cw = new ClassWriter(); Class<?> superClass; if (fieldClass == int.class) { superClass = IntegerFieldDeserializer.class; } else if (fieldClass == long.class) { superClass = LongFieldDeserializer.class; } else { superClass = StringFieldDeserializer.class; } int INVAKE_TYPE; if (clazz.isInterface()) { INVAKE_TYPE = INVOKEINTERFACE; } else { INVAKE_TYPE = INVOKEVIRTUAL; } cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, getType(superClass), null); { MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "(" + getDesc(ParserConfig.class) + getDesc(Class.class) + getDesc(FieldInfo.class) + ")V", null, null); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, 2); mw.visitVarInsn(ALOAD, 3); mw.visitMethodInsn(INVOKESPECIAL, getType(superClass), "<init>", "(" + getDesc(ParserConfig.class) + getDesc(Class.class) + getDesc(FieldInfo.class) + ")V"); mw.visitInsn(RETURN); mw.visitMaxs(4, 6); mw.visitEnd(); } if (method != null) { if (fieldClass == int.class) { MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "setValue", "(" + getDesc(Object.class) + "I)V", null, null); mw.visitVarInsn(ALOAD, 1); mw.visitTypeInsn(CHECKCAST, getType(method.getDeclaringClass())); // cast mw.visitVarInsn(ILOAD, 2); mw.visitMethodInsn(INVAKE_TYPE, getType(method.getDeclaringClass()), method.getName(), ASMUtils.getDesc(method)); mw.visitInsn(RETURN); mw.visitMaxs(3, 3); mw.visitEnd(); } else if (fieldClass == long.class) { MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "setValue", "(" + getDesc(Object.class) + "J)V", null, null); mw.visitVarInsn(ALOAD, 1); mw.visitTypeInsn(CHECKCAST, getType(method.getDeclaringClass())); // cast mw.visitVarInsn(LLOAD, 2); mw.visitMethodInsn(INVAKE_TYPE, getType(method.getDeclaringClass()), method.getName(), ASMUtils.getDesc(method)); mw.visitInsn(RETURN); mw.visitMaxs(3, 4); mw.visitEnd(); } else { // public void setValue(Object object, Object value) MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "setValue", "(" + getDesc(Object.class) + getDesc(Object.class) + ")V", null, null); mw.visitVarInsn(ALOAD, 1); mw.visitTypeInsn(CHECKCAST, getType(method.getDeclaringClass())); // cast mw.visitVarInsn(ALOAD, 2); mw.visitTypeInsn(CHECKCAST, getType(fieldClass)); // cast mw.visitMethodInsn(INVAKE_TYPE, getType(method.getDeclaringClass()), method.getName(), ASMUtils.getDesc(method)); mw.visitInsn(RETURN); mw.visitMaxs(3, 3); mw.visitEnd(); } } byte[] code = cw.toByteArray(); Class<?> exampleClass = classLoader.defineClassPublic(className, code, 0, code.length); Constructor<?> constructor = exampleClass.getConstructor(ParserConfig.class, Class.class, FieldInfo.class); Object instance = constructor.newInstance(mapping, clazz, fieldInfo); return (FieldDeserializer) instance; } static class Context { private int variantIndex = 5; private Map<String, Integer> variants = new HashMap<String, Integer>(); private Class<?> clazz; private final DeserializeBeanInfo beanInfo; private String className; private List<FieldInfo> fieldInfoList; public Context(String className, ParserConfig config, DeserializeBeanInfo beanInfo, int initVariantIndex){ this.className = className; this.clazz = beanInfo.getClazz(); this.variantIndex = initVariantIndex; this.beanInfo = beanInfo; fieldInfoList = new ArrayList<FieldInfo>(beanInfo.getFieldList()); } public String getClassName() { return className; } public List<FieldInfo> getFieldInfoList() { return fieldInfoList; } public DeserializeBeanInfo getBeanInfo() { return beanInfo; } public Class<?> getClazz() { return clazz; } public int getVariantCount() { return variantIndex; } public int var(String name, int increment) { Integer i = variants.get(name); if (i == null) { variants.put(name, variantIndex); variantIndex += increment; } i = variants.get(name); return i.intValue(); } public int var(String name) { Integer i = variants.get(name); if (i == null) { variants.put(name, variantIndex++); } i = variants.get(name); return i.intValue(); } } private void _init(ClassWriter cw, Context context) { for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { FieldInfo fieldInfo = context.getFieldInfoList().get(i); // public FieldVisitor visitField(final int access, final String name, final String desc, final String // signature, final Object value) { FieldVisitor fw = cw.visitField(ACC_PUBLIC, fieldInfo.getName() + "_asm_prefix__", "[C"); fw.visitEnd(); } for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { FieldInfo fieldInfo = context.getFieldInfoList().get(i); Class<?> fieldClass = fieldInfo.getFieldClass(); if (fieldClass.isPrimitive()) { continue; } if (fieldClass.isEnum()) { continue; } if (Collection.class.isAssignableFrom(fieldClass)) { FieldVisitor fw = cw.visitField(ACC_PUBLIC, fieldInfo.getName() + "_asm_list_item_deser__", getDesc(ObjectDeserializer.class)); fw.visitEnd(); } else { FieldVisitor fw = cw.visitField(ACC_PUBLIC, fieldInfo.getName() + "_asm_deser__", getDesc(ObjectDeserializer.class)); fw.visitEnd(); } } MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "(" + getDesc(ParserConfig.class) + getDesc(Class.class) + ")V", null, null); mw.visitVarInsn(ALOAD, 0); mw.visitVarInsn(ALOAD, 1); mw.visitVarInsn(ALOAD, 2); mw.visitMethodInsn(INVOKESPECIAL, getType(ASMJavaBeanDeserializer.class), "<init>", "(" + getDesc(ParserConfig.class) + getDesc(Class.class) + ")V"); mw.visitVarInsn(ALOAD, 0); mw.visitFieldInsn(GETFIELD, getType(ASMJavaBeanDeserializer.class), "serializer", getDesc(InnerJavaBeanDeserializer.class)); mw.visitMethodInsn(INVOKEVIRTUAL, getType(JavaBeanDeserializer.class), "getFieldDeserializerMap", "()" + getDesc(Map.class)); mw.visitInsn(POP); // init fieldNamePrefix for (int i = 0, size = context.getFieldInfoList().size(); i < size; ++i) { FieldInfo fieldInfo = context.getFieldInfoList().get(i); mw.visitVarInsn(ALOAD, 0); mw.visitLdcInsn("\"" + fieldInfo.getName() + "\":"); // public char[] toCharArray() mw.visitMethodInsn(INVOKEVIRTUAL, getType(String.class), "toCharArray", "()" + getDesc(char[].class)); mw.visitFieldInsn(PUTFIELD, context.getClassName(), fieldInfo.getName() + "_asm_prefix__", "[C"); } mw.visitInsn(RETURN); mw.visitMaxs(4, 4); mw.visitEnd(); } private void _createInstance(ClassWriter cw, Context context) { MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "createInstance", "(" + getDesc(DefaultJSONParser.class) + getDesc(Type.class) + ")Ljava/lang/Object;", null, null); mw.visitTypeInsn(NEW, getType(context.getClazz())); mw.visitInsn(DUP); mw.visitMethodInsn(INVOKESPECIAL, getType(context.getClazz()), "<init>", "()V"); mw.visitInsn(ARETURN); mw.visitMaxs(3, 3); mw.visitEnd(); } }
[ "fraczwojciech@gmail.com" ]
fraczwojciech@gmail.com
3729acb640601a5db86a64bbf7d48124923a80f6
62c945edeeff44a25b959c6fabf10b0cbc6a8042
/framework_view/src/com/segi/view/calendar/bizs/calendars/DPCNCalendar.java
b770bcad0b2d136e1026c21419f7c1e96d07bb6b
[]
no_license
haijdong/Engagement
320025129ca5ac2cbdb6cff019731b3e239627a0
d8bd6ea208cc416043a0a5b767a85e7f494a7a63
refs/heads/master
2020-03-22T04:46:47.025514
2018-12-12T03:25:03
2018-12-12T03:25:03
139,520,648
0
0
null
null
null
null
UTF-8
Java
false
false
15,143
java
package com.segi.view.calendar.bizs.calendars; import android.text.TextUtils; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * 中国月历 * * Calendar of China * * @author AigeStudio 2015-06-16 */ public class DPCNCalendar extends DPCalendar { private static final int[] FIRST_DAY_OF_LUNAR_IN_GREGORIAN = {1897, 0x75aa, 0x156a, 0x1096d, 0x95c, 0x14ae, 0xaa4d, 0x1a4c, 0x1b2a, 0x8d55, 0xad4, 0x135a, 0x495d, 0x95c, 0xd49b, 0x149a, 0x1a4a, 0xbaa5, 0x16a8, 0x1ad4, 0x52da, 0x12b6, 0xe937, 0x92e, 0x1496, 0xb64b, 0xd4a, 0xda8, 0x95b5, 0x56c, 0x12ae, 0x492f, 0x92e, 0xcc96, 0x1a94, 0x1d4a, 0xada9, 0xb5a, 0x56c, 0x726e, 0x125c, 0xf92d, 0x192a, 0x1a94, 0xdb4a, 0x16aa, 0xad4, 0x955b, 0x4ba, 0x125a, 0x592b, 0x152a, 0xf695, 0xd94, 0x16aa, 0xaab5, 0x9b4, 0x14b6, 0x6a57, 0xa56, 0x1152a, 0x1d2a, 0xd54, 0xd5aa, 0x156a, 0x96c, 0x94ae, 0x14ae, 0xa4c, 0x7d26, 0x1b2a, 0xeb55, 0xad4, 0x12da, 0xa95d, 0x95a, 0x149a, 0x9a4d, 0x1a4a, 0x11aa5, 0x16a8, 0x16d4, 0xd2da, 0x12b6, 0x936, 0x9497, 0x1496, 0x1564b, 0xd4a, 0xda8, 0xd5b4, 0x156c, 0x12ae, 0xa92f, 0x92e, 0xc96, 0x6d4a, 0x1d4a, 0x10d65, 0xb58, 0x156c, 0xb26d, 0x125c, 0x192c, 0x9a95, 0x1a94, 0x1b4a, 0x4b55, 0xad4, 0xf55b, 0x4ba, 0x125a, 0xb92b, 0x152a, 0x1694, 0x96aa, 0x15aa, 0x12ab5, 0x974, 0x14b6, 0xca57, 0xa56, 0x1526, 0x8e95, 0xd54, 0x15aa, 0x49b5, 0x96c, 0xd4ae, 0x149c, 0x1a4c, 0xbd26, 0x1aa6, 0xb54, 0x6d6a, 0x12da, 0x1695d, 0x95a, 0x149a, 0xda4b, 0x1a4a, 0x1aa4, 0xbb54, 0x16b4, 0xada, 0x495b, 0x936, 0xf497, 0x1496, 0x154a, 0xb6a5, 0xda4, 0x15b4, 0x6ab6, 0x126e, 0x1092f, 0x92e, 0xc96, 0xcd4a, 0x1d4a, 0xd64, 0x956c, 0x155c, 0x125c, 0x792e, 0x192c, 0xfa95, 0x1a94, 0x1b4a, 0xab55, 0xad4, 0x14da, 0x8a5d, 0xa5a, 0x1152b, 0x152a, 0x1694, 0xd6aa, 0x15aa, 0xab4, 0x94ba, 0x14b6, 0xa56, 0x7527, 0xd26, 0xee53, 0xd54, 0x15aa, 0xa9b5, 0x96c, 0x14ae, 0x8a4e, 0x1a4c, 0x11d26, 0x1aa4, 0x1b54, 0xcd6a, 0xada, 0x95c, 0x949d, 0x149a, 0x1a2a, 0x5b25, 0x1aa4, 0xfb52}; private static final int[] DAYS_AND_LEAP_MONTH_OF_LUNAR = {1897, 0xed436, 0xed64a, 0xed83f, 0xeda53, 0xedc48, 0xede3d, 0xee050, 0xee244, 0xee439, 0xee64d, 0xee842, 0xeea36, 0xeec4a, 0xeee3e, 0xef052, 0xef246, 0xef43a, 0xef64e, 0xef843, 0xefa37, 0xefc4b, 0xefe41, 0xf0054, 0xf0248, 0xf043c, 0xf0650, 0xf0845, 0xf0a38, 0xf0c4d, 0xf0e42, 0xf1037, 0xf124a, 0xf143e, 0xf1651, 0xf1846, 0xf1a3a, 0xf1c4e, 0xf1e44, 0xf2038, 0xf224b, 0xf243f, 0xf2653, 0xf2848, 0xf2a3b, 0xf2c4f, 0xf2e45, 0xf3039, 0xf324d, 0xf3442, 0xf3636, 0xf384a, 0xf3a3d, 0xf3c51, 0xf3e46, 0xf403b, 0xf424e, 0xf4443, 0xf4638, 0xf484c, 0xf4a3f, 0xf4c52, 0xf4e48, 0xf503c, 0xf524f, 0xf5445, 0xf5639, 0xf584d, 0xf5a42, 0xf5c35, 0xf5e49, 0xf603e, 0xf6251, 0xf6446, 0xf663b, 0xf684f, 0xf6a43, 0xf6c37, 0xf6e4b, 0xf703f, 0xf7252, 0xf7447, 0xf763c, 0xf7850, 0xf7a45, 0xf7c39, 0xf7e4d, 0xf8042, 0xf8254, 0xf8449, 0xf863d, 0xf8851, 0xf8a46, 0xf8c3b, 0xf8e4f, 0xf9044, 0xf9237, 0xf944a, 0xf963f, 0xf9853, 0xf9a47, 0xf9c3c, 0xf9e50, 0xfa045, 0xfa238, 0xfa44c, 0xfa641, 0xfa836, 0xfaa49, 0xfac3d, 0xfae52, 0xfb047, 0xfb23a, 0xfb44e, 0xfb643, 0xfb837, 0xfba4a, 0xfbc3f, 0xfbe53, 0xfc048, 0xfc23c, 0xfc450, 0xfc645, 0xfc839, 0xfca4c, 0xfcc41, 0xfce36, 0xfd04a, 0xfd23d, 0xfd451, 0xfd646, 0xfd83a, 0xfda4d, 0xfdc43, 0xfde37, 0xfe04b, 0xfe23f, 0xfe453, 0xfe648, 0xfe83c, 0xfea4f, 0xfec44, 0xfee38, 0xff04c, 0xff241, 0xff436, 0xff64a, 0xff83e, 0xffa51, 0xffc46, 0xffe3a, 0x10004e, 0x100242, 0x100437, 0x10064b, 0x100841, 0x100a53, 0x100c48, 0x100e3c, 0x10104f, 0x101244, 0x101438, 0x10164c, 0x101842, 0x101a35, 0x101c49, 0x101e3d, 0x102051, 0x102245, 0x10243a, 0x10264e, 0x102843, 0x102a37, 0x102c4b, 0x102e3f, 0x103053, 0x103247, 0x10343b, 0x10364f, 0x103845, 0x103a38, 0x103c4c, 0x103e42, 0x104036, 0x104249, 0x10443d, 0x104651, 0x104846, 0x104a3a, 0x104c4e, 0x104e43, 0x105038, 0x10524a, 0x10543e, 0x105652, 0x105847, 0x105a3b, 0x105c4f, 0x105e45, 0x106039, 0x10624c, 0x106441, 0x106635, 0x106849, 0x106a3d}; private static final String[] NUMBER_CAPITAL = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}; private static final String[] LUNAR_HEADER = {"初", "十", "廿", "卅", "正", "腊", "冬", "闰"}; private static final String[][] FESTIVAL_G = { {"元旦"}, {"世界湿地日", "情人节"}, {"全国爱耳日", "青年志愿者服务日", "国际妇女节", "保护母亲河日", "中国植树节", "白色情人节&国际警察日", "世界消费者权益日", "世界森林日&世界睡眠日", "世界水日", "世界气象日", "世界防治结核病日"}, {"愚人节", "清明节", "世界卫生日", "世界地球日", "世界知识产权日"}, {"国际劳动节", "世界哮喘日", "中国青年节", "世界红十字日", "国际护士节", "国际家庭日", "世界电信日", "全国学生营养日", "国际生物多样性日", "国际牛奶日", "世界无烟日"}, {"国际儿童节", "世界环境日", "全国爱眼日", "世界防治荒漠化日", "国际奥林匹克日", "全国土地日", "国际禁毒日"}, {"中国共产党诞生日&国际建筑日", "中国抗战纪念日", "世界人口日"}, {"中国解放军建军节", "国际青年节"}, {"抗战胜利日", "国际扫盲日", "中国教师节", "中国脑健康日&臭氧层保护日", "全国爱牙日", "世界停火日", "世界旅游日"}, {"国庆节&国际老年人日", "世界动物日", "世界教师日", "全国高血压日", "世界邮政日", "世界精神卫生日", "世界标准日", "国际盲人节&世界农村妇女日", "世界粮食日", "国际消除贫困日", "联合国日&世界发展新闻日", "中国男性健康日", "万圣节"}, {"中国记者节", "消防宣传日", "世界糖尿病日", "国际大学生节", "消除对妇女暴力日"}, {"世界爱滋病日", "世界残疾人日", "全国法制宣传日", "世界足球日", "圣诞节"}}; private static final int[][] FESTIVAL_G_DATE = { {1}, {2, 14}, {3, 5, 8, 9, 12, 14, 15, 21, 22, 23, 24}, {1, 5, 7, 22, 26}, {1, 3, 4, 8, 12, 15, 17, 20, 22, 23, 31}, {1, 5, 6, 17, 23, 25, 26}, {1, 7, 11}, {1, 12}, {3, 8, 10, 16, 20, 21, 27}, {1, 4, 5, 8, 9, 10, 14, 15, 16, 17, 24, 29, 31}, {8, 9, 14, 17, 25}, {1, 3, 4, 9, 25}}; private static final String[][] FESTIVAL_L = {{"春节", "元宵节"}, {}, {}, {}, {"端午节"}, {}, {"乞巧节"}, {"中秋节"}, {"重阳节"}, {}, {}, {"腊八节", "扫房日"}}; private static final int[][] FESTIVAL_L_DATE = { {1, 15}, {}, {}, {}, {5}, {}, {7}, {15}, {9}, {}, {}, {8, 24}}; private static final String[][] HOLIDAY = {{"1", "2", "3"}, {"18", "19", "20", "21", "22", "23", "24"}, {""}, {"4", "5", "6"}, {"1", "2", "3"}, {"20", "21", "22"}, {""}, {""}, {"3", "4", "5", "26", "27"}, {"1", "2", "3", "4", "5", "6", "7"}, {""}, {""}}; private static final String[][] DEFERRED = {{"4"}, {"15", "16", "17", "25", "26", "27", "28"}, {""}, {""}, {""}, {""}, {""}, {""}, {"6", "28", "29", "30"}, {"8", "9", "10"}, {""}, {""}}; private static final String SOLAR_TERM[][] = {{"小寒", "大寒"}, {"立春", "雨水"}, {"惊蛰", "春分"}, {"清明", "谷雨"}, {"立夏", "小满"}, {"芒种", "夏至"}, {"小暑", "大暑"}, {"立秋", "处暑"}, {"白露", "秋分"}, {"寒露", "霜降"}, {"立冬", "小雪"}, {"大雪", "冬至"}}; private final HashMap<Integer, String[][]> CACHE_SOLAR_TERM = new HashMap<Integer, String[][]>(); private SolarTerm mSolarTerm = new SolarTerm(); private class G { int d; int m; int y; } private class L { int d; int m; int y; boolean isLeap; } @Override public String[][] buildMonthFestival(int year, int month) { return buildMonthL(year, month); } @Override public Set<String> buildMonthHoliday(int year, int month) { Set<String> tmp = new HashSet<String>(); if (year == 2015) { Collections.addAll(tmp, HOLIDAY[month - 1]); } return tmp; } private String[][] buildMonthL(int year, int month) { String[][] gregorianMonth = buildMonthG(year, month); G g = new G(); String tmp[][] = new String[6][7]; for (int i = 0; i < tmp.length; i++) { for (int j = 0; j < tmp[0].length; j++) { tmp[i][j] = ""; if (!TextUtils.isEmpty(gregorianMonth[i][j])) { g.y = year; g.m = month; g.d = Integer.valueOf(gregorianMonth[i][j]); L l = null; String result = ""; if (year >= 1900 && year <= 2100) { l = GTL(g); result = getFestivalL(l.m, l.d); } if (TextUtils.isEmpty(result)) { result = getFestivalG(g.m, g.d); if (TextUtils.isEmpty(result)) { result = getSolarTerm(year, month, g.d); if (null != l && TextUtils.isEmpty(result)) { char[] c = String.valueOf(l.d).toCharArray(); tmp[i][j] = lNumToStr(c); } else { tmp[i][j] = result; } } else { tmp[i][j] = result + "F"; } } else { tmp[i][j] = result + "F"; } } } } return tmp; } /** * 判断某年某月某日是否为节气 * * @param year 公历年 * @param month 公历月 * @param day 公历日 * @return ... */ public boolean isSolarTerm(int year, int month, int day) { return null == getSolarTerm(year, month, day); } /** * 判断某月某日是否为补休 * * @param year 公历年 * @param month 公历月 * @param day 公历日 * @return ... */ public boolean isDeferred(int year, int month, int day) { if (year == 2015) { String[] deferredOfMonth = DEFERRED[month - 1]; for (String s : deferredOfMonth) { if (!TextUtils.isEmpty(s) && Integer.valueOf(s) == day) return true; } } return false; } private String getSolarTerm(int year, int month, int day) { String[][] tmp = CACHE_SOLAR_TERM.get(year); if (null == tmp) { tmp = mSolarTerm.buildSolarTerm(year); CACHE_SOLAR_TERM.put(year, tmp); } String[] STOfMonth = tmp[month - 1]; if (Integer.valueOf(STOfMonth[0]) == day) { return SOLAR_TERM[month - 1][0]; } else if (Integer.valueOf(STOfMonth[1]) == day) { return SOLAR_TERM[month - 1][1]; } return ""; } private String getFestivalL(int month, int day) { String tmp = ""; int[] daysInMonth = FESTIVAL_L_DATE[month - 1]; for (int i = 0; i < daysInMonth.length; i++) { if (day == daysInMonth[i]) { tmp = FESTIVAL_L[month - 1][i]; } } return tmp; } private String getFestivalG(int month, int day) { String tmp = ""; int[] daysInMonth = FESTIVAL_G_DATE[month - 1]; for (int i = 0; i < daysInMonth.length; i++) { if (day == daysInMonth[i]) { tmp = FESTIVAL_G[month - 1][i]; } } return tmp; } private L GTL(G g) { int index = g.y - DAYS_AND_LEAP_MONTH_OF_LUNAR[0]; int data = (g.y << 9) | (g.m << 5) | (g.d); int lunarFirstDayInGregorian; if (DAYS_AND_LEAP_MONTH_OF_LUNAR[index] > data) { index--; } lunarFirstDayInGregorian = DAYS_AND_LEAP_MONTH_OF_LUNAR[index]; int y = getBitInt(lunarFirstDayInGregorian, 12, 9); int m = getBitInt(lunarFirstDayInGregorian, 4, 5); int d = getBitInt(lunarFirstDayInGregorian, 5, 0); long offset = GToNum(g.y, g.m, g.d) - GToNum(y, m, d); int days = FIRST_DAY_OF_LUNAR_IN_GREGORIAN[index]; int leap = getBitInt(days, 4, 13); int lunarY = index + DAYS_AND_LEAP_MONTH_OF_LUNAR[0]; int lunarM = 1; int lunarD; offset += 1; for (int i = 0; i < 13; i++) { int dm = getBitInt(days, 1, 12 - i) == 1 ? 30 : 29; if (offset > dm) { lunarM++; offset -= dm; } else { break; } } lunarD = (int) (offset); L l = new L(); l.y = lunarY; l.m = lunarM; l.isLeap = false; if (leap != 0 && lunarM > leap) { l.m = lunarM - 1; if (lunarM == leap + 1) { l.isLeap = true; } } l.d = lunarD; return l; } private String lNumToStr(char[] c) { String result = ""; if (c.length == 1) { for (int i = 1; i < 10; i++) { if (c[0] == String.valueOf(i).charAt(0)) { result = LUNAR_HEADER[0] + NUMBER_CAPITAL[i]; } } } else { if (c[0] == '1') { if (c[1] == '0') { result = LUNAR_HEADER[0] + LUNAR_HEADER[1]; } else { for (int i = 1; i < 10; i++) { if (c[1] == String.valueOf(i).charAt(0)) { result = LUNAR_HEADER[1] + NUMBER_CAPITAL[i]; } } } } else if (c[0] == '2') { if (c[1] == '0') { result = LUNAR_HEADER[2] + LUNAR_HEADER[1]; } else { for (int i = 1; i < 10; i++) { if (c[1] == String.valueOf(i).charAt(0)) { result = LUNAR_HEADER[2] + NUMBER_CAPITAL[i]; } } } } else { if (c[1] == '0') { result = LUNAR_HEADER[3] + LUNAR_HEADER[1]; } else { for (int i = 1; i < 10; i++) { if (c[1] == String.valueOf(i).charAt(0)) { result = LUNAR_HEADER[3] + NUMBER_CAPITAL[i]; } } } } } return result; } }
[ "dhj_33922@163.com" ]
dhj_33922@163.com
6992cb1b89209ece854fb3d733fa823aea7da30f
b525c75c22a92d4e7301d4c2de19fa3f3ce21ec8
/app/src/main/java/touch/drag/milica/master/Setting.java
f1193b6fc36ae40ee308581aa52711ccd974de4a
[]
no_license
MilicaSelakovic/TouchDrag
d2136ef523c0e2925709862c77e15d087f969a8a
236818d59be019eafbc630d67362732f8a21df7c
refs/heads/master
2021-09-18T19:30:45.735426
2018-07-18T15:24:25
2018-07-18T15:24:25
73,170,047
0
0
null
null
null
null
UTF-8
Java
false
false
10,961
java
package touch.drag.milica.master; import android.content.Intent; import android.graphics.Color; import android.support.annotation.ColorInt; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.Switch; import com.pes.androidmaterialcolorpickerdialog.ColorPicker; import com.pes.androidmaterialcolorpickerdialog.ColorPickerCallback; public class Setting extends AppCompatActivity { private int moveColor; private int fixedColor; private int activeColor; private int canChooseColor; private int cannotChooseColor; private int otherColor; private int pointSize; private boolean label; private int textSize; private boolean hasExtra = false; private float factor; private boolean signInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); Bundle extras = getIntent().getExtras(); if (extras != null) { hasExtra = true; moveColor = extras.getInt("moveColor"); fixedColor = extras.getInt("fixedColor"); activeColor = extras.getInt("activeColor"); canChooseColor = extras.getInt("canChooseColor"); cannotChooseColor = extras.getInt("cannotChooseColor"); otherColor = extras.getInt("otherColor"); pointSize = extras.getInt("pointSize"); label = extras.getBoolean("label"); textSize = extras.getInt("textSize"); factor = extras.getFloat("factor"); signInfo = extras.getBoolean("signInfo"); } if (hasExtra) { setValues(); } this.findViewById(R.id.imageButton5).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); this.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ColorPicker cp = new ColorPicker(Setting.this, Color.red(moveColor), Color.green(moveColor), Color.blue(moveColor)); cp.show(); cp.setCallback(new ColorPickerCallback() { @Override public void onColorChosen(@ColorInt int color) { moveColor = color; findViewById(R.id.button2).setBackgroundColor(moveColor); cp.dismiss(); } }); } }); this.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ColorPicker cp = new ColorPicker(Setting.this, Color.red(fixedColor), Color.green(fixedColor), Color.blue(fixedColor)); cp.show(); cp.setCallback(new ColorPickerCallback() { @Override public void onColorChosen(@ColorInt int color) { fixedColor = color; findViewById(R.id.button3).setBackgroundColor(fixedColor); cp.dismiss(); } }); } }); this.findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ColorPicker cp = new ColorPicker(Setting.this, Color.red(activeColor), Color.green(activeColor), Color.blue(activeColor)); cp.show(); cp.setCallback(new ColorPickerCallback() { @Override public void onColorChosen(@ColorInt int color) { activeColor = color; findViewById(R.id.button4).setBackgroundColor(activeColor); cp.dismiss(); } }); } }); this.findViewById(R.id.button5).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ColorPicker cp = new ColorPicker(Setting.this, Color.red(canChooseColor), Color.green(canChooseColor), Color.blue(canChooseColor)); cp.show(); cp.setCallback(new ColorPickerCallback() { @Override public void onColorChosen(@ColorInt int color) { canChooseColor = color; findViewById(R.id.button5).setBackgroundColor(canChooseColor); cp.dismiss(); } }); } }); this.findViewById(R.id.button6).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ColorPicker cp = new ColorPicker(Setting.this, Color.red(cannotChooseColor), Color.green(cannotChooseColor), Color.blue(cannotChooseColor)); cp.show(); cp.setCallback(new ColorPickerCallback() { @Override public void onColorChosen(@ColorInt int color) { cannotChooseColor = color; findViewById(R.id.button6).setBackgroundColor(cannotChooseColor); cp.dismiss(); } }); } }); this.findViewById(R.id.button7).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ColorPicker cp = new ColorPicker(Setting.this, Color.red(otherColor), Color.green(otherColor), Color.blue(otherColor)); cp.show(); cp.setCallback(new ColorPickerCallback() { @Override public void onColorChosen(@ColorInt int color) { otherColor = color; findViewById(R.id.button7).setBackgroundColor(otherColor); cp.dismiss(); } }); } }); this.findViewById(R.id.switch1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Switch s = (Switch) findViewById(R.id.switch1); label = s.isChecked(); } }); this.findViewById(R.id.show).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Switch s = (Switch) findViewById(R.id.show); signInfo = s.isChecked(); } }); Spinner spinner = (Spinner) findViewById(R.id.spinner3); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { textSize = parent.getSelectedItemPosition(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Spinner spinner1 = (Spinner) findViewById(R.id.spinner2); spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { int pos = parent.getSelectedItemPosition(); pointSize = pos; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); final SeekBar seekBar = (SeekBar) this.findViewById(R.id.factor); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { factor = progress / 10f; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } @Override public void finish() { Intent intent = new Intent(); intent.putExtra("moveColor", moveColor); intent.putExtra("fixedColor", fixedColor); intent.putExtra("activeColor", activeColor); intent.putExtra("canChooseColor", canChooseColor); intent.putExtra("cannotChooseColor", cannotChooseColor); intent.putExtra("otherColor", otherColor); intent.putExtra("pointSize", pointSize); intent.putExtra("label", label); intent.putExtra("textSize", textSize); intent.putExtra("factor", factor); intent.putExtra("signInfo", signInfo); setResult(RESULT_OK, intent); super.finish(); } private void setValues() { Spinner spinner = (Spinner) findViewById(R.id.spinner3); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sizes, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setSelection(getTextSize()); Spinner spinner1 = (Spinner) findViewById(R.id.spinner2); spinner1.setAdapter(adapter); spinner1.setSelection(getPointSize()); Button button2 = (Button) findViewById(R.id.button2); button2.setBackgroundColor(moveColor); Button button3 = (Button) findViewById(R.id.button3); button3.setBackgroundColor(fixedColor); Button button4 = (Button) findViewById(R.id.button4); button4.setBackgroundColor(activeColor); Button button5 = (Button) findViewById(R.id.button5); button5.setBackgroundColor(canChooseColor); Button button6 = (Button) findViewById(R.id.button6); button6.setBackgroundColor(cannotChooseColor); Button button7 = (Button) findViewById(R.id.button7); button7.setBackgroundColor(otherColor); Switch switch1 = (Switch) findViewById(R.id.switch1); switch1.setChecked(label); Switch show = (Switch) findViewById(R.id.show); show.setChecked(signInfo); SeekBar seekBar = (SeekBar) findViewById(R.id.factor); seekBar.setProgress((int) factor * 10); } private int getPointSize() { return pointSize; } private int getTextSize() { return textSize; } }
[ "milica1793@gmail.com" ]
milica1793@gmail.com
fe51f2364ea3f3769be555fa1c5c0b475b3a61f6
45f63b15e9c28eec6652a540a78771614f581503
/VPD/src/com/servlets/AssignServlet.java
16ee324a0c6d69dc6175c5f36b1aae41d55439c0
[]
no_license
abhinavbhargava16/ModuleVPD
3266d073db0130a9f27589f0caeefc00c7814541
c0cc49e93914d03f6383f7165ebbac3bbf6aff29
refs/heads/master
2022-09-03T02:27:50.186735
2020-05-28T16:25:31
2020-05-28T16:25:31
266,024,909
0
0
null
null
null
null
UTF-8
Java
false
false
2,392
java
package com.servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.DAO.ProspectDAO; import com.POJO.ProspectivePOJO; @WebServlet("/AssignServlet") public class AssignServlet extends HttpServlet { private static final long serialVersionUID = 1L; public AssignServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); System.out.println("Inside assign servlet"); try { String name[] = request.getParameterValues("prospectNames"); //customer_id String salesperson = request.getParameter("salesperson"); //employee_id from assign prospects. String campaign = (String) request.getParameter("hid"); //campaign_id from assignprospects.jsp ProspectDAO obj = new ProspectDAO(); Connection conn = (Connection) request.getServletContext().getAttribute("connection"); for(String i:name) { System.out.println("Inside for loop for insert prospect."); ProspectivePOJO p = new ProspectivePOJO(); p.setCustomerID(Integer.parseInt(i)); p.setCampaginID(campaign); p.setHandlerId(Integer.parseInt(salesperson)); obj.insertProspective(conn, p); } out.print("Salesperson with <b>Employee ID</b>-"+salesperson+" has been assign "+name.length+" prospect(s) for Campaign id :"+campaign); request.getRequestDispatcher("AssignProspects.jsp").include(request, response); }catch(SQLException e) { out.println("SQL Exception"); e.printStackTrace(); } catch (NullPointerException e) { out.println("SYSTEM:CAN'T PROCESS EMPTY REQUESTS"); request.getRequestDispatcher("AssignProspects.jsp").include(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
[ "Abhinav@LAPTOP-754JRR94" ]
Abhinav@LAPTOP-754JRR94
f5856c6363e9ca62138c37c1a10bfa97171c4245
b2104a8e1d6777831d77bba882b44bde69210710
/src/main/java/com/wotif/schema/ota/_2007b/DateTimeSpanType.java
5d32d9709a872f94d01132894440c2361a76e93f
[]
no_license
wotifgroup/ota-schema
57dda9dc7d3b5d2f98326d3518f28f062d5e94d4
66c4353247fbfdadc0e6f49f2b75b2020c064ecb
refs/heads/master
2020-04-04T05:20:42.359125
2014-09-03T05:55:23
2014-09-03T05:55:23
28,319,242
2
0
null
null
null
null
UTF-8
Java
false
false
11,322
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.04.03 at 03:33:27 PM EST // package com.wotif.schema.ota._2007b; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * Used to specify a time window range by either specifying an earliest and latest date for the start date and end date or by giving a date with a time period that can be applied before and/or after the start date. * * <p>Java class for DateTimeSpanType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DateTimeSpanType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice> * &lt;element name="DateWindowRange" type="{http://www.opentravel.org/OTA/2003/05}TimeInstantType"/> * &lt;sequence> * &lt;element name="StartDateWindow" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}TimeWindowGroup"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="EndDateWindow" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}TimeWindowGroup"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/choice> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}DateTimeSpanGroup"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DateTimeSpanType", propOrder = { "startDateWindow", "endDateWindow", "dateWindowRange" }) public class DateTimeSpanType { @XmlElement(name = "StartDateWindow") protected DateTimeSpanType.StartDateWindow startDateWindow; @XmlElement(name = "EndDateWindow") protected DateTimeSpanType.EndDateWindow endDateWindow; @XmlElement(name = "DateWindowRange") protected TimeInstantType dateWindowRange; @XmlAttribute(name = "Start") protected String start; @XmlAttribute(name = "Duration") protected String duration; @XmlAttribute(name = "End") protected String end; /** * Gets the value of the startDateWindow property. * * @return * possible object is * {@link DateTimeSpanType.StartDateWindow } * */ public DateTimeSpanType.StartDateWindow getStartDateWindow() { return startDateWindow; } /** * Sets the value of the startDateWindow property. * * @param value * allowed object is * {@link DateTimeSpanType.StartDateWindow } * */ public void setStartDateWindow(DateTimeSpanType.StartDateWindow value) { this.startDateWindow = value; } /** * Gets the value of the endDateWindow property. * * @return * possible object is * {@link DateTimeSpanType.EndDateWindow } * */ public DateTimeSpanType.EndDateWindow getEndDateWindow() { return endDateWindow; } /** * Sets the value of the endDateWindow property. * * @param value * allowed object is * {@link DateTimeSpanType.EndDateWindow } * */ public void setEndDateWindow(DateTimeSpanType.EndDateWindow value) { this.endDateWindow = value; } /** * Gets the value of the dateWindowRange property. * * @return * possible object is * {@link TimeInstantType } * */ public TimeInstantType getDateWindowRange() { return dateWindowRange; } /** * Sets the value of the dateWindowRange property. * * @param value * allowed object is * {@link TimeInstantType } * */ public void setDateWindowRange(TimeInstantType value) { this.dateWindowRange = value; } /** * Gets the value of the start property. * * @return * possible object is * {@link String } * */ public String getStart() { return start; } /** * Sets the value of the start property. * * @param value * allowed object is * {@link String } * */ public void setStart(String value) { this.start = value; } /** * Gets the value of the duration property. * * @return * possible object is * {@link String } * */ public String getDuration() { return duration; } /** * Sets the value of the duration property. * * @param value * allowed object is * {@link String } * */ public void setDuration(String value) { this.duration = value; } /** * Gets the value of the end property. * * @return * possible object is * {@link String } * */ public String getEnd() { return end; } /** * Sets the value of the end property. * * @param value * allowed object is * {@link String } * */ public void setEnd(String value) { this.end = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}TimeWindowGroup"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class EndDateWindow { @XmlAttribute(name = "EarliestDate") protected String earliestDate; @XmlAttribute(name = "LatestDate") protected String latestDate; @XmlAttribute(name = "DOW") protected DayOfWeekType dow; /** * Gets the value of the earliestDate property. * * @return * possible object is * {@link String } * */ public String getEarliestDate() { return earliestDate; } /** * Sets the value of the earliestDate property. * * @param value * allowed object is * {@link String } * */ public void setEarliestDate(String value) { this.earliestDate = value; } /** * Gets the value of the latestDate property. * * @return * possible object is * {@link String } * */ public String getLatestDate() { return latestDate; } /** * Sets the value of the latestDate property. * * @param value * allowed object is * {@link String } * */ public void setLatestDate(String value) { this.latestDate = value; } /** * Gets the value of the dow property. * * @return * possible object is * {@link DayOfWeekType } * */ public DayOfWeekType getDOW() { return dow; } /** * Sets the value of the dow property. * * @param value * allowed object is * {@link DayOfWeekType } * */ public void setDOW(DayOfWeekType value) { this.dow = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}TimeWindowGroup"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class StartDateWindow { @XmlAttribute(name = "EarliestDate") protected String earliestDate; @XmlAttribute(name = "LatestDate") protected String latestDate; @XmlAttribute(name = "DOW") protected DayOfWeekType dow; /** * Gets the value of the earliestDate property. * * @return * possible object is * {@link String } * */ public String getEarliestDate() { return earliestDate; } /** * Sets the value of the earliestDate property. * * @param value * allowed object is * {@link String } * */ public void setEarliestDate(String value) { this.earliestDate = value; } /** * Gets the value of the latestDate property. * * @return * possible object is * {@link String } * */ public String getLatestDate() { return latestDate; } /** * Sets the value of the latestDate property. * * @param value * allowed object is * {@link String } * */ public void setLatestDate(String value) { this.latestDate = value; } /** * Gets the value of the dow property. * * @return * possible object is * {@link DayOfWeekType } * */ public DayOfWeekType getDOW() { return dow; } /** * Sets the value of the dow property. * * @param value * allowed object is * {@link DayOfWeekType } * */ public void setDOW(DayOfWeekType value) { this.dow = value; } } }
[ "pete.capra@wotifgroup.com" ]
pete.capra@wotifgroup.com
af1653155df0002c298afef6cc517d771b813470
80823af18af88cfaf101c9e9a96599c6dfa38190
/JavaWeb/8.JSON_Ajax/src/main/java/com/example/JsonTest/Test1.java
46999ee708bbf73871edad69aa665284c24c0cd9
[]
no_license
Yee127/JavaFile
0987546a45e44901c293877f6a4c3eaf4bcd7f20
b3a4868368ad1ca5454d185c01e21f997d62e696
refs/heads/master
2023-04-02T06:59:52.803670
2021-04-05T05:30:04
2021-04-05T05:30:04
354,558,473
0
0
null
null
null
null
UTF-8
Java
false
false
2,504
java
package com.example.JsonTest; import com.example.Bean.Person; import com.example.Bean.PersonListType; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Test1 { @Test public void BeanToJson(){ Person person = new Person("mike",22); Gson gson = new Gson(); // toJson 方法可以把 java 对象转换成为 json 字符串 System.out.println("—————————————javaBean 转 Json ———————————————"); String json = gson.toJson(person); System.out.println(json); System.out.println("——————————————Json 转 javaBean————————————————"); // fromJson 把 json 字符串转换回 Java 对象 Person person1 = gson.fromJson(json, Person.class); System.out.println(person1); } @Test public void ListAndJson(){ List<Person> list = new ArrayList<Person>(); list.add(new Person("滴滴",1)); list.add(new Person("哈哈",2)); Gson gson = new Gson(); System.out.println("—————————————List 转 Json ———————————————"); String json = gson.toJson(list); System.out.println(json); System.out.println("—————————————Json 转 List ———————————————"); List<Person> personList = gson.fromJson(json,new PersonListType().getType()); System.out.println(personList); } @Test public void MapAndJson(){ Map<Integer,Person> personMap = new HashMap<Integer,Person>(); personMap.put(1,new Person("tom",9)); personMap.put(2,new Person("lucy",19)); Gson gson = new Gson(); System.out.println("—————————————Map 转 Json ———————————————"); String json = gson.toJson(personMap); System.out.println(json); System.out.println("—————————————Json 转 Map ———————————————"); Map<Integer,Person> personMap2 = gson.fromJson(json, new TypeToken<HashMap<Integer, Person>>() { }.getType()); System.out.println(personMap2); System.out.println(personMap2.get(1)); } }
[ "yivan127@163.com" ]
yivan127@163.com
8da89b6f3bb64deda238af34eb2fb0980251be7b
ecbf8c4452f01aeff8b18122cebd4ad439185264
/algorithms/design-underground-system/src/test/java/DesignUndergroundSystemTest.java
ea78fd619a12dd41a2a850b7ef0d08c91f5dabb3
[]
no_license
XyParaCrim/brain-index
4335d397ebe93ecd5e40557de39c967f8d48fb3c
24a2952bcfc00996992a54819a50ae076a901505
refs/heads/master
2020-09-26T20:50:12.734020
2020-08-27T18:10:12
2020-08-27T18:10:12
226,341,139
0
0
null
null
null
null
UTF-8
Java
false
false
2,099
java
import org.excellent.cancer.algorithms.DesignUndergroundSystem; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class DesignUndergroundSystemTest { @Test @DisplayName("Case1: 两个HashMap:一个以游客id为键,一个以往返两地") public void testSolutionForCaseOne() { DesignUndergroundSystem undergroundSystem = DesignUndergroundSystem.solution(); undergroundSystem.checkIn(45, "Leyton", 3); undergroundSystem.checkIn(32, "Paradise", 8); undergroundSystem.checkIn(27, "Leyton", 10); undergroundSystem.checkOut(45, "Waterloo", 15); undergroundSystem.checkOut(27, "Waterloo", 20); undergroundSystem.checkOut(32, "Cambridge", 22); assertEquals(14.0, undergroundSystem.getAverageTime("Paradise", "Cambridge")); assertEquals(11.0, undergroundSystem.getAverageTime("Leyton", "Waterloo")); undergroundSystem.checkIn(10, "Leyton", 24); assertEquals(11.0, undergroundSystem.getAverageTime("Leyton", "Waterloo")); undergroundSystem.checkOut(10, "Waterloo", 38); assertEquals(12.0, undergroundSystem.getAverageTime("Leyton", "Waterloo")); } @Test @DisplayName("Case2: 两个HashMap:一个以游客id为键,一个以往返两地") public void testSolutionForCaseTwo() { DesignUndergroundSystem undergroundSystem = DesignUndergroundSystem.solution(); undergroundSystem.checkIn(10, "Leyton", 3); undergroundSystem.checkOut(10, "Paradise", 8); assertEquals(5.0, undergroundSystem.getAverageTime("Leyton", "Paradise")); undergroundSystem.checkIn(5, "Leyton", 10); undergroundSystem.checkOut(5, "Paradise", 16); assertEquals(5.5, undergroundSystem.getAverageTime("Leyton", "Paradise")); undergroundSystem.checkIn(2, "Leyton", 21); undergroundSystem.checkOut(2, "Paradise", 30); assertEquals(6.666666666666667, undergroundSystem.getAverageTime("Leyton", "Paradise")); } }
[ "xylome@qq.com" ]
xylome@qq.com
8d32865637c8c0d6d59a42d092e27395db7a8442
6a4f1944e61478e22a1f7558e16c8ee5a84f2088
/pop/lab4/semdetails.java
ccf0eebba7bdfd02406058092dba5c8180a448c9
[]
no_license
ydodeja365/LabWork
66b55c71ebff2bdaf57ded76d002a9184de1d191
a734b578a733b95bbcd19d25bba014c6bebc9c8b
refs/heads/master
2021-09-11T15:30:52.509011
2018-04-09T14:55:07
2018-04-09T14:55:07
111,224,200
0
0
null
null
null
null
UTF-8
Java
false
false
425
java
import java.util.Scanner; class semdetails { float GPA; public static void main(String args[]) { Scanner s = new Scanner(System.in); semdetails obj[] = new semdetails[8]; System.out.println("Enter all 8 sems GPA:"); float sum = 0; for(int i=0;i<8;i++) { obj[i] = new semdetails(); obj[i].GPA = s.nextFloat(); sum+=obj[i].GPA; } float CGPA = sum/8; System.out.println("Your CGPA is:"+ CGPA); } }
[ "param.catchchaos@gmail.com" ]
param.catchchaos@gmail.com
d29bb82d0bba1caf4e81134e505c5a57f725d32c
f0c0d125057716d7e186f72a7f27090a47186deb
/src/main/java/org/lukas/javach/command/SimpleControlPanel.java
225476d7b0c3fa9a331e97eff0c59387acf089a2
[]
no_license
LukasPecak/DesignPatterns
7608e27d6713d19d372682f3cffb8830c9eb1205
28f0b8b664612fbbabd37dac540d18293b1453af
refs/heads/master
2021-07-07T11:29:31.291213
2019-07-26T21:04:36
2019-07-26T21:04:36
199,079,500
0
0
null
2020-10-13T14:54:21
2019-07-26T21:01:11
Java
UTF-8
Java
false
false
3,063
java
package org.lukas.javach.command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Lukas on 29.10.2017. * * @author Lukas Pecak */ public class SimpleControlPanel implements ControlPanel { private static Logger log = LoggerFactory.getLogger(SimpleControlPanel.class); private int controllerSlotCapacity; private Command[] onCommands; private Command[] offCommands; private Command previousCommand; SimpleControlPanel(int controllerSlotCapacity) { if (0 > controllerSlotCapacity && controllerSlotCapacity < Integer.MAX_VALUE) { throw new IllegalArgumentException(String.format("Cannot create a control panel with %d slot capacity", controllerSlotCapacity)); } this.controllerSlotCapacity = controllerSlotCapacity; onCommands = new Command[controllerSlotCapacity]; offCommands = new Command[controllerSlotCapacity]; for (int i = 0; i < controllerSlotCapacity; i++) { onCommands[i] = new NoCommand(); offCommands[i] = new NoCommand(); } previousCommand = new NoCommand(); } @Override public void setDeviceSlot(int numberOfSlot, Command onCommand, Command offCommand) { ensureSlotInRange(numberOfSlot); Command checkedOnCommand = ensureCommandNotNull(onCommand); Command checkedOffCommand = ensureCommandNotNull(offCommand); onCommands[numberOfSlot] = checkedOnCommand; offCommands[numberOfSlot] = checkedOffCommand; } private Command ensureCommandNotNull(Command command) { Command checkedCommand = new NoCommand(); if (command != null) { checkedCommand = command; } return checkedCommand; } @Override public void removeDeviceSlot(int numberOfSlot) { ensureSlotInRange(numberOfSlot); onCommands[numberOfSlot] = new NoCommand(); offCommands[numberOfSlot] = new NoCommand(); } private void ensureSlotInRange(int numberOfSlot) { if (0 > numberOfSlot || numberOfSlot >= controllerSlotCapacity) { throw new IllegalArgumentException("Slot out of range"); } } @Override public void panelPressOnSlot(int slotNumber) { ensureSlotInRange(slotNumber); onCommands[slotNumber].execute(); previousCommand = onCommands[slotNumber]; } @Override public void panelPressOffSlot(int slotNumber) { ensureSlotInRange(slotNumber); offCommands[slotNumber].execute(); previousCommand = offCommands[slotNumber]; } @Override public void undoCommand() { previousCommand.undo(); } @Override public void printPanel() { log.info("---------- CONTROL PANEL ----------"); for (int i = 0; i < controllerSlotCapacity; i++) { if (log.isInfoEnabled()) { log.info(String.format("| %s |\t| %s |", onCommands[i].getClass().getSimpleName(), offCommands[i].getClass().getSimpleName())); } } } }
[ "lukas.pecak@gmail.com" ]
lukas.pecak@gmail.com
36812d8e4773e6baa8daa1cd048602963a4bd804
9d144fff1dc5b0edd8ed2d8f25164aa0a8a28004
/src/RplIt/temperature.java
d6834d54544db44cf77e55d4e3439ebdd74de0b8
[]
no_license
mirshodtairov/JavaProgrammingSpring2019
d64a7cef13dc58703d87d5ffec30f896f3a280b8
dcf99c5b0d58c6a81ef8775af2bd960c4062e630
refs/heads/master
2020-05-18T10:33:44.869942
2019-07-16T18:36:16
2019-07-16T18:36:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
520
java
package RplIt; import java.util.Scanner; public class temperature { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int k = 0; double total = 0; double avgTemp = 0; double[] temps = { scan.nextDouble(), scan.nextDouble(), scan.nextDouble(), scan.nextDouble(), scan.nextDouble(), scan.nextDouble(), scan.nextDouble(), scan.nextDouble() }; for (int i = 0; i < temps.length; i++) { total += temps[i]; } avgTemp = total / 8; System.out.println(avgTemp); } }
[ "mirshod.tairov@gmail.com" ]
mirshod.tairov@gmail.com
0ea85c4ec9cc052a473b47b235b871fc468f39e0
77a7b0a4f0085da84d8f19a29d7485226fbc291c
/Fragment_ListView_RecycleView/app/src/test/java/com/example/buidanhnam/fragment_listiew_recycleview/ExampleUnitTest.java
141a32ae4843028ee94b6794473d0c0b2b9745bd
[]
no_license
nambd-1242/-android_advance_1
614876366e7c2732ccf9d4a34045795bfb56e25c
e7731cc707d2883d543439920edc032d8a8b4bd8
refs/heads/master
2021-08-29T23:47:08.103322
2017-12-11T09:08:28
2017-12-11T09:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
429
java
package com.example.buidanhnam.fragment_listiew_recycleview; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "bui.danh.nam@framgia.com" ]
bui.danh.nam@framgia.com
1f1cf326285d98bc23b7c22269efe8e1967da3c9
a872bdec0b0ccd944bea0abb694fb3240170f84c
/src/io/joy/route/RouteTree.java
20c7311b2d47cf1066c9f5d024b1855155c8a1b9
[]
no_license
limeuser/joy
0ee3a0930fc8f70949b36a95e116fdcbe4da4b63
2448a6993255b1a4a70dadcdc97d87e04047341e
refs/heads/master
2021-01-23T01:41:06.026287
2018-06-11T05:55:19
2018-06-11T05:55:19
92,886,844
0
0
null
null
null
null
UTF-8
Java
false
false
3,803
java
package io.joy.route; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.joy.http.Handler; import io.joy.util.Bug; public class RouteTree { public class Node { RouteElem key; Handler value; Node parent; List<Node> children; String route() { if (this == tree) { return "/"; } Node node = this; List<Node> nodes = new ArrayList<Node>(); while (node != tree) { nodes.add(node); node = node.parent; } StringBuilder str = new StringBuilder(); for (int i = nodes.size() - 1; i >= 0; i--) { str.append("/").append(nodes.get(i).key); } return str.toString(); } } private Node tree = new Node(); public RouteTree() { this.tree = new Node(); this.tree.key = new StringElem("/"); } public Handler find(String path, Map<String, String> paramters) { return find(RouteParser.splitElem(path), paramters); } public Handler find(String[] keys, Map<String, String> paramters) { int i = 0, tier = 0; Node node = this.tree; List<Node> nodes = this.tree.children; for (; nodes != null && i < nodes.size() && tier < keys.length; i++) { Node child = nodes.get(i); if (child.key.matchs(keys[tier])) { tier++; node = child; nodes = child.children; i = -1; if (paramters != null && child.key.isParamter()) { paramters.put(child.key.name(), keys[tier]); } } } if (keys.length != tier) { return null; } else { return node.value; } } // path的模式:/user/xxx public void insert(String route, Handler handler) { insert(route, RouteParser.parseRoute(route), handler); } public void insert(String route, RouteElem[] keys, Handler value) { if (keys.length == 0) { this.tree.value = value; return; } int i = 0, tier = 0; List<Node> nodes = this.tree.children; Node found = this.tree; for (; nodes != null && i < nodes.size() && tier < keys.length; i++) { Node child = nodes.get(i); if (child.key.equals(keys[tier])) { tier++; i = -1; nodes = child.children; found = child; } } // found the node by keys if (tier == keys.length && found.value != null) { throw new Bug(String.format("%s has been set: %s", route, found.value)); } if (nodes == null) { found.children = new ArrayList<Node>(); nodes = found.children; } // insert remaining keys for (; tier < keys.length; tier++) { Node inserting = new Node(); inserting.children = new ArrayList<Node>(); inserting.key = keys[tier]; // set handler when node is leaf if (tier == keys.length - 1) { inserting.value = value; } insetSiblingByPriority(nodes, inserting); inserting.parent = found; nodes = inserting.children; found = inserting; } } private void insetSiblingByPriority(List<Node> nodes, Node sibling) { int i = 0; for (; i < nodes.size(); i++) { Node node = nodes.get(i); if (node.key.priority() < sibling.key.priority()) { break; } } nodes.add(null); for (int j = nodes.size() - 1; j > i; j--) { nodes.set(j, nodes.get(j - 1)); } nodes.set(i, sibling); } @Override public String toString() { return format(0, 0, tree, new StringBuilder()).toString(); } private final static StringBuilder format(int tier, int index, Node node, StringBuilder str) { if (node.value != null) { str.append(format(tier, index, node)).append("\r\n"); } if (node.children == null) { return str; } int i = 0; for (Node n : node.children) { format(tier + 1, i++, n, str); } return str; } private final static String format(int tier, int index, Node node) { return String.format("%d:%d {%s => %s}", tier, index, node.route(), node.value.getClass().getName()); } }
[ "kK644742935@gmail.com" ]
kK644742935@gmail.com
8938e3d5567f18c08e0c4b15f1665b5c05675536
2dbca48986c737b0d3ab65c7a7de3c899439d3b8
/eSandwich/COPIA 13/PantallaLogin.java
ba9fc53accaae151346e3cbec9ef5bf9437724cb
[]
no_license
msalas/esandwich
b5a8a1ec5c41d841a69e04434ac43b20167705b0
938d8b9a4cbb681e3992a46bf9dde0d81611e74f
refs/heads/master
2021-01-10T06:48:05.070539
2007-12-06T11:52:21
2007-12-06T11:52:21
36,846,676
0
0
null
null
null
null
ISO-8859-1
Java
false
false
3,723
java
import java.awt.BorderLayout; import java.awt.Rectangle; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class PantallaLogin extends JDialog { private static final long serialVersionUID = 1L; private AplicacionComprador ac; private AplicacionEmpleado ae; private JPanel jContentPane = null; private JPanel jPanel = null; private JLabel jLabel = null; private JLabel jLabel1 = null; private JTextField txtCUsuario = null; private JTextField txtPassword = null; private JButton btnLogin = null; private ControladorPantallaLogin cpl = null; public PantallaLogin(AplicacionComprador ac) { super(ac, "Iniciar Sesión ...", true); this.ac = ac; initializeAc(); } public PantallaLogin(AplicacionEmpleado ae) { super(ae, "Iniciar Sesión ...", true); this.ae = ae; initializeAe(); // Para centrar pantalla this.setLocationRelativeTo(null); } /** * This method initializes this * * @return void */ private void initializeAc() { this.setSize(300, 200); this.setContentPane(getJContentPane()); cpl = new ControladorPantallaLogin(this,ac); btnLogin.addActionListener(cpl); } private void initializeAe() { this.setSize(300, 200); this.setContentPane(getJContentPane()); cpl = new ControladorPantallaLogin(this,ae); btnLogin.addActionListener(cpl); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { jContentPane = new JPanel(); jContentPane.setLayout(new BorderLayout()); jContentPane.add(getJPanel(), BorderLayout.CENTER); } return jContentPane; } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { jLabel1 = new JLabel(); jLabel1.setBounds(new Rectangle(18, 63, 72, 16)); jLabel1.setText("Password:"); jLabel = new JLabel(); jLabel.setBounds(new Rectangle(19, 35, 67, 16)); jLabel.setText("Código usuario:"); jPanel = new JPanel(); jPanel.setLayout(null); jPanel.add(jLabel, null); jPanel.add(jLabel1, null); jPanel.add(getTxtCUsuario(), null); jPanel.add(getTxtPassword(), null); jPanel.add(getBtnLogin(), null); } return jPanel; } /** * This method initializes txtCClient * * @return javax.swing.JTextField */ public JTextField getTxtCUsuario() { if (txtCUsuario == null) { txtCUsuario = new JTextField(); txtCUsuario.setBounds(new Rectangle(104, 36, 122, 20)); } return txtCUsuario; } /** * This method initializes txtPassword * * @return javax.swing.JTextField */ public JTextField getTxtPassword() { if (txtPassword == null) { txtPassword = new JTextField(); txtPassword.setBounds(new Rectangle(103, 62, 123, 20)); } return txtPassword; } /** * This method initializes btnLogin * * @return javax.swing.JButton */ private JButton getBtnLogin() { if (btnLogin == null) { btnLogin = new JButton(); btnLogin.setBounds(new Rectangle(103, 104, 113, 28)); btnLogin.setText("Iniciar Sesión"); } return btnLogin; } }
[ "marc.salas@786e674c-0b3f-0410-8684-fb369c74eaa0" ]
marc.salas@786e674c-0b3f-0410-8684-fb369c74eaa0
32bc5dd690eb4f5fa60ed042125b6bae4b83c4a4
5ef5abccad107b2161dc77b4034dd8253e5b8294
/app/src/main/java/com/cast/tv/screen/mirroring/iptv/ui/iptv/category/CategoryViewModel.java
8cec5533aff38c8430d8c1b27be6b51c3b73fb29
[]
no_license
numadykuteko/CastTVApp2
05e0df757f489abc337e955503a0f30b75ee3cf9
7bea17776c95c9bcef12204de7cdf172dc8a1f63
refs/heads/master
2023-04-22T00:50:38.857442
2021-05-18T02:49:01
2021-05-18T02:49:01
367,902,899
4
0
null
null
null
null
UTF-8
Java
false
false
371
java
package com.cast.tv.screen.mirroring.iptv.ui.iptv.category; import android.app.Application; import androidx.annotation.NonNull; import com.cast.tv.screen.mirroring.iptv.ui.base.BaseViewModel; public class CategoryViewModel extends BaseViewModel<CategoryNavigator> { public CategoryViewModel(@NonNull Application application) { super(application); } }
[ "kevinkool9x@gmail.com" ]
kevinkool9x@gmail.com
dd940b0d4f763f690cf7d86f2af48e09e02cd619
16aedb99fdd8229192d4123481a9613b67e252f9
/src/main/java/jar/controller/HelloAction.java
5cbcdec5de4a2f2b17f4a53385179aabede809f4
[]
no_license
munivarma/devops-edu
8a58db6119f54b7f28d35bdf5033cdb0e8ee000a
27881a9810ec354cd4d2524819fab75b1bdbbd07
refs/heads/master
2021-08-10T09:22:02.849726
2017-11-12T12:33:15
2017-11-12T12:33:15
108,639,403
0
0
null
2017-10-29T10:48:59
2017-10-28T10:14:23
Java
UTF-8
Java
false
false
399
java
/* * HelloWorld! test Class * IMPORTANTE ********************************************* * * REMOVE THESE CLASS AND THE DEFAULT USER CREATED FOR TEST! */ package jar.controller; import javax.inject.Inject; import jar.business.LoginService; public class HelloAction extends BaseAction{ @Inject LoginService sv; public String execute(){ sv.createFirst(); return "success"; } }
[ "munivarma4@gmail.com" ]
munivarma4@gmail.com
48d6cadaace746840773335021bd7f4a74523703
714cbf8e2460b2520859fe4b2218f2da050aedcf
/DomainGenerators/src/main/java/ch/uzh/ifi/DomainGenerators/DomainGeneratorSpatialUncertain.java
ff410fa33b4a30f8779414a1e4d8609e0e3ad2ed
[]
no_license
dmitrymoor/DomainGenerators
e775e02b8585422e419dfb272971a0cd1bb8bb46
dc88797de2ef4b3d010141a4c03cc71662f161da
refs/heads/master
2021-01-10T13:00:47.249475
2017-10-17T10:14:29
2017-10-17T10:14:29
52,980,910
0
0
null
null
null
null
UTF-8
Java
false
false
5,982
java
package ch.uzh.ifi.DomainGenerators; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ch.uzh.ifi.MechanismDesignPrimitives.FocusedBombingStrategy; import ch.uzh.ifi.MechanismDesignPrimitives.IBombingStrategy; import ch.uzh.ifi.MechanismDesignPrimitives.JointProbabilityMass; /** * Domain generator for CATS "regions" domains with uncertain availability of goods. * @author Dmitry Moor */ public class DomainGeneratorSpatialUncertain extends DomainGeneratorSpatial { private static final Logger _logger = LogManager.getLogger(DomainGeneratorSpatialUncertain.class); /*** * Constructor * @param numberOfGoods number of goods in the auction * @throws SpacialDomainGenerationException if cannot create a square grid with the specified number of goods */ public DomainGeneratorSpatialUncertain(int numberOfGoods) throws SpacialDomainGenerationException { super(numberOfGoods); _logger.debug("DomainGeneratorCATSUncertain(numberOfGoods="+numberOfGoods+")"); _primaryReductionCoef = null; _secondaryReductionCoef = null; _probabilityOfBeingChosen = null; _probabilityOfExplosion = null; } /** * The method generates a joint probability mass function. * @throws SpacialDomainGenerationException if some "bombing" parameters are still to be specified */ public void generateJPMF() throws SpacialDomainGenerationException { _logger.debug("-> generateJPMF()"); if( _primaryReductionCoef == null) throw new SpacialDomainGenerationException("Primary reduction coefficients are not specified"); if( _secondaryReductionCoef == null) throw new SpacialDomainGenerationException("Secondary reduction coefficients are not specified"); if( _probabilityOfBeingChosen == null) throw new SpacialDomainGenerationException("Probabilities of being chosen are not specified"); if( _probabilityOfExplosion == null) throw new SpacialDomainGenerationException("Probabilities of explosion are not specified"); List<IBombingStrategy> bombs = IntStream.range(0, _probabilityOfBeingChosen.size()).boxed().parallel() .map( i -> new FocusedBombingStrategy( _grid, _probabilityOfExplosion.get(i), _primaryReductionCoef.get(i), _secondaryReductionCoef.get(i))) .collect(Collectors.toList()); _jpmf = new JointProbabilityMass( _grid ); _jpmf.setNumberOfSamples(_numberOfJPMFSamples); _jpmf.setNumberOfBombsToThrow(_numberOfBombsToThrow); _jpmf.setBombs(bombs, _probabilityOfBeingChosen); _jpmf.update(); _logger.debug("<- generateJPMF()"); } /** * The method sets up the number of sample to be used by the JPMF generator. * @param numberOfJPMFSamples number of samples to be used to generate the joint probability mass function */ public void setNumberOfJPMFSamples(int numberOfJPMFSamples) { _numberOfJPMFSamples = numberOfJPMFSamples; } /** * The method sets up the number of bombs to be thrown by the JPMF sampling procedure. * @param numberOfBombsToThrow the number of bombs to thrown by JPMF sampling */ public void setNumberOfBombsToThrow(int numberOfBombsToThrow) { _numberOfBombsToThrow = numberOfBombsToThrow; } /** * The method sets up parameters for focused bombing strategies. * @param primaryReductionCoef primary reduction coefficients * @param secondaryReductionCoef secondary reduction coefficients * @param probabilityOfBeingChosen probability of a particular bomb to be chosen * @param probabilityOfExplosion probability that a bomb explodes * @throws SpacialDomainGenerationException if wrong "bombing" parameters are specified */ public void setBombsParameters(List<Double> primaryReductionCoef, List<Double> secondaryReductionCoef, List<Double> probabilityOfBeingChosen, List<Double> probabilityOfExplosion) throws SpacialDomainGenerationException { if( (primaryReductionCoef.size() != secondaryReductionCoef.size()) || (primaryReductionCoef.size() != probabilityOfBeingChosen.size()) || (primaryReductionCoef.size() != probabilityOfExplosion.size()) ) throw new SpacialDomainGenerationException("Dimensionality mismatch"); if( Math.abs( probabilityOfBeingChosen.stream().reduce( (x1, x2) -> x1 + x2).get() - 1.) > 1e-6 ) throw new SpacialDomainGenerationException("The probability distribution must be normalized"); _primaryReductionCoef = primaryReductionCoef; _logger.debug("Primary reduction coef: " + _primaryReductionCoef.toString()); _secondaryReductionCoef = secondaryReductionCoef; _logger.debug("Secondary reduction coef: " + _secondaryReductionCoef.toString()); _probabilityOfBeingChosen = probabilityOfBeingChosen; _logger.debug("Probability of being chosen: " + _probabilityOfBeingChosen.toString()); _probabilityOfExplosion = probabilityOfExplosion; _logger.debug("Probability of explosion: " + _probabilityOfExplosion.toString()); } /** * The method returns the jpmf generated for the domain. * @return the jpmf */ public JointProbabilityMass getJPMF() { return _jpmf; } protected JointProbabilityMass _jpmf; //Joint probability mass function protected int _numberOfJPMFSamples = 10000; //The number of samples to be used for generating of the jpmf protected int _numberOfBombsToThrow = 1; //The number of bombs to throw when sampling the jpmf protected List<Double> _primaryReductionCoef; //Primary reduction coefficients of the focused bombing strategy protected List<Double> _secondaryReductionCoef; //Secondary reduction coefficients of the focused bombing strategy protected List<Double> _probabilityOfBeingChosen; //List of probabilities of different bombs too be chosen protected List<Double> _probabilityOfExplosion; //List of probabilities of each particular bomb to explode }
[ "dmitry.moor@yandex.ru" ]
dmitry.moor@yandex.ru
54abec77fe7e0ced4ef5bf51d99eff8a8ca56a72
c885ef92397be9d54b87741f01557f61d3f794f3
/results/Codec-14/org.apache.commons.codec.language.bm.PhoneticEngine/BBC-F0-opt-70/tests/29/org/apache/commons/codec/language/bm/PhoneticEngine_ESTest.java
04eb57ba05f57a27b12b202c88727583f7cb5dfd
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
5,967
java
/* * This file was automatically generated by EvoSuite * Sun Oct 24 04:31:05 GMT 2021 */ package org.apache.commons.codec.language.bm; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Set; import org.apache.commons.codec.language.bm.Languages; import org.apache.commons.codec.language.bm.NameType; import org.apache.commons.codec.language.bm.PhoneticEngine; import org.apache.commons.codec.language.bm.Rule; import org.apache.commons.codec.language.bm.RuleType; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true) public class PhoneticEngine_ESTest extends PhoneticEngine_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { NameType nameType0 = NameType.SEPHARDIC; RuleType ruleType0 = RuleType.APPROX; PhoneticEngine phoneticEngine0 = null; try { phoneticEngine0 = new PhoneticEngine(nameType0, ruleType0, false, 0); fail("Expecting exception: NoClassDefFoundError"); } catch(NoClassDefFoundError e) { // // Could not initialize class org.apache.commons.codec.language.bm.Lang // verifyException("org.apache.commons.codec.language.bm.PhoneticEngine", e); } } @Test(timeout = 4000) public void test1() throws Throwable { NameType nameType0 = NameType.SEPHARDIC; RuleType ruleType0 = RuleType.RULES; PhoneticEngine phoneticEngine0 = null; try { phoneticEngine0 = new PhoneticEngine(nameType0, ruleType0, true); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // ruleType must not be RULES // verifyException("org.apache.commons.codec.language.bm.PhoneticEngine", e); } } @Test(timeout = 4000) public void test2() throws Throwable { NameType nameType0 = NameType.GENERIC; RuleType ruleType0 = RuleType.RULES; PhoneticEngine phoneticEngine0 = null; try { phoneticEngine0 = new PhoneticEngine(nameType0, ruleType0, true, (-465)); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // ruleType must not be RULES // verifyException("org.apache.commons.codec.language.bm.PhoneticEngine", e); } } @Test(timeout = 4000) public void test3() throws Throwable { PhoneticEngine.PhonemeBuilder phoneticEngine_PhonemeBuilder0 = PhoneticEngine.PhonemeBuilder.empty((Languages.LanguageSet) null); String string0 = phoneticEngine_PhonemeBuilder0.makeString(); assertEquals("", string0); } @Test(timeout = 4000) public void test4() throws Throwable { LinkedHashSet<String> linkedHashSet0 = new LinkedHashSet<String>(); linkedHashSet0.add(""); Languages.LanguageSet languages_LanguageSet0 = Languages.LanguageSet.from(linkedHashSet0); PhoneticEngine.PhonemeBuilder phoneticEngine_PhonemeBuilder0 = PhoneticEngine.PhonemeBuilder.empty(languages_LanguageSet0); Rule.Phoneme rule_Phoneme0 = new Rule.Phoneme("", languages_LanguageSet0); // Undeclared exception! try { phoneticEngine_PhonemeBuilder0.apply(rule_Phoneme0, 1); fail("Expecting exception: NoClassDefFoundError"); } catch(NoClassDefFoundError e) { // // Could not initialize class org.apache.commons.codec.language.bm.Languages // verifyException("org.apache.commons.codec.language.bm.Languages$SomeLanguages", e); } } @Test(timeout = 4000) public void test5() throws Throwable { PhoneticEngine.PhonemeBuilder phoneticEngine_PhonemeBuilder0 = PhoneticEngine.PhonemeBuilder.empty((Languages.LanguageSet) null); LinkedList<Rule.Phoneme> linkedList0 = new LinkedList<Rule.Phoneme>(); Rule.PhonemeList rule_PhonemeList0 = new Rule.PhonemeList(linkedList0); phoneticEngine_PhonemeBuilder0.apply(rule_PhonemeList0, 0); } @Test(timeout = 4000) public void test6() throws Throwable { LinkedHashSet<String> linkedHashSet0 = new LinkedHashSet<String>(); linkedHashSet0.add("bA$"); Languages.LanguageSet languages_LanguageSet0 = Languages.LanguageSet.from(linkedHashSet0); PhoneticEngine.PhonemeBuilder phoneticEngine_PhonemeBuilder0 = PhoneticEngine.PhonemeBuilder.empty(languages_LanguageSet0); phoneticEngine_PhonemeBuilder0.append("bA$"); assertTrue(linkedHashSet0.contains("bA$")); } @Test(timeout = 4000) public void test7() throws Throwable { RuleType ruleType0 = RuleType.EXACT; NameType nameType0 = NameType.GENERIC; PhoneticEngine phoneticEngine0 = null; try { phoneticEngine0 = new PhoneticEngine(nameType0, ruleType0, false); fail("Expecting exception: NoClassDefFoundError"); } catch(NoClassDefFoundError e) { // // Could not initialize class org.apache.commons.codec.language.bm.Lang // verifyException("org.apache.commons.codec.language.bm.PhoneticEngine", e); } } @Test(timeout = 4000) public void test8() throws Throwable { LinkedHashSet<String> linkedHashSet0 = new LinkedHashSet<String>(); linkedHashSet0.add(""); Languages.LanguageSet languages_LanguageSet0 = Languages.LanguageSet.from(linkedHashSet0); PhoneticEngine.PhonemeBuilder phoneticEngine_PhonemeBuilder0 = PhoneticEngine.PhonemeBuilder.empty(languages_LanguageSet0); Set<Rule.Phoneme> set0 = phoneticEngine_PhonemeBuilder0.getPhonemes(); assertEquals(1, set0.size()); } }
[ "pderakhshanfar@serg2.ewi.tudelft.nl" ]
pderakhshanfar@serg2.ewi.tudelft.nl
b36e1cc73ca68fe2a2c1abe24b3e44c995af5d05
fb78c95928c6dc1aa3b51ad3f42df772919a0753
/03wordsearch/Driver.java
1f8af36c4c039c3b8ca885f0a5fa02aaa452a7eb
[]
no_license
drothblatt/APCSHW-term1
65bc805d0a054cd2f01c720f4ba6da6fb540ddc9
dde2f9e966fdb417b328702ebdee82869b56183d
refs/heads/master
2020-04-04T15:16:20.214538
2014-12-20T21:12:02
2014-12-20T21:12:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,359
java
import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class Driver{ public static boolean checkInputs(int rows, int cols, int randomSeed){ return rows < 3 || rows > 40 || cols < 3 || cols > 40 || randomSeed <= 0; } public static void main(String[]args) throws FileNotFoundException{ int rows, cols, randomSeed; boolean fill; // original initialization (in case it doesn't happen later) rows = 0; cols = 0; randomSeed = 0; fill = true; // end of default. boolean toosmall; try{ String x = args[2]; toosmall = false; } catch (Exception e){ System.out.println("Not enough inputs. Try again.\n" + ">> Need: Java Driver <#ofRows> <#ofCols> <RandSeed>\n" + ">> Optional: Java Driver <#ofRows> <#ofCols> <RandSeed>" ); toosmall = true; } if (!toosmall){ try{ rows = Integer.parseInt(args[0]); cols = Integer.parseInt(args[1]); randomSeed = Integer.parseInt(args[2]); //randomSeed = rSeed;. if (checkInputs(rows,cols,randomSeed)){ String y = args[100]; } } catch (Exception e){ System.out.println("Invalid inputs for #ofRows, #ofCols, and/or randomSeed." + "\n>> #ofRows/#ofCols must be btwn 3 & 40."+ "\n>> randomSeed must be greater than 0."); } } if (args.length == 4){ try{ int answers = Integer.parseInt(args[3]); if (answers == 1){ fill = false; System.out.println("\n*** THIS IS THE ANSWER KEY!"); } else{ fill = true; System.out.println("\n*** For ANSWER KEY, fourth input (index 3) must be '1'. "); } } catch (Exception e){ System.out.println("\n*** For ANSWER KEY, fourth input (index 3) must be '1'. "); } } else if (args.length == 3 && !checkInputs(rows,cols,randomSeed)){ System.out.println("\n*** For ANSWER KEY, fourth input (index 3) must be '1'. "); } if (!checkInputs(rows,cols,randomSeed)){ //wGrid must have the right inputs or we're done WordGrid w = new WordGrid(rows, cols); if(randomSeed != 0){ w.setSeed(randomSeed); } w.loadWordsFromFile("words.txt", fill); System.out.println( "\nFind these words:\n" + w.wordsInPuzzle() ); System.out.println( w ); System.out.println( "Total number of words in puzzle: " // my own addition + w.getWordCount() + "\n" ); } // The end!! } }
[ "daroth13@gmail.com" ]
daroth13@gmail.com
885d0e0aa5be2abf3ed7257a14d47246eaec913f
a53f3efa7b4e4f7562f5d5b5ff897339eaaf3896
/target/test-classes/javax/el/TestBeanELResolver.java
d2bb932586f332fb4c6317eba59266c8a333ccaa
[ "Zlib", "LZMA-exception", "CPL-1.0", "bzip2-1.0.6", "Apache-2.0", "EPL-1.0", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0" ]
permissive
waylc/apache-tomcat-8.5.37-src
3b2a2b7f9726d0331ca09c7ba869f69f1d17f663
5deda39b5ef28c753d6efbf659fe02aef40c340e
refs/heads/master
2022-02-04T15:34:55.624330
2019-07-17T11:03:20
2019-07-17T11:03:20
196,672,823
0
0
Apache-2.0
2022-01-21T23:36:14
2019-07-13T03:17:51
Java
UTF-8
Java
false
false
37,745
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.el; import java.beans.FeatureDescriptor; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.Iterator; import org.junit.Assert; import org.junit.Test; import org.apache.jasper.el.ELContextImpl; public class TestBeanELResolver { private static final String METHOD01_NAME = "toString"; private static final String METHOD02_NAME = "<init>"; private static final String METHOD03_NAME = "nonExistingMethod"; private static final String BEAN_NAME = "test"; private static final String PROPERTY01_NAME = "valueA"; private static final String PROPERTY02_NAME = "valueB"; private static final String PROPERTY03_NAME = "name"; private static final String PROPERTY_VALUE = "test1"; @Test public void testBug53421() { ExpressionFactory factory = ExpressionFactory.newInstance(); ELContext context = new ELContextImpl(factory); Bean bean = new Bean(); ValueExpression varBean = factory.createValueExpression(bean, Bean.class); context.getVariableMapper().setVariable("bean", varBean); ValueExpression ve = factory.createValueExpression( context, "${bean.valueA}", String.class); Exception e = null; try { ve.getValue(context); } catch (PropertyNotFoundException pnfe) { e = pnfe; } Assert.assertTrue("Wrong exception type", e instanceof PropertyNotFoundException); String type = Bean.class.getName(); String msg = e.getMessage(); Assert.assertTrue("No reference to type [" + type + "] where property cannot be found in [" + msg + "]", msg.contains(type)); } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected = NullPointerException.class) public void testGetType01() { BeanELResolver resolver = new BeanELResolver(); resolver.getType(null, new Object(), new Object()); } /** * Tests that a valid property is not resolved if base is null. */ @Test public void testGetType02() { doNegativeTest(null, new Object(), MethodUnderTest.GET_TYPE, true); } /** * Tests that a valid property is resolved. */ @Test public void testGetType03() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Class<?> result = resolver.getType(context, new Bean(), PROPERTY01_NAME); Assert.assertEquals(String.class, result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that an exception will be thrown when the property does not exist. */ @Test(expected = PropertyNotFoundException.class) public void testGetType04() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.getType(context, new Bean(), PROPERTY02_NAME); } /** * Tests that an exception will be thrown when a coercion cannot be * performed. */ @Test(expected = PropertyNotFoundException.class) public void testGetType05() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.getType(context, new Bean(), new Object()); } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected = NullPointerException.class) public void testGetValue01() { BeanELResolver resolver = new BeanELResolver(); resolver.getValue(null, new Object(), new Object()); } /** * Tests that a valid property is not resolved if base is null. */ @Test public void testGetValue02() { doNegativeTest(null, new Object(), MethodUnderTest.GET_VALUE, true); } /** * Tests that a valid property is resolved. */ @Test public void testGetValue03() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.getValue(context, new TesterBean(BEAN_NAME), PROPERTY03_NAME); Assert.assertEquals(BEAN_NAME, result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that an exception will be thrown when the property does not exist. */ @Test(expected = PropertyNotFoundException.class) public void testGetValue04() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.getValue(context, new Bean(), PROPERTY02_NAME); } /** * Tests that an exception will be thrown when a coercion cannot be * performed. */ @Test(expected = PropertyNotFoundException.class) public void testGetValue05() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.getValue(context, new Bean(), new Object()); } /** * Tests that an exception will be thrown when the property is not readable. */ @Test(expected = PropertyNotFoundException.class) public void testGetValue06() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.getValue(context, new Bean(), PROPERTY01_NAME); } /** * Tests that getter method throws exception which should be propagated. */ @Test(expected = ELException.class) public void testGetValue07() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.getValue(context, new TesterBean(BEAN_NAME), PROPERTY01_NAME); } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected = NullPointerException.class) public void testSetValue01() { BeanELResolver resolver = new BeanELResolver(); resolver.setValue(null, new Object(), new Object(), new Object()); } /** * Tests that a valid property is not resolved if base is null. */ @Test public void testSetValue02() { doNegativeTest(null, new Object(), MethodUnderTest.SET_VALUE, true); } /** * Tests that an exception is thrown when readOnly is true. */ @Test(expected = PropertyNotWritableException.class) public void testSetValue03() { BeanELResolver resolver = new BeanELResolver(true); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.setValue(context, new Bean(), new Object(), new Object()); } /** * Tests that a valid property is resolved. */ @Test public void testSetValue04() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); TesterBean bean = new TesterBean(BEAN_NAME); resolver.setValue(context, bean, PROPERTY03_NAME, PROPERTY_VALUE); Assert.assertEquals(PROPERTY_VALUE, resolver.getValue(context, bean, PROPERTY03_NAME)); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that an exception will be thrown when a coercion cannot be * performed. */ @Test(expected = PropertyNotFoundException.class) public void testSetValue05() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.setValue(context, new Bean(), new Object(), PROPERTY_VALUE); } /** * Tests that an exception will be thrown when the property does not exist. */ @Test(expected = PropertyNotFoundException.class) public void testSetValue06() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.setValue(context, new Bean(), PROPERTY02_NAME, PROPERTY_VALUE); } /** * Tests that an exception will be thrown when the property does not have * setter method. */ @Test(expected = PropertyNotWritableException.class) public void testSetValue07() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.setValue(context, new TesterBean(BEAN_NAME), PROPERTY01_NAME, PROPERTY_VALUE); } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected = NullPointerException.class) public void testIsReadOnly01() { BeanELResolver resolver = new BeanELResolver(); resolver.isReadOnly(null, new Object(), new Object()); } /** * Tests that the propertyResolved is false if base is null. */ @Test public void testIsReadOnly02() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.isReadOnly(context, null, new Object()); Assert.assertFalse(context.isPropertyResolved()); resolver = new BeanELResolver(true); resolver.isReadOnly(context, null, new Object()); Assert.assertFalse(context.isPropertyResolved()); } /** * Tests that if the BeanELResolver is constructed with readOnly the method * will return always true. */ @Test public void testIsReadOnly03() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); boolean result = resolver.isReadOnly(context, new TesterBean(BEAN_NAME), PROPERTY03_NAME); Assert.assertFalse(result); Assert.assertTrue(context.isPropertyResolved()); resolver = new BeanELResolver(true); result = resolver.isReadOnly(context, new TesterBean(BEAN_NAME), PROPERTY03_NAME); Assert.assertTrue(result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that an exception is thrown when a coercion cannot be performed. */ @Test(expected = PropertyNotFoundException.class) public void testIsReadOnly04() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.isReadOnly(context, new TesterBean(BEAN_NAME), Integer.valueOf(0)); } /** * Tests that an exception will be thrown when the property does not exist. */ @Test(expected = PropertyNotFoundException.class) public void testIsReadOnly05() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.isReadOnly(context, new Bean(), PROPERTY02_NAME); } /** * Tests that true will be returned when the property does not have setter * method. */ @Test public void testIsReadOnly06() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); boolean result = resolver.isReadOnly(context, new TesterBean(BEAN_NAME), PROPERTY01_NAME); Assert.assertTrue(result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that a valid FeatureDescriptors are not returned if base is not * Map. */ @Test public void testGetFeatureDescriptors01() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(context, null); Assert.assertNull(result); } /** * Tests that a valid FeatureDescriptors are returned. */ @Test public void testGetFeatureDescriptors02() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(context, new Bean()); while (result.hasNext()) { PropertyDescriptor featureDescriptor = (PropertyDescriptor) result.next(); Assert.assertEquals(featureDescriptor.getPropertyType(), featureDescriptor.getValue(ELResolver.TYPE)); Assert.assertEquals(Boolean.TRUE, featureDescriptor.getValue(ELResolver.RESOLVABLE_AT_DESIGN_TIME)); } } /** * Tests that a null context results in an NPE as per EL Javadoc. */ @Test(expected = NullPointerException.class) public void testInvoke01() { BeanELResolver resolver = new BeanELResolver(); resolver.invoke(null, new Object(), new Object(), new Class<?>[0], new Object[0]); } /** * Tests that a valid property is not resolved if base is null. */ @Test public void testInvoke02() { doNegativeTest(null, new Object(), MethodUnderTest.INVOKE, true); } /** * Tests a method invocation. */ @Test public void testInvoke03() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), METHOD01_NAME, new Class<?>[] {}, new Object[] {}); Assert.assertEquals(BEAN_NAME, result); Assert.assertTrue(context.isPropertyResolved()); } /** * Tests that the method name cannot be coerced to String. */ @Test public void testInvoke04() { doNegativeTest(new Bean(), null, MethodUnderTest.INVOKE, true); } /** * Tests that a call to &lt;init&gt; as a method name will throw an exception. */ @Test(expected = MethodNotFoundException.class) public void testInvoke05() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.invoke(context, new TesterBean(BEAN_NAME), METHOD02_NAME, new Class<?>[] {}, new Object[] {}); } /** * Tests that a call to a non existing method will throw an exception. */ @Test(expected = MethodNotFoundException.class) public void testInvoke06() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); resolver.invoke(context, new TesterBean(BEAN_NAME), METHOD03_NAME, new Class<?>[] {}, new Object[] {}); } @Test public void testInvokeVarargsCoerce01() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] {}, new String[] {}); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce02() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", null, null); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce03() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", null, new String[] {}); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce04() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] {}, null); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce05() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { null }, new String[] { null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce06() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", null, new String[] { null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce07() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { null }, null); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce08() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class }, new String[] { "true" }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce09() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class }, new Object[] { "true", null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce10() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String[].class }, new Object[] { "true", null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce11() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class }, new Object[] { "10" }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce12() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String[].class }, new String[] { "10" }); Assert.assertEquals(BEAN_NAME, result); } // Ambiguous because the Strings coerce to both Boolean and Integer hence // both varargs methods match. @Test(expected=MethodNotFoundException.class) public void testInvokeVarargsCoerce13() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class }, new String[] { "10", "11" }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce14() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class }, new String[] { "true", null }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargsCoerce15() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class }, new Object[] { "true", new ArrayList<>() }); Assert.assertEquals(BEAN_NAME, result); } // Ambiguous because the Strings coerce to both Boolean and Integer hence // both varargs methods match. @Test(expected=MethodNotFoundException.class) public void testInvokeVarargsCoerce16() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class, String.class }, new Object[] { "10", "11", "12" }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargsCoerce17() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class }, new Object[] { "10", "11", "12" }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargsCoerce18() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class, String.class, String.class }, new Object[] { "10", "11", "12" }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargsCoerce19() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class, String.class, String.class }, new Object[] { "true", "10", "11", "12" }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargsCoerce20() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class, String.class }, new Object[] { "true", "10", "11", "12" }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargsCoerce21() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { String.class, String.class, String.class, String.class, String.class }, new Object[] { "true", "10", "11", "12" }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs01() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] {}, new Object[] {}); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs02() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", null, null); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs03() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", null, new Object[] {}); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs04() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] {}, null); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs05() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { null }, new Object[] { null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs06() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", null, new Object[] { null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs07() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { null }, null); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs08() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class }, new Object[] { Boolean.TRUE }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs09() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class, Integer.class }, new Object[] { Boolean.TRUE, null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs10() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class, Integer[].class }, new Object[] { Boolean.TRUE, null }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs11() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Integer.class }, new Object[] { Integer.valueOf(10) }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs12() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Integer[].class }, new Object[] { Integer.valueOf(10) }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs13() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Integer.class, Integer.class }, new Object[] { Integer.valueOf(10), Integer.valueOf(11) }); Assert.assertEquals(BEAN_NAME, result); } // Note: The coercion rules are that a null of any type can be coerced to a // null of *any* other type so this works. @Test public void testInvokeVarargs14() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class, ArrayList.class }, new Object[] { Boolean.TRUE, null }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargs15() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class, ArrayList.class }, new Object[] { Boolean.TRUE, new ArrayList<>() }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs16() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Integer.class, Integer.class, Integer.class }, new Object[] { Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargs17() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Integer.class, Integer.class }, new Object[] { Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargs18() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Integer.class, Integer.class, Integer.class, Integer.class }, new Object[] { Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) }); Assert.assertEquals(BEAN_NAME, result); } @Test public void testInvokeVarargs19() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class, Integer.class, Integer.class, Integer.class }, new Object[] { Boolean.TRUE, Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargs20() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class, Integer.class, Integer.class }, new Object[] { Boolean.TRUE, Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) }); Assert.assertEquals(BEAN_NAME, result); } @Test(expected=MethodNotFoundException.class) public void testInvokeVarargs21() { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs", new Class<?>[] { Boolean.class, Integer.class, Integer.class, Integer.class, Integer.class }, new Object[] { Boolean.TRUE, Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) }); Assert.assertEquals(BEAN_NAME, result); } private static class Bean { @SuppressWarnings("unused") public void setValueA(String valueA) { // NOOP } } private void doNegativeTest(Object base, Object trigger, MethodUnderTest method, boolean checkResult) { BeanELResolver resolver = new BeanELResolver(); ELContext context = new StandardELContext(ELManager.getExpressionFactory()); Object result = null; switch (method) { case GET_VALUE: { result = resolver.getValue(context, base, trigger); break; } case SET_VALUE: { resolver.setValue(context, base, trigger, new Object()); break; } case GET_TYPE: { result = resolver.getType(context, base, trigger); break; } case INVOKE: { result = resolver.invoke(context, base, trigger, new Class<?>[0], new Object[0]); break; } default: { // Should never happen Assert.fail("Missing case for method"); } } if (checkResult) { Assert.assertNull(result); } Assert.assertFalse(context.isPropertyResolved()); } private static enum MethodUnderTest { GET_VALUE, SET_VALUE, GET_TYPE, INVOKE } }
[ "717195415@qq.com" ]
717195415@qq.com
8837cb18138420460b4263d80f717ada9521ef20
2389bc000bf5557423dca17da21d8cbb399214e9
/app/src/main/java/com/example/findwhousesmyhotspot/WiFiDirectBroadcastReceiver.java
5efd2518e3b36cc2753c6bea3f987f755365ae85
[]
no_license
skennetho/WifiDirectPractice
1c98d82ece12829f00917587a1ea3e19f08d9e03
1b0ce9e3a25bfb2dcea1ef90e5823434c02ffc2f
refs/heads/master
2022-11-27T22:13:48.831003
2020-07-31T16:20:40
2020-07-31T16:20:40
279,260,903
0
0
null
null
null
null
UTF-8
Java
false
false
4,713
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 com.example.findwhousesmyhotspot; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.NetworkInfo; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.util.Log; /** * 중요한 Wi-Fi P2P 이벤트를 알려주는 BroadcastReceiver * */ public class WiFiDirectBroadcastReceiver extends BroadcastReceiver { final static String TAG = "DeviceListFragment"; private WifiP2pManager manager; private Channel channel; private WiFiDirectActivity activity; /** * @param manager WifiP2pManager system service * @param channel Wifi p2p channel (어프리케이션을 Wifi p2p 프레임워크에 연결) * @param activity activity associated with the receiver(receiver가 연결된 activity) * */ public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, WiFiDirectActivity activity) { super(); this.manager = manager; this.channel = channel; this.activity = activity; } /* * (non-Javadoc) * @see android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { // UI update to indicate wifi p2p status. wifi p2p 상태 int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { // Wifi Direct 모드가 가능하면 WiFiDirectActivity 클래스 IsWifiP2pEnabled를 true로 activity.setIsWifiP2pEnabled(true); } else { activity.setIsWifiP2pEnabled(false); activity.resetData(); } Log.d(TAG, "P2P state changed - " + state); } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { /** * Wi-Fi P2P manager에서 사용할 수 있는 상대방을 요청한다. * 비동기로 호출하고, 호출 액티비티를 PeerListListener.onPeersAvailable()에 * 콜백으로 통지한다. */ if (manager != null) { manager.requestPeers(channel, (PeerListListener) activity.getSupportFragmentManager().findFragmentById(R.id.frag_list)); } Log.d(WiFiDirectActivity.TAG, "P2P peers changed"); } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { if (manager == null) { return; } NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); if (networkInfo.isConnected()) { // 그룹 오너 IP를 찾기 위해 접속 정보를 요청한다. // we are connected with the other device, request connection // info to find group owner IP DeviceDetailFragment fragment = (DeviceDetailFragment) activity .getSupportFragmentManager().findFragmentById(R.id.frag_detail); manager.requestConnectionInfo(channel, fragment); } else { // 연결을 끊는다 activity.resetData(); } // 디바이스 정보의 변경을 나타내는 인텐트 action을 전달한다. } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { DeviceListFragment fragment = (DeviceListFragment) activity.getSupportFragmentManager() .findFragmentById(R.id.frag_list); fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra( WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)); } } }
[ "thrkd613@naver.com" ]
thrkd613@naver.com
ada0fa3f1b06b5c8a2135e0757a5c8db581676cd
a52f509c87458321cebe424b6a80273b2fa41084
/src/AmazonOA/com/DistanceBetweenNodesinBST.java
c4a6a387b982121e289e5186d6f5c64e30b31a21
[]
no_license
jiefanshi/JavaCap
fa8a307dbdf316ecb431a439146fafdded04dac0
1dda027335d1cf54b4ef4c9e1bfd85b6606ed2bc
refs/heads/master
2020-08-23T20:00:29.148815
2019-10-22T01:32:40
2019-10-22T01:32:40
216,697,912
0
0
null
null
null
null
UTF-8
Java
false
false
4,761
java
package AmazonOA.com; import java.util.*; class DistanceBetweenNodesInBST { public static void main(String[] args) { DistanceBetweenNodesInBST main = new DistanceBetweenNodesInBST(); constructTreeAnyOrder consTree = new constructTreeAnyOrder(); TreeNode root = consTree.constructATree (new int[] {10,18,12,16,19,13,20,3,1,7,14}); System.out.println(root.left.right.val); TreeNode node1 = new TreeNode(18); TreeNode node2 = new TreeNode(7); //System.out.println(main.getDistance(LCA, node1)); lowestCommonAncestor lca = new lowestCommonAncestor(); //TreeNode LCA = lca.LCA(root, node1, node2); //System.out.println(LCA == null); //System.out.println(LCA.val); //TreeNode LCA = main.lowestCommonAncestor(root, node1, node2); //System.out.println(LCA == null); //System.out.println(main.getDistance(LCA, node2)); System.out.println(main.distanceCalculator(new int[] {10,18,12,16,19,13,20,3,1,7,14}, node1, node2)); } public int distanceCalculator(int[] nums, TreeNode node1, TreeNode node2){ if(nums == null || nums.length == 0){ return -1; } constructTreeAnyOrder consTree = new constructTreeAnyOrder(); TreeNode root = consTree.constructATree(nums); lowestCommonAncestor lca = new lowestCommonAncestor(); TreeNode LCA = lca.LCA(root, node1, node2); if (LCA == null){ return -1; } //System.out.println(LCA.val); return getDistance(LCA, node1) + getDistance(LCA, node2); } public int getDistance(TreeNode root, TreeNode node){ if (root.val == node.val){ return 0; } if (node.val > root.val){ return getDistance(root.right, node) + 1; }else{ return getDistance(root.left, node) + 1; } } private static class lowestCommonAncestor{ public TreeNode LCA(TreeNode root, TreeNode node1, TreeNode node2){ resultType result = LCAHelper(root, node1, node2); if (list.isEmpty()){ return null; } return list.get(0); } private List<TreeNode> list = new ArrayList<>(); public resultType LCAHelper(TreeNode root, TreeNode node1, TreeNode node2){ if (root == null){ return new resultType(false, false); } resultType left = LCAHelper(root.left, node1, node2); resultType right = LCAHelper(root.right, node1, node2); boolean aExist = root.val == node1.val || left.aExist || right.aExist; boolean bExist = root.val == node2.val || left.bExist || right.bExist; if (aExist && bExist){ list.add(root); } return new resultType(aExist, bExist); } } private static class resultType{ public boolean aExist, bExist; public resultType(boolean aExist, boolean bExist){ this.aExist = aExist; this.bExist = bExist; } } private static class constructTreePreOrder{ public TreeNode constructATree(int[] nums){// The given nums should be in preorder if (nums == null || nums.length == 0){ return null; } //System.out.println(constructTreeHelper(nums, Integer.MAX_VALUE)); return Helper(nums, Integer.MAX_VALUE); } public int i = 0; public TreeNode Helper(int[] nums, int bound){ if (i == nums.length || nums[i] > bound){ return null; } TreeNode root = new TreeNode(nums[i++]); root.left = Helper(nums, root.val); root.right = Helper(nums, bound); return root; } } private static class constructTreeAnyOrder{// The given nums could be any order public TreeNode constructATree(int[] nums){ TreeNode root = new TreeNode(nums[0]); for (int i = 1; i < nums.length; i++){ insert(root, nums[i]); } return root; } public TreeNode insert(TreeNode root, int node){ if (root == null) { return new TreeNode(node); } if (node < root.val) { root.left = insert(root.left, node); } else if (node > root.val) { root.right = insert(root.right, node); } return root; } } private static class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x){ val = x; } } }
[ "feiwanghao@gmail.com" ]
feiwanghao@gmail.com
fd7f51709fc040f5e09ace962bd9225898211324
95c49f466673952b465e19a5ee3ae6eff76bee00
/src/main/java/com/zhihu/android/app/feed/p1083ui/holder/p1103ad/AdFocusVideoDynamicViewHolder.java
b4f0df49f09cd6207bd4e6a69f9d87d3d7f47635
[]
no_license
Phantoms007/zhihuAPK
58889c399ae56b16a9160a5f48b807e02c87797e
dcdbd103436a187f9c8b4be8f71bdf7813b6d201
refs/heads/main
2023-01-24T01:34:18.716323
2020-11-25T17:14:55
2020-11-25T17:14:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,721
java
package com.zhihu.android.app.feed.p1083ui.holder.p1103ad; import android.view.View; import android.widget.TextView; import com.secneo.apkwrapper.C6969H; import com.zhihu.android.R; import com.zhihu.android.api.model.FeedAdvert; import com.zhihu.android.p945ad.C9180g; import com.zhihu.android.video.player2.widget.VideoInlineVideoView; /* renamed from: com.zhihu.android.app.feed.ui.holder.ad.AdFocusVideoDynamicViewHolder */ public class AdFocusVideoDynamicViewHolder extends AdFocusDynamicAdViewHolder { /* renamed from: B */ private boolean m61613B() { return true; } public AdFocusVideoDynamicViewHolder(View view) { super(view); } /* access modifiers changed from: protected */ @Override // com.zhihu.android.app.feed.p1083ui.holder.p1103ad.AdFocusDynamicAdViewHolder, com.zhihu.android.app.feed.p1083ui.holder.p1103ad.BaseDynamicAdViewHolder, com.zhihu.android.app.feed.p1083ui.holder.p1103ad.BaseAdFeedHolder /* renamed from: a */ public void mo56529a(FeedAdvert feedAdvert) { super.mo56529a(feedAdvert); TextView textView = (TextView) this.f43883j.findViewByStringTag(C6969H.m41409d("G68879B0CB634AE26A801864DE0E9C2CE2794DC1CB6")); if (textView == null) { C9180g.m54586b("wifiTips is null"); return; } textView.setVisibility(m61613B() ? 0 : 4); VideoInlineVideoView A = mo67275A(); if (A != null) { try { TextView textView2 = (TextView) A.findViewById(R.id.duration); if (textView2 != null) { textView2.setVisibility(4); } } catch (Exception unused) { } } } }
[ "seasonpplp@qq.com" ]
seasonpplp@qq.com
ef32e891bc02ea86e1dfcf1224e3903605141f3d
8ae1d0202278eb17ca6fca7f8cf36fd56aabbc88
/dataStructure/src/main/java/com/zj/recursive/T.java
3c273e4cee2e1f0e32dcc8d76239b001a91a9099
[ "Apache-2.0" ]
permissive
hqq2023623/notes
d077628dbe90ccb064e8df2efb9ddf13a1bad7d8
490f09f19d25af313409ad6524c4a621beddbfbe
refs/heads/master
2021-01-18T23:55:22.881340
2017-11-02T23:06:52
2017-11-02T23:06:52
47,523,491
0
0
null
null
null
null
UTF-8
Java
false
false
4,183
java
package com.zj.recursive; import java.util.ArrayList; import java.util.List; public class T { public static int tiers = 4; // tiers 层数 private static List<String> pagoda1 = new ArrayList<String>(); // 静态指针 private static List<String> pagoda2 = new ArrayList<String>(); private static List<String> pagoda3 = new ArrayList<String>(); // 映射,用来确定并打印塔的序号(使用角标),也可以使用 Map private static List[] mapping = { pagoda1, pagoda2, pagoda3 }; public static void main(String[] args) { preparePagoda(pagoda1, tiers); System.out.println("初始状态:"); printPagodas(); hanoi(tiers, pagoda1, pagoda2, pagoda3); System.out.println("最后结果:"); printPagodas(); } // --准备盘子(添加-字符串) (源塔)上 private static void preparePagoda(List<String> srcPagoda, int tiers) { // 用于拼装塔层的容器 StringBuilder builder = new StringBuilder(); // 源塔的每一层加盘子,从底层开始, i ‘代表’盘子的直径大小,等于组成盘子的"^"个数 for (int i = tiers; i > 0; i--) { // 每一层由 2*tiers-1 个格子组成,代表盘子大小的"^"格子由空格隔开 for (int k = 0; k < tiers - i; k++) builder.append(" "); // 盘子左边的空格,数量为 [2*tiers-1-(2*i-1)]/2 = // tiers-i, 右边相同 for (int j = 1; j <= 2 * i - 1; j++) { // 盘子所占格数 if (j % 2 == 1) builder.append("^"); // 间隔摆放 else builder.append(" "); } for (int k = 0; k < tiers - i; k++) builder.append(" "); // 盘子右边的空格 srcPagoda.add(builder.toString()); // 添加到塔上 builder.delete(0, builder.length()); // 下一循环前清空容器 } } // --打印塔的现状 private static void printPagodas() { // 打印层数为三座塔-现状的最大高度 int len = Math.max(pagoda1.size(), Math.max(pagoda2.size(), pagoda3.size())); // 用于-塔的空层显示 StringBuilder spaces = new StringBuilder(); spaces.append("-"); // --添加塔的左外框 for (int i = 0; i < 2 * tiers - 1; i++) spaces.append(" "); // 空层显示用空格 spaces.append("-\t"); // --添加塔的右外框和塔间间隔 for (int i = len - 1; i >= 0; i--) { // 从顶层开始 // 三座塔同一水平面的塔层放在同一行显示 // 当某个塔不存在此层时,List.get(index)会抛角标越界异常,使用try-catch处理:此层显示一层空格 try { System.out.print("-" + pagoda1.get(i) + "-\t"); } catch (Exception e1) { System.out.print(spaces); } try { System.out.print("-" + pagoda2.get(i) + "-\t"); } catch (Exception e) { System.out.print(spaces); } try { System.out.print("-" + pagoda3.get(i) + "-\t"); } catch (Exception e) { System.out.print(spaces); } System.out.print("\r\n"); } } // 这个方法(递归的核心方法)从指定的源塔上移动-指定数量的盘子-到指定的目标塔上 public static void hanoi(int moveNum, List<String> from, List<String> middle, List<String> to) { if (moveNum == 1) { // 递归到移动一个盘子时,使用 move 方法 moveTheTopOne(from, to); return; } // 将实现分为三步,一,将源塔底盘上方的所有盘子移至中间塔(递归);二,将底盘移到目标塔;三,将中间塔上的所有盘子移到目标塔上(递归)。 hanoi(moveNum - 1, from, to, middle); moveTheTopOne(from, to); hanoi(moveNum - 1, middle, from, to); } // 方法的名字就是他的作用 private static void moveTheTopOne(List<String> from, List<String> to) { String theTopOne = from.remove(from.size() - 1); to.add(theTopOne); // 打印图形,每移动一下,打印图形显示 System.out.println("********** print ***********\r\n"); // 确定塔的序号 int fromNum = 0, toNum = 0; for (int i = 0; i < mapping.length; i++) { // 遍历塔的数组 if (mapping[i] == from) { fromNum = i + 1; } if (mapping[i] == to) { toNum = i + 1; } } System.out.println("从 " + fromNum + " 号塔往 " + toNum + " 号塔\r\n"); printPagodas(); // 打印图形 } }
[ "371209704@qq.com" ]
371209704@qq.com
a1f483a6763a9313aa48f576f12e06da7fe364b3
9b3928cc052b8e829d13e11c1f342de5ee230d71
/src/main/java/com/edu/victor/Dao/StuManagementDao.java
b157a68ecf8952eebc0ee1fe003f4140a65fd5dd
[]
no_license
cquptvictor/Video_Forensics
cf57f94f64ef2e10362e729b3a6ad640be429189
f4a8ff24904cbe0aadb2265ad874e109fa39ab59
refs/heads/master
2022-12-25T03:40:16.215244
2019-12-17T08:27:14
2019-12-17T08:27:14
208,592,016
0
0
null
2022-12-16T06:47:16
2019-09-15T12:38:14
Java
UTF-8
Java
false
false
570
java
package com.edu.victor.Dao; import com.edu.victor.domain.Page; import com.edu.victor.domain.Student; import com.edu.victor.domain.StudentDto; import java.util.List; public interface StuManagementDao { Boolean addStu(String username); Boolean updateStu(Student student); Boolean deleteStudent(Integer id); Boolean deleteStudentMessage(Integer id); Page<StudentDto> searchStuByPage(Page<Student> page); Boolean batchImport(Student student); List<String> getSubmittedHomeworkUrlByStu(Integer id); String getAvatarUrlByStu(Integer id); }
[ "943382615@qq.com" ]
943382615@qq.com
11fbf6fe3378a47672437be7aee54be455b38888
4b5dabe62a869f8a74da38504f3e8c06dcef12e8
/src/com/saas/common/Query.java
92cb9e7b02c92427c22990e5a469ea913aeef9a2
[]
no_license
jasonqiu95/lili_grad_design
9afa6c10912d48649cc0f3df572fc6d04f1fa86c
8eac237d418c5301ca1cbc2e843f49ec93f6518d
refs/heads/master
2021-01-20T05:14:22.559384
2017-05-16T07:39:39
2017-05-16T07:39:39
89,765,388
0
0
null
null
null
null
UTF-8
Java
false
false
1,430
java
package com.saas.common; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Query { private Map<String,String> queryCondition; private int PageIndex; private int TotalPage; private long RecordCount; private List ResultList; public Map<String, String> getQueryCondition() { return queryCondition; } public void setQueryCondition(Map<String, String> queryCondition) { this.queryCondition = queryCondition; } public int getPageIndex() { return PageIndex; } public void setPageIndex(int pageIndex) { PageIndex = pageIndex; } public int getTotalPage() { return TotalPage; } public void setTotalPage(int totalPage) { TotalPage = totalPage; } public long getRecordCount() { return RecordCount; } public void setRecordCount(long recordCount) { RecordCount = recordCount; } public List getResultList() { return ResultList; } public void setResultList(List resultList) { ResultList = resultList; } public String getQueryStr() { StringBuffer queryStr = new StringBuffer(); for(Entry<String, String> entry: queryCondition.entrySet()) { if(!entry.getValue().equals("")) queryStr.append("&").append(entry.getKey()+"="+entry.getValue()); } if(queryStr.length()>0) queryStr.deleteCharAt(0); return queryStr.toString(); } }
[ "jasonqiu@Jasons-MacBook-Pro.local" ]
jasonqiu@Jasons-MacBook-Pro.local
29bc8c8da1f9a955e2504e92a9ea07642afe6f06
0d0d2eb6da1b7f9416f5baac5041e84e3f9e66a6
/drools-model/drools-canonical-model/src/main/java/org/drools/model/functions/Predicate3.java
396f8f0de956389c1140dfc03ed262ce827f1adb
[ "Apache-2.0" ]
permissive
denis554/drools
33dcddc6d5c61fdd405c8be2dbbfbe4ea3e189be
90479684574a001c5a5cf60ad30f02d11f6c0e98
refs/heads/master
2020-04-25T01:10:34.137932
2019-02-22T16:45:54
2019-02-22T16:45:54
172,400,914
1
0
Apache-2.0
2019-02-24T23:01:55
2019-02-24T23:01:54
null
UTF-8
Java
false
false
661
java
package org.drools.model.functions; import java.io.Serializable; public interface Predicate3<A, B, C> extends Serializable { boolean test(A a, B b, C c) throws Exception; class Impl<A, B, C> extends IntrospectableLambda implements Predicate3<A, B, C> { private final Predicate3<A, B, C> predicate; public Impl(Predicate3<A, B, C> predicate) { this.predicate = predicate; } @Override public boolean test(A a, B b, C c) throws Exception { return predicate.test(a, b, c); } @Override public Object getLambda() { return predicate; } } }
[ "mario.fusco@gmail.com" ]
mario.fusco@gmail.com
ec5b09557ed676becbb2dea8018b6f883cfca716
0e7f18f5c03553dac7edfb02945e4083a90cd854
/src/main/resources/jooqgen/.../src/main/java/com/br/sp/posgresdocker/model/jooq/pg_catalog/tables/PgReplicationOriginStatus.java
15a7c78625bed8a3276020f12e033071968a7398
[]
no_license
brunomathidios/PostgresqlWithDocker
13604ecb5506b947a994cbb376407ab67ba7985f
6b421c5f487f381eb79007fa8ec53da32977bed1
refs/heads/master
2020-03-22T00:54:07.750044
2018-07-02T22:20:17
2018-07-02T22:20:17
139,271,591
0
0
null
null
null
null
UTF-8
Java
false
true
4,850
java
/* * This file is generated by jOOQ. */ package com.br.sp.posgresdocker.model.jooq.pg_catalog.tables; import com.br.sp.posgresdocker.model.jooq.pg_catalog.PgCatalog; import com.br.sp.posgresdocker.model.jooq.pg_catalog.tables.records.PgReplicationOriginStatusRecord; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Name; import org.jooq.Record; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.11.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class PgReplicationOriginStatus extends TableImpl<PgReplicationOriginStatusRecord> { private static final long serialVersionUID = -845492361; /** * The reference instance of <code>pg_catalog.pg_replication_origin_status</code> */ public static final PgReplicationOriginStatus PG_REPLICATION_ORIGIN_STATUS = new PgReplicationOriginStatus(); /** * The class holding records for this type */ @Override public Class<PgReplicationOriginStatusRecord> getRecordType() { return PgReplicationOriginStatusRecord.class; } /** * The column <code>pg_catalog.pg_replication_origin_status.local_id</code>. */ public final TableField<PgReplicationOriginStatusRecord, Long> LOCAL_ID = createField("local_id", org.jooq.impl.SQLDataType.BIGINT, this, ""); /** * The column <code>pg_catalog.pg_replication_origin_status.external_id</code>. */ public final TableField<PgReplicationOriginStatusRecord, String> EXTERNAL_ID = createField("external_id", org.jooq.impl.SQLDataType.CLOB, this, ""); /** * @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration. */ @java.lang.Deprecated public final TableField<PgReplicationOriginStatusRecord, Object> REMOTE_LSN = createField("remote_lsn", org.jooq.impl.DefaultDataType.getDefaultDataType("\"pg_catalog\".\"pg_lsn\""), this, ""); /** * @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration. */ @java.lang.Deprecated public final TableField<PgReplicationOriginStatusRecord, Object> LOCAL_LSN = createField("local_lsn", org.jooq.impl.DefaultDataType.getDefaultDataType("\"pg_catalog\".\"pg_lsn\""), this, ""); /** * Create a <code>pg_catalog.pg_replication_origin_status</code> table reference */ public PgReplicationOriginStatus() { this(DSL.name("pg_replication_origin_status"), null); } /** * Create an aliased <code>pg_catalog.pg_replication_origin_status</code> table reference */ public PgReplicationOriginStatus(String alias) { this(DSL.name(alias), PG_REPLICATION_ORIGIN_STATUS); } /** * Create an aliased <code>pg_catalog.pg_replication_origin_status</code> table reference */ public PgReplicationOriginStatus(Name alias) { this(alias, PG_REPLICATION_ORIGIN_STATUS); } private PgReplicationOriginStatus(Name alias, Table<PgReplicationOriginStatusRecord> aliased) { this(alias, aliased, null); } private PgReplicationOriginStatus(Name alias, Table<PgReplicationOriginStatusRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment("")); } public <O extends Record> PgReplicationOriginStatus(Table<O> child, ForeignKey<O, PgReplicationOriginStatusRecord> key) { super(child, key, PG_REPLICATION_ORIGIN_STATUS); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return PgCatalog.PG_CATALOG; } /** * {@inheritDoc} */ @Override public PgReplicationOriginStatus as(String alias) { return new PgReplicationOriginStatus(DSL.name(alias), this); } /** * {@inheritDoc} */ @Override public PgReplicationOriginStatus as(Name alias) { return new PgReplicationOriginStatus(alias, this); } /** * Rename this table */ @Override public PgReplicationOriginStatus rename(String name) { return new PgReplicationOriginStatus(DSL.name(name), null); } /** * Rename this table */ @Override public PgReplicationOriginStatus rename(Name name) { return new PgReplicationOriginStatus(name, null); } }
[ "brunomathidios@yahoo.com.br" ]
brunomathidios@yahoo.com.br
e498f71cc378a2ea87cfeb9422917ec18551c874
92f88a3fb2e619b1085c8bf5fc986a9d120ab918
/src/main/java/com/fangrui/service/impl/SpiderServiceImpl.java
46b2a192e726a0f22274cd9cd00648e55e377472
[]
no_license
stevenjeff/topfive
17d587be23186687e3bc7418813641a719c48421
594a147e211a3753c1b073868b7190b23dcc88a9
refs/heads/master
2021-05-13T12:49:50.440982
2018-05-26T13:33:58
2018-05-26T13:33:58
116,686,336
0
0
null
null
null
null
UTF-8
Java
false
false
681
java
package com.fangrui.service.impl; import com.fangrui.process.GameAli213Forum; import com.fangrui.process.RarbtProcessor; import com.fangrui.process.ThreedmgameDay0; import com.fangrui.service.SpiderService; import org.springframework.stereotype.Service; /** * @author zhangfangrui * @description * @date 2018/5/3 */ @Service public class SpiderServiceImpl implements SpiderService { @Override public void getAli213Data() { new GameAli213Forum().runSpider(); } @Override public void get3dmData() { new ThreedmgameDay0().runSpider(); } @Override public void getRarbtData() { new RarbtProcessor().runSpider(); } }
[ "stevenjefff@126.com" ]
stevenjefff@126.com
12593ea6ed626372f849c258e60dcf0c00974685
6c17a35ba67d61f6d9aff1d6c3c6e957c9ab4cd4
/projects/batfish/src/main/java/org/batfish/grammar/routing_table/nxos/NxosRoutingTableCombinedParser.java
c0b56640fade59c182e80453e9e7aa8c2004a1a9
[ "Apache-2.0" ]
permissive
batfish/batfish
5e8bef0c6977cd7062f2ad03611f496b38d019a1
bfd39eb34e3a7b677bb186b6fc647aac5cb7558f
refs/heads/master
2023-09-01T08:13:38.211980
2023-08-30T21:42:47
2023-08-30T21:42:47
27,507,850
981
249
Apache-2.0
2023-09-12T09:53:49
2014-12-03T21:10:18
Java
UTF-8
Java
false
false
1,171
java
package org.batfish.grammar.routing_table.nxos; import org.batfish.grammar.BatfishANTLRErrorStrategy; import org.batfish.grammar.BatfishANTLRErrorStrategy.BatfishANTLRErrorStrategyFactory; import org.batfish.grammar.BatfishCombinedParser; import org.batfish.grammar.BatfishLexerRecoveryStrategy; import org.batfish.grammar.GrammarSettings; import org.batfish.grammar.routing_table.nxos.NxosRoutingTableParser.Nxos_routing_tableContext; public class NxosRoutingTableCombinedParser extends BatfishCombinedParser<NxosRoutingTableParser, NxosRoutingTableLexer> { private static final BatfishANTLRErrorStrategyFactory NEWLINE_BASED_RECOVERY = new BatfishANTLRErrorStrategy.BatfishANTLRErrorStrategyFactory( NxosRoutingTableLexer.NEWLINE, "\n"); public NxosRoutingTableCombinedParser(String input, GrammarSettings settings) { super( NxosRoutingTableParser.class, NxosRoutingTableLexer.class, input, settings, NEWLINE_BASED_RECOVERY, BatfishLexerRecoveryStrategy.WHITESPACE_AND_NEWLINES); } @Override public Nxos_routing_tableContext parse() { return _parser.nxos_routing_table(); } }
[ "ari@fogelti.me" ]
ari@fogelti.me
9f9a0a01653b3f055866e6c4bfad0a2214bb09b4
4f8c934f03391b8df49c3e7cc36a7b1bc3f11282
/hw2-dklaper/src/main/java/customtypes/GeneMention_Type.java
0aad400c7519ef22c0a41d798d9e1c2a67d773a4
[]
no_license
DKlaper/HW2-dklaper
dbea564e1bb445bfab919c9c234731317c8106db
eafa2525fc9b3e2ced7ae293f9cdefa53d30231b
refs/heads/master
2020-05-18T17:00:11.329156
2014-10-12T21:04:06
2014-10-12T21:04:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,095
java
/* First created by JCasGen Wed Oct 01 19:07:51 EDT 2014 */ package customtypes; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import edu.cmu.deiis.types.Annotation_Type; /** A gene mention including text * Updated by JCasGen Mon Oct 06 19:32:21 EDT 2014 * @generated */ public class GeneMention_Type extends Annotation_Type { /** @generated * @return the generator for this type */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (GeneMention_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = GeneMention_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new GeneMention(addr, GeneMention_Type.this); GeneMention_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new GeneMention(addr, GeneMention_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = GeneMention.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("customtypes.GeneMention"); /** @generated */ final Feature casFeat_mentionText; /** @generated */ final int casFeatCode_mentionText; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getMentionText(int addr) { if (featOkTst && casFeat_mentionText == null) jcas.throwFeatMissing("mentionText", "customtypes.GeneMention"); return ll_cas.ll_getStringValue(addr, casFeatCode_mentionText); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setMentionText(int addr, String v) { if (featOkTst && casFeat_mentionText == null) jcas.throwFeatMissing("mentionText", "customtypes.GeneMention"); ll_cas.ll_setStringValue(addr, casFeatCode_mentionText, v);} /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public GeneMention_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_mentionText = jcas.getRequiredFeatureDE(casType, "mentionText", "uima.cas.String", featOkTst); casFeatCode_mentionText = (null == casFeat_mentionText) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_mentionText).getCode(); } }
[ "dklaper@andrew.cmu.edu" ]
dklaper@andrew.cmu.edu
7ec344f02f5b65d3cc6a1263668e0dd3f2d9362c
03f874dc30042e8d579357ae797b510594645dab
/作业管理系统/src/com/hm_ms/factory/Factory.java
d1579a8fad4900c4c45e1e68f7dc5db6c11bc99a
[]
no_license
983100833/homework
7bd213913ea3bb1b1ef04384b928f63578f3d044
b8009224cc7757cb99a3a4f9f5b9a2f42fd27b62
refs/heads/master
2020-06-06T09:47:27.523946
2019-07-05T09:30:07
2019-07-05T09:30:07
192,705,304
0
0
null
null
null
null
GB18030
Java
false
false
814
java
package com.hm_ms.factory; import java.sql.SQLException; import com.hm_ms.dao.*; import com.hm_ms.datasource.DataSource; import com.hm_ms.proxy.*; /** * 工厂类 获取代理者 * @author Hym * */ public class Factory { public static AccountDao getUserDAOInstance() throws SQLException{ return new AccountProxy() ; } public static TeacherDao getTeacherDAOInstance(){ return new TeacherProxy() ; } public static StudentDao getStudentDAOInstance() throws SQLException{ return new StudentProxy() ; } public static AdminDao getAdminDAOInstance() throws SQLException{ return new AdminProxy() ; } // public static AdminDao getGradeDAOInstance() throws SQLException{ // return new AdminProxy() ; // } public static DataSource getDataSuorce() throws SQLException { return new DataSource(); } }
[ "983100833@qq.com" ]
983100833@qq.com
9cfd909a76c240aefef1e2108d5ab6c27837694d
74f341a20a3ef383659095d278c216dae58ddb6d
/src/test/java/com/apartmentReservation/controller/BackgroundVerificationAndLeaseUserTest.java
5a4c075be902454c46c2476035f0acad5552e98e
[]
no_license
DevanTarunKumar/Apartment-Reservation-System
24b81370e550a1d7080db41d2a576ffc894b358a
cd9dae5b3123f4bf194f0156b7d2d6e581db3152
refs/heads/master
2020-04-25T01:07:10.442603
2019-02-25T15:12:49
2019-02-25T15:12:49
172,399,015
0
0
null
null
null
null
UTF-8
Java
false
false
7,460
java
//Description: This class is used to test various methods under background verification user controller. package com.apartmentReservation.controller; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import java.io.IOException; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.ModelAndView; import com.apartmentReservation.model.Backgroundverification; import com.apartmentReservation.model.Properties; import com.apartmentReservation.model.Role; import com.apartmentReservation.model.User; import com.apartmentReservation.service.BackgroundVerificationAndLeaseAdminService; import com.apartmentReservation.service.BackgroundVerificationAndLeaseUserService; import com.apartmentReservation.service.PropertyService; import com.apartmentReservation.service.UserService; import com.itextpdf.text.DocumentException; @Transactional @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class BackgroundVerificationAndLeaseUserTest { @Mock private UserService userservice; @Mock private BindingResult bindingResult; @Mock private User user; @Autowired private BackgroundVerificationAndLeaseUser BackgroundVerificationUserController; @Mock private BackgroundVerificationAndLeaseUserService backgroundVerificationAndLeaseUserService; @Mock private MockHttpServletRequest request; @Mock private HttpSession session; @Mock private PropertyService propertyService; @Mock private BackgroundVerificationAndLeaseAdminService backgroundVerificationAndLeaseAdminService; Authentication auth = Mockito.mock(Authentication.class); SecurityContext securityContext = Mockito.mock(SecurityContext.class); @Before public void setupTest() { MockitoAnnotations.initMocks(this); } User newUser = User.builder().email("shaline@gmail.com").firstName("shaline").lastName("kocherla") .password("shaline").phoneNumber("646-240-7834").addressLine1("2001 west hickory street") .addressLine2("park place apartments").city("texas").state("Texas").zip("76201").build(); Backgroundverification backgroundverification = Backgroundverification.builder().email("tarundevan@gmail.com") .ownerSign("owner").propertyId(22).build(); Backgroundverification backgroundverification2 = Backgroundverification.builder().email("shaline@gmail.com") .firstname(null).phonenumber(null).address(null).lastname(null).ownerSign("owner").firstname_rm1("tarun") .lastname_rm1("devan").propertyOwner(0).emailid_rm1("tarundevan@gmail.com").propertyId(22).build(); Properties properties = Properties.builder().propertyId(22).propertyRent(1425) .propertyAddress("Trust Drive, Denton").propertyDeposit(400).propertyOwner(1).build(); Properties properties2 = Properties.builder().propertyId(14).propertyOwner(1).build(); /* * Description: This method tests whether a customer is able to see the signlease page. * Input: HttpSession * Output: Intended pages viewed by customer */ @Test public void testSignTheLease() { when(request.getSession()).thenReturn(session); when(session.getAttribute("userName")).thenReturn("Tarun Devan"); when(session.getAttribute("userRole")).thenReturn("CUSTOMER"); ModelAndView model = BackgroundVerificationUserController.signthelease(request); String viewName = model.getViewName(); assertEquals("user/sign_the_lease", model.getViewName()); } /* * Description: This method tests that if a customer signed the lease and the * pdf is generated successfully * Input: The sign of customer and the HttpSession * Output: The intended page viewed by customer */ @Test public void testCustomersignedthelease() throws Exception, Exception { String sign = "Virat"; when(request.getSession()).thenReturn(session); when(session.getAttribute("userEmail")).thenReturn("tarundevan@gmail.com"); // when(userservice.findUserByEmail(("tarundevan@gmail.com)").thenReturn() when(backgroundVerificationAndLeaseUserService.findUserByEmail("tarundevan@gmail.com")) .thenReturn(backgroundverification); when(backgroundVerificationAndLeaseAdminService.findByEmail("tarundevan@gmail.com")) .thenReturn(backgroundverification); when(propertyService.findProperty(backgroundverification.getPropertyId())).thenReturn(properties); String view = BackgroundVerificationUserController.signthelease(sign, request); assertEquals("redirect:/home", view); } /* * Description: This method tests to display the backgroundverification Form * input: property id and HttpSession * output: intended page viewed by customer */ @Test public void testDisplaybackgroundverificationForm() throws Exception, Exception { int pid = 14; when(request.getSession()).thenReturn(session); when(session.getAttribute("userEmail")).thenReturn("virat@gmail.com"); when(session.getAttribute("userName")).thenReturn("Virat Kohli"); when(session.getAttribute("userRole")).thenReturn("CUSTOMER"); ModelAndView model = BackgroundVerificationUserController.backgv(pid, request); assertTrue(model.getModel().containsKey("backgv")); assertEquals("user/submit_background_verification_application", model.getViewName()); } /* * Description: Test that user details are getting stored after submitting the background verification form * input: backgroundverification details of customer, mocked binding results, property Id and the HttpSession * output: the intended page that is shown to the customer */ @Test public void testforBackgroundverificationsubmitPostmethod() throws Exception, Exception { int pid = 14; when(request.getSession()).thenReturn(session); when(bindingResult.hasErrors()).thenReturn(false); when(session.getAttribute("userEmail")).thenReturn("virat@gmail.com"); when(propertyService.findProperty(pid)).thenReturn(properties); when(backgroundVerificationAndLeaseUserService.findUserByEmail("virat@gmail.com")) .thenReturn(backgroundverification2); when(backgroundVerificationAndLeaseUserService.saveUser(backgroundverification2)) .thenReturn(backgroundverification2); String view2 = BackgroundVerificationUserController.backgroundverification(backgroundverification2, bindingResult, pid, request); assertEquals("redirect:/home", view2); } }
[ "tarunkumardevan@my.unt.edu" ]
tarunkumardevan@my.unt.edu
bbfc1aaf15977639fadb50c15204c6d26342466c
22cbc240389a97d39804811c03f4f282f2cc8b70
/NetworkAnalysis/src/com/cougaarsoftware/nettool/CougaarRenderer.java
1238ae57cbb0d6bc78c879da1b694dea760d1750
[]
no_license
codeaudit/cougaar-securitycore
d49c6b94be2ee8cab77c50d9287098b4a9293851
05d1fafeb5e1c34a912efc8ae10d1f804f96a3c3
refs/heads/master
2021-01-11T21:20:13.172583
2012-06-05T23:18:51
2012-06-05T23:18:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,491
java
/* * Created on Feb 26, 2004 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.cougaarsoftware.nettool; import java.awt.Graphics; import java.awt.Color; import java.util.Iterator; import java.util.Set; import edu.uci.ics.jung.graph.Edge; import edu.uci.ics.jung.graph.Vertex; import edu.uci.ics.jung.graph.decorators.StringLabeller; import edu.uci.ics.jung.visualization.graphdraw.EdgeColorFunction; import edu.uci.ics.jung.visualization.graphdraw.SettableRenderer; import edu.uci.ics.jung.visualization.graphdraw.VertexColorFunction; /** * @author srosset * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class CougaarRenderer extends SettableRenderer { private boolean m_highlightType; private MessageTypeColorFunction m_edgeColorFunction; private NodeColorFunction m_nodeColorFunction; /** * @param arg0 */ public CougaarRenderer(StringLabeller arg0) { super(arg0); m_edgeColorFunction = new MessageTypeColorFunction(); m_nodeColorFunction = new NodeColorFunction(); } /** * @see edu.uci.ics.jung.visualization.Renderer#paintVertex(java.awt.Graphics, edu.uci.ics.jung.graph.Vertex, int, int) */ public void paintVertex(Graphics g, Vertex v, int x, int y) { //g.setColor( Color.BLUE ); g.setColor(m_nodeColorFunction.getVertexColor(v)); g.fillOval(x-3, y-3, 6, 6); } /** * @see edu.uci.ics.jung.visualization.Renderer#paintEdge(java.awt.Graphics, edu.uci.ics.jung.graph.Edge, int, int, int, int) */ public void paintEdge(Graphics g, Edge e, int x1, int y1, int x2, int y2) { //g.setColor( Color.GRAY ); g.setColor(m_edgeColorFunction.getEdgeColor(e)); g.drawLine(x1, y1, x2, y2); } public void highlightMessageTypes(Set messageType) { m_edgeColorFunction.setHighlightedType(messageType); } public void highlightNodes(Set nodeNames) { m_nodeColorFunction.setHighlightedNode(nodeNames); } private class MessageTypeColorFunction { private Set m_highlightedMessageTypes; /* (non-Javadoc) * @see edu.uci.ics.jung.visualization.graphdraw.EdgeColorFunction#getEdgeColor(edu.uci.ics.jung.graph.Edge) */ public Color getEdgeColor(Edge edge) { if (m_highlightedMessageTypes != null) { Set types = (Set) edge.getUserDatum(SocietyModel.KEY_MSG_TYPE); Iterator it = types.iterator(); while (it.hasNext()) { if (m_highlightedMessageTypes.contains(it.next())) { return Color.GREEN; } } return Color.GRAY; } else { return Color.GRAY; } } /** * @param messageType */ public void setHighlightedType(Set messageTypes) { m_highlightedMessageTypes = messageTypes; } } private class NodeColorFunction { private Set m_highlightedNodeNames; /** * @param nodeNames */ public void setHighlightedNode(Set nodeNames) { m_highlightedNodeNames = nodeNames; } /* (non-Javadoc) * @see edu.uci.ics.jung.visualization.graphdraw.VertexColorFunction#getForeColor(edu.uci.ics.jung.graph.Vertex) */ public Color getVertexColor(Vertex vertex) { if (m_highlightedNodeNames != null) { String node = (String) vertex.getUserDatum(SocietyModel.KEY_AGENT_NAME); if (m_highlightedNodeNames.contains(node)) { return Color.YELLOW; } return Color.BLUE; } else { return Color.BLUE; } } } }
[ "srosset" ]
srosset
f4861e5e82bdc84d51b3d084f6f18007948c6157
c1a9357cf34cb93fe1828a43d6782bcefa211804
/source_code/netweaver/src/main/java/com/sap/netweaver/porta/core/ServerFactory.java
80d2ada69b8ba314fd3822c4ae16c9c3b92373b9
[]
no_license
Hessah/Quality-Metrics-of-Test-suites-for-TDD-Applications
d5bd48b1c1965229f8249dcfc53a10869bb9bbb0
d7abc677685ab0bc11ae9bc41dd2554bceaf18a8
refs/heads/master
2020-05-29T22:38:33.553795
2014-12-22T23:55:02
2014-12-22T23:55:02
24,071,022
2
0
null
null
null
null
UTF-8
Java
false
false
5,693
java
/******************************************************************************* * Copyright (c) 2009, 2010 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Kaloyan Raev (SAP AG) - initial API and implementation *******************************************************************************/ package com.sap.netweaver.porta.core; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * The <code>ServerFactory</code> is used to create instances of the * <code>Server</code> interface that represent physical SAP NetWeaver Application * Server systems. * * <p> * The factory requires a set of <code>Properties</code> to create a * <code>Server</code> instance. These properties determine the correct * implementation object that will be created. The <code>Server</code> * interface hides the specifics of the implementation and provides only an * abstract interface to operate with the physical system. * </p> * * <p> * Another goal of the <code>ServerFactory</code> is to optimize the creation * of <code>Server</code> instances. The factory remembers all created * <code>Server</code> instances with their corresponding properties. If, on a * further call to create a <code>Server</code> instance, the same properties * are given, then the factory returns the <code>Server</code> instance that * has already been created. This way duplicate instances to one and the same * physical system are avoided. Users of the factory do not need to persist * the <code>Server</code> instances created from the factory, because they * can be obtained again from the factory using the same set of properties. * </p> * * @see Server */ public class ServerFactory { /** * Constant for the <b>server.type</b> property used for creating a * </code>Server</code> instance. * * <p> * The <b>server.type</b> property specifies the version of the SAP * NetWeaver Application Server system. * </p> */ public static final String SERVER_TYPE = "server.type"; /* * A map where discovered server types and their factory classes are * registered. */ private final static Map<String, String> map = new HashMap<String, String>(); /* * Browse through the JARs in the classpath to discover server types. */ static { try { // Retrieve a list of all porta.properties files in the default // package of the JARs in the classpath Enumeration<URL> resources = ServerFactory.class.getClassLoader().getResources("porta.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); // load the porta.properties file Properties props = new Properties(); props.load(url.openStream()); // retrieve the server.type property String type = props.getProperty(SERVER_TYPE); // retrieve the server.factory property String factory = props.getProperty("server.factory"); // register the discovered server type in the map if (type != null && factory != null) { map.put(type, factory); } } } catch (IOException e) { e.printStackTrace(); } } /** * Creates an instance of the <code>Server</code> interface that represents * a physical SAP NetWeaver Application Server system. * * <p> * It is mandatory to specify the <code>ServerType</code> property. It * determines the type of the implementation type that will be created for * the <code>Server</code> interface. The valid property value for a * specific implementation type could be obtained from the * </code>porta.properties</code> file in the implementation JAR. * </p> * * </p> Other required properties are specific to the selected server type. * Consult the java doc of the server factory class in the implementation * JAR. </p> * * @param props * - a set of properties that determines the implementation * object that will be returned as instance of the * <code>Server</code> interface * * @return instance of the <code>Server</code> interface. * * @throws IllegalArgumentException * - if a required property is missing, or a property value is * invalid or not supported * @throws CoreException * - if a problem happens while creating the <code>Server</code> * instance * * @see #SERVER_TYPE */ public static Server createServer(Properties properties) throws CoreException { if (properties == null) { throw new NullPointerException("properties cannot be null"); } String type = properties.getProperty(SERVER_TYPE); if (type == null) { throw new IllegalArgumentException(String.format("%s property missing", SERVER_TYPE)); } String factory = map.get(type); if (factory == null) { throw new IllegalArgumentException(String.format("%s is not supported server type. Supported types are: %s. ", type, map.keySet())); } try { Class<?> factoryClass = Class.forName(factory); Method method = factoryClass.getMethod("createServer", new Class[] { Properties.class }); return (Server) method.invoke(null, properties); } catch (Exception e) { throw new CoreException(e); } } }
[ "hesaah@gmail.com" ]
hesaah@gmail.com
d8b04b142553d16560dea60d6437cf00aa462ba5
9b12013fae8f8bf4e4de7891d5c3ac0d40e91531
/src/main/java/com/mtihc/minecraft/hungergame/game/Game.java
862efac013923ee02b830990f97d606429f31840
[]
no_license
Mtihc/HungerGame
14d21c6feff68bec0af9659705869df94165620c
d5d0379ffd79c690434d43fb1e4144e0fb38ac12
refs/heads/master
2021-01-15T22:34:04.612881
2012-05-13T21:39:07
2012-05-13T21:39:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
27,163
java
package com.mtihc.minecraft.hungergame.game; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.DoubleChest; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import com.mtihc.minecraft.hungergame.game.exceptions.GameException; import com.mtihc.minecraft.hungergame.game.exceptions.GameJoinDisabledException; import com.mtihc.minecraft.hungergame.game.exceptions.GameJoinedException; import com.mtihc.minecraft.hungergame.game.exceptions.GameRunningException; import com.mtihc.minecraft.hungergame.player.PlayerState; import com.mtihc.minecraft.hungergame.player.fields.DefaultPlayerField; import com.mtihc.minecraft.hungergame.tasks.CountdownCallback; import com.mtihc.minecraft.hungergame.tasks.CountdownTask; import com.mtihc.minecraft.hungergame.tasks.RestoreRegionCallback; import com.mtihc.minecraft.hungergame.tasks.RestoreRegionTask; import com.mtihc.minecraft.hungergame.tasks.RestoreSchematicCallback; import com.mtihc.minecraft.hungergame.tasks.RestoreSchematicTask; import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldedit.data.ChunkStore; import com.sk89q.worldedit.data.DataException; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.snapshots.Snapshot; import com.sk89q.worldguard.protection.flags.DefaultFlag; import com.sk89q.worldguard.protection.flags.StateFlag.State; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; public class Game implements CountdownCallback, RestoreRegionCallback, RestoreSchematicCallback { public enum LeaveReason { KICK, QUIT, DEATH, GAME_STOP, WIN, LEAVE; } private final GameControl control; private final GameInfo info; private final LocalWorld localWorld; private final ProtectedRegion region; private boolean running; private final File directory; private boolean joiningEnabled; private boolean invulnerabilityEnabled; private final Map<String, GamePlayer> players; private final Map<String, GamePlayer> playersDead; private final Map<String, ReconnectTimer> playersOffline; private GameFeast feast; private RestoreRegionTask taskRestore; private RestoreSchematicTask taskRestoreSchematics; private CountdownTask taskDisableJoin; private FeastTask taskFeast; private CountdownTask taskInvul; public Game(String id, GameControl control) throws GameException { this.control = control; info = control.getGameInfoCollection().getInfo(id); if(info == null) { throw new GameException("The game yml file does not exist."); } directory = info.getDirectory(); if(!directory.exists()) { throw new GameException("The game folder does not exist: " + directory.getPath()); } World world = info.getLocation().getWorld(); // find local world Iterator<LocalWorld> worlds = control.getWorldEdit().getWorldEdit().getServer().getWorlds().iterator(); LocalWorld w = null; while(worlds.hasNext()) { LocalWorld next = worlds.next(); if(next.getName().equals(world.getName())) { w = next; break; } } if(w == null) { throw new GameException("World \"" + world.getName() + "\" not found at WorldEdit."); } else { this.localWorld = w; } RegionManager mgr = control.getWorldGuard().getRegionManager(world); this.region = mgr.getRegion(info.getRegion()); if (region == null) { throw new GameException("Region \"" + info.getRegion() + "\" doesn't exist in world \"" + world.getName() + "\"."); } // players can't enter or leave the area region.setFlag(DefaultFlag.ENTRY, State.DENY); region.setFlag(DefaultFlag.EXIT, State.DENY); this.joiningEnabled = false; this.invulnerabilityEnabled = false; this.players = new HashMap<String, GamePlayer>(); this.playersDead = new LinkedHashMap<String, GamePlayer>(); this.playersOffline = new HashMap<String, ReconnectTimer>(); this.control.setGame(info.getId(), this); } /** * Creates a player state object that specified which player informations is * to be saved. * * @param player * The player to save the state of * @return The player state object */ protected PlayerState createPlayerState(Player player) { return PlayerState.fromPlayer(player, DefaultPlayerField.values()); } /** * Whether the game is currently running * * @return true if the game is running, false otherwise */ public boolean isRunning() { return running; } /** * The game id * * @return Game id */ public String getId() { return info.getId(); } /** * Single instance that serves as observer for this game. But is also * observed by the game for bukkit events. * * @return Game game control */ public GameControl getControl() { return control; } /** * The game info * * @return Game info */ public GameInfo getInfo() { return info; } /** * The game's spawn locations. If there are no spawn locations, a list * containing the main location is returned. * * @return List containing spawn locations */ public List<Location> getSpawnLocations() { List<Location> result = info.getSpawnLocations(); if (result == null || result.isEmpty()) { result = new ArrayList<Location>(); result.add(info.getLocation()); return result; } else { return result; } } // ----------------------------- // // Observers // // ----------------------------- // public boolean hasObserver(Observer observer) { // return observers.contains(observer); // } // // public boolean addObserver(Observer observer) { // return observers.add(observer); // } // // public boolean removeObserver(Observer observer) { // return observers.remove(observer); // } // // public Iterator<Observer> getObservers() { // return observers.iterator(); // } // ----------------------------- // // Region / Snapshot // // ----------------------------- public boolean containsLocation(Location location) { return location.getWorld().getName().equalsIgnoreCase(localWorld.getName()) && containsLocation(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } public boolean containsLocation(int x, int y, int z) { return region.contains(x, y, z); } /** * The game region * * @return Game region */ public ProtectedRegion getRegion() { return region; } /** * Whether the region is currently being restored * * @return true if the restore task is running, false otherwise */ public boolean isRegionRestoring() { return taskRestore != null && taskRestore.isRunning(); } protected void scheduleRestoreRegion(Snapshot snapshot, RestoreRegionCallback restoreRegionCallback) throws IOException, GameException { if (taskRestore != null && taskRestore.isRunning()) { throw new GameException("Region is already being restored."); } // get chunk store from snapshot ChunkStore chunkStore; try { chunkStore = snapshot.getChunkStore(); } catch (DataException e) { throw new GameException(e); } // create sub regions of the game region CuboidRegion cr = new CuboidRegion(localWorld, region.getMinimumPoint(), region.getMaximumPoint()); List<CuboidRegion> subRegions = RestoreRegionTask.getSubRegions(cr, info.getRestoreStepSize()); // create and return restore task taskRestore = new RestoreRegionTask(control.getPlugin(), chunkStore, subRegions, info.getRestoreStepTime(), restoreRegionCallback); taskRestore.schedule(); } // ----------------------------- // // Invulnerability // // ----------------------------- public boolean isInvulnerabilityEnabled() { return invulnerabilityEnabled; } public void setInvulnerabilityEnabled(boolean value) { invulnerabilityEnabled = value; } protected void scheduleInvulnerabilityDisable() { taskInvul = new CountdownTask(control.getPlugin(), info.getInvulnerabilitySeconds(), this); taskInvul.schedule(); } // ----------------------------- // // Joining // // ----------------------------- public boolean isJoiningEnabled() { return joiningEnabled; } protected void setJoiningEnabled(boolean value) { joiningEnabled = value; } protected void scheduleJoinDisable(int disableAfterSeconds) { taskDisableJoin = new CountdownTask(control.getPlugin(), disableAfterSeconds, this); taskDisableJoin.schedule(); } // ----------------------------- // // Feast // // ----------------------------- public GameFeast getFeast() { return feast; } public boolean hasFeast() { return feast != null; } public boolean isFeastScheduled() { return taskFeast != null && taskFeast.isRunning(); } public int getFeastRemainingSeconds() { if(!hasFeast()) { return 0; } else { if(isFeastScheduled()) { return taskFeast.getSecondsRemaining(); } else { return 0; } } } protected void setFeast(GameFeast value) { if (this.feast != value) { clearFeast(); this.feast = value; } } private void clearFeast() { Iterator<GamePlayer> values = players.values().iterator(); while (values.hasNext()) { GamePlayer p = values.next(); p.setFeastInventory(null); } this.feast = null; } protected void scheduleFeast(GameFeast feast) throws GameException { if (isFeastScheduled()) { throw new GameException("Feast is already scheduled."); } taskFeast = new FeastTask(feast); taskFeast.schedule(); } private class FeastTask extends CountdownTask { private GameFeast feast; private FeastTask(GameFeast feast) { super(control.getPlugin(), info.getFeastDelaySeconds(), Game.this); this.feast = feast; } } // ----------------------------- // on Feast click // ----------------------------- protected Inventory createFeastInventory(GameFeast feast) { Inventory result = control.getPlugin().getServer() .createInventory(feast.getHolder(), feast.getSize(), "Feast"); result.setContents(feast.getContents()); return result; } protected boolean isFeastAt(GameFeast feast, Location location) { InventoryHolder holder = feast.getHolder(); if (holder instanceof DoubleChest) { DoubleChest dchest = (DoubleChest) holder; Location leftLoc = ((Chest) dchest.getLeftSide()).getLocation(); Location rightLoc = ((Chest) dchest.getRightSide()).getLocation(); return locationsAreEqual(leftLoc, location) || locationsAreEqual(rightLoc, location); } else { return locationsAreEqual(feast.getLocation(), location); } } protected boolean locationsAreEqual(Location a, Location b) { return a.getWorld() == b.getWorld() && a.getBlockX() == b.getBlockX() && a.getBlockY() == b.getBlockY() && a.getBlockZ() == b.getBlockZ(); } // ----------------------------- // // Players / Dead Players // // ----------------------------- public int getTotalPlayers() { return players.size() + playersDead.size(); } public int getTotalAlivePlayers() { return players.size(); } public int getTotalDeadPlayers() { return playersDead.size(); } public boolean hasPlayer(String name) { return players.containsKey(name); } public boolean hasDeadPlayer(String name) { return playersDead.containsKey(name); } public GamePlayer getPlayer(String name) { return players.get(name); } public GamePlayer getDeadPlayer(String name) { return playersDead.get(name); } public Collection<GamePlayer> getPlayers() { return players.values(); } public Collection<GamePlayer> getDeadPlayers() { return playersDead.values(); } private void safeTeleport(GamePlayer player, Location spawn) { //control.getWorldEdit().wrapPlayer(player.getPlayer()).findFreePosition(new WorldVector(localWorld, spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ())); player.teleportSafe(spawn); } // ----------------------------- // // start / stop // // ----------------------------- private int startAfterSeconds; private boolean started; public void openAfterRestore(int startAfterSeconds, Snapshot snapshot) throws IOException, GameException { if (running) { throw new GameRunningException("Game \"" + getId() + "\" is already running."); } running = true; this.startAfterSeconds = startAfterSeconds; scheduleRestoreRegion(snapshot, this); } public void open(int startAfterSeconds) throws GameRunningException { if (running) { throw new GameRunningException("Game \"" + getId() + "\" is already running."); } running = true; this.startAfterSeconds = startAfterSeconds; doOpen(); } public void start() throws GameRunningException { if (running) { throw new GameRunningException("Game \"" + getId() + "\" is already running."); } running = true; this.startAfterSeconds = 0; doStart(); } private void doOpen() { scheduleJoinDisable(this.startAfterSeconds); } public boolean isStarted() { return started; } private void doStart() { if (getTotalAlivePlayers() == 0) { try { stop(); } catch (GameRunningException e) { } return; } // players that went offline are kicked Iterator<ReconnectTimer> offlines = playersOffline.values().iterator(); while (offlines.hasNext()) { ReconnectTimer timer = offlines.next(); timer.run(); } // joining is disabled if it wasn't already if (taskDisableJoin != null && taskDisableJoin.isRunning()) { taskDisableJoin.cancel(); } setJoiningEnabled(false); // restoring of the region is cancelled if it's still running if (taskRestore != null && taskRestore.isRunning()) { taskRestore.cancel(); } List<Location> locations = getSpawnLocations(); int index = 0; Iterator<GamePlayer> iterator = getPlayers().iterator(); while (iterator.hasNext()) { GamePlayer p = iterator.next(); // player get sperate spawn locations as much as possible (using // modulo operator) Location spawn = locations.get(index % locations.size()); index++; // save the state that the player is currently in // (like health, inventory etc) // so that it can be loaded again, when the player leaves the game p.setOriginalState(createPlayerState(p.getPlayer())); // add players as member to region... // player can't leave region anymore region.getMembers().addPlayer(p.getName()); // teleport the player to his spawn location safeTeleport(p, spawn); // TODO set player's values, possibly // according to player's class/job control.getObserver().onPlayerSpawn(this, p.getPlayer(), spawn); } // set the start feast setFeast(info.getStartFeast()); started = true; // notify observer control.getObserver().onGameStart(this); // schedule the big feast try { scheduleFeast(info.getDelayedFeast()); } catch (GameException e) { control.getPlugin().getLogger().warning(e.getMessage()); } // players are invulnerable for some amount of time scheduleInvulnerabilityDisable(); } public void stop() throws GameRunningException { if (!running) { throw new GameRunningException("Game \"" + getId() + "\" is already running."); } // cancel all running tasks if (taskDisableJoin != null) { taskDisableJoin.cancel(); } if (taskFeast != null) { taskFeast.cancel(); } if (taskInvul != null) { taskInvul.cancel(); } if (taskRestore != null) { taskRestore.cancel(); } // kick offline players Iterator<ReconnectTimer> offlines = playersOffline.values().iterator(); while (offlines.hasNext()) { ReconnectTimer timer = offlines.next(); timer.run(); } // kick alive players (move to dead players) Iterator<GamePlayer> iterator = players.values().iterator(); while (iterator.hasNext()) { GamePlayer p = iterator.next(); try { leavePlayer(p.getName(), LeaveReason.GAME_STOP); } catch (GameJoinedException e) { control.getPlugin().getLogger().warning("Failed to properly kick player " + p.getName() + " from game \"" + getId() + "\"."); } } running = false; // notify observer control.getObserver().onGameStop(this); control.removeGame(getId()); } private void onPlayerRemove(GamePlayer p, LeaveReason leaveReason) { // remove player as member from region... // player can't enter region anymore region.getMembers().removePlayer(p.getName()); PlayerState state = p.getOriginalState(); if(state != null) { PlayerState.toPlayer(state, p.getPlayer()); } control.getObserver().onPlayerLeave(this, p.getPlayer(), leaveReason); } // ----------------------------- // // join / leave // // ----------------------------- /** * * @param player * @throws GameJoinDisabledException * When joining is disabled * @throws GameJoinedException * When already joined */ public void joinPlayer(Player player) throws GameJoinDisabledException, GameJoinedException { if (!joiningEnabled) { throw new GameJoinDisabledException( "Joining is disabled for game \"" + getId() + "\"."); } if (hasPlayer(player.getName())) { throw new GameJoinedException("Already joined to game \"" + getId() + "\"."); } GamePlayer p = new GamePlayer(player); players.put(player.getName(), p); control.getObserver().onPlayerJoin(this, player); } /** * * @param name * @param leaveReason * @throws GameJoinedException * When not joined */ public void leavePlayer(String name, LeaveReason leaveReason) throws GameJoinedException { GamePlayer p = players.remove(name); if (p == null) { throw new GameJoinedException("Not joined to game \"" + getId() + "\"."); } playersDead.put(name, p); onPlayerRemove(p, leaveReason); // check win and stop if(!leaveReason.equals(LeaveReason.GAME_STOP)) { int alive = getTotalAlivePlayers(); if (alive == 1) { Iterator<GamePlayer> ps = players.values().iterator(); GamePlayer winner = ps.next(); leavePlayer(winner.getName(), LeaveReason.WIN); } else if (alive == 0) { try { stop(); } catch (GameRunningException e) { e.printStackTrace(); } } } } // ----------------------------- // // Event handlers // // ----------------------------- protected void onPlayerDeath(PlayerDeathEvent event) { Player p = event.getEntity(); if (hasPlayer(p.getName())) { try { leavePlayer(p.getName(), LeaveReason.DEATH); p.kickPlayer(event.getDeathMessage()); } catch (GameJoinedException e) { } } } protected void onPlayerTeleport(PlayerTeleportEvent event) { if (isStarted() && hasPlayer(event.getPlayer().getName()) && !containsLocation(event.getTo())) { event.setCancelled(true); } } protected void onPlayerJoin(PlayerJoinEvent event) { // if player disconnected a minute ago, add back to game ReconnectTimer task = playersOffline .remove(event.getPlayer().getName()); if (task != null) { task.cancel(); } } protected void onPlayerQuit(PlayerQuitEvent event) { GamePlayer p = players.remove(event.getPlayer().getName()); if (p == null) { return; } ReconnectTimer task = new ReconnectTimer(p); task.schedule(); } protected void onPlayerKick(PlayerKickEvent event) { try { leavePlayer(event.getPlayer().getName(), LeaveReason.KICK); } catch (GameJoinedException e) { } } protected void onPlayerRespawn(PlayerRespawnEvent event) { // not used } protected void onPlayerDamage(EntityDamageByEntityEvent event) { if (invulnerabilityEnabled && event.getEntity() instanceof Player) { Player p = (Player) event.getEntity(); if (players.containsKey(p.getName())) { event.setDamage(0); } } } protected void onPlayerInteract(PlayerInteractEvent event) { if(event.isCancelled() || event.useInteractedBlock().equals(Result.DENY)) { return; } GamePlayer p = getPlayer(event.getPlayer().getName()); if (p == null) { return; } if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && hasFeast() && isFeastAt(getFeast(), event.getClickedBlock().getLocation())) { if (!p.hasFeastInventory()) { p.setFeastInventory(createFeastInventory(getFeast())); } p.getPlayer().openInventory(p.getFeastInventory()); event.setUseInteractedBlock(Result.DENY); event.setCancelled(true); } } public boolean isBlockProtected(Block block) { return hasFeast() && isFeastAt(feast, block.getLocation()); } protected void onBlockBreak(BlockBreakEvent event) { if (isBlockProtected(event.getBlock())) { event.setCancelled(true); } } protected void onBlockIgnite(BlockIgniteEvent event) { if (isBlockProtected(event.getBlock())) { event.setCancelled(true); } } protected void onEntityExplode(EntityExplodeEvent event) { Iterator<Block> values = event.blockList().iterator(); while (values.hasNext()) { Block block = values.next(); if (isBlockProtected(block)) { values.remove(); } } } // ----------------------------- // // Reconnect timer // // ----------------------------- private class ReconnectTimer implements Runnable { private final GamePlayer player; private int taskId; private ReconnectTimer(GamePlayer player) { this.player = player; taskId = -1; } private void cancel() { if (taskId != -1) { control.getPlugin().getServer().getScheduler() .cancelTask(taskId); taskId = -1; if (playersOffline.remove(player.getName()) != null) { players.put(player.getName(), player); } } } private void schedule() { if (taskId == -1) { playersOffline.put(player.getName(), this); taskId = control .getPlugin() .getServer() .getScheduler() .scheduleAsyncDelayedTask(control.getPlugin(), this, info.getReconnectSeconds() * 20L); } } @Override public void run() { cancel(); try { leavePlayer(player.getName(), LeaveReason.QUIT); } catch (GameJoinedException e) { } } } @Override public void onRestoreStart(RestoreRegionTask task) { control.getObserver().onRestoreStart(this); } @Override public void onRestoreCancel(RestoreRegionTask task) { control.getPlugin().getLogger() .warning("Restoring of region \"" + getId() + "\" cancelled."); onRestoreFinish(task); } @Override public void onRestoreFinish(RestoreRegionTask task) { String[] folders = info.getSchematicFolders(); List<String> paths = new ArrayList<String>(); Random r = new Random(); for (int i = 0; i < folders.length; i++) { String[] names = info.getSchematicNames(folders[i]); if(names == null || names.length == 0) { continue; } paths.add(folders[i] + "/" + names[r.nextInt(names.length)]); } if(paths.isEmpty()) { onRestoreFinish(); } else { taskRestoreSchematics = new RestoreSchematicTask(control.getPlugin(), this, info.getSchematicsRoot(), paths.toArray(new String[paths.size()]), localWorld, -1); taskRestoreSchematics.schedule(info.getRestoreStepTime()); } } @Override public void onRestoreSchematicStart(RestoreSchematicTask task) { } @Override public void onRestoreSchematicCancel(RestoreSchematicTask task) { onRestoreSchematicFinish(task); } @Override public void onRestoreSchematicFinish(RestoreSchematicTask task) { onRestoreFinish(); } private void onRestoreFinish() { control.getObserver().onRestoreFinish(this); doOpen(); } private void placeChest(Block block) { if(block.getState() instanceof InventoryHolder) { ((InventoryHolder)block.getState()).getInventory().clear(); } else { block.setType(Material.CHEST); } } @Override public void onCountdownStart(CountdownTask task, int totalSeconds) { if(task == taskDisableJoin) { setJoiningEnabled(true); control.getObserver().onJoinEnable(this); } else if(task == taskFeast) { control.getObserver().onFeastSchedule(this, totalSeconds); } else if(task == taskInvul) { setInvulnerabilityEnabled(true); control.getObserver().onInvulnerabilityStart(this, totalSeconds); } } @Override public void onCountdownWarning(CountdownTask task, int totalSeconds, int remaining) { if(task == taskDisableJoin) { control.getObserver().onJoinDisableWarning(this, totalSeconds, remaining); } else if(task == taskFeast) { control.getObserver().onFeastWarning(this, totalSeconds, remaining); } else if(task == taskInvul) { control.getObserver().onInvulnerabilityWarning(this, totalSeconds, remaining); } } @Override public void onCountdown(CountdownTask task, int totalSeconds, int remaining) { if(task == taskDisableJoin) { control.getObserver().onJoinDisableCountdown(this, totalSeconds, remaining); } else if(task == taskFeast) { control.getObserver().onFeastCountdown(this, totalSeconds, remaining); } else if(task == taskInvul) { control.getObserver() .onInvulnerabilityCountdown(this, totalSeconds, remaining); } } @Override public void onCountdownCancel(CountdownTask task, int totalSeconds, int remaining) { if(task == taskDisableJoin) { setJoiningEnabled(false); control.getObserver().onJoinDisable(this); } else if(task == taskFeast) { } else if(task == taskInvul) { setInvulnerabilityEnabled(false); control.getObserver().onInvulnerabilityStop(this, totalSeconds, remaining); } } @Override public void onCountdownFinish(CountdownTask task, int totalSeconds) { if(task == taskDisableJoin) { setJoiningEnabled(false); doStart(); control.getObserver().onJoinDisable(this); } else if(task == taskFeast) { setFeast(taskFeast.feast); control.getObserver().onFeast(this); InventoryHolder holder = taskFeast.feast.getHolder(); if(holder instanceof DoubleChest) { Block leftBlock = ((BlockState)((DoubleChest)holder).getLeftSide()).getBlock(); Block rightBlock = ((BlockState)((DoubleChest)holder).getRightSide()).getBlock(); placeChest(leftBlock); placeChest(rightBlock); } else { Block block = ((BlockState)holder).getBlock(); placeChest(block); } } else if(task == taskInvul) { setInvulnerabilityEnabled(false); control.getObserver().onInvulnerabilityStop(this, totalSeconds, 0); } } }
[ "mitchstoffels@gmail.com" ]
mitchstoffels@gmail.com
a32d0fee1aed0f907426246d34b1f05d832099ea
206f94d27dd302c0c13d2cb0c8b9093e019501f5
/app/src/androidTest/java/com/example/xandone/textverticaldemo/ApplicationTest.java
0a2ab01aa23fe6135b7cce7476c767d539e4cceb
[]
no_license
xandone/TextVerticalDemo
81ec9e775b3e89dd21e9c14d9491216cf2e97d02
1ad583b01e875498d160d16ee2cfe5e9a12e8f18
refs/heads/master
2020-04-17T11:05:29.452769
2017-04-19T08:31:28
2017-04-19T08:31:28
67,566,549
6
0
null
null
null
null
UTF-8
Java
false
false
367
java
package com.example.xandone.textverticaldemo; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
[ "765478955@qq.com" ]
765478955@qq.com
4e0e1a5a65b1c2e332ade5da3f726aa0c75bc326
12bb4dc0a317cc25a3f41a6a6a11c5108ee8b24e
/src/main/java/com/iitb/lokavidya/core/data/Video.java
bc82157bc79233cf1cd57345a25c10ef955406b8
[]
no_license
nipandha/lokavidya-desktop
c321e68818da8ed4c58bf07f996a8acae893ad74
32025ae271747e46c5c7ddbb3340cb2803d7f41a
refs/heads/master
2020-06-21T16:37:18.194114
2016-03-03T12:44:04
2016-03-03T12:44:04
74,780,226
0
0
null
null
null
null
UTF-8
Java
false
false
2,211
java
package com.iitb.lokavidya.core.data; import java.io.Serializable; import java.util.Objects; import com.iitb.lokavidya.core.utils.GeneralUtils; /** * A Video. */ public class Video implements Serializable { public Video() { this.id= GeneralUtils.generateRandomNumber(11).intValue(); } private String videoURL; private String videoResolution; private Double videoDuration; private Double videoFPS; private Double videoSize; private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getVideoURL() { return videoURL; } public void setVideoURL(String videoURL) { this.videoURL = videoURL; } public String getVideoResolution() { return videoResolution; } public void setVideoResolution(String videoResolution) { this.videoResolution = videoResolution; } public Double getVideoDuration() { return videoDuration; } public void setVideoDuration(Double videoDuration) { this.videoDuration = videoDuration; } public Double getVideoFPS() { return videoFPS; } public void setVideoFPS(Double videoFPS) { this.videoFPS = videoFPS; } public Double getVideoSize() { return videoSize; } public void setVideoSize(Double videoSize) { this.videoSize = videoSize; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Video video = (Video) o; return Objects.equals(id, video.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Video{" + "id=" + id + ", videoURL='" + videoURL + "'" + ", videoResolution='" + videoResolution + "'" + ", videoDuration='" + videoDuration + "'" + ", videoFPS='" + videoFPS + "'" + ", videoSize='" + videoSize + "'" + '}'; } }
[ "sanketlokegaonkar@gmail.com" ]
sanketlokegaonkar@gmail.com
19d359c91f25b39125f6edbfabc4bd6b09678eba
7cee770c9a0b35fb881f2a54cac688de72e8c511
/DOM/src/dombook/suathongtin.java
0bc40f056b97723ab87dbfcaadae3fec8407cfba
[]
no_license
nguyenbahung94/Java
e65920bdeffcd7954e01f22fa9abd5a0dedc23b7
84350c6bc619fc913a8e8f9e7963fa6b8c075ee1
refs/heads/master
2021-01-10T06:22:13.219546
2016-03-21T17:47:17
2016-03-21T17:47:17
54,410,392
0
0
null
null
null
null
UTF-8
Java
false
false
4,257
java
package dombook; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Scanner; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class suathongtin { static String path="C:\\Users\\everything\\Desktop\\lap trinh huong dich vu\\DOM\\src\\dombook\\book.xml"; public static void main(String[] args) { File file=new File(path); Scanner scan=new Scanner(System.in); DocumentBuilderFactory build = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = build.newDocumentBuilder(); Document document=builder.parse(file); Element ele=document.getDocumentElement(); NodeList list=ele.getChildNodes(); System.out.println("nhap vao id"); String id=scan.nextLine(); for(int i=0;i<list.getLength();i++){ Element elstudent = (Element)document.getElementsByTagName("book").item(i); if(elstudent!=null){ if(elstudent.getAttribute("id").equalsIgnoreCase(id)) { Element elauthor = (Element)elstudent.getElementsByTagName("author").item(0); Element eltitle = (Element) elstudent.getElementsByTagName("title").item(0); Element elgenre = (Element) elstudent.getElementsByTagName("genre").item(0); Element elprince = (Element) elstudent.getElementsByTagName("price").item(0); Element elpusbli = (Element)elstudent.getElementsByTagName("publish_date").item(0); Element elxnb = (Element)elstudent.getElementsByTagName("nxb").item(0); Element elxdescrip = (Element)elstudent.getElementsByTagName("description").item(0); System.out.println("nhap vao author"); String author=scan.nextLine(); System.out.println("nhap vao title"); String title=scan.nextLine(); System.out.println("nhap vao genre"); String genre=scan.nextLine(); System.out.println("nhap vao prince"); String prince=scan.nextLine(); System.out.println("nhap vao publish date"); String publish=scan.nextLine(); System.out.println("nhap vao nxb"); String xnb=scan.nextLine(); System.out.println("nhap vao description"); String description=scan.nextLine(); elauthor.setTextContent(author); eltitle.setTextContent(title); elgenre.setTextContent(genre); elprince.setTextContent(prince); elpusbli.setTextContent(publish); elxnb.setTextContent(xnb); elxdescrip.setTextContent(description); ghi(document); } } } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static final void ghi(Document xml) throws Exception { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xml); StreamResult result = new StreamResult(new File("src\\dom\\book1.xml")); transformer.transform(source, result); // Output to console for testing Writer output = new StringWriter(); StreamResult consoleResult = new StreamResult(output); transformer.transform(source, consoleResult); System.out.println(output.toString()); } }
[ "mr.hungcity@gmail.com" ]
mr.hungcity@gmail.com
9262e47f8148eadffe62eeb63084cc01d81b7366
0a0554a98d009a22c1f3c83a0bdf1593c2f46e90
/EditText/app/src/main/java/com/yaowen/edittext/Main5Activity.java
be669ac6befca697a552f5c02272870432591683
[]
no_license
yaowen613/EditTextDemo
4b5fc34d734d6ee9a933e524eef7221b134b3f0e
7fa61d5bb5d5cdb48c17220edd0c6e303cf41bd6
refs/heads/master
2021-01-10T01:14:29.044235
2015-10-07T01:30:54
2015-10-07T01:30:54
43,788,645
0
0
null
null
null
null
UTF-8
Java
false
false
3,605
java
package com.yaowen.edittext; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class Main5Activity extends AppCompatActivity { private EditText editText1,editText2,editText3,editText4,editText5,editText6; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main5); editText1= (EditText) findViewById(R.id.txtTest0); editText2= (EditText) findViewById(R.id.txtTest1); editText3= (EditText) findViewById(R.id.txtTest2); editText4= (EditText) findViewById(R.id.txtTest3); editText5= (EditText) findViewById(R.id.txtTest4); editText6= (EditText) findViewById(R.id.txtTest5); editText1.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId== EditorInfo.IME_ACTION_GO){ Toast.makeText(Main5Activity.this,"你点了软键盘'去往'按钮",Toast.LENGTH_SHORT).show(); } return false; } }); editText2.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_SEARCH){ Toast.makeText(Main5Activity.this,"你点了软键盘'搜索'按钮",Toast.LENGTH_SHORT).show(); } return false; } }); editText3.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_SEND){ Toast.makeText(Main5Activity.this,"你点了软键盘'发送'按钮",Toast.LENGTH_SHORT).show(); } return false; } }); editText4.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_NEXT){ Toast.makeText(Main5Activity.this,"你点了软键盘'下一个'按钮",Toast.LENGTH_SHORT).show(); } return false; } }); editText5.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_DONE){ Toast.makeText(Main5Activity.this,"你点了软键盘'完成'按钮",Toast.LENGTH_SHORT).show(); } return false; } }); editText6.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_UNSPECIFIED){ Toast.makeText(Main5Activity.this,"你点了软键盘'未指定'按钮",Toast.LENGTH_SHORT).show(); } return false; } }); } }
[ "yaowen424@126.com" ]
yaowen424@126.com
4a819fbaba0d9d0e412945630a81114719ea737a
ba1aa2e72bd7b139855f52013f35260ebcdbc853
/web/src/main/java/org/tdar/struts/action/bulk/BulkUpdateStatusAction.java
47e75ff90ee1c9e218da381bfccd7c836ae830ac
[ "Apache-2.0" ]
permissive
digital-antiquity/tdar
6286194f87c559a9b50af38543b5525bfa0ca6d6
4984d088921f2a33e566e1d4b121e157d4a283f5
refs/heads/master
2023-08-15T21:21:12.184455
2023-08-04T05:58:21
2023-08-04T05:58:21
149,938,554
2
3
NOASSERTION
2023-09-14T17:04:05
2018-09-23T01:30:51
Java
UTF-8
Java
false
false
2,336
java
package org.tdar.struts.action.bulk; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.interceptor.validation.SkipValidation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.tdar.core.service.bulk.BulkUpdateReceiver; import org.tdar.core.service.bulk.BulkUploadService; import org.tdar.struts.action.AbstractAuthenticatableAction; import org.tdar.struts.interceptor.annotation.HttpsOnly; import org.tdar.struts_base.interceptor.annotation.PostOnly; import org.tdar.struts_base.result.HasJsonDocumentResult; import com.opensymphony.xwork2.Preparable; @ParentPackage("secured") @Component @HttpsOnly @Scope("prototype") @Namespace("/bulk") public class BulkUpdateStatusAction extends AbstractAuthenticatableAction implements Preparable, HasJsonDocumentResult { private static final long serialVersionUID = -5855079741655022360L; @Autowired private transient BulkUploadService bulkUploadService; private Long ticketId; private BulkUpdateReceiver status = new BulkUpdateReceiver(); @Override public void prepare() { BulkUpdateReceiver checkAsyncStatus = bulkUploadService.checkAsyncStatus(getTicketId()); if (checkAsyncStatus != null) { setStatus(checkAsyncStatus); } if (getStatus() != null) { getLogger().debug("{} {}%", getStatus().getMessage(), getStatus().getPercentComplete()); } } @Override public Object getResultObject() { return getStatus(); } @SkipValidation @Action(value = "checkstatus", results = { @Result(name = SUCCESS, type = JSONRESULT) }) @PostOnly public String checkStatus() { return SUCCESS; } public Long getTicketId() { return ticketId; } public void setTicketId(Long ticketId) { this.ticketId = ticketId; } public BulkUpdateReceiver getStatus() { return status; } public void setStatus(BulkUpdateReceiver status) { this.status = status; } }
[ "abrin@digitalantiquity.org" ]
abrin@digitalantiquity.org
23891f9084b80566921ae40a10eda86f833dcdfe
2aefc80de3a56ca555424349eb9d038fbaa2484f
/GCConnectivityService/src/com/htc/gc/connectivity/v3/internal/callables/GcWifiRemoveGroupCallable.java
9a98a23d0bb9010d4f66108a90fdad93215beb5b
[]
no_license
qmomochang/wearable
411964ca0ce1d7368bc4431095c5b256786acf7e
05a0d3b2634732655d9725bca66e4bc3eea5284b
refs/heads/master
2020-05-16T10:26:39.623457
2015-06-10T05:26:21
2015-06-10T05:26:21
37,178,936
1
0
null
null
null
null
UTF-8
Java
false
false
2,550
java
package com.htc.gc.connectivity.v3.internal.callables; import java.util.concurrent.Callable; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import com.htc.gc.connectivity.internal.common.CommonBase.GcWifiTransceiverErrorCode; import com.htc.gc.connectivity.v3.internal.component.wifi.GcWifiTransceiver; import com.htc.gc.connectivity.v3.internal.component.wifi.GcWifiTransceiverListener; import android.util.Log; public class GcWifiRemoveGroupCallable implements Callable<Integer> { private final static String TAG = "GcWifiRemoveGroupCallable"; private final static boolean bPerformanceNotify = true; private final static int DEFAULT_CALLABLE_TIMEOUT = 30000; private final LinkedBlockingQueue<GcWifiTransceiverErrorCode> mCallbackQueue = new LinkedBlockingQueue<GcWifiTransceiverErrorCode>(); protected GcWifiTransceiver mGcWifiTransceiver; protected long mTimePrev; private GcWifiTransceiverListener mGcWifiTransceiverListener = new GcWifiTransceiverListener() { @Override public void onWifiDirectGroupRemoved() { Log.d(TAG, "[MGCC] onWifiDirectGroupRemoved!!"); addCallback(GcWifiTransceiverErrorCode.ERROR_NONE); } @Override public void onError(GcWifiTransceiverErrorCode errorCode) { addCallback(errorCode); } }; public GcWifiRemoveGroupCallable(GcWifiTransceiver transceiver) { mGcWifiTransceiver = transceiver; } @Override public Integer call() throws Exception { from(); Integer ret = 0; mGcWifiTransceiver.registerListener(mGcWifiTransceiverListener); if (mGcWifiTransceiver.removeGroup()) { GcWifiTransceiverErrorCode errorCode = mCallbackQueue.poll(DEFAULT_CALLABLE_TIMEOUT, TimeUnit.MILLISECONDS); if (errorCode != GcWifiTransceiverErrorCode.ERROR_NONE) { ret = -1; } } else { ret = -1; } mGcWifiTransceiver.unregisterListener(mGcWifiTransceiverListener); to(TAG); return ret; } protected synchronized void addCallback(GcWifiTransceiverErrorCode errorCode) { Log.d(TAG, "[MGCC] addCallback errorCode = " + errorCode); if (errorCode != null) { mCallbackQueue.add(errorCode); } } private void from() { if (bPerformanceNotify) { mTimePrev = System.currentTimeMillis(); } } private void to(String task) { if (bPerformanceNotify) { long timeCurr = System.currentTimeMillis(); long timeDiff = timeCurr - mTimePrev; Log.d(TAG, "[MGCC][MPerf] [" + task + "] costs: " + timeDiff + " ms"); } } }
[ "michael_chang@htc.com" ]
michael_chang@htc.com
915bafce85bb9aa33d95e2fdd9b65985a01bf728
3bbac918768566a79a2487ceae2249b6319eb0fc
/app/src/main/java/com/example/popularmovies/MainActivity.java
105f703a102a72b4484d6ceacc6501a16f46c914
[]
no_license
SubasiniR/popular-movies
dd686e0da20e1d288cb133c466facc8d24741d2f
32b393541b123c499c73f6d624f472bb443f8b30
refs/heads/master
2020-03-15T07:50:55.822214
2018-07-13T18:52:47
2018-07-13T18:52:47
132,038,454
0
0
null
null
null
null
UTF-8
Java
false
false
7,264
java
package com.example.popularmovies; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import com.example.popularmovies.data.MoviesContract; import com.example.popularmovies.sync.MoviesSyncUtils; public class MainActivity extends AppCompatActivity implements LoaderCallbacks<Cursor>, MoviesAdapter.MoviesAdapterOnClickHandler { public static final String MOVIE_ID = "movieId"; public static final String TITLE = "title"; public static final String RELEASE_DATE = "release_date"; public static final String POSTER_LINK = "poster_link"; public static final String VOTE = "vote"; public static final String PLOT = "plot"; public static final String DEFAULT_SORT_PREFERENCE = "popular"; public static final String TOP_RATED_SORT_PREFERENCE = "top_rated"; public static final String[] MAIN_MOVIE_POSTER_PROJECTION = { MoviesContract.MoviesEntry.COLUMN_MOVIE_ID, MoviesContract.MoviesEntry.COLUMN_MOVIE_TITLE, MoviesContract.MoviesEntry.COLUMN_MOVIE_RELEASE_DATE, MoviesContract.MoviesEntry.COLUMN_MOVIE_POSTER_LINK, MoviesContract.MoviesEntry.COLUMN_MOVIE_VOTE_AVERAGE, MoviesContract.MoviesEntry.COLUMN_MOVIE_PLOT_SYNOPSIS }; public static final int INDEX_MOVIE_ID = 0; public static final int INDEX_MOVIE_TITLE = 1; public static final int INDEX_MOVIE_RELEASE_DATE = 2; public static final int INDEX_MOVIE_POSTER_LINK = 3; public static final int INDEX_MOVIE_VOTE_AVERAGE = 4; public static final int INDEX_MOVIE_PLOT_SYNOPSIS = 5; private static final int MOVIES_LOADER_ID = 44; private static final int FAVORITE_MOVIES_LOADER_ID = 55; private static final String LIST_STATE_KEY = "list_state"; Parcelable mListState; RecyclerView.LayoutManager mLayoutManager; private RecyclerView mRecyclerView; private MoviesAdapter mMoviesAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = findViewById(R.id.rv_movies_thumbnail); int numberOfColumns = 2; mLayoutManager = new GridLayoutManager(this, numberOfColumns); mRecyclerView.setLayoutManager(mLayoutManager); mMoviesAdapter = new MoviesAdapter(this, this); mRecyclerView.setAdapter(mMoviesAdapter); if (isNetworkConnectionAvailable()) { getSupportLoaderManager().initLoader(MOVIES_LOADER_ID, null, this); MoviesSyncUtils.initialize(this, DEFAULT_SORT_PREFERENCE); } else { Toast.makeText(this, "Network not available. Check the internet connection.", Toast.LENGTH_LONG).show(); } } protected void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); mListState = mLayoutManager.onSaveInstanceState(); state.putParcelable(LIST_STATE_KEY, mListState); } protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); if (state != null) mListState = state.getParcelable(LIST_STATE_KEY); } @Override protected void onResume() { super.onResume(); if (mListState != null) { mLayoutManager.onRestoreInstanceState(mListState); } } @Override public Loader<Cursor> onCreateLoader(int loaderId, Bundle bundle) { Uri moviesQueryUri = MoviesContract.MoviesEntry.CONTENT_URI; Uri moviesFavQueryUri = MoviesContract.MoviesEntry.CONTENT_URI_FAV; switch (loaderId) { case MOVIES_LOADER_ID: return new CursorLoader(this, moviesQueryUri, MAIN_MOVIE_POSTER_PROJECTION, null, null, null); case FAVORITE_MOVIES_LOADER_ID: return new CursorLoader(this, moviesFavQueryUri, MAIN_MOVIE_POSTER_PROJECTION, null, null, null); default: throw new RuntimeException("Loader Not Implemented: " + loaderId); } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mMoviesAdapter.swapCursor(data); if (mListState != null) { mLayoutManager.onRestoreInstanceState(mListState); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_popular) { item.setChecked(true); MoviesSyncUtils.startImmediateSync(MainActivity.this, DEFAULT_SORT_PREFERENCE); return true; } if (id == R.id.action_top_rated) { item.setChecked(true); MoviesSyncUtils.startImmediateSync(MainActivity.this, TOP_RATED_SORT_PREFERENCE); return true; } if (id == R.id.action_favorite) { item.setChecked(true); getSupportLoaderManager().restartLoader(FAVORITE_MOVIES_LOADER_ID, null, this); } return super.onOptionsItemSelected(item); } @Override public void onClick(int movieId, String title, String date, String poster, String vote, String plot) { Intent intentToStartDetailsActivity = new Intent(MainActivity.this, DetailActivity.class); intentToStartDetailsActivity.putExtra(MOVIE_ID, movieId); intentToStartDetailsActivity.putExtra(TITLE, title); intentToStartDetailsActivity.putExtra(RELEASE_DATE, date); intentToStartDetailsActivity.putExtra(POSTER_LINK, poster); intentToStartDetailsActivity.putExtra(VOTE, vote); intentToStartDetailsActivity.putExtra(PLOT, plot); startActivity(intentToStartDetailsActivity); } boolean isNetworkConnectionAvailable() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info == null) return false; NetworkInfo.State network = info.getState(); return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING); } }
[ "subasiniit@gmail.com" ]
subasiniit@gmail.com
ec293a5a1685735a9f8c86b33f923768c97a02ea
946d37f6148788d2e9a64698288977441a35bc0d
/DesignPatterns/studentSystem/ex2.java
b0aeec72e76e626da3a364ee5de8a8563a486f37
[]
no_license
daqiaobian/codepractice
66ee20517fde3435027679e0a6b182a4969b5d95
7608dbcb5cee9e4cf4190a25dc74f6fc4337581b
refs/heads/master
2023-08-22T21:34:12.964312
2021-10-13T03:34:02
2021-10-13T03:34:02
415,317,636
0
0
null
null
null
null
UTF-8
Java
false
false
582
java
package studentSystem; import java.lang.Math; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import java.util.Scanner; public class ex2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int sum, max = 0,day; for (int i =0; i<=7;i++){ int a = sc.nextInt(); int b = sc.nextInt(); sum = a+b; if ((sum > max) && (sum>8)){ max = sum; day = i; System.out.println(day); } } } }
[ "544118458@qq.com" ]
544118458@qq.com
6c6b0dcdc1258abc56002cf4a08b9175c4992769
17a8c11a36b9ae72fe47e584ba63a8a9d7e9dfeb
/src/main/java/com/space/demo/spider/newsRecommend/QuestionAnswer.java
5e30de6b1729af09f527a6f27f432a7846b6b801
[]
no_license
LumenWang/Knowledge_Graph_Aerospace
7a0ec1c047616a70a548b2ece0e0d36e79873469
1e745cbc1b1d1c9f073f91c8ee64a8eee2a7e75d
refs/heads/master
2023-05-13T01:31:10.050776
2021-06-01T13:14:02
2021-06-01T13:14:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,755
java
package com.space.demo.spider.newsRecommend; import com.space.demo.entity.newsReommend.Question; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.processor.PageProcessor; import us.codecraft.webmagic.selector.Selectable; import java.util.ArrayList; import java.util.List; @Component public class QuestionAnswer implements PageProcessor { @Value("${spring.spider.timeout}") private Integer timeout; @Value("${spring.spider.sleeptime}") private Integer sleeptime; @Value("${spring.spider.retrytimes}") private Integer retrytimes; @Value("${spring.spider.retrysleeptime}") private Integer retrysleeptime; List<Question> questions = new ArrayList<>(); @Override public void process(Page page) { List<Selectable> nodes = page.getHtml().xpath("//tr").nodes(); for(Selectable node:nodes){ String question = node.xpath("//dt/allText()").get().trim().substring(2); String itemA = node.xpath("//li[1]/allText()").get().trim(); String itemB = node.xpath("//li[2]/allText()").get().trim(); String itemC = node.xpath("//li[3]/allText()").get().trim(); String itemD = node.xpath("//li[4]/allText()").get().trim(); questions.add(new Question(question,itemA,itemB,itemC,itemD)); } page.putField("question",questions); } @Override public Site getSite() { return new Site().setTimeOut(timeout) .setSleepTime(sleeptime) .setRetryTimes(retrytimes) .setRetrySleepTime(retrysleeptime); } }
[ "1093453695@qq.com" ]
1093453695@qq.com
46f2d53555a0031d917b19c56da7e2381e181703
5c007a23b88f1f2c51843199904da7724ff34bae
/module/SampleModule/src/main/java/com/pds/sample/module/interpolatorplayground/InterpolatorActivity.java
dbdd0d74977aecdba408a5f06ed327a6db4eb814
[]
no_license
bubian/BlogProject
d8100916fee3ba8505c9601a216a6b9b1147b048
8278836ff8fe62af977b5ca330767a2f425d8792
refs/heads/master
2023-08-10T17:52:46.490579
2021-09-14T06:42:58
2021-09-14T06:42:58
161,014,161
0
0
null
null
null
null
UTF-8
Java
false
false
16,817
java
/* * Copyright (C) 2016 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 com.pds.sample.module.interpolatorplayground; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.os.Build; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.AnticipateInterpolator; import android.view.animation.BounceInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.animation.OvershootInterpolator; import android.widget.AdapterView; import android.widget.Button; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.LinearLayoutCompat; import com.pds.sample.R; import java.lang.reflect.Constructor; import static android.widget.LinearLayout.LayoutParams; /** * This activity allows the user to visualize the timing curves for * most of the standard Interpolator objects. It allows parameterized * interpolators to be changed, including manipulating the control * points of PathInterpolator to create custom curves. */ public class InterpolatorActivity extends AppCompatActivity { CurveVisualizer mVisualizer; TimingVisualizer mTimingVisualizer; ObjectAnimator mAnimator = null; long mDuration = 300; private int mDefaultMargin; private LinearLayoutCompat.LayoutParams params; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inter); DisplayMetrics metrics = getResources().getDisplayMetrics(); mDefaultMargin = (int) (8 * metrics.density); final LinearLayout paramatersParent = findViewById(R.id.linearLayout); final LinearLayout gridParent = (LinearLayout) findViewById(R.id.linearLayout2); final SeekBar durationSeeker = (SeekBar) findViewById(R.id.durationSeeker); final TextView durationLabel = (TextView) findViewById(R.id.durationLabel); mTimingVisualizer = (TimingVisualizer) findViewById(R.id.timingVisualizer); mAnimator = ObjectAnimator.ofFloat(this, "fraction", 0, 1); mVisualizer = new CurveVisualizer(this); gridParent.addView(mVisualizer); final Spinner spinner = (Spinner)findViewById(R.id.spinner); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) { populateParametersUI(adapterView.getItemAtPosition(pos).toString(), paramatersParent); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); durationSeeker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { durationLabel.setText("Duration " + progress + "ms"); mDuration = progress; } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); } /** * Called when the "Run" button is clicked. It cancels any running animation * and starts a new one with the values specified in the UI. */ public void runAnimation(View view) { mAnimator.cancel(); mAnimator.setInterpolator(mVisualizer.getInterpolator()); mAnimator.setDuration(mDuration); mAnimator.start(); } /** * This method is called to populate the UI according to which interpolator was * selected. */ private void populateParametersUI(String interpolatorName, LinearLayout parent) { parent.removeAllViews(); try { switch (interpolatorName) { case "Quadratic Path": createQuadraticPathInterpolator(parent); break; case "Cubic Path": createCubicPathInterpolator(parent); break; case "AccelerateDecelerate": mVisualizer.setInterpolator(new AccelerateDecelerateInterpolator()); break; case "Linear": mVisualizer.setInterpolator(new LinearInterpolator()); break; case "Bounce": mVisualizer.setInterpolator(new BounceInterpolator()); break; case "Accelerate": Constructor<AccelerateInterpolator> decelConstructor = AccelerateInterpolator.class.getConstructor(float.class); createParamaterizedInterpolator(parent, decelConstructor, "Factor", 1, 5, 1); break; case "Decelerate": Constructor<DecelerateInterpolator> accelConstructor = DecelerateInterpolator.class.getConstructor(float.class); createParamaterizedInterpolator(parent, accelConstructor, "Factor", 1, 5, 1); break; case "Overshoot": Constructor<OvershootInterpolator> overshootConstructor = OvershootInterpolator.class.getConstructor(float.class); createParamaterizedInterpolator(parent, overshootConstructor, "Tension", 1, 5, 1); break; case "Anticipate": Constructor<AnticipateInterpolator> anticipateConstructor = AnticipateInterpolator.class.getConstructor(float.class); createParamaterizedInterpolator(parent, anticipateConstructor, "Tension", 1, 5, 1); break; } } catch (NoSuchMethodException e) { Log.e("InterpolatorPlayground", "Error constructing interpolator: " + e); } } /** * Creates an Interpolator that takes a single parameter in its constructor. * The min/max/default parameters determine how the interpolator is initially * set up as well as the values used in the SeekBar for changing this value. */ private void createParamaterizedInterpolator(LinearLayout parent, final Constructor constructor, final String name, final float min, final float max, final float defaultValue) { LinearLayout inputContainer = new LinearLayout(this); inputContainer.setOrientation(LinearLayout.HORIZONTAL); LayoutParams params = new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(mDefaultMargin, mDefaultMargin, mDefaultMargin, mDefaultMargin); inputContainer.setLayoutParams(params); final TextView label = new TextView(this); params = new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT); params.weight = .5f; label.setLayoutParams(params); String formattedValue = String.format(" %.2f", defaultValue); label.setText(name + formattedValue); final SeekBar seek = new SeekBar(this); params = new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT); params.weight = .5f; seek.setLayoutParams(params); seek.setMax(100); seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { float percentage = (float) i / 100; float value = min + percentage * (max - min); String formattedValue = String.format(" %.2f", value); try { mVisualizer.setInterpolator((Interpolator) constructor.newInstance(value)); } catch (Throwable error) { Log.e("interpolatorPlayground", error.getMessage()); } label.setText(name + formattedValue); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); inputContainer.addView(label); inputContainer.addView(seek); parent.addView(inputContainer); try { mVisualizer.setInterpolator((Interpolator) constructor.newInstance(defaultValue)); } catch (Throwable error) { Log.e("interpolatorPlayground", error.getMessage()); } } /** * Creates a quadratic PathInterpolator, whose control point values can be changed * by the user dragging that handle around in the UI. */ private void createQuadraticPathInterpolator(LinearLayout parent) { float controlX = 0.5f, controlY = .2f; LinearLayout inputContainer = new LinearLayout(this); inputContainer.setOrientation(LinearLayout.VERTICAL); final LayoutParams params = new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(mDefaultMargin, mDefaultMargin, mDefaultMargin, mDefaultMargin); inputContainer.setLayoutParams(params); final TextView cx1Label = new TextView(this); cx1Label.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); cx1Label.setText("ControlX: " + controlX); final TextView cy1Label = new TextView(this); cy1Label.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); cy1Label.setText("ControlY: " + controlY); inputContainer.addView(cx1Label); inputContainer.addView(cy1Label); parent.addView(inputContainer); ControlPointCallback callback = new ControlPointCallback() { @Override void onControlPoint1Moved(float cx1, float cy1) { cx1Label.setText("ControlX: " + String.format("%.2f", cx1)); cy1Label.setText("ControlY: " + String.format("%.2f", cy1)); } @Override void onControlPoint2Moved(float cx2, float cy2) { } }; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mVisualizer.setQuadraticInterpolator(controlX, controlY, callback); } } /** * Creates a cubic PathInterpolator, whose control points values can be changed * by the user dragging the handles around in the UI. */ private void createCubicPathInterpolator(LinearLayout parent) { float cx1 = 0.5f, cy1 = .2f; float cx2 = 0.9f, cy2 = .7f; LinearLayout inputContainer = new LinearLayout(this); inputContainer.setOrientation(LinearLayout.VERTICAL); final LayoutParams params = new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(mDefaultMargin, mDefaultMargin, mDefaultMargin, mDefaultMargin); inputContainer.setLayoutParams(params); final TextView cx1Label = createControlPointLabel("ControlX1", cx1); final TextView cy1Label = createControlPointLabel("ControlY1", cy1); final TextView cx2Label = createControlPointLabel("ControlX2", cx2); final TextView cy2Label = createControlPointLabel("ControlY2", cy2); inputContainer.addView(cx1Label); inputContainer.addView(cy1Label); inputContainer.addView(cx2Label); inputContainer.addView(cy2Label); parent.addView(inputContainer); final ControlPointCallback callback = new ControlPointCallback() { @Override void onControlPoint1Moved(float cx, float cy) { cx1Label.setText("ControlX1: " + String.format("%.2f", cx)); cy1Label.setText("ControlY1: " + String.format("%.2f", cy)); } @Override void onControlPoint2Moved(float cx, float cy) { cx2Label.setText("ControlX2: " + String.format("%.2f", cx)); cy2Label.setText("ControlY2: " + String.format("%.2f", cy)); } }; // Buttons to set control points from standard Material Design interpolators LinearLayout buttonContainer = new LinearLayout(this); buttonContainer.setOrientation(LinearLayout.HORIZONTAL); buttonContainer.setLayoutParams(new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); buttonContainer.addView(createMaterialMotionButton("L out S in", 0, 0, .2f, 1, .33f, callback)); buttonContainer.addView(createMaterialMotionButton("F out S in", .4f, 0, .2f, 1, .33f, callback)); buttonContainer.addView(createMaterialMotionButton("F out L in", .4f, 0, 1, 1, .33f, callback)); inputContainer.addView(buttonContainer); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mVisualizer.setCubicInterpolator(cx1, cy1, cx2, cy2, callback); } } @NonNull private TextView createControlPointLabel(String label, float value) { final TextView cx1Label = new TextView(this); cx1Label.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); cx1Label.setText(label + ": " + value); return cx1Label; } private Button createMaterialMotionButton(String label, final float cx1, final float cy1, final float cx2, final float cy2, float weight, final ControlPointCallback callback) { Button button = new Button(this); LayoutParams params = new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT); params.weight = weight; button.setLayoutParams(params); button.setText("F out L in"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Animate the control points to their new values final float oldCx1 = mVisualizer.getCx1(); final float oldCy1 = mVisualizer.getCy1(); final float oldCx2 = mVisualizer.getCx2(); final float oldCy2 = mVisualizer.getCy2(); ValueAnimator anim = ValueAnimator.ofFloat(0, 1).setDuration(100); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { float t = valueAnimator.getAnimatedFraction(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mVisualizer.setCubicInterpolator(oldCx1 + t * (cx1 - oldCx1), oldCy1 + t * (cy1 - oldCy1), oldCx2 + t * (cx2 - oldCx2), oldCy2 + t * (cy2 - oldCy2), callback); } } }); anim.start(); } }); return button; } /** * This method is called by the animation to update the position of the animated * objects in the curve view as well as the view at the bottom showing sample animations. */ public void setFraction(float fraction) { mTimingVisualizer.setFraction(fraction); mVisualizer.setFraction(fraction); } }
[ "pengdaosong@medlinker.com" ]
pengdaosong@medlinker.com
5c8f169be0680adadbb08a828b47c976c846bf75
1931ae9362135cb31d9995decab37387c86d971d
/xuedan_zou_myruns5/xuedan_zou_myrun5/app/src/main/java/com/example/xuedan_zou_myrun2/FFT.java
d67259e7259f645225b5ddb3ea2f3fc47a2c30f7
[]
no_license
actbee/Android
c3a7c91a43ce19e0074f46d0f999a8741ba7bdda
2bbcd99b235984da41e6f36aebeafa51c9154a75
refs/heads/master
2023-08-27T21:45:42.074247
2021-10-26T00:24:28
2021-10-26T00:24:28
408,546,319
0
0
null
null
null
null
UTF-8
Java
false
false
5,141
java
package com.example.xuedan_zou_myrun2; public class FFT { int n, m; // Lookup tables. Only need to recompute when size of FFT changes. double[] cos; double[] sin; double[] window; public FFT(int n) { this.n = n; this.m = (int) (Math.log(n) / Math.log(2)); // Make sure n is a power of 2 if (n != (1 << m)) throw new RuntimeException("FFT length must be power of 2"); // precompute tables cos = new double[n / 2]; sin = new double[n / 2]; // for(int i=0; i<n/4; i++) { // cos[i] = Math.cos(-2*Math.PI*i/n); // sin[n/4-i] = cos[i]; // cos[n/2-i] = -cos[i]; // sin[n/4+i] = cos[i]; // cos[n/2+i] = -cos[i]; // sin[n*3/4-i] = -cos[i]; // cos[n-i] = cos[i]; // sin[n*3/4+i] = -cos[i]; // } for (int i = 0; i < n / 2; i++) { cos[i] = Math.cos(-2 * Math.PI * i / n); sin[i] = Math.sin(-2 * Math.PI * i / n); } makeWindow(); } protected void makeWindow() { // Make a blackman window: // w(n)=0.42-0.5cos{(2*PI*n)/(N-1)}+0.08cos{(4*PI*n)/(N-1)}; window = new double[n]; for (int i = 0; i < window.length; i++) window[i] = 0.42 - 0.5 * Math.cos(2 * Math.PI * i / (n - 1)) + 0.08 * Math.cos(4 * Math.PI * i / (n - 1)); } public double[] getWindow() { return window; } /*************************************************************** * fft.c Douglas L. Jones University of Illinois at Urbana-Champaign January * 19, 1992 http://cnx.rice.edu/content/m12016/latest/ * * fft: in-place radix-2 DIT DFT of a complex input * * input: n: length of FFT: must be a power of two m: n = 2**m input/output * x: double array of length n with real part of data y: double array of * length n with imag part of data * * Permission to copy and use this program is granted as long as this header * is included. ****************************************************************/ public void fft(double[] x, double[] y) { int i, j, k, n1, n2, a; double c, s, t1, t2; // Bit-reverse j = 0; n2 = n / 2; for (i = 1; i < n - 1; i++) { n1 = n2; while (j >= n1) { j = j - n1; n1 = n1 / 2; } j = j + n1; if (i < j) { t1 = x[i]; x[i] = x[j]; x[j] = t1; t1 = y[i]; y[i] = y[j]; y[j] = t1; } } // FFT n1 = 0; n2 = 1; for (i = 0; i < m; i++) { n1 = n2; n2 = n2 + n2; a = 0; for (j = 0; j < n1; j++) { c = cos[a]; s = sin[a]; a += 1 << (m - i - 1); for (k = j; k < n; k = k + n2) { t1 = c * x[k + n1] - s * y[k + n1]; t2 = s * x[k + n1] + c * y[k + n1]; x[k + n1] = x[k] - t1; y[k + n1] = y[k] - t2; x[k] = x[k] + t1; y[k] = y[k] + t2; } } } } // Test the FFT to make sure it's working public static void main(String[] args) { int N = 8; FFT fft = new FFT(N); double[] re = new double[N]; double[] im = new double[N]; // Impulse re[0] = 1; im[0] = 0; for (int i = 1; i < N; i++) re[i] = im[i] = 0; beforeAfter(fft, re, im); // Nyquist for (int i = 0; i < N; i++) { re[i] = Math.pow(-1, i); im[i] = 0; } beforeAfter(fft, re, im); // Single sin for (int i = 0; i < N; i++) { re[i] = Math.cos(2 * Math.PI * i / N); im[i] = 0; } beforeAfter(fft, re, im); // Ramp for (int i = 0; i < N; i++) { re[i] = i; im[i] = 0; } beforeAfter(fft, re, im); long time = System.currentTimeMillis(); double iter = 30000; for (int i = 0; i < iter; i++) fft.fft(re, im); time = System.currentTimeMillis() - time; System.out.println("Averaged " + (time / iter) + "ms per iteration"); } public static void beforeAfter(FFT fft, double[] re, double[] im) { System.out.println("Before: "); printReIm(re, im); fft.fft(re, im); System.out.println("After: "); printReIm(re, im); } public static void printReIm(double[] re, double[] im) { System.out.print("Re: ["); for (int i = 0; i < re.length; i++) System.out.print(((int) (re[i] * 1000) / 1000.0) + " "); System.out.print("]\nIm: ["); for (int i = 0; i < im.length; i++) System.out.print(((int) (im[i] * 1000) / 1000.0) + " "); System.out.println("]"); } }
[ "rainman511@outlook.com" ]
rainman511@outlook.com
71889f160ef97d92e28d94c68b67f19bfb860bef
23440b1832969662b8f8e1aacb0c9b6b5d2689f9
/03homework/src/com/company/Main.java
b4851afd3e96c791d7d941f6b204e2f78d859588
[]
no_license
ertastfl/JavaKamp2Homework
e41ad61a41d07ef78884f573aae3301582bd809f
3108c1ca4801fff02934a51a7ea4db0515496a1e
refs/heads/main
2023-04-11T21:09:53.764895
2021-04-30T07:47:23
2021-04-30T07:47:23
363,065,171
1
0
null
null
null
null
UTF-8
Java
false
false
1,107
java
package com.company; public class Main { public static void main(String[] args) { Teacher teacherEnginDemirog = new Teacher(1, "Engin Demiroğ", "Yazılım geliştirmeye lisede \"yazılım\" bölümünde okurken başladım."); Teacher teacherMustafaMuratCoskun = new Teacher(2, "Mustafa Murat Çoşkun", "yatwuloşduhıauwkl gh8awıugdh ıuakwjdsn ıhakwj bsdıuakwjd"); Course javaCourse = new Course(teacherEnginDemirog, 1, "Yazılım Geliştirici Yetiştirme Kampı (JAVA + REACT)"); Course cSharpCourse = new Course(teacherMustafaMuratCoskun, 2, "Yazılım Geliştirici Yetiştirme Kampı (C# + ANGULAR)"); Teacher[] teachers = {teacherEnginDemirog, teacherMustafaMuratCoskun}; Course[] courses = {javaCourse, cSharpCourse}; UserHelper userHelper = new UserHelper(); for (Teacher teacher : teachers) { System.out.println(teacher + "\n"); } for (Course course : courses) { System.out.println(course + "\n"); } userHelper.exitTheAccount(); userHelper.signIn(); } }
[ "73423961+ertastfl@users.noreply.github.com" ]
73423961+ertastfl@users.noreply.github.com
bf9dd337a3c1ad30374fd38cb86235f4678f8f8f
7bfe3e48037c507b3797bf7059a070ccf03b779c
/build/generated-sources/jax-ws/co/matisses/b1ws/drafts/UpdateFromXML.java
4cae1992acc06f49a5da8eae68ca063d71165484
[]
no_license
matisses/B1WSClient
c0f8147a0f86eb7ef8377f2398ecfc248c6159e2
6fdc8d1010cc6d3cc32a583b63d2d538fc1a540b
refs/heads/master
2020-03-17T12:13:04.267787
2018-05-15T22:14:50
2018-05-15T22:14:50
133,578,758
1
1
null
null
null
null
UTF-8
Java
false
false
1,516
java
package co.matisses.b1ws.drafts; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para anonymous complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.sap.com/SBO/DIS}Document" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "document" }) @XmlRootElement(name = "UpdateFromXML", namespace = "DraftsService") public class UpdateFromXML { @XmlElement(name = "Document") protected Document document; /** * Obtiene el valor de la propiedad document. * * @return * possible object is * {@link Document } * */ public Document getDocument() { return document; } /** * Define el valor de la propiedad document. * * @param value * allowed object is * {@link Document } * */ public void setDocument(Document value) { this.document = value; } }
[ "ygil@matisses.co" ]
ygil@matisses.co
bb2cb7cd06e1f1928cf12c3d9ba06a48e675e6e8
be357fa6e617dfdfa313b36fea86bd2043da62f2
/src/main/java/Command/DoneCommand.java
f5febc48eda32526081dc5aa53efc2aaef545985
[]
no_license
murtubak/ip
3d69fef3dbde86ea8285cca801b5c1185126f100
1e53b01431fc29da070e815287634dda725b0e88
refs/heads/master
2022-12-12T17:54:56.693815
2020-09-17T19:00:58
2020-09-17T19:00:58
287,766,938
0
0
null
2020-09-09T19:36:58
2020-08-15T14:53:05
Java
UTF-8
Java
false
false
1,776
java
package command; import duke.DukeException; import duke.Storage; import duke.TaskList; import duke.Ui; /** * DoneCommand will indicate the Task at the given position is complete. * * @author Joshua */ public class DoneCommand extends Command { /** * This is the position of the task that is completed. */ private int taskPosition; /** * Creates a DoneCommand with the position of the completed task in the TaskList. * * @param position the position of the task in the TaskList. */ public DoneCommand(int position) { this.taskPosition = position; } /** * Executes the DoneCommand with the following TaskList, Ui and Storage classes. * The completed task in the TaskList at the position will change its status to completed. * The Ui will return the output to be displayed to the user. The storage will update * with the new TaskList. * * @param taskList the TaskList to be updated. * @param ui the Ui that interacts with the user. * @param storage the Storage that is updated with TaskList. * @return output to be displayed to the user. * @throws DukeException throws exception if the position of the task to be completed is incorrect. */ @Override public String execute(TaskList taskList, Ui ui, Storage storage) throws DukeException { if (taskPosition < taskList.getTaskList().size() && taskPosition >= 0) { taskList.getTaskList().get(taskPosition).completeTask(); storage.updateStorage(taskList); output = ui.showDone(taskList.getTaskList().get(taskPosition)); return output; } else { throw new DukeException("OOPS !!! Esta tarea aun no existe!"); } } }
[ "murtubakchickenss@gmail.com" ]
murtubakchickenss@gmail.com
5aa07d4f87fbff69f9d1d9dabf69784dfc61e3b0
68125a6635ef9840b2b9a2a7f08dc2f4668d52b2
/mobile/app/src/main/java/com/neu/cloudfiles/ui/userInfo/UserInfoContract.java
2c455c0b495c6b739aa38077525d0b64b313ed93
[]
no_license
lintongyu418/Cloud-Files
ae615064879c36a51bfb696236abd2250371f221
33f33b6fe79a55b22439da068584cc828e314b89
refs/heads/main
2023-07-04T11:15:58.923501
2021-08-12T04:41:31
2021-08-12T04:41:31
395,517,211
0
0
null
2021-08-13T04:09:30
2021-08-13T04:09:29
null
UTF-8
Java
false
false
535
java
package com.neu.cloudfiles.ui.userInfo; import com.neu.cloudfiles.base.BaseContract; import com.neu.cloudfiles.bean.UserLoginVo; import com.neu.cloudfiles.bean.UserVo; /** * Created by lw on 2018/1/24. */ public interface UserInfoContract { interface View extends BaseContract.BaseView { void getUserInfoSuccess(UserVo user); void logoutSuccess(); } interface Presenter extends BaseContract.BasePresenter<UserInfoContract.View> { void getUserInfo(String token); void logout(); } }
[ "jiangchuan.wang@tusimple.ai" ]
jiangchuan.wang@tusimple.ai
098ccce9a9e01adc622466d46ed0902f6f0d0e22
b239b7ea52dfaaf6ad05dc4bec5cea654689a457
/app/src/main/java/com/example/administrador/starwarswiki/network/RetrofitConfig.java
97cf8c26ffe6becce74faf964f350ffdedfc495a
[ "MIT" ]
permissive
brunokreutz/entrevista-android
a44d6a64474735f62a3803e232db3c0b64b68b00
70d69b4113fad6156241a389c328b06be880a53d
refs/heads/master
2020-04-05T21:36:09.237588
2018-11-19T01:28:45
2018-11-19T01:28:45
157,226,307
0
0
null
2018-11-12T14:30:26
2018-11-12T14:30:25
null
UTF-8
Java
false
false
1,192
java
package com.example.administrador.starwarswiki.network; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; public class RetrofitConfig { private final Retrofit retrofitSwapi; private final Retrofit retrofitApiary; public RetrofitConfig() { OkHttpClient okHttpClient = new OkHttpClient(); JacksonConverterFactory jacksonConverterFactory = JacksonConverterFactory.create(); this.retrofitSwapi = new Retrofit.Builder() .client(okHttpClient) .baseUrl("http://swapi.co/") .addConverterFactory(jacksonConverterFactory) .build(); this.retrofitApiary = new Retrofit.Builder() .client(okHttpClient) .baseUrl("http://private-782d3-starwarsfavorites.apiary-mock.com/") .addConverterFactory(jacksonConverterFactory) .build(); } public SwapiService getSwapiService() { return this.retrofitSwapi.create(SwapiService.class); } public ApiaryService getApiaryService() { return this.retrofitApiary.create(ApiaryService.class); } }
[ "kreutz.dev@gmail.com" ]
kreutz.dev@gmail.com
86bb7ff26983e52b641bb95527b2ae7b005bed47
3d05618ae85fd3aa9d1df2dfe7d36f33cfbc4494
/stm/src/test/java/org/chenile/stm/test/basicflow/ConfirmPayment.java
3550ae379fc220c3935aa4be30361539313e5ce5
[ "MIT" ]
permissive
dewesh/chenile
fc375dc481b799c5f37eac17f78ad0f22a6e240e
88b0634d295a13b23c59c6a835bc517cb0e15399
refs/heads/master
2022-12-28T18:42:07.198407
2019-11-27T02:38:47
2019-11-27T02:38:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
677
java
package org.chenile.stm.test.basicflow; import org.chenile.stm.STMInternalTransitionInvoker; import org.chenile.stm.State; import org.chenile.stm.action.STMTransitionAction; import org.chenile.stm.model.Transition; public class ConfirmPayment implements STMTransitionAction<Cart> { public static final String LOGMESSAGE = "ConfirmPayment"; public void doTransition(Cart cart, Object transitionParam, State startState, String eventId,State endState,STMInternalTransitionInvoker<?> stmhandle, Transition transition) throws Exception { String confirmationId = (String)transitionParam; cart.getPayment().setConfirmationId(confirmationId); cart.log(LOGMESSAGE); } }
[ "raja.shankar@meratransport.com" ]
raja.shankar@meratransport.com
f9e9ce4f4eb1e1f796c7fd3c1732474f02bc1698
180e78725121de49801e34de358c32cf7148b0a2
/dataset/protocol1/spoon/learning/1166/CtLambdaImpl.java
c0648a9e3815702ff823c5efb937d67adfe72553
[]
no_license
ASSERT-KTH/synthetic-checkstyle-error-dataset
40e8d1e0a7ebe7f7711def96a390891a6922f7bd
40c057e1669584bfc6fecf789b5b2854660222f3
refs/heads/master
2023-03-18T12:50:55.410343
2019-01-25T09:54:39
2019-01-25T09:54:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,065
java
/** * Copyright (C) 2006-2018 INRIA and contributors * Spoon - http://spoon.gforge.inria.fr/ * * This software is governed by the CeCILL-C License under French law and * abiding by the rules of distribution of free software. You can use, modify * and/or redistribute the software under the terms of the CeCILL-C license as * circulated by CEA, CNRS and INRIA at http://www.cecill.info. * * 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 CeCILL-C License for more details. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. */ package spoon.support.reflect.code; import spoon.SpoonException; import spoon.reflect.annotations.MetamodelPropertyField; import spoon.reflect.code.CtBlock; import spoon.reflect.code.CtBodyHolder; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtLambda; import spoon.reflect.code.CtStatement; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtNamedElement; import spoon.reflect.declaration.CtParameter; import spoon.reflect.declaration.CtType; import spoon.reflect.declaration.CtExecutable; import spoon.reflect.declaration.ModifierKind; import spoon.reflect.reference.CtExecutableReference; import spoon.reflect.reference.CtTypeReference; import spoon.reflect.visitor.CtVisitor; import spoon.support.UnsettableProperty; import spoon.support.reflect.declaration.CtElementImpl; import spoon.support.util.QualifiedNameBasedSortedSet; import spoon.support.visitor.SignaturePrinter; import java.util.ArrayList; import java.util.List; import java.util.Set; import static spoon.reflect.ModelElementContainerDefaultCapacities.PARAMETERS_CONTAINER_DEFAULT_CAPACITY; import static spoon.reflect.path.CtRole.BODY; import static spoon.reflect.path.CtRole.EXPRESSION; import static spoon.reflect.path.CtRole.NAME; import static spoon.reflect.path.CtRole.PARAMETER; import static spoon.reflect.path.CtRole.THROWN; public class CtLambdaImpl<T> extends CtExpressionImpl<T> implements CtLambda<T> { @MetamodelPropertyField(role = NAME) String simpleName = ""; @MetamodelPropertyField(role = EXPRESSION) CtExpression<T> expression; @MetamodelPropertyField(role = BODY) CtBlock<?> body; @MetamodelPropertyField(role = PARAMETER) List<CtParameter<?>> parameters = emptyList(); @MetamodelPropertyField(role = THROWN) Set<CtTypeReference<? extends Throwable>> thrownTypes = emptySet(); @Override public void accept(CtVisitor visitor) { visitor.visitCtLambda(this); } @Override public String getSimpleName() { return simpleName; } @Override public <C extends CtNamedElement> C setSimpleName(String simpleName) { getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, NAME, simpleName, this.simpleName); this.simpleName = simpleName; return (C) this; } @Override @SuppressWarnings("unchecked") public CtBlock<T> getBody() { return (CtBlock<T>) body; } @Override public <C extends CtBodyHolder> C setBody(CtStatement statement) { if (statement != null) { CtBlock<?> body = getFactory().Code().getOrCreateCtBlock(statement); getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, BODY, body, this.body); if (expression != null && body != null) { throw new SpoonException("A lambda can't have two bodys."); } if (body != null) { body.setParent(this); } this.body = body; } else { getFactory().getEnvironment().getModelChangeListener().onObjectDelete(this, BODY, this.body); this.body = null; } return (C) this; } @SuppressWarnings("unchecked") @Override public <R> CtMethod<R> getOverriddenMethod() { //The type of this lambda expression. For example: `Consumer<Integer>` CtTypeReference<T> lambdaTypeRef = getType(); if (lambdaTypeRef == null) { //it can be null in noclasspath mode, so we do not know which method is called, by lambda return null; } CtType<T> lambdaType = lambdaTypeRef.getTypeDeclaration(); if (lambdaType.isInterface() == false) { throw new SpoonException("The lambda can be based on interface only. But type " + lambdaTypeRef.getQualifiedName() + " is not an interface"); } Set<CtMethod<?>> lambdaTypeMethods = lambdaType.getAllMethods(); CtMethod<?> lambdaExecutableMethod = null; if (lambdaTypeMethods.size() == 1) { //even the default method can be used, if it is the only one lambdaExecutableMethod = lambdaTypeMethods.iterator().next(); } else { for (CtMethod<?> method : lambdaTypeMethods) { if (getFactory().Method().OBJECT_METHODS.stream().anyMatch(method::isOverriding)) { continue; } if (method.isDefaultMethod() || method.hasModifier(ModifierKind.PRIVATE) || method.hasModifier(ModifierKind.STATIC)) { continue; } if (lambdaExecutableMethod != null) { throw new SpoonException("The lambda can be based on interface, which has only one method. But " + lambdaTypeRef.getQualifiedName() + " has at least two: " + lambdaExecutableMethod.getSignature() + " and " + method.getSignature()); } lambdaExecutableMethod = method; } } if (lambdaExecutableMethod == null) { throw new SpoonException("The lambda can be based on interface, which has one method. But " + lambdaTypeRef.getQualifiedName() + " has no one"); } return (CtMethod<R>) lambdaExecutableMethod; } @Override public List<CtParameter<?>> getParameters() { return unmodifiableList(parameters); } @Override public <C extends CtExecutable<T>> C setParameters(List<CtParameter<?>> params) { if (params == null || params.isEmpty()) { this.parameters = CtElementImpl.emptyList(); return (C) this; } if (this.parameters == CtElementImpl.<CtParameter<?>>emptyList()) { this.parameters = new ArrayList<>(PARAMETERS_CONTAINER_DEFAULT_CAPACITY); } getFactory().getEnvironment().getModelChangeListener().onListDeleteAll(this, PARAMETER, this.parameters, new ArrayList<>(this.parameters)); this.parameters.clear(); for (CtParameter<?> p : params) { addParameter(p); } return (C) this; } @Override public <C extends CtExecutable<T>> C addParameter(CtParameter<?> parameter) { if (parameter == null) { return (C) this; } if (parameters == CtElementImpl.<CtParameter<?>>emptyList()) { parameters = new ArrayList<>(PARAMETERS_CONTAINER_DEFAULT_CAPACITY); } parameter.setParent(this); getFactory().getEnvironment().getModelChangeListener().onListAdd(this, PARAMETER, this.parameters, parameter); parameters.add(parameter); return (C) this; } @Override public boolean removeParameter(CtParameter<?> parameter) { if (parameters == CtElementImpl.<CtParameter<?>>emptyList()) { return false; } getFactory().getEnvironment().getModelChangeListener().onListDelete(this, PARAMETER, parameters, parameters.indexOf(parameter), parameter); return parameters.remove(parameter); } @Override public Set<CtTypeReference<? extends Throwable>> getThrownTypes() { return thrownTypes; } @Override @UnsettableProperty public <C extends CtExecutable<T>> C setThrownTypes(Set<CtTypeReference<? extends Throwable>> thrownTypes) { return (C) this; } @Override public <C extends CtExecutable<T>> C addThrownType(CtTypeReference<? extends Throwable> throwType) { if (throwType == null) { return (C) this; } if (thrownTypes == CtElementImpl.<CtTypeReference<? extends Throwable>>emptySet()) { thrownTypes = new QualifiedNameBasedSortedSet<>(); } throwType.setParent(this); getFactory().getEnvironment().getModelChangeListener().onSetAdd(this, THROWN, this.thrownTypes, throwType); thrownTypes.add(throwType); return (C) this; } @Override public boolean removeThrownType(CtTypeReference<? extends Throwable> throwType) { if (thrownTypes == CtElementImpl.<CtTypeReference<? extends Throwable>>emptySet()) { return false; } getFactory().getEnvironment().getModelChangeListener().onSetDelete(this, THROWN, thrownTypes, throwType); return thrownTypes.remove(throwType); } @Override public String getSignature() { final SignaturePrinter pr = new SignaturePrinter(); pr.scan(this); return pr.getSignature(); } @Override public CtExecutableReference<T> getReference() { return getFactory().Executable().createReference(this); } @Override public CtExpression<T> getExpression() { return expression; } @Override public <C extends CtLambda<T>> C setExpression(CtExpression<T> expression) { if (body != null && expression != null) { throw new SpoonException("A lambda can't have two bodies."); } else { if (expression != null) { expression.setParent(this); } getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, EXPRESSION, expression, this.expression); this.expression = expression; } return (C) this; } @Override public CtLambda<T> clone() { return (CtLambda<T>) super.clone(); } }
[ "bloriot97@gmail.com" ]
bloriot97@gmail.com
adde80460ad0243ecaf45a9856aeb36c090e8e01
129f58086770fc74c171e9c1edfd63b4257210f3
/src/testcases/CWE191_Integer_Underflow/CWE191_Integer_Underflow__short_rand_multiply_07.java
e52d80df056a3efd00408180b201f142340bec42
[]
no_license
glopezGitHub/Android23
1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba
6215d0684c4fbdc7217ccfbedfccfca69824cc5e
refs/heads/master
2023-03-07T15:14:59.447795
2023-02-06T13:59:49
2023-02-06T13:59:49
6,856,387
0
3
null
2023-02-06T18:38:17
2012-11-25T22:04:23
Java
UTF-8
Java
false
false
10,149
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__short_rand_multiply_07.java Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-07.tmpl.java */ /* * @description * CWE: 191 Integer Underflow * BadSource: rand Set data to result of rand() * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: multiply * GoodSink: Ensure there will not be an underflow before multiplying data by 2 * BadSink : If data is negative, multiply by 2, which can cause an underflow * Flow Variant: 07 Control flow: if(private_five==5) and if(private_five!=5) * * */ package testcases.CWE191_Integer_Underflow; import testcasesupport.*; public class CWE191_Integer_Underflow__short_rand_multiply_07 extends AbstractTestCase { /* The variable below is not declared "final", but is never assigned any other value so a tool should be able to identify that reads of this will always give its initialized value. */ private int private_five = 5; public void bad() throws Throwable { short data; /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)((new java.security.SecureRandom()).nextInt(1+Short.MAX_VALUE-Short.MIN_VALUE)+Short.MIN_VALUE); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { if(data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Short.MIN_VALUE, this will underflow */ short result = (short)(data * 2); IO.writeLine("result: " + result); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ if(data < 0) /* ensure we won't have an overflow */ { /* FIX: Add a check to prevent an underflow from occurring */ if (data > (Short.MIN_VALUE/2)) { short result = (short)(data * 2); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform multiplication."); } } } } /* goodG2B1() - use goodsource and badsink by changing first private_five==5 to private_five!=5 */ private void goodG2B1() throws Throwable { short data; /* INCIDENTAL: CWE 570 Statement is Always False */ if(private_five!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* POTENTIAL FLAW: Use a random value */ data = (short)((new java.security.SecureRandom()).nextInt(1+Short.MAX_VALUE-Short.MIN_VALUE)+Short.MIN_VALUE); } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { if(data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Short.MIN_VALUE, this will underflow */ short result = (short)(data * 2); IO.writeLine("result: " + result); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ if(data < 0) /* ensure we won't have an overflow */ { /* FIX: Add a check to prevent an underflow from occurring */ if (data > (Short.MIN_VALUE/2)) { short result = (short)(data * 2); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform multiplication."); } } } } /* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { short data; /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* POTENTIAL FLAW: Use a random value */ data = (short)((new java.security.SecureRandom()).nextInt(1+Short.MAX_VALUE-Short.MIN_VALUE)+Short.MIN_VALUE); } /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { if(data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Short.MIN_VALUE, this will underflow */ short result = (short)(data * 2); IO.writeLine("result: " + result); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ if(data < 0) /* ensure we won't have an overflow */ { /* FIX: Add a check to prevent an underflow from occurring */ if (data > (Short.MIN_VALUE/2)) { short result = (short)(data * 2); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform multiplication."); } } } } /* goodB2G1() - use badsource and goodsink by changing second private_five==5 to private_five!=5 */ private void goodB2G1() throws Throwable { short data; /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)((new java.security.SecureRandom()).nextInt(1+Short.MAX_VALUE-Short.MIN_VALUE)+Short.MIN_VALUE); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } /* INCIDENTAL: CWE 570 Statement is Always False */ if(private_five!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ if(data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Short.MIN_VALUE, this will underflow */ short result = (short)(data * 2); IO.writeLine("result: " + result); } } else { if(data < 0) /* ensure we won't have an overflow */ { /* FIX: Add a check to prevent an underflow from occurring */ if (data > (Short.MIN_VALUE/2)) { short result = (short)(data * 2); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform multiplication."); } } } } /* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2() throws Throwable { short data; /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)((new java.security.SecureRandom()).nextInt(1+Short.MAX_VALUE-Short.MIN_VALUE)+Short.MIN_VALUE); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } /* INCIDENTAL: CWE 571 Statement is Always True */ if(private_five==5) { if(data < 0) /* ensure we won't have an overflow */ { /* FIX: Add a check to prevent an underflow from occurring */ if (data > (Short.MIN_VALUE/2)) { short result = (short)(data * 2); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform multiplication."); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ if(data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Short.MIN_VALUE, this will underflow */ short result = (short)(data * 2); IO.writeLine("result: " + result); } } } public void good() throws Throwable { goodG2B1(); goodG2B2(); goodB2G1(); goodB2G2(); } /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
[ "guillermo.pando@gmail.com" ]
guillermo.pando@gmail.com
e8ef7f7b4e8893d9b5b477064519c3ba68c24faa
ce7cb3b0cbafcb22b016debe39cd1e8cfe91c23c
/app/src/main/java/coder/aihui/widget/ScrollViewWithExpandListView.java
bda0062afaebfe31b0b13ba0e703fa5038367026
[]
no_license
zhougangwei/PrettyGirls-master
0812f2da9943b3e893a641be4eb26133e20bb60f
692084b1a5369b149305f999bbbd7dacc84ba03c
refs/heads/master
2021-01-02T08:44:59.913704
2018-03-28T10:03:52
2018-03-28T10:03:52
99,057,688
0
0
null
null
null
null
UTF-8
Java
false
false
897
java
package coder.aihui.widget; import android.widget.ExpandableListView; /** * @ 创建者 zhou * @ 创建时间 2016/12/28 13:22 * @ 描述 ${能在ScrollView中正常显示的ListView} * @ 更新者 $AUTHOR$ * @ 更新时间 2016/12/28$ * @ 更新描述 ${TODO} */ public class ScrollViewWithExpandListView extends ExpandableListView { public ScrollViewWithExpandListView(android.content.Context context, android.util.AttributeSet attrs) { super(context, attrs); } /** * Integer.MAX_VALUE >> 2,如果不设置,系统默认设置是显示两条 */ public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
[ "892537848@qq.com" ]
892537848@qq.com
d3bc4501e9a30489db5f2fa4a4c37482045c15c9
fb8c9892f34fa8c90aa0a1d41fc85f45616c59ac
/LowonganKerja/src/lowongankerja/LowonganKerja.java
ec1bf614c605d91942b632c2889e0a3a5007045b
[]
no_license
ismadewiliana/Tubes13
d968e369bb9d3813c46b94a250dc913c0e0daf4f
a71c7660eb43d7fd30c0909d569faf39d83089bb
refs/heads/master
2020-12-11T01:46:46.617428
2016-03-26T01:56:32
2016-03-26T01:56:32
54,173,565
0
0
null
2016-03-18T04:23:07
2016-03-18T04:23:06
null
UTF-8
Java
false
false
452
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 lowongankerja; /** * * @author adhis */ public class LowonganKerja { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
[ "adhis@DESKTOP-FMMUNAK" ]
adhis@DESKTOP-FMMUNAK
c2636a2e787c2ca7e3f7e774df16f7008cd9428b
0bc0fcc30cbe7bcfe336c8ae54b5f8536f4cca55
/src/main/java/cybersoft/java12/crmapp/util/ServletUtils.java
84c433875ab527a77fc9963c375e20cd8fa9ec54
[]
no_license
khanhhuypham/CRM
98cbd8b1d86f291040e040551cde1810c35c1fc2
85f8e1b375c71299ee44e77a7379e1dee0fa8575
refs/heads/master
2023-06-23T22:33:00.617009
2021-07-27T06:56:11
2021-07-27T06:56:11
382,773,678
0
0
null
null
null
null
UTF-8
Java
false
false
253
java
package cybersoft.java12.crmapp.util; public class ServletUtils { // Monitor public static final String MONITOR = "monitorServlet"; // Home public static final String HOME = "homeServlet"; public static final String AUTH = "authServlet"; }
[ "74364700+khanhhuypham@users.noreply.github.com" ]
74364700+khanhhuypham@users.noreply.github.com
004d5ca5d17792b5697b887a6e680460c7123bb8
d3267639a87723c4f92a83ac7b7da397c5fec2d6
/SistemaExperto/src/model/Estudios.java
0ea0bcb17e5165938405148e7e17af08c2d18114
[]
no_license
genzo16/IA-G8-1.2018
bf0fab903eef7160dbe81c40ca7cb1d5f02c32c5
7d2c54b86c6d6a22a5944b89531679ce0c76f83c
refs/heads/master
2020-03-07T14:31:55.161286
2018-06-23T19:40:19
2018-06-23T19:40:19
127,528,815
1
0
null
null
null
null
UTF-8
Java
false
false
228
java
package model; public class Estudios implements GUIFriendly { @Override public void grabFromGUI() { // TODO Auto-generated method stub } @Override public void pushToGUI() { // TODO Auto-generated method stub } }
[ "john.fraser.s@gmail.com" ]
john.fraser.s@gmail.com
0eadbca9f6b18067562d75f2fc0f889585f71867
d8e772cc19013498bf2c63dd9ed6f102bcce64e7
/src/main/java/com/project/service/MedicalService.java
23e626f8920d7e05c33e120c2d7692d6c6fab9ae
[]
no_license
elizapinteala/project_JAVA_Adoption
e21029f8a2183eb32efb17d780a187d76455812e
2b8ec0098c12eac77492a71009cfae66e71181c4
refs/heads/master
2023-02-15T08:26:06.309300
2021-01-15T08:48:48
2021-01-15T08:48:48
329,856,963
0
0
null
null
null
null
UTF-8
Java
false
false
4,387
java
package com.project.service; import com.project.entity.AdoptionEntity; import com.project.entity.AnimalEntity; import com.project.entity.MedicalEntity; import com.project.entity.VetEntity; import com.project.exception.AdoptionException; import com.project.exception.AnimalException; import com.project.exception.PersonException; import com.project.model.MedicalModel; import com.project.repo.AnimalRepository; import com.project.repo.MedicalRepository; import com.project.repo.VetRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.server.ResponseStatusException; import java.time.LocalDate; import java.util.Optional; @Service public class MedicalService { @Autowired private MedicalRepository medicalRepository; @Autowired private AnimalRepository animalRepository; @Autowired private VetRepository vetRepository; public MedicalService(MedicalRepository medicalRepository, AnimalRepository animalRepository, VetRepository vetRepository) { this.medicalRepository = medicalRepository; this.animalRepository = animalRepository; this.vetRepository = vetRepository; } public MedicalEntity modelToEntity(MedicalModel medicalModel){ if(medicalModel!=null) { MedicalEntity medicalEntity = new MedicalEntity(); medicalEntity.setIdMedical(medicalModel.getIdMedical()); medicalEntity.setChartDate(LocalDate.now()); medicalEntity.setDisease(medicalModel.getDisease()); medicalEntity.setMedication(medicalModel.getMedication()); medicalEntity.setAnimalEntity(animalRepository.findByIdAnimal(medicalModel.getIdAnimal()).orElse(null)); medicalEntity.setVetEntity(vetRepository.findByIdVet(medicalModel.getIdVet()).orElse(null)); return medicalEntity; } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } } @Transactional public MedicalEntity saveMedical(MedicalModel medicalModel){ int ok=0; MedicalEntity medicalEntity = modelToEntity(medicalModel); if(medicalEntity!=null){ AnimalEntity animalEntity=animalRepository.findByIdAnimal(medicalModel.getIdAnimal()).orElse(null); if(animalEntity!=null){ VetEntity vetEntity =vetRepository.findByIdVet(medicalModel.getIdVet()).orElse(null); if(vetEntity!=null){ medicalEntity.setIdMedical(medicalModel.getIdMedical()); medicalEntity.setChartDate(LocalDate.now()); medicalEntity.setDisease(medicalModel.getDisease()); medicalEntity.setMedication(medicalModel.getMedication()); medicalEntity.setAnimalEntity(animalRepository.findByIdAnimal(medicalModel.getIdAnimal()).orElse(null)); medicalEntity.setVetEntity(vetRepository.findByIdVet(medicalModel.getIdVet()).orElse(null)); ok=1; } else { throw PersonException.personNotFound(); } } else { throw AnimalException.animalNotFound(); } } else{ throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } if(ok==1){ return medicalRepository.save(medicalEntity); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } } public Optional<MedicalEntity> getChartById(Integer id){ Optional<MedicalEntity> medicalEntity = medicalRepository.findById(id); if(medicalEntity == null){ throw new ResponseStatusException(HttpStatus.NOT_FOUND); } else { return medicalEntity;} } @Transactional public void removeChart(Integer id){ Optional<MedicalEntity> medicalEntity = medicalRepository.findById(id); if(medicalEntity != null){ medicalRepository.deleteById(id); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } } }
[ "elizapintela@gmail.com" ]
elizapintela@gmail.com
364916a55ab427644aa589287f034d0974f0dae5
3f2fe92f11fe6a012ea87936bedbeb08fd392a1a
/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/SubmissionController.java
c92df75d092ad93d8e547b0922574089643de0b5
[]
no_license
pulipulichen/dspace-dlll
bbb61aa528876e2ce4908fac87bc9b2323baac3c
e9379176291c171c19573f7f6c685b6dc995efe1
refs/heads/master
2022-08-22T21:15:12.751565
2022-07-12T14:50:10
2022-07-12T14:50:10
9,954,185
1
1
null
null
null
null
UTF-8
Java
false
false
50,693
java
/* * SubmissionController.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.webui.servlet; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.util.SubmissionInfo; import org.dspace.app.util.SubmissionStepConfig; import org.dspace.app.util.Util; import org.dspace.app.webui.submit.JSPStepManager; import org.dspace.app.webui.util.FileUploadRequest; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.WorkspaceItem; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.workflow.WorkflowItem; import org.dspace.submit.AbstractProcessingStep; import org.dspace.submit.step.UploadStep; /** * Submission Manager servlet for DSpace. Handles the initial submission of * items, as well as the editing of items further down the line. * <p> * Whenever the submit servlet receives a GET request, this is taken to indicate * the start of a fresh new submission, where no collection has been selected, * and the submission process is started from scratch. * <p> * All other interactions happen via POSTs. Part of the post will normally be a * (hidden) "step" parameter, which will correspond to the form that the user * has just filled out. If this is absent, step 0 (select collection) is * assumed, meaning that it's simple to place "Submit to this collection" * buttons on collection home pages. * <p> * According to the step number of the incoming form, the values posted from the * form are processed (using the process* methods), and the item updated as * appropriate. The servlet then forwards control of the request to the * appropriate JSP (from jsp/submit) to render the next stage of the process or * an error if appropriate. Each of these JSPs may require that attributes be * passed in. Check the comments at the top of a JSP to see which attributes are * needed. All submit-related forms require a properly initialised * SubmissionInfo object to be present in the the "submission.info" attribute. * This holds the core information relevant to the submission, e.g. the item, * personal workspace or workflow item, the submitting "e-person", and the * target collection. * <p> * When control of the request reaches a JSP, it is assumed that all checks, * interactions with the database and so on have been performed and that all * necessary information to render the form is in memory. e.g. The * SubmitFormInfo object passed in must be correctly filled out. Thus the JSPs * do no error or integrity checking; it is the servlet's responsibility to * ensure that everything is prepared. The servlet is fairly diligent about * ensuring integrity at each step. * <p> * Each step has an integer constant defined below. The main sequence of the * submission procedure always runs from 0 upwards, until SUBMISSION_COMPLETE. * Other, not-in-sequence steps (such as the cancellation screen and the * "previous version ID verification" screen) have numbers much higher than * SUBMISSION_COMPLETE. These conventions allow the progress bar component of * the submission forms to render the user's progress through the process. * * @see org.dspace.app.util.SubmissionInfo * @see org.dspace.app.util.SubmissionConfig * @see org.dspace.app.util.SubmissionStepConfig * @see org.dspace.app.webui.submit.JSPStepManager * * @author Tim Donohue * @version $Revision$ */ public class SubmissionController extends DSpaceServlet { // Steps in the submission process /** Selection collection step */ public static final int SELECT_COLLECTION = 0; /** First step after "select collection" */ public static final int FIRST_STEP = 1; /** For workflows, first step is step #0 (since Select Collection is already filtered out) */ public static final int WORKFLOW_FIRST_STEP = 0; /** path to the JSP shown once the submission is completed */ private static String COMPLETE_JSP = "/submit/complete.jsp"; /** log4j logger */ private static Logger log = Logger .getLogger(SubmissionController.class); /** Configuration of current step in Item Submission Process */ private SubmissionStepConfig currentStepConfig; protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /* * Possible GET parameters: * * resume= <workspace_item_id> - Resumes submitting the given workspace * item * * workflow= <workflow_id> - Starts editing the given workflow item in * workflow mode * * With no parameters, doDSGet() just calls doDSPost(), which continues * the current submission (if one exists in the Request), or creates a * new submission (if no existing submission can be found). */ // try to get a workspace ID or workflow ID String workspaceID = request.getParameter("resume"); String workflowID = request.getParameter("workflow"); // If resuming a workspace item if (workspaceID != null) { try { // load the workspace item WorkspaceItem wi = WorkspaceItem.find(context, Integer .parseInt(workspaceID)); //load submission information SubmissionInfo si = SubmissionInfo.load(request, wi); //TD: Special case - If a user is resuming a submission //where the submission process now has less steps, then //we will need to reset the stepReached in the database //(Hopefully this will never happen, but just in case!) if(getStepReached(si) >= si.getSubmissionConfig().getNumberOfSteps()) { //update Stage Reached to the last step in the Process int lastStep = si.getSubmissionConfig().getNumberOfSteps()-1; wi.setStageReached(lastStep); //flag that user is on last page of last step wi.setPageReached(AbstractProcessingStep.LAST_PAGE_REACHED); //commit all changes to database immediately wi.update(); context.commit(); //update submission info si.setSubmissionItem(wi); } // start over at beginning of first step setBeginningOfStep(request, true); doStep(context, request, response, si, FIRST_STEP); } catch (NumberFormatException nfe) { log.warn(LogManager.getHeader(context, "bad_workspace_id", "bad_id=" + workspaceID)); JSPManager.showInvalidIDError(request, response, workspaceID, -1); } } else if (workflowID != null) // if resuming a workflow item { try { // load the workflow item WorkflowItem wi = WorkflowItem.find(context, Integer .parseInt(workflowID)); //load submission information SubmissionInfo si = SubmissionInfo.load(request, wi); // start over at beginning of first workflow step setBeginningOfStep(request, true); doStep(context, request, response, si, WORKFLOW_FIRST_STEP); } catch (NumberFormatException nfe) { log.warn(LogManager.getHeader(context, "bad_workflow_id", "bad_id=" + workflowID)); JSPManager .showInvalidIDError(request, response, workflowID, -1); } } else { // otherwise, forward to doDSPost() to do usual processing doDSPost(context, request, response); } } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { //need to find out what type of form we are dealing with String contentType = request.getContentType(); // if multipart form, we have to wrap the multipart request // in order to be able to retrieve request parameters, etc. if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { request = wrapMultipartRequest(request); //also, upload any files and save their contents to Request (for later processing by UploadStep) uploadFiles(context, request); } // Reload submission info from request parameters SubmissionInfo subInfo = getSubmissionInfo(context, request); // a submission info object is necessary to continue if (subInfo == null) { // Work around for problem where people select "is a thesis", see // the error page, and then use their "back" button thinking they // can start another submission - it's been removed so the ID in the // form is invalid. If we detect the "removed_thesis" attribute we // display a friendly message instead of an integrity error. if (request.getSession().getAttribute("removed_thesis") != null) { request.getSession().removeAttribute("removed_thesis"); JSPManager.showJSP(request, response, "/submit/thesis-removed-workaround.jsp"); return; } else { // If the submission info was invalid, throw an integrity error log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } } // First, check for a click on "Cancel/Save" button. if (UIUtil.getSubmitButton(request, "").equals(AbstractProcessingStep.CANCEL_BUTTON)) { // forward user to JSP which will confirm // the cancel/save request. doCancelOrSave(context, request, response, subInfo, currentStepConfig); } // Special case - no InProgressSubmission yet // If no submission, we assume we will be going // to the "select collection" step. else if (subInfo.getSubmissionItem() == null) { // we have just started this submission // (or we have just resumed a saved submission) // do the "Select Collection" step doStep(context, request, response, subInfo, SELECT_COLLECTION); } else // otherwise, figure out the next Step to call! { // Get the current step currentStepConfig = getCurrentStepConfig(request, subInfo); //if user already confirmed the cancel/save request if (UIUtil.getBoolParameter(request, "cancellation")) { // user came from the cancel/save page, // so we need to process that page before proceeding request.setAttribute("collection", subInfo.getCollection(context)); processCancelOrSave(context, request, response, subInfo); } //check for click on "<- Previous" button else if (UIUtil.getSubmitButton(request, "").startsWith( AbstractProcessingStep.PREVIOUS_BUTTON)) { // return to the previous step doPreviousStep(context, request, response, subInfo); } //check for click on Progress Bar else if (UIUtil.getSubmitButton(request, "").startsWith( AbstractProcessingStep.PROGRESS_BAR_PREFIX)) { // jumping to a particular step/page doStepJump(context, request, response, subInfo); } else { // by default, load step class to start // or continue its processing doStep(context, request, response, subInfo, currentStepConfig.getStepNumber()); } } } /** * Forward processing to the specified step. * * @param context * DSpace context * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission * @param stepNumber * The number of the step to perform */ private void doStep(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, int stepNumber) throws ServletException, IOException, SQLException, AuthorizeException { if (subInfo.getSubmissionConfig() != null) { // get step to perform currentStepConfig = subInfo.getSubmissionConfig().getStep(stepNumber); } else { log.fatal(LogManager.getHeader(context, "no_submission_process", "trying to load step=" + stepNumber + ", but submission process is null")); JSPManager.showInternalError(request, response); } // if this is the furthest step the user has been to, save that info if (!subInfo.isInWorkflow() && (currentStepConfig.getStepNumber() > getStepReached(subInfo))) { // update submission info userHasReached(subInfo, currentStepConfig.getStepNumber()); // commit changes to database context.commit(); // flag that we just started this step (for JSPStepManager class) setBeginningOfStep(request, true); } // save current step to request attribute saveCurrentStepConfig(request, currentStepConfig); log.debug("Calling Step Class: '" + currentStepConfig.getProcessingClassName() + "'"); try { JSPStepManager stepManager = JSPStepManager.loadStep(currentStepConfig); //tell the step class to do its processing boolean stepFinished = stepManager.processStep(context, request, response, subInfo); //if this step is not workflow editable, close it //if (currentStepConfig != null && currentStepConfig.isSkip() == true) // stepFinished = true; //if this step is finished, continue to next step if(stepFinished) { // If we finished up an upload, then we need to change // the FileUploadRequest object back to a normal HTTPServletRequest if(request instanceof FileUploadRequest) { request = ((FileUploadRequest)request).getOriginalRequest(); } //retrieve any changes to the SubmissionInfo object subInfo = getSubmissionInfo(context, request); //do the next step! doNextStep(context, request, response, subInfo); } else { //commit & close context context.complete(); } } catch (Exception e) { log.error("Error loading step class'" + currentStepConfig.getProcessingClassName() + "':", e); request.setAttribute("javax.servlet.error.exception", e); JSPManager.showInternalError(request, response); } } /** * Forward processing to the next step. * * @param context * DSpace context * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission */ private void doNextStep(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { // find current Step number int currentStepNum; if (currentStepConfig == null) { currentStepNum = -1; } else { currentStepNum = currentStepConfig.getStepNumber(); } // as long as there are more steps after the current step, // do the next step in the current Submission Process if (subInfo.getSubmissionConfig().hasMoreSteps(currentStepNum)) { // update the current step & do this step currentStepNum++; //flag that we are going to the start of this next step (for JSPStepManager class) setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepNum); } else { //if this submission is in the workflow process, //forward user back to relevant task page if(subInfo.isInWorkflow()) { request.setAttribute("workflow.item", subInfo.getSubmissionItem()); JSPManager.showJSP(request, response, "/mydspace/perform-task.jsp"); } else { // The Submission is COMPLETE!! // save our current Submission information into the Request object saveSubmissionInfo(request, subInfo); // forward to completion JSP showProgressAwareJSP(request, response, subInfo, COMPLETE_JSP); } } } /** * Forward processing to the previous step. This method is called if it is * determined that the "previous" button was pressed. * * @param context * DSpace context * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission */ private void doPreviousStep(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { // find current Step number int currentStepNum; if (currentStepConfig == null) { currentStepNum = -1; } else { currentStepNum = currentStepConfig.getStepNumber(); } //Check to see if we are actually just going to a //previous PAGE within the same step. int currentPageNum = AbstractProcessingStep.getCurrentPage(request); boolean foundPrevious = false; //since there are pages before this one in this current step //just go backwards one page. if(currentPageNum > 1) { //decrease current page number AbstractProcessingStep.setCurrentPage(request, currentPageNum-1); foundPrevious = true; //send user back to the beginning of same step! //NOTE: the step should handle going back one page // in its doPreProcessing() method setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepNum); } // Since we cannot go back one page, // check if there is a step before this step. // If so, go backwards one step else if (currentStepNum > FIRST_STEP) { //need to find a previous step that is VISIBLE to the user! while(currentStepNum>FIRST_STEP) { // update the current step & do this previous step currentStepNum--; //get previous step currentStepConfig = subInfo.getSubmissionConfig().getStep(currentStepNum); if(currentStepConfig.isVisible()) { foundPrevious = true; break; } } if(foundPrevious) { //flag to JSPStepManager that we are going backwards //an entire step request.setAttribute("step.backwards", new Boolean(true)); // flag that we are going back to the start of this step (for JSPStepManager class) setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepNum); } } //if there is no previous, visible step, throw an error! if(!foundPrevious) { log.error(LogManager .getHeader(context, "no_previous_visible_step", "Attempting to go to previous step for step=" + currentStepNum + "." + "NO PREVIOUS VISIBLE STEP OR PAGE FOUND!")); JSPManager.showIntegrityError(request, response); } } /** * Process a click on a button in the progress bar. This jumps to the step * whose button was pressed. * * @param context * DSpace context object * @param request * the request object * @param response * the response object * @param subInfo * SubmissionInfo pertaining to this submission */ public void doStepJump(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { // Find the button that was pressed. It would start with // "submit_jump_". String buttonPressed = UIUtil.getSubmitButton(request, ""); // Now, if the request was a multi-part (file upload), we need to // get the original request back out, as the wrapper causes problems // further down the line. if (request instanceof FileUploadRequest) { FileUploadRequest fur = (FileUploadRequest) request; request = fur.getOriginalRequest(); } int nextStep = -1; // next step to load int nextPage = -1; // page within the nextStep to load if (buttonPressed.startsWith("submit_jump_")) { // Button on progress bar pressed try { // get step & page info (in form: stepNum.pageNum) after // "submit_jump_" String stepAndPage = buttonPressed.substring(12); // split into stepNum and pageNum String[] fields = stepAndPage.split("\\."); // split on period nextStep = Integer.parseInt(fields[0]); nextPage = Integer.parseInt(fields[1]); } catch (NumberFormatException ne) { // mangled number nextStep = -1; nextPage = -1; } // Integrity check: make sure they aren't going // forward or backward too far if (nextStep < FIRST_STEP) { nextStep = -1; nextPage = -1; } // if trying to jump to a step you haven't been to yet if (!subInfo.isInWorkflow() && (nextStep > getStepReached(subInfo))) { nextStep = -1; } } if (nextStep == -1) { // Either no button pressed, or an illegal stage // reached. UI doesn't allow this, so something's // wrong if that happens. log.warn(LogManager.getHeader(context, "integrity_error", UIUtil .getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } else { // save page info to request (for the step to access) AbstractProcessingStep.setCurrentPage(request, nextPage); //flag that we are going back to the start of this step (for JSPStepManager class) setBeginningOfStep(request, true); log.debug("Jumping to Step " + nextStep + " and Page " + nextPage); // do the step (the step should take care of going to // the specified page) doStep(context, request, response, subInfo, nextStep); } } /** * Respond to the user clicking "cancel/save" * from any of the steps. This method first calls * the "doPostProcessing()" method of the step, in * order to ensure any inputs are saved. * * @param context * DSpace context * @param request * current servlet request object * @param response * current servlet response object * @param subInfo * SubmissionInfo object * @param stepConfig * config of step who's page the user clicked "cancel" on. */ private void doCancelOrSave(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, SubmissionStepConfig stepConfig) throws ServletException, IOException, SQLException { // If this is a workflow item, we need to return the // user to the "perform task" page if (subInfo.isInWorkflow()) { request.setAttribute("workflow.item", subInfo.getSubmissionItem()); JSPManager.showJSP(request, response, "/mydspace/perform-task.jsp"); } else { // if no submission has been started, if (subInfo.getSubmissionItem() == null) { // forward them to the 'cancelled' page, // since we haven't created an item yet. JSPManager.showJSP(request, response, "/submit/cancelled-removed.jsp"); } else { // As long as we're not uploading a file, go ahead and SAVE // all of the user's inputs for later try { if (!Class.forName("org.dspace.app.webui.util.FileUploadRequest") .isInstance(request)) { // call post-processing on Step (to save any inputs from JSP) log.debug("Cancel/Save Request: calling processing for Step: '" + currentStepConfig.getProcessingClassName() + "'"); try { // load the step class (using the current class loader) ClassLoader loader = this.getClass().getClassLoader(); Class stepClass = loader .loadClass(currentStepConfig.getProcessingClassName()); // load the JSPStepManager object for this step AbstractProcessingStep step = (AbstractProcessingStep) stepClass .newInstance(); //tell the step class to do its processing (to save any inputs) //but, send flag that this is a "cancellation" setCancellationInProgress(request, true); step.doProcessing(context, request, response, subInfo); //commit & close context context.complete(); } catch (Exception e) { log.error("Error loading step class'" + currentStepConfig.getProcessingClassName() + "':", e); JSPManager.showInternalError(request, response); } }//end if not file upload request } catch(Exception e) { throw new ServletException(e); } // save changes to submission info & step info for JSP saveSubmissionInfo(request, subInfo); saveCurrentStepConfig(request, stepConfig); // forward to cancellation confirmation JSP showProgressAwareJSP(request, response, subInfo, "/submit/cancel.jsp"); } } } /** * Process information from "submission cancelled" page. * This saves the item if the user decided to "cancel & save", * or removes the item if the user decided to "cancel & remove". * * @param context * current DSpace context * @param request * current servlet request object * @param response * current servlet response object * @param subInfo * submission info object */ private void processCancelOrSave(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = UIUtil.getSubmitButton(request, "submit_back"); if (buttonPressed.equals("submit_back")) { // re-load current step at beginning setBeginningOfStep(request, true); doStep(context, request, response, subInfo, currentStepConfig .getStepNumber()); } else if (buttonPressed.equals("submit_remove")) { // User wants to cancel and remove // Cancellation page only applies to workspace items WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem(); wi.deleteAll(); JSPManager.showJSP(request, response, "/submit/cancelled-removed.jsp"); context.complete(); } else if (buttonPressed.equals("submit_keep")) { // Save submission for later - just show message JSPManager.showJSP(request, response, "/submit/saved.jsp"); } else { doStepJump(context, request, response, subInfo); } } // **************************************************************** // **************************************************************** // MISCELLANEOUS CONVENIENCE METHODS // **************************************************************** // **************************************************************** /** * Show a JSP after setting attributes needed by progress bar * * @param request * the request object * @param response * the response object * @param subInfo * the SubmissionInfo object * @param jspPath * relative path to JSP */ private static void showProgressAwareJSP(HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, String jspPath) throws ServletException, IOException { saveSubmissionInfo(request, subInfo); JSPManager.showJSP(request, response, jspPath); } /** * Reloads a filled-out submission info object from the parameters in the * current request. If there is a problem, <code>null</code> is returned. * * @param context * DSpace context * @param request * HTTP request * * @return filled-out submission info, or null */ public static SubmissionInfo getSubmissionInfo(Context context, HttpServletRequest request) throws SQLException, ServletException { SubmissionInfo info = null; // Is full Submission Info in Request Attribute? if (request.getAttribute("submission.info") != null) { // load from cache info = (SubmissionInfo) request.getAttribute("submission.info"); } else { // Need to rebuild Submission Info from Request Parameters if (request.getParameter("workflow_id") != null) { int workflowID = UIUtil.getIntParameter(request, "workflow_id"); info = SubmissionInfo.load(request, WorkflowItem.find(context, workflowID)); } else if(request.getParameter("workspace_item_id") != null) { int workspaceID = UIUtil.getIntParameter(request, "workspace_item_id"); info = SubmissionInfo.load(request, WorkspaceItem.find(context, workspaceID)); } else { //by default, initialize Submission Info with no item info = SubmissionInfo.load(request, null); } // We must have a submission object if after the first step, // otherwise something is wrong! if ((getStepReached(info) > FIRST_STEP) && (info.getSubmissionItem() == null)) { log.warn(LogManager.getHeader(context, "cannot_load_submission_info", "InProgressSubmission is null!")); return null; } if (request.getParameter("bundle_id") != null) { int bundleID = UIUtil.getIntParameter(request, "bundle_id"); info.setBundle(Bundle.find(context, bundleID)); } if (request.getParameter("bitstream_id") != null) { int bitstreamID = UIUtil.getIntParameter(request, "bitstream_id"); info.setBitstream(Bitstream.find(context, bitstreamID)); } // save to Request Attribute saveSubmissionInfo(request, info); }// end if unable to load SubInfo from Request Attribute return info; } /** * Saves the submission info object to the current request. * * @param request * HTTP request * @param si * the current submission info * */ public static void saveSubmissionInfo(HttpServletRequest request, SubmissionInfo si) { // save to request request.setAttribute("submission.info", si); } /** * Get the configuration of the current step from parameters in the request, * along with the current SubmissionInfo object. * If there is a problem, <code>null</code> is returned. * * @param request * HTTP request * @param si * The current SubmissionInfo object * * @return the current SubmissionStepConfig */ public static SubmissionStepConfig getCurrentStepConfig( HttpServletRequest request, SubmissionInfo si) { int stepNum = -1; SubmissionStepConfig step = (SubmissionStepConfig) request .getAttribute("step"); if (step == null) { // try and get it as a parameter stepNum = UIUtil.getIntParameter(request, "step"); // if something is wrong, return null if (stepNum < 0 || si == null || si.getSubmissionConfig() == null) { return null; } else { return si.getSubmissionConfig().getStep(stepNum); } } else { return step; } } /** * Saves the current step configuration into the request. * * @param request * HTTP request * @param step * The current SubmissionStepConfig */ public static void saveCurrentStepConfig(HttpServletRequest request, SubmissionStepConfig step) { // save to request request.setAttribute("step", step); } /** * Checks if the current step is also the first step in the item submission * process. * * @param request * HTTP request * @param si * The current Submission Info * * @return whether or not the current step is the first step */ public static boolean isFirstStep(HttpServletRequest request, SubmissionInfo si) { SubmissionStepConfig step = getCurrentStepConfig(request, si); if ((step != null) && (step.getStepNumber() == FIRST_STEP)) { return true; } else { return false; } } /** * Get whether or not the current step has just begun. This helps determine * if we've done any pre-processing yet. If the step is just started, we * need to do pre-processing, otherwise we should be doing post-processing. * If there is a problem, <code>false</code> is returned. * * @param request * HTTP request * * @return true if the step has just started (and JSP has not been loaded * for this step), false otherwise. */ public static boolean isBeginningOfStep(HttpServletRequest request) { Boolean stepStart = (Boolean) request.getAttribute("step.start"); if (stepStart != null) { return stepStart.booleanValue(); } else { return false; } } /** * Get whether or not the current step has just begun. This helps determine * if we've done any pre-processing yet. If the step is just started, we * need to do pre-processing, otherwise we should be doing post-processing. * If there is a problem, <code>false</code> is returned. * * @param request * HTTP request * @param beginningOfStep * true if step just began */ public static void setBeginningOfStep(HttpServletRequest request, boolean beginningOfStep) { request.setAttribute("step.start", new Boolean(beginningOfStep)); } /** * Get whether or not a cancellation is in progress (i.e. the * user clicked on the "Cancel/Save" button from any submission * page). * * @param request * HTTP request * * @return true if a cancellation is in progress */ public static boolean isCancellationInProgress(HttpServletRequest request) { Boolean cancellation = (Boolean) request.getAttribute("submission.cancellation"); if (cancellation != null) { return cancellation.booleanValue(); } else { return false; } } /** * Sets whether or not a cancellation is in progress (i.e. the * user clicked on the "Cancel/Save" button from any submission * page). * * @param request * HTTP request * @param cancellationInProgress * true if cancellation is in progress */ private static void setCancellationInProgress(HttpServletRequest request, boolean cancellationInProgress) { request.setAttribute("submission.cancellation", new Boolean(cancellationInProgress)); } /** * Return the submission info as hidden parameters for an HTML form on a JSP * page. * * @param context * DSpace context * @param request * HTTP request * @return HTML hidden parameters */ public static String getSubmissionParameters(Context context, HttpServletRequest request) throws SQLException, ServletException { SubmissionInfo si = getSubmissionInfo(context, request); SubmissionStepConfig step = getCurrentStepConfig(request, si); String info = ""; if ((si.getSubmissionItem() != null) && si.isInWorkflow()) { info = info + "<input type=\"hidden\" id=\"workflow_id\" name=\"workflow_id\" value=\"" + si.getSubmissionItem().getID() + "\"/>"; } else if (si.getSubmissionItem() != null) { info = info + "<input type=\"hidden\" id=\"workspace_item_id\" name=\"workspace_item_id\" value=\"" + si.getSubmissionItem().getID() + "\"/>"; } if (si.getBundle() != null) { info = info + "<input type=\"hidden\" id=\"bundle_id\" name=\"bundle_id\" value=\"" + si.getBundle().getID() + "\"/>"; } if (si.getBitstream() != null) { info = info + "<input type=\"hidden\" id=\"bitstream_id\" name=\"bitstream_id\" value=\"" + si.getBitstream().getID() + "\"/>"; } if (step != null) { info = info + "<input type=\"hidden\" id=\"step\" name=\"step\" value=\"" + step.getStepNumber() + "\"/>"; } // save the current page from the current Step Servlet int page = AbstractProcessingStep.getCurrentPage(request); info = info + "<input type=\"hidden\" id=\"page\" name=\"page\" value=\"" + page + "\"/>"; // save the current JSP name to a hidden variable String jspDisplayed = JSPStepManager.getLastJSPDisplayed(request); info = info + "<input type=\"hidden\" id=\"jsp\" name=\"jsp\" value=\"" + jspDisplayed + "\"/>"; return info; } /** * Indicate the user has advanced to the given stage. This will only * actually do anything when it's a user initially entering a submission. It * will only increase the "stage reached" column - it will not "set back" * where a user has reached. Whenever the "stage reached" column is * increased, the "page reached" column is reset to 1, since you've now * reached page #1 of the next stage. * * @param subInfo * the SubmissionInfo object pertaining to the current submission * @param step * the step the user has just reached */ private void userHasReached(SubmissionInfo subInfo, int step) throws SQLException, AuthorizeException, IOException { if (!subInfo.isInWorkflow() && subInfo.getSubmissionItem() != null) { WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem(); if (step > wi.getStageReached()) { wi.setStageReached(step); wi.setPageReached(1); // reset page reached back to 1 (since // it's page 1 of the new step) wi.update(); } } } /** * Find out which step a user has reached in the submission process. If the * submission is in the workflow process, this returns -1. * * @param subInfo * submission info object * * @return step reached */ public static int getStepReached(SubmissionInfo subInfo) { if (subInfo == null || subInfo.isInWorkflow() || subInfo.getSubmissionItem() == null) { return -1; } else { WorkspaceItem wi = (WorkspaceItem) subInfo.getSubmissionItem(); int i = wi.getStageReached(); // Uninitialised workspace items give "-1" as the stage reached // this is a special value used by the progress bar, so we change // it to "FIRST_STEP" if (i == -1) { i = FIRST_STEP; } return i; } } /** * Wraps a multipart form request, so that its attributes and parameters can * still be accessed as normal. * * @return wrapped multipart request object * * @throws ServletException * if there are no more pages in this step */ private HttpServletRequest wrapMultipartRequest(HttpServletRequest request) throws ServletException { HttpServletRequest wrappedRequest; try { // if not already wrapped if (!Class.forName("org.dspace.app.webui.util.FileUploadRequest") .isInstance(request)) { // Wrap multipart request wrappedRequest = new FileUploadRequest(request); return (HttpServletRequest) wrappedRequest; } else { // already wrapped return request; } } catch (Exception e) { throw new ServletException(e); } } /** * Upload any files found on the Request, and save them back as * Request attributes, for further processing by the appropriate user interface. * * @param context * current DSpace context * @param request * current servlet request object */ public void uploadFiles(Context context, HttpServletRequest request) throws ServletException { FileUploadRequest wrapper = null; String filePath = null; InputStream fileInputStream = null; try { // if we already have a FileUploadRequest, use it if (Class.forName("org.dspace.app.webui.util.FileUploadRequest") .isInstance(request)) { wrapper = (FileUploadRequest) request; } else { // Wrap multipart request to get the submission info wrapper = new FileUploadRequest(request); } Enumeration fileParams = wrapper.getFileParameterNames(); while(fileParams.hasMoreElements()) { String fileName = (String) fileParams.nextElement(); File temp = wrapper.getFile(fileName); //if file exists and has a size greater than zero if (temp != null && temp.length() > 0) { // Read the temp file into an inputstream fileInputStream = new BufferedInputStream( new FileInputStream(temp)); filePath = wrapper.getFilesystemName(fileName); // cleanup our temp file temp.delete(); //save this file's info to request (for UploadStep class) request.setAttribute(fileName + "-path", filePath); request.setAttribute(fileName + "-inputstream", fileInputStream); request.setAttribute(fileName + "-description", wrapper.getParameter("description")); } } } catch (Exception e) { // Problem with uploading log.warn(LogManager.getHeader(context, "upload_error", ""), e); throw new ServletException(e); } } }
[ "pulipuli.chen@gmail.com" ]
pulipuli.chen@gmail.com
152efa84c7b8c83cbc1e335110fe9305cf19adf3
88f997d8bb36917a4dcbde5e2dea99d4f6ab6563
/workspace/okwei-myportal/src/main/java/com/okwei/myportal/service/IDistributorMgtService.java
6d20b5250f447ec4593dbe536832a51da00613a6
[]
no_license
cenbow/wd
f68843fec0da31487ce9f8928383d9979a643185
c32f30107cf44dff45027447c0b6f29fc35e571f
refs/heads/master
2021-01-21T17:23:37.337895
2016-12-01T06:57:59
2016-12-01T06:57:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
344
java
package com.okwei.myportal.service; import com.okwei.common.Limit; import com.okwei.common.PageResult; import com.okwei.myportal.bean.vo.DistributorVO; import com.okwei.service.IBaseService; public interface IDistributorMgtService extends IBaseService { PageResult<DistributorVO> getMyDistributors(Long userId, Limit limit); }
[ "okmen.zy@foxmail.com" ]
okmen.zy@foxmail.com
22468290be0b406cd8efa1fef8dc6e65eabc8c96
83a96580f4fb03ea0d720a3db4c60c18a4271b2d
/app/src/main/java/com/example/vinay/bluesample/ServerConnectThread.java
21cdc3605ab712dae1bbd65b5d30fe45b7a4f867
[]
no_license
abhik-setia/Final_project_excalBT
bbbf024a123e068101016aa345a7a5c4e7ca091b
6af089b873ef034a8ec0bff44bb48332752304fd
refs/heads/master
2021-01-16T23:09:46.777097
2016-10-08T20:54:50
2016-10-08T20:54:50
70,154,733
0
0
null
null
null
null
UTF-8
Java
false
false
1,573
java
package com.example.vinay.bluesample; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.util.Log; import java.io.IOException; import java.util.UUID; /** * Created by Dell on 30-Sep-16. */ public class ServerConnectThread extends Thread{ private BluetoothSocket bTSocket; public ServerConnectThread() { } public void acceptConnect(BluetoothAdapter bTAdapter, UUID mUUID) { BluetoothServerSocket temp = null; try { temp = bTAdapter.listenUsingRfcommWithServiceRecord("Service_Name", mUUID); } catch(IOException e) { Log.d("SERVERCONNECT", "Could not get a BluetoothServerSocket:" + e.toString()); } while(true) { try { bTSocket = temp.accept(); Log.d("SERVERCONNECT","server open"); } catch (IOException e) { Log.d("SERVERCONNECT", "Could not accept an incoming connection."); break; } if (bTSocket != null) { try { temp.close(); } catch (IOException e) { Log.d("SERVERCONNECT", "Could not close ServerSocket:" + e.toString()); } break; } } } public void closeConnect() { try { bTSocket.close(); } catch(IOException e) { Log.d("SERVERCONNECT", "Could not close connection:" + e.toString()); } } }
[ "Abhik Setia" ]
Abhik Setia
a6cf01050d836dd7ad960909383ae7711e854d7b
eca2d1cb05abb0903556b23b7056056b6ad07948
/src/com/eclink/hgpj/resource/biz/ZWHSUBService.java
840c7e78b4b5d3f91186d313146cae4e26964431
[]
no_license
wyj365372704/AmphenolBMS_PC
8cca7d8e54284cf799070a6e65421c699003d579
325031a07a382b1d6afe507223601c883a8423b3
refs/heads/master
2021-01-11T05:43:45.220838
2017-03-01T08:57:38
2017-03-01T08:57:38
71,336,264
0
0
null
null
null
null
UTF-8
Java
false
false
635
java
package com.eclink.hgpj.resource.biz; import java.util.List; import java.util.Map; import com.eclink.hgpj.resource.vo.ITMRVAVO; import com.eclink.hgpj.resource.vo.ITMSITVO; import com.eclink.hgpj.resource.vo.MenuVO; import com.eclink.hgpj.resource.vo.ZBMSCTLVO; import com.eclink.hgpj.resource.vo.ZSHPBCHVO; import com.eclink.hgpj.resource.vo.ZSHPHDRVO; import com.eclink.hgpj.resource.vo.ZWHSUBVO; /** * MenuService.java * * @Title: 菜单业务接口 * @Description: * @version 1.0 * @date May 21, 2013 5:12:44 PM * */ public interface ZWHSUBService { public List<ZWHSUBVO> queryZwhsub(ZWHSUBVO vo) throws Exception; }
[ "365372704@qq.com" ]
365372704@qq.com
4134d5d462d3701c1ca94a6b993e553ea7257f61
b4c90edfb9b7fcce6454be5510d6fc6862d23867
/src/java/src/main/java/flatgeobuf/generated/Feature.java
43fce90361943a64f1599944a69cb7868664fae2
[ "ISC" ]
permissive
nubiofs/flatgeobuf
0fa4952a84a7d6ed9f53b3e95e88a01e3daa4d91
18de12e81666c0a5e11956f8182eaeb4a70d84ce
refs/heads/master
2020-06-07T20:43:02.141493
2019-06-13T21:19:46
2019-06-13T21:19:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,313
java
package flatgeobuf.generated; // automatically generated by the FlatBuffers compiler, do not modify import java.nio.*; import java.lang.*; import java.util.*; import com.google.flatbuffers.*; @SuppressWarnings("unused") public final class Feature extends Table { public static Feature getRootAsFeature(ByteBuffer _bb) { return getRootAsFeature(_bb, new Feature()); } public static Feature getRootAsFeature(ByteBuffer _bb, Feature obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; vtable_start = bb_pos - bb.getInt(bb_pos); vtable_size = bb.getShort(vtable_start); } public Feature __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public long fid() { int o = __offset(4); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } public long ends(int j) { int o = __offset(6); return o != 0 ? (long)bb.getInt(__vector(o) + j * 4) & 0xFFFFFFFFL : 0; } public int endsLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } public ByteBuffer endsAsByteBuffer() { return __vector_as_bytebuffer(6, 4); } public ByteBuffer endsInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 6, 4); } public long endss(int j) { int o = __offset(8); return o != 0 ? (long)bb.getInt(__vector(o) + j * 4) & 0xFFFFFFFFL : 0; } public int endssLength() { int o = __offset(8); return o != 0 ? __vector_len(o) : 0; } public ByteBuffer endssAsByteBuffer() { return __vector_as_bytebuffer(8, 4); } public ByteBuffer endssInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 8, 4); } public double coords(int j) { int o = __offset(10); return o != 0 ? bb.getDouble(__vector(o) + j * 8) : 0; } public int coordsLength() { int o = __offset(10); return o != 0 ? __vector_len(o) : 0; } public ByteBuffer coordsAsByteBuffer() { return __vector_as_bytebuffer(10, 8); } public ByteBuffer coordsInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 10, 8); } public int properties(int j) { int o = __offset(12); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; } public int propertiesLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; } public ByteBuffer propertiesAsByteBuffer() { return __vector_as_bytebuffer(12, 1); } public ByteBuffer propertiesInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 12, 1); } public static int createFeature(FlatBufferBuilder builder, long fid, int endsOffset, int endssOffset, int coordsOffset, int propertiesOffset) { builder.startObject(5); Feature.addFid(builder, fid); Feature.addProperties(builder, propertiesOffset); Feature.addCoords(builder, coordsOffset); Feature.addEndss(builder, endssOffset); Feature.addEnds(builder, endsOffset); return Feature.endFeature(builder); } public static void startFeature(FlatBufferBuilder builder) { builder.startObject(5); } public static void addFid(FlatBufferBuilder builder, long fid) { builder.addLong(0, fid, 0L); } public static void addEnds(FlatBufferBuilder builder, int endsOffset) { builder.addOffset(1, endsOffset, 0); } public static int createEndsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addInt(data[i]); return builder.endVector(); } public static void startEndsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } public static void addEndss(FlatBufferBuilder builder, int endssOffset) { builder.addOffset(2, endssOffset, 0); } public static int createEndssVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addInt(data[i]); return builder.endVector(); } public static void startEndssVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } public static void addCoords(FlatBufferBuilder builder, int coordsOffset) { builder.addOffset(3, coordsOffset, 0); } public static int createCoordsVector(FlatBufferBuilder builder, double[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addDouble(data[i]); return builder.endVector(); } public static void startCoordsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } public static void addProperties(FlatBufferBuilder builder, int propertiesOffset) { builder.addOffset(4, propertiesOffset, 0); } public static int createPropertiesVector(FlatBufferBuilder builder, byte[] data) { builder.startVector(1, data.length, 1); for (int i = data.length - 1; i >= 0; i--) builder.addByte(data[i]); return builder.endVector(); } public static void startPropertiesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } public static int endFeature(FlatBufferBuilder builder) { int o = builder.endObject(); return o; } public static void finishFeatureBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); } public static void finishSizePrefixedFeatureBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); } }
[ "bjorn@septima.dk" ]
bjorn@septima.dk
066db435b435a3ef85f14e7c6636eed5e6358058
d731213c48ed1e6f315e667865df4cd148c64dcb
/src/main/java/com/onarandombox/MultiverseAdventure/commands/ResetCommand.java
21e453e58fb5dc453be8d0ba7d3e0293fbde0246
[]
no_license
Multiverse/Multiverse-Adventure
634dbfe88c8f87eea91b9b288f9976292313561a
87c922ede750308aa037c2891a0ab4ff1751eb58
refs/heads/master
2016-09-15T05:51:01.461786
2016-05-03T15:19:11
2016-05-03T15:19:11
2,578,290
13
9
null
2013-01-02T08:55:14
2011-10-14T19:20:53
Java
UTF-8
Java
false
false
2,070
java
package com.onarandombox.MultiverseAdventure.commands; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionDefault; import com.onarandombox.MultiverseAdventure.MultiverseAdventure; import com.onarandombox.MultiverseAdventure.listeners.MVAResetListener; public class ResetCommand extends BaseCommand { public ResetCommand(MultiverseAdventure plugin) { super(plugin); this.setName("Manually trigger a reset of the specified world."); this.setCommandUsage("/mva reset " + ChatColor.GREEN + "[WORLD]"); this.setArgRange(0, 1); this.addKey("mva reset"); this.addKey("mvareset"); this.setPermission("multiverse.adventure.reset", "Manually trigger a reset of the specified world.", PermissionDefault.OP); } @Override public void runCommand(final CommandSender sender, List<String> args) { String world; if (args.isEmpty()) { if (sender instanceof Player) { world = ((Player) sender).getWorld().getName(); } else { sender.sendMessage("If you want me to automatically recognize your world, you'd better be a player ;)"); return; } } else { world = args.get(0); } // checks if (plugin.getCore().getMVWorldManager().getMVWorld(world) == null) { sender.sendMessage("That world doesn't exist!"); return; } if (plugin.getAdventureWorldsManager().getMVAInfo(world) == null) { sender.sendMessage("This world is no AdventureWorld!"); return; } sender.sendMessage("Resetting world '" + world + "'..."); plugin.getAdventureWorldsManager().getMVAInfo(world).resetNow(); MVAResetListener.addTask(world, new Runnable() { public void run() { sender.sendMessage("Finished."); } }); } }
[ "main@main.dd-dns.de" ]
main@main.dd-dns.de
4312ff54d0a834e7d4c80d52112d135b6213e108
2958c01973ed778d526e49cc7273066d06ed1e42
/Code/服务窗代码/asw/trunk/src/test/java/com/alipay/account/ToAlipayPublicAccount.java
7590bbb9e36738a3d866eb5f7a51e64d33998465
[]
no_license
wlxawlx/MyFiles
e2da2e8ec342ab3b642f672bce1a2ba6bba950d0
2225f36efab785d8ff8eaa638b30caec66f46295
refs/heads/master
2021-01-21T11:45:35.991133
2017-08-05T02:31:22
2017-08-05T02:31:22
91,752,829
0
1
null
null
null
null
UTF-8
Java
false
false
4,577
java
/** * <p>Title: package-info.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2013</p> * <p>Company: Alibaba YunOS</p> * @author jinlong.rhj * @date 2015年7月1日 * @version 1.0 */ /** * @author jinlong.rhj * */ package com.alipay.account; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.request.AlipayOpenPublicAccountCreateRequest; import com.alipay.api.request.AlipayOpenPublicAccountDeleteRequest; import com.alipay.api.request.AlipayOpenPublicAccountQueryRequest; import com.alipay.api.request.AlipayOpenPublicAccountResetRequest; import com.alipay.api.response.AlipayOpenPublicAccountCreateResponse; import com.alipay.api.response.AlipayOpenPublicAccountDeleteResponse; import com.alipay.api.response.AlipayOpenPublicAccountQueryResponse; import com.alipay.api.response.AlipayOpenPublicAccountResetResponse; import com.alipay.factory.AlipayAPIClientFactory; /** * 绑定商户会员号接口 * @author liliang * */ public class ToAlipayPublicAccount{ public static void main(String[] args) { accountCreate(); // accountQuery(); // accountReset(); // accountDelete(); } //添加绑定商户会员号 public static void accountCreate() { AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient(); AlipayOpenPublicAccountCreateRequest request = new AlipayOpenPublicAccountCreateRequest(); request.setBizContent("{\"bind_account_no\":\"test001\",\"display_name\":\"test001\",\"real_name\":\"张三\",\"from_user_id\":\"2088802613423222\",\"remark\":\"备注信息\"}"); AlipayOpenPublicAccountCreateResponse response = null; try { // 使用SDK,调用交易下单接口 response = alipayClient.execute(request); System.out.println(response.getBody()); System.out.println(response.isSuccess()); // 这里只是简单的打印,请开发者根据实际情况自行进行处理 if (null != response && response.isSuccess()) { System.out.println("AgreementId: "+response.getAgreementId()); } } catch (AlipayApiException e) { } } //查询绑定商户会员号 public static void accountQuery() { AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient(); AlipayOpenPublicAccountQueryRequest request = new AlipayOpenPublicAccountQueryRequest(); request.setBizContent("{\"userId\":\"2088802608984030\"}"); AlipayOpenPublicAccountQueryResponse response = null; try { // 使用SDK,调用交易下单接口 response = alipayClient.execute(request); System.out.println(response.getBody()); System.out.println(response.isSuccess()); // 这里只是简单的打印,请开发者根据实际情况自行进行处理 if (null != response && response.isSuccess()) { System.out.println("bindAccount: "+response.getPublicBindAccounts()); } } catch (AlipayApiException e) { } } //重置绑定的商户会员号 public static void accountReset() { AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient(); AlipayOpenPublicAccountResetRequest request = new AlipayOpenPublicAccountResetRequest(); request.setBizContent("{\"bind_account_no\":\"test001\",\"display_name\":\"test001\",\"agreement_id\":\"20160727047733500603\",\"real_name\":\"张三\",\"from_user_id\":\"2088802608984030\",\"remark\":\"备注信息\"}"); AlipayOpenPublicAccountResetResponse response = null; try { // 使用SDK,调用交易下单接口 response = alipayClient.execute(request); System.out.println(response.getBody()); System.out.println(response.isSuccess()); // 这里只是简单的打印,请开发者根据实际情况自行进行处理 if (null != response && response.isSuccess()) { System.out.println("AgreementId: "+response.getAgreementId()); } } catch (AlipayApiException e) { } } //解除绑定的商户会员号 public static void accountDelete() { AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient(); AlipayOpenPublicAccountDeleteRequest request = new AlipayOpenPublicAccountDeleteRequest(); request.setBizContent("{\"agreement_id\":\"20160727047733500603\"}"); AlipayOpenPublicAccountDeleteResponse response = null; try { // 使用SDK,调用交易下单接口 response = alipayClient.execute(request); System.out.println(response.getBody()); System.out.println(response.isSuccess()); // 这里只是简单的打印,请开发者根据实际情况自行进行处理 if (null != response && response.isSuccess()) { } } catch (AlipayApiException e) { } } }
[ "120544593@qq.com" ]
120544593@qq.com
b018efa69b7ef1fafc2c00367002d2577082d52b
f5c3c76446b0e20acef3cfafb9cf322e3f2ecbf3
/jaf-examples-redis/src/test/java/com/jaf/examples/redis/cluster/spring/ClusterPerformanceTests.java
041a86b610995c69d394665cfa44851ca3f9e10f
[ "MIT" ]
permissive
walle-liao/jaf-examples
05df8673623eb92547952598abe9b215b4e6c3ab
bb6e2222bf5d89fe134843159e78fc2c7cb82c02
refs/heads/master
2021-10-12T01:38:08.786458
2021-10-05T07:54:09
2021-10-05T07:54:09
60,753,330
4
5
null
null
null
null
UTF-8
Java
false
false
995
java
package com.jaf.examples.redis.cluster.spring; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.jaf.examples.redis.jedis.spring.serializer.KryoSerializer; import com.jaf.examples.redis.performance.Job; import com.jaf.examples.redis.performance.PerformanceTestBase; /** * TODO * * @author liaozhicheng.cn@163.com * @date 2016年7月24日 * @since 1.0 */ public class ClusterPerformanceTests extends ClusterSpringTestBase { @Autowired private KryoSerializer kryoSerializer; @Test public void defaultTest() throws InterruptedException { // 测试使用 redis cluster 的性能 PerformanceTestBase.executeTest(new Job() { @Override public void execute(long index, String threadName) { String key = new StringBuilder(threadName).append("-key-").append(index).toString(); String value = threadName; getConnection().set(kryoSerializer.serialize(key), kryoSerializer.serialize(value)); } }, 20, 20000); } }
[ "liaozhicheng.cn@163.com" ]
liaozhicheng.cn@163.com
5967bdd0c774b63c5ed2c950b415c7a7f1f15a92
e717746332d16eeefe81ecf8f984b3be3ad5cf71
/src/org/app/service/UserService.java
df7c3e1e135f8a6ca5542cc83165ad82e2d5c66c
[]
no_license
bjsbl/Faster
d9ad6738f2df97a3c05fa26381f295883dd070ec
38b9c0e8eb429acced298453e4f4cc301bfdd846
refs/heads/master
2021-01-17T10:23:31.743386
2016-04-26T04:02:46
2016-04-26T04:02:46
27,257,979
0
0
null
null
null
null
UTF-8
Java
false
false
564
java
package org.app.service; import java.util.List; import java.util.Map; import com.fast.annotation.Service; import com.fast.core.base.BaseModel; import com.fast.core.base.FastService; @Service public class UserService extends FastService { public void addRecord(String test) { System.out.println("====addRecordMethod Invoke Success======="); } @Override public int save(BaseModel obj) { // TODO Auto-generated method stub return super.save(obj); } @Override public List<Map<String, Object>> query(BaseModel obj) { return super.query(obj); } }
[ "bj_sbl@163.com" ]
bj_sbl@163.com
55acdc5f629b7311439fe09952960cf755a5d2af
8848f59f3ac18ce5577373c93078c37ffb80b509
/Final402/app/src/main/java/com/example/passagon/final402/passcode3.java
20d8787764dee1bb9fc996e218bac43b320bbb90
[]
no_license
topbannawich/Door-Access-Control-and-Monitoring-System-using-smartphone
307ee051d2036b068a30604ffa43d8b7571e7a0c
7622adf8b3f85c080eda7d222845393d4900fae9
refs/heads/master
2022-11-09T09:53:31.318603
2020-06-28T13:25:36
2020-06-28T13:25:36
275,442,462
0
0
null
null
null
null
UTF-8
Java
false
false
3,529
java
package com.example.passagon.final402; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.goodiebag.pinview.Pinview; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.Random; public class passcode3 extends AppCompatActivity { String passcode; Pinview p; String ans; Context tmp; public DatabaseReference ref; public FirebaseDatabase database; TextView lo, dis; private NotificationManagerCompat notificationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_passcode3); database = FirebaseDatabase.getInstance(); ref = database.getReference("OTP"); notificationManager = NotificationManagerCompat.from(this); p= (Pinview) findViewById(R.id.pinview3); p.setPinViewEventListener(new Pinview.PinViewEventListener() { @Override public void onDataEntered(Pinview pinview, boolean fromUser) { ans = pinview.getValue(); if (ans.equals(PreferenceUtils.getPasscode(passcode3.this))){ // Toast.makeText(passcode3.this, " Invalid :", Toast.LENGTH_SHORT).show(); // String title = editTextTitle.getText().toString(); // String message = editTextMessage.getText().toString(); AlertDialog.Builder builder = new AlertDialog.Builder(passcode3.this); String otp=OTP(6); ref.setValue(otp); builder.setTitle("OTP"); builder.setMessage("your OTP is :"+otp); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Do nothing but close the dialog dialog.dismiss(); finish(); } }); AlertDialog alert = builder.create(); alert.show(); } else { Toast.makeText(passcode3.this, "Passcode Invalid", Toast.LENGTH_SHORT).show(); finish(); Intent intent = getIntent(); startActivity(intent); } } }); } static String OTP(int len) { String ot = ""; // Using numeric values String numbers = "0123456789"; // Using random method Random rndm_method = new Random(); char[] otp = new char[len]; for (int i = 0; i < len; i++) { // Use of charAt() method : to get character value // Use of nextInt() as it is scanning the value as int ot= ot+ numbers.charAt(rndm_method.nextInt(numbers.length())); } return ot; } }
[ "top.bannawich@gmail.com" ]
top.bannawich@gmail.com
2f8ccb38cb9a4aa81eb99cf8bd543871efaa4560
391405d95eb2dadc22d08fc0e088183ef2db037a
/jeethink/src/main/java/com/jeethink/project/monitor/online/mapper/UserOnlineMapper.java
6440e8bd561a15b879f6df118c64b9d82e424a14
[]
no_license
Mandy955/jeethink
bd3b71c50b6203218589522cf4b7c9ff5c6631a2
0cb7f18d0af1e7ea5b556ab2c5f09baabb149aac
refs/heads/master
2023-06-04T19:50:54.615671
2021-06-28T12:04:20
2021-06-28T12:04:20
381,015,260
0
0
null
null
null
null
UTF-8
Java
false
false
1,181
java
package com.jeethink.project.monitor.online.mapper; import java.util.List; import com.jeethink.project.monitor.online.domain.UserOnline; /** * 在线用户 数据层 * * @author jeethink 官方网址:www.jeethink.vip */ public interface UserOnlineMapper { /** * 通过会话序号查询信息 * * @param sessionId 会话ID * @return 在线用户信息 */ public UserOnline selectOnlineById(String sessionId); /** * 通过会话序号删除信息 * * @param sessionId 会话ID * @return 在线用户信息 */ public int deleteOnlineById(String sessionId); /** * 保存会话信息 * * @param online 会话信息 * @return 结果 */ public int saveOnline(UserOnline online); /** * 查询会话集合 * * @param userOnline 会话参数 * @return 会话集合 */ public List<UserOnline> selectUserOnlineList(UserOnline userOnline); /** * 查询过期会话集合 * * @param lastAccessTime 过期时间 * @return 会话集合 */ public List<UserOnline> selectOnlineByExpired(String lastAccessTime); }
[ "woshiwo_jun@126.com" ]
woshiwo_jun@126.com
84c357f264d38dd2bd42dd8c8f16a18888166bbf
35d7385f92e046e9ccf6a5697dc76396d8720244
/Clase03/AprendiendoColecciones/src/pe/uni/aprendiendocolecciones/set/Ejemplo01.java
72cf6a15f1fb01f1bd044981311dbd6989d0812d
[]
no_license
gcoronelc/JAVA-OO-2020-1
81d95e310ceabdd438cb99c12eea016dcd09e8bb
47309db120011e944add50bd3e9ab1bdbee241e3
refs/heads/master
2020-12-07T20:33:35.415018
2020-01-23T13:04:33
2020-01-23T13:04:33
232,795,350
2
0
null
null
null
null
UTF-8
Java
false
false
554
java
package pe.uni.aprendiendocolecciones.set; import java.util.HashSet; import java.util.Set; /** * * @author Gustavo Coronel * @blog gcoronelc.blogspot.pe * @videos youtube.com/c/DesarrollaSoftware */ public class Ejemplo01 { public static void main(String[] args) { Set<String> lista = new HashSet<>(); lista.add("Alianza Lima"); lista.add("Deportiva Barrio"); lista.add("Club de Gustavo"); lista.add("Real Madrid"); lista.add("Real Madrid"); for (String nombre : lista) { System.out.println(nombre); } } }
[ "gcoronelc@gmail.com" ]
gcoronelc@gmail.com
50bd613ed6cc78324350f5e9f2af391324e10763
6e77b0e8149861d9fdb0f2a04f541df540e4ac18
/src/main/java/com/github/yktakaha4/watsonmusic/api/entity/Track.java
90fb0665181b3111b09b7a3a0780acd60c092a73
[]
no_license
yktakaha4/watson-music
d7bb7f8a841b87ad34496e1df28a79bdc09ef3c1
b86d3c65d95714af907ca5bd11424cb6aa23ab2e
refs/heads/master
2020-03-17T10:50:49.126365
2018-05-15T14:22:57
2018-05-15T14:22:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
324
java
package com.github.yktakaha4.watsonmusic.api.entity; import lombok.Data; @Data public class Track { private String trackTag; private String songTitle; private String albumTitle; private String artistName; private String year; private Long playedAt; private String artwork; private TrackTime trackTime; }
[ "yk.takaha4@gmail.com" ]
yk.takaha4@gmail.com
9d4488063b7068b1f7873be8112d9aa19ef4dac4
ee461488c62d86f729eda976b421ac75a964114c
/tags/HtmlUnit-2.17/src/main/java/com/gargoylesoftware/htmlunit/javascript/host/html/HTMLFormElement.java
ce28cb25756ab8f79483c08253c4948439d0fd2b
[ "Apache-2.0" ]
permissive
svn2github/htmlunit
2c56f7abbd412e6d9e0efd0934fcd1277090af74
6fc1a7d70c08fb50fef1800673671fd9cada4899
refs/heads/master
2023-09-03T10:35:41.987099
2015-07-26T13:12:45
2015-07-26T13:12:45
37,107,064
0
1
null
null
null
null
UTF-8
Java
false
false
20,093
java
/* * Copyright (c) 2002-2015 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.javascript.host.html; import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.FORMFIELD_REACHABLE_BY_NEW_NAMES; import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.FORMFIELD_REACHABLE_BY_ORIGINAL_NAME; import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_FORM_ACTION_EXPANDURL; import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_FORM_DISPATCHEVENT_SUBMITS; import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_FORM_REJECT_INVALID_ENCODING; import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_FORM_SUBMIT_FORCES_DOWNLOAD; import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_FORM_USABLE_AS_FUNCTION; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.CHROME; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.FF; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.IE; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sourceforge.htmlunit.corejs.javascript.Context; import net.sourceforge.htmlunit.corejs.javascript.Function; import net.sourceforge.htmlunit.corejs.javascript.Scriptable; import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject; import org.apache.commons.lang3.StringUtils; import com.gargoylesoftware.htmlunit.FormEncodingType; import com.gargoylesoftware.htmlunit.WebAssert; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.FormFieldWithNameHistory; import com.gargoylesoftware.htmlunit.html.HtmlAttributeChangeEvent; import com.gargoylesoftware.htmlunit.html.HtmlButton; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlImage; import com.gargoylesoftware.htmlunit.html.HtmlImageInput; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlSelect; import com.gargoylesoftware.htmlunit.html.HtmlTextArea; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxClasses; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxSetter; import com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser; import com.gargoylesoftware.htmlunit.javascript.host.event.Event; import com.gargoylesoftware.htmlunit.protocol.javascript.JavaScriptURLConnection; /** * A JavaScript object for a Form. * * @version $Revision$ * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a> * @author Daniel Gredler * @author Kent Tong * @author Chris Erskine * @author Marc Guillemot * @author Ahmed Ashour * @author Sudhan Moghe * @author Ronald Brill * @author Frank Danek * * @see <a href="http://msdn.microsoft.com/en-us/library/ms535249.aspx">MSDN documentation</a> */ @JsxClasses({ @JsxClass(domClass = HtmlForm.class, browsers = { @WebBrowser(CHROME), @WebBrowser(FF), @WebBrowser(value = IE, minVersion = 11) }), @JsxClass(domClass = HtmlForm.class, isJSObject = false, browsers = @WebBrowser(value = IE, maxVersion = 8)) }) public class HTMLFormElement extends HTMLElement implements Function { private HTMLCollection elements_; // has to be a member to have equality (==) working /** * Creates an instance. */ @JsxConstructor({ @WebBrowser(CHROME), @WebBrowser(FF) }) public HTMLFormElement() { } /** * {@inheritDoc} */ @Override public void setHtmlElement(final HtmlElement htmlElement) { super.setHtmlElement(htmlElement); final HtmlForm htmlForm = getHtmlForm(); htmlForm.setScriptObject(this); } /** * Returns the value of the JavaScript attribute "name". * @return the value of this attribute */ @JsxGetter public String getName() { return getHtmlForm().getNameAttribute(); } /** * Sets the value of the JavaScript attribute "name". * @param name the new value */ @JsxSetter public void setName(final String name) { WebAssert.notNull("name", name); getHtmlForm().setNameAttribute(name); } /** * Returns the value of the JavaScript attribute "elements". * @return the value of this attribute */ @JsxGetter public HTMLCollection getElements() { if (elements_ == null) { final HtmlForm htmlForm = getHtmlForm(); elements_ = new HTMLCollection(htmlForm, false, "HTMLFormElement.elements") { private boolean filterChildrenOfNestedForms_; @Override protected List<Object> computeElements() { final List<Object> response = super.computeElements(); // it would be more performant to avoid iterating through // nested forms but as it is a corner case of ill formed HTML // the needed refactoring would take too much time // => filter here and not in isMatching as it won't be needed in most // of the cases if (filterChildrenOfNestedForms_) { for (final Iterator<Object> iter = response.iterator(); iter.hasNext();) { final HtmlElement field = (HtmlElement) iter.next(); if (field.getEnclosingForm() != htmlForm) { iter.remove(); } } } response.addAll(htmlForm.getLostChildren()); return response; } @Override protected Object getWithPreemption(final String name) { return HTMLFormElement.this.getWithPreemption(name); } @Override public EffectOnCache getEffectOnCache(final HtmlAttributeChangeEvent event) { return EffectOnCache.NONE; } @Override protected boolean isMatching(final DomNode node) { if (node instanceof HtmlForm) { filterChildrenOfNestedForms_ = true; return false; } return node instanceof HtmlInput || node instanceof HtmlButton || node instanceof HtmlTextArea || node instanceof HtmlSelect; } }; } return elements_; } /** * Returns the value of the JavaScript attribute "length". * Does not count input type=image elements as browsers (IE6, Firfox 1.7) do * (cf <a href="http://msdn.microsoft.com/en-us/library/ms534101.aspx">MSDN doc</a>) * @return the value of this attribute */ @JsxGetter public int getLength() { final int all = getElements().getLength(); final int images = getHtmlForm().getElementsByAttribute("input", "type", "image").size(); return all - images; } /** * Returns the value of the JavaScript attribute "action". * @return the value of this attribute */ @JsxGetter public String getAction() { String action = getHtmlForm().getActionAttribute(); if (getBrowserVersion().hasFeature(JS_FORM_ACTION_EXPANDURL)) { try { action = ((HtmlPage) getHtmlForm().getPage()).getFullyQualifiedUrl(action).toExternalForm(); } catch (final MalformedURLException e) { // nothing, return action attribute } } return action; } /** * Sets the value of the JavaScript attribute "action". * @param action the new value */ @JsxSetter public void setAction(final String action) { WebAssert.notNull("action", action); getHtmlForm().setActionAttribute(action); } /** * Returns the value of the JavaScript attribute "method". * @return the value of this attribute */ @JsxGetter public String getMethod() { return getHtmlForm().getMethodAttribute(); } /** * Sets the value of the JavaScript attribute "method". * @param method the new value */ @JsxSetter public void setMethod(final String method) { WebAssert.notNull("method", method); getHtmlForm().setMethodAttribute(method); } /** * Returns the value of the JavaScript attribute "target". * @return the value of this attribute */ @JsxGetter public String getTarget() { return getHtmlForm().getTargetAttribute(); } /** * Returns the <tt>onsubmit</tt> event handler for this element. * @return the <tt>onsubmit</tt> event handler for this element */ @JsxGetter(@WebBrowser(IE)) public Object getOnsubmit() { return getEventHandlerProp("onsubmit"); } /** * Sets the <tt>onsubmit</tt> event handler for this element. * @param onsubmit the <tt>onsubmit</tt> event handler for this element */ @JsxSetter(@WebBrowser(IE)) public void setOnsubmit(final Object onsubmit) { setEventHandlerProp("onsubmit", onsubmit); } /** * Sets the value of the JavaScript attribute "target". * @param target the new value */ @JsxSetter public void setTarget(final String target) { WebAssert.notNull("target", target); getHtmlForm().setTargetAttribute(target); } /** * Returns the value of the JavaScript attribute "enctype". * @return the value of this attribute */ @JsxGetter public String getEnctype() { final String encoding = getHtmlForm().getEnctypeAttribute(); if (!FormEncodingType.URL_ENCODED.getName().equals(encoding) && !FormEncodingType.MULTIPART.getName().equals(encoding) && !"text/plain".equals(encoding)) { return FormEncodingType.URL_ENCODED.getName(); } return encoding; } /** * Sets the value of the JavaScript attribute "enctype". * @param enctype the new value */ @JsxSetter public void setEnctype(final String enctype) { WebAssert.notNull("encoding", enctype); if (getBrowserVersion().hasFeature(JS_FORM_REJECT_INVALID_ENCODING)) { if (!FormEncodingType.URL_ENCODED.getName().equals(enctype) && !FormEncodingType.MULTIPART.getName().equals(enctype)) { throw Context.reportRuntimeError("Cannot set the encoding property to invalid value: '" + enctype + "'"); } } getHtmlForm().setEnctypeAttribute(enctype); } /** * Returns the value of the JavaScript attribute "encoding". * @return the value of this attribute */ @JsxGetter public String getEncoding() { return getEnctype(); } /** * Sets the value of the JavaScript attribute "encoding". * @param encoding the new value */ @JsxSetter public void setEncoding(final String encoding) { setEnctype(encoding); } private HtmlForm getHtmlForm() { return (HtmlForm) getDomNodeOrDie(); } /** * Submits the form (at the end of the current script execution). */ @JsxFunction public void submit() { final HtmlPage page = (HtmlPage) getDomNodeOrDie().getPage(); final WebClient webClient = page.getWebClient(); final String action = getHtmlForm().getActionAttribute().trim(); if (StringUtils.startsWithIgnoreCase(action, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) { final String js = action.substring(JavaScriptURLConnection.JAVASCRIPT_PREFIX.length()); webClient.getJavaScriptEngine().execute(page, js, "Form action", 0); } else { // download should be done ASAP, response will be loaded into a window later final WebRequest request = getHtmlForm().getWebRequest(null); final String target = page.getResolvedTarget(getTarget()); final boolean forceDownload = webClient.getBrowserVersion().hasFeature(JS_FORM_SUBMIT_FORCES_DOWNLOAD); webClient.download(page.getEnclosingWindow(), target, request, forceDownload, "JS form.submit()"); } } /** * Retrieves a form object or an object from an elements collection. * @param index Integer or String that specifies the object or collection to retrieve. * If this parameter is an integer, it is the zero-based index of the object. * If this parameter is a string, all objects with matching name or id properties are retrieved, * and a collection is returned if more than one match is made * @param subIndex Optional. Integer that specifies the zero-based index of the object to retrieve * when a collection is returned * @return an object or a collection of objects if successful, or null otherwise */ @JsxFunction(@WebBrowser(IE)) public Object item(final Object index, final Object subIndex) { if (index instanceof Number) { return getElements().item(index); } final String name = Context.toString(index); final Object response = getWithPreemption(name); if (subIndex instanceof Number && response instanceof HTMLCollection) { return ((HTMLCollection) response).item(subIndex); } return response; } /** * Resets this form. */ @JsxFunction public void reset() { getHtmlForm().reset(); } /** * Overridden to allow the retrieval of certain form elements by ID or name. * * @param name {@inheritDoc} * @return {@inheritDoc} */ @Override protected Object getWithPreemption(final String name) { if (getDomNodeOrNull() == null) { return NOT_FOUND; } final List<HtmlElement> elements = findElements(name); if (elements.isEmpty()) { return NOT_FOUND; } if (elements.size() == 1) { return getScriptableFor(elements.get(0)); } final HTMLCollection collection = new HTMLCollection(getHtmlForm(), elements) { @Override protected List<Object> computeElements() { return new ArrayList<Object>(findElements(name)); } }; return collection; } private List<HtmlElement> findElements(final String name) { final List<HtmlElement> elements = new ArrayList<>(); addElements(name, getHtmlForm().getHtmlElementDescendants(), elements); addElements(name, getHtmlForm().getLostChildren(), elements); // If no form fields are found, IE and Firefox are able to find img elements by ID or name. if (elements.isEmpty()) { for (final DomNode node : getHtmlForm().getChildren()) { if (node instanceof HtmlImage) { final HtmlImage img = (HtmlImage) node; if (name.equals(img.getId()) || name.equals(img.getNameAttribute())) { elements.add(img); } } } } return elements; } private void addElements(final String name, final Iterable<HtmlElement> nodes, final List<HtmlElement> addTo) { for (final HtmlElement node : nodes) { if (isAccessibleByIdOrName(node, name)) { addTo.add(node); } } } /** * Indicates if the element can be reached by id or name in expressions like "myForm.myField". * @param element the element to test * @param name the name used to address the element * @return <code>true</code> if this element matches the conditions */ private boolean isAccessibleByIdOrName(final HtmlElement element, final String name) { if (element instanceof FormFieldWithNameHistory && !(element instanceof HtmlImageInput)) { if (element.getEnclosingForm() != getHtmlForm()) { return false; // nested forms } if (name.equals(element.getId())) { return true; } final FormFieldWithNameHistory elementWithNames = (FormFieldWithNameHistory) element; if (getBrowserVersion().hasFeature(FORMFIELD_REACHABLE_BY_ORIGINAL_NAME)) { if (name.equals(elementWithNames.getOriginalName())) { return true; } } else if (name.equals(element.getAttribute("name"))) { return true; } if (getBrowserVersion().hasFeature(FORMFIELD_REACHABLE_BY_NEW_NAMES)) { if (elementWithNames.getNewNames().contains(name)) { return true; } } } return false; } /** * Returns the specified indexed property. * @param index the index of the property * @param start the scriptable object that was originally queried for this property * @return the property */ @Override public Object get(final int index, final Scriptable start) { if (getDomNodeOrNull() == null) { return NOT_FOUND; // typically for the prototype } return getElements().get(index, ((HTMLFormElement) start).getElements()); } /** * {@inheritDoc} */ public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if (!getBrowserVersion().hasFeature(JS_FORM_USABLE_AS_FUNCTION)) { throw Context.reportRuntimeError("Not a function."); } if (args.length > 0) { final Object arg = args[0]; if (arg instanceof String) { return ScriptableObject.getProperty(this, (String) arg); } else if (arg instanceof Number) { return ScriptableObject.getProperty(this, ((Number) arg).intValue()); } } return Context.getUndefinedValue(); } /** * {@inheritDoc} */ public Scriptable construct(final Context cx, final Scriptable scope, final Object[] args) { if (!getBrowserVersion().hasFeature(JS_FORM_USABLE_AS_FUNCTION)) { throw Context.reportRuntimeError("Not a function."); } return null; } @Override public boolean dispatchEvent(final Event event) { final boolean result = super.dispatchEvent(event); if (Event.TYPE_SUBMIT.equals(event.getType()) && getBrowserVersion().hasFeature(JS_FORM_DISPATCHEVENT_SUBMITS)) { submit(); } return result; } }
[ "asashour@5f5364db-9458-4db8-a492-e30667be6df6" ]
asashour@5f5364db-9458-4db8-a492-e30667be6df6
a7b4313e3057194ea864d4589f2c4dee248445bc
5f42030a7c0cc8c0e4aa2e942e8e07e753212241
/managent/src/main/java/com/guye/sun/managent/pojo/dto/PermissionDto.java
353d8bb40e53db8f06d0d557b99f3250abf724c8
[]
no_license
cuiyaqiang/springboot_manage
f311409962a8a5fa467f72d921f4be4a358ce0f2
17f4725285b9cc0db1117598c694701111cdc014
refs/heads/master
2020-03-28T16:57:27.318392
2018-10-12T01:26:20
2018-10-12T01:26:20
148,744,823
0
0
null
null
null
null
UTF-8
Java
false
false
1,194
java
package com.guye.sun.managent.pojo.dto; import java.util.List; import com.google.common.collect.Lists; /** * @author Levin */ public class PermissionDto { private Integer id; private Integer menuId; private String name; private String menuName; private Integer paterId; private String op; private List<PermissionDto> children = Lists.newArrayList(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPaterId() { return paterId; } public void setPaterId(Integer paterId) { this.paterId = paterId; } public List<PermissionDto> getChildren() { return children; } public void setChildren(List<PermissionDto> children) { this.children = children; } public String getOp() { return op; } public void setOp(String op) { this.op = op; } public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } }
[ "cuiyaqiang1025@163.com" ]
cuiyaqiang1025@163.com
a25f418482e148511ce04ffa42865cc9bf53419a
73302e68ce662c2baa9989dc077f7b671edc7dbc
/singa-simulation/src/main/java/bio/singa/simulation/model/modules/concentration/specifity/UpdateSpecificity.java
c579b5ea24bd7c7ab636d4c16c6961fff4ffc7b1
[ "MIT", "GPL-1.0-or-later", "GPL-3.0-only" ]
permissive
singa-bio/singa
a5c45309b973a905d70565bb07bcdb765eaad458
839b8a418e52af216367251bed2992803d32bdb1
refs/heads/master
2022-12-08T05:40:05.156523
2020-09-23T09:01:06
2020-09-23T09:01:06
67,585,201
3
2
MIT
2022-11-24T13:44:18
2016-09-07T07:57:26
Java
UTF-8
Java
false
false
1,516
java
package bio.singa.simulation.model.modules.concentration.specifity; import bio.singa.simulation.entities.ChemicalEntity; import bio.singa.simulation.model.modules.concentration.functions.AbstractDeltaFunction; import bio.singa.simulation.model.sections.CellSubsection; import bio.singa.simulation.model.sections.ConcentrationContainer; /** * Determines how fine-grained the updates need to be calculated. There are three levels of specificity: * <ul> * <li> {@link EntitySpecific} - once for every chemical entity in every subsection of a updatable * <li> {@link SectionSpecific} - once for every subsection of a updatable * <li> {@link UpdatableSpecific} - once for every updatable * </ul> * * @author cl */ public interface UpdateSpecificity<DeltaFunctionType extends AbstractDeltaFunction> { /** * Processes a concentration container. * @param container The container. */ void processContainer(ConcentrationContainer container); void processContainer(ConcentrationContainer container, CellSubsection subsection, ChemicalEntity chemicalEntity); /** * Determines all deltas for a Concentration container. * @param container The container. */ void determineDeltas(ConcentrationContainer container); /** * Adds the implementation of a {@link AbstractDeltaFunction} to be calculated during simulation. * @param deltaFunctionType The delta function. */ void addDeltaFunction(DeltaFunctionType deltaFunctionType); }
[ "leberech@hs-mittweida.de" ]
leberech@hs-mittweida.de
eecd90322c49554909280e1b28851b1633c0e508
76f95e358c3c9b4f596bbd4b5c3c45b9c1dcb6c4
/app/src/main/java/com/example/maps1/TaskLoadedCallback.java
c335b9e302d683ef3ac98a46f2d28cb756eff46f
[]
no_license
mcmisalin/Maps
845960b34afa4be6070ccb747cdb0a3b0db18a0b
fd74828b6ece904f6c5bd134711401d3e88a9694
refs/heads/master
2020-07-30T02:21:45.064743
2019-09-23T09:24:51
2019-09-23T09:24:51
210,054,510
0
0
null
null
null
null
UTF-8
Java
false
false
107
java
package com.example.maps1; public interface TaskLoadedCallback { void onTaskDone(Object... values); }
[ "misalin333@gmail.com" ]
misalin333@gmail.com
2266ec6af2e332f87397ce7763fdb083c3498e84
3d73aaf8b4960c5ab95091255da9ad553c89abe6
/EstruturaDeDados_01-2021/exerciciosEstruturasDeDados/src/com/company/Temperatura.java
5e51f0b12027ce70d321b826dd4e2a03f19c3dc7
[]
no_license
diegors-prog/EstruturaDeDados
75084548c43942bf4885aff8dcbdccef1a7a5728
2a6d37f0e5590cbf3f0ff20817acfeaf8318013b
refs/heads/main
2023-07-15T10:17:48.958812
2021-08-21T15:45:15
2021-08-21T15:45:15
398,591,462
0
0
null
null
null
null
UTF-8
Java
false
false
1,081
java
package com.company; import java.util.Scanner; public class Temperatura { public double media; public int maioresMedia = 0; public double semana[] = new double[7]; public void obterTemperatura() { Scanner tc = new Scanner(System.in); for (int i = 0; i < semana.length; i++) { System.out.println("Digite a temperatura do dia "+ (i + 1)); semana[i] = tc.nextInt(); } System.out.println("Dados da semana coletados"); calcularMedia(); System.out.println("Média das temperaturas é: " + media); } public void calcularMedia() { double valor = 0; for (int x = 0; x < semana.length; x++) { valor = valor + semana[x]; } media = valor / semana.length; } public void verificar() { for (int k = 0; k < semana.length; k++) { if (media > semana[k]) { maioresMedia++; } } System.out.println("Durante " + maioresMedia + " dias, a temperatura foi maior que a média"); } }
[ "diegors@rede.ulbra.br" ]
diegors@rede.ulbra.br
6f642b589d813e2d69881a4394f0bec06c69753f
70c8c7bbd9d07612624089b7f7ca22aa61546f70
/spring-data-orientdb-commons/src/main/java/org/springframework/data/orient/commons/repository/query/QueryDslOrientQuery.java
0cff67179662e329b284165e6bc6b454cc8cbfa0
[]
no_license
kespinosa05/spring-data-orientdb
16e7ff43fccd4cb1f5c029138afad4360c19bd70
4dce54863585db08db0cefcf796a0c50b57d5e69
refs/heads/master
2020-04-17T01:09:20.752811
2019-01-29T20:03:16
2019-01-29T20:03:16
166,078,390
0
0
null
2019-01-16T17:05:00
2019-01-16T17:05:00
null
UTF-8
Java
false
false
2,694
java
package org.springframework.data.orient.commons.repository.query; import com.orientechnologies.orient.core.sql.query.OSQLQuery; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import org.springframework.data.orient.commons.core.OrientOperations; import org.springframework.data.repository.query.parser.PartTree; /** * A {@link AbstractOrientQuery} implementation based on a {@link org.springframework.data.repository.query.parser.PartTree}. * * @author Dzmitry_Naskou */ public class QueryDslOrientQuery extends AbstractOrientQuery { /** The domain class. */ private final Class<?> domainClass; /** The tree. */ private final PartTree tree; /** The parameters. */ private final OrientParameters parameters; private final OrientQueryMethod method; /** * Instantiates a new {@link QueryDslOrientQuery} from given {@link OrientQueryMethod} and {@link OrientOperations}. * * @param method the query method * @param operations the orient object template */ public QueryDslOrientQuery(OrientQueryMethod method, OrientOperations operations) { super(method, operations); this.method = method; this.domainClass = method.getEntityInformation().getJavaType(); this.tree = new PartTree(method.getName(), domainClass); this.parameters = method.getParameters(); } /* (non-Javadoc) * @see org.springframework.data.orient.repository.object.query.AbstractOrientQuery#doCreateQuery(java.lang.Object[]) */ @Override @SuppressWarnings("rawtypes") protected OSQLQuery<?> doCreateQuery(Object[] values) { OrientParameterAccessor accessor = new OrientParametersParameterAccessor(parameters, values); OrientQueryCreator creator = new OrientQueryCreator(tree, method, accessor); return new OSQLSynchQuery(creator.createQuery()); } /* (non-Javadoc) * @see org.springframework.data.orient.repository.object.query.AbstractOrientQuery#doCreateCountQuery(java.lang.Object[]) */ @Override @SuppressWarnings("rawtypes") protected OSQLQuery<?> doCreateCountQuery(Object[] values) { OrientParameterAccessor accessor = new OrientParametersParameterAccessor(parameters, values); OrientQueryCreator creator = new OrientCountQueryCreator(tree, method, accessor); return new OSQLSynchQuery(creator.createQuery()); } /* (non-Javadoc) * @see org.springframework.data.orient.repository.object.query.AbstractOrientQuery#isCountQuery() */ @Override protected boolean isCountQuery() { return tree.isCountProjection(); } }
[ "klopez@kruger.com.ec" ]
klopez@kruger.com.ec
d5170e606c0b7811310afeb7872a270a9a9a6050
29afc94a6bcfad40b97473d62371509ce0742c70
/src/main/java/com/example/repository/CSubmissionUrlRepository.java
65e26376b1d8ba5ca26f5179492183ea36975bcc
[]
no_license
asSqr/AtCoderMemory
359080923aad720d38297341c720985cd19d2015
cf6f7d44139fdc152f5e299dc9167cf0a9a6b3d9
refs/heads/master
2022-12-23T18:56:09.400202
2020-09-26T14:37:17
2020-09-26T14:37:17
298,637,507
0
0
null
null
null
null
UTF-8
Java
false
false
379
java
package com.example.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.example.model.CSubmissionUrl; @Repository public interface CSubmissionUrlRepository extends JpaRepository<CSubmissionUrl, String> { public List<CSubmissionUrl> findByCardsUuid( String uuid ); }
[ "ryo.yossy@live.jp" ]
ryo.yossy@live.jp
f1701df03f8e637259c1ff5a030d736c922ae066
7c4997a7f8d63463293c870bd8d93d8e3dd98e7c
/src/main/java/com/ex/webservices/restfulWS/jwt/JwtUnAuthorizedResponseAuthenticationEntryPoint.java
42e6f489bcee7471e75af1930a192d1cf9ab02d7
[]
no_license
nik132barinov/restfulWS
682e8dbcc4a30ad860ad7ac6fefde5bebb0b411d
705810e1f1c68fbc2e6c8fda877b9f39df892f28
refs/heads/master
2021-05-18T01:01:40.341781
2020-03-29T13:24:39
2020-03-29T13:24:39
251,037,705
0
0
null
null
null
null
UTF-8
Java
false
false
911
java
package com.ex.webservices.restfulWS.jwt; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Serializable; @Component public class JwtUnAuthorizedResponseAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -8970718410437077606L; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You would need to provide the Jwt Token to Access This resource"); } }
[ "nikitabarinov132@gmail.com" ]
nikitabarinov132@gmail.com
1c6d2b9e8b429067fd5b3a4077ab44f8a25deb61
aa82747a53a55af77c1c7167f850ad889a1ca035
/src/test/java/employee/ut/EmployeeRepositoryTest.java
8ee6fb201870d7295e85fab34efabd852ccb3af9
[]
no_license
nikhil99/wealth-park-project
e88f64a1edb1293eb7e1e1dd8a079ba71200e79b
a8b7f7b3c1b7e609c0ef6fd580bd6caa5b2b49e8
refs/heads/master
2020-06-28T14:42:20.278976
2019-08-05T14:12:02
2019-08-05T14:12:02
200,258,565
0
0
null
null
null
null
UTF-8
Java
false
false
2,620
java
package employee.ut; import employee.data.EmployeeRepository; import employee.data.model.Employee; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import java.util.AbstractList; import java.util.List; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.samePropertyValuesAs; @RunWith(SpringRunner.class) @DataJpaTest public class EmployeeRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private EmployeeRepository employeeRepository; @Test public void getAllEmployees() { addnEmployees(4); // when List<Employee> found = employeeRepository.findAll(); // then Assert.assertThat(found.size(), samePropertyValuesAs(4)); } @Test public void save() { Employee employee = mockEmployee(); entityManager.persist(employee); entityManager.flush(); // when Employee found = employeeRepository.save(employee); // then Assert.assertThat(found, samePropertyValuesAs(employee)); } @Test public void deleteEmployee() { Employee employee = mockEmployee(); entityManager.persist(employee); entityManager.flush(); // found Employee found = employeeRepository.save(employee); // aseert employee exist Assert.assertThat(found, samePropertyValuesAs(employee)); // found employeeRepository.deleteById(employee.getId()); // aseert employee is deleted Assert.assertThat(employeeRepository.findAll().size(), is(0)); } private void addnEmployees(int n) { for (int i = 0; i < n; i++) { Employee employee = new Employee( "Test" + i, "Gulumkar"+i, 3l+i, "Tokyo, Minato-ku"+i, 4l, 8500000d); entityManager.persist(employee); } entityManager.flush(); } private Employee mockEmployee() { return new Employee( "Nikhil", "Gulumkar", new DateTime().withDate(1992,9,25).getMillis(), "Tokyo, Minato-ku", 4L, 8500000d); } }
[ "nikhil.gulumkar@gmail.com" ]
nikhil.gulumkar@gmail.com
2c34ce8627708f09db1ec06197c7e7033e245a7d
147f5c3fb73a3342a7c711775269f29b71ca2938
/src/com/oop/Accounting.java
13be4d2da71766eae959299a98f80c0793abe83e
[]
no_license
Karina-Z/Homework-ATM-3
9c310a37f23782d9f1e779297fe3cd0f9ed4e680
fcb3a7f05b42d131a906a22241414ea9775674f3
refs/heads/master
2020-05-16T13:25:23.935926
2019-05-08T14:41:54
2019-05-08T14:41:54
183,072,189
0
0
null
null
null
null
UTF-8
Java
false
false
137
java
package com.oop; public class Accounting { public double pay(double hours, double amount) { return hours * amount; } }
[ "Karina_Zaporozhets@epam.com" ]
Karina_Zaporozhets@epam.com
985c0f980c5c87d59448d4a43b644671abaf9281
9550e933cedbf5723b6c6dc82be2194615d6aaac
/sourcecode/src/main/java/wang/xiaoluobo/designpattern/composite211/CompositeTest.java
fe635c83f3c807d2f297fb53cef5491be3a9c9a1
[ "Apache-2.0" ]
permissive
P79N6A/learning-2
a7ed4713581aec24e824bca179750f74dbc07d27
4fb6ccaa03a3f6408d4904b24566094eb1881e7f
refs/heads/master
2020-04-27T20:28:07.330905
2019-03-09T06:45:26
2019-03-09T06:45:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
644
java
package wang.xiaoluobo.designpattern.composite211; public class CompositeTest { public static void main(String[] args) { Composite root = new Composite("服装"); Composite c1 = new Composite("男装"); Composite c2 = new Composite("女装"); Leaf leaf1 = new Leaf("衬衫"); Leaf leaf2 = new Leaf("夹克"); Leaf leaf3 = new Leaf("裙子"); Leaf leaf4 = new Leaf("套装"); root.addChild(c1); root.addChild(c2); c1.addChild(leaf1); c1.addChild(leaf2); c2.addChild(leaf3); c2.addChild(leaf4); root.printStruct(""); } }
[ "wangyd1005sy@163.com" ]
wangyd1005sy@163.com