blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
671d18a2bb1c98e4436c62dd8e8c7657ce5d3b49
Java
moutainhigh/dm-platform
/dm-media/dm-media-domain/src/test/java/com/damon/media/domain/SpecAggregateTest.java
UTF-8
6,119
2.046875
2
[]
no_license
package com.damon.media.domain; import com.damon.media.domain.slot.spec.aggregate.SpecAggregate; import com.damon.media.domain.slot.spec.aggregate.SpecId; import com.damon.media.domain.slot.spec.command.ActivateSpecCommand; import com.damon.media.domain.slot.spec.command.CreateSpecCommand; import com.damon.media.domain.slot.spec.command.DeactivateSpecCommand; import com.damon.media.domain.slot.spec.command.UpdateSpecCommand; import com.damon.media.domain.slot.spec.event.SpecActivatedEvent; import com.damon.media.domain.slot.spec.event.SpecCreatedEvent; import com.damon.media.domain.slot.spec.event.SpecDeactivatedEvent; import com.damon.media.domain.slot.spec.event.SpecUpdatedEvent; import com.damon.media.shared.enums.SlotType; import com.damon.shared.enums.SwitchState; import org.axonframework.test.aggregate.AggregateTestFixture; import org.axonframework.test.aggregate.FixtureConfiguration; import org.junit.Before; import org.junit.Test; import java.sql.Timestamp; import java.time.Instant; public class SpecAggregateTest { private FixtureConfiguration<SpecAggregate> aFixture; private CreateSpecCommand createSpecCommand; private SpecCreatedEvent specCreatedEvent; private UpdateSpecCommand updateSpecCommand; private SpecUpdatedEvent specUpdatedEvent; private ActivateSpecCommand activateSpecCommand; private SpecActivatedEvent specActivatedEvent; private DeactivateSpecCommand deactivateSpecCommand; private SpecDeactivatedEvent specDeactivatedEvent; @Before public void setUp() { aFixture = new AggregateTestFixture<>(SpecAggregate.class); createSpecCommand = CreateSpecCommand.builder() .specId(new SpecId()) .width(750) .height(234) .imageType("PNG,JPG") .imageSize(100) .slotType(SlotType.BANNER) .snapshot("command.getSnapshot()") .createdBy(10000L) .createdAt(Timestamp.from(Instant.now())) .build(); specCreatedEvent = SpecCreatedEvent.builder() .specId(createSpecCommand.getSpecId()) .width(createSpecCommand.getWidth()) .height(createSpecCommand.getHeight()) .imageType(createSpecCommand.getImageType()) .imageSize(createSpecCommand.getImageSize()) .state(SwitchState.ON) .type(createSpecCommand.getSlotType()) .snapshot(createSpecCommand.getSnapshot()) .createdBy(createSpecCommand.getCreatedBy()) .createdAt(createSpecCommand.getCreatedAt()) .build(); updateSpecCommand = UpdateSpecCommand.builder() .specId(createSpecCommand.getSpecId()) .width(500) .height(200) .imageType("GIF,PNG,JPG") .imageSize(200) .snapshot("getSnapshot()") .updatedBy(90000L) .updatedAt(Timestamp.from(Instant.now())) .build(); specUpdatedEvent = SpecUpdatedEvent.builder() .specId(updateSpecCommand.getSpecId()) .width(updateSpecCommand.getWidth()) .height(updateSpecCommand.getHeight()) .imageType(updateSpecCommand.getImageType()) .imageSize(updateSpecCommand.getImageSize()) .snapshot(updateSpecCommand.getSnapshot()) .updatedBy(updateSpecCommand.getUpdatedBy()) .updatedAt(updateSpecCommand.getUpdatedAt()) .build(); activateSpecCommand = new ActivateSpecCommand(createSpecCommand.getSpecId(), 20000L); specActivatedEvent = new SpecActivatedEvent( activateSpecCommand.getSpecId(), SwitchState.ON, activateSpecCommand.getUpdatedBy(), activateSpecCommand.getUpdateTime()); deactivateSpecCommand = new DeactivateSpecCommand(createSpecCommand.getSpecId(), 30000L); specDeactivatedEvent = new SpecDeactivatedEvent( deactivateSpecCommand.getSpecId(), SwitchState.OFF, deactivateSpecCommand.getUpdatedBy(), deactivateSpecCommand.getUpdateTime()); } @Test public void testCreateSpecFailed() { CreateSpecCommand createCommand = CreateSpecCommand.builder() .specId(createSpecCommand.getSpecId()) .width(700) .height(200) .imageType("JPG") .imageSize(150) // .type(SlotAggregate.TYPE.BANNER) .build(); aFixture.givenNoPriorActivity() .when(createCommand) .expectNoEvents() .expectException(IllegalArgumentException.class); } @Test public void testCreateSpec() { aFixture.givenNoPriorActivity() .when(createSpecCommand) .expectSuccessfulHandlerExecution() .expectEvents(specCreatedEvent); } @Test public void testUpdateSpec() { aFixture.given(specCreatedEvent) .when(updateSpecCommand) .expectEvents(specUpdatedEvent); } @Test public void testActivateSpec() { aFixture.given(specCreatedEvent, specDeactivatedEvent) .when(activateSpecCommand) .expectEvents(specActivatedEvent); } @Test public void testActivateSpecOnActivated() { aFixture.given(specCreatedEvent) .when(activateSpecCommand) .expectNoEvents(); } @Test public void testDeactivateSpec() { aFixture.given(specCreatedEvent) .when(deactivateSpecCommand) .expectEvents(specDeactivatedEvent); } @Test public void testDeactivateSpecOnDeactivated() { aFixture.given(specCreatedEvent, specDeactivatedEvent) .when(deactivateSpecCommand) .expectNoEvents(); } }
true
9fbe72984219bbd874f7b8fe1651401e4c243033
Java
szszwjk/yiyang
/yiyang-manager/yiyang-manager-pojo/src/main/java/com/yiyang/pojo/ParentInfo.java
UTF-8
4,579
2.359375
2
[]
no_license
package com.yiyang.pojo; import java.io.Serializable; import java.util.Calendar; import java.util.Date; public class ParentInfo implements Serializable { // <tr> <td rowspan="4"> 照片</td><td>性别:${item.infoSex}</td><td>身份证:${item.pIdnum}</td></tr> // <tr> <td>联系方式:${item.infoTel}</td><td>出生地:${item.pBirthplace}</td></tr> // <tr> <td>居住地:${item.pAddress}</td><td></td></tr> // <tr> <td>所属社区:${item.cName}</td><td>社保编号:${item.pCno}</td></tr> // <tr> <td>姓名:${item.infoName}</td><td>有无过敏史:${item.info1}</td><td>有无手术史:${item.info3}</td></tr> // <tr><td>年龄:${item.infoAge}</td> <td>有无外伤:${item.info2}</td><td>有无遗传病:${item.info4}</td></tr> private String infoSex; private String pIdnum; private String infoTel; private String pBirthplace; private String pAddress; private String cName; private String pCno; private String infoName; private String pInfo1; private String pInfo2; private String pInfo3; private String pInfo4; private Date infoAge; private String age; private String infoImg; private String infoUser; public String getInfoUser() { return infoUser; } public void setInfoUser(String infoUser) { this.infoUser = infoUser; } public String getInfoImg() { return infoImg; } public void setInfoImg(String infoImg) { this.infoImg = infoImg; } public String getAge() { Date birthday=infoAge; Calendar cal = Calendar.getInstance(); if (cal.before(birthday)) { throw new IllegalArgumentException( "The birthDay is before Now.It's unbelievable!"); } int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH) + 1; int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birthday); int yearBirth = cal.get(Calendar.YEAR); int monthBirth = cal.get(Calendar.MONTH) + 1; int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { // monthNow==monthBirth if (dayOfMonthNow < dayOfMonthBirth) { age--; } } else { // monthNow>monthBirth age--; } } return age+""; } public void setAge(String age) { this.age = age; } public String getpInfo1() { return pInfo1; } public void setpInfo1(String pInfo1) { this.pInfo1 = pInfo1; } public String getpInfo2() { return pInfo2; } public void setpInfo2(String pInfo2) { this.pInfo2 = pInfo2; } public String getpInfo3() { return pInfo3; } public void setpInfo3(String pInfo3) { this.pInfo3 = pInfo3; } public String getpInfo4() { return pInfo4; } public void setpInfo4(String pInfo4) { this.pInfo4 = pInfo4; } public String getInfoSex() { return infoSex; } public void setInfoSex(String infoSex) { this.infoSex = infoSex; } public String getpIdnum() { return pIdnum; } public void setpIdnum(String pIdnum) { this.pIdnum = pIdnum; } public String getInfoTel() { return infoTel; } public void setInfoTel(String infoTel) { this.infoTel = infoTel; } public String getpBirthplace() { return pBirthplace; } public void setpBirthplace(String pBirthplace) { this.pBirthplace = pBirthplace; } public String getpAddress() { return pAddress; } public void setpAddress(String pAddress) { this.pAddress = pAddress; } public String getcName() { return cName; } public void setcName(String cName) { this.cName = cName; } public String getpCno() { return pCno; } public void setpCno(String pCno) { this.pCno = pCno; } public String getInfoName() { return infoName; } public void setInfoName(String infoName) { this.infoName = infoName; } public Date getInfoAge() { return infoAge; } public void setInfoAge(Date infoAge) { this.infoAge = infoAge; } }
true
21c926144c2ed8f0e3deec3efa3a9e90502c7926
Java
alldatacenter/alldata
/studio/modules/service-data-dts-parent/service-data-dts/src/main/java/com/platform/admin/tool/flinkx/FlinkxJsonInterface.java
UTF-8
733
1.648438
2
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
package com.platform.admin.tool.flinkx; import java.util.Map; /** * 构建 com.guoliang.flinkx json的基础接口 * * @author AllDataDC * @ClassName FlinkxJsonHelper * @Version 2.1.1 * @date 2022/03/14 12:24 */ public interface FlinkxJsonInterface { Map<String, Object> buildJob(); Map<String, Object> buildSetting(); Map<String, Object> buildContent(); Map<String, Object> buildReader(); Map<String, Object> buildHiveReader(); Map<String, Object> buildHiveWriter(); Map<String, Object> buildHBaseReader(); Map<String, Object> buildHBaseWriter(); Map<String, Object> buildMongoDBReader(); Map<String, Object> buildMongoDBWriter(); Map<String, Object> buildWriter(); }
true
f9f3fba3cb274f606ac3013037ba58449246a9cb
Java
stef38-code/StrategyPattern
/src/main/java/com/stephane/strategy/pattern/examples/client/rest/response/post/Post.java
UTF-8
218
1.671875
2
[]
no_license
package com.stephane.strategy.pattern.examples.client.rest.response.post; import lombok.Data; public @Data class Post { private int id; private String title; private String body; private int userId; }
true
eb6e7b0a76614659afa0a661affe259742085076
Java
GeraldGono/Android_Exercises
/DIALOG_PICKER/exercises_DIALOG_PICKER/src/com/example/exercises_dialog_picker/PickerActivity.java
UTF-8
1,306
2.8125
3
[]
no_license
package com.example.exercises_dialog_picker; import android.app.Activity; import android.os.Bundle; import android.widget.NumberPicker; import android.widget.NumberPicker.OnValueChangeListener; import android.widget.TextView; public class PickerActivity extends Activity { NumberPicker np; TextView tv1, tv2; // initialize activity of PickerActivity.java @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.picker); np = (NumberPicker) findViewById(R.id.numPicker1); tv1 = (TextView) findViewById(R.id.txtView2); tv2 = (TextView) findViewById(R.id.txtView3); // set NumberPicker Minimum value and Maximum value np.setMinValue(0); np.setMaxValue(10); np.setWrapSelectorWheel(false); /* * disabling wrapping around the min/max * values */ // set NumberPicker change value behavior np.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { String Old = "Old Value : "; String New = "New Value : "; // get the oldVal and newVal of NumberPicker tv1.setText(Old.concat(String.valueOf(oldVal))); tv2.setText(New.concat(String.valueOf(newVal))); } }); } }
true
327ce5caff6fded44ca4b2e6d6d706478fda755e
Java
ArgelOrtiz/BrainCommunityApp
/app/src/main/java/com/example/braincommunity/Post/PostViewActivity.java
UTF-8
1,676
1.929688
2
[]
no_license
package com.example.braincommunity.Post; import android.content.Intent; import android.os.Bundle; import android.service.autofill.TextValueSanitizer; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.widget.Button; import android.widget.TextView; import com.example.braincommunity.R; public class PostViewActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post_view); Intent intent = getIntent(); setTitle(intent.getStringExtra("title")); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back); TextView usernameTextView, dateTextView, questionTextView, contextTextView; Button likeButton, dislikeButton, orderButton; usernameTextView = findViewById(R.id.userPostTextView); dateTextView = findViewById(R.id.datePostTextView); questionTextView = findViewById(R.id.questionPostTextView); contextTextView = findViewById(R.id.descriptionPostTextView); String title = getIntent().getStringExtra("title"); questionTextView.setText(title); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } @Override public boolean onOptionsItemSelected(MenuItem item) { finish(); return super.onOptionsItemSelected(item); } }
true
81e4a5366eabcdc9d572ef6b40dcbf537660c967
Java
Alphonsbaby/JAVA
/GFGA.JAVA
UTF-8
2,011
3.4375
3
[]
no_license
import java.util.*; public class GFGA { static void checkSymmetric(int mat[][], int row, int col) { int i, j, flag = 1; System.out.println("The matrix formed is:"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { System.out.print(mat[i][j] + "\t"); } System.out.println(""); } int[][] transpose = new int[row][col]; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { transpose[j][i] = mat[i][j]; } } if (row == col) { for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (mat[i][j] != transpose[i][j]) { flag = 0; break; } } if (flag == 0) { System.out.print( "\nThe matrix is not symmetric"); break; } } if (flag == 1) { System.out.print( "\nThe matrix is symmetric"); } } else { System.out.print( "\nThe matrix is not symmetric"); } } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int i, j, row, col, flag = 1; System.out.print("Enter the number of rows:"); row = sc.nextInt(); System.out.print("Enter the number of columns:"); col = sc.nextInt(); int[][] mat = new int[row][col]; System.out.println("Enter the matrix elements:"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { mat[i][j] = sc.nextInt(); } } checkSymmetric(mat, row, col); } }
true
c68bd14e8a709b15c66a57b6ae34f1e508abb69a
Java
sheraz-nadeem/oboe_recorder_sample
/oboe_recorder/oboe/apps/OboeTester/app/src/main/java/com/google/sample/oboe/manualtest/AudioStreamBase.java
UTF-8
3,484
2.0625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 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.google.sample.oboe.manualtest; import java.io.IOException; /** * Base class for any audio input or output. */ public abstract class AudioStreamBase { private StreamConfiguration mRequestedStreamConfiguration; private StreamConfiguration mActualStreamConfiguration; private int mBufferSizeInFrames; public StreamStatus getStreamStatus() { StreamStatus status = new StreamStatus(); status.bufferSize = getBufferSizeInFrames(); status.xRunCount = getUnderrunCount(); status.framesRead = getFramesRead(); status.framesWritten = getFramesWritten(); status.latency = getLatency(); status.state = getState(); return status; } /** * Changes dynamic at run-time. */ public static class StreamStatus { public int bufferSize; public int xRunCount; public long framesWritten; public long framesRead; public double latency; // msec public int state; } public void open(StreamConfiguration requestedConfiguration, StreamConfiguration actualConfiguration, int bufferSizeInFrames) throws IOException { mRequestedStreamConfiguration = requestedConfiguration; mActualStreamConfiguration = actualConfiguration; mBufferSizeInFrames = bufferSizeInFrames; } public abstract boolean isInput(); public abstract void start() throws IOException; public abstract void pause() throws IOException; public abstract void stop() throws IOException; public void startPlayback() throws IOException {} public void stopPlayback() throws IOException {} public abstract int write(float[] buffer, int offset, int length); public abstract void close(); public int getChannelCount() { return mActualStreamConfiguration.getChannelCount(); } public int getFramesPerBurst() { return mActualStreamConfiguration.getFramesPerBurst(); } public int getBufferCapacityInFrames() { return mBufferSizeInFrames; } public int getBufferSizeInFrames() { return mBufferSizeInFrames; } public int setBufferSizeInFrames(int bufferSize) { throw new UnsupportedOperationException("bufferSize cannot be changed"); } public long getFramesWritten() { return -1; } public long getFramesRead() { return -1; } public double getLatency() { return -1.0; } public int getState() { return -1; } public boolean isThresholdSupported() { return false; } // public boolean isLowLatencySupported() { // return false; // } public void setAmplitude(double amplitude) {} public int getUnderrunCount() { return 0; } // public boolean isUnderrunCountSupported() { // return false; // } }
true
cbac48f6c8a3472317abde821968b58453a9eaef
Java
DarkNormal/3rd-year-app
/app/src/main/java/project/b_ourguest/bourguest/BookingActivity.java
UTF-8
17,976
2
2
[]
no_license
package project.b_ourguest.bourguest; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import project.b_ourguest.bourguest.DB.DatabaseOperations; import project.b_ourguest.bourguest.Model.Bookings; import project.b_ourguest.bourguest.Model.Floorplan; import project.b_ourguest.bourguest.Model.tableObject; /** * Created by Robbie on 05/03/2015. */ public class BookingActivity extends ActionBarActivity { private DatabaseOperations db = new DatabaseOperations(); private ArrayList<tableObject> tableview = DatabaseOperations.getTables(); private ArrayList<tableObject> selected = new ArrayList<tableObject>(); private ArrayList<Floorplan> fplan = DatabaseOperations.getFloorplans(); private int k = 0; private int a = 0,totalPeople = 0; private int day, month, year, time; private long timeInMillis; private Handler h = new Handler(); private ImageView im; private ProgressDialog pd; private PorterDuffColorFilter green,blue; private String userID; private ScrollView sv; private TextView te; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences settings = getSharedPreferences("LoginPrefs", 0); userID = settings.getString("email", "").toString(); green = new PorterDuffColorFilter(Color.argb(100, 0, 255, 0), PorterDuff.Mode.SRC_ATOP); blue = new PorterDuffColorFilter(Color.argb(220,41, 121, 255), PorterDuff.Mode.SRC_ATOP); RelativeLayout.LayoutParams rlp; ScrollView scroll = new ScrollView(this); scroll.setBackgroundColor(Color.WHITE); setTitle(convertToTitleCase(MainActivity.getRestaurantToPass().getName())); RelativeLayout rel = new RelativeLayout(this); rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); im = new ImageView(this); im.setImageResource(R.drawable.blank2); im.setId(View.generateViewId()); im.setColorFilter(Color.argb(100,255,0,0)); im.setPadding(10,10,0,0); te = new TextView(this); te.setTextAppearance(this, android.R.style.TextAppearance_Large); te.setId(View.generateViewId()); te.setText("Booked"); LinearLayout lin1 = new LinearLayout(this); lin1.setId(View.generateViewId()); lin1.addView(im); lin1.addView(te); rel.addView(lin1); rlp.addRule(RelativeLayout.BELOW, lin1.getId()); im = new ImageView(this); im.setImageResource(R.drawable.blank2); im.setId(View.generateViewId()); im.setColorFilter(green); im.setPadding(10,10,0,0); te = new TextView(this); te.setTextAppearance(this, android.R.style.TextAppearance_Large); te.setId(View.generateViewId()); te.setText("Available"); te.setLayoutParams(rlp); LinearLayout lin2 = new LinearLayout(this); lin2.setId(View.generateViewId()); lin2.addView(im); lin2.addView(te); lin2.setLayoutParams(rlp); rel.addView(lin2); // rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); rlp.addRule(RelativeLayout.BELOW, lin2.getId()); im = new ImageView(this); im.setImageResource(R.drawable.blank2); im.setId(View.generateViewId()); im.setColorFilter(blue); im.setPadding(10,10,0,0); te = new TextView(this); te.setTextAppearance(this, android.R.style.TextAppearance_Large); te.setId(View.generateViewId()); te.setText("Selected"); LinearLayout lin3 = new LinearLayout(this); lin3.setId(View.generateViewId()); lin3.addView(im); lin3.addView(te); lin3.setLayoutParams(rlp); rel.addView(lin3); if (fplan.size() == 0) { setContentView(R.layout.no_floorplan_layout); TextView t = (TextView) findViewById(R.id.noFloorplanToDisplay); t.setText(convertToTitleCase(MainActivity.getRestaurantToPass().getName()) + " has no floorplan to display. Below is their phone number if you wish to contact them."); TextView t2 = (TextView) findViewById(R.id.restNum); t2.setTextColor(Color.parseColor("#ff8bd1ff")); t2.setText(MainActivity.getRestaurantToPass().getPhoneNum()); t2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:" + MainActivity.getRestaurantToPass().getPhoneNum())); startActivity(callIntent); } }); } else { for (a = 0; a < fplan.size(); a++) { if (a == 0) { rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); rlp.addRule(RelativeLayout.CENTER_HORIZONTAL); rlp.addRule(RelativeLayout.BELOW, lin3.getId()); te = new TextView(this); te.setTextAppearance(this, android.R.style.TextAppearance_Large); te.setId(View.generateViewId()); te.setText(fplan.get(a).getPlanName()); te.setLayoutParams(rlp); rel.addView(te); } else { rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); rlp.addRule(RelativeLayout.CENTER_HORIZONTAL); rlp.addRule(RelativeLayout.BELOW, sv.getId()); te = new TextView(this); te.setTextAppearance(this, android.R.style.TextAppearance_Large); te.setId(View.generateViewId()); te.setText(fplan.get(a).getPlanName()); te.setLayoutParams(rlp); rel.addView(te); } rlp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); rlp.addRule(RelativeLayout.BELOW, te.getId()); rlp.addRule(RelativeLayout.CENTER_HORIZONTAL); sv = new ScrollView(this); sv.setId(View.generateViewId()); sv.setLayoutParams(rlp); int rl = fplan.get(a).getHeight(); int cl = fplan.get(a).getWidth(); TableLayout tableLayout = createTableLayout(rl, cl); HorizontalScrollView hsv = new HorizontalScrollView(this); hsv.addView(tableLayout); sv.addView(hsv); sv.setFillViewport(true); rel.addView(sv); Bundle extras = getIntent().getExtras(); day = extras.getInt("day"); month = extras.getInt("month"); year = extras.getInt("year"); time = extras.getInt("time"); timeInMillis = extras.getLong("timeInMillis"); } scroll.addView(rel); setContentView(scroll); } } @Override public void onBackPressed() { super.onBackPressed(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.book_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.book) { if (selected.size() == 0) Toast.makeText(BookingActivity.this, "No tables were selected", Toast.LENGTH_SHORT).show(); else { new AlertDialog.Builder(BookingActivity.this) .setTitle("Confirm Booking") .setMessage("Confirm") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { db.postBooking(selected, userID, day, month, year, time,totalPeople); validateBooking(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .show(); } } return super.onOptionsItemSelected(item); } private void validateBooking() { pd = ProgressDialog.show(BookingActivity.this, "Processing", "Validating your booking.."); h.postDelayed(new Runnable() { public void run() { pd.dismiss(); Bookings b = new Bookings(selected.size(), userID,totalPeople,day,month,year,time,MainActivity.getRestaurantToPass().getId()); SignInActivity.getBookings().add(b); Intent intent = new Intent(BookingActivity.this, User_Bookings_Activity.class); intent.putExtra("time", time); intent.putExtra("userID", userID); intent.putExtra("day", day); intent.putExtra("month", month); intent.putExtra("year", year); intent.putExtra("timeInMillis", timeInMillis); intent.putExtra("numPeople", totalPeople); intent.putExtra("numTables", selected.size()); intent.putExtra("fromBooking", true); startActivity(intent); finish(); } }, 3500); } public String convertToTitleCase(String name) { String[] partOfName = name.split(" "); char upperCaseLetter; name = ""; String sub; for (int i = 0; i < partOfName.length; i++) { upperCaseLetter = Character.toUpperCase(partOfName[i].charAt(0)); sub = partOfName[i].substring(1, partOfName[i].length()); name = name + (upperCaseLetter + sub) + " "; } return name; } private TableLayout createTableLayout(int rowCount, int columnCount) { // 1) Create a tableLayout and its params TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams(); TableLayout tableLayout = new TableLayout(this); tableLayout.setBackgroundColor(Color.BLACK); // 2) create tableRow params TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams(); tableRowParams.setMargins(2, 2, 2, 2); tableRowParams.weight = 2; for (k = 0; k < rowCount; k++) { TableRow tableRow = new TableRow(this); tableRow.setBackgroundColor(Color.BLACK); for (int i = 0; i < columnCount; i++) { final ImageView im = new ImageView(this); im.setImageResource(R.drawable.blank); for (int j = 0; j < tableview.size(); j++) { im.setBackgroundColor(Color.WHITE); if (fplan.get(a).getId() == tableview.get(j).getFloorplanID()) { if (tableview.get(j).getYcoord() == k && tableview.get(j).getXcoord() == i) { int capacity; //capacity is to be used in the future /*following code sorts through the object type, from highest to lowest //within each size bracket 30,20,10 it sorts further and sets the appropriate image resource */ if (tableview.get(j).getObjType() > 30) { capacity = tableview.get(j).getObjType() - 30; if (capacity == 2) { im.setImageResource(R.drawable.tworndrot); im.setTag(2); } else { im.setImageResource(R.drawable.foursqtrot); im.setTag(4); } } else if (tableview.get(j).getObjType() > 20) { capacity = tableview.get(j).getObjType() - 20; if (capacity == 2) { im.setImageResource(R.drawable.twornd); im.setTag(2); } else { im.setImageResource(R.drawable.foursqt); im.setTag(4); } } else if (tableview.get(j).getObjType() > 10) { capacity = tableview.get(j).getObjType() - 10; if (capacity == 2) { im.setImageResource(R.drawable.twosqtrot); im.setTag(2); } else if (capacity == 4) { im.setImageResource(R.drawable.fourrndrot); im.setTag(4); } else { im.setImageResource(R.drawable.sixsqtrot); im.setTag(6); } } else { capacity = tableview.get(j).getObjType(); if (capacity == 2) { im.setImageResource(R.drawable.twosqt); im.setTag(2); } else if (capacity == 4) { im.setImageResource(R.drawable.fourrnd); im.setTag(4); } else { im.setImageResource(R.drawable.sixsqt); im.setTag(6); } } //set a color filter of green to all the images final PorterDuffColorFilter green = new PorterDuffColorFilter(Color.argb(100, 0, 255, 0), PorterDuff.Mode.SRC_ATOP); im.setColorFilter(green); im.setContentDescription("" + j); if (tableview.get(j).getColor() == 2) { //sets color filter to red if any are booked (with color of 2) im.setColorFilter(Color.argb(100, 255, 0, 0)); } else { im.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //this method of changing color filters cuts out the image swaps we were doing //if we didn't do this we would have 30+ images to swap through, red green and blue final PorterDuffColorFilter blue = new PorterDuffColorFilter(Color.argb(220, 41, 121, 255), PorterDuff.Mode.SRC_ATOP); if (im.getColorFilter().equals(green)) { im.setColorFilter(blue); totalPeople += Integer.parseInt(im.getTag().toString()); selected.add(tableview.get(Integer.parseInt("" + im.getContentDescription()))); } else { im.setColorFilter(green); totalPeople -= Integer.parseInt(im.getTag().toString()); selected.remove(tableview.get(Integer.parseInt("" + im.getContentDescription()))); } } }); } } } } tableRow.addView(im, tableRowParams); } tableLayout.addView(tableRow, tableLayoutParams); } return tableLayout; } }
true
e210488e89f27ac2f88efcf92a5ddc7eca188d35
Java
pnambic/depan
/DepanViewDoc/prod/src/com/google/devtools/depan/view_doc/layout/grid/GridLayoutRunner.java
UTF-8
3,956
2.421875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 The Depan Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.depan.view_doc.layout.grid; import com.google.devtools.depan.model.GraphNode; import com.google.devtools.depan.view_doc.layout.LayoutContext; import com.google.devtools.depan.view_doc.layout.LayoutRunner; import com.google.common.collect.Maps; import java.awt.geom.Point2D; import java.util.Collection; import java.util.Map; /** * Part of ViewDoc plug to ensure that one layout is always available. * * @author <a href="leeca@pnambic.com">Lee Carver</a> */ public class GridLayoutRunner implements LayoutRunner { public static final double UNIT = 30.0; private Map<GraphNode, Point2D> positions; private final LayoutContext context; private double columns; private double rows; private double horizontalSpace = UNIT; private double verticalSpace = UNIT; public GridLayoutRunner(LayoutContext context) { this.context = context; } public void setColumnRows(int columns, int rows) { this.columns = columns; this.rows = rows; } public void setHorizontalSpace(double horizontalSpace) { this.horizontalSpace = horizontalSpace; } public void setVerticalSpace(double verticalSpace) { this.verticalSpace = verticalSpace; } @Override public int layoutCost() { return 1; } @Override public void layoutStep() { Collection<GraphNode> layoutNodes = context.getMovableNodes(); positions = Maps.newHashMapWithExpectedSize(layoutNodes.size()); double leftPos = - horizontalSpace * ((columns / 2.0) - 0.5); double topPos = verticalSpace * ((rows / 2.0) - 0.5); double xCurr = leftPos; double yCurr = topPos; int item = (int) columns; for (GraphNode node : layoutNodes) { positions.put(node, new Point2D.Double(xCurr, yCurr)); item--; if (item > 0) { xCurr += horizontalSpace; } else { item = (int) columns; xCurr = leftPos; yCurr -= verticalSpace; } } } @Override public boolean layoutDone() { return (positions != null); } @Override public Map<GraphNode, Point2D> getPositions(Collection<GraphNode> nodes) { return positions; } public static GridLayoutRunner buildByRows( LayoutContext context, int buildRows) { Collection<GraphNode> layoutNodes = context.getMovableNodes(); int buildColumns = layoutNodes.size() / buildRows; GridLayoutRunner result = new GridLayoutRunner(context); result.setColumnRows(buildColumns, buildRows); return result; } public static GridLayoutRunner buildByColumns( LayoutContext context, int buildColumns) { Collection<GraphNode> layoutNodes = context.getMovableNodes(); int buildRows = layoutNodes.size() / buildColumns; GridLayoutRunner result = new GridLayoutRunner(context); result.setColumnRows(buildColumns, buildRows); return result; } public static GridLayoutRunner buildPortrait(LayoutContext context) { Collection<GraphNode> layoutNodes = context.getMovableNodes(); double split = Math.sqrt(layoutNodes.size()); return buildByRows(context, (int) Math.ceil(split)); } public static GridLayoutRunner buildLandscape(LayoutContext context) { Collection<GraphNode> layoutNodes = context.getMovableNodes(); double split = Math.sqrt(layoutNodes.size()); return buildByRows(context, (int) Math.floor(split)); } }
true
39448888ca2dbae9bc9d4fdc7de38207ebb78735
Java
nguyenkiemhieu1/loginVNPT
/app/src/main/java/com/example/login/adapter/NewHistoryDetailAdapter.java
UTF-8
7,899
2.15625
2
[]
no_license
package com.example.login.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.login.R; import com.example.login.common.Constants; import com.example.login.model.Login.LogInfo; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; class NewHistoryDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext; private List<LogInfo> logInfoList; private String status; @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(mContext); return new MyViewHolder(inflater.inflate(R.layout.item_new_log_detail, parent, false)); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { ((MyViewHolder) holder).bindData(logInfoList.get(position)); } @Override public int getItemCount() { return logInfoList != null ? logInfoList.size() : 0; } public class MyViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.tv_name) TextView tvName; @BindView(R.id.tv_username) TextView tvUsername; @BindView(R.id.tv_date) TextView tvDate; @BindView(R.id.tv_noidung) TextView tvNoidung; @BindView(R.id.tv_xlc_lb) TextView tvXlcLb; @BindView(R.id.txtXLC) TextView txtXLC; @BindView(R.id.tv_ph_lb) TextView tvPhLb; @BindView(R.id.txtPH) TextView txtPH; @BindView(R.id.tv_xem_lb) TextView tvXemLb; @BindView(R.id.txtXem) TextView txtXem; @BindView(R.id.tv_xyk_lb) TextView tv_xyk_lb; @BindView(R.id.txtXYK) TextView txtXYK; @BindView(R.id.line) View line; @BindView(R.id.layout_process) LinearLayout layoutProcess; public MyViewHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this, itemView); } void bindData(final LogInfo logInfo) { tvName.setText(logInfo.getFullName()); tvUsername.setText(logInfo.getUpdateBy()); if (logInfo.getUpdateDate() != null && !logInfo.getUpdateDate().trim().equals("")) { tvDate.setText(logInfo.getUpdateDate()); } else { tvDate.setText(""); } if (!status.equals(Constants.NEW_HISTORY)) { if (logInfo.getComment() != null && !logInfo.getComment().trim().equals("")) { tvNoidung.setText(logInfo.getComment()); } else { line.setVisibility(View.GONE); tvNoidung.setVisibility(View.GONE); } if (logInfo.getChuyenToi() != null && !logInfo.getChuyenToi().equals("")) { String[] data = logInfo.getChuyenToi().split("\\|"); try { if (data[0] != null && !data[0].trim().equals("") && data[0].contains(":")) { txtXLC.setText(data[0].split("\\:")[1]); tvXlcLb.setText(data[0].split("\\:")[0] + ":"); } else { if (data[0] != null && !data[0].trim().equals("")) { txtXLC.setText(data[0]); } else { txtXLC.setVisibility(View.GONE); tvXlcLb.setVisibility(View.GONE); } } } catch (Exception ex) { txtXLC.setVisibility(View.GONE); tvXlcLb.setVisibility(View.GONE); } try { if (data[1] != null && !data[1].trim().equals("") && data[1].contains(":")) { txtPH.setText(data[1].split("\\:")[1]); tvPhLb.setText(data[1].split("\\:")[0] + ":"); } else { if (data[1] != null && !data[1].trim().equals("")) { txtPH.setText(data[1]); } else { txtPH.setVisibility(View.GONE); tvPhLb.setVisibility(View.GONE); } } } catch (Exception ex) { txtPH.setVisibility(View.GONE); tvPhLb.setVisibility(View.GONE); } try { if (data[2] != null && !data[2].trim().equals("") && data[2].contains(":")) { txtXem.setText(data[2].split("\\:")[1]); tvXemLb.setText(data[2].split("\\:")[0] + ":"); } else { if (data[2] != null && !data[2].trim().equals("")) { txtXem.setText(data[2]); } else { tvXemLb.setVisibility(View.GONE); txtXem.setVisibility(View.GONE); } } } catch (Exception ex) { tvXemLb.setVisibility(View.GONE); txtXem.setVisibility(View.GONE); } try { if (data[3] != null && !data[3].trim().equals("") && data[3].contains(":")) { txtXYK.setText(data[3].split("\\:")[1]); tv_xyk_lb.setText(data[3].split("\\:")[0] + ":"); } else { if (data[3] != null && !data[3].trim().equals("")) { txtXYK.setText(data[3]); } else { txtXYK.setVisibility(View.GONE); tv_xyk_lb.setVisibility(View.GONE); } } } catch (Exception ex) { txtXYK.setVisibility(View.GONE); tv_xyk_lb.setVisibility(View.GONE); } } else { tvXlcLb.setVisibility(View.GONE); txtXLC.setVisibility(View.GONE); tvPhLb.setVisibility(View.GONE); txtPH.setVisibility(View.GONE); tvXemLb.setVisibility(View.GONE); txtXem.setVisibility(View.GONE); txtXYK.setVisibility(View.GONE); tv_xyk_lb.setVisibility(View.GONE); line.setVisibility(View.GONE); } } else { tvNoidung.setVisibility(View.GONE); tvXlcLb.setVisibility(View.GONE); txtXLC.setVisibility(View.GONE); tvPhLb.setVisibility(View.GONE); txtPH.setVisibility(View.GONE); tvXemLb.setVisibility(View.GONE); txtXem.setVisibility(View.GONE); txtXYK.setVisibility(View.GONE); tv_xyk_lb.setVisibility(View.GONE); line.setVisibility(View.GONE); } } } public NewHistoryDetailAdapter(Context mContext, List<LogInfo> datalist, String status) { this.mContext = mContext; this.logInfoList = datalist; this.status = status; } }
true
0bcf0208b6663a3cf047015d9ade408d283c0b17
Java
aniketsurya2205/aniket
/SprinMVCDropdown/src/main/java/com/controller/DropdownController.java
UTF-8
1,135
2.328125
2
[]
no_license
package com.controller; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class DropdownController { private ModelAndView mav; private void syso() { System.out.println("niteennnxscbbsucdyhbcjc hi anya"); System.out.println("hiii"); } /* @RequestMapping(value="/DropdownList") public String m1() { System.out.println("m1 method in controller"); return "DropdownPage"; } @RequestMapping(value="/CountryMethod", method = RequestMethod.GET) public ModelAndView Country() { mav=new ModelAndView(); System.out.println("m2 country method in controller"); Map<String, String> us = new LinkedHashMap<String, String>(); us.put("1", "Washington"); us.put("2", "New York"); mav.addObject("countryList", us); return mav; } */ }
true
ad3978b52b63e411d94fb1929ecb0895cfe61b79
Java
bearhsu2/design_patterns
/src/main/java/com/kuma/design_patterns/singleton/StaticBlock.java
UTF-8
401
2.75
3
[]
no_license
package com.kuma.design_patterns.singleton; /** * Created by bearhsu2 on 10/10/2016. */ // Static block initialization implementation is similar to eager initialization. public class StaticBlock { private static StaticBlock instance; static { instance = new StaticBlock(); } public static StaticBlock getInstance(){ return instance; } }
true
aee45c2ae3abc56c55fc7bed9dd065fec73e01fe
Java
rintala/DD2380
/TTT/Player.java
UTF-8
6,882
3.515625
4
[]
no_license
import java.util.*; public class Player { /** * Performs a move * * @param gameState the current state of the board * @param deadline time before which we must have returned * @return the next state the board is in after our move */ private static int PLAYER; private static int OTHER_PLAYER; private static final int DEPTH = 4; public GameState play(final GameState gameState, final Deadline deadline) { Vector<GameState> nextStates = new Vector<GameState>(); gameState.findPossibleMoves(nextStates); if (nextStates.size() == 0) { // Must play "pass" move if there are no other moves possible. return new GameState(gameState, new Move()); } /** * Here you should write your algorithms to get the best next move, i.e. * the best next state. This skeleton returns a random move instead. */ //this will always be start value double maxProb = -999999999; int maxMove = 0; double[] finalVals = new double[nextStates.size()]; PLAYER = gameState.getNextPlayer(); OTHER_PLAYER = PLAYER == 1 ? 2 : 1; for (int i = 0; i < nextStates.size(); i++) { //Choose algorithm here - alphabeta-pruning OR minimax double theVal = alphabetaPruning(nextStates.get(i), 0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, OTHER_PLAYER); //System.err.println("THE FINAL VAL: " + theVal); finalVals[i] = theVal; if (theVal > maxProb) { maxProb = theVal; maxMove = i; } } System.err.println("THE MAX Prob-...................................." + maxProb); System.err.println("THE MAX MOVE-...................................." + maxMove); System.err.println("fiVals: "+Arrays.toString(finalVals)); return nextStates.elementAt(maxMove); } public int[][] createGameMatrix(GameState gState) { int[][] theGameMatrix = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { theGameMatrix[i][j] = gState.at(i, j); } } return theGameMatrix; } public double getHeuristic(GameState gState) { //Check if depth was reached or actual leaf node if (gState.isEOG()) { if (gState.isXWin()) { return Double.MAX_VALUE; } else if (gState.isOWin()) { return -Double.MAX_VALUE; } else { return 0; } } //will be used by both max and min player i.e. both player X and player O int playerIs = Constants.CELL_X; int opponentIs = playerIs == 1 ? 2 : 1; int[][] theGameMatrix = createGameMatrix(gState); //print2D(theGameMatrix); //Will use the following sub-heuristics to add onto each player's score //1.rows //2.columns //3.diagonals int playerScore = 0; int opponentScore = 0; //1. Rows---------------------------------------------------------- for (int j = 0; j < theGameMatrix[0].length; j++) { for (int i = 0; i < theGameMatrix.length; i++) { if (theGameMatrix[i][j] == playerIs) { playerScore++; } else if (theGameMatrix[i][j] == opponentIs) { opponentScore++; } } } //2. Cols---------------------------------------------------------- for (int i = 0; i < theGameMatrix.length; i++) { for (int j = 0; j < theGameMatrix[0].length; j++) { //System.err.println("\n\n "+i+" "+j); if (theGameMatrix[i][j] == playerIs) { playerScore++; } else if (theGameMatrix[i][j] == opponentIs) { opponentScore++; } } } //3. Diagonals------------------------------------------------------ //3.1 Upper left to lower right for (int i = 0; i < theGameMatrix.length; i++) { //System.err.println("\n\n "+i+" "+i); if (theGameMatrix[i][i] == playerIs) { playerScore++; } else if (theGameMatrix[i][i] == opponentIs) { opponentScore++; } } //3.2 Lower left to upper right------------------------- int j = 0; for (int i = theGameMatrix.length - 1; i >= 0; i--) { if (theGameMatrix[i][j] == playerIs) { playerScore++; } else if (theGameMatrix[i][j] == opponentIs) { opponentScore++; } j++; } //----------------------------------------------------------------------------- double playerHeuristic = Math.pow(playerScore, 2) - Math.pow(opponentScore, 2); return playerHeuristic; } private double alphabetaPruning(GameState gameState, int depth, double alpha, double beta, int player){ Vector<GameState> nextStates = new Vector<GameState>(); gameState.findPossibleMoves(nextStates); double v = 0; if (nextStates.size() == 0 || depth == DEPTH){ return getHeuristic(gameState); } else{ if (player == PLAYER){ v = Double.NEGATIVE_INFINITY; for (int child = 0; child < nextStates.size(); child++) { v = Math.max(v, alphabetaPruning(nextStates.get(child), depth+1, alpha, beta, OTHER_PLAYER)); alpha = Math.max(alpha, v); if (beta <= alpha){ break; } } } else if(player == OTHER_PLAYER){ v = Double.POSITIVE_INFINITY; for (int child = 0; child < nextStates.size(); child++) { v = Math.min(v, alphabetaPruning(nextStates.get(child), depth+1, alpha, beta, PLAYER)); beta = Math.min(beta, v); if (beta <= alpha){ break; } } } } return v; } public static void print2D(int matrix[][]){ int counter = 0; try{ for (int[] row : matrix) { if(counter==0){} else{ System.err.print("\n"); } for(int i =0;i<row.length;i++){ System.err.print(row[i]+" "); } counter++; } } catch(Exception e){ System.err.println("ERROR w map print"); } } }
true
3b7bad50e7e1a79d435baa9cd91dac02b019a398
Java
bruno1022/mercado-acoes
/src/main/java/com/javaee/bruno/mercadoacoes/controllers/v1/AcaoController.java
UTF-8
5,457
2.109375
2
[]
no_license
package com.javaee.bruno.mercadoacoes.controllers.v1; import java.util.HashSet; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.javaee.bruno.mercadoacoes.domain.MessageId; import com.javaee.bruno.mercadoacoes.domain.Acao; import com.javaee.bruno.mercadoacoes.domain.AcaoDemanda; import com.javaee.bruno.mercadoacoes.domain.AcaoDemandaRest; import com.javaee.bruno.mercadoacoes.domain.AcaoMercado; import com.javaee.bruno.mercadoacoes.domain.AcaoOferta; import com.javaee.bruno.mercadoacoes.domain.AcaoOfertaRest; import com.javaee.bruno.mercadoacoes.domain.AcaoRest; import com.javaee.bruno.mercadoacoes.services.EmpresaService; import com.javaee.bruno.mercadoacoes.services.AcaoService; @RestController @RequestMapping(AcaoController.BASE_URL) public class AcaoController { public static final String BASE_URL = "/api/v1/acoes"; @Autowired private AcaoService acaoService; @Autowired private EmpresaService empresaService; /* Listar ações - I */ // GET @GetMapping @ResponseStatus(HttpStatus.OK) public Set<AcaoRest> getAll() { Set<AcaoRest> stockRest = new HashSet<>(); acaoService.getAll().forEach((Acao stock) -> { stockRest.add(new AcaoRest(stock)); }); return stockRest; } @GetMapping({ "/{id}" }) @ResponseStatus(HttpStatus.OK) public AcaoRest getById(@PathVariable String id) { return new AcaoRest(acaoService.getById(id)); } /* Listar ações - F */ /* Emissão de Ações - I */ // GET @GetMapping({ "/emit/{empresaId}" }) @ResponseStatus(HttpStatus.OK) public Set<AcaoRest> getAllEmpresa(@PathVariable String empresaId) { Set<AcaoRest> stockRest = new HashSet<>(); empresaService.getAllStocks(empresaId).forEach((Acao stock) -> { stockRest.add(new AcaoRest(stock)); }); return stockRest; } @GetMapping({ "/emit/{empresaId}/{acaoId}" }) @ResponseStatus(HttpStatus.OK) public AcaoRest getById(@PathVariable String empresaId, @PathVariable String stockId) { return new AcaoRest (empresaService.getStockById(empresaId, stockId)); } // POST @PostMapping({ "/emit/{empresaId}" }) @ResponseStatus(HttpStatus.CREATED) public AcaoRest createNew(@PathVariable String empresaId, @RequestBody Acao acao) { return new AcaoRest(acaoService.emitNew(empresaId, acao)); } /* Emissão de Ações - F */ /* Comprar ações - I */ // GET @GetMapping({ "/comprar" }) @ResponseStatus(HttpStatus.OK) public Set<AcaoDemandaRest> getDemands() { Set<AcaoDemandaRest> demandsRest = new HashSet<>(); acaoService.getAll().forEach((Acao acao) -> { acao.getDemandas().forEach((AcaoDemanda demanda) -> { if (demanda.getQuantidade() - demanda.getQuantidadeComprador() > 0) { demandsRest.add(new AcaoDemandaRest(demanda)); } }); }); return demandsRest; } // POST @PostMapping({ "/comprar" }) @ResponseStatus(HttpStatus.CREATED) public MessageId comprar(@RequestBody AcaoMercado acaoMercado) { return acaoService.sendMessage("demanda", acaoMercado); } @PostMapping({ "/comprar/{acaoId}" }) @ResponseStatus(HttpStatus.CREATED) public MessageId comprar(@PathVariable String acaoId, @RequestBody AcaoMercado acaoMercado) { acaoMercado.setAcaoId(acaoId); return acaoService.sendMessage("demanda", acaoMercado); } @PostMapping({ "/bcompraruy/{acaoId}/{investidorId}" }) @ResponseStatus(HttpStatus.CREATED) public MessageId comprarStockInvestor(@PathVariable String acaoId, @PathVariable String investidorId, @RequestBody AcaoMercado acaoMercado) { acaoMercado.setAcaoId(acaoId); acaoMercado.setInvestidorId(investidorId); return acaoService.sendMessage("demanda", acaoMercado); } /* Comprar ações - F */ /* Vender ações - I */ // GET @GetMapping({ "/vender" }) @ResponseStatus(HttpStatus.OK) public Set<AcaoOfertaRest> getOffers() { Set<AcaoOfertaRest> acaoOfertaRest = new HashSet<>(); acaoService.getAll().forEach((Acao acao) -> { acao.getOfertas().forEach((AcaoOferta oferta) -> { if (oferta.getQuantidade() - oferta.getQuantidadeVendido() > 0) { acaoOfertaRest.add(new AcaoOfertaRest(oferta)); } }); }); return acaoOfertaRest; } // POST @PostMapping({ "/vender" }) @ResponseStatus(HttpStatus.CREATED) public MessageId vender(@RequestBody AcaoMercado acaoMercado) { return acaoService.sendMessage("oferta", acaoMercado); } @PostMapping({ "/vender/{acaoId}" }) @ResponseStatus(HttpStatus.CREATED) public MessageId venderAcao(@PathVariable String acaoId, @RequestBody AcaoMercado acaoMercado) { acaoMercado.setAcaoId(acaoId); return acaoService.sendMessage("oferta", acaoMercado); } @PostMapping({ "/vender/{acaoId}/{investidorId}" }) @ResponseStatus(HttpStatus.CREATED) public MessageId vender(@PathVariable String acaoId, @PathVariable String investidorId, @RequestBody AcaoMercado acaoMercado) { acaoMercado.setAcaoId(acaoId); acaoMercado.setInvestidorId(investidorId); return acaoService.sendMessage("oferta", acaoMercado); } /* Vender ações - F */ }
true
13cbf5853aad9df60992a02ffe9b7c8edf954b36
Java
Baltiless/LisUbuntu
/program/java/leetcode/Solution.java
UTF-8
1,159
3.421875
3
[]
no_license
import java.util.*; public class Solution { public List<String[]> nQueens(int n) { List<String[]> output = new ArrayList<String[]>(); } private void helper(int n, int row, int[] thQueen, List<String[]> output) { if(row == n) { String[] entry = new String[n]; for(int i = 0;i < n;i++) { StringBuilder sb = new StringBuilder(); for(int j = 0;j < n;j++) { sb.append(j == thQueen[i] ? "Q" : "."); } entry[i] = sb.toString(); } output.add(entry); return; } for(int i = 0;i < n;i++) { thQueen[row] = i; if(isValid(thQueen, row)) { helper(n, row + 1, thQueen, output); } } } private boolean isValid(int[] thQueen, int row) { for(int i = 0;i < row;i++) { if(thQueen[i] == thQueen[row]) { return false; } if(Math.abs((thQueen[i] - thQueen[row]) / (i - row)) == 1) { return false; } } return true; } }
true
8a9cad01416153798e2b61d80392b3f8e14fbcb5
Java
zhangwan/xiaohuplay_android
/common/src/main/java/com/tinytiger/common/net/data/home2/NewsBean.java
UTF-8
1,128
1.875
2
[]
no_license
package com.tinytiger.common.net.data.home2; /** * 游戏分类 */ public class NewsBean { public String id; public int type=1; public String title; public String cover; public int view_num; public String video_url; public long video_length; public String create_time; public String game_id=""; public int comment_count; public int comment_user_num; public int comment_num; public String game_name; public String name; public String user_id; /*"id": 124, #内容ID "type": 1, #类型:1为图文,2为视频 "title": "张晓伟666666", #内容标题 "cover": "https://cdn.tinytiger.cn/FnMRUJUaLJYRKBXz2Gxm3FCUePqX", #内容封面 "view_num": 12, #浏览数 "video_url": null, #视频URL(type=2时有返回值) "video_length": 0, #视频时长(单位秒,type=2时有返回值) "create_time": "2020-01-17 16:34:27", #内容创建时间 "game_id": 0, #游戏ID "comment_count": 0, #评论总数 "game_name": 0 #游戏名*/ }
true
b91b91c19248feeebd0a2d1270bcd86854d52d00
Java
hbkuang/yangjian
/agent-plugins/agent-plugin-jedis/src/main/java/com/yametech/yangjian/agent/plugin/jedis/JedisConvert.java
UTF-8
4,259
1.96875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 yametech. * * 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.yametech.yangjian.agent.plugin.jedis; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; import com.yametech.yangjian.agent.api.IConfigReader; import com.yametech.yangjian.agent.api.bean.ConfigNotifyType; import com.yametech.yangjian.agent.api.bean.TimeEvent; import com.yametech.yangjian.agent.api.common.StringUtil; import com.yametech.yangjian.agent.api.convert.IMethodAsyncConvert; import com.yametech.yangjian.agent.plugin.jedis.bean.RedisKeyBean; /** * 转换jedis调用事件 * * @author dengliming * @date 2019/12/4 */ public class JedisConvert implements IMethodAsyncConvert, IConfigReader { private List<String> keyRules = new CopyOnWriteArrayList<>(); @Override public List<Object> convert(Object thisObj, long startTime, Object[] allArguments, Method method, Object ret, Throwable t, Map<Class<?>, Object> globalVar) throws Throwable { byte[][] args = (byte[][]) allArguments[1]; if (args == null || args.length == 0) { return null; } String key = StringUtil.encode(args[0]); if (StringUtil.isEmpty(key)) { return null; } long now = System.currentTimeMillis(); return Arrays.asList(new RedisKeyBean(Arrays.asList(key), now, now - startTime)); } @Override public List<TimeEvent> convert(Object eventBean) { RedisKeyBean redisKeyBean = (RedisKeyBean) eventBean; return getMatchKeyTimeEvents(redisKeyBean); } public List<TimeEvent> getMatchKeyTimeEvents(RedisKeyBean redisKeyBean) { Map<String, Integer> matchKeyNums = new HashMap<>(); for (String key : redisKeyBean.getKeys()) { Set<String> matchKeyRules = getMatchKeyRules(key); if (matchKeyRules == null) { continue; } for (String keyRule : matchKeyRules) { Integer num = matchKeyNums.getOrDefault(keyRule, 0); matchKeyNums.put(keyRule, num + 1); } } return matchKeyNums.entrySet() .stream() .map(o -> { TimeEvent timeEvent = new TimeEvent(); timeEvent.setEventTime(redisKeyBean.getEventTime()); timeEvent.setUseTime(redisKeyBean.getUseTime()); timeEvent.setIdentify(o.getKey()); timeEvent.setNumber(o.getValue()); return timeEvent; }) .collect(Collectors.toList()); } public Set<String> getMatchKeyRules(String key) { if (StringUtil.isEmpty(key) || keyRules == null) { return null; } return keyRules.stream() .filter(r -> key.indexOf(r) != -1) .collect(Collectors.toSet()); } @Override public Set<String> configKey() { return new HashSet<>(Arrays.asList("redis\\.key\\.rule", "redis\\.key\\.rule\\..*")); } /** * 覆盖更新 * * @param kv 配置数据 */ @Override public void configKeyValue(Map<String, String> kv) { if (kv == null) { return; } keyRules.clear();// 此处没有原子的方法可以直接替换其中的元素,所以在有更新时可能导致短暂的无配置数据 keyRules.addAll(kv.values()); } @Override public ConfigNotifyType notifyType() { return ConfigNotifyType.CHANGE; } }
true
62d725c217e9221396e517868ee194162343bb36
Java
Ayushi51/HappyPlace
/app/src/main/java/com/example/happyplace/SwiggyActivity.java
UTF-8
696
1.976563
2
[]
no_license
package com.example.happyplace; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class SwiggyActivity extends AppCompatActivity { WebView webo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_swiggy); webo=findViewById(R.id.webo); WebSettings settings =webo.getSettings(); settings.setJavaScriptEnabled(true); webo.setWebViewClient(new WebViewClient()); webo.loadUrl("https://www.swiggy.com/"); } }
true
8831b4a7579c5ed3a3965e08052e96c483505ddb
Java
marciowillian/PedidoVenda
/src/main/java/TesteCliente.java
UTF-8
976
2.4375
2
[]
no_license
import com.mwcc.pedidovenda.model.*; import javax.persistence.*; import java.math.BigDecimal; public class TesteCliente { public static void main(String[]args){ EntityManagerFactory factory = Persistence.createEntityManagerFactory("PedidoPU"); EntityManager manager = factory.createEntityManager(); EntityTransaction trx = manager.getTransaction(); trx.begin(); Cliente cliente = new Cliente(); cliente.setNome("João das Couves"); cliente.setEmail("joao@dascouves.com"); cliente.setDocumentoReceitaFederal("123.133.123.12"); cliente.setTipo(TipoPessoa.FISICA); Endereco en = new Endereco(); en.setLogradouro("Rua das Aboboras Vermelhas"); en.setNumero("111"); en.setCidade("Uberlândia"); en.setUf("MG"); en.setCep("38400-000"); en.setCliente(cliente); cliente.getEnderecos().add(en); manager.persist(cliente); trx.commit(); } }
true
1393def15c4edcb798fd6ce579514dbb4500a5cd
Java
chihyuyang/Maze
/stuff/Main.java
UTF-8
545
2.796875
3
[]
no_license
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("Maze"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); MazePanel ballPanel = new MazePanel(); frame.add(ballPanel, BorderLayout.CENTER); //frame.setSize(511, 539); frame.setSize(1511, 989); frame.setVisible(true); } }
true
6c5be16368fe35f1b46a3f546fe604b308350ec7
Java
OrysiaKozak/Online_Shop
/src/main/java/ua/controllers/HomeControllers.java
UTF-8
619
1.976563
2
[]
no_license
package ua.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeControllers { /*Home Page*/ @RequestMapping(value="/") public String welcome(){ return "homePage"; } /*Redirect to Home Page*/ @RequestMapping(value="home") public String backHome(){ return "redirect:/"; } @RequestMapping(value="registration") public String register(){ return "registrationPage"; } @RequestMapping(value="products") public String viewProducts(){ return "productsPage"; } }
true
67977b3b946ff48607bb9a0fadd4d2bf94f50f43
Java
Randehh/Epic-Quiz
/src/randy/quiz/quiz.java
UTF-8
7,709
2.109375
2
[]
no_license
package randy.quiz; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.Listener; import org.bukkit.event.Event.Priority; import org.bukkit.plugin.java.JavaPlugin; public class quiz extends JavaPlugin{ static HashMap<String, String> questions = new HashMap<String, String>(); @SuppressWarnings("rawtypes") static Map score = new HashMap<String, Integer>(); static HashMap<String, Integer> current = new HashMap<String, Integer>(); static HashMap<String, Integer> delay = new HashMap<String, Integer>(); static HashMap<String, String> announcer = new HashMap<String, String>(); static HashMap<String, Boolean> moneyrewards = new HashMap<String, Boolean>(); static HashMap<String, Boolean> banlist = new HashMap<String, Boolean>(); static HashMap<String, Integer> rewards = new HashMap<String, Integer>(); static HashMap<String, Integer> achievements = new HashMap<String, Integer>(); private final quizPlayerListener playerListener = new quizPlayerListener(); @Override public void onDisable() { quizSaver.saveScore(); } @Override public void onEnable() { quizLoader.loadPlugin(); quizSaver.loadScore(); getServer().getPluginManager().registerEvent(Event.Type.PLAYER_CHAT, (Listener) playerListener, Priority.Normal, Bukkit.getServer().getPluginManager().getPlugin("EpicQuiz")); } public static void startSystem(final String world){ int time = delay.get("delay"); nextQuestion(world); int timer = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Bukkit.getPluginManager().getPlugin("EpicQuiz"), new Runnable() { public void run(){ nextQuestion(world); } }, time * 20L, time * 20L); //TODO World.timer current.put(world+".timer", timer); } public static void nextQuestion(final String world){ //TODO Use new world string current.put("question", -1); int total = current.get(world+".total"); Random generator = new Random(); final int questionno = generator.nextInt(total); final String question = questions.get(world+"."+questionno+".question"); final List<Player> players = Bukkit.getServer().getWorld(world).getPlayers(); int a; for(a = 0; a < players.size(); a++){ players.get(a).sendMessage(announcer.get("ready")); } Bukkit.getServer().getScheduler().scheduleAsyncDelayedTask(Bukkit.getServer().getPluginManager().getPlugin("EpicQuiz"), new Runnable() { public void run(){ String askstring = announcer.get("ask"); askstring = askstring.replace("[question]", question); int e; for(e = 0; e < players.size(); e++){ players.get(e).sendMessage(askstring); current.put(world+".question", questionno); } } }, 2 * 20L); } public static void stopSystem(String world){ int timer = current.get(world+".timer"); Bukkit.getServer().getScheduler().cancelTask(timer); current.put(world+".question", -1); } @SuppressWarnings("rawtypes") public boolean onCommand(CommandSender sender, Command command, String commandName, String[] args){ if(commandName.equalsIgnoreCase("quiz")){ if(args.length == 1){ if(args[0].equalsIgnoreCase("help")){ if(sender.hasPermission("epicquiz.help")){ sender.sendMessage(ChatColor.GOLD + "EpicQuiz Help"); sender.sendMessage(ChatColor.GOLD + "/quiz help - Display this page."); sender.sendMessage(ChatColor.GOLD + "/quiz next [world] - Goes to the next question of the specified world."); sender.sendMessage(ChatColor.GOLD + "/quiz top [number] - Shows the top scorers."); sender.sendMessage(ChatColor.GOLD + "/quiz ban [playername] - Bans a player form the quiz."); sender.sendMessage(ChatColor.GOLD + "/quiz unban [playername] - Unbans a player from the quiz."); }else{ sender.sendMessage(ChatColor.RED + "EpicQuiz: You don't have permission to do that."); return true; } } } if(args.length == 2){ if(args[0].equalsIgnoreCase("ban")){ if(sender.hasPermission("epicquiz.ban")){ String playername = args[1]; if(banlist.containsKey(playername)){ if(banlist.get(playername).equals(true)){ sender.sendMessage(playername + " is already banned from the quiz."); return true; }else{ banlist.put(playername, true); sender.sendMessage(playername + " is now banned from the quiz."); return true; } }else{ banlist.put(playername, true); sender.sendMessage(playername + " is now banned from the quiz."); return true; } } } if(args[0].equalsIgnoreCase("unban")){ if(sender.hasPermission("epicquiz.unban")){ String playername = args[1]; if(banlist.containsKey(playername)){ if(banlist.get(playername).equals(false)){ sender.sendMessage(playername + " is not banned."); return true; }else{ banlist.put(playername, false); sender.sendMessage(playername + " is now banned from the quiz."); return true; } }else{ banlist.put(playername, false); sender.sendMessage(playername + " is now banned from the quiz."); return true; } } } if(args[0].equalsIgnoreCase("top")){ if(sender.hasPermission("epicquiz.top")){ sender.sendMessage(ChatColor.GOLD + "[==== Top Players ====]"); int e = 0; for (Iterator i = sortByValue(score).iterator(); e < Integer.parseInt(args[1]); ) { try{ String key = ChatColor.stripColor((String) i.next()); sender.sendMessage(ChatColor.YELLOW + key + ": " + score.get(key)); e++; if(!i.hasNext()){ break; } }catch(NoSuchElementException a){ } } sender.sendMessage(ChatColor.GOLD + "[======================]"); return true; }else{ sender.sendMessage(ChatColor.RED + "EpicQuiz: You don't have permission to do that."); return true; } } if(args[0].equalsIgnoreCase("next")){ if(sender.hasPermission("epicquiz.next")){ if(current.get(args[1]+".question") != -1){ current.put(args[1]+".question", -1); quiz.nextQuestion(args[1]); }else{ sender.sendMessage(ChatColor.RED + "[EpicQuiz]: That world doesn't exist or the next question is incoming."); } return true; }else{ sender.sendMessage(ChatColor.RED + "EpicQuiz: You don't have permission to do that."); return true; } } } } return false; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static List sortByValue(final Map m) { List keys = new ArrayList(); keys.addAll(m.keySet()); Collections.sort(keys, new Comparator() { public int compare(Object o1, Object o2) { Object v1 = m.get(o1); Object v2 = m.get(o2); if (v1 == null) { return (v2 == null) ? 0 : 1; } else if (v1 instanceof Comparable) { return ((Comparable) v1).compareTo(v2); } else { return 0; } } }); return keys; } }
true
66945f11b75870ce4a3100a045c5b341de549aca
Java
paulxi/LeetCodeJava
/src/main/java/com/leetcode/algorithm/easy/intersectionoftwoarrays/Solution.java
UTF-8
548
3.328125
3
[ "MIT" ]
permissive
package com.leetcode.algorithm.easy.intersectionoftwoarrays; import java.util.HashSet; class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashSet<Integer> set = new HashSet<>(); HashSet<Integer> result = new HashSet<>(); for (int num : nums1) { set.add(num); } for (int num: nums2) { if (set.contains(num)) { result.add(num); } } int[] ans = new int[result.size()]; int index = 0; for (int num: result) { ans[index++] = num; } return ans; } }
true
669776b5b57944a42d94805a097c0e565bbd6b32
Java
alexkng97/Employees-Project
/EmployeeProject/src/main/java/org/sparta/alex/controller/ThreadManager.java
UTF-8
2,235
3.046875
3
[]
no_license
package org.sparta.alex.controller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.sparta.alex.model.EmployeeDTO; import org.sparta.alex.model.EmployeeThread; import java.util.ArrayList; public class ThreadManager { private Thread[] employeeThreads; private int size; private ArrayList<ArrayList<EmployeeDTO>> splitList; private ArrayList<EmployeeDTO> employeeList; static Logger logger = LogManager.getLogger(ThreadManager.class); public ThreadManager(ArrayList<EmployeeDTO> employeeList, int size){ this.size = size; this.employeeList = employeeList; splitList = new ArrayList<>(size); } public void splitEmployeeList(){ int startIndexOfSplit = 0; int interval = employeeList.size() / size; for(int i = 0; i < size ; i ++){ ArrayList<EmployeeDTO> splitToAdd =new ArrayList<>(employeeList.subList(startIndexOfSplit, startIndexOfSplit + interval)); splitList.add(splitToAdd); startIndexOfSplit += interval; } int leftOverRecords = employeeList.size() - (interval * size); if(leftOverRecords > 0){ for(int i = employeeList.size() - leftOverRecords; i < employeeList.size();i++) { splitList.get(0).add(employeeList.get(i)); } } } public void initAndRunThreads(){ logger.info("Creating " + size + " threads"); try { employeeThreads = new Thread[size]; long start = System.currentTimeMillis(); for(int i = 0 ; i < employeeThreads.length; i++){ employeeThreads[i] = new Thread( new EmployeeThread(splitList.get(i))); employeeThreads[i].start(); } for(int i = 0 ; i < employeeThreads.length; i++){ employeeThreads[i].join(); } System.out.println("Time taken for threads to run: " + (System.currentTimeMillis() - start) + " ms"); logger.info("Time taken for threads to run: " + (System.currentTimeMillis() - start) + " ms"); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
e55824e777aaae73c28f3df8bac8804aadad4179
Java
qonfi/AndroidPermissionRequester
/PermissionRequester.java
UTF-8
2,787
2.59375
3
[]
no_license
package com.example.baker.permissiontest; import android.app.Activity; import android.os.Build; import android.support.v4.app.ActivityCompat; import android.support.v4.content.PermissionChecker; import android.content.Context; import static android.content.pm.PackageManager.*; import static com.example.baker.permissiontest.PermissionConstantsWrapper.*; /** * Created by Baker on 2017/07/11. */ /** * パーミッションのリクエストを取り扱うクラス。 * 自作の PermissionConstantsWrapper クラスに依存している。 */ public class PermissionRequester { /** * パーミッションの許可を求めるダイアログを表示する。 * Marshmallow 以前のOSであるか、すでに許可されている場合はリクエストしない。 * @param activity * @param permission */ public static void request(Activity activity, Permission permission){ // Marshmallow より昔のバージョンならインストール時にすでに許可されている? if (isMarshmallowOrLater() == false){ return; } // すでに許可されているかどうか調べに行く。 Context context = activity.getApplicationContext(); boolean permitted = isPermitted(context, permission); // すでに許可されている場合。 if (permitted){ return; } // Marshmallow 以降のバージョン && 許可されていない場合、許可を求める。。 String[] permissionValue = new String[]{permission.permissionName}; ActivityCompat.requestPermissions(activity, permissionValue, 1); // 最後の int はonRequestPermissionResult で使うようだが、利用しないならどんな値でもいいのかも } /** * ビルドのバージョン(Build.VERSION.SDK_INT) が Marshmallow 以後のバージョンか調べる。 * @return */ private static boolean isMarshmallowOrLater(){ int detectedVersion = Build.VERSION.SDK_INT; int marshmallowVersion = Build.VERSION_CODES.M; if (detectedVersion < marshmallowVersion){return false;} return true; } /** * パーミッションが許可されているかどうか調べる。 * 自作の PermissionConstantsWrapper クラスに依存している。 * @param context * @param permission * @return */ public static boolean isPermitted(Context context, Permission permission){ int result = PermissionChecker.checkSelfPermission(context, permission.permissionName); if (result == PERMISSION_GRANTED){ return true; } return false; } }
true
87e532c2aaf765d71253e920ee934c2901a4a04a
Java
zheddie/samplecodes
/src_java/zGCtest.java
UTF-8
267
2.25
2
[]
no_license
public class zGCtest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String s = new String("xxxx"); Integer i = new Integer(100); s = s+"yyyyyy"; System.gc(); System.out.println("s="+s); } }
true
a77ea302dddf235d7a3dc2be8d15e173ed93698b
Java
m15581052050/mqttDemo
/src/main/java/com/example/demo/Controller/PublishMessage.java
UTF-8
3,146
2.34375
2
[]
no_license
package com.example.demo.Controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.example.demo.client.Client; import com.example.demo.server.Server; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttTopic; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by pengcheng.du on 2018/10/12. */ @RestController public class PublishMessage { private static String HOST = "tcp://0.0.0.0:61613"; public static MqttClient client; public static final String SERVER_URL = "tcp://0.0.0.0:61613"; //推送消息 @RequestMapping(value = "mqtt/publishMessageOnTopic/{topic}",method = RequestMethod.POST) public Map<String,Object> publishMessageOnTopic( @PathVariable(value = "topic") String topic, @RequestBody String message) throws Exception { Map<String,Object> map = new HashMap<>(); JSONObject jsonObject = (JSONObject) JSONObject.parse(message); String mess = (String) jsonObject.get("message"); MqttMessage mqttMessage = new MqttMessage(); mqttMessage.setPayload(mess.getBytes()); mqttMessage.setQos(2); mqttMessage.setRetained(true); if (this.findIndex(topic) == -1) { map.put("data","no topic"); return map; } Server server = new Server(); server.connect(topic); MqttTopic mqttTopic1 = server.mqttTopic1; Server.publish(mqttTopic1,mqttMessage); map.put("data","已发送"); return map; } public int findIndex(String topic) throws Exception{ Server server = new Server(); final List<String> topicList = server.getTOPIC(); int Idnex = 0; for (String topic1: topicList) { if (topic.equals(topic1)) { break; } Idnex++; } if (Idnex==topicList.size()) { return -1; } else { return Idnex; } } private MqttClient getMqttClient(String clientId) throws MqttException { if (client != null && clientId.equals(client.getClientId())) { return client; } return new MqttClient(HOST, clientId); } //创建主题 @RequestMapping(value = "mqtt/createNewTopic/{topic}/{clientId}",method = RequestMethod.POST) public Map<String,Object> createNewTopic(@PathVariable(value = "topic") String topic , @PathVariable(value = "clientId") String clientId){ System.out.println("topic:"+topic+",clientId"+clientId); try{ Server server = new Server(topic,clientId); //server.connect(topic); MqttTopic topic1 = server.getMqttClient().getTopic(""); System.out.println("topic1:"+topic1); } catch (Exception e){ System.out.println(e.toString()); } return null; } }
true
42e3b2c8a0469d63f64b01e40696819a0ec3ca97
Java
xujie01/DigitalShop
/digital-fp/src/com/digital/dao/impl/UserInfoDAOImpl.java
GB18030
961
2.34375
2
[ "MIT" ]
permissive
package com.digital.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; import com.digital.dao.UserInfoDAO; import com.digital.entity.UserInfo; public class UserInfoDAOImpl implements UserInfoDAO { SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public List<UserInfo> search(UserInfo cond) { List<UserInfo> uiList = null; // session Session session = sessionFactory.getCurrentSession(); // Criteria Criteria c = session.createCriteria(UserInfo.class); // ʹExampleഴʾ Example example = Example.create(cond); // ΪCriteriaָʾexampleΪѯ c.add(example); // ִвѯ uiList = c.list(); // ؽ return uiList; } }
true
c5523abebd5425d9739e069a626eb67073ea8fc4
Java
yeonsu100/CodingTest
/JavaCollection/src/dynamic/UniquePath02.java
UTF-8
495
3.296875
3
[]
no_license
package dynamic; public class UniquePath02 { // Dynamic Programming public static void main(String[] args) { int m=7, n=3; System.out.println(uniquePaths(m,n)); } public static int uniquePaths(int m, int n) { Integer[][] map=new Integer[m][n]; for(int i=0; i<m; i++) { map[i][0]=1; } for(int i=0; i<n; i++) { map[0][i]=1; } for(int i=1; i<m; i++) { for(int j=1; j<n; j++) { map[i][j]=map[i][j-1]+map[i-1][j]; } } return map[m-1][n-1]; } }
true
19428494b9ef59e4b9ce31939bf477fe50f4a47a
Java
cckmit/OCS
/oct-app/oct-web-commons/src/test/java/eu/europa/ec/eci/oct/webcommons/services/translations/TranslationServiceImplTest.java
UTF-8
1,639
2.265625
2
[]
no_license
package eu.europa.ec.eci.oct.webcommons.services.translations; import org.junit.Test; import eu.europa.ec.eci.oct.entities.system.Language; import eu.europa.ec.eci.oct.webcommons.services.commons.ServicesTest; import eu.europa.ec.eci.oct.webcommons.services.exceptions.OCTException; import eu.europa.ec.eci.oct.webcommons.services.exceptions.TranslationException; public class TranslationServiceImplTest extends ServicesTest { @Test public void testRetrieveTranslation_OK() throws OCTException, TranslationException { Language en = systemManager.getLanguageByCode("en"); String translation = translationService.getTranslation("public.en.title", en); assertEquals(translation, "Title of something"); Language fr = systemManager.getLanguageByCode("fr"); translation = translationService.getTranslation("public.fr.title", fr); assertEquals(translation, "le title de la chanson"); } @Test public void testRetrieveTranslation_noMatchingLang() throws OCTException, TranslationException { Language it = systemManager.getLanguageByCode("it"); String translation = translationService.getTranslation("public.en.title", it); assertEquals(translation, "[public.en.title:it]"); } @Test public void testRetrieveTranslation_noMatchingKey() throws OCTException, TranslationException { Language en = systemManager.getLanguageByCode("en"); String translation = translationService.getTranslation("public.blabla", en); assertEquals(translation, "[public.blabla:en]"); } }
true
bc92f042a158ca117caaac52ca66102736502175
Java
Daply/rebus-generator-app
/src/main/java/com/rebusgenerator/entity/Rebus.java
UTF-8
1,414
2.328125
2
[]
no_license
package com.rebusgenerator.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * * @author Daria Pleshchankova * */ @Entity @Table(name = "rebus") public class Rebus implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "rebus_id") private long rebusId; @Column(name = "rebus_word") private String rebusWord; @ElementCollection(fetch = FetchType.EAGER) private List<String> rebusSequence; public Rebus() { super(); } public Rebus(Long rebusId, String rebusWord) { super(); this.rebusId = rebusId; this.rebusWord = rebusWord; } public Long getRebusId() { return rebusId; } public String getRebusWord() { return rebusWord; } public void setRebusWord(String rebusWord) { this.rebusWord = rebusWord; } public List<String> getRebusSequence() { return rebusSequence; } public void setRebusSequence(List<String> rebusSequence) { this.rebusSequence = rebusSequence; } public void setRebusId(long rebusId) { this.rebusId = rebusId; } }
true
09ab8a67c00625a0194a470c50a5f8b478e048f2
Java
luutb/SourceChat
/src/main/java/com/giaynhap/service/UserConversationService.java
UTF-8
340
1.648438
2
[]
no_license
package com.giaynhap.service; import org.springframework.stereotype.Service; import java.time.LocalDateTime; @Service public interface UserConversationService { public void updateKey(String conversationUuid,String userUuid,String key); public void updateLastSeen(String conversationUuid, String userUuid, LocalDateTime time); }
true
f80fdbfd4f55fa259f22904afe2941341c70d17e
Java
llac78/HeroesAPI
/src/main/java/com/llac/model/Hero.java
UTF-8
978
2.296875
2
[]
no_license
package com.llac.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import lombok.Data; @Data @Entity @Table(name = "hero") public class Hero implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String name; @ManyToOne @JoinColumn(name = "company_id") private Company company; @OneToOne @JoinColumn(name = "file_id") private FileDB file; public Hero() { } public Hero(String name, Company company, FileDB file) { this.name = name; this.company = company; this.file = file; this.file.setHero(this); } }
true
ad86b6fb7017f349358b892880099445b4298bc3
Java
deenliu/AndroidInstantMsg
/server/Connector.java
UTF-8
12,275
2.875
3
[]
no_license
import java.sql.*; import java.io.*; import java.util.*; import java.util.Calendar; public class Connector { public static final String SUCCESSFUL = "1"; public static final String FAILED = "0"; public static final String SIGN_UP_USERNAME_CRASHED = "2"; public static final String ADD_NEW_USERNAME_NOT_FOUND = "2"; public static final String USER_APPROVED = "1"; String dburl; // Connection to the database. Kept open between calls. Connection con; public boolean isConnected; // Constructors public Connector(String url) { dburl = url; isConnected = false; } public Connector() { this("jdbc:mysql://mydb.ics.purdue.edu:3306/chen932"); } public boolean Connect() { if (isConnected) return true; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(dburl, "chen932", "1234"); isConnected = true; } catch (Exception e) { e.printStackTrace(); return false; } return true; } public void Disconnect() { if (!isConnected) return; try { con.close(); isConnected = false; } catch (Exception e) { } } private synchronized ResultSet executeQuery(String query) { Connect(); ResultSet output = null; if (!isConnected) return null; try { Statement stmt = con.createStatement(); output = stmt.executeQuery(query); } catch (Exception e) { output = null; } return output; } private synchronized boolean execute(String query) { Connect(); boolean output = true; if (!isConnected) return false; try { Statement stmt = con.createStatement(); stmt.execute(query); } catch (Exception e) { e.printStackTrace(); output = false; } Disconnect(); return output; } private String EscapeString(String input) { String output = ""; for (int i = 0; i < input.length(); i++) { int charvalue = (int) input.charAt(i); if ((charvalue >= 48 && charvalue <= 57) || (charvalue >= 65 && charvalue <= 90) || (charvalue >= 97 && charvalue <= 122)) { output += input.charAt(i); } else { output += "#" + String.valueOf(charvalue) + "#"; } } return output; } private String UnescapeString(String input) { if (input == null) return ""; String output = ""; boolean converting = false; int charvalue = 0; for (int i = 0; i < input.length(); i++) { char curchar = input.charAt(i); if (!converting) { // looking at normal if (curchar == '#') { converting = true; continue; } output += curchar; } else { if (curchar == '#') { output += (char) charvalue; charvalue = 0; converting = false; continue; } charvalue *= 10; charvalue += Character.getNumericValue(curchar); } } return output; } private String ResultSetToString(ResultSet rs) { String output = ""; if (rs == null) { // TODO Disconnect(); return ""; } try { boolean first = true; while (rs.next()) { if (!first) { output = output + ":;:"; } int cols = rs.getMetaData().getColumnCount(); for (int i = 1; i <= cols; i++) { if (i != 1) output = output + ":;:"; output = output + UnescapeString(rs.getString(i)); } first = false; } } catch (SQLException e) { output = ""; e.printStackTrace(); } // TODO Disconnect(); return output; } /* execute */ public String GetUser(String user_ID){ user_ID = EscapeString(user_ID); String query = "SELECT * FROM user WHERE user_ID='"+user_ID+"'"; return ResultSetToString(executeQuery(query)); } public boolean AddUser(String user_ID, String password, String first_name, String last_name, String phone){ user_ID = EscapeString(user_ID); password = EscapeString(password); first_name = EscapeString(first_name); last_name = EscapeString(last_name); phone = EscapeString(phone); String query = "INSERT INTO user (user_ID,password,first_name,last_name, phone, address) VALUES ('" + user_ID+ "','" + password + "','" + first_name + "','"+ last_name + "','" +phone + "','fdfd');"; //String query = "INSERT INTO user (user_ID, password,first_name,last_name) VALUES ('LOGG','123','dd','sdfd');"; //return true; System.out.println("query:"+query); return execute(query); } public boolean CreateGroup(String grouptitle, String leader_ID, String member_list){ leader_ID = EscapeString(leader_ID); String query = "INSERT INTO groupN (group_ID, team_leader_ID, team_member_list, timestamp, group_title) VALUES (null,'" + leader_ID+ "','" + member_list + "', NOW() ,'" + grouptitle + "');"; System.out.println("query:"+query); return execute(query); } public String isValidLogin(String userName, String password, String ipaddr){ String cc=authenticateUser(userName, password, ipaddr); if(cc.length()<=0) { return ""; } userName = EscapeString(userName); password = EscapeString(password); String sqlCheck = "select id from users where username = '" + userName+"' AND password = '"+password+"' limit 1;"; String user_ID = ResultSetToString(executeQuery(sqlCheck)); String sql = "select u.Id, u.username, (NOW()-u.authenticationTime) as authenticateTimeDifference, u.IP,f.providerId, f.requestId, f.status, u.port from friends f left join users u on u.Id = if ( f.providerId = "+user_ID+", f.requestId, f.providerId ) where (f.providerId = "+user_ID+" and f.status= 1 ) or f.requestId = "+user_ID+"; "; String sqlmessage = "SELECT m.id, m.fromuid, m.touid, m.sentdt, m.read, m.readdt, m.messagetext, u.username from messages m left join users u on u.Id = m.fromuid WHERE `touid` = "+user_ID+" AND `read` = 0 LIMIT 0, 30 ;"; System.out.println("output: \n" + sql); String output1 = ResultSetToString(executeQuery(sql)); String output2 = ResultSetToString(executeQuery(sqlmessage)); String out = ""; String friendName, status, ip, id, port; out += "<data>"; out += "<user userKey='" +user_ID+ "' />"; String[] parts1 = output1.split(":;:"); int i = 0; for(i = 0; i < parts1.length/8; i++){ status = "offline"; friendName = parts1[i*8+1]; status = parts1[i*8+6]; if( !status.equals("1")){ status = "unApproved"; }else{ status = "offline"; } ip = parts1[i*8+3]; id = parts1[i*8]; port = parts1[i*8+7]; out += "<friend username = '"+ friendName+"' status='"+status+"' IP='"+ip+"' userKey = '"+id+"' port='"+port+"'/>"; } String uName, sendt, messagetxt; String[] parts2 = output2.split(":;:"); for(i = 0; i < parts2.length/8; i++){ uName = parts2[i*8+7]; sendt = parts2[i*8+3]; messagetxt = parts2[i*8+6]; out += "<meesage from='"+uName+ "'sendt='"+sendt+"' text='"+messagetxt+ "' />"; } // need to update System.out.println(out); //String result = ResultSetToString(executeQuery(sql)); return out; } public boolean sendMessage(String fromUser, String password ,String message, String toUser, String ipaddr){ String cc=authenticateUser(fromUser, password, ipaddr); if(cc.length()<=0) { return false; } String sqlto = " select Id from users where username = '" + toUser + "' limit 1 ;" ; if(execute(sqlto)){ String sql22 = "INSERT INTO messages (fromuid, touid, sentdt, messagetext) VALUES ("+fromUser+", "+toUser+", NOW(), '"+message+"');"; //DATE("Y-m-d H:i") return execute(sql22); } return false; } public boolean SignUpUser(String email, String UserName, String password, String ipaddr){ //String cc=authenticateUser(UserName, password, ipaddr); String sqlCheck = "select id from users where username = '" +UserName+"' limit 1;"; if(execute(sqlCheck)){ String sql = "insert into users (username, password, email) values ('"+UserName+"','"+password+"','"+email+"');"; authenticateUser(UserName, password, ipaddr); return execute(sql); } return false; } public boolean addNewFriend(String userName, String password , String friendUserName, String ipaddr){ String cc=authenticateUser(userName, password, ipaddr); if(cc.length()<=0) { return false; } String sqlCheck = "select id from users where username = '" +userName+"' and password = '" +password+"' limit 1;"; if(execute(sqlCheck)){ String sqlCheckAg = "select id from users where username = '"+ friendUserName+ "' limit 1;"; if(execute(sqlCheckAg)){ String userID = ResultSetToString(executeQuery("select id from users where username = '" +userName+"' limit 1;")); String requestID = ResultSetToString(executeQuery("select id from users where username = '" +friendUserName+"' limit 1;")); String sql = "insert into friends (providerID, requestId, status) values (" + userID + "," + requestID+", " + 0 +" );"; return execute(sql); } } return false; } public boolean reponseOfFriendReqs(String userName, String password, String approvedName, String discardName, String ipaddr){ String cc=authenticateUser(userName, password, ipaddr); if(cc.length()<=0) { return false; } String sqlCheck = "select id from users where username = '" +userName+"' and password = '" +password+"' limit 1;"; String friendUserName = ""; int approveORdiscard = 1; String sql; if(approvedName.equals("none")) { friendUserName = discardName; approveORdiscard = 0;} if(discardName.equals("none")) { friendUserName = approvedName; approveORdiscard = 1;} if(execute(sqlCheck)){ String sqlCheckAg = "select id from users where username = '"+ friendUserName+ "' limit 1;"; if(execute(sqlCheckAg)){ String userID = ResultSetToString(executeQuery("select id from users where username = '" +userName+"' limit 1;")); String requestID = ResultSetToString(executeQuery("select id from users where username = '" +friendUserName+"' limit 1;")); sql = "update friends set status = " + approveORdiscard + " where requestID = "+userID+" AND providerId = " +requestID+";"; return execute(sql); } } return false; } public boolean DeleteFriendList(String user_ID, String target){ user_ID = EscapeString(user_ID); String query = "SELECT contact_list from user where user_ID ='"+user_ID+"';"; String output = ResultSetToString(executeQuery(query)); String []temp; temp = output.split(":\\*:"); int t=-1; for(int i=0;i<temp.length;i++){ if(temp[i].equals(target)){ t=i; break; } } if(t==-1){ return true; } for(int i=t;i<temp.length-1;i++){ temp[i]=temp[i+1]; } boolean first=false; String newlist=""; for(int i=0;i<temp.length-1;i++){ if(first){ newlist=newlist+":\\*:"; } newlist=newlist+temp[i]; first=true; } query = "UPDATE user set contact_list = '" + newlist + "' where user_ID = '" + user_ID + "';"; System.out.println("query:"+query); return execute(query); } public boolean AddFriend(String user_ID, String target_ID){ user_ID = EscapeString(user_ID); String query = "SELECT user_ID from user where user_ID ='"+target_ID+"';"; if(ResultSetToString(executeQuery(query)).length()>1){ query = "SELECT contact_list from user where user_ID ='"+user_ID+"';"; String list=ResultSetToString(executeQuery(query)); list=list+":\\*:"+target_ID; query = "UPDATE user set contact_list = '" + list + "' where user_ID = '" + user_ID + "';"; return execute(query); } else{ return false; } } public String authenticateUser(String username, String password, String ipaddr) { String query="select * from users where username = '" + username + "' and password = '" +password +"' limit 1;"; String output = ResultSetToString(executeQuery(query)); //System.out.println(output); String [] temp; temp = output.split(":;:"); ipaddr=getAddr(ipaddr); if(output.length()>0) { query="update users set authenticationTime = NOW(), IP = '"+ipaddr+"' ,port = 15145 where Id = "+temp[0]+" limit 1"; if(execute(query)) { System.out.println("Update Successfully"); } else { System.out.println("failed to update"); } } return temp[0]; } private String getAddr(String addr) { //System.out.println(addr); String output=addr.subSequence(1, addr.lastIndexOf(":")).toString(); //System.out.println("******"+addr); return output; } public static void main(String[] args) { Connector c = new Connector(); c.Connect(); } }
true
384c587148e3c6ef8032570d29858cd3b3e5705b
Java
moutainhigh/jkzx1
/auth-service/src/main/java/tech/tongyu/bct/auth/service/intel/DepartmentService.java
UTF-8
1,222
1.921875
2
[]
no_license
package tech.tongyu.bct.auth.service.intel; import tech.tongyu.bct.auth.dto.CompanyInfo; import tech.tongyu.bct.auth.dto.Department; public interface DepartmentService { /*------------------------ department related api --------------------------*/ Department authDepartmentCreate(String departmentName, String departmentType, String description, String parentId, Number sort); Department authDepartmentRemove(String departmentId); Department authDepartmentModify(String departmentId, String departmentName, String departmentType , String description); Department authDepartmentMove(String departmentId, String parentId); Department authDepartmentGet(String departmentId); Department authAllDepartmentGet(); /*------------------------ department related api --------------------------*/ /*------------------------ company related api --------------------------*/ CompanyInfo authCompanyGet(); CompanyInfo authCompanyCreate(String companyName, String companyType, String unifiedSocialCreditCode , String legalPerson, String contactEmail, String description); /*------------------------ company related api --------------------------*/ }
true
5021cf8b98ea2133a79329e22ae6298fc641754b
Java
zjclugger/JLibrary
/oa/src/main/java/com/metashare/oa/ui/OABaseFragment.java
UTF-8
673
1.773438
2
[ "Apache-2.0" ]
permissive
package com.zjclugger.oa.ui; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.lifecycle.ViewModelProviders; import com.zjclugger.lib.base.BaseFragment; /** * @title <br> * Created by King.Zi on 2020/1/2.<br> * Copyright (c) 2020 zjclugger.com */ public abstract class OABaseFragment extends BaseFragment { protected OAViewModel mViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mViewModel = ViewModelProviders.of(getActivity()).get(OAViewModel.class); } @Override public boolean doBackPress() { return false; } }
true
55635fbb77968f63a55b20c52928059f3240a8e9
Java
ingvaras/DDD-BackEnd
/src/main/java/com/ddd/Shipment/mybatis/model/ShipmentEvent.java
UTF-8
4,812
2.265625
2
[]
no_license
package com.ddd.Shipment.mybatis.model; public class ShipmentEvent { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column PUBLIC.SHIPMENTEVENT.ID * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ private Integer id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column PUBLIC.SHIPMENTEVENT.ORDER_STATE * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ private String orderState; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column PUBLIC.SHIPMENTEVENT.CITY * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ private String city; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column PUBLIC.SHIPMENTEVENT.DATE * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ private String date; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column PUBLIC.SHIPMENTEVENT.ORDER_ID * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ private Integer orderId; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PUBLIC.SHIPMENTEVENT.ID * * @return the value of PUBLIC.SHIPMENTEVENT.ID * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PUBLIC.SHIPMENTEVENT.ID * * @param id the value for PUBLIC.SHIPMENTEVENT.ID * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PUBLIC.SHIPMENTEVENT.ORDER_STATE * * @return the value of PUBLIC.SHIPMENTEVENT.ORDER_STATE * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public String getOrderState() { return orderState; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PUBLIC.SHIPMENTEVENT.ORDER_STATE * * @param orderState the value for PUBLIC.SHIPMENTEVENT.ORDER_STATE * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public void setOrderState(String orderState) { this.orderState = orderState; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PUBLIC.SHIPMENTEVENT.CITY * * @return the value of PUBLIC.SHIPMENTEVENT.CITY * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public String getCity() { return city; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PUBLIC.SHIPMENTEVENT.CITY * * @param city the value for PUBLIC.SHIPMENTEVENT.CITY * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public void setCity(String city) { this.city = city; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PUBLIC.SHIPMENTEVENT.DATE * * @return the value of PUBLIC.SHIPMENTEVENT.DATE * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public String getDate() { return date; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PUBLIC.SHIPMENTEVENT.DATE * * @param date the value for PUBLIC.SHIPMENTEVENT.DATE * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public void setDate(String date) { this.date = date; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PUBLIC.SHIPMENTEVENT.ORDER_ID * * @return the value of PUBLIC.SHIPMENTEVENT.ORDER_ID * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public Integer getOrderId() { return orderId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PUBLIC.SHIPMENTEVENT.ORDER_ID * * @param orderId the value for PUBLIC.SHIPMENTEVENT.ORDER_ID * * @mbg.generated Sat May 08 13:31:26 EEST 2021 */ public void setOrderId(Integer orderId) { this.orderId = orderId; } }
true
b5a9760a0c84cb676d6f118c45e90eeb6e7b4a81
Java
Nansy-S/UserManagementApp
/src/main/java/com/prokopovich/usermanagementapp/enumeration/UserRole.java
UTF-8
806
3
3
[]
no_license
package com.prokopovich.usermanagementapp.enumeration; import java.util.ArrayList; import java.util.List; public enum UserRole { ROLE_ADMIN("ADMIN"), ROLE_USER("USER"); private final String title; UserRole(String title) { this.title = title; } public String getTitle() { return title; } public static UserRole fromString(String text) { for (UserRole b : UserRole.values()) { if (b.title.equals(text)) { return b; } } return null; } public static List<String> getAllTitle() { List<String> roleTitleList = new ArrayList<>(); for(UserRole value : UserRole.values()) { roleTitleList.add(value.getTitle()); } return roleTitleList; } }
true
07c91829fec7502d443578c7a682aa455324f72a
Java
RemigiuszDudek/flink-playground
/src/test/java/prv/dudekre/FlinkTest.java
UTF-8
1,525
2.25
2
[]
no_license
package prv.dudekre; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.serialization.TypeInformationSerializationSchema; import org.apache.flink.api.java.typeutils.GenericTypeInfo; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer; import org.junit.Test; import prv.dudekre.flink.exception.ExceptionEvent; import prv.dudekre.flink.util.ListSource; import java.util.Arrays; import java.util.List; import java.util.UUID; import static prv.dudekre.flink.exception.ExceptionState.OPENED; public class FlinkTest { private StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); @Test public void twoSubsequentMessagesForTheSameException() throws Exception { String id = UUID.randomUUID().toString(); sendEvents( new ExceptionEvent("1", OPENED) ); System.out.println(id); env.execute(); } private void sendEvents(ExceptionEvent... exceptionEvents) { List<ExceptionEvent> events = Arrays.asList(exceptionEvents); // Collections.reverse(events); env.addSource(new ListSource(events)) .addSink(new FlinkKafkaProducer<>( "localhost:9092", "my-test-topic", new TypeInformationSerializationSchema<>(new GenericTypeInfo<>(ExceptionEvent.class), new ExecutionConfig()))); } }
true
119ed7d4003a0ac7d288d085fac7870f19a5c0d0
Java
zhangyiweizyw/searchForLovedOnes
/SearchForLovedOnes/app/src/main/java/com/example/administrator/searchforlovedones/Idv_SerachFamily.java
UTF-8
3,477
1.945313
2
[]
no_license
package com.example.administrator.searchforlovedones; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.google.gson.Gson; import com.loper7.layout.TitleBar; public class Idv_SerachFamily extends Activity { private TextView l_name;//失踪者姓名 private TextView l_sex;//失踪者性别 private TextView l_borndate;//失踪者出生日期 private TextView l_phone;//联系方式 private TextView l_email;//邮箱 private TextView lheight;//失踪者失踪时大致身高 private TextView l_missdate;//失踪日期 private TextView isBlood;//是否采血 private TextView isReport;//是否报案 private TextView l_native;//失踪人籍贯 private TextView l_missaddr;//失踪地点 private TextView l_fearture;//失踪人特征描述 private TextView l_process;//失踪经过 private TextView l_family;//家庭背景及其线索资料 private TextView t_familyaddr;//目标家庭地址 private TextView t_relationfamily;//与目标家庭联系 private TextView t_describefamily;//目标家庭描述 private SearchFamilyBean Spb; private TitleBar bar; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.idv_serachfamily); bar = findViewById(R.id.bar); bar.setBackImageResource(R.drawable.back); bar.setUseRipple(true); l_name=findViewById(R.id.l_name); l_sex=findViewById(R.id.l_sex); l_borndate=findViewById(R.id.l_borndate); l_phone=findViewById(R.id.l_phone); l_email =findViewById(R.id. l_email); lheight=findViewById(R.id. lheight); l_missdate=findViewById(R.id. l_missdate); isBlood=findViewById(R.id.l_isblood); isReport=findViewById(R.id. l_isreport ); l_native=findViewById(R.id. l_native); l_missaddr=findViewById(R.id. l_missaddr); l_fearture =findViewById(R.id.l_feature); l_process =findViewById(R.id. l_process); l_family=findViewById(R.id. l_family); t_familyaddr =findViewById(R.id. t_familyaddr); t_relationfamily =findViewById(R.id. t_relationfamily); t_describefamily=findViewById(R.id. t_describefamily); String str = getIntent().getStringExtra("2"); Spb = new Gson().fromJson(str, SearchFamilyBean.class); l_name.setText(Spb.getL_name()); l_sex.setText(Spb.getL_sex()); l_borndate.setText(Spb.getL_borndate()); l_phone.setText(Spb.getL_phone()); l_email .setText(Spb.getL_email()); lheight.setText(Spb.getLheight()); l_missdate.setText(Spb.getL_missdate()); isBlood.setText(Spb.getIsBlood()); isReport.setText(Spb.getIsReport()); l_native.setText(Spb.getL_native()); l_missaddr.setText(Spb.getL_missaddr()); l_fearture .setText(Spb.getL_fearture()); l_process .setText(Spb.getL_process()); l_family.setText(Spb.getL_family()); t_familyaddr .setText(Spb.getT_familyaddr()); t_relationfamily .setText(Spb.getT_relationfamily()); t_describefamily.setText(Spb.getT_describefamily()); } }
true
d491ee8e06999c32bd7dcb797090cf5cbf363d05
Java
fujirah/helloworld
/fujairah/src/main/java/com/woom/baseTool/catcher/Catcher.java
UTF-8
188
1.78125
2
[]
no_license
package com.woom.baseTool.catcher; import com.woom.baseTool.resource.Resource; /** * Created by yuhao.zx on 14-9-11. */ public interface Catcher<T> { T catchContent(String url); }
true
bf47fe56b33d14542ae7933ab1a005762eacb51a
Java
brayJava/bray
/common/src/main/java/com/whiteplanet/config/JMessageType.java
UTF-8
1,133
2.328125
2
[]
no_license
package com.whiteplanet.config; /** * @author:wuzhiyuan * @description: IM相关类型常量 * @date: Created in 10:05 2018/6/21 * @modified By: */ public class JMessageType { /** * 用户类型:user */ public static final String USER_TYPE_USER = "user"; /** * 用户类型:admin */ public static final String USER_TYPE_ADMIN = "admin"; /** * 用户类型:single */ public static final String MESSAGE_TYPE_SINGLE = "single"; /** * 用户类型:group */ public static final String MESSAGE_TYPE_GROUP = "group"; /** * 用户类型:group */ public static final String MESSAGE_CONTENT = "你好,我是C医O :大米。\n" + "欢迎关注我诊所!\n" + "你可以预约我线下接诊,或让我帮你转诊对症的医生;\n" + "请尽快完善你的患者档案,以便我能了解你的详细情况。\n" + "本平台不做任何咨询,需要转接诊请发送约诊单!\n" + "由于医院工作比较繁忙,如未能及时回复,尽请谅解!"; }
true
544f30d47dafdf14baaef745eb9e0a2adbc1e433
Java
guray/javarest
/src/main/java/com/javahelps/restservice/entity/Hastalar.java
UTF-8
1,968
2.171875
2
[]
no_license
package com.javahelps.restservice.entity; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Hastalar { @Id private String kimlikno; private String adsoyad; private String hastano; private String dtarih; private String dyer; private String meslek; private String kangrubu; private String ceptel; private String adres; public String getKimlikno() { return kimlikno; } public void setKimlikno(String kimlikno) { this.kimlikno = kimlikno; } public String getAdsoyad() { return adsoyad; } public void setAdsoyad(String adsoyad) { this.adsoyad = adsoyad; } public String getHastano() { return hastano; } public void setHastano(String hastano) { this.hastano = hastano; } public String getDtarih() { return dtarih; } public void setDtarih(String dtarih) { this.dtarih = dtarih; } public String getDyer() { return dyer; } public void setDyer(String dyer) { this.dyer = dyer; } public String getMeslek() { return meslek; } public void setMeslek(String meslek) { this.meslek = meslek; } public String getKangrubu() { return kangrubu; } public void setKangrubu(String kangrubu) { this.kangrubu = kangrubu; } public String getCeptel() { return ceptel; } public void setCeptel(String ceptel) { this.ceptel = ceptel; } public String getAdres() { return adres; } public void setAdres(String adres) { this.adres = adres; } @Override public String toString() { return "Hastalar{" + "kimlikno='" + kimlikno + '\'' + ", adsoyad='" + adsoyad + '\'' + ", hastano='" + hastano + '\'' + ", dtarih='" + dtarih + '\'' + ", dyer='" + dyer + '\'' + ", meslek='" + meslek + '\'' + ", kangrubu='" + kangrubu + '\'' + ", ceptel='" + ceptel + '\'' + ", adres='" + adres + '\''+ '}'; } }
true
6e0671b3c74ee899e87016846d68f8aef3204893
Java
tianlong513/NGOA
/src/main/java/org/oa/service/impl/ContractServiceImpl.java
UTF-8
2,032
2.15625
2
[]
no_license
package org.oa.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.oa.bean.ResponseBean; import org.oa.entity.TbContract; import org.oa.mapper.ContractMapper; import org.oa.service.ContractService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @program: Spring-Boot-Shiro-master * @description: * @author: tianlong * @create: 2019-01-10 15:14 **/ @Service public class ContractServiceImpl implements ContractService { @Autowired private ContractMapper contractMapper; @Override public Object getContract() { QueryWrapper<TbContract> wrapper = new QueryWrapper<>(); wrapper.eq("`del`", 1); IPage<TbContract> iPage = new Page<>(); IPage<TbContract> contractIPage = contractMapper.selectPage(iPage, wrapper); return new ResponseBean(200, "success", iPage); } @Override public Object removeContra(Integer id) { try { int res = contractMapper.removeContra(id); if (res < 1) { return new ResponseBean(500, "删除失败", null); } } catch (Exception e) { e.printStackTrace(); return new ResponseBean(500, "删除失败,服务器发生错误" + e.getMessage(), null); } return new ResponseBean(200, "success", null); } @Override public Object addContra(TbContract tbContract) { try { int res = contractMapper.addContra(tbContract); if (res < 1) { return new ResponseBean(500, "添加失败", null); } } catch (Exception e) { e.printStackTrace(); return new ResponseBean(500, "添加失败,服务器发生错误" + e.getMessage(), null); } return new ResponseBean(200, "success", null); } }
true
087d9e3b6e44b4317240e4013baf859624163d67
Java
ReikaKalseki/ReactorCraft
/ClientProxy.java
UTF-8
5,387
1.507813
2
[]
no_license
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.ReactorCraft; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import Reika.DragonAPI.DragonOptions; import Reika.DragonAPI.Auxiliary.Trackers.DonatorController; import Reika.DragonAPI.Auxiliary.Trackers.DonatorController.Donator; import Reika.DragonAPI.Auxiliary.Trackers.PatreonController; import Reika.DragonAPI.Auxiliary.Trackers.PlayerSpecificRenderer; import Reika.DragonAPI.Instantiable.Rendering.ItemSpriteSheetRenderer; import Reika.ReactorCraft.Auxiliary.DonatorToroidRender; import Reika.ReactorCraft.Auxiliary.ReactorRenderList; import Reika.ReactorCraft.Entities.EntityFusion; import Reika.ReactorCraft.Entities.EntityNeutron; import Reika.ReactorCraft.Entities.EntityPlasma; import Reika.ReactorCraft.Entities.EntityRadiation; import Reika.ReactorCraft.Entities.RenderFusion; import Reika.ReactorCraft.Entities.RenderNeutron; import Reika.ReactorCraft.Entities.RenderPlasma; import Reika.ReactorCraft.Entities.RenderRadiation; import Reika.ReactorCraft.Registry.ReactorItems; import Reika.ReactorCraft.Registry.ReactorTiles; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.client.registry.RenderingRegistry; public class ClientProxy extends CommonProxy { public static final ItemSpriteSheetRenderer[] items = { new ItemSpriteSheetRenderer(ReactorCraft.instance, ReactorCraft.class, "Textures/Items/items1.png"), }; private static final ReactorItemRenderer reactor = new ReactorItemRenderer(); public static SteamLineRenderer line; public static TritiumLampRenderer lamp; private static final HashMap<ReactorItems, String> armorAssets = new HashMap(); @Override public void addArmorRenders() { hazmat = RenderingRegistry.addNewArmourRendererPrefix("hazmat"); addArmorTexture(ReactorItems.HAZBOOTS, "/Reika/ReactorCraft/Textures/Misc/haz_1.png"); addArmorTexture(ReactorItems.HAZHELMET, "/Reika/ReactorCraft/Textures/Misc/haz_1.png"); addArmorTexture(ReactorItems.HAZCHEST, "/Reika/ReactorCraft/Textures/Misc/haz_1.png"); addArmorTexture(ReactorItems.HAZLEGS, "/Reika/ReactorCraft/Textures/Misc/haz_2.png"); } private static void addArmorTexture(ReactorItems item, String tex) { ReactorCraft.logger.log("Adding armor texture for "+item+": "+tex); String[] s = tex.split("/"); String file = s[s.length-1]; String defaultTex = "reactorcraft:textures/models/armor/"+file; armorAssets.put(item, defaultTex); } public static String getArmorTextureAsset(ReactorItems item) { return armorAssets.get(item); } @Override public void registerSounds() { sounds.register(); } @Override public void registerRenderers() { if (DragonOptions.NORENDERS.getState()) { ReactorCraft.logger.log("Disabling all machine renders for FPS and lag profiling."); } else { this.loadModels(); } this.addArmorRenders(); lineRender = RenderingRegistry.getNextAvailableRenderId(); line = new SteamLineRenderer(lineRender); RenderingRegistry.registerBlockHandler(lineRender, line); lampRender = RenderingRegistry.getNextAvailableRenderId(); lamp = new TritiumLampRenderer(lampRender); RenderingRegistry.registerBlockHandler(lampRender, lamp); this.registerSpriteSheets(); RenderingRegistry.registerEntityRenderingHandler(EntityNeutron.class, new RenderNeutron()); RenderingRegistry.registerEntityRenderingHandler(EntityRadiation.class, new RenderRadiation()); RenderingRegistry.registerEntityRenderingHandler(EntityPlasma.class, new RenderPlasma()); RenderingRegistry.registerEntityRenderingHandler(EntityFusion.class, new RenderFusion()); } private void registerSpriteSheets() { for (int i = 0; i < ReactorItems.itemList.length; i++) { if (ReactorItems.itemList[i].getSpriteIndex() > -1) MinecraftForgeClient.registerItemRenderer(ReactorItems.itemList[i].getItemInstance(), items[ReactorItems.itemList[i].getSpriteSheet()]); } } public void loadModels() { for (int i = 0; i < ReactorTiles.TEList.length; i++) { ReactorTiles m = ReactorTiles.TEList[i]; if (m.hasRender() && !m.isPipe()) { ClientRegistry.bindTileEntitySpecialRenderer(m.getTEClass(), ReactorRenderList.instantiateRenderer(m)); } } MinecraftForgeClient.registerItemRenderer(ReactorItems.PLACER.getItemInstance(), reactor); } @Override public World getClientWorld() { return FMLClientHandler.instance().getClient().theWorld; } @Override public void loadDonatorRender() { Collection<Donator> donators = new ArrayList(); donators.addAll(DonatorController.instance.getReikasDonators()); donators.addAll(PatreonController.instance.getModPatrons("Reika")); for (Donator s : donators) { if (s.ingameName != null) PlayerSpecificRenderer.instance.registerRenderer(s.ingameName, DonatorToroidRender.instance); else ReactorCraft.logger.logError("Donator "+s.displayName+" UUID could not be found! Cannot give special render!"); } } }
true
5022d5423214847d32ff72dfccc0aeba527e2c91
Java
WilianPeng/datakit
/src/com/datakit/account/action/LoginAction.java
UTF-8
1,771
2.25
2
[]
no_license
package com.datakit.account.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.springframework.stereotype.Controller; import com.datakit.entity.Account; import com.datakit.service.account.AccountService; import com.opensymphony.xwork2.ActionSupport; /** * * @author wilian * 账户域的Action */ @Controller public class LoginAction extends ActionSupport { private static final long serialVersionUID = 1L; @Resource private AccountService userService; private String username; private String password; /** * 登录操作 * @return */ public String login(){ HttpServletRequest request = ServletActionContext.getRequest(); Account user = userService.findAccountByNameAndPassword(username, password); if (user != null) { request.setAttribute("username", username); return SUCCESS; } else { return ERROR; } } /** * 注册操作 * @return */ public String register() { HttpServletRequest request = ServletActionContext.getRequest(); Account account = new Account(); account.setUserName(username); account.setPassword(password); userService.saveAccount(account); Account user = userService.findAccountByNameAndPassword(username, password); if (user != null) { request.setAttribute("username", username); return SUCCESS; } else { return ERROR; } } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
true
6ae03a4d57b62362c8151b971dbda98f2417431b
Java
Fuizziy/FY_Reputation
/src/fr/fuizziy/reputation/Reputation.java
ISO-8859-1
945
2.171875
2
[]
no_license
package fr.fuizziy.reputation; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import fr.fuizziy.commands.MainCommand; import fr.fuizziy.listeners.Listeners; import net.md_5.bungee.api.ChatColor; public class Reputation extends JavaPlugin { public static Plugin instance; public void onEnable() { getServer().getConsoleSender().sendMessage(String.format(ChatColor.GREEN + "[FY] [%s v.%s] " + ChatColor.BLUE + " activ", getDescription().getName(), getDescription().getVersion())); instance = this; this.getCommand("reputation").setExecutor(new MainCommand(this)); getServer().getPluginManager().registerEvents(new Listeners(), this); } public void onDisable() { getServer().getConsoleSender().sendMessage(String.format(ChatColor.GREEN + "[FY] [%s v.%s] " + ChatColor.RED + " dsactiv", getDescription().getName(), getDescription().getVersion())); } }
true
e1b19495dc3eda1adcfd5e4c1cbb6a8b1606ec8a
Java
pthahnil/simple
/simple-common/src/main/java/com/simple/xrcraft/common/useless/StringLongConverterFactory.java
UTF-8
942
2.65625
3
[]
no_license
package com.simple.xrcraft.common.useless; import lombok.Getter; import java.util.HashMap; import java.util.Map; /** * @description: * @author pthahnil * @date 2021/5/31 11:45 */ public class StringLongConverterFactory { private static final Map<ConverterType, StringLongConverter> converterMap = new HashMap<>(); static { converterMap.put(ConverterType.IP, new IpStringLongConverter()); } public static Long toLong(String target, ConverterType type){ StringLongConverter converter = converterMap.get(type); if(null == converter){ throw new RuntimeException("converter type error"); } return converter.toLong(target); } public static String toStr(Long target, ConverterType type){ StringLongConverter converter = converterMap.get(type); if(null == converter){ throw new RuntimeException("converter type error"); } return converter.toStr(target); } @Getter public enum ConverterType{ IP, ; } }
true
263108454b5acf601016bd3e0405bddd926e93e9
Java
FirstTestOrganizationForLearning/hotel
/b2b_admin/src/main/java/com/fntx/admin/service/impl/BFrequencyLogServiceImpl.java
UTF-8
559
1.515625
2
[]
no_license
package com.fntx.admin.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fntx.admin.service.IBFrequencyLogService; import com.fntx.common.dao.BFrequencyLogMapper; import com.fntx.common.domain.BFrequencyLog; import org.springframework.stereotype.Service; /** * <p> * 分销商接口频次日志表 服务实现类 * </p> * * @author 王俊文 * @since 2019-09-02 */ @Service public class BFrequencyLogServiceImpl extends ServiceImpl<BFrequencyLogMapper, BFrequencyLog> implements IBFrequencyLogService { }
true
7ae64310d492e6c8f3b3ebee453ef99efdb5d4ca
Java
taehyuk0314/bit_etland_sf4
/bit_etland/src/main/java/com/bit_etland/web/supp/Supplier.java
UTF-8
329
1.789063
2
[]
no_license
package com.bit_etland.web.supp; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import lombok.Data; @Component @Data @Lazy public class Supplier { private String supplierID, supplierName ,contactName ,address ,city ,postalCode ,country ,phone; }
true
9078e56d4b9b4fb1d9ef8b589beb85533612f234
Java
Baros2535/eu5-jdbc-practice
/src/test/java/Homework/HomeworkAPI1.java
UTF-8
3,286
2.578125
3
[]
no_license
package Homework; import DAY6_POJO.Spartan; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import utilities.ConfigurationReader; import utilities.ExcelUtil; import java.math.BigDecimal; import java.util.Arrays; import java.util.Locale; import static io.restassured.RestAssured.baseURI; import static io.restassured.RestAssured.given; public class HomeworkAPI1 { @BeforeClass public void beforeClass(){ baseURI= ConfigurationReader.get("spartanBaseURL"); } //Optional homeworks //Homework-1 //1-Create csv file from mackaroo website, which includes name,gender,phone //2-Download excel file //3- using testng data provider and apache poi create data driven posting from spartan //Homework-2 //-Create one mackaroo api for name,gender,phone //send get request to retrieve random info from that api //use those info to send post request to spartan @DataProvider public Object[][] data(){ String projectPath=System.getProperty("user.dir"); String filePath=projectPath+"/src/test/resources/Spartan.xlsx"; System.out.println(filePath); ExcelUtil excelUtil=new ExcelUtil(filePath,"spartans"); String[][] dataArray = excelUtil.getDataArrayWithoutFirstRow(); System.out.println("Array "+Arrays.deepToString(dataArray)); return dataArray; } @Test(dataProvider = "data") public void postWithDataprovider(String name,String gender,String phone){ BigDecimal decimal=new BigDecimal(phone); /* String phoneString=phone.substring(0,phone.indexOf("."))+phone.substring(2,phone.indexOf("E")); System.out.println("phoneString = " + phoneString); if (phoneString.length()!=10){ phoneString=phoneString+"0"; }*/ long decimal2=decimal.longValue(); Spartan spartanEU=new Spartan(); spartanEU.setName(name); spartanEU.setGender(gender); spartanEU.setPhone(decimal2); System.out.println("spartanEU = " + spartanEU); Response response = given() .accept(ContentType.JSON) .and() .contentType(ContentType.JSON) .and() .log().all() .body(spartanEU) .when() .post("/api/spartans"); int idOfSpartan = response.path("data.id"); String nameOfSpartan = response.path("data.name"); String genderOfSpartan = response.path("data.gender"); System.out.println("idOfSpartan = " + idOfSpartan); System.out.println("nameOfSpartan = " + nameOfSpartan); System.out.println("genderOfSpartan = " + genderOfSpartan); given().accept(ContentType.JSON).and().pathParam("id",idOfSpartan) .when().get("/api/spartans/{id}") .then() .statusCode(200); } }
true
305348e6d9f2103030f26910befff7ac06f764f1
Java
Murilovisque/payment-exercise
/payment-api/src/test/java/com/payment/api/BuyerAPITest.java
UTF-8
2,943
2.296875
2
[]
no_license
package com.payment.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.sql.SQLException; import java.util.List; import java.util.Optional; import com.payment.api.exceptions.PaymentException; import com.payment.api.models.Buyer; import com.payment.api.repositories.BuyerRepository; import com.payment.api.repositories.PaymentRepository; import com.payment.api.search.SearchConditions; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class BuyerAPITest { private BuyerAPI buyerAPI; @BeforeClass public static void setup() throws SQLException { TestUtils.deleteAllOfTable(PaymentRepository.TABLE_NAME, BuyerRepository.TABLE_NAME); } @Before public void before() { buyerAPI = new BuyerAPI(TestUtils.getApiClientProvider(), TestUtils.getConnectionProvider()); } @Test public void test1_ShouldFalseWhenBuyerDoesNotExists() throws PaymentException { assertTrue(buyerAPI.getBuyers(TestUtils.QUERY_LIMIT).isEmpty()); } @Test public void test2_ShouldSaveBuyer() throws PaymentException { buyerAPI.save(TestUtils.getBuyerOne()); } @Test public void test3_ShouldBuyer() throws PaymentException { Optional<Buyer> buyer = buyerAPI.getBuyerWithCPF(TestUtils.BUYER_1_CPF); assertTrue(buyer.isPresent()); TestUtils.assertAllFields(TestUtils.getBuyerOne(), buyer.get()); } @Test public void test4_ShouldTrueBuyerByName() throws PaymentException { String partialName = TestUtils.BUYER_1_NAME.substring(0, TestUtils.BUYER_1_NAME.length() / 2); List<Buyer> buyers = buyerAPI.search(new SearchConditions().put(BuyerRepository.COLUMN_NAME, partialName), TestUtils.QUERY_LIMIT); assertEquals(1, buyers.size()); TestUtils.assertAllFields(TestUtils.getBuyerOne(), buyers.get(0)); } @Test public void test4_ShouldTrueBuyerByCPF() throws PaymentException { String partialCPF = TestUtils.BUYER_1_CPF.substring(0, TestUtils.BUYER_1_CPF.length() / 2); List<Buyer> buyers = buyerAPI.search(new SearchConditions().put(BuyerRepository.COLUMN_CPF, partialCPF), TestUtils.QUERY_LIMIT); assertEquals(1, buyers.size()); TestUtils.assertAllFields(TestUtils.getBuyerOne(), buyers.get(0)); } @Test public void test4_ShouldTrueBuyerByEmail() throws PaymentException { String partialEmail = TestUtils.BUYER_1_EMAIL.substring(0, TestUtils.BUYER_1_EMAIL.length() / 2); List<Buyer> buyers = buyerAPI.search(new SearchConditions().put(BuyerRepository.COLUMN_EMAIL, partialEmail), TestUtils.QUERY_LIMIT); assertEquals(1, buyers.size()); TestUtils.assertAllFields(TestUtils.getBuyerOne(), buyers.get(0)); } }
true
9fadfb11737ef534b1fcfb7980dd1ef0eb48fcd4
Java
wesource/springboot-foo-artifact
/src/main/java/se/wesource/fooartifact/controller/CustomerController.java
UTF-8
1,371
2.4375
2
[]
no_license
package se.wesource.fooartifact.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import se.wesource.fooartifact.exception.CustomNotFoundException; import se.wesource.fooartifact.model.Customer; import se.wesource.fooartifact.service.CustomerService; import se.wesource.otherspringbootservice.model.Other; import se.wesource.otherspringbootservice.service.OtherService; @RestController @Slf4j public class CustomerController { @Autowired private CustomerService customerService; @Autowired private OtherService otherService; @RequestMapping(value="/customer/{name}") public Customer findCustomerByName(@PathVariable("name")String name){ Customer cust = customerService.findCustomerByName(name); if(null == cust){ throw new CustomNotFoundException("Not found customer with name is " + name); } return cust; } @RequestMapping(value="/other/{name}") public Other findOther(@PathVariable("name")String name){ log.info("findOther in other! "); Other other = otherService.findOtherByName(name); return other; } }
true
4101894451092007e2181adce041573320456ec5
Java
popovdenys/design-patterns
/src/main/java/po/patterns/postredirectget/galaxy/domain/Galaxy.java
UTF-8
1,178
2.734375
3
[ "Apache-2.0" ]
permissive
/* * File : Galaxy.java * Description : Galaxy bean * * Author : Popov Denys * Created : 01 Feb, 2018 * * Modified : 01 Feb, 2018 * Modified by: Popov Denys * * Last modification : Galaxy object */ package po.patterns.postredirectget.galaxy.domain; public class Galaxy { private int id; private String name; private String type; private String constellation; public Galaxy() { } public Galaxy(int id, String name, String type, String constellation) { super(); this.id = id; this.name = name; this.type = type; this.constellation = constellation; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getConstellation() { return constellation; } public void setConstellation(String constellation) { this.constellation = constellation; } @Override public String toString() { return "Galaxy '" + name + "' of type " + type + " in constellation '" + constellation + "'"; } }
true
1db163c74fbdd33b5b2667e9f247eb0c844a276d
Java
chidocodigo/2018-07-27-desacoplar-logica-controlador
/src/main/java/mx/gob/catalogos/controlador/MunicipioControlador.java
UTF-8
2,158
2.171875
2
[]
no_license
package mx.gob.catalogos.controlador; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import mx.gob.catalogos.servicio.MunicipioServicio; import mx.gob.catalogos.modelo.Municipio; @RestController @RequestMapping("/api") public class MunicipioControlador { @Autowired MunicipioServicio municipios; @GetMapping("/municipios") public List<Municipio> getMunicipios() { return municipios.getMunicipios(); } @GetMapping("/municipios/estado/{estadoId}") public List<Municipio> getMunicipiosByEstadoId(@PathVariable (value = "estadoId") Integer estadoId ) { return municipios.getMunicipiosbyEstadoId(estadoId); } @PostMapping("/municipios/estado/{estadoId}") public Municipio guardarMunicipio(@PathVariable (value = "estadoId") Integer estadoId, @Valid @RequestBody Municipio municipio) { return municipios.guardarMunicipio(municipio, estadoId); } @GetMapping("/municipios/{id}") public Municipio getMunicipioById(@PathVariable(value = "id") Integer municipioId) { return municipios.getMunicipioById(municipioId); } @PutMapping("/municipios/{municipioId}") public Municipio actualizarMunicipio(@PathVariable(value = "municipioId") Integer municipioId, @Valid @RequestBody Municipio nuevoMunicipio) { return municipios.actualizarMunicipio(nuevoMunicipio, municipioId); } @DeleteMapping("/municipios/{id}") public ResponseEntity<?> borrarMunicipio(@PathVariable(value = "id") Integer municipioId) { municipios.borrarMunicipio(municipioId); return ResponseEntity.ok().build(); } }
true
e937e83ac1003ca8c0961a786fbbba02ff28d770
Java
Amirr90/PlayLudo
/app/src/main/java/com/example/playludo/fragments/AddedSuccessfullyFragment.java
UTF-8
1,111
1.75
2
[]
no_license
package com.example.playludo.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.playludo.HomeScreen; import com.example.playludo.R; import com.example.playludo.databinding.FragmentAddedSuccessfullyBinding; import org.jetbrains.annotations.NotNull; public class AddedSuccessfullyFragment extends Fragment { FragmentAddedSuccessfullyBinding binding; @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentAddedSuccessfullyBinding.inflate(getLayoutInflater()); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); binding.btnOk.setOnClickListener(v -> HomeScreen.getInstance().onSupportNavigateUp()); } }
true
489458c2f0f55a5b250dc9a44fbbc43b7562f3bc
Java
fstanchese/reservatorio
/reservatorio/src/main/java/br/com/stanchese/reservatorio/repository/SistemaRepositorio.java
UTF-8
427
1.890625
2
[]
no_license
package br.com.stanchese.reservatorio.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import br.com.stanchese.reservatorio.model.Sistema; public interface SistemaRepositorio extends JpaRepository<Sistema, Long> { @Query("select s from Sistema s order by s.nome") List<Sistema> findAllOrderByNome(); }
true
808e2d04ea888ba7c9208a94153f8d31e34e4c9a
Java
AkankshaNagpal/RecommendationSystemYelp
/src/com/cmpe239/dao/TestClass.java
UTF-8
952
2.34375
2
[]
no_license
package com.cmpe239.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.cmpe239.entities.BusinessEntity; import com.cmpe239.entities.UserEntity; import com.cmpe239.model.Business; import com.cmpe239.util.HibernateUtil; public class TestClass { public static void main(String args[]) { BusinessEntity b = new BusinessEntity(); SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); Query query = session.createSQLQuery( "select Name from businessdetails where BusinessID = :YelpBID") .setParameter("YelpBID", "7EvTeABfqSt0z75huEOqNA"); String name = new String(); if(query.list() != null) { List result = query.list(); if(result !=null && result.size() > 0) { name = (String) result.get(0); } } System.out.println(name); } }
true
b5440a73ffa95d1eb4ac236a84ffc2837b5b3d4a
Java
EastSunrise/oj-java
/src/main/java/cn/wsg/oj/leetcode/problems/offer/Offer36.java
UTF-8
1,500
3.328125
3
[]
no_license
package cn.wsg.oj.leetcode.problems.offer; import cn.wsg.oj.leetcode.problems.base.Solution; /** * 剑指 Offer 36. 二叉搜索树与双向链表 LCOF (MEDIUM) * * @author Kingen * @see <a href="https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/">二叉搜索树与双向链表 * LCOF</a> */ public class Offer36 implements Solution { /** * @see #INORDER */ public Node treeToDoublyList(Node root) { if (root == null) { return null; } Node[] tmp = new Node[2]; inorder(root, tmp); tmp[0].left = tmp[1]; tmp[1].right = tmp[0]; return tmp[0]; } private void inorder(Node node, Node[] tmp) { if (node == null) { return; } inorder(node.left, tmp); if (tmp[0] == null) { // the head node tmp[0] = node; } if (tmp[1] != null) { tmp[1].right = node; node.left = tmp[1]; } tmp[1] = node; inorder(node.right, tmp); } /** * Definition for a Node. */ static class Node { public int val; public Node left; public Node right; public Node() { } public Node(int val) { this.val = val; } public Node(int val, Node left, Node right) { this.val = val; this.left = left; this.right = right; } } }
true
e5ca8c5e20788259f9edad7b1f58ac3ce3324fb9
Java
carnifex1389/job4j_elementary
/src/ru/job4j/array/Machine.java
UTF-8
1,420
3.5625
4
[]
no_license
package ru.job4j.array; import java.util.Arrays; public class Machine { private final int[] COINS = {10, 5, 2, 1}; public int[] changeOnce(int money, int price) { int[] result = new int[100]; int emptyCellPointer = 0; int number = money - price; for (int i = 0; i < COINS.length; i++) { int numberQuantity = number / COINS[i]; int leftover = number % COINS[i]; if (numberQuantity >= 1) { for (int counter = 1; counter <= numberQuantity; counter++) { result[emptyCellPointer] = COINS[i]; emptyCellPointer += 1; } if (leftover != 0) { number = leftover; } else { break; } } } return Arrays.copyOf(result, emptyCellPointer); } public int[] change(int money, int price) { int[] result = new int[100]; byte emptyCellPointer = 0; int delta = money - price; for (byte i = 0; i < COINS.length; i++) { while (delta >= COINS[i]) { result[emptyCellPointer] = COINS[i]; delta -= COINS[i]; emptyCellPointer++; } if (delta == 0) { break; } } return Arrays.copyOf(result, emptyCellPointer); } }
true
95f2ce5b7ffb36a407ec0603ecfa942502ed1b4b
Java
Akers/AkSchedule
/Sources/MySchedule 1.5/src/MyGui/TitlePanel.java
UTF-8
1,037
2.578125
3
[ "Apache-2.0" ]
permissive
package MyGui; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; public class TitlePanel extends JPanel { private static final long serialVersionUID = 2L; private ImageIcon icon_close; private ImageIcon icon_min; JButton close; JButton min; public TitlePanel() { icon_close = new ImageIcon("././images/close.gif"); icon_min = new ImageIcon("././images/min.gif"); close = new JButton(); min = new JButton(); add(close); add(min); } public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setColor(new Color(51,181,255)); g2d.fillRect(0, 0, 435, 22); g.setFont(new Font("dialog",1,13)); g.setColor(Color.BLACK); g.drawString("日程事务管理器 beta 1.5 by Akers", 0, 15); close.setSize(20, 20); close.setLocation(409, 1); close.setIcon(icon_close); min.setSize(20, 20); min.setLocation(385, 1); min.setIcon(icon_min); } }
true
065b7a2fa30f0d4b2c42da8c460cbbe6a3f70ab2
Java
bucky1995/CS_509_DSS
/cs509resources/WordMap/src/shapes/controller/moves/VConnectShape.java
UTF-8
2,011
3.15625
3
[]
no_license
package shapes.controller.moves; import shapes.controller.Move; import shapes.model.*; /** * Needs access to the model to make this happen. * */ public class VConnectShape extends Move { final Shape shape; final Shape target; int oldSelectedX; int oldSelectedY; int releaseX; // where mouse was released (x,y) int releaseY; int targetx; int targety; int lastSelectedY; int lastSelectedX; final Model model; Shape newShape; public VConnectShape(Model model, Shape movedShape, int oldx, int oldy, Shape target, int relx, int rely) { this.model = model; this.shape = movedShape; this.target = target; this.targetx = target.getX(); this.targety = target.getY(); this.releaseX = relx; this.releaseY = rely; this.oldSelectedX = oldx; this.oldSelectedY = oldy; this.lastSelectedX = movedShape.getX(); this.lastSelectedY = movedShape.getY(); } @Override public boolean execute() { Board b = model.getBoard(); // should work regardless of the structure of 'target' and 'shape', which // are both Shapes (but one could be WordShape the other PoemShape) System.out.println(target.getX() + "," + target.getY() + "," + oldSelectedX + "," + oldSelectedY + "," + shape.getX()+ ","+ shape.getY()+ ","+ releaseX+ ","+ releaseY); shape.setLocation(lastSelectedX, lastSelectedY); newShape = target.verticalConnect(shape, releaseX, releaseY); if (newShape == null) { return false; } b.remove(shape); b.remove(target); b.add(newShape); return true; } @Override public boolean undo() { Board b = model.getBoard(); b.remove(newShape); b.add(target); b.add(shape); System.out.println(target.getX() + "," + target.getY() + "," + oldSelectedX + "," + oldSelectedY + "," + shape.getX()+ ","+ shape.getY()+ ","+ releaseX+ ","+ releaseY + " UNDO"); shape.setLocation(oldSelectedX, oldSelectedY); target.setLocation(targetx, targety); return true; } }
true
251fe326510c74016c741baa6281043f30a0186b
Java
aliceb64/amapj
/src/fr/amapj/service/services/mescontrats/MesCartesPrepayeesService.java
UTF-8
3,660
2.203125
2
[]
no_license
/* * Copyright 2013-2016 Emmanuel BRUN (contact@amapj.fr) * * This file is part of AmapJ. * * AmapJ is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AmapJ 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with AmapJ. If not, see <http://www.gnu.org/licenses/>. * * */ package fr.amapj.service.services.mescontrats; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import fr.amapj.common.AmapjRuntimeException; import fr.amapj.common.DateUtils; import fr.amapj.common.SQLUtils; import fr.amapj.model.models.contrat.modele.ModeleContrat; import fr.amapj.model.models.contrat.modele.ModeleContratDate; import fr.amapj.model.models.contrat.modele.NatureContrat; /** * Partie spécifique aux cartes prépayées * */ public class MesCartesPrepayeesService { public MesCartesPrepayeesService() { } /** * Permet de calculer les informations relatives à une carte prepayée * * @param mc * @param em * @param now * @return */ public CartePrepayeeDTO computeCartePrepayee(ModeleContrat mc, EntityManager em,Date now) { if (mc.nature!=NatureContrat.CARTE_PREPAYEE) { return null; } CartePrepayeeDTO dto = new CartePrepayeeDTO(); Query q = em.createQuery("select mcd from ModeleContratDate mcd WHERE mcd.modeleContrat=:mc order by mcd.dateLiv , mcd.id"); q.setParameter("mc",mc); List<ModeleContratDate> datLivs = q.getResultList(); dto.cartePrepayeeDelai = mc.cartePrepayeeDelai; dto.nbLigModifiable = getNbLigModifiable(datLivs,now,mc.cartePrepayeeDelai); dto.nextDateLiv = getNextDateLivraison(datLivs,now,mc.cartePrepayeeDelai); dto.nextDateLivModifiable = getNextDateLivModifiable(datLivs,now,mc.cartePrepayeeDelai); return dto; } /** * Indique le nombre de lignes encore modifiables * @param cartePrepayeeDelai * @param now */ private int getNbLigModifiable(List<ModeleContratDate> datLivs, Date now, int cartePrepayeeDelai) { int res = 0; for (ModeleContratDate lig : datLivs) { if (cartePrepayeeLigModifiable(lig,now,cartePrepayeeDelai)) { res++; } } return res; } /** * Retourne la date de la prochaine livraison (aujourd'hui est une valeur possible) */ private Date getNextDateLivraison(List<ModeleContratDate> datLivs, Date now, int cartePrepayeeDelai) { Date ref = DateUtils.addDays(now, -1); for (ModeleContratDate lig : datLivs) { if (ref.before(lig.getDateLiv())) { return lig.getDateLiv(); } } return null; } public Date getNextDateLivModifiable(List<ModeleContratDate> datLivs, Date now, int cartePrepayeeDelai) { for (ModeleContratDate lig : datLivs) { if (cartePrepayeeLigModifiable(lig,now,cartePrepayeeDelai)) { return lig.getDateLiv(); } } return null; } private boolean cartePrepayeeLigModifiable(ModeleContratDate lig,Date now, int cartePrepayeeDelai) { Date d = DateUtils.addDays(lig.getDateLiv(), -cartePrepayeeDelai); return d.after(now); } }
true
52339aa6b5c01da733554c7746fd1cb36d88b5b8
Java
cga2351/code
/DecompiledViberSrc/app/src/main/java/com/mixpanel/android/c/o.java
UTF-8
16,668
1.65625
2
[]
no_license
package com.mixpanel.android.c; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.text.Editable; import android.text.TextWatcher; import android.util.SparseArray; import android.view.View; import android.view.View.AccessibilityDelegate; import android.view.ViewGroup; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.mixpanel.android.b.f; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.WeakHashMap; @TargetApi(16) abstract class o implements h.a { private final List<h.c> a; private final h b; protected o(List<h.c> paramList) { this.a = paramList; this.b = new h(); } public abstract void a(); protected List<h.c> b() { return this.a; } public void b(View paramView) { this.b.a(paramView, this.a, this); } protected h c() { return this.b; } public static class a extends o.d { private final int a; private final WeakHashMap<View, a> b; public a(List<h.c> paramList, int paramInt, String paramString, o.h paramh) { super(paramString, paramh, false); this.a = paramInt; this.b = new WeakHashMap(); } private View.AccessibilityDelegate d(View paramView) { try { View.AccessibilityDelegate localAccessibilityDelegate = (View.AccessibilityDelegate)paramView.getClass().getMethod("getAccessibilityDelegate", new Class[0]).invoke(paramView, new Object[0]); return localAccessibilityDelegate; } catch (NoSuchMethodException localNoSuchMethodException) { return null; } catch (IllegalAccessException localIllegalAccessException) { return null; } catch (InvocationTargetException localInvocationTargetException) { f.d("MixpanelAPI.ViewVisitor", "getAccessibilityDelegate threw an exception when called.", localInvocationTargetException); } return null; } public void a() { Iterator localIterator = this.b.entrySet().iterator(); while (localIterator.hasNext()) { Map.Entry localEntry = (Map.Entry)localIterator.next(); View localView = (View)localEntry.getKey(); a locala = (a)localEntry.getValue(); View.AccessibilityDelegate localAccessibilityDelegate = d(localView); if (localAccessibilityDelegate == locala) localView.setAccessibilityDelegate(locala.a()); else if ((localAccessibilityDelegate instanceof a)) ((a)localAccessibilityDelegate).a(locala); } this.b.clear(); } public void a(View paramView) { View.AccessibilityDelegate localAccessibilityDelegate = d(paramView); if (((localAccessibilityDelegate instanceof a)) && (((a)localAccessibilityDelegate).a(d()))) return; a locala = new a(localAccessibilityDelegate); paramView.setAccessibilityDelegate(locala); this.b.put(paramView, locala); } private class a extends View.AccessibilityDelegate { private View.AccessibilityDelegate b; public a(View.AccessibilityDelegate arg2) { Object localObject; this.b = localObject; } public View.AccessibilityDelegate a() { return this.b; } public void a(a parama) { if (this.b == parama) this.b = parama.a(); while (!(this.b instanceof a)) return; ((a)this.b).a(parama); } public boolean a(String paramString) { if (o.a.this.d() == paramString) return true; if ((this.b instanceof a)) return ((a)this.b).a(paramString); return false; } public void sendAccessibilityEvent(View paramView, int paramInt) { if (paramInt == o.a.a(o.a.this)) o.a.this.c(paramView); if (this.b != null) this.b.sendAccessibilityEvent(paramView, paramInt); } } } public static class b extends o.d { private final Map<TextView, TextWatcher> a = new HashMap(); public b(List<h.c> paramList, String paramString, o.h paramh) { super(paramString, paramh, true); } public void a() { Iterator localIterator = this.a.entrySet().iterator(); while (localIterator.hasNext()) { Map.Entry localEntry = (Map.Entry)localIterator.next(); ((TextView)localEntry.getKey()).removeTextChangedListener((TextWatcher)localEntry.getValue()); } this.a.clear(); } public void a(View paramView) { if ((paramView instanceof TextView)) { TextView localTextView = (TextView)paramView; a locala = new a(localTextView); TextWatcher localTextWatcher = (TextWatcher)this.a.get(localTextView); if (localTextWatcher != null) localTextView.removeTextChangedListener(localTextWatcher); localTextView.addTextChangedListener(locala); this.a.put(localTextView, locala); } } private class a implements TextWatcher { private final View b; public a(View arg2) { Object localObject; this.b = localObject; } public void afterTextChanged(Editable paramEditable) { o.b.this.c(this.b); } public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { } public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { } } } private static class c { private boolean a(TreeMap<View, List<View>> paramTreeMap, View paramView, List<View> paramList) { if (paramList.contains(paramView)) return false; if (paramTreeMap.containsKey(paramView)) { List localList = (List)paramTreeMap.remove(paramView); paramList.add(paramView); int i = localList.size(); for (int j = 0; j < i; j++) if (!a(paramTreeMap, (View)localList.get(j), paramList)) return false; paramList.remove(paramView); } return true; } public boolean a(TreeMap<View, List<View>> paramTreeMap) { ArrayList localArrayList = new ArrayList(); while (!paramTreeMap.isEmpty()) if (!a(paramTreeMap, (View)paramTreeMap.firstKey(), localArrayList)) return false; return true; } } private static abstract class d extends o { private final o.h a; private final String b; private final boolean c; public d(List<h.c> paramList, String paramString, o.h paramh, boolean paramBoolean) { super(); this.a = paramh; this.b = paramString; this.c = paramBoolean; } protected void c(View paramView) { this.a.a(paramView, this.b, this.c); } protected String d() { return this.b; } } public static class e { private final String a; private final String b; public e(String paramString1, String paramString2) { this.a = paramString1; this.b = paramString2; } public String a() { return this.a; } public String b() { return this.b; } } public static class f { public final int a; public final int b; public final int c; public f(int paramInt1, int paramInt2, int paramInt3) { this.a = paramInt1; this.b = paramInt2; this.c = paramInt3; } } public static class g extends o { private static final Set<Integer> d; private static final Set<Integer> e = new HashSet(Arrays.asList(arrayOfInteger2)); private final WeakHashMap<View, int[]> a = new WeakHashMap(); private final List<o.f> b; private final String c; private boolean f; private final o.i g; private final o.c h; static { Integer[] arrayOfInteger1 = new Integer[4]; arrayOfInteger1[0] = Integer.valueOf(0); arrayOfInteger1[1] = Integer.valueOf(1); arrayOfInteger1[2] = Integer.valueOf(5); arrayOfInteger1[3] = Integer.valueOf(7); d = new HashSet(Arrays.asList(arrayOfInteger1)); Integer[] arrayOfInteger2 = new Integer[5]; arrayOfInteger2[0] = Integer.valueOf(2); arrayOfInteger2[1] = Integer.valueOf(3); arrayOfInteger2[2] = Integer.valueOf(4); arrayOfInteger2[3] = Integer.valueOf(6); arrayOfInteger2[4] = Integer.valueOf(8); } public g(List<h.c> paramList, List<o.f> paramList1, String paramString, o.i parami) { super(); this.b = paramList1; this.c = paramString; this.f = true; this.g = parami; this.h = new o.c(null); } private boolean a(Set<Integer> paramSet, SparseArray<View> paramSparseArray) { TreeMap localTreeMap = new TreeMap(new Comparator() { public int a(View paramAnonymousView1, View paramAnonymousView2) { if (paramAnonymousView1 == paramAnonymousView2) return 0; if (paramAnonymousView1 == null) return -1; if (paramAnonymousView2 == null) return 1; return paramAnonymousView2.hashCode() - paramAnonymousView1.hashCode(); } }); int i = paramSparseArray.size(); for (int j = 0; j < i; j++) { View localView = (View)paramSparseArray.valueAt(j); int[] arrayOfInt = ((RelativeLayout.LayoutParams)localView.getLayoutParams()).getRules(); ArrayList localArrayList = new ArrayList(); Iterator localIterator = paramSet.iterator(); while (localIterator.hasNext()) { int k = arrayOfInt[((Integer)localIterator.next()).intValue()]; if ((k > 0) && (k != localView.getId())) localArrayList.add(paramSparseArray.get(k)); } localTreeMap.put(localView, localArrayList); } return this.h.a(localTreeMap); } public void a() { Iterator localIterator = this.a.entrySet().iterator(); while (localIterator.hasNext()) { Map.Entry localEntry = (Map.Entry)localIterator.next(); View localView = (View)localEntry.getKey(); int[] arrayOfInt = (int[])localEntry.getValue(); RelativeLayout.LayoutParams localLayoutParams = (RelativeLayout.LayoutParams)localView.getLayoutParams(); for (int i = 0; i < arrayOfInt.length; i++) localLayoutParams.addRule(i, arrayOfInt[i]); localView.setLayoutParams(localLayoutParams); } this.f = false; } public void a(View paramView) { ViewGroup localViewGroup = (ViewGroup)paramView; SparseArray localSparseArray = new SparseArray(); int i = localViewGroup.getChildCount(); for (int j = 0; j < i; j++) { View localView2 = localViewGroup.getChildAt(j); int n = localView2.getId(); if (n > 0) localSparseArray.put(n, localView2); } int k = this.b.size(); int m = 0; o.f localf; View localView1; if (m < k) { localf = (o.f)this.b.get(m); localView1 = (View)localSparseArray.get(localf.a); if (localView1 != null); } while (true) { m++; break; RelativeLayout.LayoutParams localLayoutParams = (RelativeLayout.LayoutParams)localView1.getLayoutParams(); int[] arrayOfInt = (int[])localLayoutParams.getRules().clone(); if (arrayOfInt[localf.b] != localf.c) { Set localSet; if (this.a.containsKey(localView1)) { localLayoutParams.addRule(localf.b, localf.c); if (!d.contains(Integer.valueOf(localf.b))) break label272; localSet = d; } while (true) { if ((localSet == null) || (a(localSet, localSparseArray))) break label305; a(); this.g.a(new o.e("circular_dependency", this.c)); return; this.a.put(localView1, arrayOfInt); break; label272: if (e.contains(Integer.valueOf(localf.b))) localSet = e; else localSet = null; } label305: localView1.setLayoutParams(localLayoutParams); } } } public void b(View paramView) { if (this.f) c().a(paramView, b(), this); } } public static abstract interface h { public abstract void a(View paramView, String paramString, boolean paramBoolean); } public static abstract interface i { public abstract void a(o.e parame); } public static class j extends o { private final a a; private final a b; private final WeakHashMap<View, Object> c; private final Object[] d; public j(List<h.c> paramList, a parama1, a parama2) { super(); this.a = parama1; this.b = parama2; this.d = new Object[1]; this.c = new WeakHashMap(); } public void a() { Iterator localIterator = this.c.entrySet().iterator(); while (localIterator.hasNext()) { Map.Entry localEntry = (Map.Entry)localIterator.next(); View localView = (View)localEntry.getKey(); Object localObject = localEntry.getValue(); if (localObject != null) { this.d[0] = localObject; this.a.a(localView, this.d); } } } public void a(View paramView) { Object localObject1; Object localObject2; if (this.b != null) { Object[] arrayOfObject = this.a.a(); if (1 == arrayOfObject.length) { localObject1 = arrayOfObject[0]; localObject2 = this.b.a(paramView); if (localObject1 == localObject2); do { return; if (localObject1 == null) break; if ((!(localObject1 instanceof Bitmap)) || (!(localObject2 instanceof Bitmap))) break label118; } while (((Bitmap)localObject1).sameAs((Bitmap)localObject2)); if ((!(localObject2 instanceof Bitmap)) && (!(localObject2 instanceof BitmapDrawable)) && (!this.c.containsKey(paramView))) break label181; } } while (true) { this.a.a(paramView); return; label118: if (((localObject1 instanceof BitmapDrawable)) && ((localObject2 instanceof BitmapDrawable))) { Bitmap localBitmap1 = ((BitmapDrawable)localObject1).getBitmap(); Bitmap localBitmap2 = ((BitmapDrawable)localObject2).getBitmap(); if ((localBitmap1 == null) || (!localBitmap1.sameAs(localBitmap2))) break; return; } if (!localObject1.equals(localObject2)) break; return; label181: this.d[0] = localObject2; if (this.a.a(this.d)) this.c.put(paramView, localObject2); else this.c.put(paramView, null); } } } public static class k extends o.d { private boolean a = false; public k(List<h.c> paramList, String paramString, o.h paramh) { super(paramString, paramh, false); } public void a() { } public void a(View paramView) { if ((paramView != null) && (!this.a)) c(paramView); if (paramView != null); for (boolean bool = true; ; bool = false) { this.a = bool; return; } } } } /* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar * Qualified Name: com.mixpanel.android.c.o * JD-Core Version: 0.6.2 */
true
4bc0ca35f84783ccc7532117458b193e8c15ea91
Java
zhongxingyu/Seer
/Diff-Raw-Data/5/5_bd719f9c06ce017979af6e18501e03ae8b5981db/AlleleFrequencyEstimate/5_bd719f9c06ce017979af6e18501e03ae8b5981db_AlleleFrequencyEstimate_t.java
UTF-8
6,910
2.328125
2
[]
no_license
package org.broadinstitute.sting.playground.utils; import org.broadinstitute.sting.playground.gatk.walkers.AlleleFrequencyWalker; import java.util.Arrays; import java.lang.Math; import org.broadinstitute.sting.utils.GenomeLoc; public class AlleleFrequencyEstimate { static { boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side effect!!! if (!assertsEnabled) { System.err.printf("\n\n\nERROR: You must run with asserts enabled. \"java -ea\".\n\n\n"); throw new RuntimeException("Asserts must be enabled!"); } } //AlleleFrequencyEstimate(); public GenomeLoc location; public char ref; public char alt; public int N; public double qhat; public double qstar; public double lodVsRef; public double lodVsNextBest; public double pBest; public double pRef; public int depth; public String notes; public String bases; public double[][] quals; public double[] posteriors; GenomeLoc l; public AlleleFrequencyEstimate(GenomeLoc location, char ref, char alt, int N, double qhat, double qstar, double lodVsRef, double lodVsNextBest, double pBest, double pRef, int depth, String bases, double[][] quals, double[] posteriors) { if( Double.isNaN(lodVsRef)) { System.out.printf("%s: lodVsRef is NaN\n", location.toString()); } if( Double.isNaN(lodVsNextBest)) { System.out.printf("lodVsNextBest is NaN\n"); } if( Double.isNaN(qhat)) { System.out.printf("qhat is NaN\n"); } if( Double.isNaN(qstar)) { System.out.printf("qstar is NaN\n"); } if( Double.isNaN(pBest)) { System.out.printf("pBest is NaN\n"); } if( Double.isNaN(pRef)) { System.out.printf("pRef is NaN\n"); } if( Double.isInfinite(lodVsRef)) { System.out.printf("lodVsRef is Infinite: %s %c %s\n", location.toString(), ref, bases); for (int i = 0; i < posteriors.length; i++) { System.out.printf("POSTERIOR %d %f\n", i, posteriors[i]); } } if( Double.isInfinite(lodVsNextBest)) { System.out.printf("lodVsNextBest is Infinite\n"); } if( Double.isInfinite(qhat)) { System.out.printf("qhat is Infinite\n"); } if( Double.isInfinite(qstar)) { System.out.printf("qstar is Infinite\n"); } if( Double.isInfinite(pBest)) { System.out.printf("pBest is Infinite\n"); } if( Double.isInfinite(pRef)) { System.out.printf("pRef is Infinite\n"); } assert(! Double.isNaN(lodVsRef)); assert(! Double.isNaN(lodVsNextBest)); assert(! Double.isNaN(qhat)); assert(! Double.isNaN(qstar)); assert(! Double.isNaN(pBest)); assert(! Double.isNaN(pRef)); assert(! Double.isInfinite(lodVsRef)); assert(! Double.isInfinite(lodVsNextBest)); assert(! Double.isInfinite(qhat)); assert(! Double.isInfinite(qstar)); assert(! Double.isInfinite(pBest)); assert(! Double.isInfinite(pRef)); this.location = location; this.ref = ref; this.alt = alt; this.N = N; this.qhat = qhat; this.qstar = qstar; this.lodVsRef = lodVsRef; this.lodVsNextBest = lodVsNextBest; this.depth = depth; this.notes = ""; this.bases = bases; this.quals = quals; this.posteriors = posteriors; } /** Return the most likely genotype. */ public String genotype() { int alt_count = (int)(qstar * N); int ref_count = N-alt_count; char[] alleles = new char[N]; int i; for (i = 0; i < ref_count; i++) { alleles[i] = ref; } for (; i < N; i++) { alleles[i] = alt; } Arrays.sort(alleles); return new String(alleles); } public double emperical_allele_frequency() { return (double)Math.round((double)qstar * (double)N) / (double)N; } public double emperical_allele_frequency(int N) { return (double)Math.round((double)qstar * (double)N) / (double)N; } public String asGFFString() { String s = ""; s += String.format("%s\tCALLER\tVARIANT\t%s\t%s\t%f\t.\t.\t", location.getContig(), location.getStart(), location.getStart(), lodVsRef); s += String.format("\t;\tREF %c", ref); s += String.format("\t;\tALT %c", alt); s += String.format("\t;\tFREQ %f", qstar); s += String.format("\t;\tDEPTH %d", depth); s += String.format("\t;\tLODvsREF %f", lodVsRef); s += String.format("\t;\tLODvsNEXTBEST %f", lodVsNextBest); s += String.format("\t;\tQHAT %f", qhat); s += String.format("\t;\tQSTAR %f", qstar); s += String.format("\t;\tBASES %s", bases); s += ";\n"; // add quals. return s; } public String asTabularString() { return String.format("RESULT %s %c %c %f %f %f %f %d %s\n", location, ref, alt, qhat, qstar, lodVsRef, lodVsNextBest, depth, notes); } public String toString() { return asTabularString(); } public String asString() { // Print out the called bases // Notes: switched from qhat to qstar because qhat doesn't work at n=1 (1 observed base) where having a single non-ref // base has you calculate qstar = 0.0 and qhat = 0.49 and that leads to a genotype predicition of AG according // to qhat, but AA according to qstar. This needs to be further investigated to see whether we really want // to use qstar, but make N (number of chormosomes) switch to n (number of reads at locus) for n=1 long numNonrefBases = Math.round(qstar * N); long numRefBases = N - numNonrefBases; if (ref < alt) { // order bases alphabetically return AlleleFrequencyWalker.repeat(ref, numRefBases) + AlleleFrequencyWalker.repeat(alt, numNonrefBases); }else{ return AlleleFrequencyWalker.repeat(alt, numNonrefBases) + AlleleFrequencyWalker.repeat(ref, numRefBases); } } public double posterior() { return this.posteriors[(int)this.qstar * this.N]; } }
true
2995e71fd8387d39f667baf6221829db5debefab
Java
Edward83528/OCEJWCD
/course/examples/OCEJWCD_CH16/src/java/net/hello/servlets/StepTwoServlet.java
UTF-8
1,658
2.5
2
[]
no_license
package net.hello.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.hello.domain.Customer; public class StepTwoServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String phone = request.getParameter("phone"); String notify = request.getParameter("notify"); List<String> errorMessages = new ArrayList<>(); if (phone == null || phone.length() == 0) { errorMessages.add("Phone is required."); } if (errorMessages.isEmpty()) { HttpSession session = request.getSession(); Customer customer = (Customer) session.getAttribute("customer"); customer.setPhone(phone); customer.setNotify(notify != null); RequestDispatcher rd = request.getRequestDispatcher( "add_customer_success.jsp"); rd.forward(request, response); } else { request.setAttribute("errorMessages", errorMessages); RequestDispatcher rd = request.getRequestDispatcher( "step_two_form.jsp"); rd.forward(request, response); } } }
true
1b2e36c8dedf7800833145b17128d013dc4151a6
Java
jsubodh06/SubodhDunzoAssingment
/src/main/java/com/dunzo/assignment/model/Ingredient.java
UTF-8
728
2.8125
3
[]
no_license
package com.dunzo.assignment.model; /** * created by Subodh Jain * date :- 06-sept-2020 * Ingredient enum to add new Beverages. */ public enum Ingredient { Hotmilk(Unit.ml,100.0f), HotWater(Unit.ml,100.0f), TeaLeavesSyrup(Unit.ml,100.0f), GingerSyrup(Unit.ml,10.0f), SugarSyrup(Unit.ml,10.0f), CoffeeSyrup(Unit.ml,100.0f), GreenMixture(Unit.ml,30f); private Unit unit; private Float minThresholdValue; Ingredient(Unit unit, Float minThresholdValue) { this.unit = unit; this.minThresholdValue = minThresholdValue; } public Unit getUnit () { return this.unit; } public float getMinThresholdValue() { return minThresholdValue; } }
true
5cf637d41badd1a17bab9e00dc6d229a9342c541
Java
aqqbjlgu/rms-spring-cloud
/authority/src/main/java/com/youngsun/authority/service/impl/RoleServiceImpl.java
UTF-8
7,253
1.976563
2
[]
no_license
package com.youngsun.authority.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.youngsun.authority.dto.RoleDto; import com.youngsun.authority.dto.RolePermissionDto; import com.youngsun.authority.entity.RoleEntity; import com.youngsun.authority.entity.UserRoleEntity; import com.youngsun.authority.mapper.RoleMapper; import com.youngsun.authority.service.PermissionService; import com.youngsun.authority.service.RolePermissionService; import com.youngsun.authority.service.RoleService; import com.youngsun.authority.service.UserRoleService; import com.youngsun.vo.RolePermissionVo; import com.youngsun.vo.RoleVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import tk.mybatis.mapper.entity.Example; import java.util.Date; import java.util.List; import java.util.stream.Collectors; /** * Created by 国平 on 2016/10/21. */ @Service public class RoleServiceImpl extends BasicServiceImpl<RoleEntity> implements RoleService { @Autowired private PermissionService permissionService; @Autowired private UserRoleService userRoleService; @Autowired private RolePermissionService rolePermissionService; @Autowired private RoleMapper roleMapper; public List<RolePermissionDto> getAllwithPermission(String belongTo) { // roleMapper.getAllRoleWithPermissionByUserId(belongTo); return null; } @Override public List<RolePermissionDto> getAllRoleWithPermissionByUserId(Integer start, Integer pageSize, String userId, String belongTo) { List<RolePermissionDto> rolePermissionDtos = roleMapper.getAllRoleWithPermissionByUserId(userId, belongTo); return rolePermissionDtos; } @Override public List<RoleDto> getRoleByUserId(String userId) { UserRoleEntity userRoleEntity = new UserRoleEntity(); userRoleEntity.setUserId(userId); List<UserRoleEntity> userRoleEntities = userRoleService.getAllByObject(userRoleEntity); List<RoleDto> roleDtos = null; if (!CollectionUtils.isEmpty(userRoleEntities)) { List<String> roleIds = userRoleEntities.stream().map(e -> e.getRoleId()).collect(Collectors.toList()); Example example = new Example(RoleEntity.class); example.createCriteria().andIn("id", roleIds); List<RoleEntity> roleEntities = roleMapper.selectByExample(example); roleDtos = roleEntities.stream().map(e -> { RoleDto roleDto = new RoleDto(); BeanUtils.copyProperties(e, roleDto); return roleDto; }).collect(Collectors.toList()); } return roleDtos; } @Override public PageInfo<RoleDto> getAllRoles(int page, int limit,String belongTo) { RoleEntity roleEntity = new RoleEntity(); roleEntity.setAvailable(true); roleEntity.setBelongTo(belongTo); List<RoleEntity> roleEntities = roleMapper.select(roleEntity); List<RoleDto> roleDtos = roleEntities.stream().map(e -> { RoleDto roleDto = new RoleDto(); BeanUtils.copyProperties(e, roleDto); return roleDto; }).collect(Collectors.toList()); PageInfo<RoleDto> returnPage = new PageInfo<>(roleDtos); Integer count = roleMapper.selectCount(null); Integer pages = count%limit==0 ? count/limit : (count/limit) + 1; returnPage.setTotal(count); returnPage.setPages(pages); return returnPage; } @Override public PageInfo<RoleDto> getByRoleVo(Integer start, Integer limit, RoleVo roleVo) { PageHelper.startPage(start, limit); Example example = new Example(RoleEntity.class); Example.Criteria criteria = example.createCriteria(); if (StringUtils.isEmpty(roleVo.getName())) { roleVo.setName(null); } else { criteria.andLike("name", "%"+roleVo.getName()+"%"); } if (StringUtils.isEmpty(roleVo.getAvailable())) { roleVo.setAvailable(null); } else { criteria.andEqualTo("available", roleVo.getAvailable()); } criteria.andEqualTo("belongTo",roleVo.getBelongTo()); List<RoleEntity> roleEntities = roleMapper.selectByExample(example); List<RoleDto> roleDtos = roleEntities.stream().map(e -> { RoleDto roleDto = new RoleDto(); BeanUtils.copyProperties(e, roleDto); return roleDto; }).collect(Collectors.toList()); PageInfo<RoleDto> returnPage = new PageInfo<>(roleDtos); Integer count = roleMapper.selectCountByExample(example); Integer pages = count%limit==0 ? count/limit : (count/limit) + 1; returnPage.setTotal(count); returnPage.setPages(pages); return returnPage; } @Override @Transactional(rollbackFor = Exception.class) public RoleDto save(RoleVo roleVo) { RoleEntity roleEntity = new RoleEntity(); BeanUtils.copyProperties(roleVo, roleEntity); if (StringUtils.isEmpty(roleVo.getId())) { roleEntity.setInsertDate(new Date()); roleEntity.setId(null); roleMapper.insert(roleEntity); } else { roleEntity.setInsertUserId(null); roleMapper.updateByPrimaryKeySelective(roleEntity); } RoleDto roleDto = new RoleDto(); BeanUtils.copyProperties(roleEntity, roleDto); return roleDto; } @Override public void delete(String id) { RoleEntity roleEntity = new RoleEntity(); roleEntity.setId(id); roleEntity.setAvailable(false); roleMapper.updateByPrimaryKeySelective(roleEntity); } @Override public PageInfo<RoleDto> getAllRolesByUserId(int page, int limit, String userId) { UserRoleEntity userRoleEntity = new UserRoleEntity(); userRoleEntity.setUserId(userId); List<UserRoleEntity> userRoleEntities = userRoleService.getAllByObject(userRoleEntity); if (CollectionUtils.isEmpty(userRoleEntities)) { return null; } List<String> roleIds = userRoleEntities.stream().map(e -> e.getRoleId()).collect(Collectors.toList()); Example example = new Example(RoleEntity.class); example.createCriteria().andIn("id", roleIds); PageHelper.startPage(page, limit); List<RoleEntity> roleEntities = roleMapper.selectByExample(example); List<RoleDto> roleDtos = roleEntities.stream().map(e -> { RoleDto roleDto = new RoleDto(); BeanUtils.copyProperties(e, roleDto); return roleDto; }).collect(Collectors.toList()); PageInfo<RoleDto> returnPage = new PageInfo<>(roleDtos); Integer count = roleMapper.selectCountByExample(example); Integer pages = count%limit==0 ? count/limit : (count/limit) + 1; returnPage.setTotal(count); returnPage.setPages(pages); return returnPage; } }
true
f40f01668d92b80e701d2f3aedb7c16b4a1978a3
Java
Telecooperation/big-sense
/MeasureApplications/Acceleration/app/src/main/java/de/tudarmstadt/tk/dbsystel/acceleration/StartService.java
UTF-8
3,683
2.109375
2
[ "MIT" ]
permissive
package de.tudarmstadt.tk.dbsystel.acceleration; import android.app.Notification; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import org.json.JSONException; import org.json.JSONObject; public class StartService extends Service { public final static String LOG_TAG = "Acceleration"; public static String API_URL; public static String AUTH_PW; public static int API_PORT; public static int MIN_GPS_UPDATE_INTERVAL_SEC; public static int MIN_GPS_UPDATE_DISTANCE_METER; public static float ACCELERATION_THRESHOLD; public static String IMPORTANT_AXES; //This can be a combination of x, y and z @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Notification notification = new NotificationCompat.Builder(this).build(); startForeground(startId, notification); //First get config if(intent.getExtras() != null) { Object extra_conf = intent.getExtras().get("config"); JSONObject config = new JSONObject(); if (extra_conf instanceof JSONObject) { config = (JSONObject) extra_conf; } else if (extra_conf instanceof String) { String str = (String) extra_conf; try { config = new JSONObject(str); } catch (JSONException e) { } } else { throw new IllegalStateException("Type of intent extra not a config: " + extra_conf.getClass().getCanonicalName()); } //Get the possible config parameters, which can be set by webinterface try { API_URL = config.getString("api_url"); } catch (JSONException e) { API_URL = Config.API_URL; } try { AUTH_PW = config.getString("auth_pw"); } catch (JSONException e) { AUTH_PW = Config.AUTH_PW; } try { API_PORT = config.getInt("api_port"); } catch (JSONException e) { API_PORT = Config.API_PORT; } try { MIN_GPS_UPDATE_INTERVAL_SEC = config.getInt("min_gps_update_interval_sec"); } catch (JSONException e) { MIN_GPS_UPDATE_INTERVAL_SEC = Config.MIN_GPS_UPDATE_INTERVAL_SEC; } try { MIN_GPS_UPDATE_DISTANCE_METER = config.getInt("min_gps_update_distance_meter"); } catch (JSONException e) { MIN_GPS_UPDATE_DISTANCE_METER = Config.MIN_GPS_UPDATE_DISTANCE_METER; } try { ACCELERATION_THRESHOLD = (float) config.getDouble("acceleration_threshold"); } catch (JSONException e) { ACCELERATION_THRESHOLD = Config.ACCELERATION_THRESHOLD; } try { IMPORTANT_AXES = config.getString("important_axes"); } catch (JSONException e) { IMPORTANT_AXES = Config.IMPORTANT_AXES; } } final CollectAndSend collectAndSend = new CollectAndSend(getApplicationContext()); //Send old measurements at start of the app new Thread(new Runnable() { @Override public void run() { collectAndSend.sendMeasurements(); } }).start(); return flags; } @Override public void onDestroy() { super.onDestroy(); } }
true
b423b2879c804f3580dcea15a7a5cf7a21382c68
Java
tuean/leetcodeRecords
/src/main/java/com/tuean/LeetCode/L200toL299/L290.java
UTF-8
724
3.1875
3
[]
no_license
package com.tuean.LeetCode.L200toL299; import java.util.HashMap; import java.util.Map; public class L290 { public boolean wordPattern(String pattern, String str) { String[] ss = str.split(" "); if (ss.length != pattern.length()) return false; Map<Character, String> map = new HashMap<>(); for (int x = 0; x < pattern.length(); x++) { if (map.containsKey(pattern.charAt(x))) { String tmp = map.get(pattern.charAt(x)); if (!tmp.equals(ss[x])) return false; } else { if (map.containsValue(ss[x])) return false; map.put(pattern.charAt(x), ss[x]); } } return true; } }
true
84d783cc1071735b1cb9937bb26332dadff67ddf
Java
feiyu2016/make-better-ui
/DemoTrunk/src/com/qihoo/move_gridview/DiskManager.java
UTF-8
10,681
2.0625
2
[]
no_license
package com.qihoo.move_gridview; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.qihoo.trunk.R; import android.content.Context; import android.text.TextUtils; import android.util.Log; /** * @author xulc * * 瓷片管理器 */ public class DiskManager { /** 使用固定ID但不直接显示磁片,如:垃圾短信和垃圾电话 **/ public static final int DISK_TRASH_MESSAGE = 1;//垃圾短信 public static final int DISK_BLOCK_CALL = 2;//垃圾电话 /** 磁片ID显示区域,注:此区域ID不能随便改动,如需添加新的磁片ID请告知 **/ public static final int DISK_PHONE_EXAM = 100;//手机体检 public static final int DISK_PHONE_ACCELERATE = 101;//手机加速 public static final int DISK_FLOW_TRAFFIC = 102;//流量监控 public static final int DISK_ANTI_SCAN = 103;//手机杀毒 public static final int DISK_PROGRAM_MANAGER = 104;//软件管家 public static final int DISK_POWER_MANAGER = 105;//节电管理 public static final int DISK_DETECTION = 106;//硬件检测 public static final int DISK_ADVERTISE_BLOCK = 107;//恶意广告拦截 private Context mContext; /** * The disk order. */ private static final int[] mDiskIdCollections = { DISK_PHONE_EXAM , DISK_PHONE_ACCELERATE , DISK_FLOW_TRAFFIC , DISK_ANTI_SCAN , DISK_PROGRAM_MANAGER , DISK_POWER_MANAGER , DISK_DETECTION , DISK_ADVERTISE_BLOCK }; private static final int[][] mDiskTextCollections = { { DISK_PHONE_EXAM, R.string.disk_phone_exam } , { DISK_PHONE_ACCELERATE, R.string.sysclear } , { DISK_FLOW_TRAFFIC, R.string.disk_flow_traffic } , { DISK_ANTI_SCAN, R.string.disk_anti_scan } , { DISK_PROGRAM_MANAGER, R.string.disk_program_manager } , { DISK_POWER_MANAGER, R.string.disk_power_manager } , { DISK_DETECTION, R.string.disk_detection} , { DISK_ADVERTISE_BLOCK, R.string.disk_advertise_block} }; private static final int[][] mDiskIconCollections = { { DISK_PHONE_EXAM, R.drawable.disk_phone_exam_default }, { DISK_PHONE_ACCELERATE, R.drawable.disk_sysclear_alert }, { DISK_FLOW_TRAFFIC, R.drawable.disk_flow_traffic }, { DISK_ANTI_SCAN, R.drawable.disk_anti_scan }, { DISK_PROGRAM_MANAGER, R.drawable.disk_program_manager }, { DISK_POWER_MANAGER, R.drawable.disk_power_manager_default }, { DISK_DETECTION, R.drawable.disk_power_manager_default }, { DISK_ADVERTISE_BLOCK, R.drawable.disk_advertise_block } }; private static final String DISK_MAIN_SCREEN_DEFAULT_DATA = "main_screen_disk.dat";//磁片显示ID private static final String DISK_MAIN_SCREEN_DEFAULT_DATA_TIMESTAMP = "main_screen_disk.dat.timestamp";//磁片显示ID时间戳 /** * mDiskTextMap 默认磁片文字 * mDiskIconMap 默认磁片图标 */ private HashMap<Integer, Integer> mDiskTextMap = null, mDiskIconMap = null; public DiskManager(Context context) { this.mContext = context; } /** * Get the collection of id. * * @return */ public int[] getDiskId() { return mDiskIdCollections; } /** * To check the id exist. * * @param id * @return */ public boolean isExistId(int id) { for (int i = 0; i < mDiskIdCollections.length; i++) { if (mDiskIdCollections[i] == id) { return true; } } return false; } /** * Get the new id. * * @param dataListForSave * @return */ public ArrayList<Disk> getNewIdList(List<Disk> dataListForSave) { ArrayList<Disk> newId = null; if (dataListForSave != null) { for (int i = 0; i < mDiskIdCollections.length; i++) { boolean bFind = false; for (int j = 0; j < dataListForSave.size(); j++) { if (dataListForSave.get(j).getId() == mDiskIdCollections[i]) { bFind = true; break; } } if (!bFind) { if (newId == null) { newId = new ArrayList<Disk>(); } Disk disk = new Disk(); disk.setId(mDiskIdCollections[i]); disk.setPosition(i); newId.add(disk); } } } return newId; } /** * Get the default disk text id. * * @param diskId * @return */ public int getDiskTextId(int diskId) { if (mDiskTextMap == null) { mDiskTextMap = new HashMap<Integer, Integer>(); for (int i = 0; i < mDiskTextCollections.length; i++) { mDiskTextMap.put(mDiskTextCollections[i][0], mDiskTextCollections[i][1]); } } if (mDiskTextMap != null && mDiskTextMap.containsKey(diskId)) { return mDiskTextMap.get(diskId); } return -1; } /** * Get the default disk icon id. * * @param diskId * @return */ public int getDiskIconId(int diskId) { if (mDiskIconMap == null) { mDiskIconMap = new HashMap<Integer, Integer>(); for (int i = 0; i < mDiskIconCollections.length; i++) { mDiskIconMap.put(mDiskIconCollections[i][0], mDiskIconCollections[i][1]); } } if (mDiskIconMap != null && mDiskIconMap.containsKey(diskId)) { return mDiskIconMap.get(diskId); } return -1; } /** * Get the push data of id. * * @return */ public ArrayList<Integer> getPushHideDisk() { return new ArrayList<Integer>(); } /** * Get the disk position data. * * @return */ public ArrayList<Integer> getMainScreenDisk() { return null; } /** * Write the file. * * @param filePath * @param str * @throws IOException */ public void writeFile(String str) throws IOException { writeTimeStampFile(); File file = new File(mContext.getFilesDir(), DISK_MAIN_SCREEN_DEFAULT_DATA); FileOutputStream outStream = new FileOutputStream(file); outStream.write(str.getBytes()); outStream.flush(); outStream.close(); } /** * Write the time stamp file. * * @throws IOException */ public void writeTimeStampFile() throws IOException { String str = System.currentTimeMillis() / 1000 + ""; File file = new File(mContext.getFilesDir(), DISK_MAIN_SCREEN_DEFAULT_DATA_TIMESTAMP); FileOutputStream outStream = new FileOutputStream(file); outStream.write(str.getBytes()); outStream.flush(); outStream.close(); } /** * Read the file. * * @param filePath * @return * @throws IOException */ public ArrayList<Integer> readFile(InputStream is) throws IOException { ArrayList<Integer> list = new ArrayList<Integer>(); if (is != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(is)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (!line.equals("")) { list.add(Integer.parseInt(line.trim())); } } } catch (Exception e) { return null; } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { } } } } else { return null; } return list; } /** * Get the data string. * * @param lists * @param diskList * @return */ public String getDataStr(List<ArrayList<Disk>> lists, List<Disk> noVisibleList, List<Disk> noExistList) { ArrayList<Integer> listAll = new ArrayList<Integer>(); for (int i = 0; i < lists.size(); i++) { ArrayList<Disk> list = lists.get(i); if (list != null && list.size() > 0) { for (int j = 0; j < list.size(); j++) { if (list.get(j).getId() != -1) { listAll.add(list.get(j).getId()); } } } } if (noVisibleList != null && noVisibleList.size() > 0) { listAll = addDiskList(noVisibleList, listAll); } if (noExistList != null && noExistList.size() > 0) { listAll = addDiskList(noExistList, listAll); } StringBuilder sb = new StringBuilder(); for (int j = 0; j < listAll.size(); j++) { sb.append(listAll.get(j) + "\n"); } return sb.toString(); } /** * Add the hide disk list and no exist disk list of data. * * @param diskList * @param listAll * @return */ private ArrayList<Integer> addDiskList(List<Disk> diskList, ArrayList<Integer> listAll) { //从前往后插入,因为之前保存的位置是在原始数组中的位置。 for (int i = 0; i < diskList.size(); i++) { Disk disk = diskList.get(i); int id = disk.getId(); if (id != -1) { int position = disk.getPosition(); if (position >= listAll.size()) { listAll.add(disk.getId()); } else { listAll.add(disk.getPosition(), disk.getId()); } } } return listAll; } /** * Get the source data string. * * @param diskList * @return */ public String getSourceStr(List<Disk> diskList) { StringBuilder sb = new StringBuilder(); if (diskList != null && diskList.size() > 0) { for (int i = 0; i < diskList.size(); i++) { Disk disk = diskList.get(i); sb.append(disk.getId() + "\n"); } } return sb.toString(); } }
true
efe8ddaede732c8d1a8172b99f3dce4ed1bac7e4
Java
DavidGnanaraj1/KonakartCss
/Practo old/src/main/java/com/atmecs/automations/pageactions/PageActions.java
UTF-8
1,161
2.21875
2
[]
no_license
package com.atmecs.automations.pageactions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import com.atmecs.practo.utils.LogReport; public class PageActions { LogReport log = new LogReport(); public void click(WebDriver driver, String locator) { driver.findElement(By.xpath(locator)).click(); } public void dropdown(WebDriver driver, String locator, String value) { WebElement element = driver.findElement(By.xpath(locator)); Select select = new Select(element); select.selectByVisibleText(value); } public void sendKeys(WebDriver driver, String locator, String value) { WebElement element = driver.findElement(By.xpath(locator)); element.sendKeys(value); } public void isDisplayed(WebDriver driver,String path) { boolean isDisplayed=driver.findElement(By.xpath(path)).isDisplayed(); if(isDisplayed==true) { log.info("Element is displayed"); } else { log.info("Element not found"); } } }
true
43dc7319ec9a47cf4d04e835e9699179d64bea16
Java
AneeshMishra/GenpactLibraryManagementSystemApplication
/src/main/java/com/aneesh/mylibrary/GenpactLibraryManagementSystem/config/RestExceptionHandler.java
UTF-8
1,007
2.21875
2
[]
no_license
package com.aneesh.mylibrary.GenpactLibraryManagementSystem.config; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<Object> resourceEntityNotFound( ResourceNotFoundException ex ) { ApiError apiError = createError( ex.getLocalizedMessage(), HttpStatus.BAD_REQUEST, ex ); return new ResponseEntity<>( apiError, apiError.getStatus() ); } private ApiError createError( String msg, HttpStatus status, Exception e ) { ApiError apiError = new ApiError( status ); apiError.setMessage( msg ); apiError.setDebugMessage( e.getMessage() ); return apiError; } }
true
ed06c75c6e3210874fea63bd8ac3911190335d14
Java
1000000000/Minecraft-Ping-Tool
/src/aor/PingTool/PingToolPlayerListener.java
UTF-8
1,656
2.453125
2
[]
no_license
package aor.PingTool; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.material.Dye; import org.bukkit.material.MaterialData; public class PingToolPlayerListener implements Listener { public static PingTool plugin; public static final boolean ALLOW_PING_MIDAIR = true; //public static List<BlockState> replacedBlocksState=new ArrayList<BlockState>(); public PingToolPlayerListener(PingTool instance) { plugin = instance; } @EventHandler public void onPlayerInteract(PlayerInteractEvent event){ Player player = event.getPlayer(); MaterialData itemInHand = player.getItemInHand().getData(); // Right clicking air or a block event: if ((event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) && itemInHand.getItemType() == Material.INK_SACK) // If they left clicked with dye. { Location targetBlock = player.getTargetBlock(null, 1000).getLocation(); // Select the target block. //player.sendMessage("Pinging " + targetBlock); if (targetBlock.getBlock().getType() == Material.AIR) { targetBlock = player.getTargetBlock(null, 10).getLocation(); } if (targetBlock.getBlock().getType() != Material.AIR || ALLOW_PING_MIDAIR) // No pinging midair! (unless you can ping midair) { event.setCancelled(true); plugin.pingBlock(plugin.getServer().getOnlinePlayers(), targetBlock, Material.WOOL, ((Dye)itemInHand).getColor().getWoolData(), 20L); } } } }
true
9fbada5f289aef2b1eb5c968ebf1cff1927f5927
Java
feiyunruyue/zhihu
/Spider/src/Zhihu.java
UTF-8
634
2.09375
2
[]
no_license
public class Zhihu { private String questionTitle;// 问题标题 private String questionDetail;// 问题描述 private String questionUrl;// 问题url public String getQuestionTitle() { return questionTitle; } public void setQuestionTitle(String questionTitle) { this.questionTitle = questionTitle; } public String getQuestionDetail() { return questionDetail; } public void setQuestionDetail(String questionDetail) { this.questionDetail = questionDetail; } public String getQuestionUrl() { return questionUrl; } public void setQuestionUrl(String questionUrl) { this.questionUrl = questionUrl; } }
true
209e6b9d42886b477b64bc91e3910e5f421b511e
Java
fahadzafar/ServerYouMp3
/src/com/yt/thread/WorkerThread.java
UTF-8
3,465
2.453125
2
[]
no_license
/* * 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 com.yt.thread; import com.yt.parse.ParseOperation; import com.yt.util.SharedData; import java.io.File; import java.util.List; import org.parse4j.ParseObject; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class WorkerThread implements Runnable { private String myCompleteId; public WorkerThread(int threadNo) { this.myCompleteId = threadNo + "_" + SharedData.baseId; } @Override public void run() { long startTime = System.nanoTime(); processCommand(); long endTime = System.nanoTime(); long duration = (endTime - startTime); // System.out.println(myCompleteId + " Work processing Start-End. TTE=" + (duration / 1000000000) + " secs" // ); } private void processCommand() { try { List<ParseObject> queueItem = ParseOperation.GetWork(myCompleteId); if (queueItem != null) { if (queueItem.size() > 0) SharedData.TaskCompletedCount ++; for (int i = 0; i < queueItem.size(); i++) { String vidId = queueItem.get(i).getString("videoId"); String title = queueItem.get(i).getString("title"); // Perform the work ----------------- if (vidId == null || vidId.equals("")) { return; } try { Process p = Runtime.getRuntime().exec(SharedData.BaseCommandExtractAudio + vidId + ".mp3" + " https://www.youtube.com/watch?v=" + vidId, null, new File(SharedData.RootStoragePath)); // 10 min vid = qYILKnaVPgw // 3.5 mins = d3bUg8wsgVE p.waitFor(); // Now upload the file to Parse. Path path = Paths.get(SharedData.RootStoragePath + vidId + ".mp3"); ParseOperation.UploadFileAndDeleteQueueEntry(queueItem.get(i), Files.readAllBytes(path)); String det = path.toString(); File storedFile = new File(SharedData.RootStoragePath + vidId + ".mp3"); System.out.println("Finished:" + title + "\n \t \t, state, idle:" + SharedData.TaskIdleCount + ", completed:" + SharedData.TaskCompletedCount); storedFile.delete(); } catch (Exception ex) { ParseOperation.UploadError(ex.getMessage() + "--- i= " + i + " + , queueItem.size= " + queueItem.size(), "WorkerThread (queueItem loop)"); } // ------------------------ } // for each retrieved item. } else { SharedData.TaskIdleCount++; } Thread.sleep(SharedData.WaitAfterWorkComplete); } catch (InterruptedException e) { ParseOperation.UploadError(e.getMessage(), "WorkerThread (processCommand())"); } } @Override public String toString() { return this.myCompleteId; } }
true
4f50a03d319cc2153b1a2002e56d324dc710c1d9
Java
TommesDee/cpachecker
/src/org/sosy_lab/cpachecker/cfa/blocks/builder/.svn/text-base/LoopPartitioning.java.svn-base
UTF-8
4,937
1.914063
2
[ "Apache-2.0" ]
permissive
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2013 Dirk Beyer * All rights reserved. * * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cfa.blocks.builder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.sosy_lab.common.LogManager; import org.sosy_lab.cpachecker.cfa.CFA; import org.sosy_lab.cpachecker.cfa.model.BlankEdge; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.cfa.model.CFAEdgeType; import org.sosy_lab.cpachecker.cfa.model.CFANode; import org.sosy_lab.cpachecker.cfa.model.FunctionEntryNode; import org.sosy_lab.cpachecker.util.CFATraversal; import org.sosy_lab.cpachecker.util.CFAUtils.Loop; import com.google.common.collect.Iterables; /** * <code>PartitioningHeuristic</code> that creates blocks for each loop- and function-body. */ public class LoopPartitioning extends PartitioningHeuristic { private static final CFATraversal TRAVERSE_CFA_INSIDE_FUNCTION = CFATraversal.dfs().ignoreFunctionCalls(); private Map<CFANode, Set<CFANode>> loopHeaderToLoopBody; private final CFA cfa; public LoopPartitioning(LogManager pLogger, CFA pCfa) { loopHeaderToLoopBody = null; cfa = pCfa; } private void initLoopMap() { loopHeaderToLoopBody = new HashMap<>(); if (cfa.getLoopStructure().isPresent()) { for (String functionName : cfa.getLoopStructure().get().keySet()) { for (Loop loop : cfa.getLoopStructure().get().get(functionName)) { if (loop.getLoopHeads().size() == 1) { //currently only loops with single loop heads supported loopHeaderToLoopBody.put(Iterables.getOnlyElement(loop.getLoopHeads()), loop.getLoopNodes()); } } } } } @Override protected boolean shouldBeCached(CFANode pNode) { if (pNode instanceof FunctionEntryNode && pNode.getNumEnteringEdges() == 0) { //main function return true; } if (isLoopHead(pNode)) { if (hasBlankEdgeFromLoop(pNode) || selfLoop(pNode)) { return false; } return true; } return false; } private boolean isLoopHead(CFANode pNode) { return cfa.getAllLoopHeads().get().contains(pNode); } private boolean hasBlankEdgeFromLoop(CFANode pNode) { for (int i = 0; i < pNode.getNumEnteringEdges(); i++) { CFAEdge edge = pNode.getEnteringEdge(i); if (edge instanceof BlankEdge && isLoopHead(edge.getPredecessor())) { return true; } } return false; } private static boolean selfLoop(CFANode pNode) { return pNode.getNumLeavingEdges() == 1 && pNode.getLeavingEdge(0).getSuccessor().equals(pNode); } @Override protected Set<CFANode> getBlockForNode(CFANode pNode) { if (pNode instanceof FunctionEntryNode) { return TRAVERSE_CFA_INSIDE_FUNCTION.collectNodesReachableFrom(pNode); } if (isLoopHead(pNode)) { Set<CFANode> loopBody = new HashSet<>(); if (loopHeaderToLoopBody == null) { initLoopMap(); } Set<CFANode> immutableLoopBody = loopHeaderToLoopBody.get(pNode); if (immutableLoopBody == null) { return null; } loopBody.addAll(immutableLoopBody); insertLoopStartState(loopBody, pNode); insertLoopReturnStates(loopBody); return loopBody; } return null; } private void insertLoopStartState(Set<CFANode> pLoopBody, CFANode pLoopHeader) { for (int i = 0; i < pLoopHeader.getNumEnteringEdges(); i++) { CFAEdge edge = pLoopHeader.getEnteringEdge(i); if (edge instanceof BlankEdge && !pLoopBody.contains(edge.getPredecessor())) { pLoopBody.add(edge.getPredecessor()); } } } private void insertLoopReturnStates(Set<CFANode> pLoopBody) { List<CFANode> addNodes = new ArrayList<>(); for (CFANode node : pLoopBody) { for (int i = 0; i < node.getNumLeavingEdges(); i++) { CFAEdge edge = node.getLeavingEdge(i); if (!pLoopBody.contains(edge.getSuccessor()) && !(node.getLeavingEdge(i).getEdgeType() == CFAEdgeType.FunctionCallEdge)) { addNodes.add(edge.getSuccessor()); } } } pLoopBody.addAll(addNodes); } }
true
b95e7ec29b54afdd89d957abd113b279ccf420a0
Java
fredrickRoyal/Ludo
/src/hello/Singletones/Singleton.java
UTF-8
5,756
2.4375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hello.Singletones; import hello.ArtficialIntelligence; import hello.Controller; import hello.players.*; import javax.microedition.lcdui.Image; /** * * @author Royal */ public class Singleton { private static BluePlayer bluePlayer1; private static BluePlayer bluePlayer2; private static BluePlayer bluePlayer3; private static BluePlayer bluePlayer4; private static RedPlayer redPlayer1; private static RedPlayer redPlayer2; private static RedPlayer redPlayer3; private static RedPlayer redPlayer4; private static GreenPlayer greenPlayer1; private static GreenPlayer greenPlayer2; private static GreenPlayer greenPlayer3; private static GreenPlayer greenPlayer4; private static YellowPlayer yellowPlayer1; private static YellowPlayer yellowPlayer2; private static YellowPlayer yellowPlayer3; private static YellowPlayer yellowPlayer4; private static Controller game_manager; private static ArtficialIntelligence kasozi; private static Image ludo_board; //integers private static int initial_y = 0; private static int img_height = 0; //strings private static String score; //booleans private static boolean drawScoreAllowed = false; private static boolean draw_number = false; private static boolean drawRoadBlockedSign = false; private static boolean drawBluePlayerHasFinishedSign = false; private static boolean green_has_finished = false; private static boolean yellow_has_finished = false; private static boolean red_has_finished = false; private static boolean blue_has_finished = false; /** * @return the bluePlayer1 */ public static BluePlayer getBluePlayer1() { return bluePlayer1; } /** * @return the bluePlayer2 */ public static BluePlayer getBluePlayer2() { return bluePlayer2; } /** * @return the bluePlayer3 */ public static BluePlayer getBluePlayer3() { return bluePlayer3; } /** * @return the bluePlayer4 */ public static BluePlayer getBluePlayer4() { return bluePlayer4; } /** * @return the redPlayer1 */ public static RedPlayer getRedPlayer1() { return redPlayer1; } /** * @return the redPlayer2 */ public static RedPlayer getRedPlayer2() { return redPlayer2; } /** * @return the redPlayer3 */ public static RedPlayer getRedPlayer3() { return redPlayer3; } /** * @return the redPlayer4 */ public static RedPlayer getRedPlayer4() { return redPlayer4; } /** * @return the greenPlayer1 */ public static GreenPlayer getGreenPlayer1() { return greenPlayer1; } /** * @return the greenPlayer2 */ public static GreenPlayer getGreenPlayer2() { return greenPlayer2; } /** * @return the greenPlayer3 */ public static GreenPlayer getGreenPlayer3() { return greenPlayer3; } /** * @return the greenPlayer4 */ public static GreenPlayer getGreenPlayer4() { return greenPlayer4; } /** * @return the yellowPlayer1 */ public static YellowPlayer getYellowPlayer1() { return yellowPlayer1; } /** * @return the yellowPlayer2 */ public static YellowPlayer getYellowPlayer2() { return yellowPlayer2; } /** * @return the yellowPlayer3 */ public static YellowPlayer getYellowPlayer3() { return yellowPlayer3; } /** * @return the yellowPlayer4 */ public static YellowPlayer getYellowPlayer4() { return yellowPlayer4; } /** * @return the game_manager */ public static Controller getGame_manager() { return game_manager; } /** * @return the kasozi */ public static ArtficialIntelligence getKasozi() { return kasozi; } /** * @return the ludo_board */ public static Image getLudo_board() { return ludo_board; } /** * @return the initial_y */ public static int getInitial_y() { return initial_y; } /** * @return the img_height */ public static int getImg_height() { return img_height; } /** * @return the score */ public static String getScore() { return score; } /** * @return the drawScoreAllowed */ public static boolean isDrawScoreAllowed() { return drawScoreAllowed; } /** * @return the draw_number */ public static boolean isDraw_number() { return draw_number; } /** * @return the drawRoadBlockedSign */ public static boolean isDrawRoadBlockedSign() { return drawRoadBlockedSign; } /** * @return the drawBluePlayerHasFinishedSign */ public static boolean isDrawBluePlayerHasFinishedSign() { return drawBluePlayerHasFinishedSign; } /** * @return the green_has_finished */ public static boolean isGreen_has_finished() { return green_has_finished; } /** * @return the yellow_has_finished */ public static boolean isYellow_has_finished() { return yellow_has_finished; } /** * @return the red_has_finished */ public static boolean isRed_has_finished() { return red_has_finished; } /** * @return the blue_has_finished */ public static boolean isBlue_has_finished() { return blue_has_finished; } }
true
2b36e54592e7cfd8323a4a9ce148f0a8757782c4
Java
tuannt39-study/vietjack-jsp-servlet-bookstore
/src/com/vietjack/dao/OrderDAO.java
UTF-8
5,561
2.453125
2
[]
no_license
package com.vietjack.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import com.vietjack.core.Order; public class OrderDAO { private Connection conn; private static CustomerDAO customerDAO = new CustomerDAO(); public Connection getConnection() throws SQLException { if (conn == null) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore", "root", "123456"); return conn; } return conn; } public void closeConnection() { if (conn != null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public boolean addNewOrder(Order order) throws SQLException { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String query = "insert into bs_order(id, customer_id, order_date) values (" + order.getId() + ", " + order.getCustomer().getId() + ",'" + sdf.format(order.getOrderDate()) + "')"; Statement stmt = getConnection().createStatement(); int n = stmt.executeUpdate(query); // return (n!=0); if (n != 0) return true; return false; } public ArrayList<Order> findAllOrder() throws SQLException { String query = "select * from bs_order "; Statement stmt = getConnection().createStatement(); ResultSet resultSet = stmt.executeQuery(query); ArrayList<Order> orderList = new ArrayList<Order>(); while (resultSet.next()) { Order order = new Order(); order.setId(resultSet.getLong("id")); Long customerId = resultSet.getLong("customer_id"); order.setCustomer(customerDAO.findCustomerById(customerId)); order.setOrderDate(resultSet.getDate("order_date")); orderList.add(order); } return orderList; } public Order findOrderById(long id) throws SQLException { String query = "select * from bs_order where id='" + id + "'"; Statement stmt = getConnection().createStatement(); ResultSet resultSet = stmt.executeQuery(query); if (resultSet.next()) { Order order = new Order(); order.setId(resultSet.getLong("id")); Long customerId = resultSet.getLong("customer_id"); order.setCustomer(customerDAO.findCustomerById(customerId)); order.setOrderDate(resultSet.getDate("order_date")); return order; } else return null; } public boolean modifyOrder(Order order) throws SQLException { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String query = "update bs_order set customer_id='" + order.getCustomer().getId() + "', order_date='" + sdf.format(order.getOrderDate()) + "' where id=" + order.getId(); Statement stmt = getConnection().createStatement(); int n = stmt.executeUpdate(query); // return (n!=0); if (n != 0) return true; return false; } public boolean deleteOrderByID(Long orderId) throws SQLException { String query = "delete from bs_order where id = ?"; java.sql.PreparedStatement stmt = getConnection().prepareStatement(query); stmt.setLong(1, orderId); int n = stmt.executeUpdate(); // return (n!=0); if (n != 0) { System.out.println(n + " rows deleted"); } return false; } public long calculateRevenueOfDay(Date date) throws SQLException { long revenue = 0l; java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String query = "SELECT bs_book.PRICE, bs_order_detail.quantity FROM bs_book, bs_order_detail, bs_order WHERE bs_book.id = bs_order_detail.book_id and bs_order_detail.order_id = bs_order.ID and bs_order.order_date = '" + sdf.format(date) + "'"; Statement stmt = getConnection().createStatement(); ResultSet resultSet = stmt.executeQuery(query); while (resultSet.next()) { revenue += resultSet.getLong("bs_book.PRICE") * resultSet.getLong("bs_order_detail.quantity"); } return revenue; } public long calculateRevenueOfTime(Date date1, Date date2) throws SQLException { long revenue = 0l; java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String query = "SELECT bs_book.PRICE, bs_order_detail.quantity FROM bs_book, bs_order_detail, bs_order WHERE bs_book.id = bs_order_detail.book_id and bs_order_detail.order_id = bs_order.ID and bs_order.order_date between '" + sdf.format(date1) + "' and '" + sdf.format(date2) + "'"; Statement stmt = getConnection().createStatement(); ResultSet resultSet = stmt.executeQuery(query); while (resultSet.next()) { revenue += resultSet.getLong("bs_book.PRICE") * resultSet.getLong("bs_order_detail.quantity"); } return revenue; } public long generateId() throws SQLException { String query = "select max(id) as maxId from bs_order"; Statement stmt = getConnection().createStatement(); ResultSet resultSet = stmt.executeQuery(query); if (resultSet.next()) { return resultSet.getLong("maxId") + 1; } else { return 0; } } }
true
c9da3d5f667d2529a63dc53d19376ecb060f17ca
Java
MMeunierSide/buck
/src/com/facebook/buck/skylark/function/ReadConfig.java
UTF-8
3,646
1.921875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.skylark.function; import com.facebook.buck.skylark.packages.PackageContext; import com.facebook.buck.skylark.packages.PackageFactory; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.skylarkinterface.Param; import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature; import com.google.devtools.build.lib.syntax.BuiltinFunction; import com.google.devtools.build.lib.syntax.Environment; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.FuncallExpression; import com.google.devtools.build.lib.syntax.SkylarkSignatureProcessor; import javax.annotation.Nullable; /** * Exposes a {@code read_config} for Skylark parser. * * <p>This is a temporary solution to simplify migration from Python DSL to Skylark and allows * clients to query values from {@code .buckconfig} files and {@code --config} command line * arguments. * * <p>Example, when buck is invoked with {@code --config user.value=my_value} an invocation of * {@code read_config("user", "value", "default_value")} will return {@code my_value}. */ public class ReadConfig { private static final String FUNCTION_NAME = "read_config"; /** Prevent instantiations */ private ReadConfig() {} @SkylarkSignature( name = FUNCTION_NAME, objectType = Object.class, returnType = Object.class, doc = "Returns a list of files that match glob search pattern.", parameters = { @Param( name = "section", type = String.class, doc = "the name of the .buckconfig section with the desired value." ), @Param( name = "field", type = String.class, doc = "the name of the .buckconfig field with the desired value." ), @Param( name = "defaultValue", noneable = true, type = String.class, defaultValue = "None", doc = "the value to return if the desired value is not set in the .buckconfig." ), }, documented = false, // this is an API that we should remove once select is available useAst = true, useEnvironment = true ) private static final BuiltinFunction readConfig = new BuiltinFunction(FUNCTION_NAME) { @SuppressWarnings("unused") public Object invoke( String section, String field, Object defaultValue, FuncallExpression ast, Environment env) throws EvalException { PackageContext packageContext = PackageFactory.getPackageContext(env, ast); @Nullable String value = packageContext.getRawConfig().getOrDefault(section, ImmutableMap.of()).get(field); return value != null ? value : defaultValue; } }; public static BuiltinFunction create() { return readConfig; } // configure read_config function using annotations on this class static { SkylarkSignatureProcessor.configureSkylarkFunctions(ReadConfig.class); } }
true
c82389d3a0d69fd739c8de8fdb90d50f22f6a759
Java
cliangtime/huangliwo_android
/app/src/main/java/com/feitianzhu/huangliwo/GlobalUtil.java
UTF-8
2,453
2.421875
2
[ "Apache-2.0" ]
permissive
package com.feitianzhu.huangliwo; import android.app.Application; import android.support.v4.app.FragmentActivity; import android.text.Html; import android.text.Spanned; import com.feitianzhu.huangliwo.utils.ScreenUtil; /** * Created by bch on 2020/5/11 * 全局对象保存 * 全局操作,方便调用 */ public class GlobalUtil { private static Application application; /** * APP的主activity */ private static FragmentActivity mainActivity; /** * 当前的activity */ private static FragmentActivity currentActivity; public static void setApplication(Application application) { GlobalUtil.application = application; } /** * 获取APP对象 * * @return */ public static Application getApplication() { return application; } /** * 设置主Activity * * @param mainActivity */ public static void setMainActivity(FragmentActivity mainActivity) { GlobalUtil.mainActivity = mainActivity; currentActivity = mainActivity; } /** * 获取主Activity * * @return */ public static FragmentActivity getMainActivity() { return mainActivity; } /** * 设置当前Activity * * @param currentActivity */ public static void setCurrentActivity(FragmentActivity currentActivity) { GlobalUtil.currentActivity = currentActivity; } /** * @return */ public static FragmentActivity getCurrentActivity() { return currentActivity; } /** * 判断apk包是否是debug模式 */ public static boolean isDebugMode() { return BuildConfig.DEBUG; } public static int px2dp(float pxValue) { return ScreenUtil.px2dp(mainActivity, pxValue); } public static int dp2px(float dipValue) { return ScreenUtil.dp2px(mainActivity, dipValue); } public static String getString(int resid, Object... formatArgs) { return application.getResources().getString(resid, formatArgs); } public static Spanned getHtmlString(int resid, Object... formatArgs) { return Html.fromHtml(application.getResources().getString(resid, formatArgs)); } public static String getStringSafe(int resid) { try { return application.getResources().getString(resid); } catch (Exception e) { return ""; } } }
true
e6e1c0c4b149e3210ca1bb85071d630b7f17468c
Java
JavaRubyNode/Projetos_NetBeans
/ProjetosNetbeans/CadastroVeiculosSwing/src/cadastroveiculosswing/Sistema.java
UTF-8
684
3.125
3
[]
no_license
package cadastroveiculosswing; import java.util.ArrayList; public class Sistema { // ArrayList que guardará os veículos cadastrados private ArrayList<Veiculo> veiculos = new ArrayList(); // método que permite cadastrar um novo veículo public void cadastrarVeiculo(Veiculo v){ this.veiculos.add(v); } // método que retorna a quantidade de veículos cadastrados public int quantVeiculosCadastrados(){ return this.veiculos.size(); } // método que retorna uma ArrayList com todos os veículos cadastrados public ArrayList<Veiculo> obterVeiculos(){ return this.veiculos; } }
true
39e7be74d2b2e3d23050ba02438cb37f239223c6
Java
cuba-platform/cuba
/modules/gui/src/com/haulmont/cuba/gui/export/ExportFormat.java
UTF-8
3,780
1.9375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.gui.export; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Format of data exported by {@link ExportDisplay}. * */ public final class ExportFormat implements Serializable { private static final long serialVersionUID = -8448531804422711852L; public static final ExportFormat HTML = new ExportFormat("text/html", "html"); public static final ExportFormat HTM = new ExportFormat("text/html", "htm"); public static final ExportFormat PDF = new ExportFormat("application/pdf", "pdf"); public static final ExportFormat XLS = new ExportFormat("application/vnd.ms-excel", "xls"); public static final ExportFormat XLSX = new ExportFormat("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx"); public static final ExportFormat RTF = new ExportFormat("application/rtf", "rtf"); public static final ExportFormat DOC = new ExportFormat("application/doc", "doc"); public static final ExportFormat DOCX = new ExportFormat("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx"); public static final ExportFormat XML = new ExportFormat("text/xml", "xml"); public static final ExportFormat CSV = new ExportFormat("application/csv", "csv"); public static final ExportFormat JPEG = new ExportFormat("image/jpeg", "jpeg"); public static final ExportFormat JPG = new ExportFormat("image/jpeg", "jpg"); public static final ExportFormat PNG = new ExportFormat("image/png", "png"); public static final ExportFormat RAR = new ExportFormat("application/x-rar-compressed", "rar"); public static final ExportFormat ZIP = new ExportFormat("application/zip", "zip"); public static final ExportFormat GZ = new ExportFormat(" application/x-gzip", "gz"); public static final ExportFormat JSON = new ExportFormat(" application/json", "json"); public static final ExportFormat OCTET_STREAM = new ExportFormat("application/octet-stream", ""); public static final ExportFormat TEXT = new ExportFormat("text/plain", ""); public static final List<ExportFormat> DEFAULT_FORMATS = Collections.unmodifiableList( Arrays.asList(HTML, HTM, PDF, XLS, XLSX, RTF, DOC, DOCX, XML, CSV, JPEG, JPG, PNG, RAR, GZ, ZIP, OCTET_STREAM, JSON)); protected final String contentType; protected final String fileExt; public ExportFormat(String contentType, String fileExt) { this.contentType = contentType; this.fileExt = fileExt; } public static ExportFormat getByExtension(String extension) { if (StringUtils.isEmpty(extension)) { return OCTET_STREAM; } String extLowerCase = StringUtils.lowerCase(extension); List<ExportFormat> formats = DEFAULT_FORMATS; for (ExportFormat f : formats) { if (f.getFileExt().equals(extLowerCase)) return f; } return OCTET_STREAM; } public String getContentType() { return contentType; } public String getFileExt() { return fileExt; } }
true
511d053dd36a15ff6e502ecdabdaa04de98cdfb2
Java
GillesVanDeVyver/ir
/Engine.java
UTF-8
5,669
2.546875
3
[]
no_license
/* * This file is part of the computer assignment for the * Information Retrieval course at KTH. * * Johan Boye, 2017 */ package ir; import java.util.ArrayList; import java.util.Map.Entry; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.RandomAccessFile; /** * This is the main class for the search engine. */ public class Engine { /** The inverted index. */ //Index index = new HashedIndex(); // Index index = new PersistentHashedIndex(); // Index index = new PersistentScalableHashedIndex(); Index index; /** The indexer creating the search index. */ Indexer indexer; /** K-gram index */ KGramIndex kgIndex; /** The searcher used to search the index. */ Searcher searcher; /** Spell checker */ SpellChecker speller; /** The engine GUI. */ SearchGUI gui; /** Directories that should be indexed. */ ArrayList<String> dirNames = new ArrayList<String>(); /** Lock to prevent simultaneous access to the index. */ Object indexLock = new Object(); /** The patterns matching non-standard words (e-mail addresses, etc.) */ String patterns_file = null; /** The file containing the logo. */ String pic_file = ""; /** The file containing the pageranks. */ String rank_file = ""; /** For persistent indexes, we might not need to do any indexing. */ boolean is_indexing = true; private HITSRanker hitsRanker; /* ----------------------------------------------- */ /** * Constructor. * Indexes all chosen directories and files */ public Engine( String[] args ) { decodeArgs( args ); // Index index = new PersistentScalableHashedIndex(is_indexing); Index index = new HashedIndex(); // Index index = new PersistentHashedIndex(); indexer = new Indexer( index, kgIndex, patterns_file ); hitsRanker = new HITSRanker("linksDavis.txt", "davisTitles.txt", index ); searcher = new Searcher( index, kgIndex, hitsRanker ); gui = new SearchGUI( this ); gui.init(); /* * Calls the indexer to index the chosen directory structure. * Access to the index is synchronized since we don't want to * search at the same time we're indexing new files (this might * corrupt the index). */ if (is_indexing) { synchronized ( indexLock ) { gui.displayInfoText( "Indexing, please wait..." ); long startTime = System.currentTimeMillis(); for ( int i=0; i<dirNames.size(); i++ ) { File dokDir = new File( dirNames.get( i )); indexer.processFiles( dokDir, is_indexing ); } long elapsedTime = System.currentTimeMillis() - startTime; gui.displayInfoText( String.format( "Indexing done in %.1f seconds.", elapsedTime/1000.0 )); index.cleanup(); } } else { gui.displayInfoText( "Index is loaded from disk" ); } // calculateDocLenghts("euclid.txt"); //only once readDocLengths("euclid.txt"); searcher.initPageRankVector(); } private void readDocLengths(String fileName) { try { BufferedReader in = new BufferedReader( new FileReader( fileName )); String line; while ((line = in.readLine()) != null) { String[] splittedLine = line.split(":"); index.euclidDocLengths.put(Integer.parseInt(splittedLine[0]), Double.parseDouble(splittedLine[1])); } } catch (NumberFormatException | IOException e) { e.printStackTrace(); } } private void calculateDocLenghts(String fileName) { indexer.lastDocID=0; synchronized ( indexLock ) { for ( int i=0; i<dirNames.size(); i++ ) { File dokDir = new File( dirNames.get( i )); indexer.processFilesSecondPass( dokDir ); } } HITSRanker.writeToFile(index.euclidDocLengths, fileName, index.euclidDocLengths.size()); } /* ----------------------------------------------- */ /** * Decodes the command line arguments. */ private void decodeArgs( String[] args ) { int i=0, j=0; while ( i < args.length ) { if ( "-d".equals( args[i] )) { i++; if ( i < args.length ) { dirNames.add( args[i++] ); } } else if ( "-p".equals( args[i] )) { i++; if ( i < args.length ) { patterns_file = args[i++]; } } else if ( "-l".equals( args[i] )) { i++; if ( i < args.length ) { pic_file = args[i++]; } } else if ( "-r".equals( args[i] )) { i++; if ( i < args.length ) { rank_file = args[i++]; } } else if ( "-ni".equals( args[i] )) { i++; is_indexing = false; } else { is_indexing = false; break; } } } /* ----------------------------------------------- */ public static void main( String[] args ) { Engine e = new Engine( args ); } }
true
6d5d0dfe37b9ccbe7869637ceebe67fcd5523d45
Java
google-code-export/zkcalendar
/zkcalendar3/calendar/src/org/zkoss/calendar/api/DateFormatter.java
UTF-8
1,377
2.59375
3
[]
no_license
/* ContentHandler.java {{IS_NOTE Purpose: Description: History: Mar 11, 2009 4:27:29 PM , Created by jumperchen }}IS_NOTE Copyright (C) 2009 Potix Corporation. All Rights Reserved. {{IS_RIGHT }}IS_RIGHT */ package org.zkoss.calendar.api; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * A date formatter is used to display the different date format in the calendar. * @author jumperchen * */ public interface DateFormatter { /** * Returns the caption of the day of week. */ public String getCaptionByDayOfWeek(Date date, Locale locale, TimeZone timezone); /** * Returns the caption of the time of day. */ public String getCaptionByTimeOfDay(Date date, Locale locale, TimeZone timezone); /** * Returns the caption of the date. */ public String getCaptionByDate(Date date, Locale locale, TimeZone timezone); /** * Returns the caption of the date of month. */ public String getCaptionByDateOfMonth(Date date, Locale locale, TimeZone timezone); /** * Returns the caption of the popup title. */ public String getCaptionByPopup(Date date, Locale locale, TimeZone timezone); /** * Returns the caption of the week number within the current year. */ public String getCaptionByWeekOfYear(Date date, Locale locale, TimeZone timezone); }
true
f6191700eb2d20f35e253eac4cdd166a3d2445c6
Java
NintendoLink/leetcode
/src/com/qhl/leetcode/tree/RangeSumBSTSolution.java
UTF-8
2,264
3.75
4
[]
no_license
/** * @Author: LinK * @Date: 2019/5/20 14:48 */ package com.qhl.leetcode.tree; import com.qhl.leetcode.basestructure.TreeNode; /** * 给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。 二叉搜索树保证具有唯一的值。 示例 1: 输入:root = [10,5,15,3,7,null,18], L = 7, R = 15 输出:32 示例 2: 输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 输出:23 提示: 树中的结点数量最多为 10000 个。 最终的答案保证小于 2^31。 在真实的面试中遇到过这道题? */ public class RangeSumBSTSolution { public static int res = 0; public int rangeSumBST(TreeNode root, int L, int R) { solution(root,L,R); return res; } public static void solution(TreeNode root,int L,int R){ // 递归版本,结果有错误 //todo // if (root == null){ // return; // } // // if (root.val >= L && root.val<= R){ // res += root.val; // solution(root.left,L,R); // solution(root.right,L,R); // }else if (root.val>R){ // solution(root.left,L,R); // }else { // solution(root.right,L,R); // } // } //TODO //前序遍历版本,有错误 if (root == null){ return; } if (root.val >= L && root.val<=R){ res += root.val; } solution(root.left,L,R); solution(root.right,L,R); } /** * 二叉树的前序遍历 * @param root */ public static void preOrder(TreeNode root){ if (root == null){ return; } System.out.println(root.val); preOrder(root.left); preOrder(root.right); } public static void main(String[] args) { TreeNode root = new TreeNode(3); TreeNode rootLeft = new TreeNode(9); TreeNode rootRight = new TreeNode(20); TreeNode rightLeft = new TreeNode(15); TreeNode rightRight = new TreeNode(7); root.left = rootLeft; root.right = rootRight; rootRight.left = rightLeft; rootRight.right = rightRight; preOrder(root); } }
true
82028b9b139c88015e968db47c88ab083db3c8bc
Java
G-Jay-R/Project-javaweb
/jspForStudent/src/com/tz/jspstudy/test/ReflectTest.java
UTF-8
3,625
3.203125
3
[]
no_license
package com.tz.jspstudy.test; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.tz.jspstudy.sysmanage.bean.User; import com.tz.jspstudy.sysmanage.bean.UserReflect; /** * * 类描述: 测试两个有相同属性的对象互相复制属性的值 * 类名称:com.tz.jspstudy.test.ReflectTest * 创建人:keven * 创建时间:2016年7月26日 下午8:18:44 * @version V1.0 */ public class ReflectTest{ /** * 思路:1:获得from对象和to对象所有属性, * 2:通过from属性的get方法得到值 ,然后通过to对象属性的set方法赋值 * @Title: beanReflect * @Description: TODO * @param objFrom * @param objTo * @throws SecurityException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void beanReflect(Object objFrom,Object objTo) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ //获取objFrom对象的 class Class objFromClass = objFrom.getClass(); //获取objTo对象的class Class objToClass = objTo.getClass(); //通过对象获得对象的所有属性 Field[] objFromFields = objFromClass.getDeclaredFields(); Field[] objToFields = objToClass.getDeclaredFields(); //轮询from对象的所有属性,与to对象里的属性匹配,然后取值和赋值 for(int i= 0;i<objFromFields.length;i++){ String objFromFieldName = objFromFields[i].getName(); if(!objFromFieldName.equals("serialVersionUID")){ for(int j= 0 ;j<objToFields.length;j++){ String objToFeildName = objToFields[j].getName(); if(objFromFieldName.equals(objToFeildName)){ //获取get和set方法备用 String setMethodString = "set"+objFromFieldName.substring(0,1).toUpperCase() +objFromFieldName.substring(1); //获取get和set方法备用 String getMethodString = "get"+objFromFieldName.substring(0,1).toUpperCase() +objFromFieldName.substring(1); System.out.println("setMethod="+setMethodString); System.out.println("getMethod="+getMethodString); //获取from对象的get属性的方法 //获取to对象的set属性的方法 Method getMethod = objFromClass.getMethod(getMethodString, new Class[]{}); Method setMethod = objToClass.getMethod(setMethodString, new Class[]{objToFields[j].getType()}); //取值 Object fromValue = getMethod.invoke(objFrom, new Object[]{}); //设置值 setMethod.invoke(objTo, new Object[]{fromValue}); } } } } } public static void main(String[] args) { User user = new User(); user.setUserId(1l); user.setUserName("aaaa"); UserReflect userReflect = new UserReflect(); try { ReflectTest.beanReflect(user, userReflect); System.out.println(userReflect.getUserId()); System.out.println(userReflect.getUserName()); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
b2047becd3710a28bd50cc9a29378486887ba20e
Java
sajal02gupta/hetznerAssignment
/src/main/java/com/hetzner/demo/controller/ServerController.java
UTF-8
655
2.109375
2
[]
no_license
package com.hetzner.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.hetzner.demo.model.ServerRequest; import com.hetzner.demo.model.ServerResponse; import com.hetzner.demo.repo.CreateServerDAL; @RestController public class ServerController { @Autowired private CreateServerDAL createserverDal; @PostMapping("/servers") public ServerResponse create(@RequestBody ServerRequest c){ return createserverDal.create(c); } }
true
08508af95510e7d9cf8dd5140729641e7d62a2bd
Java
soberhjj/tianyan-cloud-service
/tianyan-gateway-service/src/main/java/com/newland/tianyan/gateway/filter/ApiLogRespFilter.java
UTF-8
3,748
1.960938
2
[]
no_license
package com.newland.tianyan.gateway.filter; import com.newland.tianyan.gateway.support.GatewayLoggerSupport; import com.newland.tianyan.gateway.support.ResponseBodyTraceIdDecorator; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.reactivestreams.Publisher; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter; import org.springframework.core.Ordered; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.http.server.reactive.ServerHttpResponseDecorator; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.LocalDateTime; /** * 会话响应信息打印 * * @author: RojiaHuang * @date: 2021/2/27 */ @Component @Slf4j public class ApiLogRespFilter extends GatewayLoggerSupport implements GlobalFilter, Ordered { @SneakyThrows @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpResponse serverHttpResponse = exchange.getResponse(); DataBufferFactory dataBufferFactory = serverHttpResponse.bufferFactory(); ServerHttpRequest serverHttpRequest = exchange.getRequest(); //后置过滤器,发生在ApiLogReqFilter后置过滤器顺序之后 ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(serverHttpResponse) { @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { if (body instanceof Flux) { Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body; return super.writeWith(fluxBody.map(dataBuffer -> { byte[] content = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(content); DataBufferUtils.release(dataBuffer); String responseBody = new String(content, StandardCharsets.UTF_8); String traceId = getTradeIdFromHeads(serverHttpResponse); String makeUpTraceIdRequestBody = ResponseBodyTraceIdDecorator.putTraceId(responseBody, traceId); String requestTime = getRequestTimeFromHeads(serverHttpRequest); LocalDateTime now = LocalDateTime.now(); Double consuming = StringUtils.isEmpty(requestTime) ? null : Duration.between(LocalDateTime.parse(requestTime), now).getNano() / 1000000.0; log.info("requestTime:{},responseTime:{},consuming:{}ms,responseBody:{}", requestTime, now.toString(), consuming, makeUpTraceIdRequestBody); byte[] uppedContent = makeUpTraceIdRequestBody.getBytes(StandardCharsets.UTF_8); return dataBufferFactory.wrap(uppedContent); })); } return super.writeWith(body); } }; return chain.filter(exchange.mutate().response(decoratedResponse).build()); } @Override public int getOrder() { return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER; } }
true
f324e01e4a56748ebc6743e2cd62f9d7ce00edb0
Java
so0487/Spring
/spring_board/src/main/java/kr/or/ddit/service/BoardServiceImpl.java
UTF-8
2,045
2.3125
2
[]
no_license
package kr.or.ddit.service; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import kr.or.ddit.dao.BoardDAO; import kr.or.ddit.dao.ReplyDAO; import kr.or.ddit.dto.BoardVO; import kr.or.ddit.request.PageMaker; import kr.or.ddit.request.SearchCriteria; public class BoardServiceImpl implements BoardService { private BoardDAO boardDAO; public void setBoardDAO(BoardDAO boardDAO) { this.boardDAO=boardDAO; } private ReplyDAO replyDAO; public void setReplyDAO(ReplyDAO replyDAO) { this.replyDAO = replyDAO; } @Override public BoardVO getBoardForModify(int bno) throws SQLException { BoardVO board = boardDAO.selectBoardByBno(bno); return board; } @Override public BoardVO getBoard(int bno) throws SQLException { BoardVO board = boardDAO.selectBoardByBno(bno); boardDAO.increaseViewCnt(bno); return board; } @Override public void write(BoardVO board) throws SQLException { int bno=boardDAO.selectBoardSeqNext(); board.setBno(bno); boardDAO.insertBoard(board); } @Override public void modify(BoardVO board) throws SQLException { boardDAO.updateBoard(board); } @Override public void remove(int bno) throws SQLException { boardDAO.deleteBoard(bno); } @Override public Map<String, Object> getBoardList(SearchCriteria cri) throws SQLException { Map<String,Object> dataMap=new HashMap<String,Object>(); //현재 page 번호에 맞는 리스트를 perPageNum 개수 만큼 가져오기. List<BoardVO> boardList=boardDAO.selectBoardCriteria(cri); //reply count 입력 for(BoardVO board : boardList) { int replycnt=replyDAO.countReply(board.getBno()); board.setReplycnt(replycnt); } //전체 board 개수 int totalCount=boardDAO.selectBoardCriteriaTotalCount(cri); //PageMaker 생성. PageMaker pageMaker = new PageMaker(); pageMaker.setCri(cri); pageMaker.setTotalCount(totalCount); dataMap.put("boardList", boardList); dataMap.put("pageMaker",pageMaker); return dataMap; } }
true
c5e63ee47aa1ce91cb7fad68958f0cd562e4f425
Java
gaurav-shashank/MyProjects
/library/src/main/java/com/example/library/repository/BooksRepository.java
UTF-8
405
1.625
2
[]
no_license
package com.example.library.repository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.example.library.entity.Books; @Repository public interface BooksRepository extends CrudRepository<Books, Integer>,JpaSpecificationExecutor<Books> { }
true
b0085c52d0875c85a9232ce9d8f7e7bb0852d32c
Java
luotianwen/pgy
/dd_adserver/src/com/kokmobi/server/protocol/service/impl/AdLogDataProcessServiceImpl.java
UTF-8
11,589
1.757813
2
[]
no_license
package com.kokmobi.server.protocol.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.kokmobi.server.servlet.util.CompatibleUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.kokmobi.server.bean.AdLogData; import com.kokmobi.server.bean.AdLogInfo; import com.kokmobi.server.bean.AdLogPackage; import com.kokmobi.server.bean.AdLogReq; import com.kokmobi.server.bean.AdProjectInfo; import com.kokmobi.server.bean.Country; import com.kokmobi.server.bean.CountryLevel; import com.kokmobi.server.commons.Constants; import com.kokmobi.server.protocol.service.AdLogDataProcessService; import com.kokmobi.server.protocol.service.ProtocolUtil; import com.kokmobi.server.service.AreaService; import com.kokmobi.server.service.CacheInfoUtil; import com.kokmobi.server.service.RedisTool; import com.kokmobi.server.service.SdkService; import com.kokmobi.server.util.CalendarFormat; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class AdLogDataProcessServiceImpl implements AdLogDataProcessService { private static Log logger = LogFactory.getLog(AdLogDataProcessServiceImpl.class); @Override public AdLogReq parseRequest(HttpServletRequest req) throws Exception { AdLogReq reqInfo = new AdLogReq(); String xmodel = ProtocolUtil.getReqPara(req,"xmodel"); String coo_id = ProtocolUtil.getReqPara(req,"coo_id"); String xcoo_id = ProtocolUtil.getReqPara(req,"xc_coo_id"); String imei = ProtocolUtil.getReqPara(req,"imei"); String channelId = ProtocolUtil.getReqPara(req,"channelId"); String xversion = ProtocolUtil.getReqPara(req,"xversion"); String sdkversion = ProtocolUtil.getReqPara(req,"sdkversion"); String infors = ProtocolUtil.getReqPara(req,"infors"); if("1".equals(sdkversion) || "1.0".equals(sdkversion)) { sdkversion = "1"; } JSONObject inforoot = JSONObject.fromObject(infors); JSONArray pkgs = inforoot.getJSONArray("infors"); List<AdLogPackage> logPkgs = new ArrayList<AdLogPackage>(); for(int i=0; i<pkgs.size();i++) { JSONObject pkg = pkgs.getJSONObject(i); AdLogPackage logPkg = new AdLogPackage(); logPkg.setPkgid(pkg.getString("pkgid")); JSONArray logs = pkg.getJSONArray("infors"); List<AdLogInfo> logInfos = new ArrayList<AdLogInfo>(); for(int j=0; j<logs.size(); j++) { AdLogInfo log = new AdLogInfo(); JSONObject logObj = logs.getJSONObject(j); log.setApkId(logObj.getInt("apkid")); log.setSdkType(logObj.getInt("sdkType")); //广告类型 log.setDataType(logObj.getInt("dataType"));//数据类型 String sdk = logObj.getString("sdk"); //插件类型 // int sdkStyle = Constants.SDKSTYLE_SDK; // if("1".equals(sdkversion)) { // if(!ProtocolUtil.isNullOrEmpty(xcoo_id) && !"0".equals(xcoo_id)){ // sdkStyle = Constants.SDKSTYLE_DOWN; // } // // } // else { // if("3".equals(sdk)) { // sdkStyle = Constants.SDKSTYLE_GUIDE; // } // if("4".equals(sdk)) { // sdkStyle = Constants.SDKSTYLE_DOWN; // } // if("5".equals(sdk)) { // sdkStyle = Constants.SDKSTYLE_SILENCE; // } // } int sdkType = CompatibleUtil.getSDKType(sdk, sdkversion, xcoo_id); log.setSdkStyle(sdkType); logInfos.add(log); } logPkg.setInfors(logInfos); logPkgs.add(logPkg); } reqInfo.setCoo_id(coo_id); reqInfo.setChannelId(channelId); reqInfo.setImei(imei); reqInfo.setInfors(logPkgs); reqInfo.setSdkversion(sdkversion); reqInfo.setXc_coo_id(ProtocolUtil.isNullOrEmpty(xcoo_id) ? "0" : xcoo_id); reqInfo.setXmodel(xmodel); reqInfo.setXversion(xversion); JSONObject j = JSONObject.fromObject(reqInfo); logger.info(String.format("got a log: %s.", j.toString())); return reqInfo; } @Override public void process(SdkService sdkService, AreaService areaService, AdLogReq req) { // 判断该pkgId是否处理过,没处理过就塞入待保存队列 try{ if ((ProtocolUtil.isNullOrEmpty(req.getXc_coo_id())) || (ProtocolUtil.isNullOrEmpty(req.getChannelId())) || (ProtocolUtil.isNullOrEmpty(req.getCoo_id())) || (ProtocolUtil.isNullOrEmpty(req.getImei()) || req.getInfors().size() == 0)) { logger.error(String.format("log data error:%s", req.getIpaddr())); return ; } if (!ProtocolUtil.isIntegers(req.getCoo_id(), req.getXc_coo_id(), req.getChannelId(), req.getSdkversion())) { logger.error(String.format("log data is no int error:%s", req.getIpaddr())); return; } String imei=req.getImei(); String black=String.format(Constants.KEY_BLACKLIST_USER, imei); //黑名单 if(!ProtocolUtil.isNullOrEmpty(RedisTool.get(black))) { return ; } String backcount=String.format(Constants.KEY_BACK_COUNT, imei); String backshPkg=RedisTool.get(backcount); //检测数据超过50认为异常 if(ProtocolUtil.isNullOrEmpty(backshPkg)) { backshPkg="1"; RedisTool.set(backcount,"1"); RedisTool.expire(backcount, Constants.KEY_BACK_COUNT_EXPIRE); } else { RedisTool.incr(backcount); } int numInt = Integer.parseInt(backshPkg); if(numInt>50) { RedisTool.set(black,"1"); RedisTool.expire(black, 259200); logger.error(String.format("error: is black id: %s", imei)); return ; } AdProjectInfo project = CacheInfoUtil.getAdProjectInfo(sdkService, req.getCoo_id()); if(project == null) { logger.error(String.format("error: can not find project with id: %s", req.getCoo_id())); return; } // 获取国家id和国家等级 int countryId = -1; int countryLevel = 4; Country c = CacheInfoUtil.getCountry(areaService,req.getIpaddr()); if(c != null) { countryId = c.getId(); CountryLevel cl = CacheInfoUtil.getCountryLevel(sdkService, req.getCoo_id(), c.getId()); if(cl != null) { countryLevel = cl.getLevel(); } } req.setCou(countryId); req.setCountryLevel(countryLevel); req.setCdate(new Date()); for(AdLogPackage pkg : req.getInfors()){ String pkey = String.format(Constants.KEY_LOG_PKG_INFO, pkg.getPkgid()); String strPkg = RedisTool.get(pkey); if(ProtocolUtil.isNullOrEmpty(strPkg)) { RedisTool.set(pkey, pkg.getPkgid()); RedisTool.expire(pkey, Constants.KEY_LOG_PKG_INFO_EXPIRE); //expired after 3 days. // List<String> toList = new ArrayList<String>(); for(AdLogInfo logInfo : pkg.getInfors()) { AdLogData log = new AdLogData(); log.setApkid(logInfo.getApkId()); log.setCdate(CalendarFormat.getDateString(req.getCdate().getTime())); log.setChannelid(req.getChannelId()); log.setCoo_id(req.getCoo_id()); log.setCou(req.getCou()); log.setCountryLevel(req.getCountryLevel()); log.setImei(imei); log.setPkgid(pkg.getPkgid()); switch(logInfo.getSdkType()) { case 1: log.setSdk(Constants.ADTYPE_PUSH); break; case 2: log.setSdk(Constants.ADTYPE_POP); break; case 3: log.setSdk(Constants.ADTYPE_GUIDE); break; case 4: log.setSdk(Constants.ADTYPE_DOWN); break; case 5: log.setSdk(Constants.ADTYPE_SILENCE); break; } if(logInfo.getDataType() == 8){ log.setSdk(Constants.ADTYPE_SILENCE); // } log.setSdkstyle(logInfo.getSdkStyle()); log.setSdkversion(req.getSdkversion()); log.setXc_coo_id(req.getXc_coo_id()); JSONObject jsObj = JSONObject.fromObject(log); String shkey,shPkg; //dataType:展示,点击,下载成功,安装成功,引导成功,下沉成功,静默安装 激活成功(1,2,3,4,5,6,7,8) logger.info(String.format("datatype:%s, push log to redis:%s.", logInfo.getDataType(), jsObj.toString())); if(1==logInfo.getDataType()){ shkey = String.format(Constants.KEY_AD_SHOW, imei,logInfo.getApkId()); shPkg = RedisTool.get(shkey); if(ProtocolUtil.isNullOrEmpty(shPkg)) { RedisTool.set(shkey, "1"); RedisTool.expire(shkey, Constants.KEY_AD_SHOW_EXPIRE); RedisTool.lpush(Constants.KEY_LOG_SHOW_TOSAVE, jsObj.toString()); } } else if(3==logInfo.getDataType()){ shkey = String.format(Constants.KEY_AD_DOWNLOAD, imei,logInfo.getApkId()); shPkg = RedisTool.get(shkey); if(ProtocolUtil.isNullOrEmpty(shPkg)) { RedisTool.set(shkey, "1"); RedisTool.expire(shkey, Constants.KEY_AD_DOWNLOAD_EXPIRE); RedisTool.lpush(Constants.KEY_LOG_DOWNLOAD_TOSAVE, jsObj.toString()); } } else if(4==logInfo.getDataType()||5==logInfo.getDataType()||6==logInfo.getDataType()||7==logInfo.getDataType()){ shkey = String.format(Constants.KEY_AD_INSTALL, imei,logInfo.getApkId()); shPkg = RedisTool.get(shkey); if(ProtocolUtil.isNullOrEmpty(shPkg)) { RedisTool.set(shkey, "1"); RedisTool.expire(shkey, Constants.KEY_AD_INSTALL_EXPIRE); RedisTool.lpush(Constants.KEY_LOG_INSTALLED_TOSAVE, jsObj.toString()); } } else if(8==logInfo.getDataType()){ shkey = String.format(Constants.KEY_AD_ACTIVATE, imei,logInfo.getApkId()); shPkg = RedisTool.get(shkey); if(ProtocolUtil.isNullOrEmpty(shPkg)) { RedisTool.set(shkey, "1"); RedisTool.expire(shkey, Constants.KEY_AD_ACTIVATE_EXPIRE); RedisTool.lpush(Constants.KEY_LOG_ACTIVATE_TOSAVE, jsObj.toString()); } } else{ shkey = String.format(Constants.KEY_AD_CLICK, imei,logInfo.getApkId()); shPkg = RedisTool.get(shkey); if(ProtocolUtil.isNullOrEmpty(shPkg)) { RedisTool.set(shkey, "1"); RedisTool.expire(shkey, Constants.KEY_AD_CLICK_EXPIRE); RedisTool.lpush(Constants.KEY_LOG_CLICK_TOSAVE, jsObj.toString()); } } /*switch(logInfo.getDataType()) { case 1: RedisTool.lpush(Constants.KEY_LOG_SHOW_TOSAVE, jsObj.toString()); break; case 2: RedisTool.lpush(Constants.KEY_LOG_CLICK_TOSAVE, jsObj.toString()); break; case 3: RedisTool.lpush(Constants.KEY_LOG_DOWNLOAD_TOSAVE, jsObj.toString()); break; case 4: RedisTool.lpush(Constants.KEY_LOG_INSTALLED_TOSAVE, jsObj.toString()); break; case 5: RedisTool.lpush(Constants.KEY_LOG_INSTALLED_TOSAVE, jsObj.toString()); break; case 6: RedisTool.lpush(Constants.KEY_LOG_INSTALLED_TOSAVE, jsObj.toString()); break; case 7: RedisTool.lpush(Constants.KEY_LOG_INSTALLED_TOSAVE, jsObj.toString()); break; case 8: RedisTool.lpush(Constants.KEY_LOG_ACTIVATE_TOSAVE, jsObj.toString()); break; default: RedisTool.lpush(Constants.KEY_LOG_CLICK_TOSAVE, jsObj.toString()); break; }*/ } } else { logger.error(String.format("log error: the package with id %s already done.", pkg.getPkgid())); continue; } } } catch(Exception ex) { ex.printStackTrace(); } } }
true
88e3f0f8dc3e9e26d4e45722b8b8937f0cb81efa
Java
lightbatis/lightbatis
/lightbatis-core/src/main/java/titan/lightbatis/table/DataSourceTableSchemaManager.java
UTF-8
16,772
1.96875
2
[ "Apache-2.0" ]
permissive
/** * */ package titan.lightbatis.table; import com.google.common.primitives.Primitives; import com.querydsl.sql.codegen.DefaultNamingStrategy; import com.querydsl.sql.types.Type; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.*; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.lang.reflect.Field; import java.math.BigDecimal; import java.sql.*; import java.util.*; /** * 获取当前 DataSource 下相关的所有的表结构 * * @author lifei * */ @Service("tableSchemaManager") @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Slf4j public class DataSourceTableSchemaManager implements ITableSchemaManager, InitializingBean, ApplicationContextAware { @Value("${snowflake.workerId:1}") private long workerId; @Value("${snowflake.datacenterId:1}") private long datacenterId; @Value("${dal.startup.loadtable:true}") private boolean startupLoadTable = true; private static final int CATALOG_NAME = 1; private static final int SCHEMA_NAME = 2; private static final int TABLE_NAME = 3; private static final int PK_COLUMN_NAME = 4; // private static final int PK_NAME = 6; private static final int COLUMN_NAME = 4; private static final int COLUMN_TYPE = 5; private static final int COLUMN_SIZE = 7; private static final int DECIMAL_DIGITS = 9; private SnowflakeIdWorker idWorker = null; private DefaultNamingStrategy namingStrategy = new DefaultNamingStrategy(); private final JDBCTypeMapping jdbcTypeMapping = new JDBCTypeMapping(); private final JavaTypeMapping javaTypeMapping = new JavaTypeMapping(); private static final Map<Class<?>, String> class2type = new HashMap<Class<?>, String>(); static { for (Class<?> cl : new Class[] { Boolean.class, Byte.class, Double.class, Float.class, Integer.class, Long.class, Short.class, String.class }) { class2type.put(cl, cl.getSimpleName().toLowerCase(Locale.ENGLISH)); } class2type.put(Boolean.class, "bit"); class2type.put(Byte.class, "tinyint"); class2type.put(Long.class, "bigint"); class2type.put(Short.class, "smallint"); class2type.put(String.class, "varchar"); class2type.put(java.sql.Date.class, "date"); class2type.put(java.sql.Time.class, "time"); class2type.put(java.sql.Timestamp.class, "timestamp"); class2type.put(BigDecimal.class, "decimal"); } public static final String getTypeForClass(Class<?> cl) { Class<?> clazz = Primitives.wrap(cl); if (class2type.containsKey(clazz)) { return class2type.get(clazz); } else { throw new IllegalArgumentException("Got not type for " + clazz.getName()); } } // @Autowired // private DataSource dataSource = null; private ApplicationContext applicationContext = null; private HashSet<String> tableSet = new HashSet<String>(); private List<TableSchema> tables = new ArrayList<>(); private boolean loadedAllTable = false; static DataSourceTableSchemaManager manager = null; // private ITableSchemaSQLBuilder tableSchemaSQLBuilder = new // MySqlTableSchemaSQLBuilder(); /* * (非 Javadoc) * * @see titan.lightbatis.table.ITableSchemaManager#getTable(java.lang.String) */ @Override public TableSchema getTable(String tableName) { if (loadedAllTable) { Optional<TableSchema> found = tables.stream() .filter(schema -> schema.getTableName().equalsIgnoreCase(tableName)).findFirst(); if (found.isPresent()) { return found.get(); } } else { Optional<TableSchema> found = tables.stream() .filter(schema -> schema.getTableName().equalsIgnoreCase(tableName)).findFirst(); if (found.isPresent()) { return found.get(); }else { try { TableSchema schema = loadTableSchema(tableName); return schema; } catch (Exception e) { e.printStackTrace(); return null; } } } return null; } /** * */ public DataSourceTableSchemaManager() { super(); idWorker = new SnowflakeIdWorker(workerId, datacenterId); log.debug("Table Schema Manager 构建中 ..... "); } /* * (非 Javadoc) * * @see titan.lightbatis.table.ITableSchemaManager#listTables() */ @Override public List<TableSchema> listTables() { if (!loadedAllTable) { try{ loadAllTables(); }catch (Exception ex) { ex.printStackTrace(System.err); } loadedAllTable = true; } List<TableSchema> list = Collections.unmodifiableList(tables); return list; } @Override public List<TableSchema> listTables(DataSource dataSource,String dsName) { if (!loadedAllTable) { try { loadTables(dataSource, dsName); } catch (Exception e) { throw new RuntimeException(e); } loadedAllTable = true; } List<TableSchema> list = Collections.unmodifiableList(tables); return list; } @Override public void afterPropertiesSet() throws Exception { // String[] names = applicationContext.getBeanNamesForType(DataSource.class); // for (String name : names) { // DataSource dataSource = (DataSource) applicationContext.getBean(name); // try { // long start = System.currentTimeMillis(); // //loadTables(dataSource, name); // long end = System.currentTimeMillis(); // long els = (end - start) / 1000; // System.err.println("加载表结构启动用时: " + (els)); // } catch (Exception ex) { // ex.printStackTrace(System.err); // throw ex; // } // // } if (startupLoadTable) { listTables(); } DataSourceTableSchemaManager.manager = this; } public Class<?> getJavaType(int sqlType, String tableName, String columnName) { Type<?> type = javaTypeMapping.getType(tableName, columnName); if (type != null) { return type.getReturnedClass(); } return null; // else { // return jdbcTypeMapping.get(sqlType); // } } private ITableSchemaSQLBuilder getSchemaSQLBuilder(DataSource ds) throws Exception { ITableSchemaSQLBuilder tableSchemaSQLBuilder = new MySqlTableSchemaSQLBuilder(); // Connection conn = ds.getConnection(); // // DatabaseMetaData dmd = conn.getMetaData(); // String dbtype = dmd.getDatabaseProductName(); // System.out.println("dbtype = " + dbtype); return tableSchemaSQLBuilder; } private void loadAllTables() throws Exception{ String[] names = applicationContext.getBeanNamesForType(DataSource.class); for (String name : names) { DataSource dataSource = (DataSource) applicationContext.getBean(name); try { long start = System.currentTimeMillis(); loadTables(dataSource, name); long end = System.currentTimeMillis(); long els = (end - start) / 1000; System.err.println("加载表结构启动用时: " + (els)); } catch (Exception ex) { ex.printStackTrace(System.err); throw ex; } } } private TableSchema loadTableSchema(String table) throws Exception{ String[] names = applicationContext.getBeanNamesForType(DataSource.class); ResultSet rs = null; Statement stmt = null; Connection conn = null; for (String name : names) { DataSource dataSource = (DataSource) applicationContext.getBean(name); try { conn = dataSource.getConnection(); DatabaseMetaData metaData = conn.getMetaData(); String catalog = conn.getCatalog(); rs = metaData.getTables(catalog, null, table, new String[] { "TABLE"}); while (rs.next()) { String tableType = rs.getString("TABLE_TYPE"); if (!tableType.equals("TABLE")) { continue; } TableSchema schema = loadTableSchema(rs, conn, name, metaData); if (schema != null) { tables.add(schema); return schema; } } } catch (Exception ex) { ex.printStackTrace(System.err); throw ex; } finally { if (stmt != null){ stmt.close(); } if (rs != null){ rs.close(); } if (conn != null){ conn.close(); } } } return null; } private void loadTables(DataSource dataSource, String dsname) throws Exception { Connection conn = dataSource.getConnection(); ResultSet rs = null; Statement stmt = null; try { String dbschema = null; DatabaseMetaData metaData = conn.getMetaData(); String catalog = conn.getCatalog(); //String dbtype = metaData.getDatabaseProductName(); //if (StringUtils.equalsIgnoreCase(dbtype, "PostgreSQL")) { // 获取所有的表名 rs = metaData.getTables(catalog, dbschema, null, new String[] { "TABLE"}); while (rs.next()) { String tableType = rs.getString("TABLE_TYPE"); if (!tableType.equals("TABLE")) { continue; } TableSchema schema = loadTableSchema(rs, conn, dsname, metaData); tables.add(schema); } // } else { // ITableSchemaSQLBuilder tableSchemaSQLBuilder = getSchemaSQLBuilder(dataSource); // String queryTableSql = tableSchemaSQLBuilder.buildTableSQL(); // // String queryTableColumns = tableSchemaSQLBuilder.buildColumsSQL(); // stmt = conn.createStatement(); // rs = stmt.executeQuery(queryTableSql); // while (rs.next()) { // TableSchema schema = new TableSchema(); // schema.setDs(dsname); // String tableName = rs.getString("name"); // String schemaName = ""; // // String tmpName = dsname + tableName.toLowerCase(); // if (tableSet.contains(tmpName)) { // String msg = dsname + "系统中已经存在一个以上表名为 " + tmpName + "的数据表,但又没有为这个表指定数据的读写路由规则,请确认."; // System.err.println(msg); // throw new RuntimeException(msg); // } // tableSet.add(tmpName); // String common = rs.getString("Comment"); // schema.setCommon(common); // schema.setDbSchema(schemaName); // schema.setTableName(tableName); // String clzName = namingStrategy.getClassName(tableName); // schema.setEntityName(clzName); // // // ///////////////////////////// 加载Column 的信息 // ResultSet colRs = metaData.getColumns(null, "%", tableName, "%"); // while (colRs.next()) { // // String field = colRs.getString("COLUMN_NAME"); // int dataType = colRs.getInt("DATA_TYPE"); // String type = colRs.getString("TYPE_NAME"); // int nullable = colRs.getInt("NULLABLE"); // int length = colRs.getInt("COLUMN_SIZE"); // // String key = rs.getString("Key"); // String comment = colRs.getString("REMARKS"); // // ColumnSchema col = new ColumnSchema(field); // col.setCommon(comment); // col.setNullable(nullable); // col.setLength(length); // col.setPropertyName(namingStrategy.getPropertyName(field, null)); // // col.setPrimary(key.equalsIgnoreCase("PRI")); // col.setType(dataType); // col.setTypeName(type); // col.setColumnClz(JDBCTypeMapping.defaultTypes.get(dataType)); // schema.addColumn(col); // } // colRs.close(); // // 获取表的主键字段 // ResultSet keyRes = null; // try{ // keyRes = metaData.getPrimaryKeys(null, null, tableName); // while (keyRes.next()) { // String field = keyRes.getString("COLUMN_NAME"); // schema.addPrimaryKey(field); // schema.setPrimaryField(field, true); // } // // } catch (Exception ex) { // // } finally { // if (keyRes != null) // keyRes.close(); // } // // //loadTableColumns(schema, conn, tableName, tableSchemaSQLBuilder); // tables.add(schema); // } // } } finally { if (stmt != null){ stmt.close(); } if (rs != null){ rs.close(); } if (conn != null){ conn.close(); } } } private TableSchema loadTableSchema(ResultSet rs, Connection conn, String dsname, DatabaseMetaData metaData) throws SQLException{ TableSchema schema = new TableSchema(); schema.setDs(dsname); String catalog = conn.getCatalog(); String tableName = rs.getString("TABLE_NAME"); //System.out.println("=========== tableName = " + tableName); String clzName = namingStrategy.getClassName(tableName); String schemaName = conn.getSchema(); schema.setEntityName(clzName); String tmpName = dsname + tableName.toLowerCase(); if (tableSet.contains(tmpName)) { String msg = dsname + "系统中已经存在一个以上表名为 " + tmpName + "的数据表,但又没有为这个表指定数据的读写路由规则,请确认."; System.err.println(msg); //throw new RuntimeException(msg); } tableSet.add(tmpName); String common = rs.getString("REMARKS"); schema.setCommon(common); schema.setDbSchema(schemaName); schema.setTableName(tableName); ///////////////////////////// 加载Column 的信息 ResultSet colRs = metaData.getColumns(catalog, schemaName, tableName, "%"); while (colRs.next()) { String field = colRs.getString("COLUMN_NAME"); int dataType = colRs.getInt("DATA_TYPE"); String type = colRs.getString("TYPE_NAME"); int nullable = colRs.getInt("NULLABLE"); int length = colRs.getInt("COLUMN_SIZE"); // String key = rs.getString("Key"); String comment = colRs.getString("REMARKS"); ColumnSchema col = new ColumnSchema(field); col.setCommon(comment); col.setNullable(nullable); col.setLength(length); col.setPropertyName(namingStrategy.getPropertyName(field, null)); // col.setPrimary(key.equalsIgnoreCase("PRI")); col.setType(dataType); col.setTypeName(type); col.setColumnClz(JDBCTypeMapping.defaultTypes.get(dataType)); schema.addColumn(col); } colRs.close(); // 获取表的主键字段 ResultSet keyRes = metaData.getPrimaryKeys(catalog, null, tableName); while (keyRes.next()) { String field = keyRes.getString("COLUMN_NAME"); schema.addPrimaryKey(field); schema.setPrimaryField(field, true); } keyRes.close(); return schema; } private void loadTableColumns(TableSchema schema, Connection conn, String tableName, ITableSchemaSQLBuilder tableSchemaSQLBuilder) throws SQLException { String sql = tableSchemaSQLBuilder.buildColumsSQL(tableName); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { String field = rs.getString("Field"); String type = rs.getString("Type"); String nullStr = rs.getString("Null"); String key = rs.getString("Key"); String comment = rs.getString("comment"); int length = rs.getInt("COLUMN_SIZE"); ColumnSchema col = new ColumnSchema(field); col.setCommon(comment); col.setLength(length); col.setNullable(nullStr.equalsIgnoreCase("YES") ? 1 : 0); col.setPrimary(key.equalsIgnoreCase("PRI")); col.setTypeName(type); col.setPropertyName(namingStrategy.getPropertyName(field, null)); String columnClz = col.getTypeName().split("\\(")[0].toUpperCase(); if (columnClz.equals("DATETIME")) { columnClz = "TIMESTAMP"; } if (columnClz.equals("TEXT")) { columnClz = "VARCHAR"; } if (columnClz.equals("INT")) { columnClz = "INTEGER"; } Field fiel = Types.class.getDeclaredField(columnClz); int id = fiel.getInt(Types.class); col.setColumnClz(JDBCTypeMapping.defaultTypes.get(id)); schema.addColumn(col); } } catch (Exception e) { System.err.println("=============== tableName = " + tableName); e.printStackTrace(System.err); } finally { stmt.close(); rs.close(); } } /** * Set the ApplicationContext that this object runs in. Normally this call will * be used to initialize the object. * <p> * Invoked after population of normal bean properties but before an init * callback such as {@link InitializingBean#afterPropertiesSet()} or a custom * init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader}, * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and * {@link MessageSourceAware}, if applicable. * * @param applicationContext the ApplicationContext object to be used by this * object * @throws ApplicationContextException in case of context initialization errors * @throws BeansException if thrown by application context methods * @see BeanInitializationException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public Long nextId() { return idWorker.nextId(); } @Override public Long[] nextIds(int size) { Long[] ids = new Long[size]; for (int i=0; i < size; i++) { ids[i] = nextId(); } return ids; } }
true
985aaef3ead792fccf4ba7520c545cc3caf3c9f3
Java
lazx24/Java
/Kinglo/src/com/common/util/zip/FileResourceCollection.java
UTF-8
969
2.703125
3
[]
no_license
package com.common.util.zip; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.FileResource; /** * * 类的描述:文件资源集合类 * 创建人:邹建华 * 创建时间:2015-4-11 */ public final class FileResourceCollection implements ResourceCollection { List<FileResource> list = new ArrayList<FileResource>(); /** * 添加文件到集合中 * @param file File对象 */ public void add(File file) { if ((file == null) || (!file.exists())) { return; } this.list.add(new FileResource(file)); } public List<FileResource> getFileResourceList() { return this.list; } public boolean isFilesystemOnly() { return true; } public Iterator<?> iterator() { return this.list.iterator(); } public int size() { return this.list.size(); } }
true
3b229e3b8b17359551e59ca76095cfe81a2f41fc
Java
prarthnasl/FoodieApp
/iFoodieDemo/app/src/main/java/com/ifoodie/prarthnasl/ifoodiedemo/controllers/category/CategoryListActivity.java
UTF-8
4,825
2.234375
2
[]
no_license
package com.ifoodie.prarthnasl.ifoodiedemo.controllers.category; import android.graphics.Color; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.ifoodie.prarthnasl.ifoodiedemo.R; import com.ifoodie.prarthnasl.ifoodiedemo.constants.Constants; import com.ifoodie.prarthnasl.ifoodiedemo.controllers.baseControllers.BaseActivity; import com.ifoodie.prarthnasl.ifoodiedemo.controllers.baseControllers.ServerResponseInterface; import com.ifoodie.prarthnasl.ifoodiedemo.models.CategoryData; import com.ifoodie.prarthnasl.ifoodiedemo.models.CategoryResponse; import com.ifoodie.prarthnasl.ifoodiedemo.repo.CategoryRepo; import com.ifoodie.prarthnasl.ifoodiedemo.viewHelpers.category.FoodCategoryAdapter; import java.util.ArrayList; import java.util.HashMap; import fr.castorflex.android.smoothprogressbar.SmoothProgressBar; /** * Created by prarthnasl on 4/30/2016. */ public class CategoryListActivity extends BaseActivity implements ServerResponseInterface { public static final String TAG = "CategoryListActivity"; private RecyclerView foodCategoryRecyclerView; private FoodCategoryAdapter foodCategoryAdapter; private ArrayList<CategoryData> categoryArrayList = new ArrayList<>(); private String restaurantId; private SwipeRefreshLayout refreshLayout; private SmoothProgressBar smoothProgressBar; private TextView loadingTextView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.category_list_layout); restaurantId = getIntent().getStringExtra("restaurant_id"); initUI(); setListeners(); if (categoryArrayList.size() == 0) { loadCategoryList(); } } private void loadCategoryList() { smoothProgressBar.setVisibility(View.VISIBLE); loadingTextView.setVisibility(View.VISIBLE); CategoryRepo categoryRepo = new CategoryRepo(this, this); HashMap<String, String> params = new HashMap<>(); params.put(Constants.RESTAURANT_ID, restaurantId); categoryRepo.getCategories(params); } private void initUI() { loadingTextView = (TextView) findViewById(R.id.loading_text_view); smoothProgressBar = (SmoothProgressBar) findViewById(R.id.smooth_progress_bar); foodCategoryRecyclerView = (RecyclerView) findViewById(R.id.food_category_recycler_view); refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout); refreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE); } private void setListeners() { refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { categoryArrayList.clear(); loadCategoryList(); refreshLayout.setRefreshing(false); } }); } private void setRecyclerView() { foodCategoryAdapter = new FoodCategoryAdapter(this, categoryArrayList); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); foodCategoryRecyclerView.setLayoutManager(linearLayoutManager); foodCategoryRecyclerView.setAdapter(foodCategoryAdapter); foodCategoryRecyclerView.setItemAnimator(new DefaultItemAnimator()); } @Override public void onResponseSuccess(Object response) { smoothProgressBar.setVisibility(View.GONE); loadingTextView.setVisibility(View.GONE); CategoryResponse categoryResponse = (CategoryResponse) response; categoryArrayList.clear(); for (CategoryData category : categoryResponse.getResult()) { if (category != null && !category.getId().toString().isEmpty()) { categoryArrayList.add(category); } } if (categoryArrayList.size() > 0) { foodCategoryAdapter.setCategoryArrayList(categoryArrayList); foodCategoryAdapter.notifyDataSetChanged(); } } @Override public void onResponseFailure(Object response) { Toast.makeText(CategoryListActivity.this, "There was an error processing your request. Try Again", Toast.LENGTH_SHORT).show(); smoothProgressBar.setVisibility(View.GONE); loadingTextView.setVisibility(View.GONE); finish(); } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); setRecyclerView(); } }
true
e608b2aa39da25126034c0470bbbcd0e5df1c378
Java
zaiternouara/MyApplication
/app/src/main/java/com/example/myapplication/Repository/MyfileRequeteSingleton.java
UTF-8
1,273
2.375
2
[]
no_license
package com.example.myapplication.Repository; import android.app.Application; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; //pour evite a chq fois de fair connection avec le web sevice public class MyfileRequeteSingleton extends Application { private static MyfileRequeteSingleton ourInstance; Application application; private RequestQueue myRequestQueue; private MyfileRequeteSingleton(Application application) { this.application = application; } public static synchronized MyfileRequeteSingleton getInstance(Application application) { if (ourInstance == null) { ourInstance = new MyfileRequeteSingleton(application); } return ourInstance; } @Override public void onCreate() { super.onCreate(); ourInstance = this; myRequestQueue = getMyRequestQueue(); } private RequestQueue getMyRequestQueue() { if (myRequestQueue == null) { myRequestQueue = Volley.newRequestQueue(application.getApplicationContext()); } return myRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getMyRequestQueue().add(req); } }
true
a2ab9b08c924b0d3b69413bbbd1b11b71dec5f54
Java
olegmentuz1991/Day1ProjectsMentuz
/src/by/javatr/task1/util/test/Tester.java
UTF-8
889
2.5
2
[]
no_license
package by.javatr.task1.util.test; import by.javatr.task1.util.LastNumberSquareCalculation; import org.junit.Assert; import org.junit.Test; public class Tester{ @Test public void LastNumberSquareCalculation_Test_Right_Number() { int a = 3; int expected = 9; int actual = LastNumberSquareCalculation.caseNumbers(a); Assert.assertEquals(expected,actual); } @Test public void LastNumberSquareCalculation_Test_Null_Number() { int a = 0; int expected = 0; int actual = LastNumberSquareCalculation.caseNumbers(a); Assert.assertEquals(expected,actual); } @Test public void LastNumberSquareCalculation_Test_Big_Number() { int a = (int)432632456; int expected = 0; int actual = LastNumberSquareCalculation.caseNumbers(a); Assert.assertEquals(expected,actual); } }
true
22ed38136c00f2a83e3b8c78344e2c298c6fa971
Java
youyiliang/homework
/homework/src/student/Computer.java
UTF-8
562
2.953125
3
[]
no_license
package student; public class Computer extends Student { private double makeScore; private double engScore; public Computer() { } public Computer(String name,String id ,String sex, int age,double lastScore,double minScore,double makeScore,double engScore) { super(name, id ,sex ,age ,lastScore,minScore); this.engScore = engScore; this.makeScore = makeScore; } @Override public double getScore() { double score = makeScore * .4 +engScore * .2+ getLastScore()*.2 + getLastScore()*.2; return score; } }
true
0c39258782b3ed46c4f8047bf14a42eb7e9d1b8c
Java
P79N6A/icse_20_user_study
/methods/Method_44648.java
UTF-8
229
1.960938
2
[]
no_license
private static Stream<LimitOrder> adaptLimitOrders(OrderType type,BigDecimal[][] list,Date timestamp,CurrencyPair currencyPair){ return Arrays.stream(list).map(data -> adaptLimitOrder(type,data,currencyPair,null,timestamp)); }
true