blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
885bda9915f09589738d6a197e3388b34d251eed
5a1bb7df4a9671c18d54d149560246b66e6333fa
/app/src/main/java/com/example/falconp/dndapp/ui/character/CharacterViewModel.java
d1b7a8b2e4ef4affc07f7dff56ef23b51131d45e
[]
no_license
FalconJ/DragonApp
82c6db8494db7027bc936201b41540666b9ec94a
dc71aa941363da42d08f2e8d501cb570d27df029
refs/heads/master
2020-03-17T21:07:15.008499
2018-05-21T05:27:34
2018-05-21T05:27:34
133,943,993
0
0
null
null
null
null
UTF-8
Java
false
false
880
java
package com.example.falconp.dndapp.ui.character; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import com.example.falconp.dndapp.data.DragonRepository; import com.example.falconp.dndapp.data.database.CharacterEntry; import java.util.List; public class CharacterViewModel extends AndroidViewModel { private DragonRepository mRepository; private LiveData<List<CharacterEntry>> mAllCharacters; public CharacterViewModel(Application application){ super(application); mRepository = new DragonRepository(application); mAllCharacters = mRepository.getAllCharacters(); } public LiveData<List<CharacterEntry>> getAllCharacters(){ return mAllCharacters; } public void insert(CharacterEntry character){ mRepository.insert(character); } }
b1a62e57b3e4695e8fb6b792de86cff51e5d4123
552c42b246bef7eb154217d464635358d7e18bad
/serviceDemo/app/src/main/java/com/example/sunny_joy/servicedemo/service/MyService.java
ae5af24eb0990805935e368897f9933bcd1eab63
[]
no_license
enre1008/android
2246077cbcc7c7cc3da1bf5a82748f8727c22238
49a0267d648deda2afc5c369754d5c7bbbdd434c
refs/heads/master
2020-05-08T22:27:14.438340
2019-04-12T08:51:10
2019-04-12T08:51:10
180,969,291
0
0
null
null
null
null
UTF-8
Java
false
false
1,258
java
package com.example.sunny_joy.servicedemo.service; import android.app.Service; import android.content.Intent; import android.nfc.TagLostException; import android.os.IBinder; import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.util.Log; /** * Created by sunny-joy on 2018/6/11. */ public class MyService extends Service { private static final String TAG="MyService"; //只有生命周期的第一次才被调用 @Override public void onCreate() { super.onCreate(); Log.i(TAG, "onCreate"); } @Override public void onDestroy() { Log.i(TAG, "onDestroy"); super.onDestroy(); } //每次startService启动会被调用 @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "onStartCommand"); return super.onStartCommand(intent, flags, startId); } //bindService启动时调用,在整个生命周期中只被调用一次 @Nullable @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind"); return new MyBinder(); //必须返回一个对象,才能表示连接成功了 } class MyBinder extends android.os.Binder{ } }
e10b9e499588935464ae9afe88665e7d7b5ab1e7
2b4df652feb0383b192de78fca3480b430ee4b65
/SplashScreen.java
64668658622ef3e5bc96463881a4acb253ff1970
[]
no_license
aleksandraczarnecka/Breakout
f6fb10f04bf0b83587e31fbdd6979afa942efc6f
75903480a8bc5d70c7d15f537a40c71c98d113b4
refs/heads/master
2021-05-31T16:03:03.444789
2016-01-31T00:36:28
2016-01-31T00:36:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,464
java
/** * Created by SPARK on 2016-01-28. */ import java.awt.*; import java.awt.event.ActionListener; import javax.swing.*; public class SplashScreen extends JWindow { private static JProgressBar progressBar = new JProgressBar(); public static SplashScreen execute; private static int count; private static Timer timer1; public SplashScreen() { Container container = getContentPane(); container.setLayout(null); JPanel panel = new JPanel(); panel.setBorder(new javax.swing.border.EtchedBorder()); panel.setBackground(new Color(255, 255, 255)); panel.setBounds(10, 10, 348, 450); panel.setLayout(null); container.add(panel); JLabel label = new JLabel("Welcome to Breakout!"); label.setFont(new Font("Verdana", Font.BOLD, 14)); label.setBounds(85, 25, 280, 30); panel.add(label); JLabel label2 = new JLabel("Button Introduction"); label2.setFont(new Font("Verdana", Font.BOLD, 14)); label2.setBounds(85, 45, 280, 30); panel.add(label2); JLabel label3 = new JLabel("Q : Quit Game"); label3.setFont(new Font("Verdana", Font.BOLD, 14)); label3.setBounds(75, 75, 280, 30); panel.add(label3); JLabel label4 = new JLabel("ESC : Pause Game"); label4.setFont(new Font("Verdana", Font.BOLD, 14)); label4.setBounds(75, 95, 280, 30); panel.add(label4); JLabel label5 = new JLabel("SPACE BAR : Start Game"); label5.setFont(new Font("Verdana", Font.BOLD, 14)); label5.setBounds(75, 115, 280, 30); panel.add(label5); JLabel label6 = new JLabel("A : Increase Ball Size"); label6.setFont(new Font("Verdana", Font.BOLD, 14)); label6.setBounds(75, 135, 280, 30); panel.add(label6); JLabel label7 = new JLabel("S : Decrease Ball Size"); label7.setFont(new Font("Verdana", Font.BOLD, 14)); label7.setBounds(75, 155, 280, 30); panel.add(label7); JLabel label8 = new JLabel("D : Increase Paddle Width"); label8.setFont(new Font("Verdana", Font.BOLD, 14)); label8.setBounds(75, 175, 280, 30); panel.add(label8); JLabel label9 = new JLabel("F : Decrease Paddle Width"); label9.setFont(new Font("Verdana", Font.BOLD, 14)); label9.setBounds(75, 195, 280, 30); panel.add(label9); JLabel label13 = new JLabel("G : Increase Ball Speed"); label13.setFont(new Font("Verdana", Font.BOLD, 14)); label13.setBounds(75, 215, 280, 30); panel.add(label13); JLabel label14 = new JLabel("H : Decrease Ball Speed"); label14.setFont(new Font("Verdana", Font.BOLD, 14)); label14.setBounds(75, 235, 280, 30); panel.add(label14); JLabel label15 = new JLabel("(Set Speed of Ball before Game Starts)"); label15.setFont(new Font("Verdana", Font.BOLD, 10)); label15.setBounds(75, 250, 280, 30); panel.add(label15); JLabel label10 = new JLabel("1~9: Set Level 1~9"); label10.setFont(new Font("Verdana", Font.BOLD, 14)); label10.setBounds(75, 285, 280, 30); panel.add(label10); JLabel label11 = new JLabel("0: Set to Max Level"); label11.setFont(new Font("Verdana", Font.BOLD, 14)); label11.setBounds(75, 305, 280, 30); panel.add(label11); JLabel label12 = new JLabel("(Press ESC to re-start with selected level)"); label12.setFont(new Font("Verdana", Font.BOLD, 10)); label12.setBounds(75, 325, 280, 30); panel.add(label12); JLabel label20 = new JLabel("Built by Sang Min Park, 20339192"); label20.setFont(new Font("Verdana", Font.BOLD, 10)); label20.setBounds(75, 400, 280, 30); panel.add(label20); progressBar.setMaximum(100); progressBar.setBounds(55, 480, 250, 15); container.add(progressBar); loadProgressBar(); setSize(370, 515); setLocationRelativeTo(null); setVisible(true); } private void loadProgressBar() { ActionListener al = new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { count++; progressBar.setValue(count); if (count%10 == 0) System.out.println(count); if (count == 100) { createFrame(); execute.setVisible(false); //swapped this around with timer1.stop() timer1.stop(); } } private void createFrame() throws HeadlessException { ////////////////////////////////////////////////////////////////////// JFrame frame = new JFrame("Breakout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1280, 740); frame.setMinimumSize(new Dimension(1280, 740)); frame.setLayout(new BorderLayout()); frame.setLocationRelativeTo(null); Breakout game = new Breakout(1280, 720); frame.add(game, BorderLayout.CENTER); frame.setVisible(true); ////////////////////////////////////////////////////////////////////// } }; timer1 = new Timer(100, al); timer1.start(); } };
c422fb07f196799e0852d12b3546f6c5348a312d
cfa35b90ea92b386543d629cf060b4d02ccba6e3
/app/src/main/java/com/digibarber/app/activities/EditProfileActivity.java
99e86b34ebbb9b30646c5fe180512e2e73928cb6
[]
no_license
KoderAndrey/digibarber-digibarber-partner
629dc317a9495cd60532662dfeb8ea4ffa3db6db
10ac30fbf04b16f222867c0c6daf4d22f583a422
refs/heads/master
2023-01-13T05:55:14.084837
2020-11-14T11:11:54
2020-11-14T11:11:54
309,145,621
0
0
null
null
null
null
UTF-8
Java
false
false
7,084
java
package com.digibarber.app.activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.ImageView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyLog; import com.android.volley.error.AuthFailureError; import com.android.volley.error.VolleyError; import com.android.volley.request.StringRequest; import com.digibarber.app.CustomClasses.AppController; import com.digibarber.app.CustomClasses.BaseActivity; import com.digibarber.app.CustomClasses.ConnectivityReceiver; import com.digibarber.app.CustomClasses.Constants; import com.digibarber.app.Interfaces.ApiCallback; import com.digibarber.app.R; import com.digibarber.app.apicalls.ApiClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class EditProfileActivity extends BaseActivity implements View.OnClickListener { private ImageView btn_edit_Services; private ImageView btn_gallery_images; private ImageView btn_change_open_hours; private ImageView btn_change_private_info; private ImageView view_text; private String mobile; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window window = getWindow(); setContentView(R.layout.edit_profile_activity); mobile = getIntent().getStringExtra("mobile"); btn_change_private_info = (ImageView) findViewById(R.id.btn_change_private_info); btn_edit_Services = (ImageView) findViewById(R.id.btn_edit_Services); btn_gallery_images = (ImageView) findViewById(R.id.btn_gallery_images); btn_change_open_hours = (ImageView) findViewById(R.id.btn_change_open_hours); view_text = (ImageView) findViewById(R.id.view_text); btn_change_private_info.setOnClickListener(this); btn_edit_Services.setOnClickListener(this); btn_gallery_images.setOnClickListener(this); btn_change_open_hours.setOnClickListener(this); view_text.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); loadProfileData(); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } /* Back click */ public void backClick(View v) { Intent it = new Intent(EditProfileActivity.this, HomeActivity.class); startActivity(it); finish(); } @Override public void onBackPressed() { Intent it = new Intent(EditProfileActivity.this, HomeActivity.class); startActivity(it); finish(); } public void loadProfileData() { ApiClient.getInstance().getBarberProfile(this, prefs, new ApiCallback() { @Override public void onSuccess() { } @Override public void onFailure() { } }); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_change_private_info: Intent it = new Intent(EditProfileActivity.this, ChangePrivateInformationActivity.class); startActivity(it); break; case R.id.btn_edit_Services: try { String services = prefs.getString(Constants.KEY_SERVICES, ""); if (!services.equalsIgnoreCase("")) { JSONArray jaService = new JSONArray(services); JSONObject joHair = new JSONObject(); JSONObject joBeard = new JSONObject(); JSONObject joPamper = new JSONObject(); JSONObject joMiscellnous = new JSONObject(); JSONObject joMobile = new JSONObject(); for (int i = 0; i < jaService.length(); i++) { if (i == 0) { joHair = jaService.getJSONObject(i); } else if (i == 1) { joBeard = jaService.getJSONObject(i); } else if (i == 2) { joPamper = jaService.getJSONObject(i); } else if (i == 3) { joMiscellnous = jaService.getJSONObject(i); } else if (i == 4) { joMobile = jaService.getJSONObject(i); } } it = new Intent(EditProfileActivity.this, ServiceListActivity.class); it.putExtra("From", "EditProfile"); it.putExtra("joHair", joHair.toString()); it.putExtra("joBeard", joBeard.toString()); it.putExtra("joPamper", joPamper.toString()); it.putExtra("joMiscellaneous", joMiscellnous.toString()); it.putExtra("joMobile", joMobile.toString()); startActivityForResult(it, 1); } else { it = new Intent(EditProfileActivity.this, ServiceListActivity.class); it.putExtra("From", "EditProfile"); startActivityForResult(it, 1); } } catch (Exception e) { } break; case R.id.btn_gallery_images: String gallery = prefs.getString(Constants.KEY_GALLERY_IMAGES, ""); it = new Intent(EditProfileActivity.this, AddGalleryImagesActivity.class); it.putExtra("galleryImages", gallery); it.putExtra("From", "EditProfile"); startActivity(it); break; case R.id.btn_change_open_hours: String openHours = prefs.getString(Constants.KEY_OPEN_HOURS, ""); it = new Intent(EditProfileActivity.this, AddOpenHoursActivity.class); it.putExtra("openHours", openHours); it.putExtra("From", "EditProfile"); startActivity(it); break; case R.id.view_text: Intent intent = new Intent(EditProfileActivity.this, ViewActivity.class); startActivity(intent); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 1) { // getBarberProfile(); } } } }
[ "I&LqJz0E" ]
I&LqJz0E
69fb76038bde154a47f91bb23ab5fcb4515ccff8
ddd6a6d33c4bf638d8130721d35ac586ea0d1c45
/src/main/java/com/techstack/designpatterns/behavioral/chainofresponsibility/OutForDeliveryYard.java
03d1f3cbb954e68389e6f568699db7598ddce124
[]
no_license
sudheerrachuri/LearnDesignPatterns
ef122af1dbd307fb379cc26db2ff01e0a15f267d
a6238251ced5f2c7943e654495df933e8159f757
refs/heads/master
2022-01-31T17:17:55.026458
2019-07-22T14:00:04
2019-07-22T14:00:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
546
java
/** * */ package com.techstack.designpatterns.behavioral.chainofresponsibility; import com.techstack.designpatterns.behavioral.chainofresponsibility.vo.Car; /** * @author Karthikeyan N * */ public class OutForDeliveryYard implements Stage { @Override public void previousStage() { // TODO Auto-generated method stub } @Override public void prepare(Car car) { System.out.println("Congrats! All set, your car has been out for delivery"); } @Override public void nextStage() { // TODO Auto-generated method stub } }
3ab0aff98867c9d7e5c8321d364ce13611e0ff5e
9c7ce5b2af7e3c7f23eb8800e862560876dfa45d
/Spark/ParameterCombos.java
3546aa43f4fe3c09bc7984e06bf0080791fafe97
[]
no_license
jeffyjahfar/NeuralNetworks_MASS
3242a458e62fde7be0ed693a39c3eb83eea3e45c
ea5a393afa0abc920126f096d10500a7fdbbebcb
refs/heads/master
2021-01-08T09:17:43.335854
2020-02-20T20:47:30
2020-02-20T20:47:30
241,983,031
1
0
null
null
null
null
UTF-8
Java
false
false
4,491
java
import java.io.Serializable; import java.util.ArrayList; public class ParameterCombos implements Serializable { /** * Neural Network Parameters: * -------------------------- * 1) Learning rate * 2) Number of iterations * 3) Number of hidden layers * 4) Size of hidden layers (all are the same size for simplicity) */ public class Combo implements Serializable { Double learningRate; Integer numIterations; Integer numHiddenLayers; Integer hiddenLayerSize; public Combo ( Double learningRate, Integer numIterations, Integer numHiddenLayers, Integer hiddenLayerSize ) { this.learningRate = learningRate; this.numIterations = numIterations; this.numHiddenLayers = numHiddenLayers; this.hiddenLayerSize = hiddenLayerSize; } public void print(){ System.out.println("******* MAX ACCURACY PARAMETERS ********"); System.out.println("learningRate = "+ learningRate); System.out.println("numIterations = "+ numIterations); System.out.println("numHiddenLayers = "+ numHiddenLayers); System.out.println("hiddenLayerSize = "+ hiddenLayerSize); } } ArrayList<Combo> combos; public ParameterCombos() { this( // Learning Rate related params: 0.01, // learningRateMin 0.5, // learningRateMax 0.1, // learningRateStep // Number of iterations related params: 3, // numIterationsMin 3, // numIterationsMax 1, //numIterationStep // Number of hidden layer related params: 2, // numHiddenLayersMin 6, //numHiddenLayersMax 2, // numHiddenLayersStep // Hidden layer 50, // hiddenLayerSizeMin 200, // hiddenLayerSizeMax 50 // hiddenLayerSizeStep ); } public ParameterCombos( // Learning Rate related params: double learningRateMin, double learningRateMax, double learningRateStep, // Number of iterations related params: int numIterationsMin, int numIterationsMax, int numIterationStep, // Number of hidden layer related params: int numHiddenLayersMin, int numHiddenLayersMax, int numHiddenLayersStep, // Hidden layer int hiddenLayerSizeMin, int hiddenLayerSizeMax, int hiddenLayerSizeStep ) { combos = new ArrayList<Combo>(); ArrayList<Integer> numIterationOptions = new ArrayList<Integer>(); for ( double learningRate = learningRateMin; learningRate <= learningRateMax; learningRate += learningRateStep ) { for ( int numIterations = numIterationsMin; numIterations <= numIterationsMax; numIterations += numIterationStep ) { for ( int numHiddenLayers = numHiddenLayersMin; numHiddenLayers <= numIterationsMax; numHiddenLayers += numHiddenLayersStep ) { for ( int hiddenLayerSize = hiddenLayerSizeMin; hiddenLayerSize <= hiddenLayerSizeMax; hiddenLayerSize += hiddenLayerSizeStep ) { // Combo combo = new Combo( learningRate, numIterations, numHiddenLayers, hiddenLayerSize ); combos.add(combo); } } } } } public static void main(String[] args) { ParameterCombos paramCombos = new ParameterCombos(); // System.out.println(paramCombos.combos.size()); // System.out.println(paramCombos.combos.get(0).numIterations); // System.out.println(paramCombos.combos.get(10).numIterations); } }
86d93985c42db9e8ae581d9dd639d5d01f0e2116
052c3faff839100b941c13508af8b3b3a94827e3
/src/main/java/com/ironyard/repositories/AddressRepo.java
7842f7dc11411c2ec22b667b62df5ad634d959a6
[]
no_license
osmancano/HWork15
2c1bfcc44225f59d3e47f41eb2d267ca95f7ca6f
e4896aae21747e01b77b2b1bbe413739ea5f7c5a
refs/heads/master
2021-01-11T09:29:54.784336
2017-02-07T13:50:50
2017-02-07T13:50:50
81,213,068
0
0
null
null
null
null
UTF-8
Java
false
false
244
java
package com.ironyard.repositories; import com.ironyard.data.Address; import org.springframework.data.repository.CrudRepository; /** * Created by osmanidris on 2/5/17. */ public interface AddressRepo extends CrudRepository<Address, Long>{ }
3d63ed18e4be9099a8047302da6f07109ffbaf97
4894fc77f40cf3aa89c7d2d92bd2ec43c9c9cc0a
/university/src/test/java/university/service/DepartmentServiceTest.java
522c0043b67ef3f8399b12ec23c40cd5819b4e89
[]
no_license
olexandra-dmytrenko/PetitProjects
1e4b059199f240263de59dab592cd00cbdcf0212
c7e0b287a8a14f6382edf593bc245a8adef247b0
refs/heads/master
2021-07-06T11:14:21.707049
2021-03-15T20:30:58
2021-03-15T20:30:58
43,643,717
1
1
null
2020-12-26T10:41:55
2015-10-04T16:45:47
Java
UTF-8
Java
false
false
1,414
java
package university.service; import org.junit.Test; import university.exception.ProfessorNotFountException; import university.exception.SubjectNotFountException; import university.pojo.MyDepartment; import university.pojo.Professor; import university.pojo.Subject; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.*; class DepartmentServiceTest { private static final String DEPARTMENT_TEF = "TEF"; /* @Test public void whenFindProfByExistingSubject_ProfFound() { // GIVEN final MyDepartment d = new MyDepartment(DEPARTMENT_TEF); final Subject subject = new Subject("Math", new Professor("Gavrylo Petrovych")); assertNotNull(d.getProfessorBySubject("Math")); } @Test(expected = SubjectNotFountException.class) public void whenFindProfByNonExistingSubject_ThrowSubjectNotFoundEx() { // GIVEN final MyDepartment d = new MyDepartment(DEPARTMENT_TEF); final Subject subject = new Subject("Math", new Professor("Gavrylo Petrovych")); //WHEN d.getProfessorBySubject("Math1"); } @Test(expected = ProfessorNotFountException.class) public void whenFindNonExistingProfByExistingSubject_ThrowSubjectNotFoundEx() { // GIVEN final MyDepartment d = new MyDepartment(DEPARTMENT_TEF); //WHEN d.getProfessorBySubject("Science"); } */ }
[ "DevIT0319" ]
DevIT0319
64efee3a0ce63cd3b1fafcf5a88442ad4de1c5df
20d7b7490422f5d6a66560e5d05f4cedf495c87c
/FaultyVersions/CDL_29/productor.java
3472df7127a67eec58e28555918ec7b384041a7b
[]
no_license
liubaoli-and/Tax
a14e4d93a000b355fb90802a5ead744f44d62a1d
87a6d1a727fab42d2edc3a578906452a2a57e48a
refs/heads/main
2023-08-13T10:57:19.209964
2021-09-09T11:50:46
2021-09-09T11:50:46
352,620,156
4
2
null
null
null
null
UTF-8
Java
false
false
13,721
java
// This is a mutant program. // Author : ysma package ustb.edu.cn.tax.CDL_29; import com.salesapp.products.BookProduct; import com.salesapp.products.FoodProduct; import com.salesapp.products.MedicalProduct; import com.salesapp.products.MiscellaneousProduct; import com.salesapp.products.Product; import com.salesapp.shopdomain.StoreShelf; import java.util.HashMap; public class productor { public static java.lang.String name; public static double price; public static java.lang.Boolean imported; public static int quantity; public static double importCost; public static double saleCost; public static double extendCost; public static double taxedCost; public static java.util.HashMap<String,productor> productItems; public productor() { this.name = ""; this.price = 0.0; this.imported = false; this.quantity = 0; this.taxedCost = 0.0; } public productor( java.lang.String name, double price, boolean imported, int quantity ) { this.name = name; this.price = price * quantity; this.imported = imported; this.quantity = quantity; this.taxedCost = 0.0; } public static java.lang.String getName() { return name; } public void setName( java.lang.String name ) { this.name = name; } public static double getPrice() { return price; } public void setPrice( double price ) { this.price = price * quantity; } public static boolean isImported() { return imported; } public void setImported( boolean imported ) { this.imported = imported; } public static int getQuantity() { return quantity; } public void setQuantity( int quantity ) { this.quantity = quantity; } public static double getTaxedCost() { return taxedCost; } public void setTaxedCost( double taxedCost ) { this.taxedCost = taxedCost; } public static void setProductItems( java.util.HashMap<String,productor> productItems ) { productItems.put( "book", new productor() ); productItems.put( "music CD", new productor() ); productItems.put( "chocolate bar", new productor() ); productItems.put( "box of chocolates", new productor() ); productItems.put( "bottle of perfume", new productor() ); productItems.put( "packet of headache pills", new productor() ); productItems.put( "clothes", new productor() ); productItems.put( "furniture", new productor() ); productItems.put( "freezing", new productor() ); } public static double gettax( java.lang.String name, double price, boolean imported, int quantity, java.lang.String area ) { com.salesapp.shopdomain.StoreShelf storeShelf = new com.salesapp.shopdomain.StoreShelf(); productItems = new java.util.HashMap<String,productor>(); setProductItems( productItems ); storeShelf.addProductItemsToShelf( "book", new com.salesapp.products.BookProduct() ); storeShelf.addProductItemsToShelf( "music CD", new com.salesapp.products.MiscellaneousProduct() ); storeShelf.addProductItemsToShelf( "chocolate bar", new com.salesapp.products.FoodProduct() ); storeShelf.addProductItemsToShelf( "box of chocolates", new com.salesapp.products.FoodProduct() ); storeShelf.addProductItemsToShelf( "bottle of perfume", new com.salesapp.products.MiscellaneousProduct() ); storeShelf.addProductItemsToShelf( "packet of headache pills", new com.salesapp.products.MedicalProduct() ); storeShelf.addProductItemsToShelf( "clothes", new com.salesapp.products.MiscellaneousProduct() ); storeShelf.addProductItemsToShelf( "furniture", new com.salesapp.products.MiscellaneousProduct() ); storeShelf.addProductItemsToShelf( "freezing", new com.salesapp.products.FoodProduct() ); if (name.equals( "book" )) { productor buy = productItems.get( "book" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; } else { importCost = 0; } saleCost = 0; if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } if (name.equals( "music CD" )) { productor buy = productItems.get( "music CD" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } else { importCost = 0; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } if (name.equals( "chocolate bar" )) { productor buy = productItems.get( "chocolate bar" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; } else { importCost = 0; } saleCost = 0; if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost + 0.5) * 0.05; } if (name.equals( "box of chocolates" )) { productor buy = productItems.get( "box of chocolates" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; } else { importCost = 0; } saleCost = 0; if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } if (name.equals( "bottle of perfume" )) { productor buy = productItems.get( "bottle of perfume" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } else { importCost = 0; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } if (name.equals( "packet of headache pills" )) { productor buy = productItems.get( "packet of headache pills" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; } else { importCost = 0; } saleCost = 0; if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } if (name.equals( "clothes" )) { productor buy = productItems.get( "clothes" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } else { importCost = 0; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } if (name.equals( "furniture" )) { productor buy = productItems.get( "furniture" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } else { importCost = 0; if (area.equals( "local" )) { saleCost = price * 0.1 * quantity; } if (area.equals( "other" )) { saleCost = price * 0.15 * quantity; } if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } if (name.equals( "freezing" )) { productor buy = productItems.get( "freezing" ); buy.setName( name ); buy.setImported( imported ); buy.setQuantity( quantity ); buy.setPrice( price ); if (imported == true) { importCost = price * 0.05 * quantity; } else { importCost = 0; } saleCost = 0; if (buy.getQuantity() > 200) { extendCost = (buy.getQuantity() - 200) * 0.05 * price; } else { extendCost = 0; } taxedCost = importCost + saleCost + extendCost; taxedCost = (int) (taxedCost / 0.05 + 0.5) * 0.05; } return taxedCost; } public static void main( java.lang.String[] args ) { double t = gettax( "book", 25, false, 200, "local" ); System.out.println( t ); } }
4e8e4c0e0db136956686ef9c1ca256118920ced1
252a2a5f574974851289c4790829c0be6db7ee9a
/src/dcad/model/marker/MarkerLineAngle.java
adb61d09708cbac70403d2e253687f48fad8171e
[]
no_license
saurabh3240/DrawCAD
8811f75280808ef0fc0e784aa197025fdcf81fc3
f2e1bb350429c0f7b27aea56e7c0e03e7f6c6813
refs/heads/master
2021-01-20T20:18:22.882155
2010-11-24T09:43:56
2010-11-24T09:43:56
62,727,912
0
0
null
null
null
null
UTF-8
Java
false
false
1,017
java
package dcad.model.marker; import dcad.model.geometry.Text; import dcad.model.geometry.segment.SegLine; public class MarkerLineAngle extends Marker { private Text m_text = null; private double m_angle = 45; private SegLine m_segLine = null; public MarkerLineAngle(SegLine seg, Text text) { super(null); setM_segLine(seg); setM_text(text); setM_type(Marker.TYPE_LINE_ANGLE); } public Text getM_text() { return m_text; } public void setM_text(Text m_text) { // convert the text to length, if possible try { double angle = Double.parseDouble(m_text.getM_text()); if(angle >= 0) { setM_angle(angle); this.m_text = m_text; } } catch (NumberFormatException e) { setM_angle(45); e.printStackTrace(); } } public double getM_angle() { return m_angle; } public void setM_angle(double m_angle) { this.m_angle = m_angle; } public SegLine getM_segLine() { return m_segLine; } public void setM_segLine(SegLine seg) { m_segLine = seg; } }
[ "prateek@prateek.(none)" ]
prateek@prateek.(none)
5a32a6687b381fdf2bb087ca3eca0dfe8f4b092b
1235e1e3df7aa3a719c19e07db3db476f8808205
/src/application/Program.java
b2d482c1f9a24bde8b83ae20132c91b55b4042d1
[]
no_license
marcosdenisalves/CovarianceAndContravariance
761d38d3c5e9898bca1d3273a262138c98b53f4b
df8c4ff4cecc5a7c92dc5b4a44e0a9e2f4c00f14
refs/heads/master
2022-07-06T12:21:27.708918
2020-05-14T05:22:18
2020-05-14T05:22:18
263,822,032
0
0
null
null
null
null
UTF-8
Java
false
false
716
java
package application; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Program { public static void main(String[] args) { List<Integer> myInts = Arrays.asList(1, 2, 3, 4); List<Double> myDoubles = Arrays.asList(3.14, 6.28); List<Object> myObjs = new ArrayList<Object>(); copy(myInts, myObjs); printList(myObjs); copy(myDoubles, myObjs); printList(myObjs); } public static void copy(List<? extends Number> source, List<? super Number> destiny) { for (Number number : source) { destiny.add(number); } } public static void printList(List<?> list) { for (Object obj : list) { System.out.print(obj + " "); } System.out.println(); } }
9b36727d1b298ea5b74357c3b10abad58a2c276e
961a20a1201a9a915fff455234381343348f4446
/content/src/androidTest/java/com/coshx/chocolatine/content/ApplicationTest.java
48a069355db0d7423208418abc2f48669078f564
[ "MIT" ]
permissive
coshx/chocolatine
daceed403548403784fec6b12d9909a5b385cfce
6dcd7a499d3fbae84f24623d6e97d4ce398a125c
refs/heads/master
2021-01-23T08:15:24.081092
2016-02-22T22:08:47
2016-02-22T22:08:47
32,535,952
0
0
null
2016-02-22T22:08:48
2015-03-19T17:19:50
Java
UTF-8
Java
false
false
363
java
package com.coshx.chocolatine.content; 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); } }
7dbd91f3045599a9d9ccbe3afc9fb76e9aaf2cc2
00b9c9a9f653a96a5110dc5ad8ba5f0c8459baf0
/app/src/main/java/com/example/leonardescorcia/altosdelalgoritmo/Listado_Apartamentos.java
8a8c268b5a69eace7b17791f47ad8bbe3d600b63
[]
no_license
ingescorcia1427/Altos-del-Algoritmo
f969701437abf70f523cbe6ff0684323af6699bf
e717b26349df771e3eb911e653ef5998eac73f2f
refs/heads/master
2020-12-30T12:35:06.640324
2017-05-20T22:43:14
2017-05-20T22:43:14
91,391,337
0
0
null
null
null
null
UTF-8
Java
false
false
1,794
java
package com.example.leonardescorcia.altosdelalgoritmo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.text.DecimalFormat; import java.util.ArrayList; public class Listado_Apartamentos extends AppCompatActivity { private TableLayout tabla; private ArrayList<Apartamento> apartamentos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_listado__apartamentos); tabla = (TableLayout)findViewById(R.id.tblApartamento); apartamentos = Datos.traerApartamento(getApplicationContext()); for (int i = 0; i < apartamentos.size(); i++) { TableRow fila = new TableRow(this); TextView c1 = new TextView(this); TextView c2 = new TextView(this); TextView c3 = new TextView(this); TextView c4 = new TextView(this); TextView c5 = new TextView(this); TextView c6 = new TextView(this); c1.setText(" "+(i+1)); c2.setText(" " + apartamentos.get(i).getPiso() + "-" + apartamentos.get(i).getNomenclatura()); c3.setText(apartamentos.get(i).getTamano() + " m2"); c4.setText(apartamentos.get(i).getCaracteristica() + " "); c5.setText(apartamentos.get(i).getCaracteristica() + " "); c6.setText("$ "+ apartamentos.get(i).getPrecio() + ".00"); fila.addView(c1); fila.addView(c2); fila.addView(c3); fila.addView(c4); fila.addView(c5); fila.addView(c6); tabla.addView(fila); } } }
3f9d4e19a2067566d6bb935333248361b10f94e1
bb7454e9347a4c219e7582830c72dfd71cbc6503
/src/source/Test.java
ec6b2a5108eaffc2b09a9183afcb7de09a3be1dd
[]
no_license
yichunzhao/Cases-for-Oracle-OCPJP-Certificate
1fdd38dd728c86cfec40264f563639d83cca4601
09c8755ba12fee994444e5a50b5edf2ab3d84642
refs/heads/master
2020-12-28T19:34:54.469593
2017-10-01T21:30:01
2017-10-01T21:30:01
54,158,776
0
1
null
null
null
null
UTF-8
Java
false
false
1,078
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package source; /** * * @author YNZ */ public class Test { private static final int C1=10; private static final int C2=40; public static final int C3=50; private int c1=20; public int getC_1(){ return Test.C1; } public static int getC1(){ //int a =a+c1; class method cannot access instance var. return Test.C2+Test.C1; } /** * @param args the command line arguments */ public static void main(String[] args) { int a = 10; float b = 20; double c = 12; System.out.println("result = " + (a + b)); System.out.println("private staic var = " + Test.C1); Calculator cal = new CalculationImpl(); cal.calculate(a, a); //cal.calculate(a, a,b); Test tst = new Test(); System.out.println("tst c1 " +tst.c1 + Test.C1); } }
944c601870ee1443a928c9cc7a912c687868c4c9
8cae4c912d66c3a530cd1e13025285be1da259bd
/sdk/src/main/java/org/elastos/did/backend/DIDResolveResponse.java
977e374ccf98a925ee95e5086bf17f250a3d4174
[ "MIT" ]
permissive
elastos/Elastos.DID.Java.SDK
c7c7b2c24bc25c2c92a10836fdd94f29dcc21e9e
7cf79021379e89683e19a31ae88ab3885e7a34a1
refs/heads/master
2023-07-10T23:08:25.077391
2023-06-29T03:11:41
2023-06-29T03:34:53
227,095,310
8
7
MIT
2023-06-29T03:34:55
2019-12-10T10:52:20
Java
UTF-8
Java
false
false
2,078
java
/* * Copyright (c) 2019 Elastos Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.elastos.did.backend; import com.fasterxml.jackson.annotation.JsonCreator; /** * DID(document) resolve response object. */ public class DIDResolveResponse extends ResolveResponse<DIDResolveResponse, DIDBiography> { @JsonCreator protected DIDResolveResponse() { super(); } /** * Create a success DIDResolveResponse object with the specific result object. * * @param responseId the response id, normally same with the related request id * @param result a DIDBiography object */ protected DIDResolveResponse(String responseId, DIDBiography result) { super(responseId, result); } /** * Create an error DIDResolveResponse object. * * @param responseId the response id, normally same with the related request id * @param code an error code * @param message an error message, could be null */ protected DIDResolveResponse(String responseId, int code, String message) { super(responseId, code, message); } }
3694f905c9b43bff1824c450c66f51f0f80f881a
5e5153f502292f8a5d3203d183342a08e98eb575
/app/src/main/java/com/example/sirojiddinjumaev/niholeatit/ViewHolder/CartAdapter.java
462a22165e37da89cff7d72ff8244bb006c4aa7d
[]
no_license
JorisJD/Delivery-App-for-the-Client-Side
4e5ee6b5cd8d7c728186c16a96bda6a279e6cb8a
abf572085e1b1ded2db9cb40c9e933130b8f5a4d
refs/heads/master
2022-12-04T08:09:21.122366
2020-08-05T16:16:24
2020-08-05T16:24:03
285,333,107
0
0
null
null
null
null
UTF-8
Java
false
false
3,930
java
package com.example.sirojiddinjumaev.niholeatit.ViewHolder; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.amulyakhare.textdrawable.TextDrawable; import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton; import com.example.sirojiddinjumaev.niholeatit.Cart; import com.example.sirojiddinjumaev.niholeatit.Common.Common; import com.example.sirojiddinjumaev.niholeatit.Database.Database; import com.example.sirojiddinjumaev.niholeatit.Interface.ItemClickListener; import com.example.sirojiddinjumaev.niholeatit.Model.Order; import com.example.sirojiddinjumaev.niholeatit.R; import com.squareup.picasso.Picasso; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class CartAdapter extends RecyclerView.Adapter<CartViewHolder>{ private List<Order> listData = new ArrayList<>(); private Cart cart; public CartAdapter(List<Order> listData, Cart cart) { this.listData = listData; this.cart = cart; } @Override public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(cart); View itemView = inflater.inflate(R.layout.cart_layout, parent, false); return new CartViewHolder(itemView); } @Override public void onBindViewHolder(CartViewHolder holder, final int position) { // TextDrawable drawable = TextDrawable.builder() // .buildRound(""+listData.get(position).getQuantity(), Color.RED); // holder.img_cart_count.setImageDrawable(drawable); Picasso.with(cart.getBaseContext()) .load(listData.get(position).getImage()) .resize(70, 70) .centerCrop() .into(holder.cart_image); holder.btn_quantity.setNumber(listData.get(position).getQuantity()); holder.btn_quantity.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() { @Override public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) { Order order = listData.get(position); order.setQuantity(String.valueOf(newValue)); new Database(cart).updateCart(order); //Update txttotal //Calculate Total Price int total=0; List<Order> orders = new Database(cart).getCarts(Common.currentUser.getPhone()); for (Order item:orders) total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(item.getQuantity())); Locale locale = new Locale("en", "US"); NumberFormat fmt = NumberFormat.getCurrencyInstance(locale); cart.txtTotalPrice.setText(fmt.format(total)); } }); Locale locale = new Locale("en", "US"); NumberFormat fmt = NumberFormat.getCurrencyInstance(locale); int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity())); holder.txt_price.setText(fmt.format(price)); holder.txt_cart_name.setText(listData.get(position).getProductName()); } @Override public int getItemCount() { return listData.size(); } public Order getItem(int position) { return listData.get(position); } public void removeItem(int position) { listData.remove(position); notifyItemRemoved(position); } public void restoreItem(Order item , int position) { listData.add(position,item); notifyItemInserted(position); } }
92e35b300d67d83a490eb65675e1e2321537931a
6703a9841fbdd1eee690921f075a0a8391c9a966
/src/main/java/es/karenina/layer/app/resources/data/dao/provider/jpa/AJpaDaoGenerico.java
700500f2c9dfbf11e28f657e96ebb04705db1bee
[]
no_license
BethyShort/persistencia
78bc1a4440321d5dc0b9b866117e8bdc334e8306
8072ea1983a145756b751c543aaffbd735020ca1
refs/heads/master
2021-05-11T23:41:05.612871
2018-01-19T12:03:09
2018-01-19T12:03:09
117,516,936
0
0
null
null
null
null
UTF-8
Java
false
false
1,280
java
package es.karenina.layer.app.resources.data.dao.provider.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import es.karenina.layer.app.resources.data.interfaces.IDao; import es.karenina.layer.app.resources.data.interfaces.IEntidad; import es.karenina.layer.app.resources.data.interfaces.IEntidadCuerpo; import es.karenina.layer.app.resources.data.interfaces.IEntidadPk; public abstract class AJpaDaoGenerico <J extends IEntidadPk, K extends IEntidadCuerpo, L extends IEntidad<J,K>> implements IDao<J,K,L> { private Class<L> clazz; @PersistenceContext EntityManager entityManager; public void setClazz(Class<L> clazzToSet) { this.clazz = clazzToSet; } public L findByPk(final J pk) { return entityManager.find(clazz, pk); } public List<L> findAll() { return entityManager.createQuery("from " + clazz.getName()).getResultList(); } public void create(final L entity) { entityManager.persist(entity); } public L update(final L entity) { return entityManager.merge(entity); } public void delete(final L entity) { entityManager.remove(entity); } public void deleteByPk(final J pk) { L entity = findByPk(pk); delete(entity); } }
b0b9a77e9092d10dbad15d129f916ae2d80867d4
cc8193385bd8a40ea9ab250d20a8f47de12c1e35
/src/main/java/com/cnaude/purpleirc/Events/IRCMessageEvent.java
8b6393bcbd0201852d074f72f6a47e72bbc10cb5
[]
no_license
cnaude/PurpleBungeeIRC
ae29efc137f7d6a08ffff7901fe9ce14b2807cac
85573f8b0b8c4d4cf44f68d7bd8be53e039e5847
refs/heads/master
2023-01-24T02:11:20.493107
2023-01-23T16:43:40
2023-01-23T16:43:40
24,254,735
3
14
null
2023-01-22T02:20:13
2014-09-20T05:31:46
Java
UTF-8
Java
false
false
2,544
java
/* * Copyright (C) 2014 - 2017 cnaude * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.cnaude.purpleirc.Events; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Event; /** * * @author Chris Naude Event listener for plugins that want to catch irc message * events from PurpleIRC */ public class IRCMessageEvent extends Event { private String message; private final String channel; private final String permission; private final ProxiedPlayer player; /** * * @param message * @param channel * @param permission */ public IRCMessageEvent(String message, String channel, String permission) { this.message = message; this.channel = channel; this.permission = permission; this.player = null; } /** * * @param message * @param channel * @param permission * @param player */ public IRCMessageEvent(String message, String channel, String permission, ProxiedPlayer player) { this.message = message; this.channel = channel; this.permission = permission; this.player = player; } /** * * @return */ public ProxiedPlayer getProxiedPlayer() { return this.player; } /** * * @return */ public String getMessage() { return this.message; } /** * * @return */ public String getPermission() { return this.permission; } /** * * @return */ public String getChannel() { return this.channel; } /** * Change the IRC message being sent to the game * * @param message the message from IRC */ public void setMessage(String message) { this.message = message; } }
9620d91a53a8fbe6d614d5e048a993e93f03c635
2bfbb55cee5ca970f6932f69047267541ec6edf5
/app/src/xwalk/java/io/gonative/android/PoolWebViewClient.java
36f75b1bc056ad6d3e115271928b7a248fe7c5bf
[]
no_license
lucakiebel/ListX-App
9a9d8578986aa6196a3525acfbedd5bf45aaadd8
3d46e54409a5bb4d2e316542c6ea966dd028e3e3
refs/heads/master
2021-04-12T03:51:26.927436
2018-03-17T22:10:35
2018-03-17T22:10:35
125,671,444
2
0
null
2020-11-23T13:42:23
2018-03-17T21:44:59
Java
UTF-8
Java
false
false
1,657
java
package io.gonative.android; import android.webkit.WebResourceResponse; import org.xwalk.core.XWalkResourceClient; import org.xwalk.core.XWalkUIClient; import org.xwalk.core.XWalkView; /** * Created by weiyin on 9/9/15. */ public class PoolWebViewClient { private WebViewPool.WebViewPoolCallback webViewPoolCallback; private PoolWebViewUIClient uiClient; private PoolWebViewResourceClient resourceClient; private class PoolWebViewUIClient extends XWalkUIClient { public PoolWebViewUIClient(XWalkView view) { super(view); } @Override public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) { super.onPageLoadStopped(view, url, status); if (status == LoadStatus.FINISHED) { webViewPoolCallback.onPageFinished((GoNativeWebviewInterface)view, url); } } } private class PoolWebViewResourceClient extends XWalkResourceClient { public PoolWebViewResourceClient(XWalkView view) { super(view); } @Override public WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) { return webViewPoolCallback.interceptHtml((GoNativeWebviewInterface)view, url); } } public PoolWebViewClient(WebViewPool.WebViewPoolCallback webViewPoolCallback, LeanWebView view) { this.webViewPoolCallback = webViewPoolCallback; uiClient = new PoolWebViewUIClient(view); view.setUIClient(uiClient); resourceClient = new PoolWebViewResourceClient(view); view.setResourceClient(resourceClient); } }
8c184d25eb4a6a4db4aa0f70ff8666f8b6a1b3fe
460b146c295355d34b47a5a7c771a3c3c52f238d
/app/src/main/java/com/hj/app/oschina/ui/fragment/BlogFragment.java
0e3d8d2814c57ed21b36b5836e6048a68825c2df
[]
no_license
toberole/oschina-mvp
611a2d889872285ad807ca7dd999c34973a11896
9700c7d9409514285d1f45e7f3e63deed59cf293
refs/heads/master
2021-06-10T04:03:59.185625
2016-09-26T10:58:04
2016-09-26T10:58:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
118
java
package com.hj.app.oschina.ui.fragment; /** * Created by huangjie08 on 2016/8/19. */ public class BlogFragment { }
[ "huangjie" ]
huangjie
d357a50f457ef27f97f2b3953495abb2f5bba198
91dc827a16575cb7167fe223e2bc3e8abad61bf1
/src/main/java/deep/lambdaexpressions/PersonMapString.java
7e7b00d351dd8fc17fc7621b83e0d8c80b480c45
[]
no_license
muratsplat/javaInDeep
ead88b45a448003b6a18defc4e53b8b5bf02c216
369dd3fdd55e8e455b110640c8784afc756598e7
refs/heads/master
2020-08-12T19:20:15.153610
2019-10-29T19:52:56
2019-10-29T19:52:56
214,827,297
0
0
null
null
null
null
UTF-8
Java
false
false
114
java
package deep.lambdaexpressions; public interface PersonMapString <S extends Person, T> { public T map(S p); }
5f9705a7fc6ddf3608cb477c36cc16256d6fa98b
c9e5ffde325b509516498c0ce2a2fde6b9d9f30f
/src/main/java/com/revature/application/Application.java
2ba727ebe2d87f36b4a99255d84bd386a7df47b9
[]
no_license
brandonrost/ProjectOne
86ffd2606fba55fc9172985b522fbe72ab68b100
b1de2a7f3340bc28696d4961b0d20661ec16e970
refs/heads/main
2023-05-04T02:18:50.465494
2021-05-21T18:51:02
2021-05-21T18:51:02
362,933,922
0
0
null
null
null
null
UTF-8
Java
false
false
1,511
java
package com.revature.application; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.revature.controllers.Controller; import com.revature.controllers.ExceptionController; import com.revature.controllers.ReimbController; import com.revature.controllers.StaticFileController; import com.revature.controllers.UserController; import com.revature.dbsetup.HibernateDBSetup; import io.javalin.Javalin; import io.javalin.plugin.json.JavalinJackson; public class Application { private static Logger logger = LoggerFactory.getLogger(Application.class); private static HibernateDBSetup setup = new HibernateDBSetup(); public static void main(String[] args) { //setup.setUp(); //This can be used to reset the database and set up a new one ObjectMapper mapper = JsonMapper.builder() .addModule(new JavaTimeModule()) .build(); JavalinJackson.configure(mapper); Javalin app = Javalin.create((config) -> { config.addStaticFiles("static"); config.enableCorsForAllOrigins(); }); mapControllers(app, new ExceptionController(), new UserController(), new StaticFileController(), new ReimbController()); app.start(7000); } private static void mapControllers(Javalin app, Controller... controllers) { for (Controller c : controllers) { c.mapEndpoints(app); } } }
92a7c39aee132b06bfcb42913dd2cb7f41c4045f
afd2dc8f35c298a5f23e482ba3ece27c56eeed3c
/app/src/main/java/com/example/prueba_2/AdminSQLiteOpenHelper.java
2e858375bdffb37a94042cf69eac964494b6feaf
[]
no_license
Yeddcito/Prueba_2
c4b806e49b4416d1f15a28ed38dbcb043b8ccc66
902cfc6e11a666fc951af7aa83dad681329e6a55
refs/heads/master
2023-01-07T20:36:02.994010
2020-11-08T11:27:59
2020-11-08T11:27:59
311,047,054
0
0
null
null
null
null
UTF-8
Java
false
false
713
java
package com.example.prueba_2; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class AdminSQLiteOpenHelper extends SQLiteOpenHelper { public AdminSQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE clientes (codigo int primary key, nombre text, salario float)"); } @Override public void onUpgrade(SQLiteDatabase db, int i, int i1) { } }
ae8984e28609ccd00164c361f30ddf226d1e7585
7affe77430b32872b3b6209beb9596166dd95b6d
/src/main/java/org/moshe/arad/kafka/consumers/config/GetAllGameRoomsCommandConfig.java
754252c2aa2a67cb0f098a243e9425e31c867ef3
[]
no_license
moshe-arad/Lobby-View-Service-4.0
a681ac7a29bc74a9102834a85de4402a77b35e99
dab0bf3981046c6731542a800d56a3ee7751394f
refs/heads/master
2020-12-30T13:27:32.232371
2017-06-19T11:15:44
2017-06-19T11:15:44
91,211,714
0
0
null
2017-06-19T11:15:45
2017-05-14T01:07:04
Java
UTF-8
Java
false
false
432
java
package org.moshe.arad.kafka.consumers.config; import org.moshe.arad.kafka.KafkaUtils; import org.moshe.arad.kafka.consumers.config.SimpleConsumerConfig; import org.springframework.stereotype.Component; @Component public class GetAllGameRoomsCommandConfig extends SimpleConsumerConfig{ public GetAllGameRoomsCommandConfig() { super(); super.getProperties().put("group.id", KafkaUtils.GET_ALL_GAME_ROOMS_COMMAND_GROUP); } }
d154ba29c2453fd9152f472c8c456b2fb044be72
aaa166f4d767beffc4ed9cf7c07f07e3750478a4
/src/test/java/com/queueoperations/MyQueueTest.java
fc95fa64b526b3e789fca8d68656158d0d71b21d
[]
no_license
myramoon/QueueOperations
c6525c428ec8ea678bce3c433c3685acaf7ff2b2
228d1abb4c27e598561b929cf260137e2e2d51b8
refs/heads/master
2023-01-03T18:03:20.964994
2020-10-27T21:04:29
2020-10-27T21:04:29
307,824,674
0
0
null
null
null
null
UTF-8
Java
false
false
1,349
java
package com.queueoperations; import org.junit.Assert; import org.junit.Test; public class MyQueueTest { @Test public void given3Numbers_WhenAddedToQueue_ShouldReturnFirstAddedNode() { MyQueue myQueue = new MyQueue(); MyNode<Integer> myFirstNode = new MyNode<>(56); MyNode<Integer> mySecondNode = new MyNode<>(30); MyNode<Integer> myThirdNode = new MyNode<>(70); myQueue.enqueue(myFirstNode); //add elements to queue using linked list append method myQueue.enqueue(mySecondNode); myQueue.enqueue(myThirdNode); INode peek = myQueue.peek(); //call to check the topmost element in queue Assert.assertEquals(myFirstNode , peek); } @Test public void given3NumbersInQueue_WhenDequeued_ShouldReturnFirstAddedNode() { MyQueue myQueue = new MyQueue(); MyNode<Integer> myFirstNode = new MyNode<>(56); MyNode<Integer> mySecondNode = new MyNode<>(30); MyNode<Integer> myThirdNode = new MyNode<>(70); myQueue.enqueue(myFirstNode); //add elements to queue using linked list append method myQueue.enqueue(mySecondNode); myQueue.enqueue(myThirdNode); INode dequeue = myQueue.dequeue(); //call to check the topmost element in queue Assert.assertEquals(myFirstNode , dequeue); } }
0c3fbd94f850cb3f393a5123cbccc14e89e84ce2
0de6146f8570e9db96a7f54d0013fe16d072f264
/PListView2/app/src/androidTest/java/com/example/aigua/plistview2/ApplicationTest.java
3edd6afaa4c8d0b9f8218e28278f171a4104e095
[]
no_license
vigomez/DAM.PMM.2016_17
df97cf9e420f577264765b6218d3af60be68b060
04be792687f1e4d0b39d50e005ad7e0666a79bac
refs/heads/master
2021-01-11T07:21:56.054459
2016-12-19T10:08:18
2016-12-19T10:08:18
69,222,273
0
0
null
null
null
null
UTF-8
Java
false
false
359
java
package com.example.aigua.plistview2; 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); } }
84b835ebf2ba1e56678aa499c786f4878e4949ea
8becc1fd6e2b224fc43cf370cd4bed4f00ddeee0
/src/java/org/infoglue/cms/applications/workflowtool/util/ContentFactory.java
a35f8a582602809e1dd7d5a3adc029ed5050b8d0
[]
no_license
bogeblad/infoglue298
b742a0963ff969c77eaef5b32bc570626e6c3a30
b5d04b6f5dccb0dd0ade904be5b411778f9bb654
refs/heads/master
2016-09-05T20:26:08.468775
2014-03-26T14:01:50
2014-03-26T14:01:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,355
java
/* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.cms.applications.workflowtool.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.exolab.castor.jdo.Database; import org.infoglue.cms.controllers.kernel.impl.simple.CategoryController; import org.infoglue.cms.controllers.kernel.impl.simple.ContentCategoryController; import org.infoglue.cms.controllers.kernel.impl.simple.ContentControllerProxy; import org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController; import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController; import org.infoglue.cms.entities.content.Content; import org.infoglue.cms.entities.content.ContentVO; import org.infoglue.cms.entities.content.ContentVersion; import org.infoglue.cms.entities.content.ContentVersionVO; import org.infoglue.cms.entities.management.CategoryVO; import org.infoglue.cms.entities.management.ContentTypeAttribute; import org.infoglue.cms.entities.management.ContentTypeDefinitionVO; import org.infoglue.cms.entities.management.LanguageVO; import org.infoglue.cms.exception.ConstraintException; import org.infoglue.cms.exception.SystemException; import org.infoglue.cms.security.InfoGluePrincipal; import org.infoglue.cms.util.ConstraintExceptionBuffer; import org.infoglue.cms.util.dom.DOMBuilder; /** * */ public class ContentFactory { /** * The class logger. */ private final static Logger logger = Logger.getLogger(ContentFactory.class.getName()); /** * The content type. */ private final ContentTypeDefinitionVO contentTypeDefinitionVO; /** * The content bean. */ private final ContentValues contentValues; /** * The content version bean. */ private final ContentVersionValues contentVersionValues; /** * The creator. */ private final InfoGluePrincipal principal; /** * The language associated with the content version. */ private final LanguageVO language; /** * The database to use. */ private Database db; /** * * @param contentTypeDefinitionVO * @param contentValues * @param contentVersionValues * @param principal * @param language */ public ContentFactory(final ContentTypeDefinitionVO contentTypeDefinitionVO, final ContentValues contentValues, final ContentVersionValues contentVersionValues, final InfoGluePrincipal principal, final LanguageVO language) { this.contentTypeDefinitionVO = contentTypeDefinitionVO; this.contentValues = contentValues; this.contentVersionValues = contentVersionValues; this.principal = principal; this.language = language; if(logger.isDebugEnabled()) { logger.info("*********ContentFactory**********"); logger.info("contentTypeDefinitionVO:" + contentTypeDefinitionVO); logger.info("contentValues:" + contentValues); logger.info("contentVersionValues:" + contentVersionValues); logger.info("principal:" + principal); logger.info("language:" + language); logger.info("*********END ContentFactory**********"); } } /** * * @param parentContent * @param categories * @param db * @return * @throws ConstraintException */ public ContentVO create(final ContentVO parentContent, final Map categories, final Database db) throws ConstraintException, SystemException, Exception { if(logger.isDebugEnabled()) { logger.info("*********ContentFactory.create**********"); logger.info("contentTypeDefinitionVO:" + contentTypeDefinitionVO); logger.info("contentValues:" + contentValues); logger.info("contentVersionValues:" + contentVersionValues); logger.info("principal:" + principal); logger.info("language:" + language); logger.info("parentContent:" + parentContent); logger.info("categories:" + categories); } this.db = db; final ContentVO contentVO = createContentVO(); final Document contentVersionDocument = buildContentVersionDocument(); final ContentVersionVO contentVersionVO = createContentVersionVO(contentVersionDocument.asXML()); ConstraintExceptionBuffer ceb = validate(contentVO, contentVersionVO); if(ceb.isEmpty()) { return createContent(parentContent, contentVO, contentVersionVO, categories); } else { try { ceb.throwIfNotEmpty(); } catch (ConstraintException e) { logger.error("Problem creating content:" + e.getMessage()); } catch (Exception e) { logger.error("Problem creating content:" + e.getMessage(), e); } } return null; } /** * * @param contentVO * @param categories * @return * @throws ConstraintException */ public ContentVO update(final ContentVO contentVO, final Map categories, final Database db) throws ConstraintException { this.db = db; populateContentVO(contentVO); final ContentVersionVO contentVersionVO = createContentVersionVO(buildContentVersionDocument().asXML()); ConstraintExceptionBuffer ceb = validate(contentVO, contentVersionVO); if(ceb.isEmpty()) { return updateContent(contentVO, contentVersionVO, categories); } else { logger.error("Error: Not valid content or version - cancelling update."); /* try { ceb.throwIfNotEmpty(); } catch(Exception e) { e.printStackTrace(); } */ } return null; } /** * * @return */ public ConstraintExceptionBuffer validate() { final ContentVO contentVO = createContentVO(); final ContentVersionVO contentVersionVO = createContentVersionVO(buildContentVersionDocument().asXML()); return validate(contentVO, contentVersionVO); } /** * * @param contentVO * @param contentVersionVO * @return */ private ConstraintExceptionBuffer validate(final ContentVO contentVO, final ContentVersionVO contentVersionVO) { final ConstraintExceptionBuffer ceb = contentVO.validate(); ceb.add(contentVersionVO.validateAdvanced(contentTypeDefinitionVO)); return ceb; } /** * * @param parentContent * @param contentVO * @param contentVersionVO * @param categories * @return */ private ContentVO createContent(final ContentVO parentContent, final ContentVO contentVO, final ContentVersionVO contentVersionVO, final Map categories) throws Exception { try { if(logger.isDebugEnabled()) { logger.info("************createContent**********"); logger.info("parentContent:" + parentContent); logger.info("contentVO:" + contentVO); logger.info("contentVersionVO:" + contentVersionVO); logger.info("categories:" + categories); } final Content content = ContentControllerProxy.getContentController().create(db, parentContent.getId(), contentTypeDefinitionVO.getId(), parentContent.getRepositoryId(), contentVO); final ContentVersion newContentVersion = ContentVersionController.getContentVersionController().create(content.getId(), language.getId(), contentVersionVO, null, db); createCategories(newContentVersion, categories); if(logger.isDebugEnabled()) logger.info("Returning:" + content + ":" + content.getValueObject()); return content.getValueObject(); } catch(Exception e) { //logger.error(e); throw e; } //if(logger.isDebugEnabled()) // logger.info("Returning null...."); //return null; } /** * * @param contentVO * @param contentVersionVO * @param categories * @return */ private ContentVO updateContent(final ContentVO contentVO, final ContentVersionVO contentVersionVO, final Map categories) { try { final Content content = ContentControllerProxy.getContentController().getContentWithId(contentVO.getId(), db); content.setValueObject(contentVO); final ContentVersion contentVersion = ContentVersionController.getContentVersionController().getLatestActiveContentVersion(content.getId(), language.getId(), db); if(contentVersion != null) { contentVersion.getValueObject().setVersionValue(contentVersionVO.getVersionValue()); deleteCategories(contentVersion); createCategories(contentVersion, categories); } else { final ContentVersion newContentVersion = ContentVersionController.getContentVersionController().create(content.getId(), language.getId(), contentVersionVO, null, db); createCategories(newContentVersion, categories); } return content.getValueObject(); } catch(Exception e) { e.printStackTrace(); logger.warn(e); } return null; } /** * Deletes all content categories associated with the specified content version. * * @param contentVersion the content version. * @throws Exception if an exception occurs while deleting the content categories. */ private void deleteCategories(final ContentVersion contentVersion) throws Exception { ContentCategoryController.getController().deleteByContentVersion(contentVersion.getId(), db); } /** * * @param contentVersion * @param categorieVOs * @throws Exception */ private void createCategories(final ContentVersion contentVersion, final Map categorieVOs) throws Exception { if(categorieVOs != null) { for(Iterator i=categorieVOs.keySet().iterator(); i.hasNext(); ) { String attributeName = (String) i.next(); List categoryVOs = (List) categorieVOs.get(attributeName); createCategory(contentVersion, attributeName, categoryVOs); } } } /** * * @param contentVersion * @param attributeName * @param categoryVOs * @throws Exception */ private void createCategory(final ContentVersion contentVersion, final String attributeName, final List categoryVOs) throws Exception { final List categories = categoryVOListToCategoryList(categoryVOs); ContentCategoryController.getController().create(categories, contentVersion, attributeName, db); } /** * * @param db the database to use in the operation. * @param categoryVOList * @return * @throws Exception */ private List categoryVOListToCategoryList(final List categoryVOList) throws Exception { final List result = new ArrayList(); for(Iterator i=categoryVOList.iterator(); i.hasNext(); ) { CategoryVO categoryVO = (CategoryVO) i.next(); result.add(CategoryController.getController().findById(categoryVO.getCategoryId(), db)); } return result; } /** * Creates a new content value object and populates it using the content bean. * * @return the content value object. */ private ContentVO createContentVO() { final ContentVO contentVO = new ContentVO(); populateContentVO(contentVO); return contentVO; } /** * Populates the specified content value object using the content bean. * * @param contentVO the content value object. */ private void populateContentVO(final ContentVO contentVO) { contentVO.setName(contentValues.getName()); if(contentValues.getPublishDateTime() != null) contentVO.setPublishDateTime(contentValues.getPublishDateTime()); if(contentValues.getExpireDateTime() != null) contentVO.setExpireDateTime(contentValues.getExpireDateTime()); contentVO.setIsBranch(Boolean.FALSE); contentVO.setCreatorName(principal.getName()); } /** * Creates a new content version value object with the specified version value. * * @param versionValue the version value. * @return the content version value object. */ private ContentVersionVO createContentVersionVO(final String versionValue) { final ContentVersionVO contentVersion = new ContentVersionVO(); contentVersion.setVersionComment(""); contentVersion.setVersionModifier(principal.getName()); contentVersion.setVersionValue(versionValue); return contentVersion; } /** * Returns all attributes of the content type. * * @return the attributes. */ private Collection getContentTypeAttributes() { return ContentTypeDefinitionController.getController().getContentTypeAttributes(contentTypeDefinitionVO.getSchemaValue()); } /** * Builds the content version value document using the content version bean. * * @return the document. */ private Document buildContentVersionDocument() { final DOMBuilder builder = new DOMBuilder(); final Document document = builder.createDocument(); final Element rootElement = builder.addElement(document, "root"); builder.addAttribute(rootElement, "xmlns", "x-schema:Schema.xml"); final Element attributesRoot = builder.addElement(rootElement, "attributes"); buildAttributes(builder, attributesRoot); return document; } /** * Builds the attributes part of the content version value document. * * @param domBuilder the document builder. * @param parentElement the parent element of all the attributes. */ private void buildAttributes(final DOMBuilder domBuilder, final Element parentElement) { final Collection typeAttributes = getContentTypeAttributes(); for(final Iterator i=typeAttributes.iterator(); i.hasNext(); ) { final ContentTypeAttribute attribute = (ContentTypeAttribute) i.next(); final Element element = domBuilder.addElement(parentElement, attribute.getName()); final String value = contentVersionValues.get(attribute.getName()); if(value != null) { domBuilder.addCDATAElement(element, value); } } } }
a94b8f26a55e80663a559ba3be93eeb8fe4df8ae
e3fc12ae06f9ed6e3a2443d4173488406970c8e5
/src/main/java/com/swithlink/interview/security/JwtTokenProvider.java
ab2b113fa18560bf848d1fb263ead82706d94a3d
[]
no_license
ryananyangu/slinktprocessor
8f620aff2834aeb156f84e17264ac0a3e32eab80
3d1c15a5fb71e33ba0ebffc7a752b7f45d5c0d63
refs/heads/master
2022-12-30T09:28:16.179222
2020-10-22T17:29:26
2020-10-22T17:29:26
305,277,057
0
0
null
null
null
null
UTF-8
Java
false
false
3,112
java
package com.swithlink.interview.security; import java.util.Base64; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import com.swithlink.interview.exceptions.CustomException; import com.swithlink.interview.models.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Component public class JwtTokenProvider { /** * THIS IS NOT A SECURE PRACTICE! For simplicity, we are storing a static key here. Ideally, in a * microservices environment, this key would be kept on a config-server. */ // @Value("${security.jwt.token.secret-key:secret-key}") private String secretKey = System.getenv("SECRET"); // @Value("${security.jwt.token.expire-length:3600000}") private long validityInMilliseconds = 3600000; // 1h @Autowired private MyUserDetails myUserDetails; @PostConstruct protected void init() { secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); } public String createToken(String username, List<Role> roles) { Claims claims = Jwts.claims().setSubject(username); claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList())); Date now = new Date(); Date validity = new Date(now.getTime() + validityInMilliseconds); return Jwts.builder()// .setClaims(claims)// .setIssuedAt(now)// .setExpiration(validity)// .signWith(SignatureAlgorithm.HS256, secretKey)// .compact(); } public Authentication getAuthentication(String token) { UserDetails userDetails = myUserDetails.loadUserByUsername(getUsername(token)); return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } public String getUsername(String token) { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); } public String resolveToken(HttpServletRequest req) { String bearerToken = req.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } public boolean validateToken(String token) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); return true; } catch (JwtException | IllegalArgumentException e) { throw new CustomException("Expired or invalid JWT token", HttpStatus.INTERNAL_SERVER_ERROR); } } }
b7a73219e640173cda475a674903aafced87dcd0
03a1977c39a7bbf5016f2178f2e0112d79d8e555
/implementation/src/main/java/stan/mym1y/clean/managers/SecurityManager.java
8c4bade212e7ea7dfedd4e4b9fcf47435435cd54
[]
no_license
kepocnhh/MyM1yClean
2153b27f30f41892a9cdbb86b7ac0b596df34a22
286b93a1ef6a875cb6f1b858dbdf38bdc99fd7ce
refs/heads/master
2021-01-09T06:17:16.089984
2017-07-17T18:07:23
2017-07-17T18:07:23
80,951,344
2
0
null
null
null
null
UTF-8
Java
false
false
1,354
java
package stan.mym1y.clean.managers; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import java.util.UUID; import stan.mym1y.clean.components.Security; public class SecurityManager implements Security { private final Random random = new Random(); private final MessageDigest messageDigestSha512; public SecurityManager() { try { messageDigestSha512 = MessageDigest.getInstance("SHA-512"); } catch(NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public String sha512(String data) { try { byte[] bytes = messageDigestSha512.digest(data.getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for(byte aByte : bytes) { sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch(UnsupportedEncodingException e) { throw new RuntimeException(e); } } public int newUniqueId() { return random.nextInt(Integer.MAX_VALUE-2)+1; } public String newUUID() { return UUID.randomUUID().toString(); } }
e592a18d3770e2a67fa1e2a5fc353128de4157f6
9b04c5a90b31776a17c254d218abb63f59889f5d
/gsb/gsb-api/src/main/java/com/gongsibao/api/dto/GoodsDTO.java
6adee6fd524fb3df53b03d15fd5f9f3e2b2361ff
[]
no_license
damogui/testtt
de80c460e878c22553dabe965a7dfe21181d83cf
ae486b93370db3b3153239a25aecd1caeea8d248
refs/heads/master
2021-09-14T19:46:43.345265
2018-05-18T08:29:08
2018-05-18T08:29:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,006
java
package com.gongsibao.api.dto; import java.math.BigDecimal; /** * @author hw * 服务项 */ public class GoodsDTO extends BaseDTO{ /** * */ private static final long serialVersionUID = -1931988684440679949L; /** * 名称 */ private String name = ""; /** * 价格 */ private BigDecimal price; /** * 工时 */ private Integer duration = 0; /** * 描述 */ private String description = ""; public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
9a626f532805005ea3520de98b81e23ecdce45c2
96d71f73821cfbf3653f148d8a261eceedeac882
/external/tools/Coddec/coddec/src/net/rim/tools/compiler/classfile/ai.java
aad7b5ea7c41e2a20df7084f2b48213161894ea0
[]
no_license
JaapSuter/Niets
9a9ec53f448df9b866a8c15162a5690b6bcca818
3cc42f8c2cefd9c3193711cbf15b5304566e08cb
refs/heads/master
2020-04-09T19:09:40.667155
2012-09-28T18:11:33
2012-09-28T18:11:33
5,751,595
2
1
null
null
null
null
UTF-8
Java
false
false
35,975
java
// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) fieldsfirst ansi package net.rim.tools.compiler.classfile; import java.util.Vector; import net.rim.tools.compiler.util.CompileException; import net.rim.tools.compiler.analysis.InstructionStackEntry; import net.rim.tools.compiler.analysis.InstructionWalker; import net.rim.tools.compiler.analysis.Instruction; // Referenced classes of package net.rim.tools.compiler.e: // x, ad, al, u, // af public final class ai implements net.rim.tools.compiler.classfile.u { private Vector z_o4Vector; private Vector z_o6Vector; private Vector z_o3Vector; private boolean z_o2Z; private Vector z_o8Vector; private int z_o5I; private InstructionTarget z_o7x; public ai() { this(0); } public ai(int i) { z_o4Vector = new Vector(); z_o4Vector.addElement(new InstructionTarget(0, i, null, null)); InstructionTarget x1 = new InstructionTarget(i, 1, null, null); x1._biIV(9); z_o4Vector.addElement(x1); z_o3Vector = new Vector(); } public void _doxvV(net.rim.tools.compiler.classfile.InstructionTarget x1, int i) { z_o4Vector.insertElementAt(x1, i); } public void _dxV(net.rim.tools.compiler.classfile.InstructionTarget x1) throws net.rim.tools.compiler.util.CompileException { int i = x1.getOffset(); int j = _d3vI(); for(int k = 0; k < j; k++) if(_bkIx(k).getOffset() > i) { _doxvV(x1, k); return; } throw new net.rim.tools.compiler.util.CompileException("byte code offset: " + i + " out of range: 0-" + _bkIx(j - 1).getOffset()); } void _voidxV(net.rim.tools.compiler.classfile.InstructionTarget x1) { _doxvV(x1, z_o5I++); } public void _boIV(int i) { z_o4Vector.removeElementAt(i); } public int _d3vI() { return z_o4Vector.size(); } public net.rim.tools.compiler.classfile.InstructionTarget _bkIx(int i) { return (net.rim.tools.compiler.classfile.InstructionTarget)z_o4Vector.elementAt(i); } public int _cxI(net.rim.tools.compiler.classfile.InstructionTarget x1) { return z_o4Vector.indexOf(x1); } public void _aadvV(net.rim.tools.compiler.classfile.ad ad1, int i) { if(z_o6Vector == null) z_o6Vector = new Vector(); z_o6Vector.insertElementAt(ad1, i); } public void _aIIIIV(int i, int j, int k, int l, net.rim.tools.compiler.types.ClassType g1) throws net.rim.tools.compiler.util.CompileException { net.rim.tools.compiler.classfile.InstructionTarget x1 = _bvIx(j); if(x1.getOffset() != j) if(x1._baIZ(8)) { x1 = _bkIx(_cxI(x1) + 1); } else { x1 = x1._aIZx(j, true, false); _dxV(x1); } net.rim.tools.compiler.classfile.InstructionTarget x2 = _intIZx(k, true); net.rim.tools.compiler.classfile.InstructionTarget x3 = _intIZx(l, false); int i1 = _cxI(x2); for(int j1 = _cxI(x1); j1 < i1; j1++) _bkIx(j1)._bytexV(x3); net.rim.tools.compiler.classfile.ad ad1 = new net.rim.tools.compiler.classfile.ad(x1, x2, x3, g1); if(z_o6Vector == null) z_o6Vector = new Vector(); z_o6Vector.addElement(ad1); } public void _bwIV(int i) { z_o6Vector.removeElementAt(i); if(z_o6Vector.size() == 0) z_o6Vector = null; } public void _longIIV(int i, int j) { net.rim.tools.compiler.classfile.ad ad1 = _bpIad(i); net.rim.tools.compiler.classfile.ad ad2 = _bpIad(j); z_o6Vector.setElementAt(ad1, j); z_o6Vector.setElementAt(ad2, i); } public int _dVvI() { return z_o6Vector != null ? z_o6Vector.size() : 0; } public net.rim.tools.compiler.classfile.ad _bpIad(int i) { return (net.rim.tools.compiler.classfile.ad)z_o6Vector.elementAt(i); } public void _aalvV(net.rim.tools.compiler.classfile.al al1, int i) { z_o3Vector.insertElementAt(al1, i); } public void _aIIV(int i, int j, net.rim.tools.compiler.classfile.af af1) throws net.rim.tools.compiler.util.CompileException { InstructionTarget x1 = _bvIx(i); if(x1._baIZ(8)) { if(i != x1.getOffset()) { x1 = x1._dwvx(); i = x1.getOffset(); } } else { x1 = _intIZx(i, true); } InstructionTarget x2 = _intIZx(j, true); net.rim.tools.compiler.classfile.al al1 = new net.rim.tools.compiler.classfile.al(x1, x2, af1); z_o3Vector.addElement(al1); } public void _blIV(int i) { z_o3Vector.removeElementAt(i); } public void _elseIIV(int i, int j) { net.rim.tools.compiler.classfile.al al1 = _buIal(i); net.rim.tools.compiler.classfile.al al2 = _buIal(j); z_o3Vector.setElementAt(al1, j); z_o3Vector.setElementAt(al2, i); } public int _dPvI() { return z_o3Vector.size(); } public net.rim.tools.compiler.classfile.al _buIal(int i) { return (net.rim.tools.compiler.classfile.al)z_o3Vector.elementAt(i); } public boolean _dUvZ() { return z_o2Z; } public net.rim.tools.compiler.classfile.InstructionTarget _bsIx(int i) { if(z_o8Vector == null) z_o8Vector = new Vector(); net.rim.tools.compiler.classfile.InstructionTarget x1 = new net.rim.tools.compiler.classfile.InstructionTarget(i, 0, null, null); x1._biIV(10); z_o8Vector.addElement(x1); return x1; } public int _dSvI() { return z_o8Vector != null ? z_o8Vector.size() : 0; } public net.rim.tools.compiler.classfile.InstructionTarget _bmIx(int i) { return (InstructionTarget)z_o8Vector.elementAt(i); } void _bqIV(int i) { z_o5I = i; } void _bxV(net.rim.tools.compiler.classfile.InstructionTarget x1) { z_o7x = x1; } net.rim.tools.compiler.classfile.InstructionTarget _d0vx() { return z_o7x; } public void _gotoIIV(int i, int j) throws CompileException { net.rim.tools.compiler.classfile.InstructionTarget x1 = _bvIx(i); if(x1._baIZ(8) && i != x1.getOffset()) { x1 = x1._dwvx(); i = x1.getOffset(); } net.rim.tools.compiler.analysis.Instruction g1 = x1.findInstruction(i); if(g1 != null && g1._eOvI() == 0) g1.setValueOp(j); } public InstructionTarget _bvIx(int i) throws net.rim.tools.compiler.util.CompileException { InstructionTarget x1 = null; int j = 0; int k = _d3vI() - 1; do { int l = (j + k) / 2; x1 = _bkIx(l); if(i < x1.getOffset()) { x1 = null; k = l - 1; continue; } if(x1.checkOffset(i)) break; x1 = null; j = l + 1; } while(j <= k); if(x1 == null) throw new net.rim.tools.compiler.util.CompileException("byte code offset: " + i + " out of range: 0-" + _bkIx(_d3vI() - 1).getOffset()); else return x1; } public InstructionTarget _intIZx(int i, boolean flag) throws net.rim.tools.compiler.util.CompileException { InstructionTarget x1 = _bvIx(i); if(x1.getOffset() == i) { return x1; } else { x1 = x1._aIZx(i, flag, false); _dxV(x1); return x1; } } public void _aIdV(int i, net.rim.tools.compiler.analysis.InstructionStackEntry d) throws net.rim.tools.compiler.util.CompileException { InstructionTarget x1 = _intIZx(i, true); x1.setStackEntry(d); } public boolean _ifeZ(InstructionWalker e) throws CompileException { boolean flag = false; int i = _d3vI(); for(int j = 0; j < i; j++) { InstructionTarget x1 = _bkIx(j); flag = x1._aeZ(e) || flag; } return flag; } void _dZvV() throws CompileException { int j = _d3vI(); for(int i = 0; i < j; i++) { InstructionTarget x1 = _bkIx(i); if(x1._baIZ(1)) { for(int k = _dVvI() - 1; k >= 0; k--) { ad ad1 = _bpIad(k); if(ad1._charxZ(x1)) { ad ad2 = ad1._doaiad(this, x1); if(ad2 == null) { if(ad1._dNvx() == ad1._dKvx()) _bwIV(k); } else { _aadvV(ad2, k + 1); } } } x1._dGvV(); } } } void _d7vV() throws CompileException { int k = _dVvI(); for(int i = 0; i < k; i++) { ad ad1 = _bpIad(i); ad1._elsexV(_bvIx(ad1._dKvx().getOffset() - 1)); } k = _dPvI(); for(int j = 0; j < k; j++) { al al1 = _buIal(j); al1._exV(_bvIx(al1._d9vx().getOffset() - 1)); } } void _dWvV() { boolean flag; do { flag = false; for(int i = _dVvI() - 1; i >= 0; i--) { ad ad1 = _bpIad(i); InstructionTarget x1 = ad1._dNvx(); InstructionTarget x4 = ad1._dKvx(); if(x1 != x4) { int i2 = _cxI(x1); int k2 = _cxI(x4); if(i2 > k2) throw new RuntimeException("bad exception range: " + i2 + " to " + k2); for(int l2 = k2; l2 >= i2; l2--) { InstructionTarget x14 = _bkIx(l2); if(x14._dvvx() != null) { if(l2 != k2) { InstructionTarget x15 = _bkIx(l2 + 1); ad ad4 = ad1._axad(x14, x15); _aadvV(ad4, i); ad1 = ad4; k2 = l2; flag = true; } do { l2--; x14 = _bkIx(l2); } while(x14._dvvx() != null && l2 >= i2); if(l2 >= i2) { InstructionTarget x16 = _bkIx(l2 + 1); ad ad5 = ad1._axad(x14, x16); _aadvV(ad5, i); ad1 = ad5; k2 = l2; flag = true; } } } } } int j1 = _dVvI(); for(int j = 0; j < j1; j++) { ad ad3 = _bpIad(j); InstructionTarget x5 = ad3._dNvx()._dvvx(); InstructionTarget x8 = ad3._dKvx()._dvvx(); InstructionTarget x10 = ad3._dMvx()._dvvx(); if(x5 != null && x8 != null && x10 == null) throw new RuntimeException("Internal error: exception handler not cloned"); } } while(flag); for(int k = _dPvI() - 1; k >= 0; k--) { al al1 = _buIal(k); int k1 = _cxI(al1._d8vx()); int l1 = _cxI(al1._d9vx()); for(int j2 = l1; j2 >= k1; j2--) { InstructionTarget x11 = _bkIx(j2); if(x11._dvvx() != null) { if(j2 != l1) { InstructionTarget x12 = _bkIx(j2 + 1); al al3 = al1._forxal(x11, x12); _aalvV(al3, k); l1 = j2; al1 = al3; } do { j2--; x11 = _bkIx(j2); } while(x11._dvvx() != null && j2 >= k1); if(j2 >= k1) { InstructionTarget x13 = _bkIx(j2 + 1); al al4 = al1._forxal(x11, x13); _aalvV(al4, k); l1 = j2; al1 = al4; } } } } for(int l = _dVvI() - 1; l >= 0; l--) { ad ad2 = _bpIad(l); InstructionTarget x2 = ad2._dNvx()._dvvx(); InstructionTarget x6 = ad2._dKvx()._dvvx(); InstructionTarget x9 = ad2._dMvx()._dvvx(); if(x2 != null && x6 != null) { ad2 = ad2._axad(x2, x6, x9); _aadvV(ad2, l + 1); } } for(int i1 = _dPvI() - 1; i1 >= 0; i1--) { al al2 = _buIal(i1); InstructionTarget x3 = al2._d8vx()._dvvx(); InstructionTarget x7 = al2._d9vx()._dvvx(); if(x3 != null && x7 != null) { al2 = al2._doxal(x3, x7); _aalvV(al2, i1 + 1); } } } void _nullxV(InstructionTarget x1) { x1._duvV(); for(int i = 0; i < _d3vI(); i++) { InstructionTarget x2 = _bkIx(i); x2._aaiV(this); } int k = _d3vI(); for(int j = 0; j < k; j++) { InstructionTarget x3 = _bkIx(j); x3._djvV(); } } void _dYvV() { _bqIV(0); _bxV(null); int j = _d3vI(); for(int i = 0; i < j; i++) { InstructionTarget x1 = _bkIx(i); x1._davV(); } } public void _dZV(boolean flag) { int i1 = _d3vI(); for(int i = 0; i < i1; i++) { InstructionTarget x1 = _bkIx(i); x1._dfvV(); } _bkIx(0)._dkvV(); boolean flag1; do { flag1 = false; i1 = _d3vI(); for(int j = 0; j < i1; j++) { InstructionTarget x2 = _bkIx(j); if(flag || x2._c9vZ()) { InstructionTarget x4 = x2._dwvx(); if(x4 == null) { int j1 = j + 1; if(x2._dxvI() == 0 && j1 < i1) x4 = _bkIx(j1); } if(x4 != null) { if(!x4._c9vZ()) flag1 = true; x4._dkvV(); } int k1 = x2._dsvI(); for(int l1 = 0; l1 < k1; l1++) { InstructionTarget x5 = x2._a5Ix(l1); if(!x5._c9vZ()) flag1 = true; if(_cxI(x5) <= j) x5._dAvV(); else x5._c8vV(); } } } i1 = _dVvI(); for(int k = 0; k < i1; k++) { ad ad1 = _bpIad(k); InstructionTarget x6 = ad1._dNvx(); x6._drvV(); InstructionTarget x8 = ad1._dKvx(); x8._drvV(); int i2 = _cxI(x6); int j2 = _cxI(x8); boolean flag2 = false; for(int k2 = i2; k2 <= j2; k2++) { if(!_bkIx(k2)._c9vZ()) continue; flag2 = true; break; } if(flag2) { InstructionTarget x10 = ad1._dMvx(); if(!x10._c9vZ()) flag1 = true; if(_cxI(x10) <= i2) x10._dAvV(); else x10._c8vV(); } } } while(flag1); for(i1 = _d3vI(); --i1 >= 0;) { InstructionTarget x3 = _bkIx(i1); if(x3._dxvI() > 0 && !x3._baIZ(9)) { if(!x3._baIZ(4) && !x3._baIZ(6)) { z_o2Z = true; if(!x3._c9vZ()) x3._c8vV(); } break; } } i1 = _dPvI(); for(int l = 0; l < i1; l++) { al al1 = _buIal(l); InstructionTarget x7 = al1._d8vx(); x7._dgvV(); InstructionTarget x9 = al1._d9vx(); x9._dgvV(); } } InstructionTarget _ifxx(InstructionTarget x1, InstructionTarget x2) { if(x2 != x1) { int i = _cxI(x2); for(; x2._dxvI() == 0; x2 = _bkIx(i)) i++; if(x2._baIZ(6)) x2 = x2._a5Ix(0); } return x2; } boolean _dOvZ() throws CompileException { boolean flag = false; int i = _d3vI(); flag = false; boolean flag1 = false; do { flag1 = false; for(int j = 0; j < i; j++) { InstructionTarget x2 = _bkIx(j); x2._dlvV(); int i1 = x2._dsvI(); for(int k1 = 0; k1 < i1; k1++) { InstructionTarget x8 = x2._a5Ix(k1); InstructionTarget x11 = _ifxx(x2, x8); if(x11 != x8) { x2._ifxvV(x11, k1); flag = true; flag1 = true; } } } } while(flag1); for(int k = 0; k < i; k++) { InstructionTarget x3 = _bkIx(k); if(x3._baIZ(6)) { InstructionTarget x4 = x3._a5Ix(0); if(x3 != x4) { int l1 = k + 1; InstructionTarget x9 = _bkIx(l1); for(InstructionTarget x12 = x9; l1 < i; x12 = _bkIx(l1)) { if(x12 == x4) { int k2 = x3._dJvI(); x3._doxV(x9); if(x9 != x4) { l1 = k + 1; InstructionTarget x14; for(x12 = x9; x12 != x4; x12 = x14) { l1++; x14 = _bkIx(l1); x12._doxV(x14); } } flag = true; if(k2 != 0) { for(; x4 != null && x4._dxvI() == 0; x4 = x4._dwvx()); if(x4 != null) x4._bbIV(k2); } break; } if(x12._dxvI() != 0) break; l1++; } } } } InstructionTarget x1 = null; for(int l = 0; l < i; l++) { InstructionTarget x5 = _bkIx(l); if(x5._baIZ(6)) { InstructionTarget x6 = x5._a5Ix(0); if(x5._tryxZ(x6)) if(x6._baIZ(4) && x6._dxvI() <= 2) { x5._intxV(x6); flag = true; } else if(x6._dBvZ() && x1 != null && x1._tryxZ(x6) && x5._dmvZ()) { int i2 = _cxI(x6); if(i2 != 0) { InstructionTarget x13 = _bkIx(i2 - 1); int l2 = x13._casexI(x1); if(l2 != 0) { InstructionTarget x15 = x13; InstructionTarget x17 = x13._bdIx(l2); if(x17 != null) { if(i2 <= l) { x17._dAvV(); l++; } else { x17._c8vV(); } x17._dkvV(); int k3 = _cxI(x13); _doxvV(x17, k3 + 1); i++; x15 = x17; } x5._ifxvV(x15, 0); x5.setStackEntry(null); x1._a9IV(l2); flag = true; } } } } if(x5._dxvI() != 0 || !x5._dmvZ()) x1 = x5; } x1 = null; for(int j1 = 0; j1 < i; j1++) { InstructionTarget x7 = _bkIx(j1); if(x7._baIZ(6) && x1 != null) { InstructionTarget x10 = x7._a5Ix(0); if(x7 != x10 && x7._dmvZ() && x1._tryxZ(x10) && x7._tryxZ(x10)) { x10._ifxV(x1); int j2 = x10._ddvI(); if(j2 > 1) { j2--; for(int i3 = 0; i3 < j2; i3++) { InstructionTarget x16 = x10._beIx(i3); if(x1._tryxZ(x16)) { int j3 = x1._casexI(x16); if(j3 != 0) { InstructionTarget x18 = null; for(int l3 = _cxI(x16) + 1; l3 < i; l3++) { InstructionTarget x19 = _bkIx(l3); if(!x19._dmvZ()) break; if(x19._baIZ(6)) { x18 = x19; break; } if(x19._dxvI() != 0) break; } if(x18 != null) { InstructionTarget x20 = x1; InstructionTarget x21 = x1._bdIx(j3); if(x21 != null) { x21._c8vV(); x21._dkvV(); int i4 = _cxI(x1); _doxvV(x21, i4 + 1); j1++; i++; x20 = x21; } x18._ifxvV(x20, 0); x18.setStackEntry(null); x16._a9IV(j3); x10._bfIV(i3); j2--; i3--; x20._ifxV(x16); flag = true; if(x21 != null) { x10._bfIV(j2); x10._ifxV(x21); x1 = x21; } } } } } } } } if(x7._dxvI() != 0 || !x7._dmvZ()) x1 = x7; } return flag; } boolean _d4vZ() { boolean flag = false; for(int i = _dVvI() - 1; i >= 0; i--) { ad ad1 = _bpIad(i); InstructionTarget x1 = ad1._dNvx(); int j = _cxI(x1); for(InstructionTarget x2 = ad1._dKvx(); x1._dxvI() == 0 && x1 != x2; x1 = _bkIx(j)) j++; if(x1._dxvI() == 0) { _bwIV(i); flag = true; } } return flag; } boolean _dRvZ() { int i = _d3vI(); boolean flag = false; boolean flag1; do { flag1 = false; _dZV(false); for(int j = 0; j < i - 1; j++) { InstructionTarget x1 = _bkIx(j); if(!x1._c9vZ()) if(x1._dwvx() != null || x1._dsvI() != 0) { x1._dJvI(); flag1 = true; } else if(x1._dxvI() != 0) { x1._dJvI(); flag1 = true; } } flag |= flag1; } while(flag1); return flag; } void _bnIV(int i) throws CompileException { i = i; boolean flag; do { flag = false; flag |= _dOvZ(); flag |= _d4vZ(); flag |= _dRvZ(); } while(flag); } private int _eZI(boolean flag) throws CompileException { InstructionTarget x1 = null; int i = 0; int j = _d3vI() - 1; for(int k = 0; k < j; k++) { x1 = _bkIx(k); i = x1._forIZI(i, flag); } x1 = _bkIx(j); x1.setOffset(i); x1._a7IV(1); return i; } void _dQvV() throws CompileException { for(int i = _dVvI() - 1; i >= 0; i--) { ad ad1 = _bpIad(i); InstructionTarget x1 = ad1._dKvx(); int k = x1.getOffset() + x1._dxvI(); if(ad1._dNvx().getOffset() == k) _bwIV(i); else ad1._elsexV(_bvIx(k)); } for(int j = _dPvI() - 1; j >= 0; j--) { al al1 = _buIal(j); InstructionTarget x2 = al1._d9vx(); int l = x2.getOffset() + x2._dxvI(); al1._exV(_bvIx(l)); } } void _dXvV() throws CompileException { boolean flag; do { flag = false; _dZV(false); for(int i = _d3vI() - 1; i >= 0; i--) { InstructionTarget x1 = _bkIx(i); InstructionTarget x3 = x1._dwvx(); if(x3 != null) if(x3._dxvI() == 0) { x1._doxV(_bvIx(x3.getOffset())); flag = true; } else if(x3._dmvZ() && x3.getStackEntry() == null && !x3._dzvZ() && x1._dsvI() == 0) { x1._forxV(x3); flag = true; } for(int i1 = x1._dsvI() - 1; i1 >= 0; i1--) { InstructionTarget x4 = x1._a5Ix(i1); if(x4._dxvI() == 0) { x1._ifxvV(_bvIx(x4.getOffset()), i1); flag = true; } } } for(int j = _dVvI() - 1; j >= 0; j--) { ad ad1 = _bpIad(j); InstructionTarget x5 = ad1._dNvx(); if(x5._dxvI() == 0) ad1._longxV(_bvIx(x5.getOffset())); InstructionTarget x7 = ad1._dKvx(); if(x7._dxvI() == 0) ad1._elsexV(_bvIx(x7.getOffset())); InstructionTarget x9 = ad1._dMvx(); if(x9._dxvI() == 0) ad1._gotoxV(_bvIx(x9.getOffset())); } for(int k = _dPvI() - 1; k >= 0; k--) { al al1 = _buIal(k); InstructionTarget x6 = al1._d8vx(); if(x6._dxvI() == 0) al1._fxV(_bvIx(x6.getOffset())); InstructionTarget x8 = al1._d9vx(); if(x8._dxvI() == 0) al1._exV(_bvIx(x8.getOffset())); } for(int l = _d3vI() - 2; l >= 0; l--) { InstructionTarget x2 = _bkIx(l); if(x2._dxvI() == 0) _boIV(l); } } while(flag); } void _d1vV() throws CompileException { int i1 = _dVvI(); for(int i = 0; i < i1; i++) { ad ad1 = _bpIad(i); int j1 = ad1._dNvx().getOffset(); for(int i2 = i + 1; i2 < i1; i2++) { ad ad4 = _bpIad(i2); if(ad1._dMvx() != ad4._dMvx() || ad1._dLvg() != ad4._dLvg()) break; int j3 = ad4._dNvx().getOffset(); if(j1 > j3) { j1 = j3; ad1 = ad4; _longIIV(i, i2); } } } for(int j = 0; j < _dVvI() - 1; j++) { ad ad2 = _bpIad(j); ad ad3 = _bpIad(j + 1); if(ad2._dMvx() == ad3._dMvx() && ad2._dLvg() == ad3._dLvg() && ad2._aadZ(ad3)) { int j2 = ad2._dKvx().getOffset(); int i3 = ad3._dKvx().getOffset(); if(i3 > j2) ad2._elsexV(ad3._dKvx()); _bwIV(j + 1); j--; } } i1 = _dPvI(); for(int k = 0; k < i1; k++) { al al1 = _buIal(k); int k1 = al1._d8vx().getOffset(); for(int k2 = k + 1; k2 < i1; k2++) { al al4 = _buIal(k2); int k3 = al4._d8vx().getOffset(); if(k1 > k3) { k1 = k3; al al2 = al4; _elseIIV(k, k2); } } } for(int l = 0; l < _dPvI(); l++) { al al3 = _buIal(l); int l1 = al3._d9vx().getOffset(); for(int l2 = l + 1; l2 < _dPvI(); l2++) { al al5 = _buIal(l2); int l3 = al5._d8vx().getOffset(); if(l1 < l3) break; if(al3._eavaf().equals(al5._eavaf()) && al3._aalZ(al5)) { int i4 = al5._d9vx().getOffset(); if(i4 > l1) { l1 = i4; al3._exV(al5._d9vx()); } _blIV(l2); l2--; } } } } public int _brII(int i) throws CompileException { _dZvV(); _d7vV(); for(int j = 0; j < _d3vI(); j++) { InstructionTarget x1 = _bkIx(j); if(x1._baIZ(1)) { _bqIV(j + 1); _bxV(x1._dwvx()); x1._ifaiV(this); _dWvV(); _dYvV(); } } _bnIV(i); int k = _eZI(false); _dQvV(); _dXvV(); _d1vV(); _dZV(false); return k; } public int _btII(int i) throws CompileException { _d7vV(); _bnIV(i); int j = _eZI(false); _dQvV(); _dXvV(); _d1vV(); _dZV(false); return j; } public int _dTvI() throws CompileException { _dRvZ(); int i = _eZI(false); _dXvV(); _dZV(false); return i; } public int _d5vI() { int i = _d3vI(); for(int j = 0; j < i; j++) _bkIx(j)._dqvV(); InstructionTarget x1 = _bkIx(0); x1._bjIV(0); x1._dtvV(); i = _dVvI(); for(int k = 0; k < i; k++) { InstructionTarget x2 = _bpIad(k)._dMvx(); x2._bjIV(1); x2._dtvV(); } i = _d3vI() - 1; boolean flag; do { flag = false; for(int l = 0; l < i; l++) { InstructionTarget x3 = _bkIx(l); if(x3._dpvZ()) { x3._dqvV(); int j1 = x3._dcvI(); InstructionTarget x4 = x3._dwvx(); if(x4 != null && x4._dIvI() < j1) { x4._bjIV(j1); x4._dtvV(); flag = true; } if(x3._baIZ(8)) j1--; int i2 = x3._dsvI(); for(int j2 = 0; j2 < i2; j2++) { InstructionTarget x5 = x3._a5Ix(j2); if(x5 != x3 && x5._dIvI() < j1) { x5._bjIV(j1); x5._dtvV(); flag = true; } } } } } while(flag); int i1 = 0; for(int k1 = 0; k1 < i; k1++) { int l1 = _bkIx(k1)._dbvI(); if(l1 > i1) i1 = l1; } return i1; } public int _d6vI() throws CompileException { return _eZI(true); } public int _d2vI() { int i = 0; int j = _d3vI(); for(int k = 0; k < j; k++) i += _bkIx(k)._dhvI(); return i; } }
fc2a93db1556dfac9cf0cbcb07aab72af5da1267
d8d1f3ea057b40ef2a80672ee43a7278f591b3ff
/MacroProcessor/src/com/macro/MacroProcessor.java
643e9c1a07bf2600eafc6f4bc452af1b5f26344d
[ "Apache-2.0" ]
permissive
Otaka/mydifferentprojects
3e0971fc08a563660d943942cc9dd682cf7ee81a
28489042fb574d1178a6d814b6accc29cdc3aeed
refs/heads/master
2020-04-07T05:39:07.776684
2018-04-09T19:21:37
2018-04-09T19:21:37
40,618,466
0
0
null
null
null
null
UTF-8
Java
false
false
5,321
java
package com.macro; import com.macro.exception.MacrosCompilationException; import com.macro.functions.AbstrMacroFunction; import com.macro.functions.AbstrMacroFunctionWithoutBrackets; import com.macro.tokenizer.Token; import com.macro.tokenizer.TokenType; import com.macro.tokenizer.Tokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author sad */ public class MacroProcessor { private final Map<String, AbstrMacroFunction> macroFunctions = new HashMap<>(); public MacroProcessor() { } public void addMacroFunction(String macroFunction, AbstrMacroFunction function) { macroFunctions.put(macroFunction, function); } private AbstrMacroFunction getMacroFunction(String name) { return macroFunctions.get(name); } private boolean isMacroFunction(String name) { return macroFunctions.get(name) != null; } public String process(String text) { StringBuilder result = new StringBuilder(text.length()); Tokenizer tokenizer = new Tokenizer(text); while (true) { Token t = tokenizer.nextToken(); if (t == null) { break; } if (t.getTokenType() != TokenType.Data) { result.append(t.getValue()); } else { String word = t.getValue(); if (isMacroFunction(word)) { String macroResult = processMacro(word, tokenizer); result.append(macroResult); int startMacroLine = t.getLine(); int endLine = tokenizer.getLineNumber(); if (endLine != startMacroLine) { appendMissingNewLines(result, endLine - startMacroLine); } } else { result.append(word); } } } return result.toString(); } private void appendMissingNewLines(StringBuilder sb, int newLinesCount) { for(int i=0;i<newLinesCount;i++){ sb.append("\n"); } } private boolean isOpenBracket(Token t) { return t.getValue().equals("("); } private String processMacro(String macroFunction, Tokenizer tokenizer) { AbstrMacroFunction function = getMacroFunction(macroFunction); if (function instanceof AbstrMacroFunctionWithoutBrackets) { Token t = tokenizer.nextTokenSkipComment(); if (t == null) { throw new MacrosCompilationException("Find end of input while try to find argument for macrofunction [" + macroFunction + "]"); } if (isOpenBracket(t) || t.getTokenType() == TokenType.Space) { throw new MacrosCompilationException("Macrofunction [" + macroFunction + "] is macro function withot bracket. It is should be followed by the argument immideately, without spaces"); } String result = function.process(Arrays.asList(t.getValue())); return result; } else { Token t = tokenizer.nextTokenSkipSpaceAndComments(); if (!isOpenBracket(t)) { throw new MacrosCompilationException("Macrofunction [" + macroFunction + "] should be followed by the open bracket with arguments"); } List<String> args = parseArgumentList(macroFunction, tokenizer); String result = function.process(args); return result; } } private List<String> parseArgumentList(String macroFunction, Tokenizer tokenizer) { List<String> args = new ArrayList<String>(); while (true) { Token t = tokenizer.nextTokenSkipSpaceAndComments(); if (t == null) { throw new MacrosCompilationException("Found end of input while trying to find end ')' for macro function [" + macroFunction + "]"); } String textValue = t.getValue(); if (textValue.equals(")")) { break; } else if (isMacroFunction(textValue)) { textValue = processMacro(textValue, tokenizer); args.add(textValue); } else if (textValue.equals(",")) { throw new MacrosCompilationException("Found ',' but try to find argument for macro function [" + macroFunction + "]"); } else { args.add(textValue); } t = tokenizer.nextTokenSkipSpaceAndComments(); if (t == null) { throw new MacrosCompilationException("Found end of input while trying to find end ')' for macro function [" + macroFunction + "]"); } textValue = t.getValue(); if (textValue.equals(",")) { continue; } else if (textValue.equals(")")) { break; } else { throw new MacrosCompilationException("Found [" + textValue + "] while search ',' or ')' in arguments for macro function [" + macroFunction + "]"); } } return args; } }
7e2a796f372e2366c449993adfbc7c0898ba882f
825113f81c8cc762f540b97e3509e79a2fadaf68
/src/main/java/ibm/eda/demo/app/infrastructure/OrderEventProducer.java
6ee6ed985fbe47443b4929995304f80a4d05d799
[]
no_license
juangarcia4ks/quarkus-kafka-producer
44da896112fc606209746d54fb7d57c0cffb0979
44c11a349859d2ec46ebf394688de53ff0d96fb2
refs/heads/master
2023-06-06T21:48:50.313021
2021-07-02T14:38:02
2021-07-02T14:38:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,328
java
package ibm.eda.demo.app.infrastructure; import java.util.List; import java.util.UUID; import javax.inject.Singleton; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.jboss.logging.Logger; import ibm.eda.demo.app.infrastructure.events.EventEmitter; import ibm.eda.demo.app.infrastructure.events.OrderEvent; @Singleton public class OrderEventProducer implements EventEmitter { Logger logger = Logger.getLogger(OrderEventProducer.class.getName()); private KafkaProducer<String,OrderEvent> kafkaProducer = null; private KafkaConfiguration configuration = null; public OrderEventProducer() { super(); configuration = new KafkaConfiguration(); kafkaProducer = new KafkaProducer<String, OrderEvent>(configuration.getProducerProperties("OrderProducer_" + UUID.randomUUID())); } public OrderEventProducer(KafkaConfiguration configuration) { this.configuration = configuration; } public void sendOrderEvents(List<OrderEvent> l) { for (OrderEvent t : l) { emit(t); } } public void emit(OrderEvent oevent) { ProducerRecord<String, OrderEvent> producerRecord = new ProducerRecord<String, OrderEvent>( configuration.getTopicName(), oevent.getOrderID(), oevent); logger.info("sending to " + configuration.getTopicName() + " item " + producerRecord .toString()); try { this.kafkaProducer.send(producerRecord, new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception != null) { exception.printStackTrace(); } else { logger.info("The offset of the record just sent is: " + metadata.offset()); } } }); } catch (Exception e) { e.printStackTrace(); } // logger.info("Partition:" + resp.partition()); } @Override public void safeClose(){ kafkaProducer.close(); kafkaProducer = null; } }
24a1206ced7accc818d9b1106773570c3fd37320
2d253b99c2f1a6940e10c578b285a6365653db17
/inda08/vt6/src/InsertionSort.java
214ee7d80d25d71f81535d236ef21747f171730c
[]
no_license
Hkau/kth
3e5bf4ca8302bfdc477bb12e09a123023ea60529
68e10faad71ea4026e3fb9a4588d85fe545bee17
refs/heads/master
2021-10-27T09:53:47.274504
2021-10-15T07:40:57
2021-10-15T07:40:57
19,637,092
0
0
null
null
null
null
UTF-8
Java
false
false
478
java
/** * @author lemming * Implementation av Insertion sort. * * Sorterar monster (Se Pokédex för referens av vilka monster som sorteras). */ public class InsertionSort implements Sorting{ /** * Sortera en array av intar * @param v array att sortera */ public void sort(int[] v){ for(int i = 1; i < v.length; ++i){ if(v[i-1]>v[i]){ int tmp = v[i]; int j = i; while(j > 0 && v[j-1] > tmp){ v[j] = v[--j]; } v[j] = tmp; } } } }
42ff1b1ac3003d63b60f016ba0d3e58669593d5d
5f3e4f47da5f34149eb64b7f66ff8076d4c09fbb
/src/test/java/testcases/arrivalCalendarClick.java
582764d38ad4f12d5d46ac69f9ffc2803110b67d
[]
no_license
subhashc2706/HappyTrip-selenium
dbed7e2a9f5f2de224ab37f0216c66edfcb4c25a
58b229ed6aac208fddc3619ae3a17e915bcba7a0
refs/heads/master
2022-11-17T05:09:39.532997
2020-07-03T20:24:19
2020-07-03T20:24:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
936
java
package testcases; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.Test; public class arrivalCalendarClick { private static Logger Log = LogManager.getLogger(arrivalCalendarClick.class.getName()); excel ex=new excel(); @Test public void arrivalCalendarClick_() { Log.info("entering as admin"); ex.signin("[email protected]", "admin"); Log.info("Checking for clicking on arrival calendar"); WebElement calendar = ex.driver.findElement(By.xpath("//*[@id=\"AddSchedule\"]/dl/dd[8]/img")); calendar.click(); String expected = "1"; WebElement element= ex.driver.findElement(By.className(("ui-state-default"))); String actual= element.getText(); Assert.assertEquals(actual, expected); ex.driver.navigate().refresh(); ex.driver.close(); } }
229b7303fdd2c2edf4a43c69b56e4691898f8306
ebf2540973f3479897bbef5e7b19d65d879e8a23
/src/main/java/edu/mssm/pharm/maayanlab/G2N/enrichment/G2Nweb.java
7b135c336ab95ce4d1466d12a40743f7e19ec674
[ "Apache-2.0" ]
permissive
MaayanLab/g2n
4ab9a97dc05dca7dc23c5052cdb1c682000d6458
7cae4ed646dadfb8d76ba6770e18e41ed24d10b8
refs/heads/master
2021-07-10T13:54:15.557850
2020-07-07T22:33:32
2020-07-07T22:33:32
144,897,502
0
0
Apache-2.0
2020-07-07T00:31:48
2018-08-15T19:57:27
Java
UTF-8
Java
false
false
6,355
java
package edu.mssm.pharm.maayanlab.G2N.enrichment; import edu.mssm.pharm.maayanlab.Genes2Networks.Genes2Networks; import edu.mssm.pharm.maayanlab.Genes2Networks.NetworkNode; import edu.mssm.pharm.maayanlab.common.core.Settings; import edu.mssm.pharm.maayanlab.common.core.SettingsChanger; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; public class G2Nweb implements SettingsChanger { private final static String MAXIMUM_PATH_LENGTH = "max_path_length"; private final static String MINIMUM_NETWORK_SIZE = "min_network_size"; private final static String ENABLE_YED_OUTPUT = "output results in yEd"; private final static String ENABLE_CYTOSCAPE_OUTPUT = "output results in Cytoscape"; private final static String ENABLE_PAJEK_OUTPUT = "output results in Pajek"; private final static String TF_NODE_COLOR = "color of TF nodes"; private final static String KINASE_NODE_COLOR = "color of kinase nodes"; private final static String SUBSTRATE_NODE_COLOR = "color of substrate nodes"; private final static String PATH_LENGTH = "actual_path_length"; private final Settings settings = new Settings() { { // Integer: minimum network size; otherwise, the path length is increased until the minimum met. [>0] set(G2Nweb.MINIMUM_NETWORK_SIZE, 50); // Integer: minimum path length [>0] set(G2Nweb.MAXIMUM_PATH_LENGTH, 4); // Boolean: output a yEd graphml file for network visualization. [true/false] set(G2Nweb.ENABLE_YED_OUTPUT, true); // Boolean: output a Cytoscape XGMML file for network visualization. [true/false] set(G2Nweb.ENABLE_CYTOSCAPE_OUTPUT, false); // Boolean: output a Pajek NET file for network visualization. [true/false] set(G2Nweb.ENABLE_PAJEK_OUTPUT, false); // String: web color of the transcription factors in the Cytoscape and yEd network outputs. [#000000 - #FFFFFF] set(G2Nweb.TF_NODE_COLOR, "#FF0000"); // String: web color of the kinases in the Cytoscape and yEd network outputs. [#000000 - #FFFFFF] set(G2Nweb.KINASE_NODE_COLOR, "#00FF00"); // String: web color of the substrates in the Cytoscape and yEd network outputs. [#000000 - #FFFFFF] set(G2Nweb.SUBSTRATE_NODE_COLOR, "#FFFF00"); set(Genes2Networks.ENABLE_BIND, "false"); set(Genes2Networks.ENABLE_BIOCARTA, "false"); set(Genes2Networks.ENABLE_BIOGRID, "false"); set(Genes2Networks.ENABLE_BIOPLEX, "false"); set(Genes2Networks.ENABLE_DIP, "false"); set(Genes2Networks.ENABLE_FIGEYS, "false"); set(Genes2Networks.ENABLE_HPRD, "false"); set(Genes2Networks.ENABLE_HUMAP, "false"); set(Genes2Networks.ENABLE_IREF, "false"); set(Genes2Networks.ENABLE_INNATEDB, "false"); set(Genes2Networks.ENABLE_INTACT, "false"); set(Genes2Networks.ENABLE_KEA, "false"); set(Genes2Networks.ENABLE_KEGG, "false"); set(Genes2Networks.ENABLE_MINT, "false"); set(Genes2Networks.ENABLE_MIPS, "false"); set(Genes2Networks.ENABLE_MURPHY, "false"); set(Genes2Networks.ENABLE_PDZBASE, "false"); set(Genes2Networks.ENABLE_PPID, "false"); set(Genes2Networks.ENABLE_PREDICTEDPPI, "false"); set(Genes2Networks.ENABLE_SNAVI, "false"); set(Genes2Networks.ENABLE_STELZL, "false"); set(Genes2Networks.ENABLE_VIDAL, "false"); } }; protected Genes2Networks g2n; private HashSet<String> network; public G2Nweb(HttpServletRequest req) { Enumeration<String> reqKeys = req.getParameterNames(); for (String setting : Collections.list(reqKeys)) { this.setSetting(setting, req.getParameter(setting)); } } public G2Nweb(Settings settings) { settings.loadSettings(settings); } @Override public void setSetting(String key, String value) { settings.set(key, value); } public void run(ArrayList<String> inputList) { g2n = new Genes2Networks(settings); int path_length = Math.min( settings.getInt(Genes2Networks.PATH_LENGTH), settings.getInt(MAXIMUM_PATH_LENGTH) ); do { g2n.setSetting(Genes2Networks.PATH_LENGTH, Integer.toString(path_length)); g2n.run(inputList); network = g2n.getNetwork(); path_length++; } while ( network.size() < settings.getInt(MINIMUM_NETWORK_SIZE) && path_length < settings.getInt(MAXIMUM_PATH_LENGTH) ); setSetting(G2Nweb.PATH_LENGTH, Integer.toString(path_length - 1)); } public Network webNetworkFiltered(ArrayList<String> textGenes) { Network network = new Network(); ArrayList<String> SimpleNames = new ArrayList<>(); ArrayList<NetworkNode> inputNodes = new ArrayList<>(); for (String inputNode : textGenes) { inputNodes.add(new NetworkNode(inputNode, "NA", "NA", "inputNode", "NA")); } for (NetworkNode in : inputNodes) { network.addNode(Network.nodeTypes.inputNode, in, in.getName()); SimpleNames.add(in.getName()); } HashSet<NetworkNode> networkSet = g2n.getNetworkSet(); for (NetworkNode node : networkSet) { if (node.getName() != null) { if (!SimpleNames.contains(node.getName())) { network.addNode(Network.nodeTypes.networkNode, node, node.getName().split("-")[0]); } } } for (NetworkNode node : networkSet) { HashSet<NetworkNode> neighbors = node.getNeighbors(); for (NetworkNode neighbor : neighbors) { if ((neighbor.getName() != null) && (node.getName() != null)) { if (network.contains(neighbor.getName())) { network.addInteraction(node.getName().split("-")[0], neighbor.getName().split("-")[0]); } } } } return network; } }
bb04b2da6101b11cc8a35720741e4c50c5b386e9
941713442f50815895364ef64ac499739f1dd951
/src/exercises_complete/ProjectDaoSellerDepartment/DepartmentDao.java
c0e62436376edbd1d07b652a4878216246956e06
[]
no_license
Gabrielcf200/Java_exercises
977b440f0ea3baf81fe6766fc20ba1bac462370c
726366e45b44e22f14cb3a5e4670cbcc66576f48
refs/heads/main
2023-04-05T13:08:15.144675
2021-04-05T17:47:28
2021-04-05T17:47:28
344,861,637
0
0
null
null
null
null
UTF-8
Java
false
false
289
java
package exercises_complete.ProjectDaoSellerDepartment; import java.util.List; public interface DepartmentDao { void insert(Department obj); void update(Department obj); void deleteById(Integer id); Department findById(Integer id); List <Department> findAll(); }
a8f79291e25cd126a78f0427f59831affbda9255
850c6f3b61e23229249b145a8421edb58edd5205
/application/src/main/java/com/changhong/system/web/event/AbstractActionEvent.java
bf353574d394fb0e43dde871159f2401ed4d969c
[]
no_license
kunkun39/UPDATE
f42003a8ef0d39fda2692c90ef68e9bbdcb342ce
25d86495ec0b6a2662a2f4e0151312fe09cacc17
refs/heads/master
2021-01-17T09:27:20.314280
2016-04-13T01:39:08
2016-04-13T01:39:08
23,613,118
0
0
null
null
null
null
UTF-8
Java
false
false
877
java
package com.changhong.system.web.event; import com.changhong.system.domain.SystemActionLog; import org.springframework.context.ApplicationEvent; /** * User: Jack Wang * Date: 14-5-5 * Time: 上午11:27 */ public class AbstractActionEvent extends ApplicationEvent { private SystemActionLog.ActionType type; private String userName; private String userNumber; public AbstractActionEvent(Object source, SystemActionLog.ActionType type, String userName, String userNumber) { super(source); this.userName = userName; this.userNumber = userNumber; this.type = type; } public SystemActionLog.ActionType getType() { return type; } public String getUserName() { return userName; } public String getUserNumber() { return userNumber; } }
aee1d6495b63063ba197e51344ca574159f6aa90
3fc42365268a1f60a37aab30ffd3f4b17759ef0f
/Ex28.java
7cc8e8ed42d9894c4a66f36675fd1d0a78f6c7f6
[]
no_license
FuruyaSKR/Lista-de-Exercicios-3
3663bc7f953608da184ff37060eba456e9d7386f
54048215e77944a79551c6ac184eb051f9f8035e
refs/heads/master
2020-07-04T22:42:25.155216
2019-08-15T00:33:04
2019-08-15T00:33:04
202,445,718
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
1,223
java
import java.util.Scanner; public class Ex28 { public static void main (String[] args) { Scanner entrada = new Scanner(System.in); boolean sair = false; int tempmaior = 0; int tempmenor = 0; int media = 0; boolean fi = true; int i = 0; while(sair != true) { System.out.println("Digite um temperatura: "); int temp = entrada.nextInt(); if(fi == true) { tempmaior = temp; tempmenor = temp; }else if (temp > tempmaior) { tempmaior = temp; }else if(temp < tempmenor) { tempmenor = temp; } fi = false; media = media + temp; i++; System.out.println("Deseja continuar? \n1- Continuar \n2- Parar o Programa"); int nintendo = entrada.nextInt(); switch(nintendo) { case(1): System.out.println("Continuando \n. \n. \n."); break; case(2): sair = true; break; default: System.out.println("Continuando \n. \n. \n."); } } System.out.println("Temperatura mais alta: "+tempmaior+" °C"); System.out.println("Temperatura menor :"+tempmenor+" °C"); media = media / i; System.out.println("Media de Temperatura: "+media+" °C"); } }
f7254f526c63348a8d9596736eff0e044f54bd53
4b50c09e08b29a88db1ed1fa8bdc173c7305fa1b
/Atividades POO - Semana 2/Atividade 2/src/livro/Autor.java
5705d876551748aba0589734dca789dd36ca5347
[ "MIT" ]
permissive
LuizFN/ProjetosJava
3aad9ef89a35599d7faf70db13c20f6c585748e3
3fd68924fe56208443c6c057b4fbdc9425a24ad7
refs/heads/main
2023-03-19T10:14:18.841038
2021-03-16T19:36:43
2021-03-16T19:36:43
null
0
0
null
null
null
null
ISO-8859-1
Java
false
false
654
java
package livro; public class Autor { private String nome; private String pais; private String sexo; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getPais() { return pais; } public void setPais(String pais) { this.pais = pais; } public String getSexo() { return sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public void imprimir() { System.out.println("Mais Informações Sobre o Autor:"); System.out.println("Nome: " + this.nome); System.out.println("País de Origem: " + this.pais); System.out.println("Sexo: " + this.sexo); } }
a5cbd8153bae24def97576eeffd66934e50a0c29
0c295ea54071f2b785b7d2d4504730ce2032e1ae
/javapractice/src/trees/BinaryTreeboundaryTraversal.java
5315603ace3faba54effe7fb05d9a0fca9238817
[]
no_license
sivasai-mudigonda/JAVA-Programs
9e221417bfa351a749736a06acfcd6a9a4f15fe1
2668a7e30d84411b33f77e006613a9dbcc46c41f
refs/heads/master
2022-11-21T07:32:01.489894
2019-12-28T04:44:46
2019-12-28T04:45:35
143,819,767
0
0
null
null
null
null
UTF-8
Java
false
false
2,034
java
package trees; /** * * Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise * starting from the root? Refer * https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/ * */ // Print Binary Tree Boundary in Anti Clock Wise Direction. public class BinaryTreeboundaryTraversal { Node root; // Driver program to test above functions public static void main(String args[]) { BinaryTreeboundaryTraversal tree = new BinaryTreeboundaryTraversal(); tree.root = new Node(20); tree.root.left = new Node(8); tree.root.left.left = new Node(4); tree.root.left.right = new Node(12); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(14); tree.root.right = new Node(22); tree.root.right.right = new Node(25); tree.printBoundary(tree.root); } private void printBoundary(Node root) { if (root != null) { System.out.print(root.data + " "); printLeftTree(root.left); printLeaf(root.left); printLeaf(root.right); printRightTree(root.right); } } private void printLeftTree(Node node) { if (node != null) { if (node.left != null) { System.out.print(node.data + " "); printLeftTree(node.left); } else if (node.right != null) { System.out.print(node.data + " "); printLeftTree(node.right); } // Do not do anything if it is a leaf. } } private void printRightTree(Node node) { if (node != null) { if (node.right != null) { printRightTree(node.right); System.out.print(node.data + " "); } else if (node.left != null) { printRightTree(node.left); System.out.print(node.data + " "); } } // Do not do anything if it is a leaf. } private void printLeaf(Node node) { if (node != null) { printLeaf(node.left); if (node.right == null && node.left == null) { System.out.print(node.data + " "); } printLeaf(node.right); } } private static class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; } } }
7ae624788695bf6c496c09255da2352a080eb0d2
e26a8434566b1de6ea6cbed56a49fdb2abcba88b
/model-seev-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CorporateActionInstructionCancellationRequest002V04.java
2df5e5e935c3c22c8df64462fc296255d7dad581
[ "Apache-2.0" ]
permissive
adilkangerey/prowide-iso20022
6476c9eb8fafc1b1c18c330f606b5aca7b8b0368
3bbbd6804eb9dc4e1440680e5f9f7a1726df5a61
refs/heads/master
2023-09-05T21:41:47.480238
2021-10-03T20:15:26
2021-10-03T20:15:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,465
java
package com.prowidesoftware.swift.model.mx.dic; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Scope * An account owner sends the CorporateActionInstructionCancellationRequest message to an account servicer to request cancellation of a previously sent corporate action election instruction. * Usage * The message may also be used to: * - re-send a message previously sent (the sub-function of the message is Duplicate), * - provide a third party with a copy of a message for information (the sub-function of the message is Copy), * - re-send to a third party a copy of a message for information (the sub-function of the message is Copy Duplicate), * using the relevant elements in the business application header (BAH). * ISO 15022 - 20022 COEXISTENCE SUBSET * This message definition is a subset of an ISO 20022 message that was reversed engineered from ISO 15022. A subset is a message definition that is compatible with another definition, but is more restrictive * The ISO 15022 and ISO 20022 standards will coexist for a number of years. Until this coexistence period ends, the usage of certain data types is restricted to ensure interoperability between ISO 15022 and 20022 users. These restrictions, which are described by textual usage rules in the ISO 20022 message, have been made mandatory in this subset. * NOTE: The ISO 20022 message coexistence textual rules have been kept in the subset to explain why specific data types have been restricted. These textual rules are identified as follows: CoexistenceXxxxRule. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CorporateActionInstructionCancellationRequest002V04", propOrder = { "chngInstrInd", "instrId", "corpActnGnlInf", "acctDtls", "corpActnInstr", "splmtryData" }) public class CorporateActionInstructionCancellationRequest002V04 { @XmlElement(name = "ChngInstrInd") protected Boolean chngInstrInd; @XmlElement(name = "InstrId", required = true) protected DocumentIdentification19 instrId; @XmlElement(name = "CorpActnGnlInf", required = true) protected CorporateActionGeneralInformation68 corpActnGnlInf; @XmlElement(name = "AcctDtls", required = true) protected AccountIdentification19 acctDtls; @XmlElement(name = "CorpActnInstr", required = true) protected CorporateActionOption43 corpActnInstr; @XmlElement(name = "SplmtryData") protected List<SupplementaryData1> splmtryData; /** * Gets the value of the chngInstrInd property. * * @return * possible object is * {@link Boolean } * */ public Boolean isChngInstrInd() { return chngInstrInd; } /** * Sets the value of the chngInstrInd property. * * @param value * allowed object is * {@link Boolean } * */ public CorporateActionInstructionCancellationRequest002V04 setChngInstrInd(Boolean value) { this.chngInstrInd = value; return this; } /** * Gets the value of the instrId property. * * @return * possible object is * {@link DocumentIdentification19 } * */ public DocumentIdentification19 getInstrId() { return instrId; } /** * Sets the value of the instrId property. * * @param value * allowed object is * {@link DocumentIdentification19 } * */ public CorporateActionInstructionCancellationRequest002V04 setInstrId(DocumentIdentification19 value) { this.instrId = value; return this; } /** * Gets the value of the corpActnGnlInf property. * * @return * possible object is * {@link CorporateActionGeneralInformation68 } * */ public CorporateActionGeneralInformation68 getCorpActnGnlInf() { return corpActnGnlInf; } /** * Sets the value of the corpActnGnlInf property. * * @param value * allowed object is * {@link CorporateActionGeneralInformation68 } * */ public CorporateActionInstructionCancellationRequest002V04 setCorpActnGnlInf(CorporateActionGeneralInformation68 value) { this.corpActnGnlInf = value; return this; } /** * Gets the value of the acctDtls property. * * @return * possible object is * {@link AccountIdentification19 } * */ public AccountIdentification19 getAcctDtls() { return acctDtls; } /** * Sets the value of the acctDtls property. * * @param value * allowed object is * {@link AccountIdentification19 } * */ public CorporateActionInstructionCancellationRequest002V04 setAcctDtls(AccountIdentification19 value) { this.acctDtls = value; return this; } /** * Gets the value of the corpActnInstr property. * * @return * possible object is * {@link CorporateActionOption43 } * */ public CorporateActionOption43 getCorpActnInstr() { return corpActnInstr; } /** * Sets the value of the corpActnInstr property. * * @param value * allowed object is * {@link CorporateActionOption43 } * */ public CorporateActionInstructionCancellationRequest002V04 setCorpActnInstr(CorporateActionOption43 value) { this.corpActnInstr = value; return this; } /** * Gets the value of the splmtryData property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the splmtryData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSplmtryData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SupplementaryData1 } * * */ public List<SupplementaryData1> getSplmtryData() { if (splmtryData == null) { splmtryData = new ArrayList<SupplementaryData1>(); } return this.splmtryData; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the splmtryData list. * @see #getSplmtryData() * */ public CorporateActionInstructionCancellationRequest002V04 addSplmtryData(SupplementaryData1 splmtryData) { getSplmtryData().add(splmtryData); return this; } }
1451811ed7ada25b6c77804a64deb7701d158778
9164db656e8c89b0598c90612f39704a1d0262fd
/TestApplication1/fullscreentest/src/main/java/com/example/yinhf/fullscreentest/StartingWindow.java
16d6f1cee810cc085cb9d65a2147643d63909247
[]
no_license
yinhangfeng/Diordna
78436d2ea6b299bdc37647427b8913473fc689bc
c9351b0e783aa83b11536ba134a64e7062218f41
refs/heads/master
2020-05-30T04:37:41.241569
2017-06-15T07:42:14
2017-06-15T07:42:14
30,445,826
1
0
null
null
null
null
UTF-8
Java
false
false
5,394
java
package com.example.yinhf.fullscreentest; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Handler; import android.os.IBinder; import android.os.SystemClock; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.PopupWindow; import java.lang.reflect.Method; public class StartingWindow { private static final String TAG = "LoadingWindow"; private static final int MIN_LOADING_DURATION = 2333; private static final int MAX_LOADING_DURATION = 8000; private static final Handler handler = new Handler(); public interface OnHideListener { void onHide(); } private Activity context; private OnHideListener mOnHideListener; private PopupWindow popupWindow; private long showStartTime; /** * @param onHideListener 隐藏回调 * @param imgRes 载入界面图片 */ public StartingWindow(Activity context, OnHideListener onHideListener, int imgRes) { mOnHideListener = onHideListener; this.context = context; ImageView imageView = new ImageView(context); imageView.setImageResource(imgRes); //imageView.setBackgroundColor(Color.WHITE); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setBackgroundColor(0xffee7777); popupWindow = new PopupWindow(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); popupWindow.setFocusable(true); popupWindow.setTouchable(true); popupWindow.setOutsideTouchable(false); // try { // Method setWindowLayoutType = PopupWindow.class.getDeclaredMethod("setWindowLayoutType", int.class); // setWindowLayoutType.setAccessible(true); // //设置WindowManager.LayoutParams.type为LAST_APPLICATION_WINDOW 使得本窗口在所有alert之上(只能在popupWindow之上) // setWindowLayoutType.invoke(popupWindow, android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW); // } catch(Exception e) { // e.printStackTrace(); // } popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { if(mOnHideListener != null) { mOnHideListener.onHide(); } } }); } public void show() { show(MAX_LOADING_DURATION); } /** * 显示载入页面 * @param maxDuration 最大界面显示时间 <=0则需手动hide,如果<MIN_LOADING_DURATION 则会使用MIN_LOADING_DURATION */ public void show(int maxDuration) { if(popupWindow.isShowing()) { return; } // try { // Method showAtLocation = PopupWindow.class.getDeclaredMethod("showAtLocation", IBinder.class, int.class, int.class, int.class); // showAtLocation.setAccessible(true); // showAtLocation.invoke(popupWindow, null, Gravity.NO_GRAVITY, 0, 0); // } catch(Exception e) { // e.printStackTrace(); // return; // } popupWindow.showAtLocation(context.getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, 0); showStartTime = SystemClock.elapsedRealtime(); if(maxDuration > 0) { if(maxDuration < MIN_LOADING_DURATION) { maxDuration = MIN_LOADING_DURATION; } handler.postDelayed(dismissWindowRunnable, maxDuration); } setFullScreen(true); } /** * 隐藏载入界面 * @param checkDuration 隐藏时是否检测MIN_LOADING_DURATION */ public void dismiss(boolean checkDuration) { if(!popupWindow.isShowing()) { return; } //UiThreadHelper.removeCallbacks(dismissWindowRunnable); if(checkDuration) { long dt = SystemClock.elapsedRealtime() - showStartTime; long remainTime = MIN_LOADING_DURATION - dt; if(remainTime > 0) { handler.postDelayed(dismissWindowRunnable, remainTime); } else { popupWindow.dismiss(); } } else { popupWindow.dismiss(); } setFullScreen(false); } private Runnable dismissWindowRunnable = new Runnable() { @Override public void run() { dismiss(false); } }; private void setFullScreen(boolean b) { View v; v = popupWindow.getContentView(); //v = context.getWindow().getDecorView(); if(b) { v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } else { handler.postDelayed(new Runnable() { @Override public void run() { context.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); } }, 20); } } }
9fb67bab9e388bffc5c5671666321a97dce781e6
3f6cab445b551f7b6c35a1fe4f179587075fbca0
/src/Klondike.java
1c0dd0a6d1cfdb17fef10a785b6e67e7225f876f
[]
no_license
achigbrow/klondike-solitaire
28356ee1952145a0405b5b0b8d5d9222dca1baab
ec7c34ed9f9645e28687ebd36f942246775e7231
refs/heads/master
2020-09-25T05:13:40.748441
2019-12-06T04:01:23
2019-12-06T04:01:23
225,925,234
0
0
null
null
null
null
UTF-8
Java
false
false
7,043
java
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; import javax.swing.*; import java.util.*; /** Graphic user interface for the Klondike solitaire game. */ public class Klondike { /** Color for the background. */ public static final Color DARK_GREEN = new Color(0, 63, 0); public static final int GAME_WIDTH = 700; public static final int GAME_HEIGHT = 600; public static final int CARD_WIDTH = 72; public static final int CARD_HEIGHT = 96; public static final int SPLAY_OFFSET = 25; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Klondike game = new Klondike(); } }); } private class GamePanel extends JPanel { /** Game model associated with this GUI. */ private KlondikeModel model; /** null when waiting for a first mouse click. */ private boolean waitingForSource; private Deck source = null; /** Cache of loaded card images. */ private Map<String, BufferedImage> images = new HashMap<>(); public GamePanel() { setBackground(DARK_GREEN); setPreferredSize( new Dimension(GAME_WIDTH, GAME_HEIGHT) ); model = new KlondikeModel(); waitingForSource = true; addMouseListener( new MouseAdapter() { @Override public void mouseReleased( MouseEvent e ) { doMouseClick(e.getX(), e.getY()); } }); } private void doMouseClick(int x, int y) { int column = x*7/getWidth() + 1; if(column < 1) column = 1; else if (column > 7) column = 7; //System.out.println("column = " + column); if(waitingForSource) { if(y < 0.3*getHeight()) { if(column == 1) { model.drawNextCard(); } else if(column == 2 && model.getDrawPile().size() > 0) { source = model.getDrawPile(); waitingForSource = false; } } else { source = model.getTableau(column - 1); if(source.size() > 0) { waitingForSource = false; } } } else { waitingForSource = true; if(y < 0.3*getHeight()) { model.moveToFoundation(source, column - 4); } else { model.moveToTableau(source, column - 1); } } repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int xUnit = getWidth() / 7 ; int xOffset = (xUnit - CARD_WIDTH) / 2; int yPos = 20; draw(g, model.getDeck(), xOffset, yPos, false); draw(g, model.getDrawPile(), xUnit + xOffset, yPos, false); for (int i = 0; i < 4; i++) { draw(g, model.getFoundation(i), (i + 3)*xUnit + xOffset, yPos, false); } for (int i = 0; i < 7; i++) { draw(g, model.getTableau(i), i*xUnit + xOffset, (int)(0.3*getHeight()), true); } // Draw labels for foundations g.setColor(Color.WHITE); g.drawString("Clubs", 3*xUnit + xOffset, yPos - 5); g.drawString("Spades", 4*xUnit + xOffset, yPos - 5); g.drawString("Hearts", 5*xUnit + xOffset, yPos - 5); g.drawString("Diamonds", 6*xUnit + xOffset, yPos - 5); // Draw instructions g.drawString(waitingForSource ? "Click on deck, draw pile, or tableau." : "Click on destination, or on background to abort move.", 30, getHeight() - 40); } /** * Draws this deck at x, y. If splayed is false, only the top card is drawn. * Otherwise, the cards appear splayed, with cards closer to the top of the * deck lower on the screen but in front of other cards. */ public void draw(Graphics g, Deck deck, int x, int y, boolean splayed) { // Highlight deck if it's selected if(!waitingForSource && deck == source) { g.setColor(Color.YELLOW); int height = CARD_HEIGHT+10; if(splayed && deck.size() > 0) { height += SPLAY_OFFSET*(deck.size() - 1); } g.fillRect(x-5, y-5, CARD_WIDTH+10, height); } if (deck.size() == 0) { g.setColor(Color.GRAY); g.fillRect(x, y, CARD_WIDTH, CARD_HEIGHT); } else if (splayed) { for (int i = 0; i < deck.size(); i++) { draw(g, deck.getCardAt(i), x, y); y += SPLAY_OFFSET; } } else { draw(g, deck.getCardAt(deck.size() - 1), x, y); } } /** Draw one card */ private void draw(Graphics g, Card card, int x, int y) { if(card != null) { BufferedImage image = getImage(card); g.drawImage(image, x, y, CARD_WIDTH, CARD_HEIGHT, null); } } public BufferedImage getImage(Card card) { String filename = imageFilename(card); BufferedImage image = images.get(filename); if(image == null) { // Image not already stored in cache, // so load it from file and remember it try { image = ImageIO.read(new File(filename)); images.put(filename, image); } catch (Exception ex) { ex.printStackTrace(); } } return image; } } /** * Returns the filename of the image for this card. All of the files (from * http://www.jfitz.com/cards/) should be in a directory "card-images". */ public static String imageFilename(Card card) { if (!card.isFaceUp()) { return "card-images" + File.separator + "b2fv.png"; } int result = 1 + card.getSuit().ordinal(); if(card.getRank().ordinal() > 0) { result += 4 * (13 - card.getRank().ordinal()); } return "card-images" + File.separator + result + ".png"; } public Klondike() { JFrame frame = new JFrame("Klondike Solitaire"); JPanel gamePanel = new GamePanel(); frame.add(gamePanel, BorderLayout.CENTER); frame.pack(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setLocationRelativeTo ( null ); frame.setResizable ( false ); frame.setVisible ( true ); } }
86f3c46f91f2fc7f54740829e8a066d372241e40
3828e8ff124e1d628e505fd6a00a1a3ddd23cb55
/spring-mvc-demo/src/com/luv2code/springdemo/mvc/HomeController.java
e34176384ae857c232363e0a6cc8edec7e4d95f5
[]
no_license
stephen121212/JEE-Projects
6b4e2c383b6bc39899c5e761dc3f763e72b27977
1b77181a369c5087fb4128055125584a500c12f1
refs/heads/master
2020-08-01T20:09:34.576269
2020-04-03T18:01:23
2020-04-03T18:01:23
211,101,725
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package com.luv2code.springdemo.mvc; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.stereotype.Controller; @Controller public class HomeController { @RequestMapping("/") public String showPage() { return "main-menu"; } }
5ff6acd97f3c6b9b5a2fee7a742792fc01776abc
c5aa3d92daad1076fe88ee2c3196e523fa8c174d
/src/main/java/uk/ac/ncl/cs/groupproject/Exception/CommunicationFinishedException.java
03aee4dc5b61f631d887da1ef1bf606d81d5208d
[]
no_license
lizequn/privategroup
dc2618127035ce342438d858c4dbfbd6b2044796
960c3e7ac1ca7aa441d509e5ce9f304037a456aa
refs/heads/master
2021-06-05T00:44:51.306491
2018-09-11T07:49:34
2018-09-11T07:49:34
18,071,661
0
0
null
null
null
null
UTF-8
Java
false
false
360
java
package uk.ac.ncl.cs.groupproject.Exception; /** * @Auther: Li Zequn * Date: 20/03/14 */ public class CommunicationFinishedException extends RuntimeException { public CommunicationFinishedException(String message){ super(message); } public CommunicationFinishedException(){ super("Communication has already finished"); } }
743510353bf6b31e7aa24a7b92dd0c7c2fd6537a
480190757990319506cbb33dab6864d741180034
/ach/Lab2AchReducer2.java
79f5f05c5174486734e3b97a9a003ba5a0fe20d8
[]
no_license
vadimosipov/hadoop-hbase-job
a4957d0807326062f13a64cc5de2742cb618c08c
7d58cc974fdc01e002a59c92557b995e3baa19c1
refs/heads/master
2021-01-23T01:07:45.646321
2017-03-22T21:05:24
2017-03-22T21:05:24
85,875,760
0
0
null
null
null
null
UTF-8
Java
false
false
1,278
java
package lab2.ach; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.ReduceContext.ValueIterator; public class Lab2AchReducer2 extends Reducer<IntWritable, Text, Text, IntWritable> { private static final int LIMIT = 350; public Lab2AchReducer2() { } public void run(Reducer<IntWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException { int iterations = 0; while(context.nextKey()) { this.reduce((IntWritable)context.getCurrentKey(), context.getValues(), context); Iterator iter = context.getValues().iterator(); if(iter instanceof ValueIterator) { ((ValueIterator)iter).resetBackupStore(); } ++iterations; if(iterations == 350) { break; } } } protected void reduce(IntWritable count, Iterable<Text> values, Reducer<IntWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException { context.write(values.iterator().next(), new IntWritable(2147483647 - count.get())); } }
3e5d09f69fc149a222f6e58fc458e40111717bba
4ec3bf36837420a2cb84bec4adb772d2664f6e92
/FrameworkDartesESP_alunosSDIS/brokerOM2M/org.eclipse.om2m/org.eclipse.om2m.commons/src/main/java/org/eclipse/om2m/commons/resource/flexcontainerspec/DeviceTemperatureDetectorFlexContainerAnnc.java
1997aaa571fb2d4639c25da448aa906e75d2f5f7
[]
no_license
BaltasarAroso/SDIS_OM2M
1f2ce310b3c1bf64c2a95ad9d236c64bf672abb0
618fdb4da1aba5621a85e49dae0442cafef5ca31
refs/heads/master
2020-04-08T19:08:22.073674
2019-01-20T15:42:48
2019-01-20T15:42:48
159,641,777
0
2
null
2020-03-06T15:49:51
2018-11-29T09:35:02
C
UTF-8
Java
false
false
4,338
java
/* ******************************************************************************** * Copyright (c) 2014, 2017 Orange. * 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 ******************************************************************************** Device : DeviceTemperatureDetectorAnnc A SwitchButton is a device that provides button. Created: 2017-09-28 17:26:40 */ package org.eclipse.om2m.commons.resource.flexcontainerspec; 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; import org.eclipse.om2m.commons.resource.AbstractFlexContainer; import org.eclipse.om2m.commons.resource.AbstractFlexContainerAnnc; @XmlRootElement(name = DeviceTemperatureDetectorFlexContainerAnnc.SHORT_NAME, namespace = "http://www.onem2m.org/xml/protocols/homedomain") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = DeviceTemperatureDetectorFlexContainerAnnc.SHORT_NAME, namespace = "http://www.onem2m.org/xml/protocols/homedomain") public class DeviceTemperatureDetectorFlexContainerAnnc extends AbstractFlexContainerAnnc { public static final String LONG_NAME = "deviceTemperatureDetectorAnnc"; public static final String SHORT_NAME = "deTDrAnnc"; public DeviceTemperatureDetectorFlexContainerAnnc () { setContainerDefinition("org.onem2m.home.device." + DeviceTemperatureDetectorFlexContainer.LONG_NAME); setLongName(LONG_NAME); setShortName(SHORT_NAME); } public void finalizeSerialization() { getAlarmSensor(); getAlarmSensorAnnc(); getTemperature(); getTemperatureAnnc(); } public void finalizeDeserialization() { if (this.alarmSensor != null) { setAlarmSensor(this.alarmSensor); } if (this.alarmSensorAnnc != null) { setAlarmSensorAnnc(this.alarmSensorAnnc); } if (this.temperature != null) { setTemperature(this.temperature); } if (this.temperatureAnnc != null) { setTemperatureAnnc(this.temperatureAnnc); } } @XmlElement(name="alSer", required=true, type=AlarmSensorFlexContainerAnnc.class) private AlarmSensorFlexContainer alarmSensor; public void setAlarmSensor(AlarmSensorFlexContainer alarmSensor) { this.alarmSensor = alarmSensor; getFlexContainerOrContainerOrSubscription().add(alarmSensor); } public AlarmSensorFlexContainer getAlarmSensor() { this.alarmSensor = (AlarmSensorFlexContainer) getResourceByName(AlarmSensorFlexContainer.SHORT_NAME); return alarmSensor; } @XmlElement(name="alSerAnnc", required=true, type=AlarmSensorFlexContainerAnnc.class) private AlarmSensorFlexContainerAnnc alarmSensorAnnc; public void setAlarmSensorAnnc(AlarmSensorFlexContainerAnnc alarmSensorAnnc) { this.alarmSensorAnnc = alarmSensorAnnc; getFlexContainerOrContainerOrSubscription().add(alarmSensorAnnc); } public AlarmSensorFlexContainerAnnc getAlarmSensorAnnc() { this.alarmSensorAnnc = (AlarmSensorFlexContainerAnnc) getResourceByName(AlarmSensorFlexContainerAnnc.SHORT_NAME); return alarmSensorAnnc; } @XmlElement(name="tempe", required=true, type=TemperatureFlexContainerAnnc.class) private TemperatureFlexContainer temperature; public void setTemperature(TemperatureFlexContainer temperature) { this.temperature = temperature; getFlexContainerOrContainerOrSubscription().add(temperature); } public TemperatureFlexContainer getTemperature() { this.temperature = (TemperatureFlexContainer) getResourceByName(TemperatureFlexContainer.SHORT_NAME); return temperature; } @XmlElement(name="tempeAnnc", required=true, type=TemperatureFlexContainerAnnc.class) private TemperatureFlexContainerAnnc temperatureAnnc; public void setTemperatureAnnc(TemperatureFlexContainerAnnc temperatureAnnc) { this.temperatureAnnc = temperatureAnnc; getFlexContainerOrContainerOrSubscription().add(temperatureAnnc); } public TemperatureFlexContainerAnnc getTemperatureAnnc() { this.temperatureAnnc = (TemperatureFlexContainerAnnc) getResourceByName(TemperatureFlexContainerAnnc.SHORT_NAME); return temperatureAnnc; } }
37d98496603157376778e14211ef0277754fd345
5f75fa1ea11752435ae023bf197a30aaef531385
/springbootQueryAnnotaion/src/main/java/com/gaurav/repository/PersonRepository.java
4248bdbe00f4298daa2496803946b22e6f27880e
[]
no_license
kesagaurav/spring-boot
4d3acf7fbefaa1318f129b9fb23972c19c7306a4
2981e9353c7191958484a0328ad2ac9ff85eb2f9
refs/heads/master
2023-08-18T09:32:55.533272
2021-10-19T22:25:22
2021-10-19T22:25:22
418,873,324
0
0
null
null
null
null
UTF-8
Java
false
false
746
java
package com.gaurav.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.gaurav.model.Person; @Repository public interface PersonRepository extends JpaRepository<Person, Integer> { @Query(" from Person where name=:n and city=:c") List<Person> findByNameAndCity(@Param("n") String name,@Param("c")String city); @Query(" from Person where name=:n and salarly=:s") List<Person> findByNameAndSalarly(@Param("n") String name,@Param("s") String salarly); List<Person> findByGenderAndContact(String contact,String gender); }
8b700ccb2007d75aea02701e8104d4c905f235a7
4991436c2b266b2892363b4e8d421247a8d29c6e
/checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/separatorwrap/InputSeparatorWrapForArrayDeclarator.java
591d543fcc7fc624cebe48f3c687d2adc14adee4
[ "Apache-2.0" ]
permissive
spoole167/java-static-analysis-samples
d9f970104bb69abb968e0ecf09c11aa25c364ebd
880f9b394e531d8c03af425b1b4e5a95302a3359
refs/heads/main
2023-08-14T22:26:12.012352
2021-09-15T05:50:20
2021-09-15T05:50:20
406,629,824
0
0
Apache-2.0
2021-09-15T05:49:41
2021-09-15T05:49:41
null
UTF-8
Java
false
false
380
java
/* SeparatorWrap option = (default)EOL tokens = ARRAY_DECLARATOR */ package com.puppycrawl.tools.checkstyle.checks.whitespace.separatorwrap; class InputSeparatorWrapForArrayDeclarator { protected int[] arrayDeclarationWithGoodWrapping = new int[ ] {1, 2}; protected int[] arrayDeclarationWithBadWrapping = new int [] {1, 2}; // violation }
8b896ba145a8aa5230fed7ef78778e432207d83b
bbbfd6d69631eb55fcb142ee11595565fcaa482a
/GamersArc/app/src/main/java/il/ac/hit/gamersarc/MessagesFragment.java
595f45495566261a6babc9dd404fa4f925cdabbb
[]
no_license
nati888/GamersArc
f722bacdc97e1209c57d9b3d8c7bb0f522275c1b
1649499c50793461710d7d0afed46506b62f655c
refs/heads/master
2023-06-08T02:06:35.002055
2021-07-03T14:11:17
2021-07-03T14:11:17
378,909,406
0
0
null
2021-07-03T14:11:18
2021-06-21T11:36:04
Java
UTF-8
Java
false
false
3,911
java
package il.ac.hit.gamersarc; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.Collections; import il.ac.hit.gamersarc.model.UserWithLastMessage; public class MessagesFragment extends Fragment { private MessagesVM messagesVM; private ArrayList<UserWithLastMessage> friends = new ArrayList<>(); private MessagesAdepter adapter; BroadcastReceiver receiver; interface OnClickOnMessages{ void onClickMessages(User user); } private OnClickOnMessages onClickOnMessages; @Override public void onAttach(@NonNull Context context) { messagesVM = new ViewModelProvider(getActivity()).get(MessagesVM.class); try { onClickOnMessages = (il.ac.hit.gamersarc.MessagesFragment.OnClickOnMessages) context; } catch (ClassCastException e){ throw new ClassCastException("Activity must implement OnClickMessages"); } super.onAttach(context); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.messages_fragment,container,false); messagesVM.getFriendsId(); RecyclerView recyclerView = root.findViewById(R.id.recycleMessages); adapter = new MessagesAdepter(friends,getContext()); recyclerView.setAdapter(adapter); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); messagesVM.getFriends().observe(getViewLifecycleOwner(), new Observer<ArrayList<UserWithLastMessage>>() { @Override public void onChanged(ArrayList<UserWithLastMessage> users) { friends.clear(); friends.addAll(users); adapter.notifyDataSetChanged(); } }); adapter.setMessagesLitener(new MessagesAdepter.MessagesLitener() { @Override public void onClickedMessages(User user, View view) { onClickOnMessages.onClickMessages(user); messagesVM.saveIfOpen(false,user.getUserId()); } }); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int i = 0 ,k = 0; for (UserWithLastMessage user:friends) { if(intent.getStringExtra("userId").equals(user.getUser().getUserId())){ user.getMessage().setContent(intent.getStringExtra("message")); user.getMessage().setTime(intent.getStringExtra("time")); user.setNew(true); messagesVM.saveIfOpen(true,user.getUser().getUserId()); k=i; } i++; } for (int j = k; j > 0 ; j--) { Collections.swap(friends,j,j-1); } adapter.notifyDataSetChanged(); } }; IntentFilter filter = new IntentFilter("messagesReceiver"); LocalBroadcastManager.getInstance(getContext()).registerReceiver(receiver,filter); return root; } }
0f7be3b0386f92bd651a9c62c9aff27e9a5ead23
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/15/15_37d4cb60f1df834903747f508d6078d436b55fe2/FacebookRs/15_37d4cb60f1df834903747f508d6078d436b55fe2_FacebookRs_t.java
eda107a73536cc423f1ca8979bd8a312b2eadeda
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
10,530
java
/** * Copyright (c) 2009-2011, netBout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * 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 com.netbout.rest.auth; import com.netbout.rest.AbstractPage; import com.netbout.rest.AbstractRs; import com.netbout.rest.LoginRequiredException; import com.netbout.rest.page.PageBuilder; import com.netbout.spi.Identity; import com.netbout.spi.Urn; import com.restfb.DefaultFacebookClient; import com.restfb.FacebookClient; import com.restfb.types.User; import com.rexsl.core.Manifests; import com.ymock.util.Logger; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.util.Locale; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.LocaleUtils; /** * Facebook authentication page. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @see <a href="http://developers.facebook.com/docs/authentication/">facebook.com</a> */ @Path("/fb") public final class FacebookRs extends AbstractRs { /** * Namespace. */ public static final String NAMESPACE = "facebook"; /** * Facebook authentication page (callback hits it). * @param code Facebook "authorization code" * @return The JAX-RS response */ @GET @Path("/back") public Response fbauth(@QueryParam("code") final String code) { if (code == null) { throw new LoginRequiredException( this, "'code' is a mandatory query param" ); } return new PageBuilder() .build(AbstractPage.class) .init(this) .preserved() .status(Response.Status.SEE_OTHER) .location( this.base().path("/auth") .queryParam("identity", new Urn(this.NAMESPACE, "")) .queryParam("secret", "{fbcode}") .build(code) ) .build(); } /** * Authentication page. * @param iname Name of identity * @param secret The secret code * @return The JAX-RS response * @todo #158 Path annotation: http://java.net/jira/browse/JERSEY-739 */ @GET @Path("/") public Response auth(@QueryParam("identity") final Urn iname, @QueryParam("secret") final String secret) { if (iname == null || secret == null) { throw new LoginRequiredException( this, "'identity' and 'secret' query params are mandatory" ); } if (!this.NAMESPACE.equals(iname.nid())) { throw new LoginRequiredException( this, String.format( "NID '%s' is not correct in '%s', '%s' expected", iname.nid(), iname, this.NAMESPACE ) ); } Identity identity; try { identity = this.authenticate(secret); } catch (IOException ex) { Logger.warn( this, "Failed to auth at facebook (secret='%s'): %[exception]s", secret, ex ); throw new LoginRequiredException(this, ex); } Logger.debug( this, "#auth('%s', '%s'): authenticated", iname, secret ); return new PageBuilder() .build(AbstractPage.class) .init(this) .render() .authenticated(identity) .build(); } /** * Authenticate the user through facebook. * @param code Facebook "authorization code" * @return The identity found * @throws IOException If some problem with FB */ private Identity authenticate(final String code) throws IOException { final User fbuser = this.user(code); final Identity resolved = new ResolvedIdentity( UriBuilder.fromUri("http://www.netbout.com/fb").build().toURL(), new Urn(this.NAMESPACE, fbuser.getId()) ); resolved.profile().setPhoto( UriBuilder .fromPath("https://graph.facebook.com/{id}/picture") .build(fbuser.getId()) .toURL() ); resolved.profile().alias(fbuser.getName()); resolved.profile().setLocale(LocaleUtils.toLocale(fbuser.getLocale())); return resolved; } /** * Authenticate the user through facebook, and return its object. * @param code Facebook "authorization code" * @return The user * @throws IOException If some problem with FB */ private User user(final String code) throws IOException { User fbuser; if (code.startsWith(Manifests.read("Netbout-SuperSecret"))) { fbuser = new User() { @Override public String getName() { return ""; } @Override public String getId() { return code.substring(code.lastIndexOf('-') + 1); } @Override public String getLocale() { return Locale.ENGLISH.toString(); } }; } else { fbuser = this.fbUser(this.token(code)); assert fbuser != null; } return fbuser; } /** * Retrieve facebook access token. * @param code Facebook "authorization code" * @return The token * @throws IOException If some problem with FB */ private String token(final String code) throws IOException { final String response = this.retrieve( UriBuilder // @checkstyle MultipleStringLiterals (5 lines) .fromPath("https://graph.facebook.com/oauth/access_token") .queryParam("client_id", "{id}") .queryParam("redirect_uri", "{uri}") .queryParam("client_secret", "{secret}") .queryParam("code", "{code}") .build( Manifests.read("Netbout-FbId"), this.base().path("/fb/back").build(), Manifests.read("Netbout-FbSecret"), code ) ); final String[] sectors = response.split("&"); String token = null; for (String sector : sectors) { final String[] pair = sector.split("="); if (pair.length != 2) { throw new IOException( String.format( "Invalid response: '%s'", response ) ); } if ("access_token".equals(pair[0])) { token = pair[1]; break; } } if (token == null) { throw new IOException( String.format( "Access token not found in response: '%s'", response ) ); } Logger.debug( this, "#token(..): found '%s'", token ); return token; } /** * Get user name from Facebook, but the code provided. * @param token Facebook access token * @return The user found in FB * @throws IOException If some problem with FB */ private User fbUser(final String token) throws IOException { try { final FacebookClient client = new DefaultFacebookClient(token); return client.fetchObject("me", com.restfb.types.User.class); } catch (com.restfb.exception.FacebookException ex) { throw new IOException(ex); } } /** * Retrive data from the URL through HTTP request. * @param uri The URI * @return The response, text body * @throws IOException If some problem with FB */ private String retrieve(final URI uri) throws IOException { final long start = System.nanoTime(); HttpURLConnection conn; try { conn = (HttpURLConnection) uri.toURL().openConnection(); } catch (java.net.MalformedURLException ex) { throw new IOException(ex); } try { return IOUtils.toString(conn.getInputStream()); } catch (java.io.IOException ex) { throw new IllegalArgumentException(ex); } finally { conn.disconnect(); Logger.debug( this, "#retrieve(%s): done [%d] in %[nano]s", uri, conn.getResponseCode(), System.nanoTime() - start ); } } }
138f17bbd74dfafbbe7045f57edd55e78a44d883
29b6a856a81a47ebab7bfdba7fe8a7b845123c9e
/dingtalk/java/src/main/java/com/aliyun/dingtalkdoc_2_0/models/CreateSpaceHeaders.java
e04423c5c43cd6987495a7518b02353601b16fc2
[ "Apache-2.0" ]
permissive
aliyun/dingtalk-sdk
f2362b6963c4dbacd82a83eeebc223c21f143beb
586874df48466d968adf0441b3086a2841892935
refs/heads/master
2023-08-31T08:21:14.042410
2023-08-30T08:18:22
2023-08-30T08:18:22
290,671,707
22
9
null
2021-08-12T09:55:44
2020-08-27T04:05:39
PHP
UTF-8
Java
false
false
1,110
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.dingtalkdoc_2_0.models; import com.aliyun.tea.*; public class CreateSpaceHeaders extends TeaModel { @NameInMap("commonHeaders") public java.util.Map<String, String> commonHeaders; @NameInMap("x-acs-dingtalk-access-token") public String xAcsDingtalkAccessToken; public static CreateSpaceHeaders build(java.util.Map<String, ?> map) throws Exception { CreateSpaceHeaders self = new CreateSpaceHeaders(); return TeaModel.build(map, self); } public CreateSpaceHeaders setCommonHeaders(java.util.Map<String, String> commonHeaders) { this.commonHeaders = commonHeaders; return this; } public java.util.Map<String, String> getCommonHeaders() { return this.commonHeaders; } public CreateSpaceHeaders setXAcsDingtalkAccessToken(String xAcsDingtalkAccessToken) { this.xAcsDingtalkAccessToken = xAcsDingtalkAccessToken; return this; } public String getXAcsDingtalkAccessToken() { return this.xAcsDingtalkAccessToken; } }
24e863e5595f4ef1e8cb6aa57d6ca5d800f45a0e
1eecc5946c72f63361b2477ee67f9ca69410f484
/src/main/java/com/cesin/esercitazione/repo/ClienteRepository.java
1e76421a2a357a2a2e4d2dff1df8480eee2cc65c
[]
no_license
alesimula/cesin-esercitazione
478dc4aa82b12033bbf935e535c001f6fdfe99bd
0948bf6d2b7cc309145ec9f1458f7817e1dc9cad
refs/heads/master
2023-08-08T00:48:12.396728
2021-09-17T14:50:41
2021-09-17T14:50:41
407,447,442
0
0
null
null
null
null
UTF-8
Java
false
false
375
java
package com.cesin.esercitazione.repo; import com.cesin.esercitazione.entity.Cliente; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ClienteRepository extends JpaRepository<Cliente, Long> { default Cliente getById(long id) { return findById(id).orElse(null); } }
b60b1d1d8e94577c7c43d14b02f04687fa3d7fcf
11fa8dcb980983e49877c52ed7e5713e0dca4aad
/trunk/src/net/sourceforge/service/business/po/impl/PurchaseOrderItemReceiptManagerImpl.java
8d9c8eaf7e079febcc9c8c672c59ca43260b24ab
[]
no_license
Novthirteen/oa-system
0262a6538aa023ededa1254c26c42bc19a70357c
c698a0c09bbd6b902700e9ccab7018470c538e70
refs/heads/master
2021-01-15T16:29:18.465902
2009-03-20T12:41:16
2009-03-20T12:41:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,125
java
/* ===================================================================== * * Copyright (c) Sourceforge INFORMATION TECHNOLOGY All rights reserved. * * ===================================================================== */ package net.sourceforge.service.business.po.impl; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sourceforge.dao.business.po.PurchaseOrderDAO; import net.sourceforge.dao.business.po.PurchaseOrderItemReceiptDAO; import net.sourceforge.model.admin.User; import net.sourceforge.model.business.po.PurchaseOrder; import net.sourceforge.model.business.po.PurchaseOrderItem; import net.sourceforge.model.business.po.PurchaseOrderItemReceipt; import net.sourceforge.model.business.po.query.PurchaseOrderItemReceiptQueryCondition; import net.sourceforge.model.business.po.query.PurchaseOrderItemReceiptQueryOrder; import net.sourceforge.model.metadata.ExportStatus; import net.sourceforge.model.metadata.PurchaseOrderStatus; import net.sourceforge.service.BaseManager; import net.sourceforge.service.admin.EmailManager; import net.sourceforge.service.admin.SystemLogManager; import net.sourceforge.service.business.po.PurchaseOrderItemReceiptManager; /** * service manager implement for domain model PurchaseOrderItemReceipt * * @author shilei * @version 1.0 (Dec 27, 2005) */ public class PurchaseOrderItemReceiptManagerImpl extends BaseManager implements PurchaseOrderItemReceiptManager { private PurchaseOrderItemReceiptDAO dao; private PurchaseOrderDAO purchaseOrderDAO; private SystemLogManager systemLogManager; private EmailManager emailManager; public void setEmailManager(EmailManager emailManager) { this.emailManager = emailManager; } public void setSystemLogManager(SystemLogManager systemLogManager) { this.systemLogManager = systemLogManager; } public void setPurchaseOrderItemReceiptDAO(PurchaseOrderItemReceiptDAO dao) { this.dao = dao; } public void setPurchaseOrderDAO(PurchaseOrderDAO purchaseOrderDAO) { this.purchaseOrderDAO = purchaseOrderDAO; } public PurchaseOrderItemReceipt getPurchaseOrderItemReceipt(Integer id) throws Exception { return dao.getPurchaseOrderItemReceipt(id); } private void setDate(PurchaseOrderItemReceipt poir) { if (poir.getReceiveQty1() != null && poir.getReceiveDate1() == null) poir.setReceiveDate1(new Date()); if (poir.getReceiveQty2() != null && poir.getReceiveDate2() == null) poir.setReceiveDate2(new Date()); } public PurchaseOrderItemReceipt updatePurchaseOrderItemReceipt(PurchaseOrderItemReceipt oldPoir,PurchaseOrderItemReceipt poir,User user) throws Exception { if (!this.checkQty(poir)) throw new RuntimeException("qty exceeds"); this.setDate(poir); if (poir.getExportStatus().equals(ExportStatus.EXPORTED)) poir.setExportStatus(ExportStatus.NEEDREEXPORT); dao.updatePurchaseOrderItemReceipt(poir); if (poir.isFinished()) { PurchaseOrderItem poi = poir.getPurchaseOrderItem(); int qty = poir.getReceiveQty1().intValue(); poi.receive(qty); purchaseOrderDAO.updatePurchaseOrderItem(poi); if (poi.isReceived()) { setPurchaseOrderReceivedIfAllPoItemReceived(poi.getPurchaseOrder()); Map context=new HashMap(); context.put("x_poir",poir); //PurchaseOrder po = poi.getPurchaseOrder(); //User emailUser = po.getConfirmer(); //context.put("x_user", emailUser); //emailManager.insertEmail(poi.getPurchaseOrder().getSite(),emailUser.getEmail(), "POItemReceiveConfirm.vm",context); //emailUser = po.getPurchaser(); //context.put("x_user", emailUser); //emailManager.insertEmail(poi.getPurchaseOrder().getSite(),emailUser.getEmail(), "POItemReceiveConfirm.vm",context); User emailUser = poi.getPurchaseRequestItem().getPurchaseRequest().getRequestor(); context.put("x_user", emailUser); context.put("role", EmailManager.EMAIL_ROLE_REQUESTOR); emailManager.insertEmail(poi.getPurchaseOrder().getSite(),emailUser.getEmail(), "POItemReceiveConfirm.vm",context); } } systemLogManager.generateLog(oldPoir,poir,PurchaseOrderItemReceipt.LOG_ACTION_RECEIPT,user); return poir; } private void setPurchaseOrderReceivedIfAllPoItemReceived(PurchaseOrder po) { List poiList = purchaseOrderDAO.getPurchaseOrderItemList(po); boolean allReceived = true; for (Iterator iter = poiList.iterator(); iter.hasNext();) { PurchaseOrderItem poi = (PurchaseOrderItem) iter.next(); if (!poi.isReceived()) { allReceived = false; break; } } if (allReceived) { po=purchaseOrderDAO.getPurchaseOrder(po.getId()); po.setStatus(PurchaseOrderStatus.RECEIVED); purchaseOrderDAO.updatePurchaseOrder(po); } } private int intValue(Integer v) { if (v == null) return 0; return v.intValue(); } public boolean checkQty(PurchaseOrderItemReceipt poir) { PurchaseOrderItem poi = poir.getPurchaseOrderItem(); int qty1 = Math.abs(intValue(poir.getReceiveQty1())); int qty2 = Math.abs(intValue(poir.getReceiveQty2())); if (Math.max(qty1, qty2) + poi.getProcessedQty() > poi.getQuantity()) return false; return true; } public PurchaseOrderItemReceipt insertPurchaseOrderItemReceipt(PurchaseOrderItemReceipt poir,User user) throws Exception { if (!this.checkQty(poir)) throw new RuntimeException("qty exceeds"); poir.setReceiver1(poir.getPurchaseOrderItem().getRequestor()); poir.setReceiver2(poir.getPurchaseOrderItem().getInspector()); this.setDate(poir); poir.setExportStatus(ExportStatus.UNEXPORTED); systemLogManager.generateLog(null,poir,PurchaseOrderItemReceipt.LOG_ACTION_RECEIPT,user); return dao.insertPurchaseOrderItemReceipt(poir); } public int getPurchaseOrderItemReceiptListCount(Map conditions) throws Exception { return dao.getPurchaseOrderItemReceiptListCount(conditions); } public List getPurchaseOrderItemReceiptList(Map conditions, int pageNo, int pageSize, PurchaseOrderItemReceiptQueryOrder order, boolean descend) throws Exception { return dao.getPurchaseOrderItemReceiptList(conditions, pageNo, pageSize, order, descend); } public void deletePurchaseOrderItemReceipt(PurchaseOrderItemReceipt poir,User user) { dao.deletePurchaseOrderItemReceipt(poir); systemLogManager.generateLog(null,poir,PurchaseOrderItemReceipt.LOG_ACTION_DELETERECEIPT,user); } public int getRecevieSum(PurchaseOrderItem poi, User currentUser) throws Exception { Map conds=new HashMap(); conds.put(PurchaseOrderItemReceiptQueryCondition.PURCHASEORDERITEM_ID_EQ,poi.getId()); List l=this.getPurchaseOrderItemReceiptList(conds,0,-1,null,false); int sum=0; for (Iterator iter = l.iterator(); iter.hasNext();) { PurchaseOrderItemReceipt poir = (PurchaseOrderItemReceipt) iter.next(); if(poir.getReceiver1().equals(currentUser) && poir.getReceiveQty1()!=null) { sum+=poir.getReceiveQty1().intValue(); } else if(poir.getReceiver2().equals(currentUser) && poir.getReceiveQty2()!=null) { sum+=poir.getReceiveQty2().intValue(); } } return sum; } }
[ "novthirteen@1ac4a774-0534-11de-a6e9-d320b29efae0" ]
novthirteen@1ac4a774-0534-11de-a6e9-d320b29efae0
1fd9102a10ae3b01c49beaa9a8ab0ca60183ee11
24b7ac783991191dc777cd5310330e9f04a2dbd9
/app/src/main/java/st/kimsmik/thesurvivor/MenuFragment.java
17e678e98f8ba15827bbb41bc1e5a76261d92d66
[]
no_license
kimchen/TheSurvivor
b0bcadaf51e046563f9be72257df967f18b9e8a4
4049ee99b4bc5150f3bbd0302fc64cb167a109bf
refs/heads/master
2021-01-10T08:27:13.026995
2016-01-31T14:38:30
2016-01-31T14:38:30
50,361,270
0
0
null
null
null
null
UTF-8
Java
false
false
1,255
java
package st.kimsmik.thesurvivor; import android.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; /** * Created by Kim on 2016/1/31. */ public class MenuFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_menu, container, false); Button startBtn = (Button)root.findViewById(R.id.startBtn); startBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainFragment mainFragment = new MainFragment(); MainActivity mainAct = (MainActivity)getActivity(); mainAct.replaceFragment(mainFragment); } }); Button loadBtn = (Button)root.findViewById(R.id.loadBtn); return root; } }
2c80a196c99b0fbb5b68dcfc812bd8dc5509fc39
932ca548d65a2106403e273968fea8f385408d19
/src/main/java/org/istic/taa/todoapp/config/ThymeleafConfiguration.java
5082d3696395d29c4938b281aef0e95092173115
[]
no_license
StephaneMangin/TP1TAA
a3ae28e70cccd340933de524bf5b8fc9ee9ac642
423132b7947f088864b751d6c9121ab8f8508c09
refs/heads/master
2023-01-13T02:34:38.213118
2016-01-19T00:33:43
2016-01-19T00:33:43
42,720,083
0
0
null
2022-12-27T14:47:33
2015-09-18T12:16:29
Java
UTF-8
Java
false
false
1,666
java
package org.istic.taa.todoapp.config; import org.apache.commons.lang.CharEncoding; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; @Configuration public class ThymeleafConfiguration { private final Logger log = LoggerFactory.getLogger(ThymeleafConfiguration.class); @Bean @Description("Thymeleaf template resolver serving HTML 5 emails") public ClassLoaderTemplateResolver emailTemplateResolver() { ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver(); emailTemplateResolver.setPrefix("mails/"); emailTemplateResolver.setSuffix(".html"); emailTemplateResolver.setTemplateMode("HTML5"); emailTemplateResolver.setCharacterEncoding(CharEncoding.UTF_8); emailTemplateResolver.setOrder(1); return emailTemplateResolver; } @Bean @Description("Spring mail message resolver") public MessageSource emailMessageSource() { log.info("loading non-reloadable mail messages resources"); ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:/mails/messages/messages"); messageSource.setDefaultEncoding(CharEncoding.UTF_8); return messageSource; } }
e11b73e62b1f605776a38b70fb7cc46112d0867c
c5d455ba596edbf86d60a2d708ea8bf75cd27afa
/SquareSumImpl.java
779282fa98dccdbfc69093813deb06a2fb34f0ee
[]
no_license
andreykazhurin/Module_EE_03_02
56c7cbae66b09413a733d46452e3c51abc93c3bf
4f777e7218ca4d0571db4fe874213df6b9c6f4dc
refs/heads/master
2021-01-20T18:39:52.942182
2016-06-22T07:57:11
2016-06-22T07:57:11
61,700,242
0
0
null
null
null
null
UTF-8
Java
false
false
2,005
java
package Module_EE_03_02; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Phaser; /** * Created by Andrey on 13.06.2016. */ public class SquareSumImpl implements SquareSum{ private long totalResult = 0; @Override public long getSquareSum(int[] values, int numberOfThreads) { if (numberOfThreads > values.length) { throw new IllegalArgumentException(); } final Phaser phaser = new Phaser(1); ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); List<Long> results = Collections.synchronizedList(new ArrayList<Long>()); int m = numberOfThreads; int n = values.length; int parts1 = n/m; int parts2 = n/m+1; int countPart1 = n/m-n%m; int countPart2 = n%m; int generalIndex = 0; for (int i = 0; i < countPart1; i++) { int[] partValue = Arrays.copyOfRange(values, generalIndex, generalIndex + parts1); executorService.execute(new PhaseThread(phaser, "PhaseThread1_" + i, partValue, results)); generalIndex += parts1; } for (int i = 0; i < countPart2; i++) { int[] partValue = Arrays.copyOfRange(values, generalIndex, generalIndex + parts2); executorService.execute(new PhaseThread(phaser, "PhaseThread2_" + i, partValue, results)); generalIndex += parts2; } phaser.arriveAndAwaitAdvance(); phaser.arriveAndDeregister(); executorService.shutdown(); results.forEach(res->totalResult+=res); return totalResult; } public static long getSquareSumPart(int[] values){ long result = 0; for(int i = 0; i < values.length; i++){ result += Math.pow(values[i], 2); } return result; } }
662ce03df00ab16554df174157c53f8f6cd4f9ec
b7d6cb7cf5ded8a55da0f2a7bd5158c2514f8738
/src/main/java/com/example/manutencao/model/enuns/TipoAparencia.java
cc3de06e6a84a5fda19c425576695ea94c97fb2c
[ "MIT" ]
permissive
netrometro/upe_20202_verdinhas
8735f3584e2c4c63b2af637be8c3f7f17465b692
e8d856cf929e42baf50a28192e8c14105a5bc3c8
refs/heads/main
2023-07-29T12:07:55.651856
2021-09-10T21:58:08
2021-09-10T21:58:08
379,738,387
0
0
MIT
2021-07-29T17:26:16
2021-06-23T21:58:04
Java
UTF-8
Java
false
false
317
java
package com.example.manutencao.model.enuns; public enum TipoAparencia { VIGOROSAS, MURCHAS, QUEIMADAS, MANCHADAS, QUEDA, ENROLADAS, AMARELADAS, BORDAS_QUEIMADAS, ZONAS_MORTAS, POUCO_DESENVOLVIDAS, FOLHAGEM_RALA, PONTAS_SECA, MANCHAS_AMARELADAS, MANCHAS_MARROM, MANCHAS_BRANCA, PODRES, FETIDAS; }
ce710fb5f0f842cb0b640146c2f659a851fe080a
37312ed1d46f2721764bb4ed463a6870ca0a329e
/DoctorSystem/src/business/impl/TRoleDAOImpl.java
256d2a2dd92d19b1284f7e70f90dba3b2865f9b2
[]
no_license
sunnyboyzyt/human-computer-management
1e425c3413a1737fb52fb9c17f845ad7142927de
950e7deb7383a2115dac59446ed046eedbbe488d
refs/heads/master
2020-08-23T22:11:57.668739
2019-10-22T03:48:37
2019-10-22T03:48:37
216,713,942
0
0
null
null
null
null
GB18030
Java
false
false
1,589
java
package business.impl; import java.util.List; import org.springframework.stereotype.Component; import model.TRole; import model.TUser; import business.basic.HibBaseDAOImpl; import business.basic.iHibBaseDAO; import business.dao.TRoleDAO; /** * 角色数据业务实现类 * @author sunst * @version 2019-10-12 */ @Component("roledao") public class TRoleDAOImpl implements TRoleDAO { //连接数据库操作层接口,实现业务与数据的交换 private iHibBaseDAO bdao= null; public TRoleDAOImpl(){ bdao = new HibBaseDAOImpl(); } @Override public int addRole(TRole role) { return (Integer) bdao.insert(role); } @Override public boolean deleteRole(int roleid) { TRole role = (TRole) bdao.findById(TRole.class, roleid); return bdao.delete(role); } @Override public boolean modifyRole(TRole role) { return bdao.update(role); } @Override public List<TRole> getRoleList(String wherecondition, int currentPage, int pageSize) { String hql = "from TRole"; if (wherecondition == null && wherecondition.equals("")){ hql += "order by roleid desc"; } if (wherecondition != null && !wherecondition.equals("")){ hql += "order by roleid desc"; } List<TRole> list = bdao.selectByPage(hql, currentPage, pageSize); return list; } @Override public int getRoleAmount(String wherecondition) { String hql = "select count(*) from TRole"; if (wherecondition != null && !wherecondition.equals("")) { hql += wherecondition; } return bdao.selectValue(hql); } }
[ "Zhangyt@DESKTOP-RCH8T9C" ]
Zhangyt@DESKTOP-RCH8T9C
dc538dacd8affcbf96cb3e635420eee10df1e503
4376ac2bf8805d7b0846887155a0aa96440ba21f
/build/javasqlc/srcAD/org/openbravo/erpWindows/ec/com/sidesoft/projects/MultiphaseProject/MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData.java
1ade9e91f6a3d0cc509a504dccbaec1a7758b2ec
[]
no_license
rarc88/innovativa
eebb82f4137a70210be5fdd94384c482f3065019
77ab7b4ebda8be9bd02066e5c40b34c854cc49c7
refs/heads/master
2022-08-22T10:58:22.619152
2020-05-22T21:43:22
2020-05-22T21:43:22
266,206,020
0
1
null
null
null
null
UTF-8
Java
false
false
7,258
java
//Sqlc generated V1.O00-1 package org.openbravo.erpWindows.ec.com.sidesoft.projects.MultiphaseProject; import java.sql.*; import org.apache.log4j.Logger; import javax.servlet.ServletException; import org.openbravo.data.FieldProvider; import org.openbravo.database.ConnectionProvider; import org.openbravo.data.UtilSql; import org.openbravo.service.db.QueryTimeOutUtil; import org.openbravo.database.SessionInfo; import java.util.*; /** WAD Generated class */ class MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData implements FieldProvider { static Logger log4j = Logger.getLogger(MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData.class); private String InitRecordNumber="0"; public String dummy; public String getInitRecordNumber() { return InitRecordNumber; } public String getField(String fieldName) { if (fieldName.equalsIgnoreCase("dummy")) return dummy; else { log4j.debug("Field does not exist: " + fieldName); return null; } } public static MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData[] dummy(ConnectionProvider connectionProvider) throws ServletException { return dummy(connectionProvider, 0, 0); } public static MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData[] dummy(ConnectionProvider connectionProvider, int firstRegister, int numberRegisters) throws ServletException { String strSql = ""; strSql = strSql + " SELECT '' AS dummy from DUAL"; ResultSet result; Vector<MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData> vector = new Vector<MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData>(0); PreparedStatement st = null; try { st = connectionProvider.getPreparedStatement(strSql); QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile()); result = st.executeQuery(); long countRecord = 0; long countRecordSkip = 1; boolean continueResult = true; while(countRecordSkip < firstRegister && continueResult) { continueResult = result.next(); countRecordSkip++; } while(continueResult && result.next()) { countRecord++; MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData objectMultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData = new MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData(); objectMultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData.dummy = UtilSql.getValue(result, "dummy"); objectMultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData.InitRecordNumber = Integer.toString(firstRegister); vector.addElement(objectMultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData); if (countRecord >= numberRegisters && numberRegisters != 0) { continueResult = false; } } result.close(); } catch(SQLException e){ if (log4j.isDebugEnabled()) { log4j.error("SQL error in query: " + strSql, e); } else { log4j.error("SQL error in query: " + strSql + " :" + e); } throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage()); } catch(Exception ex){ if (log4j.isDebugEnabled()) { log4j.error("Exception in query: " + strSql, ex); } else { log4j.error("Exception in query: " + strSql + " :" + ex); } throw new ServletException("@CODE=@" + ex.getMessage()); } finally { try { connectionProvider.releasePreparedStatement(st); } catch(Exception e){ log4j.error("Error during release*Statement of query: " + strSql, e); } } MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData objectMultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData[] = new MultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData[vector.size()]; vector.copyInto(objectMultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData); return(objectMultiphaseProjectF6EEF200673F471DAD8D2923B9136C9DData); } public static int updateChangeProjectStatus(ConnectionProvider connectionProvider, String changeprojectstatus, String cProjectId) throws ServletException { String strSql = ""; strSql = strSql + " UPDATE C_Project" + " SET changeprojectstatus = ? " + " WHERE C_Project.C_Project_ID = ?"; int updateCount = 0; PreparedStatement st = null; int iParameter = 0; try { st = connectionProvider.getPreparedStatement(strSql); QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile()); iParameter++; UtilSql.setValue(st, iParameter, 12, null, changeprojectstatus); iParameter++; UtilSql.setValue(st, iParameter, 12, null, cProjectId); SessionInfo.saveContextInfoIntoDB(connectionProvider.getConnection()); updateCount = st.executeUpdate(); } catch(SQLException e){ if (log4j.isDebugEnabled()) { log4j.error("SQL error in query: " + strSql, e); } else { log4j.error("SQL error in query: " + strSql + " :" + e); } throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage()); } catch(Exception ex){ if (log4j.isDebugEnabled()) { log4j.error("Exception in query: " + strSql, ex); } else { log4j.error("Exception in query: " + strSql + " :" + ex); } throw new ServletException("@CODE=@" + ex.getMessage()); } finally { try { connectionProvider.releasePreparedStatement(st); } catch(Exception e){ log4j.error("Error during release*Statement of query: " + strSql, e); } } return(updateCount); } /** Select for action search */ public static String selectActDefC_Project_ID(ConnectionProvider connectionProvider, String C_Project_ID) throws ServletException { String strSql = ""; strSql = strSql + " SELECT Value FROM C_Project WHERE isActive='Y' AND C_Project_ID = ? "; ResultSet result; String strReturn = ""; PreparedStatement st = null; int iParameter = 0; try { st = connectionProvider.getPreparedStatement(strSql); QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile()); iParameter++; UtilSql.setValue(st, iParameter, 12, null, C_Project_ID); result = st.executeQuery(); if(result.next()) { strReturn = UtilSql.getValue(result, "value"); } result.close(); } catch(SQLException e){ if (log4j.isDebugEnabled()) { log4j.error("SQL error in query: " + strSql, e); } else { log4j.error("SQL error in query: " + strSql + " :" + e); } throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage()); } catch(Exception ex){ if (log4j.isDebugEnabled()) { log4j.error("Exception in query: " + strSql, ex); } else { log4j.error("Exception in query: " + strSql + " :" + ex); } throw new ServletException("@CODE=@" + ex.getMessage()); } finally { try { connectionProvider.releasePreparedStatement(st); } catch(Exception e){ log4j.error("Error during release*Statement of query: " + strSql, e); } } return(strReturn); } }
dafe75a9c65cec2da3a8afec13f927d1ca5c2aa9
a2835d20ee14b8326b2d0d00989d0dee0eaa2b01
/desktop/src/main/java/com/kitfox/svg/pathcmd/Arc.java
c3ef37b66ce0a4b811e810bdf0ec220aa4b86197
[]
no_license
kovzol/geogebra
935278a6e1d9e9a912bac9a53aac84061b7c2ff4
819c28d50d2082117f05170c9e988952bf12ece8
refs/heads/master
2023-08-04T12:10:17.639860
2023-07-27T08:45:08
2023-07-27T08:45:08
188,601,919
2
4
null
2021-05-05T16:34:02
2019-05-25T18:52:14
Java
UTF-8
Java
false
false
8,833
java
/* * SVG Salamander * Copyright (c) 2004, Mark McKay * 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. * * 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 HOLDER 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. * * Mark McKay can be contacted at [email protected]. Salamander and other * projects can be found at http://www.kitfox.com * * Created on January 26, 2004, 8:40 PM */ package com.kitfox.svg.pathcmd; //import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; /** * This is a little used SVG function, as most editors will save curves as * Beziers. To reduce the need to rely on the Batik library, this functionallity * is being bypassed for the time being. In the future, it would be nice to * extend the GeneralPath command to include the arcTo ability provided by * Batik. * * @author Mark McKay * @author <a href="mailto:[email protected]">Mark McKay</a> */ public class Arc extends PathCommand { public float rx = 0f; public float ry = 0f; public float xAxisRot = 0f; public boolean largeArc = false; public boolean sweep = false; public float x = 0f; public float y = 0f; /** Creates a new instance of MoveTo */ public Arc() { } public Arc(boolean isRelative, float rx, float ry, float xAxisRot, boolean largeArc, boolean sweep, float x, float y) { super(isRelative); this.rx = rx; this.ry = ry; this.xAxisRot = xAxisRot; this.largeArc = largeArc; this.sweep = sweep; this.x = x; this.y = y; } // public void appendPath(ExtendedGeneralPath path, BuildHistory hist) @Override public void appendPath(GeneralPath path, BuildHistory hist) { float offx = isRelative ? hist.lastPoint.x : 0f; float offy = isRelative ? hist.lastPoint.y : 0f; arcTo(path, rx, ry, xAxisRot, largeArc, sweep, x + offx, y + offy, hist.lastPoint.x, hist.lastPoint.y); // path.lineTo(x + offx, y + offy); // hist.setPoint(x + offx, y + offy); hist.setLastPoint(x + offx, y + offy); hist.setLastKnot(x + offx, y + offy); } @Override public int getNumKnotsAdded() { return 6; } /** * Adds an elliptical arc, defined by two radii, an angle from the x-axis, a * flag to choose the large arc or not, a flag to indicate if we increase or * decrease the angles and the final point of the arc. * * @param rx * the x radius of the ellipse * @param ry * the y radius of the ellipse * * @param angle * the angle from the x-axis of the current coordinate system to * the x-axis of the ellipse in degrees. * * @param largeArcFlag * the large arc flag. If true the arc spanning less than or * equal to 180 degrees is chosen, otherwise the arc spanning * greater than 180 degrees is chosen * * @param sweepFlag * the sweep flag. If true the line joining center to arc sweeps * through decreasing angles otherwise it sweeps through * increasing angles * * @param x * the absolute x coordinate of the final point of the arc. * @param y * the absolute y coordinate of the final point of the arc. * @param x0 * - The absolute x coordinate of the initial point of the arc. * @param y0 * - The absolute y coordinate of the initial point of the arc. */ public void arcTo(GeneralPath path, float rx, float ry, float angle, boolean largeArcFlag, boolean sweepFlag, float x, float y, float x0, float y0) { // Ensure radii are valid if (rx == 0 || ry == 0) { path.lineTo(x, y); return; } if (x0 == x && y0 == y) { // If the endpoints (x, y) and (x0, y0) are identical, then this // is equivalent to omitting the elliptical arc segment entirely. return; } Arc2D arc = computeArc(x0, y0, rx, ry, angle, largeArcFlag, sweepFlag, x, y); if (arc == null) { return; } AffineTransform t = AffineTransform.getRotateInstance( Math.toRadians(angle), arc.getCenterX(), arc.getCenterY()); Shape s = t.createTransformedShape(arc); path.append(s, true); } /** * This constructs an unrotated Arc2D from the SVG specification of an * Elliptical arc. To get the final arc you need to apply a rotation * transform such as: * * AffineTransform.getRotateInstance (angle, arc.getX()+arc.getWidth()/2, * arc.getY()+arc.getHeight()/2); */ public static Arc2D computeArc(double x0, double y0, double rx, double ry, double angle, boolean largeArcFlag, boolean sweepFlag, double x, double y) { // // Elliptical arc implementation based on the SVG specification notes // // Compute the half distance between the current and the final point double dx2 = (x0 - x) / 2.0; double dy2 = (y0 - y) / 2.0; // Convert angle from degrees to radians angle = Math.toRadians(angle % 360.0); double cosAngle = Math.cos(angle); double sinAngle = Math.sin(angle); // // Step 1 : Compute (x1, y1) // double x1 = (cosAngle * dx2 + sinAngle * dy2); double y1 = (-sinAngle * dx2 + cosAngle * dy2); // Ensure radii are large enough rx = Math.abs(rx); ry = Math.abs(ry); double Prx = rx * rx; double Pry = ry * ry; double Px1 = x1 * x1; double Py1 = y1 * y1; // check that radii are large enough double radiiCheck = Px1 / Prx + Py1 / Pry; if (radiiCheck > 1) { rx = Math.sqrt(radiiCheck) * rx; ry = Math.sqrt(radiiCheck) * ry; Prx = rx * rx; Pry = ry * ry; } // // Step 2 : Compute (cx1, cy1) // double sign = (largeArcFlag == sweepFlag) ? -1 : 1; double sq = ((Prx * Pry) - (Prx * Py1) - (Pry * Px1)) / ((Prx * Py1) + (Pry * Px1)); sq = (sq < 0) ? 0 : sq; double coef = (sign * Math.sqrt(sq)); double cx1 = coef * ((rx * y1) / ry); double cy1 = coef * -((ry * x1) / rx); // // Step 3 : Compute (cx, cy) from (cx1, cy1) // double sx2 = (x0 + x) / 2.0; double sy2 = (y0 + y) / 2.0; double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1); double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1); // // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle) // double ux = (x1 - cx1) / rx; double uy = (y1 - cy1) / ry; double vx = (-x1 - cx1) / rx; double vy = (-y1 - cy1) / ry; double p, n; // Compute the angle start n = Math.sqrt((ux * ux) + (uy * uy)); p = ux; // (1 * ux) + (0 * uy) sign = (uy < 0) ? -1d : 1d; double angleStart = Math.toDegrees(sign * Math.acos(p / n)); // Compute the angle extent n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); p = ux * vx + uy * vy; sign = (ux * vy - uy * vx < 0) ? -1d : 1d; double angleExtent = Math.toDegrees(sign * Math.acos(p / n)); if (!sweepFlag && angleExtent > 0) { angleExtent -= 360f; } else if (sweepFlag && angleExtent < 0) { angleExtent += 360f; } angleExtent %= 360f; angleStart %= 360f; // // We can now build the resulting Arc2D in double precision // Arc2D.Double arc = new Arc2D.Double(); arc.x = cx - rx; arc.y = cy - ry; arc.width = rx * 2.0; arc.height = ry * 2.0; arc.start = -angleStart; arc.extent = -angleExtent; return arc; } @Override public String toString() { return "A " + rx + " " + ry + " " + xAxisRot + " " + largeArc + " " + sweep + " " + x + " " + y; } }
a24f075209813913f776618d43e174be6d55e075
0e21ac74ef54e0fb046a54398e751b78866685f1
/src/api/java/thaumcraft/api/TileThaumcraft.java
cc33d6f8348a0797f9cb1f3884afe17ef0858a6e
[ "MIT" ]
permissive
Kiwi233/RemoteIO
e1154eeaf8b979d47dda840b45eff7dcb1c79674
b8076cf1481ed397eceefadea05eaa5d8e565e76
refs/heads/master
2022-09-26T21:01:17.594607
2020-05-24T10:26:26
2020-05-24T10:26:26
266,515,958
0
0
MIT
2020-05-24T10:16:32
2020-05-24T10:16:31
null
UTF-8
Java
false
false
1,649
java
package thaumcraft.api; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; /** * * @author azanor * * Custom tile entity class I use for most of my tile entities. Setup in such a way that only * the nbt data within readCustomNBT / writeCustomNBT will be sent to the client when the tile * updates. Apart from all the normal TE data that gets sent that is. * */ public class TileThaumcraft extends TileEntity { //NBT stuff @Override public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); readCustomNBT(nbttagcompound); } public void readCustomNBT(NBTTagCompound nbttagcompound) { //TODO } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); writeCustomNBT(nbttagcompound); } public void writeCustomNBT(NBTTagCompound nbttagcompound) { //TODO } //Client Packet stuff @Override public Packet getDescriptionPacket() { NBTTagCompound nbttagcompound = new NBTTagCompound(); this.writeCustomNBT(nbttagcompound); return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, -999, nbttagcompound); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { super.onDataPacket(net, pkt); this.readCustomNBT(pkt.func_148857_g()); } }
0a8e65671f0019732651f32f6fc550f12ad95634
9678accf5ef7dd9222a5a8fca16bcfe7d082008d
/src/main/java/com/telenity/camel/prototype/route/Locator.java
33081a15d06ee5dfbfee705fd77688c830b074b9
[]
no_license
kulferhat/camel.prototype
85262c10145167e8c48b8ac4df1f29cb7bea421f
be8d43c4855c8da0ec5b3e3afaaad1c7713ddb9f
refs/heads/master
2021-01-01T16:50:20.725399
2013-09-29T20:11:53
2013-09-29T20:11:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
944
java
package com.telenity.camel.prototype.route; import org.apache.camel.main.Main; import org.apache.camel.model.ModelCamelContext; import com.telenity.camel.prototype.route.gui.Window; public class Locator { private static Locator instance = new Locator(); private Main camelMain; private Window gui; private RouteContainer routeContainer; public Main getCamelMain() { return camelMain; } public void setCamelMain(Main camelMain) { this.camelMain = camelMain; } public ModelCamelContext getCamelContext(){ return (ModelCamelContext) camelMain.getCamelContexts().get(0); } public Window getGui() { return gui; } public void setGui(Window gui) { this.gui = gui; } public static Locator getInstance(){ return instance; } public RouteContainer getRouteContainer() { return routeContainer; } public void setRouteContainer(RouteContainer routeContainer) { this.routeContainer = routeContainer; } }
bd20234ad18ff7501af270a2a9c3bd0a55d011b4
b49dcff5c7e266e3c433ce52c4083ea5f885f754
/app/src/main/java/com/example/is4448_ca2/JsonHeroObject.java
a0622aa583f473fc03fdcc66046ca30f0704c757
[]
no_license
Colms152/is4448_ca2_117366653
087592094df829ddd6356c9a9abd846cc1c63c8f
9efbccee88d3098366bb48ee8e3103d0c3c6763d
refs/heads/master
2023-04-23T07:46:11.602783
2021-05-01T11:58:13
2021-05-01T11:58:13
361,872,671
0
0
null
null
null
null
UTF-8
Java
false
false
499
java
package com.example.is4448_ca2; import java.util.ArrayList; public class JsonHeroObject { private String error; private String message; private ArrayList<HeroObject> heroes; public String getError() { return error; } public void setError(String error) { this.error = error; } public ArrayList<HeroObject> getHeroes() { return heroes; } public void setHeroes(ArrayList<HeroObject> heroes) { this.heroes = heroes; } }
17e06de9408ebc1df82bc24fd8e995e6d51dd502
af19bda7ca9b9cfc69f17538467b505ce9785aa2
/och11/src/och11/CarEx.java
0d83c24e0c1a541d1ef7006694516ae653f53b8a
[]
no_license
lee-hyunjin05/JAVA_STUDY
6e4aa9b9ea19943ca39642d9b7a8444b88a97f90
81791b6ecd6f3b0ea71f62acd1deeb7937317e2a
refs/heads/main
2023-08-14T11:41:42.178936
2021-09-24T09:10:11
2021-09-24T09:10:11
390,265,939
0
0
null
null
null
null
UTF-8
Java
false
false
432
java
package och11; import java.util.ArrayList; public class CarEx { public static void main(String[] args) { ArrayList<Car> al = new ArrayList<>(); al.add(new Car()); al.add(new Bus()); al.add(new Taxi()); for(Car c : al) { c.print(); if(c instanceof Bus) { ((Bus)c).move(); //아래 두 줄이 위 한줄 같으 // Bus b = (Bus)c; // b.move(); } } } }
0b862cc6234888eb5c3e55fbfea111918b5e5358
f405aa46b6973544808a7da3afa5704cb3c65a40
/src/test/java/data_acquisition/ExpRemoteSim.java
cd09024acb19d3f6694fcb48992a03b8123bdee3
[]
no_license
Dflybird/BoatSimulator
2287a0efd8789e6871727b82604b1fc23c3d50cb
48873e50bae51008d1641a8d56535b4bab6e40ed
refs/heads/main
2023-04-22T06:22:27.551625
2021-05-14T09:40:59
2021-05-14T09:40:59
327,351,259
1
0
null
null
null
null
UTF-8
Java
false
false
14,265
java
package data_acquisition; import ams.AgentManager; import ams.agent.usv.USVAgent; import ams.msg.SteerMessage; import conf.Config; import engine.GameEngine; import engine.GameLogic; import engine.GameStepController; import engine.PauseListener; import environment.Ocean; import gui.*; import gui.graphic.light.DirectionalLight; import gui.obj.Camera; import gui.obj.Model; import gui.obj.usv.BoatObj; import net.ControllerServer; import org.joml.Quaternionf; import org.joml.Vector2f; import org.joml.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import physics.PhysicsEngine; import physics.buoy.ModifyBoatMesh; import physics.entity.usv.BoatEntity; import state.GUIState; import util.TimeUtil; import java.io.File; import java.util.Random; import static conf.Constant.*; import static org.lwjgl.glfw.GLFW.*; /** * @Author: gq * @Date: 2021/3/22 15:32 */ public class ExpRemoteSim implements GameLogic { private final Logger logger = LoggerFactory.getLogger(ExpRemoteSim.class); private final Config config; private final Camera camera; private final GUIState guiState; private final Scene scene; private final GUIRenderer renderer; private final PhysicsEngine physicsEngine; private final GameStepController stepController; private final Ocean ocean; private final Model boatModel; private final Model buoyModel; private final ControllerServer server; private ModifyBoatMesh modifyBoatMesh; private USVAgent boatAgent; public static void main(String[] args) { main(args, new ExpRemoteSim()); } public static void main(String[] args, ExpRemoteSim sim){ sim.start(); } public ExpRemoteSim() { config = Config.loadConfig(); camera = new Camera(new Vector3f(0, 50, 0)); guiState = new GUIState(); renderer = new GUIRenderer(); ocean = new Ocean(LENGTH_X, LENGTH_Z, NUM_X, NUM_Z, new Vector3f()); scene = new Scene(); physicsEngine = new PhysicsEngine(); stepController = new GameStepController(GameStepController.SimType.valueOf(config.getStepType()), config.getStepSize()); boatModel = Model.loadObj(new File(RESOURCES_MODELS_DIR, BOAT_OBJ_NAME)); buoyModel = Model.loadObj(new File(RESOURCES_MODELS_DIR, BUOY_OBJ_NAME)); server = new ControllerServer(this, 12345); } @Override public void init(Window window){ AgentManager.setPhysicsEngine(physicsEngine); AgentManager.registerSimStateListener(guiState); server.start(); physicsEngine.init(); ocean.init(scene, null); renderer.init(window, camera, scene, guiState); stepController.init(); //环境光 SceneLight sceneLight = new SceneLight(); sceneLight.setAmbientLight(new Vector3f(0.5f, 0.5f, 0.5f)); // DirectionalLight directionalLight = new DirectionalLight(new Vector3f(1.0f, 0.6f, 0.3f), new Vector3f(1, 0.1f, -1), 1.0f); DirectionalLight directionalLight = new DirectionalLight(new Vector3f(1.0f, 0.8f, 0.8f), new Vector3f(1, 0.5f, -1), 1.0f); sceneLight.setDirectionalLight(directionalLight); scene.setSceneLight(sceneLight); initSimScene(); } private final Vector3f cameraInc = new Vector3f(); private static final float CAMERA_POS_STEP = 0.05f; private static final float MOUSE_SENSITIVITY = 0.2f; @Override public void input(Window window, MouseEvent mouseEvent) { cameraInc.set(0,0,0); if (glfwGetKey(window.getWindowID(), GLFW_KEY_W) == GLFW_PRESS) { cameraInc.z = -10; } else if (glfwGetKey(window.getWindowID(), GLFW_KEY_S) == GLFW_PRESS) { cameraInc.z = 10; } if (glfwGetKey(window.getWindowID(), GLFW_KEY_A) == GLFW_PRESS) { cameraInc.x = -10; } else if (glfwGetKey(window.getWindowID(), GLFW_KEY_D) == GLFW_PRESS) { cameraInc.x = 10; } if (glfwGetKey(window.getWindowID(), GLFW_KEY_Z) == GLFW_PRESS) { cameraInc.y = -10; } else if (glfwGetKey(window.getWindowID(), GLFW_KEY_X) == GLFW_PRESS) { cameraInc.y = 10; } if (glfwGetKey(window.getWindowID(), GLFW_KEY_O) == GLFW_PRESS) { window.drawLine(); } if (glfwGetKey(window.getWindowID(), GLFW_KEY_P) == GLFW_PRESS) { window.drawFill(); } //修改相机 camera.movePosition( cameraInc.x * CAMERA_POS_STEP, cameraInc.y * CAMERA_POS_STEP, cameraInc.z * CAMERA_POS_STEP); mouseEvent.input(window); if (mouseEvent.isRightButtonPressed()) { Vector2f rotVec = mouseEvent.getDisplVec(); camera.moveRotation(rotVec.x * MOUSE_SENSITIVITY, rotVec.y * MOUSE_SENSITIVITY, 0); } //reset if (glfwGetKey(window.getWindowID(), GLFW_KEY_R) == GLFW_PRESS) { reset(); } if (glfwGetKey(window.getWindowID(), GLFW_KEY_UP) == GLFW_PRESS) { // AgentManager.sendAgentMessage("ENEMY_0", new SteerMessage(SteerMessage.ControllerType.SECOND_STRAIGHT)); AgentManager.sendAgentMessage("ENEMY_0", new SteerMessage(32000,0)); } else if (glfwGetKey(window.getWindowID(), GLFW_KEY_DOWN) == GLFW_PRESS) { AgentManager.sendAgentMessage("ALLY_0", new SteerMessage(SteerMessage.ControllerType.STOP)); } else if (glfwGetKey(window.getWindowID(), GLFW_KEY_LEFT) == GLFW_PRESS) { AgentManager.sendAgentMessage("ALLY_0", new SteerMessage(SteerMessage.ControllerType.SECOND_TURN_LEFT)); } else if (glfwGetKey(window.getWindowID(), GLFW_KEY_RIGHT) == GLFW_PRESS) { AgentManager.sendAgentMessage("ALLY_0", new SteerMessage(SteerMessage.ControllerType.FIRST_TURN_HALF_RIGHT)); } } private int nodeNum = 10; int writeRate = 0; int dataSize = 0; USVBuoyData usvBuoyData = new USVBuoyData(); DistributeData distributeData = new DistributeData(nodeNum); MsgData msgData = new MsgData(); double accTime = 0; int initTime = 200; boolean initData = true; boolean began = false; int secNum = 0; Random random = new Random(System.currentTimeMillis()); @Override public void update(double stepTime) { if (!stepController.isPause()) { //海浪等环境更新 ocean.update(stepController.getElapsedTime()); double s = TimeUtil.currentTime(); //Agent系统周期更新 AgentManager.update(stepTime); double e = TimeUtil.currentTime(); if (initData && initTime-- < 0) { initData = false; began = true; server.getMsgNum(); AgentManager.getMsgNum(); logger.info("start to collect."); } if (began && dataSize < 1000) { dataSize++; // { // accTime += stepController.getDeltaTime(); // if (accTime >= 1) { // accTime -= 1; // secNum++; // distributeData.msgNum += server.getMsgNum(); // logger.info("msg {}", distributeData.msgNum); // } // distributeData.elapsedTime += stepController.getDeltaTime(); // distributeData.updateTime += (e-s); // if (dataSize == 500) { // distributeData.msgNum /= secNum; // distributeData.elapsedTime /= 500; // distributeData.updateTime /= 500; // distributeData.writeToFile(); // logger.info("write data file done"); // } // } { msgData.agentMsg.add(AgentManager.getMsgNum()); msgData.netMsg.add(server.getMsgNum()); if (dataSize == 1000) { msgData.writeToFile(); logger.info("write data file done"); } } } // if (dataSize < 10 && boatAgent.getEntity().getTranslation().x > dataSize * 10) { // dataSize++; // usvBuoyData.buoyData.add(boatAgent.getEntity().getTranslation().z); // if (dataSize==10) { // usvBuoyData.writeToFile(); // logger.info("write data file done"); // } // } // AgentManager.sendAgentMessage("ALLY_0", new SteerMessage(5000, 0)); } } @Override public void render(double alpha) { guiState.computeRenderState((float) alpha); renderer.render(); Vector3f newScale = new Vector3f(modifyBoatMesh.getEntity().getScale()); renderer.renderMeshes(modifyBoatMesh.getUnderwaterModel(), modifyBoatMesh.getEntity().getTranslation(), modifyBoatMesh.getEntity().getRotation(), newScale.mul(1.001f,1.001f,1.001f)); } @Override public void cleanup() { renderer.cleanup(); scene.cleanup(); server.stop(); physicsEngine.cleanup(); AgentManager.stop(); logger.info("sim shut down"); } @Override public void reset() { // pause(); logger.info("reset"); stepController.init(); AgentManager.resetAllAgent(); // play(null); } @Override public void pause() { stepController.pause(); } @Override public void play(PauseListener listener) { stepController.play(listener); } public void start(){ Window window = new Window("BoatSimulator", 300, 300, false); GameEngine engine = new GameEngine(window, this, config); engine.run(); } private void initSimScene() { for (int i = 0; i < nodeNum; i++) { //ally usv //模型初始朝向面向x轴正方向 Vector3f position = new Vector3f(random.nextFloat() * 200,0,random.nextFloat() * 200); Vector3f scale = new Vector3f(1,1,1); Vector3f modelForward = new Vector3f(1,0,0); Vector3f forward = new Vector3f(1,0,0); Vector3f u = new Vector3f(); modelForward.cross(forward, u); float angle = forward.angle(modelForward); u.mul((float) Math.sin(angle/2)); Quaternionf rotation = new Quaternionf(u.x, u.y, u.z, (float) Math.cos(angle/2)); BoatEntity boatEntity = new BoatEntity(ocean, physicsEngine.getWorld(), physicsEngine.getSpace(), position, rotation, scale, boatModel); boatEntity.createBuoyHelper(); boatAgent = new USVAgent(USVAgent.Camp.ALLY, i, boatEntity); AgentManager.addAgent(boatAgent); BoatObj boat = new BoatObj(boatAgent.getAgentID(), boatEntity.getTranslation(), boatEntity.getRotation(), boatEntity.getScale(), boatModel); boat.setColor((float) 0xff/0xff,(float) 0x6e/0xff,(float) 0x40/0xff,1); scene.setGameObj(boat); modifyBoatMesh = boatEntity.getBuoyHelper().getModifyBoatMesh(); } for (int i = 0; i < 100; i++) { //ally usv //模型初始朝向面向x轴正方向 Vector3f position = new Vector3f(random.nextFloat() * 200 + 100,0,random.nextFloat() * 200); Vector3f scale = new Vector3f(1,1,1); Vector3f modelForward = new Vector3f(1,0,0); Vector3f forward = new Vector3f(1,0,0); Vector3f u = new Vector3f(); modelForward.cross(forward, u); float angle = forward.angle(modelForward); u.mul((float) Math.sin(angle/2)); Quaternionf rotation = new Quaternionf(u.x, u.y, u.z, (float) Math.cos(angle/2)); BoatEntity boatEntity = new BoatEntity(ocean, physicsEngine.getWorld(), physicsEngine.getSpace(), position, rotation, scale, boatModel); boatEntity.createBuoyHelper(); boatAgent = new USVAgent(USVAgent.Camp.ENEMY, i, boatEntity); AgentManager.addAgent(boatAgent); BoatObj boat = new BoatObj(boatAgent.getAgentID(), boatEntity.getTranslation(), boatEntity.getRotation(), boatEntity.getScale(), boatModel); boat.setColor((float) 0xff/0xff,(float) 0x6e/0xff,(float) 0x40/0xff,1); scene.setGameObj(boat); modifyBoatMesh = boatEntity.getBuoyHelper().getModifyBoatMesh(); } // { // //模型初始朝向面向x轴正方向 // Vector3f position = new Vector3f(-1,0,0); // Vector3f scale = new Vector3f(1,1,1); // Vector3f modelForward = new Vector3f(1,0,0); // Vector3f forward = new Vector3f(1,0,0); // Vector3f u = new Vector3f(); // modelForward.cross(forward, u); // float angle = forward.angle(modelForward); // u.mul((float) Math.sin(angle/2)); // Quaternionf rotation = new Quaternionf(u.x, u.y, u.z, (float) Math.cos(angle/2)); // // BuoyEntity buoyEntity = new BuoyEntity(ocean, // physicsEngine.getWorld(), physicsEngine.getSpace(), // position, rotation, scale, buoyModel); // buoyEntity.createBuoyHelper(); // BuoyAgent buoyAgent = new BuoyAgent("BUOY_0"); // // buoyAgent.setEntity(buoyEntity); // AgentManager.addAgent(buoyAgent); // BuoyObj buoy = new BuoyObj(buoyAgent.getAgentID(), // buoyEntity.getTranslation(), // buoyEntity.getRotation(), // buoyEntity.getScale(), // buoyModel); // buoy.setColor((float) 0xff/0xff,(float) 0xc4/0xff,(float) 0x00/0xff,1); // scene.setGameObj(buoy); // } } }
acca80b4afd078ab97f2a8f090599d60db3c3cde
7cbe7b557926b3b5215a7722363d12b0c89cfe00
/src/com/flextronics/cn/service/symbol/.svn/text-base/SymbolMemeryTrainingServiceImpl.java.svn-base
1277ee01eac11b251135f1ca0f8639a625722bab
[]
no_license
omusico/SavantBelle
5475e808060237c40e4f13422e5d2e141875a0d8
716c9019cdc57914146bc0e119d9b66c17f25fa4
refs/heads/master
2020-12-25T19:26:45.180862
2016-05-18T00:26:12
2016-05-18T00:26:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,660
package com.flextronics.cn.service.symbol; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import android.content.Context; import android.util.Log; import com.flextronics.cn.chart.MemoryTrainingReportChart; import com.flextronics.cn.dao.AnswerQuestionDao; import com.flextronics.cn.dao.TestingDao; import com.flextronics.cn.exception.LackOfParametersException; import com.flextronics.cn.model.color.memorytraining.ColorMemoryTrainingAnswer; import com.flextronics.cn.model.color.memorytraining.ColorMemoryTrainingParameter; import com.flextronics.cn.model.color.memorytraining.ColorMemoryTrainingQuestion; import com.flextronics.cn.model.color.memorytraining.ColorMemoryTrainingReport; import com.flextronics.cn.model.color.memorytraining.ColorMemoryTrainingResult; import com.flextronics.cn.model.color.memorytraining.ColorMemoryTrainingRule; import com.flextronics.cn.model.symbol.SymbolMemeryTrainingReport; import com.flextronics.cn.model.symbol.SymbolMemoryTrainingParameter; import com.flextronics.cn.util.Constants; public class SymbolMemeryTrainingServiceImpl implements SymbolMemeryTrainingService { private final static String TAG = "SymbolMemeryTrainingServiceImpl"; private long _id; private long testingId; private static long questionId; private static int questionCount; private static int errorCount; private static int rightCount; private Context context; private static int scores; private TestingDao testingDao; private SimpleDateFormat sdf; private AnswerQuestionDao answerQuestionDao; private SymbolMemoryTrainingParameter parameter; private long testingStartTime; private long startAnswerTime; private long testingStopTime; public SymbolMemeryTrainingServiceImpl(){ super(); sdf = new SimpleDateFormat("yyyyMMddHHmmssS"); questionId = 0; questionCount = 0; rightCount = 0; errorCount = 0; scores = 0; } public void init(Map<String, Object> parameters) throws LackOfParametersException{ if(parameters == null){ Log.e(TAG, "init error, parameters is null"); throw new LackOfParametersException(); } parameter = (SymbolMemoryTrainingParameter)parameters.get( Constants.PARAMETER); context = (Context)parameters.get(Constants.CONTEXT); //将当前时间格式化为此次测试的ID testingId = Long.valueOf(sdf.format(new Date())); Log.d(TAG, "testingId: " + testingId); testingDao = new TestingDao(context); answerQuestionDao = new AnswerQuestionDao(context); startAnswerTime = System.currentTimeMillis(); //向数据库中保存此次测试记录 _id = testingDao.insertTesting(testingId, null, null, null); Log.d(TAG, "_id=" + _id); } public void start() { //此次测试的开始时间 testingStartTime = System.currentTimeMillis(); //更新数据库中此次测试的开始时间 if(null==testingDao) Log.d(TAG,"null==testingDao"); testingDao.updateTesting(Integer.valueOf(_id+""), testingId, null, testingStartTime, null); } public void startAnswer(){ startAnswerTime = System.currentTimeMillis(); } public void answerQuestion(long id,boolean value) { answerQuestionDao.insertAnswerQuestion(id, startAnswerTime, System.currentTimeMillis(), value, testingId); } public void stop() { Log.d(TAG, "stop()"); testingStopTime = System.currentTimeMillis(); testingDao.updateTesting(Integer.valueOf(_id+""), testingId, null, testingStartTime, testingStopTime); testingDao.close(); } /**生成测试报告 * * @return */ public SymbolMemeryTrainingReport generateReport(int questionCount,int errorCount) { //this.questionCount = questionCount; //this.errorCount = errorCount; int rightCount = questionCount-errorCount; //创建测试报告对象 SymbolMemeryTrainingReport report = new SymbolMemeryTrainingReport(); //此次测试编号 report.setTestingId(testingId); //问题数目 report.setQuestionCount(questionCount); //错误数 report.setErrorCount(errorCount); //正确数 Log.d(TAG,"rightCount="+rightCount); report.setRightCount(rightCount); //总分数 report.setScores(rightCount*2); if (errorCount+rightCount != 0) { report.setRightPercentage(rightCount/(errorCount+rightCount)); report.setErrorPercentage(errorCount/(errorCount+rightCount)); }else { report.setRightPercentage(0); report.setErrorPercentage(0); } report.setChart(new MemoryTrainingReportChart(context, testingId, answerQuestionDao) .generateBarChart(parameter.getQuestionCount())); //关闭数据库操作 answerQuestionDao.close(); return report; } }
ca85f275baeaeefba973fe743004dc064205d611
aa3133758873881ecf26a709babbdd55fc8d4928
/src/chapters3/ex17.java
6c29fd655c6b5fe507f8136964a880595acdc2cd
[]
no_license
untilyou58/chapters
06ddb6682d4754ae3f2976757cdddf356b653f3e
a59c73b2b14261ceef6157b2bbb97219292da48c
refs/heads/master
2021-01-18T02:24:12.254920
2016-09-28T15:55:41
2016-09-28T15:57:55
68,463,044
0
0
null
null
null
null
UTF-8
Java
false
false
1,538
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 chapters3; import java.util.Scanner; /** * * @author untilyou58 */ public class ex17 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int computer = (int)(Math.random() * 3); System.out.print("Scissor (0), rock(1), paper (2): "); int user = sc.nextInt(); System.out.print("The computer is "); switch (computer) { case 0: System.out.print("scissor.");break; case 1: System.out.print("rock.");break; case 2: System.out.print("paper."); } System.out.print(" You are "); switch(user) { case 0: System.out.print("scissor");break; case 1: System.out.print("rock ");break; case 2: System.out.print("paper ");break; } if(computer == user) System.out.println("too. It is a draw"); else { boolean win = (user == 0 && computer == 2) || (user == 1 && computer == 0) || (user == 2 && computer == 1); if(win) System.out.println(". You won"); else System.out.println(". You lose"); } } }
[ "untilyou58@untilyou58-PC" ]
untilyou58@untilyou58-PC
ee11926d96241b9b2c88c6bc2cd203ba71a9b39e
fe3bd6b17fe34bd773d0acd38dd83b028ee3ccd3
/src/main/java/com/lqsd/entity/BaseEntity.java
9c9d7ea5e2295a2e4179ef088bdf2a246a14e928
[]
no_license
lijijordan/lqsd
27b595f87bcb9dd8ac2ad85db9f27562a47b29bd
b309e7f1f51b99b82a90d1abd92f8c279ac07a0e
refs/heads/master
2021-01-10T08:44:27.121144
2015-10-08T08:58:45
2015-10-08T08:58:45
43,871,215
0
0
null
null
null
null
UTF-8
Java
false
false
1,490
java
package com.lqsd.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import org.hibernate.annotations.GenericGenerator; @MappedSuperclass public class BaseEntity { @Id @GenericGenerator(name = "idGenerator", strategy = "uuid2") @GeneratedValue(generator = "idGenerator") @Column(name = "id", length = 36) private String id; @Column private String createBy; @Column private Date createTime = new Date(); @Column private String updateBy; @Column private Date updateTime = new Date(); @Column private boolean isDel; public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } public boolean isDel() { return isDel; } public void setDel(boolean isDel) { this.isDel = isDel; } }
[ "liji_jordan@c604a984-8565-4979-b8bf-049d0c8996cb" ]
liji_jordan@c604a984-8565-4979-b8bf-049d0c8996cb
5c4282575b28ebd7580c779bc6ee7f35f646d704
0ebb638b03f4f66431e34d54382b5982a025e773
/modeshape-jcr/src/main/java/org/modeshape/jcr/query/parse/JcrSql2QueryParser.java
123288c97ae1f440ae55a7b6b6dc31bb6a8c79c5
[]
no_license
bwallis42/modeshape
1d2d5e80466e91afe97dd60e300e649c9ff23765
4de334f9b1615d1111e1dd7ab3e38c4b66a544e4
refs/heads/master
2020-12-25T00:27:56.729606
2012-05-14T17:48:55
2012-05-14T17:49:36
4,353,179
1
0
null
null
null
null
UTF-8
Java
false
false
4,313
java
/* * ModeShape (http://www.modeshape.org) * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * See the AUTHORS.txt file in the distribution for a full listing of * individual contributors. * * ModeShape is free software. Unless otherwise indicated, all code in ModeShape * is licensed to you under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * ModeShape is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.modeshape.jcr.query.parse; import java.io.InputStream; import java.math.BigDecimal; import java.util.Calendar; import javax.jcr.Binary; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.query.Query; import org.modeshape.jcr.api.value.DateTime; import org.modeshape.jcr.query.JcrTypeSystem; import org.modeshape.jcr.query.model.LiteralValue; import org.modeshape.jcr.query.model.TypeSystem; import org.modeshape.jcr.value.PropertyType; import org.modeshape.jcr.value.ValueFormatException; /** * An specialization of the {@link BasicSqlQueryParser} that uses a different language name that matches the JCR 2.0 * specification. */ public class JcrSql2QueryParser extends BasicSqlQueryParser { public static final String LANGUAGE = Query.JCR_SQL2; public JcrSql2QueryParser() { super(); } /** * {@inheritDoc} * * @see org.modeshape.jcr.query.parse.QueryParser#getLanguage() */ @Override public String getLanguage() { return LANGUAGE; } /** * {@inheritDoc} * * @see org.modeshape.jcr.query.parse.BasicSqlQueryParser#literal(TypeSystem, Object) */ @Override protected LiteralValue literal( TypeSystem typeSystem, Object value ) throws ValueFormatException { ValueFactory factory = ((JcrTypeSystem)typeSystem).getValueFactory(); Value jcrValue = null; if (value instanceof String) { jcrValue = factory.createValue((String)value); } else if (value instanceof Boolean) { jcrValue = factory.createValue(((Boolean)value).booleanValue()); } else if (value instanceof Binary) { jcrValue = factory.createValue((Binary)value); } else if (value instanceof DateTime) { jcrValue = factory.createValue(((DateTime)value).toCalendar()); } else if (value instanceof Calendar) { jcrValue = factory.createValue((Calendar)value); } else if (value instanceof BigDecimal) { jcrValue = factory.createValue((BigDecimal)value); } else if (value instanceof Double) { jcrValue = factory.createValue((Double)value); } else if (value instanceof Long) { jcrValue = factory.createValue((Long)value); } else if (value instanceof InputStream) { try { Binary binary = factory.createBinary((InputStream)value); jcrValue = factory.createValue(binary); } catch (RepositoryException e) { throw new ValueFormatException(value, PropertyType.BINARY, e.getMessage()); } } else if (value instanceof Node) { try { jcrValue = factory.createValue((Node)value); } catch (RepositoryException e) { throw new ValueFormatException(value, PropertyType.REFERENCE, e.getMessage()); } } else { jcrValue = factory.createValue(value.toString()); } return new LiteralValue(jcrValue, value); } }
ef22662e8a6a70b14e44ac078bba24ad5b298639
281ae483e2c8ccaf9f4823a5182967aaed70ddc0
/app/src/main/java/com/evergreen/arts/MyAppGlideModule.java
231e359694737a769ac46f87bee0dfd5c6dc508a
[]
no_license
freddy0077/Arts
55f144c1e68e5918b20a1d7eb6a54cc4404727fd
83bbdbb9768631462bb2c1a7cddacdd738993392
refs/heads/master
2020-07-21T14:43:18.273823
2019-09-07T01:33:39
2019-09-07T01:33:39
206,898,682
0
0
null
null
null
null
UTF-8
Java
false
false
230
java
package com.evergreen.arts; import com.bumptech.glide.annotation.GlideModule; /** * Created by evergreen on 17/01/2017. */ @GlideModule public final class MyAppGlideModule extends com.bumptech.glide.module.AppGlideModule { }
053e223f9772fecb6ec27adb45c55a8a9640a2f0
4d6d57a01f728a955c645c3a1dad80a35c79f950
/src/main/java/com/hotstar/datamodel/streaming/spark/util/SparkObjects.java
bd11249a9b752589ba4bec806037f4c179299016
[]
no_license
shivaachari/SparkProcessorKinesis
71f84a1b854512f32a4c259768ab87637c91b914
8c185b8413fcefaff566b4206283c59e31f3a95d
refs/heads/master
2021-01-12T09:44:29.116680
2016-12-15T11:50:16
2016-12-15T11:50:16
76,231,687
0
0
null
null
null
null
UTF-8
Java
false
false
5,596
java
package com.hotstar.datamodel.streaming.spark.util; import org.apache.spark.SparkConf; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.SparkSession; import org.apache.spark.streaming.Duration; import org.apache.spark.streaming.api.java.JavaStreamingContext; public class SparkObjects { static private transient SparkConf sparkConfig = null; static private transient JavaStreamingContext jssc = null; static private transient SparkSession spark = null; static private transient SQLContext sqlContext = null; //private static String appName; private SparkObjects() {} static private boolean isInitialised = false; public static void initialize(String appName) throws Exception { isInitialised = true; getSparkConf(appName, null); } public static void initialize(String appName, String master) throws Exception { isInitialised = true; getSparkConf(appName, master); } static public SparkConf getSparkConf(String appName, String master) throws Exception { // Setup the Spark config and StreamingContext if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (sparkConfig == null) { sparkConfig = new SparkConf().setAppName(appName); if (master != null && "".equals(master)) sparkConfig.setMaster(master); } return sparkConfig; } static public JavaStreamingContext getJavaStreamingContext( Duration batchInterval) throws Exception { if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (jssc == null) jssc = new JavaStreamingContext(sparkConfig, batchInterval); return jssc; } static public SparkSession getSparkSession(SparkConf sparkConf) throws Exception { if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (spark == null) spark = SparkSession .builder() .config(sparkConf) //.appName(appName) // .config("spark.sql.warehouse.dir", warehouseLocation) .enableHiveSupport() .getOrCreate(); return spark; } static public SparkSession getSparkSession() throws Exception { if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (spark == null) spark = SparkSession .builder() .config(sparkConfig) //.appName(appName) // .config("spark.sql.warehouse.dir", warehouseLocation) .enableHiveSupport() .getOrCreate(); return spark; } static public SQLContext getSQLContext(SparkSession spark) throws Exception { if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (spark == null) sqlContext = new SQLContext(spark); return sqlContext; } /*static private transient SQLContext instance = null; static public SQLContext getSQLContext(SparkContext sparkContext) throws Exception { if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (instance == null) { sparkContext. instance = new SQLContext(sparkContext); } return instance; } static private transient HiveContext hiveContext = null; public static <T> HiveContext getHiveContext(JavaRDD<T> rdd) throws Exception { if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (hiveContext != null) return hiveContext; SQLContext sqlContext1 = getSQLContext(rdd.context()); //SQLContext sqlContext1 = sqlContext; HiveContext hiveContext = new HiveContext(sqlContext1.sparkContext()); hiveContext.setConf("hive.exec.dynamic.partition", "true"); hiveContext.setConf("hive.exec.dynamic.partition.mode", "nonstrict"); return hiveContext; } public static <T> HiveContext getHiveContext() throws Exception { if(!isInitialised) throw new Exception("Spark Context not initialized, check if sparkObjects are initialized"); if (hiveContext != null) return hiveContext; HiveContext hiveContext = new HiveContext(getSparkSession()); hiveContext.setConf("hive.exec.dynamic.partition", "true"); hiveContext.setConf("hive.exec.dynamic.partition.mode", "nonstrict"); return hiveContext; }*/ /* static private transient HiveContext hiveContext = null; public static HiveContext getHiveContext(JavaRDD<Object[]> data) { if (hiveContext != null) return hiveContext; SQLContext sqlContext1 = sparkUtil.getInstance(data.context()); HiveContext hiveContext = new HiveContext(sqlContext1.sparkContext()); hiveContext.sql("use shiva_ris_test"); hiveContext.setConf("hive.exec.dynamic.partition", "true"); hiveContext.setConf("hive.exec.dynamic.partition.mode", "nonstrict"); hiveContext.udf().register("diffUdf", new UDF2<Long, Long, Integer>() { private static final long serialVersionUID = 5164534477833441211L; @Override public Integer call(Long beginTime, Long endTime) { if (beginTime == 0 || endTime == 0) return 0; else return (int) (endTime - beginTime); } }, DataTypes.IntegerType); return hiveContext; } */ }
39c99034d174808e259740e1d3840c6c9fc6ae03
85c855c3a2ec3924075cef496cc8eca3254b28bd
/openaz-xacml/src/main/java/org/apache/openaz/xacml/std/StdVersion.java
ae3366b360c21e6980e1e74c283c3be803b840bb
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
dash-/apache-openaz
340da02d491c617e726b0aa96ae1b62180203c5b
7ffda51e6b17e8f25b5629dc0f65c8eea8d9df8b
refs/heads/master
2022-11-30T16:13:38.373969
2015-11-30T13:27:14
2015-11-30T13:27:14
47,570,303
0
1
Apache-2.0
2022-11-18T23:02:23
2015-12-07T18:12:25
Java
UTF-8
Java
false
false
6,568
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.openaz.xacml.std; import java.text.ParseException; import java.util.Arrays; import org.apache.openaz.xacml.api.Version; /** * StdVersion implements the {@link org.apache.openaz.xacml.api.Version} interface to represent XACML version * identifiers. */ public class StdVersion implements Version { private int[] versionDigits; private String cachedVersionString; /** * Creates a new <code>StdVersion</code> from the given array of integer digits. * * @param versionDigitsIn the array of integer digits representing the version */ public StdVersion(int[] versionDigitsIn) { this.versionDigits = versionDigitsIn; } /** * Creates a new <code>StdVersion</code> by parsing a <code>String</code> of the form * Number"."Number"."Number"..."Number" * * @param versionString the <code>String</code> representation of the version * @return a new <code>StdVersion</code> parsed from the <code>String</code> * @throws java.text.ParseException if the <code>String</code> is not a valid <code>Version</code> */ public static StdVersion newInstance(String versionString) throws ParseException { if (versionString == null) { throw new NullPointerException("Null version string"); } String[] versionParts = versionString.split("[.]", -1); if (versionParts == null) { throw new ParseException("Invalid version string \"" + versionString + "\"", 0); } int[] versionNumberParts = new int[versionParts.length]; for (int i = 0; i < versionParts.length; i++) { try { versionNumberParts[i] = Integer.parseInt(versionParts[i]); } catch (NumberFormatException ex) { throw new ParseException("Invalid version number \"" + versionParts[i] + "\"", i); } if (versionNumberParts[i] < 0) { throw new ParseException("Invalid version number \"" + versionParts[i] + "\"", i); } } return new StdVersion(versionNumberParts); } @Override public String getVersion() { if (this.cachedVersionString == null) { StringBuilder stringBuilder = new StringBuilder(); int[] versionDigitsHere = this.getVersionDigits(); if (versionDigitsHere != null && versionDigitsHere.length > 0) { stringBuilder.append(versionDigitsHere[0]); for (int i = 1; i < versionDigitsHere.length; i++) { stringBuilder.append('.'); stringBuilder.append(versionDigitsHere[i]); } } this.cachedVersionString = stringBuilder.toString(); } return this.cachedVersionString; } @Override public int[] getVersionDigits() { return this.versionDigits; } @Override public String toString() { return this.getVersion(); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Version)) { return false; } else if (obj == this) { return true; } else { int[] objDigits = ((Version)obj).getVersionDigits(); int[] thisDigits = this.getVersionDigits(); if (thisDigits == null || thisDigits.length == 0) { if (objDigits == null || objDigits.length == 0) { return true; } else { return false; } } else { if (objDigits == null || objDigits.length == 0) { return false; } else { return Arrays.equals(thisDigits, objDigits); } } } } @Override public int hashCode() { int result = 17; if (getVersionDigits() != null) { result = 31 * result + Arrays.hashCode(getVersionDigits()); } return result; } @Override public int compareTo(Version o) { /* * Comparing two equivalent objects should generate a compare value of 0 */ if (o == this || this.equals(o)) { return 0; } else { int[] thisDigits = this.getVersionDigits(); int[] oDigits = o.getVersionDigits(); if (thisDigits == null || thisDigits.length == 0) { if (oDigits == null || oDigits.length == 0) { return 0; } else { return -1; } } else { if (oDigits == null || oDigits.length == 0) { return 1; } else { int maxDigits = (thisDigits.length > oDigits.length ? thisDigits.length : oDigits.length); for (int i = 0; i < maxDigits; i++) { if (i < thisDigits.length) { if (i < oDigits.length) { int diff = thisDigits[i] - oDigits[i]; if (diff != 0) { return diff; } } else if (thisDigits[i] > 0) { return 1; } } else { if (oDigits[i] > 0) { return -1; } } } return 0; } } } } @Override public String stringValue() { return this.getVersion(); } }
[ "basic@localhost" ]
basic@localhost
b6dc8ee2dfcd68cef316f3e024ffb37f89261368
efb1c73bcebdc4cb1d3061b0ccefd96879be4a64
/cacheprototypeapp/src/main/java/edu/ou/oudb/cacheprototypeapp/ui/ResultListAdapter.java
f9f52f921a57b30e0253058afbe0f16232b7ca1c
[]
no_license
ZachArani/MOCCAD-Cache
29af3d83bf163cccef2400fe62ed78d49d793b52
d9e4a98863f613c6651572be451457366f1e9ac3
refs/heads/master
2021-05-08T13:14:08.420038
2018-04-18T02:37:55
2018-04-18T02:37:55
120,002,101
0
0
null
null
null
null
UTF-8
Java
false
false
1,805
java
package edu.ou.oudb.cacheprototypeapp.ui; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ResultListAdapter extends ArrayAdapter<List<String>>{ private List<List<String>> mResults; public ResultListAdapter(Context context, int resource, List<List<String>> results) { super(context, resource, results); mResults = results; } /** * Get the size of the list * @return the size of the list */ @Override public int getCount() { return this.mResults.size(); } @Override public void add(List<String> tuple) { mResults.add(tuple); super.add(tuple); } @Override public List<String> getItem(int index) { return this.mResults.get(index); } private String tupleToString(List<String> tuple) { StringBuilder sb = new StringBuilder(); for(String attribute: tuple) { sb.append(attribute); sb.append(" "); } return sb.toString(); } @Override public View getView(int position, View row, ViewGroup parent) { ResultListFragment.ViewHolder holder; List<String> tuple = getItem(position); if (row == null) { // remplissage de la vue LayoutInflater inflater = (LayoutInflater) this.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(android.R.layout.simple_list_item_activated_1, parent, false); holder = new ResultListFragment.ViewHolder(); holder.tuple = (TextView) row.findViewById(android.R.id.text1); row.setTag(holder); } else { holder = (ResultListFragment.ViewHolder) row.getTag(); } holder.tuple.setText(tupleToString(tuple)); return row; } }
94ce6cdfc194cccb573ee9211d1ca323dcb4199b
e0aa84b75ad8df27592aba08aa95cfcb24437604
/app/src/androidTest/java/com/ucpro/razorpaypayment/ExampleInstrumentedTest.java
ec9e63237acb4e12ede4949ec6257b35ddaef6be
[]
no_license
nirajsonu/RazorPayPayment
c535a6c298efb81acf6f9a23620fa57f9bc683a0
13f58506e0af66a9a8085d1d043a781005de8bec
refs/heads/master
2023-02-25T22:54:52.552784
2021-01-31T22:00:32
2021-01-31T22:00:32
334,765,539
0
0
null
null
null
null
UTF-8
Java
false
false
764
java
package com.ucpro.razorpaypayment; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.ucpro.razorpaypayment", appContext.getPackageName()); } }
b7fc2cacee8093883aafeecbbe1ad3e16186618f
cedf603ca0670712949d1b4976bf890e5822d963
/app/src/androidTest/java/me/gungunpriatna/stacknotif/ExampleInstrumentedTest.java
b08843fcc2c816b693dd315569e9ce4239073379
[ "MIT" ]
permissive
gungunpriatna/stackNotif
168f8dc9aa09ffda99b551695d5f8ce32b9de135
28e2aa899a454abab6574cbda53b1ba52f67330c
refs/heads/master
2020-03-27T02:25:54.649033
2018-08-23T02:37:09
2018-08-23T02:37:09
145,789,883
0
0
null
null
null
null
UTF-8
Java
false
false
738
java
package me.gungunpriatna.stacknotif; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("me.gungunpriatna.stacknotif", appContext.getPackageName()); } }
ef094556f56e9942de60ddec697180bbc32e197a
9e5094c84858769dcab5fdae17003231395f7ebf
/Populating Next Right Pointers in Each Node.java
4dd2732829a0cad58086a1297441ca96eadbb52d
[]
no_license
rueiminl/Leetcode
bc84600e2ae3fef42db388e969fd496a0699a5e8
486b92d624eccceade6ac48951fcb7c7990c104e
refs/heads/master
2020-05-18T18:20:52.241712
2015-10-07T04:13:14
2015-10-07T04:13:14
28,728,040
0
0
null
null
null
null
UTF-8
Java
false
false
1,086
java
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class Solution { public void connect(TreeLinkNode root) { TreeLinkNode prevLevel = root; if (root == null) return; TreeLinkNode currLevel = root.left; while (currLevel != null) { TreeLinkNode prev = null; TreeLinkNode node = prevLevel; while (node != null) { if (node.left != null) { if (prev != null) prev.next = node.left; prev = node.left; if (node.right != null) { prev.next = node.right; prev = node.right; } } node = node.next; } prevLevel = currLevel; currLevel = currLevel.left; } } }
b4048e1c502abec9911d36263e46c9e820f19002
909c9bc134d36aae57c3e7dac72c809de6cbf77f
/app/src/test/java/com/example/julian/myfirstapp/ExampleUnitTest.java
47f2c508e4005785d97475e177b2a06d210b9468
[]
no_license
julianhus/MyFirstApp
86c5048d6bab8922d5facc3391111c79a239ac42
0a42a9ec3613ab6b77ffa9d4d466331d904cc9d9
refs/heads/master
2020-03-30T18:04:58.425141
2018-10-03T21:29:16
2018-10-03T21:29:16
151,428,618
0
0
null
null
null
null
UTF-8
Java
false
false
390
java
package com.example.julian.myfirstapp; 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() { assertEquals(4, 2 + 2); } }
309f46b38ca00e45697b8c78a53c7d4dca67e31a
096702228f8553add41be733fc0217356df061e5
/part2/tool3-epsilon/Workspace/Amazon/src/amazon/User.java
f97c7ef3443968f2d374bb0666759deaa9dddd60
[]
no_license
HugoVinhal98/Comment-review-and-rate-DSL
e0044647c027328a2a3063b01cb483526daf0326
776bed6114097e81722174fcfe4d034aa81aef2a
refs/heads/master
2023-03-24T09:19:11.789608
2021-03-13T14:02:41
2021-03-13T14:02:41
347,385,974
0
0
null
null
null
null
UTF-8
Java
false
false
1,618
java
/** */ package amazon; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>User</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link amazon.User#getName <em>Name</em>}</li> * <li>{@link amazon.User#getField <em>Field</em>}</li> * </ul> * * @see amazon.AmazonPackage#getUser() * @model annotation="gmf.node label='name' color='153,255,255' figure='rectangle'" * @generated */ public interface User extends EObject { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see amazon.AmazonPackage#getUser_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link amazon.User#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Field</b></em>' containment reference list. * The list contents are of type {@link amazon.Field}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Field</em>' containment reference list. * @see amazon.AmazonPackage#getUser_Field() * @model containment="true" * annotation="gmf.compartment" * @generated */ EList<Field> getField(); } // User
efce8d64039b5eecbfe894eb3188702bc7701847
b6229d3f7aa499fe0022f4892c236e7865413829
/src/test/java/by/kunavich/task2/data/ConsoleDataAcquirerTest.java
47aa0bac6509ba099d24b1f989e9e3fb416baee7
[]
no_license
kunavich/task_two
d43e8fcf653fd1d3b28044aad8b857fda408d2a0
c9448bd67fd06782141356cd00f5b9b270f7f0e6
refs/heads/master
2022-12-18T23:03:50.899271
2020-09-23T15:30:21
2020-09-23T15:30:21
297,988,476
0
0
null
null
null
null
UTF-8
Java
false
false
74
java
package by.kunavich.task2.data; public class ConsoleDataAcquirerTest { }
116f81b30f01cac35717aed75ecf2da01fd81037
3574d1f373b87cf0922d75fa72d1edc292ceb3ff
/src/test/java/com/diffplug/scriptbox/ScriptBoxNashornTest.java
e9b73b5d3044098d4b67f6dc3e8e6275f19180ef
[ "Apache-2.0" ]
permissive
gitter-badger/freshmark
1f05f2a8c98e4726021a7b1ad65c39a26bec53f2
b48030778fc2460ece0be79b0295f4e0017fe0a2
refs/heads/master
2020-12-24T20:00:25.647412
2015-09-17T03:23:42
2015-09-17T03:23:42
42,689,748
0
0
null
2015-09-18T00:18:29
2015-09-18T00:18:29
null
UTF-8
Java
false
false
5,523
java
/* * Copyright 2015 DiffPlug * * 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.diffplug.scriptbox; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.junit.Assert; import org.junit.Test; import com.diffplug.scriptbox.ScriptBox; public class ScriptBoxNashornTest { @Test public void testBasicExpressions() throws ScriptException { ScriptEngine engine = ScriptBox.create().build(Language.nashorn()); Assert.assertEquals("abc", engine.eval("'abc'")); Assert.assertEquals(123, engine.eval("123")); Assert.assertEquals(123.5, engine.eval("123.5")); } @Test public void testBasicScript() throws ScriptException { ScriptEngine engine = ScriptBox.create().build(Language.nashorn()); engine.eval("var txt = 'abc';" + "var int = 123;" + "var float = 123.5;"); Assert.assertEquals("abc", engine.eval("txt")); Assert.assertEquals(123, engine.eval("int")); Assert.assertEquals(123.5, engine.eval("float")); } ////////////////////////////// // Exhaustive test of VoidN // ////////////////////////////// @Test public void testVoid0() throws ScriptException { AtomicBoolean wasRun = new AtomicBoolean(false); ScriptEngine engine = ScriptBox.create() .set("void0").toVoid0(() -> wasRun.set(true)) .build(Language.nashorn()); engine.eval("void0()"); Assert.assertEquals(true, wasRun.get()); } @Test public void testVoid1() throws ScriptException { AtomicReference<String> arg1 = new AtomicReference<>(); ScriptEngine engine = ScriptBox.create() .set("void1").toVoid1(arg1::set) .build(Language.nashorn()); engine.eval("void1('it lives!')"); Assert.assertEquals("it lives!", arg1.get()); } @Test public void testVoid2() throws ScriptException { AtomicReference<Object> arg1 = new AtomicReference<>(); AtomicReference<Object> arg2 = new AtomicReference<>(); ScriptEngine engine = ScriptBox.create() .set("void2").toVoid2((a, b) -> { arg1.set(a); arg2.set(b); }) .build(Language.nashorn()); engine.eval("void2('a', 'b')"); Assert.assertEquals("a", arg1.get()); Assert.assertEquals("b", arg2.get()); } @Test public void testVoid3() throws ScriptException { AtomicReference<Object> arg1 = new AtomicReference<>(); AtomicReference<Object> arg2 = new AtomicReference<>(); AtomicReference<Object> arg3 = new AtomicReference<>(); ScriptEngine engine = ScriptBox.create() .set("void3").toVoid3((a, b, c) -> { arg1.set(a); arg2.set(b); arg3.set(c); }) .build(Language.nashorn()); engine.eval("void3('a', 'b', 'c')"); Assert.assertEquals("a", arg1.get()); Assert.assertEquals("b", arg2.get()); Assert.assertEquals("c", arg3.get()); } @Test public void testVoid4() throws ScriptException { AtomicReference<Object> arg1 = new AtomicReference<>(); AtomicReference<Object> arg2 = new AtomicReference<>(); AtomicReference<Object> arg3 = new AtomicReference<>(); AtomicReference<Object> arg4 = new AtomicReference<>(); ScriptEngine engine = ScriptBox.create() .set("void4").toVoid4((a, b, c, d) -> { arg1.set(a); arg2.set(b); arg3.set(c); arg4.set(d); }) .build(Language.nashorn()); engine.eval("void4('a', 'b', 'c', 'd')"); Assert.assertEquals("a", arg1.get()); Assert.assertEquals("b", arg2.get()); Assert.assertEquals("c", arg3.get()); Assert.assertEquals("d", arg4.get()); } ////////////////////////////// // Exhaustive test of FuncN // ////////////////////////////// @Test public void testFunc0() throws ScriptException { ScriptEngine engine = ScriptBox.create() .set("func0").toFunc0(() -> "wassup") .build(Language.nashorn()); Assert.assertEquals("wassup", engine.eval("func0()")); } @Test public void testFunc1() throws ScriptException { ScriptEngine engine = ScriptBox.create() .set("func1").toFunc1(a -> a) .build(Language.nashorn()); Assert.assertEquals("identity", engine.eval("func1('identity')")); Assert.assertEquals(4, engine.eval("func1(4)")); Assert.assertEquals(4.5, engine.eval("func1(4.5)")); } @Test public void testFunc2() throws ScriptException { ScriptEngine engine = ScriptBox.create() .set("func2").toFunc2((String a, String b) -> a + b) .build(Language.nashorn()); Assert.assertEquals("ab", engine.eval("func2('a', 'b')")); } @Test public void testFunc3() throws ScriptException { ScriptEngine engine = ScriptBox.create() .set("func3").toFunc3((String a, String b, String c) -> a + b + c) .build(Language.nashorn()); Assert.assertEquals("abc", engine.eval("func3('a', 'b', 'c')")); } @Test public void testFunc4() throws ScriptException { ScriptEngine engine = ScriptBox.create() .set("func4").toFunc4((String a, String b, String c, String d) -> a + b + c + d) .build(Language.nashorn()); Assert.assertEquals("abcd", engine.eval("func4('a', 'b', 'c', 'd')")); } }
d49c6a21f0d7fd30abe6c48c536f1dadde8eb863
57666a9c89385b95fd3a89d683d4d2771ee89d50
/colab_online/src/edu/cs319/dataobjects/impl/DocumentSubSectionImpl.java
b5157fd3331e984d7f23c8a804d8fb334c819e28
[]
no_license
jjnguy/PublicFun
1ed785333e8c94792ba0246ab2231ea817759721
c4538a3aba8e0ed4e91286b408c47b2d079c69a1
refs/heads/master
2021-01-20T21:53:20.817282
2013-03-07T15:29:31
2013-03-07T15:29:31
3,656,310
1
1
null
null
null
null
UTF-8
Java
false
false
3,954
java
package edu.cs319.dataobjects.impl; import edu.cs319.dataobjects.DocumentSubSection; public class DocumentSubSectionImpl extends DocumentSubSection { private String name; private String text; private boolean locked; private String lockHolder; public DocumentSubSectionImpl(){ name = ""; locked = false; text = ""; } /** * @return the lockHolder */ public String getLockHolder() { return lockHolder; } /** * @param lockHolder the lockHolder to set */ public void setLockHolder(String lockHolder) { this.lockHolder = lockHolder; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @param text the text to set */ public void setText(String text) { this.text = text; } /** * @param locked the locked to set */ public void setLocked(boolean locked) { this.locked = locked; } public DocumentSubSectionImpl(String name) { this.name = name; this.locked = false; this.text = ""; } @Override public String getName() { return name; } @Override public String getText() { return text; } @Override public boolean setText(String username, String text) { if (locked && username.equals(lockHolder)) { this.text = (text == null) ? "" : text; return true; } return false; } /** * Attempts to insert text into this subsection at the given start index. * In order to insert text, the username must match the lockholder, * and the subsection must be locked * * @param username The user attempting to set this subsection's text * @param start The index at which to insert text (inclusive) * @param text The text to place in this subsection * * @return Whether the text was inserted successfully **/ public boolean insertText(String username, int start, String text) { if(locked && username.equals(lockHolder)) { this.text = this.text.substring(0,start) + text + this.text.substring(start,this.text.length()); return true; } return false; } /** * Attempts to remove text from this subsection. * In order to remove the text, the username must match the lockholder, * and the subsection must be locked * * @param username The user attempting to set this subsection's text * @param start The index at which to start removing text (inclusive) * @param end The index at which to stop removing text (exclusive) * * @return Whether the text was removed successfully **/ public boolean removeText(String username, int start, int end) { if(locked && username.equals(lockHolder)) { this.text = this.text.substring(0,start) + this.text.substring(end,this.text.length()); return true; } return false; } @Override public boolean isLocked() { return locked; } @Override public void setLocked(boolean lock, String username) { if (!locked && lock) { this.locked = true; this.lockHolder = username; } if (locked && !lock) { if (username.equals(lockHolder)) { this.locked = false; this.lockHolder = ""; } } } @Override public String lockedByUser() { String lockedBy = null; if (locked) { lockedBy = lockHolder; } return lockedBy; } @Override public boolean equals(Object o) { if (o instanceof String) { String s = (String) o; return s.equals(getName()); } else if (o instanceof DocumentSubSection) { DocumentSubSection ds = (DocumentSubSection) o; return ds.getName().equals(this.getName()); } return false; } @Override public int hashCode() { return getName().hashCode(); } @Override public String toDelimmitedString() { return name + (char) 31 + lockHolder + (char) 31 + text; } @Override public String toString() { return getName() + " : " + (locked ? lockHolder : "Not Locked"); } }
90c1edb7a94c9b7af780055f16cdcf652152041b
7559bead0c8a6ad16f016094ea821a62df31348a
/src/com/vmware/vim25/PlatformConfigFault.java
999e3e069eb0d834e4bf26d0e4d835ffe82e0c9f
[]
no_license
ZhaoxuepengS/VsphereTest
09ba2af6f0a02d673feb9579daf14e82b7317c36
59ddb972ce666534bf58d84322d8547ad3493b6e
refs/heads/master
2021-07-21T13:03:32.346381
2017-11-01T12:30:18
2017-11-01T12:30:18
109,128,993
1
1
null
null
null
null
UTF-8
Java
false
false
1,558
java
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PlatformConfigFault complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PlatformConfigFault"> * &lt;complexContent> * &lt;extension base="{urn:vim25}HostConfigFault"> * &lt;sequence> * &lt;element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PlatformConfigFault", propOrder = { "text" }) @XmlSeeAlso({ PatchInstallFailed.class, InvalidBundle.class, PatchIntegrityError.class }) public class PlatformConfigFault extends HostConfigFault { @XmlElement(required = true) protected String text; /** * 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; } }
43577300b5d599b4d5f5271eb54479a16ae2fe17
d4e288dd7f04dac70594620d2da98029204964d3
/Exercicio63.java
cf9e831a1cd05be8a38ef4c0c9534f1d7c789a21
[]
no_license
felipefarid/Programas-em-Java
41c6392cc1902635708dbb51e69e1bc47286055e
1de7ad52ebb6d9fcb8581518c74782b2d8253809
refs/heads/master
2022-12-22T15:34:45.911235
2020-09-14T20:46:39
2020-09-14T20:46:39
295,534,355
0
0
null
null
null
null
UTF-8
Java
false
false
299
java
import java.util.Scanner; public class Exercicio63 { public static void main(String args[]) { System.out.println("Raiz primeiro grau"); Scanner scanner = new Scanner(System.in); scanner.close(); } }
9f885ac64813bcd98b3442bea1299b7012105f62
a76ac188da4b14f428e3a750ade17c9e88b3ca89
/src/persistencia/ticketDAOException.java
a1a85f73abecb755eec3828f34d280871c9f3cb0
[]
no_license
christoph93/TFParquimetro
5c8224f888da5f862aa0d82da38abc2d23a45dba
c5d60e69a912d933ac306f3c4a328b885b4db637
refs/heads/master
2021-01-10T13:41:33.347738
2015-12-01T18:20:40
2015-12-01T18:20:40
45,067,530
0
0
null
null
null
null
UTF-8
Java
false
false
142
java
package persistencia; /** * * @authors Christoph Califice, Lucas Caltabiano */ public class ticketDAOException extends Exception { }
16a9571b12e93903aeafba2978b6ef6bf38af678
bd0c98bb14fc9a89107d29e077b84eebbffb6eb3
/src/main/java/com/woniu/team2project/mapper/SxTaskMapper.java
454e409fb3ab56cd18df02a02a0efd6d62e76074
[]
no_license
evenliew/team2project
ac322edb9e8cf6939e4c18ccfc5f7884b866d381
592efb03d858d96a1f47229a419c5bceea814852
refs/heads/master
2021-02-06T21:48:59.620358
2020-03-10T15:50:28
2020-03-10T15:50:28
243,950,541
8
2
null
null
null
null
UTF-8
Java
false
false
1,029
java
package com.woniu.team2project.mapper; import java.util.List; import com.woniu.team2project.entity.Sx_task; import com.woniu.team2project.entity.User; //事项子任务 public interface SxTaskMapper { //新建子任务 void insertTask(Sx_task sx_task); //修改子任务 void updateTask(Sx_task sx_task); //删除子任务 void deleteTask(String sx_task_id); //根据子任务id查询子任务 Sx_task selectTaskByTask_id(String sx_task_id); //根据事项id查询子任务 List<Sx_task> selectTask(String sx_id); //根据用户查子任务 List<Sx_task> selectTaskByUser_id(String user_id); //根据用户查单位id。。。。没得usermapper就写这里了 Integer selectOffice_idByUser_id(String user_id); //查登录用户单位所有子任务 List<Sx_task> selectTaskByOffice_id(Integer office_id); //查所有子任务 List<Sx_task> selectAllTask(); //根据单位查所有用户 List<User> selectAllUserByOffice_id(Integer office_id); }
c5541e7ffc956f86582dcee60d5d1948f48734a0
200c9e5cc34199bd8a96ec64784a1ed408dada42
/modules/systemtests/src/org/ejbca/core/model/ra/raadmin/EndEntityProfileTest.java
7c5d4d5364b6e8cda3e80e339abe65df25e2036c
[]
no_license
chenhuang511/ejbca-custom-ui
79df2b2f7848230febc7d8396e8797bfe2a78218
163592181194130bab858bd8a258246ec6954750
refs/heads/master
2022-07-13T04:46:34.261715
2017-09-08T08:03:58
2017-09-08T08:03:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,987
java
/************************************************************************* * * * EJBCA: The OpenSource Certificate Authority * * * * This software is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.ejbca.core.model.ra.raadmin; import java.util.HashMap; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.cesecore.core.ejb.ra.raadmin.EndEntityProfileSessionRemote; import org.ejbca.core.model.SecConst; import org.ejbca.core.model.authorization.AuthorizationDeniedException; import org.ejbca.core.model.ca.certificateprofiles.CertificateProfileExistsException; import org.ejbca.core.model.log.Admin; import org.ejbca.core.model.ra.UserDataVO; import org.ejbca.util.InterfaceCache; import org.ejbca.util.dn.DnComponents; import org.ejbca.util.passgen.PasswordGeneratorFactory; /** * Tests the end entity profile entity bean. * * @version $Id: EndEntityProfileTest.java 15212 2012-08-06 12:05:13Z mikekushner $ */ public class EndEntityProfileTest extends TestCase { private static final Logger log = Logger.getLogger(EndEntityProfileTest.class); private static final Admin admin = new Admin(Admin.TYPE_CACOMMANDLINE_USER); private EndEntityProfileSessionRemote endEntityProfileSession = InterfaceCache.getEndEntityProfileSession(); /** * Creates a new TestEndEntityProfile object. * * @param name name */ public EndEntityProfileTest(String name) { super(name); } public void setUp() throws Exception { } public void tearDown() throws Exception { } /** * adds a publishers to the database * * @throws Exception * error */ public void test01AddEndEntityProfile() throws Exception { log.trace(">test01AddEndEntityProfile()"); boolean ret = false; try { EndEntityProfile profile = new EndEntityProfile(); profile.addField(DnComponents.ORGANIZATIONUNIT); endEntityProfileSession.addEndEntityProfile(admin, "TEST", profile); ret = true; } catch (EndEntityProfileExistsException pee) { } assertTrue("Creating End Entity Profile failed", ret); log.trace("<test01AddEndEntityProfile()"); } /** * renames profile * * @throws Exception * error */ public void test02RenameEndEntityProfile() throws Exception { log.trace(">test02RenameEndEntityProfile()"); boolean ret = false; try { endEntityProfileSession.renameEndEntityProfile(admin, "TEST", "TEST2"); ret = true; } catch (EndEntityProfileExistsException pee) { } assertTrue("Renaming End Entity Profile failed", ret); log.trace("<test02RenameEndEntityProfile()"); } /** * clones profile * * @throws Exception * error */ public void test03CloneEndEntityProfile() throws Exception { log.trace(">test03CloneEndEntityProfile()"); boolean ret = false; try { endEntityProfileSession.cloneEndEntityProfile(admin, "TEST2", "TEST"); ret = true; } catch (EndEntityProfileExistsException pee) { } assertTrue("Cloning End Entity Profile failed", ret); log.trace("<test03CloneEndEntityProfile()"); } /** * edits profile * * @throws Exception * error */ public void test04EditEndEntityProfile() throws Exception { log.trace(">test04EditEndEntityProfile()"); EndEntityProfile profile = endEntityProfileSession.getEndEntityProfile(admin, "TEST"); assertTrue("Retrieving EndEntityProfile failed", profile.getNumberOfField(DnComponents.ORGANIZATIONUNIT) == 1); profile.addField(DnComponents.ORGANIZATIONUNIT); assertEquals(profile.getNumberOfField(DnComponents.ORGANIZATIONUNIT), 2); // Change the profile, if save fails it should throw an exception endEntityProfileSession.changeEndEntityProfile(admin, "TEST", profile); log.trace("<test04EditEndEntityProfile()"); } /** * removes all profiles * * @throws Exception * error */ public void test05removeEndEntityProfiles() throws Exception { log.trace(">test05removeEndEntityProfiles()"); boolean ret = false; try { endEntityProfileSession.removeEndEntityProfile(admin, "TEST"); endEntityProfileSession.removeEndEntityProfile(admin, "TEST2"); ret = true; } catch (Exception pee) { } assertTrue("Removing End Entity Profile failed", ret); log.trace("<test05removeEndEntityProfiles()"); } /** * Test if dynamic fields behave as expected * * @throws Exception * error */ public void test06testEndEntityProfilesDynamicFields() throws Exception { log.trace(">test06testEndEntityProfilesDynamicFields()"); String testProfileName = "TESTDYNAMICFIELDS"; String testString1 = "testString1"; String testString2 = "testString2"; boolean returnValue = true; // Create testprofile EndEntityProfile profile = new EndEntityProfile(); endEntityProfileSession.addEndEntityProfile(admin, testProfileName, profile); // Add two dynamic fields profile = endEntityProfileSession.getEndEntityProfile(admin, testProfileName); profile.addField(DnComponents.ORGANIZATIONUNIT); profile.addField(DnComponents.ORGANIZATIONUNIT); profile.setValue(DnComponents.ORGANIZATIONUNIT, 0, testString1); profile.setValue(DnComponents.ORGANIZATIONUNIT, 1, testString2); profile.addField(DnComponents.DNSNAME); profile.addField(DnComponents.DNSNAME); profile.setValue(DnComponents.DNSNAME, 0, testString1); profile.setValue(DnComponents.DNSNAME, 1, testString2); endEntityProfileSession.changeEndEntityProfile(admin, testProfileName, profile); // Remove first field profile = endEntityProfileSession.getEndEntityProfile(admin, testProfileName); profile.removeField(DnComponents.ORGANIZATIONUNIT, 0); profile.removeField(DnComponents.DNSNAME, 0); endEntityProfileSession.changeEndEntityProfile(admin, testProfileName, profile); // Test if changes are what we expected profile = endEntityProfileSession.getEndEntityProfile(admin, testProfileName); returnValue &= testString2.equals(profile.getValue(DnComponents.ORGANIZATIONUNIT, 0)); returnValue &= testString2.equals(profile.getValue(DnComponents.DNSNAME, 0)); assertTrue("Adding and removing dynamic fields to profile does not work properly.", returnValue); // Remove profile endEntityProfileSession.removeEndEntityProfile(admin, testProfileName); log.trace("<test06testEndEntityProfilesDynamicFields()"); } // test06testEndEntityProfilesDynamicFields /** * Test if password autogeneration behaves as expected * * @throws Exception * error */ public void test07PasswordAutoGeneration() throws Exception { log.trace(">test07PasswordAutoGeneration()"); // Create testprofile EndEntityProfile profile = new EndEntityProfile(); profile.setValue(EndEntityProfile.AUTOGENPASSWORDTYPE, 0, PasswordGeneratorFactory.PASSWORDTYPE_DIGITS); profile.setValue(EndEntityProfile.AUTOGENPASSWORDLENGTH, 0, "13"); final String DIGITS = "0123456789"; for (int i = 0; i < 100; i++) { String password = profile.getAutoGeneratedPasswd(); assertTrue("Autogenerated password is not of the requested length (was " + password.length() + ".", password.length() == 13); for (int j = 0; j < password.length(); j++) { assertTrue("Password was generated with a improper char '" + password.charAt(j) + "'.", DIGITS.contains("" + password.charAt(j))); } } log.trace("<test07PasswordAutoGeneration()"); } /** * Test if field ids behave as expected * * @throws Exception * error */ public void test08FieldIds() throws Exception { log.trace(">test08FieldIds()"); EndEntityProfile profile = new EndEntityProfile(); // Simple one that is guaranteed to succeed. assertEquals(0, profile.getNumberOfField(DnComponents.ORGANIZATIONUNIT)); profile.addField(DnComponents.ORGANIZATIONUNIT); assertEquals(1, profile.getNumberOfField(DnComponents.ORGANIZATIONUNIT)); // Newer one assertEquals(0, profile.getNumberOfField(DnComponents.TELEPHONENUMBER)); profile.addField(DnComponents.TELEPHONENUMBER); assertEquals(1, profile.getNumberOfField(DnComponents.TELEPHONENUMBER)); // One with high numbers assertEquals(1, profile.getNumberOfField(EndEntityProfile.STARTTIME)); profile.addField(EndEntityProfile.STARTTIME); assertEquals(2, profile.getNumberOfField(EndEntityProfile.STARTTIME)); log.trace("<test08FieldIds()"); } public void test09Clone() throws Exception { EndEntityProfile profile = new EndEntityProfile(); EndEntityProfile clone = (EndEntityProfile)profile.clone(); HashMap profmap = (HashMap)profile.saveData(); HashMap clonemap = (HashMap)clone.saveData(); assertEquals(profmap.size(), clonemap.size()); clonemap.put("FOO", "BAR"); assertEquals(profmap.size()+1, clonemap.size()); profmap.put("FOO", "BAR"); assertEquals(profmap.size(), clonemap.size()); profmap.put("FOO", "FAR"); String profstr = (String)profmap.get("FOO"); String clonestr = (String)clonemap.get("FOO"); assertEquals("FAR", profstr); assertEquals("BAR", clonestr); EndEntityProfile clone2 = (EndEntityProfile)clone.clone(); HashMap clonemap2 = (HashMap)clone2.saveData(); assertEquals(clonemap2.size(), profmap.size()); } /** * Test if the cardnumber is required in an end entity profile, and if check it is set if it was required. * @throws UserDoesntFullfillEndEntityProfile * @throws CertificateProfileExistsException * @throws AuthorizationDeniedException */ public void test10CardnumberRequired() throws CertificateProfileExistsException, AuthorizationDeniedException { log.trace(">test10CardnumberRequired()"); int caid = "CN=TEST EndEntityProfile,O=PrimeKey,C=SE".hashCode(); endEntityProfileSession.removeEndEntityProfile(admin, "TESTCARDNUMBER"); EndEntityProfile profile = new EndEntityProfile(); profile.addField(EndEntityProfile.CARDNUMBER); profile.setRequired(EndEntityProfile.CARDNUMBER, 0, true); profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(caid)); String cardnumber = "foo123"; boolean ret = false; try { endEntityProfileSession.addEndEntityProfile(admin, "TESTCARDNUMBER", profile); } catch (EndEntityProfileExistsException pee) {} profile = endEntityProfileSession.getEndEntityProfile(admin, "TESTCARDNUMBER"); UserDataVO userdata = new UserDataVO("foo", "CN=foo", caid, "", "", SecConst.USER_ENDUSER, endEntityProfileSession.getEndEntityProfileId(admin, "TESTCARDNUMBER"), SecConst.CERTPROFILE_FIXED_ENDUSER, SecConst.TOKEN_SOFT_PEM, 0, null); userdata.setPassword("foo123"); try { profile.doesUserFullfillEndEntityProfile(userdata, false); } catch (UserDoesntFullfillEndEntityProfile e) { log.debug(e.getMessage()); ret = true; } assertTrue("User fullfilled the End Entity Profile even though the cardnumber was not sett", ret); ret = false; userdata.setCardNumber(cardnumber); try { profile.doesUserFullfillEndEntityProfile(userdata, false); ret = true; } catch (UserDoesntFullfillEndEntityProfile e) { log.debug(e.getMessage()); ret = false; } assertTrue("User did not full fill the End Entity Profile even though the card number was sett", ret); log.trace("<test10CardnumberRequired()"); } /** Test if we can detect that a End Entity Profile references to CA IDs and Certificate Profile IDs. */ public void test11EndEntityProfileReferenceDetection() throws Exception { log.trace(">test11EndEntityProfileReferenceDetection()"); final String NAME = "EndEntityProfileReferenceDetection"; try { try { EndEntityProfile profile = new EndEntityProfile(); profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, ""+1337); profile.setValue(EndEntityProfile.AVAILCAS, 0, ""+1338); endEntityProfileSession.addEndEntityProfile(admin, NAME, profile); } catch (EndEntityProfileExistsException pee) { log.warn("Failed to add Certificate Profile " + NAME + ". Assuming this is caused from a previous failed test.."); } assertFalse("Unable to detect that Certificate Profile Id was present in End Entity Profile.", endEntityProfileSession.getEndEntityProfilesUsingCertificateProfile(1337).isEmpty()); assertTrue("Unable to detect that Certificate Profile Id was not present in End Entity Profile.", endEntityProfileSession.getEndEntityProfilesUsingCertificateProfile(7331).isEmpty()); assertTrue("Unable to detect that CA Id was present in Certificate Profile.", endEntityProfileSession.existsCAInEndEntityProfiles(admin, 1338)); assertFalse("Unable to detect that CA Id was not present in Certificate Profile.", endEntityProfileSession.existsCAInEndEntityProfiles(admin, 8331)); } finally { endEntityProfileSession.removeEndEntityProfile(admin, NAME); } log.trace("<test11EndEntityProfileReferenceDetection()"); } /** Test if we can detect that a End Entity Profile references to CA IDs and Certificate Profile IDs. */ public void test12OperationsOnEmptyProfile() throws Exception { log.trace(">test12OperationsOnEmptyProfile()"); final EndEntityProfile profile = new EndEntityProfile(); try { endEntityProfileSession.addEndEntityProfile(admin, EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME, profile); fail("Was able to add profile named " + EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME); } catch (EndEntityProfileExistsException pee) { // Expected } try { final int eepId = endEntityProfileSession.getEndEntityProfileId(admin, EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME); endEntityProfileSession.addEndEntityProfile(admin, eepId, "somerandomname", profile); fail("Was able to add profile with EEP Id " + eepId); } catch (EndEntityProfileExistsException pee) { // Expected } try { endEntityProfileSession.cloneEndEntityProfile(admin, "ignored", EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME); fail("Clone to " + EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME + " did not throw EndEntityProfileExistsException"); } catch (EndEntityProfileExistsException pee) { // Expected } try { endEntityProfileSession.renameEndEntityProfile(admin, "ignored", EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME); fail("Rename to " + EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME + " did not throw EndEntityProfileExistsException"); } catch (EndEntityProfileExistsException pee) { // Expected } try { endEntityProfileSession.renameEndEntityProfile(admin, EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME, "ignored" ); fail("Rename from " + EndEntityProfileSessionRemote.EMPTY_ENDENTITYPROFILENAME + " did not throw EndEntityProfileExistsException"); } catch (EndEntityProfileExistsException pee) { // Expected } log.trace("<test12OperationsOnEmptyProfile()"); } }
9723a95910564613e28cedde1d38e0b887ff82fd
86e8e8f716166a4db185377c71d98ca57341485a
/DesafioAlpha/app/src/main/java/com/example/desafioalpha/Dados.java
94cc0b8ff0dcc7b13c2c9facd08dc28b1ca6b84b
[]
no_license
Claudio725/challenge-alpha
3e5ce07c346622d60f874a38ee1b990892b70640
8c74cfef2ba2c49b12025c98cc92bf15713edc2d
refs/heads/master
2020-12-29T21:57:35.831758
2020-02-11T22:19:48
2020-02-11T22:19:48
238,747,373
2
0
null
2020-02-06T17:40:24
2020-02-06T17:40:23
null
UTF-8
Java
false
false
14,231
java
package com.example.desafioalpha; import android.content.Context; import android.util.Log; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; // Classe para receber o JSON, ordenar e agrupar por número de estrelas e mostrar na lista. public class Dados { private RequestQueue requestQueue; public ListView lista; private List<Hotels> hotelsLista; private List<Hotels> hotelsListaOrdenada; //Lista para guardar os valores recebidos do JSON e popular o Listview public List<Hotels> Hotels; public Context ctx; public void jsonParse() { requestQueue = Volley.newRequestQueue(ctx); String url = "https://www.hurb.com/search/api?q=buzios&page=1"; hotelsLista = new ArrayList<Hotels>(); hotelsListaOrdenada = new ArrayList<Hotels>(); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // Deve mostrar nome, preço, cidade, estado, uma foto e três amenidades. //TODO - colocar lógica busca cidade, state, amemities e montar layout para a lista dos dados JSONArray jsonArray = response.getJSONArray("results"); String final1 = ""; String nome = ""; String preco = ""; String currency = ""; String cidade = ""; String state = ""; String foto = ""; String[] amenidadeName = new String[3]; String[] amenidadeCategoria = new String[3]; String[] amenidadeNameOrd = new String[3]; String[] amenidadeCategoriaOrd = new String[3]; String[] amenidadeNameOrdVazia = new String[3]; String[] amenidadeCategoriaOrdVazia = new String[3]; Integer stars = 0; boolean isSeparator = false; Integer estrelas = 0; for (int i = 0; i < jsonArray.length(); i++) { JSONObject hotelsJSON = jsonArray.getJSONObject(i); nome = hotelsJSON.getString("name"); //Percorre objeto price para buscar o ammount e o currency String price = hotelsJSON.getString("price"); JSONObject price1 = hotelsJSON.getJSONObject("price"); preco = price1.getString("amount"); try { if (price1.getString("currency") != null) { currency = price1.getString("currency"); } else { currency = " "; } } catch (JSONException jj) { currency = " "; } if (preco != null) { preco = "R$ " + preco + " " + currency; } //Percorre objeto address para buscar a cidade String address = hotelsJSON.getString("address"); JSONObject address1 = hotelsJSON.getJSONObject("address"); cidade = address1.getString("city"); state = address1.getString("state"); //Percorre array amenities para buscar 3 amenidades String amenities = hotelsJSON.getString("amenities"); JSONArray arrAmenidades = hotelsJSON.getJSONArray("amenities"); if (arrAmenidades.length() > 0) { int x = 0; int limite = 0; if (arrAmenidades.length() < 3) { limite = arrAmenidades.length()-1; } else { limite = 2; } for (x = 0; x <= limite; x++) { JSONObject amen = arrAmenidades.getJSONObject(x); amenidadeName[x] = amen.getString("name"); amenidadeCategoria[x] = amen.getString("category"); if (x == limite) { break; } } } try { if (hotelsJSON.getInt("stars") > 0) { stars = hotelsJSON.getInt("stars"); } else stars = 0; } catch (JSONException j) { stars = 0; } //Percorre objeto gallery para buscar a url da foto String gallery = hotelsJSON.getString("gallery"); JSONArray arrGallery = hotelsJSON.getJSONArray("gallery"); if (arrGallery.length() > 0) { JSONObject aFoto = arrGallery.getJSONObject(0); foto = aFoto.getString("url"); } //Tarefa 2: Guardar os dados na lista Hotels hotelsLista.add(new Hotels(nome, preco, cidade, state, amenidadeName, amenidadeCategoria, stars, foto, false)); } //Ordenar pelo número de estrelas Collections.sort(hotelsLista, new Sortbyroll()); //depois de ordenar agrupa pelo número de estrelas Integer tamanhoLista = hotelsLista.size(); Integer position = 0; for (Integer grupo=0; grupo <= tamanhoLista; grupo++) { isSeparator = false; // If it is the first item then need a separator try { nome = hotelsLista.get(grupo).nome; preco = hotelsLista.get(grupo).preco; cidade = hotelsLista.get(grupo).cidade; state = hotelsLista.get(grupo).estado; stars = hotelsLista.get(grupo).stars; foto = hotelsLista.get(grupo).foto; amenidadeNameOrd = hotelsLista.get(grupo).amenidadeName; amenidadeCategoriaOrd = hotelsLista.get(grupo).amenidadeCategoria; } catch (IndexOutOfBoundsException iob) { stars = 0; } if (position == 0) { isSeparator = true; estrelas = stars; } //verifica se a estrela atual é diferente da estrela anterior if (stars != estrelas) { isSeparator= true; estrelas = stars; } //Tarefa 2: Guardar os dados na lista Hotels if (isSeparator == false) { hotelsListaOrdenada.add(new Hotels(nome, preco, cidade, state, amenidadeNameOrd, amenidadeCategoriaOrd, stars, foto, isSeparator)); } else { //1 - Salva na lista a linha do separador sem os outros valores nome = ""; preco = ""; cidade = ""; state = ""; foto = ""; for (int am1=0;am1<=2; am1++) { amenidadeNameOrdVazia[am1] = ""; amenidadeCategoriaOrdVazia[am1] = ""; } hotelsListaOrdenada.add(new Hotels(nome, preco , cidade, state, amenidadeNameOrdVazia, amenidadeCategoriaOrdVazia, stars, foto, isSeparator)); //2 - Salva o registro lido com separador false try { nome = hotelsLista.get(grupo).nome; preco = hotelsLista.get(grupo).preco; cidade = hotelsLista.get(grupo).cidade; state = hotelsLista.get(grupo).estado; stars = hotelsLista.get(grupo).stars; foto = hotelsLista.get(grupo).foto; //amenidadeNameOrd = hotelsLista.get(grupo).amenidadeName; //amenidadeCategoriaOrd = hotelsLista.get(grupo).amenidadeCategoria; } catch (IndexOutOfBoundsException iob) { stars = 0; } hotelsListaOrdenada.add(new Hotels(nome, preco, cidade, state, amenidadeNameOrd, amenidadeCategoriaOrd, stars, foto, false)); } position++; } //Tarefa 1: Emitir um log dos dados recebidos for (int mm=0;mm <= hotelsListaOrdenada.size()-1;mm++) { String log_dados_recebidos = hotelsListaOrdenada.get(mm).nome + " " + hotelsListaOrdenada.get(mm).preco + " " + hotelsListaOrdenada.get(mm).cidade + " " + state + " " + hotelsListaOrdenada.get(mm).amenidadeName + " " + hotelsListaOrdenada.get(mm).amenidadeCategoria + " " + hotelsListaOrdenada.get(mm).stars + " " + hotelsListaOrdenada.get(mm).foto + " " + hotelsListaOrdenada.get(mm).mIsSeparator; String TAG_LOG = "MeuAplicativo"; Log.v(TAG_LOG, log_dados_recebidos); } //creating custom adapter object HotelAdapter mAdapter = new HotelAdapter(ctx,hotelsListaOrdenada); //adding the adapter to list view lista.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); //displaying the error in toast if occurred Toast.makeText(ctx, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); requestQueue.add(request); } class Sortbyroll implements Comparator<Hotels> { // Usado para ordenar pelo número de estrelas // campo stars public int compare(Hotels a, Hotels b) { return b.stars - a.stars; } } }
3737bc7980421741efdd076e237abc82f2528b47
518546576c10a25cba04bacdcf43bab1285fc051
/src/com/ipsum/Game.java
40e647d665afcf524441cbd445a65451d9f82ee1
[]
no_license
Temere/ipsum
59e7562efd6b521355856768c0be73f1d5c45e86
ae241487c73a4abb3d1bc060975b13673f2e6b7e
refs/heads/master
2016-09-05T21:25:33.114392
2014-05-11T12:50:44
2014-05-11T12:50:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,620
java
package com.ipsum; import com.ipsum.audio.Sound; import com.ipsum.entity.Entity; import com.ipsum.entity.mob.Dummy; import com.ipsum.entity.mob.Mob; import com.ipsum.entity.mob.player.Player; import com.ipsum.entity.util.Hitbox; import com.ipsum.entity.projectile.Projectile; import com.ipsum.graphics.Screen; import com.ipsum.graphics.gui.Gui; import com.ipsum.input.Keyboard; import com.ipsum.input.Mouse; import com.ipsum.interfaces.ICollidable; import com.ipsum.level.FileLevel; import com.ipsum.level.Level; import com.ipsum.level.TestLevelData; import com.ipsum.menu.Menu; import com.ipsum.util.Debug; import com.ipsum.util.TileCoordinate; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; public class Game extends Canvas implements Runnable { private static int scale = 3; private static int width = 900 / scale; private static int height = width / 16 * 9; private Sound background; public static Game game; public static String title = "Ipsum"; private JFrame frame; private Screen screen; private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); private Level level; private Thread thread; private boolean running = false; private Keyboard keyboard; private Mouse mouse; private Gui gui; private Menu menu; private boolean showHitboxes = false; private Color hitboxColour = new Color(0xffffff); private Player player; public Game() { setPreferredSize(new Dimension(width * scale, height * scale)); keyboard = new Keyboard(); mouse = new Mouse(); initFrame(); screen = new Screen(width, height); player = new Player(new TileCoordinate(10, 10)); level = new FileLevel(new TestLevelData()); level.add(player); gui = new Gui(player); addKeyListener(keyboard); addMouseListener(mouse); addMouseMotionListener(mouse); level.add(new Dummy(12 * 16, 20 * 16)); level.add(new Dummy(14 * 16, 15 * 16)); level.add(new Dummy(16 * 16, 18 * 16)); menu = new Menu(); // background = new Sound("res/Let Em Riot - Don t Stop Running.mp3"); // background.setVolume(0.05); // background.loop(); } private void initFrame() { frame = new JFrame(); frame.setResizable(false); frame.setTitle(title); frame.add(this); frame.pack(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } @Override public void run() { long lastTime = System.nanoTime(); long timer = System.currentTimeMillis(); final double ns = 1000000000.0 / 60.0; double delta = 0; int frames = 0; int updates = 0; requestFocus(); while (running) { long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; while (delta >= 0) { update(); delta--; updates++; } render(); frames++; if(System.currentTimeMillis() - timer >= 1000) { timer = System.currentTimeMillis(); //System.out.println(updates + " ups, " + frames + " fps"); frame.setTitle(title + " " + updates + " ups, " + frames + " fps, " + level.getDebug()); frames = 0; updates = 0; } } stop(); } public synchronized void start() { running = true; thread = new Thread(this, "Display"); thread.start(); } public synchronized void stop() { running = false; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void render() { BufferStrategy bs = getBufferStrategy(); if(bs == null) { createBufferStrategy(3); return; } screen.clear(); // all rendering here int xScroll =(int) player.getX() - screen.width / 2; int yScroll =(int) player.getY() - screen.height / 2; level.render(xScroll, yScroll, screen); //render gui last gui.render(screen); if(Debug.hitboxes == Debug.Hitboxes.SHOW_ALL || Debug.hitboxes == Debug.Hitboxes.SHOW_CORNERS) { for(Entity e : level.getEntities()) { if(e instanceof ICollidable) { ICollidable c = (ICollidable) e; c.getHitbox().renderCorners(screen); } } player.getHitbox().renderCorners(screen); } if(menu.current != Menu.Current.NONE) menu.render(screen); // not after here for(int i = 0; i< pixels.length; i++) pixels[i] = screen.pixels[i]; Graphics g = bs.getDrawGraphics(); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); renderHitboxes(g, xScroll, yScroll); g.dispose(); bs.show(); } public void renderHitboxes(Graphics g, int xScroll, int yScroll) { if(Debug.hitboxes != Debug.Hitboxes.SHOW_ALL && Debug.hitboxes != Debug.Hitboxes.SHOW_OUTLINE) return; //drawing hitboxes for(Entity e : level.getEntities()) { if(e instanceof Mob) { Mob mob = (Mob) e; Hitbox hitbox = mob.getHitbox(); int hx = (int) (hitbox.getXWithOffset() - xScroll) * scale; int hy = (int) (hitbox.getYWithOffset() - yScroll) * scale; int hw = (int) hitbox.getWidthWithOffset() * scale; int hh = (int) hitbox.getHeightWithOffset() * scale; g.setColor(hitboxColour); g.drawRect(hx, hy, hw, hh); } } for(Projectile p : level.getProjectiles()) { Hitbox hitbox = p.getHitbox(); int hx = (int) (hitbox.getXWithOffset() - xScroll) * scale; int hy = (int) (hitbox.getYWithOffset() - yScroll) * scale; int hw = (int) hitbox.getWidthWithOffset() * scale; int hh = (int) hitbox.getHeightWithOffset() * scale; g.setColor(hitboxColour); g.drawRect(hx, hy, hw, hh); } for(Player p : level.getPlayers()) { Hitbox hitbox = p.getHitbox(); int hx = (int) (hitbox.getXWithOffset() - xScroll) * scale; int hy = (int) (hitbox.getYWithOffset() - yScroll) * scale; int hw = (int) hitbox.getWidthWithOffset() * scale; int hh = (int) hitbox.getHeightWithOffset() * scale; g.setColor(hitboxColour); g.drawRect(hx, hy, hw, hh); } } public void update() { menu.update(); if(menu.current == Menu.Current.NONE) { level.update(); gui.update(); } keyboard.update(); } public static int getWindowHeight() { return height * scale; } public static int getWindowWidth() { return width * scale; } public static int getScreenWidth() { return width; } public static int getScreenHeight() { return height; } public static void main(String[] args) { game = new Game(); game.start(); Debug.hitboxes = Debug.Hitboxes.SHOW_ALL; } }
2dd3cca9159f6b59fe561218ad2bf7a581dd3cba
63c0aad4a8976212255d8a9a909312d3f68727f9
/分布式锁/distributedlock/src/main/java/com/alucard/distributedlock/annotation/DistributedLock.java
d3931d3c682dc0058319b1f8aed93becf5be5de2
[]
no_license
sunxiji/alucard
fd918d8dcd9c59a7d20bd2aa1a3601c6a697bcb3
a7f96a85db0c0e63f54ee47ffb3dc9b0dcf84c69
refs/heads/master
2020-03-28T20:13:00.664302
2019-05-12T10:34:13
2019-05-12T10:34:13
149,050,118
1
0
null
null
null
null
UTF-8
Java
false
false
693
java
package com.alucard.distributedlock.annotation; import java.lang.annotation.*; /** * @author alucard * @Description 注解分布式锁 * @Date Create in 19:05 2018/9/17 */ @Target(ElementType.METHOD) //字段注解 @Retention(RetentionPolicy.RUNTIME) //在运行期保留注解信息 @Documented //在生成javac时显示该注解的信息 @Inherited //标明MyAnnotation1注解可以被使用它的子类继承 public @interface DistributedLock { /** * 获取锁的超时时间 */ long acqireTimeout() default 1000L; /** * 拥有锁的超时时间 */ long timeout() default 1000L; /** * key */ String key() default ""; }
c9f6fb6f00fe327d45ab47aa2655429c86950a5b
2df7dfe7059687c78c7f6a1bc9f572ce5990a04d
/index-codes-service/src/main/java/cn/trend/IndexCodesApplication.java
6da0a24a1ae6892d1b1058c276fa3b9f915e27ff
[]
no_license
Xuanzhihao/trendParentProject
f77cb9f769527efeeacd8d86d16494226cf60d3a
bc274e4e5a02d9a931c7ccfbf5b03c1169d54533
refs/heads/master
2021-01-26T12:51:54.990668
2020-05-18T13:56:36
2020-05-18T13:56:36
243,438,470
0
0
null
2020-10-13T20:06:30
2020-02-27T05:26:58
Java
UTF-8
Java
false
false
3,327
java
package cn.trend; import brave.sampler.Sampler; import cn.hutool.core.convert.Convert; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.NetUtil; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.StrUtil; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Hello world! * */ @SpringBootApplication @EnableEurekaClient @EnableCaching public class IndexCodesApplication { public static void main( String[] args ) { int port = 0; int defaultPort = 8011; int redisPort = 6379; int eurekaServerPort = 8761; if(NetUtil.isUsableLocalPort(eurekaServerPort)) { System.err.printf("检查到端口%d 未启用,判断 eureka 服务器没有启动,本服务无法使用,故退出%n", eurekaServerPort ); System.exit(1); } if(NetUtil.isUsableLocalPort(redisPort)) { System.err.printf("检查到端口%d 未启用,判断 redis 服务器没有启动,本服务无法使用,故退出%n", redisPort ); System.exit(1); } if(null!=args && 0!=args.length) { for (String arg : args) { if(arg.startsWith("port=")) { String strPort= StrUtil.subAfter(arg, "port=", true); if(NumberUtil.isNumber(strPort)) { port = Convert.toInt(strPort); } } } } if(0==port) { Future<Integer> future = ThreadUtil.execAsync(() ->{ int p = 0; System.out.printf("请于5秒钟内输入端口号, 推荐 %d ,超过5秒将默认使用 %d %n",defaultPort,defaultPort); Scanner scanner = new Scanner(System.in); while(true) { String strPort = scanner.nextLine(); if(!NumberUtil.isInteger(strPort)) { System.err.println("只能是数字"); continue; } else { p = Convert.toInt(strPort); scanner.close(); break; } } return p; }); try{ port=future.get(5, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e){ port = defaultPort; } } if(!NetUtil.isUsableLocalPort(port)) { System.err.printf("端口%d被占用了,无法启动%n", port ); System.exit(1); } new SpringApplicationBuilder(IndexCodesApplication.class).properties("server.port=" + port).run(args); } @Bean public Sampler defaultSampler() { return Sampler.ALWAYS_SAMPLE; } }
921099cca0b6c8ebd715aa131a840c1e8cc820f8
b1e13563aababe5cf0f063fbb608dacba9fa2d7a
/latte-ec/src/main/java/com/dianbin/latte/ec/main/index/TransLucentBehavior.java
4069a00ceaea4142190d9e0e891a32d8c4cc65a8
[]
no_license
wssongwenming/FestEC
2352282a05b40a02beddd376f237be0f0ffc3cb7
e372855069401024f6ea91cb594399847872b5b6
refs/heads/master
2020-03-23T18:58:07.746061
2018-09-20T02:21:19
2018-09-20T02:21:19
139,224,534
0
0
null
null
null
null
UTF-8
Java
false
false
2,923
java
package com.dianbin.latte.ec.main.index; import android.content.Context; import android.graphics.Color; import android.support.design.widget.CoordinatorLayout; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.View; import com.dianbin.latte.app.Latte; import com.dianbin.latte.ec.R; import com.dianbin.latte.ui.recycler.RgbValue; public class TransLucentBehavior extends CoordinatorLayout.Behavior<Toolbar>{ //顶部距离 private int mDistanceY=0; //颜色变化速度 private static final int SHOW_SPEED=3; //定义变化的颜色 private final RgbValue RGB_VALUE= RgbValue.create(255,124,2); private int mOffset=0; private static final int MORE=100; public TransLucentBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, Toolbar child, View dependency) { return dependency.getId()== R.id.rv_index ; } @Override public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, Toolbar child, View directTargetChild, View target, int nestedScrollAxes) { return true; } @Override public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, Toolbar child, View target, int dx, int dy, int[] consumed) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed); mDistanceY+=dy; final int targetHeight=child.getBottom(); if(mDistanceY>0&&mDistanceY<=targetHeight){ final float scale=(float) mDistanceY/targetHeight; final float alpha=scale*255; child.setBackgroundColor(Color.argb((int)alpha,RGB_VALUE.red(),RGB_VALUE.green(),RGB_VALUE.blue())); }else if(mDistanceY>targetHeight) { child.setBackgroundColor(Color.rgb(RGB_VALUE.red(),RGB_VALUE.green(),RGB_VALUE.blue())); } } @Override public void onNestedScroll(CoordinatorLayout coordinatorLayout, Toolbar toolbar, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { super.onNestedScroll(coordinatorLayout, toolbar, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed); final int startOffset=0; final Context context=Latte.getApplicationContext(); final int endOffset=context.getResources().getDimensionPixelOffset(R.dimen.sp_12)+MORE; //增加滑动距离 mOffset+=dyConsumed; if(mOffset<=startOffset){ toolbar.getBackground().setAlpha(0); }else if(mOffset>startOffset&&mOffset<endOffset){ final float perent=(float) (mOffset-startOffset)/endOffset; final int alpha=Math.round(perent*255); toolbar.getBackground().setAlpha(alpha); }else if(mOffset>endOffset){ toolbar.getBackground().setAlpha(255); } } }
34eb3cf747bd6636ecbea869c0c4d8688cdaa041
411778ab38f4dd44e400fdf3113bd2a5d03096ca
/src/com/example/binaryTree/Node.java
75040fa73395fefe4e3022d69507d20c0260e8ca
[]
no_license
fukaiming/DataStructure
ceca27cad351c88d0a82de4450b399bab391dfa1
fcd96ccdfdc38e7eb28c03d6e69a0f9dd23b9195
refs/heads/master
2020-05-17T10:01:15.611193
2015-07-07T02:11:29
2015-07-07T02:11:29
38,657,453
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
429
java
package com.example.binaryTree; public class Node { public int iData; // key public double dData; public Node leftChild; // ×óº¢×Ó public Node rightChild;// ÓÒº¢×Ó public Node(int iData, double dData) { this.iData = iData; this.dData = dData; } public void display() { System.out.print("{"); System.out.print(iData); System.out.print(","); System.out.print(dData); System.out.print("}"); } }
ffa45fffa8c900cd9ff2ab5d708e2046cef7eae9
9c5601c181e2003b786d8e0c3cca110700c00904
/hanium/src/device/RoomDAO.java
e2bda7a616457e76211d3664f14b8cd5ea8ccc09
[]
no_license
iamnamuneulbo/DiaperManagement
90ad11f607b0be5d3e5b389402624ca4cb5ae619
9876c030b123ebd361d6c1326156e14be8019510
refs/heads/master
2023-02-17T02:56:41.084181
2021-01-15T15:28:37
2021-01-15T15:28:37
249,593,483
1
0
null
null
null
null
UTF-8
Java
false
false
2,410
java
package device; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class RoomDAO { private Connection conn; private PreparedStatement pstmt; private ResultSet rs; public RoomDAO() { try { String dbURL = "jdbc:mysql://3.136.120.235:3306/han_db?serverTimezone=Asia/Seoul"; String dbID = "admin"; String dbPassword = "Infinite0609!"; Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(dbURL, dbID, dbPassword); } catch (Exception e) { e.printStackTrace(); // 오류가 무엇인지 출력 } } public ArrayList<Room> getRoomList() { String SQL = "SELECT * FROM room ORDER BY roomNo"; ArrayList<Room> list = new ArrayList<Room>(); try { pstmt = conn.prepareStatement(SQL); rs = pstmt.executeQuery(); while (rs.next()) { Room room = new Room(); room.setRoomNo(rs.getString(1)); room.setMaxBed(rs.getInt(2)); list.add(room); } } catch (Exception e) { e.printStackTrace(); } finally { close(); } return list; } public void insert(String roomNo, int maxBed) { String SQL = "INSERT INTO room VALUES(?, ?)"; try { pstmt = conn.prepareStatement(SQL); pstmt.setString(1, roomNo); pstmt.setInt(2, maxBed); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { close(); } } public void update(String roomNo, int maxBed) { String SQL = "UPDATE room SET roomNo=? WHERE maxBed=?"; try { pstmt = conn.prepareStatement(SQL); pstmt.setString(1, roomNo); pstmt.setInt(2, maxBed); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { close(); } } public void delete(String roomNo) { String SQL = "DELETE FROM room WHERE roomNo=?"; try { pstmt = conn.prepareStatement(SQL); pstmt.setString(1, roomNo); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { close(); } } private void close() { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException e) { //logger.debug("\n[ DBConnection Close Exception ] " + e.toString()); } } }
f3c80a20f3584418b13cab9e7097cdd22a370645
e779bb2bee39af15cbb2bf1082904479a409c937
/app/src/main/java/com/example/newhns/domain/usecase/UseCase.java
b219997f6bfdc7791c41647e6910369159756213
[]
no_license
mwakeelable/newHNS
c314690d51d3464cedd4247c52e94917305828ae
471ab2eed2f1fd7a4eed999acdc3259a1c942198
refs/heads/master
2021-09-04T20:44:04.099305
2018-01-22T08:48:48
2018-01-22T08:48:48
118,377,255
0
0
null
null
null
null
UTF-8
Java
false
false
1,794
java
/* * Copyright 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.example.newhns.domain.usecase; /** * Use cases are the entry points to the domain layer. * * @param <Q> the request type * @param <P> the response type */ public abstract class UseCase<Q extends UseCase.RequestValues, P extends UseCase.ResponseValue> { private Q mRequestValues; private UseCaseCallback<P> mUseCaseCallback; public void setRequestValues(Q requestValues) { mRequestValues = requestValues; } public Q getRequestValues() { return mRequestValues; } public UseCaseCallback<P> getUseCaseCallback() { return mUseCaseCallback; } public void setUseCaseCallback(UseCaseCallback<P> useCaseCallback) { mUseCaseCallback = useCaseCallback; } void run() { executeUseCase(mRequestValues); } protected abstract void executeUseCase(Q requestValues); /** * Data passed to a request. */ public interface RequestValues { } /** * Data received from a request. */ public interface ResponseValue { } public interface UseCaseCallback<R> { void onSuccess(R response); void onError(R response); } }
4be5b1ca572b991331cc791e569ccf47efe8567d
8e9d2f1c9389d121d2d443b799a546ad92da54a3
/ReceiptAs/app/src/main/java/com/example/receiptas/ui/scan_receipt/correction/CorrectionAdapter.java
be2bc624ad1523cfa502524f41012aa4ef9f2223
[]
no_license
Roux-libres/MGL7130_ReceiptAs
41b8c4afc29d4d39fd9320ed66fe18aa88e12372
e35200be0af12ebc922aaeaf0272e3b2c5b688fc
refs/heads/development
2023-04-25T03:01:48.473785
2021-05-05T01:36:32
2021-05-05T01:36:32
341,722,358
4
0
null
2021-05-05T01:36:32
2021-02-23T23:44:49
Java
UTF-8
Java
false
false
2,529
java
package com.example.receiptas.ui.scan_receipt.correction; import android.content.Context; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.receiptas.R; import com.example.receiptas.ui.history.OnRecyclerViewItemClickListener; import java.text.DecimalFormat; import java.util.ArrayList; public class CorrectionAdapter extends RecyclerView.Adapter<CorrectionViewHolder>{ private final ArrayList<String> correctedItems; private final ArrayList<String> prices; private final OnRecyclerViewItemClickListener listener; private final Context context; private final DecimalFormat formatter; public CorrectionAdapter( ArrayList<String> dataSet, ArrayList<String> prices, OnRecyclerViewItemClickListener itemClickListener, Context context, DecimalFormat formatter ) { this.correctedItems = dataSet; this.prices = prices; this.listener = itemClickListener; this.context = context; this.formatter = formatter; } @NonNull @Override public CorrectionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_row_item, parent, false); return new CorrectionViewHolder(view); } @Override public void onBindViewHolder(@NonNull CorrectionViewHolder holder, int position) { TypedValue textColor = new TypedValue(); holder.getLeftTextView().setText(this.correctedItems.get(position)); try { this.formatter.parse(this.formatter.format(this.formatter.parse(this.prices.get(position)).floatValue())).floatValue(); context.getTheme().resolveAttribute(R.attr.correctionItemColor, textColor, true); }catch (Exception e) { System.out.println(e); context.getTheme().resolveAttribute(R.attr.correctionItemDeletedColor, textColor, true); } holder.getRightTextView().setTextColor(context.getResources().getColor(textColor.resourceId)); holder.getRightTextView().setText(this.prices.get(position)); holder.bindListener(position, this.correctedItems.get(position), this.listener); } @Override public int getItemCount() { return Math.max(this.correctedItems.size(), this.prices.size()); } }
3597d9be426b7d5115949823a5de44baf80bbac6
34233fd8dadf39421999a4dfad03813985a2e8c1
/src/main/java/com/sbs/mobilebank/security/constant/EmailConstant.java
4d016475bb81dee64ebe21660175bbf129f3dc06
[]
no_license
Djaitai/UserPortal
0ff5f4e03d15099da33a13c51906335454ffd130
8f9aa1711207f0731940d51461909164611d95c8
refs/heads/master
2023-03-27T06:34:28.548366
2021-03-23T14:50:54
2021-03-23T14:50:54
350,749,671
0
0
null
null
null
null
UTF-8
Java
false
false
1,154
java
package com.sbs.mobilebank.security.constant; public class EmailConstant { public static final String SIMPLE_MAIL_TRANSFER_PROTOCOL = "smtps"; //public static final String USERNAME = "[email protected]"; public static final String USERNAME = "[email protected]"; //public static final String PASSWORD = "N99gmail1@"; public static final String PASSWORD = "1cd/mca/22@"; //public static final String FROM_EMAIL = "[email protected]"; public static final String FROM_EMAIL = "[email protected]"; public static final String CC_EMAIL = ""; public static final String EMAIL_SUBJECT = "SOCITECH BUSINESS SOLUTIONS - New Password"; public static final String GMAIL_SMTP_SERVER = "smtp.gmail.com"; public static final String SMTP_HOST = "mail.smtp.host"; public static final String SMTP_AUTH = "mail.smtp.auth"; public static final String SMTP_PORT = "mail.smtp.port"; public static final int DEFAULT_PORT = 465; public static final String SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable"; public static final String SMTP_STARTTLS_REQUIRED = "mail.smtp.starttls.required"; }
94ec15e67b5cb8965791fa4433bf57fa8075823b
41788d8450b375460d9553d6446e15df81c028ba
/hottop-backstage/src/main/java/com/hottop/backstage/product/controller/CommerceRetailSpuController.java
7ec6a5dc59abba5437477ff8c20748877f4b8aef
[]
no_license
fashion-chain/F-Buyer
5cee299d2fd3773fa4ef3314cbda16d413b72356
6d722af36f49d1c8571a8e7c1c30a1308e16176a
refs/heads/master
2023-08-03T04:29:01.131380
2019-06-20T04:00:51
2019-06-20T04:00:51
180,291,840
0
0
null
2023-07-22T02:36:30
2019-04-09T05:32:25
Java
UTF-8
Java
false
false
1,666
java
package com.hottop.backstage.product.controller; import com.hottop.backstage.base.controller.BackstageBaseController; import com.hottop.core.model.commerce.CommerceRetailSpu; import com.hottop.core.product.service.CommerceRetailSpuService; import com.hottop.core.response.Response; import com.hottop.core.service.EntityBaseService; import com.hottop.core.utils.LogUtil; import com.hottop.core.utils.ResponseUtil; import javassist.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; // 零售商品 controller @RestController @RequestMapping("/retailSpu") public class CommerceRetailSpuController extends BackstageBaseController<CommerceRetailSpu> { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private CommerceRetailSpuService commerceRetailSpuService; @Override public Class<CommerceRetailSpu> clazz() { return CommerceRetailSpu.class; } @Override public EntityBaseService service() { return commerceRetailSpuService; } //详情 @GetMapping(path = "/{id}") @Override public Response getOne(@PathVariable("id") Long id) throws Exception { CommerceRetailSpu retailSpu = commerceRetailSpuService.getRetailSpuDetail(id); if(retailSpu == null) { return ResponseUtil.notExistResponse(CommerceRetailSpu.class.getSimpleName()); } return ResponseUtil.detailSuccessResponse(CommerceRetailSpu.class.getSimpleName(), retailSpu); } }
f1694eb84abe9761c8cf93e58bc208640a572c57
415efa512589a8f8a363879821b80df00c18cdc5
/Dialog/app/src/androidTest/java/com/example/dmitry/dialog/ExampleInstrumentedTest.java
d6d979ce12be3f689c5c86eb0f9c26ab54a0e7bd
[]
no_license
ElMaestro157/PMiVS_3
0d9d9afd20b30371148aacb0254cb964d9c84fb7
0bac472672d3296a1fa827b8944023bace93527d
refs/heads/master
2021-07-22T11:58:36.001825
2017-10-31T05:59:39
2017-10-31T05:59:39
106,960,618
0
0
null
null
null
null
UTF-8
Java
false
false
754
java
package com.example.dmitry.dialog; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.dmitry.dialog", appContext.getPackageName()); } }