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
a2c39156e886463c1389d85df8d4a1077e141dde
Java
UrgrimRock/CarRental
/src/main/java/com/RobertM/CarRental/model/entity/Reservation.java
UTF-8
1,332
2.546875
3
[]
no_license
package com.RobertM.CarRental.model.entity; import javax.persistence.*; @Entity public class Reservation { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String date; @OneToOne private User user; @OneToOne private Car car; private String fromDate; private String toDate; @ManyToOne private Base base; public Reservation() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public Base getBase() { return base; } public void setBase(Base base) { this.base = base; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getFromDate() { return fromDate; } public void setFromDate(String fromDate) { this.fromDate = fromDate; } public String getToDate() { return toDate; } public void setToDate(String toDate) { this.toDate = toDate; } }
true
7f618c75d6c56dff87da33bb68de48f14f86f36a
Java
vegazhou/billing-crm
/core/src/main/java/com/kt/sys/WafContext.java
UTF-8
724
2.03125
2
[]
no_license
package com.kt.sys; import com.kt.session.Principal; import java.util.HashMap; import java.util.Map; /** * Created by Vega Zhou on 2015/11/30. */ public class WafContext { public static final String IGNORE_MAIL = "ignore_mail"; private static ThreadLocal<Map<String, Object>> props = new ThreadLocal<Map<String, Object>>() { @Override protected Map<String, Object> initialValue() { return new HashMap<>(); } }; public static void put(String key, Object value) { props.get().put(key, value); } public static Object get(String key) { return props.get().get(key); } public static void clear() { props.get().clear(); } }
true
615b5eb6005fc3d450d083db386d489e30686d0a
Java
sunyang713/6998
/src/main/java/coms6998/fall2016/managers/Neo4jDBManager.java
UTF-8
11,050
2.625
3
[]
no_license
package coms6998.fall2016.managers; import java.util.Set; import org.neo4j.ogm.config.Configuration; import org.neo4j.ogm.config.DriverConfiguration; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import coms6998.fall2016.models.Address; import coms6998.fall2016.models.Comment; import coms6998.fall2016.models.DBReturnCode; import coms6998.fall2016.models.Episode; import coms6998.fall2016.models.Franchise; import coms6998.fall2016.models.Person; import coms6998.fall2016.models.Property; import coms6998.fall2016.models.Series; public class Neo4jDBManager implements GraphDBManager { private Session session; public Neo4jDBManager() { Configuration configuration = new Configuration(); configuration.driverConfiguration() .setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver") .setURI("http://serverless:3SqmIQ7C75bhLh6RbeJU@hobby-cbkknbeejildgbkehipmbhol.dbs.graphenedb.com:24789"); SessionFactory sessionFactory = new SessionFactory(configuration, "coms6998.fall2016.models"); session = sessionFactory.openSession(); } public static void main(String args[]){ Neo4jDBManager graphDBManager = new Neo4jDBManager(); /*Person p1 = new Person(); p1.setEmail("gaurav@gmail.com"); p1.setFirstName("gaurav"); p1.setLastName("singhal"); graphDBManager.addPerson(p1); p1 = graphDBManager.getPerson(p1.getId()); Person p2 = new Person(); p2.setEmail("gaurav2@gmail.com"); p2.setFirstName("gaurav2"); p2.setLastName("singhal"); p2.addFollows(p1); graphDBManager.addPerson(p1);*/ Person p = graphDBManager.getPerson(13).cloneRemoveRecursiveRelationship(); System.out.println(p.getFriends().size()); for(Person friend: p.getFriends()){ System.out.println(friend.getFriends().size()); } } public DBReturnCode addComment(Comment comment) { session.save(comment); return DBReturnCode.Success; } public Comment getComment(long id){ return session.load(Comment.class, id); } @Override public DBReturnCode addPerson(Person person) { session.save(person); return DBReturnCode.Success; } @Override public Person getPerson(long id) { Person person = session.load(Person.class, id); if(person.isDeleted()) { return null; } return person; } @Override public DBReturnCode deletePerson(Person person) { Person personToDelete = session.load(Person.class, person.getId()); if(personToDelete != null) { personToDelete.setDeleted(true); session.save(personToDelete); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode updatePerson(Person person) { Person personToUpdate = this.getPerson(person.getId()); if(personToUpdate != null){ if(person.getFirstName() != null && !person.getFirstName().isEmpty()){ personToUpdate.setFirstName(person.getFirstName()); } if(person.getLastName() != null && !person.getLastName().isEmpty()){ personToUpdate.setLastName(person.getLastName()); } session.save(personToUpdate); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode addProperty(Property property) { session.save(property); return DBReturnCode.Success; } @Override public Property getProperty(long id) { Property property = session.load(Property.class, id); if(property.isDeleted()) { return null; } return property; } @Override public DBReturnCode deleteProperty(Property property) { Property propertyToDelete = getProperty(property.getId()); if(propertyToDelete != null) { propertyToDelete.setDeleted(true); session.save(propertyToDelete); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode updateProperty(Property property) { Property oldProperty = session.load(Property.class, property.getId()); if(oldProperty == null || oldProperty.isDeleted()) { return DBReturnCode.NotFound; } else{ property.setName(property.getName()); } session.save(property); return DBReturnCode.Success; } @Override public DBReturnCode addFranchise(Franchise franchise) { session.save(franchise); return DBReturnCode.Success; } @Override public Franchise getFranchise(long id) { Franchise franchise = session.load(Franchise.class, id); if(franchise.isDeleted()) { return null; } return franchise; } @Override public DBReturnCode deleteFranchise(Franchise franchise) { Franchise franchiseToDelete = getFranchise(franchise.getId()); if(franchiseToDelete != null) { franchiseToDelete.setDeleted(true); session.save(franchiseToDelete); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode updateFranchise(Franchise franchise) { Franchise oldFranchise = session.load(Franchise.class, franchise.getId()); if(oldFranchise == null || oldFranchise.isDeleted()) { return DBReturnCode.NotFound; } else{ franchise.setName(franchise.getName()); } session.save(franchise); return DBReturnCode.Success; } @Override public DBReturnCode addSeries(Series series) { session.save(series); return DBReturnCode.Success; } @Override public Series getSeries(long id) { Series series = session.load(Series.class, id); if(series.isDeleted()) { return null; } return series; } @Override public DBReturnCode deleteSeries(Series series) { Series seriesToDelete = getSeries(series.getId()); if(seriesToDelete != null) { seriesToDelete.setDeleted(true); session.save(seriesToDelete); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode updateSeries(Series series) { Series oldSeries = session.load(Series.class, series.getId()); if(oldSeries == null || oldSeries.isDeleted()) { return DBReturnCode.NotFound; } else{ series.setName(series.getName()); } session.save(series); return DBReturnCode.Success; } @Override public DBReturnCode addEpisode(Episode episode) { session.save(episode); return DBReturnCode.Success; } @Override public Episode getEpisode(long id) { Episode episode = session.load(Episode.class, id); if(episode.isDeleted()) { return null; } return episode; } @Override public DBReturnCode deleteEpisode(Episode episode) { Episode episodeToDelete = getEpisode(episode.getId()); if(episodeToDelete != null) { episodeToDelete.setDeleted(true); session.save(episodeToDelete); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode updateEpisode(Episode episode) { Episode oldEpisode = session.load(Episode.class, episode.getId()); if(oldEpisode == null || oldEpisode.isDeleted()) { return DBReturnCode.NotFound; } else{ episode.setName(episode.getName()); } session.save(episode); return DBReturnCode.Success; } @Override public DBReturnCode addComment(Person person, Comment comment) { person = this.getPerson(person.getId()); if(person != null){ person.addComment(comment); session.save(person); } return DBReturnCode.NotFound; } @Override public Set<Comment> getComments(Person person) { person = this.getPerson(person.getId()); if(person != null){ return person.getComments(); } return null; } @Override public DBReturnCode deleteComment(Comment comment) { comment = this.getComment(comment.getId()); if(comment != null){ session.delete(comment); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode updateComment(Comment comment) { Comment commentToUpdate = this.getComment(comment.getId()); if(commentToUpdate != null){ if(comment.getText()!=null && !comment.getText().isEmpty()){ commentToUpdate.setText(comment.getText()); } session.save(commentToUpdate); return DBReturnCode.Success; } return DBReturnCode.NotFound; } @Override public DBReturnCode addFriend(Person p1, Person p2) { p1 = this.getPerson(p1.getId()); p2 = this.getPerson(p2.getId()); if(p1 != null && p2 != null) { p1.addFriend(p2); session.save(p1); p2.addFriend(p1); session.save(p2); return DBReturnCode.NotFound; } return DBReturnCode.Success; } @Override public Set<Person> getFriends(Person person) { person = this.getPerson(person.getId()); if(person != null){ return person.getFriends(); } return null; } @Override public DBReturnCode addFollows(Person p1, Person p2) { p1 = this.getPerson(p1.getId()); p2 = this.getPerson(p2.getId()); if(p1 != null && p2 != null) { p1.addFollows(p2); p2.addFollowedBy(p1); session.save(p1); session.save(p2); return DBReturnCode.NotFound; } return DBReturnCode.Success; } @Override public Set<Person> getFollows(Person person) { person = this.getPerson(person.getId()); if(person != null){ return person.getFollows(); } return null; } @Override public Set<Person> getFollowedBy(Person person) { person = this.getPerson(person.getId()); if(person != null){ return person.getFollowedBy(); } return null; } @Override public Set<Comment> getComments(Property property) { property = session.load(Property.class, property.getId()); if (property.isDeleted()) { return null; } return property.getComments(); } @Override public Set<Comment> getComments(Franchise franchise) { franchise = session.load(Franchise.class, franchise.getId()); if (franchise.isDeleted()) { return null; } return franchise.getComments(); } @Override public Set<Comment> getComments(Series series) { series = session.load(Series.class, series.getId()); if (series.isDeleted()) { return null; } return series.getComments(); } @Override public Set<Comment> getComments(Episode episode) { episode = session.load(Episode.class, episode.getId()); if (episode.isDeleted()) { return null; } return episode.getComments(); } @Override public DBReturnCode addComments(Comment comment, Property property) { property = session.load(Property.class, property.getId()); if (property.isDeleted()) { return null; } property.addComment(comment); session.save(property); return DBReturnCode.Success; } @Override public DBReturnCode addComments(Comment comment, Franchise franchise) { franchise = session.load(Franchise.class, franchise.getId()); if (franchise.isDeleted()) { return null; } franchise.addComment(comment); session.save(franchise); return DBReturnCode.Success; } @Override public DBReturnCode addComments(Comment comment, Series series) { series = session.load(Series.class, series.getId()); if (series.isDeleted()) { return null; } series.addComment(comment); session.save(series); return DBReturnCode.Success; } @Override public DBReturnCode addComments(Comment comment, Episode episode) { episode = session.load(Episode.class, episode.getId()); if (episode.isDeleted()) { return null; } episode.addComment(comment); session.save(episode); return DBReturnCode.Success; } }
true
0d54514e76919791708a01d5c987bd688eca11fb
Java
mschvarc/SoftwareEvolution18
/Series_1/tests/UnitSizeTest.java
UTF-8
506
2.046875
2
[]
no_license
package tests; /* module tests::UnitSizeTest import UnitSize; loc small_test_proj = |project://smallsql0.21_src|; */ public class UnitSizeTest { /** * Docblock for the function that should not be counted */ private int fiveLineFunction(int arg1) { // comment line for (int i = 0; i < 0; i++) { return 0; } // whitelines and comments don't count // or at least they shouldn't switch(arg1) { case 1: break; case 2: break; default: break; } return -1; } }
true
adb86b98b98f41785ea61386f6de9e173c9c3c19
Java
libgdx/libgdx
/extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/graphics/ParticleEmitterBox2D.java
UTF-8
4,927
2.59375
3
[ "Apache-2.0", "LicenseRef-scancode-other-copyleft", "CC-BY-SA-3.0", "LicenseRef-scancode-proprietary-license" ]
permissive
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.physics.box2d.graphics; import java.io.BufferedReader; import java.io.IOException; import com.badlogic.gdx.graphics.g2d.ParticleEmitter; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.RayCastCallback; import com.badlogic.gdx.physics.box2d.World; /** @author kalle_h * * ParticleEmitterBox2D use box2d rayCast:ing to achieve continuous collision detection against box2d fixtures. If * particle detect collision it change it's direction before actual collision would occur. Velocity is 100% reflected. * * These particles does not have any other physical attributes or functionality. Particles can't collide to other * particles. */ public class ParticleEmitterBox2D extends ParticleEmitter { final World world; final Vector2 startPoint = new Vector2(); final Vector2 endPoint = new Vector2(); /** collision flag */ boolean particleCollided; float normalAngle; /** If velocities squared is shorter than this it could lead 0 length rayCast that cause c++ assertion at box2d */ private final static float EPSILON = 0.001f; /** default visibility to prevent synthetic accessor creation */ final RayCastCallback rayCallBack = new RayCastCallback() { public float reportRayFixture (Fixture fixture, Vector2 point, Vector2 normal, float fraction) { ParticleEmitterBox2D.this.particleCollided = true; ParticleEmitterBox2D.this.normalAngle = MathUtils.atan2(normal.y, normal.x) * MathUtils.radiansToDegrees; return fraction; } }; /** Constructs default ParticleEmitterBox2D. Box2d World is used for rayCasting. Assumes that particles use same unit system * that box2d world does. * * @param world */ public ParticleEmitterBox2D (World world) { super(); this.world = world; } /** /**Constructs ParticleEmitterBox2D using bufferedReader. Box2d World is used for rayCasting. Assumes that particles use * same unit system that box2d world does. * * @param world * @param reader * @throws IOException */ public ParticleEmitterBox2D (World world, BufferedReader reader) throws IOException { super(reader); this.world = world; } /** Constructs ParticleEmitterBox2D fully copying given emitter attributes. Box2d World is used for rayCasting. Assumes that * particles use same unit system that box2d world does. * * @param world * @param emitter */ public ParticleEmitterBox2D (World world, ParticleEmitter emitter) { super(emitter); this.world = world; } @Override protected Particle newParticle (Sprite sprite) { return new ParticleBox2D(sprite); } /** Particle that can collide to box2d fixtures */ private class ParticleBox2D extends Particle { public ParticleBox2D (Sprite sprite) { super(sprite); } /** translate particle given amount. Continuous collision detection achieved by using RayCast from oldPos to newPos. * * @param velocityX * @param velocityY */ @Override public void translate (float velocityX, float velocityY) { /** If velocities squares summed is shorter than Epsilon it could lead ~0 length rayCast that cause nasty c++ assertion * inside box2d. This is so short distance that moving particle has no effect so this return early. */ if ((velocityX * velocityX + velocityY * velocityY) < EPSILON) return; /** Position offset is half of sprite texture size. */ final float x = getX() + getWidth() / 2f; final float y = getY() + getHeight() / 2f; /** collision flag to false */ particleCollided = false; startPoint.set(x, y); endPoint.set(x + velocityX, y + velocityY); if (world != null) world.rayCast(rayCallBack, startPoint, endPoint); /** If ray collided boolean has set to true at rayCallBack */ if (particleCollided) { // perfect reflection angle = 2f * normalAngle - angle - 180f; angleCos = MathUtils.cosDeg(angle); angleSin = MathUtils.sinDeg(angle); velocityX *= angleCos; velocityY *= angleSin; } super.translate(velocityX, velocityY); } } }
true
16afaeab149f602d5d77dbe1723b0581dde4f411
Java
mx0c/Mobile-Computing-SS18
/app/src/main/java/ss18/mc/positime/Overview_Week.java
UTF-8
4,648
2.171875
2
[]
no_license
package ss18.mc.positime; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import ss18.mc.positime.dbmodel.Arbeitsort; import ss18.mc.positime.dbmodel.Arbeitszeit; import ss18.mc.positime.local.BenutzerDatabase; import ss18.mc.positime.utils.Constants; import ss18.mc.positime.utils.DatabaseInitializer; import ss18.mc.positime.utils.Overview_Details_Week_Adapter; public class Overview_Week extends Fragment { View view; private static String TAG = "Overview Weeks"; BenutzerDatabase db; Overview_Details_Week_Adapter adapter; SharedPreferences mSharedPreferences; TextView month_year; String month_yearS; public String workplace; public Overview_Week(){ } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initSharedPreferences(); initDaysList(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view= inflater.inflate(R.layout.activity_overview__week, container, false); initDaysList(); return view; } private void initDaysList() { BenutzerDatabase db = BenutzerDatabase.getBenutzerDatabase(getContext()); //Temporary //DatabaseInitializer.populateSync(db); String userMail = mSharedPreferences.getString(Constants.EMAIL, null); List<Arbeitsort> workplaces = db.arbeitsortDAO().getArbeitsorteForUser(userMail); DateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); Calendar now = Calendar.getInstance(Locale.ENGLISH); Integer weekNr = now.get(Calendar.WEEK_OF_YEAR); now.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY); Date monday= now.getTime(); String mondayS= df.format(monday); now.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); Date friday= now.getTime(); String fridayS = df.format(friday); DateFormatSymbols dfs = new DateFormatSymbols(Locale.ENGLISH); String [] months =dfs.getMonths(); Integer actualMonthNumber= now.get(Calendar.MONTH); String year = " "+String.valueOf(now.get(Calendar.YEAR)); String actualMonth= months[now.get(Calendar.MONTH)]; month_yearS = actualMonth + year; Integer monthNumberStart = actualMonthNumber; now.set(Calendar.WEEK_OF_MONTH,1); now.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY) ; now.set(Calendar.HOUR_OF_DAY, 0); String monthStart= df.format(now.getTime()); if( !months[now.get(Calendar.MONTH)].equals(actualMonth)){ now.set(Calendar.MONTH, actualMonthNumber); now.set(Calendar.WEEK_OF_MONTH, 2); } Integer maxWeekCount = now.getActualMaximum(Calendar.WEEK_OF_MONTH); now.set(Calendar.WEEK_OF_MONTH, maxWeekCount); now.set(Calendar.DAY_OF_WEEK ,Calendar.FRIDAY); now.set(Calendar.HOUR_OF_DAY, 23); String monthEnd = df.format( now.getTime()); Integer monthNumerEnd = now.get(Calendar.MONTH); List<Arbeitszeit> workingTimes = db.arbeitszeitDAO().getArbeitszeitenForArbeitsortBetween(workplace, monthStart, monthEnd); Log.d(TAG, "Workplaces found for user with email " + userMail + ": " + workplaces.size()); Log.d(TAG, "Working Times found for workplace" + workplace + ": " + workplaces.size()); adapter = new Overview_Details_Week_Adapter(workingTimes, getContext(), workplace); updateUI(); } private void initSharedPreferences() { mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); } private void updateUI() { if (view == null) { // Check if view is already inflated return; } else{ month_year = view.findViewById(R.id.actual_month); month_year.setText(month_yearS); ListView lView = (ListView) view.findViewById(R.id.workplace_list_view); lView.setAdapter(adapter); } } }
true
6ad23866ed16c842edf1fd3eccc9e7117e97670d
Java
qiansheng1987/utility
/algorithm/src/main/java/com/qs/leedcode/SearchInsert.java
UTF-8
812
3.734375
4
[]
no_license
package com.qs.leedcode; /** //给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 * * @author 1987qiansheng@gmail.com * @date 2020/9/4 14:50 */ public class SearchInsert { // 输入: [1,3,5,6], 5 //输出: 2 // 输入: [1,3,5,6], 4 //输出: 2 public static void main(String[] args) { int[] nums = new int[] {1,3,5,6}; System.out.println(searchInsert(nums, 0)); } public static int searchInsert(int[] nums, int target) { int n = nums.length; int left = 0, right = n - 1, ans = n; while (left <= right) { int mid = ((right - left) >> 1) + left; if (target <= nums[mid]) { ans = mid; right = mid - 1; } else { left = mid + 1; } } return ans; } }
true
a15f74af775174d10a1fd65ae1923f5bd868048c
Java
FreemanChening/VideoTest2
/app/src/main/java/com/example/admin/videotest3/db/Video.java
UTF-8
861
2.046875
2
[]
no_license
package com.example.admin.videotest3.db; import android.provider.MediaStore; import org.litepal.crud.DataSupport; /** * Created by admin on 2017/7/3. */ public class Video extends DataSupport{ private int id; private String videouri; private String videoabout; private int good; public int getId(){ return id; } public void setId(int id){ this.id = id; } public int getGood(){ return good; } public void setGood(int good){ this.good = good; } public String getVideouri(){ return getVideouri(); } public void setVideouri(String videouri){ this.videouri = videouri; } public String getVideoabout(){ return getVideoabout(); } public void setVideoabout(String videoabout){ this.videoabout = videoabout; } }
true
da0af1d6f7e045f398c2fe3d9ad6c8015c629101
Java
fatihaydilek/mango
/src/main/java/org/jfaster/mango/page/InvocationPageHandler.java
UTF-8
2,442
2.171875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 mango.jfaster.org * * The Mango Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jfaster.mango.page; import org.jfaster.mango.binding.BoundSql; import org.jfaster.mango.binding.InvocationContext; import org.jfaster.mango.descriptor.ParameterDescriptor; import java.util.List; /** * @author ash */ public class InvocationPageHandler { private final PageHandler pageHandler; private final List<ParameterDescriptor> parameterDescriptors; public InvocationPageHandler(PageHandler pageHandler, List<ParameterDescriptor> parameterDescriptors) { this.pageHandler = pageHandler; this.parameterDescriptors = parameterDescriptors; } public void handlePageAndSort(BoundSql boundSql, InvocationContext context) { List<Object> parameterValues = context.getParameterValues(); Page page = null; Sort sort = null; for (int i = 0; i < parameterValues.size(); i++) { ParameterDescriptor pd = parameterDescriptors.get(i); if (Page.class.equals(pd.getRawType())) { Object val = parameterValues.get(i); if (val == null) { throw new IllegalArgumentException("Parameter page is null"); } page = (Page) val; } if (Sort.class.equals(pd.getRawType())) { Object val = parameterValues.get(i); if (val == null) { throw new IllegalArgumentException("Parameter sort is null"); } sort = (Sort) val; } } if (page != null & sort != null) { // Page和Sort不能同时存在 throw new IllegalArgumentException("page and sort can't be used on a query"); } if (page != null) { pageHandler.handlePage(boundSql, page); } if (sort != null) { pageHandler.handleSort(boundSql, sort); } } public void handleCount(BoundSql boundSql) { pageHandler.handleCount(boundSql); } }
true
9099376d1f0ba5f1a9c198e22ce0b245ee7c371d
Java
mohsin111/leetcode
/Java/SparseMatrixMultiplication.java
UTF-8
1,618
3.6875
4
[]
no_license
public class SparseMatrixMultiplication { //Naive soltuion. TLE. If A is m x n, B is n x t, then it is O(mnt) time. public int[][] multiply0(int[][] A, int[][] B) { if (A.length == 0 || B.length == 0) { return null; } int[][] result = new int[A.length][B[0].length]; for (int i = 0; i < result.length; ++i) { for (int j = 0; j < result[i].length; ++j) { for (int k = 0; k < A[i].length; ++k) { if (A[i][k] != 0 && B[k][j] != 0) { result[i][j] += A[i][k] * B[k][j]; } } } } return result; } //Better soltuion. If A is m x n, B is n x t, then it is O(mnt) time. //Change the order of computing products, so that when A[i][k] is zero, //skip the iteration of an entire row in B. //https://discuss.leetcode.com/topic/72871/54ms-detailed-summary-of-easiest-java-solutions-beating-99-9 public int[][] multiply(int[][] A, int[][] B) { if (A.length == 0 || B.length == 0) { return null; } int[][] result = new int[A.length][B[0].length]; for (int i = 0; i < result.length; ++i) { for (int k = 0; k < A[0].length; ++k) { if (A[i][k] != 0) { for (int j = 0; j < result[i].length; ++j) { if (B[k][j] != 0) { result[i][j] += A[i][k] * B[k][j]; } } } } } return result; } }
true
bd0923f27268e81cce2285fff2faa6885a1abf25
Java
waamande/OnlineDoctorAppointmentSystem
/OnlineDoctorAppointmentSystem/src/main/java/ca/sheridancollege/waamande/OnlineDoctorAppointmentSystemApplication.java
UTF-8
366
1.5
2
[]
no_license
package ca.sheridancollege.waamande; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OnlineDoctorAppointmentSystemApplication { public static void main(String[] args) { SpringApplication.run(OnlineDoctorAppointmentSystemApplication.class, args); } }
true
96ca062df1349ce04ca89c2c1651e66859476831
Java
drodriva/transactions
/src/main/java/com/david/transactions/service/CustomerServiceImpl.java
UTF-8
2,139
2.375
2
[]
no_license
package com.david.transactions.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.david.transactions.exception.NoDataFoundException; import com.david.transactions.model.Customer; import com.david.transactions.model.CustomerRepository; @Service @CacheConfig(cacheNames={"customerCache"}) public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerRepository customerRepository; @Cacheable @Override public Customer getCustomerById(Long id) { return customerRepository.findById(id).orElseThrow(NoDataFoundException::new); } @Cacheable @Override public Customer getCustomerByCustomerName(String customerName) { List<Customer> customerNames = customerRepository.findByCustomerNameIgnoreCase(customerName); if (customerNames.isEmpty()) { throw new NoDataFoundException(); } return customerNames.get(0); } @CachePut(key = "#customer.id") @Override public Customer saveCustomer(Customer customer) { return customerRepository.save(customer); } @CacheEvict(key="#id") @Override public void deleteCustomer(Long id) { customerRepository.deleteById(id); } @CachePut(key = "#id") @Override public Customer editCustomer(Customer customer, Long id) { final Optional<Customer> customerOptional = customerRepository.findById(id); if (!customerOptional.isPresent()) { throw new NoDataFoundException("Customer id=" + id + " not found"); } final Customer editCustomer = customerOptional.get(); editCustomer.setCustomerName(customer.getCustomerName()); editCustomer.setContactDetails(customer.getContactDetails()); return customerRepository.save(editCustomer); } @Override public List<Customer> findAllCustomers() { return customerRepository.findAll(); } }
true
5acfa69cd6eb02947b3d8ae9afe41c54a06820e9
Java
hundredin/spring-boot-jpa
/rest-api/src/main/java/com/spring/api/RestApiApplication.java
UTF-8
1,816
1.914063
2
[]
no_license
package com.spring.api; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.spring.common.CoreApplication; import com.spring.common.config.HibernateAwareObjectMapper; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; @SpringBootApplication(exclude = { AopAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, SecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }) public class RestApiApplication { public static void main(String[] args) throws Exception { new SpringApplicationBuilder() .sources(CoreApplication.class) .child(RestApiApplication.class) .run(args); } @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new HibernateAwareObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonConverter.setObjectMapper(objectMapper); return jsonConverter; } }
true
4866d71963aec6803c45085ac07f11d258389643
Java
Kaungkhant97/The-Match
/app/src/main/java/com/anglehack/thematch/thematch/adapters/PlaceViewHolder.java
UTF-8
526
2.03125
2
[]
no_license
package com.anglehack.thematch.thematch.adapters; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.anglehack.thematch.thematch.R; class PlaceViewHolder extends RecyclerView.ViewHolder { TextView textview; TextView textviewAddress; public PlaceViewHolder(View itemView) { super(itemView); textview = itemView.findViewById(R.id.txt_place_name); textviewAddress = itemView.findViewById(R.id.txt_place_address); } }
true
20fd148b5dee0426da7f40013139ad7f5ac2b2b1
Java
bellmit/Medscape-decompile
/sources/com/adobe/mobile/AnalyticsTimedAction.java
UTF-8
451
1.921875
2
[]
no_license
package com.adobe.mobile; import java.util.Map; final class AnalyticsTimedAction { protected long adjustedStartTime; protected Map<String, Object> contextData; protected int databaseID; protected long startTime; protected AnalyticsTimedAction(Map<String, Object> map, long j, long j2, int i) { this.contextData = map; this.databaseID = i; this.startTime = j; this.adjustedStartTime = j2; } }
true
701127932ef92d038f7109a8d2ebd4e778120faa
Java
Abdisalan/NEAT-MsPac-Man
/game/controllers/COMP135/Genome.java
UTF-8
8,151
3.125
3
[]
no_license
package game.controllers.COMP135; import java.util.ArrayList; import java.util.HashMap; public class Genome { public ArrayList<Gene> genes; public Network network; public int fitness = 0; public int adjustedFitness = 0; public int maxNeurons; public int globalRank; public double CONNECTIONS_MUTATION_CHANCE = 0.25; public double LINK_MUTATION_CHANCE = 2.0; public double BIAS_MUTATION_CHANCE = 0.40; public double NODE_MUTATION_CHANCE = 0.50; public double ENABLE_MUTATION_CHANCE = 0.2; public double DISABLE_MUTATION_CHANCE = 0.4; public double STEP_SIZE = 0.1; // basic genome public static Genome basicGenome() { Genome g = new Genome(); g.maxNeurons = NEAT.NUM_INPUTS; g.mutate(g); return g; } // mutates the weight of every gene public void pointMutate(Genome g) { double step = g.STEP_SIZE; for (Gene gene : g.genes) { if (Math.random() < NEAT.PERTURB_CHANCE) { gene.weight = gene.weight + (Math.random() * step * 2) - step; // WHY??? } else { gene.weight = (Math.random() * 4) - 2; // chance for negative number... } } } // creates a random link between two nodes with a weight public void linkMutate(Genome g, boolean forceBias) { int neuron1 = Neuron.randomNeuron(g.genes, false); // could contain input neuron int neuron2 = Neuron.randomNeuron(g.genes, true); // does not contain input neuron Gene newLink = new Gene(); // quit if they're both input nodes if (neuron1 <= NEAT.NUM_INPUTS && neuron2 <= NEAT.NUM_INPUTS) { return; } // quit if they're both input nodes if (neuron1 >= NEAT.MAX_NODES && neuron2 >= NEAT.MAX_NODES) { return; } // swap output and input if (neuron2 <= NEAT.NUM_INPUTS) { int tmp = neuron1; neuron1 = neuron2; neuron2 = tmp; } newLink.into = neuron1; newLink.out = neuron2; if (forceBias) newLink.into = NEAT.NUM_INPUTS - 1; if (Gene.containsLink(g.genes, newLink)) return; // don't want to repeat any nodes... newLink.innovation = 10; // TODO Make a global POOL for this newLink.weight = (Math.random()* 4) - 2; // could create negative weight g.genes.add(newLink); if (neuron2 >= NEAT.MAX_NODES) { // its an output node Neuron output = g.network.neurons.get(neuron2); output.incoming.put(output.incoming.size(), newLink); } } public void nodeMutate(Genome g) { if (g.genes.size() == 0) return; g.maxNeurons += 1; //get a random gene Gene gene1 = g.genes.get((int) (Math.random()*g.genes.size())); //give up if its not enabled if (gene1.enabled == false) return; //disable any lucky enabled gene gene1.enabled = false; //add another gene to the list Gene gene2 = new Gene(gene1); gene2.out = g.maxNeurons; gene2.weight = 1; gene2.innovation = 10; //TODO Make a global gene2.enabled = true; g.genes.add(gene2); // connect Gene gene3 = new Gene(gene1); gene3.into = g.maxNeurons; gene3.innovation = 10; //TODO Make a global gene3.enabled = true; g.genes.add(gene3); } public void enableDisableMutate(Genome g, boolean enable) { ArrayList<Gene> candidates = new ArrayList<>(); for (Gene gene : g.genes) { if (gene.enabled != enable) candidates.add(gene); } if (candidates.size() == 0) return; Gene gene1 = candidates.get((int) (Math.random() * candidates.size())); gene1.enabled = !gene1.enabled; } public void mutate(Genome g) { //adjust the mutation rate of the genome into two arbitrary buckets g.CONNECTIONS_MUTATION_CHANCE *= (Math.random() > 0.5) ? 0.95 : 1.05263; g.LINK_MUTATION_CHANCE *= (Math.random() > 0.5) ? 0.95 : 1.05263; g.BIAS_MUTATION_CHANCE *= (Math.random() > 0.5) ? 0.95 : 1.05263; g.NODE_MUTATION_CHANCE *= (Math.random() > 0.5) ? 0.95 : 1.05263; g.ENABLE_MUTATION_CHANCE *= (Math.random() > 0.5) ? 0.95 : 1.05263; g.DISABLE_MUTATION_CHANCE *= (Math.random() > 0.5) ? 0.95 : 1.05263; g.STEP_SIZE *= (Math.random() > 0.5) ? 0.95 : 1.05263; //randomly mutate everywhere if (Math.random() < g.CONNECTIONS_MUTATION_CHANCE) pointMutate(g); for (double i = g.LINK_MUTATION_CHANCE; i > 0; i--) { if (Math.random() < i) linkMutate(g, false); } for (double i = g.BIAS_MUTATION_CHANCE; i > 0; i--) { if (Math.random() < i) linkMutate(g, true); } for (double i = g.NODE_MUTATION_CHANCE; i > 0; i--) { if (Math.random() < i) nodeMutate(g); } for (double i = g.ENABLE_MUTATION_CHANCE; i > 0; i--) { if (Math.random() < i) enableDisableMutate(g, true); } for (double i = g.DISABLE_MUTATION_CHANCE; i > 0; i--) { if (Math.random() < i) enableDisableMutate(g, false); } } // constructor public Genome() { genes = new ArrayList<>(); network = new Network(this); } // deep copy constructor public Genome(Genome g) { this.genes = new ArrayList<>(); this.network = new Network(g); for (int i = 0; i < g.genes.size(); i++) { this.genes.add(new Gene(g.genes.get(i))); } //copy over network for (Integer i : g.network.neurons.keySet()) { this.network.neurons.put(i, new Neuron(g.network.neurons.get(i))); // deep copy } this.fitness = g.fitness; this.adjustedFitness = g.adjustedFitness; this.CONNECTIONS_MUTATION_CHANCE = g.CONNECTIONS_MUTATION_CHANCE; this.LINK_MUTATION_CHANCE = g.LINK_MUTATION_CHANCE; this.BIAS_MUTATION_CHANCE = g.BIAS_MUTATION_CHANCE; this.NODE_MUTATION_CHANCE = g.NODE_MUTATION_CHANCE; this.ENABLE_MUTATION_CHANCE = g.ENABLE_MUTATION_CHANCE; this.DISABLE_MUTATION_CHANCE = g.DISABLE_MUTATION_CHANCE; this.STEP_SIZE = g.STEP_SIZE; // maybe this shouldn't be copied.... } // cross over two Genomes constructor public Genome(Genome g1, Genome g2) { this.genes = new ArrayList<>(); this.network = new Network(); //make sure g1 has a higher fitness if (g2.fitness > g1.fitness) { Genome temp = g1; g1 = g2; g2 = temp; } //make a dictionary that matches the genes' innovation of g2 to the gene HashMap<Integer, Gene> innovations = new HashMap<>(); for (Gene gene2 : g2.genes) { innovations.put(gene2.innovation, new Gene(gene2)); // copy the gene or put reference?? copy it! } //distribute the genes to the child randomly from the two Genomes for (Gene gene1 : g1.genes) { Gene gene2 = innovations.get(gene1.innovation); int rand = (int) (Math.random()*2); // 50% chance for inheriting Genome1 vs Genome2 if (gene2 != null && rand == 1 && gene2.enabled) { this.genes.add(new Gene(gene2)); } else { this.genes.add(new Gene(gene1)); } } //set the maxneurons for child this.maxNeurons = Math.max(g1.maxNeurons, g2.maxNeurons); //pass over all mutation rates of more fit Genome 1 this.CONNECTIONS_MUTATION_CHANCE = g1.CONNECTIONS_MUTATION_CHANCE; this.LINK_MUTATION_CHANCE = g1.LINK_MUTATION_CHANCE; this.BIAS_MUTATION_CHANCE = g1.BIAS_MUTATION_CHANCE; this.NODE_MUTATION_CHANCE = g1.NODE_MUTATION_CHANCE; this.ENABLE_MUTATION_CHANCE = g1.ENABLE_MUTATION_CHANCE; this.DISABLE_MUTATION_CHANCE = g1.DISABLE_MUTATION_CHANCE; this.STEP_SIZE = g1.STEP_SIZE; } }
true
184e063b634e5adbc9797ca8df6cbe8faceacef0
Java
liuawen/Learning-Programming
/DesignPattern/src/main/java/ZenofDesignPatterns/isp/section2/IGreatTemperamentGirl.java
UTF-8
160
2.25
2
[]
no_license
package ZenofDesignPatterns.isp.section2; /** * 气质定义 */ public interface IGreatTemperamentGirl { //要有气质 public void greatTemperament(); }
true
03c4c5ea1ca70fd93084867cc092c8148a23ccb1
Java
1997ankit09joshi/RetrofitRailwayApi
/app/src/main/java/com/example/retrofitrailwayapi/Adapter.java
UTF-8
1,499
2.296875
2
[]
no_license
package com.example.retrofitrailwayapi; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class Adapter extends RecyclerView.Adapter<Adapter.ProgramAdapter> { private ArrayList<RouteModel.Route_> list; Context content; public Adapter(ArrayList<RouteModel.Route_> list,Context content) { this.list = list; this.content=content; } @NonNull @Override public ProgramAdapter onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); View view = inflater.inflate(R.layout.adapter, viewGroup, false); return new ProgramAdapter(view); } @Override public void onBindViewHolder(@NonNull ProgramAdapter programAdapter, int i) { RouteModel.Route_ d = list.get(i); programAdapter.textView.setText(list.get(i).getStation().getName().toString()); } @Override public int getItemCount() { return list.size(); } public class ProgramAdapter extends RecyclerView.ViewHolder { TextView textView; public ProgramAdapter(@NonNull View itemView) { super(itemView); textView=itemView.findViewById(R.id.route1); } } }
true
10708920ff109d6de720507f4eeb1c935d289fa2
Java
nielmclaren/repcounter
/src/com/danielmclaren/repcounter/MainActivity.java
UTF-8
3,148
2.46875
2
[]
no_license
package com.danielmclaren.repcounter; import io.socket.*; import java.net.MalformedURLException; import org.json.*; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.WindowManager; public class MainActivity extends Activity implements IOCallback, SensorEventListener { private static final String TAG = "MainActivity"; private SensorManager sensorManager; private Sensor accelerometer; SocketIO socket; private boolean emitEvents; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); try { socket = new SocketIO("http://192.168.0.104:3000"); socket.connect(this); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } emitEvents = false; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } protected void onResume() { super.onResume(); sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME); } protected void onPause() { super.onPause(); sensorManager.unregisterListener(this); } public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { if (emitEvents) { socket.emit( "sensorChanged", System.currentTimeMillis(), event.values[0], event.values[1], event.values[2]); } } public void onMessage(JSONObject json, IOAcknowledge ack) { try { System.out.println("Server said:" + json.toString(2)); } catch (JSONException e) { e.printStackTrace(); } } public void onMessage(String data, IOAcknowledge ack) { System.out.println("Server said: " + data); } public void onError(SocketIOException socketIOException) { System.out.println("an Error occured"); socketIOException.printStackTrace(); } public void onDisconnect() { System.out.println("Connection terminated."); } public void onConnect() { System.out.println("Connection established"); } public void on(String event, IOAcknowledge ack, Object... args) { System.out.println("Server triggered event '" + event + "'"); if (event.equals("whoIs")) { socket.emit("iAm", "reader"); } } public void toggleEvents(View view) { emitEvents = !emitEvents; if (emitEvents) { System.out.println("Emitting events."); } else { System.out.println("Stopped emitting events."); } } }
true
94ad582fbc0ce30b0d809484f090a72c9a8864bc
Java
mayc0n23/hearth-stone-api
/src/main/java/com/sistemas/tema/domain/repository/CartaRepository.java
UTF-8
529
1.859375
2
[]
no_license
package com.sistemas.tema.domain.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.sistemas.tema.domain.model.Carta; import com.sistemas.tema.domain.model.Classe; import com.sistemas.tema.domain.model.Tipo; @Repository public interface CartaRepository extends JpaRepository<Carta, Integer> { List<Carta> findByNome(String nome); List<Carta> findByTipo(Tipo tipo); List<Carta> findByClasse(Classe classe); }
true
fd36eefaa7488a11fd8584b7186bb2cfccd4134c
Java
cha63506/CompSecurity
/Entertainment/crackle_source/src/org/apache/thrift/meta_data/FieldValueMetaData.java
UTF-8
574
1.765625
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package org.apache.thrift.meta_data; import java.io.Serializable; public class FieldValueMetaData implements Serializable { public final byte type; public FieldValueMetaData(byte byte0) { type = byte0; } public boolean isContainer() { return type == 15 || type == 13 || type == 14; } public boolean isStruct() { return type == 12; } }
true
e9755ce0b840d14fd5cfb9d6b3cf5cd11df709aa
Java
Sangram1996/First-Project
/qspider/src/runtimepolymorphism/A.java
UTF-8
142
2.234375
2
[]
no_license
package runtimepolymorphism; public class A { void m1(){ System.out.println("m1 of A"); } }
true
be40c9b7a66c50f93d9c5f836bd8bb007aa9469c
Java
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/arc050/A/2173733.java
UTF-8
275
3.21875
3
[]
no_license
import java.util.Scanner; public class Main { public static void main(String[] args) { final Scanner sc = new Scanner(System.in); String s = sc.next(); String s1 = sc.next(); System.out.println(s.toLowerCase().equals(s1.toLowerCase()) ? "Yes" : "No"); } }
true
e8939633347ed6ca99cfc6eb63611d22783cd12e
Java
honeyflyfish/com.tencent.mm
/src/com/tencent/mm/kiss/d/p.java
UTF-8
500
1.671875
2
[]
no_license
package com.tencent.mm.kiss.d; public class p { public Object[] bmY; public static <$1, $2> r<$1, $2> j($1 param$1, $2 param$2) { r localr = new r(); bmY = new Object[] { param$1, param$2 }; return (r)localr; } public final <T> T get(int paramInt) { if (bmY.length <= paramInt) { return null; } return (T)bmY[paramInt]; } } /* Location: * Qualified Name: com.tencent.mm.kiss.d.p * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
66c1e683e43356b1e6a45741b4e6a1da0f4bf81f
Java
HoYuanhao/bangbanmessage
/src/main/java/com/xunyanhui/service/impl/CityServiceImpl.java
UTF-8
744
1.875
2
[]
no_license
/** * 创建日期:2017-1-12下午7:35:54 * 修改日期: * 作者:邢传军 */ package com.xunyanhui.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xunyanhui.dao.AccountDao; import com.xunyanhui.dao.CityDao; import com.xunyanhui.model.City; import com.xunyanhui.service.CityService; @Service public class CityServiceImpl implements CityService { @Autowired private CityDao cityDao; /* (non-Javadoc) * @see com.xunyanhui.service.CityService#getCityList() */ @Override public List<City> getCityList() { // TODO Auto-generated method stub return cityDao.getCityList(); } }
true
1e5faace5b916ba75558a8ac6e90a0e0c640c2b1
Java
feifeio0/Java-Programming-Language
/Review/Review_2th/src/OOP/Phone.java
UTF-8
380
3.046875
3
[]
no_license
package OOP; public class Phone { // 成员变量(属性) public String brand;// 品牌 public double price;// 价格 public String color;// 颜色 // 成员方法(行为) public void call(String who) { System.out.println("给" + who + "打电话"); } public void sendMessage(){ System.out.println("群发短信"); } }
true
80315b7f7fcbe9f26f8b5b3c9bfb6410851fdf45
Java
q1113225201/LBOX
/app/src/main/java/com/sjl/lbox/app/DesignPattern/Memento/Memento.java
UTF-8
376
2.5
2
[]
no_license
package com.sjl.lbox.app.DesignPattern.Memento; /** * Memento * * @author SJL * @date 2017/1/6 */ //备份数据 public class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
true
79d3bbe0a48b1f94aac81ad247b7d3ce58bc8b42
Java
kurtishu/Recorder
/app/src/main/java/com/dreamfactory/recorder/common/Constants.java
UTF-8
782
1.757813
2
[ "Apache-2.0" ]
permissive
package com.dreamfactory.recorder.common; import android.os.Environment; import java.io.File; public class Constants { public static final String FOLDER_URL = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Records"; public static final String RECORDING_NAME = "-recording.wav"; public static final String KEY_ACTION_RECORDING = "KEY_ACTION_RECORDING"; public static final String ACTION_START = "ACTION_RECORDING_START"; public static final String ACTION_PAUSE = "ACTION_RECORDING_PAUSE"; public static final String ACTION_RESUME = "ACTION_RECORDING_RESUME"; public static final String ACTION_STOP = "ACTION_RECORDING_STOP"; public static final String ACTIVITY_LIFECYCLE_CHANGE = "ACTIVITY_LIFECYCLE_CHANGE"; }
true
853a981032f96b709b1f4b47a825bf36b80f6ea9
Java
vagnur/LAB_SD
/SD_cache/src/sd_cache/Servidor.java
UTF-8
12,903
3.40625
3
[]
no_license
package sd_cache; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Servidor { //Se crea el cache estatico static LRUCache cacheEstatica = new LRUCache(6); //Se crean los caches dinámicos para distintos rangos de iniciales de forma de balancer cargas static LRUCache cache = new LRUCache(5); static LRUCache cache1 = new LRUCache(5); static LRUCache cache2 = new LRUCache(5); static LRUCache cache3 = new LRUCache(5); static LRUCache cache4 = new LRUCache(5); static LRUCache cache5 = new LRUCache(5); public static void main(String[] args) throws IOException { //Variables String fromClient; String resultado; String salida; //Socket para el servidor en el puerto 5000 ServerSocket acceptSocket = new ServerSocket(5000); System.out.println("Server is running...\n"); //Llenado de cache estatico cacheEstatica.addEntryToCache("BS 1", "R de CE"); cacheEstatica.addEntryToCache("BS 2", "R de CE"); cacheEstatica.addEntryToCache("BS 3", "R de CE"); cacheEstatica.addEntryToCache("BS 4", "R de CE"); cacheEstatica.addEntryToCache("BS 5", "R de CE"); cacheEstatica.addEntryToCache("BS 6", "R de CE"); while(true){ //Socket listo para recibir Socket connectionSocket = acceptSocket.accept(); //Buffer para recibir desde el cliente BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); //Buffer para enviar al cliente DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); //Recibimos el dato del cliente y lo mostramos en el server fromClient =inFromClient.readLine(); System.out.println("Received: " + fromClient); String[] tokens = fromClient.split(" "); String parametros = tokens[1]; // PARAMETROS String http_method = tokens[0]; // METODO POST O GET String[] tokens_parametros = parametros.split("="); String valor = null; if(tokens_parametros.length==2){ valor = tokens_parametros[1]; }else if(tokens_parametros.length==1 && http_method!="POST"){ http_method="GET"; } else{http_method="ERROR HTTP";} switch(http_method){ case("GET"): //Se revisa si el resultado está en la caché estática resultado = cacheEstatica.getEntryFromCache(fromClient); if(resultado!=null){//Hit en estático System.out.println("EL RESULTADO DE LA BUSQUEDA ES: "+resultado); salida = resultado+"\n"; outToClient.writeBytes(salida); } else{//Miss en estático //Se revisa en que cache se debe buscar switch(fromClient.charAt(0)){ case 'a':case 'b':case 'c':case 'd':case 'A':case 'B':case 'C':case 'D':case '1':case '2': //Se analiza el resultado resultado = cache.getEntryFromCache(fromClient); //Y se imprime System.out.println("EL RESULTADO DE LA BUSQUEDA ES: "+resultado); //Si es un miss en la cache se informa que no está y se guarda el resultado //El resultado por ahora es solo un string estático ya que no se tiene un //front service real (además así aseguro que realmente se leyó desde la cache solicitada) if(resultado==null){//MISS salida="nulo\n"; String respuesta = "R de C1"; cache.addEntryToCache(fromClient, respuesta); } //Si es un hit en la cache se envia el resultado else{//HIT salida = resultado+"\n"; } //Se le envia al cliente outToClient.writeBytes(salida); break; //Se hace el mismo procedimiento para cada cache case 'e':case 'f':case 'g':case 'h':case 'E':case 'F':case 'G':case 'H':case '3':case '4': resultado = cache1.getEntryFromCache(fromClient); System.out.println("EL RESULTADO DE LA BUSQUEDA ES: "+resultado); if(resultado==null){//MISS salida="nulo\n"; String respuesta = "R de C2"; cache1.addEntryToCache(fromClient, respuesta); } else{//HIT salida = resultado+"\n"; } //Se le envia al cliente outToClient.writeBytes(salida); break; case 'i':case 'j':case 'k':case 'l':case 'I':case 'J':case 'K':case 'L':case '5':case '6': resultado = cache2.getEntryFromCache(fromClient); System.out.println("EL RESULTADO DE LA BUSQUEDA ES: "+resultado); if(resultado==null){//MISS salida="nulo\n"; String respuesta = "R de C3"; cache2.addEntryToCache(fromClient, respuesta); } else{//HIT salida = resultado+"\n"; } //Se le envia al cliente outToClient.writeBytes(salida); break; case 'm':case 'n':case 'o':case 'p':case 'M':case 'N':case 'O':case 'P':case '7':case '8': resultado = cache3.getEntryFromCache(fromClient); System.out.println("EL RESULTADO DE LA BUSQUEDA ES: "+resultado); if(resultado==null){//MISS salida="nulo\n"; String respuesta = "R de C4"; cache3.addEntryToCache(fromClient, respuesta); } else{//HIT salida = resultado+"\n"; } //Se le envia al cliente outToClient.writeBytes(salida); break; case 'q':case 'r':case 's':case 't':case 'Q':case 'R':case 'S':case 'T':case '9': resultado = cache4.getEntryFromCache(fromClient); System.out.println("EL RESULTADO DE LA BUSQUEDA ES: "+resultado); if(resultado==null){//MISS salida="nulo\n"; String respuesta = "R de C5"; cache4.addEntryToCache(fromClient, respuesta); } else{//HIT salida = resultado+"\n"; } //Se le envia al cliente outToClient.writeBytes(salida); break; case 'u':case 'v':case 'w':case 'x':case 'y':case 'z':case 'U':case 'V':case 'W':case 'X':case 'Y':case 'Z':case '0': resultado = cache5.getEntryFromCache(fromClient); System.out.println("EL RESULTADO DE LA BUSQUEDA ES: "+resultado); if(resultado==null){//MISS salida="nulo\n"; String respuesta = "R de C6"; cache5.addEntryToCache(fromClient, respuesta); } else{//HIT salida = resultado+"\n"; } //Se le envia al cliente outToClient.writeBytes(salida); break; } } break; case("POST"): switch(fromClient.charAt(0)){ case 'a':case 'b':case 'c':case 'd':case 'A':case 'B':case 'C':case 'D':case '1':case '2': cache.addEntryToCache(fromClient, valor); salida = "Agregado con exito en Cache\n"; //Se le envia al cliente outToClient.writeBytes(salida); break; //Se hace el mismo procedimiento para cada cache case 'e':case 'f':case 'g':case 'h':case 'E':case 'F':case 'G':case 'H':case '3':case '4': cache1.addEntryToCache(fromClient, valor); salida = "Agregado con exito en Cache\n"; //Se le envia al cliente outToClient.writeBytes(salida); break; case 'i':case 'j':case 'k':case 'l':case 'I':case 'J':case 'K':case 'L':case '5':case '6': cache2.addEntryToCache(fromClient, valor); salida = "Agregado con exito en Cache\n"; //Se le envia al cliente outToClient.writeBytes(salida); break; case 'm':case 'n':case 'o':case 'p':case 'M':case 'N':case 'O':case 'P':case '7':case '8': cache3.addEntryToCache(fromClient, valor); salida = "Agregado con exito en Cache\n"; //Se le envia al cliente outToClient.writeBytes(salida); break; case 'q':case 'r':case 's':case 't':case 'Q':case 'R':case 'S':case 'T':case '9': cache4.addEntryToCache(fromClient, valor); salida = "Agregado con exito en Cache\n"; //Se le envia al cliente outToClient.writeBytes(salida); break; case 'u':case 'v':case 'w':case 'x':case 'y':case 'z':case 'U':case 'V':case 'W':case 'X':case 'Y':case 'Z':case '0': cache5.addEntryToCache(fromClient, valor); salida = "Agregado con exito en Cache\n"; //Se le envia al cliente outToClient.writeBytes(salida); break; } break; default: System.out.println("Incorrecto ingreso de metodo HTTP"); break; } } } }
true
94b7fe7baa9d606453a0da0133e3a97d8437f30c
Java
GeorgeOfSystem/PatronesDeDiseno
/src/main/java/Practica3/Ejercicio4/Client.java
UTF-8
447
2
2
[]
no_license
package Practica3.Ejercicio4; public class Client { public static void main (String [] args){ Organizador organizador = new Organizador(); organizador.answerOrder("Limpiezas"); organizador.answerOrder("Manifestaciones"); organizador.answerOrder("Desbloqueos"); organizador.answerOrder("Disciplina"); organizador.answerOrder("Entrevistas"); organizador.answerOrder("Otros"); } }
true
b7ffe693eeebc2772a276a3eb1599178b7132165
Java
shilpym7/Selenium
/SelProj/src/pro/prog2.java
UTF-8
852
2.234375
2
[]
no_license
package pro; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class prog2 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "chromedriver_v75.exe"); WebDriver dr=new ChromeDriver(); dr.get("http://examples.codecharge.com/Store/Default.php"); String tt=dr.getTitle(); if(tt.equals("Online Bookstore")) System.out.println("Title verified"); else System.out.println("Title not verified"); WebElement we=dr.findElement(By.name("category_id")); Select s1=new Select(we); s1.selectByVisibleText("Databases"); dr.findElement(By.name("DoSearch")).click(); dr.close(); } }
true
b9f8026fa56874df2efe90de9436263d9f875c7d
Java
CatastrophiClam/Java-Programs
/Useful/src/graphicsTemplates/DrawTester.java
UTF-8
1,886
3.359375
3
[]
no_license
package graphicsTemplates; import javax.swing.*; import java.awt.Graphics2D; import java.awt.*; import java.lang.Math; public class DrawTester extends JFrame{ public DrawTester(){ add(new Panel()); } public static void main(String[] args) { // TODO Auto-generated method stub DrawTester frame = new DrawTester(); frame.setTitle("Tester"); frame.setSize(519,546); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class Panel extends JPanel{ @Override protected void paintComponent(Graphics g){ super.paintComponent(g); int x = 193; int y = 150; int x1 = 250; int y1 = 50; //Graphics2D g2D = (Graphics2D) g; g.drawLine(x,y,x1,y1); g.setColor(Color.RED); //g2D.rotate(120, x, y); int[] coords; for (int i = 0; i < 120; i++){ coords = rotate(x,getHeight()-y, x1, getHeight()-y1, i); g.drawLine(x, y, coords[0], getHeight()-coords[1]); } //g.drawRect(0, 0, 500, 500); } protected int[] rotate(int x, int y, int x1, int y1, int degrees){ int newX1 = x1 - x; int newY1 = y1 - y; double lineLength = Math.sqrt(Math.pow(x1 - x, 2) + Math.pow(y1 - y, 2)); double degreesFromHorizontal = Math.toDegrees(Math.atan(newY1/newX1)); if (y1 == y){ if (newX1 < 0){ degreesFromHorizontal = 180; } } double toAngle = degrees + degreesFromHorizontal; int returnX = (int)(x + lineLength*Math.cos(Math.toRadians(toAngle))); int returnY = (int)(y + lineLength*Math.sin(Math.toRadians(toAngle))); return new int[]{returnX, returnY}; } /** * * @param x * @param y * @param x1 * @param y1 * @return returns -1 for a negative slope and 1 for a positive slope */ protected int checkSlope(int x, int y, int x1, int y1){ y = getHeight()-y; y1 = getHeight()-y1; if(x-x1 != 0 && (y-y1)/(x-x1) != 0) return ((y-y1)/(x-x1))/Math.abs((y-y1)/(x-x1)); return 1; } }
true
2651e7e498e030c88253eebd8e29dbf04744bf7c
Java
knkk0824/spring_lecture-1
/spring_REST_Reply_Board_FileUpload_Interceptor_security_mail/src/main/java/com/spring/domain/UserVO.java
UTF-8
1,408
2.203125
2
[]
no_license
package com.spring.domain; public class UserVO { private String uid; private String upwd; private String uname; private int upoint; private String enabled; private String uemail; public UserVO(){} public UserVO(String uid, String upwd, String uname, int upoint, String enabled, String uemail) { super(); this.uid = uid; this.upwd = upwd; this.uname = uname; this.upoint = upoint; this.enabled = enabled; this.uemail = uemail; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUpwd() { return upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public int getUpoint() { return upoint; } public void setUpoint(int upoint) { this.upoint = upoint; } public String getEnabled() { return enabled; } public void setEnabled(String enabled) { this.enabled = enabled; } public String getUemail() { return uemail; } public void setUemail(String uemail) { this.uemail = uemail; } @Override public String toString() { return "UserVO [uid=" + uid + ", upwd=" + upwd + ", uname=" + uname + ", upoint=" + upoint + ", enabled=" + enabled + ", uemail=" + uemail + "]"; } }
true
1566885d1f3b56932bb34ae326af6b41065cd98c
Java
readmycodetanos/HuobiCoinSMart
/upbittrade/src/main/java/com/readmycodetanos/upbittrade/bean/TradeRecord.java
UTF-8
744
2.0625
2
[]
no_license
package com.readmycodetanos.upbittrade.bean; import com.readmycodetanos.upbittrade.api.data.UpbitData; /** * ================================================ * Date:2018/10/13 * Description: * ================================================ */ public class TradeRecord { private UpbitData upbitData = new UpbitData(); private UpbitData lastUpbitData = new UpbitData(); public UpbitData getUpbitData() { return upbitData; } public void setUpbitData(UpbitData upbitData) { this.upbitData = upbitData; } public UpbitData getLastUpbitData() { return lastUpbitData; } public void setLastUpbitData(UpbitData lastUpbitData) { this.lastUpbitData = lastUpbitData; } }
true
c804bc52d53f87e87ce8d5f60eda68ed6b3bc979
Java
anhhao1996/Java_Web
/src/tdt/it/soa/models/Cart.java
UTF-8
759
2.875
3
[]
no_license
package tdt.it.soa.models; import java.util.HashMap; public class Cart { private HashMap<String, Item> cartItems; public Cart(HashMap<String, Item> cartItems) { super(); this.cartItems = cartItems; } public Cart() { cartItems = new HashMap<>(); } public HashMap<String, Item> getCartItems() { return cartItems; } public void setCartItems(HashMap<String, Item> cartItems) { this.cartItems = cartItems; } public void insertToCart(String key, Item item) { boolean value = cartItems.containsKey(key); if (value) { int quantity_old = item.getQuantity(); item.setQuantity(quantity_old + 1); cartItems.put(item.getProduct().getProductID(), item); } else { cartItems.put(item.getProduct().getProductID(), item); } } }
true
89af339eda163b01856f3b92f3805b8a0216596b
Java
jkaas/review
/src/sfirstb.java
UTF-8
553
3.046875
3
[]
no_license
public class sfirstb { public static void main(String[] args) { StringBuffer sbn = new StringBuffer("Hello world and happy new year"); StringBuffer ss = new StringBuffer(""); String s = sbn.toString(); String[] sb = s.split(" "); for (int i = 0; i < sb.length; i++) { sb[i] = sb[i].substring(0,1).toUpperCase() + sb[i].substring(1); } for (int i = 0; i < sb.length; i++) { ss.append(sb[i]); ss.append(" "); } System.out.println(ss); } }
true
c3979dc76a2384b87cc0b1ecdefcd3369b4da075
Java
pawarrahul00010/kliklinc
/src/main/java/com/technohertz/repo/UserRegisterRepository.java
UTF-8
731
2.03125
2
[]
no_license
package com.technohertz.repo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import com.technohertz.model.UserRegister; @EnableJpaRepositories("com.technohertz.repo") public interface UserRegisterRepository extends JpaRepository<UserRegister, Integer>,JpaSpecificationExecutor<UserRegister>{ @Query(value="SELECT r from UserRegister r WHERE r.Token=?1") UserRegister findByToken(Integer Token); @Query(value="SELECT r from UserRegister r WHERE r.email=?1") UserRegister findByEmail(String email); }
true
4e2f4e2f6ba5ce62f68c945e59cdf9fa9052d070
Java
vatsalvora/Drum_OOP
/src/model/SharedResources.java
UTF-8
4,493
3.03125
3
[]
no_license
package model; import model.customExceptions.NoIrrigationLeftException; import model.customExceptions.NoPalaceTilesLeft; import model.customExceptions.NoThreeBlockLeftException; import java.util.ArrayList; public class SharedResources { private Deck deck; private int numIrrigationTiles; private int numThreeBlockTiles; private int levelTwoPalace; private int levelFourPalace; private int levelSixPalace; private int levelEightPalace; private int levelTenPalace; public SharedResources() { this.deck = new Deck(); this.numIrrigationTiles = 16; this.numThreeBlockTiles = 56; levelTwoPalace = 6; levelFourPalace = 7; levelSixPalace = 8; levelEightPalace = 9; levelTenPalace = 10; } public Deck getDeck() { return deck; } public void setDeck(ArrayList<PalaceCard> list) { deck.reset(list, new ArrayList<PalaceCard>()); } public int getNumIrrigationTiles() { return numIrrigationTiles; } public int getNumThreeBlockTiles() { return numThreeBlockTiles; } public int getNumTwoPalaces() { return levelTwoPalace; } public int getNumFourPalaces() { return levelFourPalace; } public int getNumSixPalaces() { return levelSixPalace; } public int getNumEightPalaces() { return levelEightPalace; } public int getNumTenPalaces() { return levelTenPalace; } public void placeIrrigationTile() throws NoIrrigationLeftException { if(numIrrigationTiles > 0) { numIrrigationTiles--; } else { //put-in: no irrigation tiles left } } public void returnIrrigationTile() { numIrrigationTiles++; } public void placeThreeBlock() throws NoThreeBlockLeftException { if(numThreeBlockTiles > 0) { numThreeBlockTiles--; } else { throw new NoThreeBlockLeftException(); } } public void returnThreeBlock() { numThreeBlockTiles++; } public void placePalaceTile(int i) throws NoPalaceTilesLeft { switch(i) { case 2: if(levelTwoPalace > 0) { levelTwoPalace--; } else { throw new NoPalaceTilesLeft("2"); } break; case 4: if(levelFourPalace > 0) { levelFourPalace--; } else { throw new NoPalaceTilesLeft("4"); } break; case 6: if(levelSixPalace > 0) { levelSixPalace--; } else { throw new NoPalaceTilesLeft("6"); } break; case 8: if(levelEightPalace > 0) { levelEightPalace--; } else { throw new NoPalaceTilesLeft("8"); } break; case 10: if(levelTenPalace > 0) { levelTenPalace--; } else { throw new NoPalaceTilesLeft("10"); } break; default: throw new NoPalaceTilesLeft("" + i + ""); } } public void returnPalace(int i) { switch(i) { case 2: levelTwoPalace++; break; case 4: levelFourPalace++; break; case 6: levelSixPalace++; break; case 8: levelEightPalace++; break; case 10: levelTenPalace++; break; default: break; } } public PalaceCard drawCard() { return deck.drawCard(); } public void discardCard(PalaceCard c) { deck.discardCard(c); } public void returnCard(PalaceCard c) { deck.returnCard(c); } }
true
f081f8b3424b30f1874e3018d315297db72d42ea
Java
Wave39/BuildItBigger
/jokedisplaylibrary/src/main/java/com/wave39/jokedisplaylibrary/JokeDisplayActivity.java
UTF-8
1,143
2.390625
2
[]
no_license
package com.wave39.jokedisplaylibrary; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; /** * JokeDisplayActivity * Created by bp on 11/7/15. */ public class JokeDisplayActivity extends AppCompatActivity { //public final String LOG_TAG = JokeDisplayActivity.class.getSimpleName(); String theJoke; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.joke_activity); if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras == null) { theJoke = null; } else { theJoke = extras.getString(Intent.EXTRA_TEXT); } } else { theJoke = (String) savedInstanceState.getSerializable(Intent.EXTRA_TEXT); } //Log.i(LOG_TAG, "The joke is: " + theJoke); TextView textView = (TextView) this.findViewById(R.id.joke_text_view); textView.setText(theJoke); } }
true
8c7d85325e9a2cbc79860e08465d733b35f26aea
Java
MasterForCode/soliloquize-base
/src/main/java/top/soliloquize/string/StringUtils.java
UTF-8
1,062
3.328125
3
[]
no_license
package top.soliloquize.string; import top.soliloquize.validator.Validator; /** * @author wb * @date 2020/2/25 */ public class StringUtils { /** * 判断字符串的每个字符是否全相等 * * @param str 待判断字符串 * @return 判断结果 */ public static boolean isCharEqual(String str) { Validator.parameterRequireNonNull(str); if ("".equals(str)) { return true; } return str.replace(str.charAt(0), ' ').trim().length() == 0; } /** * 判断字符串的每个字符是否都是数字 * * @param str 待判断字符串 * @return 判断结果 */ public static boolean isNumeric(String str) { Validator.parameterRequireNonNull(str); for (int i = str.length(); --i >= 0; ) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } public static void main(String[] args) { System.out.println(StringUtils.isNumeric("")); } }
true
144553f237f7924ad06c51cb28e3b04736ee8fa8
Java
RobertSabadosh/Projects
/src/lesson19/CheckString.java
UTF-8
354
3.328125
3
[]
no_license
package lesson19; public class CheckString { public static void main(String[] args) { checkStringCyrillic("А роза упала на лапу Азора"); } public static void checkStringCyrillic(String s){ for (int i = 0; i < s.length(); i++) { System.out.println(s.codePointAt(i)); } } }
true
bd256654f13c16d0d004652d7288aaafebe7e668
Java
HanSJin/soma-mukja-and
/app/src/main/java/com/hansjin/mukja_android/FCM/MyFcmListenerService.java
UTF-8
2,754
2.265625
2
[]
no_license
package com.hansjin.mukja_android.FCM; import android.app.Application; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.hansjin.mukja_android.R; import com.hansjin.mukja_android.Splash.SplashActivity; import java.util.Map; /** * Created by mijeong on 2016. 11. 15.. */ public class MyFcmListenerService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage message) { /* String from = message.getFrom(); Map<String, String> data = message.getData(); String title = data.get("title"); String msg = data.get("message"); */ RemoteMessage.Notification dd = message.getNotification(); String title = dd.getTitle(); String msg = dd.getBody(); sendNotification(title, msg); } /** * 실제 디바에스에 GCM으로부터 받은 메세지를 알려주는 함수이다. 디바이스 Notification Center에 나타난다. * @param title * @param message */ private void sendNotification(String title, String message) { Intent intent = new Intent(this, SplashActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } } /* public class MyFcmListenerService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { String refreshedToken = FirebaseInstanceId.getInstance().getToken(); // 이 token을 서버에 전달 한다. } } */
true
51aa0004c3fb629d066a20aaafc5b5589551d0fb
Java
alec-liu/jo-widgets
/modules/core/org.jowidgets.validation/src/main/java/org/jowidgets/validation/Validator.java
UTF-8
3,587
1.992188
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2011, grossmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the jo-widgets.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL jo-widgets.org BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.jowidgets.validation; import java.io.Serializable; public final class Validator { @SuppressWarnings("rawtypes") private static final IValidator OK_VALIDATOR = createOkValidator(); private Validator() {} @SuppressWarnings("rawtypes") private static IValidator createOkValidator() { return new OkValidatorImpl(); } @SuppressWarnings("unchecked") public static <VALUE_TYPE> IValidator<VALUE_TYPE> okValidator() { return OK_VALIDATOR; } private static final class OkValidatorImpl<VALUE_TYPE> implements IValidator<VALUE_TYPE>, Serializable { private static final long serialVersionUID = -654830472836975532L; private final String className = OkValidatorImpl.class.getName(); @Override public IValidationResult validate(final VALUE_TYPE value) { return ValidationResult.ok(); } @Override public String toString() { return OkValidatorImpl.class.getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((className == null) ? 0 : className.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof IValidator)) { return false; } final IValidator<?> other = (IValidator<?>) obj; if (className == null) { if (other.getClass().getName() != null) { return false; } } else if (!className.equals(other.getClass().getName())) { return false; } return true; } } }
true
e2f32322b6c1ec9729041bd4f9b4f6c963ddb3b7
Java
836154942/SedentaryTips
/app/src/main/java/com/spc/sedentary/tips/database/dao/RemarkDao.java
UTF-8
3,293
2.171875
2
[]
no_license
package com.spc.sedentary.tips.database.dao; import android.content.Context; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.DeleteBuilder; import com.spc.sedentary.tips.database.helper.DBHelper; import com.spc.sedentary.tips.mvp.entity.RemarkEntity; import com.spc.sedentary.tips.utils.Constant; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by spc on 2017/3/2. */ public class RemarkDao { private Dao<RemarkEntity, Integer> frameDao; private DBHelper helper; public RemarkDao(Context context) { try { helper = DBHelper.getHelper(context); frameDao = helper.getDao(RemarkEntity.class); } catch (SQLException e) { e.printStackTrace(); } } public boolean insert(RemarkEntity entity) { try { frameDao.create(entity); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean delete(RemarkEntity entity) { try { frameDao.delete(entity); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean deleteAllComplete() { try { DeleteBuilder<RemarkEntity, Integer> workFrameEntityIntegerDeleteBuilder = frameDao.deleteBuilder(); workFrameEntityIntegerDeleteBuilder.where().eq("status", Constant.REMARK_STATUS_COMPLETE); workFrameEntityIntegerDeleteBuilder.delete(); return true; } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean update(RemarkEntity entity) { try { frameDao.update(entity); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public RemarkEntity queryForFrameId(String id) { try { List<RemarkEntity> list = frameDao.queryForEq("id", id); return list == null ? null : list.size() == 0 ? null : list.get(0); } catch (SQLException e) { e.printStackTrace(); } return null; } public List<RemarkEntity> queryForAll() { List<RemarkEntity> list = new ArrayList<>(); try { list = frameDao.queryForAll(); } catch (SQLException e) { e.printStackTrace(); } return list; } public List<RemarkEntity> queryNormalAll() { List<RemarkEntity> list = new ArrayList<>(); try { list = frameDao.queryBuilder() .orderBy("position", true) .where().eq("status", Constant.REMARK_STATUS_NORMAL) .query(); } catch (SQLException e) { e.printStackTrace(); } return list; } public List<RemarkEntity> queryCompletelAll() { List<RemarkEntity> list = new ArrayList<>(); try { list = frameDao.queryBuilder().where().eq("status", Constant.REMARK_STATUS_COMPLETE).query(); } catch (SQLException e) { e.printStackTrace(); } return list; } }
true
036a28eb8f62ef89a0d2b230fb1e6f3660ce20f0
Java
stoty/cloudbreak
/core/src/main/java/com/sequenceiq/cloudbreak/service/rdsconfig/RedbeamsDbCertificateProvider.java
UTF-8
4,057
1.875
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.sequenceiq.cloudbreak.service.rdsconfig; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.sequenceiq.cloudbreak.api.endpoint.v4.common.StackType; import com.sequenceiq.cloudbreak.domain.stack.Stack; import com.sequenceiq.cloudbreak.domain.stack.cluster.Cluster; import com.sequenceiq.cloudbreak.service.sharedservice.DatalakeService; import com.sequenceiq.cloudbreak.service.stack.StackService; import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.SslMode; import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.responses.DatabaseServerV4Response; import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.responses.SslConfigV4Response; @Service public class RedbeamsDbCertificateProvider { private static final Logger LOGGER = LoggerFactory.getLogger(RedbeamsDbCertificateProvider.class); private final RedbeamsDbServerConfigurer dbServerConfigurer; private final StackService stackService; private final DatalakeService datalakeService; private final String certsPath; public RedbeamsDbCertificateProvider(RedbeamsDbServerConfigurer dbServerConfigurer, StackService stackService, DatalakeService datalakeService, @Value("${cb.externaldatabase.ssl.rootcerts.path:}") String certsPath) { this.dbServerConfigurer = dbServerConfigurer; this.stackService = stackService; this.datalakeService = datalakeService; this.certsPath = certsPath; } public String getSslCertsFilePath() { return certsPath; } public Set<String> getRelatedSslCerts(Stack stack, Cluster cluster) { Set<String> result = new HashSet<>(); getDatalakeDatabaseRootCerts(stack, result); result.addAll(getDatabaseRootCerts(cluster)); //TODO persist the gathered certs for the cluster to support cert rotation in the future return result; } private void getDatalakeDatabaseRootCerts(Stack stack, Set<String> result) { if (StackType.WORKLOAD.equals(stack.getType())) { Optional<Stack> datalakeStack = datalakeService.getDatalakeStackByDatahubStack(stack); LOGGER.debug("Gathering datalake and its database if exists for the cluster"); if (datalakeStack.isPresent()) { Cluster dataLakeCluster = datalakeStack.get().getCluster(); result.addAll(getDatabaseRootCerts(dataLakeCluster)); } else { LOGGER.info("There is no datalake resource could be found for the cluster."); } } } private Set<String> getDatabaseRootCerts(Cluster cluster) { Set<String> result = new HashSet<>(); if (dbServerConfigurer.isRemoteDatabaseNeeded(cluster)) { String stackResourceCrn = cluster.getStack().getResourceCrn(); String clusterName = cluster.getName(); LOGGER.info("Gathering cluster's(crn:'{}', name: '{}') remote database root certificates", stackResourceCrn, clusterName); String databaseServerCrn = cluster.getDatabaseServerCrn(); DatabaseServerV4Response databaseServer = dbServerConfigurer.getDatabaseServer(databaseServerCrn); SslConfigV4Response sslConfig = databaseServer.getSslConfig(); if (sslConfig != null) { if (SslMode.isEnabled(sslConfig.getSslMode())) { Set<String> sslCertificates = sslConfig.getSslCertificates(); result.addAll(sslCertificates); LOGGER.info("Number of certificates found:'{}' for cluster(crn:'{}', name: '{}')", sslCertificates.size(), stackResourceCrn, clusterName); } } else { LOGGER.info("There no SSL config could be found for the remote database('{}').", databaseServerCrn); } } return result; } }
true
884121545bd6825f4c12482d22e1e6583e277c3f
Java
gitissosogood/cmfz
/cmfz_fjq/src/main/java/com/baizhi/entity/Chapter.java
UTF-8
870
1.992188
2
[]
no_license
package com.baizhi.entity; import cn.afterturn.easypoi.excel.annotation.Excel; import cn.afterturn.easypoi.excel.annotation.ExcelTarget; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.Table; import java.util.Date; @Data @Table(name = "t_chapter") @ExcelTarget("chapter") public class Chapter { private String id; @Excel(name = "章节名") private String title; @Excel(name = "章节大小") private String size; @Excel(name = "章节时长") private String duration; @JSONField(format = "yyyy-MM-dd HH:hh:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:hh:ss") @Excel(name = "章节上传时间", format = "yyyy-MM-dd HH:mm:ss") private Date publishDate; private String newName; private String oldName; }
true
3400eaab6099c1e355063acd166b5967d82340da
Java
IshikaJindal12/DataStructures
/DoublyLinkList_Insertion.java
UTF-8
1,462
3.96875
4
[]
no_license
class DoublyLinkList{ class Node{ int data; Node next; Node previous; public Node(int data) { this.data=data; this.next=null; this.previous=null; } } public Node head=null; public Node tail=null; public void print(){ Node current=head; if(head==null) { System.out.println("List is empty"); } else { System.out.println("Elements of the doubly linklist are: "); while(current!=null) { System.out.print(current.data+" "); current=current.next; } } } public void InsertAtBeg(int data) { Node temp=new Node(data); if(head==null) { tail=temp; } else{ head.previous=temp; } temp.next=head; head=temp; } public void InsertAtEnd(int data) { Node temp=new Node(data); if(tail==null) { head=temp; } else{ tail.next=temp; temp.previous=tail; } tail=temp; } } class Main{ public static void main(String args[]) { DoublyLinkList obj=new DoublyLinkList(); obj.InsertAtBeg(30); obj.InsertAtBeg(20); obj.InsertAtBeg(10); obj.InsertAtEnd(40); obj.print(); } }
true
04b5030e5510215f186a61721b400c659d41b329
Java
juanmbellini/genetic-algorithms
/src/main/java/ar/edu/itba/genetic_algorithms/main/customization/CrossoverParameter.java
UTF-8
3,662
2.984375
3
[]
no_license
package ar.edu.itba.genetic_algorithms.main.customization; import ar.edu.itba.genetic_algorithms.algorithms.crossover_strategies.*; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * Parameter for choosing a {@link CrossoverParameter}. */ @JsonSubTypes({@JsonSubTypes.Type(value = CrossoverParameter.NoParametersCrossover.class, name = "ONE_POINT"), @JsonSubTypes.Type(value = CrossoverParameter.NoParametersCrossover.class, name = "TWO_POINT"), @JsonSubTypes.Type(value = CrossoverParameter.UniformCrossoverParameters.class, name = "UNIFORM"), @JsonSubTypes.Type(value = CrossoverParameter.NoParametersCrossover.class, name = "ANNULAR"),}) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "strategy", visible = true) public abstract class CrossoverParameter { /** * Indicates the strategy to be used. */ @JsonProperty private CrossoverType strategy; /** * @return The {@link CrossoverStrategy} created from the sent parameters. */ @JsonIgnore public abstract CrossoverStrategy getStrategy(); /** * @return The strategy enum. */ @JsonIgnore /* package */ CrossoverType getStrategyEnum() { return strategy; } /** * Parameters for choosing any {@link CrossoverStrategy} (all of them do not need parameters) * (i.e {@link OnePointCrossover}, {@link TwoPointCrossover}, and {@link UniformCrossover}). */ /* package */ static final class NoParametersCrossover extends CrossoverParameter { // Implementation for those strategies without parameters. @Override public CrossoverStrategy getStrategy() { return getStrategyEnum().getStrategy(); } } /** * Parameters for {@link UniformCrossover} strategy. */ /* package */ static final class UniformCrossoverParameters extends CrossoverParameter { /** * The {@link UniformCrossover} "p" parameter. */ @JsonProperty private Double p; @Override public CrossoverStrategy getStrategy() { return getStrategyEnum().getStrategy(p); } } /** * Enum indicating types of crossovers. */ private enum CrossoverType { ONE_POINT { @Override public CrossoverStrategy getStrategy(Object... parameters) { return new OnePointCrossover(); } }, TWO_POINT { @Override public CrossoverStrategy getStrategy(Object... parameters) { return new TwoPointCrossover(); } }, UNIFORM { @Override public CrossoverStrategy getStrategy(Object... parameters) { return new UniformCrossover((double) parameters[0]); } }, ANNULAR { @Override protected CrossoverStrategy getStrategy(Object... parameters) { return new AnnularCrossover(); } }; /** * Returns the {@link CrossoverStrategy} being represented by the enum value. * * @param parameters The parameters needed to initialize the returned {@link CrossoverStrategy}. * @return The {@link CrossoverStrategy} being represented by the enum value. */ protected abstract CrossoverStrategy getStrategy(Object... parameters); } }
true
8b36440bca67c3d637f6a0fd6e1275cb00a15153
Java
BJdeBordeaux/finalProjetIN002
/Coach.java
UTF-8
1,707
3.234375
3
[]
no_license
public class Coach extends Personne{ //attribut // des valeurs par défaut public static final double salaireDefaut = 1; // valeurs pour une instance private double capacite; protected int addTeamCapacite = (int)(capacite / 40); //methode /*** * constructeur a partir de salaire et la capacite * @param salaire * @param capacite */ public Coach(double salaire, double capacite) // Constructeur { super(salaire); this.capacite = capacite; } /** * constructeur a partir de capacite, salaire = salaireDefaut * @param capacite */ public Coach(double capacite) // Constructeur { super(salaireDefaut); this.capacite = capacite; } /** * constructeur par défaut */ public Coach() { this(Outil.aleatoireIntEntre(50,60)); } /** * afficher des information pour l'utilisateur */ public void sePresenter() { System.out.println(this.toString()); } public void setCoachCapaciteMatch(int nbvictoire, int nbdefaite){ if(nbvictoire > nbdefaite){ this.capacite += (nbvictoire - nbdefaite)/10; } else{ this.capacite-= (nbdefaite - nbvictoire) / 10; } } //getters and setters @Override public String toString() { return "Coach [nom=" + nom + ", capacite=" + capacite + ", salaire=" + salaire + "]\n"; } public static double getSalairedefaut() { return salaireDefaut; } public double getCapacite() { return capacite; } public void setCapacite(double capacite) { this.capacite = capacite; } }
true
a4f2611f222a81b195eda23b37863c76701a55bc
Java
AlicjaCiura/TTMS-demo
/src/main/java/com/example/demo/validations/ValidationMaxSize.java
UTF-8
986
2.71875
3
[]
no_license
package com.example.demo.validations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class ValidationMaxSize { public static final int MAX_SIZE = 5; @Constraint(validatedBy = MaxSizeConstraintValidator.class) @Retention(RetentionPolicy.RUNTIME) public @interface MaxSizeConstraint { String message() default "The input list cannot contain more than 5 addresses."; Class<?>[] groups() default {}; Class<? extends String>[] payload() default {}; } public static class MaxSizeConstraintValidator implements ConstraintValidator<MaxSizeConstraint, List<String>> { @Override public boolean isValid(List<String> values, ConstraintValidatorContext context) { return values.size() <= MAX_SIZE; } } }
true
bfe86cdb5d961f16b27c7fd891e26597bb8a1f9f
Java
cjfcsjt/Budget-editing-and-reporting-system
/src/test/java/com/cjf/ysxt/dao/BudgetDaoTest.java
UTF-8
3,673
2.3125
2
[]
no_license
package com.cjf.ysxt.dao; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.cjf.ysxt.BaseTest; import com.cjf.ysxt.entity.AcquisitionTable; import com.cjf.ysxt.entity.Budget; import com.cjf.ysxt.dao.BudgetDao; public class BudgetDaoTest extends BaseTest{ @Autowired private BudgetDao budgetDao; @Test public void testQueryById() throws Exception { System.out.println("测试testQueryById"); int id = 5; Budget budget = budgetDao.queryByBudgetId(id); System.out.println(budget); } @Test public void testQueryAll() throws Exception { System.out.println("测试testQueryAll"); List<Budget> budgets = budgetDao.queryAll(0, 4); for (Budget budget : budgets) { System.out.println(budget); } } @Test public void testQueryBadStatus() throws Exception { System.out.println("测试testQueryBadStatus"); String name = "软件学院"; boolean auditResult = false; List<Budget> budgets = budgetDao.queryBadStatus(name, auditResult); for (Budget budget : budgets) { System.out.println(budget); } } @Test public void testQueryByCollegeName() throws Exception { System.out.println("测试testQueryByCollegeName"); String name = "软件学院"; List<Budget> budgets = budgetDao.queryByCollegeName(name); for (Budget budget : budgets) { System.out.println(budget); } } @Test public void testQueryByDepartmentId() throws Exception { System.out.println("测试testQueryByDepartmentId"); int id = 3; List<Budget> budgets = budgetDao.queryByDepartmentId(id); for (Budget budget : budgets) { System.out.println(budget); } } @Test public void testQueryByProjectId() throws Exception { System.out.println("测试testQueryByProjectId"); int id = 4; List<Budget> budgets = budgetDao.queryByProjectId(id); for (Budget budget : budgets) { System.out.println(budget); } } @Test public void testQueryByPDC() throws Exception { System.out.println("测试testQueryByPDC"); int projectId = 1; int departmentId = 17; String collegeName="计算机学�?"; Budget budget = budgetDao.queryByPDC(projectId, departmentId, collegeName); System.out.println(budget); } @Test public void testQueryByDC() throws Exception { System.out.println("测试testQueryByDC"); int departmentId = 1; String collegeName="软件学院"; List<Budget> budgets = budgetDao.queryByDC(departmentId, collegeName); for (Budget budget: budgets) { System.out.println(budget); } } @Test public void testInsertBudget() throws Exception { Budget budget = new Budget("软件学院",8,3,153222.151f,"测试","20180713",false); int insert = budgetDao.insertBudget(budget); System.out.println("insert=" + insert); } @Test public void testUpdate() throws Exception { boolean auditResult = false; int update = budgetDao.updateAuditResult(2, 2, "软件学院", auditResult); System.out.println("update=" + update); } @Test public void testquerySummaryBudget() throws Exception { System.out.println("testquerySummaryBudget"); String collegeName = "软件学院"; List<Budget> budgets = budgetDao.querySummaryBudget(collegeName); for(Budget budget: budgets) { System.out.println(budget); } } @Test public void queryProjectBudget() throws Exception { System.out.println("queryProjectBudget"); List<Budget> budgets = budgetDao.queryProjectBudget(); for(Budget budget: budgets) { System.out.println(budget); } } }
true
c8cae971bde8e3272f2f06bf49f135c1461608cd
Java
alesj/grapher
/modules/src/main/java/org/jboss/grapher/modules/graph/ModuleDependencyInfo.java
UTF-8
3,501
1.773438
2
[]
no_license
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.grapher.modules.graph; import org.jboss.grapher.graph.DependencyInfo; import org.jboss.grapher.graph.DependencyItem; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; /** * Module dependency info * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class ModuleDependencyInfo implements DependencyInfo<ModuleIdentifier> { private static Logger log = Logger.getLogger(ModuleDependencyInfo.class.getName()); private static Method getDependencies; private static Method getModuleIdentifier; private Module module; static { try { getDependencies = Module.class.getDeclaredMethod("getDependencies"); getDependencies.setAccessible(true); Class<?> clazz = ModuleDependencyInfo.class.getClassLoader().loadClass("org.jboss.modules.ModuleDependency"); getModuleIdentifier = clazz.getDeclaredMethod("getIdentifier"); getModuleIdentifier.setAccessible(true); } catch (Throwable t) { log.severe("Error using reflection: " + t); throw new RuntimeException(t); } } public ModuleDependencyInfo(Module module) { this.module = module; } public Set<DependencyItem<ModuleIdentifier>> getIDependOn() { try { Object[] dependecies = (Object[]) getDependencies.invoke(module); if (dependecies == null || dependecies.length == 0) return Collections.emptySet(); Set<DependencyItem<ModuleIdentifier>> modules = new HashSet<DependencyItem<ModuleIdentifier>>(dependecies.length); for (Object dependency : dependecies) { Class<?> clazz = dependency.getClass(); if (clazz.getName().contains("ModuleDependency")) { ModuleIdentifier mi = (ModuleIdentifier) getModuleIdentifier.invoke(dependency); modules.add(new ModuleDependencyItem(mi)); } } return modules; } catch (Throwable t) { throw new RuntimeException(t); } } public Set<DependencyItem<ModuleIdentifier>> getDependsOnMe() { return null; // TODO } public Set<DependencyItem<ModuleIdentifier>> getUnresolved() { return null; // TODO } }
true
fb9220745202b237d1bb10cf273b79e00d825342
Java
tobihoffmann/CG
/src/a1/Aufgabe1.java
UTF-8
992
2.390625
2
[]
no_license
package a1; import static org.lwjgl.opengl.GL30.*; import lenz.opengl.AbstractOpenGLBase; import lenz.opengl.ShaderProgram; public class Aufgabe1 extends AbstractOpenGLBase { public static void main(String[] args) { new Aufgabe1().start("CG Aufgabe 1", 700, 700); } @Override protected void init() { ShaderProgram shaderProgram = new ShaderProgram("#version 330\nlayout(location=0) in vec2 vtx;void main(){gl_Position=vec4(vtx,0.0,1.0);}", "aufgabe1.glsl"); glUseProgram(shaderProgram.getId()); glBindVertexArray(glGenVertexArrays()); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, glGenBuffers()); glBufferData(GL_ARRAY_BUFFER, new int[] { -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1 }, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_INT, false, 0, 0); } @Override public void update() { } @Override protected void render() { glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 6); } @Override public void destroy() { } }
true
10a4b74a1a6569d50cbfbccf48f9037fd694723c
Java
fmiglianico/FirstProject
/src/com/test/dao/RestaurantDAO.java
UTF-8
1,890
2.9375
3
[]
no_license
package com.test.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; public class RestaurantDAO { //Static final attributes private static final String DB_NAME = "ortva"; private static final String DB_USER = "root"; private static final String DB_PASSWORD = ""; //Singleton instance private static RestaurantDAO instance; private Properties connectionProps = null; private RestaurantDAO() { connectionProps = new Properties(); connectionProps.put("user", DB_USER); connectionProps.put("password", DB_PASSWORD); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception e) { System.err.println("Error in DBHandler constructor: " + e.getMessage()); e.printStackTrace(); } } public Connection getConn() { Connection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/" + DB_NAME, connectionProps); } catch (Exception e) { System.err.println("Error in getConn: " + e.getMessage()); e.printStackTrace(); } return conn; } public ResultSet executeQueryRS(Connection conn, String query) { Statement statement = null; ResultSet rs = null; try { statement = conn.createStatement(); rs = statement.executeQuery(query); } catch (Exception e) { System.err.println("Error in executeQueryRS:" + e.getMessage()); } return rs; } public boolean executeQuery(Connection conn, String query) { Statement statement = null; try { statement = conn.createStatement(); statement.executeUpdate(query); return true; } catch (Exception e) { System.err.println("Error in executeQuery:" + e.getMessage()); } return false; } public static RestaurantDAO getInstance() { if(instance == null) instance = new RestaurantDAO(); return instance; } }
true
03f6533a4c5a5781abad0ef8b29f59ec1ea7ea03
Java
mariamura/jsonReader
/src/main/java/Ticket.java
UTF-8
323
2.40625
2
[]
no_license
import java.util.Date; import java.util.List; public class Ticket { public List<TicketValue> tickets; public List<TicketValue> getTickets() { return tickets; } @Override public String toString() { return "Ticket{" + "tickets=" + tickets + '}'; } }
true
4bf48b8e3799d46ad6931d1fbb538f91886f2c73
Java
SamAyodeji/AttendanceSystem
/app/src/main/java/com/techview/ayodeji/attendancesystem/loginActivity.java
UTF-8
1,232
2.15625
2
[]
no_license
package com.techview.ayodeji.attendancesystem; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class loginActivity extends Activity { private EditText Name; private EditText password; private TextView Info; private Button Login; private Button Reg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Name = (EditText)findViewById(R.id.username); password = (EditText)findViewById(R.id.etPassword); Info = (TextView)findViewById(R.id.reginfo); Login = (Button)findViewById(R.id.btnLogin); Reg = (Button)findViewById(R.id.btnReg); Reg.setOnClickListener(new View.OnClickListener(){ @Override public void onClick (View v){ openregActivity(); } }); } public void openregActivity(){ Intent intent = new Intent(this, registerActivity.class); startActivity(intent); } }
true
edc8cc4f923b6b48c16f689da33a0550231f3fa5
Java
dworkin/snowman
/snowman-client/src/main/java/com/sun/darkstar/example/snowman/ClientApplication.java
UTF-8
5,096
1.945313
2
[]
no_license
/* * * Copyright (c) 2007-2010, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package com.sun.darkstar.example.snowman; import java.net.URL; import java.io.File; import com.jme.app.AbstractGame.ConfigShowMode; import com.sun.darkstar.example.snowman.client.Client; import com.sun.darkstar.example.snowman.client.handler.ClientHandler; import com.sun.darkstar.example.snowman.exception.MissingComponentException; import com.sun.darkstar.example.snowman.game.Game; /** * <code>ClientApplication</code> is the main class for the client program. * It initializes all the <code>Component</code> and starts the program. * * @author Yi Wang (Neakor) * @version Creation date: 05-23-2008 14:00 EST * @version Modified date: 06-06-2008 17:31 EST */ public class ClientApplication { /** * Main entry point of client program. * @param args Nothing needs to be passed in. */ public static void main(String[] args) throws Exception { setLibraryPath(); // Construct components. ClientHandler handler = new ClientHandler(); Client client = new Client(); Game game = new Game(); game.setConfigShowMode(ConfigShowMode.ShowIfNoConfig, (URL) null); // Establish component connections. handler.connect(game); client.connect(handler); game.connect(client); // Initialize components. try { handler.activate(); client.activate(); game.activate(); } catch (MissingComponentException e) { e.printStackTrace(); } } private static void setLibraryPath() throws Exception { if (System.getProperty("org.lwjgl.librarypath") == null) { URL jarLocation = ClientApplication.class. getProtectionDomain().getCodeSource().getLocation(); File jarFile = new File(jarLocation.toURI()); File jarDirectory = jarFile.getParentFile(); String name = System.getProperty("os.name"); String arch = System.getProperty("os.arch"); String nativeDir = ""; if ("Linux".equals(name) && "i386".equals(arch)) { nativeDir = "linux"; } else if ("Linux".equals(name) && ("x86_64".equals(arch) || "amd64".equals(arch))) { nativeDir = "linux64"; } else if ("Mac OS X".equals(name) && ("i386".equals(arch) || "x86_64".equals(arch))) { nativeDir = "macosx"; } else if ("SunOS".equals(name) && "x86".equals(arch)) { nativeDir = "solaris"; } else if (name != null && name.startsWith("Windows")) { nativeDir = "win32"; } else { throw new IllegalStateException("Unsupported platform: \n" + "Name : " + name + "\n" + "Arch : " + arch); } File nativesDirectory = new File(jarDirectory, "lib" + File.separator + "natives" + File.separator + nativeDir); System.setProperty("org.lwjgl.librarypath", nativesDirectory.getAbsolutePath()); } } }
true
fae7510fa7425195ba3e68401cb468fa0331df79
Java
kklachkou/pidor-bot
/src/main/java/by/kobyzau/tg/bot/pbot/tg/action/SendAnimationBotAction.java
UTF-8
1,172
2.375
2
[]
no_license
package by.kobyzau.tg.bot.pbot.tg.action; import by.kobyzau.tg.bot.pbot.bots.Bot; import by.kobyzau.tg.bot.pbot.util.DateUtil; import org.telegram.telegrambots.meta.api.methods.send.SendAnimation; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; public class SendAnimationBotAction implements BotAction<Message> { private final long chatId; private final String docId; public SendAnimationBotAction(long chatId, String docId) { this.chatId = chatId; this.docId = docId; } @Override public Message process(Bot bot) throws TelegramApiException { SendAnimation sendAnimation = SendAnimation.builder() .chatId(String.valueOf(chatId)) .animation(new InputFile(docId)) .disableNotification(DateUtil.sleepTime()) .build(); return bot.execute(sendAnimation); } @Override public long getChatId() { return chatId; } @Override public String toString() { return this.getClass().getSimpleName() + ": " + chatId + "-" + docId; } }
true
0ffe494c04b8fae4d59db66381df76f848a4bae7
Java
Pallava/spring-boot-rest-api
/assignment_2/src/main/java/com/wipro/pa832670/assignment_2/services/BankService.java
UTF-8
3,411
2.578125
3
[]
no_license
package com.wipro.pa832670.assignment_2.services; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; import com.wipro.pa832670.assignment_2.model.Bank; import com.wipro.pa832670.assignment_2.model.Branch; import com.wipro.pa832670.assignment_2.model.City; import com.wipro.pa832670.assignment_2.model.Services; @Service public class BankService { private static List<Bank> bankList = new ArrayList<Bank>(); private static List<City> cityList_1 = new ArrayList<City>(); private static List<City> cityList_2 = new ArrayList<City>(); private static List<Branch> branches_1 = new ArrayList<Branch>(); private static List<Branch> branches_2 = new ArrayList<Branch>(); private static List<Services> servicesList_1 = new ArrayList<Services>(); private static List<Services> servicesList_2 = new ArrayList<Services>(); static{ servicesList_1.add(new Services("Travellers Cheques")); servicesList_1.add(new Services("Credit Card")); servicesList_1.add(new Services("Home Loan")); servicesList_1.add(new Services("Personal loan")); } static{ servicesList_2.add(new Services("Cheque Deposits")); servicesList_2.add(new Services("remittance")); servicesList_2.add(new Services("Mutual funds")); servicesList_2.add(new Services("Insurance")); } static{ branches_1.add(new Branch("JP Nagar")); branches_1.add(new Branch("BTM Layout")); branches_1.add(new Branch("Sarjapura")); branches_1.add(new Branch("Electronic city")); branches_1.add(new Branch("Basaweshwara Nagara")); branches_1.add(new Branch("Banashankari")); branches_1.add(new Branch("Kodathi")); branches_1.add(new Branch("HRBR Layout")); branches_1.add(new Branch("Rajarajeshwari Nagara")); branches_1.add(new Branch("Koramangala")); } static{ branches_2.add(new Branch("Dadar")); branches_2.add(new Branch("Kalina")); branches_2.add(new Branch("Nariman bhavan")); branches_2.add(new Branch("Zaveri")); branches_2.add(new Branch("Andheri")); branches_2.add(new Branch("Mazgaon")); branches_2.add(new Branch("Bandra")); branches_2.add(new Branch("Nana chowk")); branches_2.add(new Branch("Santacruz")); branches_2.add(new Branch("Borivali")); } static{ cityList_1.add(new City("Bangalore", branches_1)); cityList_2.add(new City("Mumbai", branches_2)); } static{ bankList.add(new Bank("HDFC",cityList_1,servicesList_1)); bankList.add(new Bank("ICICI",cityList_2,servicesList_2)); } public List<String> getAllBankNames() { List<String> banks = new ArrayList<String>(); for (Bank bank : bankList) { banks.add(bank.getBankName()); } return banks; } public List<Branch> getAllBranches(String bankName) { List<Branch> branches = new ArrayList<Branch>(); for (Bank bank : bankList) { if(bank.getBankName().equalsIgnoreCase(bankName)) { List<City> cities = bank.getCities(); for (City city : cities) { for (Branch branch : city.getBranches()) { branches.add(branch); } } } } return branches; } public List<Services> getServicesOfBank(String bankName) { List<Services> services = new ArrayList<Services>(); for (Bank bank : bankList) { if(bank.getBankName().equalsIgnoreCase(bankName)) { return bank.getServiceList(); } } return services; } }
true
e052aa3ccc0ca43c872cd3aadb83bd7007cd9f9c
Java
manishabajracharya/algorithm_practice
/minimum_num_after_removing_digit.java
UTF-8
2,026
4.09375
4
[]
no_license
/* Build Lowest Number by Removing n digits from a given number Given a string ‘str’ of digits and an integer ‘n’, build the lowest possible number by removing ‘n’ digits from the string and not changing the order of input digits. Examples: Input: str = "4325043", n = 3 Output: "2043" Input: str = "765028321", n = 5 Output: "0221" Input: str = "121198", n = 2 Output: "1118" Idea: instead of thinking which one to remove, think which one will be in result. We need to pick the first number in the result. steps for last example "856394789" 1) what can the result start from: 8, 5, 6, 3 . this mean, if we start from "3" , it implies previous 3 digits are deleted. so pick the maximum from 8, 5, 6 to minimize the output num value. we pick 8. 2) now S= 56394789, d=2. what can the result start from: 5, 6, 3 . this mean, if we start from "3" , it implies previous 2 digits are deleted. so pick the maximum from 5, 6 to minimize the output num value. we pick 6. 3) now S= 5394789, d=1. what can the result start from: 5, 3 . this mean, if we start from "3" , it implies previous 1 digits are deleted. so pick the maximum from 5 to minimize the output num value. we pick 5. 4) now S=394789, d=0. we cannot delete any more as d=0. This is the result. */ public class practice{ String min_num(String num, int digit, String result_prefix){ if(digit>=num.length()){ return result_prefix; } if(digit==0){ return result_prefix+num; } int min=Integer.MAX_VALUE; int min_index=0; for(int i=min_index;i<=digit;i++){ int each_value = Character.getNumericValue(num.charAt(i)); if(each_value<min){ min=each_value; min_index=i; } } return min_num(num.substring(min_index+1,num.length()),digit-min_index,result_prefix+num.charAt(min_index)); } public static void main(String[] args){ practice obj = new practice(); String s1="4325043"; int d1=3; String s2="765028321"; int d2=5; String s3="121198"; int d3=2; System.out.println(obj.min_num(s3,d3,"")); } }
true
cfc666e3de943118b6679554708eaf40e329bfb3
Java
suevip/FintechSearch
/src/main/java/com/tracy/task/service/SearchService.java
UTF-8
3,257
2.15625
2
[]
no_license
package com.tracy.task.service; import com.tracy.task.base.CommonUtils; import com.tracy.task.dbconfig.ITaskBaseService; import com.tracy.task.model.BaseEs; import com.tracy.task.model.FinTechArticle; import com.tracy.task.model.FinTechArticleEs; import com.tracy.task.repositories.ArticleRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * Created by lurenjie on 2017/1/7 */ @Slf4j @Service public class SearchService { @Resource private ITaskBaseService taskBaseService; @Resource private ElasticsearchTemplate elasticsearchTemplate; @Resource private ArticleRepository articleRepository; /** * 创建索引 */ public <T> boolean builderSearchIndex(Class<T> obj) throws Exception { return elasticsearchTemplate.createIndex(obj); } /** * 删除索引 * * @param obj 类型 */ public <T> boolean deleteIndex(Class<T> obj) throws Exception { return elasticsearchTemplate.deleteIndex(obj); } /** * 刷新数据到es * * @param obj 需要刷新的obj */ public void refreshData(List<FinTechArticleEs> obj, String type) { if (StringUtils.isEmpty(obj) || StringUtils.isEmpty(type)) { throw new IllegalArgumentException("刷新参数不能为空"); } List<IndexQuery> indexQueries = new ArrayList<>(obj.size()); elasticsearchTemplate.putMapping(FinTechArticleEs.class); elasticsearchTemplate.refresh(FinTechArticleEs.class); Document annotation = FinTechArticleEs.class.getAnnotation(Document.class); if (annotation == null) { throw new RuntimeException("实体类中必须包含Document注解"); } String indexName = annotation.indexName(); if (StringUtils.isEmpty(indexName)) { throw new RuntimeException("Document注解中必须包含indexName"); } for (FinTechArticleEs item : obj) { articleRepository.save(item); } elasticsearchTemplate.refresh(FinTechArticleEs.class); } public void refreshAndUpdate(FinTechArticle finTechArticle) { FinTechArticleEs finTechArticleEs = CommonUtils.convertFinTech2Es(finTechArticle); articleRepository.save(finTechArticleEs); finTechArticle.setIsNotify(true); taskBaseService.update(finTechArticle); } /** * 根据关键词检索 * * @param word 关键词 */ public Page<FinTechArticleEs> searchInfo(String word, Integer index) throws Exception { return articleRepository.findByTitleOrContent(word, word, new PageRequest(index, 10)); } }
true
b9d2c9f36fb75d65df25dfcaf95a0b01815942b6
Java
breezedu/LeetCode2012
/NextPermutation.java
WINDOWS-1252
3,242
4.09375
4
[]
no_license
package leetCode2012; import java.util.Arrays; import java.util.Scanner; /****************** * Implement next permutation, which rearranges numbers * into the lexicographically next greater permutation of numbers. * If such arrangement is not possible, it must rearrange it as the lowest possible order * (ie, sorted in ascending order). * The replacement must be in-place, do not allocate extra memory. * Here are some examples. Inputs are in the left-hand column and * its corresponding outputs are in the right-hand column. * * 1,2,3 1,3,2 * 3,2,1 1,2,3 * 1,1,5 1,5,1 * * @author Frog * */ public class NextPermutation { public static void main(String[] args){ System.out.println("This is Next Permutation program."); //1st, create an array of num elements; int[] array = createArray(); //int[] array = {4,2,0,2,3,2,0}; //int[] array = {2, 3, 1}; printArray(array); //2nd, take the array as an permutation arrange; calculate the next permutation; nextPermutation(array); System.out.println("After the NextPermutation operation."); printArray(array); }//end main(); /*********** * from the end index i to the front index j, find out the first pair * array[j] < array[i], check the right part of index i, if any element at k * array[k] > array[j]: swap array[j] and array[k]; and sort the right part of k; * * if no such pair exist, swap the whole array back forward; * @param array */ private static void nextPermutation(int[] array) { // TODO get the 'next' permutation of the original array if(array == null || array.length==1) return; int Len = array.length; int sortIndex = 0; //at this point the array needs reverse; for(int i=Len-1; i>0; i--){ int j = i-1; if(array[i] > array[j]){ for(int k=array.length-1; k>j; k--){ if(array[k] > array[j]){ swap(array, k, j); sortIndex = i; k=j=i=0; //jump out of both for loop; } }//end for k>j loop; }//end if array[i]>array[j] condition; }//end outer for i>0 loop; //last step, sort the array from index[k] to the end; Arrays.sort(array, sortIndex, array.length); }//end nextPermutation() method; private static void swap(int[] array, int i, int j) { // TODO swap two elements in an array int temp = array[i]; array[i] = array[j]; array[j] = temp; }//end swap() method; private static int[] createArray(){ // TODO create an array System.out.println("PLease input the num of elements in the array."); Scanner input = new Scanner(System.in); System.out.print(" num = "); int num = input.nextInt(); input.close(); if(num == 0) return null; int[] array = new int[num]; for(int i=0; i<num; i++){ array[i] = (int)(Math.random()*10); } return array; }//end createArray() method; private static void printArray(int[] array) { // TODO Printout an array if(array == null){ System.out.println("It's an empty array."); return; } int Len = array.length; for(int i=0; i<Len; i++){ System.out.print(" " + array[i]); } System.out.println(); }//end of printArray() method; }//end of everything in NextPermutation class
true
e886a72b4838d6c18e273fa44b3d3273ec56e08f
Java
jelem/capella
/task_18/sergey.bendas/src/main/java/com/hillel/task2/CustomArrayList.java
UTF-8
3,378
3.34375
3
[]
no_license
package com.hillel.task2; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; public class CustomArrayList implements CustomList { private static final int BASE_LEN = 10; private String[] array; private int size; private int startLen; public CustomArrayList() { this(BASE_LEN); } public CustomArrayList(int capacity) { array = new String[capacity]; startLen = capacity; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public boolean contains(String element) { for (int i = 0; i < size; i++) { if (array[i].equals(element)) { return true; } } return false; } @Override public void add(String element) { checkArraySize(); array[size] = element; size++; } @Override public void add(int index, String element) { checkSuchElementException(index); checkArraySize(); System.arraycopy(array, index, array, index + 1, size - index); array[index] = element; size++; } @Override public boolean remove(String element) { if (!contains(element)) { return false; } int index = indexOf(element); size--; System.arraycopy(array, index + 1, array, index, size - index); checkArraySize(); return true; } @Override public String remove(int index) { String element = get(index); size--; System.arraycopy(array, index + 1, array, index, size - index); return element; } @Override public void clear() { array = new String[startLen]; size = 0; } @Override public String get(int index) { checkSuchElementException(index); return array[index]; } @Override public void set(int index, String element) { checkSuchElementException(index); array[index] = element; } @Override public int indexOf(String element) { for (int i = 0; i < size; i++) { if (array[i].equals(element)) { return i; } } throw new NoSuchElementException(); } private void checkArraySize() { if (size >= array.length) { enlargeArray(); return; } if (size >= 2 * startLen && size < array.length >> 2) { reduceArray(); } } private void reduceArray() { String[] newArray = new String[array.length >> 1]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } private void enlargeArray() { String[] newArray = new String[array.length * 2]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } private void checkSuchElementException(int index) { if (index < 0 || index > size) { throw new NoSuchElementException(); } } @Override public RandomListIterator iterator() { return new RandomListIterator(); } private class RandomListIterator implements Iterator { private ArrayList<Integer> list; private int current; RandomListIterator() { list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(i); } Collections.shuffle(list); current = 0; } @Override public boolean hasNext() { return current < size; } @Override public Object next() { return array[list.get(current++)]; } } }
true
72244331db817fb792af0aac5c7cf4db34d01c00
Java
fengyts/yiyuan
/bayue/parent/common-util/src/main/java/ng/bayue/service/impl/ImageDownload.java
UTF-8
1,929
2.265625
2
[]
no_license
package ng.bayue.service.impl; import java.io.IOException; import java.util.Map; import ng.bayue.fastdfs.ImageUrlUtil; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; /** * <pre> * 图片下载地址生成组件,用于ftp页面当中生成图片路径 * </pre> * * @author fengyts * @version $Id: ImageDownload.java, v 0.1 2016年7月25日 下午12:00:30 fengyts Exp $ */ public class ImageDownload implements TemplateDirectiveModel { @Autowired private ImageUrlUtil imageUrlUtil; @SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // 图片key Object codeObj = params.get("code"); // 图片宽度 Object width = params.get("width"); if (codeObj == null) { } else { String code = codeObj.toString(); if (code.indexOf("http://") != -1) { env.getOut().write(code); } else { Integer w = null; if (null != width) { w = Integer.valueOf(width.toString()); } if (w == null) { String group = imageUrlUtil.getStartGroups().get(0); String domain = imageUrlUtil.getDomainMap().get(group); if (StringUtils.isNotBlank(domain)) { String[] domainArr = domain.split(","); domain = domainArr[0]; } System.out.println(domain); if (domain.indexOf("http://") != -1) { env.getOut().write(domain + "/" + code); } else { env.getOut().write("http://" + domain + "/" + code); } return; } String result = imageUrlUtil.getSnapshotUrl(code, w); env.getOut().write(result); } } } }
true
3f432d13484fbe93b148aff94caf1b81e7e0e290
Java
chenjiajiabianmi/wc
/src/crawler/moeyo/ListPageExtractor.java
UTF-8
3,015
2.4375
2
[]
no_license
package crawler.moeyo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import persistence.entity.PageInfo; import persistence.entity.base.BaseModel; import crawler.base.Extractor; import crawler.entity.base.ExtractedElements; import crawler.entity.base.SeedElement; public class ListPageExtractor extends Extractor{ private static final Logger logger = Logger.getLogger(ListPageExtractor.class); private final static Object syncLock = new Object(); private static ListPageExtractor extractor; private ListPageExtractor() { } public static ListPageExtractor getExtractor() { if(extractor == null) { synchronized(syncLock){ if(extractor == null) { extractor = new ListPageExtractor(); } } } return extractor; } private static final String ARTICLE_ELEMENTS_FITURE = "div[class=article] div[class=title figures] a"; private static final String ATRICLE_ELEMENTS_EVENT = "div[class=article] div[class=title event] a"; private static final String ARTICLE_ELEMENTS_NEWS = "div[class=article] div[class=title news] a"; private static final String ATTRIBUTE_KEY_HREF = "href"; private static final String ATTRIBUTE_KEY_TITLE = "title"; @Override public ExtractedElements extractDataModel(String detailPageUrl, String html) { Document doc = Jsoup.parse(html); Elements elements = doc.select(ARTICLE_ELEMENTS_FITURE); elements.addAll(doc.select(ATRICLE_ELEMENTS_EVENT)); elements.addAll(doc.select(ARTICLE_ELEMENTS_NEWS)); List<SeedElement> seeds = new ArrayList<SeedElement>(); List<BaseModel> pageInfos = new ArrayList<BaseModel>(); for(Element element: elements) { String targetUrl = element.attr(ATTRIBUTE_KEY_HREF); if(targetUrl == null) { logger.fatal("FATAL -- extract inside links encounter fatal error, selector match up failed"); continue; } logger.info("seed link : <" + targetUrl + ">"); String uid = getArticleId(targetUrl); if(uid == null) { logger.fatal("FATAL -- extract link unique id failed"); continue; } // seems useless String title = element.attr(ATTRIBUTE_KEY_TITLE); SeedElement seed = new SeedElement(); seed.setTargetUrl(targetUrl); seed.setDirectoryAppender(uid + "\\"); seed.setExtractor(DetailPageExtractor.getExtractor()); seeds.add(seed); PageInfo pageInfo = new PageInfo(); pageInfo.setUniqueId(uid); pageInfo.setTitle(title); pageInfo.setUrl(targetUrl); Date now = new Date(); pageInfo.setCreateDate(now); pageInfo.setModifyDate(now); pageInfos.add(pageInfo); } ExtractedElements baseElement = new ExtractedElements(); baseElement.setSeeds(seeds); baseElement.setPersistInfos(pageInfos); return baseElement; } public String getArticleId(String url) { String[] tmp = url.split("/"); return tmp[tmp.length - 1]; } }
true
79f5b2ae19787ee363771f0ce68f77a76cca35ea
Java
JiangXiNJU/JavaLearn
/src/main/java/DesignPatterns/CommandPattern/Light.java
UTF-8
350
3.15625
3
[]
no_license
package DesignPatterns.CommandPattern; import static java.lang.System.out; /** * Created by cycy on 2018/6/19. */ public class Light { String name="Light"; public Light(String str){ name=str; } public void on(){ out.println(name+" is on"); } public void off(){ out.println(name+" is off"); } }
true
1a5ad4ec3c973989676069516c08d392a43d2886
Java
incognito050924/ReactiveTutorials
/src/main/java/me/incognito/reactive/Async.java
UTF-8
3,491
2.78125
3
[]
no_license
package me.incognito.reactive; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureTask; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import lombok.extern.slf4j.Slf4j; /** * Create by incognito on 2021/6/2 */ @Slf4j public class Async { private static ExecutorService ES = Executors.newFixedThreadPool(10); private static Supplier<String> stringSupplier = () -> { final String value = "ABC"; log.info("value is {}", value); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); } return value; }; private static Callable<String> stringCallable = stringSupplier::get; private static void futureTest() throws Exception { final Future<String> future = ES.submit(stringCallable); log.info("Future: {}", future); log.info("Future Result: {}", future.get()); } private static void listenableFutureTest() { final ListenableFuture<String> future = new ListenableFutureTask<>(stringCallable); future.addCallback( result -> { log.info("Future Result: {}", result); // Callback Hell final ListenableFutureTask<String> f2 = new ListenableFutureTask<>(() -> "Nested " + result); f2.addCallback( result2 -> { log.info("Future2 Result: {}", result2); }, err2 -> { log.error(err2.getMessage()); }); ES.submit(f2); }, err -> { log.error(err.getMessage()); }); ES.submit((Runnable) future); } private static void completableFutureTest() { final CompletableFuture<String> completableFuture = new CompletableFuture<>(); completableFuture .thenComposeAsync(result -> { log.info("Future Result: {}", result); return CompletableFuture.completedFuture("Nested " + result); }) .thenComposeAsync(result -> { log.info("Nested Future Result: {}", result); return CompletableFuture.completedFuture("Nested " + result); }) .thenAcceptAsync(result -> log.info("Result: {}", result)); completableFuture.complete("ABC"); // final CompletableFuture<?> future = CompletableFuture.supplyAsync(stringSupplier) // .thenAcceptAsync(result -> log.info("Future Result: {}", result)); } public static void main(String[] args) throws Exception { // futureTest(); // listenableFutureTest(); // completableFutureTest(); CompletableFuture.supplyAsync(Async.stringSupplier) .thenAccept(System.out::println); ForkJoinPool.commonPool().shutdown(); ForkJoinPool.commonPool().awaitTermination(10, TimeUnit.SECONDS); ES.shutdown(); log.info("Finished"); } }
true
fff5b2a80fbbbc9f28d26fba4e7de49479573caa
Java
Shivam-Paul/in.stackbook
/CollaborationBackEnd/src/main/java/in/stackbook/collaboration/daoimpl/FriendDAOImpl.java
UTF-8
8,238
2.28125
2
[]
no_license
package in.stackbook.collaboration.daoimpl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import javax.transaction.Transactional; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.hibernate.query.Query; import org.hibernate.resource.transaction.spi.SynchronizationRegistryImplementor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import in.stackbook.collaboration.dao.FriendDAO; import in.stackbook.collaboration.model.Friend; import in.stackbook.collaboration.model.User; @Repository("friendDAO") @Transactional public class FriendDAOImpl implements FriendDAO { /* * Fourth difference between save and persist method in Hibernate: * persist method is called outside of transaction boundaries, * it is useful in long-running conversations with an extended Session context. * On the other hand save method is not good in a long-running conversation with an extended Session context. */ @Autowired private SessionFactory sessionFactory; private Session getSession() { return sessionFactory.getCurrentSession(); } public boolean save(Friend friend) { try { if(friend.getFriends() == 0) { friend.setFriends(2); } getSession().save(friend); return true; } catch(Exception e) { e.printStackTrace(); return false; } } public boolean update(Friend friend) { try { getSession().update(friend); return true; } catch(Exception e) { e.printStackTrace(); return false; } } public boolean delete(int friend_id) { try { getSession().delete(get(friend_id)); return true; } catch(Exception e) { e.printStackTrace(); return false; } } public Friend get(int friend_id) { return (Friend)getSession().get(Friend.class, friend_id); } public Friend get(String email_id1, String email_id2) { String hql = "from Friend where (email_id1 = :email_id1 and email_id2 = :email_id2 and friends = 1)" + " or (email_id1 = :email_id2 and email_id2 = :email_id1 and friends = 1)"; Query query = getSession().createQuery(hql); query.setParameter("email_id1", email_id1); query.setParameter("email_id2", email_id2); return (Friend)query.uniqueResult(); } public List<Friend> listFriends(String email_id) { String hql = "from Friend where (email_id1 = :email_id and friends = 1)" + " or (email_id2 = :email_id and friends = 1)"; Query query = getSession().createQuery(hql); query.setParameter("email_id", email_id); return (List<Friend>)query.list(); /*return (List<Friend>)getSession().createNativeQuery("select * from c_friend where " + "(email_id1='"+email_id+"' and friends=1) or " + "(email_id2='"+email_id+"' and friends=1)").list();*/ } public List<Friend> listSentFriendRequests(String email_id) { return (List<Friend>)getSession().createCriteria(Friend.class) .add(Restrictions.eq("email_id1", email_id)) .add(Restrictions.eq("friends", 2)) .list(); } public List<Friend> listReceivedFriendRequests(String email_id) { return (List<Friend>)getSession().createCriteria(Friend.class) .add(Restrictions.eq("email_id2", email_id)) .add(Restrictions.eq("friends", 2)) .list(); } public List<User> listBlockedUsers(String email_id) { String first = "from User where email_id in (select email_id1 as email_id from Friend where" + " (email_id2 = :email_id and (friends = 4 or friends = 6)))"; String second = "from User where email_id in (select email_id2 as email_id from Friend where" + " (email_id1 = :email_id and (friends = 5 or friends = 6)))"; Query list1 = getSession().createQuery(first); Query list2 = getSession().createQuery(second); list1.setParameter("email_id", email_id); list2.setParameter("email_id", email_id); List<User> temp1 = (List<User>)list1.list(); List<User> temp2 = (List<User>)list2.list(); return combineList(temp1, temp2); } /*select * from c_user where email_id not in (select email_id1 as email_id from c_friend where email_id2 = '1@2.com' union select email_id2 as email_id from c_friend where email_id1 = '1@2.com') and email_id!='1@2.com'*/ public List<User> listSuggestedUsers(String email_id) { String first = "from User where email_id not in" + " (select email_id1 as email_id from Friend where email_id2 = :email_id) and email_id != :email_id"; String second = "from User where email_id not in" + " (select email_id2 as email_id from Friend where email_id1 = :email_id) and email_id != :email_id"; Query list1 = getSession().createQuery(first); Query list2 = getSession().createQuery(second); list1.setParameter("email_id", email_id); list2.setParameter("email_id", email_id); List<User> temp1 = (List<User>)list1.list(); List<User> temp2 = (List<User>)list2.list(); return combineList(temp1, temp2); } private synchronized List<User> combineList(List<User> temp1, List<User> temp2) { List<User> result = new ArrayList<User>(); for(User tempUser : temp2) { if(temp1.contains(tempUser)) { result.add(tempUser); } } for(User tempUser : temp1) { if(temp2.contains(tempUser) && !result.contains(tempUser)) { result.add(tempUser); } } for(User temp : result) { System.out.println("result" + temp.getEmail_id()); } return result; } /*select * from c_user where email_id in (((select email_id1 as email_id from c_friend where email_id1 = 'abc@gmail.com' and friends = 1) union (select email_id2 as email_id from c_friend where email_id2 = 'abc@gmail.com' and friends = 1)) intersect ((select email_id1 as email_id from c_friend where email_id1 = 'temp@gmail.com' and friends = 1) union (select email_id2 as email_id from c_friend where email_id2 = 'temp@gmail.com' and friends = 1)))*/ public List<User> listMutualFriends(String email_id1, String email_id2) { String first = "from User where email_id in (select email_id2 as email_id from Friend where" + " (email_id1 = :email_id1 and friends = 1))"; String second = "from User where email_id in (select email_id1 as email_id from Friend where" + " (email_id2 = :email_id1 and friends = 1))"; String third = "from User where email_id in (select email_id2 as email_id from Friend where" + " (email_id1 = :email_id2 and friends = 1))"; String fourth = "from User where email_id in (select email_id1 as email_id from Friend where" + " (email_id2 = :email_id2 and friends = 1))"; Query list1 = getSession().createQuery(first); Query list2 = getSession().createQuery(second); Query list3 = getSession().createQuery(third); Query list4 = getSession().createQuery(fourth); list1.setParameter("email_id1", email_id1); list2.setParameter("email_id1", email_id1); list3.setParameter("email_id2", email_id2); list4.setParameter("email_id2", email_id2); List<User> temp1 = (List<User>)list1.list(); List<User> temp2 = (List<User>)list2.list(); List<User> temp3 = (List<User>)list3.list(); List<User> temp4 = (List<User>)list4.list(); for(User temp : temp1) { System.out.println("temp1" + temp.getEmail_id()); } for(User temp : temp2) { System.out.println("temp2" + temp.getEmail_id()); } for(User temp : temp3) { System.out.println("temp3" + temp.getEmail_id()); } for(User temp : temp4) { System.out.println("temp4" + temp.getEmail_id()); } List<User> combined1 = mutualList(temp1, temp2); List<User> combined2 = mutualList(temp3, temp4); for(User temp : combined1) { System.out.println("combined1" + temp.getEmail_id()); } for(User temp : combined2) { System.out.println("combined2" + temp.getEmail_id()); } return combineList(combined1, combined2); } private synchronized List<User> mutualList(List<User> list1, List<User> list2) { List<User> result = new ArrayList<User>(); for(User tempUser : list1) { if(!list2.contains(tempUser)) { result.add(tempUser); } } for(User tempUser : list2) { if(!list1.contains(tempUser) && !result.contains(tempUser)) { result.add(tempUser); } } return result; } }
true
2669302da6c52e29819df50c3b590d4d96f65ed8
Java
h2oai/h2o-3
/h2o-core/src/main/java/water/Value.java
UTF-8
33,075
2.421875
2
[ "Apache-2.0" ]
permissive
package water; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import jsr166y.ForkJoinPool; import water.fvec.Frame; import water.fvec.Vec; import water.util.Log; import water.util.StringUtils; /** The core Value stored in the distributed K/V store, used to cache Plain Old * Java Objects, and maintain coherency around the cluster. It contains an * underlying byte[] which may be spilled to disk and freed by the {@link * MemoryManager}, which is the {@link Iced} serialized version of the POJO, * and a cached copy of the POJO itself. * <p> * Requests to extract the POJO from the Value object first try to return the * cached POJO. If that is missing, then they will re-inflate the POJO from * the {@link Iced} byte[]. If that is missing it is only because the byte[] * was swapped to disk by the {@link Cleaner}. It will be reloaded from disk * and then inflated as normal. * <p> * The H2O {@link DKV} supports the full <em>Java Memory Model</em> coherency * but only with Gets and Puts. Normal Java updates to the cached POJO are * local-node visible (due to X86 and Java coherency rules) but NOT cluster-wide * visible until a Put completes after the update. * <p> * By the same token, updates ot the POJO are not reflected in the serialized * form nor the disk-spill copy unless a Put is triggered. As long as a local * thread keeps a pointer to the POJO, they can update it at will. If they * wish to recover the POJO from the DKV at a later time with all updates * intact, they <em>must</em> do a final Put after all updates. * <p> * Value objects maintain the needed coherency state, as well as any cached * copies, plus a bunch of utility and convenience functions. */ public final class Value extends Iced implements ForkJoinPool.ManagedBlocker { /** The Key part of a Key/Value store. Transient, because the Value is * typically found via its Key, and so the Key is available before we get * the Value and does not need to be passed around the wire. Not final, * because Keys are interned slowly (for faster compares) and periodically a * Value's Key will be updated to an interned but equivalent Key. * <p> * Should not be set by any user code. */ public transient Key _key; // --- // Type-id of serialized object; see TypeMap for the list. // Might be a primitive array type, or a Iced POJO private short _type; public int type() { return _type; } /** Class name of the embedded POJO, without needing an actual POJO. */ public String className() { return TypeMap.className(_type); } // Max size of Values before we start asserting. // Sizes around this big, or larger are probably true errors. // In any case, they will cause issues with both GC (giant pause times on // many collectors) and I/O (long term blocking of TCP I/O channels to // service a single request, causing starvation of other requests). public static final int MAX = Integer.MAX_VALUE; //DeepWater models can contain a single byte[] state as large as 3GB /** Size of the serialized wad of bits. Values are wads of bits; known small * enough to 'chunk' politely on disk, or fit in a Java heap (larger Vecs * are built via Chunks) but (much) larger than a UDP packet. Values can * point to either the disk or ram version or both. There's no compression * smarts (done by the big data Chunks) nor de-dup smarts (done by the * nature of a K/V). This is just a local placeholder for some user bits * being held at this local Node. */ public int _max; // --- // A array of this Value when cached in DRAM, or NULL if not cached. The // contents of _mem are immutable (Key/Value mappings can be changed by an // explicit PUT action). Cleared to null asynchronously by the memory // manager (but only if persisted to some disk or in a POJO). Can be filled // in by reloading from disk, or by serializing a POJO. private volatile byte[] _mem; final byte[] rawMem() { return _mem; } // --- // A POJO version of the _mem array, or null if the _mem has not been // serialized or if _mem is primitive data and not a POJO. Cleared to null // asynchronously by the memory manager (but only if persisted to some disk, // or in the _mem array). Can be filled in by deserializing the _mem array. // NOTE THAT IF YOU MODIFY any fields of a POJO that is part of a Value, // - this is NOT the recommended programming style, // - those changes are visible to all CPUs on the writing node, // - but not to other nodes, and // - the POJO might be dropped by the MemoryManager and reconstituted from // disk and/or the byte array back to it's original form, losing your changes. private volatile Freezable _pojo; Freezable rawPOJO() { return _pojo; } /** Invalidate byte[] cache. Only used to eagerly free memory, for data * which is expected to be read-once. */ public final void freeMem() { assert isPersisted() || _pojo != null || _key.isChunkKey(); _mem = null; } /** Invalidate POJO cache. Only used to eagerly free memory, for data * which is expected to be read-once. */ public final void freePOJO() { assert isPersisted() || _mem != null; _pojo = null; } public final boolean isConsistent() { byte[] mem = _mem; // Read once! if (mem == null) return true; Freezable<?> pojo = _pojo; // Read once! if (pojo == null) return true; if (pojo instanceof Keyed) { Freezable<?> reloaded = TypeMap.newInstance(_type); reloaded = reloaded.reloadFromBytes(mem); return reloaded instanceof Keyed && ((Keyed<?>) reloaded).checksum(true) == ((Keyed<?>) pojo).checksum(true); } else { byte[] pojoBytes = pojo.asBytes(); return Arrays.equals(pojoBytes, mem); } } /** The FAST path get-byte-array - final method for speed. Will (re)build * the mem array from either the POJO or disk. Never returns NULL. * @return byte[] holding the serialized POJO */ public final byte[] memOrLoad() { byte[] mem = _mem; // Read once! if( mem != null ) return mem; Freezable pojo = _pojo; // Read once! if( pojo != null ) // Has the POJO, make raw bytes return _mem = pojo.asBytes(); if( _max == 0 ) return (_mem = new byte[0]); return (_mem = loadPersist()); } // Just an empty shell of a Value, no local data but the Value is "real". // Any attempt to look at the Value will require a remote fetch. final boolean isEmpty() { return _max > 0 && _mem==null && _pojo == null && !isPersisted(); } /** The FAST path get-POJO as an {@link Iced} subclass - final method for * speed. Will (re)build the POJO from the _mem array. Never returns NULL. * @return The POJO, probably the cached instance. */ public final <T extends Iced> T get() { touch(); Iced pojo = (Iced)_pojo; // Read once! if( pojo != null ) return (T)pojo; pojo = TypeMap.newInstance(_type); return (T)(_pojo = pojo.reloadFromBytes(memOrLoad())); } /** The FAST path get-POJO as a {@link Freezable} - final method for speed. * Will (re)build the POJO from the _mem array. Never returns NULL. This * version has more type-checking. * @return The POJO, probably the cached instance. */ public final <T extends Freezable> T get(Class<T> fc) { T pojo = getFreezable(); assert fc.isAssignableFrom(pojo.getClass()); return pojo; } /** The FAST path get-POJO as a {@link Freezable} - final method for speed. * Will (re)build the POJO from the _mem array. Never returns NULL. * @return The POJO, probably the cached instance. */ public final <T extends Freezable> T getFreezable() { touch(); Freezable pojo = _pojo; // Read once! if( pojo != null ) return (T)pojo; pojo = TypeMap.newFreezable(_type); pojo.reloadFromBytes(memOrLoad()); return (T)(_pojo = pojo); } // --- // Time of last access to this value. transient long _lastAccessedTime = System.currentTimeMillis(); private void touch() {_lastAccessedTime = System.currentTimeMillis();} // Exposed and used for testing only; used to trigger premature cleaning/disk-swapping void touchAt(long time) {_lastAccessedTime = time;} // --- // Backend persistence info. 3 bits are reserved for 8 different flavors of // backend storage. 1 bit for whether or not the latest _mem field is // entirely persisted on the backend storage. The low 3 bits are final. The // other bit monotonically changes from 0->1. The deleted bit ALSO // monotonically changes 0->1. These two bits cannot be combined without the // use of atomic operations. private volatile byte _persist; // 1 bit of disk/notdisk; 3 bits of backend flavor public final static byte ICE = 1<<0; // ICE: distributed local disks public final static byte HDFS= 2<<0; // HDFS: backed by Hadoop cluster public final static byte S3 = 3<<0; // Amazon S3 public final static byte NFS = 4<<0; // NFS: Standard file system public final static byte GCS = 5<<0; // Google Cloud Storage public final static byte HTTP= 6<<0; // HTTP/HTTPS data source (that accepts byte ranges, "Accept-Ranges: bytes") public final static byte TCP = 7<<0; // TCP: For profile purposes, not a storage system private final static byte BACKEND_MASK = (8-1); final byte backend() { return (byte)(_persist&BACKEND_MASK); } boolean onICE (){ return (backend()) == ICE; } private boolean onHDFS(){ return (backend()) == HDFS; } private boolean onNFS (){ return (backend()) == NFS; } private boolean onS3 (){ return (backend()) == S3; } private boolean onGCS (){ return (backend()) == GCS; } // Manipulate the on-disk bit private final static byte NOTdsk = 0<<3; // latest _mem is persisted or not private final static byte ON_dsk = 1<<3; /** Check if the backing byte[] has been saved-to-disk */ public final boolean isPersisted() { return (_persist&ON_dsk)!=0; } public final void setDsk() { _persist |= ON_dsk; } // note: not atomic, but only monotonically set bit private volatile byte _deleted; // 1 bit of deleted public final boolean isDeleted() { return _deleted != 0; } public final void setDel() { _deleted=1; } // note: not atomic, but only monotonically set bit /** Best-effort store complete Values to disk. */ void storePersist() throws java.io.IOException { // 00 then start writing // 01 delete requested; do not write // 10 already written; do nothing // 11 already written & deleted; do nothing if( isDeleted() ) return; // 01 and 11 cases if( isPersisted() ) return; // 10 case H2O.getPM().store(backend(), this); // Write to disk // 00 -> 10 expected, set write bit // 10 assert; only Cleaner writes // 01 delete-during-write; delete again // 11 assert; only Cleaner writes assert !isPersisted(); // Only Cleaner writes setDsk(); // Not locked, not atomic, so can only called by one thread: Cleaner if( isDeleted() ) // Check del bit AFTER setting persist bit; close race with deleting user thread H2O.getPM().delete(backend(), this); // Possibly nothing to delete (race with writer) } /** Remove dead Values from disk */ public void removePersist() { // do not yank memory, as we could have a racing get hold on to this // free_mem(); // 00 -> 01 try to delete (racing, probably nothing to delete) // 01 double delete; do nothing // 10 -> 11 delete // 11 double delete; do nothing if( !onICE() ) return; // Wrong filestore? if( isDeleted() ) return; // Already deleted? setDel(); // Set del bit BEFORE testing isPersist if( !isPersisted() ) return;// Nothing there H2O.getPM().delete(backend(), this); // Possibly nothing to delete (race with writer) } /** Load some or all of completely persisted Values */ byte[] loadPersist() { // 00 assert: not written yet // 01 assert: load-after-delete // 10 expected; read // 11 assert: load-after-delete assert isPersisted(); try { byte[] res = H2O.getPM().load(backend(), this); assert !isDeleted(); // Race in user-land: load-after-delete return res; } catch( IOException ioe ) { throw Log.throwErr(ioe); } } String nameOfPersist() { return nameOfPersist(backend()); } /** One of ICE, HDFS, S3, GCS, NFS or TCP, according to where this Value is persisted. * @return Short String of the persitance name */ public static String nameOfPersist(int x) { switch( x ) { case ICE : return "ICE"; case HDFS: return "HDFS"; case S3 : return "S3"; case NFS : return "NFS"; case TCP : return "TCP"; case GCS : return "GCS"; default : return null; } } /** Check if the Value's POJO is a subtype of given type integer. Does not require the POJO. * @return True if the Value's POJO is a subtype. */ public static boolean isSubclassOf(int type, Class clz) { return type != TypeMap.PRIM_B && clz.isAssignableFrom(TypeMap.theFreezable(type).getClass()); } /** Check if the Value's POJO is a {@link Key} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link Key} subtype. */ public boolean isKey() { return _type != TypeMap.PRIM_B && TypeMap.theFreezable(_type) instanceof Key; } /** Check if the Value's POJO is a {@link Frame} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link Frame} subtype. */ public boolean isFrame() { return _type != TypeMap.PRIM_B && TypeMap.theFreezable(_type) instanceof Frame; } /** Check if the Value's POJO is a {@link water.fvec.Vec.VectorGroup} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link water.fvec.Vec.VectorGroup} subtype. */ public boolean isVecGroup() { return _type == TypeMap.VECGROUP; } /** Check if the Value's POJO is a {@link water.fvec.Vec.ESPC} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link water.fvec.Vec.ESPC} subtype. */ public boolean isESPCGroup() { return _type == TypeMap.ESPCGROUP; } /** Check if the Value's POJO is a {@link Lockable} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link Lockable} subtype. */ public boolean isLockable() { return _type != TypeMap.PRIM_B && TypeMap.theFreezable(_type) instanceof Lockable; } /** Check if the Value's POJO is a {@link Vec} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link Vec} subtype. */ public boolean isVec() { return _type != TypeMap.PRIM_B && TypeMap.theFreezable(_type) instanceof Vec; } /** Check if the Value's POJO is a {@link hex.Model} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link hex.Model} subtype. */ public boolean isModel() { return _type != TypeMap.PRIM_B && TypeMap.theFreezable(_type) instanceof hex.Model; } /** Check if the Value's POJO is a {@link Job} subtype. Does not require the POJO. * @return True if the Value's POJO is a {@link Job} subtype. */ public boolean isJob() { return _type != TypeMap.PRIM_B && TypeMap.theFreezable(_type) instanceof Job; } public Class<? extends Freezable> theFreezableClass() { return TypeMap.theFreezable(this._type).getClass(); } // -------------------------------------------------------------------------- /** Construct a Value from all parts; not needed for most uses. This special * constructor is used by {@link water.fvec} to build Value objects over * already-existing Files, so that the File contents will be lazily * swapped-in as the Values are first used. */ public Value(Key k, int max, byte[] mem, short type, byte be ) { assert mem==null || mem.length==max; assert max < MAX : "Value size=0x"+Integer.toHexString(max); _key = k; _max = max; _mem = mem; _type = type; _pojo = null; // For the ICE backend, assume new values are not-yet-written. // For HDFS & NFS backends, assume we from global data and preserve the // passed-in persist bits byte p = (byte)(be&BACKEND_MASK); _persist = (p==ICE) ? p : be; _rwlock = new AtomicInteger(1); _replicas = null; } // --- public Value(Key k, byte[] mem ) { this(k, mem.length, mem, TypeMap.PRIM_B, ICE); } // --- Value(Key k, String s ) { this(k, StringUtils.bytesOf(s)); } Value(Key k, Iced pojo ) { this(k,pojo,ICE); } Value(Key k, Iced pojo, byte be ) { _key = k; _pojo = pojo; _type = (short)pojo.frozenType(); _mem = pojo.asBytes(); _max = _mem.length; assert _max < MAX : "Value size = " + _max + " (0x"+Integer.toHexString(_max) + ") >= (MAX=" + MAX + ")."; // For the ICE backend, assume new values are not-yet-written. // For HDFS & NFS backends, assume we from global data and preserve the // passed-in persist bits byte p = (byte)(be&BACKEND_MASK); _persist = (p==ICE) ? p : be; _rwlock = new AtomicInteger(1); _replicas = null; } public Value(Key k, Freezable pojo, int pojoByteSz, byte be) { _key = k; _pojo = pojo; _type = (short)pojo.frozenType(); _mem = null; _max = pojoByteSz; byte p = (byte)(be&BACKEND_MASK); _persist = (p==ICE) ? p : be; _rwlock = new AtomicInteger(1); _replicas = null; } /** Standard constructor to build a Value from a POJO and a Key. */ public Value(Key k, Freezable pojo) { this(k,pojo,ICE); } Value(Key k, Freezable pojo, byte be) { _key = k; _pojo = pojo; _type = (short)pojo.frozenType(); _mem = pojo.asBytes(); _max = _mem.length; byte p = (byte)(be&BACKEND_MASK); _persist = (p==ICE) ? p : be; _rwlock = new AtomicInteger(1); _replicas = null; } // Custom serializers: the _mem field is racily cleared by the MemoryManager // and the normal serializer then might ship over a null instead of the // intended byte[]. Also, the value is NOT on the deserialize'd machines disk public final AutoBuffer write_impl( AutoBuffer ab ) { return ab.put1(_persist).put2(_type).putA1(memOrLoad()); } // Custom serializer: set _max from _mem length; set replicas & timestamp. public final Value read_impl(AutoBuffer bb) { assert _key == null; // Not set yet // Set persistence backend but... strip off saved-to-disk bit _persist = (byte)(bb.get1()&BACKEND_MASK); _type = (short) bb.get2(); _mem = bb.getA1(); _max = _mem.length; assert _max < MAX : "Value size=0x"+Integer.toHexString(_max)+" during read is larger than "+Integer.toHexString(MAX)+", type: "+TypeMap.className(_type); _pojo = null; // On remote nodes _rwlock is initialized to 1 (signaling a remote PUT is // in progress) flips to -1 when the remote PUT is done, or +2 if a notify // needs to happen. _rwlock = new AtomicInteger(-1); // Set as 'remote put is done' _replicas = null; touch(); return this; } // --------------------- // Ordering of K/V's! This field tracks a bunch of things used in ordering // updates to the same Key. Ordering Rules: // - Program Order. You see your own writes. All writes in a single thread // strongly ordered (writes never roll back). In particular can: // PUT(v1), GET, PUT(null) and The Right Thing happens. // - Unrelated writes can race (unless fencing). // - Writes are not atomic: some people can see a write ahead of others. // - Last-write-wins: if we do a zillion writes to the same Key then wait "a // long time", then do reads all reads will see the same last value. // - Blocking on a PUT stalls until the PUT is cloud-wide visible // // For comparison to H2O get/put MM // IA Memory Ordering, 8 principles from Rich Hudson, Intel // 1. Loads are not reordered with other loads // 2. Stores are not reordered with other stores // 3. Stores are not reordered with older loads // 4. Loads may be reordered with older stores to different locations but not // with older stores to the same location // 5. In a multiprocessor system, memory ordering obeys causality (memory // ordering respects transitive visibility). // 6. In a multiprocessor system, stores to the same location have a total order // 7. In a multiprocessor system, locked instructions have a total order // 8. Loads and stores are not reordered with locked instructions. // // My (KN, CNC) interpretation of H2O MM from today: // 1. Gets are not reordered with other Gets // 2 Puts may be reordered with Puts to different Keys. // 3. Puts may be reordered with older Gets to different Keys, but not with // older Gets to the same Key. // 4. Gets may be reordered with older Puts to different Keys but not with // older Puts to the same Key. // 5. Get/Put amongst threads doesn't obey causality // 6. Puts to the same Key have a total order. // 7. no such thing. although RMW operation exists with Put-like constraints. // 8. Gets and Puts may be reordered with RMW operations // 9. A write barrier exists that creates Sequential Consistency. Same-key // ordering (3-4) can't be used to create the effect. // // A Reader/Writer lock for the home node to control racing Gets and Puts. // - 0 for unlocked // - +N for locked by N concurrent GETs-in-flight // - -1 for write-locked // // An ACKACK from the client GET lowers the reader lock count. // // Home node PUTs alter which Value is mapped to a Key, then they block until // there are no active GETs, then atomically set the write-lock, then send // out invalidates to all the replicas. PUTs return when all invalidates // have reported back. // // An initial remote PUT will default the value to 1. A 2nd PUT attempt will // block until the 1st one completes (multiple writes to the same Key from // the same JVM block, so there is at most 1 outstanding write to the same // Key from the same JVM). The 2nd PUT will CAS the value to 2, indicating // the need for the finishing 1st PUT to call notify(). // // Note that this sequence involves a lot of blocking on repeated writes with // cached readers, but not the readers - i.e., writes are slow to complete. private transient AtomicInteger _rwlock; private boolean RW_CAS( int old, int nnn, String msg ) { if( !_rwlock.compareAndSet(old,nnn) ) return false; //System.out.println(_key+", "+old+" -> "+nnn+", "+msg); return true; } // List of who is replicated where private volatile byte[] _replicas; private static final AtomicReferenceFieldUpdater<Value,byte[]> REPLICAS_UPDATER = AtomicReferenceFieldUpdater.newUpdater(Value.class,byte[].class, "_replicas"); // Fills in the _replicas field atomically, on first set of a replica. private byte[] replicas( ) { byte[] r = _replicas; if( r != null ) return r; byte[] nr = makeReplicaIndicatorSpace(); if( REPLICAS_UPDATER.compareAndSet(this,null,nr) ) return nr; r = _replicas/*read again, since CAS failed must be set now*/; assert r!= null; return r; } private byte[] makeReplicaIndicatorSpace() { int size = H2ONode.IDX.length + 1 /*1-based numbering*/ + 10 /*buffer for 10 clients, if we exceed the buffer we just invalidate regardless if they have a copy or not*/; return new byte[size]; } // Bump the read lock, once per pending-GET or pending-Invalidate boolean read_lock() { while( true ) { // Repeat, in case racing GETs are bumping the counter int old = _rwlock.get(); if( old == -1 ) return false; // Write-locked; no new replications. Read fails to read *this* value assert old >= 0; // Not negative if( RW_CAS(old,old+1,"rlock+") ) return true; } } /** Atomically insert h2o into the replica list; reports false if the Value * flagged against future replication with a -1. Also bumps the active * Get count, which remains until the Get completes (we receive an ACKACK). */ boolean setReplica( H2ONode h2o ) { assert _key.home(); // Only the HOME node for a key tracks replicas assert h2o != H2O.SELF; // Do not track self as a replica if( !read_lock() ) return false; // Write-locked; no new replications. Read fails to read *this* value // Narrow non-race here. Here is a time window where the rwlock count went // up, but the replica list does not account for the new replica. However, // the rwlock cannot go down until an ACKACK is received, and the ACK // (hence ACKACK) doesn't go out until after this function returns. markHotReplica(h2o); // Both rwlock taken, and replica count is up now. return true; } private void markHotReplica(H2ONode n) { n.markLocalDKVAccess(); byte[] r = replicas(); if (n._unique_idx < r.length) r[n._unique_idx] = 1; } /** Atomically lower active GET and Invalidate count */ void lowerActiveGetCount( H2ONode h2o ) { assert _key.home(); // Only the HOME node for a key tracks replicas assert h2o != H2O.SELF;// Do not track self as a replica while( true ) { // Repeat, in case racing GETs are bumping the counter int old = _rwlock.get(); // Read the lock-word assert old > 0; // Since lowering, must be at least 1 assert old != -1; // Not write-locked, because we are an active reader assert (h2o==null) || (_replicas!=null && (h2o._unique_idx >= _replicas.length || _replicas[h2o._unique_idx]==1)); // Self-bit is set if( RW_CAS(old,old-1,"rlock-") ) { if( old-1 == 0 ) // GET count fell to zero? synchronized( this ) { notifyAll(); } // Notify any pending blocked PUTs return; // Repeat until count is lowered } } } /** This value was atomically extracted from the local STORE by a successful * TaskPutKey attempt (only 1 thread can ever extract and thus call here). * No future lookups will find this Value, but there may be existing uses. * Atomically set the rwlock count to -1 locking it from further GETs and * ship out invalidates to caching replicas. May need to block on active * GETs. Updates a set of Future invalidates that can be blocked against. */ Futures lockAndInvalidate( H2ONode sender, Value newval, Futures fs ) { assert _key.home(); // Only the HOME node for a key tracks replicas assert newval._rwlock.get() >= 1; // starts read-locked // Write-Lock against further GETs while( true ) { // Repeat, in case racing GETs are bumping the counter int old = _rwlock.get(); assert old >= 0 : _key+", rwlock="+old; // Count does not go negative assert old != -1; // Only the thread doing a PUT ever locks if( old !=0 ) { // has readers? // Active readers: need to block until the GETs (of this very Value!) // all complete, before we can invalidate this Value - lest a racing // Invalidate bypass a GET. try { ForkJoinPool.managedBlock(this); } catch( InterruptedException ignore ) { } } else if( RW_CAS(0,-1,"wlock") ) break; // Got the write-lock! } // We have the set of Nodes with replicas now. Ship out invalidates. // Bump the newval read-lock by 1 for each pending invalidate byte[] r = _replicas; if( r!=null ) { // No replicas, nothing to invalidate final int max = r.length; for( int i=0; i<max; i++ ) if( r[i]==1 && H2ONode.IDX[i] != sender ) TaskInvalidateKey.invalidate(H2ONode.IDX[i],_key,newval,fs); // Speculatively invalidate replicas also on nodes that were not known when the cluster was formed (clients) final int unseenMax = H2ONode.IDX.length; for (int i=max; i<unseenMax; i++) { final H2ONode node = H2ONode.IDX[i]; if (node != null && // can happen when the IDX array is being expanded node != sender && // ignore myself node.isRemovedFromCloud() && // ignore nodes that are not active anymore node.accessedLocalDKV()) // ignore nodes that appear active but didn't actually read DKV ever TaskInvalidateKey.invalidate(node, _key, newval, fs); } } newval.lowerActiveGetCount(null); // Remove initial read-lock, accounting for pending inv counts return fs; } void blockTillNoReaders( ) { assert _key.home(); // Only the HOME node for a key tracks replicas // Write-Lock against further GETs while( true ) { // Repeat, in case racing GETs are bumping the counter int old = _rwlock.get(); if( old <= 0) return; // No readers, or this Value already replaced with a later value // Active readers: need to block until the GETs (of this very Value!) all complete try { ForkJoinPool.managedBlock(this); } catch( InterruptedException ignore ) { } } } /** Initialize the _replicas field for a PUT. On the Home node (for remote * PUTs), it is initialized to the one replica we know about, and not * read-locked. Used on a new Value about to be PUT on the Home node. */ void initReplicaHome( H2ONode h2o, Key key ) { assert key.home(); assert _key == null; // This is THE initializing key write for serialized Values assert h2o != H2O.SELF; // Do not track self as a replica _key = key; // Set the replica bit for the one node we know about, and leave the // rest clear. markHotReplica(h2o); _rwlock.set(1); // An initial read-lock, so a fast PUT cannot wipe this one out before invalidates have a chance of being counted } /** Block this thread until all prior remote PUTs complete - to force * remote-PUT ordering on the home node. */ void startRemotePut() { assert !_key.home(); int x; // assert I am waiting on threads with higher priority? while( (x=_rwlock.get()) != -1 ) // Spin until rwlock==-1 if( x == 2 || RW_CAS(1,2,"remote_need_notify") ) try { ForkJoinPool.managedBlock(this); } catch( InterruptedException ignore ) { } } /** The PUT for this Value has completed. Wakeup any blocked later PUTs. */ void completeRemotePut() { assert !_key.home(); // Attempt an eager blind attempt, assuming no blocked pending notifies if( RW_CAS(1, -1,"remote_complete") ) return; synchronized(this) { boolean res = RW_CAS(2, -1,"remote_do_notify"); assert res; // Must succeed notifyAll(); // Wake up pending blocked PUTs } } // Construct a Value which behaves like a "null" or "deleted" Value, but // allows for counting pending invalidates on the delete operation... and can // thus stall future Puts overriding the deletion until the delete completes. static Value makeNull( Key key ) { assert key.home(); return new Value(key,0,null,(short)0,TCP); } boolean isNull() { assert _type != 0 || _key.home(); return _type == 0; } // Get from the local STORE. If we fetch out a special Null Value, and it is // unlocked (it will never be write-locked, but may be read-locked if there // are pending invalidates on it), upgrade it in-place to a true null. // Return the not-Null value, or the true null. public static Value STORE_get( Key key ) { Value val = H2O.STORE.get(key); if( val == null ) return null; // A true null if( !val.isNull() ) return val; // Not a special Null // One-shot throwaway attempt at upgrading the special Null to a true null if( val._rwlock.get()==0 ) H2O.putIfMatch(key,null,val); return null; // Special null, but missing from callers point of view } /** Return true if blocking is unnecessary. * Alas, used in TWO places and the blocking API forces them to share here. */ @Override public boolean isReleasable() { int r = _rwlock.get(); if( _key.home() ) { // Called from lock_and_invalidate // Home-key blocking: wait for active-GET count to fall to zero, or blocking on deleted object return r <= 0; } else { // Called from start_put // Remote-key blocking: wait for active-PUT lock to hit -1 assert r == 2 || r == -1; // Either waiting (2) or done (-1) but not started(1) return r == -1; // done! } } /** Possibly blocks the current thread. Returns true if isReleasable would * return true. Used by the FJ Pool management to spawn threads to prevent * deadlock is otherwise all threads would block on waits. */ @Override public synchronized boolean block() { while( !isReleasable() ) { try { wait(); } catch( InterruptedException ignore ) { } } return true; } }
true
a55a484a3fd7168b12e269d317d470989994ec7a
Java
Bavarna/tictactoe-android-app
/app/src/main/java/com/bavarna/tictactoeapp/model/GameData.java
UTF-8
1,810
3.34375
3
[]
no_license
package com.bavarna.tictactoeapp.model; public class GameData { Player playerX, playerY; int totalNumberOfMovesMade; int currentRow; int currentColumn; boolean isCurrentPlayerX; private static GameData gameData; GameData(Player X, Player Y) { playerX = X; playerY = Y; currentRow= -1; currentColumn = -1; isCurrentPlayerX = true; totalNumberOfMovesMade = 0; } public static GameData getInstance(Player X, Player Y) { if(gameData == null) { gameData = new GameData(X, Y); } return gameData; } public void resetData() { currentRow= -1; currentColumn = -1; isCurrentPlayerX = true; totalNumberOfMovesMade = 0; } public void incrementMoves() { switch (gameData.getCurrentPlayer()) { case X: gameData.playerX.incrementMovesMade(); break; case Y: gameData.playerY.incrementMovesMade(); break; } totalNumberOfMovesMade++; } public int getTotalNumberOfMovesMade() { return totalNumberOfMovesMade; } public void setCurrentColumn(int currentColumn) { this.currentColumn = currentColumn; } public void setCurrentRow(int currentRow) { this.currentRow = currentRow; } public void switchPlayer() { isCurrentPlayerX = !isCurrentPlayerX; } public PlayerType getCurrentPlayer() { if(isCurrentPlayerX) { return PlayerType.X; } else { return PlayerType.Y; } } public String getCurrentInput() { if(isCurrentPlayerX) { return "X"; } else { return "Y"; } } }
true
a3e74c50856e6e58b075e176d10d4a6d428a01a4
Java
wang1198/temp
/src/main/java/com/ctsi/dao/CscpBusinessDao.java
UTF-8
542
1.820313
2
[]
no_license
package com.ctsi.dao; import com.ctsi.domain.CscpBusiness; import com.ctsi.model.CscpBusinessDTO; import org.apache.ibatis.annotations.Mapper; import java.util.List; import java.util.Map; /** * ClassName CscpTestDao * Description TODO * Author tongliwei * Date 2020/2/2 21:26 * Version v1.0 **/ @Mapper public interface CscpBusinessDao { List<CscpBusiness> getBusinessList(CscpBusinessDTO business); void insert(CscpBusiness business); void update(CscpBusiness business); int delete(Map<String,List<String>> maps); }
true
77e4674ed027e513f7be99090904016282d4ac98
Java
qiaohhgz/easybuy
/EasyBuy/src/com/facade/ProductFacade.java
UTF-8
200
1.945313
2
[]
no_license
package com.facade; import com.dao.ProductDao; public class ProductFacade { private ProductDao productDao; public void setProductDao(ProductDao productDao) { this.productDao = productDao; } }
true
44a26a411ef1464aeda258559750ab0f5c6b22a6
Java
YehchanPark/sofeDesignAssignment3
/Exercise3/Observer.java
UTF-8
137
2.15625
2
[]
no_license
package Exercise3; public abstract class Observer { abstract void update(String[] text);//Creates the update method for observers }
true
99a6a7b218b8c6e6b3961e712d2f1f4fb820ac38
Java
npmcdn-to-unpkg-bot/tictactoe
/core/src/main/java/org/dorofeev/tictactoe/core/NodeStatus.java
UTF-8
184
1.796875
2
[]
no_license
package org.dorofeev.tictactoe.core; /** * NodeStatus * @author Yury Dorofeev * @version 2015-09-29 */ public enum NodeStatus { WIN, LOSE, DRAW, UNKNOWN, NEW_NODE }
true
c288915769d3263e13484038cdf6159de91c9b4a
Java
StefanLazea/cts
/Command/src/program/Program.java
UTF-8
785
2.921875
3
[]
no_license
package program; import clase.ComandaInternare; import clase.ComandaTratare; import clase.ICommand; import clase.Medic; import clase.OperatorPrimiriUrgente; public class Program { public static void main(String[] args) { // TODO Auto-generated method stub Medic mInternist = new Medic("Medic Internist"); Medic mGeneralist = new Medic("Medic Generalist"); OperatorPrimiriUrgente operator = new OperatorPrimiriUrgente(); ICommand comanda1 = new ComandaInternare(mInternist); operator.invoca(comanda1, "Gigel"); ICommand comanda2 = new ComandaTratare(mGeneralist); operator.invoca(comanda2, "George"); operator.executaComenzi(1); ICommand comanda3 = new ComandaTratare(mGeneralist); operator.invoca(comanda3, "Misu"); operator.executaComenzi(3); } }
true
8ce9a4984bf85f8bab56fc33c6cd5ba7dc77978b
Java
tonytw1/ukcasualties
/src/nz/gen/wellington/ukcasualties/screenscrapers/CasualtiesDAO.java
UTF-8
419
1.914063
2
[]
no_license
package nz.gen.wellington.ukcasualties.screenscrapers; import java.util.List; import com.sun.syndication.feed.synd.SyndEntry; public class CasualtiesDAO { private AfghanistanScraper scraper; public CasualtiesDAO(AfghanistanScraper scraper) { this.scraper = scraper; } public List<SyndEntry> getCasualties() { return scraper.parseContent(); } }
true
08a1816cd745d77bdc8525202234fdb45734847e
Java
xone-team/p0001
/xone-model/src/main/java/com/xone/model/hibernate/app/OverheadDao.java
UTF-8
216
1.523438
2
[]
no_license
package com.xone.model.hibernate.app; import com.xone.model.hibernate.entity.Overhead; import com.xone.model.hibernate.generic.HibernateDao; public interface OverheadDao extends HibernateDao<Overhead> { }
true
eb91c6eb9c2e21c02cb38e17f54e66c5b1f94944
Java
facebook/react-native
/packages/react-native/ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/IdleWaiter.java
UTF-8
386
1.78125
2
[ "MIT", "CC-BY-4.0", "CC-BY-NC-SA-4.0", "CC-BY-SA-4.0" ]
permissive
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.testing.idledetection; /** Interface for something that knows how to wait for bridge and UI idle. */ public interface IdleWaiter { void waitForBridgeAndUIIdle(); }
true
7a13be2e6ff12ec519013bd7c066c9888ae5fb73
Java
viniciodf/builder
/src/br/com/vinicio/BuilderApp.java
UTF-8
880
3.015625
3
[]
no_license
package br.com.vinicio; import br.com.vinicio.builder.CarroBuilder; import br.com.vinicio.builder.CarroLivroManualBuilder; import br.com.vinicio.model.Carro; import br.com.vinicio.model.CarroLivroManual; public class BuilderApp { public static void main(String[] args) { DiretorCarro diretorCarro = new DiretorCarro(); CarroBuilder carroBuilder = new CarroBuilder(); diretorCarro.construirCarroSport(carroBuilder); Carro carro = carroBuilder.build(); CarroLivroManualBuilder carroLivroManualBuilder = new CarroLivroManualBuilder(); diretorCarro.construirCarroSport(carroLivroManualBuilder); CarroLivroManual carroLivroManual = carroLivroManualBuilder.build(); System.out.println("Carro : " + carro.toString()); System.out.println("Carro Livro Manual: " + carroLivroManual.toString()); } }
true
3bde555c55af0586f25abd3b8599cb3d3ac975fb
Java
Lars-Janssen/Inleiding-Programmeren
/Opgave5/Paar.java
UTF-8
4,249
3.484375
3
[]
no_license
/* Deze klasse bestaat uit een coefficient en een macht en vormt 1 term van een polynoom. De coefficient is een reeel getal en de macht een positief geheel getal. */ class Paar implements Comparable<Paar> { final private double coefficient; final private int macht; /* Deze constructor neemt een double en een int en maakt de coefficient de double en de macht de int. Als de macht negatief is wordt hij 0 en geeft het een bericht. */ Paar(double coefficient, int macht) { this.coefficient = coefficient; if(macht >= 0) { this.macht = macht; } else { throw new IllegalArgumentException("Er is iets fout gegaan bij het maken van een paar," + " de macht is negatief."); } } /* Deze constructor neemt een Paar en geeft de coefficient en macht door aan de constructor hierboven. */ Paar(Paar p) { this(p.coefficient, p.macht); } /* De methode geeft de coefficient van een paar. */ public double geefCoefficient() { return coefficient; } /* De methode geeft de macht van een paar. */ public int geefMacht() { return macht; } /* Deze methode geeft de som van twee paren door de coefficienten op te tellen. */ public Paar telOp(Paar ander) { double opgeteldCoefficient = this.coefficient + ander.coefficient; Paar opgeteldPaar = new Paar(opgeteldCoefficient, this.macht); return opgeteldPaar; } /* Deze methode geeft het product van twee paren, door de coefficienten te vermenigvuldigen en de machten op te tellen. */ public Paar vermenigvuldig(Paar ander) { double vermenigvuldigdCoefficient = this.coefficient * ander.coefficient; int vermenigvuldigdMacht = this.macht + ander.macht; Paar vermenigvuldigdPaar = new Paar(vermenigvuldigdCoefficient, vermenigvuldigdMacht); return vermenigvuldigdPaar; } /* Deze methode geeft de differentiatie een paar, door de coefficient te vermenigvuldigen met de macht en de macht 1 te verlagen. */ public Paar differentieer() { if(this.macht > 0) { double gedifCoefficient = this.macht * this.coefficient; int gedifMacht = this.macht - 1; Paar gedifPaar = new Paar(gedifCoefficient, gedifMacht); return gedifPaar; } else { return new Paar(0, 0); } } /* Deze methode geft de integraal een paar, door de macht 1 te verhogen en de coefficient te delen door deze nieuwe macht. */ public Paar integreer() { int geintMacht = this.macht + 1; double geintCoefficient = this.coefficient / geintMacht; Paar geintPaar = new Paar(geintCoefficient, geintMacht); return geintPaar; } /* Deze methode vergelijkt twee machten en returned het verschil. Dit wordt gebruikt om het polynoom te sorteren. */ public int compareTo(Paar ander) { return ander.macht - this.macht; } /* Deze methode kijkt of twee paren hetzelfde zijn, door met de compareTo methode te kijken of de machten gelijk zijn en te kijken of de coefficienten hetzelfde zijn. */ public boolean equals(Paar ander) { if(this.compareTo(ander) == 0 && this.coefficient == ander.coefficient) { return true; } return false; } /* Deze methode zet het paar om in een String om te printen. */ public String toString() { if(macht == 0) { return(coefficient + ""); } if(macht == 1 && coefficient == 1.0 || coefficient == 0) { return("x"); } if(macht == 1) { return(coefficient + " x"); } if(coefficient == 1.0) { return("x^" + macht); } return(coefficient + " x^" + macht); } }
true
d6f9014befaddec95475882309f729990fb3d57a
Java
moon-util/moon-util
/src/main/java/com/moon/poi/excel/table/Assert.java
UTF-8
2,667
2.421875
2
[ "MIT" ]
permissive
package com.moon.poi.excel.table; // import com.moon.more.excel.annotation.FieldTransform; // import com.moon.more.excel.annotation.TableColumn; // import com.moon.more.excel.annotation.TableColumnGroup; // import com.moon.more.excel.annotation.defaults.DefaultValue; import com.moon.core.lang.NumberUtil; import com.moon.core.time.DateUtil; import com.moon.poi.excel.annotation.TableColumn; /** * @author moonsky */ final class Assert { // private final static String DFT_VAL = "@" + DefaultValue.class.getSimpleName(); // private final static String TRANSFORM = "@" + FieldTransform.class.getSimpleName(); // private final static String COLUMN_NAME = "@" + TableColumn.class.getSimpleName(); // private final static String GROUP_NAME = "@" + TableColumnGroup.class.getSimpleName(); // private final static String NOT_ALLOWED = COLUMN_NAME + // " & " + // GROUP_NAME + // " 不能用于同一字段: {} (包括对应的 getter | setter): \n\t\t[ " + // // COLUMN_NAME + // " ] 用于普通数据字段(int、double、String、BigDecimal 等;注解在复合字段上将视为 String 最终调用 toString() 方法);\n\t\t[ " + // // GROUP_NAME + // " ] 用于实体字段(里面由普通字段组成)。\n\n"; // private final static String NOT_SUPPORT = "暂不支持 " + DFT_VAL + " 和 " + TRANSFORM + // // " \n\t\t为被 " + GROUP_NAME + " 注解的字段提供默认值或转换: {};"; // static void notDuplicated(Descriptor descriptor) { // TableColumn column = descriptor.getTableColumn(); // TableColumnGroup group = descriptor.getTableColumnGroup(); // notDuplicated(column, group, descriptor.getName()); // } // static void notDuplicated(TableColumn column, TableColumnGroup group, String propertyName) { // if (column != null && group != null) { // throw new IllegalStateException(NOT_ALLOWED.replace("{}", propertyName)); // } // } final static void notDuplicated(Marked onMethod, Marked onField) { TableColumn mCol = onMethod == null ? null : onMethod.getTableColumn(); TableColumn fCol = onField == null ? null : onField.getTableColumn(); if (mCol != null && fCol != null) { throw new IllegalStateException("@" + TableColumn.class.getSimpleName() + " 不能同时注解在 getter/setter 方法和字段上"); } } static boolean isNumberType(Class type) { return NumberUtil.isGeneralNumberClass(type); } static boolean isImportedJodaTime() { return DateUtil.isImportedJodaTime(); } }
true
b9c387d4eee84290eec126b1cc6904cee8ad3050
Java
novator007/javaslimserver
/src/main/java/org/bff/squeezeserver/events/VolumeChangeEvent.java
UTF-8
1,147
2.859375
3
[]
no_license
package org.bff.squeezeserver.events; /** * Represents a change in the volume of a Slim player. * * @author Bill Findeisen * @version 1.0 */ public class VolumeChangeEvent extends java.util.EventObject { private int volume; private String msg; /** * Creates a new instance of MusicPlayerStatusChangedEvent * * @param source the object on which the Event initially occurred * @param volume the new volume */ public VolumeChangeEvent(Object source, int volume) { this(source, volume, null); } /** * Creates a new instance of MusicPlayerStatusChangedEvent * * @param source the object on which the Event initially occurred * @param volume the new volume * @param msg an optional message */ public VolumeChangeEvent(Object source, int volume, String msg) { super(source); this.volume = volume; this.msg = msg; } /** * Returns the message attached to this event. If there is no message null * is returned. * * @return the optional message */ public String getMsg() { return msg; } }
true
7f976a47cb8d2777be99e837f6733dd5b3e0b9e4
Java
ashwiniswag/My-Quotes
/app/src/main/java/com/example/myquotes/GenreAdapter.java
UTF-8
1,344
2.296875
2
[]
no_license
package com.example.myquotes; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; public class GenreAdapter extends BaseAdapter { List<String> sher,pname,titl; Context context; LayoutInflater inflater; public GenreAdapter(Context context,List<String> sher,List<String> pname,List<String> title){ this.context=context; this.sher=sher; this.pname=pname; this.titl=title; inflater=LayoutInflater.from(context); } @Override public int getCount() { return sher.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v=inflater.inflate(R.layout.content,null); TextView content=v.findViewById(R.id.sher); TextView penname=v.findViewById(R.id.wname); TextView title=v.findViewById(R.id.tit); content.setText(sher.get(position)); penname.setText("-"+pname.get(position)); title.setText(titl.get(position)); return v; } }
true
547b52a291b11f8691420bb631a67eea1617f4a6
Java
moutainhigh/platform-parent
/platform-common/src/main/java/com/slljr/finance/common/pojo/vo/WithdrawDepositDetailVO.java
UTF-8
2,510
2.03125
2
[]
no_license
package com.slljr.finance.common.pojo.vo; import com.slljr.finance.common.pojo.model.WithdrawDetail; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; /** * @description: * @author: goodni. * @date: 2019/2/27 * @time: 17:39 */ public class WithdrawDepositDetailVO extends WithdrawDetail implements Serializable { @ApiModelProperty(value = "用户姓名", required = false) private String userName; @ApiModelProperty(value = "银行卡号", required = false) private String bankCardNo; @ApiModelProperty(value = "开户银行", required = false) private String openingBank; @ApiModelProperty(value = "审核人员", required = false) private String auditorName; @ApiModelProperty(value = "手机", required = false) private String phone; @ApiModelProperty(value = "开户省份", required = false) private String openingBankProvince; @ApiModelProperty(value = "开户城市", required = false) private String openingBankCity; //公钥,RSAUtil使用该公钥解密 private String bankCardNoSign; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getBankCardNo() { return bankCardNo; } public void setBankCardNo(String bankCardNo) { this.bankCardNo = bankCardNo; } public String getOpeningBank() { return openingBank; } public void setOpeningBank(String openingBank) { this.openingBank = openingBank; } public String getAuditorName() { return auditorName; } public void setAuditorName(String auditorName) { this.auditorName = auditorName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getOpeningBankProvince() { return openingBankProvince; } public void setOpeningBankProvince(String openingBankProvince) { this.openingBankProvince = openingBankProvince; } public String getOpeningBankCity() { return openingBankCity; } public void setOpeningBankCity(String openingBankCity) { this.openingBankCity = openingBankCity; } public String getBankCardNoSign() { return bankCardNoSign; } public void setBankCardNoSign(String bankCardNoSign) { this.bankCardNoSign = bankCardNoSign; } }
true
603428466ef55bbf148a5063d7ddac4fbd329a26
Java
Thyssoda/Gladiators
/src/com/thyssoda/gladiators/Engines/CreationEngine.java
ISO-8859-1
17,960
2.015625
2
[]
no_license
package com.thyssoda.gladiators.Engines; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Sign; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; import com.thyssoda.gladiators.Gladiators; import com.thyssoda.gladiators.Game.GladiatorsState; public class CreationEngine implements CommandExecutor, Listener { private Gladiators pl; private WaitingPlayersEngine wpe; private GameEngine se; public CreationEngine(Gladiators pl, WaitingPlayersEngine wpe, GameEngine se) { this.pl = pl; this.wpe = wpe; this.se = se; } private int i = 1; public ArrayList<UUID> playerInGame = new ArrayList<>(); public Player player; public Scoreboard scoreboard; public Objective obj; public Objective objHealthTab; public Objective objHealthBN; public Team bleu; public Team rouge; int kills; int lastkills; private int players; private int timer; private int killsBleu; private int lastkillsBleu; private int killsRouge; private int lastkillsRouge; private int timer2; private int lastTimer; private String lastS; private String S; public void createScoreboard() { scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); obj = scoreboard.registerNewObjective("gladiators", "dummy"); obj = scoreboard.getObjective("gladiators"); objHealthTab = scoreboard.registerNewObjective("hpTab", "health"); objHealthTab = scoreboard.getObjective("hpTab"); objHealthBN = scoreboard.registerNewObjective("hpBN", "health"); objHealthBN = scoreboard.getObjective("hpBN"); bleu = scoreboard.registerNewTeam("Bleu"); bleu.setPrefix(ChatColor.BLUE + "[BLUE]"); bleu.setAllowFriendlyFire(false); rouge = scoreboard.registerNewTeam("Rouge"); rouge.setPrefix(ChatColor.RED + "[RED]"); rouge.setAllowFriendlyFire(false); } public void setScoreboard(Player p) { obj.setDisplayName(ChatColor.GOLD + "" + ChatColor.BOLD + "Gladiators"); obj.setDisplaySlot(DisplaySlot.SIDEBAR); objHealthTab.setDisplaySlot(DisplaySlot.PLAYER_LIST); objHealthBN.setDisplaySlot(DisplaySlot.BELOW_NAME); objHealthBN.setDisplayName("/ 20"); if (GladiatorsState.isState(GladiatorsState.WAIT)) { players = playerInGame.size() - 1; obj.getScoreboard().resetScores("" + players); obj.getScore("" + playerInGame.size()).setScore(9); obj.getScoreboard().resetScores("7En attente de joueurs !"); obj.getScore("7En attente de joueurs !").setScore(7); } else if (GladiatorsState.isState(GladiatorsState.LOBBY)) { timer = wpe.temps - 1; obj.getScoreboard().resetScores("7En attente de joueurs !"); obj.getScore("7Lancement de la partie dans : ").setScore(7); obj.getScoreboard().resetScores("" + wpe.temps); obj.getScore("" + timer).setScore(6); } else { if (se.kills.containsKey(this.player)) { kills = se.kills.get(this.player); lastkills = kills - 1; } killsBleu = se.scoreBleu; lastkillsBleu = se.scoreBleu - 1; killsRouge = se.scoreRouge; lastkillsRouge = se.scoreRouge - 1; timer2 = 480 - se.temps4; lastTimer = timer2 + 1; lastS = new SimpleDateFormat("mm:ss").format(lastTimer * 1000); S = new SimpleDateFormat("mm:ss").format(timer2 * 1000); obj.getScoreboard().resetScores("7Lancement de la partie dans : "); obj.getScoreboard().resetScores("" + wpe.temps); obj.getScoreboard().resetScores("" + players); obj.getScore("" + playerInGame.size()).setScore(9); obj.getScoreboard().resetScores("" + lastkills); obj.getScoreboard().resetScores("7Fin de la partie dans : "); obj.getScore("7Fin de la partie dans : ").setScore(7); obj.getScoreboard().resetScores(lastS); obj.getScore(S).setScore(6); obj.getScoreboard().resetScores("7 Kills bleus : "); obj.getScore("7 Kills bleus : ").setScore(4); obj.getScoreboard().resetScores(lastkillsBleu + ""); obj.getScore(killsBleu + "").setScore(3); obj.getScoreboard().resetScores("7 Kills rouges : "); obj.getScore("7 Kills rouges : ").setScore(2); obj.getScoreboard().resetScores(lastkillsRouge + ""); obj.getScore(killsRouge + "").setScore(1); obj.getScore("8 ").setScore(11); obj.getScore("7Joueurs: ").setScore(10); obj.getScore("e ").setScore(8); obj.getScore("a ").setScore(5); } p.setScoreboard(scoreboard); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage("Tu dois etre un joueur afin d'executer cette commande !"); return false; } else { Player player = (Player) sender; Inventory inv = Bukkit.createInventory(null, 9, "Gladiators"); ItemStack lobbyItem = nameItem(Material.DIAMOND_SWORD, ChatColor.LIGHT_PURPLE + "Ajoute le point de spawn du lobby !"); ItemStack spawnItem = nameItem2(Material.WOOL, (short) 11, ChatColor.BLUE + "Ajoute un point de spawn pour l'quipe bleue !"); ItemStack spawnItem2 = nameItem2(Material.WOOL, (short) 14, ChatColor.DARK_RED + "Ajoute un point de spawn pour l'quipe rouge !"); ItemStack blockItem1 = nameItem(Material.LAPIS_BLOCK, ChatColor.GREEN + "Bloc dtruire (quipe bleu) !"); ItemStack blockItem2 = nameItem(Material.REDSTONE_BLOCK, ChatColor.GREEN + "Bloc dtruire (quipe rouge) !"); ItemStack nullItem = nameItem2(Material.STAINED_GLASS_PANE, (short) 14, ChatColor.LIGHT_PURPLE + "###########"); inv.setItem(0, spawnItem); inv.setItem(1, spawnItem2); inv.setItem(2, blockItem1); inv.setItem(3, blockItem2); inv.setItem(8, lobbyItem); for (int i = 4; i <= 7; i++) { inv.setItem(i, nullItem); } player.openInventory(inv); return true; } } public void registerEvents() { PluginManager pm = Bukkit.getPluginManager(); pm.registerEvents(this, pl); } @EventHandler public void onDamage(EntityDamageByEntityEvent event) { Entity p = event.getDamager(); if (event.getEntity() instanceof ItemFrame) { if (p instanceof Player || p instanceof Arrow) { event.setCancelled(true); Arrow a = (Arrow) p; if (a.getShooter() instanceof Player) { event.setCancelled(true); } } } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { Player p = event.getPlayer(); if (GladiatorsState.isState(GladiatorsState.GAMEPVP)) { p.sendMessage(ChatColor.RED + "La partie a commenc !"); p.sendMessage(ChatColor.DARK_RED + "Tu as t mis en spectateur !"); p.setGameMode(GameMode.SPECTATOR); } } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if (!(event.getBlockPlaced().getType() == Material.EMERALD_BLOCK) && !(event.getBlockPlaced().getState() instanceof Sign)) { event.setCancelled(true); } } @EventHandler public void onSignChange(SignChangeEvent e) { if (e.getBlock().getState() instanceof Sign) { Sign s = (Sign) e.getBlock().getState(); if (s.getLine(1).equals("[setlobby]")) { s.setLine(1, ChatColor.AQUA + "[LOBBY]"); s.setLine(2, ChatColor.RED + String.valueOf(playerInGame.size()) + " / 6"); if (pl.getConfig().getConfigurationSection("Sign") == null) { pl.getConfig().createSection("Sign.x"); pl.getConfig().createSection("Sign.y"); pl.getConfig().createSection("Sign.z"); pl.getConfig().set("Sign.x", s.getBlock().getX()); pl.getConfig().set("Sign.y", s.getBlock().getY()); pl.getConfig().set("Sign.z", s.getBlock().getZ()); pl.saveConfig(); } else { pl.getConfig().set("Sign.x", s.getBlock().getX()); pl.getConfig().set("Sign.y", s.getBlock().getY()); pl.getConfig().set("Sign.z", s.getBlock().getZ()); pl.saveConfig(); } s.update(); } } } @EventHandler public void onInventoryClick(InventoryClickEvent e) { Inventory inv = e.getInventory(); if (!(e.getWhoClicked() instanceof Player)) { return; } else { Player p = (Player) e.getWhoClicked(); if (!inv.getTitle().equals("Gladiators")) { return; } else { ItemStack item = e.getCurrentItem(); if (item.getType() == Material.DIAMOND_SWORD) { if (pl.getConfig().getConfigurationSection("Lobby") == null) { pl.getConfig().createSection("Lobby.x"); pl.getConfig().createSection("Lobby.y"); pl.getConfig().createSection("Lobby.z"); pl.saveConfig(); Location loc = p.getLocation(); double x = loc.getBlockX() + 0.5; double y = loc.getBlockY() + 0.5; double z = loc.getBlockZ() + 0.5; pl.getConfig().set("Lobby.x", Double.valueOf(x)); pl.getConfig().set("Lobby.y", Double.valueOf(y)); pl.getConfig().set("Lobby.z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.GOLD + "Spawn du lobby dfini !"); e.setCancelled(true); p.closeInventory(); } else { Location loc = p.getLocation(); double x = loc.getBlockX() + 0.5; double y = loc.getBlockY() + 0.5; double z = loc.getBlockZ() + 0.5; pl.getConfig().set("Lobby.x", Double.valueOf(x)); pl.getConfig().set("Lobby.y", Double.valueOf(y)); pl.getConfig().set("Lobby.z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.GOLD + "Spawn du lobby dfini !"); e.setCancelled(true); p.closeInventory(); } } if (item.getType() == Material.STAINED_GLASS_PANE && item.getDurability() == 14) { e.setCancelled(true); } if (item.getType() == Material.LAPIS_BLOCK) { if (pl.getConfig().getConfigurationSection("Block") == null) { pl.getConfig().createSection("Block.Type"); pl.getConfig().set("Block.Type", "EMERALD_BLOCK"); pl.getConfig().createSection("Block.bleu.x"); pl.getConfig().createSection("Block.bleu.y"); pl.getConfig().createSection("Block.bleu.z"); pl.getConfig().createSection("Block.rouge.x"); pl.getConfig().createSection("Block.rouge.y"); pl.getConfig().createSection("Block.rouge.z"); pl.saveConfig(); Location loc = p.getLocation(); double x = loc.getBlockX(); double y = loc.getBlockY(); double z = loc.getBlockZ(); pl.getConfig().set("Block.bleu.x", Double.valueOf(x)); pl.getConfig().set("Block.bleu.y", Double.valueOf(y)); pl.getConfig().set("Block.bleu.z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.GOLD + "Bloc dtruire (quipe bleu) !"); e.setCancelled(true); p.closeInventory(); } else { Location loc = p.getLocation(); double x = loc.getBlockX(); double y = loc.getBlockY(); double z = loc.getBlockZ(); pl.getConfig().set("Block.bleu.x", Double.valueOf(x)); pl.getConfig().set("Block.bleu.y", Double.valueOf(y)); pl.getConfig().set("Block.bleu.z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.GOLD + "Bloc dtruire (quipe bleu) !"); e.setCancelled(true); p.closeInventory(); } } else if (item.getType() == Material.REDSTONE_BLOCK) { if (pl.getConfig().getConfigurationSection("Block") == null) { pl.getConfig().createSection("Block.Type"); pl.getConfig().set("Block.Type", "EMERALD_BLOCK"); pl.getConfig().createSection("Block.bleu.x"); pl.getConfig().createSection("Block.bleu.y"); pl.getConfig().createSection("Block.bleu.z"); pl.getConfig().createSection("Block.rouge.x"); pl.getConfig().createSection("Block.rouge.y"); pl.getConfig().createSection("Block.rouge.z"); pl.saveConfig(); Location loc = p.getLocation(); double x = loc.getBlockX(); double y = loc.getBlockY(); double z = loc.getBlockZ(); pl.getConfig().set("Block.rouge.x", Double.valueOf(x)); pl.getConfig().set("Block.rouge.y", Double.valueOf(y)); pl.getConfig().set("Block.rouge.z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.GOLD + "Bloc dtruire (quipe rouge) !"); e.setCancelled(true); p.closeInventory(); } else { Location loc = p.getLocation(); double x = loc.getBlockX(); double y = loc.getBlockY(); double z = loc.getBlockZ(); pl.getConfig().set("Block.rouge.x", Double.valueOf(x)); pl.getConfig().set("Block.rouge.y", Double.valueOf(y)); pl.getConfig().set("Block.rouge.z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.GOLD + "Bloc dtruire (quipe rouge) !"); e.setCancelled(true); p.closeInventory(); } } if (item.getType() == Material.WOOL && item.getDurability() == 11) { Location loc = p.getLocation(); if (pl.getConfig().getConfigurationSection("Spawns_bleu") == null) { pl.getConfig().createSection("Spawns_bleu"); pl.saveConfig(); double x = loc.getBlockX() + 0.5; double y = loc.getBlockY(); double z = loc.getBlockZ() + 0.5; if (i <= 3) { pl.getConfig().getConfigurationSection("Spawns_bleu").createSection(String.valueOf(i)); pl.getConfig().set("Spawns_bleu." + i + ".x", Double.valueOf(x)); pl.getConfig().set("Spawns_bleu." + i + ".y", Double.valueOf(y)); pl.getConfig().set("Spawns_bleu." + i + ".z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.AQUA + "Tu viens de crer un spawn pour les bleus !"); i++; e.setCancelled(true); p.closeInventory(); } } else { double x = loc.getBlockX() + 0.5; double y = loc.getBlockY(); double z = loc.getBlockZ() + 0.5; if (i <= 3) { pl.getConfig().getConfigurationSection("Spawns_bleu").createSection(String.valueOf(i)); pl.getConfig().set("Spawns_bleu." + i + ".x", Double.valueOf(x)); pl.getConfig().set("Spawns_bleu." + i + ".y", Double.valueOf(y)); pl.getConfig().set("Spawns_bleu." + i + ".z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.AQUA + "Tu viens de crer un spawn pour les bleus !"); i++; e.setCancelled(true); p.closeInventory(); } else { e.setCancelled(true); p.closeInventory(); p.sendMessage(ChatColor.DARK_RED + "Tu ne peux pas crer plus de points de spawns pour les bleus !"); } } } if (item.getType() == Material.WOOL && item.getDurability() == 14) { if (i < 4) { p.sendMessage("Tu dois enregistrer les spawns bleus en premier !"); e.setCancelled(true); p.closeInventory(); } Location loc = p.getLocation(); if (pl.getConfig().getConfigurationSection("Spawns_rouge") == null) { pl.getConfig().createSection("Spawns_rouge"); pl.saveConfig(); double x = loc.getBlockX() + 0.5; double y = loc.getBlockY(); double z = loc.getBlockZ() + 0.5; if (i <= 6 && i > 3) { pl.getConfig().getConfigurationSection("Spawns_rouge").createSection(String.valueOf(i)); pl.getConfig().set("Spawns_rouge." + i + ".x", Double.valueOf(x)); pl.getConfig().set("Spawns_rouge." + i + ".y", Double.valueOf(y)); pl.getConfig().set("Spawns_rouge." + i + ".z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.RED + "Tu viens de crer un spawn pour les rouges !"); i++; e.setCancelled(true); p.closeInventory(); } } else { double x = loc.getBlockX() + 0.5; double y = loc.getBlockY(); double z = loc.getBlockZ() + 0.5; if (i <= 6 && i > 3) { pl.getConfig().getConfigurationSection("Spawns_rouge").createSection(String.valueOf(i)); pl.getConfig().set("Spawns_rouge." + i + ".x", Double.valueOf(x)); pl.getConfig().set("Spawns_rouge." + i + ".y", Double.valueOf(y)); pl.getConfig().set("Spawns_rouge." + i + ".z", Double.valueOf(z)); pl.saveConfig(); p.sendMessage(ChatColor.RED + "Tu viens de crer un spawn pour les rouges !"); i++; e.setCancelled(true); p.closeInventory(); } else if (i > 3) { e.setCancelled(true); p.closeInventory(); p.sendMessage(ChatColor.DARK_RED + "Tu ne peux pas crer plus de points de spawns pour les rouges !"); } } } } } } private ItemStack nameItem(ItemStack item, String name) { ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); return item; } private ItemStack nameItem(Material item, String name) { return nameItem(new ItemStack(item), name); } private ItemStack nameItem2(ItemStack item, short id, String name) { ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); item.setDurability(id); return item; } private ItemStack nameItem2(Material item, short id, String name) { return nameItem2(new ItemStack(item), id, name); } }
true
9f7a16d41ddb03c9a7995636bfb00b62d12d6b40
Java
PrimedSoftLimited/FrebbyChapTen
/chapten/Package.java
UTF-8
654
2.9375
3
[]
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 chapten; /** * * @author Frebby */ public class Package { private double weight; private char shippingMethod; private String shippingCost; public Package(double weight, char shippingMethod) { this.weight = weight; this.shippingMethod = shippingMethod; } public void display(){ System.out.println(weight); System.out.println(shippingMethod); System.out.println(shippingCost); } }
true
6e23fff3ae326df29ad352a65062ae97971c2092
Java
leechaean7714/Academy_java
/Java17_IO/src/com/test01/onlyTest.java
UTF-8
589
2.875
3
[]
no_license
package com.test01; import java.io.File; import java.io.IOException; public class onlyTest { public static void main(String[] args) { File fi = new File("C:/test01_io"); if (fi.exists()) { System.out.println("exists"); } else { System.out.println("new!"); fi.mkdirs(); } File fic1 = new File(fi,"AA"); fic1.mkdir(); File fic2 = new File("C:/test01_io","BB"); fic2.mkdir(); File fitxt = new File(fic1,"a.text"); try { fitxt.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } }
true
bcc27e7c798b76a987a36908089b5c7d13c9c980
Java
ShreyaJB/SpringRestfulWebservices
/moviecuriser/src/main/java/com/cognizant/moviecuriser/controller/FavoritiesController.java
UTF-8
2,337
2.546875
3
[]
no_license
package com.cognizant.moviecuriser.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.cognizant.moviecuriser.model.Movie; import com.cognizant.moviecuriser.service.MovieService; import com.cognizant.moviecuriser.service.exception.MovieNotFoundException; import lombok.extern.slf4j.Slf4j; @RestController @Slf4j public class FavoritiesController { @Autowired MovieService movieService; /** * Gets favorite movie list for customer * * @param userId * @param map * @return favorite movie list for customer * @throws MovieNotFoundException if no movie is in list * */ @GetMapping("/favoritiesMovies/{userId}") public List<Movie> showFav(@PathVariable("userId") Integer id) throws MovieNotFoundException { log.info("Start"); List<Movie> movie= movieService.getFaviorateMovies(id); log.info("End"); return movie; } /** * Adds the movie to list * * @param movie_id * @param modelMap * @return success status if movie does not exist else display movie already * exist */ @GetMapping("/addToFavorities/{id}") public String addFaviorateMovie(@PathVariable("id") Integer id) { log.info("Start"); String url = ""; movieService.getMoviesListCustomer(); try { if (movieService.getFaviorateMovies(1).contains(movieService.getByMovieId(id))) { url = "movie-list-customer-already-present"; } else { movieService.saveToFaviorate(movieService.getByMovieId(id)); url = "success"; } } catch (MovieNotFoundException e) { // TODO: handle exception movieService.saveToFaviorate(movieService.getByMovieId(id)); url = "suceess"; } log.info("End"); return url; } /** * Deletes from favorites * * @param movie_id * @param map * @return success status if movie is deleted else empty page * */ @GetMapping("/deleteFromFavorities/{id}") public String deleteFromFaviorates(@PathVariable("id") Integer movie_id) { log.info("Start"); movieService.deleteFaviorate(movie_id); return "success"; } }
true
7064f8818eefb3b6984418f12c940d71219e7a94
Java
fugerit-org/fj-doc
/fj-doc-sample/src/test/java/test/org/fugerit/java/doc/sample/simpletable/TestSimpleTable.java
UTF-8
2,959
2.375
2
[ "Apache-2.0" ]
permissive
package test.org.fugerit.java.doc.sample.simpletable; import static org.junit.Assert.fail; import java.io.File; import java.io.FileOutputStream; import org.fugerit.java.core.cfg.ConfigException; import org.fugerit.java.core.lang.helpers.BooleanUtils; import org.fugerit.java.doc.base.config.DocTypeHandler; import org.fugerit.java.doc.base.config.DocTypeHandlerXML; import org.fugerit.java.doc.lib.simpletable.SimpleTableDocConfig; import org.fugerit.java.doc.lib.simpletable.SimpleTableFacade; import org.fugerit.java.doc.lib.simpletable.model.SimpleCell; import org.fugerit.java.doc.lib.simpletable.model.SimpleRow; import org.fugerit.java.doc.lib.simpletable.model.SimpleTable; import org.fugerit.java.doc.mod.fop.PdfFopTypeHandler; import org.fugerit.java.doc.mod.opencsv.OpenCSVTypeHandler; import org.fugerit.java.doc.mod.poi.XlsxPoiTypeHandler; import org.junit.Before; import org.junit.Test; import lombok.extern.slf4j.Slf4j; import test.org.fugerit.java.doc.sample.facade.BasicFacadeTest; @Slf4j public class TestSimpleTable { private static final DocTypeHandler[] HANDLERS = { DocTypeHandlerXML.HANDLER_UTF8, XlsxPoiTypeHandler.HANDLER, OpenCSVTypeHandler.HANDLER, new PdfFopTypeHandler() }; private SimpleTableDocConfig docConfig; private File baseDir = new File( BasicFacadeTest.BASIC_OUTPUT_PATH ); @Before public void init() throws ConfigException { this.docConfig = SimpleTableDocConfig.newConfig(); log.info( "config init ok {}", this.docConfig ); if ( !baseDir.exists() ) { this.baseDir.mkdirs(); } } @Test public void testSimpleTable01() { SimpleTable simpleTableModel = SimpleTableFacade.newTable( 30, 30, 40 ); simpleTableModel.setDefaultBorderWidth( 1 ); SimpleRow headerRow = new SimpleRow( BooleanUtils.BOOLEAN_TRUE ); headerRow.addCell( "Name" ); headerRow.addCell( "Surname" ); headerRow.addCell( "Title" ); simpleTableModel.addRow( headerRow ); SimpleRow luthienRow = new SimpleRow(); luthienRow.addCell( "Luthien" ); luthienRow.addCell( "Tinuviel" ); luthienRow.addCell( SimpleCell.newCell( "Queen" ).bold().center() ); simpleTableModel.addRow( luthienRow ); SimpleRow thorinRow = new SimpleRow(); thorinRow.addCell( "Thorin" ); thorinRow.addCell( "Oakshield" ); thorinRow.addCell( SimpleCell.newCell( "King" ).bold().center() ); SimpleRow lastRow = new SimpleRow(); lastRow.addCell( "Bilbo" ); lastRow.addCell( "Baggins" ); lastRow.addCell( SimpleCell.newCell( "<Hero>" ).bold().center() ); simpleTableModel.addRow( lastRow ); for ( int k=0; k<HANDLERS.length; k++ ) { DocTypeHandler handler = HANDLERS[k]; File file = new File( this.baseDir, "simple_table_01."+handler.getType() ); try ( FileOutputStream fos = new FileOutputStream( file ) ) { this.docConfig.processSimpleTable(simpleTableModel, handler, fos); } catch (Exception e) { String message = "Error : "+e; log.error( message, e ); fail( message ); } } } }
true
ac64cc46e7c77f2ae099a4a023bd58126af217f7
Java
caocf/bee_parent
/bee_busi/src/main/java/com/bee/busi/controller/shop/ShopController.java
UTF-8
6,501
2.21875
2
[]
no_license
package com.bee.busi.controller.shop; import com.bee.commons.Codes; import com.bee.commons.Consts; import com.bee.domain.response.ServiceSupportResponse; import com.bee.image.ImageParser; import com.bee.pojo.shop.Shop; import com.bee.services.shop.busi.IShopBusiService; import com.qsd.framework.domain.response.Response; import com.qsd.framework.hibernate.exception.DataRunException; import com.qsd.framework.spring.BaseResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; /** * Created by suntongwei on 15/11/15. */ @RestController @RequestMapping("/shop") public class ShopController { private static final Logger Log = LoggerFactory.getLogger(ShopController.class); @Autowired private IShopBusiService shopBusiService; /** * 获取商家支持信息 * * @return */ @RequestMapping(value = "/{sid}/support", method = RequestMethod.GET) public ServiceSupportResponse getShopServiceSupport(@PathVariable Long sid) { ServiceSupportResponse res = new ServiceSupportResponse(); Shop shop = shopBusiService.getShopById(sid); if (shop != null) { res.setIsPosCard(shop.getIsPosCard()); res.setIsFood(shop.getIsFood()); res.setIsFreeParking(shop.getIsFreeParking()); res.setIsInvoice(shop.getIsInvoice()); res.setCode(Codes.Success); } else { res.setCode(Codes.Error); res.setMsg("未查询到商家信息"); } return res; } /** * 保存商家支持信息 * * @return */ @RequestMapping(value = "/{sid}/support", method = RequestMethod.POST) public Response saveShopServiceSupport(@PathVariable Long sid, boolean isPosCard, boolean isFreeParking, boolean isFood, boolean isInvoice) { Response res = new Response(); try { Shop shop = shopBusiService.getShopById(sid); if (shop != null) { shop.setIsPosCard(isPosCard ? Consts.True : Consts.False); shop.setIsFreeParking(isFreeParking ? Consts.True : Consts.False); shop.setIsFood(isFood ? Consts.True : Consts.False); shop.setIsInvoice(isInvoice ? Consts.True : Consts.False); shopBusiService.update(shop); } else { res.setCode(Codes.Error); res.setMsg("未查询到商家信息"); } } catch (DataRunException e) { res.setCode(Codes.Error); res.setMsg("更新失败,请重试"); } return res; } /** * 关闭商家 * * @param sid 商家ID * @return */ @RequestMapping(value = "/{sid}", method = RequestMethod.DELETE) public Response openOrCloseShop(@PathVariable long sid, int status) { Response res = new Response(); Shop shop = shopBusiService.getShopById(sid); if (shop != null) { if (shop.getStatus() == Consts.Shop.Status.Close) { res.setCode(Codes.Error); res.setMsg("商家被管理员关闭,请联系管理员"); } else { try { shop.setStatus(status); shopBusiService.closeShop(shop); res.setCode(Codes.Success); } catch (DataRunException e) { Log.error("BusiShopController.openOrCloseShop error.", e); res.setCode(Codes.Error); res.setMsg("保存状态出错,请重试"); } } } else { res.setCode(Codes.Error); res.setMsg("未知商家"); } return res; } /** * 上传商家列表图片 * * @param req * @return */ @RequestMapping(value = "/{sid}/edit/image/list", method = RequestMethod.POST) public Response updateShopListImage(@PathVariable Long sid, MultipartHttpServletRequest req) { Response res = new Response(); MultipartFile file = req.getFile("thumbnailFile"); if (null == file) { res.setCode(Codes.Error); res.setMsg("图片不存在"); return res; } String fileName = file.getOriginalFilename().trim().toLowerCase(); String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length()); if (!ImageParser.ImageTypeEnum.JPG.toString().equals(ext) && !ImageParser.ImageTypeEnum.JPEG.toString().equals(ext) && !ImageParser.ImageTypeEnum.PNG.toString().equals(ext)) { res.setCode(Codes.Error); res.setMsg("图片格式不正确,只支持JPG,JPEG,PNG格式"); return res; } shopBusiService.saveShopListImage(sid, req); res.setCode(Codes.Success); return res; } /** * 上传商家门店图片 * * @param req * @return */ @RequestMapping(value = "/{sid}/edit/image/face", method = RequestMethod.POST) public Response updateShopImage(@PathVariable Long sid, MultipartHttpServletRequest req) { Response res = new Response(); MultipartFile file = req.getFile("file"); if (null == file) { res.setCode(Codes.Error); res.setMsg("图片不存在"); return res; } String fileName = file.getOriginalFilename().trim().toLowerCase(); String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length()); if (!ImageParser.ImageTypeEnum.JPG.toString().equals(ext) && !ImageParser.ImageTypeEnum.JPEG.toString().equals(ext) && !ImageParser.ImageTypeEnum.PNG.toString().equals(ext)) { res.setCode(Codes.Error); res.setMsg("图片格式不正确,只支持JPG,JPEG,PNG格式"); return res; } shopBusiService.saveShopImage(sid, req); res.setCode(Codes.Success); return res; } }
true
20419558a7d68988aacbdf538a57f4f52ceeb976
Java
anirudhnain/Anti_Poaching
/app/src/main/java/com/example/anirudh_pc/anti_poaching/UserHome.java
UTF-8
1,789
1.609375
2
[]
no_license
package com.example.anirudh_pc.anti_poaching; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.TabHost; import android.widget.TextView; /** * Created by anand on 3/5/15. */ public class UserHome extends ActionBarActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.userhome); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); TabHost tabHost = (TabHost) findViewById(R.id.tabHost); tabHost.setup(); TabHost.TabSpec tabSpec = tabHost.newTabSpec("animal"); tabSpec.setContent(R.id.tabanimal); tabSpec.setIndicator("Animals"); tabHost.addTab(tabSpec); tabSpec = tabHost.newTabSpec("userdetail"); tabSpec.setContent(R.id.tabuserdetail); tabSpec.setIndicator("TrackDetails"); tabHost.addTab(tabSpec); } @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(UserHome.this, MainActivity.class)); finish(); } public void create(View view) { Intent intent = new Intent(this, Create.class); startActivity(intent); } public void update(View view) { Intent intent = new Intent(this, Update.class); startActivity(intent); } public void delete(View view) { Intent intent = new Intent(this, Delete.class); startActivity(intent); } public void track(View view) { Intent intent = new Intent(this, track_Map.class); startActivity(intent); } }
true
96d73bbb0f76af287031f9e7d663bc9c26b13d1e
Java
optimatika/ojAlgo
/src/main/java/org/ojalgo/array/OffHeapZ008.java
UTF-8
2,967
2.21875
2
[ "MIT" ]
permissive
/* * Copyright 1997-2023 Optimatika * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.ojalgo.array; import org.ojalgo.scalar.Scalar; import org.ojalgo.type.NativeMemory; final class OffHeapZ008 extends OffHeapArray { private final long myPointer; OffHeapZ008(final long count) { super(OffHeapArray.Z008, count); myPointer = NativeMemory.allocateByteArray(this, count); } @Override public void add(final long index, final Comparable<?> addend) { this.add(index, Scalar.byteValue(addend)); } @Override public byte byteValue(final long index) { return NativeMemory.getByte(myPointer, index); } @Override public double doubleValue(final long index) { return NativeMemory.getByte(myPointer, index); } @Override public byte byteValue(final int index) { return NativeMemory.getByte(myPointer, index); } @Override public double doubleValue(final int index) { return NativeMemory.getByte(myPointer, index); } @Override public void reset() { NativeMemory.initialiseByteArray(myPointer, this.count()); } @Override public void set(final long index, final byte value) { NativeMemory.setByte(myPointer, index, value); } @Override public void set(final long index, final Comparable<?> value) { this.set(index, Scalar.byteValue(value)); } @Override public void set(final long index, final double value) { NativeMemory.setByte(myPointer, index, (byte) Math.toIntExact(Math.round(value))); } @Override public void set(final long index, final float value) { NativeMemory.setByte(myPointer, index, (byte) Math.round(value)); } @Override public void set(final int index, final double value) { NativeMemory.setByte(myPointer, index, (byte) Math.toIntExact(Math.round(value))); } }
true
f4e629aa9d21b51f2e4666618b4de395eae60a53
Java
5GExchange/lattice-monitoring-framework
/source/eu/fivegex/monitoring/appl/probes/delay/unidirectional/UDPMgmSender.java
UTF-8
5,185
2.578125
3
[ "Apache-2.0" ]
permissive
/* * 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 eu.fivegex.monitoring.appl.probes.delay.unidirectional; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author uceeftu */ public class UDPMgmSender implements Runnable { DatagramSocket mgmSocket; InetAddress mgmSourceAddr; int mgmSourcePort; int packets; int timeout; int interval; // every interval seconds Thread t; Boolean isRunning = false; Long timeOffset; private Logger LOGGER = LoggerFactory.getLogger(UDPMgmSender.class); public UDPMgmSender(InetAddress mgmLocalAddr, int mgmLocalPort, InetAddress mgmSourceAddr, int mgmSourcePort, int packets, int timeout, int interval) throws SocketException, UnknownHostException { mgmSocket = new DatagramSocket(mgmLocalPort, mgmLocalAddr); this.mgmSourceAddr = mgmSourceAddr; this.mgmSourcePort = mgmSourcePort; this.packets = packets; this.timeout = timeout; this.interval = interval * 1000; // converting to milliseconds } public void start() { if (!isRunning) { isRunning = true; t = new Thread(this); t.start(); } } public void stop() { if (isRunning) { isRunning = false; mgmSocket.close(); } } private Long measureTimeOffset() { DatagramPacket pingPacket; DatagramPacket replyPacket; int sequenceNumber = 0; int timedOut = 0; long timeOffsetSum = 0; LOGGER.info("Measuring time offset"); while (sequenceNumber < packets) { long nsSend = System.nanoTime(); String pingPayload = "PING " + sequenceNumber + " " + nsSend + " \n"; byte[] sendBuf = pingPayload.getBytes(); pingPacket = new DatagramPacket(sendBuf, sendBuf.length, mgmSourceAddr, mgmSourcePort); try { mgmSocket.send(pingPacket); byte[] rcvBuf = new byte[1024]; replyPacket = new DatagramPacket(rcvBuf, rcvBuf.length); mgmSocket.setSoTimeout(timeout); mgmSocket.receive(replyPacket); long nsReceived = System.nanoTime(); String pongPayload = new String(replyPacket.getData()); String [] pongPayloadFields = pongPayload.split(" "); Integer receivedSequenceNumber = Integer.valueOf(pongPayloadFields[1]); Long nsSent = Long.valueOf(pongPayloadFields[2]); Long nsSourceReceived = Long.valueOf(pongPayloadFields[3]); LOGGER.debug("receivedSequenceNumber => " + receivedSequenceNumber); // this should always be true as an exception would be raised before if (receivedSequenceNumber.equals(sequenceNumber) && nsSent.equals(nsSend)) { // we double check we got the correct reply long rtt = (nsReceived - nsSend); long timeOffsetSample = nsSourceReceived - nsSent - (rtt/2); timeOffsetSum += timeOffsetSample; LOGGER.debug("Offset evaluated: " + timeOffsetSample); } } catch (SocketTimeoutException e) { timedOut++; LOGGER.warn("Timeout for REPLY packet " + sequenceNumber); } catch (SocketException so) { LOGGER.info("Socket was closed: shutting down"); break; } catch (IOException e) { LOGGER.warn("Error while sending PING packet: " + sequenceNumber); } sequenceNumber++; } Long avgTimeOffsetMs = timeOffsetSum/(packets - timedOut)/(1000*1000); LOGGER.info("AVG measured time offset => " + avgTimeOffsetMs); return avgTimeOffsetMs; } public Long getTimeOffset() { synchronized(this) { return this.timeOffset; } } private void setTimeOffset(Long timeOffset) { synchronized(this) { this.timeOffset = timeOffset; } } @Override public void run() { Long tOffset; while (isRunning) { try { tOffset = measureTimeOffset(); setTimeOffset(tOffset); Thread.sleep(interval); } catch (InterruptedException ie) { LOGGER.info("Thread was stopped"); isRunning = false; } } } }
true
53bec16e05c0a8d8114bae0ade844ef6ebc10e45
Java
ITriangle/HadoopCoreDamon
/hadoop-spark/MapReduceMultipleOutputs/src/main/java/utils/ORCSample.java
UTF-8
2,557
2.46875
2
[]
no_license
package utils; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.orc.TypeDescription; import org.apache.orc.mapred.OrcStruct; import org.apache.orc.mapreduce.OrcInputFormat; import org.apache.orc.mapreduce.OrcOutputFormat; /** * Created by wl on 1/16/18. */ public class ORCSample { public static class ORCMapper extends Mapper<NullWritable, OrcStruct, Text, Text> { public void map(NullWritable key, OrcStruct value, Context output) throws IOException, InterruptedException { output.write((Text) value.getFieldValue(1), (Text) value.getFieldValue(2)); } } public static class ORCReducer extends Reducer<Text, Text, NullWritable, OrcStruct> { private TypeDescription schema = TypeDescription.fromString("struct<name:string,mobile:string>"); private OrcStruct pair = (OrcStruct) OrcStruct.createValue(schema); private final NullWritable nw = NullWritable.get(); public void reduce(Text key, Iterable<Text> values, Context output) throws IOException, InterruptedException { for (Text val : values) { pair.setFieldValue(0, key); pair.setFieldValue(1, val); output.write(nw, pair); } } } public static void main(String args[]) throws Exception { Configuration conf = new Configuration(); conf.set("orc.mapred.output.schema", "struct<name:string,mobile:string>"); Job job = Job.getInstance(conf, "ORC Test"); job.setJarByClass(ORCSample.class); job.setMapperClass(ORCMapper.class); job.setReducerClass(ORCReducer.class); job.setInputFormatClass(OrcInputFormat.class); job.setOutputFormatClass(OrcOutputFormat.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(OrcStruct.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
true
3615d7adc04075b87d231107154650379c3893a5
Java
RamsayBoy/CRM-sprint3-ISI
/src/main/java/kapesystems/crmsprint3isi/CrmSprint3IsiApplication.java
UTF-8
332
1.6875
2
[ "MIT" ]
permissive
package kapesystems.crmsprint3isi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CrmSprint3IsiApplication { public static void main(String[] args) { SpringApplication.run(CrmSprint3IsiApplication.class, args); } }
true
27697bd638502149fa07f0d606d3d76d5dd12043
Java
juanbecerra/WebCenter_FastStart
/2BSorted/aggregatedtasklist/code/java/AggregatedTaskList/Model/src/au/com/leighton/portal/aggregatedtasklist/model/util/PropertyUtil.java
UTF-8
3,271
2.265625
2
[]
no_license
package au.com.leighton.portal.aggregatedtasklist.model.util; import java.text.MessageFormat; import java.util.ResourceBundle; import java.util.Set; import oracle.javatools.resourcebundle.BundleFactory; public class PropertyUtil { private PropertyUtil() { super(); } private static ResourceBundle _resourceBundle = null; private static ResourceBundle getResourceBundle() { if (_resourceBundle == null) { _resourceBundle = BundleFactory.getBundle("au.com.leighton.portal.aggregatedtasklist.model.AggregatedTaskList"); } return _resourceBundle; } private static String getResourceValue(String key, Object[] parameters) { String result = null; String stringVal = getResourceBundle().getString(key); if ((stringVal != null) && (stringVal.trim().length() > 0)) { if (parameters != null) { result = MessageFormat.format(stringVal, parameters); } else { result = stringVal; } } return result; } public static String getServiceWSDL() { if (EnvironmentUtil.isDevelopment()) { return getResourceValue("service.WSDL.DEV", null); } else if (EnvironmentUtil.isSIT()) { return getResourceValue("service.WSDL.SIT", null); } else if (EnvironmentUtil.isUAT()) { return getResourceValue("service.WSDL.UAT", null); } else if (EnvironmentUtil.isPSUP()) { return getResourceValue("service.WSDL.PSUP", null); } else { return getResourceValue("service.WSDL.PROD", null); } } public static String getServiceNamespace() { return getResourceValue("service.namespace", null); } public static String getServiceName() { return getResourceValue("service.name", null); } public static String getDefaultSubjectText() { return getResourceValue("default.task.subject.text", null); } public static String getWarningMessageSystemsDown(Set<String> systemNames) { String result = null; if (systemNames != null) { if (systemNames.size() == 1) { result = getResourceValue("warning.message.1.system.down", systemNames.toArray()); } else { StringBuilder systems = new StringBuilder(); for (String systemName : systemNames) { if (systems.length() > 0) { systems.append(", "); } systems.append(systemName); } result = getResourceValue("warning.message.many.systems.down", new String[] { systems.toString() }); } } return result; } }
true
d89ab6dbba705ea322a4764afd1b39ea569c898b
Java
aymanBA92/bumblebee-plugin
/src/test/java/com/agiletestware/bumblebee/pc/RunPcTestContextImplTest.java
UTF-8
5,965
1.9375
2
[]
no_license
package com.agiletestware.bumblebee.pc; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import org.junit.Test; import com.agiletestware.bumblebee.BumblebeeGlobalConfig; import com.agiletestware.bumblebee.client.utils.action.RetrySettings; import hudson.FilePath; /** * Tests for {@link RunPcTestContextImpl}. * * @author Sergey Oplavin * */ public class RunPcTestContextImplTest { @Test public void testGetBumblebeeUrl() { final String expBumblebeeUrl = "exp bbe url"; final RunPcTestBuildStep step = new RunPcTestBuildStep(); step.setOutputDir("output"); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, createGlobalConfigMock(expBumblebeeUrl, null, null, null, null, 0), new FilePath(new File(""))); assertEquals(expBumblebeeUrl, context.getBumblebeeUrl()); } @Test public void testGetPcConnectionParameters() { final String almUrl = "alm"; final String pcUrl = "pcUrl"; final String user = "user"; final String pwd = "pwd"; final String domain = "domain"; final String project = "project"; final RunPcTestBuildStep step = new RunPcTestBuildStep(); step.setOutputDir("output"); step.setDomain(domain); step.setProject(project); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, createGlobalConfigMock(null, almUrl, pcUrl, user, pwd, 0), new FilePath(new File(""))); final PcConnectionParameters params = context.getConnectionParameters(); assertEquals(almUrl, params.getAlmUrl()); assertEquals(pcUrl, params.getPcUrl()); assertEquals(user, params.getUser()); assertEquals(pwd, params.getPassword()); assertEquals(domain, params.getDomain()); assertEquals(project, params.getProject()); } @Test public void testGetOutputDir() { final RunPcTestBuildStep step = new RunPcTestBuildStep(); final File file = new File("temp"); step.setOutputDir("output"); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, mock(BumblebeeGlobalConfig.class), new FilePath(file)); assertEquals(new File(file, "output"), context.getOutputDir()); } @Test public void testGetStartRunParameters() { final PostRunAction action = PostRunAction.COLLATE_AND_ANALYZE; final String testPath = "Subject\\aaa"; final String testSetPath = "Root\\aaa"; final int timeSlotDuration = 42; final RunPcTestBuildStep step = new RunPcTestBuildStep(); step.setOutputDir("output"); step.setPostRunActionString(action.getLabel()); step.setTestPlanPath(testPath); step.setTestLabPath(testSetPath); step.setTimeslotDuration(timeSlotDuration); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, mock(BumblebeeGlobalConfig.class), new FilePath(new File(""))); final StartRunParameters params = context.getStartRunParameters(); assertEquals(action, params.getPostRunAction()); assertEquals(testPath, params.getTestPath()); assertEquals(testSetPath, params.getTestSetPath()); assertEquals(timeSlotDuration, params.getTimeslotDuration()); } @Test public void testGetRetrySettings() { final int retryCount = 1; final int retryInterval = 2; final double increaseFactor = 2.0; final RunPcTestBuildStep step = new RunPcTestBuildStep(); step.setOutputDir("output"); step.setRetryCount(retryCount); step.setRetryInterval(retryInterval); step.setRetryIntervalMultiplier(increaseFactor); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, mock(BumblebeeGlobalConfig.class), new FilePath(new File(""))); final RetrySettings settings = context.getRetrySettings(); assertEquals(retryCount, settings.getRetryAttempts()); assertEquals(retryInterval, settings.getRetryIntervalSeconds()); assertEquals(increaseFactor, settings.getRetryIntervalMultiplyFactor(), 0); } @Test public void testGetPollingInterval() { final int pollingInterval = 42; final RunPcTestBuildStep step = new RunPcTestBuildStep(); step.setOutputDir("output"); step.setPollingInterval(pollingInterval); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, mock(BumblebeeGlobalConfig.class), new FilePath(new File(""))); assertEquals(pollingInterval, context.getPollingInterval()); } @Test public void testGetTimeOutFromTask() { final int timeout = 42; final RunPcTestBuildStep step = new RunPcTestBuildStep(); step.setOutputDir("output"); step.setTimeout(timeout); final BumblebeeGlobalConfig global = mock(BumblebeeGlobalConfig.class); when(global.getPcTimeOut()).thenReturn(24); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, global, new FilePath(new File(""))); assertEquals(timeout * 60, context.getTimeout()); } @Test public void testGetTimeOutFromGlobal() { final int timeout = 42; final RunPcTestBuildStep step = new RunPcTestBuildStep(); step.setOutputDir("output"); final BumblebeeGlobalConfig global = mock(BumblebeeGlobalConfig.class); when(global.getPcTimeOut()).thenReturn(timeout); final RunPcTestContextImpl context = new RunPcTestContextImpl(step, global, new FilePath(new File(""))); assertEquals(timeout * 60, context.getTimeout()); } private BumblebeeGlobalConfig createGlobalConfigMock(final String bumblbeeUrl, final String almUrl, final String pcUrl, final String userName, final String pwd, final int pcTimeout) { final BumblebeeGlobalConfig conf = mock(BumblebeeGlobalConfig.class); when(conf.getBumblebeeUrl()).thenReturn(bumblbeeUrl); when(conf.getQcUrl()).thenReturn(almUrl); when(conf.getPcUrl()).thenReturn(pcUrl); when(conf.getQcUserName()).thenReturn(userName); when(conf.getPassword()).thenReturn(pwd); when(conf.getPcTimeOut()).thenReturn(pcTimeout); return conf; } }
true
820361e4f9cce1eca0d6a4a06ccff6a2288801ba
Java
NecoNicoUsedTradeProject/neconico
/src/main/java/com/neconico/neconico/restcontroller/store/StoreReviewRestController.java
UTF-8
1,177
2.046875
2
[ "MIT" ]
permissive
package com.neconico.neconico.restcontroller.store; import com.neconico.neconico.config.web.LoginUser; import com.neconico.neconico.dto.users.SessionUser; import com.neconico.neconico.service.store.StoreReviewService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @RequiredArgsConstructor @RestController public class StoreReviewRestController { private final StoreReviewService storeReviewService; @PostMapping("/mystore/review/{purchasedId}/new") public void storeReviewCreate(@PathVariable("purchasedId") Long purchasedId, @RequestParam(name = "content") String content){ storeReviewService.createStoreReview(purchasedId, content); } @PostMapping("/mystore/review/{purchasedId}/edit") public void storeReviewModify(@PathVariable("purchasedId") Long purchasedId, @RequestParam(name = "content") String content) { storeReviewService.updateStoreReview(purchasedId, content); } @PostMapping("/mystore/review/{purchasedId}/delete") public void storeReviewDelete(@PathVariable("purchasedId") Long purchasedId){ storeReviewService.deleteStoreReview(purchasedId); } }
true
ccb385b2f18ca7ae66303f558a6900006dc90f4e
Java
ArtemMalash/zenna
/src/main/java/com/project/store/controllers/ProductController.java
UTF-8
2,154
2.40625
2
[]
no_license
package com.project.store.controllers; import com.project.store.model.Product; import com.project.store.repos.CategoryRepo; import com.project.store.repos.ProductRepo; import com.project.store.repos.SubcategoryRepo; import com.project.store.services.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @Controller public class ProductController{ @Autowired ProductRepo productRepo; private ProductService productService = new ProductService(); @PostMapping("/newProduct") public String addProduct(Product product, @RequestParam("file") MultipartFile file, Model model) throws IOException { if(!file.isEmpty()){ product.setImage(file.getBytes()); }else{ product.setImage(null); } productRepo.save(product); return "redirect:/shop"; } @PostMapping("/editProduct") public String editProduct(Product product, @RequestParam("file") MultipartFile file, Model model) throws IOException { if(!file.isEmpty()){ product.setImage(file.getBytes()); }else{ product.setImage(productRepo.getById(product.getId()).getImage()); } productRepo.save(product); return "redirect:/shop"; } @GetMapping("/productImage/{id}") public void getImage(@PathVariable("id") Long id, HttpServletResponse response) { productService.writeImageToResponse(productRepo.getById(id).getImage(), response); } @GetMapping("/deleteProduct/{id}") public String deleteProduct(@PathVariable Long id){ productRepo.deleteById(id); return "redirect:/shop"; } }
true
53c846204b052dbcc8335a74130b45960c7a67d7
Java
RoboDilbert/FRC-2020-Infinite-Recharge
/Competition-Code/src/main/java/frc/robot/subsystems/LiftSystem.java
UTF-8
2,451
2.71875
3
[]
no_license
package frc.robot.subsystems; import frc.robot.util.Constants; import com.revrobotics.CANEncoder; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMax.IdleMode; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class LiftSystem{ private static CANSparkMax lifterMotor1; private static CANSparkMax lifterMotor2; private static CANEncoder lifterMotor1Encoder; private static CANEncoder lifterMotor2Encoder; private static DoubleSolenoid m_pinLock1; //private DoubleSolenoid m_pinLock2; public enum LifterState{ FORWARD, REVERSE, STOP; } public static void init(){ lifterMotor1 = new CANSparkMax(Constants.lifterLeftMotorID,MotorType.kBrushless); lifterMotor1.setIdleMode(IdleMode.kBrake); lifterMotor2 = new CANSparkMax(Constants.lifterRightMotorID,MotorType.kBrushless); lifterMotor2.setIdleMode(IdleMode.kBrake); lifterMotor1Encoder = lifterMotor1.getEncoder(); lifterMotor2Encoder = lifterMotor2.getEncoder(); m_pinLock1 = new DoubleSolenoid(Constants.pinLockForwardSolenoid, Constants.pinLockBackSolenoid); // m_pinLock2 = new DoubleSolenoid(1, 0); } public void liftLock(){ m_pinLock1.set(Value.kForward); } public void liftUnlock(){ m_pinLock1.set(Value.kReverse); } public static void controlLifter(LifterState value){ powerLifter(lifterMotor1, lifterMotor2, value); } private static void powerLifter(SpeedController motor1, SpeedController motor2, LifterState value){ if(value == LifterState.FORWARD){ motor1.set(-Constants.lifterSpeedUp); motor2.set(Constants.lifterSpeedUp); } else if(value == LifterState.REVERSE){ motor1.set(Constants.lifterSpeedDown); motor2.set(-Constants.lifterSpeedDown); } else if (value == LifterState.STOP){ motor1.set(0); motor2.set(0); } } public void debugLift(){ SmartDashboard.putNumber("Lift Motor 1 Encoder",lifterMotor1Encoder.getPosition()); SmartDashboard.putNumber("Lift Motor 2 Encoder", lifterMotor2Encoder.getPosition()); } }
true