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
4d2bae0fb15a848dbd819f263a79e642f85ad745
Java
denkprozess/IntelligentSystems07
/src/main/java/UE4/ScheduledJob.java
UTF-8
513
2.65625
3
[]
no_license
package UE4; public class ScheduledJob { private Job job; private int start; private int end; private ConfigurationSchedule schedule; public ScheduledJob(Job job, int start, int end, ConfigurationSchedule schedule) { this.job = job; this.start = start; this.end = end; this.schedule = schedule; } public Job getJob() { return job; } public int getStart() { return start; } public int getEnd() { return end; } public ConfigurationSchedule getSchedule() { return schedule; } }
true
0e8cf9bc1c68bb5f550faa38056ce52e2bf5cce0
Java
SivPal12/PG5100
/forelesning02/2_7-rmi-egentrening/src/main/java/no/nith/pg5100/BillingService.java
UTF-8
439
1.929688
2
[]
no_license
package no.nith.pg5100; import java.math.BigDecimal; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.List; public interface BillingService extends Remote { void registerInvoice(Invoice invoice) throws RemoteException; List<Invoice> getRegisteredInvoices() throws RemoteException; BigDecimal getTotalAmount() throws RemoteException; void deleteInvoice(int invoiceId) throws RemoteException; }
true
0236c7be6cd81e2b36e53c2e6a7f2d914b959a90
Java
olukayodepaul/mobiletreaderv3
/app/src/main/java/com/mobile/mtrader/util/AppUtil.java
UTF-8
2,950
2.4375
2
[]
no_license
package com.mobile.mtrader.util; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import java.net.InetAddress; public class AppUtil { static Toast mToast; public static void showToast(Context context, String statusMsg) { if (mToast != null) mToast.cancel(); mToast = Toast.makeText(context, statusMsg, Toast.LENGTH_SHORT); mToast.show(); } public static void showAlertDialog(Context context, String title, String msg, String buttons) { final AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle(title) .setCancelable(false) .setMessage(msg) .setNegativeButton(buttons, (paramDialogInterface, paramInt) -> { paramDialogInterface.dismiss(); }); dialog.show(); } public static void showAlertDialogWithIntent(Context context, String title, String msg, String buttons, Class object) { final AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle(title) .setMessage(msg) .setCancelable(false) .setNegativeButton(buttons, (DialogInterface paramDialogInterface, int paramInt) -> { Intent intent = new Intent(context, object); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(intent); }); dialog.show(); } public static boolean checkConnection(Context context) { return ((ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null; } public static boolean checkConnections(Context context) { final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo(); if (activeNetworkInfo != null) { // connected to the internet if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // connected to wifi return true; } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // connected to the mobile provider's data plan return true; } } return false; //3.554547 } public static boolean insideRadius(double custLat, double custLng, double curLat, double curLng) { int ky = 400000/360; //40000/360; double kx = Math.cos(Math.PI*custLat/180) * ky; double dx = Math.abs(custLng-curLng)*kx; double dy = Math.abs(custLat-curLat)*ky; return Math.sqrt(dx*dx+dy*dy)<=5; } }
true
9061cdbaed0c0080d76d5a7dc3b7cd3b5989ddee
Java
atok/twilio-experiment
/src/main/java/atk/handlers/ErrorHandler.java
UTF-8
3,681
2.234375
2
[]
no_license
package atk.handlers; import atk.model.ErrorMessage; import atk.utils.JsonSender; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.util.JSONPObject; import io.undertow.Handlers; import io.undertow.io.Sender; import io.undertow.server.DefaultResponseListener; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.ResponseCodeHandler; import io.undertow.util.Headers; import io.undertow.util.StatusCodes; import javax.xml.ws.spi.http.HttpExchange; import io.undertow.server.HttpHandler; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class ErrorHandler implements HttpHandler { private volatile io.undertow.server.HttpHandler next = ResponseCodeHandler.HANDLE_404; /** * The response codes that this handler will handle. If this is null then it will handle all 4xx and 5xx codes. */ private volatile Set<Integer> responseCodes = null; public ErrorHandler(final io.undertow.server.HttpHandler next) { this.next = next; } public ErrorHandler() { } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.addDefaultResponseListener(new DefaultResponseListener() { @Override public boolean handleDefaultResponse(final HttpServerExchange exchange) { if (!exchange.isResponseChannelAvailable()) { return false; } Set<Integer> codes = responseCodes; if (codes == null ? exchange.getResponseCode() >= 400 : codes.contains(Integer.valueOf(exchange.getResponseCode()))) { final ErrorMessage errorMessage = new ErrorMessage(); errorMessage.message = "not found"; errorMessage.requestUrl = exchange.getRequestURL(); exchange.setResponseCode(404); try { JsonSender.sendResource(exchange, "error", errorMessage); } catch (JsonProcessingException e) { e.printStackTrace(); } return true; } return false; } }); try { next.handleRequest(exchange); } catch (Exception e) { if(exchange.isResponseChannelAvailable()) { final ErrorMessage errorMessage = new ErrorMessage(); errorMessage.stackTrace = ExceptionUtils.getStackTrace(e); errorMessage.requestUrl = exchange.getRequestURL(); exchange.setResponseCode(500); JsonSender.sendResource(exchange, "error", errorMessage); } } } public io.undertow.server.HttpHandler getNext() { return next; } public ErrorHandler setNext(final io.undertow.server.HttpHandler next) { Handlers.handlerNotNull(next); this.next = next; return this; } public Set<Integer> getResponseCodes() { return Collections.unmodifiableSet(responseCodes); } public ErrorHandler setResponseCodes(final Set<Integer> responseCodes) { this.responseCodes = new HashSet<Integer>(responseCodes); return this; } public ErrorHandler setResponseCodes(final Integer... responseCodes) { this.responseCodes = new HashSet<Integer>(Arrays.asList(responseCodes)); return this; } }
true
ad4326620dcdf46c4dc1e798d8bc8cc71fd721b6
Java
shalongteng/netty
/src/main/java/com/slt/netty/io/nio/another/TestChannel2.java
UTF-8
1,080
3.234375
3
[]
no_license
package com.slt.netty.io.nio.another; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; /** * http://ifeve.com/java-nio-channel-to-channel/ * 如果两个通道中有一个是FileChannel,那你可以直接将数据从一个channel传输到另外一个channel。 */ public class TestChannel2 { public static void main(String[] args) throws Exception { String path = "G:\\git_workspace\\netty\\src\\main\\java\\com\\slt\\netty\\io\\nio\\another\\TestChannel.java"; //随机流(RandomAccessFile)不属于IO流,支持对文件的读取和写入随机访问。 RandomAccessFile fromFile = new RandomAccessFile(path, "rw"); FileChannel fromChannel = fromFile.getChannel(); RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw"); FileChannel toChannel = toFile.getChannel(); long position = 0; long count = fromChannel.size(); toChannel.transferFrom(fromChannel, position,count); } }
true
5b4245e06b4cb6e9c22eb923aebe007a9925c84c
Java
civyshk/anstop
/app/src/main/java/An/stop/AccelerometerListener.java
UTF-8
3,581
2.125
2
[]
no_license
/*************************************************************************** * Copyright (C) 2009 by mj * * fakeacc.mj@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ package An.stop; import java.util.List; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class AccelerometerListener implements SensorEventListener { private SensorManager sensorManager; private List<Sensor> sensors; private Sensor sensor; private long lastUpdate = -1; private long currentTime = -1; private float last_x, last_y, last_z; private float current_x, current_y, current_z, currenForce; private static final int FORCE_THRESHOLD = 900; private final int DATA_X = SensorManager.DATA_X; private final int DATA_Y = SensorManager.DATA_Y; private final int DATA_Z = SensorManager.DATA_Z; private Clock clock; public AccelerometerListener(Activity parent, Clock clock) { SensorManager sensorManager = (SensorManager) parent.getSystemService(Context.SENSOR_SERVICE); this.sensorManager = sensorManager; this.sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER); this.clock = clock; if (sensors.size() > 0) { sensor = sensors.get(0); } } public void start () { if (sensor!=null) { sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME); } } public void stop () { sensorManager.unregisterListener(this); } public void onAccuracyChanged(Sensor s, int valu) { //nothing to do yet } public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER || event.values.length < 3) return; currentTime = System.currentTimeMillis(); if ((currentTime - lastUpdate) > 100) { long diffTime = (currentTime - lastUpdate); lastUpdate = currentTime; current_x = event.values[DATA_X]; current_y = event.values[DATA_Y]; current_z = event.values[DATA_Z]; currenForce = Math.abs(current_x+current_y+current_z - last_x - last_y - last_z) / diffTime * 10000; if (currenForce > FORCE_THRESHOLD) clock.count(); //phone has been shaken last_x = current_x; last_y = current_y; last_z = current_z; } } }
true
c3f9d9ceb6b0fbbd0bda6daa9084481941409509
Java
P79N6A/icse_20_user_study
/methods/Method_54148.java
UTF-8
359
1.695313
2
[]
no_license
/** * Unsafe version of: {@link #aiGetMaterialProperty GetMaterialProperty} */ public static int naiGetMaterialProperty(long pMat,long pKey,int type,int index,long mPropOut){ long __functionAddress=Functions.GetMaterialProperty; if (CHECKS) { AIMaterial.validate(pMat); } return invokePPPI(pMat,pKey,type,index,mPropOut,__functionAddress); }
true
788d89361030750414b12cca34a4943240918a30
Java
anttiranta/feeds-reader-java
/src/main/java/com/antti/task/item/importing/Helper.java
UTF-8
356
2.203125
2
[]
no_license
package com.antti.task.item.importing; import org.springframework.stereotype.Component; @Component public class Helper { public String normalizeUrl(String url) { return (url != null && !url.startsWith("http://") && !url.startsWith("https://")) ? "http://" + url : url; } }
true
d8923efd00f9f292b9f5d03979ed024b6e9ad614
Java
endrec/sdn4-abstraction-demo
/src/main/java/com/example/demo/security/domain/AuthUser.java
UTF-8
1,474
2.375
2
[]
no_license
package com.example.demo.security.domain; import com.example.demo.domain.UserRole; import com.example.demo.domain.node.User; import lombok.RequiredArgsConstructor; import lombok.experimental.Delegate; import org.springframework.security.core.GrantedAuthority; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * @author Endre Czirbesz <endre@czirbesz.hu> */ public class AuthUser extends org.springframework.security.core.userdetails.User { private static final long serialVersionUID = 1L; @Delegate private final User user; @RequiredArgsConstructor private static class AuthRole implements GrantedAuthority { private static final long serialVersionUID = 1L; private final UserRole role; @Override public String getAuthority() { return role.toString(); } @Override public String toString() { return role.toString(); } } public AuthUser(final User user) { super(user.getEmail(), user.getPassword(), getAuthorityRoles(user.getRoles())); this.user = user; } private static Collection<GrantedAuthority> getAuthorityRoles(final Collection<UserRole> roles) { final Set<GrantedAuthority> authorities = new HashSet<>(); roles.forEach(role -> authorities.add(new AuthRole(role))); return authorities; } @Override public boolean isAccountNonLocked() { return true; } }
true
accaea9b751ed6fc99a24d94102b9d692d91e9e1
Java
mitraman/hal-forms-spring-example
/src/main/java/com/example/demo/APIListingController.java
UTF-8
5,393
2.109375
2
[]
no_license
package com.example.demo; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.stream.Collectors; import javax.persistence.Entity; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.RepresentationModel; import org.springframework.hateoas.server.core.Relation; import org.springframework.http.HttpEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class APIListingController { Logger log = LoggerFactory.getLogger(SandboxController.class); private final APIListingRepository repository; private final String APIListingPath = "/sandbox/apis"; APIListingController(APIListingRepository repository) { this.repository = repository; } @GetMapping(value = "/sandbox/apis", produces = { "application/hal+json" }) CollectionModel<EntityModel<APIListing>> all() { List<EntityModel<APIListing>> apiListingCollection = repository.findAll().stream() .map(apiListing -> EntityModel.of(apiListing, linkTo(methodOn(APIListingController.class).one(apiListing.getId())).withSelfRel())) .collect(Collectors.toList()); return CollectionModel.of(apiListingCollection, linkTo(methodOn(APIListingController.class).all()).withSelfRel()); } @GetMapping(value = "/sandbox/apis/{id}", produces = { "application/hal+json", "application/prs.hal-forms+json" }) EntityModel<APIListing> one(@PathVariable Long id) { APIListing apiListing = repository.findById(id).get(); return EntityModel.of(apiListing, linkTo(methodOn(APIListingController.class).one(id)).withSelfRel() .andAffordance(afford(methodOn(APIListingController.class).updateAPIListing(apiListing)))); } // Factory endpoint for creating a new API listing @PostMapping(value = "/sandbox/apis", produces = { "application/hal+json" }) APIListing newAPIListing(@RequestBody APIListing newAPIListing) { return repository.save(newAPIListing); } // Patch an existing endpoint @PatchMapping(value ="/sandbox/apis/{id}", produces = { "application/hal+json" }) APIListing updateAPIListing(@RequestBody APIListing updatedAPIListing) { // TODO: perform the update return updatedAPIListing; } // A VO to build the form data. This may not be needed in the future. class APIListingFormRep extends RepresentationModel<APIListingFormRep> { String name; String baseURI; APIListingFormRep(String name, String baseURI) { this.name = name; this.baseURI = baseURI; } public String getName() { return this.name; } public String getBaseURI() { return this.baseURI; } public void setName(String name) { this.name = name; } public void setBaseURI(String baseURI) { this.baseURI = baseURI; } } // This endpoint serves the HAL-FORM for the api-listing rel @GetMapping(value = "/sandbox/rels/api-listing", produces = { "application/prs.hal-forms+json" }) EntityModel<APIListingFormRep> newAPIForm(@RequestParam(required = false) Long _id) { // Create an empty VO so that we can generate a form based on it's properties APIListingFormRep apiListingForm = new APIListingFormRep("", ""); // The use of '_id' is a non-standard implementation, but we're using it for now to avoid the complexity // of handling _hdoc parameters. if (_id != null) { // Try to retrieve an API listing matching this id APIListing apiListing = repository.findById(_id).get(); apiListingForm.setName(apiListing.getName()); apiListingForm.setBaseURI(apiListing.getBaseURI()); // Return a model with an affordance to the update listing method. This will generate a form // through the middleware. return EntityModel.of(apiListingForm, linkTo(methodOn(APIListingController.class).newAPIForm(_id)).withSelfRel() .andAffordance(afford(methodOn(APIListingController.class).updateAPIListing(apiListing)))); } // We need to create a link to self and an 'affordance' that points to the target of the form return EntityModel.of(apiListingForm, linkTo(methodOn(APIListingController.class).newAPIForm(null)).withSelfRel() .andAffordance(afford(methodOn(APIListingController.class).newAPIListing(null)))); } }
true
c07f316bed743fca5412698c8ac576997b9cfe8f
Java
Mariusz3100/MaDKit
/src/madkit/kernel/NetworkAgent.java
UTF-8
14,766
1.875
2
[]
no_license
/* * Copyright 1997-2014 Fabien Michel, Olivier Gutknecht, Jacques Ferber * * This file is part of MaDKit. * * MaDKit is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MaDKit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MaDKit. If not, see <http://www.gnu.org/licenses/>. */ package madkit.kernel; import static madkit.kernel.AbstractAgent.State.LIVING; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import madkit.agr.CloudCommunity; import madkit.agr.LocalCommunity; import madkit.agr.LocalCommunity.Groups; import madkit.agr.LocalCommunity.Roles; import madkit.agr.Organization; import madkit.gui.AgentStatusPanel; import madkit.kernel.Madkit.LevelOption; import madkit.message.EnumMessage; import madkit.message.ObjectMessage; /** * @author Fabien Michel * @version 0.9 * @since MaDKit 5 * */ final class NetworkAgent extends Agent { final private ConcurrentHashMap<KernelAddress, KernelConnection> peers = new ConcurrentHashMap<>(); private KernelServer myServer; private MultiCastListener multicastListener; private boolean running = true; private AgentAddress kernelAgent; // /** // * // */ // NetworkAgent() { // peers = new ConcurrentHashMap<><KernelAddress, KernelConnection>(); // // setLogLevel(Level.OFF); // } // /** // * @return the netConfig // */ // public KernelServer getNetConfig() { // return myServer; // } /* (non-Javadoc) * @see madkit.kernel.AbstractAgent#activate() */ @Override protected void activate() { setName(super.getName()+getKernelAddress()); setLogLevel(LevelOption.networkLogLevel.getValue(getMadkitConfig())); // setLogLevel(Level.INFO); requestRole(LocalCommunity.NAME, Groups.NETWORK, madkit.agr.LocalCommunity.Roles.NET_AGENT); kernelAgent = getAgentWithRole(LocalCommunity.NAME, Groups.NETWORK, Organization.GROUP_MANAGER_ROLE); myThread.setPriority(Thread.MAX_PRIORITY-3); if(kernelAgent == null) throw new AssertionError(this+" no kernel agent to work with... Please bug report"); //build servers running = launchNetwork(); } /** * @return true if servers are launched */ private boolean launchNetwork() { if(ReturnCode.SUCCESS != createGroup(CloudCommunity.NAME, CloudCommunity.Groups.NETWORK_AGENTS,true)){ return false; } requestRole(CloudCommunity.NAME, CloudCommunity.Groups.NETWORK_AGENTS, CloudCommunity.Roles.NET_AGENT); myServer = KernelServer.getNewKernelServer(); if(myServer == null) { if (logger != null) logger.warning("\n\t\t\t\t---- Unable to start the Madkit kernel server ------\n"); stopNetwork(); return false; } myServer.activate(this); if (logger != null) logger.config("\n\t\t\t\t----- MaDKit server activated on "+myServer+" ------\n"); // build multicast listener try { multicastListener = MultiCastListener.getNewMultiCastListener(myServer.getPort()); multicastListener.activate(this); if (logger != null){ logger.config("\n\t\t\t\t----- MaDKit MulticastListener activated on "+MultiCastListener.ipAddress+" ------\n"); } } catch (final IOException e) { if (logger != null){ logger.warning("\n\t\t\t\t---- Unable to start a Multicast Listener "+e.getClass().getName()+" "+e.getMessage()+" ------\n"); } stopNetwork(); return false; } Message m = null; final ArrayList<Message> toDoList = new ArrayList<>(); do { if (logger != null) logger.finest("Waiting for some connections first"); m = waitNextMessage(400); if (m != null) { if(m.getSender() == null && m instanceof NetworkMessage && ((NetworkMessage)m).getCode() == NetCode.NEW_PEER_REQUEST) newPeerRequest((Socket) ((NetworkMessage) m).getContent()[0]);//FIXME verify that this is ok else toDoList.add(m); } } while (m != null); if (logger != null) logger.finest("Now purge mailbox"); for (final Message message : toDoList) { handleMessage(message); } if (logger != null) logger.finest("Now activating all connections"); for (final KernelConnection kc : peers.values()) { if (! kc.isActivated()) { kc.start(); } } AgentStatusPanel.updateAll(); if (logger != null){ logger.info("\n\t\t\t\t----- "+getKernelAddress()+" network started on "+myServer+" ------\n"); } return true; } /* (non-Javadoc) * @see madkit.kernel.Agent#live() */ @Override protected void live() { while(isAlive() && running){ handleMessage(waitNextMessage()); } } @Override protected void end() { stopNetwork(); } /** * */ private void stopNetwork() { if (logger != null){ logger.info("\n\t\t\t\t----- "+getKernelAddress()+" network closed ------\n"); logger.finer("Closing all connections : "+peers.values()); } for(final Map.Entry<KernelAddress, KernelConnection> entry : peers.entrySet()){ peerDeconnected(entry.getKey()); entry.getValue().closeConnection(); } peers.clear(); if (logger != null){ logger.finer("Closing multicast listener and kernel server"); } if (multicastListener != null) { multicastListener.stop(); } if (myServer != null) { myServer.stop(); myServer = null; } leaveGroup(CloudCommunity.NAME, CloudCommunity.Groups.NETWORK_AGENTS); AgentStatusPanel.updateAll(); } @SuppressWarnings("unchecked") private void handleMessage(final Message m) throws ClassCastException{ final AgentAddress sender = m.getSender(); if(sender == null){//contacted by my private objects (or by the kernel ? no) proceedEnumMessage((EnumMessage<?>) m); } else if(sender.isFrom(getKernelAddress())){//contacted locally switch (sender.getRole()) { case Roles.UPDATER://It is a CGR update broadcastUpdate(m); break; case Roles.EMMITER://It is a message to send elsewhere sendDistantMessage((ObjectMessage<Message>) m); break; case Roles.KERNEL://message from the kernel proceedEnumMessage((EnumMessage<?>) m); break; default: getLogger().severeLog("not understood :\n"+m); break; } } else{//distant message switch (sender.getRole()) { case Roles.UPDATER:////It is a distant CGR update if (logger != null){ final CGRSynchro synchro = (CGRSynchro) m; logger.finer("Injecting distant CGR " + synchro.getCode() + " on " + synchro.getContent()); } getMadkitKernel().injectOperation((CGRSynchro) m); break; case Roles.EMMITER://It is a distant message to inject if (logger != null) logger.finer("Injecting distant message "+getState()+" : "+m); getMadkitKernel().injectMessage((ObjectMessage<Message>) m); break; default: getLogger().severeLog("not understood :\n"+m); break; } } } @SuppressWarnings("unused") private void exit(){ running = false; } /** * Removes ka from peers and clean organization accordingly * @param ka */ private void peerDeconnected(final KernelAddress ka) { if (peers.remove(ka) != null) { if (logger != null) logger.info("\n\t\t\t\t----- " + getKernelAddress() + " deconnected from " + ka + "------\n"); getMadkitKernel().removeAgentsFromDistantKernel(ka); // System.err.println(getOrganizationSnapShot(false)); } } /** * @param s */ private void newPeerRequest(final Socket s) { if (logger != null) logger.fine("Contacted by peer "+s+" -> opening kernel connection"); KernelConnection kc = null; try { kc = new KernelConnection(this,s); } catch (final IOException e) { if (logger != null) logger.warning("I give up: Unable to contact peer on "+s+" because "+e.getMessage()); return; } if(logger != null) logger.finer("KC opened: "+kc+"\n\tsending connection INFO"); if (sendingConnectionInfo(kc)) { if (logger != null) logger.fine("Connection info sent, now waiting reply from " + kc.getDistantKernelSocket() + "..."); final KernelAddress dka = gettingConnectionInfo(kc); if (dka != null) addConnection(dka, kc, getState().equals(LIVING)); } } /** * @param kc * @param startConnection start to receive message if living */ private void addConnection(final KernelAddress ka, final KernelConnection kc, final boolean startConnection) { peers.put(ka,kc); if (logger != null) logger.info("\n\t\t\t\t----- "+getKernelAddress()+" now connected with "+kc.getKernelAddress()+"------\n"); if (startConnection) { kc.start(); } } /** * @param packet * @param startConnection start to receive message if living */ private void newPeerDetected(final DatagramPacket packet) { if (logger != null) logger.fine("Contacting peer: "+packet.getAddress()+" port = "+packet.getPort()+"\n\t-> opening KernelConnection"); KernelConnection kc = null; try { kc = new KernelConnection(this,packet.getAddress(),packet.getPort()); if(logger != null) logger.finer("KC created "+kc); } catch (final IOException e) { if (logger != null) logger.warning("Unable to contact peer: "+packet.getAddress()+" port = "+packet.getPort()+" because "+e.getMessage()); return; } final KernelAddress dka = gettingConnectionInfo(kc); if (dka != null) { if (logger != null) logger.finer("Now replying to " + dka); if (sendingConnectionInfo(kc)) addConnection(dka, kc, getState().equals(LIVING)); } } @SuppressWarnings("unused")//used by reflection private void connectToIp(final InetAddress ipAddress) throws IOException{ if (! ipAddress.equals(myServer.getIp())) { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(bos); dos.writeLong(System.nanoTime()); dos.close(); newPeerDetected(new DatagramPacket(bos.toByteArray(), 8, ipAddress, 4444)); } } /** * @param kc * @return */ private KernelAddress gettingConnectionInfo(final KernelConnection kc) { if (logger != null) logger.finest("Waiting distant kernel address..."); KernelAddress dka = null; try { dka = kc.waitForDistantKernelAddress(); if (logger != null) logger.finest("... Distant Kernel Address is "+dka+"\nWaiting distant organization info..."); // Map<String, Map<String, Map<String, Set<AgentAddress>>>> org = null; // try { // org = kc.waitForDistantOrg(); // if (logger != null) // logger.finer("... Distant organization received from "+dka+" Org is\n\n"+org+"\n"); // kernel.importDistantOrg(org); // } catch (Throwable e) { // e.printStackTrace(); // } // kernel.getMadkitKernel().importDistantOrg(cleanUp(kc.waitForDistantOrg(),dka)); return dka; } catch (final IOException | ClassNotFoundException e) { if(dka == null) getLogger().severeLog("I give up: Unable to get distant kernel address info on "+kc, e); else getLogger().severeLog("I give up: Unable to get distant organization from "+dka,e); } return null; } private boolean sendingConnectionInfo(final KernelConnection kc){ if (logger != null){ logger.fine("Sending connection info to "+(kc.getKernelAddress() == null ? kc.getDistantKernelSocket() : kc.getKernelAddress())); logger.finer("Local org is\n\n"+getOrganizationSnapShot(false)+"\n"); } try { kc.sendConnectionInfo(getKernelAddress(), getOrganizationSnapShot(false)); } catch (final IOException e) { if (logger != null) logger.warning("I give up: Unable to send connection info to "+(kc.getKernelAddress() == null ? kc.getDistantKernelSocket() : kc.getKernelAddress())+" because "+e.getMessage()); return false; } return true; } private Map<String, Map<String, Map<String, Set<AgentAddress>>>> cleanUp( Map<String, Map<String, Map<String, Set<AgentAddress>>>> organizationSnapShot, KernelAddress from) { for (Iterator<Entry<String, Map<String, Map<String, Set<AgentAddress>>>>> iterator = organizationSnapShot.entrySet().iterator(); iterator.hasNext();) { Entry<String, Map<String, Map<String, Set<AgentAddress>>>> org = iterator.next(); for (Iterator<Entry<String, Map<String, Set<AgentAddress>>>> iterator2 = org.getValue().entrySet().iterator(); iterator2.hasNext();) { Entry<String, Map<String, Set<AgentAddress>>> group = iterator2.next(); for (Iterator<Entry<String, Set<AgentAddress>>> iterator3 = group.getValue().entrySet().iterator(); iterator3.hasNext();) { Entry<String, Set<AgentAddress>> role = iterator3.next(); for (Iterator<AgentAddress> iterator4 = role.getValue().iterator(); iterator4.hasNext();) { final KernelAddress dka = iterator4.next().getKernelAddress(); if(! from.equals(dka) && ! peers.containsKey(dka)) iterator4.remove(); } if(role.getValue().isEmpty()){ iterator3.remove(); } } if(group.getValue().isEmpty()){ iterator2.remove(); } } if(org.getValue().isEmpty()){ iterator.remove(); } } return organizationSnapShot; } /** * @param message */ private void broadcastUpdate(final Message message) { if (logger != null){ logger.finer("Local CGR update\nBroadcasting "+" to "+peers.values()+message); // logger.finest("Local org is\n\n"+getOrganizationSnapShot(false)+"\n"); } for (final KernelConnection kc : peers.values()) { kc.sendMessage(message); } } private void sendDistantMessage(final ObjectMessage<Message> m){ if (logger != null) logger.finer("sending to "+m.getContent().getReceiver().getKernelAddress()+m); final KernelConnection kc = peers.get(m.getContent().getReceiver().getKernelAddress()); if(kc != null){ kc.sendMessage(m); } else { // if (m.getContent().getReceiver().isFrom(getKernelAddress())){//the agent address which is used has been encapsulated and is not up-to-date (agent) // getMadkitKernel().injectMessage(m); // } // else{ // m.getContent().getSender().getAgent().handleException(Influence.SEND_MESSAGE, new IOException(m.getContent().getReceiver().getKernelAddress().toString()+" is deconnected")); // } } } @Override public String getServerInfo() { if (myServer != null) { return myServer.toString(); } return ""; } }
true
345abbc71dd284646a6916b1e29f5ab47e5442e1
Java
jgoldstein46/CaptialTechGroup
/SmartAutoInsurance/src/main/java/RuleTable.java
UTF-8
1,528
2.921875
3
[]
no_license
public class RuleTable { private boolean isRaining; private int acceleration; private int risk; public RuleTable(boolean raining, int inputAcceleration) { isRaining = raining; acceleration = inputAcceleration; } public RuleTable(){ isRaining = false; acceleration = 0; } public boolean getIsRaining () { return isRaining; } public int getAcceleration () { return acceleration; } public void setProp (String prop, String value) { int lastIndx = prop.lastIndexOf(".csv"); prop = prop.substring(0,lastIndx); // prop = prop.substring(0,-3); // System.out.println(prop); // System.out.println(prop.equals("acceleration")); if (!value.equals("") && prop.equals("acceleration")) { // System.out.println(value); acceleration = Integer.parseInt(value); } else if (!value.equals("") && prop.equals("isRaining")) { isRaining = Boolean.parseBoolean(value); } } public void setAcceleration (int accel) { acceleration = accel; } public void setIsRaining (boolean raining) { isRaining = raining; } public int scoreRisk () { int totalRisk = 0; // System.out.println(acceleration); // System.out.println(isRaining); if (isRaining) { totalRisk += 5; } if (acceleration > 5){ totalRisk += 10; } return totalRisk; } }
true
cd3c58a9160b82bf776f2a9d42a78f069fd68dcf
Java
HiagoMM/Sistema-De-Vendas
/src/main/java/projeto/Service/ClienteServ.java
UTF-8
406
1.929688
2
[]
no_license
package projeto.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import projeto.Abstracts.ServiceAbs; import projeto.domain.entities.Cliente; import projeto.Repository.ClienteRep; @Service public class ClienteServ extends ServiceAbs<Cliente>{ @Autowired public ClienteServ(ClienteRep repository) { super(repository); } }
true
8d6f57ab529dbf730df1e57322112dd615595338
Java
AntiDesert5/Ingenieria-en-Computacion-UAEM
/AlgoritmosGeneticos/src/org/jgap/audit/FitnessImprovementMonitor.java
UTF-8
9,449
2.640625
3
[ "MIT" ]
permissive
/* * This file is part of JGAP. * * JGAP offers a dual license model containing the LGPL as well as the MPL. * * For licensing information please see the file license.txt included with JGAP * or have a look at the top of class org.jgap.Chromosome which representatively * includes the JGAP license policy applicable for any file delivered with JGAP. */ package org.jgap.audit; import java.util.*; import org.jgap.*; import org.jgap.eval.*; /** * Monitors the evolution and stops it if evolution does not make a progress * as desired. * For usage of this monitor class, see class examples.audit.EvolutionMonitorExample. * * @author Klaus Meffert * @since 3.4.4 */ public class FitnessImprovementMonitor implements IEvolutionMonitor { /** String containing the CVS revision. Read out via reflection!*/ private final static String CVS_REVISION = "$Revision: 1.4 $"; private int m_initialWaitSeconds; private int m_checkIntervalSeconds; private double m_improvedFitnessExpected; private long m_startMillis; private long m_lastCheckMillis; private double m_bestFitnessPreviously; private int m_checks; /** * Constructor. * * @param a_initialWaitSeconds number of seconds to wait until first check * @param a_checkIntervalSeconds number of seconds to wait after the previous * check (except for the first check, where a_initialWaitSeconds is taken) * @param a_improvedFitnessExpected number of fitness units the current best * solution evolved is better than the best solution from the previously check * * @author Klaus Meffert * @since 3.4.4 */ public FitnessImprovementMonitor(int a_initialWaitSeconds, int a_checkIntervalSeconds, double a_improvedFitnessExpected) { m_initialWaitSeconds = a_initialWaitSeconds; m_checkIntervalSeconds = a_checkIntervalSeconds; m_improvedFitnessExpected = a_improvedFitnessExpected; m_bestFitnessPreviously = FitnessFunction.NO_FITNESS_VALUE; } /** * Called after another evolution cycle has been executed. * * @param a_pop the currently evolved population * @param a_messages the monitor can append messages to indicate why it asks * evolution to stop * @return true: continue with the evolution; false: stop evolution * * @author Klaus Meffert * @since 3.4.4 */ public boolean nextCycle(Population a_pop, List<String> a_messages) { long currentMillis = System.currentTimeMillis(); boolean doCheck = false; if (m_checks == 0) { if (currentMillis - m_startMillis >= m_initialWaitSeconds * 1000) { doCheck = true; } } else { if (currentMillis - m_lastCheckMillis >= m_checkIntervalSeconds * 1000) { doCheck = true; } } if (doCheck) { // Let's verify the progress since our last check. // ----------------------------------------------- IChromosome best = a_pop.determineFittestChromosome(); if (best != null) { // A best solution exists. // ----------------------- if (Math.abs(m_bestFitnessPreviously - FitnessFunction.NO_FITNESS_VALUE) < FitnessFunction.DELTA) { // There was no previous best solution. // ------------------------------------ m_bestFitnessPreviously = best.getFitnessValue(); } else { // Is the current best solution better than the previous one? // ---------------------------------------------------------- if (Math.abs(best.getFitnessValue() - m_bestFitnessPreviously) < m_improvedFitnessExpected) { // Bad luck, not enough progress. // ------------------------------ a_messages.add("Not enough progress was made after initial delay"); return false; } else { m_bestFitnessPreviously = best.getFitnessValue(); } } } else { if (m_checks > 0) { // No result evolved during two check cycles. // ------------------------------------------ a_messages.add( "No solution at all was evolved during two check cycles."); return false; } } m_lastCheckMillis = System.currentTimeMillis(); m_checks++; } // No check needed yet. // -------------------- return true; } /** * Called just before the evolution starts. * * @param a_config the configuration used * * @author Klaus Meffert * @since 3.4.4 */ public void start(Configuration a_config) { m_startMillis = System.currentTimeMillis(); } /** * Called whenever it's worth monitoring. * * @param a_monitorEvent see constants at top of class IEvolutionMonitor * @param a_evolutionNo the index of the evolution round (1, 2, ...) * @param a_information event-specific information * * @author Klaus Meffert * @since 3.5 */ public void event(String a_monitorEvent, int a_evolutionNo, Object[] a_information) { // Just a sample implemetation here to show how to react to the specific // monitor events that are supported. // --------------------------------------------------------------------- if (a_monitorEvent == null) { // Should never happen. // -------------------- return; } if (a_information == null) { return; } // The events are queried in the chronological order they do appear. // ----------------------------------------------------------------- if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_REMOVE_CHROMOSOME)) { Population pop = (Population) a_information[0]; Integer chromosomeIndex = (Integer) a_information[1]; } if (a_monitorEvent.equals(IEvolutionMonitor. MONITOR_EVENT_BEFORE_UPDATE_CHROMOSOMES1)) { Population pop = (Population) a_information[0]; } if (a_monitorEvent.equals(IEvolutionMonitor. MONITOR_EVENT_AFTER_UPDATE_CHROMOSOMES1)) { Population pop = (Population) a_information[0]; } if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_BEFORE_SELECT)) { NaturalSelector selector = (NaturalSelector) a_information[0]; Population pop = (Population) a_information[1]; int selectionSize = (Integer) a_information[2]; boolean a_processBeforeGeneticOperators = (Boolean) a_information[3]; /* * a_processBeforeGeneticOperators = true: * called after MONITOR_EVENT_AFTER_UPDATE_CHROMOSOMES1 * a_processBeforeGeneticOperators = false: * called after MONITOR_EVENT_AFTER_UPDATE_CHROMOSOMES2 */ } if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_AFTER_SELECT)) { NaturalSelector selector = (NaturalSelector) a_information[0]; Population pop = (Population) a_information[1]; Population newPop = (Population) a_information[2]; int selectionSize = (Integer) a_information[3]; boolean a_processBeforeGeneticOperators = (Boolean) a_information[4]; /* * a_processBeforeGeneticOperators = true: * called after MONITOR_EVENT_AFTER_UPDATE_CHROMOSOMES1 * a_processBeforeGeneticOperators = false: * called after MONITOR_EVENT_AFTER_UPDATE_CHROMOSOMES2 */ } if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_BEFORE_OPERATE)) { GeneticOperator operator = (GeneticOperator) a_information[0]; Population pop = (Population) a_information[1]; List<IChromosome> chromosomes = (List<IChromosome>) a_information[2]; } if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_AFTER_OPERATE)) { GeneticOperator operator = (GeneticOperator) a_information[0]; Population pop = (Population) a_information[1]; List<IChromosome> chromosomes = (List<IChromosome>) a_information[2]; } if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_BEFORE_BULK_EVAL)) { BulkFitnessFunction bulkFitnessFunction = (BulkFitnessFunction) a_information[0]; Population pop = (Population) a_information[1]; } if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_AFTER_BULK_EVAL)) { BulkFitnessFunction bulkFitnessFunction = (BulkFitnessFunction) a_information[0]; Population pop = (Population) a_information[1]; } if (a_monitorEvent.equals(IEvolutionMonitor. MONITOR_EVENT_BEFORE_UPDATE_CHROMOSOMES2)) { Population pop = (Population) a_information[0]; } if (a_monitorEvent.equals(IEvolutionMonitor. MONITOR_EVENT_AFTER_UPDATE_CHROMOSOMES2)) { Population pop = (Population) a_information[0]; } if (a_monitorEvent.equals(IEvolutionMonitor. MONITOR_EVENT_BEFORE_ADD_CHROMOSOME)) { Population pop = (Population) a_information[0]; IChromosome newChromosome = (IChromosome) a_information[1]; } if (a_monitorEvent.equals(IEvolutionMonitor.MONITOR_EVENT_READD_FITTEST)) { Population pop = (Population) a_information[0]; IChromosome fittest = (IChromosome) a_information[1]; } } /** * @return null as no data is gathered by this monitor * * @author Klaus Meffert * @since 3.5 */ public PopulationHistoryIndexed getPopulations() { return null; } }
true
689472610807e8e280a40b8a6010e30e9bc6d451
Java
rex390/JavaLearningExercises
/IntialProject/src/LibraryExample/RentableItem.java
UTF-8
745
3.09375
3
[]
no_license
package LibraryExample; public abstract class RentableItem { private String name; private boolean rentedOut = false; private int rentPeriod; private static int counter =0; public RentableItem(String name, boolean rentedOut, int rentPeriod) { super(); this.name = name; this.rentedOut = false; this.rentPeriod = rentPeriod; counter++; } public static int getCounter() { return counter; } public static void setCounter(int counter) { RentableItem.counter = counter; } public String getName() { return name; } public boolean isRentedOut() { return rentedOut; } public void setRentedOut(boolean rentedOut) { this.rentedOut = rentedOut; } public int getRentPeriod() { return rentPeriod; } }
true
f369631e78167d2e489ba6a9ee825e01105dd97d
Java
josueolvera/respaldo
/src/main/java/mx/bidg/model/BudgetConceptDistributor.java
UTF-8
4,867
2
2
[]
no_license
package mx.bidg.model; import com.fasterxml.jackson.annotation.JsonView; import mx.bidg.config.JsonViews; import javax.persistence.*; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.math.BigDecimal; /** * * @author rafael */ @Entity @Table( name = "BUDGET_CONCEPT_DISTRIBUTOR", uniqueConstraints = { @UniqueConstraint( name = "UNIQUE_CONCEPT_DISTRIBUTOR", columnNames = {"ID_BUDGET_MONTH_CONCEPT", "ID_DISTRIBUTOR"} ) } ) public class BudgetConceptDistributor implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_BUDGET_CONCEPT_DISTRIBUTOR") @JsonView(JsonViews.Root.class) private Integer idBudgetConceptDistributor; @Column(name = "ID_BUDGET_MONTH_CONCEPT", insertable = false, updatable = false) @JsonView(JsonViews.Root.class) private Integer idBudgetMonthConcept; @Basic(optional = false) @NotNull @Column(name = "ID_DISTRIBUTOR", insertable = false, updatable = false) @JsonView(JsonViews.Root.class) private int idDistributor; @Basic(optional = false) @NotNull @Column(name = "AMOUNT") @JsonView(JsonViews.Root.class) private BigDecimal amount; @Max(value = 1) @Basic(optional = false) @NotNull @Column(name = "PERCENT") @JsonView(JsonViews.Root.class) private BigDecimal percent; @JoinColumn(name = "ID_DISTRIBUTOR", referencedColumnName = "ID_DISTRIBUTOR") @ManyToOne(optional = false) @JsonView(JsonViews.Embedded.class) private CDistributors distributor; @JoinColumn(name = "ID_BUDGET_MONTH_CONCEPT", referencedColumnName = "ID_BUDGET_MONTH_CONCEPT") @ManyToOne(optional = false) @JsonView(JsonViews.Embedded.class) private BudgetMonthConcepts budgetMonthConcept; public BudgetConceptDistributor() { } public BudgetConceptDistributor(Integer idBudgetConceptDistributor) { this.idBudgetConceptDistributor = idBudgetConceptDistributor; } public BudgetConceptDistributor(Integer idBudgetConceptDistributor, int idDistributor, BigDecimal amount, BigDecimal percent) { this.idBudgetConceptDistributor = idBudgetConceptDistributor; this.idDistributor = idDistributor; this.amount = amount; this.percent = percent; } public Integer getIdBudgetConceptDistributor() { return idBudgetConceptDistributor; } public void setIdBudgetConceptDistributor(Integer idBudgetConceptDistributor) { this.idBudgetConceptDistributor = idBudgetConceptDistributor; } public int getIdDistributor() { return idDistributor; } public void setIdDistributor(int idDistributor) { this.idDistributor = idDistributor; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public BigDecimal getPercent() { return percent; } public void setPercent(BigDecimal percent) { this.percent = percent; } public Integer getIdBudgetMonthConcept() { return idBudgetMonthConcept; } public void setIdBudgetMonthConcept(Integer idBudgetMonthConcept) { this.idBudgetMonthConcept = idBudgetMonthConcept; } public CDistributors getDistributor() { return distributor; } public void setDistributor(CDistributors distributor) { this.distributor = distributor; } public BudgetMonthConcepts getBudgetMonthConcept() { return budgetMonthConcept; } public void setBudgetMonthConcept(BudgetMonthConcepts budgetMonthConcept) { this.budgetMonthConcept = budgetMonthConcept; } @Override public int hashCode() { int hash = 0; hash += (idBudgetConceptDistributor != null ? idBudgetConceptDistributor.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof BudgetConceptDistributor)) { return false; } BudgetConceptDistributor other = (BudgetConceptDistributor) object; if ((this.idBudgetConceptDistributor == null && other.idBudgetConceptDistributor != null) || (this.idBudgetConceptDistributor != null && !this.idBudgetConceptDistributor.equals(other.idBudgetConceptDistributor))) { return false; } return true; } @Override public String toString() { return "mx.bidg.model.BudgetConceptDistributor[ idBudgetConceptDistributor=" + idBudgetConceptDistributor + " ]"; } }
true
021d9cb7d86b40ae0fe3032364d84c28a00a023a
Java
EvgeniiFedorov/mailrem
/app/src/main/java/com/example/mailrem/app/pojo/ProcessesManager.java
UTF-8
4,695
2.328125
2
[]
no_license
package com.example.mailrem.app.pojo; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.util.Log; import com.example.mailrem.app.Constants; import com.example.mailrem.app.components.AccountsDataBase; import com.example.mailrem.app.components.service.NotifyFromDB; import com.example.mailrem.app.components.service.UpdateData; public class ProcessesManager { private static final String UPDATE_SWITCH = "update_switch"; private static final String NOTIFY_SWITCH = "notify_switch"; private static final String UPDATE_INTERVAL = "update_frequency"; private static final String WIFI_ONLY = "update_use_wifi"; private static final String ROUMING_USE = "update_use_roaming"; public static void restartUpdate(Context context) { Log.d(Constants.LOG_TAG, "ProcessesManager restartUpdate"); stopUpdate(context); if (checkStateUpdate(context)) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String interval = sharedPreferences.getString(UPDATE_INTERVAL, "err"); int intervalUpdate = Integer.parseInt(interval); Log.i(Constants.LOG_TAG, "ProcessesManager restartUpdate: start update"); UpdateData.startUpdateProcess(context, intervalUpdate * 60 * 1000); } } public static void restartNotify(Context context) { Log.d(Constants.LOG_TAG, "ProcessesManager restartNotify"); stopNotify(context); if (checkStateNotify(context)) { Log.i(Constants.LOG_TAG, "ProcessesManager restartNotify: start notify"); NotifyFromDB.startNotifyProcess(context); } } public static void stopUpdate(Context context) { Log.d(Constants.LOG_TAG, "ProcessesManager stopUpdate"); UpdateData.stopUpdate(context); } public static void stopNotify(Context context) { Log.d(Constants.LOG_TAG, "ProcessesManager stopNotify"); NotifyFromDB.stopNotify(context); } private static boolean checkStateUpdate(Context context) { Log.d(Constants.LOG_TAG, "ProcessesManager checkStateUpdate"); AccountsDataBase db = AccountsDataBase.getInstance(context); db.open(); if (db.countAccount() == 0) { Log.i(Constants.LOG_TAG, "ProcessesManager checkStateUpdate: " + "start update cancel - no account"); return false; } db.close(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); if (!sharedPreferences.getBoolean(UPDATE_SWITCH, false)) { Log.i(Constants.LOG_TAG, "ProcessesManager checkStateUpdate: " + "start update cancel - update switch off"); return false; } ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); if (!isConnected) { Log.i(Constants.LOG_TAG, "ProcessesManager checkStateUpdate: " + "start update cancel - no connection"); return false; } boolean wifiOnly = sharedPreferences.getBoolean(WIFI_ONLY, false); if (wifiOnly) { boolean isWifi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; if (!isWifi) { Log.i(Constants.LOG_TAG, "ProcessesManager checkStateUpdate: " + "start update cancel - no wifi connection"); return false; } } boolean NoRoamingUseOnly = sharedPreferences.getBoolean(ROUMING_USE, true); if (NoRoamingUseOnly) { boolean isRoaming = activeNetwork.isRoaming(); if (isRoaming) { Log.i(Constants.LOG_TAG, "ProcessesManager checkStateUpdate: " + "start update cancel: roaming"); return false; } } return true; } private static boolean checkStateNotify(Context context) { Log.d(Constants.LOG_TAG, "ProcessesManager checkStateNotify"); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); return sharedPreferences.getBoolean(NOTIFY_SWITCH, false); } }
true
c61c6e1bb9db837265078e3463e0aa515a0ea8ac
Java
ucam-cl-dtg/urop-2013-questions
/src/main/java/uk/ac/cam/sup/form/TagDel.java
UTF-8
236
1.945313
2
[]
no_license
package uk.ac.cam.sup.form; import javax.ws.rs.FormParam; public class TagDel { @FormParam("qid") private int qid; @FormParam("tag") private String tag; public int getQid(){return qid;} public String getTag(){return tag;} }
true
f7060bfbe1e646041cd731db9d5e788024c821f5
Java
as063LAUNCH/csci205Labs
/csci205Labs/test/lab11/AccountTest.java
UTF-8
1,554
2.859375
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 lab11; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author as063 */ public class AccountTest { static final double EPSILON = 1.0E-10; private Account instance; private Account acc; public AccountTest() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of credit method, of class Account. */ @Test public void testCredit() { System.out.println("credit"); double amount = 50.0; double balance = 50.0; instance.credit(amount); Assert.assertEquals(100.0, acc.getBalance(),EPSILON); } /** * Test of debit method, of class Account. */ @Test public void testDebit() throws Exception { System.out.println("debit"); double amount = 0.0; acc.debit(500); Assert.assertEquals(1500.0, acc.getBalance(),EPSILON); } /** * Test of processCheck method, of class Account. */ @Test public void testProcessCheck() throws Exception { System.out.println("processCheck"); Payable payee = null; double hoursBilled = 0.0; Account instance = null; instance.processCheck(payee, hoursBilled); } }
true
e9825111a25b001e9a90e0e61935edca66c18223
Java
Majhi/GitHubRepository
/src/main/java/com/wordsmith/dao/WordUploadDao.java
UTF-8
144
1.992188
2
[]
no_license
package com.wordsmith.dao; import com.wordsmith.domain.Word; public interface WordUploadDao { public void uploadWord( Word word); }
true
3594107792aeaf53bd5a4ee5f3254baa9ad1d634
Java
larscase98/lob-pong
/Entity.java
UTF-8
1,124
2.703125
3
[]
no_license
package my.game; import java.awt.Rectangle; import javax.swing.JComponent; public abstract class Entity extends JComponent { private static final long serialVersionUID = 1L; protected double x, y, velX, velY, width, height; protected ID id; public abstract void tick(); public double getPosX() { return x; } public double getPosY() { return y; } public double getVelX() { return velX; } public double getVelY() { return velY; } public int getWidth() { return (int) width; } public int getHeight() { return (int) height; } public ID getID() { return id; } public void setX (double x) { this.x = x; } public void setY (double y) { this.y = y; } public void setVelX (double velX) { this.velX = velX; } public void setVelY (double velY) { this.velY = velY; } public void setWidth (double width) { this.width = width; } public void setHeight (double height) { this.height = height; } public void setID (ID id) { this.id = id; } //-- Other useful methods. public Rectangle getBounds() { return new Rectangle((int) x, (int) y, (int) width, (int) height); } }
true
03bc97b23783dbc4a5b497d5d64320d4ca21d229
Java
Dzikovskiy/BugTracker
/src/app/Const.java
UTF-8
690
1.703125
2
[]
no_license
package app; public class Const { public static final String USER_TABLE = "users"; public static final String USERS_ID = "id"; public static final String USERS_FIRSTNAME = "firstname"; public static final String USERS_LOGIN = "login"; public static final String USERS_PASSWORD = "password"; public static final String USERS_EMAIL = "email"; public static final String USERS_ADMIN = "admin"; public static final String TASK_TABLE = "tasks"; public static final String TASKS_ID = "id"; public static final String TASKS_TASK = "task"; public static final String TASKS_CREATOR = "creator"; public static final String TASKS_STAGE = "stage"; }
true
9d3baf7c3bd1367611d9da2d9e655e66cf15de14
Java
aardralilie/ProjectManagement
/src/main/java/com/pm/service/impl/UserServiceImpl.java
UTF-8
623
2.125
2
[]
no_license
package com.pm.service.impl; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.pm.model.User; import com.pm.repository.UserRepository; import com.pm.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired UserRepository userRepository; public List<User> getAllUsers() { List<User> users = userRepository.findAll(); return users; } public User addUpdateUser(User user) { return userRepository.save(user); } }
true
0e3db92552d46c89296f7b5e422928fff7362dc0
Java
13554659514/java-notes
/src/main/java/staticImport/pkg2/ConstantInterface2.java
UTF-8
223
1.828125
2
[]
no_license
package staticImport.pkg2; /** * @Author: YuTengjing * @Date: 2019/1/3 */ public interface ConstantInterface2 { String PROJECT_NAME = "java-notes"; Double JAVA_VERSION = 1.8; String BUILD_TOOL = "Gradle"; }
true
0617948724c31cd1ed271074dc5e7f4c4a5a2f9b
Java
xttlalala/servelt-curd
/src/com/oracle/servlet/DeleteBookServlet.java
WINDOWS-1252
971
2.234375
2
[]
no_license
package com.oracle.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.oracle.dao.BookDao; /** * Servlet implementation class DeleteBookServlet */ @WebServlet("/DeleteBook") public class DeleteBookServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //id Integer bookId = Integer.valueOf(request.getParameter("bookid")); BookDao dao =new BookDao(); dao.delete(bookId); response.sendRedirect("listbook"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
true
55b8f0438a7070e3f5c9afd80c6dc6d2f68681ff
Java
Coding-hu/Java-
/EXP2/src/Exp2/money.java
UTF-8
2,648
3.65625
4
[]
no_license
package Exp2; import java.util.Scanner; public class money { public static void main(String[] args){ String number1[]=new String[]{"零","元","拾","佰","仟"}; String number3[]=new String[]{"0","分","角"}; String number2[]=new String[]{"0","壹","贰","叁","肆","伍","陆","柒","捌","镹"}; int arrayInt[]=new int[10]; int arrayDou[]=new int[3]; Scanner input=new Scanner(System.in); System.out.print("请输入一个数值:"); String mon=input.nextLine(); double money=Double.parseDouble(mon); //将字符串转为double,并且去掉了字符串的前后缀0 int partOfInt=(int)money; //钱的整数部分 double partOfDou=money-partOfInt; //钱的小数部分 int partOfDouToInt=(int)(partOfDou*100); //将小数乘100转换为整数 int count=1; //整数位数 while (partOfInt!=0){ //将整数钱每位的数字提取 arrayInt[count++]=partOfInt%10; partOfInt/=10; } int countDou=1; //小数位数 while (partOfDouToInt!=0){ //将小数的钱每位数字提取 arrayDou[countDou++]=partOfDouToInt%10; partOfDouToInt/=10; } //输出整数部分的钱 int flag=1; //判断是否连续的第一次出现的零 for (int i=count-1;i>=1;i--){ if(arrayInt[i]==0) { if (i!=1){ if (flag==1) { //连续出现的第一个零,保证连续的零只输出一个‘零’ System.out.print("零"); flag=0; //置假 } i--; //出现零就下一个数 if (flag==0) i--; //如果该零是连续的零,就直接判断下一个数,其他的什么都不做 }else { //个位数为0 System.out.print(number1[1]); flag=1; //连续的零中断,再把标志置真,只有四位整数,其实用不到 break; } } else System.out.print(number2[arrayInt[i]]+number1[i]); } if (partOfDou==0) System.out.print('整'); else { //小数部分最多两位数 if (arrayDou[2]==0) System.out.print("零"); else System.out.print(number2[arrayDou[2]]+number3[2]); if (arrayDou[1]==0) ; else System.out.print(number2[arrayDou[1]]+number3[1]); } } }
true
e8a1fcb56da6085313df57411b6e8c5a61f80375
Java
Francispp/cms
/src/src/com/cyberway/common/menu/service/MenuResourceService.java
UTF-8
1,817
2.390625
2
[]
no_license
package com.cyberway.common.menu.service; import java.util.List; import org.hibernate.Criteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import com.cyberway.common.menu.domain.MenuResource; import com.cyberway.core.dao.HibernateEntityDao; /** * com.cyberway.common.menu.service.MenuResourceService * * @author Janice Yang * * @createTime 2012-2-24 下午12:13:51 * * @Description: * */ public class MenuResourceService extends HibernateEntityDao<MenuResource> { /** * 获取顶级菜单的集合 * * @return */ public List<MenuResource> getTopMenu() { Criteria c = getEntityCriteria(); c.add(Restrictions.isNull("pid")); c.addOrder(Order.asc("orderNo")); return c.list(); } /** * 获取顶级菜单的集合 * * @return */ public List<MenuResource> getTopMenu(Long id) { Criteria c = getEntityCriteria(); if(id != null){ c.add(Restrictions.not(Restrictions.eq("id", id))); } c.add(Restrictions.isNull("pid")); c.addOrder(Order.asc("orderNo")); return c.list(); } /** * 判断菜单代码是否唯一 * * @param id * 菜单id * @param menuCode * 菜单代码 * @return "0"表示不唯一,"1"表示唯一 */ public int menuCodeIsUnique(Long id, String menuCode) { List<MenuResource> menuList; if (!id.equals(0L)) { MenuResource menu = get(id); if (menu.getMenuCode().equals(menuCode)) { return 1; } else { menuList = findBy("menuCode", menuCode); if (menuList.size() > 0) { return 0; } else { return 1; } } } else { menuList = findBy("menuCode", menuCode); if (menuList.size() > 0) { return 0; } else { return 1; } } } }
true
0a22d88255a654e260ae4590419887b2303c459f
Java
mokhtarmoustafa/Wasellak-master
/app/src/main/java/com/unicom/wasalakclientproduct/model/user/LanguageClass.java
UTF-8
535
2.125
2
[]
no_license
package com.unicom.wasalakclientproduct.model.user; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class LanguageClass { @SerializedName("languageName") @Expose private String languageName; public LanguageClass(String languageName) { this.languageName = languageName; } public String getLanguageName() { return languageName; } public void setLanguageName(String languageName) { this.languageName = languageName; } }
true
91174a80aee7aa1b2151b31b85a5b92130ee3009
Java
leeaforbes/PaintballCTF
/src/com/javabean/paintballctf/PBCTFGameManager.java
UTF-8
5,022
2.78125
3
[]
no_license
package com.javabean.paintballctf; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.Timer; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; public class PBCTFGameManager implements ActionListener{ //map with arena name key, CTF game value to ensure only one game per arena private HashMap<String, PBCTFGame> games = new HashMap<String, PBCTFGame>(); //player name, Arena public static HashMap<String, Arena> playersInArena = new HashMap<String, Arena>(); //the plugin Plugin plugin; //ticks once every 10 seconds to remove any empty games Timer gameGarbageCollector = new Timer(10000, this); public PBCTFGameManager(Plugin p){ plugin = p; gameGarbageCollector.setRepeats(true); gameGarbageCollector.setInitialDelay(0); gameGarbageCollector.start(); } public void createGame(Arena arena){ //called whenever player joins and game does not exist yet games.putIfAbsent(arena.getName(), new PBCTFGame(arena, plugin)); } //called whenever one player left or time runs out public void deleteGame(Arena arena){ games.remove(arena.getName()); } public void attemptPlayerJoin(Player player, Arena arena){ //arena not playable if(!arena.isPlayable()){ player.sendMessage(ChatColor.RED + "Arena: " + arena.getName() + " is not playable yet."); } //already in a game else if(getPlayerGameArena(player) != null){ player.sendMessage(ChatColor.RED + "You are already in arena: " + arena.getName() + ". Leave with /pbctf leave."); } //arena already has a game going else if(isInProgress(arena)){ player.sendMessage(ChatColor.RED + "Arena: " + arena.getName() + " has a game in progress."); } else{ //allow player to join arena game playerJoin(player, arena); } } public void playerJoin(Player player, Arena arena){ if(games.get(arena.getName()) == null){ createGame(arena); } games.get(arena.getName()).playerJoin(player); player.teleport(games.get(arena.getName()).getPlayerGameData(player.getName()).getTeam().getRandomSpawn().getLocation()); notifyPlayers(ChatColor.LIGHT_PURPLE + player.getName() + " joined arena: " + arena.getName() + ".", arena); } public void playerLeave(Player player, Arena arena){ games.get(arena.getName()).playerLeave(player); if(games.get(arena.getName()).getNumPlayers() == 0){ //no more players playing, so delete the game deleteGame(arena); } } public void setPlayerTeam(Player player, Arena arena, Team team){ games.get(arena.getName()).setPlayerTeam(player, team); } public PBCTFGame getGame(Arena arena){ return games.get(arena.getName()); } //returns arena of game player is in, otherwise null public Arena getPlayerGameArena(Player player){ //will be null if not in a game return playersInArena.get(player.getName()); } public PlayerGameData getPlayerGameData(Player player, Arena arena){ return games.get(arena.getName()).getPlayerGameData(player.getName()); } public String timeLeft(Arena arena){ return games.get(arena.getName()).timeLeft(); } public int getNumPlayersInArena(Arena arena){ return games.get(arena.getName()).getNumPlayers(); } public int getNumGames(){ return games.size(); } public void startArena(Arena arena){ games.get(arena.getName()).start(); } public boolean isInProgress(Arena arena){ if(games.get(arena.getName()) == null){ return false; } return games.get(arena.getName()).isInProgress(); } public void notifyPlayers(String message, Arena arena){ games.get(arena.getName()).notifyPlayers(message); } public void getInfo(Player player){ for(String arenaName : games.keySet()){ TextComponent message = new TextComponent((games.get(arenaName).isInProgress() ? ChatColor.RED : ChatColor.GREEN) + "\u25CF " + ChatColor.GREEN + arenaName + ": " + games.get(arenaName).getInfo()); if(games.get(arenaName).isInProgress()){ message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder( ChatColor.RED + arenaName + " is in progress").create())); } else{ message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder( ChatColor.DARK_GREEN + "" + ChatColor.MAGIC + "|" + ChatColor.GREEN + "Join " + arenaName + ChatColor.DARK_GREEN + "" + ChatColor.MAGIC + "|").create())); message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/pbctf join " + arenaName)); } player.spigot().sendMessage(message); } } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == gameGarbageCollector){ for(String arenaName : games.keySet()){ if(games.get(arenaName).getNumPlayers() == 0){ deleteGame(games.get(arenaName).getArena()); } } } } }
true
2939998c44e76c817fa3d50d52b61f2772e35e67
Java
apache/pulsar
/pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/MembershipManager.java
UTF-8
10,979
1.875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown", "LicenseRef-scancode-protobuf" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.functions.worker; import static org.apache.pulsar.functions.worker.SchedulerManager.checkHeartBeatFunction; import com.google.common.annotations.VisibleForTesting; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.common.functions.WorkerInfo; import org.apache.pulsar.common.policies.data.ConsumerStats; import org.apache.pulsar.common.policies.data.TopicStats; import org.apache.pulsar.functions.proto.Function; import org.apache.pulsar.functions.utils.FunctionCommon; /** * A simple implementation of leader election using a pulsar topic. */ @Slf4j public class MembershipManager implements AutoCloseable { private final WorkerConfig workerConfig; private PulsarAdmin pulsarAdmin; static final String COORDINATION_TOPIC_SUBSCRIPTION = "participants"; private static final String WORKER_IDENTIFIER = "id"; // How long functions have remained assigned or scheduled on a failed node // FullyQualifiedFunctionName -> time in millis @VisibleForTesting Map<Function.Instance, Long> unsignedFunctionDurations = new HashMap<>(); MembershipManager(WorkerService workerService, PulsarClient pulsarClient, PulsarAdmin pulsarAdmin) { this.workerConfig = workerService.getWorkerConfig(); this.pulsarAdmin = pulsarAdmin; } public List<WorkerInfo> getCurrentMembership() { List<WorkerInfo> workerIds = new LinkedList<>(); TopicStats topicStats = null; try { topicStats = this.pulsarAdmin.topics().getStats(this.workerConfig.getClusterCoordinationTopic()); } catch (PulsarAdminException e) { log.error("Failed to get status of coordinate topic {}", this.workerConfig.getClusterCoordinationTopic(), e); throw new RuntimeException(e); } for (ConsumerStats consumerStats : topicStats.getSubscriptions() .get(COORDINATION_TOPIC_SUBSCRIPTION).getConsumers()) { WorkerInfo workerInfo = WorkerInfo.parseFrom(consumerStats.getMetadata().get(WORKER_IDENTIFIER)); workerIds.add(workerInfo); } return workerIds; } public WorkerInfo getLeader() { TopicStats topicStats = null; try { topicStats = this.pulsarAdmin.topics().getStats(this.workerConfig.getClusterCoordinationTopic()); } catch (PulsarAdminException e) { log.error("Failed to get status of coordinate topic {}", this.workerConfig.getClusterCoordinationTopic(), e); throw new RuntimeException(e); } String activeConsumerName = topicStats.getSubscriptions().get(COORDINATION_TOPIC_SUBSCRIPTION).getActiveConsumerName(); WorkerInfo leader = null; for (ConsumerStats consumerStats : topicStats.getSubscriptions() .get(COORDINATION_TOPIC_SUBSCRIPTION).getConsumers()) { if (consumerStats.getConsumerName().equals(activeConsumerName)) { leader = WorkerInfo.parseFrom(consumerStats.getMetadata().get(WORKER_IDENTIFIER)); } } if (leader == null) { log.warn("Failed to determine leader in functions cluster"); } return leader; } @Override public void close() { } public void checkFailures(FunctionMetaDataManager functionMetaDataManager, FunctionRuntimeManager functionRuntimeManager, SchedulerManager schedulerManager) { Set<String> currentMembership = this.getCurrentMembership().stream() .map(entry -> entry.getWorkerId()).collect(Collectors.toSet()); List<Function.FunctionMetaData> functionMetaDataList = functionMetaDataManager.getAllFunctionMetaData(); Map<String, Function.FunctionMetaData> functionMetaDataMap = new HashMap<>(); for (Function.FunctionMetaData entry : functionMetaDataList) { functionMetaDataMap.put(FunctionCommon.getFullyQualifiedName(entry.getFunctionDetails()), entry); } Map<String, Map<String, Function.Assignment>> currentAssignments = functionRuntimeManager.getCurrentAssignments(); Map<String, Function.Assignment> assignmentMap = new HashMap<>(); for (Map<String, Function.Assignment> entry : currentAssignments.values()) { assignmentMap.putAll(entry); } long currentTimeMs = System.currentTimeMillis(); // remove functions Iterator<Map.Entry<Function.Instance, Long>> it = unsignedFunctionDurations.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Function.Instance, Long> entry = it.next(); String fullyQualifiedFunctionName = FunctionCommon.getFullyQualifiedName( entry.getKey().getFunctionMetaData().getFunctionDetails()); String fullyQualifiedInstanceId = FunctionCommon.getFullyQualifiedInstanceId(entry.getKey()); //remove functions that don't exist anymore if (!functionMetaDataMap.containsKey(fullyQualifiedFunctionName)) { it.remove(); } else { //remove functions that have been scheduled Function.Assignment assignment = assignmentMap.get(fullyQualifiedInstanceId); if (assignment != null) { String assignedWorkerId = assignment.getWorkerId(); // check if assigned to worker that has failed if (currentMembership.contains(assignedWorkerId)) { it.remove(); } } } } // check for function instances that haven't been assigned for (Function.FunctionMetaData functionMetaData : functionMetaDataList) { Collection<Function.Assignment> assignments = FunctionRuntimeManager.findFunctionAssignments(functionMetaData.getFunctionDetails().getTenant(), functionMetaData.getFunctionDetails().getNamespace(), functionMetaData.getFunctionDetails().getName(), currentAssignments); Set<Function.Instance> assignedInstances = assignments.stream() .map(assignment -> assignment.getInstance()) .collect(Collectors.toSet()); Set<Function.Instance> instances = new HashSet<>(SchedulerManager.computeInstances(functionMetaData, functionRuntimeManager.getRuntimeFactory().externallyManaged())); for (Function.Instance instance : instances) { if (!assignedInstances.contains(instance)) { if (!this.unsignedFunctionDurations.containsKey(instance)) { this.unsignedFunctionDurations.put(instance, currentTimeMs); } } } } // check failed nodes for (Map.Entry<String, Map<String, Function.Assignment>> entry : currentAssignments.entrySet()) { String workerId = entry.getKey(); Map<String, Function.Assignment> assignmentEntries = entry.getValue(); if (!currentMembership.contains(workerId)) { for (Function.Assignment assignmentEntry : assignmentEntries.values()) { Function.Instance instance = assignmentEntry.getInstance(); // avoid scheduling-trigger for heartbeat-function if owner-worker is not up if (checkHeartBeatFunction(instance) != null) { continue; } if (!this.unsignedFunctionDurations.containsKey(instance)) { this.unsignedFunctionDurations.put(instance, currentTimeMs); } } } } boolean triggerScheduler = false; // check unassigned Collection<Function.Instance> needSchedule = new LinkedList<>(); Collection<Function.Assignment> needRemove = new LinkedList<>(); Map<String, Integer> numRemoved = new HashMap<>(); for (Map.Entry<Function.Instance, Long> entry : this.unsignedFunctionDurations.entrySet()) { Function.Instance instance = entry.getKey(); long unassignedDurationMs = entry.getValue(); if (currentTimeMs - unassignedDurationMs > this.workerConfig.getRescheduleTimeoutMs()) { needSchedule.add(instance); // remove assignment from failed node Function.Assignment assignment = assignmentMap.get(FunctionCommon.getFullyQualifiedInstanceId(instance)); if (assignment != null) { needRemove.add(assignment); Integer count = numRemoved.get(assignment.getWorkerId()); if (count == null) { count = 0; } numRemoved.put(assignment.getWorkerId(), count + 1); } triggerScheduler = true; } } if (!needRemove.isEmpty()) { functionRuntimeManager.removeAssignments(needRemove); } if (triggerScheduler) { log.info( "Failure check - Total number of instances that need to be scheduled/rescheduled: {} " + "| Number of unassigned instances that need to be scheduled: {} | Number of instances " + "on dead workers that need to be reassigned {}", needSchedule.size(), needSchedule.size() - needRemove.size(), numRemoved); schedulerManager.schedule(); } } }
true
e0fb7f6e5592ea1c61e049bc121b09b4e616f77c
Java
marmihajl/InteractivePPT
/InteractivePPT-android/entities/src/main/java/hr/foi/air/interactiveppt/entities/Survey.java
UTF-8
406
1.75
2
[]
no_license
package hr.foi.air.interactiveppt.entities; import com.google.gson.annotations.SerializedName; /** * Created by zeko868 on 31.12.2016.. */ public class Survey { @SerializedName("id") public int id; @SerializedName("name") public String name; @SerializedName("description") public String description; @SerializedName("num_of_questions") public int numOfQuestions; }
true
ec4572b11605fd55d8bc2009388ede2f5ee72676
Java
xiaodnn/erp
/src/main/java/com/erp/orm/inter/IWaresWholepriceGroupMapper.java
UTF-8
929
1.875
2
[]
no_license
package com.erp.orm.inter; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.erp.orm.entity.WaresWholepriceGroup; import com.erp.orm.entity.WaresWholepriceGroupKey; @Repository("waresWholepriceGroupMapper") public interface IWaresWholepriceGroupMapper { int deleteByPrimaryKey(WaresWholepriceGroupKey key); int insert(WaresWholepriceGroup waresWholepriceGroup); int insertSelective(WaresWholepriceGroup waresWholepriceGroup); WaresWholepriceGroup selectByPrimaryKey(WaresWholepriceGroupKey key); int updateByPrimaryKeySelective(WaresWholepriceGroup waresWholepriceGroup); int updateByPrimaryKey(WaresWholepriceGroup waresWholepriceGroup); List<WaresWholepriceGroup> selectByName(String name); List<WaresWholepriceGroup> selectByPage(Map<String,Integer> map); Integer selectCount(Map<String,Object> map); }
true
d87f6b8fb8e61403b5d6e133f6eb75224977be99
Java
ycourtois/hackernews-graphql-java
/src/main/java/com/howtographql/graphql/resolvers/LinkResolver.java
UTF-8
779
2.140625
2
[]
no_license
package com.howtographql.graphql.resolvers; import com.coxautodev.graphql.tools.GraphQLResolver; import com.howtographql.graphql.type.Link; import com.howtographql.graphql.type.User; import com.howtographql.repositories.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; /** * @author yann.courtois@ippon.fr * @since 12/28/2017 */ @Component @RequiredArgsConstructor // We need it because "postedby" does not match any class property inside Link public class LinkResolver implements GraphQLResolver<Link> { private final UserRepository userRepository; public User postedBy(Link link) { if (link.getUserId() == null) { return null; } return userRepository.findOne(link.getUserId()); } }
true
475313723efb0b66fa98ae2ee1b6418138c8f8ea
Java
Cole-Dalton/CIT360
/CIT360/src/personalSandboxCode/threadsExecutablesRunnables/Fisherman.java
UTF-8
1,733
4.21875
4
[]
no_license
package personalSandboxCode.threadsExecutablesRunnables; /** * Created by daltonsolo on 5/4/2017. */ public class Fisherman { public static void main(String[] args) { /* We're going to create the thread here. You can't implement a class in here if you don't have it implementing "runnable". Remember that x = name in the Salmon constructor. */ Thread t1 = new Thread(new Salmon("one")); /* Basically what this code does is create a thread object called t1 from the class Salmon, which gives it a name and random time then puts it to sleep. */ /* This creates 3 more threads, based off of the Salmon class, and names them using x from the constructor function argument in the Salmon class. */ Thread t2 = new Thread(new Salmon("two")); Thread t3 = new Thread(new Salmon("three")); Thread t4 = new Thread(new Salmon("four")); /* This is how you start a thread. The other threads have not been started yet. Start essentially calls the run() method. */ t1.start(); // Start other threads. t2.start(); t3.start(); t4.start(); /* The output of running this so far will be shown in a random order, and that's because they all executed at once so there isn't really an order to put them in, with the exception of the statements saying when the thread has woken up, which will be shown in the order of the threads which have the shortest sleep time (because the statement is printed right after the thread "wakes up". */ } }
true
1179b2056d13a4e76e69a15e0d3a7d20a29afc47
Java
jchmb/java-evolution
/src/nl/jchmb/evolution/repository/EvolverRepository.java
UTF-8
898
2.21875
2
[]
no_license
package nl.jchmb.evolution.repository; import nl.jchmb.evolution.evolver.Evolver; import nl.jchmb.evolution.evolver.SimpleEvolver; import nl.jchmb.evolution.replicator.PlanetReplicator; import nl.jchmb.evolution.replicator.PlanetReplicatorFactory; import nl.jchmb.math.random.FloatGenerator; import nl.jchmb.math.vector.FloatVectorGenerator; public class EvolverRepository<G, P> extends Repository<Evolver<G, P, PlanetReplicator<G, P>>> { public EvolverRepository() { addPlanetEvolver(); } private void addPlanetEvolver() { Evolver<G, P, PlanetReplicator<G, P>> evolver = new SimpleEvolver<G, P, PlanetReplicator<G, P>>(); evolver.setReplicatorFactory( new PlanetReplicatorFactory<G, P>( new FloatVectorGenerator( 2, new FloatGenerator() ) ) ); add( new SimpleSource<Evolver<G, P, PlanetReplicator<G, P>>>(evolver, "PlanetEvolver") ); } }
true
c26844f76c6b4efcbea307ca293630c168bd5b7a
Java
Coady1991/groupboardgame
/src/controllers/Game.java
UTF-8
20,819
3.140625
3
[]
no_license
package controllers; import models.*; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import static utils.RaceCard.*; import static utils.RaceCard.raceCardCostForMove; //=================================================================================================================================================== //TODO: RACE CARD /* * raceCardCostForMove(move) : Returns the cost (carrots) for the specified move (number of squares). * raceCardMaxMoveForCost(cost) : Returns the maximum move (number of squares) for the specified cost. */ //=================================================================================================================================================== /** * This class will be used to set up a object of Game. * * @author Niall Coady & Mark McDonald * version 18/04/2017 */ public class Game { //TODO: Added players private Hashtable<Integer, Player> players; public Board board; public HareCards hareCards; public int currentPlayerKey; public int numberOfPlayers; public int playerLastMove; public int playerLastCost; public int playersFinished; /** * Constructor for a new Game. * * */ public Game(Hashtable<Integer, Player> players) { this.players = players; board = new Board(); hareCards = new HareCards(); currentPlayerKey = 1; numberOfPlayers = players.size(); playerLastMove = 0; playerLastCost = 0; playersFinished = 0; } //******************************************************************************************************************************* // Getters for the game //******************************************************************************************************************************* /** * Returns the players in the HashTable. * * @return the players in the HashTable. */ public Hashtable<Integer, Player> getPlayers() { return players; } /** * Returns the Board. * * @return the Board. */ public Board getBoard() { return board; } /** * Returns the HareCards. * * @return the HareCards. */ public HareCards getHareCards() { return hareCards; } /** * Returns the currentPlayerKey. * * @return the currentPlayerKey. */ public int currentPlayerKey() { return currentPlayerKey; } /** * Returns the number of Players in the game. * * @return the number of players in the game. */ public int numberOfPlayers() { return numberOfPlayers; } /** * Returns the players last move. * * @return the players last move. */ public int playerLastMove() { return playerLastMove; } /** * Returns the carrot cost for the players last move. * * @return the carrot cost for the players last move. */ public int playerLastCost() { return playerLastCost; } /** * Returns the players who are finished the game. * * @return the players who are finished the game. */ public int playersFinished() { return playersFinished; } //******************************************************************************************************************************* // Setters for the game //******************************************************************************************************************************* /** * Sets the players in the HashTable. * * @param players Updates the players in the HashTable. */ public void setPlayers(Hashtable<Integer, Player> players) { this.players = players; } /** * Updates the board. * * @param board */ public void setBoard(Board board) { this.board = board; } /** * Updates the HareCards. * * @param hareCards */ public void setHareCards(HareCards hareCards) { this.hareCards = hareCards; } /** * Updates the currentPlayerKey field. * * @param currentPlayerKey */ public void currentPlayerKey(int currentPlayerKey) { this.currentPlayerKey = currentPlayerKey; } /** * Updates the numberOfPlayers field. * * @param numberOfPlayers */ public void numberOfPlayers(int numberOfPlayers) { this.numberOfPlayers = numberOfPlayers; } /** * Updates the playerLastMove field. * * @param playerLastMove */ public void playerlastMove(int playerLastMove) { this.playerLastMove = playerLastMove; } /** * Updates the playerlastCost field. * * @param playerLastCost */ public void playerLastCost(int playerLastCost) { this.playerLastCost = playerLastCost; } /** * Updates the playersFinished field. * * @param playersFinished */ public void playersFinished(int playersFinished) { this.playersFinished = playersFinished; } //******************************************************************************************************************************* // START PHASE //******************************************************************************************************************************* /** * Returns the currentPlayer * * @return the currentPlayer */ public Player currentPlayer() { return players.get(currentPlayerKey); } //MMcD: Added this method to integrate the hare card processing in Driver public SquareType currentSquareType(Player player) { return board.currentSquareType(player); } /** * If the player reaches the finish square, this sets their finish flag to true. * * @param player sets finish flag to true. */ public void isFinished(Player player) { if(player.getIndex() == 64) { player.setFinished(true); Turn(); } } /** * If the player has been skipped on their previous turn, * this turns the flag false to allow the player play on their next turn * * @param player Skip flag is set to false to allow a move next turn. */ public void isSkipTurn(Player player) { if(player.getSkip() == true) { player.setSkip(false); Turn(); } } /** * This method allows the player to collect carrots depending on the number square they are on * and the current rank they hold within the game. * If the players rank and number square match, they receive 10 carrots*rank. * * @param player receives carrots depending if their rank matches the number square. */ public void getCarrotsNumberSquare(Player player) { if(board.currentSquareType(player) == SquareType.NUMBER2 || board.currentSquareType(player) == SquareType.NUMBER3 || board.currentSquareType(player) == SquareType.NUMBER4 || board.currentSquareType(player) == SquareType.NUMBER156) { int rank = calculateRank(player); String squareNumber = Square.squareTypeString(board.currentSquareType(player)); if (squareNumber.contains(String.format("%s", rank))) { int currentCarrots = player.getCarrots(); player.addCarrots(currentCarrots + rank*10); } } } /** * This method allows the player to receive carrots after they have discarded a lettuce. * The player will receive 10 carrots*rank in the game. * * @param player receives carrots after discarding a lettuce. */ public void getLettuceSquareCarrots(Player player) { if(player.getChew() == true) { player.discardLettuce(); int rank = calculateRank(player); int currentCarrots = player.getCarrots(); player.addCarrots(currentCarrots + rank*10); player.setChew(false); } } /** * Returns the valid moves the player can make. * * @param player The player currently looking to move. * * @return the valid moves a player can make. */ public HashSet<Integer> validMoves(Player player) { return board.validMoves(player); } //******************************************************************************************************************************* // MOVE PHASE //******************************************************************************************************************************* /** * This method removes the cost of the move the player made in carrots. * * @param player currently making a move * * @param moves Depending on how many moves the player made depends on how many carrots are spent. */ public void movePlayerForward(Player player, int moves) { int cost = raceCardCostForMove(moves); player.removeCarrots(cost); board.movePlayerForward(player, moves); playerLastMove = moves; playerLastCost = cost; } /** * This method allows the player to receive carrots after moving backwards to a tortoise square, if that square is unoccupied.. * The player receives 10 carrots*the number of squares they moved backwards to reach the tortoise square. * * @param player That is moving back to a tortoise. */ public void getTortoiseSquareCarrots(Player player) { playerLastMove = board.movePlayerBack(player); playerLastCost = 0; player.addCarrots(playerLastMove * 10); } /** * If the player is on a carrot square they can stay put for their move and receive 10 carrots. * * @param player That is currently on the carrot square. */ public void canStayPutReceive(Player player) { int currentCarrots = player.getCarrots(); player.addCarrots(currentCarrots + 10); } /** * If the player is on a carrot square they can stay put and pay 10 carrots. But if they have less then 10 carrots and wish to pay 10 carrots, * they are forced to receive 10 carrots. * * @param player That is currently on the carrot square. */ public void canStayPutPay(Player player) { if (player.getCarrots() < 10) { int currentCarrots = player.getCarrots(); player.addCarrots(currentCarrots + 10); } else if (player.getCarrots() > 10) { int currentCarrots = player.getCarrots(); player.addCarrots(currentCarrots - 10); } } /** * Returns the number of squares that have to be moved for the payer to finish from its current position. * * @param player The current player moving * * @return The number of squares needed to moved to reach the finish. */ public int movesToFinish(Player player) { return board.movesToFinish(player); } /** * Moves the player to the finish square and sets the player finished to true. * * @param player Current player moved to finish square and setFinished to true. * */ public void playerFinish(Player player, int moves) { int cost = raceCardCostForMove(moves); player.removeCarrots(cost); board.movePlayerForward(player, moves); playerLastMove = moves; playerLastCost = cost; player.setSkip(false); player.setChew(false); player.setCanStayPut(false); player.setPlaysAgain(false); player.setCanMoveBack(false); player.setCanMoveForward(false); player.setCanFinish(false); player.setFinished(true); } // ********************************************************************************************************************************** // START: Hare Card Processing // ---------------------------------------------------------------------------------------------------------------------------------- // @author Mark McDonald (20077698@mail.wit.ie) // @version 1.0 (06/04/2017) // ********************************************************************************************************************************** /** * This method draws the top card from the hare card deck. * * @return The top card drawn from the hare card deck. */ public HareCard drawHareCard() { return hareCards.draw(); } /** * This method performs the processing for hare card type PLAYERSBEHIND: * * "IF THERE ARE MORE PLAYERS BEHIND YOU THAN IN FRONT OF YOU, MISS A TURN. IF NOT, PLAY AGAIN." * "If equal, of course play again." * * @param player The player who has drawn the hare card. */ public void hareCardPlayersBehind(Player player) { int rank = calculateRank(player); int playersAhead = rank - 1; int playersBehind = numberOfPlayers - rank; if (playersBehind > playersAhead) { player.setSkip(true); } else { player.setPlaysAgain(true); } } /** * This method performs the processing for hare card type DRAWCARROTS: * * "DRAW 10 CARROTS FOR EACH LETTUCE YOU STILL HOLD." * "If you have none left, miss a turn." * * @param player The player who has drawn the hare card. */ public void hareCardDrawCarrots(Player player) { int lettuces = player.getLettuces(); if (lettuces > 0) { player.addCarrots(10 * lettuces); } else { player.setSkip(true); } } /** * This method performs the processing for hare card type RESTORECARROTS: * * "RESTORE YOUR CARROT HOLDING TO EXACTLY 65." * "If you have more than 65, pay extras to the carrot patch; if fewer, draw extras from the carrot patch." * * @param player The player who has drawn the hare card. */ public void hareCardRestoreCarrots(Player player) { player.setCarrots(Player.INITIAL_CARROTS); } /** * This method performs the processing for hare card type LOSEHALFCARROTS: * * "LOSE HALF YOUR CARROTS!" * "If an odd number, keep the odd one." * * @param player The player who has drawn the hare card. */ public void hareCardLoseHalfCarrots(Player player) { int carrots = player.getCarrots(); if (carrots % 2 == 1) { player.setCarrots(1 + ((carrots - 1) / 2)); } else { player.setCarrots(carrots / 2); } } /** * This method performs the processing for hare card type SHUFFLECARDS: * * "SHUFFLE THE HARE CARDS AND RECEIVE FROM EACH PLAYER 1 CARROT FOR DOING SO." * "Do not replace this card at the bottom of the pack but include it in the shuffle." * * @param player The player who has drawn the hare card. */ public void hareCardShuffleCards(Player player) { hareCards.shuffle(); for (Player p : players.values()) { if ((!p.getFinished()) && (p.getKey() != player.getKey()) && (p.getCarrots() > 0)) { p.removeCarrots(1); player.addCarrots(1); } } } /** * This method performs the processing for hare card type FREERIDE: * * "FREE RIDE!" * "Your last turn costs nothing; retrieve the carrots you paid to reach this square." * * @param player The player who has drawn the hare card. */ public void hareCardFreeRide(Player player) { player.addCarrots(playerLastCost); } /** * This method performs part of the processing for hare card type GIVECARROTS: * * "GIVE 10 CARROTS TO EACH PLAYER LYING BEHIND YOU IN THE RACE (IF ANY)." * "If you haven't enough carrots, give them five each; if still not possible, one each." * "A player who doesn't want extra carrots may discard them to the 'carrot patch'." * * This method returns a list of players who are behind the specified player * in the game (if any). This means all players who have an index less than * the index of the specified player. * * If there are no players behind this player then an empty list is returned. * * @param player The player who has drawn the hare card. * * @return The list of players who are behind the specified player * in the game (if any). */ public List<Player> hareCardGiveCarrotsPlayersBehind(Player player) { List<Player> result = new ArrayList<>(); for (Player p : players.values()) { if (p.getIndex() < player.getIndex()) { result.add(p); } } return result; } /** * This method performs part of the processing for hare card type GIVECARROTS: * * "GIVE 10 CARROTS TO EACH PLAYER LYING BEHIND YOU IN THE RACE (IF ANY)." * "If you haven't enough carrots, give them five each; if still not possible, one each." * "A player who doesn't want extra carrots may discard them to the 'carrot patch'." * * This method calculates what payment the player can afford to make to each of the * players behind. This will be either 10, 5, 1 or 0. * * If 0, then the player can't afford any payment to any of the players behind and * so the carrot holding for the player is set to zero so that (subject to no change * in circumstances) the player will be sent back to the start on their next turn. * (Ref. as per Siobhan on 27/03/2017, player is returned to start in this case.) * * If the payment the player can afford to make is greater than zero (10, 5 or 1) * then the carrot holding for the player is reduced by that amount for each of * the players behind that player. * * @param player The player who has drawn the hare card. * * @param count The number of players behind the specified player in the game. * This value will always be greater than zero as further processing of this * hare card type is only carried out in that case. * * @return The payment the player can afford to make to each of the players behind. * This will be either 10, 5, 1 or 0. */ public int hareCardGiveCarrotsPayment(Player player, int count) { int carrots = player.getCarrots(); int payment = 10; if (payment * count > carrots) { payment = 5; if (payment * count > carrots) { payment = 1; if (count > carrots) { payment = 0; } } } if (payment == 0) { //Insufficient carrots so send back to the start on next turn player.setCarrots(0); } else { //Pay the total carrots to be paid to each player behind player.removeCarrots(payment * count); } return payment; } /** * This method performs the last part of the processing for hare card type GIVECARROTS: * * "GIVE 10 CARROTS TO EACH PLAYER LYING BEHIND YOU IN THE RACE (IF ANY)." * "If you haven't enough carrots, give them five each; if still not possible, one each." * "A player who doesn't want extra carrots may discard them to the 'carrot patch'." * * This method is called for each player behind the current player in the game who * accepts receipt of the payment of carrots by the current player to each of the * players behind. * * The method simply adds the carrot payment to the carrot holding of the specified * player behind. * * @param player The player behind who has accepted the offered payment of carrots. * * @param payment The number of carrots in payment that the player behind has accepted * from the current player. */ public void hareCardGiveCarrotsAccept(Player player, int payment) { player.addCarrots(payment); } // ********************************************************************************************************************************** // END: Hare Card Processing // ********************************************************************************************************************************** /** * Controls the player turn loop. * */ public void Turn() { currentPlayerKey++; if (currentPlayerKey > numberOfPlayers) { currentPlayerKey = 1; } } /** * Returns the players rank on the board 1st, 2nd, 3rd etc. * * @param player The current players ranking in game. * * @return the players rank in the game. */ private int calculateRank(Player player) { //Return the current rank for the passed in player //check players forward, plus check players finished. Add them, and current player //is int playerRanking = 1; //checking indexes of all other players against this player. for (Integer key : players.keySet()) { Player px = players.get(key); //MMcD: Fixed bug //if(px.getIndex()<player.getIndex()) if (px.getIndex() > player.getIndex()) { playerRanking += 1; } } return playerRanking; } /** * If there is no valid move available this method returns the player * to the start of the game, setting carrots back to 65, * and player keeps the same amount of lettuce. The immediately get to play again. * * @param player is returned to the start square of the game and allowed to move. */ public void restartPlayer(Player player) { player.setIndex(Player.INITIAL_INDEX);//returned to starting number of 65 player.setCarrots(Player.INITIAL_CARROTS);//returned to square index 0 player.setPlaysAgain(true); } }
true
be5d2acd27117140d6d4f93d1a02c31c5465ab9a
Java
wendyxie327/codelibrary
/代码库/可复用Fragement框架/MainActivity.java
UTF-8
9,309
1.929688
2
[]
no_license
package com.miaotech.health.ui.activity; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.miaotech.health.R; import com.miaotech.health.ui.fragement.EssayFragment; import com.miaotech.health.ui.fragement.FoodFragment; import com.miaotech.health.ui.fragement.MineFragment; import com.miaotech.health.utils.ExitApplication; import com.miaotech.health.widget.MyToast; import com.umeng.analytics.AnalyticsConfig; import com.umeng.analytics.MobclickAgent; /** * 负责控制下方按钮与页面切换 */ public class MainActivity extends FragmentActivity implements View.OnClickListener { private FoodFragment foodFragment=new FoodFragment(); private EssayFragment essayFragment=new EssayFragment(); private MineFragment mineFragment=new MineFragment(); private FragmentManager fragmentManager = getSupportFragmentManager(); private FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); private Fragment mfrom = foodFragment;// 默认显示控制第一个默认的界面 为 第一个 为后面 交换界面初始化 参数 private ImageView fragementfoodButton;// 食材按钮 private ImageView fragementessayButton;//文章按钮 private ImageView fragementmineButton;//我的按钮 private LinearLayout fragementfoodly;// 食材按钮 private LinearLayout fragementessayly;//文章按钮 private LinearLayout fragementminely;//我的按钮 private TextView fragementfoodtv; private TextView fragementessaytv; private TextView fragementminetv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ExitApplication.getInstance().addActivity(this);// 添加到应用界面队列用于统一退出 AnalyticsConfig.enableEncrypt(true);//友盟加密传输 assignViews(); addDefaultFragment(); } public void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub //super.onSaveInstanceState(outState); //将这一行注释掉,阻止activity崩溃时候保存fragment的状态防止重叠现象 } /** * 分配屏幕控件 */ private void assignViews() { fragementfoodtv=(TextView)findViewById(R.id.fragementfood_tv); fragementessaytv=(TextView)findViewById(R.id.fragementessay_tv);; fragementminetv=(TextView)findViewById(R.id.fragementmine_tv);; fragementfoodButton = (ImageView) findViewById(R.id.fragementfood_button); fragementessayButton = (ImageView) findViewById(R.id.fragementessay_button); fragementmineButton = (ImageView) findViewById(R.id.fragementmine_button); fragementfoodly = (LinearLayout) findViewById(R.id.fragementfood_ly); fragementessayly= (LinearLayout) findViewById(R.id.fragementessay_ly); fragementminely= (LinearLayout) findViewById(R.id.fragementmine_ly); fragementessayly.setOnClickListener(this); fragementminely.setOnClickListener(this); fragementfoodly.setOnClickListener(this); } /** * 添加默认显示的Fragment */ public void addDefaultFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.fragContent, foodFragment); fragmentTransaction.commit(); } /** * 屏幕底部按钮点击事件 * * @param v */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.fragementfood_ly: changeFoodMenu(); switchContent(mfrom, foodFragment); mfrom = foodFragment; break; case R.id.fragementessay_ly: changeEssayMenu(); switchContent(mfrom, essayFragment); mfrom = essayFragment; break; case R.id.fragementmine_ly: changeMineMenu(); switchContent(mfrom, mineFragment); mfrom = mineFragment; break; default: break; } } /** * 控制从activity * * @param from * @param to */ public void switchContent(Fragment from, Fragment to) { fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); if (!to.isAdded()) { // 先判断是否被add过 fragmentTransaction.hide(from).add(R.id.fragContent, to).commit(); // 隐藏当前的fragment,add下一个到Activity中 Log.i("noADD过===", "noADD过==="); } else { fragmentTransaction.hide(from).show(to).commit(); // 隐藏当前的fragment,显示下一个 Log.i("ADD过===", "ADD过==="); } } /** * 修改食物按钮样式 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void changeFoodMenu(){ // Drawable drawable = getResources().getDrawable(R.mipmap.book_menu_normal); //drawable.setBounds(0, 0, drawable.getMinimumWidth(), // drawable.getMinimumHeight()); // 设置边界 // fragementessayButton.setCompoundDrawables(null, drawable, null, null);// 画在右边 // fragementessayButton.setTextColor(getResources().getColor(R.color.menu_normal_color)); fragementessayButton.setBackground(getResources().getDrawable(R.drawable.book_menu_normal)); fragementfoodButton.setBackground(getResources().getDrawable(R.drawable.food_menu_pressed)); fragementmineButton.setBackground(getResources().getDrawable(R.drawable.mine_menu_normal)); fragementfoodtv.setTextColor(getResources().getColor(R.color.menu_pressed_color)); fragementessaytv.setTextColor(getResources().getColor(R.color.menu_normal_color)); fragementminetv.setTextColor(getResources().getColor(R.color.menu_normal_color)); } /** * 修改知识按钮样式 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void changeEssayMenu(){ fragementessayButton.setBackground(getResources().getDrawable(R.drawable.book_menu_pressed)); fragementfoodButton.setBackground(getResources().getDrawable(R.drawable.food_menu_normal)); fragementmineButton.setBackground(getResources().getDrawable(R.drawable.mine_menu_normal)); fragementfoodtv.setTextColor(getResources().getColor(R.color.menu_normal_color)); fragementessaytv.setTextColor(getResources().getColor(R.color.menu_pressed_color)); fragementminetv.setTextColor(getResources().getColor(R.color.menu_normal_color)); } /** * 修改我的按钮样式 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void changeMineMenu(){ fragementessayButton.setBackground(getResources().getDrawable(R.drawable.book_menu_normal)); fragementfoodButton.setBackground(getResources().getDrawable(R.drawable.food_menu_normal)); fragementmineButton.setBackground(getResources().getDrawable(R.drawable.mine_menu_pressed)); fragementfoodtv.setTextColor(getResources().getColor(R.color.menu_normal_color)); fragementessaytv.setTextColor(getResources().getColor(R.color.menu_normal_color)); fragementminetv.setTextColor(getResources().getColor(R.color.menu_pressed_color)); } /** * 重写返回键 */ private long exitTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // showDialog(); if((System.currentTimeMillis()-exitTime) > 2000){ MyToast.showToastShort(getApplicationContext(), "再按一次退出程序"); exitTime = System.currentTimeMillis(); } else { ExitApplication.getInstance().exit();//退出 } return true; } return super.onKeyDown(keyCode, event); } //友盟统计------------------ public void onResume() { super.onResume(); MobclickAgent.onResume(this); } public void onPause() { super.onPause(); MobclickAgent.onPause(this); } }
true
62e25d58222e3675187052154abfdbfcece54185
Java
J4ck5R3v3vng3/RC-Backend
/src/main/java/com/rc/SpringRefridgeCreatorApplication.java
UTF-8
478
1.648438
2
[]
no_license
package com.rc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication //@ComponentScan({"com.rc.core", "com.rc.service"}) //@EntityScan({"com.rc.entity"}) //@EnableJpaRepositories(basePackages = "com.rc.repository") public class SpringRefridgeCreatorApplication { public static void main(String[] args) { SpringApplication.run(SpringRefridgeCreatorApplication.class, args); } }
true
fa8a7a5345eac6ca0ab4152c7233408f601105eb
Java
tiebenxin/tp
/app/src/main/java/com/example/haoyuban111/mubanapplication/adapter/AdapterHostList.java
UTF-8
4,138
2.234375
2
[]
no_license
package com.example.haoyuban111.mubanapplication.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.haoyuban111.mubanapplication.R; import com.example.haoyuban111.mubanapplication.help_class.ContextHelper; import com.example.haoyuban111.mubanapplication.model.SecondModel; import com.example.haoyuban111.mubanapplication.ui.view.RoundImageView; import com.example.haoyuban111.mubanapplication.utils.DensityUtil; import java.util.ArrayList; import java.util.List; /** * Created by haoyuban111 on 2016/11/5. */ public class AdapterHostList<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private OnItemClickListener mItemClickListener; private final int TYPE_NORMAL = 0; private final int TYPE_LONG = 1; private final LayoutInflater inflater; private final Context mContext; private List<T> datas; public AdapterHostList(Context context) { super(); inflater = LayoutInflater.from(context); mContext = context; } public void setData(List<T> list) { if (datas == null) { datas = new ArrayList<T>(); } datas.clear(); datas.addAll(list); notifyDataSetChanged(); } public List<T> getList() { return datas; } @Override public int getItemCount() { return datas.size(); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { final ChildViewHolder holder = (ChildViewHolder) viewHolder; T model = datas.get(position); holder.setModel(model); if (mItemClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int layoutPosition = holder.getLayoutPosition(); mItemClickListener.onItemClick(holder.itemView, layoutPosition); } }); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewHolder, int viewType) { View view = inflater.inflate(R.layout.item_manage_list, null); ChildViewHolder holder = new ChildViewHolder(view); return holder; } public interface OnItemClickListener { void onItemClick(View view, int position); } public void setItemClickListener(OnItemClickListener mItemClickListener) { this.mItemClickListener = mItemClickListener; } public class ChildViewHolder extends RecyclerView.ViewHolder { public ChildViewHolder(View v) { super(v); iv_image = (RoundImageView) v.findViewById(R.id.iv_image); iv_trust = (ImageView) v.findViewById(R.id.iv_trust); tv_area = (TextView) v.findViewById(R.id.tv_area); tv_name = (TextView) v.findViewById(R.id.tv_name); ll_parent = (LinearLayout) v.findViewById(R.id.ll_parent); ll_root = (LinearLayout) v.findViewById(R.id.ll_root); } RoundImageView iv_image; ImageView iv_trust; TextView tv_area, tv_name; LinearLayout ll_parent, ll_root; private void setModel(T t) { if (t instanceof String) { String name = (String) t; tv_name.setText(name); tv_area.setText(name); } else if (t instanceof SecondModel) { SecondModel model = (SecondModel) t; Glide.with(ContextHelper.getApplicationContext()) .load(model.getAvatarUrl()) .centerCrop() .error(R.drawable.default_male) .into(iv_image); tv_name.setText(model.getName()); tv_area.setText(model.getText()); } } } }
true
991058ff206507203b045b6f659e98c4ded00cd8
Java
lxingfei/design-pattern
/factory-pattern/src/main/java/com/leh/factorypattern/factory/AbstractFactory/DefaultFactory.java
UTF-8
455
2.984375
3
[]
no_license
package com.leh.factorypattern.factory.AbstractFactory; import com.leh.factorypattern.factory.model.Car; /** * @Auther: leh * @Date: 2019/8/29 11:05 * @Description: 假设默认生产奥迪 */ public class DefaultFactory extends AbstractFactory{ private AudiFactory defaultFactory = new AudiFactory(); @Override public Car getCar() { System.out.println("excute DefaultFactory"); return defaultFactory.getCar(); } }
true
ea97f5712503d11454212b07ac15faccce45543d
Java
Hamdy10024/Datastructures2
/AVLTREES/src/binarySearchTrees/AVL.java
UTF-8
2,741
3.265625
3
[]
no_license
package binarySearchTrees; /** * Created by heshamelsawaf on 24/03/17. AVL tree based on BST; */ public class AVL<T extends Comparable<T>> extends BST<T> implements AVLTree<T> { @Override public INode<T> getTree() { return super.getRoot(); } private void leftRotate(INode<T> node) { INode<T> temp = node.getRightChild(); temp.setParent(node.getParent()); if (temp.getParent() == null) { this.root = temp; } node.pushRight(temp.getLeftChild()); temp.pushLeft(node); node.setParent(temp); this.updateHeight(node); this.updateHeight(temp); } private void updateHeight(INode<T> node) { node.setHeight(Math.max(this.height(node.getLeftChild()), height(node.getRightChild())) + 1); } private int height(INode<T> node) { if (node == null) { return 0; } return node.getHeight(); } private void rightRotate(INode<T> node) { INode<T> temp = node.getLeftChild(); temp.setParent(node.getParent()); if (temp.getParent() == null) { this.root = temp; } node.pushLeft(temp.getRightChild()); temp.pushRight(node); this.updateHeight(node); this.updateHeight(temp); } private void rebalance(INode<T> node) { while (node != null) { this.updateHeight(node); if (this.height(node.getLeftChild()) >= 2 + this.height(node.getRightChild())) { if (this.height(node.getLeftChild().getLeftChild()) < this.height(node.getLeftChild().getRightChild())) { this.leftRotate(node.getLeftChild()); } this.rightRotate(node); } else if (this.height(node.getRightChild()) >= 2 + this.height(node.getLeftChild())) { if (this.height(node.getRightChild().getRightChild()) < this.height(node.getRightChild().getLeftChild())) { this.rightRotate(node.getRightChild()); } this.leftRotate(node); } node = node.getParent(); } } @Override public void insert(T key) { INode<T> pus = super.insertNode(key); if (pus == null) { return; } this.rebalance(pus); } @Override public boolean delete(T key) { INode<T> todelete = find(key); if (todelete == null) { return false; } INode<T> inst = popMin(todelete.getRightChild()); if (inst == null) { if (todelete.getParent().getLeftChild() == todelete) { todelete.getParent().pushLeft(todelete.getLeftChild()); } else { todelete.getParent().pushRight(todelete.getLeftChild()); } rebalance(todelete.getParent()); } else { todelete.setValue(inst.getValue()); rebalance(inst.getParent()); } nodes--; return true; } }
true
fcb4a9571dd6c1d4eb2814ca18cba6287a92d42e
Java
Monkeyprime-hub/spring_project
/soulmate/src/main/java/com/example/soulmate/events/BNRestController.java
UTF-8
1,573
2.203125
2
[ "MIT" ]
permissive
package com.example.soulmate.events; import lombok.val; import org.springframework.context.event.EventListener; import org.springframework.http.MediaType; import org.springframework.scheduling.annotation.Async; 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.servlet.mvc.method.annotation.SseEmitter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; @RestController public class BNRestController { private final Set<SseEmitter> subscribers = new CopyOnWriteArraySet<>(); @RequestMapping(method = RequestMethod.GET, value = "/news-stream") public SseEmitter events() { val emitter = new SseEmitter(); subscribers.add(emitter); emitter.onTimeout(() -> subscribers.remove(emitter)); emitter.onCompletion(() -> subscribers.remove(emitter)); return emitter; } @Async @EventListener public void handleNews(BreakingNews breakingNews) { List<SseEmitter> deadEmmiters = new ArrayList<>(); subscribers.forEach( emitter -> { try { events().send(breakingNews, MediaType.APPLICATION_JSON); } catch (Exception e) { deadEmmiters.add(emitter); } } ); subscribers.removeAll(deadEmmiters); } }
true
7ce95d087f479aee339cfe72cc25f3cdc1932978
Java
KandyKad/Computer-Networks
/Java/Single Version/Server.java
UTF-8
1,947
3.0625
3
[]
no_license
/** * A UDP Server * @author Kunal Kanade Go Back N ARQ(Automatic Repeat Request) Again just a simulation.. */ import java.net.*; import java.io.*; import java.util.*; public class Server { public static void main(String args[]) throws Exception { ServerSocket server = new ServerSocket(6262); System.out.println("Server established."); Socket client = server.accept(); ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(client.getInputStream()); System.out.println("Client is now connected."); int x = (Integer)ois.readObject(); int k = (Integer)ois.readObject(); int j = 0; int i = (Integer)ois.readObject(); boolean flag = true; Random r = new Random(6); int mod =r.nextInt(6); while(mod == 1 || mod == 0) mod = r.nextInt(6); while(true) { int c = k; for(int h = 0; h <= x; h++) { System.out.print("|"+c+"|"); c =( c+1) % x; } System.out.println(); System.out.println(); if(k == j) { System.out.println("Frame " + k + " recieved" + "\n" + "Data: " + j); j++; System.out.println(); } else System.out.println("Frames recieved not in correct order" + "\n" + " Expected farme: " + j + "\n"+ " Recieved frame no :" + k); System.out.println(); if(j % mod == 0 && flag) { System.out.println("Error found. Acknowledgement not sent. "); flag = !flag; j--; } else if(k == j-1) { oos.writeObject(k); System.out.println("Acknowledgement sent."); } System.out.println(); if(j % mod == 0) flag = !flag; k = (Integer)ois.readObject(); if(k == -1) break; i = (Integer)ois.readObject(); } System.out.println("Client finished sending data. Exiting"); oos.writeObject(-1); } }
true
b0b6c90d113ecd50a07d4182abe1c98aa479170d
Java
ARESKAN2108/SimakouMaksimTMS2021
/Lesson3/src/main/java/HomeWork.java
UTF-8
9,465
4
4
[]
no_license
import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class HomeWork { public static void main(String[] args) { //Некоторые тесты для проверки задач. Можно также написать свои тесты. printArray(); System.out.println(operation(1)); System.out.println(operation(0)); System.out.println(calculateCountOfOddElementsInMatrix(new int[]{1, 2, 3, 4, 5, 6})); calculateSumOfDiagonalElements(); countDevs(103); foobar(6); foobar(10); foobar(15); printMatrix(); printPrimeNumbers(); } /** * Необходимо прочитать с консоли значение числа типа int, * далее создать одноменрый массив типа int размера прочитаного с консоли * далее заполнить массив случайными значениями * далее вывести массив на консоль */ private static void printArray() { // Можно еще через Random сделать.Я сделал через класс Math. System.out.println("Введите число:"); Scanner scanner = new Scanner(System.in); int sizeArray = scanner.nextInt(); int[] array = new int[sizeArray]; if (sizeArray == 0) { System.out.println("Array is empty"); } else { for (int i = 0; i < array.length; i++) { array[i] = (int) (Math.random() * 100); } System.out.println(Arrays.toString(array)); } } /** * Метод должен выполнять некоторую операцию с int "number" в зависимости от некоторых условий: * - if number положительное число, то необходимо number увеличить на 1 * - if number отрицательное - уменьшить на 2 * - if number равно 0 , то замените значение number на 10 * вернуть number после выполнения операций */ public static int operation(int number) { if (number > 0) { number++; } else if (number < 0) { number = number - 2; } else { number = 10; } return number; } /** * На вход приходит массив целых чисел типа int * Необходимо найти количество нечетных элементов в массиве и вернуть значение в метод main, * в котором это значение распечатается на консоль. */ public static int calculateCountOfOddElementsInMatrix(int[] ints) { int count = 0; if (ints.length == 0) { System.out.println("Array is empty"); } else { for (int anInt : ints) { if (anInt % 2 != 0) { count++; } } } return count; } /** * На вход приходит число. * Вывести в консоль фразу из разряда "_COUNT_ программистов", * заменить _COUNT_ на число которое пришло на вход в метод и заменить окончание в слове "программистов" на * уместное с точки зрения русского языка. * Пример: 1 программист, 42 программиста, 50 программистов * * @param count - количество программистов */ // не нравится стиль кода, но по-другому не смог придумать пока что public static void countDevs(int count) { int devsCount = count % 100; if (devsCount < 11 || devsCount > 14) { devsCount = count % 10; if (devsCount == 1) { System.out.println(count + " программист"); } else if (devsCount >= 2 && devsCount <= 4) { System.out.println(count + " программиста"); } else { System.out.println(count + " программистов"); } } else { System.out.println(count + " программистов"); } } /** * Метод должен выводить разные строки в консоли в зависимости от некоторых условий: * - если остаток от деления на 3 равен нулю - выведите "foo" (example of number - 6) * - если остаток от деления на 5 равен нулю - вывести "bar" (example of number - 10) * - если остаток от деления на 3 и 5 равен нулю 0 ,то вывести "foobar" (example of number - 15) */ public static void foobar(int number) { if (number % 3 == 0 && number % 5 == 0) { System.out.println("foobar"); } else if (number % 3 == 0) { System.out.println("foo"); } else if (number % 5 == 0) { System.out.println("bar"); } else { System.out.println("Let`s go again"); } } /** * заполнить рандомно 2-х мерный массив и посчитать сумму элементов на диагонали */ public static void calculateSumOfDiagonalElements() { int[][] array = new int[3][3]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = (int) (Math.random() * 10); System.out.print(array[i][j]); } System.out.println(); } int sum = 0; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (i == j) { sum += array[i][j]; } } } System.out.println("Сумма главной диагонали: " + sum); } /** * Шаги по реализации: * - Прочитать два int из консоли * - Создайте двумерный массив int (используйте целые числа, которые вы читаете по высоте и ширине консоли) * - Заполнить массив случайными значениями (до 100) * - Вывести в консоль матрицу заданного размера, но: * - Если остаток от деления элемента массива на 3 равен нулю - выведите знак "+" вместо значения элемента массива. * - Если остаток от деления элемента массива на 7 равен нулю - выведите знак "-" вместо значения элемента массива. * - В противном случае выведите "*" * <p> * Example: * - Значения с консоли - 2 и 3 * - Массив будет выглядеть так (значения будут разными, потому что он случайный) * 6 11 123 * 1 14 21 * - Для этого значения вывод в консоли должен быть: * <p> * + * * * * - + * <p> * Обратите внимание, что 21% 3 == 0 и 21% 7 = 0, но выводить надо не +-, а + */ public static void printMatrix() { //В этом методе казалось все намного проще чем я придумал! Спасибо за совет! Random random = new Random(); Scanner scanner = new Scanner(System.in); int heigh = scanner.nextInt(); int width = scanner.nextInt(); int[][] array = new int[heigh][width]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = random.nextInt(100); if (array[i][j] % 3 == 0) { System.out.print("+ "); } else if (array[i][j] % 7 == 0) { System.out.print("- "); } else { System.out.print("* "); } } System.out.println(); } } /** * Задача со звездочкой! * Метод должен печатать все простые числа <1000 * что такое просто число (https://www.webmath.ru/poleznoe/formules_18_5.php) */ public static void printPrimeNumbers() { for (int i = 2; i < 1000; i++) { boolean isPrime = true; for (int j = 2; j < i; j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) { System.out.println(i); } } } }
true
15ec8a64d5330fd19c4f378e72fd2c277d335c23
Java
ryw123/misskiss
/src/main/java/com/lin/missyou/dto/BannerDTO.java
UTF-8
454
1.765625
2
[]
no_license
package com.lin.missyou.dto; import com.lin.missyou.model.BannerItem; import lombok.Getter; import lombok.Setter; import java.util.Date; import java.util.List; /** * @author yanwei.ren * @date Created in 11:01 2020/4/21 * @Description: */ @Getter @Setter public class BannerDTO { private Long id; private String name; private String description; private String title; private String img; private List<BannerItem> items; }
true
4910d2cca7b76cdebf2885d851c9ccca5f50070d
Java
paulthoms/JavaSpringBoot
/src/main/java/com/webapp/demo/controller/FileUploadController.java
UTF-8
1,038
2.546875
3
[]
no_license
package com.webapp.demo.controller; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { public String UPLOAD_DIRECTORY = System.getProperty("user.dir") + "/uploads"; @PostMapping(path = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String UploadFile(@RequestParam("file") MultipartFile file) throws IOException { StringBuilder fileBuilder = new StringBuilder(); Path fileNameAndPath = Paths.get(UPLOAD_DIRECTORY,file.getOriginalFilename()); fileBuilder.append(file.getOriginalFilename()); Files.write(fileNameAndPath,file.getBytes()); return "upload success file"; } }
true
77676376824d42592caa0efdfd0f37ef8dbf65fa
Java
bkiers/Clay
/src/test/java/clay/ClayTest.java
UTF-8
5,116
3.125
3
[ "MIT", "Apache-2.0" ]
permissive
package clay; import clay.input.FileInput; import clay.input.CSVInput; import clay.input.StringInput; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; public class ClayTest { static class Address { String street; String number; String zipcode; String country; String city; Location location; } static class Location { double latitude; double longitude; } static class A { B b; } static class B { C c; } static class C { D d; } static class D { E e; } static class E { String x; } static class SimplePerson { String name; int age; } static class Person { String name; SimpleAddress address; } static class SimpleAddress { String street; String zipcode; String city; } @Test public void as_NonNullsFile_ShouldAllMapToNonNulls() throws Exception { CSVInput input = new FileInput(new File("src/test/resources/addresses.csv"), "|"); Clay clay = new Clay(input); List<Person> people = clay.as(Person.class); // 101 records of which the 1st is the header assertThat(people.size(), is(100)); for (Person p : people) { assertThat(p.name, is(not(nullValue()))); assertThat(p.address, is(not(nullValue()))); assertThat(p.address.street, is(not(nullValue()))); assertThat(p.address.zipcode, is(not(nullValue()))); assertThat(p.address.city, is(not(nullValue()))); } } @Test public void testWithAndWithoutHeaders() { // With headers in the input CSVInput input = new StringInput("street,number,zipcode,country,location.latitude,location.longitude,city\n" + "Kruiskade,1,2394CM,\"The Netherlands\",51.923626,4.477680,Rotterdam"); Clay clay = new Clay(input); List<Address> addresses = clay.as(Address.class); assertThat(addresses.size(), is(1)); Address address = addresses.get(0); assertThat(address.street, is("Kruiskade")); assertThat(address.number, is("1")); assertThat(address.zipcode, is("2394CM")); assertThat(address.country, is("The Netherlands")); assertThat(address.location.latitude, is(51.923626)); assertThat(address.location.longitude, is(4.477680)); assertThat(address.city, is("Rotterdam")); // Without headers in the input input = new StringInput("Kruiskade,1,2394CM,\"The Netherlands\",51.923626,4.477680,Rotterdam"); clay = new Clay(input, "street", "number", "zipcode", "country", "location.latitude", "location.longitude", "city"); addresses = clay.as(Address.class); assertThat(addresses.size(), is(1)); address = addresses.get(0); assertThat(address.street, is("Kruiskade")); assertThat(address.number, is("1")); assertThat(address.zipcode, is("2394CM")); assertThat(address.country, is("The Netherlands")); assertThat(address.location.latitude, is(51.923626)); assertThat(address.location.longitude, is(4.477680)); assertThat(address.city, is("Rotterdam")); } @Test public void deeplyNestedFieldsTest() { CSVInput input = new StringInput("b.c.d.e.x\nMU"); Clay clay = new Clay(input); List<A> as = clay.as(A.class); assertThat(as.size(), is(1)); A a = as.get(0); assertThat(a.b.c.d.e.x, is("MU")); } @Test public void newClay_ListHeaderValues_ShouldPass() { List<String> header = Arrays.asList("name", "age"); Clay clay = new Clay(new StringInput("John Doe,42"), header); List<SimplePerson> people = clay.as(SimplePerson.class); assertThat(people.size(), is(1)); assertThat(people.get(0).name, is("John Doe")); assertThat(people.get(0).age, is(42)); } @Test public void newClay_VarargsHeaderValues_ShouldPass() { Clay clay = new Clay(new StringInput("John Doe,42"), "name", "age"); List<SimplePerson> people = clay.as(SimplePerson.class); assertThat(people.size(), is(1)); assertThat(people.get(0).name, is("John Doe")); assertThat(people.get(0).age, is(42)); } @Test(expected = IllegalArgumentException.class) public void newClay_NoRecords_ShouldThrowException() { new Clay(new StringInput("")); } @Test(expected = IllegalArgumentException.class) public void newClay_OnlyHeaderNoRecord1_ShouldThrowException() { new Clay(new StringInput("name,age")); } @Test(expected = IllegalArgumentException.class) public void newClay_OnlyHeaderNoRecord2_ShouldThrowException() { new Clay(new StringInput("John Doe,42"), new ArrayList<String>()); } }
true
06daedc21f9c6ac48bda1859d36e6b148fe9ef34
Java
BobAndPlay/PlayWeb
/src/main/java/com/bob/ssm/service/impl/UserServiceImpl.java
UTF-8
1,930
2.234375
2
[]
no_license
package com.bob.ssm.service.impl; import com.bob.ssm.base.BaseResponse; import com.bob.ssm.dao.UserDao; import com.bob.ssm.model.User; import com.bob.ssm.service.UserService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; /** * Author: Bob * Date: 2016/7/15. */ @Service @Transactional(rollbackFor = Exception.class) public class UserServiceImpl implements UserService { @Resource private UserDao userDao; public User getUserById(Long userId) { return userDao.selectUserById(userId); } public void addUser(User user) { userDao.addUser(user); } public void updateUser(User user) { userDao.updateUser(user); } public void deleteUser(User user) { userDao.deleteUser(user); } public User getUserByPhoneOrEmail(String emailOrPhone, Short state) { return userDao.selectUserByPhoneOrEmail(emailOrPhone, state); } public List<User> getAllUser() { return userDao.selectAllUser(); } public List<User> searchUser(String name) { return userDao.selectUserByName(name); } public String login(String username, String pwd) throws JsonProcessingException { BaseResponse response = new BaseResponse(); ObjectMapper objectMapper = new ObjectMapper(); List<User> users = userDao.selectUserByName(username); if (users != null && users.size() > 0) { return objectMapper.writeValueAsString(response); } else { response.setCode("2"); response.setMsg("用户不存在"); return objectMapper.writeValueAsString(response); } } }
true
0666f4f6bd8fd80f81891893f527869e7b4777a8
Java
shitianxianga/mystudy
/src/suanfa/K连续位的最小翻转次数.java
UTF-8
702
2.546875
3
[]
no_license
package suanfa; /** * @author shitianxiang * @version 1.0 * @description * @updateRemark * @updateUser * @createDate 2021/2/19 10:20 * @updateDate 2021/2/19 10:20 **/ public class K连续位的最小翻转次数 { public int minKBitFlips(int[] A, int K) { int l=0; int[] diff=new int[A.length+1]; int rev=0; int r=l+K-1; int count=0; while (r<A.length) { rev+=diff[l]; if (A[l]==1||(A[l]+rev)%2!=0) { l++; r++; } else { diff[r+1]--; count++; } } return count; } }
true
bb9635fd2a3ec128beae16c849178936c713435d
Java
gliiii/store02
/src/main/java/cn/tedu/store02/mapper/DistrictMapper.java
UTF-8
583
2.328125
2
[]
no_license
package cn.tedu.store02.mapper; /** * 处理省市区数据的持久层接口 * @author glii0 * */ import java.util.List; import cn.tedu.store02.entity.District; public interface DistrictMapper { /** * 根据父级代号查询所有省/某省的所有市/某市的所有区 * @param parent 父级代号 * @return 数据集合 */ List<District> findListByParent(String parent); /** * 根据某省市区的代号,查询数据 * @param code 省/市/区代号 * @return 省/市/区名 */ District findByCode(String code); }
true
4c29f9b67715eadb8f02db16ddd2afd22fc09c90
Java
nuno1212s/Orb
/Punishments/src/main/java/com/nuno1212s/punishments/commands/PunishCommand.java
UTF-8
1,780
2.375
2
[]
no_license
package com.nuno1212s.punishments.commands; import com.nuno1212s.main.MainData; import com.nuno1212s.playermanager.PlayerData; import com.nuno1212s.punishments.main.Main; import com.nuno1212s.util.Pair; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.UUID; public class PunishCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { if (!commandSender.hasPermission("punishments")) { MainData.getIns().getMessageManager().getMessage("NO_PERMISSION").sendTo(commandSender); return true; } if (args.length < 1) { commandSender.sendMessage(ChatColor.RED + "/punish <player>"); return true; } String playerName = args[0]; Player player = Bukkit.getPlayer(playerName); UUID playerID; if (player != null) { playerID = player.getUniqueId(); } else { Pair<PlayerData, Boolean> playerData = MainData.getIns().getPlayerManager().getOrLoadPlayer(playerName); if (playerData.key() == null) { MainData.getIns().getMessageManager().getMessage("PLAYER_NOT_FOUND").sendTo(commandSender); return true; } playerID = playerData.key().getPlayerID(); } Main.getIns().getInventoryManager().setPlayerToTarget(((Player) commandSender).getUniqueId(), playerID); ((Player) commandSender).openInventory(Main.getIns().getInventoryManager().getMainInventory()); return true; } }
true
06eb917581553c6a4bcb06f0c1339165bd005676
Java
ridixcr/projects
/SVA_1.0/src/java/org/edessco/sva/cv/EstandarBean.java
UTF-8
16,109
1.648438
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.edessco.sva.cv; import java.util.Date; import java.util.LinkedList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.servlet.http.HttpSession; import org.edessco.sva.be.*; import org.edessco.sva.bl.*; import org.edessco.sva.util.Tarea; import static org.edessco.sva.util.Utilitario.setTareaEvento; @ManagedBean @ViewScoped public class EstandarBean { @ManagedProperty(value = "#{estandarBL}") private EstandarBL estandarBL; @ManagedProperty(value = "#{estandar}") private Estandar estandar; private List<Estandar> listaEstandares = new LinkedList<>(); private List<SelectItem> selectOneItemsEstandar; @ManagedProperty(value = "#{matrizRecoleccionDatosBL}") private MatrizRecoleccionDatosBL matrizRecoleccionDatosBL; @ManagedProperty(value = "#{matrizRecoleccionDatos}") private MatrizRecoleccionDatos matrizRecoleccionDatos; @ManagedProperty(value = "#{registroResultadoBL}") private RegistroResultadoBL registroResultadoBL; @ManagedProperty(value = "#{registroResultado}") private RegistroResultado registroResultado; @ManagedProperty(value = "#{registroGradoCumplimientoBL}") private RegistroGradoCumplimientoBL registroGradoCumplimientoBL; @ManagedProperty(value = "#{registroGradoCumplimiento}") private RegistroGradoCumplimiento registroGradoCumplimiento; @ManagedProperty(value = "#{iniciativaMejoraBL}") private IniciativaMejoraBL iniciativaMejoraBL; @ManagedProperty(value = "#{iniciativaMejora}") private IniciativaMejora iniciativaMejora; @ManagedProperty(value = "#{autoevaluacionBL}") private AutoevaluacionBL autoevaluacionBL; @ManagedProperty(value = "#{autoevaluacion}") private Autoevaluacion autoevaluacion; private List listaResultadosEncuestaDocente = new LinkedList<>(); @PostConstruct public void init() { setAutoevaluacion(getAutoevaluacionBL().buscar(getAutoevaluacionBL().maxId())); listar(); } public void recuperarResultadosFMR(long id_estandar) { setMatrizRecoleccionDatos(getMatrizRecoleccionDatosBL().buscar(id_estandar, getAutoevaluacion().getIdautoevaluacion())); if (getMatrizRecoleccionDatos() == null) { setMatrizRecoleccionDatos(new MatrizRecoleccionDatos()); getMatrizRecoleccionDatos().setEstandar(getEstandarBL().buscar(id_estandar)); getMatrizRecoleccionDatos().setAutoevaluacion(getAutoevaluacion()); getMatrizRecoleccionDatos().setFechaRegistro(new Date()); listaResultadosEncuestaDocente.clear(); listaResultadosEncuestaDocente.addAll(getEstandarBL().respuestaCuestionarioDocente(id_estandar)); for (Object item : listaResultadosEncuestaDocente) { Object[] o = (Object[]) item; if (Double.parseDouble(o[0].toString()) >= 50) { getMatrizRecoleccionDatos().setResultadoCuestionario(true); } else { getMatrizRecoleccionDatos().setResultadoCuestionario(false); } } } } public void recuperarResultadosFRR(long id_estandar) { setRegistroResultado(getRegistroResultadoBL().buscar(id_estandar, getAutoevaluacion().getIdautoevaluacion())); if (getRegistroResultado() == null) { setRegistroResultado(new RegistroResultado()); getRegistroResultado().setEstandar(getEstandarBL().buscar(id_estandar)); getRegistroResultado().setAutoevaluacion(getAutoevaluacion()); getRegistroResultado().setFechaTaller(new Date()); listaResultadosEncuestaDocente.clear(); listaResultadosEncuestaDocente.addAll(getEstandarBL().respuestaCuestionarioDocente(id_estandar)); for (Object item : listaResultadosEncuestaDocente) { Object[] o = (Object[]) item; if (Double.parseDouble(o[0].toString()) >= 50) { getRegistroResultado().setEstado(true); } else { getRegistroResultado().setEstado(false); } } } } public void recuperarResultadosFRC(long id_estandar) { setRegistroGradoCumplimiento(getRegistroGradoCumplimientoBL().buscar(id_estandar, getAutoevaluacion().getIdautoevaluacion())); if (getRegistroGradoCumplimiento() == null) { setRegistroGradoCumplimiento(new RegistroGradoCumplimiento()); getRegistroGradoCumplimiento().setEstandar(getEstandarBL().buscar(id_estandar)); getRegistroGradoCumplimiento().setAutoevaluacion(getAutoevaluacion()); listaResultadosEncuestaDocente.clear(); listaResultadosEncuestaDocente.addAll(getEstandarBL().respuestaCuestionarioDocente(id_estandar)); for (Object item : listaResultadosEncuestaDocente) { Object[] o = (Object[]) item; if (Double.parseDouble(o[0].toString()) >= 50) { getRegistroGradoCumplimiento().setCumplimiento(true); } else { getRegistroGradoCumplimiento().setCumplimiento(false); } } } } public void recuperarResultadosFRM(long id_estandar) { setIniciativaMejora(getIniciativaMejoraBL().buscar(id_estandar, getAutoevaluacion().getIdautoevaluacion())); if (getIniciativaMejora() == null) { setIniciativaMejora(new IniciativaMejora()); getIniciativaMejora().setEstandar(getEstandarBL().buscar(id_estandar)); getIniciativaMejora().setAutoevaluacion(getAutoevaluacion()); listaResultadosEncuestaDocente.clear(); listaResultadosEncuestaDocente.addAll(getEstandarBL().respuestaCuestionarioDocente(id_estandar)); for (Object item : listaResultadosEncuestaDocente) { Object[] o = (Object[]) item; if (Double.parseDouble(o[0].toString()) >= 50) { getIniciativaMejora().setEstado(true); } else { getIniciativaMejora().setEstado(false); } } } } public void guardarMatrizRecoleccionDatos() { if (getMatrizRecoleccionDatos().getIdmatriz() <= 0) { setTareaEvento(new Tarea(Tarea.REGISTRO, getMatrizRecoleccionDatosBL().registrar(getMatrizRecoleccionDatos())) { @Override public void proceso() { setMatrizRecoleccionDatos(new MatrizRecoleccionDatos()); } }); } else { setTareaEvento(new Tarea(Tarea.ACTUALIZACION,getMatrizRecoleccionDatosBL().actualizar(getMatrizRecoleccionDatos())) { @Override public void proceso() {} }); ; } setMatrizRecoleccionDatos(new MatrizRecoleccionDatos()); } public void guardarRegistroResultados() { if (getRegistroResultado().getIdregistroresultado() <= 0) { setTareaEvento(new Tarea(Tarea.REGISTRO, getRegistroResultadoBL().registrar(getRegistroResultado())) { @Override public void proceso() { setMatrizRecoleccionDatos(new MatrizRecoleccionDatos()); } }); } else { setTareaEvento(new Tarea(Tarea.ACTUALIZACION,getRegistroResultadoBL().actualizar(getRegistroResultado())) { @Override public void proceso() {} }); ; } setMatrizRecoleccionDatos(new MatrizRecoleccionDatos()); } public void guardarRegistroGradoCumplimiento() { if (getRegistroGradoCumplimiento().getIdgradocumplimiento() <= 0) { setTareaEvento(new Tarea(Tarea.REGISTRO, getRegistroGradoCumplimientoBL().registrar(getRegistroGradoCumplimiento())) { @Override public void proceso() { setRegistroGradoCumplimiento(new RegistroGradoCumplimiento()); } }); } else { setTareaEvento(new Tarea(Tarea.ACTUALIZACION,getRegistroGradoCumplimientoBL().actualizar(getRegistroGradoCumplimiento())) { @Override public void proceso() {} }); ; } setMatrizRecoleccionDatos(new MatrizRecoleccionDatos()); } public void guardarIniciativaMejora() { if (getIniciativaMejora().getIdiniciativa() <= 0) { setTareaEvento(new Tarea(Tarea.REGISTRO, getIniciativaMejoraBL().registrar(getIniciativaMejora())) { @Override public void proceso() { setIniciativaMejora(new IniciativaMejora()); } }); } else { setTareaEvento(new Tarea(Tarea.ACTUALIZACION,getIniciativaMejoraBL().actualizar(getIniciativaMejora())) { @Override public void proceso() {} }); ; } setMatrizRecoleccionDatos(new MatrizRecoleccionDatos()); } public void registrar() { setTareaEvento(new Tarea(Tarea.REGISTRO, getEstandarBL().registrar(getEstandar())) { @Override public void proceso() { estandar = new Estandar(); listar(); } }); } public void listar() { HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); if (httpSession.getAttribute("idCriterio") != null) { setListaEstandares(getEstandarBL().listarEstandar(Long.parseLong(httpSession.getAttribute("idCriterio").toString()))); } else { setListaEstandares(getEstandarBL().listar("")); } } public void actualizar() { Estandar temp = new Estandar(); String msg; temp = buscarId(); temp.setNumeroEstandar(getEstandar().getNumeroEstandar()); temp.setTitulo(getEstandar().getTitulo()); temp.setDescripcion(getEstandar().getDescripcion()); temp.setTipoEstandar(getEstandar().getTipoEstandar()); temp.setEstado(getEstandar().getEstado()); temp.setCriterio(getEstandar().getCriterio()); long res = getEstandarBL().actualizar(temp); if (res == 0) { msg = "Se actualizó correctamente el registro."; FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención", msg); FacesContext.getCurrentInstance().addMessage(null, message); } else { msg = "Error al actualizar el registro."; FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atención", msg); FacesContext.getCurrentInstance().addMessage(null, message); } listar(); } public void eliminar() { Estandar temp = new Estandar(); String msg; temp = buscarId(); long res = getEstandarBL().eliminar(temp); if (res == 0) { msg = "Se eliminó correctamente el registro."; FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Atención", msg); FacesContext.getCurrentInstance().addMessage(null, message); } else { msg = "Error al eliminar el registro."; FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Atención", msg); FacesContext.getCurrentInstance().addMessage(null, message); } listar(); } public Estandar buscarId() { return estandarBL.buscar(getEstandar().getIdestandar()); } public void limpiar() { this.estandar.setIdestandar(null); this.estandar.setNumeroEstandar(null); this.estandar.setTitulo(""); this.estandar.setDescripcion(""); this.estandar.setEstado(false); estandar.setCriterio(new Criterio()); } public EstandarBL getEstandarBL() { return estandarBL; } public void setEstandarBL(EstandarBL estandarBL) { this.estandarBL = estandarBL; } public Estandar getEstandar() { return estandar; } public void setEstandar(Estandar estandar) { this.estandar = estandar; } public List<Estandar> getListaEstandares() { return listaEstandares; } public void setListaEstandares(List<Estandar> listaEstandares) { this.listaEstandares = listaEstandares; } public List<SelectItem> getSelectOneItemsEstandar() { this.selectOneItemsEstandar = new LinkedList<SelectItem>(); for (Estandar estandar1 : listaEstandares) { this.setEstandar(estandar1); SelectItem selectItem = new SelectItem(estandar.getIdestandar(), estandar.getTitulo()); this.selectOneItemsEstandar.add(selectItem); } return selectOneItemsEstandar; } public void setSelectOneItemsEstandar(List<SelectItem> selectOneItemsEstandar) { this.selectOneItemsEstandar = selectOneItemsEstandar; } public MatrizRecoleccionDatosBL getMatrizRecoleccionDatosBL() { return matrizRecoleccionDatosBL; } public void setMatrizRecoleccionDatosBL(MatrizRecoleccionDatosBL matrizRecoleccionDatosBL) { this.matrizRecoleccionDatosBL = matrizRecoleccionDatosBL; } public MatrizRecoleccionDatos getMatrizRecoleccionDatos() { return matrizRecoleccionDatos; } public void setMatrizRecoleccionDatos(MatrizRecoleccionDatos matrizRecoleccionDatos) { this.matrizRecoleccionDatos = matrizRecoleccionDatos; } public AutoevaluacionBL getAutoevaluacionBL() { return autoevaluacionBL; } public void setAutoevaluacionBL(AutoevaluacionBL autoevaluacionBL) { this.autoevaluacionBL = autoevaluacionBL; } public Autoevaluacion getAutoevaluacion() { return autoevaluacion; } public void setAutoevaluacion(Autoevaluacion autoevaluacion) { this.autoevaluacion = autoevaluacion; } public RegistroResultadoBL getRegistroResultadoBL() { return registroResultadoBL; } public void setRegistroResultadoBL(RegistroResultadoBL registroResultadoBL) { this.registroResultadoBL = registroResultadoBL; } public RegistroResultado getRegistroResultado() { return registroResultado; } public void setRegistroResultado(RegistroResultado registroResultado) { this.registroResultado = registroResultado; } public RegistroGradoCumplimientoBL getRegistroGradoCumplimientoBL() { return registroGradoCumplimientoBL; } public void setRegistroGradoCumplimientoBL(RegistroGradoCumplimientoBL registroGradoCumplimientoBL) { this.registroGradoCumplimientoBL = registroGradoCumplimientoBL; } public RegistroGradoCumplimiento getRegistroGradoCumplimiento() { return registroGradoCumplimiento; } public void setRegistroGradoCumplimiento(RegistroGradoCumplimiento registroGradoCumplimiento) { this.registroGradoCumplimiento = registroGradoCumplimiento; } public IniciativaMejoraBL getIniciativaMejoraBL() { return iniciativaMejoraBL; } public void setIniciativaMejoraBL(IniciativaMejoraBL iniciativaMejoraBL) { this.iniciativaMejoraBL = iniciativaMejoraBL; } public IniciativaMejora getIniciativaMejora() { return iniciativaMejora; } public void setIniciativaMejora(IniciativaMejora iniciativaMejora) { this.iniciativaMejora = iniciativaMejora; } }
true
661122310758d61d7b49f12c5e657e37b48241a5
Java
showkatbinidris70/CoreJava
/Test/src/TwoDArrySort.java
UTF-8
695
2.984375
3
[]
no_license
import java.util.Arrays; /* * 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. */ /** * * @author User */ public class TwoDArrySort { public static void main(String[] args) { int[][] data = { {2, 3, 4, 6}, {2, 4, 4, 6}, {3, 3, 1, 0}, {2, 9, 4, 6} }; System.out.println("Data Table"); for (int[] d : data) { Arrays.sort(d); for (int a : d) { System.out.println(a + " ,"); } System.out.println(); } } }
true
e91a11b680f336bf07a18cde015c577bc6ce4a3a
Java
RKUniRitter/thread1
/src/MeuTeste.java
UTF-8
552
3.328125
3
[]
no_license
//Professor Isidro Explica - Episódio 11 - Threads //https://www.youtube.com/watch?v=gILOMDm1xxk&feature=youtu.be public class MeuTeste { public static void main(String[] args) { // TODO Auto-generated method stub MinhaThread t1, t2; t1 = new MinhaThread(1, 10, 500); t2 = new MinhaThread(2, 10, 800); t1.start(); t2.start(); try { t1.join(); t2.join(); System.out.println("Thread principal encerra."); } catch (Exception ex) { System.out.println("Deu ruim ne thread principal... " +ex.getMessage()); } } }
true
e3d08d9c962849cab486f5089055ec5648079b4c
Java
RalphSu/789
/p2p-web/src/main/java/com/icebreak/p2p/base/BaseHandlerExceptionResolver.java
UTF-8
808
2.203125
2
[]
no_license
package com.icebreak.p2p.base; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class BaseHandlerExceptionResolver implements HandlerExceptionResolver { private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(getClass()); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(baos)); String exception = baos.toString(); logger.error(exception); return null; } }
true
597f34f1e74b5613c5e295e4891915d1baa40580
Java
ladyhua/javaOJ
/src/com/leetcode/code/Main15.java
UTF-8
1,932
3.296875
3
[]
no_license
package com.leetcode.code; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //AC public class Main15 { public static void main(String args[]) { int[] nums = {-1,0,1,2,-1,-4}; System.out.println(threeSum(nums)); } public static List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> l = new ArrayList<List<Integer>>(); Arrays.sort(nums); for(int i=nums.length-1; i>1; i--) { if(i < nums.length-1 && nums[i] == nums[i+1]) continue; List<List<Integer>> twoList = twoSum(nums,i-1,-nums[i]); for(List<Integer> lTemp : twoList) { lTemp.add(nums[i]); } l.addAll(twoList); } return l; } private static List<List<Integer>> twoSum(int[] nums, int end, int target) { List<List<Integer>> list = new ArrayList<List<Integer>>(); int i = 0,j = end; while(i < j) { if(nums[i] + nums[j] > target) { j--; } else if(nums[i] + nums[j] < target) { i++; } else { List<Integer> ll = new ArrayList<Integer>(); ll.add(nums[i]); ll.add(nums[j]); list.add(ll); i++; j--; while(i<j && nums[i] == nums[i-1]) i++; while(i<j && nums[j] == nums[j+1]) j--; } } return list; } /** * @Description 超时 * @author hlz * @param nums * @return */ public static List<List<Integer>> threeSum1(int[] nums) { List<List<Integer>> l = new ArrayList<List<Integer>>(); Arrays.sort(nums); int sum = -1; for(int i=0; i<nums.length-2; i++) { for(int j=i+1; j< nums.length-1; j++) { for(int k=nums.length-1; k>j;k--) { sum = nums[i] + nums[j] + nums[k]; if(sum < 0) break; if(sum == 0) { List<Integer> lTemp = new ArrayList<Integer>(); lTemp.add(nums[i]); lTemp.add(nums[j]); lTemp.add(nums[k]); if(!l.contains(lTemp)) l.add(lTemp); } } } } return l; } }
true
771601e7deb77c7fe2219f98ce636993b8491af6
Java
hechengming1112/manage
/src/main/java/admin/com/student/sys/mapper/SysUserRoleMapper.java
UTF-8
470
1.890625
2
[]
no_license
package admin.com.student.sys.mapper; import admin.com.student.sys.domain.SysUserRole; import java.util.List; /** * 用户和角色关联Mapper接口 * * @author hecm * @date 2019-09-05 */ public interface SysUserRoleMapper { /** * 查询用户和角色关联列表 * * @param sysUserRole 用户和角色关联 * @return 用户和角色关联集合 */ public List<SysUserRole> selectSysUserRoleList(SysUserRole sysUserRole); }
true
e32f4f90a72bd88af6f5c913fa8b75700c271afc
Java
ly10228/SpringCloud
/cloud2020/cloud-provider-payment8001/src/main/java/com/ly/springcloud/controller/PaymentController.java
UTF-8
2,587
2.109375
2
[]
no_license
package com.ly.springcloud.controller; import com.ly.springcloud.common.CommonResult; import com.ly.springcloud.common.enums.ResultEnum; import com.ly.springcloud.entity.Payment; import com.ly.springcloud.service.PaymentService; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author luoyong * 
* @create 2020-03-29 4:59 下午 * 
* @last modify by [luoyong 2020-03-29 4:59 下午] * @Description: PaymentController **/ @RestController @Slf4j @RequestMapping("/payment") public class PaymentController { @Autowired private PaymentService paymentService; @Autowired private EurekaDiscoveryClient discoveryClient; @PostMapping("save") @ApiOperation(value = "保存支付流水信息") CommonResult<Boolean> create(@RequestBody Payment payment) { int i = paymentService.create(payment); if (i <= 0) { return new CommonResult(ResultEnum.FAil.getCode(), ResultEnum.FAil.getDesc(), true); } return new CommonResult(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getDesc(), true); } @GetMapping("getPaymentById") @ApiOperation(value = "获取支付信息") CommonResult<Payment> getPaymentById(@RequestParam Long id) { Payment payment = paymentService.getPaymentById(id); if (null == payment) { return new CommonResult(ResultEnum.FAil.getCode(), ResultEnum.FAil.getDesc(), null); } return new CommonResult(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getDesc(), payment); } /** * @return * @Description: 服务发现 获取服务信息 * @author luoyong * @create 7:08 下午 2020/4/12 * @last modify by [LuoYong 7:08 下午 2020/4/12 ] */ @GetMapping("/discovery") public Object discovery() { List<String> services = discoveryClient.getServices(); for (String element : services) { log.info("element:\t" + element); } List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE"); for (ServiceInstance instance : instances) { log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri()); } return this.discoveryClient; } }
true
76c0886c285f73e3a399363c8e36dc2c9c5cca2c
Java
wesson818/SMSPluginForCordova2.3.0
/SMSComposer.java
UTF-8
1,817
2.234375
2
[]
no_license
/** * * Phonegap SMS composer plugin for Android with multiple attachments handling * * Version 1.0 * * Edit from EmailComposer Guido Sabatini 2012 * */ package com.wishbonemedia.jimsbookingDev; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Intent; import android.net.Uri; import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.LOG; public class SMSComposer extends CordovaPlugin { @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if ("showSMSComposer".equals(action)) { try { JSONObject parameters = args.getJSONObject(0); if (parameters != null) { sendSMS(parameters); } } catch (Exception e) { } callbackContext.success(); return true; } return false; // Returning false results in a "MethodNotFound" error. } private void sendSMS(JSONObject parameters) { final Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW); //String callback = parameters.getString("callback"); smsIntent.setType("vnd.android-dir/mms-sms"); // setting body try { String body = parameters.getString("body"); if (body != null && body.length() > 0) { smsIntent.putExtra("sms_body", body); } } catch (Exception e) { LOG.e("SMSComposer", "Error handling body param: " + e.toString()); } this.cordova.startActivityForResult(this, smsIntent, 0); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { // TODO handle callback super.onActivityResult(requestCode, resultCode, intent); LOG.e("SMSComposer", "ResultCode: " + resultCode); // IT DOESN'T SEEM TO HANDLE RESULT CODES } }
true
be108653680870f8e1846d3139b79a24d47ece15
Java
vedant9/Hostel-DBMS
/DBS/src/db/Studdetails.java
UTF-8
4,305
2.59375
3
[]
no_license
package db; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import java.awt.Toolkit; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Studdetails extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Studdetails frame = new Studdetails(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Studdetails() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); setExtendedState(JFrame.MAXIMIZED_BOTH); setUndecorated(true); setVisible(true); getContentPane().setPreferredSize(Toolkit.getDefaultToolkit().getScreenSize()); pack(); JButton btnStudentDetails = new JButton("Student Details"); btnStudentDetails.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(Mainpage.admin==1) { StudentRecords r1 = new StudentRecords(); r1.setVisible(true); } else { Newstud ns1 = new Newstud(); ns1.setVisible(true); } } }); btnStudentDetails.setBounds(33, 72, 117, 23); contentPane.add(btnStudentDetails); JButton btnIncidents = new JButton("Incidents"); btnIncidents.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Incidents i1= new Incidents(); i1.setVisible(true); } }); btnIncidents.setBounds(33, 121, 117, 23); contentPane.add(btnIncidents); JButton btnLists = new JButton("Lists"); btnLists.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Lists list1= new Lists(); list1.setVisible(true); } }); btnLists.setBounds(33, 170, 117, 23); contentPane.add(btnLists); JButton btnHostelDatabase = new JButton("Hostel Database"); btnHostelDatabase.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(Mainpage.admin==1) { HostelData h1 = new HostelData(); h1.setVisible(true); } else { JOptionPane.showMessageDialog(null,"ACCESS DENIED! You need administrator privileges to view this file."); } } }); btnHostelDatabase.setBounds(265, 72, 117, 23); contentPane.add(btnHostelDatabase); JButton btnMaintenance = new JButton("Maintenance"); btnMaintenance.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(Mainpage.admin==1) { Maintenance m1= new Maintenance(); m1.setVisible(true); } else { JOptionPane.showMessageDialog(null,"ACCESS DENIED! You need administrator privileges to view this file."); } } }); btnMaintenance.setBounds(265, 121, 117, 23); contentPane.add(btnMaintenance); JButton btnRoomtype = new JButton("Roomtype"); btnRoomtype.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Roomtype room1 = new Roomtype(); room1.setVisible(true); } }); btnRoomtype.setBounds(265, 170, 117, 23); contentPane.add(btnRoomtype); JButton btnCaretakerInfo = new JButton("Caretaker Info"); btnCaretakerInfo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Caretaker care1 = new Caretaker(); care1.setVisible(true); } }); btnCaretakerInfo.setBounds(33, 213, 117, 23); contentPane.add(btnCaretakerInfo); JButton btnExit = new JButton("Exit"); btnExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); btnExit.setBounds(265, 213, 117, 23); contentPane.add(btnExit); JButton btnBookARoom = new JButton("Book a room"); btnBookARoom.setBounds(33, 258, 117, 23); contentPane.add(btnBookARoom); } }
true
782158279a9b162cf61832a621b7c9c10843cb4b
Java
WeiXuanYap/tp
/src/test/java/seedu/budgettracker/logic/commands/AddBudgetTest.java
UTF-8
2,359
3.015625
3
[]
no_license
package seedu.budgettracker.logic.commands; import org.junit.jupiter.api.Test; import seedu.budgettracker.data.RecordList; import seedu.budgettracker.data.records.exceptions.DuplicateBudgetException; import seedu.budgettracker.logic.commands.exceptions.CommandException; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertFalse; public class AddBudgetTest { @Test void addBudget_rawCommand_budgetListAmount_20() { double spendingLimit = 20.00; int month = 12; RecordList currentBudgetList = new RecordList(month); try { currentBudgetList.addBudget(spendingLimit); } catch (DuplicateBudgetException e) { e.printStackTrace(); } assertEquals(20.00, currentBudgetList.getBudget().getAmount()); } @Test void execute_invalidAmount_throwsCommandException() { double negativeAmount = -20.00; double zeroAmount = 0.00; double tooLargeAmount = 1000000001; int month = LocalDate.now().getMonthValue(); AddBudgetCommand addNegativeBudgetCommand = new AddBudgetCommand(negativeAmount, month); assertThrows(CommandException.class, addNegativeBudgetCommand::execute); AddBudgetCommand addZeroBudgetCommand = new AddBudgetCommand(zeroAmount, month); assertThrows(CommandException.class, addZeroBudgetCommand::execute); AddBudgetCommand addTooLargeBudgetCommand = new AddBudgetCommand(tooLargeAmount, month); assertThrows(CommandException.class, addTooLargeBudgetCommand::execute); } @Test public void equals() { AddBudgetCommand addTest1Command = new AddBudgetCommand(100, LocalDate.now().getMonthValue()); AddBudgetCommand addTest2Command = new AddBudgetCommand(200, LocalDate.now().getMonthValue()); //same object -> returns true assertEquals(addTest1Command, addTest1Command); //different types -> returns false assertFalse(addTest1Command.equals(1)); // different expenditures -> returns false assertFalse(addTest1Command.equals(addTest2Command)); } }
true
c023ccc1e236155ba3b12e5ca7def4665cfe93b3
Java
eltazar/RobotSample
/src/it/sapienza/robotsample/MyAbsoluteLayout.java
UTF-8
3,953
2.828125
3
[]
no_license
package it.sapienza.robotsample; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.RemoteViews.RemoteView; /** * A layout that lets you specify exact locations (x/y coordinates) of its * children. Absolute layouts are less flexible and harder to maintain than * other types of layouts without absolute positioning. * * <p><strong>XML attributes</strong></p> <p> See {@link * android.R.styleable#ViewGroup ViewGroup Attributes}, {@link * android.R.styleable#View View Attributes}</p> * * <p>Note: This class is a clone of AbsoluteLayout, which is now deprecated. */ @RemoteView public class MyAbsoluteLayout extends ViewGroup { public MyAbsoluteLayout(Context context) { super(context); } public MyAbsoluteLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); int maxHeight = 0; int maxWidth = 0; // Find out how big everyone wants to be measureChildren(widthMeasureSpec, heightMeasureSpec); // Find rightmost and bottom-most child for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childRight; int childBottom; MyAbsoluteLayout.LayoutParams lp = (MyAbsoluteLayout.LayoutParams) child.getLayoutParams(); childRight = lp.x + child.getMeasuredWidth(); childBottom = lp.y + child.getMeasuredHeight(); maxWidth = Math.max(maxWidth, childRight); maxHeight = Math.max(maxHeight, childBottom); } } // Account for padding too maxWidth += getPaddingLeft () + getPaddingRight (); maxHeight += getPaddingTop () + getPaddingBottom (); // Check against minimum height and width maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), resolveSize(maxHeight, heightMeasureSpec)); } /** * Returns a set of layout parameters with a width of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, * a height of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} * and with the coordinates (0, 0). */ @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int count = getChildCount(); int paddingL = getPaddingLeft (); int paddingT = getPaddingTop (); for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { MyAbsoluteLayout.LayoutParams lp = (MyAbsoluteLayout.LayoutParams) child.getLayoutParams(); int childLeft = paddingL + lp.x; int childTop = paddingT + lp.y; child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new MyAbsoluteLayout.LayoutParams(getContext(), attrs); } // Override to allow type-checking of LayoutParams. @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof MyAbsoluteLayout.LayoutParams; } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } public static class LayoutParams extends ViewGroup.LayoutParams { public int x; public int y; public LayoutParams(int width, int height, int x, int y) { super(width, height); this.x = x; this.y = y; } public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } }
true
2c25fdbfa60a6a6fa3852b6d05788f8bee9db164
Java
ShubhamPatelGit/BookShop
/BookShop/src/com/dao/BookDao.java
UTF-8
6,975
2.734375
3
[]
no_license
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import com.pojos.BookPojo; import com.sql.SQLConnection; public class BookDao { public int maxid() throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("select max(id) from books"); ResultSet rs = ps.executeQuery(); if(!rs.next()) return 1; //rs.next(); int max = Integer.parseInt(rs.getString(1)); return max+1; } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public void upload(BookPojo book) throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("insert into books values(?,?,?,?,?,?)"); ps.setInt(1, book.getbId()); ps.setString(2, book.getbName()); ps.setString(3, book.getbAuthor()); ps.setInt(4, book.getbPrice()); ps.setInt(5, book.getbQuantity()); ps.setString(6, book.getbCourse()); ps.execute(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public BookPojo edit(int id)throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("select * from books where id= "+id); ResultSet rs = ps.executeQuery(); BookPojo book = new BookPojo(); if(!rs.next()) book.setbId(0); else { book.setbId(Integer.parseInt(rs.getString(1))); book.setbName(rs.getString(2)); book.setbAuthor(rs.getString(3)); book.setbPrice(Integer.parseInt(rs.getString(4))); book.setbQuantity(Integer.parseInt(rs.getString(5))); book.setbCourse(rs.getString(6)); } return book; } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public void editBook(BookPojo book) throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("update books set name=?, author=?, price=?, quantity=?, course=? where id=?"); ps.setInt(6, book.getbId()); ps.setString(1, book.getbName()); ps.setString(2, book.getbAuthor()); ps.setInt(3, book.getbPrice()); ps.setInt(4, book.getbQuantity()); ps.setString(5, book.getbCourse()); ps.execute(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public void delete(int id) throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("delete from books where id="+id); ps.execute(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public BookPojo purchase(int id, int quantity) throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("select * from books where id=?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); BookPojo book = new BookPojo(); rs.next(); book.setbId(Integer.parseInt(rs.getString(1))); book.setbName(rs.getString(2)); book.setbAuthor(rs.getString(3)); book.setbPrice(Integer.parseInt(rs.getString(4))); book.setbQuantity(Integer.parseInt(rs.getString(5))); if(book.getbQuantity() < quantity) book.setbId(0); book.setbCourse(rs.getString(6)); return book; } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public void purchaseConfirm(int id, int quantity) throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("update books set quantity =? where id=?"); ps.setInt(2, id); ps.setInt(1, quantity); ps.execute(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public ArrayList<BookPojo> search(String type, String value) throws Exception{ Connection con = null; try { con = SQLConnection.connect(); PreparedStatement ps = null; ArrayList<BookPojo> books = new ArrayList<>(); if(type.equals("id")) { ps = con.prepareStatement("select * from books where id=?"); ps.setString(1, value); } else if(type.equals("title")) { ps = con.prepareStatement("select * from books where name=?"); ps.setString(1, value); } else if(type.equals("author")) { ps = con.prepareStatement("select * from books where author=?"); ps.setString(1, value); } else if(type.equals("price")) { ps = con.prepareStatement("select * from books where price=?"); ps.setString(1, value); } else if(type.equals("quantity")) { ps = con.prepareStatement("select * from books where quantity=?"); ps.setString(1, value); } else if(type.equals("courses")) { ps = con.prepareStatement("select * from books where course=?"); ps.setString(1, value); } ResultSet rs = ps.executeQuery(); while(rs.next()) { BookPojo book = new BookPojo(); book.setbId(rs.getInt(1)); book.setbName(rs.getString(2)); book.setbAuthor(rs.getString(3)); book.setbPrice(rs.getInt(4)); book.setbQuantity(rs.getInt(5)); book.setbCourse(rs.getString(6)); books.add(book); } return books; } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } public ArrayList <BookPojo> allBooks() throws Exception{ Connection con = null; try { ArrayList <BookPojo> list = new ArrayList<>(); con = SQLConnection.connect(); PreparedStatement ps = con.prepareStatement("select * from books"); ResultSet rs = ps.executeQuery(); while(rs.next()) { BookPojo book = new BookPojo(); book.setbId(Integer.parseInt(rs.getString(1))); book.setbName(rs.getString(2)); book.setbAuthor(rs.getString(3)); book.setbPrice(Integer.parseInt(rs.getString(4))); book.setbQuantity(Integer.parseInt(rs.getString(5))); book.setbCourse(rs.getString(6)); list.add(book); } return list; } catch (Exception e) { e.printStackTrace(); throw e; } finally { con.close(); } } }
true
793f7e54bebfc756a972b01769e23cfe0e4963de
Java
fisher377164/spring-angular-calculator
/src/main/java/com/techmix/fisher/exeptions/DivisionZeroException.java
UTF-8
348
2.03125
2
[]
no_license
package com.techmix.fisher.exeptions; import org.springframework.http.HttpStatus; /** * @author fisher * @since 4/8/16 */ public class DivisionZeroException extends BaseException { private static final HttpStatus status = HttpStatus.BAD_REQUEST; public DivisionZeroException(String message) { super(status, message); } }
true
ab8edbeeb38e0524a67094e0349c7b93f5f5e6d8
Java
snnynhr/stockprediction
/new_src/ark-sage/src/edu/cmu/cs/ark/sage/effects/IntegerEffect.java
UTF-8
2,197
3.34375
3
[]
no_license
package edu.cmu.cs.ark.sage.effects; /** * This is an implementation of a SAGE {@link Effect} that is indexed by an <code>int</code> <code>id</code>. * * @author Yanchuan Sim * @version 0.1 */ public class IntegerEffect extends Effect { private final int id; /** * Construct a fixed {@link IntegerEffect} object with <code>id</code>. * * @param id * the <code>id</code> of this effect. */ public IntegerEffect(int id) { super(); this.id = id; } /** * Construct a non-fixed {@link IntegerEffect} object with <code>id</code> and L1 regularization. * * @param id * the <code>id</code> of this effect. * @param l1regularizer * L1 regularization weight. */ public IntegerEffect(int id, double l1regularizer) { super(l1regularizer); this.id = id; } /** * Construct a non-fixed {@link IntegerEffect} object with <code>id</code>, L1 and L2 regularization. * * @param id * the <code>id</code> of this effect. * @param l1regularizer * L1 regularization weight. * @param l2regularizer * L2 regularization weight. */ public IntegerEffect(int id, double l1regularizer, double l2regularizer) { super(l1regularizer, l2regularizer); this.id = id; } /* * (non-Javadoc) * @see edu.cmu.cs.ark.sage.effects.Effect#getDescription() */ @Override public String getDescription() { return Integer.toString(id); } /** * Hash code for this function is essentially just its <code>id</code>. * * @see Object#hashCode() */ @Override public int hashCode() { return id; } /** * Compares the <code>id</code> value of two {@link IntegerEffect}s for equality. * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; IntegerEffect other = (IntegerEffect) obj; if (id != other.id) return false; return true; } }
true
db25f9ac1f420f2ea6b61f6dc1aded435a292003
Java
atafs/BackEnd_JavaSE_PCD
/LinguagemJAVA_super/src/control_1Logica/OperadorInstanceOf.java
UTF-8
967
4.03125
4
[]
no_license
package control_1Logica; /** Apresentar conceitos de Variaveis @autor Americo Tomas */ public class OperadorInstanceOf { //método main: public static void main (String[] args) { int x = 6; x %= 3; //x = x + 3; -=, +=, /=, *=; System.out.println(x); //x == 6 : true; // = atribuicao; == comparacao //boolean true false; System.out.println(!(x == 6)); //so consigo comparar tipos semelhantes System.out.println(x != 7); System.out.println(x > 5); System.out.println((x >= 1) || (x <= 5)); System.out.println(); //paragrafo //instanceof compara tipos de dados (valido para objectos) Integer y = 6; System.out.println(y instanceof Integer); //class Wrapper System.out.println("Ola" instanceof String); } } /* Operadores de comparacao Java Operador logicos: && e; || ou, ! negacao; ou basta uma verdadeira; && tem que ser os dois verdadeiros; operdaores de atribuicao +=, -=, Operadores especiais: */
true
f0e2730d7324e9ba0a27855521a886ebcb749cd8
Java
KenAyotte/Comp830-Exam
/Question6/Observer/WorkManager.java
UTF-8
502
3.09375
3
[]
no_license
import java.util.ArrayList; import java.util.List; public class WorkManager { private List<Worker> workers = new ArrayList<Worker>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyAllObservers(); } public void attach(Worker worker){ worker.add(worker); } public void notifyAllObservers(){ for (Worker worker : worker) { worker.update(); } } }
true
c67e0958570673d8ae74cc51a20b02a88198c558
Java
blue19demon/spring-cloud
/spring-cloud/user-web/user-web/src/main/java/com/zimadai/userweb/controller/PageController.java
UTF-8
870
2.140625
2
[]
no_license
package com.zimadai.userweb.controller; import java.math.BigDecimal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import com.zimadai.userweb.feign.MovieFeign; import com.zimadai.userweb.feign.UserFeign; @Controller public class PageController { //编译器报错,无视。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。 @Autowired private UserFeign userFeign; @Autowired private MovieFeign movieFeign; @GetMapping("/index") public String index() { userFeign.addUser("张三", "123456", "18402850503"); return "index"; } @GetMapping("/movieIndex") public String movieIndex() { movieFeign.addMovie("卧虎藏龙",new BigDecimal(11.2)); return "movieIndex"; } }
true
ad8876db414718c53cff30c607459b8ecdf90afa
Java
KevinGitonga/mmarauinfo
/app/src/main/java/ke/co/ipandasoft/mmaraumobileinfo/SingleInfo.java
UTF-8
4,583
1.929688
2
[]
no_license
package ke.co.ipandasoft.mmaraumobileinfo; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Typeface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Html; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import ke.co.ipandasoft.mmaraumobileinfo.config.Config; public class SingleInfo extends AppCompatActivity { private String text_info; private Typeface montserrat_regular; private Typeface montserrat_semiBold; private Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_info); toolbar = findViewById(R.id.toolbar_article); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); floatingButton(); assetManager(); receiveFromDataAdapter(montserrat_regular, montserrat_semiBold); } private void assetManager() { AssetManager assetManager = this.getApplicationContext().getAssets(); montserrat_regular = Typeface.createFromAsset(assetManager, "fonts/Montserrat-Regular.ttf"); montserrat_semiBold = Typeface.createFromAsset(assetManager, "fonts/Montserrat-SemiBold.ttf"); } private void receiveFromDataAdapter(Typeface montserrat_regular, Typeface montserrat_semiBold) { String eventTitle=getIntent().getStringExtra(Config.INTENT_CONTENT_TITLE); String eventDescription=getIntent().getStringExtra(Config.INTENT_CONTENT_DESCRIPTION); String eventImage=getIntent().getStringExtra(Config.INTENT_CONTENT_IMAGE_URL); String eventStart=getIntent().getStringExtra(Config.INTENT_CONTENT_START_DATE); String eventEnd=getIntent().getStringExtra(Config.INTENT_CONTENT_END_DATE); Log.e("data_from_intent",eventTitle+" " + eventDescription); text_info=eventTitle+"\n"+eventDescription; TextView content_title; content_title = (TextView) findViewById(R.id.item_title); content_title.setText(eventTitle); content_title.setTypeface(montserrat_semiBold); getSupportActionBar().setTitle(eventTitle); TextView content_Description = findViewById(R.id.item_description); content_Description.setText(eventDescription); content_Description.setTypeface(montserrat_regular); TextView content_start_date = findViewById(R.id.item_start_date); String appendStartData="Start:"; content_start_date.setText(appendStartData+eventStart); content_start_date.setTypeface(montserrat_regular); TextView content_end_date = findViewById(R.id.item_end_date); String appendEndData="End:"; content_end_date.setText(appendEndData+eventEnd); content_end_date.setTypeface(montserrat_regular); ImageView collapsingImage = findViewById(R.id.collapsingImage); String imageLogoPath= Config.EVENT_IMAGE_ROOT_URL+ eventImage; String url = Html.fromHtml(imageLogoPath).toString(); Picasso.with(this).load(url).placeholder(R.drawable.image_placeholder).into(collapsingImage); } private void floatingButton() { FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, "Check out this Info! Shared from Mmarau Mobile Info App\n"+text_info); startActivity(Intent.createChooser(shareIntent, "Share with")); } }); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { /* * Override the Up/Home Button * */ case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed(){ super.onBackPressed(); overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right); } }
true
df7b4174e405d31638b98d4d909a4809f9c34e1c
Java
felipecesargomes/PROJETO-POSWEB-T52020-FELIPE-CESAR-GOMES
/src/main/java/dev/fujioka/felipe/projetoJava/rest/ConsultasResource.java
UTF-8
3,984
2.28125
2
[ "MIT" ]
permissive
package dev.fujioka.felipe.projetoJava.rest; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import dev.fujioka.felipe.projetoJava.domain.*; import dev.fujioka.felipe.projetoJava.service.*; /** * @author felipecesar * */ @Controller @RequestMapping("/consultas") public class ConsultasResource { @Autowired private ConsultasService consultasService; @Autowired private PacienteService pacienteService; @Autowired private NutricionistaService nutricionistaService; //-------------------------------------LISTAGEM------------------------------------- @GetMapping("/listar") public String getConsultasList(ModelMap model) { model.addAttribute("consultas", consultasService.findAll()); return "/consultas/listar"; } //---------------------------------------------------------------------------------- //-------------------------------------CADASTRO------------------------------------- @GetMapping("/cadastrar") public String cadastrar(Consultas consultas) { return "/consultas/cadastrar"; } @PostMapping("/salvar") public String save(@Valid Consultas consultas, BindingResult result, RedirectAttributes pact, Model model) { if (result.hasErrors()) { model.addAttribute("fail", "Não foi possível cadastrar, verifique os dados novamente!"); return "consultas/cadastrar"; } else { consultasService.save(consultas); pact.addFlashAttribute("success", "Consulta inserida com sucesso."); return "redirect:/consultas/cadastrar"; } } //---------------------------------------------------------------------------------- //--------------------------------------UPDATE-------------------------------------- @GetMapping("/edit/{id}") public String showUpdateForm(@PathVariable("id") long id, Model model) { Consultas consultas = consultasService.findById(id) .orElseThrow(() -> new IllegalArgumentException("Invalid Consultas Id:" + id)); model.addAttribute("consultas", consultas); return "consultas/editar"; } @PostMapping("/update/{id}") public String updateConsultas(@PathVariable("id") long id, @Valid Consultas consultas, BindingResult result, Model model, RedirectAttributes pact) { if (result.hasErrors()) { consultas.setId(id); model.addAttribute("fail", "Consulta não editada."); return "consultas/editar"; } consultasService.save(consultas); pact.addFlashAttribute("success", "Consulta editada com sucesso."); model.addAttribute("pac", consultasService.findAll()); return "redirect:/consultas/listar"; } //---------------------------------------------------------------------------------- //--------------------------------------DELETE-------------------------------------- @GetMapping("/delete/{id}") public String excluir(@PathVariable("id") Long id, RedirectAttributes pact) { consultasService.deleteById(id); pact.addFlashAttribute("success", "Consulta excluída com sucesso."); return "redirect:/consultas/listar"; } //---------------------------------------------------------------------------------- //----------------------------------MODELATTRIBUTE---------------------------------- @ModelAttribute("paciente") public List<Paciente> listaDePaciente() { return pacienteService.findAll(); } @ModelAttribute("nutricionista") public List<Nutricionista> listaDeNutricionista() { return nutricionistaService.findAll(); } }
true
df3f0798d5ba1c91471bec3fc357438a60fe9264
Java
thabitaaroeira/marvel-rest-client-api
/marvel-client/src/main/java/br/com/thabita/controllers/CharacterController.java
UTF-8
2,886
2.53125
3
[]
no_license
package br.com.thabita.controllers; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import br.com.thabita.business.CharacterBusiness; import br.com.thabita.model.Character; import br.com.thabita.model.constants.Parametro; @Component @Path("/characters") @Produces(MediaType.APPLICATION_JSON) public class CharacterController { private static final int DEFAULT_LIMIT = 10; private static Logger logger = LogManager.getLogger(CharacterController.class); @Autowired private CharacterBusiness business; @Path("{id}") @GET public Character get(@PathParam("id") int id) { Character character = business.read(id); logger.debug("> get/" + id + " = " + character); return character; } @GET public List<Character> getAll(@QueryParam("name") String name, @QueryParam("nameStartsWith") String nameStartsWith, @QueryParam("orderBy") String orderBy) { Map<String, Object> params = createParameters(name, nameStartsWith, orderBy); logger.debug("> getAll params = " + params.toString()); List<Character> characters = business.getAll(params); logger.debug("> getAll result = " + characters.toString()); return characters; } public Map<String, Object> createParameters(String nome, String nameStartsWith, String orderBy) { Map<String, Object> params = new HashMap<String, Object>(); if (nome != null) { params.put(Parametro.NAME.getName(), nome); } if (nameStartsWith != null) { params.put(Parametro.NAME_STARTS_WITH.getName(), nameStartsWith); } if (orderBy != null) { params.put(Parametro.ORDER_BY.getName(), orderBy); } params.put(Parametro.LIMIT.getName(), DEFAULT_LIMIT); return params; } @POST @Consumes(MediaType.APPLICATION_JSON) public Character add(Character character) { character = business.create(character); logger.debug("> add/ = " + character); return character; } @DELETE @Path("{id}") public Response remove(@PathParam("id") int id) { business.delete(id); logger.debug("> remove/ = " + id); return Response.ok().build(); } @PUT @Path("{id}") @Consumes(MediaType.APPLICATION_JSON) public Character update(@PathParam("id") int id, Character character) { logger.debug("> update/ = " + id); character = business.update(character); return character; } }
true
91dbaeaba74647dbedb08b36ebdc9af475db0432
Java
fazoolmail89/gopawpaw
/Capricornus/src/com/gopawpaw/erp/hibernate/c/CclsMstr.java
UTF-8
828
1.710938
2
[]
no_license
package com.gopawpaw.erp.hibernate.c; import java.util.Date; /** * CclsMstr entity. @author MyEclipse Persistence Tools */ public class CclsMstr extends AbstractCclsMstr implements java.io.Serializable { // Constructors /** default constructor */ public CclsMstr() { } /** full constructor */ public CclsMstr(CclsMstrId id, Boolean cclsEditLcShipper, Boolean cclsCcInvoice, Boolean cclsLcInvoice, Boolean cclsCcAsn, Boolean cclsLcAsn, String cclsChargeType, String cclsModUserid, Date cclsModDate, String cclsUserc01, String cclsUserc02, String cclsQadc01, String cclsQadc02, Double oidCclsMstr) { super(id, cclsEditLcShipper, cclsCcInvoice, cclsLcInvoice, cclsCcAsn, cclsLcAsn, cclsChargeType, cclsModUserid, cclsModDate, cclsUserc01, cclsUserc02, cclsQadc01, cclsQadc02, oidCclsMstr); } }
true
2b6a887b16a59f31fd78c9b2284cf11f03f773a9
Java
MayurSolanki/BackgroundLocationTrigger
/app/src/main/java/com/locationtrigger/LocationAdapter.java
UTF-8
2,330
2.109375
2
[]
no_license
package com.locationtrigger; import android.content.Context; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import java.util.List; import java.util.Locale; /** * Created by nikunj on 21/11/17. */ class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder> { private List<LocationModel> locationList; Context context; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView mLatitudeTextView; public TextView mLongitudeTextView; public TextView mLastUpdateTimeTextView; public MyViewHolder(View view) { super(view); mLatitudeTextView = (TextView) view.findViewById(R.id.latitude_text); mLongitudeTextView = (TextView) view.findViewById(R.id.longitude_text); mLastUpdateTimeTextView = (TextView) view.findViewById(R.id.last_update_time_text); } } public LocationAdapter(List<LocationModel> categoryList, Context context) { this.locationList = categoryList; this.context = context; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_location, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(final MyViewHolder holder, final int position) { LocationModel locationModel = locationList.get(position); holder.mLatitudeTextView.setText("Lat : " +locationModel.getLocation().getLatitude()); holder.mLongitudeTextView.setText("Lon : " +locationModel.getLocation().getLongitude()); holder.mLongitudeTextView.setText("Time : " +locationModel.getmLocationUpdateTime()); } @Override public int getItemCount() { return locationList.size(); } public void updateItems(List<LocationModel> newItems) { // locationList.clear(); locationList.addAll(newItems); // notifyDataSetChanged(); } }
true
a7c8cde1c5f6c651c6654b6e8f9fed61f413a693
Java
leenapark/mysite5
/src/main/java/com/javaex/service/GalleryService.java
UTF-8
2,836
2.46875
2
[]
no_license
package com.javaex.service; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.javaex.dao.GalleryDao; import com.javaex.vo.GalleryVo; @Service public class GalleryService { @Autowired private GalleryDao galleryDao; // 갤러리 리스트 출력: 저장된 이미지 불러오기 public List<GalleryVo> imageList() { System.out.println("GalleryService imageList"); return galleryDao.galleryList(); } public String restore(MultipartFile file, GalleryVo galleryVo) { System.out.println("GalleryService: " + file.getOriginalFilename()); // db 저장할 정보 수집 String saveDir = "C:\\javaStudy\\upload"; // 오리지널 파일이름 String orgName = file.getOriginalFilename(); System.out.println("orgName: " + orgName); // 파일 확장자 String exName = orgName.substring(orgName.lastIndexOf(".")); System.out.println("exName: " + exName); // 서버 저장 파일 이름 숫자 + 알 수 없는 문자열 String saveName = System.currentTimeMillis()+UUID.randomUUID().toString() + exName; System.out.println("saveName: " + saveName); // 서버 파일 패스 --> 저장 경로 String filePath = saveDir + "\\" + saveName; System.out.println("filePath: " + filePath); // 파일 사이즈 long fileSize = file.getSize(); System.out.println("fileSize: " + fileSize); // 서버 하드 디스크 저장 try { byte[] fileData = file.getBytes(); OutputStream out = new FileOutputStream(filePath); BufferedOutputStream bos = new BufferedOutputStream(out); bos.write(fileData); bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // db 저장 //Map<String, Object> map = new HashMap<String, Object>(); //map.put("", value); galleryVo.setFilePath(filePath); galleryVo.setFileSize(fileSize); galleryVo.setOrgName(orgName); galleryVo.setSaveName(saveName); System.out.println("GalleryService: " + galleryVo); galleryDao.insert(galleryVo); return saveName; } // 데이터 하나 가져오기 public GalleryVo selectOne(String savaName) { System.out.println("GalleryService: " + savaName); return galleryDao.selectOne(savaName); } // 데이터 삭제 public int remove(int no) { System.out.println("GalleryService remove"); return galleryDao.delete(no); } }
true
12612d86adaa9ed549e74262ef26d1793683e391
Java
JacobPooleCV/SuperAP_21-22
/2015_ABCD/34. ExtraStuff/Nick Fish/NickFish Code/MBSGUI.java
UTF-8
4,246
2.890625
3
[]
no_license
// AP(r) Computer Science Marine Biology Simulation: // The MBSGUI class is copyright(c) 2002 College Entrance // Examination Board (www.collegeboard.com). // // This class is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation. // // This class is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** * AP&reg; Computer Science Marine Biology Simulation:<br> * The <code>MBSGUI</code> class provides a main method for a version * of the AP Computer Science Marine Biology Simulation with a graphical * user interface. * * <p> * This class will NOT be tested on the Advanced Placement exam. * * <p> * The <code>MBSGUI</code> class is * copyright&copy; 2002 College Entrance Examination Board * (www.collegeboard.com). * * @author Alyce Brady * @author Chris Nevison * @author Julie Zelenski * @version 1 July 2002 * @see DisplayMap * @see MBSGUIFrame **/ public class MBSGUI { /** Start the Marine Biology Simulation program. * The String arguments (args) are not used in this application. **/ public static void main(String[] args) { // Specify which fish classes are available. This array is used // to provide a choice of fish classes in the pull-down menu when // manually placing objects into the environment. String[] fishClassNames = {"nuFish", "Fish", "DarterFish", "SlowFish", "NervousFish"}; // FOR CHAPTER 4, use the following instead: // String[] fishClassNames = {"Fish", "DarterFish", "SlowFish"}; // As you create new subclasses of the Fish class, add the class // names to the list. // Specify classes that know how to draw various environment objects; // in other words, map environment object classes (like Fish) to // display objects (like the FishDisplay object). DisplayMap.associate("Fish", new FishDisplay()); DisplayMap.associate("nuFish", new FishImageDisplay("nuFish.gif", Direction.EAST)); DisplayMap.associate("deadFish", new FishImageDisplay("deadFish.gif", Direction.EAST)); // Use lines like the following to give different fish // different shapes. You can use images for any of the fish // classes, as in the SlowFish example below. // DisplayMap.associate("Fish", new RoundFishDisplay()); // DisplayMap.associate("DarterFish", new LittleFishDisplay()); // DisplayMap.associate("SlowFish", // new FishImageDisplay("smallfish.gif", // Direction.EAST)); // Display classes available in mbsgui.jar include FishDisplay, // LittleFishDisplay, NarrowFishDisplay, RoundFishDisplay, and // FishImageDisplay. One gif file is provided: smallfish.gif. // The constructor for FishImageDisplay takes two parameters: the // name of the image file and the direction the fish in the image // is facing. // Determine what classes are available for representing bounded // and unbounded environments. String[] boundedClassNames = {"BoundedEnv"}; String[] unboundedClassNames = {"UnboundedEnv"}; // FOR CHAPTER 5, use something like the following instead: // String[] boundedClassNames = {"BoundedEnv", "VLBoundedEnv"}; // String[] unboundedClassNames = {"UnboundedEnv", "SLUnboundedEnv"}; // Inform the factory object of the classes being used in this program // so it can construct instances of those classes when environments // are read or created. MBSFactory.addEnvObjClassNames(fishClassNames); MBSFactory.addBoundedEnvClassNames(boundedClassNames); MBSFactory.addUnboundedEnvClassNames(unboundedClassNames); // Create and show the window containing the graphical user interface MBSGUIFrame guiFrame = new MBSGUIFrame(); guiFrame.setVisible(true); } }
true
8fa1a700b0c49c7b85ae5604c363b5fc0262dacb
Java
mttoksoy/project
/src/main/java/restApi/UserController.java
UTF-8
2,893
2.40625
2
[]
no_license
package restApi; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import Entity.Users; import SercurityJWT.JwtUtil; import Services.MyUserDetailsService; import Services.UserService; import model.AuthenticationRequest; import model.AuthenticationResponse; /* Ben bu proje içerisinde kendi yazdığım sorguları controller'a adapte ettim * ancak PagingSortingRepository ögesini içeren sınıfı da yazdım istenirse ordan * hazır sınıflar alınabilir. Daha iyi sonuçlar elde edilebilir. */ @Controller public class UserController { @Autowired private AuthenticationManager authenticationManager; private UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @Autowired private MyUserDetailsService userDetailsService; @Autowired private JwtUtil jwtUtil; private static Logger log = Logger.getLogger(UserController.class); @GetMapping("/add") public void add(@RequestBody Users user) { userService.add(user); } @GetMapping("/update") public void update(@RequestBody Users user) { userService.update(user); } @GetMapping("/delete") public void delete(@RequestBody Users user) { userService.delete(user); } @GetMapping("/getById/{id}") public Users getByUser(@PathVariable int id) { return userService.getById(id); } @RequestMapping({"/hello"}) public String hello(){ return "Hello World"; } @RequestMapping(value = "/authenticate", method = RequestMethod.POST) public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) throws Exception{ try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())); } catch (BadCredentialsException e) { throw new Exception("Yanlış kullanıcı adı veya parolar",e); } final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String jwt=jwtUtil.generateToken(userDetails); return ResponseEntity.ok(new AuthenticationResponse(jwt)); } }
true
0dbc78dfdc6cf4028160fb2a15ab42c0382b3fa4
Java
ali-sh1985/Appointment-Management-System
/src/main/java/com/cs4/appointmentManagement/jms/AppointmentJmsSender.java
UTF-8
914
2.359375
2
[]
no_license
package com.cs4.appointmentManagement.jms; import java.io.Serializable; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Component; @Component(value="appointmentJmsSender") public class AppointmentJmsSender implements MessageSender { @Autowired @Qualifier("jmsTemplateAppointment") private JmsTemplate jmsTemplateAppointment; @Override public void sendMessage(Object object) { this.jmsTemplateAppointment.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createObjectMessage((Serializable) object); } }); } }
true
5575653e0c92e68a95c7313f63dbc53ac3d1fffc
Java
DalavanCloud/isis
/core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/swagger/SwaggerServiceDefault.java
UTF-8
2,798
1.679688
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.metamodel.services.swagger; import java.util.Map; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.services.swagger.SwaggerService; import org.apache.isis.core.metamodel.services.swagger.internal.SwaggerSpecGenerator; import org.apache.isis.core.metamodel.specloader.SpecificationLoader; @DomainService( nature = NatureOfService.DOMAIN, menuOrder = "" + Integer.MAX_VALUE ) public class SwaggerServiceDefault implements SwaggerService { @SuppressWarnings("unused") private final static Logger LOG = LoggerFactory.getLogger(SwaggerServiceDefault.class); public static final String KEY_RESTFUL_BASE_PATH = "isis.services.swagger.restfulBasePath"; public static final String KEY_RESTFUL_BASE_PATH_DEFAULT = "/restful"; private String basePath; @PostConstruct public void init(final Map<String,String> properties) { this.basePath = getPropertyElse(properties, KEY_RESTFUL_BASE_PATH, KEY_RESTFUL_BASE_PATH_DEFAULT); } static String getPropertyElse(final Map<String, String> properties, final String key, final String dflt) { String basePath = properties.get(key); if(basePath == null) { basePath = dflt; } return basePath; } @Programmatic @Override public String generateSwaggerSpec( final Visibility visibility, final Format format) { final SwaggerSpecGenerator swaggerSpecGenerator = new SwaggerSpecGenerator(specificationLoader); final String swaggerSpec = swaggerSpecGenerator.generate(basePath, visibility, format); return swaggerSpec; } @javax.inject.Inject SpecificationLoader specificationLoader; }
true
49db2e729f29bf5d6ec474ef4e11a5526829d01b
Java
qiankeqin/dubbo-mao
/guns-gateway/src/main/java/com/stylefeng/guns/rest/modular/vo/ResponseVO.java
UTF-8
2,094
2.453125
2
[ "Apache-2.0" ]
permissive
package com.stylefeng.guns.rest.modular.vo; /** * @author qiankeqin * @Description: DESCRIPTION * @date 2019-03-18 20:31 */ public class ResponseVO<M> { /** * 返回状态 * 0成功,1失败,999系统异常 */ private int status; /** * 返回信息 */ private String msg; /** * 返回实体数据 */ private M data; private String imgPre; private ResponseVO() { } public static<M> ResponseVO success(String imgPre,M m){ ResponseVO responseVO = new ResponseVO(); responseVO.setStatus(0); responseVO.setImgPre(imgPre); responseVO.setMsg("成功"); responseVO.setData(m); return responseVO; } public static<M> ResponseVO success(M m){ ResponseVO responseVO = new ResponseVO(); responseVO.setStatus(0); responseVO.setMsg("成功"); responseVO.setData(m); return responseVO; } public static<M> ResponseVO success(String msg){ ResponseVO responseVO = new ResponseVO(); responseVO.setStatus(0); responseVO.setMsg(msg); return responseVO; } public static<M> ResponseVO serviceFail(String msg){ ResponseVO responseVO = new ResponseVO(); responseVO.setStatus(1); responseVO.setMsg(msg); return responseVO; } public static<M> ResponseVO appFail(String msg){ ResponseVO responseVO = new ResponseVO(); responseVO.setStatus(999); responseVO.setMsg(msg); return responseVO; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public M getData() { return data; } public void setData(M data) { this.data = data; } public String getImgPre() { return imgPre; } public void setImgPre(String imgPre) { this.imgPre = imgPre; } }
true
49fbaf50cefecc4a31492352706f571ecf134730
Java
Robinak47/It-centre-Management-sytem
/project/frames/ForgetFrame.java
UTF-8
2,787
2.5625
3
[]
no_license
package frames; import java.lang.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import repository.*; import entity.*; public class ForgetFrame extends JFrame implements ActionListener { private JLabel answerLabel, npasswordLabel,idLabel; private JPasswordField npasswordfild; private JTextField idfield,answerfield; private JButton backBtn, submitBtn; private JPanel panel; SecurityRepo pe=new SecurityRepo(); public ForgetFrame() { super("ForgetFrame"); this.setSize(800,450); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new JPanel(); panel.setLayout(null); idLabel = new JLabel("id: "); idLabel.setBounds(200, 40, 160, 30); panel.add(idLabel); idfield = new JTextField(); idfield.setBounds(310, 40, 150, 30); panel.add(idfield); answerLabel = new JLabel("gf/bf name:"); answerLabel.setBounds(200, 100, 160, 30); panel.add(answerLabel); answerfield = new JTextField(); answerfield.setBounds(310, 100, 150, 30); panel.add(answerfield); npasswordLabel = new JLabel("New Password: "); npasswordLabel.setBounds(200, 140, 160, 30); panel.add(npasswordLabel); npasswordfild = new JPasswordField(); npasswordfild.setBounds(310, 140, 150, 30); panel.add(npasswordfild); submitBtn= new JButton("Submit"); submitBtn.setBounds(420, 200, 100, 30); submitBtn.addActionListener(this); panel.add(submitBtn); backBtn= new JButton("Back"); backBtn.setBounds(300, 300, 100, 30); backBtn.addActionListener(this); panel.add(backBtn); this.add(panel); } public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); if(command.equals(submitBtn.getText())) { User me=new User(); UserRepo ur = new UserRepo(); Security security = pe.getSecurity(idfield.getText(),answerfield.getText()); if(security != null) { try{ me.setUserId(idfield.getText()); me.setStatus(1); me.setPassword(npasswordfild.getText()); ur.updatePassword(me); JOptionPane.showMessageDialog(this, "Updated"); } catch(Exception ro) { JOptionPane.showMessageDialog(this, "operation halted"); ro.printStackTrace(); } LoginFrame e = new LoginFrame(); e.setVisible(true); this.setVisible(false); } else { JOptionPane.showMessageDialog(this, "Invaild ans"); } } else if(command.equals(backBtn.getText())) { LoginFrame pw = new LoginFrame(); pw.setVisible(true); this.setVisible(false); } } }
true
28280e4153226fd8db7af6c932d1ecebfa51f234
Java
toughie88/Machine-Learning-for-Malware-Data-Analysis
/WuKong/com/adobe/reader/javascript/ARJavaScriptUtil.java
UTF-8
262
1.695313
2
[]
no_license
package com.adobe.reader.javascript; public class ARJavaScriptUtil { public ARJavaScriptUtil() {} public String printd() { return null; } public String printf() { return null; } public String printx() { return null; } }
true
b21dc4f0b10220cb7adda6e38ab680540ff0776b
Java
ArekOsiecki/OOP_Project
/DivingCalculator/src/DivingCalculator/src/RdpFrame.java
UTF-8
14,458
2.6875
3
[]
no_license
import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; public class RdpFrame extends JFrame implements ActionListener { JFrame rdpFrame; JMenuBar guiMenuBar = new JMenuBar(); JMenu diveMenu = new JMenu("Dive Menu"); JMenuItem createProfile = new JMenuItem("Create Profile"); JMenuItem planDive = new JMenuItem("Plan dive"); JMenuItem showDiveLog = new JMenuItem("Show dive log"); //declaration of menu, menu bar and items JTextArea logArea, RDPArea; //Text areas public static void main(String[] args) { new RdpFrame(); } public RdpFrame() { rdpFrame = new JFrame("Plan second dive"); rdpFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//Setting exit method diveMenu.add(createProfile); createProfile.addActionListener(this);//adding items to menus and registering listeners diveMenu.add(planDive); planDive.addActionListener(this); diveMenu.add(showDiveLog); showDiveLog.addActionListener(this); guiMenuBar.add(diveMenu); //adding menus to bar GridLayout diveFrameLayout = new GridLayout(0, 1); rdpFrame.setLayout(diveFrameLayout); rdpFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JMenu diveGridMenu = new JMenu("Dive Menu"); diveGridMenu.setVisible(true); JTextField surfaceIntervalText = new JTextField(20);//Creating fields for user input and corresponding labels surfaceIntervalText.setBorder(BorderFactory.createTitledBorder("Where you plan to dive?")); JTextField nextDepthText = new JTextField(20); nextDepthText.setBorder(BorderFactory.createTitledBorder("When you plan to dive?")); JTextField nextLengthText = new JTextField(20); nextLengthText.setBorder(BorderFactory.createTitledBorder("Enter maximum planned depth in meters")); JPanel buttonsPanel = new JPanel(); buttonsPanel.setBorder(new EmptyBorder(15, 15, 15, 15)); GridLayout buttonsLayout = new GridLayout(0, 2, 25, 0); buttonsPanel.setLayout(buttonsLayout); JButton confirmButton = new JButton("Confirm"); JButton cancelButton = new JButton("Cancel"); rdpFrame.setJMenuBar(guiMenuBar);//adding components to layout buttonsPanel.add(confirmButton); buttonsPanel.add(cancelButton); rdpFrame.add(buttonsPanel); rdpFrame.setSize(400, 640); //adding menu bar to frame, setting visibility and size rdpFrame.setLocationRelativeTo(null); rdpFrame.setVisible(true); rdpFrame.setFocusable(true); } public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getSource() == createProfile) { try { new ProfileFrame(); } catch (IOException e) { e.printStackTrace(); } rdpFrame.dispose(); } if (actionEvent.getSource() == planDive) { try { new DiveFrame(); } catch (IOException e) { e.printStackTrace(); } rdpFrame.dispose(); } if (actionEvent.getSource() == showDiveLog) { try { new LogFrame(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } rdpFrame.dispose(); } } } /* *import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; public class RdpFrame extends JFrame implements ActionListener { JFrame rdpFrame; JMenuBar guiMenuBar = new JMenuBar(); JMenu diveMenu = new JMenu("Dive Menu"); JMenuItem createProfile = new JMenuItem("Create Profile"); JMenuItem planDive = new JMenuItem("Plan dive"); JMenuItem showDiveLog = new JMenuItem("Show dive log"); public static void main(String[] args) throws IOException, ClassNotFoundException { new RdpFrame(); } public RdpFrame() throws ClassNotFoundException, FileNotFoundException, IOException { rdpFrame = new JFrame("Plan second dive"); rdpFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//Setting exit method diveMenu.add(createProfile); createProfile.addActionListener(this);//adding items to menus and registering listeners diveMenu.add(planDive); planDive.addActionListener(this); diveMenu.add(showDiveLog); showDiveLog.addActionListener(this); guiMenuBar.add(diveMenu); //adding menus to bar GridLayout diveFrameLayout = new GridLayout(0, 1); rdpFrame.setLayout(diveFrameLayout); rdpFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JMenu diveGridMenu = new JMenu("Dive Menu"); diveGridMenu.setVisible(true); JTextField surfaceIntervalText = new JTextField(20);//Creating fields for user input and corresponding labels surfaceIntervalText.setBorder(BorderFactory.createTitledBorder("Where you plan to dive?")); JTextField nextDepthText = new JTextField(20); nextDepthText.setBorder(BorderFactory.createTitledBorder("When you plan to dive?")); JTextField nextLengthText = new JTextField(20); nextLengthText.setBorder(BorderFactory.createTitledBorder("Enter maximum planned depth in meters")); JPanel buttonsPanel = new JPanel(); buttonsPanel.setBorder(new EmptyBorder(15, 15, 15, 15)); GridLayout buttonsLayout = new GridLayout(0, 2, 25, 0); buttonsPanel.setLayout(buttonsLayout); JButton confirmButton = new JButton("Confirm"); JButton cancelButton = new JButton("Cancel"); rdpFrame.setJMenuBar(guiMenuBar); buttonsPanel.add(confirmButton); buttonsPanel.add(cancelButton); rdpFrame.add(buttonsPanel); //adding components to layout //adding menu bar to frame, setting visibility and size rdpFrame.setSize(400, 640); rdpFrame.setLocationRelativeTo(null); rdpFrame.setVisible(true); rdpFrame.setFocusable(true); File outFile = new File("objects.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); ObjectOutputStream outObjectStream = new ObjectOutputStream(outFileStream); confirmButton.addActionListener(e -> { boolean valid = false; try { while(!valid) { File inFile = new File("objects.data"); FileInputStream inFileStream = new FileInputStream(inFile); ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream); Dive dive = (Dive)inObjectStream.readObject(); Diver diver = dive.getDiver(); BreathingDevice bd =dive.getBreathingDevice(); if(bd.getSize()>8){ JOptionPane.showMessageDialog(rdpFrame,"You can dive again after completing post-dive and pre-dive procedures on surface"); }else { class GroupPressure { private HashMap<Integer,Integer[]> pressureGroup; { pressureGroup.put(0, new Integer[]{10, 9, 8, 7, 6, 5, 4, 3}); pressureGroup.put(1, new Integer[]{20, 17, 15, 13, 11, 10, 9, 8, 6, 5, 5}); pressureGroup.put(2, new Integer[]{25, 23, 19, 17, 15, 13, 12, 10, 8, 7, 6}); pressureGroup.put(3, new Integer[]{30, 26, 22, 19, 16, 15, 13, 11, 9, 8, 8}); pressureGroup.put(4, new Integer[]{34, 29, 24, 21, 18, 16, 15, 13, 10, 7, 7}); pressureGroup.put(5, new Integer[]{37, 32, 27, 23, 20, 18, 16, 14, 11, 9, 8}); pressureGroup.put(6, new Integer[]{41, 35, 29, 25, 22, 20, 18, 15, 12, 10}); pressureGroup.put(7, new Integer[]{45, 38, 32, 27, 24, 21, 19, 17, 13, 12}); pressureGroup.put(8, new Integer[]{50, 42, 35, 29, 26, 23, 21, 18, 14, 12}); pressureGroup.put(9, new Integer[]{54, 45, 37, 32, 28, 25, 22, 19, 15, 13}); pressureGroup.put(10, new Integer[]{59, 49, 40, 34, 30, 26, 24, 21, 16}); pressureGroup.put(11, new Integer[]{64, 53, 43, 37, 32, 28, 25, 22, 17}); pressureGroup.put(12, new Integer[]{70, 57, 47, 39, 34, 30, 27, 23, 19}); pressureGroup.put(13, new Integer[]{75, 62, 50, 42, 36, 32, 29, 25}); pressureGroup.put(14, new Integer[]{82, 66, 53, 45, 39, 34, 30, 26}); pressureGroup.put(15, new Integer[]{88, 71, 57, 48, 41, 36, 32, 28}); pressureGroup.put(16, new Integer[]{95, 76, 61, 50, 43, 38, 34}); pressureGroup.put(17, new Integer[]{104, 82, 64, 53, 46, 40, 36}); pressureGroup.put(18, new Integer[]{112, 88, 68, 56, 48, 42}); pressureGroup.put(19, new Integer[]{122, 94, 73, 60, 51, 44}); pressureGroup.put(20, new Integer[]{133, 101, 77, 63, 53}); pressureGroup.put(21, new Integer[]{145, 108, 82, 67, 55}); pressureGroup.put(22, new Integer[]{160, 116, 87, 70}); pressureGroup.put(23, new Integer[]{178, 125, 92}); pressureGroup.put(24, new Integer[]{199, 134}); Object[] keys = pressureGroup.keySet().toArray(); int lastDepth = dive.getDepth(); int lastLength = dive.getLength(); int pressureG = diver.getPressureGroup(); int diverExp = diver.getExperienceLevel(); DiveDriver.validateNumber(surfaceIntervalText.getText()); DiveDriver.validateNumber(nextDepthText.getText()); DiveDriver.validateNumber(nextLengthText.getText()); int nextDepth = DiveDriver.validateDepth(nextDepthText.getText()); DiveDriver.validateDepthAndExperience(nextDepth, diverExp); int nextLength = DiveDriver.validateDiveLength(nextDepth, nextLengthText.getText()); int surfaceInterval = Integer.parseInt(surfaceIntervalText.getText()); pressureGroup.get(keys[lastDepth]); String myKey = keys[lastDepth].toString(); pressureG+=Integer.parseInt(myKey); diver.setPressureGroup(pressureG); System.out.println(diver.toString()); } } /* public Integer indexOf(int length){ } } } public Object getElementByIndex(HashMap GroupPressure int depth){ return GroupPressure.get( (GroupPressure.keySet().toArray())[ depth ] ); } //JOptionPane.showMessageDialog(null,DiveDriver.nextSafeDive(lastDepth,lastLength)); } } } catch (RuntimeException | IOException | ClassNotFoundException f) { JOptionPane.showMessageDialog(rdpFrame, f.fillInStackTrace(), "Incorrect input!", JOptionPane.WARNING_MESSAGE); } } ); cancelButton.addActionListener(e -> { JOptionPane.showMessageDialog(rdpFrame, "Closing dive planner", "Canceled", JOptionPane.WARNING_MESSAGE); rdpFrame.setVisible(false);//disposing of current frame });//adding action listeners to buttons using lambda statements } public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getSource() == createProfile) { try { new ProfileFrame(); } catch (IOException e) { e.printStackTrace(); } rdpFrame.dispose(); } if (actionEvent.getSource() == planDive) { try { new DiveFrame(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } rdpFrame.dispose(); } if (actionEvent.getSource() == showDiveLog) { try { new LogFrame(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } rdpFrame.dispose(); } } } */
true
55e06d1eb7d744ab5f264b6d65969aaee506b826
Java
ncummons/Java-Fundamentals
/src/labs_examples/objects_classes_methods/labs/oop/A_inheritance/Animals.java
UTF-8
1,290
3.984375
4
[]
no_license
package labs_examples.objects_classes_methods.labs.oop.A_inheritance; public class Animals { private int NumLegs; private double length; private double speed; public void makeSound(){ System.out.println("Grrr... Says the animal."); } public void eatAndGrow(double amount){ System.out.println("Your animal has now eaten: " + amount + " units of food and grown proportionally."); setLength(this.length+(amount/10)); } public int getNumLegs() { return NumLegs; } public void setNumLegs(int numLegs) { NumLegs = numLegs; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getSpeed() { return speed; } public void setSpeed(double speed) { this.speed = speed; } @Override public String toString() { return "Animals{" + "NumLegs=" + NumLegs + ", length=" + length + ", speed=" + speed + '}'; } public Animals(int numLegs, double length, double speed) { NumLegs = numLegs; this.length = length; this.speed = speed; } public Animals() { } }
true
9bdcfd1c0654c6c581750e9155a3ff2fd6fc06b0
Java
xuxiangyunuaa/monitorServer
/src/main/java/org/nit/monitorserver/udpClient/udpClient.java
UTF-8
1,853
2.390625
2
[]
no_license
package org.nit.monitorserver.udpClient; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.datagram.DatagramSocket; import io.vertx.core.datagram.DatagramSocketOptions; public class udpClient { public int port; public String address; public int listenPort; public String listenAddress; public byte[] buffer; private final Vertx vertx = Vertx.vertx(); public void setPort(int port) { this.port=port; } public void setListenPort(int listenPort) { this.listenPort=listenPort; } public void setAddress(String address) { this.address=address; } public void setListenAddress(String listenAddress) { this.listenAddress=listenAddress; } public void setBuffer(byte[] buffer) { this.buffer=buffer; } public String send(){ DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions()); socket.send(Buffer.buffer(buffer),port,address,asyncResult->{ if(asyncResult.succeeded()){ return; } }); return "send failed!"; } // public byte[] ListenAcquisition(){ // DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions()); // // Future receive=Future.future(); // socket.ListenAcquisition(listenPort,listenAddress,asyncResult->{ // if(asyncResult.succeeded()){ // socket.handler(packet->{ // receive.complete(packet.data().getBytes()); //// byte[] result=packet.data().getBytes(); // return; // }); // } // }); // receive.setHandler(rece->{ // byte[] // }); // return "Faild!".getBytes(); // } }
true
40c795c453ab48c813c1828d06f9da5f24930fff
Java
gurjeet/sqlg
/sqlg-test/src/main/java/org/umlg/sqlg/test/schema/TestGlobalUniqueIndex.java
UTF-8
27,747
2.421875
2
[ "MIT" ]
permissive
package org.umlg.sqlg.test.schema; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Assert; import org.junit.Test; import org.umlg.sqlg.structure.*; import org.umlg.sqlg.structure.topology.*; import org.umlg.sqlg.test.BaseTest; import java.util.*; import static org.junit.Assert.fail; /** * Date: 2016/12/03 * Time: 9:08 PM */ public class TestGlobalUniqueIndex extends BaseTest { @Test public void testGlobalUniqueIndexAccrossMultipleVerticesAndEdges() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("name1", PropertyType.STRING); properties.put("name2", PropertyType.STRING); VertexLabel aVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("A", properties); Assert.assertTrue(aVertexLabel.isUncommitted()); properties.clear(); properties.put("name3", PropertyType.STRING); properties.put("name4", PropertyType.STRING); VertexLabel bVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("B", properties); Assert.assertTrue(bVertexLabel.isUncommitted()); properties.clear(); properties.put("name5", PropertyType.STRING); properties.put("name6", PropertyType.STRING); EdgeLabel edgeLabel = aVertexLabel.ensureEdgeLabelExist("ab", bVertexLabel, properties); Assert.assertTrue(edgeLabel.isUncommitted()); Set<PropertyColumn> globalUniqueIndexPRopertyColumns = new HashSet<>(); globalUniqueIndexPRopertyColumns.addAll(new HashSet<>(aVertexLabel.getProperties().values())); globalUniqueIndexPRopertyColumns.addAll(new HashSet<>(bVertexLabel.getProperties().values())); globalUniqueIndexPRopertyColumns.addAll(new HashSet<>(edgeLabel.getProperties().values())); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(globalUniqueIndexPRopertyColumns); this.sqlgGraph.tx().commit(); Assert.assertFalse(aVertexLabel.isUncommitted()); Assert.assertFalse(bVertexLabel.isUncommitted()); Assert.assertFalse(edgeLabel.isUncommitted()); Assert.assertEquals(1, this.sqlgGraph.getTopology().getGlobalUniqueIndexes().size()); Assert.assertEquals("globalUniqueIndex_0", this.sqlgGraph.getTopology().getGlobalUniqueIndexes().iterator().next().getName()); Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name1", "1", "name2", "2"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name3", "3", "name4", "4"); a1.addEdge("ab", b1, "name5", "5", "name6", "6"); this.sqlgGraph.tx().commit(); try { a1.addEdge("ab", b1, "name5", "5", "name6", "6"); fail("GlobalUniqueIndex should not allow this to happen"); } catch (Exception e) { //swallow this.sqlgGraph.tx().rollback(); } //This should pass a1.addEdge("ab", b1, "name5", "7", "name6", "8"); } @Test public void testTopologyGlobalUniqueIndexCache() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("namec", PropertyType.STRING); properties.put("namea", PropertyType.STRING); properties.put("nameb", PropertyType.STRING); this.sqlgGraph.getTopology().ensureVertexLabelExist("A", properties); @SuppressWarnings("OptionalGetWithoutIsPresent") Collection<PropertyColumn> propertyColumns = this.sqlgGraph.getTopology().getPublicSchema().getVertexLabel("A").get().getProperties().values(); Assert.assertTrue(propertyColumns.stream().allMatch(PropertyColumn::isUncommitted)); GlobalUniqueIndex globalUniqueIndex = this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<>(propertyColumns)); Assert.assertTrue(globalUniqueIndex.isUncommitted()); Assert.assertEquals(1, this.sqlgGraph.getTopology().getGlobalUniqueIndexes().size()); this.sqlgGraph.tx().commit(); Assert.assertEquals(1, this.sqlgGraph.getTopology().getGlobalUniqueIndexes().size()); Assert.assertFalse(propertyColumns.stream().allMatch(PropertyColumn::isUncommitted)); Assert.assertFalse(globalUniqueIndex.isUncommitted()); } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test public void testGlobalUniqueIndexOnVertex() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("namec", PropertyType.STRING); properties.put("namea", PropertyType.STRING); properties.put("nameb", PropertyType.STRING); this.sqlgGraph.getTopology().ensureVertexLabelExist("A", properties); @SuppressWarnings("OptionalGetWithoutIsPresent") Collection<PropertyColumn> propertyColumns = this.sqlgGraph.getTopology().getPublicSchema().getVertexLabel("A").get().getProperties().values(); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<>(propertyColumns)); this.sqlgGraph.tx().commit(); Schema globalUniqueIndexSchema = this.sqlgGraph.getTopology().getGlobalUniqueIndexSchema(); Optional<GlobalUniqueIndex> globalUniqueIndexOptional = globalUniqueIndexSchema.getGlobalUniqueIndex("A_namea_A_nameb_A_namec"); Assert.assertTrue(globalUniqueIndexOptional.isPresent()); Optional<PropertyColumn> nameaPropertyColumnOptional = this.sqlgGraph.getTopology().getPublicSchema().getVertexLabel("A").get().getProperty("namea"); Assert.assertTrue(nameaPropertyColumnOptional.isPresent()); @SuppressWarnings("OptionalGetWithoutIsPresent") Set<GlobalUniqueIndex> globalUniqueIndices = nameaPropertyColumnOptional.get().getGlobalUniqueIndices(); Assert.assertEquals(1, globalUniqueIndices.size()); GlobalUniqueIndex globalUniqueIndex = globalUniqueIndices.iterator().next(); Assert.assertEquals("A_namea_A_nameb_A_namec", globalUniqueIndex.getName()); Vertex a = this.sqlgGraph.addVertex(T.label, "A", "namea", "a"); this.sqlgGraph.tx().commit(); try { this.sqlgGraph.addVertex(T.label, "A", "namea", "a"); fail("GlobalUniqueIndex should prevent this from executing"); } catch (Exception e) { //swallow } this.sqlgGraph.tx().rollback(); Vertex aa = this.sqlgGraph.addVertex(T.label, "A", "namea", "aa"); this.sqlgGraph.tx().commit(); List<Vertex> globalUniqueIndexVertexes = this.sqlgGraph.globalUniqueIndexes().V().toList(); //This is 6 because all PropertyColumns with a GlobalUniqueIndex gets a value. If no value is present then a null is inserted as the value. //null do not partake in the unique constraint so all is well Assert.assertEquals(6, globalUniqueIndexVertexes.size()); Assert.assertTrue(globalUniqueIndexVertexes.stream().allMatch(g -> g.label().equals(Schema.GLOBAL_UNIQUE_INDEX_SCHEMA + "." + globalUniqueIndex.getName()))); Assert.assertEquals(1, globalUniqueIndexVertexes.stream().filter(g -> g.property(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_VALUE).isPresent() && g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_VALUE).equals("a")).count()); Assert.assertEquals(3, globalUniqueIndexVertexes.stream().filter(g -> g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_RECORD_ID).equals(a.id().toString())).count()); Assert.assertEquals(1, globalUniqueIndexVertexes.stream().filter(g -> g.property(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_VALUE).isPresent() && g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_VALUE).equals("aa")).count()); Assert.assertEquals(3, globalUniqueIndexVertexes.stream().filter(g -> g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_RECORD_ID).equals(aa.id().toString())).count()); } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test public void testGlobalIndexAcrossMultipleVertexLabels() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("a", PropertyType.STRING); VertexLabel aVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("A", properties); VertexLabel bVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("B", properties); Set<PropertyColumn> globalUniqueIndexProperties = new HashSet<>(); globalUniqueIndexProperties.add(aVertexLabel.getProperty("a").get()); globalUniqueIndexProperties.add(bVertexLabel.getProperty("a").get()); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(globalUniqueIndexProperties); this.sqlgGraph.tx().commit(); try { this.sqlgGraph.addVertex(T.label, "A", "a", "123"); this.sqlgGraph.tx().commit(); this.sqlgGraph.addVertex(T.label, "B", "a", "123"); fail("GlobalUniqueIndex should prevent this from happening"); } catch (Exception e) { //swallow } } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test public void testGlobalUniqueIndexOnEdge() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("name", PropertyType.STRING); VertexLabel vertexLabelA = this.sqlgGraph.getTopology().ensureVertexLabelExist("A", properties); VertexLabel vertexLabelB = this.sqlgGraph.getTopology().ensureVertexLabelExist("B", properties); properties.clear(); properties.put("namea", PropertyType.STRING); properties.put("nameb", PropertyType.STRING); properties.put("namec", PropertyType.STRING); vertexLabelA.ensureEdgeLabelExist("ab", vertexLabelB, properties); @SuppressWarnings("OptionalGetWithoutIsPresent") Collection<PropertyColumn> propertyColumns = this.sqlgGraph.getTopology().getPublicSchema().getEdgeLabel("ab").get().getProperties().values(); GlobalUniqueIndex globalUniqueIndex = this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<>(propertyColumns)); Assert.assertNotNull(globalUniqueIndex); this.sqlgGraph.tx().commit(); Schema globalUniqueIndexSchema = this.sqlgGraph.getTopology().getGlobalUniqueIndexSchema(); Optional<GlobalUniqueIndex> globalUniqueIndexOptional = globalUniqueIndexSchema.getGlobalUniqueIndex(globalUniqueIndex.getName()); Assert.assertTrue(globalUniqueIndexOptional.isPresent()); Optional<PropertyColumn> nameaPropertyColumnOptional = this.sqlgGraph.getTopology().getPublicSchema().getEdgeLabel("ab").get().getProperty("namea"); Assert.assertTrue(nameaPropertyColumnOptional.isPresent()); @SuppressWarnings("OptionalGetWithoutIsPresent") Set<GlobalUniqueIndex> globalUniqueIndices = nameaPropertyColumnOptional.get().getGlobalUniqueIndices(); Assert.assertEquals(1, globalUniqueIndices.size()); Assert.assertEquals(globalUniqueIndex, globalUniqueIndices.iterator().next()); Assert.assertEquals("ab_namea_ab_nameb_ab_namec", globalUniqueIndex.getName()); Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b"); Edge edge = a1.addEdge("ab", b1, "namea", "a", "nameb", "b", "namec", "c"); this.sqlgGraph.tx().commit(); try { a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a"); b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b"); a1.addEdge("ab", b1, "namea", "a", "nameb", "b", "namec", "c"); fail("GlobalUniqueIndex should prevent this from executing"); } catch (Exception e) { //swallow } this.sqlgGraph.tx().rollback(); this.sqlgGraph.addVertex(T.label, "A", "namea", "aa"); this.sqlgGraph.tx().commit(); List<Vertex> globalUniqueIndexVertexes = this.sqlgGraph.globalUniqueIndexes().V().toList(); Assert.assertEquals(3, globalUniqueIndexVertexes.size()); Assert.assertTrue(globalUniqueIndexVertexes.stream().allMatch(g -> g.label().equals(Schema.GLOBAL_UNIQUE_INDEX_SCHEMA + "." + globalUniqueIndex.getName()))); Assert.assertEquals(1, globalUniqueIndexVertexes.stream().filter(g -> g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_VALUE).equals("a")).count()); Assert.assertEquals(1, globalUniqueIndexVertexes.stream().filter(g -> g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_VALUE).equals("b")).count()); Assert.assertEquals(1, globalUniqueIndexVertexes.stream().filter(g -> g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_VALUE).equals("c")).count()); Assert.assertTrue(globalUniqueIndexVertexes.stream().allMatch(g -> g.<String>value(GlobalUniqueIndex.GLOBAL_UNIQUE_INDEX_RECORD_ID).equals(edge.id().toString()))); } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test public void testGlobalUniqueIndexAcrossDifferentEdges() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("a", PropertyType.STRING); VertexLabel aVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("A", properties); VertexLabel bVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("B", properties); EdgeLabel abEdgeLabel = aVertexLabel.ensureEdgeLabelExist("ab", bVertexLabel, properties); VertexLabel cVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("C", properties); VertexLabel dVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("D", properties); EdgeLabel cdEdgeLabel = cVertexLabel.ensureEdgeLabelExist("cd", dVertexLabel, properties); PropertyColumn abEdgeProperty = abEdgeLabel.getProperty("a").get(); PropertyColumn cdEdgeProperty = cdEdgeLabel.getProperty("a").get(); Set<PropertyColumn> globalUniqueIndexProperties = new HashSet<>(); globalUniqueIndexProperties.add(abEdgeProperty); globalUniqueIndexProperties.add(cdEdgeProperty); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(globalUniqueIndexProperties); this.sqlgGraph.tx().commit(); Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "a", "132"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "a", "132"); a1.addEdge("ab", b1, "a", "123"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C", "a", "132"); Vertex d1 = this.sqlgGraph.addVertex(T.label, "D", "a", "132"); try { c1.addEdge("cd", d1, "a", "123"); fail("GlobalUniqueIndex should prevent this from happening"); } catch (Exception e) { //swallow } } @Test public void testVertexUniqueConstraintUpdate() { VertexLabel vertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("A", new HashMap<String, PropertyType>() {{ put("namea", PropertyType.STRING); put("nameb", PropertyType.STRING); put("namec", PropertyType.STRING); }}); Set<PropertyColumn> properties = new HashSet<>(vertexLabel.getProperties().values()); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(properties); Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "namea", "a"); this.sqlgGraph.tx().commit(); a1.property("namea", "aa"); this.sqlgGraph.tx().commit(); try { //this should pass this.sqlgGraph.addVertex(T.label, "A", "namea", "a"); } catch (Exception e) { fail("GlobalUniqueIndex should not fire"); } try { this.sqlgGraph.addVertex(T.label, "A", "nameb", "aa"); fail("GlobalUniqueIndex should prevent this from executing"); } catch (Exception e) { //swallow } } @Test public void testEdgeUniqueConstraintUpdate() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("name", PropertyType.STRING); VertexLabel vertexLabelA = this.sqlgGraph.getTopology().ensureVertexLabelExist("A", properties); VertexLabel vertexLabelB = this.sqlgGraph.getTopology().ensureVertexLabelExist("B", properties); properties.clear(); properties.put("namea", PropertyType.STRING); properties.put("nameb", PropertyType.STRING); properties.put("namec", PropertyType.STRING); vertexLabelA.ensureEdgeLabelExist("ab", vertexLabelB, properties); @SuppressWarnings("OptionalGetWithoutIsPresent") Collection<PropertyColumn> propertyColumns = this.sqlgGraph.getTopology().getPublicSchema().getEdgeLabel("ab").get().getProperties().values(); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<>(propertyColumns)); this.sqlgGraph.tx().commit(); Schema globalUniqueIndexSchema = this.sqlgGraph.getTopology().getGlobalUniqueIndexSchema(); Optional<GlobalUniqueIndex> globalUniqueIndexOptional = globalUniqueIndexSchema.getGlobalUniqueIndex("ab_namea_ab_nameb_ab_namec"); Assert.assertTrue(globalUniqueIndexOptional.isPresent()); Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b"); Edge e = a1.addEdge("ab", b1, "namea", "a", "nameb", "b", "namec", "c"); this.sqlgGraph.tx().commit(); e.property("namea", "aa"); this.sqlgGraph.tx().commit(); try { //this should pass a1.addEdge("ab", b1, "namea", "a", "nameb", "bb", "namec", "cc"); } catch (Exception ex) { fail("GlobalUniqueIndex should not fire"); } try { a1.addEdge("ab", b1, "namea", "aa", "nameb", "bb", "namec", "cc"); fail("GlobalUniqueIndex should prevent this from executing"); } catch (Exception ex) { //swallow } } @Test public void testVertexUniqueConstraintDelete() { VertexLabel vertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("A", new HashMap<String, PropertyType>() {{ put("namea", PropertyType.STRING); put("nameb", PropertyType.STRING); put("namec", PropertyType.STRING); }}); Set<PropertyColumn> properties = new HashSet<>(vertexLabel.getProperties().values()); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(properties); Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "namea", "a1"); this.sqlgGraph.addVertex(T.label, "A", "namea", "a2"); this.sqlgGraph.tx().commit(); Assert.assertEquals(6, this.sqlgGraph.globalUniqueIndexes().V().count().next().intValue()); try { this.sqlgGraph.addVertex(T.label, "A", "namea", "a1"); fail("GlobalUniqueIndex should prevent this form happening"); } catch (Exception e) { //swallow this.sqlgGraph.tx().rollback(); } a1.remove(); this.sqlgGraph.tx().commit(); Assert.assertEquals(3, this.sqlgGraph.globalUniqueIndexes().V().count().next().intValue()); this.sqlgGraph.addVertex(T.label, "A", "namea", "a1"); //this time it passes. this.sqlgGraph.tx().commit(); Assert.assertEquals(6, this.sqlgGraph.globalUniqueIndexes().V().count().next().intValue()); } @Test public void testEdgeUniqueConstraintDelete() { Map<String, PropertyType> properties = new HashMap<>(); properties.put("namea", PropertyType.STRING); VertexLabel aVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("A", properties); VertexLabel bVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("B", properties); EdgeLabel edgeLabel = aVertexLabel.ensureEdgeLabelExist("ab", bVertexLabel, properties); Set<PropertyColumn> propertyColumns = new HashSet<>(edgeLabel.getProperties().values()); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(propertyColumns); Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "namea", "a1"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "namea", "a2"); Edge edge = a1.addEdge("ab", a2, "namea", "123"); this.sqlgGraph.tx().commit(); Assert.assertEquals(1, this.sqlgGraph.globalUniqueIndexes().V().count().next().intValue()); try { a1.addEdge("ab", a2, "namea", "123"); fail("GlobalUniqueIndex should prevent this form happening"); } catch (Exception e) { //swallow this.sqlgGraph.tx().rollback(); } edge.remove(); this.sqlgGraph.tx().commit(); Assert.assertEquals(0, this.sqlgGraph.globalUniqueIndexes().V().count().next().intValue()); a1.addEdge("ab", a2, "namea", "123"); //this time it passes. this.sqlgGraph.tx().commit(); Assert.assertEquals(1, this.sqlgGraph.globalUniqueIndexes().V().count().next().intValue()); } //Lukas's tests @Test public void testVertexSingleLabelUniqueConstraint() throws Exception { Map<String, PropertyType> properties = new HashMap<String, PropertyType>() {{ put("name", PropertyType.STRING); }}; VertexLabel personVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Person", properties); Assert.assertTrue(personVertexLabel.isUncommitted()); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<>(personVertexLabel.getProperties().values())); this.sqlgGraph.tx().commit(); this.sqlgGraph.addVertex(T.label, "Person", "name", "Joe"); this.sqlgGraph.tx().commit(); try { this.sqlgGraph.addVertex(T.label, "Person", "name", "Joe"); fail("Should not have been possible to add 2 people with the same name."); } catch (Exception e) { //good this.sqlgGraph.tx().rollback(); } } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test public void testVertexMultiLabelUniqueConstraint() throws Exception { Map<String, PropertyType> properties = new HashMap<String, PropertyType>() {{ put("name", PropertyType.STRING); }}; VertexLabel chocolateVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Chocolate", properties); VertexLabel candyVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Candy", properties); this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Icecream", properties); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<PropertyColumn>() {{ add(chocolateVertexLabel.getProperty("name").get()); add(candyVertexLabel.getProperty("name").get()); }}); this.sqlgGraph.addVertex(T.label, "Chocolate", "name", "Yummy"); this.sqlgGraph.tx().commit(); try { this.sqlgGraph.addVertex(T.label, "Candy", "name", "Yummy"); fail("A chocolate and a candy should not have the same name."); } catch (Exception e) { //good this.sqlgGraph.tx().rollback(); } this.sqlgGraph.addVertex(T.label, "Icecream", "name", "Yummy"); this.sqlgGraph.tx().commit(); } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test public void testVertexMultipleConstraintsOnSingleProperty() throws Exception { Map<String, PropertyType> properties = new HashMap<String, PropertyType>() {{ put("name", PropertyType.STRING); }}; VertexLabel chocolateVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Chocolate", properties); VertexLabel candyVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Candy", properties); this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Icecream", properties); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<PropertyColumn>() {{ add(chocolateVertexLabel.getProperty("name").get()); }}); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<PropertyColumn>() {{ add(candyVertexLabel.getProperty("name").get()); }}); this.sqlgGraph.addVertex(T.label, "Chocolate", "name", "Yummy"); this.sqlgGraph.addVertex(T.label, "Candy", "name", "Yummy"); this.sqlgGraph.addVertex(T.label, "Icecream", "name", "Yummy"); this.sqlgGraph.addVertex(T.label, "Icecream", "name", "Yummy"); this.sqlgGraph.tx().commit(); try { this.sqlgGraph.addVertex(T.label, "Chocolate", "name", "Yummy"); fail("Two chocolates should not have the same name."); } catch (Exception e) { //good this.sqlgGraph.tx().rollback(); } try { this.sqlgGraph.addVertex(T.label, "Candy", "name", "Yummy"); fail("Two candies should not have the same name."); } catch (Exception e) { //good this.sqlgGraph.tx().rollback(); } } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test public void testUpdateUniqueProperty() throws Exception { Map<String, PropertyType> properties = new HashMap<String, PropertyType>() {{ put("name", PropertyType.STRING); }}; VertexLabel personVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Person", properties); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<PropertyColumn>() {{ add(personVertexLabel.getProperty("name").get()); }}); this.sqlgGraph.tx().commit(); Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person"); v1.property("name", "Joseph"); Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "Joe"); this.sqlgGraph.tx().commit(); v2 = this.sqlgGraph.traversal().V(v2.id()).next(); try { v2.property("name", "Joseph"); fail("Should not be able to call a person a pre-existing name."); } catch (Exception e) { //good } } @Test public void testDeleteUniqueProperty() throws Exception { Map<String, PropertyType> properties = new HashMap<String, PropertyType>() {{ put("name", PropertyType.STRING); }}; VertexLabel personVertexLabel = this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist("Person", properties); this.sqlgGraph.getTopology().ensureGlobalUniqueIndexExist(new HashSet<>(personVertexLabel.getProperties().values())); this.sqlgGraph.tx().commit(); Vertex v = this.sqlgGraph.addVertex(T.label, "Person", "name", "Joseph"); this.sqlgGraph.tx().commit(); try { this.sqlgGraph.addVertex(T.label, "Person", "name", "Joseph"); fail("Should not be able to call a person a pre-existing name."); } catch (Exception e) { this.sqlgGraph.tx().rollback(); //good } this.sqlgGraph.traversal().V(v.id()).next().remove(); //this time it passes this.sqlgGraph.addVertex(T.label, "Person", "name", "Joseph"); } }
true
998015b8fdb3df705dbb9db7d666076bc0613487
Java
badbuda/JavaProjects
/CDUD/crudSQL/HttpClientMonitor.java
UTF-8
2,121
2.5
2
[]
no_license
package il.co.ilrd.sql; import java.io.IOException; import java.util.Observable; import java.util.Observer; import com.google.gson.JsonObject; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpClientMonitor implements Observer{ //private HttpPost post; private final String url; private final String CommandType; private final String Company; private final String Product; private final String Serial; public HttpClientMonitor(String url , String CommandType, String Company, String Product, String SerialNumber) { this.CommandType = (CommandType == null ? "" : CommandType); this.Company = (Company == null ? "" : Company); this.Product = (Product == null ? "" : Product); Serial = (SerialNumber == null ? "" : SerialNumber); this.url = url; } @Override public void update(Observable o, Object arg) { try { String updateThisData = arg.toString(); CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); JsonObject jsonObjectForRequest = createJsonRequest(CommandType, Company, Product, Serial, updateThisData); StringEntity entity = new StringEntity(jsonObjectForRequest.toString()); httpPost.setEntity(entity); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); client.execute(httpPost); client.close(); } catch (IOException e) { e.printStackTrace(); } } public static JsonObject createJsonRequest(String commandType, String Company, String Product, String SerialNu, String DataToParse) { JsonObject jsonToUser = new JsonObject(); jsonToUser.addProperty("commandType", commandType); jsonToUser.addProperty("Company", Company); jsonToUser.addProperty("Product", Product); jsonToUser.addProperty("SerialNumber", SerialNu); jsonToUser.addProperty("Data", DataToParse); return jsonToUser; } }
true
8ddacf0811953cf5c986d9cf831f8040fb0a125a
Java
bechte/JUT
/src/test/java/de/bechte/jut/matchers/MultipleTimesTest.java
UTF-8
1,502
2.8125
3
[]
no_license
/* * Copyright (c) 2014. Stefan Bechtold. All rights reserved. */ package de.bechte.jut.matchers; import de.bechte.jut.annotations.Test; import static de.bechte.jut.matchers.ExpectThrowable.expectThrowable; import static de.bechte.jut.matchers.MultipleTimes.multipleTimes; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class MultipleTimesTest { @Test public void givenAPositiveNumberOfRepetitions_performsNumberOfRepetitionRuns() throws Exception { int repetitions = 10; int[] counter = { 0 }; multipleTimes(repetitions).run(() -> { counter[0]++; }); assertThat(counter[0], is(repetitions)); } @Test public void givenOnlyOneRepetition_throwsIllegalArgumentException() throws Exception { expectThrowable(IllegalArgumentException.class) .withMessage(MultipleTimes.INVALID_NUMBEROFREPETITIONS).in(() -> { multipleTimes(1).run(() -> {}); }); } @Test public void givenZeroRepetitions_throwsIllegalArgumentException() throws Exception { expectThrowable(IllegalArgumentException.class) .withMessage(MultipleTimes.INVALID_NUMBEROFREPETITIONS).in(() -> { multipleTimes(0).run(() -> {}); }); } @Test public void givenNegativeNumberOfRepetitions_throwsIllegalArgumentException() throws Exception { expectThrowable(IllegalArgumentException.class) .withMessage(MultipleTimes.INVALID_NUMBEROFREPETITIONS).in(() -> { multipleTimes(-1).run(() -> {}); }); } }
true
d6d197ef238992fac7ad88356771c95356d79ec8
Java
Jason-githubs/repo-jt
/jt-common/src/main/java/com/jt/vo/SysResult.java
UTF-8
1,568
3.046875
3
[]
no_license
package com.jt.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** * 该VO对象是系统返回值VO对象,主要包含3个属性 * 1.设定状态码 200表示执行成功 201执行失败 人为定义的(和浏览器没关系)业务定义. * 2.定义返回值信息 服务器可能会给用户一些提示信息.例如:执行成功,用户名或密码错误等 * 3.定义返回值对象 服务器在后端处理完成业务之后,将对象返回给前端 */ @Data @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor public class SysResult { private Integer status; //200成功 201失败 private String msg; //服务器提示信息 private Object data; //服务器返回前端的业务数据 /** * 为了简化用户的调用过程,准备了一些工具API * 用户的关注点: 1.执行成功 2.执行失败 */ public static SysResult fail(){ return new SysResult(201,"业务执行失败",null); } public static SysResult success(){//只标识成功!不携带数据 return new SysResult(200,"业务执行成功",null); } //注意事项:写工具API方法时切记方法重载千万不要耦合 public static SysResult success(Object data){//成功之后返回业务数据 return new SysResult(200,"业务执行成功",data); } public static SysResult success(String msg,Object data){ return new SysResult(200,msg,data); } }
true
6cdb813ab62b42088bdd7c687fffb0acbff8ac0f
Java
xanthos203/Pac-Man
/Pac-Man/src/control/listeners/WindowListener.java
ISO-8859-1
3,656
3.328125
3
[]
no_license
package control.listeners; import java.awt.Component; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JOptionPane; import view.frames.GameMainFrame; /**Diese <i>Listener-Klasse</i> namens <b>WindowListener</b> wird aufgerufen, wenn der Benutzer das <b>Programm schlieen</b> mchte.<br> * Hierbei wird der Benutzer nocheinmal gefragt, ob er das Spiel wirklich beenden mchte.<br> * <br> * Diese Klasse <b>erbt</b> von der Klasse <b>WindowAdapter</b>. * Diese <i>"KeyAdapter-Klasse"</i> wird sozusagen von <i>"JAVA"</i> vorgeschrieben, um den Benutzer ein wenig <i>"unter die Arme zu greifen".</i> * * @version 1.0 * * @author Manuel Glantschnig * @author Thomas Mader-Ofer * @author Cristina Erhart */ public final class WindowListener extends WindowAdapter { /**In der Variable <B>frameReference</B> wird gespeichert um <b>welches Fenster</b> es sich handelt, wenn diese Klasse aufgerufen wird.*/ private JFrame frameReference; /**Im follgenden <b>Konstruktor</b> wird der <b>Wert der Variable "frame" in der Variable "frameReference" gespeichert</b>. * @param frame Die Variable <i>frame</i> erstellt eine <i>Referenz</i> auf das <b>JFrame</b>.*/ public WindowListener(JFrame frame) { /*In der Variable "frameReference" wird der Wert von der Variable "frame" gespeichert und somit wird eine Referenz auf die jeweilige Klasse, die den Konstruktor bzw. den Listener aufruft, erstellt.*/ frameReference = frame; /*Wenn man auf das "X" in der rechten oberern Ecke klickt, soll nichts passieren.*/ frameReference.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } /**Die <b>"windowClosing-Methode" kommt immer dann zum Vorschein, wenn ein Benutzer das Programm schleien mchte..<br> * Es erscheint dann ein <i>"kleines Fenster"</i> am Bildschirm. * @param weEvent Die Variable "<i>weEvent</i>" speichert, wenn ein Fenster geschlossen werden soll.*/ @Override public void windowClosing(WindowEvent weEvent) { /*in parentComponent wird gespeichert, auf welchem Fenster der Dialog angezeigt wird*/ Component parentComponent = frameReference; /*Die Variable "warning" speichert einen kleinen Warnhinwei.*/ String warning = "M\u00F6chten Sie das Spiel wirklich beenden\u003F"; /*Die Variable "title" speichert den Text in der oberen (meist eingefrbten) Leiste.*/ String titel = "Spiel beenden\u003F"; /*In der Variable "optionPane" wird gespeichert, welchen Typ dieses optionPane hat.*/ int optionType = JOptionPane.YES_NO_OPTION; /*In der Variable "messageType" wird die Art der Nachricht des JOptionPanes gespeichert.*/ int messageType = JOptionPane.QUESTION_MESSAGE; /*"optionen" speichert die Mglichkeiten, die dem Benutzer zur Auswahl stehen, wenn er das Programm beendet.*/ Object[] optionen = { "Beenden", "Abbrechen" }; /*Wenn die Variable "frameReference" nicht null ist, wird follgendes ausgefhrt.*/ if(frameReference instanceof GameMainFrame) { /*Zu dem Text der Variable "warning" wird noch ein Teil hinzugefgt.*/ warning += "\n\nDadurch geht Ihr gesamter Spielfortschritt verloren\u0021"; } /*Ein neues JOptionPane wird erstellt. Dieses fragt den Benutzer, ob er das Spiel wirklich beenden mchte.*/ int optionPane = JOptionPane.showOptionDialog(parentComponent, warning, titel, optionType, messageType, null, optionen, optionen[0]); /*Follgendes wird ausgefhrt, wenn der Benutzer auf "Beenden" klickt.*/ if(optionPane == JOptionPane.YES_OPTION) { /*Das Programm wird beendet*/ System.exit(0); } } }
true
c9dc369db59cd659e37632dc4e3abd45ffbbb8f9
Java
Davi-zzz/Login-e-Cadastro-de-Usuario-JSF
/src/controller/WelcomeController.java
UTF-8
614
1.984375
2
[]
no_license
package controller; import java.io.Serializable; import javax.faces.view.ViewScoped; import javax.inject.Named; import model.User; import util.Session; import util.Util; @Named @ViewScoped public class WelcomeController implements Serializable { /** * */ private static final long serialVersionUID = -8394143630266495351L; public void encerrarSessao() { Session.getInstance().invalidateSession(); Util.redirect("login.xhtml"); } public User getUsuarioLogado() { Object obj = Session.getInstance().getAttribute("usuarioLogado"); if (obj == null) return null; return (User) obj; } }
true
3b252b44259196e64c96d6c5f71bfac6f7ef8afb
Java
matheusspaiva/projeto_java
/trabalho/src/view/Inicio.java
UTF-8
5,199
2.21875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author mathe */ package view; public class Inicio extends javax.swing.JFrame { /** * Creates new form principal */ public Inicio() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnconectar = new javax.swing.JButton(); btncadastrar = new javax.swing.JButton(); lblTitulo = new javax.swing.JFormattedTextField(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("BEM VINDO"); setResizable(false); getContentPane().setLayout(null); btnconectar.setText("conectar"); btnconectar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnconectarActionPerformed(evt); } }); getContentPane().add(btnconectar); btnconectar.setBounds(150, 120, 90, 30); btncadastrar.setText("cadastrar"); btncadastrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btncadastrarActionPerformed(evt); } }); getContentPane().add(btncadastrar); btncadastrar.setBounds(150, 190, 90, 30); lblTitulo.setEditable(false); lblTitulo.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true)); lblTitulo.setHorizontalAlignment(javax.swing.JTextField.CENTER); lblTitulo.setText(" IMath"); lblTitulo.setFont(new java.awt.Font("Segoe UI Historic", 0, 11)); // NOI18N getContentPane().add(lblTitulo); lblTitulo.setBounds(170, 30, 50, 40); jLabel2.setIcon(new javax.swing.ImageIcon("C:\\Users\\mathe\\Downloads\\Fundo.png")); // NOI18N getContentPane().add(jLabel2); jLabel2.setBounds(0, 0, 400, 300); setSize(new java.awt.Dimension(416, 339)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnconectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnconectarActionPerformed new Entrar().setVisible(true); dispose(); }//GEN-LAST:event_btnconectarActionPerformed private void btncadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btncadastrarActionPerformed new Cadastro().setVisible(true); dispose(); }//GEN-LAST:event_btncadastrarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new Inicio().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btncadastrar; private javax.swing.JButton btnconectar; private javax.swing.JLabel jLabel2; private javax.swing.JFormattedTextField lblTitulo; // End of variables declaration//GEN-END:variables }
true
378229f5b39ba5c5527d569976d7bcf65c192aac
Java
vjetteam/vjet
/core/org.ebayopensource.vjet.core.jsgenshared/src/org/ebayopensource/dsf/jsgen/shared/validation/vjo/semantic/rules/VjoRepoGenerator.java
UTF-8
3,231
1.90625
2
[]
no_license
/******************************************************************************* * Copyright (c) 2005-2011 eBay Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.ebayopensource.dsf.jsgen.shared.validation.vjo.semantic.rules; import org.ebayopensource.dsf.jsgen.shared.validation.vjo.IVjoSemanticRule; import org.ebayopensource.dsf.jsgen.shared.validation.vjo.IVjoSemanticRuleSet; public class VjoRepoGenerator { public void setUp(){ // Logger.initLogProperties("logging.properties"); } public static void main(String[] args) { testPolicy(); } public static void testRuleRepo(){ String prefix = "public static final PreferenceKey PREF_PB_"; StringBuffer declairation = new StringBuffer(); StringBuffer getKeys = new StringBuffer("return new Key[] { "); StringBuffer storeValue = new StringBuffer(); StringBuffer content = new StringBuffer(); String ruleSetName = ""; String ruleName = ""; for(IVjoSemanticRuleSet ruleSet : VjoSemanticRuleRepo.getInstance().getRuleSets()){ ruleSetName = ruleSet.getRuleSetName(); for(IVjoSemanticRule<?> rule : ruleSet.getRules()){ ruleName = rule.getRuleName().toUpperCase(); ruleName = ruleName.replace(" ", "_"); declairation.append(prefix).append(ruleName) .append(" = getVJETCoreKey(\"").append(ruleSetName).append(".") .append(rule.getRuleName()).append("\");\n"); getKeys.append(" PREF_PB_").append(ruleName).append(",\n"); storeValue.append(" storeValue( PREF_PB_").append(ruleName).append(");\n"); content.append("if (keyName.equals(PREF_PB_").append(ruleName).append(".getName())) {\n") .append(" addComboBox(inner, label, PREF_PB_").append(ruleName).append(",\n") .append(" errorWarningIgnore, errorWarningIgnoreLabels,\n") .append(" defaultIndent);\n") .append("}\n"); } } getKeys.deleteCharAt(getKeys.length() -2 ).append("};"); // System.out.print(declairation); // System.out.println(getKeys); // System.out.print(storeValue); // System.out.print(content); ruleSetName = "Accessibility"; ruleName = "Property_Is_Not_Visible"; // assertNotNull(VjoSemanticRuleRepo.getInstance().getRule(ruleSetName, ruleName)); } public static void testPolicy(){ // String ruleName = null; // String ruleSetName = null; // for(IVjoSemanticRuleSet ruleSet : VjoSemanticRuleRepo.getInstance().getRuleSets()){ // ruleSetName = ruleSet.getRuleSetName(); // // for(IVjoSemanticRule<?> rule : ruleSet.getRules()){ // ruleName = rule.getRuleName().toUpperCase(); //// System.out.println(rule); //// System.out.println(rule.getRulePolicy(null).getProblemSeverity(null)); //// System.out.println("========================================"); // } // } } }
true
afe64bfec361a20f738d2096ad2d19fd7ca0ee4d
Java
MShultz/Shopping-List
/src/shultz/shopping/Logout.java
UTF-8
923
2.296875
2
[]
no_license
package shultz.shopping; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/logout") public class Logout extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) { logout(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) { logout(request, response); } private void logout(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(true); session.invalidate(); try { response.sendRedirect("index.html"); } catch (IOException e) { e.printStackTrace(); } } }
true
258e015dce7781c20c3b1b552568eb5195e3d50a
Java
elaine-mou-nisc/Dump
/src/com/example/SystemHealth_Android/MyActivity.java
UTF-8
3,538
2.375
2
[]
no_license
package com.example.SystemHealth_Android; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; /* * First screen; displays tile fragments to click and lead into activities * */ public class MyActivity extends FragmentActivity { public static String updateTime = "11:46am June 20, 2014"; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //selects layout based on orientation if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){ setContentView(R.layout.main_landscape); } else { setContentView(R.layout.main_portrait); } /* String status = null; JSONArray jsonArray = null; BackgroundJsonTask jsonTask = new BackgroundJsonTask(this); try { JSONObject jsonObject = jsonTask.execute(R.raw.test2).get(); if(jsonObject.has("status")){ status = jsonObject.getString("status"); } if(jsonObject.has("services")){ jsonArray = (JSONArray) jsonObject.get("services"); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } boolean healthy = false; if(status.equals("OK")){ healthy = true; }else{ healthy = false; }*/ FragmentManager fragmentManager = getSupportFragmentManager(); /*SystemHealthFragment greenFragment = (SystemHealthFragment) fragmentManager.findFragmentById(R.id.green_fragment); ProgressFragment progressFragment = (ProgressFragment) fragmentManager.findFragmentById(R.id.progress_fragment);*/ ContactTrackingTile contactTrackingTile = (ContactTrackingTile) fragmentManager.findFragmentById(R.id.pie_fragment); //lazy loads fragments if(/*greenFragment==null || progressFragment==null || */contactTrackingTile ==null) { /*greenFragment = new SystemHealthFragment(healthy); progressFragment = new ProgressFragment();*/ contactTrackingTile = new ContactTrackingTile(); /* fragmentManager.beginTransaction().replace(R.id.green_fragment,greenFragment).commit(); fragmentManager.beginTransaction().replace(R.id.progress_fragment,progressFragment).commit();*/ fragmentManager.beginTransaction().replace(R.id.pie_fragment, contactTrackingTile).commit(); } /* if(status.equals("Bad")){ ArrayList<String> stringArrayList = new ArrayList<String>(3); for(int i=0;i<3 && i<jsonArray.length() ;i++){ try { stringArrayList.add(jsonArray.getString(i)); } catch (JSONException e) { e.printStackTrace(); } } if(!stringArrayList.isEmpty()){ greenFragment.text1=stringArrayList.get(0); } if(stringArrayList.size()>1){ greenFragment.text2=stringArrayList.get(1); } if(stringArrayList.size()>2){ greenFragment.text3=stringArrayList.get(2); } }*/ } }
true
64ea20e962f9044c08150ca2baf427292b15fccf
Java
Seojeonguk/Algorithm_practice
/BOJ/6889.java
UTF-8
1,140
3.3125
3
[]
no_license
import java.util.*; import java.io.*; public class Main { static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws Exception { int adjectiveCnt = Integer.parseInt(br.readLine()); int nounCnt = Integer.parseInt(br.readLine()); String[] adjectives = new String[adjectiveCnt]; String[] nouns = new String[nounCnt]; for(int i=0;i<adjectiveCnt;i++) { adjectives[i] = br.readLine(); } for(int i=0;i<nounCnt;i++) { nouns[i] = br.readLine(); } for(String adjective : adjectives) { for(String noun : nouns) { sb.append(adjective) .append(" as ") .append(noun) .append("\n"); } } bw.write(sb.toString()); bw.flush(); bw.close(); br.close(); } }
true
b2457d449f36bb8db266c4314c502c82aaa6ee4c
Java
alexand34/algorithms
/lab11/src/Main.java
UTF-8
1,534
2.890625
3
[]
no_license
import java.util.List; public class Main { public static void main(String[] args) { Node nLutsk=new Node("Lutsk"); Node nKovel=new Node("Kovel"); Node nRatne=new Node("Ratne"); Node nKK=new Node("Kamin'-Kashyrs'kyi"); Node nManevichy=new Node("Manevichy"); Node nNovovolynsk=new Node("Novovolynsk"); Node nKivertsy = new Node("Kivertsy"); Node nLubeshiv = new Node("Lubeshiv"); Node nGorohiv = new Node("Gorohiv"); Graph g=new Graph(); g.addNode(nLutsk); g.addNode(nKovel); g.addNode(nRatne); g.addNode(nKK); g.addNode(nManevichy); g.addNode(nNovovolynsk); g.addNode(nKivertsy); g.addNode(nLubeshiv); g.addNode(nGorohiv); g.setRootNode(nLutsk); g.connectNode(nLutsk,nKovel, 0.74); g.connectNode(nLutsk,nRatne, 1.24); g.connectNode(nLutsk, nKK, 1.26); g.connectNode(nLutsk,nManevichy, 0.76); g.connectNode(nLutsk,nNovovolynsk, 0.92); g.connectNode(nLutsk,nKivertsy, 0.15); g.connectNode(nLutsk,nLubeshiv, 1.36); g.connectNode(nLutsk,nGorohiv, 0.52); Node found_node = g.bfs_find("Lutsk"); List<Tuple> distanceTuple= g.getDistanceBetweenNodes(found_node); for (Tuple node: distanceTuple) { System.out.println("Distance from " + found_node.label + " to " + node.EndPoint.label + " " + node.Disttance + "km"); } } }
true
3e88cc80d352a325b2ee724ac554cc8c2972cfda
Java
Bharathstark/Hibernate
/com/hibernate/project/EmployeeMain2.java
UTF-8
487
2.328125
2
[]
no_license
package com.hibernate.project; import com.hibernate.dao.EmployeeAddDao; import com.hibernate.datamodel.Address; import com.hibernate.datamodel.EmployeeAddress; //Component mapping between Employee and address public class EmployeeMain2 { public static void main(String args[]) { EmployeeAddDao ME = new EmployeeAddDao(); Address address1 = ME.addAddress("Kondapur","Hyderabad","AP","532"); Integer empID1 = ME.addEmployeeAddress("Manoj", "Kumar", address1); ME.listEmployees(); } }
true
f87a646965a6bc775edef0a6d4682b64f648acd9
Java
EfraimChu/CodeDemo
/Test.java
UTF-8
1,230
3.15625
3
[]
no_license
import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; /** * @Author efraim.zhu * @Date 2020/5/28 **/ public class Test { public static void main(String[] args) { String re = MessageFormat.format("{0},{1}", 11, "haha"); System.out.println(re); // List<List<Integer>> groupList = new ArrayList<>(); // List<Integer> tem = new ArrayList<>(); // IntStream.rangeClosed(1, 23).forEach(tem::add); // groupList = print(tem); // groupList.forEach(System.out::println); } public static List<List<Integer>> print(List<Integer> integerList) { List<List<Integer>> groupList = new ArrayList<>(); int i = 0; int size = integerList.size(); List<Integer> tem = new ArrayList<>(); while (i < size) { if (tem.size() == 10) { groupList.add(tem); tem = new ArrayList<>(); tem.add(integerList.get(i)); }else { tem.add(integerList.get(i)); } i++; } if (!tem.isEmpty()) { groupList.add(tem); } return groupList; } }
true
ea885c3186e8f28b22948aaa85ba258a658aac19
Java
unenergizer/MPRPG
/MPRPG/src/com/minepile/mprpg/items/ItemIdentifierManager.java
UTF-8
1,043
2.703125
3
[]
no_license
package com.minepile.mprpg.items; import net.md_5.bungee.api.ChatColor; import org.bukkit.entity.Player; import com.minepile.mprpg.MPRPG; public class ItemIdentifierManager { //setup instance variables public static MPRPG plugin; static ItemIdentifierManager itemIdentifierManagerInstance = new ItemIdentifierManager(); //Create instance public static ItemIdentifierManager getInstance() { return itemIdentifierManagerInstance; } //Setup AlchemyManager @SuppressWarnings("static-access") public void setup(MPRPG plugin) { this.plugin = plugin; } /** * This will be toggled when a player left-clicks or right clicks a player. * * @param player The player who clicked the NPC. */ public static void toggleCitizenInteract(Player player, Player npc) { String playerName = player.getName(); //Send player a message. player.sendMessage(ChatColor.GRAY + npc.getDisplayName() + ChatColor.DARK_GRAY + ": " + ChatColor.WHITE + "Umm, " + playerName + " you have no items to identify."); } }
true
ca667a02510cba526d73513f8c6b38ae7835f1c5
Java
singh-ajeet/leetcode
/src/main/java/org/ajeet/algorithms/concurrency/Solution.java
UTF-8
2,037
2.9375
3
[]
no_license
package org.ajeet.algorithms.concurrency; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; class Solution { private static int K; private static long maxAllowed = 100; private static AtomicLong startTime = new AtomicLong(0); //10 s private static AtomicInteger counter = new AtomicInteger(0); // private static Map<String, Integer> sizeLimit = ; private static Map<String, Long> cache = new ConcurrentHashMap<>(); public static boolean shouldPrintMessage(long timestamp, String message) { long currentTimeStamp = System.currentTimeMillis(); long diff = currentTimeStamp - startTime.get(); if(diff >= K){ // cache.clear(); long expected = startTime.get(); startTime.compareAndSet(expected, currentTimeStamp); } long messageDuration = currentTimeStamp - timestamp; if(messageDuration <= K && !cache.containsValue(message)){ cache.put(message, timestamp); System.out.println(message); return true; } else if(messageDuration > K){ cache.remove(message); } return false; } public static void main(String[] args) { startTime = new AtomicLong(System.currentTimeMillis()); K = 10; shouldPrintMessage(System.currentTimeMillis() - 8, "Some message 1"); shouldPrintMessage(System.currentTimeMillis() - 18, "Some message 3"); shouldPrintMessage(System.currentTimeMillis() - 1, "Some message 4"); shouldPrintMessage(System.currentTimeMillis(), "Some message 5"); shouldPrintMessage(System.currentTimeMillis() - 7, "Some message 6"); shouldPrintMessage(System.currentTimeMillis() - 18, "Some message 7"); shouldPrintMessage(System.currentTimeMillis() - 200, "Some message 8"); shouldPrintMessage(System.currentTimeMillis() - 18, "Some message 9"); } }
true