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
81dd02371e8d7d2f1bf6a68b6c34aec6fd8ca9d7
Java
Narrator/ParkIt
/app/src/main/java/com/getparkit/parkit/Async/ExchangeToken.java
UTF-8
3,990
2.515625
3
[]
no_license
package com.getparkit.parkit.Async; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import com.getparkit.parkit.Classes.UserAccess; import com.getparkit.parkit.Activities.HelperActivities.ErrorActivity; import com.getparkit.parkit.Activities.AsyncDrawerActivities.RoleSelectActivity; import com.getparkit.parkit.SQLite.Helper; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class ExchangeToken extends AsyncTask <String, Void, JSONObject> { private Context mContext; public ExchangeToken (Context context) { mContext = context; } public JSONObject doInBackground(String ...params) { HttpURLConnection connection; OutputStreamWriter request = null; URL url = null; String response = null; try { url = new URL("https://parkit-api.herokuapp.com/auth/google/token"); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type","application/json"); connection.setRequestMethod("POST"); String str = "{\"id_token\": \"" + params[0].toString() +"\"}"; byte[] outputInBytes = str.getBytes("UTF-8"); OutputStream os = connection.getOutputStream(); os.write( outputInBytes ); os.close(); request = new OutputStreamWriter(connection.getOutputStream()); request.flush(); request.close(); String line = ""; InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } // Response from server after login process will be stored in response variable. response = sb.toString(); // You can perform UI operations here isr.close(); reader.close(); } catch(IOException e) { Log.d("SERVER_ERROR","Error exchanging token with server"); Intent i = new Intent(); i.setClass(mContext, ErrorActivity.class); mContext.startActivity(i); } System.out.println(response); JSONObject jObj; // Try to parse the string to a JSON Object try { jObj = new JSONObject(response); } catch (JSONException e) { Log.e("JSON_ERROR", "Error parsing data " + e.toString()); Intent i = new Intent(); i.setClass(mContext, ErrorActivity.class); mContext.startActivity(i); return null; } // Return the JSONObject return jObj; } protected void onPostExecute(JSONObject jObj) { try { // Store in SQLite (Insert) UserAccess ua = new UserAccess(jObj); Helper helper = new Helper(mContext); helper.deleteAll(); ua = helper.insertUserAccess(ua); // ASYNC->ACTIVITY CALL STARTING ACTIVITY FROM ASYNC Intent i = new Intent(); i.putExtra("user-access", ua); i.setClass(mContext, RoleSelectActivity.class); mContext.startActivity(i); return; } catch (Exception e) { Log.d("ASYNC_SQLITE_ERROR","Error inserting user access in SQLite DB"); Intent i = new Intent(); i.setClass(mContext, ErrorActivity.class); mContext.startActivity(i); return; } } }
true
25f9bf1d1420f75ff59fc24cf4471ea626415779
Java
546974842/test
/vitily.com.java/src/main/java/vitily/com/consts/SysTypeDesc.java
UTF-8
745
2.515625
3
[]
no_license
package vitily.com.consts; /** * 公共类型 * @author lether 2016年03月19日12:05:42 * */ public enum SysTypeDesc { CMS信息(Const.NEWSCATE_SYSTYPE_ID,"CMS"), 普通产品(Const.PROCATE_SYSTYPE_ID,"产品信息"), 字典分类(2,"字典分类"), 图片信息(3,"imagesams"), 文件类别(4,"文件类别"), 常见问题索引(5,"常见问题索引"), 品牌类型(6,"品牌类型"), 借款用途(7,"借款用途"), 标的分类(8,"标的分类"), 体验类目(9,"体验类目"), 其他(99,"其他"); private final int value; private final String desc; SysTypeDesc(int value, String desc){ this.value=value; this.desc=desc; } public int getValue() { return value; } public String getDesc() { return desc; } }
true
6e3e07ed8e68c0d686ad03445fbedf75eedeba10
Java
KienKse/thread-study
/src/br/com/ucsal/threads/study/ThreadRaizImpar.java
UTF-8
577
3.4375
3
[]
no_license
package br.com.ucsal.threads.study; public class ThreadRaizImpar implements Runnable{ private static Integer contador = 1; @Override public void run() { try { while(contador <= 99) { if(contador%2!=0) { System.out.println("Número: " + contador + " -> " + Math.sqrt(contador)); } Thread.sleep(50L); contador++; } System.out.println("Fim"); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
cefa7baed94831834a8b53841050330db9a77b39
Java
DanielCochavi/Movies-App
/app/src/main/java/com/academy/fundamentals/mymoviesapp/Threads/IAsyncTaskEvents.java
UTF-8
590
2.203125
2
[]
no_license
package com.academy.fundamentals.mymoviesapp.Threads; //Interface for communicating with the UI /** * This interface must be implemented by activities that contain the * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * **/ public interface IAsyncTaskEvents { void createAsyncTask(); void startAsyncTask(); void cancelAsyncTask(); void onPreExecute(); void onPostExecute(); void onProgressUpdate(Integer integer); void onCancel(); }
true
6d2fa0ae0074c916708da41778eefd520407fe17
Java
DP-1718/base-project
/src/main/java/services/ActorService.java
UTF-8
1,175
2.46875
2
[]
no_license
package services; import java.util.Collection; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import domain.Actor; import repositories.ActorRepository; import security.LoginService; import security.UserAccount; @Service @Transactional public class ActorService { @Autowired private ActorRepository actorRepository; public Collection<Actor> findAll() { Collection<Actor> actors; actors = this.actorRepository.findAll(); Assert.notNull(actors); return actors; } /* * Check if actor is logged */ public Boolean isActorLogged() { Boolean result; result = true; try { Assert.notNull(this.getActorLogged()); } catch (final Exception e) { result = false; } return result; } /* * Get actor logged. Throw exception if actor is not logged. */ public Actor getActorLogged() { UserAccount userAccount; Actor result; userAccount = LoginService.getPrincipal(); result = this.actorRepository.findOneByPrincipal(userAccount.getId()); Assert.notNull(result); return result; } }
true
7f7cb2e5394969d295e86a5dc9473ff1336a8c63
Java
MartaCorVa/MTKGamesCliente
/MTKGames/app/src/main/java/cat/paucasesnoves/mtkgames/utilidades/BibliotecaAdapter.java
UTF-8
2,143
2.421875
2
[]
no_license
package cat.paucasesnoves.mtkgames.utilidades; import android.content.Context; import android.graphics.BitmapFactory; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import cat.paucasesnoves.mtkgames.R; import cat.paucasesnoves.mtkgames.entidades.Juego; public class BibliotecaAdapter extends RecyclerView.Adapter<BibliotecaAdapter.ViewHolder> { private Context context; private ArrayList<Juego> juegos = new ArrayList<>(); public BibliotecaAdapter(ArrayList<Juego> mJuegos, @NonNull Context context) { this.juegos = mJuegos; this.context = context; } public class ViewHolder extends RecyclerView.ViewHolder { public ImageView imagen_juego; public TextView nombre_juego; public ViewHolder(View view) { super(view); imagen_juego = view.findViewById(R.id.imagen_juego); nombre_juego = view.findViewById(R.id.nombre_juego); } } @Override public BibliotecaAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.juego_layout, parent, false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(BibliotecaAdapter.ViewHolder viewHolder, int position) { Juego juego = juegos.get(position); viewHolder.nombre_juego.setText(juego.getNombre()); byte[] imageAsBytes = Base64.decode(juego.getImagenJuego(), Base64.DEFAULT); viewHolder.imagen_juego.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)); viewHolder.imagen_juego.setVisibility(View.VISIBLE); } @Override public int getItemCount() { return juegos.size(); } }
true
d3eede95bb0b06edca07d947e08ab385085a26a9
Java
hortonworks/cloudbreak
/cloud-aws-cloudformation/src/main/java/com/sequenceiq/cloudbreak/cloud/aws/connector/resource/AwsTerminateService.java
UTF-8
10,691
1.734375
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.sequenceiq.cloudbreak.cloud.aws.connector.resource; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.sequenceiq.cloudbreak.cloud.aws.AwsCloudFormationClient; import com.sequenceiq.cloudbreak.cloud.aws.CloudFormationStackUtil; import com.sequenceiq.cloudbreak.cloud.aws.client.AmazonAutoScalingClient; import com.sequenceiq.cloudbreak.cloud.aws.client.AmazonCloudFormationClient; import com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonEc2Client; import com.sequenceiq.cloudbreak.cloud.aws.common.view.AuthenticatedContextView; import com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView; import com.sequenceiq.cloudbreak.cloud.aws.util.AwsCloudFormationErrorMessageProvider; import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext; import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException; import com.sequenceiq.cloudbreak.cloud.model.CloudResource; import com.sequenceiq.cloudbreak.cloud.model.CloudResourceStatus; import com.sequenceiq.cloudbreak.cloud.model.CloudStack; import com.sequenceiq.cloudbreak.cloud.model.Group; import com.sequenceiq.cloudbreak.service.Retry; import com.sequenceiq.cloudbreak.service.Retry.ActionFailedException; import com.sequenceiq.common.api.type.ResourceType; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup; import software.amazon.awssdk.services.autoscaling.model.DeleteLaunchConfigurationRequest; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import software.amazon.awssdk.services.autoscaling.model.ResumeProcessesRequest; import software.amazon.awssdk.services.autoscaling.model.UpdateAutoScalingGroupRequest; import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest; import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; import software.amazon.awssdk.services.cloudformation.model.ResourceStatus; import software.amazon.awssdk.services.cloudformation.waiters.CloudFormationWaiter; import software.amazon.awssdk.services.ec2.model.DeleteKeyPairRequest; @Service public class AwsTerminateService { private static final Logger LOGGER = LoggerFactory.getLogger(AwsTerminateService.class); @Inject private AwsComputeResourceService awsComputeResourceService; @Inject private AwsCloudFormationClient awsClient; @Inject private CloudFormationStackUtil cfStackUtil; @Inject private AwsResourceConnector awsResourceConnector; @Inject private AwsCloudFormationErrorMessageProvider awsCloudFormationErrorMessageProvider; @Inject @Qualifier("DefaultRetryService") private Retry retryService; @Inject private AwsCloudWatchService awsCloudWatchService; public List<CloudResourceStatus> terminate(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources) { LOGGER.debug("Deleting stack: {}", ac.getCloudContext().getId()); AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); AuthenticatedContextView authenticatedContextView = new AuthenticatedContextView(ac); String regionName = authenticatedContextView.getRegion(); AmazonEc2Client amazonEC2Client = authenticatedContextView.getAmazonEC2Client(); AmazonCloudFormationClient amazonCloudFormationClient = awsClient.createCloudFormationClient(credentialView, regionName); LOGGER.debug("Calling deleteCloudWatchAlarmsForSystemFailures from AwsTerminateService"); awsCloudWatchService.deleteAllCloudWatchAlarmsForSystemFailures(stack, regionName, credentialView); waitAndDeleteCloudformationStack(ac, stack, resources, amazonCloudFormationClient); awsComputeResourceService.deleteComputeResources(ac, stack, resources); deleteKeyPair(ac, stack, amazonEC2Client, credentialView, regionName); deleteLaunchConfiguration(resources, ac); LOGGER.debug("Deleting stack finished"); return awsResourceConnector.check(ac, resources); } private void waitAndDeleteCloudformationStack(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources, AmazonCloudFormationClient amazonCloudFormationClient) { CloudResource stackResource = cfStackUtil.getCloudFormationStackResource(resources); if (stackResource == null) { LOGGER.debug("No cloudformation stack in resources"); return; } String cFStackName = stackResource.getName(); LOGGER.debug("Search and wait stack with name: {}", cFStackName); boolean exists = retryService.testWith2SecDelayMax15Times(() -> cfStackUtil.isCfStackExists(amazonCloudFormationClient, cFStackName)); if (exists) { DescribeStacksRequest describeStacksRequest = DescribeStacksRequest.builder().stackName(cFStackName).build(); resumeAutoScalingPolicies(ac, stack); LOGGER.debug("Delete cloudformation stack from resources"); DeleteStackRequest deleteStackRequest = DeleteStackRequest.builder().stackName(cFStackName).build(); try { retryService.testWith2SecDelayMax5Times(() -> isStackDeleted(amazonCloudFormationClient, describeStacksRequest, deleteStackRequest)); } catch (Exception e) { String errorReason = awsCloudFormationErrorMessageProvider.getErrorReason(ac, cFStackName, ResourceStatus.DELETE_FAILED); if (!StringUtils.hasText(errorReason)) { LOGGER.debug("Cannot fetch the error reason from AWS by DELETE_FAILED, fallback to exception message."); errorReason = e.getMessage(); } String message = String.format("Cloudformation stack delete failed: %s", errorReason); LOGGER.debug(message, e); throw new CloudConnectorException(message, e); } LOGGER.debug("Cloudformation stack from resources has been deleted"); } } private Boolean isStackDeleted(AmazonCloudFormationClient cfRetryClient, DescribeStacksRequest describeStacksRequest, DeleteStackRequest deleteStackRequest) { cfRetryClient.deleteStack(deleteStackRequest); LOGGER.debug("Waiting for final state of CloudFormation deletion attempt."); try (CloudFormationWaiter cloudFormationWaiter = cfRetryClient.waiters()) { cloudFormationWaiter.waitUntilStackDeleteComplete(describeStacksRequest); } catch (Exception e) { LOGGER.debug("CloudFormation stack delete ended in failed state. Delete operation will be retried."); throw new ActionFailedException(e.getMessage()); } return Boolean.TRUE; } private void deleteKeyPair(AuthenticatedContext ac, CloudStack stack, AmazonEc2Client amazonEC2Client, AwsCredentialView credentialView, String regionName) { LOGGER.debug("Deleting keypairs"); if (!awsClient.existingKeyPairNameSpecified(stack.getInstanceAuthentication())) { try { DeleteKeyPairRequest deleteKeyPairRequest = DeleteKeyPairRequest.builder().keyName(awsClient.getKeyPairName(ac)).build(); amazonEC2Client.deleteKeyPair(deleteKeyPairRequest); } catch (Exception e) { String errorMessage = String.format("Failed to delete public key [roleArn:'%s', region: '%s'], detailed message: %s", credentialView.getRoleArn(), regionName, e.getMessage()); LOGGER.warn(errorMessage, e); } } } private void resumeAutoScalingPolicies(AuthenticatedContext ac, CloudStack stack) { for (Group instanceGroup : stack.getGroups()) { try { String regionName = ac.getCloudContext().getLocation().getRegion().value(); String asGroupName = cfStackUtil.getAutoscalingGroupName(ac, instanceGroup.getName(), regionName); if (asGroupName != null) { AmazonAutoScalingClient amazonASClient = awsClient.createAutoScalingClient(new AwsCredentialView(ac.getCloudCredential()), regionName); List<AutoScalingGroup> asGroups = amazonASClient.describeAutoScalingGroups(DescribeAutoScalingGroupsRequest.builder() .autoScalingGroupNames(asGroupName) .build()).autoScalingGroups(); if (!asGroups.isEmpty()) { if (!asGroups.get(0).suspendedProcesses().isEmpty()) { amazonASClient.updateAutoScalingGroup(UpdateAutoScalingGroupRequest.builder() .autoScalingGroupName(asGroupName) .minSize(0) .desiredCapacity(0) .build()); amazonASClient.resumeProcesses(ResumeProcessesRequest.builder().autoScalingGroupName(asGroupName).build()); } } } else { LOGGER.debug("Autoscaling Group's physical id is null (the resource doesn't exist), it is not needed to resume scaling policies."); } } catch (AwsServiceException e) { String errorMessage = e.awsErrorDetails().errorMessage(); if (errorMessage.matches(".*Resource.*does not exist for stack.*") || errorMessage.matches(".*Stack '.*' does not exist.*")) { LOGGER.debug(e.getMessage()); } else { throw e; } } } } private void deleteLaunchConfiguration(List<CloudResource> resources, AuthenticatedContext ac) { if (resources == null) { return; } AmazonAutoScalingClient autoScalingClient = awsClient.createAutoScalingClient(new AwsCredentialView(ac.getCloudCredential()), ac.getCloudContext().getLocation().getRegion().value()); resources.stream().filter(cloudResource -> cloudResource.getType() == ResourceType.AWS_LAUNCHCONFIGURATION).forEach(cloudResource -> autoScalingClient.deleteLaunchConfiguration( DeleteLaunchConfigurationRequest.builder().launchConfigurationName(cloudResource.getName()).build())); } }
true
2c125ae679b88b19571be90eb87a94f8751aeb49
Java
ShashankSR/AndroidPlanner
/src/com/stealthmode/planb/LibraryTab.java
UTF-8
855
2.0625
2
[]
no_license
package com.stealthmode.planb; import android.app.Activity; import android.os.Bundle; import android.widget.TabHost; import android.widget.TabHost.TabSpec; public class LibraryTab extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.library); TabHost tbHost = (TabHost)findViewById(R.id.tabhost); tbHost.setup(); TabSpec specs = tbHost.newTabSpec("tag1"); specs.setContent(R.id.tab1); specs.setIndicator("ABC char"); tbHost.addTab(specs); specs = tbHost.newTabSpec("tag2"); specs.setContent(R.id.tab2); specs.setIndicator("ABC char 2.0"); tbHost.addTab(specs); specs = tbHost.newTabSpec("tag3"); specs.setContent(R.id.tab3); specs.setIndicator("ABC char 3.0"); tbHost.addTab(specs); } }
true
145d4fa8a8217334886087c128b60dcce84ad774
Java
NateBuckley/expense-reimbursement-asciibetical
/src/main/java/com/revature/repo/RequestDAOImpl.java
UTF-8
5,671
2.46875
2
[]
no_license
package com.revature.repo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import com.revature.models.ReimbursementStatus; import com.revature.models.ReimbursementType; import com.revature.models.Request; import com.revature.util.ConnectionFactory; public class RequestDAOImpl implements RequestDAO { @Override public Request selectRequestById(int id) { String sql = "SELECT * FROM reimbursement WHERE id = ?"; Request selectedRequestById = new Request(); try (Connection conn = ConnectionFactory.getConnection()) { PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); while (rs.next()) { selectedRequestById = new Request(rs.getInt("id"), rs.getString("user_username_fk"), ReimbursementType.valueOf(rs.getString("reimbursement_type")), rs.getDouble("amount"), rs.getString("description"), rs.getTimestamp("time_of_request"), ReimbursementStatus.valueOf(rs.getString("status"))); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return selectedRequestById; } @Override public List<Request> selectAllRequests() { String sql = "SELECT * FROM reimbursement"; List<Request> allRequests = new ArrayList<Request>(); try (Connection conn = ConnectionFactory.getConnection()) { PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { allRequests.add(new Request(rs.getInt("id"), rs.getString("user_username_fk"), ReimbursementType.valueOf(rs.getString("reimbursement_type")), rs.getDouble("amount"), rs.getString("description"), rs.getTimestamp("time_of_request"), ReimbursementStatus.valueOf(rs.getString("status")))); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return allRequests; } @Override public List<Request> selectRequestByUsername(String username) { String sql = "SELECT * FROM reimbursement WHERE user_username_fk = ?"; List<Request> employeeRequests = new ArrayList<Request>(); try (Connection conn = ConnectionFactory.getConnection()) { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ResultSet rs = ps.executeQuery(); while (rs.next()) { employeeRequests.add(new Request(rs.getInt("id"), rs.getString("user_username_fk"), ReimbursementType.valueOf(rs.getString("reimbursement_type")), rs.getDouble("amount"), rs.getString("description"), rs.getTimestamp("time_of_request"), ReimbursementStatus.valueOf(rs.getString("status")))); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return employeeRequests; } @Override public boolean updateRequestStatus(int id, ReimbursementStatus status) { boolean success = false; String sql = "UPDATE reimbursement SET status = ?::reimbursement_status WHERE id = ?;"; try (Connection conn = ConnectionFactory.getConnection()) { PreparedStatement updateStatus = conn.prepareStatement(sql); updateStatus.setString(1, status.name()); updateStatus.setInt(2, id); updateStatus.execute(); sql = "SELECT * FROM reimbursement WHERE id = ? AND status = ?::reimbursement_status"; PreparedStatement confirmUpdate = conn.prepareStatement(sql); confirmUpdate.setInt(1, id); confirmUpdate.setString(2, status.name()); success = confirmUpdate.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } @Override public boolean insertRequest(String username, ReimbursementType type, double amount, String description) { boolean success = false; Timestamp timeOfRequest = Timestamp.valueOf(LocalDateTime.now()); try (Connection conn = ConnectionFactory.getConnection()) { String sql = "INSERT INTO reimbursement(user_username_fk,reimbursement_type,amount,description,time_of_request,status) " + "VALUES( ?, ?::reimbursement_types, ?, ?, ?, ?::reimbursement_status );"; PreparedStatement insertStatement = conn.prepareStatement(sql); insertStatement.setString(1, username); insertStatement.setString(2, type.name()); insertStatement.setDouble(3, amount); insertStatement.setString(4, description); insertStatement.setTimestamp(5, timeOfRequest); insertStatement.setString(6, ReimbursementStatus.PENDING.name()); insertStatement.execute(); sql = "SELECT * FROM reimbursement WHERE user_username_fk = ? AND time_of_request = ?;"; PreparedStatement confirmInsert = conn.prepareStatement(sql); confirmInsert.setString(1, username); confirmInsert.setTimestamp(2, timeOfRequest); success = confirmInsert.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } @Override public boolean deleteRequest(int id) { boolean success = false; String sql = "DELETE FROM reimbursement WHERE id =?;"; try (Connection conn = ConnectionFactory.getConnection()) { PreparedStatement updateStatus = conn.prepareStatement(sql); updateStatus.setInt(1, id); updateStatus.execute(); sql = "SELECT * FROM reimbursement WHERE id = ?;"; PreparedStatement confirmDelete = conn.prepareStatement(sql); confirmDelete.setInt(1, id); success = !(confirmDelete.execute()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } }
true
133a509b9477fdeea52ba157344b0a3d2dc88872
Java
bradchao/bjava2
/src/tw/org/iii/java/Brad43.java
UTF-8
308
2.46875
2
[]
no_license
package tw.org.iii.java; import java.util.LinkedList; public class Brad43 { public static void main(String[] args) { LinkedList list = new LinkedList(); list.add(1); list.add(2); list.add(3); list.add(4); //list.add(7,5); System.out.println(list.toString()); } }
true
7636d2ebb11904b0dfb9a407c42f4f6ef20d16a3
Java
zhonglh/logisticsc
/WebSource/Distributor/src/com/yc/Controller/AppVersionInfoController.java
UTF-8
2,308
2.15625
2
[]
no_license
package com.yc.Controller; import java.io.File; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.servlet.ServletRequestContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.yc.Canstant.Constant; import com.yc.Entity.AppVersionInfo; import com.yc.Service.AppVersionInfoService; import com.yc.Tool.FengUtil; import com.yc.Tool.MD5; import net.dongliu.apk.parser.ApkParser; import net.dongliu.apk.parser.bean.ApkMeta; /** * app版本信息管理 * @Author:luojing * @2016年8月11日 下午3:13:22 */ @Controller public class AppVersionInfoController { @Autowired private AppVersionInfoService iAppVersionInfoService; /** * 查询版本信息 * @Author:luojing * @2016年8月11日 下午3:13:05 */ @RequestMapping("app/getVersion") public void getVersion(HttpServletRequest request,HttpServletResponse response){ try{ /*String path = request.getSession().getServletContext().getRealPath("/apk/xsl-yc.apk"); ApkParser apkParser = new ApkParser(path); ApkMeta apkMeta = apkParser.getApkMeta(); int versionCode = Integer.parseInt(request.getParameter("versionCode")); if(apkMeta.getVersionCode()>versionCode){ //有新版本 AppVersionInfo version = new AppVersionInfo(); version.setVersionCode(Integer.parseInt(apkMeta.getVersionCode().toString())); File file = new File(path); version.setReleaseTime(file.lastModified()+""); version.setLatestMd5(MD5.md5sum(path)); version.setFileSize(file.length()+""); version.setVersionName(apkMeta.getVersionName()); version.setFileUri(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/apk/xsl-yc.apk"); version.setChangeLog(""); FengUtil.OUTAPPSUCCESS(Constant.APP_SUCCESS, version, response); }else{ FengUtil.RuntimeExceptionFeng("当前为最新版本"); }*/ }catch(Exception e){ e.printStackTrace(); FengUtil.OUTAPPERROR(Constant.APP_ERROR, e.getMessage(), response); } } }
true
26c188d85e2b05e3a92d8e23d670a33b0ee0ae0d
Java
11figure/CrazyJAVA
/src/Chapter6/closureTest/Teachable.java
UTF-8
568
3.15625
3
[]
no_license
package Chapter6.closureTest; /** * @Author: LevenLiu * @Description: * @Date: Create 0:41 2017/9/10 * @Modified By: */ public interface Teachable { void work(); } class Programmer { private String name; //Programmer 类的两个构造器 public Programmer(){}; public Programmer(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void work() { System.out.println(name + "敲键盘"); } }
true
627b0362e722ecbc161fc94317a0f369e8b3a469
Java
jiafan940618/Repository
/guangfu-2/src/main/java/creater/CreateUtil.java
UTF-8
1,369
2.46875
2
[]
no_license
package creater; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import utils.FileUtil; import utils.StrUtil; import utils.XFileUtils; public class CreateUtil { public static void createEntity2(String packagePath, String tableName, String domainObjectName) { String path = System.getProperty("user.dir") + StrUtil.codePath + packagePath.replaceAll("\\.", "/"); path = StrUtil.createFileDir(packagePath, path,"/util/"); String resPath = path+ "ObjToMap.java"; try { File file = new File("src/main/java/template/ObjToMap.java"); FileUtils.copyFile(file, new File(resPath)); } catch (IOException e) { e.printStackTrace(); } } public static void createEntity(String packagePath, String tableName, String domainObjectName) { String readFileByLines = FileUtil.readFileByLines("src/main/java/template/ObjToMap.java"); String content = readFileByLines.replace("package template;", "package " + packagePath + ".util;\r\n\r\n"); String path = System.getProperty("user.dir") + StrUtil.codePath + packagePath.replaceAll("\\.", "/"); path = StrUtil.createFileDir(packagePath, path,"/util/"); String resPath = path+ "ObjToMap.java"; try { XFileUtils.writStringToFile2(content, resPath); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
09300d9a1cafa7185ff79a667971d7563020ef5b
Java
cha63506/CompSecurity
/Photography/amazon_photos_source/src/com/amazon/gallery/framework/gallery/video/captioning/SubtitleFormat.java
UTF-8
1,185
2.078125
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.amazon.gallery.framework.gallery.video.captioning; public final class SubtitleFormat extends Enum { private static final SubtitleFormat $VALUES[]; public static final SubtitleFormat VTT; private final String extension; private final String mimeType; private SubtitleFormat(String s, int i, String s1, String s2) { super(s, i); mimeType = s1; extension = s2; } public static SubtitleFormat valueOf(String s) { return (SubtitleFormat)Enum.valueOf(com/amazon/gallery/framework/gallery/video/captioning/SubtitleFormat, s); } public static SubtitleFormat[] values() { return (SubtitleFormat[])$VALUES.clone(); } public String getExtension() { return extension; } public String getMimeType() { return mimeType; } static { VTT = new SubtitleFormat("VTT", 0, "text/vtt", ".vtt"); $VALUES = (new SubtitleFormat[] { VTT }); } }
true
5effebc391e7aa2b9edabeeb41b91430357a75ad
Java
yr569416310/pager
/pager/src/com/imooc/page/servlet/HibernateDataServlet.java
GB18030
2,482
2.34375
2
[]
no_license
package com.imooc.page.servlet; import java.io.IOException; import java.io.Writer; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import com.imooc.page.Constant; import com.imooc.page.model.Pager; import com.imooc.page.model.Student; import com.imooc.page.service.HibernateStudentServiceImpl; import com.imooc.page.service.StudentService; public class HibernateDataServlet extends HttpServlet { private static final long serialVersionUID = -4873699362194465829L; private StudentService studentService = new HibernateStudentServiceImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //requestIJ String stuName = request.getParameter("stuName"); int gender = Constant.DEFAULT_GENDER; String genderStr = request.getParameter("gender"); if(genderStr!=null&&!"".equals(genderStr.trim())){ gender = Integer.parseInt(genderStr); } String pageNumStr = request.getParameter("pageNum"); int pageNum = Constant.DEFAULT_PAGE_NUM; if(pageNumStr!=null&&!"".equals(pageNumStr.trim())){ pageNum = Integer.parseInt(pageNumStr); } int pageSize = Constant.DEFAULT_PAGE_SIZE; String pageSizeStr = request.getParameter("pageSize"); if(pageSizeStr!=null&&!"".equals(pageSizeStr.trim())){ pageSize = Integer.parseInt(pageSizeStr); } //װѯ Student searchModel = new Student(); searchModel.setStuName(stuName); searchModel.setGender(gender); //serviceȡѯ Pager<Student> result = studentService.findStudent(searchModel, pageNum, pageSize); //ʹû response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); //óʱʱΪ0 response.addDateHeader("Expires", 0); //ñʽΪutf-8 response.setContentType("text/html;charset=utf-8"); //ȡѯݵjsonʽ String responseStr = JSON.toJSONString(result); Writer writer = response.getWriter(); writer.write(responseStr); writer.flush(); } }
true
e6afa17ced8304d7465b880e9e25123544d4e202
Java
erikmellum/MedievalConquest
/current/Armor.java
UTF-8
2,745
3.1875
3
[ "BSD-3-Clause" ]
permissive
/** * Armor is-a Item created to allow the user an equippable item to negate the damage taken * It provides methods for changing the protection and getting the protection. * * @author Erik Mellum * @version 1.0 */ import java.util.HashMap; import java.io.Serializable; public class Armor extends Equippable { protected HashMap<String, HashMap> armor; public Armor() { name = "Clothes"; description = "Hardly any protection, and very itchy."; location = "Chest"; equippable = true; droppable = true; buildArmor(); } public Armor(String newName, String newLocation) { name = newName; description = "No Description"; location = newLocation; equippable = true; droppable = true; buildArmor(); } public Armor(String newName, String newDescription, String newLocation) { name = newName; description = newDescription; location = newLocation; equippable = true; droppable = true; buildArmor(); } public Armor(String newName, String newDescription, String newLocation, int protection, int value, int weight, int number, int level, int quantity, int type) { equip = armor = new HashMap<String, HashMap>(); name = newName; description = newDescription; location = newLocation; stats.put("Protection",new Stat("Protection",protection)); stats.get("Value").setValue(value); stats.get("Weight").setValue(weight); stats.get("Number").setValue(number); stats.get("Level").setValue(level); stats.get("Quantity").setValue(quantity); stats.put("Type",new Stat("Type",type)); } public Armor(String newName, String newDescription, String newLocation, HashMap<String, Effect> newEffects, HashMap<String, Augment> newAugments, HashMap<String, Enchant> newEnchants, int protection, int value, int weight, int number, int level, int quantity, int type) { equip = armor = new HashMap<String, HashMap>(); name = newName; description = newDescription; location = newLocation; effects = newEffects; augments = newAugments; enchants = newEnchants; stats.put("Protection",new Stat("Protection",protection)); stats.get("Value").setValue(value); stats.get("Weight").setValue(weight); stats.get("Number").setValue(number); stats.get("Level").setValue(level); stats.get("Quantity").setValue(quantity); stats.put("Type",new Stat("Type",type)); } public void buildArmor() { equip = armor = new HashMap<String, HashMap>(); stats.put("Protection",new Stat("Protection",1)); stats.get("Value").setValue(1); stats.get("Weight").setValue(1); stats.get("Number").setValue(1); stats.get("Level").setValue(1); stats.get("Quantity").setValue(1); } }
true
885f8dcfd00a1c3ba140946297a4384acd4bbee0
Java
dji-sdk/Mobile-UXSDK-Beta-Android
/android-uxsdk-beta-sample/src/main/java/com/dji/ux/beta/sample/util/MapUtil.java
UTF-8
2,685
2.015625
2
[ "MIT" ]
permissive
/* * Copyright (c) 2018-2020 DJI * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.dji.ux.beta.sample.util; import android.content.Context; import android.os.Build; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import dji.log.DJILog; /** * Utility class for maps. */ public final class MapUtil { private static final String TAG = "MapUtil"; private MapUtil() { // Util class } /** * HERE Maps are supported by ARM V7 and AMR V8 devices. They are not supported by x86 or mips * devices. * * @return `true` if HERE Maps are supported by this device. */ public static boolean isHereMapsSupported() { String abi; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { abi = Build.CPU_ABI; } else { abi = Build.SUPPORTED_ABIS[0]; } DJILog.d(TAG, "abi=" + abi); //The possible values are armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips, mips64. return abi.contains("arm"); } /** * Google maps are supported only if Google Play Services are available on this device. * * @param context An instance of {@link Context}. * @return `true` if Google Maps are supported by this device. */ public static boolean isGoogleMapsSupported(Context context) { GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance(); int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context); return resultCode == ConnectionResult.SUCCESS; } }
true
40f45c572f48c5852b0bc64aaad1b8f3e61efa3a
Java
icecooly/SmartJdbc
/src/main/java/io/itit/smartjdbc/enums/OrderByType.java
UTF-8
128
1.507813
2
[]
no_license
/** * */ package io.itit.smartjdbc.enums; /** * * @author skydu * */ public enum OrderByType { ASC, DESC ; }
true
08e6b46703e1242b4221dc264c9e1b0a08732f5b
Java
501658362/Robot
/lol/src/test/java/top/chenyanjin/robot/lol/service/ClientServiceTest.java
UTF-8
1,389
2.140625
2
[]
no_license
//package top.chenyanjin.robot.lol.service; // //import com.sun.jna.platform.win32.WinDef; //import org.junit.Test; //import top.chenyanjin.robot.lol.enums.WindowNameEnum; //import top.chenyanjin.robot.lol.thread.GlobalData; //import top.chenyanjin.robot.lol.thread.MatchingGame; //import top.chenyanjin.robot.lol.thread.SelectHeroGame; //import top.chenyanjin.robot.lol.util.DelayUtil; //import top.chenyanjin.robot.lol.util.WinUtil; // //import static org.junit.Assert.*; // //public class ClientServiceTest { // // @org.junit.Before // public void setUp() throws Exception { // for (WindowNameEnum value : WindowNameEnum.values()) { // WinDef.HWND game = WinUtil.findWindow(value); // if (game != null ) { // GlobalData.mode.set(value.getMode()); // GlobalData.hwnd = game; // break; // } // } // } // // @org.junit.Test // public void run() { //// ClientService clientService = new ClientService(); //// clientService.run(); // // } // // @Test // public void t() { //// MatchingGame matchingGame = new MatchingGame(); //// matchingGame.start(); //// SelectHeroGame selectHeroGame = new SelectHeroGame(); //// selectHeroGame.start(); //// while (true){ //// DelayUtil.delay(3000L); //// } // } //}
true
07d5af0782e8d36d35771aabd6695d2fa4b2dc6d
Java
LempDnote/MC2
/GrafoRegular/src/main/java/Elementos/Temporal.java
UTF-8
897
3.09375
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 Elementos; /** * * @author Eduardo */ public class Temporal { Nodo cabeza; public Temporal(Nodo cabeza) { this.cabeza = cabeza; } public int Grado(){ Nodo aux = this.cabeza; int grado = 0; while(aux != null){ if(aux.datos.getGrado() > grado){ // System.out.println("______________________"); // System.out.println(aux.datos.getNumero()); // System.out.println(aux.datos.getGrado()); // System.out.println("_______________________"); grado = aux.datos.getGrado(); } aux = aux.getSiguiente(); } return grado; } }
true
54439f0ade600642110a092a110b50d316383222
Java
wcmbeta/java-web
/spring_mvc/src/com/water/pojo/User.java
UTF-8
2,180
2.46875
2
[ "Apache-2.0" ]
permissive
package com.water.pojo; import java.io.Serializable; public class User implements Serializable{ private String uid; private String name; private String email; private String phone; private String sex; private int state; private String username; private String password; private int age; private int id; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "User{" + "uid='" + uid + '\'' + ", name='" + name + '\'' + ", email='" + email + '\'' + ", phone='" + phone + '\'' + ", sex='" + sex + '\'' + ", state=" + state + ", username='" + username + '\'' + ", password='" + password + '\'' + ", age=" + age + ", id=" + id + '}'; } }
true
298813effe02a5853f73a100c97620959ca225f3
Java
tnus/keycloak-offline-client
/src/main/java/de/nuss/keycloak/client/JWTTokenResolver.java
UTF-8
3,830
2.421875
2
[ "Apache-2.0" ]
permissive
package de.nuss.keycloak.client; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedHashMap; import org.keycloak.util.TokenUtil; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import lombok.extern.slf4j.Slf4j; /** * This class can be used to resolve an open id token. * * @author Thorsten Nuss * */ @Slf4j public class JWTTokenResolver { public static final String AUTHORIZATION_HEADER = "Authorization"; private String authServerUrl; private String clientId; private String realm; private String accessToken; private String refreshToken; private String username; private String password; private JWTTokenResolver(String authServerUrl, String realm, String clientId) { this.authServerUrl = authServerUrl; this.realm = realm; this.clientId = clientId; } public JWTTokenResolver(String authServerUrl, String realm, String clientId, String username, String password) { this(authServerUrl, realm, clientId); this.username = username; this.password = password; } public JWTTokenResolver(String authServerUrl, String realm, String clientId, String offlineToken) { this(authServerUrl, realm, clientId); this.refreshToken = offlineToken; } /** * This method can be used to resolve the access token * * @return */ public String getAccessToken() { try { // check if access token is present and not expired if (accessToken != null && !TokenUtil.getRefreshToken(accessToken).isExpired()) { return accessToken; } RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> mapForm = new LinkedMultiValueMap<>(); mapForm.add("client_id", clientId); // access token must be generated if (refreshToken != null && !TokenUtil.getRefreshToken(refreshToken).isExpired()) { log.debug("create new access token"); mapForm.add("grant_type", "refresh_token"); mapForm.add("refresh_token", refreshToken); } else { // use username and password mapForm.add("grant_type", "password"); mapForm.add("username", username); mapForm.add("password", password); } HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(mapForm, headers); ResponseEntity<Object> response = restTemplate.exchange(getAuthServerURI(), HttpMethod.POST, request, Object.class); if (!HttpStatus.OK.equals(response.getStatusCode())) { throw new IllegalStateException(response.getStatusCodeValue() + ": " + response.getBody().toString()); } LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) response.getBody(); this.accessToken = (String) map.get("access_token"); String tokenType = (String) map.get("token_type"); this.refreshToken = (String) map.get("refresh_token"); int expires_in = (int) map.get("expires_in"); String scope = (String) map.get("scope"); log.trace("accesstoken: {}", accessToken); log.trace("tokenType: {}", tokenType); log.trace("refreshToken: {}", refreshToken); log.trace("expires_in: {}", expires_in); log.trace("scope: {}", scope); return accessToken; } catch (Exception e) { throw new IllegalStateException("access token cannot be retrieved!", e); } } private URI getAuthServerURI() throws URISyntaxException { return new URI(authServerUrl + "/realms/" + realm + "/protocol/openid-connect/token"); } }
true
de111cd04de8dd3b0105d5fef0ad196c8cc06b9e
Java
difr/msm8937-8953_qcom_vendor
/mm-audio/voiceprint/apps/demo/src/com/qualcomm/qti/biometrics/voiceprint/voiceprintdemo/data/KeyPhraseAction.java
UTF-8
1,592
2.1875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright (c) 2015 Qualcomm Technologies, Inc. * All Rights Reserved. * Confidential and Proprietary - Qualcomm Technologies, Inc. */ package com.qualcomm.qti.biometrics.voiceprint.voiceprintdemo.data; import android.content.pm.ResolveInfo; /* * The Class KeyPhraseAction. */ public class KeyPhraseAction { // These must be unique. // Make sure to not change these as the database stores the ids. public static final int NO_ACTION = -1; public static final int EMAIL = 0; public static final int BROWSER = 1; public static final int SMS = 2; private int mAction = NO_ACTION; private String mActionName = null; private ResolveInfo mResolveInfo = null; public KeyPhraseAction(){ this(NO_ACTION); } public KeyPhraseAction(int action) { mActionName = action == EMAIL ? "EMAIL" : action == BROWSER ? "BROWSER" : action == SMS ? "SMS" : "NO_ACTION"; } public static KeyPhraseAction getDefault() { return new KeyPhraseAction(NO_ACTION); } public KeyPhraseAction(int action, String name, ResolveInfo info) { mAction = action; mActionName = name; mResolveInfo = info; } public String getActionName() { return mActionName == null ? "NO_ACTION" : mActionName; } public ResolveInfo getResolveInfo() { return mResolveInfo; } @Override public String toString() { return mActionName; } public int getId() { return mAction; } }
true
203eca0d060e0f47ee03fcabd1dab6705a3615fa
Java
cogbin/sprited
/core/src/main/java/eu/cogbin/sprited/core/io/impl/BufferedImageDeserializer.java
UTF-8
841
2.21875
2
[ "BSD-3-Clause" ]
permissive
package eu.cogbin.sprited.core.io.impl; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.imageio.ImageIO; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.DeserializationContext; import org.codehaus.jackson.map.deser.std.StdDeserializer; /** * * @author Danny * */ public class BufferedImageDeserializer extends StdDeserializer<BufferedImage> { public BufferedImageDeserializer() { super(BufferedImage.class); } @Override public BufferedImage deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { byte[] bytes = jp.getBinaryValue(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); return ImageIO.read(in); } }
true
444b3ff8480103a92145d5d5a9e201f3cacf0d2b
Java
ytl2009/CustomView
/app/src/main/java/com/ytl/customview/widget/timer/MessageHandler.java
UTF-8
1,050
2.390625
2
[]
no_license
package com.ytl.customview.widget.timer; import android.os.Handler; import android.os.Message; import com.ytl.customview.widget.view.WheelView; /** * package:com.ytl.customview.widget.timer * description: * author: ytl * date:18.4.27 8:58. */ public class MessageHandler extends Handler { private WheelView mWheelView; public static final int INVALIDATE_WHEEL_VIEW = 1000; public static final int SMOOTH_FLING = 2000; public static final int ITEM_SELECTED = 3000; public MessageHandler(WheelView wheelView) { mWheelView = wheelView; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case INVALIDATE_WHEEL_VIEW: mWheelView.invalidate(); break; case SMOOTH_FLING: mWheelView.smoothScroll(WheelView.ActionEvent.FLING); break; case ITEM_SELECTED: mWheelView.onItemSelected(); break; } } }
true
7e08d840b8b81475f7f8474332b1e2c141eb201e
Java
gsonigithub/Chordiant
/src/main/java/com/vodacom/chordiant/reporting/mvc/view/MaterialisedView.java
UTF-8
885
2.078125
2
[]
no_license
package com.vodacom.chordiant.reporting.mvc.view; public class MaterialisedView { private String objectName; private String objectType; private String lastDdl; /** * @return the objectName */ public String getObjectName() { return objectName; } /** * @param objectName * the objectName to set */ public void setObjectName(String objectName) { this.objectName = objectName; } /** * @return the objectType */ public String getObjectType() { return objectType; } /** * @param objectType * the objectType to set */ public void setObjectType(String objectType) { this.objectType = objectType; } /** * @return the lastDdl */ public String getLastDdl() { return lastDdl; } /** * @param lastDdl * the lastDdl to set */ public void setLastDdl(String lastDdl) { this.lastDdl = lastDdl; } }
true
c4d5456e593e6875e0f4614ae64ead732cbc2f68
Java
rohitchaitanya7/Vert.X-CTS-Aug-21
/functional-gettingstarted/src/main/java/com/cts/fp/higherorderfun/HttpHandler.java
UTF-8
100
1.71875
2
[]
no_license
package com.cts.fp.higherorderfun; public interface HttpHandler<T> { void handle(T payload); }
true
cc6ded67a864b0975b913c3e15c669968ac1927b
Java
gngpp/wallpaper
/src/test/java/SerializeTest.java
UTF-8
1,480
2.265625
2
[ "Apache-2.0" ]
permissive
import com.zf1976.wallpaper.datasource.DbStoreUtil; import com.zf1976.wallpaper.datasource.NetbianStoreStrategy; import com.zf1976.wallpaper.entity.NetbianEntity; import io.vertx.core.file.FileSystem; import io.vertx.core.file.impl.FileSystemImpl; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public class SerializeTest { public static void main(String[] args) { try (Connection connection = DbStoreUtil.createConnection()) { final var resultSet = connection.prepareStatement("select * from index_entity") .executeQuery(); final var netbianStoreStrategy = new NetbianStoreStrategy(); while (resultSet.next()) { final var netbianEntity = new NetbianEntity() .setDataId(resultSet.getString("data_id")) .setName(resultSet.getString("name")) .setType(resultSet.getString("type")) .setId(resultSet.getInt("id")); netbianStoreStrategy.store(netbianEntity); } } catch (SQLException | ClassNotFoundException ignored) { } } @Test public void readTest() { final var netbianStoreStrategy = new NetbianStoreStrategy(); netbianStoreStrategy.read().forEach(System.out::println); System.out.println(netbianStoreStrategy.container("5055")); } }
true
0123a68003da587c380674d0110beece89991e7d
Java
lianqiangjava/BadNews
/app/src/main/java/com/lianqiang/badnews/base/BaseViewHolder.java
UTF-8
1,566
2.296875
2
[]
no_license
package com.lianqiang.badnews.base; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lianqiang.badnews.R; /** * Describe: * * @author lianqiang on 2017/5/28. */ public class BaseViewHolder extends RecyclerView.ViewHolder { private SparseArray<View> mViews; private View mItemView; private Context mContext; private TextView tv; public BaseViewHolder(Context context,View itemView) { super(itemView); mContext = context; mItemView = itemView; mViews = new SparseArray<>(); tv = (TextView) itemView.findViewById(R.id.live_list_status); } public static BaseViewHolder get(Context context, ViewGroup parent,int layoutId){ View itemView = LayoutInflater.from(context).inflate(layoutId,parent,false); BaseViewHolder viewHolder = new BaseViewHolder(context,itemView); return viewHolder; } public View getItemView(){ return mItemView; } public <T extends View> T getView(int viewId){ View view = mViews.get(viewId); if(view == null){ view = mItemView.findViewById(viewId); mViews.put(viewId,view); } return (T)view; } public BaseViewHolder setText(int viewId,String text){ TextView textView = getView(viewId); textView.setText(text); return this; } }
true
1c41eb64fcddb29d8a12081100553fcecaa18ed2
Java
zjgyjd/JavaLearn
/javalern/ele25/Test.java
UTF-8
454
2.59375
3
[]
no_license
package com.github.zjgyjd; public class Test { private Object data; private Test next; public Test(Object data, Test next) { this.data = data; this.next = next; } public Object getData() { return data; } public Test getNext() { return next; } public void setData(Object data) { this.data = data; } public void setNext(Test next) { this.next = next; } }
true
69c569aaf71c440c93eee10f43c9f71d164c2b52
Java
ralphsa95/PROJETC2-2018
/src/java/beans/LoginBean.java
UTF-8
3,586
2.140625
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 beans; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import objects.Login; import operation.SessionBean; import session.SessionUtil; /** * * @author Hp */ @ManagedBean @SessionScoped public class LoginBean { private String pwd; private String msg; private String user; private String name; SessionBean sessionBean = new SessionBean(); public LoginBean() { } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public void setName(String name) { this.name = name; } public String validateUsernamePassword() throws SQLException { boolean valid = Login.validate(user, pwd); if (valid) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest origRequest = (HttpServletRequest) context.getExternalContext().getRequest(); String contextPath = origRequest.getContextPath(); try { FacesContext.getCurrentInstance().getExternalContext() .redirect(contextPath + "/faces/home.xhtml"); sessionBean.insertUserLog(user,"I"); } catch (IOException e) { e.printStackTrace(); } return "home"; } else { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Incorrect Username or Passowrd", "Please enter correct username and Password")); return "login"; } } public String getName() { return SessionUtil.getName(); } public String getUserCode() { return SessionUtil.getUserCode(); } public String getYear() { return SessionUtil.getYear(); } public String getSemester() { return SessionUtil.getSemester(); } public String logout() throws SQLException { HttpSession session = SessionUtil.getSession(); sessionBean.insertUserLog(SessionUtil.getUserName(),"U"); session.invalidate(); return "login"; } public boolean isAdmin() { return "A".equalsIgnoreCase(SessionUtil.getUserRole()); } public boolean isTeacher() { return "T".equalsIgnoreCase(SessionUtil.getUserRole()); } public boolean isHead() { return "H".equalsIgnoreCase(SessionUtil.getUserRole()); } public boolean isStudent() { return "S".equalsIgnoreCase(SessionUtil.getUserRole()); } }
true
5f3ffff725a380e647afba777d951fb439cfecf9
Java
Jimut123/code-backup
/java_backup/my java/siddhartha/Siddhartha/Digits.java
UTF-8
282
2.703125
3
[ "MIT" ]
permissive
public class Digits {public static void main(int n) { int c=5,i,j,a,k,s; for ( i=1;i<=n;i++) { s=0; for ( j=i;j<=n;j++) { s=s+j; if(s==n) { for(k=i;k<=j;k++) System.out.print(k+" "); System.out.println(); break; } else if(s>n) { break; } } } } }
true
b49d2ef1be456fd3ada90208f61d5744cf782801
Java
Wallart/RobotsBoxes
/src/fr/ups/m2dl/sma/dm/start/StartGui.java
UTF-8
273
1.570313
2
[]
no_license
/** * */ package fr.ups.m2dl.sma.dm.start; import fr.ups.m2dl.sma.dm.gui.swing.GuiRunnableComponentImpl; /** * @author SERIN Kevin * */ public class StartGui { public static void main(String[] args) { new GuiRunnableComponentImpl().newComponent().run().run(); } }
true
573dc3742c384d576a6f5a69136f948a991e518a
Java
brendarlq/equipo-medico
/src/main/java/com/mantenimiento/equipomedico/app/entidad/Repuesto.java
UTF-8
5,425
2.046875
2
[]
no_license
package com.mantenimiento.equipomedico.app.entidad; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; /** * Repuesto para el equipo. * * @author Brenda Quiñonez * */ @Entity @Table(name = "repuesto") public class Repuesto implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name = "id") private Long id; @Column(name = "codigo", unique = true) private String codigo; @Column(name = "descripcion_articulo") private String descripcionArticulo; @Column(name = "precio") private Float precio; @Column(name = "fecha_actualizacion") private Date fechaActualizacion; @Column(name = "cantidad_adquirida") private Integer cantidadAdquirida; @Column(name = "cantidad_existente") private Integer cantidadExistente; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="tipo_equipo_id") private TipoEquipo tipoEquipo; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="modelo_equipo_id") private Modelo modelo; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="marca_equipo_id") private Marca marca; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="representante_id") private Representante representante; @ManyToMany(mappedBy = "repuestos") @JsonIgnore List<Contrato> contratos; /** * Gets id * * @return value of id */ public Long getId() { return id; } /** * Set id * * @param id */ public void setId(Long id) { this.id = id; } /** * Gets codigo * * @return value of codigo */ public String getCodigo() { return codigo; } /** * Set codigo * * @param codigo */ public void setCodigo(String codigo) { this.codigo = codigo; } /** * Gets descripcionArticulo * * @return value of descripcionArticulo */ public String getDescripcionArticulo() { return descripcionArticulo; } /** * Set descripcionArticulo * * @param descripcionArticulo */ public void setDescripcionArticulo(String descripcionArticulo) { this.descripcionArticulo = descripcionArticulo; } /** * Gets precio * * @return value of precio */ public Float getPrecio() { return precio; } /** * Set precio * * @param precio */ public void setPrecio(Float precio) { this.precio = precio; } /** * Gets fechaActualizacion * * @return value of fechaActualizacion */ public Date getFechaActualizacion() { return fechaActualizacion; } /** * Set fechaActualizacion * * @param fechaActualizacion */ public void setFechaActualizacion(Date fechaActualizacion) { this.fechaActualizacion = fechaActualizacion; } /** * Gets cantidadAdquirida * * @return value of cantidadAdquirida */ public Integer getCantidadAdquirida() { return cantidadAdquirida; } /** * Set cantidadAdquirida * * @param cantidadAdquirida */ public void setCantidadAdquirida(Integer cantidadAdquirida) { this.cantidadAdquirida = cantidadAdquirida; } /** * Gets cantidadExistente * * @return value of cantidadExistente */ public Integer getCantidadExistente() { return cantidadExistente; } /** * Set cantidadExistente * * @param cantidadExistente */ public void setCantidadExistente(Integer cantidadExistente) { this.cantidadExistente = cantidadExistente; } /** * Gets tipoEquipo * * @return value of tipoEquipo */ public TipoEquipo getTipoEquipo() { return tipoEquipo; } /** * Set tipoEquipo * * @param tipoEquipo */ public void setTipoEquipo(TipoEquipo tipoEquipo) { this.tipoEquipo = tipoEquipo; } /** * Gets representante * * @return value of representante */ public Representante getRepresentante() { return representante; } /** * Set representante * * @param representante */ public void setRepresentante(Representante representante) { this.representante = representante; } /** * Gets modelo * * @return value of modelo */ public Modelo getModelo() { return modelo; } /** * Set modelo * * @param modelo */ public void setModelo(Modelo modelo) { this.modelo = modelo; } /** * Gets marca * * @return value of marca */ public Marca getMarca() { return marca; } /** * Set marca * * @param marca */ public void setMarca(Marca marca) { this.marca = marca; } /** * Gets contratos * * @return value of contratos */ public List<Contrato> getContratos() { return contratos; } /** * Set contratos * * @param contratos */ public void setContratos(List<Contrato> contratos) { this.contratos = contratos; } }
true
5c7a5415d559059a0e335af5322fd7f56e4fed0a
Java
araceli-garcia/RolDeJuegosJPAPSQL
/src/service/CampeonServiceImpl.java
UTF-8
834
2.3125
2
[]
no_license
package service; import dao.CampeonDao; import dao.CampeonDaoImpl; import java.util.List; import model.Campeon; public class CampeonServiceImpl implements CampeonService{ private CampeonDao campeonDao = new CampeonDaoImpl(); @Override public void crearRegistro(Campeon campeon) { campeonDao.crearRegistro(campeon); } @Override public void eliminarRegistro(Campeon campeon) { campeonDao.eliminarRegistro(campeon); } @Override public void actualizarRegistro(Campeon campeon) { campeonDao.actualizarRegistro(campeon); } @Override public List<Campeon> obtenerRegistros() { return campeonDao.obtenerRegistros(); } @Override public Campeon obtenerRegistro(Long idCampeon) { return campeonDao.obtenerRegistro(idCampeon); } }
true
400a77561edc4533dab72440946716706430dce1
Java
snehadubey/Gui_projectapplication
/Gui_Interface.java
UTF-8
25,760
2.078125
2
[]
no_license
package Image_display; import java.awt.Color; import java.awt.Font; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; /** * * @author KAVYA JANARDHANA */ public class Gui_Interface extends javax.swing.JFrame { private int param_max_count; private String arr[]; static int[] cols; private final DefaultListModel leftlist; private final DefaultListModel rightlist; public static progres_bar p1 = null; static boolean obj_exists=false; public static Irig_graph Irig_g = null; public static Irig_graph_Img Irig_g_p = null; public static Irig_slide_img Irig_s = null; public static String delimeter="\t"; Gui_Interface() { initComponents(); this.rightlist = new DefaultListModel(); this.leftlist = new DefaultListModel(); select_radio_Group.add(jRadio_slide); select_radio_Group.add(jRadio_slide); } /** * 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() { select_radio_Group = new javax.swing.ButtonGroup(); add_jbutton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); parameter_jList = new javax.swing.JList<>(); jScrollPane2 = new javax.swing.JScrollPane(); para_selected_jList2 = new javax.swing.JList<>(); jTextField1 = new javax.swing.JTextField(); parameter_jButton = new javax.swing.JButton(); remove_jbutton = new javax.swing.JButton(); jTextField2 = new javax.swing.JTextField(); image_folder_jButton = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); load_jbutton = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jRadio_slide = new javax.swing.JRadioButton(); jRadio_graph = new javax.swing.JRadioButton(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Video & Text"); setForeground(java.awt.Color.gray); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); add_jbutton.setText("ADD"); add_jbutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { add_jbuttonActionPerformed(evt); } }); parameter_jList.setFont(new java.awt.Font("Tahoma", 2, 12)); // NOI18N jScrollPane1.setViewportView(parameter_jList); para_selected_jList2.setFont(new java.awt.Font("Tahoma", 2, 12)); // NOI18N jScrollPane2.setViewportView(para_selected_jList2); parameter_jButton.setText("Attach"); parameter_jButton.setToolTipText("Select Text File"); parameter_jButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { parameter_jButtonActionPerformed(evt); } }); remove_jbutton.setText("Remove"); remove_jbutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { remove_jbuttonActionPerformed(evt); } }); image_folder_jButton.setText("Attach"); image_folder_jButton.setToolTipText("Select Image Folder"); image_folder_jButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { image_folder_jButtonActionPerformed(evt); } }); jLabel1.setText("Parameters from text file"); jLabel2.setText("Selected Parameters "); load_jbutton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N load_jbutton.setText("Load"); load_jbutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { load_jbuttonActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("Select the Image Folder : "); select_radio_Group.add(jRadio_slide); jRadio_slide.setText("Parameters"); select_radio_Group.add(jRadio_graph); jRadio_graph.setText("Graph"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("Select the Text file :"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(image_folder_jButton)) .addGroup(layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(parameter_jButton)) .addComponent(jLabel3) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(load_jbutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(add_jbutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(remove_jbutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadio_graph) .addComponent(jRadio_slide)))) .addGap(14, 14, 14) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(35, 35, 35)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(49, Short.MAX_VALUE) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(image_folder_jButton) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(parameter_jButton)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE) .addComponent(jScrollPane1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(62, 62, 62) .addComponent(add_jbutton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(remove_jbutton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE) .addComponent(jRadio_slide) .addGap(9, 9, 9) .addComponent(jRadio_graph) .addGap(18, 18, 18) .addComponent(load_jbutton) .addGap(36, 36, 36)))) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void add_jbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_jbuttonActionPerformed // TODO add your handling code here: int[] selectedIx = parameter_jList.getSelectedIndices(); //System.out.println("selectedIx: "+selectedIx); //System.out.println("selectedIx.length:"+selectedIx.length); //System.out.println("rightlist.getSize():"+rightlist.getSize()); if(parameter_jList.getSelectedValue()==null) { JOptionPane.showMessageDialog(null, "Select the parameter"); } String item_at_index; for (int i = 0; i < selectedIx.length; i++) { item_at_index =parameter_jList.getModel().getElementAt(selectedIx[i]); if(!(rightlist.contains(item_at_index))){ rightlist.addElement(item_at_index); } } para_selected_jList2.setModel(rightlist); }//GEN-LAST:event_add_jbuttonActionPerformed private void parameter_jButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_parameter_jButtonActionPerformed //jList1.repaint(); //parameter_jList.removeAll(); //parameter_jList.repaint(); final JFileChooser text_file = new JFileChooser(); text_file.setDialogTitle("Select Parameter text file"); text_file.setCurrentDirectory(new java.io.File(".")); FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text"); text_file.setFileFilter(filter); //text_file.showOpenDialog(null); // For File File file_open=null; text_file.setFileSelectionMode(JFileChooser.FILES_ONLY); text_file.setAcceptAllFileFilterUsed(false); text_file.setApproveButtonText("Select"); text_file.setForeground(new Color(200, 255, 255)); text_file.setFont(new Font("Trebuchet MS", Font.PLAIN, 12)); if(text_file.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){ file_open=text_file.getSelectedFile(); if(file_open!=null){ rightlist.removeAllElements(); leftlist.removeAllElements(); parameter_jList.setModel(leftlist); para_selected_jList2.setModel(rightlist); jTextField1.setText(""); jTextField1.setText(file_open.getAbsolutePath()); populate_parameter2(); } }//else file not selected text_file.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { if(e.getClickCount()==2){ File file_click=text_file.getSelectedFile(); if(file_click!=null){ rightlist.removeAllElements(); leftlist.removeAllElements(); parameter_jList.setModel(leftlist); para_selected_jList2.setModel(rightlist); jTextField1.setText(""); jTextField1.setText(file_click.getAbsolutePath()); populate_parameter2(); } } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); }//GEN-LAST:event_parameter_jButtonActionPerformed private void populate_parameter(){ Scanner s1 = null; int i=0; int j=0; try { s1 = new Scanner(new File(jTextField1.getText())); s1.nextLine(); s1.nextLine(); arr= s1.nextLine().split("\t"); //System.out.println("Number of parameters are: "+arr.length); param_max_count= arr.length; for(i=1;i<arr.length;i++){ leftlist.addElement(arr[i]); } parameter_jList.setModel(leftlist); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "File is not found"); } finally{ s1.close(); } // System.out.println(j); } private void populate_parameter2(){ Scanner s1 = null; int i=0; int j=0; try { s1 = new Scanner(new File(jTextField1.getText())); String line= s1.nextLine(); int pos; if((pos=line.lastIndexOf(";"))!=-1){ arr= line.substring(pos+1,line.length()).split(delimeter); } else{ arr= line.split(delimeter); i=1; } param_max_count= arr.length; while(i<arr.length){ leftlist.addElement(arr[i]); i++; } parameter_jList.setModel(leftlist); if( "\t".equals(delimeter) && leftlist.getElementAt(0).toString().contains(",")){ JOptionPane.showMessageDialog(null, "Delimeter of text file should be ======> "+delimeter+ "\n or "+"\nChange the delimeter as per requirement in code."); leftlist.removeElementAt(0); jTextField1.setText(""); }else if(",".equals(delimeter) && leftlist.getElementAt(0).toString().contains("\t")){ JOptionPane.showMessageDialog(null, "Delimeter of text file should be ======> "+delimeter+ "\n or "+"\nChange the delimeter as per requirement in code."); leftlist.removeElementAt(0); jTextField1.setText(""); } } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "File is not found"); } finally{ if(s1!=null) s1.close(); } } private void remove_jbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remove_jbuttonActionPerformed if(rightlist.getSize()==0){ JOptionPane.showMessageDialog(null, "No parameters to remove"); } else{ if(para_selected_jList2.getSelectedIndices().length > 0) { int[] selectedIndices = para_selected_jList2.getSelectedIndices(); for (int i = selectedIndices.length-1; i >=0; i--) { rightlist.removeElementAt(selectedIndices[i]); } } else{ JOptionPane.showMessageDialog(null, "Select the parameters to remove"); } } }//GEN-LAST:event_remove_jbuttonActionPerformed private void image_folder_jButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_image_folder_jButtonActionPerformed // TODO add your handling code here: JFileChooser Image_directory = new JFileChooser(); Image_directory.setCurrentDirectory(new java.io.File(".")); Image_directory.setDialogTitle("Select Image Folder"); Image_directory.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); Image_directory.setApproveButtonText("Select"); Image_directory.setAcceptAllFileFilterUsed(false); if(Image_directory.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){ File f=Image_directory.getSelectedFile(); if(f!=null){ jTextField2.setText(""); String Image_dir_name=f.getAbsolutePath(); jTextField2.setText(Image_dir_name); } } //else JOptionPane.showMessageDialog(null, "folder is not selected"); }//GEN-LAST:event_image_folder_jButtonActionPerformed private void load_jbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_load_jbuttonActionPerformed // TODO add your handling code here: int temp=0; cols= new int[para_selected_jList2.getModel().getSize()]; Arrays.fill(cols,-1); while(temp<cols.length){ Object searched =para_selected_jList2.getModel().getElementAt(temp); for (int i = 0; i < parameter_jList.getModel().getSize(); i++) { Object item_at_index =parameter_jList.getModel().getElementAt(i); if(item_at_index.equals(searched)){ cols[temp++]=i; } } } if("".equals(jTextField1.getText()) || "".equals(jTextField2.getText())){ JOptionPane.showMessageDialog(null, "Image folder or Parameter file is not selected"); } else { if(para_selected_jList2.getModel().getSize()!=0){ if(jRadio_graph.isSelected()==true){ if(para_selected_jList2.getModel().getSize()<=5){ if(!obj_exists){ //Irig_g= new Irig_graph(jTextField1.getText(),jTextField2.getText(),param_max_count); Irig_g_p= new Irig_graph_Img(jTextField1.getText(),jTextField2.getText(),param_max_count); this.setState(Gui_Interface.ICONIFIED); } else JOptionPane.showMessageDialog(null, "object is not destroyed"); } else { JOptionPane.showMessageDialog(null, "Only 5 Parameters can be plotted"); } }else if(jRadio_slide.isSelected()==true) { if(!obj_exists){ Irig_s= new Irig_slide_img(jTextField1.getText(),jTextField2.getText(),para_selected_jList2.getModel().getSize()); this.setState(Gui_Interface.ICONIFIED); } else JOptionPane.showMessageDialog(null, "object is not destroyed"); } else if(jRadio_graph.isSelected()==false &&jRadio_slide.isSelected()==false) JOptionPane.showMessageDialog(null, "Select either parameter or graph to display"); }else{ JOptionPane.showMessageDialog(null, "Drop parameter to display"); } } }//GEN-LAST:event_load_jbuttonActionPerformed private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed // TODO add your handling code here: }//GEN-LAST:event_formWindowClosed /** * @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(Gui_Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Gui_Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Gui_Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Gui_Interface.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() { public void run() { new Gui_Interface().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton add_jbutton; private javax.swing.JButton image_folder_jButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JRadioButton jRadio_graph; private javax.swing.JRadioButton jRadio_slide; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JButton load_jbutton; private javax.swing.JList<String> para_selected_jList2; private javax.swing.JButton parameter_jButton; private javax.swing.JList<String> parameter_jList; private javax.swing.JButton remove_jbutton; private javax.swing.ButtonGroup select_radio_Group; // End of variables declaration//GEN-END:variables }
true
fc06d89b484f07777a0eb54f1a60b2d20709c6bf
Java
uoclnotario/4DBSET-PRODUCTO2
/src/logicaEmpresarial/Usuario.java
UTF-8
1,989
3.015625
3
[]
no_license
package logicaEmpresarial; import java.math.BigInteger; import java.security.MessageDigest; import java.util.concurrent.CopyOnWriteArraySet; public class Usuario { public enum tipoUsuarios{USUARIO,ADMINISTRADOR}; private String nombre; private String hasing; private tipoUsuarios rol; private int id; public Usuario() { } public Usuario(String nombre,String pass, tipoUsuarios tipo){ this.nombre = nombre; this.rol = tipo; this.setPassword(pass); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void setPassword(String password){ try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update((nombre+password).getBytes("utf8")); hasing = String.format("%040x", new BigInteger(1, digest.digest())); } catch (Exception e){ e.printStackTrace(); } } public void setRol(tipoUsuarios rol) { this.rol = rol; } public void setHasing(String hasing) { this.hasing = hasing;} public void setId(int id) { this.id = id; } public String getHasing() { if(hasing == null) return ""; else return hasing; } public tipoUsuarios getRol() {return rol;} public String getRolString(){ switch (rol){ case ADMINISTRADOR:return "ADMINISTRADOR"; default:return "USUARIO"; } } public int getId() {return id;} public Integer getIntRol(){ if(this.rol == null) return 1; switch (this.rol){ case ADMINISTRADOR:return 2; default:return 1; } } public void setIntRol(int e){ switch (e){ case 1: this.rol = tipoUsuarios.USUARIO;break; case 2: this.rol = tipoUsuarios.ADMINISTRADOR;break; } } }
true
96cd3d487c5a92e3aaedc899f1e45dae85f655af
Java
odra/bf-jenkins-plugin
/src/main/java/org/jenkinsci/plugins/LSBuildStep.java
UTF-8
2,395
2.421875
2
[]
no_license
package org.jenkinsci.plugins; import hudson.AbortException; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.ArgumentListBuilder; import jenkins.tasks.SimpleBuildStep; import org.kohsuke.stapler.DataBoundConstructor; import javax.annotation.Nonnull; import java.io.ByteArrayOutputStream; import java.io.IOException; public class LSBuildStep extends Builder implements SimpleBuildStep { public String path; @DataBoundConstructor public LSBuildStep(String path) { this.path = path; } @Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath filePath, @Nonnull Launcher launcher, @Nonnull TaskListener taskListener) throws InterruptedException, IOException { if (this.path == null) { throw new AbortException("Path field is required."); } ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); Launcher.ProcStarter proc = launcher.launch(); ArgumentListBuilder args = new ArgumentListBuilder(); args.add("ls"); args.add(this.path); int rc = proc .cmds(args) .stdout(stdout) .stderr(stderr) .join(); if (rc == 0) { taskListener.getLogger().write(stdout.toByteArray()); } else { taskListener.getLogger().write(stderr.toByteArray()); throw new AbortException("Error while executing ls command"); } } @Override public LSBuildStep.DescriptorImpl getDescriptor() { return (LSBuildStep.DescriptorImpl) super.getDescriptor(); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { @Override public String getDisplayName() { return "List Folder"; } protected DescriptorImpl(Class<? extends Builder> clazz) { super(clazz); } public DescriptorImpl() { load(); } @Override public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } } }
true
d45f6107182cd6f46d3226107dccc0831226c9d3
Java
rockneverendz/AACS3094-GUI
/src/Practical5/FourTierApp/src/ui/MaintainInformationFrame.java
UTF-8
1,335
3.015625
3
[]
no_license
package ui; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MaintainInformationFrame extends JFrame { private MaintainInformationFrame(){ GridLayout gridlayout = new GridLayout(2,1,10,10); this.setLayout(gridlayout); JButton jbtStudent = new JButton("Maintain Student"); JButton jbtProgramme = new JButton("Maintain Programme"); add(jbtProgramme); add(jbtStudent); jbtProgramme.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MaintainProgrammeFrame.main(); setVisible(false); } }); jbtStudent.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MaintainStudentFrame.main(); setVisible(false); } }); } public static void main(String[] args) { MaintainInformationFrame frm = new MaintainInformationFrame(); frm.setTitle("Maintain Information"); frm.setSize(300, 200); frm.setLocationRelativeTo(null); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } }
true
c5634f7b5ebc35145d5615f1f8f1a8105b135b7e
Java
salvatorecorsaro/production-service
/src/main/java/com/mrcookies/productionservice/proxy/FortuneMessageProxy.java
UTF-8
387
1.75
2
[]
no_license
package com.mrcookies.productionservice.proxy; import com.mrcookies.productionservice.dto.FortuneMessage; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient("FORTUNE-MESSAGE-SERVICE") public interface FortuneMessageProxy { @GetMapping("/fortune-messages/chuck") FortuneMessage getChuckMessages(); }
true
268783b21f2eec930c43de694ce4e5281f6a6866
Java
kuba3351/camera-server
/src/main/java/com/raspberry/camera/service/PendriveService.java
UTF-8
5,583
2.578125
3
[]
no_license
package com.raspberry.camera.service; import com.raspberry.camera.MatUtils; import com.raspberry.camera.other.MatContainer; import com.raspberry.camera.other.Photo; import org.apache.log4j.Logger; import org.opencv.core.Mat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Optional; @Service public class PendriveService { private final static Logger logger = Logger.getLogger(PendriveService.class); @Autowired public PendriveService(ConfigFileService configFileService) { if (configFileService.getSavingPlacesDTO().getJpgPendriveSave() || configFileService.getSavingPlacesDTO().getMatPendriveSave()) { Thread thread = new Thread(() -> { logger.info("Sprawdzam pendrive..."); if (checkIfPendriveConnected()) { logger.info("Pendrive podłączony. Sprawdzam montowanie..."); try { if (checkWherePendriveMounted().isPresent()) { logger.info("Pendrive już zamontowany. Kontynuuję uruchomienie..."); } else { logger.info("Montuję pendrive..."); if (mountPendrive()) { logger.info("Pendrive zamontowany. Kontynuuję uruchomienie..."); } else logger.error("Problem z montowaniem pendrive..."); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } else logger.warn("Pendrive nie jest podłączony!"); }); thread.start(); } } public boolean checkIfPendriveConnected() { return new File("/dev/sda").exists(); } public Optional<String> checkWherePendriveMounted() throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("mount"); process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); return reader.lines().filter(line -> line.startsWith("/dev/sda")) .map(line -> new ArrayList<>(Arrays.asList(line.split(" ")))) .map(list -> list.get(2)).findFirst(); } public boolean mountPendrive() throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("sudo mount /dev/sda /home/pi/pendrive"); return process.waitFor() == 0; } public void saveJpgToPendrive(Photo photo1, Photo photo2) throws Exception { String path = checkWherePendriveMounted().orElseThrow(() -> new Exception("Nie można znaleźć pendrive")); File jpgPath = new File(path + "/jpg"); if (!jpgPath.isDirectory()) jpgPath.mkdir(); if (photo1 != null) { String jpgFilePath = jpgPath.toString() + "/" + LocalDateTime.now().toString().replace(":", "-") + "-camera1.jpg"; File photo = new File(jpgFilePath.replace(":", "-")); photo.createNewFile(); FileWriter writer = new FileWriter(photo); writer.write(new String(photo1.getJpgImage())); writer.close(); } if (photo2 != null) { String jpgFilePath = jpgPath.toString() + "/" + LocalDateTime.now().toString().replace(":", "-") + "-camera2.jpg"; FileWriter writer = new FileWriter(new File(jpgFilePath.replace(":", "-"))); writer.write(new String(photo2.getJpgImage())); writer.close(); } } public void saveMatToPendrive(Photo photo1, Photo photo2) throws Exception { String path = checkWherePendriveMounted().orElseThrow(() -> new Exception("Nie można znaleźć pendrive")); File matPath = new File(path + "/mat"); if (!matPath.isDirectory()) matPath.mkdir(); if (photo1 != null) { String matFilePath = matPath.toString() + "/" + LocalDateTime.now() + "-camera1.yml"; File matFile = new File(matFilePath.replace(":", "-")); matFile.createNewFile(); FileWriter fileWriter = new FileWriter(matFile); MatContainer matContainer = new MatContainer(); Mat mat = photo1.getMatImage(); matContainer.setCols(mat.cols()); matContainer.setRows(mat.rows()); matContainer.setData(MatUtils.extractDataFromMat(mat)); ByteArrayOutputStream outputStream = MatUtils.writeMat(matContainer); fileWriter.write(new String(outputStream.toByteArray())); fileWriter.close(); } if (photo2 != null) { String matFilePath = matPath.toString() + "/" + LocalDateTime.now() + "-camera2.yml"; FileWriter fileWriter = new FileWriter(new File(matFilePath.replace(":", "-"))); MatContainer matContainer = new MatContainer(); Mat mat = photo2.getMatImage(); matContainer.setCols(mat.cols()); matContainer.setRows(mat.rows()); matContainer.setData(MatUtils.extractDataFromMat(mat)); ByteArrayOutputStream outputStream = MatUtils.writeMat(matContainer); fileWriter.write(new String(outputStream.toByteArray())); fileWriter.close(); } } }
true
5d947380675ac2f702be0c437704d5247874ae11
Java
Leinadh/GesBib
/GesBibSoftController/src/pe/edu/pucp/gesbibsoft/mysql/AdministradorSIMySQL.java
UTF-8
3,952
2.625
3
[]
no_license
package pe.edu.pucp.gesbibsoft.mysql; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import pe.edu.pucp.gesbibsoft.dao.AdministradorSIDAO; import pe.edu.pucp.gesbibsoft.model.AdministradorSI; import pe.edu.pucp.gesbibsoft.config.DBManager; public class AdministradorSIMySQL implements AdministradorSIDAO{ Connection con = null; Statement st = null; CallableStatement cs = null; @Override public void insertar(AdministradorSI adminSI) { try{ con = DriverManager.getConnection(DBManager.url, DBManager.user, DBManager.password); cs = con.prepareCall("{call INSERTAR_ADMINISTRADOR_SI(?,?,?,?,?)}"); cs.setString("_APELLIDO", adminSI.getApellido()); cs.setString("_NOMBRE", adminSI.getNombre()); cs.setString("_EMAIL", adminSI.getEmail()); cs.setString("_PASSWORD", adminSI.getContrasenia()); cs.registerOutParameter("_ID_USUARIO", java.sql.Types.INTEGER); cs.executeUpdate(); adminSI.setId(cs.getInt("_ID_USUARIO")); }catch(SQLException ex){ System.out.println(ex.getMessage()); }finally{ try{con.close();}catch(SQLException ex){System.out.println(ex.getMessage());} } } @Override public void actualizar(AdministradorSI adminSI) { try{ con = DriverManager.getConnection(DBManager.url, DBManager.user, DBManager.password); cs = con.prepareCall("{call ACTUALIZAR_ADMINISTRADOR(?,?,?,?,?)}"); cs.setInt("_ID", adminSI.getId()); cs.setString("_NOMBRE", adminSI.getNombre()); cs.setString("_APELLIDO", adminSI.getApellido()); cs.setString("_EMAIL", adminSI.getEmail()); cs.setString("_PASSWORD", adminSI.getContrasenia()); cs.executeUpdate(); }catch(SQLException ex){ System.out.println(ex.getMessage()); }finally{ try{con.close();}catch(SQLException ex){System.out.println(ex.getMessage());} } } @Override public void eliminar(int idAdministradorSI) { try { con = DriverManager.getConnection(DBManager.url, DBManager.user, DBManager.password); cs = con.prepareCall("{call ELIMINAR_ADMINISTRADOR_SI(?)}"); cs.setInt("_ID", idAdministradorSI); cs.executeUpdate(); } catch ( SQLException ex) { System.out.println(ex.getMessage()); } finally { try { con.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } } @Override public ArrayList<AdministradorSI> listar() { ArrayList<AdministradorSI> administradoresSI = new ArrayList<>(); try{ con = DriverManager.getConnection(DBManager.url, DBManager.user, DBManager.password); CallableStatement cStmt = con.prepareCall("{call LISTAR_ADMINISTRADORES_SI()}"); ResultSet rs=cStmt.executeQuery(); while(rs.next()){ AdministradorSI e = new AdministradorSI(); e.setId(rs.getInt("ID_USUARIO")); e.setNombre(rs.getString("NOMBRE")); e.setApellido(rs.getString("APELLIDO")); e.setEmail(rs.getString("EMAIL")); e.setContrasenia(rs.getString("PASSWORD")); administradoresSI.add(e); } }catch(SQLException ex){ System.out.println(ex.getMessage()); }finally{ try{con.close();}catch(SQLException ex){System.out.println(ex.getMessage());} } return administradoresSI; } }
true
8399427f5603bd2e1afb64c7a6aee2b46d3535ff
Java
zj7816/quark
/src/main/java/ren/quark/application/processor/realasset/LianJIaProcessor.java
UTF-8
1,786
1.929688
2
[ "Apache-2.0" ]
permissive
/** *dianping.com Inc *Copyright(c)2004-2017 All Rights Reserved. */ package ren.quark.application.processor.realasset; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.processor.PageProcessor; import java.util.List; /** * 链家数据爬取 * * @author zhangjie * @version $Id: LianJIaProcessor.java, v 0.1 2017-01-06 下午1:53 zhangjie Exp $$ */ public class LianJIaProcessor implements PageProcessor { private Site site = Site.me(); private static final String LIST_REX="http://sh.lianjia.com/ershoufang/rs\\w+"; public void process(Page page) { List<String> links = page.getHtml().xpath("//div[@class=\"main-box clear\"]").links().regex("/ershoufang/\\w+\\.html").all(); page.addTargetRequests(links); if (!page.getUrl().regex(LIST_REX).match()) { page.putField("departmentName", page.getHtml().xpath("/html/body/div[3]/div[2]/div[2]/table/tbody/tr[5]/td/a/text()").get()); page.putField("acreage", page.getHtml().xpath("/html/body/div[3]/div[2]/div[2]/div[1]/div[5]/div/text()").get()); page.putField("totalPrice", page.getHtml().xpath("/html/body/div[3]/div[2]/div[2]/div[1]/div[1]/div/text()").get()); page.putField("pricePerAcreage", page.getHtml().xpath("/html/body/div[3]/div[2]/div[2]/table/tbody/tr[1]/td/text()").get()); page.putField("floorDesc", page.getHtml().xpath("/html/body/div[3]/div[2]/div[2]/table/tbody/tr[2]/td[1]/text()").get()); page.putField("address", page.getHtml().xpath("/html/body/div[3]/div[2]/div[2]/table/tbody/tr[6]/td/p/text()").get()); } else { page.setSkip(true); } } @Override public Site getSite() { return site; } }
true
3354f9624d78be629a2ee994013da4560cecd8cb
Java
wmc007/U17
/app/src/main/java/com/example/ice/u17/MainActivity.java
UTF-8
3,550
1.921875
2
[]
no_license
package com.example.ice.u17; import android.content.res.ColorStateList; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.RadioGroup; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private RadioButton mRbRecommend; private RadioButton mRbBoutique; private RadioButton mRbBookshelf; private RadioButton mRbGame; private RadioGroup mRg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } private void initView() { mRbRecommend = (RadioButton) findViewById(R.id.rb_recommend); mRbBoutique = (RadioButton) findViewById(R.id.rb_boutique); mRbBookshelf = (RadioButton) findViewById(R.id.rb_bookshelf); mRbGame = (RadioButton) findViewById(R.id.rb_game); mRg = (RadioGroup) findViewById(R.id.rg); ColorStateList stateList = getResources().getColorStateList(R.color.selector_radiobutton); for (int i = 0; i < mRg.getChildCount(); i++) { CompoundButton childView = ((CompoundButton) mRg.getChildAt(i)); DrawableCompat.setTintList(childView.getCompoundDrawables()[1],stateList); } } }
true
c53f94d7c29905b7deb9a70be20d09367c7fd33c
Java
zzzzjinxiang/DesignModel
/src/com/DesignModels/MVC/DAO.java
UTF-8
210
2.109375
2
[]
no_license
package com.DesignModels.MVC; public class DAO { public void startup(){ System.out.println("extract data"); } public void shutdown(){ System.out.println("transport ...."); } }
true
d2c24006ca4ea72aa3188748e3b221fec7282a6b
Java
coromotov/Baby
/BabyCaredUnified/BabyCareWeb/src/main/java/com/veneconsult/dao/service/business/PharmacyService.java
UTF-8
473
1.554688
2
[]
no_license
/** * */ package com.veneconsult.dao.service.business; import javax.transaction.Transactional; import org.springframework.stereotype.Component; import com.veneconsult.common.business.Pharmacy; import com.veneconsult.dao.business.PharmacyDao; import com.veneconsult.dao.service.parent.EntityService; /** * @author Yelitza * */ @Component @Transactional public class PharmacyService extends EntityService<Pharmacy> implements PharmacyDao { }
true
55b4e46ab71cd59978cb4ed1226e12534f98e514
Java
veeresh-111/pass
/selenium practice/src/scanner/Screenshot.java
UTF-8
788
2.203125
2
[]
no_license
package scanner; import java.io.File; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import com.google.common.io.Files; public class Screenshot { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.gecko.driver","./softwares1/geckodriver.exe"); WebDriver driver= new FirefoxDriver(); driver.get("https://www.facebook.com"); Thread.sleep(3000); TakesScreenshot ts= (TakesScreenshot)driver; File src=ts.getScreenshotAs(OutputType.FILE); File dst= new File("E:\\veeresh\\Pictures\\facebook.jpeg"); } }
true
08831578416f86c39f4af51cc925d9eb570010d2
Java
Sebion/PresovGo
/app/src/main/java/com/example/sebastian/presovgo2/MapFragment.java
UTF-8
3,283
1.882813
2
[]
no_license
package com.example.sebastian.presovgo2; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.ArrayList; import static android.content.Context.LOCATION_SERVICE; /** * A simple {@link Fragment} subclass. */ public class MapFragment extends Fragment implements OnMapReadyCallback { private GoogleMap mMap; SupportMapFragment mapFragment; IMainActivity iMainActivity; public MapFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onAttach(Context context) { super.onAttach(context); iMainActivity = (IMainActivity) getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_map, container, false); mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); if (mapFragment == null) { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); mapFragment = SupportMapFragment.newInstance(); ft.replace(R.id.map, mapFragment).commit(); } mapFragment.getMapAsync(this); return v; } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng presov = new LatLng(48.997631, 21.2401873); // FontanyPramene fontanyPramene = new FontanyPramene(); for (int i = 0; i < fontanyPramene.getNames().size(); i++) { mMap.addMarker(new MarkerOptions().position(fontanyPramene.getLatLng().get(i)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)).title(fontanyPramene.getNames().get(i))); } SakralneObjekty sakralneObjekty = new SakralneObjekty(); for (int i = 0; i < sakralneObjekty.getNames().size(); i++) { mMap.addMarker(new MarkerOptions().position(sakralneObjekty.getLatLng().get(i)).title(sakralneObjekty.getNames().get(i))); } mMap.moveCamera(CameraUpdateFactory.newLatLng(presov)); mMap.setMinZoomPreference(11); } }
true
abf5307ac588bfe306775c2e710cac5b4540b9c2
Java
jakewins/gremlin
/src/test/java/com/tinkerpop/gremlin/compiler/functions/g/string/SubstringFunctionTest.java
UTF-8
1,186
2.65625
3
[ "BSD-3-Clause" ]
permissive
package com.tinkerpop.gremlin.compiler.functions.g.string; import com.tinkerpop.gremlin.BaseTest; import com.tinkerpop.gremlin.compiler.Atom; import com.tinkerpop.gremlin.compiler.functions.Function; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SubstringFunctionTest extends BaseTest { public void testSubstring() { Function<String> function = new SubstringFunction(); this.stopWatch(); Atom<String> atom = function.compute(createUnaryArgs("marko",0,3)); printPerformance(function.getFunctionName() + " function", 1, "evaluation", this.stopWatch()); assertEquals(atom.getValue(), "mar"); this.stopWatch(); atom = function.compute(createUnaryArgs("marko",4)); printPerformance(function.getFunctionName() + " function", 1, "evaluation", this.stopWatch()); assertEquals(atom.getValue(), "o"); } public void testIllegalArguments() { try { Function<String> function = new SubstringFunction(); function.compute(createUnaryArgs("marko")); assertFalse(true); } catch (Exception e) { assertTrue(true); } } }
true
987199eb494da36d78a300ec6921918c7b7aac15
Java
archubongale/Android_People_Trimet
/app/src/main/java/com/example/archanabongale/peoplestrimet/MainActivity.java
UTF-8
789
2.078125
2
[]
no_license
package com.example.archanabongale.peoplestrimet; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { private TextView mTitleText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitleText = (TextView) findViewById(R.id.textView); mTitleText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,PostActivity.class); startActivity(intent); } }); } }
true
63e71f349c01293e02d2cf33e27c52111bbd0869
Java
greenstripes4/USACO
/completed/USACO/Silver/2017-Open-pairup.java
UTF-8
1,477
3.140625
3
[]
no_license
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { //Scanner f = new Scanner(new File("uva.in")); //Scanner f = new Scanner(System.in); BufferedReader f = new BufferedReader(new FileReader("pairup.in")); //BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("pairup.out"))); int N = Integer.parseInt(f.readLine()); TreeMap<Integer,Integer> cows = new TreeMap<>(); for(int i = 0; i < N; i++) { StringTokenizer st = new StringTokenizer(f.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); cows.put(y,x); } int maxTime = 0; while(!cows.isEmpty()) { int Ay = cows.firstKey(); int By = cows.lastKey(); maxTime = Math.max(maxTime,Ay+By); if(cows.get(Ay) < cows.get(By)) { cows.put(By,cows.get(By)-cows.get(Ay)); cows.remove(Ay); } else if(cows.get(Ay) > cows.get(By)) { cows.put(Ay,cows.get(Ay)-cows.get(By)); cows.remove(By); } else { cows.remove(Ay); cows.remove(By); } } out.println(maxTime); f.close(); out.close(); } }
true
d5f5240b8c51dde1d1900daf4381c08d1df578d7
Java
jinterval/jinterval
/jinterval-ils/src/main/java/net/java/jinterval/linear/RationalVector.java
UTF-8
2,231
1.835938
2
[ "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2012, JInterval Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package net.java.jinterval.linear; import net.java.jinterval.rational.ExtendedRational; import net.java.jinterval.rational.ExtendedRationalContext; /** * */ public interface RationalVector { public int getDimension(); public ExtendedRational getEntry(int i); public void setEntry(int i, ExtendedRational v); public RationalVector getSubVector(int from, int len); public void setSubVector(int from, RationalVector v); public RationalVector copy(); public ExtendedRational getMinValue(); public ExtendedRational getL1Norm(ExtendedRationalContext ctx); public RationalVector subtract(ExtendedRationalContext ctx, RationalVector that); public RationalVector mapMultiply(ExtendedRationalContext ctx, ExtendedRational v); public RationalVector mapDivide(ExtendedRationalContext ctx, ExtendedRational v); }
true
5a95764ec5cff9f9182093946e920069c63f5dc6
Java
Ghost-chu/BinarySync
/src/main/java/studio/potatocraft/binarysync/BinarySync.java
UTF-8
477
2.21875
2
[]
no_license
package studio.potatocraft.binarysync; import org.bukkit.plugin.java.JavaPlugin; public final class BinarySync extends JavaPlugin { private static BinarySync instance; public BinarySync(){ instance = this; } @Override public void onEnable() { // Plugin startup logic } @Override public void onDisable() { // Plugin shutdown logic } public static BinarySync getInstance() { return instance; } }
true
8978ee3f9d7d7a690b08d59f9e3494d2a90b8163
Java
arpurush/ARCSJDevExtension
/src/oracle/apps/fnd/arcs/commands/ArcsJavaBridge.java
UTF-8
615
1.945313
2
[]
no_license
package oracle.apps.fnd.arcs.commands; import oracle.apps.fnd.arcs.log.Logger; public interface ArcsJavaBridge { /** * Should return the hostname of the session server. Example: rws3220122.us.oracle.com * @return */ public String getHostName(); /** * Should return the GUID of the user. Example: arpurush * @return */ public String getUserName(); /** * Should return the session server password of the user * @return */ public String getPassword(); /** * Should return an instance of Logger which will be used to log information * @return */ public Logger getLogger(); }
true
e9d7043cd131ae924cbbddb3caa08232caf838e5
Java
RSSS4/TicTacToe
/src/test/java/model/CheckWinnerTest.java
UTF-8
3,137
2.484375
2
[]
no_license
package model; //import org.junit.jupiter.api.Test; import org.junit.Test; import view.GameField; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; //import static org.junit.jupiter.api.Assertions.*; public class CheckWinnerTest { @Test public void refreshDataTestShouldReturnTrue() { CheckWinner checkWinner = new CheckWinner(5,5); Buttons buttons[][] = new Buttons[5][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++){ buttons[i][j] = new Buttons(1); buttons[i][j].setTest(1,true); } checkWinner.refreshData(buttons); //update checkWinner buttons[][] assertArrayEquals(buttons, checkWinner.getButtons()); } @Test public void checkWinTestShouldReturnTrue() { CheckWinner checkWinner = new CheckWinner(5,5); Buttons buttons[][] = new Buttons[5][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) { buttons[i][j] = new Buttons(1); } for (int i = 0; i < 5; i++){ buttons[i][1].setTest(1,false); } checkWinner.refreshData(buttons); assertEquals(true, checkWinner.checkWin(1,0,1)); } @Test public void checkWinTestShouldReturnFalse() { CheckWinner checkWinner = new CheckWinner(5,5); Buttons buttons[][] = new Buttons[5][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) { buttons[i][j] = new Buttons(1); } for (int i = 0; i < 5; i++){ buttons[i][1].setTest(1,false); } buttons[2][1].setTest(0,true); checkWinner.refreshData(buttons); assertEquals(false, checkWinner.checkWin(1,0,1)); } @Test public void checkDrawTestShouldReturnFalse() { CheckWinner checkWinner = new CheckWinner(5,5); Buttons buttons[][] = new Buttons[5][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++){ buttons[i][j] = new Buttons(1); buttons[i][j].setTest(0,true); //set all cells to free } checkWinner.refreshData(buttons); assertEquals(false, checkWinner.checkDraw()); //we expect false because all cells are free } @Test public void checkDrawTestShouldReturnTrue() { CheckWinner checkWinner = new CheckWinner(5,5); Buttons buttons[][] = new Buttons[5][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++){ buttons[i][j] = new Buttons(1); buttons[i][j].setTest(1,false); //set all cells to free } checkWinner.refreshData(buttons); assertEquals(true, checkWinner.checkDraw()); //we expect false because all cells are free } @Test public void checkOutOfFieldTestShouldReturnTrue() { CheckWinner checkWinner = new CheckWinner(5,5); assertEquals(true, checkWinner.checkOutOfField(4,4)); } }
true
a5ceb0b1b7939eae3785a39c85a87e3febef3358
Java
liuji789/kylin
/kylin-multidatasource/src/main/java/com/store59/kylin/multidatasource/DBConfiguration.java
UTF-8
4,312
2.0625
2
[]
no_license
/** * Copyright (c) 2016, 59store. All rights reserved. */ package com.store59.kylin.multidatasource; import com.store59.kylin.multidatasource.db.DBLink; import com.store59.kylin.multidatasource.factory.DBFactory; import com.store59.kylin.multidatasource.mybatis.scanner.MapperAutoScannerConfigurer; import org.apache.commons.beanutils.BeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * 数据库启动配置类 * * @author <a href="mailto:zhongc@59store.com">士兵</a> * @version 1.0 16/8/7 * @since 1.0 */ @Component @EnableTransactionManagement public class DBConfiguration implements ApplicationContextAware, BeanDefinitionRegistryPostProcessor, EnvironmentAware { private final static Logger logger = LoggerFactory.getLogger(DBConfiguration.class); private ApplicationContext applicationContext; private DBFactory dbFactory; private List<DBLink> dbLinks; @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { dbFactory = new DBFactory((DefaultListableBeanFactory) beanFactory); dbLinks.stream().forEach(db -> { //创建datasource dbFactory.registerDataSource(db); //创建sqlSessionFactoryBean dbFactory.registerSqlSessionFactoryBean(db.getKey()); //创建sqlSessionTemplate dbFactory.registerSqlSessionTemplate(db.getKey()); //创建事务transactionManager if(null == db.getTransactionAble()) { logger.error("transactionAble must not be null"); throw new RuntimeException("transactionAble must not be null"); } else if(db.getTransactionAble()) { dbFactory.registerTransactionManager(db.getKey()); } //创建mybatis扫描 MapperAutoScannerConfigurer.scan(applicationContext, (DefaultListableBeanFactory) beanFactory, db.getKey(), db.getMapperPath()); }); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void setEnvironment(Environment environment) { //拿到spring.datasource的属性解析器 RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment,"spring.datasource."); //将属性转换成map, 病获得 dbLinks[n]的set集合 Map<String, Object> properties = propertyResolver.getSubProperties(""); Set<String> dbLinksKey = new HashSet<>(); //e.split("\\.")[0] = dbLink[n] properties.keySet().forEach(e -> dbLinksKey.add(e.split("\\.")[0])); this.dbLinks = dbLinksKey.parallelStream().map(e -> { Map<String, Object> dbLinkMap = propertyResolver.getSubProperties(e +"."); DBLink dbLink = new DBLink(); try { BeanUtils.populate(dbLink, dbLinkMap); } catch (Exception ex) { logger.error("spring.datasource convert error"); throw new RuntimeException("spring.datasource.dbLinks is error"); } return dbLink; }).collect(Collectors.toList()); } }
true
f58e5103db193fbd011ccfd67c2a0eb2ab82185f
Java
ruicarvoeiro/ta_capgemini
/Projecto/src/projecto/EditarMeeting.java
UTF-8
14,878
2.109375
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 projecto; import java.util.List; import javax.swing.table.DefaultTableModel; import projecto.MeetingsOrganizer; /** * * @author DMORAIS */ public class EditarMeeting extends javax.swing.JFrame { /** * Creates new form EditarParticipante */ public EditarMeeting() { 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() { jScrollPane1 = new javax.swing.JScrollPane(); jTableMeetings = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jLabelNumeroColaborador = new javax.swing.JLabel(); jTextFieldNumeroC = new javax.swing.JTextField(); jLabelIdEvento = new javax.swing.JLabel(); jTextFieldIdNum = new javax.swing.JTextField(); jComboBoxOperacao = new javax.swing.JComboBox<>(); jLabelOperacao = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jTableMeetings1 = new javax.swing.JTable(); jButtonConfirmarAlteracao = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jTableMeetings.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Id Evento", "Descrição", "Data", "Hora", "Local" } )); jScrollPane1.setViewportView(jTableMeetings); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Editar Meeting", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 18))); // NOI18N jLabelNumeroColaborador.setText("Número de colaborador:"); jTextFieldNumeroC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldNumeroCActionPerformed(evt); } }); jLabelIdEvento.setText("ID Evento:"); jComboBoxOperacao.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Adicionar", "Eliminar" })); jComboBoxOperacao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxOperacaoActionPerformed(evt); } }); jLabelOperacao.setText("Escolha operação"); jTableMeetings1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Descrição", "Data", "Hora", "Local", "Participantes" } )); jScrollPane2.setViewportView(jTableMeetings1); jButtonConfirmarAlteracao.setText("Confirmar"); jButtonConfirmarAlteracao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonConfirmarAlteracaoActionPerformed(evt); } }); jButton2.setText("Voltar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(58, 58, 58) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton2) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonConfirmarAlteracao) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 573, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelNumeroColaborador) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldNumeroC, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelIdEvento) .addGap(36, 36, 36) .addComponent(jTextFieldIdNum))) .addGap(29, 29, 29) .addComponent(jLabelOperacao) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxOperacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(190, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton2) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelNumeroColaborador, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNumeroC, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelIdEvento) .addComponent(jTextFieldIdNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelOperacao) .addComponent(jComboBoxOperacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31) .addComponent(jButtonConfirmarAlteracao) .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(26, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jComboBoxOperacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxOperacaoActionPerformed }//GEN-LAST:event_jComboBoxOperacaoActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed MeetingsOrganizer c = new MeetingsOrganizer(); c.setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed private void jTextFieldNumeroCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNumeroCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldNumeroCActionPerformed private void jButtonConfirmarAlteracaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConfirmarAlteracaoActionPerformed PainelOrganizador m = new PainelOrganizador(); int n = Integer.parseInt(jTextFieldNumeroC.getText()); int idEvento = Integer.parseInt(jTextFieldIdNum.getText()); Colaborador c = m.getColaboradorByNum(n); if(c!= null){ List<Meeting> listaMeetings = c.getListMeeting(); Meeting mee = null; for(Meeting meet : listaMeetings){ if(meet.getIdEvento() == idEvento ){ //pegar operacao String s = (String)jComboBoxOperacao.getSelectedItem(); if(s.equals("Adicionar")){ meet.addParticipante(c.getNumeroColaborador()); } else meet.eliminarParticipante(n); } } //popular a tabela!! DefaultTableModel tableModel = (DefaultTableModel) this.jTableMeetings.getModel(); tableModel = eliminarLinhas(tableModel); for(Meeting met : listaMeetings){ List<Integer> lc = met.getListaParticipantes(); // System.out.println(met.getDescricaoEvento()+"tamanho lista: " + lc.size()); StringBuilder sb = new StringBuilder(); String s = null; for(Integer co : lc){ Colaborador cola = m.getColaboradorByNum(co); sb.append(cola.getNomeColaborador()+" nº"+cola.getNumeroColaborador()); sb.append(","); } sb.deleteCharAt(sb.length() - 1); s = sb.toString(); Object [] ob = new Object[6]; ob[0] = met.getIdEvento(); ob[1] = met.getDescricaoEvento(); ob[2] = met.getDataEvento(); ob[3] = met.getHoraEvento(); ob[4] = met.getLocal(); if(s!= null) ob[5] = s; tableModel.addRow(ob); } jTableMeetings.setModel(tableModel); } }//GEN-LAST:event_jButtonConfirmarAlteracaoActionPerformed /** * @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(EditarMeeting.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EditarMeeting.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EditarMeeting.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EditarMeeting.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() { public void run() { new EditarMeeting().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JButton jButtonConfirmarAlteracao; private javax.swing.JComboBox<String> jComboBoxOperacao; private javax.swing.JLabel jLabelIdEvento; private javax.swing.JLabel jLabelNumeroColaborador; private javax.swing.JLabel jLabelOperacao; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTableMeetings; private javax.swing.JTable jTableMeetings1; private javax.swing.JTextField jTextFieldIdNum; private javax.swing.JTextField jTextFieldNumeroC; // End of variables declaration//GEN-END:variables private DefaultTableModel eliminarLinhas(DefaultTableModel t) { while (t.getRowCount() != 0) { for (int i = 0; i < t.getRowCount(); i++) { t.removeRow(i); } } return t; } }
true
22af5c9538afcfd1dc413f9af8810e0519e53b54
Java
lhj2543/river-srping-boot
/river-boot/rivert-boot/rivert-service/rivert-site-api/src/main/java/com/river/site/service/impl/SiteConnentMainServiceImpl.java
UTF-8
845
1.78125
2
[]
no_license
package com.river.site.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.river.api.dto.site.SiteConnentMainDto; import com.river.api.entity.site.SiteConnentMain; import com.river.site.mapper.SiteConnentMainMapper; import com.river.site.service.ISiteConnentMainService; import org.springframework.stereotype.Service; /** * <p> * 站点内容主表 服务实现类 * </p> * * @author river * @since 2020-09-17 */ @Service public class SiteConnentMainServiceImpl extends ServiceImpl<SiteConnentMainMapper, SiteConnentMain> implements ISiteConnentMainService { @Override public SiteConnentMainDto getDetail(String sid) { return baseMapper.getDetail(sid); } @Override public boolean relationDelete(String sid) { return baseMapper.relationDelete(sid); } }
true
710bbbcf6ab4c85b9fdec79f2fe761e157bec6d7
Java
liuxinyun/haq
/haq-bms/src/main/java/com/lanwei/haq/bms/service/log/SysLogService.java
UTF-8
2,226
2.3125
2
[]
no_license
package com.lanwei.haq.bms.service.log; import com.lanwei.haq.bms.dao.log.SysLogDao; import com.lanwei.haq.bms.entity.log.SysLogEntity; import com.lanwei.haq.comm.enums.ResponseEnum; import com.lanwei.haq.comm.util.ListUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @作者: liuxinyun * @日期: 2017/6/15 14:53 * @描述: 类文件 */ @Service public class SysLogService { private final SysLogDao sysLogDao; @Autowired public SysLogService(SysLogDao sysLogDao){ this.sysLogDao = sysLogDao; } /** * 根据id查询日志 * @param id * @return */ public SysLogEntity getLogById(int id){ SysLogEntity sysLogEntity = new SysLogEntity(); sysLogEntity.setId(id); List<SysLogEntity> list = sysLogDao.query(sysLogEntity); return ListUtil.isNotEmpty(list) ? list.get(0) : null; } /** * 新增日志 * @param sysLogEntity * @return */ public int add(SysLogEntity sysLogEntity) { return sysLogDao.add(sysLogEntity); } /** * 删除日志 * @param sysLogEntity * @return */ public void del(SysLogEntity sysLogEntity) { sysLogDao.del(sysLogEntity); } /** * 查询所有日志,带分页 * * @param sysLogEntity * @return */ public Map<String, Object> logList(SysLogEntity sysLogEntity) { Map<String, Object> resultMap = ResponseEnum.SUCCESS.getResultMap(); if(null == sysLogEntity) { sysLogEntity = new SysLogEntity(); } // 查询总数 int count = sysLogDao.count(sysLogEntity); sysLogEntity.setCount(count); // 没有查询到则不执行下面的查询 if (count > 0) { resultMap.put("list", sysLogDao.query(sysLogEntity)); } resultMap.put("count", count); resultMap.put("queryEntity", sysLogEntity); return resultMap; } /** * 批量删除日志 * @param id * @return */ public void delBatch(int[] id) { sysLogDao.delList(id, 0); } }
true
f91eb7bf0de87d82ca79f8fcb369520736306337
Java
YMNNs/his-springboot-backend
/src/main/java/com/ymnns/his/backend/entity/Drugs.java
UTF-8
334
2.015625
2
[]
no_license
package com.ymnns.his.backend.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; @Entity @Data public class Drugs { @Id private Integer id; private String name; private String format; private Float price; private String mnemonic_code; private String drug_code; }
true
5a16720f1341daa413807a84e17cc77518e036bc
Java
MatheusGeorge/Tully-01-11-2017
/app/src/main/java/com/example/edu/menutb/model/notificacao/Notifications.java
UTF-8
2,943
2.1875
2
[]
no_license
package com.example.edu.menutb.model.notificacao; import com.example.edu.menutb.model.UserTully; /** * Created by jeffkenichi on 12/10/17. */ public class Notifications { //Para seguir private String idUsuario; private String urlFotoPerfilUsuario; private String nome; private String experiencia; private String cidade; //Para avaliacao private String urlFotoTimeline; private String fotoLike; private String fotoDislike; //pros dois private String texto; public Notifications(String idUsuario, String texto, String urlFotoPerfilUsuario, String nome, String experiencia, String cidade) { this.idUsuario = idUsuario; this.texto = texto; this.urlFotoPerfilUsuario = urlFotoPerfilUsuario; this.nome = nome; this.experiencia = experiencia; this.cidade = cidade; } public Notifications(String urlFotoTimeline, String fotoLike, String fotoDislike, String texto) { this.urlFotoTimeline = urlFotoTimeline; this.fotoLike = fotoLike; this.fotoDislike = fotoDislike; this.texto = texto; } public Notifications(String texto, String name, String cidadePais,String fotoUrl,String fotoPerfil){ this.urlFotoTimeline = fotoUrl; this.cidade = cidadePais; this.nome = name; this.texto = texto; this.urlFotoPerfilUsuario = fotoPerfil; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getExperiencia() { return experiencia; } public void setExperiencia(String experiencia) { this.experiencia = experiencia; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } public String getUrlFotoTimeline() { return urlFotoTimeline; } public void setUrlFotoTimeline(String urlFotoTimeline) { this.urlFotoTimeline = urlFotoTimeline; } public String getFotoLike() { return fotoLike; } public void setFotoLike(String fotoLike) { this.fotoLike = fotoLike; } public String getFotoDislike() { return fotoDislike; } public void setFotoDislike(String fotoDislike) { this.fotoDislike = fotoDislike; } public Notifications(){}; public String getIdUsuario() { return idUsuario; } public void setIdUsuario(String idUsuario) { this.idUsuario = idUsuario; } public String getTexto() { return texto; } public void setTexto(String texto) { this.texto = texto; } public String getUrlFotoPerfilUsuario() { return urlFotoPerfilUsuario; } public void setUrlFotoPerfilUsuario(String urlFotoPerfilUsuario) { this.urlFotoPerfilUsuario = urlFotoPerfilUsuario; } }
true
e94aa5aaad753240a8d201b2cd298fb945779092
Java
MRL6140xuan/springbootdemo
/src/main/java/com/liuxx/awesome/domain/entity/ErrorInfo.java
UTF-8
633
2.28125
2
[]
no_license
package com.liuxx.awesome.domain.entity; import lombok.Getter; import lombok.Setter; /** * 自定义错误信息(返回前端) * * @author :liuxx * @date: 2017/11/10 15:43 */ @Getter @Setter public class ErrorInfo<T> { /** * 错误代码 */ private String code; /** * 错误信息 */ private String message; /** * 数据 */ private T date; /** * 发生错误的页面 */ private StringBuffer url; public ErrorInfo(String code, String message, T date) { this.code = code; this.message = message; this.date = date; } }
true
82c16594b95cb5476be33d9d092fa80d4252aa50
Java
541205249/TestModeDemo
/app/src/main/java/testmode/eebbk/com/testmodedemo/statistician/AudioLogStatistician.java
UTF-8
2,396
2.65625
3
[]
no_license
package testmode.eebbk.com.testmodedemo.statistician; import java.util.List; import testmode.eebbk.com.testmodedemo.model.LogModule; import testmode.eebbk.com.testmodedemo.model.LogEntity; import testmode.eebbk.com.testmodedemo.model.ModuleEntity; /** * @author LiXiaoFeng * @date 2018/4/18 */ public class AudioLogStatistician implements LogStatistician { @Override public String statistics(ModuleEntity moduleEntity, List<LogEntity> logEntities) { if (logEntities == null) { return null; } int decibelNumber = 0; float minimalDecibel = 0f; float maximumDecibel = 0f; float totalDecibel = 0f; int samplingRateNumber = 0; float totalSamplingRate = 0f; for (LogEntity logEntity : logEntities) { if (logEntity == null) { return null; } switch (logEntity.getTarget()) { case LogModule.Audio.DECIBEL: { decibelNumber++; float decibel = logEntity.getValue(); if (decibel < minimalDecibel) { minimalDecibel = decibel; } if (decibel > maximumDecibel) { maximumDecibel = decibel; } totalDecibel += decibel; break; } case LogModule.Audio.SAMPLING_RATE: { samplingRateNumber++; float samplingRate = logEntity.getValue(); totalSamplingRate += samplingRate; break; } } } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("历史最低分贝:"); stringBuilder.append(minimalDecibel); stringBuilder.append("\n"); stringBuilder.append("历史最高分贝:"); stringBuilder.append(maximumDecibel); stringBuilder.append("\n"); stringBuilder.append("平均分贝:"); stringBuilder.append(decibelNumber == 0 ? 0 : totalDecibel / decibelNumber); stringBuilder.append("\n"); stringBuilder.append("平均采样率:"); stringBuilder.append(samplingRateNumber == 0 ? 0 : totalSamplingRate / samplingRateNumber + "%"); return stringBuilder.toString(); } }
true
983c2a2b636f6dc1495e5987914526a081c65578
Java
test0day/xmldecoder-payload-generator
/src/main/java/me/gv7/woodpecker/plugin/payloads/HttplogPayloadGenerator.java
UTF-8
1,326
2.34375
2
[]
no_license
package me.gv7.woodpecker.plugin.payloads; import me.gv7.woodpecker.plugin.*; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttplogPayloadGenerator implements IHelper { public String getHelperTabCaption() { return "httplog"; } public IArgsUsageBinder getHelperCutomArgs() { IArgsUsageBinder argsUsageBinder = XMLDecoderPlugin.pluginHelper.createArgsUsageBinder(); List<IArg> args = new ArrayList<IArg>(); IArg args1 = XMLDecoderPlugin.pluginHelper.createArg(); args1.setName("url"); args1.setDefaultValue("http://127.0.0.1/ok"); args1.setDescription("httplog server url"); args1.setRequired(true); args.add(args1); argsUsageBinder.setArgsList(args); return argsUsageBinder; } public void doHelp(Map<String, Object> customArgs, IResultOutput resultOutput) throws Throwable { String url = (String)customArgs.get("url"); String payload = String.format("<java>\n" + " <new class=\"java.net.URL\">\n" + " <string>%s</string>\n" + " <void method=\"getContent\"/>\n" + " </new>\n" + "</java>",url); resultOutput.rawPrintln("\n" + payload + "\n"); } }
true
d0e2816cdf871f90c95863b6a05b3a61092729ab
Java
sandeepkumaaar/COVID-19_TRACKER_Android_APP
/app/src/main/java/com/example/covid_19trackerapp/OnboardingActivity.java
UTF-8
1,516
2.046875
2
[]
no_license
package com.example.covid_19trackerapp; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager2.widget.ViewPager2; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import com.example.covid_19trackerapp.adapters.OnboardingAdapter; import com.example.covid_19trackerapp.fragments.SlideOneFragment; import com.example.covid_19trackerapp.fragments.SlideThreeFragment; import com.example.covid_19trackerapp.fragments.SlideTwoFragment; public class OnboardingActivity extends AppCompatActivity { ViewPager2 viewpager2Slider; OnboardingAdapter onboardingAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_onboarding); viewpager2Slider = findViewById(R.id.viewpager2_slider); setupViewpager(viewpager2Slider); } private void setupViewpager(ViewPager2 viewpager2Slider) { onboardingAdapter = new OnboardingAdapter(getSupportFragmentManager(),getLifecycle()); onboardingAdapter.addFragment(new SlideOneFragment()); onboardingAdapter.addFragment(new SlideTwoFragment()); onboardingAdapter.addFragment(new SlideThreeFragment()); viewpager2Slider.setAdapter(onboardingAdapter); } }
true
f52274948168037daf8081ed43ccddcab15ab1d3
Java
STAMP-project/dspot-experiments
/benchmark/test/org/apache/hadoop/hbase/util/TestBloomFilterChunk.java
UTF-8
8,844
2.25
2
[]
no_license
/** * 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.hadoop.hbase.util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.nio.ByteBuffer; import junit.framework.TestCase; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.nio.MultiByteBuff; import org.apache.hadoop.hbase.testclassification.MiscTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.junit.ClassRule; import org.junit.experimental.categories.Category; import static Hash.MURMUR_HASH; @Category({ MiscTests.class, SmallTests.class }) public class TestBloomFilterChunk extends TestCase { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestBloomFilterChunk.class); public void testBasicBloom() throws Exception { BloomFilterChunk bf1 = new BloomFilterChunk(1000, ((float) (0.01)), MURMUR_HASH, 0); BloomFilterChunk bf2 = new BloomFilterChunk(1000, ((float) (0.01)), MURMUR_HASH, 0); bf1.allocBloom(); bf2.allocBloom(); // test 1: verify no fundamental false negatives or positives byte[] key1 = new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] key2 = new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 7 }; bf1.add(key1, 0, key1.length); bf2.add(key2, 0, key2.length); TestCase.assertTrue(BloomFilterUtil.contains(key1, 0, key1.length, new MultiByteBuff(bf1.bloom), 0, ((int) (bf1.byteSize)), bf1.hash, bf1.hashCount)); TestCase.assertFalse(BloomFilterUtil.contains(key2, 0, key2.length, new MultiByteBuff(bf1.bloom), 0, ((int) (bf1.byteSize)), bf1.hash, bf1.hashCount)); TestCase.assertFalse(BloomFilterUtil.contains(key1, 0, key1.length, new MultiByteBuff(bf2.bloom), 0, ((int) (bf2.byteSize)), bf2.hash, bf2.hashCount)); TestCase.assertTrue(BloomFilterUtil.contains(key2, 0, key2.length, new MultiByteBuff(bf2.bloom), 0, ((int) (bf2.byteSize)), bf2.hash, bf2.hashCount)); byte[] bkey = new byte[]{ 1, 2, 3, 4 }; byte[] bval = Bytes.toBytes("this is a much larger byte array"); bf1.add(bkey, 0, bkey.length); bf1.add(bval, 1, ((bval.length) - 1)); TestCase.assertTrue(BloomFilterUtil.contains(bkey, 0, bkey.length, new MultiByteBuff(bf1.bloom), 0, ((int) (bf1.byteSize)), bf1.hash, bf1.hashCount)); TestCase.assertTrue(BloomFilterUtil.contains(bval, 1, ((bval.length) - 1), new MultiByteBuff(bf1.bloom), 0, ((int) (bf1.byteSize)), bf1.hash, bf1.hashCount)); TestCase.assertFalse(BloomFilterUtil.contains(bval, 0, bval.length, new MultiByteBuff(bf1.bloom), 0, ((int) (bf1.byteSize)), bf1.hash, bf1.hashCount)); // test 2: serialization & deserialization. // (convert bloom to byte array & read byte array back in as input) ByteArrayOutputStream bOut = new ByteArrayOutputStream(); bf1.writeBloom(new DataOutputStream(bOut)); ByteBuffer bb = ByteBuffer.wrap(bOut.toByteArray()); BloomFilterChunk newBf1 = new BloomFilterChunk(1000, ((float) (0.01)), MURMUR_HASH, 0); TestCase.assertTrue(BloomFilterUtil.contains(key1, 0, key1.length, new MultiByteBuff(bb), 0, ((int) (newBf1.byteSize)), newBf1.hash, newBf1.hashCount)); TestCase.assertFalse(BloomFilterUtil.contains(key2, 0, key2.length, new MultiByteBuff(bb), 0, ((int) (newBf1.byteSize)), newBf1.hash, newBf1.hashCount)); TestCase.assertTrue(BloomFilterUtil.contains(bkey, 0, bkey.length, new MultiByteBuff(bb), 0, ((int) (newBf1.byteSize)), newBf1.hash, newBf1.hashCount)); TestCase.assertTrue(BloomFilterUtil.contains(bval, 1, ((bval.length) - 1), new MultiByteBuff(bb), 0, ((int) (newBf1.byteSize)), newBf1.hash, newBf1.hashCount)); TestCase.assertFalse(BloomFilterUtil.contains(bval, 0, bval.length, new MultiByteBuff(bb), 0, ((int) (newBf1.byteSize)), newBf1.hash, newBf1.hashCount)); TestCase.assertFalse(BloomFilterUtil.contains(bval, 0, bval.length, new MultiByteBuff(bb), 0, ((int) (newBf1.byteSize)), newBf1.hash, newBf1.hashCount)); System.out.println((("Serialized as " + (bOut.size())) + " bytes")); TestCase.assertTrue((((bOut.size()) - (bf1.byteSize)) < 10));// ... allow small padding } public void testBloomFold() throws Exception { // test: foldFactor < log(max/actual) BloomFilterChunk b = new BloomFilterChunk(1003, ((float) (0.01)), MURMUR_HASH, 2); b.allocBloom(); long origSize = b.getByteSize(); TestCase.assertEquals(1204, origSize); for (int i = 0; i < 12; ++i) { byte[] ib = Bytes.toBytes(i); b.add(ib, 0, ib.length); } b.compactBloom(); TestCase.assertEquals((origSize >> 2), b.getByteSize()); int falsePositives = 0; for (int i = 0; i < 25; ++i) { byte[] bytes = Bytes.toBytes(i); if (BloomFilterUtil.contains(bytes, 0, bytes.length, new MultiByteBuff(b.bloom), 0, ((int) (b.byteSize)), b.hash, b.hashCount)) { if (i >= 12) falsePositives++; } else { TestCase.assertFalse((i < 12)); } } TestCase.assertTrue((falsePositives <= 1)); // test: foldFactor > log(max/actual) } public void testBloomPerf() throws Exception { // add float err = ((float) (0.01)); BloomFilterChunk b = new BloomFilterChunk(((10 * 1000) * 1000), ((float) (err)), MURMUR_HASH, 3); b.allocBloom(); long startTime = System.currentTimeMillis(); long origSize = b.getByteSize(); for (int i = 0; i < ((1 * 1000) * 1000); ++i) { byte[] ib = Bytes.toBytes(i); b.add(ib, 0, ib.length); } long endTime = System.currentTimeMillis(); System.out.println((("Total Add time = " + (endTime - startTime)) + "ms")); // fold startTime = System.currentTimeMillis(); b.compactBloom(); endTime = System.currentTimeMillis(); System.out.println((("Total Fold time = " + (endTime - startTime)) + "ms")); TestCase.assertTrue((origSize >= ((b.getByteSize()) << 3))); // test startTime = System.currentTimeMillis(); int falsePositives = 0; for (int i = 0; i < ((2 * 1000) * 1000); ++i) { byte[] bytes = Bytes.toBytes(i); if (BloomFilterUtil.contains(bytes, 0, bytes.length, new MultiByteBuff(b.bloom), 0, ((int) (b.byteSize)), b.hash, b.hashCount)) { if (i >= ((1 * 1000) * 1000)) falsePositives++; } else { TestCase.assertFalse((i < ((1 * 1000) * 1000))); } } endTime = System.currentTimeMillis(); System.out.println((("Total Contains time = " + (endTime - startTime)) + "ms")); System.out.println(("False Positive = " + falsePositives)); TestCase.assertTrue((falsePositives <= (((1 * 1000) * 1000) * err))); // test: foldFactor > log(max/actual) } public void testSizing() { int bitSize = (8 * 128) * 1024;// 128 KB double errorRate = 0.025;// target false positive rate // How many keys can we store in a Bloom filter of this size maintaining // the given false positive rate, not taking into account that the n long maxKeys = BloomFilterUtil.idealMaxKeys(bitSize, errorRate); TestCase.assertEquals(136570, maxKeys); // A reverse operation: how many bits would we need to store this many keys // and keep the same low false positive rate? long bitSize2 = BloomFilterUtil.computeBitSize(maxKeys, errorRate); // The bit size comes out a little different due to rounding. TestCase.assertTrue(((((Math.abs((bitSize2 - bitSize))) * 1.0) / bitSize) < 1.0E-5)); } public void testFoldableByteSize() { TestCase.assertEquals(128, BloomFilterUtil.computeFoldableByteSize(1000, 5)); TestCase.assertEquals(640, BloomFilterUtil.computeFoldableByteSize(5001, 4)); } }
true
140f3e23f1766f30cbf115c6b0d188c5b5539cf7
Java
xzq52788/tools
/src/main/java/com/rengu/tools7/filter/JwtLoginFilter.java
UTF-8
4,528
2.46875
2
[]
no_license
package com.rengu.tools7.filter; import com.fasterxml.jackson.databind.ObjectMapper; import com.rengu.tools7.entity.User; import com.rengu.tools7.utils.JsonResultUtil; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.Date; /** * @author Zeng * @date 2020/2/25 11:16 */ public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter { public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) { super(new AntPathRequestMatcher(defaultFilterProcessesUrl)); setAuthenticationManager(authenticationManager); } /** * 从登录参数中提取出用户名密码, 然后调用 AuthenticationManager.authenticate() 方法去进行自动校验 * @param req * @param resp * @return * @throws AuthenticationException * @throws IOException * @throws ServletException */ @Override public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse resp) throws AuthenticationException, IOException, ServletException { String username = req.getParameter("username"); String password = req.getParameter("password"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); return getAuthenticationManager().authenticate(token); } /** * 校验成功的回调函数,生成jwt的token * @param req * @param resp * @param chain * @param authResult * @throws IOException * @throws ServletException */ @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse resp, FilterChain chain, Authentication authResult) throws IOException, ServletException { Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities(); StringBuffer roles = new StringBuffer(); //遍历用户角色,将其写入jwt中 for (GrantedAuthority authority : authorities) { roles.append(authority.getAuthority()) .append(","); } String jwt = Jwts.builder() .claim("authorities", roles)//配置用户角色 .setSubject(authResult.getName())//设置jwt的主题为用户的用户名 .setExpiration(new Date(System.currentTimeMillis() + 10 * 60 * 1000))//设置过期时间为10分钟 .signWith(SignatureAlgorithm.HS512,"turing-team") //使用密钥对头部和载荷进行签名 .compact();//生成jwt //返回给前端 resp.setContentType("application/json;charset=utf-8"); PrintWriter out = resp.getWriter(); User user = (User) authResult.getPrincipal(); user.setToken(jwt); JsonResultUtil jsonResultUtil = JsonResultUtil.success("登录成功", user); System.out.println(jsonResultUtil.toString()); out.write(new ObjectMapper().writeValueAsString(jsonResultUtil)); out.flush(); out.close(); } /** * 校验失败的回调函数 * @param req * @param resp * @param failed * @throws IOException * @throws ServletException */ @Override protected void unsuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp, AuthenticationException failed) throws IOException, ServletException { resp.setContentType("application/json;charset=utf-8"); PrintWriter out = resp.getWriter(); JsonResultUtil failure = JsonResultUtil.failure("用户名或密码错误,请重新登录!", null); out.write(new ObjectMapper().writeValueAsString(failure)); out.flush(); out.close(); } }
true
7d5a94656a1f0bb9df17debfb8267ecec63df2f3
Java
dev-nguyenhoanganh/Java-Course
/Day 27 - Java Swing/32_Day 27_Ex2_RGB Color/src/com/luvina/btvn/gui/panel/checkBoxPanel.java
UTF-8
2,736
2.6875
3
[]
no_license
/** * @Project_Name 32_Day 27_Ex2_RGB Color */ package com.luvina.btvn.gui.panel; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JCheckBox; import com.luvina.btvn.gui.GUI; import com.luvina.btvn.gui.icommon.IChangeColor; /** * @author Hoang Anh * @since 20 thg 1, 2021 * @version 1.0 */ @SuppressWarnings("serial") public class checkBoxPanel extends BasePanel { private static final int MARGIN_TOP = 25; private static final int MARGIN_LEFT = 20; private static final int COLOR_DEPTH = 255; private IChangeColor event; private JCheckBox cbRed; private JCheckBox cbBlue; private JCheckBox cbGreen; private int red = 0; private int green = 0; private int blue = 0; public void addGUI(IChangeColor event) { this.event = event; } @Override public void init() { setSize(200, 200); setLayout(null); setLocation(150, 90); // setBackground(Color.green); } @Override public void addComponent() { // FontMetrics fm = getFontMetrics(GUI.fontNormal); cbRed = new JCheckBox("Red"); cbRed.setFont(GUI.fontNormal); cbRed.setSize(cbRed.getPreferredSize()); cbRed.setLocation(MARGIN_LEFT, MARGIN_TOP); cbBlue = new JCheckBox("Blue"); cbBlue.setFont(GUI.fontNormal); cbBlue.setSize(cbBlue.getPreferredSize()); cbBlue.setLocation(MARGIN_LEFT, MARGIN_TOP + cbRed.getY() + cbRed.getHeight()); cbGreen = new JCheckBox("Green"); cbGreen.setFont(GUI.fontNormal); cbGreen.setSize(cbGreen.getPreferredSize()); cbGreen.setLocation(MARGIN_LEFT, MARGIN_TOP + cbBlue.getY() + cbBlue.getHeight()); add(cbRed); add(cbBlue); add(cbGreen); } @Override public void addEvent() { checkBoxAction(); } // ------------------------ Private layer ------------------------ /** * */ private void changeColor(int red, int green, int blue) { if (red == 0 && green == 0 && blue == 0) { event.changeColor(Color.pink); } else { event.changeColor(new Color(red, green, blue)); } } /** * */ private void checkBoxAction() { cbRed.setName("red"); cbGreen.setName("green"); cbBlue.setName("blue"); ActionListener action = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String name = ((JCheckBox) e.getSource()).getName(); switch (name) { case "red": red = cbRed.isSelected() ? COLOR_DEPTH : 0; break; case "green": green = cbGreen.isSelected() ? COLOR_DEPTH : 0; break; case "blue": blue = cbBlue.isSelected() ? COLOR_DEPTH : 0; break; } changeColor(red, green, blue); } }; cbRed.addActionListener(action); cbGreen.addActionListener(action); cbBlue.addActionListener(action); } }
true
7d6cc8658ba4e4b8e1462c8e028a44dfa0422f08
Java
liuyiling/coding
/coding-spring/src/main/java/com/liuyiling/spring/ioc/IocBeanDecorator.java
UTF-8
569
2.890625
3
[]
no_license
package com.liuyiling.spring.ioc; /** * Created by liuyl on 15/12/7. */ public class IocBeanDecorator implements IocBean{ private IocBean iocBean; public IocBeanDecorator() { System.out.println("IocBeanDecorator init"); } @Override public void sayHello() { System.out.println("decorator begin"); iocBean.sayHello(); System.out.println("decorator end"); } public IocBean getIocBean() { return iocBean; } public void setIocBean(IocBean iocBean) { this.iocBean = iocBean; } }
true
3ad9b79d535c6ee0681c2e1d0c90466758dd120b
Java
Gieey/springboot-quartz-demo
/src/main/java/com/gieey/boot/quartz/job/MyJob.java
UTF-8
517
2.078125
2
[]
no_license
package com.gieey.boot.quartz.job; import com.gieey.boot.quartz.service.ServiceSample; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; /** * @author china_ */ public class MyJob implements Job { @Autowired ServiceSample serviceSample; @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { serviceSample.hello(); } }
true
d0c7c07a259bce3407ff6c3924af7081bbb433e4
Java
ianfahning/gaycity
/app/src/main/java/project/gaycity/ui/childViewHolder.java
UTF-8
3,795
2.203125
2
[]
no_license
package project.gaycity.ui; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import project.gaycity.R; import project.gaycity.expandableRecyclerView.viewholders.ChildViewHolder; import project.gaycity.ui.connect.ConnectFragment; import project.gaycity.ui.getInvolved.GiveFragment; import project.gaycity.ui.getInvolved.VolunteerFragment; import project.gaycity.ui.getInvolved.VoteFragment; import project.gaycity.ui.health.AppointmentFragment; import project.gaycity.ui.health.HealthCareFragment; import project.gaycity.ui.health.PrepFragment; import project.gaycity.ui.health.TestResultsFragment; import project.gaycity.ui.home.HomeFragment; import project.gaycity.ui.resources.ORCAFragment; import project.gaycity.ui.resources.OutreachFragment; import project.gaycity.ui.resources.QCCFragment; import project.gaycity.ui.resources.ResourcesDatabaseFragment; import project.gaycity.ui.resources.TechnicalFragment; public class childViewHolder extends ChildViewHolder { public TextView textView; private final ImageView imageView; public childViewHolder(View itemView){ super(itemView); textView = itemView.findViewById(R.id.lblListItem); imageView = itemView.findViewById(R.id.imgView); } public void bind(subHeader model, FragmentManager fm, DrawerLayout drawer) { textView.setText(model.name); //if the model is not supposed change fragments and the image or fragment in non zero that means //that it is supposed to show an image and the value in the imageOrFragment is an image if (!model.isFragment && model.imageOrFragment != 0) { imageView.setImageResource(model.imageOrFragment); imageView.setVisibility(View.VISIBLE); //if the model is supposed to change fragments then set the on click. this means that the //imageOrFragment value is a fragment } else if (model.isFragment) { View.OnClickListener changeFragment = v -> { fm.beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.nav_host_fragment, findFragment(model.imageOrFragment), null).commit(); drawer.close(); }; textView.setOnClickListener(changeFragment); } } private Fragment findFragment(int num){ switch(num){ case R.id.fragment_home: return new HomeFragment(); case R.id.fragment_appointment: return new AppointmentFragment(); case R.id.fragment_test_results: return new TestResultsFragment(); case R.id.fragment_prep: return new PrepFragment(); case R.id.fragment_health_care: return new HealthCareFragment(); case R.id.fragment_resources_database: return new ResourcesDatabaseFragment(); case R.id.fragment_qcc: return new QCCFragment(); case R.id.fragment_orca: return new ORCAFragment(); case R.id.fragment_outreach: return new OutreachFragment(); case R.id.fragment_technical: return new TechnicalFragment(); case R.id.fragment_volunteer: return new VolunteerFragment(); case R.id.fragment_vote: return new VoteFragment(); case R.id.fragment_give: return new GiveFragment(); case R.id.fragment_connect: return new ConnectFragment(); } return new HomeFragment(); } }
true
df593a29ac5d45873195a0544c556fe4897b3c47
Java
Faxar/Cards
/Deck.java
UTF-8
956
3.3125
3
[]
no_license
package com.company; import java.sql.Connection; import java.util.*; /** * Created by vassili.holenev on 4.04.2016. */ public class Deck { private Stack<Card> myCollection; private String name; public Deck(String name) { this.name = name; this.myCollection = new Stack<>(); } public String getName() { return name; } public int amountCardsInDeck(){ return myCollection.size(); } public void populateDeck(Card card){ myCollection.push(card); } public void shuffle(){ Collections.shuffle(myCollection); } public Card fetch(){ if(!myCollection.empty()){ return myCollection.pop(); } return null; } public void showCards(){ for(int i=0; i<myCollection.size(); i++){ System.out.println(myCollection.get(i)); } } }
true
fab764620965d6dfd97ca0eef9f60831d26de864
Java
anushapala/application
/application/src/com/login/loginpage/LoginPageServlet.java
UTF-8
1,867
2.328125
2
[]
no_license
package com.login.loginpage; import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginPageServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) { String username=request.getParameter("username"); String password=request.getParameter("password"); PersistenceManager pm= PMF.get().getPersistenceManager(); username=username.trim(); Query query=pm.newQuery(User.class); query.declareParameters("String loginUser,String loginPass"); query.setFilter("username==loginUser && password==loginPass"); try { response.setContentType("text/html"); List<User> results = (List<User>)query.execute(username,password); if (!results.isEmpty()) { for(User user:results) { HttpSession session = request.getSession(); session.setAttribute("firstname", user.getFirst_name()); session.setAttribute("lastname", user.getLast_name()); session.setAttribute("username", user.getUsername()); session.setAttribute("emailid", user.getEmail_id()); session.setAttribute("gender", user.getGender()); session.setAttribute("userId", user.getKey()); } response.sendRedirect("/LoginSuccess.jsp"); } else { String loginpage ="/LoginPage.jsp"; response.getWriter().println("<html><head><body><p>login failed! </p><a href='"+loginpage+"'> LogIn </a></body></head></html>"); } } catch(Exception e) { e.printStackTrace(); } finally { query.closeAll(); } } }
true
6e786d02b7c904224546811741d6c227a3129ad7
Java
XuhuiLee/configServer
/src/main/java/com/createarttechnology/config/service/ReadService.java
UTF-8
4,574
2.234375
2
[]
no_license
package com.createarttechnology.config.service; import com.createarttechnology.config.bean.AppConfig; import com.createarttechnology.config.util.InnerUtil; import com.createarttechnology.logger.Logger; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.createarttechnology.jutil.StringUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.zookeeper.data.Stat; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.security.InvalidParameterException; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by lixuhui on 2018/11/12. */ @Service public class ReadService { private static final Logger logger = Logger.getLogger(ReadService.class); @Resource private ZKService zkService; public List<AppConfig> getConfigList() throws Exception { List<String> profileList = zkService.getInstance().getChildren().forPath(InnerUtil.getRoot()); if (CollectionUtils.isEmpty(profileList)) { return null; } List<AppConfig> configList = Lists.newArrayList(); for (String profile : profileList) { List<String> configNameList = zkService.getInstance().getChildren().forPath(InnerUtil.getConfigRoot(profile)); if (CollectionUtils.isEmpty(configNameList)) { continue; } for (String configName : configNameList) { int version = zkService.getInstance().checkExists().forPath(InnerUtil.getConfigFilePath(profile, configName)).getVersion(); byte[] configContent = zkService.getInstance().getData().forPath(InnerUtil.getConfigFilePath(profile, configName)); AppConfig config = new AppConfig(); config.setConfigName(configName); config.setConfigContent(InnerUtil.convert(configContent)); config.setProfile(profile); config.setVersion(version); configList.add(config); } } Collections.sort(configList, new Comparator<AppConfig>() { @Override public int compare(AppConfig o1, AppConfig o2) { return o1.getConfigName().compareTo(o2.getConfigName()); } }); return configList; } public AppConfig getConfig(String profile, String configName, int version) throws Exception { Preconditions.checkArgument(StringUtil.isNotEmpty(configName)); Preconditions.checkArgument(version > -2); Stat stat = zkService.getInstance().checkExists().forPath(InnerUtil.getConfigNamePath(profile, configName)); if (stat == null) { throw new InvalidParameterException("configName invalid"); } // 去掉trunk int configVersion = stat.getNumChildren() - 1; if (version == -1) { String configNamePath = InnerUtil.getConfigFilePath(profile, configName); byte[] configContent = zkService.getInstance().getData().forPath(configNamePath); AppConfig config = new AppConfig(); config.setConfigName(configName); config.setConfigContent(InnerUtil.convert(configContent)); config.setVersion(configVersion); config.setProfile(profile); return config; } else { if (version > configVersion) { throw new InvalidParameterException("version invalid"); } List<String> tagList = zkService.getInstance().getChildren().forPath(InnerUtil.getConfigNamePath(profile, configName)); if (CollectionUtils.isNotEmpty(tagList) && version + 1 < tagList.size()) { Collections.sort(tagList, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); String curConfigName = tagList.get(version + 1); byte[] configContent = zkService.getInstance().getData().forPath(InnerUtil.getConfigTagFilePath(profile, configName, curConfigName)); AppConfig config = new AppConfig(); config.setConfigName(configName); config.setConfigContent(InnerUtil.convert(configContent)); config.setProfile(profile); config.setVersion(configVersion); return config; } } return null; } }
true
c8d677ee3b5125d6b2b9f405830b30a7a1dd806c
Java
sakshisacharoyo/HotelManagementSystem
/src/main/java/com/hms/hotelmanagementsystem/Controller/CityController.java
UTF-8
1,010
2.203125
2
[]
no_license
package com.hms.hotelmanagementsystem.Controller; import com.hms.hotelmanagementsystem.entities.City; import com.hms.hotelmanagementsystem.entities.State; import com.hms.hotelmanagementsystem.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class CityController { @Autowired CityService cityService; @RequestMapping(value = "/createCity", method = RequestMethod.POST) public void createState(@RequestBody City city){ cityService.createCity(city); } @RequestMapping(value = "/getAllCity" , method = RequestMethod.GET) public List<City> getAllCity(){ List<City> cityList = cityService.getAllCity(); return cityList; } }
true
4d79dcc966695bbb5f3e67b90a3c4384b404ce32
Java
muckleproject/muckle
/src/org/sh/muckle/runtime/js/HttpErrorWrapper.java
UTF-8
1,887
2.1875
2
[ "Apache-2.0" ]
permissive
package org.sh.muckle.runtime.js; /* Copyright 2013 The Muckle Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import org.mozilla.javascript.Scriptable; import org.sh.muckle.jssupport.AbstractReadOnlyScriptable; import org.sh.muckle.runtime.EHttpCommsError; import org.sh.muckle.runtime.ICommsErrorVisitor; public class HttpErrorWrapper extends AbstractReadOnlyScriptable implements ICommsErrorVisitor{ EHttpCommsError error; Boolean isConnect; Boolean isSend; Boolean isReceive; public Object get(String name, Scriptable scope) { Object property = null; if("isConnect".equals(name)){ property = isConnect; } else if("isSend".equals(name)){ property = isSend; } else if("isReceive".equals(name)){ property = isReceive; } return property; } public String getClassName() { return "HttpError"; } public HttpErrorWrapper setError(EHttpCommsError error) { this.error = error; error.accept(this); return this; } //-------------------------- public Object visitConnect() { isConnect = true; isSend = false; isReceive = false; return null; } public Object visitSend() { isConnect = false; isSend = true; isReceive = false; return null; } public Object visitReceive() { isConnect = false; isSend = false; isReceive = true; return null; } }
true
649631e4ca051e97a9f1b063b611afd655ecc2b4
Java
te253111/work
/app/src/main/java/com/myproject/repaircar/fragment/SampleFragment.java
UTF-8
636
2.125
2
[]
no_license
package com.myproject.repaircar.fragment; import android.os.Bundle; import android.view.View; import com.myproject.repaircar.base.BaseFragment; /** * Created by Semicolon07 on 4/20/2017 AD. */ public class SampleFragment extends BaseFragment { public static SampleFragment newInstance() { SampleFragment fragment = new SampleFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override protected int getLayoutId() { return 0; } @Override protected void initInstances(View rootView, Bundle savedInstanceState) { } }
true
4845cc2eac3c16b5306947d1108e793d73e101e7
Java
oguzeker/betting-store
/store-core/src/main/java/com/betting/store/util/HashcodeUtil.java
UTF-8
797
2.546875
3
[]
no_license
package com.betting.store.util; import lombok.experimental.UtilityClass; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.HashCodeBuilder; @UtilityClass public class HashcodeUtil { public final String REGEX = "[^0-9]"; public final int BASE_TWO = 2; public final int NUMBER_ZERO = 0; public int buildHashcode(final int PRIME, String documentId) { String extractedId = documentId.replaceAll(REGEX, StringUtils.EMPTY); int id = Integer.parseInt(extractedId.subSequence(NUMBER_ZERO, extractedId.length() / BASE_TWO).toString()); return new HashCodeBuilder(isNumberEven(id) ? ++id : id, PRIME).toHashCode(); } private boolean isNumberEven(int number) { return number % BASE_TWO == NUMBER_ZERO; } }
true
2b9b673571bd4a4f8832a9661fddf49e0910ac5e
Java
suholee0612/Java_Fundamental
/src/java_20190722/MethodDemo.java
UTF-8
1,987
4.09375
4
[]
no_license
package java_20190722; public class MethodDemo { // 5~8 라인까지 메소드를 정의. // boolean 메소드의 반환값 // instance 메소드 // int year => 매개변수(parameter) public boolean isLeafYear(int year) { // 메소드의 반환값이 boolean이기 때문에 return value의 value도 boolean이어야 한다. return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; } // String msg , int index => 매개변수(parameter) public char charofString(String msg, int index) { // String msg = "hello"; 0이면 h 반환, 1이면 e가 반환... return msg.charAt(index); } public long plus(int first, int second) { return (long) first + (long) second; } public double divide(int first, int second) { return (double) second / (double) first; } public void ascending(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length - (i + 1); j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } public static void main(String[] args) { MethodDemo m1 = new MethodDemo(); // 인스턴스 메소드의 사용방법 // 객체를 생성한 후에 reference(m1)를 이용해서 호출하면 됨 // 2019 => 전달인자(argument) boolean isLeafYear = m1.isLeafYear(236); System.out.println(isLeafYear); System.out.println(new MethodDemo().isLeafYear(2019)); // "hello", 0 => 전달인자 char c = m1.charofString("hello", 0); System.out.println(c); long sum = m1.plus(2100000000, 2100000000); System.out.println(sum); double divide = m1.divide(3, 5); System.out.println(divide); int[] temp = { 1, 2, 3, 4, 5, 41, 6, 25, 11 }; for (int a : temp) { System.out.print(a + "\t"); } System.out.println(); m1.ascending(temp); for (int a : temp) { System.out.print(a + "\t"); } System.out.println(); } }
true
432cf21fcfc859a7983bd2144b0307558e38be4b
Java
guillermo-chang/Module_I
/proyectos-main/Proyectos/Proyecto3/src/proyecto3/Proyecto3.java
UTF-8
1,032
3.0625
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 proyecto3; import Helpers.Empleado; import Helpers.Empleo; /** * * @author proyectos */ public class Proyecto3 { /** * @param args the command line arguments */ public static void main(String[] args) { Empleo empleo = new Empleo(); Empleado e1 = new Empleado("Nayi", "Ramirez", 18000); empleo.addEmpleado(e1); Empleado e2 = new Empleado("Alfredo", "Ramirez", 15000); empleo.addEmpleado(e2); empleo.imprimir(); /** * Aumento del %10 */ e1.aumentar(10); e2.aumentar(10); empleo.imprimir(); System.out.println("====================="); System.out.println("Número de empleados que han pasado en la empresa: " + empleo.getEmpleados().size()); } }
true
12621775c57700ec674a7525ebf4be5a355c4ac0
Java
lkp1985/crawler
/src/com/lkp/project/baidulvyou/BdlyDto.java
UTF-8
3,031
1.929688
2
[]
no_license
package com.lkp.project.baidulvyou; public class BdlyDto { private String sid;//景点ID private String url; private String lytype;//旅游类型:古镇、海边 private String name;//景点名称 private String impression;//景点简要描述 private String mor_desc;//详细描述 private String price;// private String bestvisittime; private String besttime; private String traffic; private String map_info; private String address; private String jingdianhref; private String score; private String commentnum; private String point; public String getScore() { return score; } public void setScore(String score) { this.score = score; } public String getCommentnum() { return commentnum; } public void setCommentnum(String commentnum) { this.commentnum = commentnum; } public String getPoint() { return point; } public void setPoint(String point) { this.point = point; } public String getSid() { return sid; } public void setSid(String id) { this.sid = id; } public String getLytype() { return lytype; } public void setLytype(String lytype) { this.lytype = lytype; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImpression() { return impression; } public void setImpression(String impression) { this.impression = impression; } public String getMor_desc() { return mor_desc; } public void setMor_desc(String mor_desc) { this.mor_desc = mor_desc; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getBestvisittime() { return bestvisittime; } public void setBestvisittime(String bestvisittime) { this.bestvisittime = bestvisittime; } public String getBesttime() { return besttime; } public void setBesttime(String besttime) { this.besttime = besttime; } public String getTraffic() { return traffic; } public void setTraffic(String traffic) { this.traffic = traffic; } public String getMap_info() { return map_info; } public void setMap_info(String map_info) { this.map_info = map_info; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getTicket_info() { return ticket_info; } public void setTicket_info(String ticket_info) { this.ticket_info = ticket_info; } public String getOpen_time_desc() { return open_time_desc; } public void setOpen_time_desc(String open_time_desc) { this.open_time_desc = open_time_desc; } public String getJingdianhref() { return jingdianhref; } public void setJingdianhref(String jingdianhref) { this.jingdianhref = jingdianhref; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } private String phone; private String ticket_info; private String open_time_desc; }
true
bceba59a1c56e9542313a6c729ef11fc7c62aae1
Java
Thomas-X/old-repos
/javaopdrachten/src/hoofdstuk14/opdracht1.java
UTF-8
1,573
3.3125
3
[]
no_license
package hoofdstuk14; import java.applet.Applet; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Created by Thomas on 10/29/2016. */ public class opdracht1 extends Applet { Button button1; @Override public void init() { super.init(); button1 = new Button("RollCards"); button1.addActionListener(new ButtonCheck()); add(button1); } @Override public void paint(Graphics g) { super.paint(g); } class ButtonCheck implements ActionListener { @Override public void actionPerformed(ActionEvent e) { Graphics g = getGraphics(); g.clearRect(0,0, getWidth(), getHeight()); int random1 = (int) (Math.random() * 4 + 0); int random2 = (int) (Math.random() * 13 + 0); String[] cards1 = new String[5]; cards1[0] = "Clubs"; cards1[1] = "Spades"; cards1[2] = "Hearts"; cards1[3] = "Diamonds"; String[] cards2 = new String[13]; cards2[0] = "2"; cards2[1] = "3"; cards2[2] = "4"; cards2[3] = "5"; cards2[4] = "6"; cards2[5] = "7"; cards2[6] = "8"; cards2[7] = "9"; cards2[8] = "10"; cards2[9] = "Jack"; cards2[10] = "Queen"; cards2[11] = "King"; cards2[12] = "Ace"; g.drawString("" + (cards1[random1]) + " " + (cards2[random2]), 50, 50); } } }
true
35b67b6aa9b1807ef1f9a14d5ea0f27aec430ddb
Java
CU-Boulder-Phd-work/TestCaseGenerator
/src/bentleyhoang/test/Test.java
UTF-8
763
2.265625
2
[]
no_license
package bentleyhoang.test; import bentleyhoang.com.control.KMaxWeightPathsAlg; import bentleyhoang.com.model.Graph; import bentleyhoang.com.model.State; import bentleyhoang.com.model.Vertex; public class Test { public static void main(String[] args) { String dataFilePath = "C://Users//hoang//Documents//workspace//TestCasesGenerator//src//bentleyhoang//test//LTS.txt"; String resultFilePath = "C://Users//hoang//Documents//workspace//TestCasesGenerator//src//bentleyhoang//test//TC.txt"; Graph graph = new Graph(dataFilePath); KMaxWeightPathsAlg alg = new KMaxWeightPathsAlg(graph); Vertex v0 = new Vertex(new State("S0", 0, 0)); Vertex v5 = new Vertex(new State("S5", 2, 10)); alg.findPathsHaveKMaxLength(v0, v5, 8, resultFilePath); } }
true
3c245e8d1b5a69dc540b0cafb01fb19e93cc711c
Java
RenatFayzullin/InfaWithSidikov
/semestr one/InfaHoWo/src/main/java/ru/itis/dto/CarDto.java
UTF-8
313
1.890625
2
[]
no_license
package ru.itis.dto; import lombok.*; @Getter @Setter @EqualsAndHashCode @Builder @ToString public class CarDto { private Integer id; private String title; private String description; private Integer price; private String model; private Integer markLogoId; private String country; }
true
0e8d3de0b067061d3a494a3920ed2bca5e1faa83
Java
lioncub3/AdroidProjects
/PrivateImager/app/src/main/java/com/example/privateimager/PImageAdapter.java
UTF-8
1,754
2.296875
2
[]
no_license
package com.example.privateimager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.io.FileInputStream; import java.util.List; public class PImageAdapter extends ArrayAdapter<PImage> { private LayoutInflater inflater; private int layout; private List<PImage> pImages; public PImageAdapter(Context context, int resource, List<PImage> pImages) { super(context, resource, pImages); this.pImages = pImages; this.layout = resource; this.inflater = LayoutInflater.from(context); } public View getView(int position, View convertView, ViewGroup parent) { View view = inflater.inflate(this.layout, parent, false); ImageView imageView = view.findViewById(R.id.imageView); TextView nameView = view.findViewById(R.id.name); PImage pImage = pImages.get(position); nameView.setText(pImage.getName()); if (pImage.getPath() != null) { FileInputStream fin = null; try { Bitmap bitmap = null; fin = getContext().openFileInput(pImage.getPath()); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; bitmap = BitmapFactory.decodeStream(fin, null, options); imageView.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); } } return view; } }
true
5694c00038b0db878a37688f87b943a32779ae82
Java
aljazmedic/eclipse-git
/Programming Problems/src/Problems/Euler11.java
WINDOWS-1250
5,183
2.703125
3
[]
no_license
package Problems; public class Euler11 { public static void main(String[] args) { // v polju najde 4 prilena tevila(|, -, /, \), ki imajo skupaj najveji // produkt.... stvar ni e optimalno prilagojena Grid theGrid = new Grid("08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 " + "49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 " + "81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 " + "52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 " + "22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 " + "24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 " + "32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 " + "67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 " + "24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 " + "21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 " + "78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 " + "16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 " + "86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 " + "19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 " + "04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 " + "88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 " + "04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 " + "20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 " + "20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 " + "01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48", 20, 20, 2); // Grid theGrid = new Grid("1 0 3 4 5" // + " 6 7 8 4 2" // + " 4 0 6 2 4" // + " 9 9 5 0 7" // + " 3 8 4 7 2", 5, 5, 1); int maxProduct = Math.max(horizontalProduct(theGrid, 4), verticalProduct(theGrid, 4)); int maxDiag = Math.max(Diag1Product(theGrid, 4), Diag2Product(theGrid, 4)); System.out.println(); System.out.println(Math.max(maxProduct, maxDiag)); } private static int Diag1Product(Grid theGrid,int numberOfnumbers) { // SV-JZ int currPro, maxPro = 0; String maxLocation = ""; for (int y = numberOfnumbers - 1; y < theGrid.numOfRows; y++) for (int x = 0; x < theGrid.numOfCols - numberOfnumbers; x++) { currPro = 1; for (int p = 0; p < numberOfnumbers; p++) { currPro *= theGrid.cells[y - p][x + p]; maxLocation = (currPro > maxPro) ? "DiagSV-JZ " + y + ":" + x + " " + (y - numberOfnumbers) + ":" + (x + numberOfnumbers) : maxLocation; maxPro = (currPro > maxPro) ? currPro : maxPro; } } System.out.println(maxLocation); return maxPro; } private static int Diag2Product(Grid theGrid,int numberOfnumbers) { // SZ-JV int currPro, maxPro = 0; String maxLocation = ""; for (int y = 0; y <= theGrid.numOfRows - numberOfnumbers; y++) for (int x = 0; x <= theGrid.numOfCols - numberOfnumbers; x++) { currPro = 1; for (int p = 0; p < numberOfnumbers; p++) { currPro *= theGrid.cells[y + p][x + p]; maxLocation = (currPro > maxPro) ? "DiagSZ-JV " + y + ":" + x + " " + (y + numberOfnumbers) + ":" + (x + numberOfnumbers) : maxLocation; maxPro = (currPro > maxPro) ? currPro : maxPro; } } System.out.println(maxLocation); return maxPro; } private static int verticalProduct(Grid theGrid, int numberOfnumbers) { int currPro, maxPro = 0; String maxLocation = ""; for (int y = 0; y < theGrid.numOfRows; y++) for (int x = 0; x <= theGrid.numOfCols - numberOfnumbers; x++) { currPro = 1; for (int p = 0; p < numberOfnumbers; p++) { currPro *= theGrid.cells[y][x + p]; maxLocation = (currPro > maxPro) ? "Vertical " + y + ":" + x + " " + y + ":" + (x + numberOfnumbers) : maxLocation; maxPro = (currPro > maxPro) ? currPro : maxPro; } } System.out.println(maxLocation); return maxPro; } private static int horizontalProduct(Grid theGrid, int numberOfnumbers) { int currPro, maxPro = 0; String maxLocation = ""; for (int y = 0; y <= theGrid.numOfRows - numberOfnumbers; y++) for (int x = 0; x < theGrid.numOfCols; x++) { currPro = 1; for (int p = 0; p < numberOfnumbers; p++) { currPro *= theGrid.cells[y + p][x]; maxLocation = (currPro > maxPro) ? "Horizontal " + y + ":" + x + " " + (y + numberOfnumbers) + ":" + x : maxLocation; maxPro = (currPro > maxPro) ? currPro : maxPro; } } System.out.println(maxLocation); return maxPro; } public static class Grid { int numOfCols, numOfRows, numberChars; StringBuffer stringGrid; boolean valid; int[][] cells; public Grid(String str, int w, int h, int nc) { numOfCols = w; numOfRows = h; numberChars = nc; stringGrid = new StringBuffer(str); valid = ((str.length() + 1) % (numberChars + 1) == 0) ? true : false; int counter = 0; if (valid) { cells = new int[w][h]; for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[0].length; j++) { cells[i][j] = Integer.parseInt(stringGrid.substring(counter, counter + numberChars)); counter += numberChars + 1; } } } } } }
true
0e4863fb660da3b61ca18f346b3972a3be387679
Java
Carzy-jun/Algorithms
/src/com/lxj/algorithms/chapter1_4/BinarySearch.java
UTF-8
1,015
3.53125
4
[]
no_license
package com.lxj.algorithms.chapter1_4; public class BinarySearch { /// <summary> /// 用递归方法进行二分查找。 /// </summary> /// <param name="key">关键字。</param> /// <param name="a">查找范围。</param> /// <param name="lo">查找的起始下标。</param> /// <param name="hi">查找的结束下标。</param> /// <returns>返回下标,如果没有找到则返回 -1。</returns> public static int Rank(int key, int[] a, int lo, int hi) { if (hi < lo) return -1; int mid = (hi - lo) / 2 + lo; if (a[mid] == key) { int mini = Rank(key, a, lo, mid - 1); if (mini != -1) return mini; return mid; } else if (a[mid] < key) { return Rank(key, a, mid + 1, hi); } else return Rank(key, a, lo, mid - 1); } }
true
40230e096ffca33b461bbbdd72e8ae612ac44ed3
Java
FIFA-legend/MetrologyLab1
/src/main/java/by/bsuir/ChepinMetricsController.java
UTF-8
5,737
2.234375
2
[]
no_license
package by.bsuir; import by.bsuir.holshed.Container; import by.bsuir.chepin.ChepinMetrics; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.stage.FileChooser; import java.io.File; import java.util.LinkedList; import java.util.List; import java.util.Map; public class ChepinMetricsController { @FXML private Button OpenButton; @FXML private Button ReturnButton; @FXML private TableView<DTO> OperandTable; @FXML private TableColumn<DTO, String> OperandsNumber; @FXML private TableColumn<DTO, String> OperandsName; @FXML private TableColumn<DTO, String> Type; @FXML private TableColumn<DTO, String> InputOutputType; @FXML private TableColumn<DTO, String> OperandsCount; @FXML void initialize() { OperandsNumber.setCellValueFactory(number -> number.getValue().number.asString()); OperandsName.setCellValueFactory(name -> name.getValue().name); Type.setCellValueFactory(type -> type.getValue().type); InputOutputType.setCellValueFactory(type -> type.getValue().inputOutputType); OperandsCount.setCellValueFactory(count -> count.getValue().count.asString()); ReturnButton.setOnAction(actionEvent -> App.hideWindow("MainWindow.fxml")); OpenButton.setOnAction(actionEvent -> { FileChooser chooser = new FileChooser(); File file = chooser.showOpenDialog(App.getMainStage()); if (file != null) { if (!file.getAbsolutePath().endsWith(".txt")) { this.showError(); } else { ChepinMetrics metrics = new ChepinMetrics(new Container(), file); metrics.initLexemes(); Map<String, Integer> result = metrics.getOperatorsCount(metrics.getContainer().getOperands()); Map<String, String> chepinMetricsMap = metrics.chepinMetrics(result); Map<String, String> inputOutputMap = metrics.chepinInputOutputMetrics(chepinMetricsMap); ObservableList<DTO> observableList = FXCollections.observableList(this.convertMapToList(result, chepinMetricsMap, inputOutputMap)); OperandTable.setItems(observableList); showInformation(result, chepinMetricsMap, inputOutputMap); } } }); } private void showInformation(Map<String, Integer> spenMap, Map<String, String> chepinMap, Map<String, String> inputOutputMap) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText(null); alert.setTitle("Информация"); int summary = this.countSummarySpen(spenMap); double metrics = this.countMetrics(chepinMap); double inputOutputMetrics = this.countMetrics(inputOutputMap); String str = "Суммарный Спен программы - " + summary; str = str.concat(String.format("\nМетрика Чепина - %.2f\n", metrics)); str = str.concat(String.format("Метрика Чепина ввода/вывода - %.2f", inputOutputMetrics)); alert.setContentText(str); alert.showAndWait(); } private double countMetrics(Map<String, String> map) { int p = this.countType(map, "P"); int m = this.countType(map, "M"); int c = this.countType(map, "C"); int t = this.countType(map, "T"); return p + 2 * m + 3 * c + 0.5 * t; } private int countSummarySpen(Map<String, Integer> map) { return map.values() .stream() .mapToInt(count -> count) .sum(); } private int countType(Map<String, String> chepinMap, String type) { return (int) chepinMap.values() .stream() .filter(value -> value.equals(type)) .count(); } private void showError() { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setTitle("Ошибка"); alert.setContentText("Откройте файл с расширением .txt"); alert.showAndWait(); } private List<DTO> convertMapToList(Map<String, Integer> map, Map<String, String> chepikMap, Map<String, String> inputOutputMap) { List<DTO> list = new LinkedList<>(); int number = 1; for (Map.Entry<String, Integer> entry : map.entrySet()) { String str; str = inputOutputMap.getOrDefault(entry.getKey(), "-"); list.add(new DTO(number++, entry.getKey(), chepikMap.get(entry.getKey()), str, entry.getValue())); } return list; } private static class DTO { IntegerProperty number; StringProperty name; StringProperty type; StringProperty inputOutputType; IntegerProperty count; public DTO(Integer number, String name, String type, String inputOutputType, Integer count) { this.number = new SimpleIntegerProperty(number); this.name = new SimpleStringProperty(name); this.type = new SimpleStringProperty(type); this.inputOutputType = new SimpleStringProperty(inputOutputType); this.count = new SimpleIntegerProperty(count); } } }
true
dfa95e88446109d1ad4afc106c81c3895b5af1a5
Java
CodingClubGECB/practice-questions
/Java/Week-3/Q03_Average.java
UTF-8
445
3.796875
4
[]
no_license
//3.Write a program to find the average of numbers in an array. import java.util.*; public class Q03_Average{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); float avg = 0; for(int i = 0; i < n; ++i){ a.add(in.nextInt()); } for(int i = 0; i < n; ++i){ avg += a.get(i); } avg = avg / n; System.out.println(avg); } }
true
d4852eb6d8bb20432c7c79b9d56d4b1500c3d2e2
Java
hekescott/test
/app/src/main/java/com/example/heke/test/MyScrollView.java
UTF-8
4,543
2.671875
3
[]
no_license
package com.example.heke.test; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.ScrollView; /** * Created by heke on 18/7/4. */ public class MyScrollView extends ScrollView { String TAG ="MyScrollView"; GestureDetector gestureDetector; DefaultGestureListener defaultGestureListener; int totalH; Context context; Onsroll onsroll; public MyScrollView(Context context) { super(context); } public MyScrollView(Context context, AttributeSet attrs) { super(context, attrs); defaultGestureListener = new DefaultGestureListener(); gestureDetector = new GestureDetector(context,defaultGestureListener); this.context =context; } public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setOnsroll(Onsroll onsroll) { this.onsroll = onsroll; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); totalH += getMeasuredHeight(); } @Override public boolean onTouchEvent(MotionEvent ev) { if( gestureDetector.onTouchEvent(ev)) { return true; }else { return super.onTouchEvent(ev); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); } private class DefaultGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void onLongPress(MotionEvent e) { } /** * @param e1 The first down motion event that started the scrolling. @param e2 The move motion event that triggered the current onScroll. @param distanceX The distance along the X axis(轴) that has been scrolled since the last call to onScroll. This is NOT the distance between e1 and e2. @param distanceY The distance along the Y axis that has been scrolled since the last call to onScroll. This is NOT the distance between e1 and e2. 无论是用手拖动view,或者是以抛的动作滚动,都会多次触发 ,这个方法在ACTION_MOVE动作发生时就会触发 参看GestureDetector的onTouchEvent方法源码 * */ @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { Log.d(TAG, "onScroll: "+getTop()); Log.d(TAG, "onScrollY: "+getY()); // int showH = (int) (DensityUtils.getPhoneheight(context)- getTop()); // if(totalH>showH){ // onsroll.scrollDistacke(distanceY); // return true; // }else { // return false; // } return false; } /** * @param e1 第1个ACTION_DOWN MotionEvent 并且只有一个 * @param e2 最后一个ACTION_MOVE MotionEvent * @param velocityX X轴上的移动速度,像素/秒 * @param velocityY Y轴上的移动速度,像素/秒 * 这个方法发生在ACTION_UP时才会触发 参看GestureDetector的onTouchEvent方法源码 * * */ @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onDown(MotionEvent e) { return false; } @Override public boolean onDoubleTap(MotionEvent e) { return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } /** * 这个方法不同于onSingleTapUp,他是在GestureDetector确信用户在第一次触摸屏幕后,没有紧跟着第二次触摸屏幕,也就是不是“双击”的时候触发 * */ @Override public boolean onSingleTapConfirmed(MotionEvent e) { return false; } } public static interface Onsroll{ void scrollDistacke(float distanceY); } }
true
7abb5b75f443699cc1dad6a3f1797586349ccf00
Java
sagaryadavs/NisumCodeChallenges
/src/main/java/com/williams/sonoma/test/pages/ShoppingCartSection.java
UTF-8
1,325
2.609375
3
[]
no_license
package com.williams.sonoma.test.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import com.williams.sonoma.test.common.Global; /** * This class is responsible to store Web elements on Shopping Cart page and operations performed on it which we have used in our entire framework. */ public class ShoppingCartSection { public ShoppingCartSection(){ String ShoppingCartSectionIdentifier = "Shopping Cart | Williams Sonoma"; try { if (Global.driver.getTitle().contains(ShoppingCartSectionIdentifier)) { PageFactory.initElements(Global.driver, this); System.out.println("You are on Shopping Cart Section"); } else { System.out.println("you are not on Shopping Cart Section, Sorry i can't continue..."); Assert.fail("Shopping Cart Section not loaded.."); } } catch (Exception e) { } } @FindBy(xpath="//a[@class='moveToSFL save-for-later-link']") WebElement saveForLatrBtn; /** * Method saveForLater is responsible for moving the product to 'Save For Later' section. */ public SaveForLaterSection saveForLater(){ PageFactory.initElements(Global.driver, this); this.saveForLatrBtn.click(); return new SaveForLaterSection(); } }
true
a8d35e290507d417129f4e15e7c0802c263fc96a
Java
9ao2hen/MBlog
/src/main/java/com/mervyn/blog/service/BlogService.java
UTF-8
358
1.796875
2
[]
no_license
package com.mervyn.blog.service; import com.mervyn.blog.bean.BlogReq; import com.mervyn.blog.model.Blog; import com.mervyn.blog.util.PageInfo; public interface BlogService { /** * 保存blog * @param blogReq * @return */ public Blog saveBlog(BlogReq blogReq); Blog getBlog(BlogReq blogReq); PageInfo<Blog> queryBlogList(BlogReq blogReq); }
true
7b6e0e5e9400d8c240ca13bf7154c27265a9dd5d
Java
F7YYY/IT178
/APK/flappybirds/sources/org/andengine/a/c/b.java
UTF-8
686
2.203125
2
[ "MIT" ]
permissive
package org.andengine.a.c; import android.content.Context; public class b { private static String a = ""; public static a a(c cVar, Context context, String str) { a aVar; synchronized (cVar) { aVar = new a(cVar, cVar.c().load(context.getAssets().openFd(String.valueOf(a) + str), 1)); cVar.a(aVar); } return aVar; } public static void a() { a(""); } public static void a(String str) { if (str.endsWith("/") || str.length() == 0) { a = str; return; } throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); } }
true
ad255b9237bf9fe85a418c4aa986ca7df73384b3
Java
wisniewskikr/rep_cq5
/Cq5-helloWorld-37-redirect-component-link-servlet/src/main/java/pl/kwi/servlets/RedirectServlet.java
UTF-8
1,309
2.21875
2
[]
no_license
package pl.kwi.servlets; import java.io.IOException; import javax.servlet.ServletException; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.SlingAllMethodsServlet; @Component(immediate=true, metatype=false, label="EXAMPLE SERVLET") @Service @Properties(value = { @org.apache.felix.scr.annotations.Property(name="sling.servlet.methods", value={"GET"}), @org.apache.felix.scr.annotations.Property(name="sling.servlet.resourceTypes", value={"sling/servlet/default"}), @org.apache.felix.scr.annotations.Property(name="sling.servlet.selectors", value={"REDIRECT"}), @org.apache.felix.scr.annotations.Property(name="sling.servlet.extensions", value={"html"}) }) public class RedirectServlet extends SlingAllMethodsServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String redirectPath = request.getParameter("redirectPath") + ".html"; response.sendRedirect(redirectPath); } }
true
0d7ea32ca3bd4c6f11dd5f7c9d1bc8304f9a5683
Java
ebKim0327/0gan
/0gan/src/main/java/com/gan/user/dao/UserInfoDao.java
UTF-8
492
1.992188
2
[]
no_license
package com.gan.user.dao; import org.springframework.stereotype.Repository; import com.gan.user.db.DBManager; import com.gan.vo.UserVo; @Repository public class UserInfoDao { /** * 회원가입 * * @param * @return */ public int insertUser(UserVo user) { return DBManager.insertUser(user); } public UserVo selectUser(int user_num) { return DBManager.selectUser(user_num); } public UserVo getUser(String user_email) { return DBManager.getUser(user_email); } }
true
ffad8cb3673d0b58029e1174d9899a0fdb73c3f1
Java
bala4604/Taxi_Booking_System_JAVA
/src/taxiHold.java
UTF-8
636
2.828125
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. */ import java.lang.*; /** * * @author Balaji */ class taxiHold extends Thread { taxi t; taxiHold(taxi t) { this.t=t; } public void run() { t.isFree=false; try { System.out.println("Taxi id "+t.id+" is Assigned "); Thread.sleep(6000000);//10 sec but calculation = Math.abs(pp-dp)*60*60*1000 t.isFree=true; } catch(Exception e) { System.out.println(e); } } }
true
c47bd72eb757fb22b7fc2e3f129b4c6a7223d7da
Java
Organisationn/SeleniumJavaFrameWork1
/SeleniumFramework/src/test/java/listeners/TestNGListenerDemo2.java
UTF-8
798
2.640625
3
[]
no_license
package listeners; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /*i)If you want the listeners to be used by all methods then declare it at class level * ii)if you have more than one class where you have defined the listeners then mention all using comma separated value * inside @Listeners annotation*/ //@Listeners(listeners.TestNGListeners.class) public class TestNGListenerDemo2 { @Test public void test4() { System.out.println("I am inside test4"); } @Test public void test5() { System.out.println("I am inside test5"); } @Test public void test6() { System.out.println("I am inside test6"); throw new SkipException("This test is skipped"); } }
true
b146d1edaeac6a38b245d39634512680fab74070
Java
xcesco/kripton
/kripton-processor/src/test/java/sqlite/feature/contentprovider/staticmethod/Person.java
UTF-8
1,897
2.03125
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2015, 2017 Francesco Benincasa (info@abubusoft.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package sqlite.feature.contentprovider.staticmethod; import java.util.Date; import com.abubusoft.kripton.android.annotation.BindSqlColumn; import com.abubusoft.kripton.annotation.BindType; /** * The Class Person. */ @BindType public class Person { /** The id. */ public long id; /** The parent id. */ @BindSqlColumn(value = "alias_parent_id", parentEntity = Person.class, nullable = true) public long parentId; /** The birth city. */ public String birthCity; /** The birth day. */ public Date birthDay; /** The value. */ public long value; /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name the new name */ public void setName(String name) { this.name = name; } /** * Gets the surname. * * @return the surname */ public String getSurname() { return surname; } /** * Sets the surname. * * @param surname the new surname */ public void setSurname(String surname) { this.surname = surname; } /** The name. */ protected String name; /** The surname. */ protected String surname; }
true
b31a7fca001e83e128748615bde284af6313bc7f
Java
XuZiqi3015218159/lab1
/src/pack1/Main.java
UTF-8
324
2.90625
3
[]
no_license
package pack1; public class Main { int triangle(int a,int b,int c) { if( a < ( b + c ) && c < ( a + b ) && b < ( a + c ) && a > 0 && b > 0 && c > 0) { if( a == b && b == c) { return 1; } else if(a == b || b == c || a == c) { return 2; } else { return 3; } }else { return 0; } } }
true
e0b3e71f8d47f4ef64aaf568d734fa0824afd8f7
Java
WalterBejar/Comunicaciones_App
/app/src/main/java/com/pango/comunicaciones/adapter/NoticiaAdapter.java
UTF-8
4,777
1.960938
2
[]
no_license
package com.pango.comunicaciones.adapter; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.pango.comunicaciones.ActImgNot; import com.pango.comunicaciones.GlobalVariables; import com.pango.comunicaciones.MainActivity; import com.pango.comunicaciones.R; import com.pango.comunicaciones.Utils; import com.pango.comunicaciones.model.Noticias; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Created by Andre on 25/09/2017. */ public class NoticiaAdapter extends ArrayAdapter<Noticias> { private Context context; private List<Noticias> data = new ArrayList<Noticias>(); DateFormat formatoInicial = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00"); DateFormat formatoRender = new SimpleDateFormat("EEEE d 'de' MMMM 'de' yyyy"); public NoticiaAdapter(Context context, List<Noticias> data) { super(context, R.layout.public_noticias,data); this.data = data; this.context = context; } @Override public View getView(final int position, final View convertView, final ViewGroup parent) { //ViewHolder viewHolder; LayoutInflater inflater = LayoutInflater.from(context); View rowView=inflater.inflate(R.layout.public_noticias, null,true); ImageView icono = (ImageView) rowView.findViewById(R.id.icon_inicio); //TextView nNom_publicador = (TextView) rowView.findViewById(R.id.tx_publicador); TextView nFecha = (TextView) rowView.findViewById(R.id.txfecha); TextView nTitulo = (TextView) rowView.findViewById(R.id.titulo_noticia); ImageView nImagNot = (ImageView) rowView.findViewById(R.id.imag_not); TextView nDescripcion = (TextView) rowView.findViewById(R.id.txdesc); //TextView nDescs2= (TextView) rowView.findViewById(R.id.desc_inv); //asignando a las variables los valores obtenidos //final String tempNombre=data.get(position).getNom_publicador(); final String tempFecha=data.get(position).getFecha(); final String tempTitulo=data.get(position).getTitulo(); final String tempDescripcion=data.get(position).getDescripcion(); //cargar la data al layout////// icono.setImageResource(R.drawable.ic_noticia3); //nNom_publicador.setText(tempNombre); //nFecha.setText(tempFecha); Typeface face=Typeface.createFromAsset(context.getAssets(),"fonts/HelveticaThn.ttf"); try { nFecha.setTypeface(face); nFecha.setText(formatoRender.format(formatoInicial.parse(tempFecha))); } catch (ParseException e) { e.printStackTrace(); } Typeface face1=Typeface.createFromAsset(context.getAssets(),"fonts/HelveticaMed.ttf"); nTitulo.setTypeface(face1); nTitulo.setText(tempTitulo); nDescripcion.setTypeface(face); nDescripcion.setText(tempDescripcion); //comunicadoModel.setFecha(formatoRender.format(formatoInicial.parse(comunicado.getFecha()))); //nImagNot.setVisibility(View.GONE); int ds=data.get(position).getUrlmin().length(); if(ds==0) { //nDescs.setVisibility(View.VISIBLE); //nDescripcion.setVisibility(View.GONE); nImagNot.setVisibility(View.GONE); //nDescs.setText(tempDescripcion); }else { String dddf=data.get(position).getUrlmin(); Glide.with(context) .load(GlobalVariables.Urlbase + Utils.ChangeUrl(dddf)) .into(nImagNot); } nImagNot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GlobalVariables.listdetimg.clear(); GlobalVariables.flag_orienta=true; // ((ListView) parent).performItemClick(convertView, position, 0); Intent intent=new Intent(v.getContext(), ActImgNot.class); intent.putExtra("codreg",data.get(position).getCod_reg()); //intent.putExtra("url_img", GlobalVariables.Urlbase + data.get(position).getFiledata().get(0).replaceAll("\\s", "%20")); intent.putExtra("posIn",0); //intent.putExtra(ActVidDet.EXTRA_PARAM_ID, item.getId()); v.getContext().startActivity(intent); } }); return rowView; } }
true