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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1ff0604d1b6735e1c6acf4db589d80fa5b9f4e49 | Java | ramendushandilya/coreJavaConcepts | /MultiThreading/src/com/ramendu/basic/SemaphoreDemo.java | UTF-8 | 1,887 | 3.875 | 4 | [] | no_license | package com.ramendu.basic;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Semaphores maintain a set of permits
* acquire() - if a permit is available then take it
* release() - adds a permit
* Semaphore will just keep count of the number available
* new Semaphore(int permits, boolean fairnessFactor)
*
* In the below example we have create a semaphore with 3 permits
* If we have 12 threads trying to do a task, then at a time only 3 permits will be assigned by the semaphore
*/
enum Downloader {
INSTANCE;
//Creating a semaphore with three permits/slots with fairness factor as true
private Semaphore semaphore = new Semaphore(3, true);
public void downloadData() {
try {
//Acquire the semaphore
semaphore.acquire();
//Call download
download();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} finally {
//Once done release semaphore
semaphore.release();
}
}
private void download() {
System.out.println("Downloading from the web...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class SemaphoreDemo {
public static void main(String[] args) {
//Made use of Executors to create a thread pool
ExecutorService executors = Executors.newCachedThreadPool();
//Creating a certain number threads to access the downloadData() method
for(int i = 0 ; i < 2 ; i++) {
executors.execute(new Runnable() {
@Override
public void run() {
Downloader.INSTANCE.downloadData();
}
});
}
}
}
| true |
a4e957d1edb244280d43d3db8df1ac81c191b86f | Java | liuhyneusoft/thymeleaf3.0-demo | /src/main/java/com/web/UserEntity.java | UTF-8 | 1,326 | 2.328125 | 2 | [] | no_license | package com.web;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* Created by Administrator on 2017/6/4.
*/
public class UserEntity {
private Integer id;
@Size(max = 10,min = 2, message="备注: 长度2-10")
@NotEmpty(message="name: 不能为空")
@NotNull(message="name: 不能为空")
private String username;
private String password;
private String petname;
public UserEntity() {
}
public UserEntity(Integer id, String username, String password, String petname) {
this.id = id;
this.username = username;
this.password = password;
this.petname = petname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 String getPetname() {
return petname;
}
public void setPetname(String petname) {
this.petname = petname;
}
}
| true |
0ac9954ae0e2c882e9e4e5d5b0a10c4f9f65f566 | Java | Jahia/jahia | /taglib/src/main/java/org/jahia/taglibs/search/SuggestionsTag.java | UTF-8 | 8,227 | 1.757813 | 2 | [] | no_license | /*
* ==========================================================================================
* = JAHIA'S DUAL LICENSING - IMPORTANT INFORMATION =
* ==========================================================================================
*
* http://www.jahia.com
*
* Copyright (C) 2002-2023 Jahia Solutions Group SA. All rights reserved.
*
* THIS FILE IS AVAILABLE UNDER TWO DIFFERENT LICENSES:
* 1/Apache2 OR 2/JSEL
*
* 1/ Apache2
* ==================================================================================
*
* Copyright (C) 2002-2023 Jahia Solutions Group SA. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* 2/ JSEL - Commercial and Supported Versions of the program
* ===================================================================================
*
* IF YOU DECIDE TO CHOOSE THE JSEL LICENSE, YOU MUST COMPLY WITH THE FOLLOWING TERMS:
*
* Alternatively, commercial and supported versions of the program - also known as
* Enterprise Distributions - must be used in accordance with the terms and conditions
* contained in a separate written agreement between you and Jahia Solutions Group SA.
*
* If you are unsure which license is appropriate for your use,
* please contact the sales department at sales@jahia.com.
*/
package org.jahia.taglibs.search;
import org.jahia.exceptions.JahiaRuntimeException;
import org.jahia.registries.ServicesRegistry;
import org.jahia.services.render.RenderContext;
import org.jahia.services.search.SearchCriteria;
import org.jahia.services.search.Suggestion;
import org.slf4j.Logger;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import java.io.*;
import java.util.List;
/**
* Performs the content search and exposes search results for being displayed.
*
* @author Sergiy Shyrkov
*/
public class SuggestionsTag extends ResultsTag {
private static Logger logger = org.slf4j.LoggerFactory.getLogger(SuggestionsTag.class);
private static final long serialVersionUID = -4991766714209759529L;
private Suggestion suggestion;
private String suggestionVar = "suggestion";
private boolean runQuery = true;
private int maxTermsToSuggest = 1;
@Override
public int doEndTag() throws JspException {
if (suggestionVar != null) {
pageContext.removeAttribute(suggestionVar, PageContext.PAGE_SCOPE);
}
return super.doEndTag();
}
/*
* (non-Javadoc)
*
* @see org.jahia.taglibs.search.ResultsTag#getDefaultCountVarName()
*/
@Override
protected String getDefaultCountVarName() {
return "suggestedCount";
}
/*
* (non-Javadoc)
*
* @see org.jahia.taglibs.search.ResultsTag#getDefaultVarName()
*/
@Override
protected String getDefaultVarName() {
return "suggestedHits";
}
/*
* (non-Javadoc)
*
* @see
* org.jahia.taglibs.search.ResultsTag#getSearchCriteria(org.jahia.services
* .render.RenderContext)
*/
@Override
protected SearchCriteria getSearchCriteria(RenderContext ctx) {
SearchCriteria criteria = super.getSearchCriteria(ctx);
return criteria != null ? suggest(criteria) : null;
}
@Override
public int doStartTag() throws JspException {
int retVal = super.doStartTag();
if (retVal == SKIP_BODY && !runQuery) {
retVal = EVAL_BODY_INCLUDE;
} else if (retVal == EVAL_BODY_INCLUDE) {
final Object countVarValue = pageContext.getAttribute(getCountVar());
int count = countVarValue == null ? 0 : (Integer) countVarValue;
List<String> allSuggestions = suggestion.getAllSuggestions();
int iterationCount = 1;
while (count == 0 && iterationCount < allSuggestions.size()) {
SearchCriteria criteria = (SearchCriteria)pageContext.getAttribute(getSearchCriteriaVar());
SearchCriteria suggestedCriteria = cloneCriteria(criteria);
suggestedCriteria.getTerms().get(0).setTerm(allSuggestions.get(iterationCount));
count = searchAndSetAttributes(suggestedCriteria, getRenderContext());
if (count > 0) {
suggestion.setSuggestedQuery(allSuggestions.get(iterationCount));
}
iterationCount++;
}
}
return retVal;
}
/**
* @return the suggestion
*/
public Suggestion getSuggestion() {
return suggestion;
}
@Override
protected void resetState() {
suggestionVar = "suggestion";
suggestion = null;
runQuery = true;
maxTermsToSuggest = 1;
super.resetState();
}
public void setSuggestionVar(String suggestionVar) {
this.suggestionVar = suggestionVar;
}
private SearchCriteria suggest(SearchCriteria criteria) {
SearchCriteria suggestedCriteria = null;
if (!criteria.getTerms().isEmpty() && !criteria.getTerms().get(0).isEmpty()) {
suggestion = ServicesRegistry.getInstance().getSearchService().suggest(
criteria, getRenderContext(), maxTermsToSuggest);
if (logger.isDebugEnabled()) {
logger.debug("Suggestion for search query '" + criteria.getTerms().get(0).getTerm() + "' site '"
+ getRenderContext().getSite().getSiteKey() + "' and locale "
+ getRenderContext().getMainResourceLocale() + ": " + suggestion);
}
if (suggestion != null) {
if (suggestionVar != null) {
pageContext.setAttribute(suggestionVar, suggestion);
}
if (runQuery) {
// we've found a suggestion
suggestedCriteria = cloneCriteria(criteria);
suggestedCriteria.getTerms().get(0).setTerm(suggestion.getSuggestedQuery());
}
}
}
return suggestedCriteria;
}
private static SearchCriteria cloneCriteria(SearchCriteria criteria) {
SearchCriteria clone;
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
out = new ObjectOutputStream(bos);
out.writeObject(criteria);
in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
clone = (SearchCriteria) in.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new JahiaRuntimeException("Cannot clone criteria object", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
return clone;
}
public void setRunQuery(boolean runQuery) {
this.runQuery = runQuery;
}
public void setMaxTermsToSuggest(int maxTermsToSuggest) {
this.maxTermsToSuggest = maxTermsToSuggest;
}
}
| true |
74fa584729b483bb981f407341fd96eb1a459386 | Java | FuZhongWang/JD | /app/src/main/java/xudeyang/bawie/com/jd/model/UpdateCarts.java | UTF-8 | 1,228 | 2 | 2 | [] | no_license | package xudeyang.bawie.com.jd.model;
import android.content.Context;
import android.util.Log;
import java.util.Map;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import xudeyang.bawie.com.jd.utils.RxRetrofitUtil;
import xudeyang.bawie.com.jd.view.base.BaseBean;
/**
* Created by Mac on 2018/4/22.
*/
public class UpdateCarts {
private static final String TAG = "UpdateCarts";
public static void onUpdateCarts(Map<String,String> params, final Context context){
RxRetrofitUtil.doGet().getUpdateCarts(params)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableSubscriber<BaseBean>() {
@Override
public void onNext(BaseBean baseBean) {
Log.e(TAG, "onNext: "+baseBean.getCode() );
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
});
}
}
| true |
0f46d7b8bb7da6469c2dc7d22fa036caa3c84044 | Java | sycomix/OpenSource_Cryptography | /to_organize/catoblepas_web/phase_2/LOCAL/src/FileServer.java | UTF-8 | 17,843 | 2.75 | 3 | [] | no_license | /*
*Note: This is just a test code for a distributed crypto project I am
*working on as a hobby. Must fully test the functionality, then will optimize!
*/
import java.net.Socket;
import java.util.Scanner;
//import javax.swing.JOptionPane;
import java.io.*;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.InetAddress;
public class FileServer extends Thread implements Hello
{
public FileServer() {} //add code to possibly modify this and allow for some fix to give ip and port ?
public String sayHello(String filename)
{
//check if we have the file
//System.out.println("The requested file is : "+filename);
File f=new File(filename);
//File f=new File("../../what.jpg");
//System.out.println(filename);
if(f.exists())
{
return "YES";
}
else
{
return "NO";
}
}
public static void main(String args[]) throws IOException
{
new FileServer().start();
}
public void run()
{
int remote_RMI_port_integer1 = 0;
int remote_RMI_port_integer2 = 0;
int RMI_port_integer = 0;
String IP_Address_Remote_RMI1_string = "";
String IP_Address_Remote_RMI2_string = "";
String s = "";
Scanner scanServ = new Scanner(System.in);
System.out.println("What is the server port?");
String port_string = scanServ.nextLine();
int port_value = Integer.parseInt(port_string);
//Setting up connection!
ServerSocket ss=null;
try
{
ss=new ServerSocket(port_value);
}
catch(IOException e)
{
System.out.println("Couldn't Listen!");
System.exit(0);
}
//Add code here to bind to the RMI Registry
try
{
System.out.println("Local RMI Port: ");
String RMI_port_string = scanServ.nextLine();
System.out.println("IP Address of Remote Server 1: ");
IP_Address_Remote_RMI1_string = scanServ.nextLine();
System.out.println("Remote RMI Registry Port 1: ");
String remote_RMI_port_string1 = scanServ.nextLine();
System.out.println("IP Address of Remote Server 2: ");
IP_Address_Remote_RMI2_string = scanServ.nextLine();
System.out.println("Remote RMI Registry Port 2: ");
String remote_RMI_port_string2 = scanServ.nextLine();
InetAddress myIPAddress = InetAddress.getLocalHost();
//System.out.println(myIPAddress);
String hostaddress = myIPAddress.getHostAddress();
String registry_string = "IP: " + hostaddress + " Port: " + port_string;
System.out.println(registry_string);
FileServer obj = new FileServer();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Bind the remote object's stub in the registry
//add code to convert FROM STRING TO INTEGER!!!
RMI_port_integer = Integer.parseInt(RMI_port_string);
remote_RMI_port_integer1 = Integer.parseInt(remote_RMI_port_string1);
remote_RMI_port_integer2 = Integer.parseInt(remote_RMI_port_string2);
Registry registry = LocateRegistry.getRegistry(RMI_port_integer);
registry.bind(registry_string, stub);
Registry registry_remote1 = LocateRegistry.getRegistry(IP_Address_Remote_RMI1_string, remote_RMI_port_integer1);
Registry registry_remote2 = LocateRegistry.getRegistry(IP_Address_Remote_RMI2_string, remote_RMI_port_integer2);
//add code here also for the case of the ip address of the remote host! :)
System.err.println("Server ready");
}
catch (Exception e)
{
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
while(true)
{
System.out.println("Listening...");
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
try
{
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String x = st.readLine();
/***********************************************************************************************
****************************************Client Download!***************************************
***********************************************************************************************/
if(x.equals("1"))
{
System.out.println("\nAttempting to Send File to Client!");
s=st.readLine();
String testfilename = s;
System.out.println("The requested file is : "+s);
File f=new File(s);
//***********************SERVER HAS FILE**********************/
if(f.exists()) //server has the file, so we service the request
{
put.println("SERVER_HAS_FILE");
BufferedInputStream d=new BufferedInputStream(new FileInputStream(s));
BufferedOutputStream outStream = new BufferedOutputStream(cs.getOutputStream());
BufferedReader disb =new BufferedReader(new InputStreamReader(cs.getInputStream()));
int amountClientRead = Integer.parseInt(disb.readLine());
System.out.println("\n\n\nAMOUNT THE CLIENT HAS READ!" + amountClientRead);
if(amountClientRead > 0){System.out.println("\n\nRESUMING DOWNLOAD!!!");}
byte buffer[] = new byte[1024];
int read;
while((read = d.read(buffer))!=-1)
{
outStream.write(buffer, 0, read);
outStream.flush();
}
//put.println("SERVER_HAS_FILE");
d.close();
outStream.close();
System.out.println("File Transferred to Client Succesfully!");
cs.close();
}
//***********************SERVER DOES NOT HAVE REQUESTED FILE**********************/
else
{
System.out.println("Looks like we don't have the file on this server!");
//This server does not have the requested file!
//String host = (args.length < 1) ? null : args[0];
try
{
System.out.println("\nSending out a broadcast to the other servers to see if they have the file!");
//wait until receiving the responses...
Registry registry = LocateRegistry.getRegistry(RMI_port_integer);
String[] registry_list = registry.list();
String[] hasFileList = new String[registry_list.length]; //an array of strings for holding the ip&port of servers that have the file
System.out.println("DEBUGGING THIS");
Registry registry_remote1 = LocateRegistry.getRegistry(IP_Address_Remote_RMI1_string, remote_RMI_port_integer1);
String[] registry_list_remote1 = registry_remote1.list();
String[] hasFileList_remote1 = new String[registry_list_remote1.length]; //an array of strings for holding the ip&port of servers that have the file
Registry registry_remote2 = LocateRegistry.getRegistry(IP_Address_Remote_RMI2_string, remote_RMI_port_integer2);
String[] registry_list_remote2 = registry_remote2.list();
String[] hasFileList_remote2 = new String[registry_list_remote2.length]; //an array of strings for holding the ip&port of servers that have the file
System.out.println("I got here!!!");
//going through all of the entries in the registry, assuming we have fewer than 10000 servers
///*****************************************LOCAL check**********************/
try
{
int numHasFile = 0; //the number of mirrors with the requested file
int testcount = 0;
while(testcount < 10000)
{
System.out.println(registry_list[testcount]);
//add code fix here where you get rid of the hardcoded lookup! i.e. we will need to broadcast!
Hello stub = (Hello) registry.lookup(registry_list[testcount]);
//Hello stub = (Hello) registry.lookup("1235");
String response = stub.sayHello(testfilename);
System.out.println("response: " + response);
//response == yes, has file list places the value
if(response.equals("YES"))
{ //adds the ip and port values for servers which responded with yes to an array of strings!
hasFileList[numHasFile] = registry_list[testcount];
//System.out.println(hasFileList[numHasFile]);
numHasFile++;
}
testcount++;
//add code for NOW passing the list to the client!
//make a list based upon the responses to transmit the (IP Address, Port #)
//passing the responses from the broadcast back to the client here
}
}
catch(Exception fail)
{
System.out.println("registry end");
}
///*****************************************1st**********************/
try
{
int numHasFile = 0; //the number of mirrors with the requested file
int testcount = 0;
while(testcount < 10000)
{
System.out.println(registry_list_remote1[testcount]);
//add code fix here where you get rid of the hardcoded lookup! i.e. we will need to broadcast!
Hello stub1 = (Hello) registry_remote1.lookup(registry_list_remote1[testcount]);
String response_remote1 = stub1.sayHello(testfilename);
System.out.println("response: " + response_remote1);
//response == yes, has file list places the value
if(response_remote1.equals("YES"))
{ //adds the ip and port values for servers which responded with yes to an array of strings!
hasFileList_remote1[numHasFile] = registry_list_remote1[testcount];
//System.out.println(hasFileList[numHasFile]);
numHasFile++;
}
testcount++;
//add code for NOW passing the list to the client!
//make a list based upon the responses to transmit the (IP Address, Port #)
//passing the responses from the broadcast back to the client here
}
}
catch(Exception fail)
{
System.out.println("registry end 2");
}
////****************************************2nd**********************/
try
{
int numHasFile = 0; //the number of mirrors with the requested file
int testcount = 0;
while(testcount < 10000)
{
System.out.println(registry_list_remote2[testcount]);
//add code fix here where you get rid of the hardcoded lookup! i.e. we will need to broadcast!
Hello stub2 = (Hello) registry_remote2.lookup(registry_list_remote2[testcount]);
String response_remote2 = stub2.sayHello(testfilename);
System.out.println("response: " + response_remote2);
//response == yes, has file list places the value
if(response_remote2.equals("YES"))
{ //adds the ip and port values for servers which responded with yes to an array of strings!
hasFileList_remote2[numHasFile] = registry_list_remote2[testcount];
//System.out.println(hasFileList[numHasFile]);
numHasFile++;
}
testcount++;
//add code for NOW passing the list to the client!
//make a list based upon the responses to transmit the (IP Address, Port #)
//passing the responses from the broadcast back to the client here
}
}
catch(Exception fail)
{
System.out.println("registry end 3");
}
/*************************FORWARDING DETAILS OF MIRROR SERVERS TO CLIENT********************************************/
//print what you want to send to the client here from hasFileList arrays of strings for now
System.out.println("Will send these mirrors to the client: ");
try //ADD CODE HERE
{
//display the contents of the three arrays of strings concatenated!
//handle the case of no other servers being available
String[] combinedHasFileArray = new String[hasFileList.length + hasFileList_remote1.length + hasFileList_remote2.length];
System.arraycopy(hasFileList, 0, combinedHasFileArray, 0, hasFileList.length);
System.arraycopy(hasFileList_remote1, 0, combinedHasFileArray, hasFileList.length, hasFileList_remote1.length);
System.arraycopy(hasFileList_remote2, 0, combinedHasFileArray, hasFileList.length+hasFileList_remote1.length, hasFileList_remote2.length);
put.println("SERVER_NOT_HAVE_FILE");
System.out.println("THE CODE GOT HERE!");
int i = 0;
while(i < combinedHasFileArray.length)
{
put.println(combinedHasFileArray[i]);
System.out.println(combinedHasFileArray[i]); //add code to send this to client!!!
i++;
}
put.println("END!!!");
}
catch(Exception Noooooooooooo)
{
System.out.println("Noooooooo");
}
}
catch (Exception e)
{
System.err.println("Server without file exception: " + e.toString());
e.printStackTrace();
}
cs.close(); //temporarily have this to close the client socket!
}
}
/***********************************************************************************************
****************************************Client Upload!***************************************
***********************************************************************************************/
else if (x.equals("2"))
{
System.out.println("Attempting to Retrieve File from Client!");
s=st.readLine();
System.out.println("\nThe file to be uploaded is : "+s);
s = st.readLine();
System.out.println("\nThe uploading file will be stored here : "+s);
//Take the file from the client!!!
File test = new File(s);
/**************************RESUME CASE***********************************/
if(test.exists())
{
System.out.println("File already exists!");
System.out.println("Resuming!");
//get the amount of bytes already uploaded to the server by the client!
int amountRead = ((int) test.length()); //amount of bytes already read
System.out.println("THIS IS THE AMOUNT OF BYTES READ: " + amountRead);
FileOutputStream fs=new FileOutputStream(s, true);
BufferedInputStream d=new BufferedInputStream(cs.getInputStream());
//send file size to server
put.println(amountRead);
byte buffer[] = new byte[1024];
int read;
while((read = d.read(buffer))!=-1)
{
fs.write(buffer, 0, read);
fs.flush();
}
d.close();
System.out.println("File taken from client successfully!");
cs.close();
fs.close();
}
/**************************NORMAL CASE***********************************/
else
{
FileOutputStream fs=new FileOutputStream(s);
BufferedInputStream d=new BufferedInputStream(cs.getInputStream());
put.println(0); //send the file size as zero to the client so we know to send the full file
byte buffer[] = new byte[1024];
int read;
while((read = d.read(buffer))!=-1)
{
fs.write(buffer, 0, read);
fs.flush();
}
d.close();
System.out.println("File taken from client successfully!");
cs.close();
fs.close();
}
}
/***********************************************************************************************
****************************************Mirror Download!***************************************
***********************************************************************************************/
else if (x.equals("3"))
{
System.out.println("Service Discovery!");
//add code here to service the request
//this is where the client has selected this server for download after the initial server
//did not have the file!
//so basically just do a normal download ?
//this server is listening and a request comes in from another server
//to search the files located at this server
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
} | true |
cddd2fe2baa8a0df348a7aa64ec9adbd8f757ee8 | Java | u-ma-jak/innlevering3 | /Innlevering3/src/SnuTekst.java | UTF-8 | 503 | 3.53125 | 4 | [] | no_license | import java.util.Scanner;
public class SnuTekst {
public static void main(String[] args)
Scanner input = new Scanner(System.in);
System.out.print("Skriv inn en tekst: ");
String s = input.nextLine();
System.out.print("Teksten baklengs blir: ");
baklengs(s);
}
public static void baklengs(String tekst) {
if (tekst.length() > 0) {
System.out.print(tekst.charAt(tekst.length() - 1));
baklengs(tekst.substring(0, tekst.length() - 1));
}
}
}
| true |
df2629c33685a1765b1de631e4bdb8fc0d822dc7 | Java | auxor/android-wear-decompile | /decompiled/android/filterfw/core/Frame.java | UTF-8 | 41,412 | 1.953125 | 2 | [] | no_license | package android.filterfw.core;
import android.graphics.Bitmap;
import java.nio.ByteBuffer;
public abstract class Frame {
public static final int NO_BINDING = 0;
public static final long TIMESTAMP_NOT_SET = -2;
public static final long TIMESTAMP_UNKNOWN = -1;
private long mBindingId;
private int mBindingType;
private FrameFormat mFormat;
private FrameManager mFrameManager;
private boolean mReadOnly;
private int mRefCount;
private boolean mReusable;
private long mTimestamp;
Frame(android.filterfw.core.FrameFormat r1, android.filterfw.core.FrameManager r2) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.<init>(android.filterfw.core.FrameFormat, android.filterfw.core.FrameManager):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.<init>(android.filterfw.core.FrameFormat, android.filterfw.core.FrameManager):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e6
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.<init>(android.filterfw.core.FrameFormat, android.filterfw.core.FrameManager):void");
}
Frame(android.filterfw.core.FrameFormat r1, android.filterfw.core.FrameManager r2, int r3, long r4) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.<init>(android.filterfw.core.FrameFormat, android.filterfw.core.FrameManager, int, long):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.<init>(android.filterfw.core.FrameFormat, android.filterfw.core.FrameManager, int, long):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e6
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.<init>(android.filterfw.core.FrameFormat, android.filterfw.core.FrameManager, int, long):void");
}
protected static android.graphics.Bitmap convertBitmapToRGBA(android.graphics.Bitmap r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.convertBitmapToRGBA(android.graphics.Bitmap):android.graphics.Bitmap
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.convertBitmapToRGBA(android.graphics.Bitmap):android.graphics.Bitmap
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.convertBitmapToRGBA(android.graphics.Bitmap):android.graphics.Bitmap");
}
protected void assertFrameMutable() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.assertFrameMutable():void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.assertFrameMutable():void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.assertFrameMutable():void");
}
final int decRefCount() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.decRefCount():int
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.decRefCount():int
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e3
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.decRefCount():int");
}
public long getBindingId() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.getBindingId():long
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.getBindingId():long
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e4
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.getBindingId():long");
}
public int getBindingType() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.getBindingType():int
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.getBindingType():int
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e3
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.getBindingType():int");
}
public abstract Bitmap getBitmap();
public int getCapacity() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.getCapacity():int
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.getCapacity():int
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.getCapacity():int");
}
public abstract ByteBuffer getData();
public abstract float[] getFloats();
public android.filterfw.core.FrameFormat getFormat() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.getFormat():android.filterfw.core.FrameFormat
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.getFormat():android.filterfw.core.FrameFormat
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e5
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.getFormat():android.filterfw.core.FrameFormat");
}
public android.filterfw.core.FrameManager getFrameManager() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.getFrameManager():android.filterfw.core.FrameManager
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.getFrameManager():android.filterfw.core.FrameManager
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e5
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.getFrameManager():android.filterfw.core.FrameManager");
}
public abstract int[] getInts();
public abstract Object getObjectValue();
public int getRefCount() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.getRefCount():int
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.getRefCount():int
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e3
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.getRefCount():int");
}
public long getTimestamp() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.getTimestamp():long
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.getTimestamp():long
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e4
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.getTimestamp():long");
}
protected abstract boolean hasNativeAllocation();
final int incRefCount() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.incRefCount():int
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.incRefCount():int
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e3
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.incRefCount():int");
}
final void markReadOnly() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.markReadOnly():void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.markReadOnly():void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e6
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.markReadOnly():void");
}
public android.filterfw.core.Frame release() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.release():android.filterfw.core.Frame
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.release():android.filterfw.core.Frame
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e5
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.release():android.filterfw.core.Frame");
}
protected abstract void releaseNativeAllocation();
protected void reset(android.filterfw.core.FrameFormat r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.reset(android.filterfw.core.FrameFormat):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.reset(android.filterfw.core.FrameFormat):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.reset(android.filterfw.core.FrameFormat):void");
}
public android.filterfw.core.Frame retain() {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.retain():android.filterfw.core.Frame
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.retain():android.filterfw.core.Frame
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e5
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.retain():android.filterfw.core.Frame");
}
public abstract void setBitmap(Bitmap bitmap);
public void setData(java.nio.ByteBuffer r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setData(java.nio.ByteBuffer):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setData(java.nio.ByteBuffer):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setData(java.nio.ByteBuffer):void");
}
public abstract void setData(ByteBuffer byteBuffer, int i, int i2);
public void setData(byte[] r1, int r2, int r3) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setData(byte[], int, int):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setData(byte[], int, int):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setData(byte[], int, int):void");
}
public void setDataFromFrame(android.filterfw.core.Frame r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setDataFromFrame(android.filterfw.core.Frame):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setDataFromFrame(android.filterfw.core.Frame):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setDataFromFrame(android.filterfw.core.Frame):void");
}
public abstract void setFloats(float[] fArr);
protected void setFormat(android.filterfw.core.FrameFormat r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setFormat(android.filterfw.core.FrameFormat):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setFormat(android.filterfw.core.FrameFormat):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setFormat(android.filterfw.core.FrameFormat):void");
}
protected void setGenericObjectValue(java.lang.Object r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setGenericObjectValue(java.lang.Object):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setGenericObjectValue(java.lang.Object):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setGenericObjectValue(java.lang.Object):void");
}
public abstract void setInts(int[] iArr);
public void setObjectValue(java.lang.Object r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setObjectValue(java.lang.Object):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setObjectValue(java.lang.Object):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setObjectValue(java.lang.Object):void");
}
protected void setReusable(boolean r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setReusable(boolean):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setReusable(boolean):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e6
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setReusable(boolean):void");
}
public void setTimestamp(long r1) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.DecodeException: Load method exception in method: android.filterfw.core.Frame.setTimestamp(long):void
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:113)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:256)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:281)
at jadx.api.JavaClass.decompile(JavaClass.java:59)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:161)
Caused by: jadx.core.utils.exceptions.DecodeException: in method: android.filterfw.core.Frame.setTimestamp(long):void
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:46)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:98)
... 7 more
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e7
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1196)
at com.android.dx.io.OpcodeInfo.getFormat(OpcodeInfo.java:1212)
at com.android.dx.io.instructions.DecodedInstruction.decode(DecodedInstruction.java:72)
at jadx.core.dex.instructions.InsnDecoder.decodeInsns(InsnDecoder.java:43)
... 8 more
*/
/*
// Can't load method instructions.
*/
throw new UnsupportedOperationException("Method not decompiled: android.filterfw.core.Frame.setTimestamp(long):void");
}
public boolean isReadOnly() {
return this.mReadOnly;
}
protected boolean requestResize(int[] newDimensions) {
return false;
}
protected void onFrameStore() {
}
protected void onFrameFetch() {
}
final boolean isReusable() {
return this.mReusable;
}
}
| true |
ac0b5cc63ba9961b1255aa3f5c11ec758e2106e9 | Java | okellyson/jogo-da-vida | /src/application/Vida.java | UTF-8 | 1,994 | 3.328125 | 3 | [] | no_license | package application;
public class Vida {
private int tamanho;
private int field[][];
public Vida () {
this.tamanho = 6;
this.field = new int[this.tamanho][this.tamanho];
for (int i = 1; i < (this.tamanho - 1); i++) {
for (int j = 1; j < (this.tamanho - 1); j++) {
this.field[i][j] = (int) (Math.random() * 1.5);
}
}
}
private int getVizinho(int i, int j){
try {
return field[i][j];
} catch (Exception e) {
return 0;
}
}
public int contarVizinhos(int i, int j) {
// Linha acima
return getVizinho(i-1, j-1) +
getVizinho(i-1, j+1) +
getVizinho(i-1, j) +
// Linha atual
getVizinho(i, j-1) +
getVizinho(i, j+1) +
// Linha abaixo
getVizinho(i+1, j-1) +
getVizinho(i+1, j+1) +
getVizinho(i+1, j);
}
public int[][] proximaGeracao() {
int nextField[][] = new int[this.tamanho][this.tamanho];
int vizinhos = 0;
for (int i = 0; i < this.tamanho; i++) {
for (int j = 0; j < this.tamanho; j++) {
vizinhos = contarVizinhos(i, j);
if (field[i][j] == 1) {
if (vizinhos < 2 || vizinhos > 3) {
nextField[i][j] = 0;
} else {
nextField[i][j] = 1;
}
} else {
if (vizinhos == 3) {
nextField[i][j] = 1;
} else {
nextField[i][j] = 0;
}
}
}
}
return nextField;
}
public void simularNovaGeracao() {
imprimirTabuleiro();
this.field = proximaGeracao();
System.out.println("\nNova geração:");
imprimirTabuleiro();
System.out.println("---");
}
public void imprimirTabuleiro() {
System.out.println();
for (int i = 0; i < this.tamanho; i++) {
for (int j = 0; j < this.tamanho; j++) {
System.out.print(this.field[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public int getTamanho() {
return this.tamanho;
}
public int[][] getField() {
return this.field;
}
public void setField(int[][] matriz) {
this.field = matriz;
}
}
| true |
ead2e143cba89c104094e228a8b14ea3d694c502 | Java | marky-mark/MTT | /acceptance-tests/src/test/java/com/mtt/test/page/registration/RegisterForm.java | UTF-8 | 424 | 2.09375 | 2 | [] | no_license | package com.mtt.test.page.registration;
import com.mtt.test.page.BaseForm;
import org.openqa.selenium.WebDriver;
public class RegisterForm extends BaseForm {
public RegisterForm(WebDriver driver) {
super(driver);
}
@Override
protected String getSubmitButtonName() {
return "register-user";
}
@Override
protected String getFormName() {
return "register-form";
}
}
| true |
caf6ebbd990b10ca5da1966bb70013697ff2be8f | Java | nicolasssssguo/franklin | /src/tests/responders/RedirectResponderTest.java | UTF-8 | 1,035 | 2.4375 | 2 | [] | no_license | package tests.responders;
import httpserver.responders.RedirectResponder;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class RedirectResponderTest {
RedirectResponder responder;
Map<String, Object> request;
@Before
public void setUp() {
responder = new RedirectResponder("/fakefake");
request = new HashMap<>();
request.put("HTTP-Version", "HTTP/1.1");
request.put("Host", "www.fakesite.com");
}
@Test
public void testRedirect() {
Map<String, Object> response = responder.respond(request);
Map<String, String> headers = (Map<String, String>) response.get("message-header");
assertEquals("HTTP/1.1 301 Moved Permanently", response.get("status-line"));
assertEquals("http://www.fakesite.com/fakefake", headers.get("Location"));
assertNotNull(response.get("message-body"));
}
}
| true |
c46fa34041db8ef6b7a85b09d3ee0008cdad7e1f | Java | nathan2303/projet_software_groupe23 | /Group23_Projet_IS1220_part1_Nativel_Vermeersch/GUI_restaurant/AddDish.java | ISO-8859-1 | 2,480 | 2.640625 | 3 | [] | no_license | package GUI_restaurant;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import Food.Dessert;
import Food.Dish;
import Food.DishType;
import Food.MainDish;
import Food.Starter;
import Main.MyFoodora;
import Users.Restaurant;
public class AddDish extends ChangeMenu implements ActionListener{
JFrame frameA = new JFrame();
JPanel panA = new JPanel();
JTextField name = new JTextField("nom",20);
JTextField price = new JTextField("prix",20);
String[] dishTypes = {"entre","plat principal","dessert"};
JComboBox<String> type = new JComboBox<String>(dishTypes);
String[] dishTypes2 = {"Standard","Vegetarian",
"GlutenFree",
"VegetarianAndGlutenFree"};
JComboBox<String> type2 = new JComboBox<String>(dishTypes2);
JButton ok = new JButton("ok");
DishType d;
AddDish(){
frameA.add(panA);
frameA.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameA.setTitle("ajouter un plat");
frameA.setLocationRelativeTo(null);
frameA.setSize(800, 400);
panA.setLayout(new BoxLayout(dish,BoxLayout.PAGE_AXIS));
panA.add(name);
panA.add(price);
panA.add(type);
panA.add(type2);
panA.add(ok);
ok.addActionListener(this);
}
void actionPerformed(){
MyFoodora system = MyFoodora.getInstance();
Restaurant resto = new Restaurant();
resto = (Restaurant) system.getConnectedUser();
double pri = Double.parseDouble(price.getText());
switch(type2.getSelectedIndex()){
case 0:
d = DishType.Standard;
case 1:
d = DishType.Vegetarian;
case 2:
d = DishType.GlutenFree;
case 3:
d = DishType.VegetarianAndGlutenFree;
}
switch(type.getSelectedIndex()){
case 0:
resto.addDish(new Starter(pri,name.getText(),d));
case 1:
resto.addDish(new MainDish(pri,name.getText(),d));
case 2:
resto.addDish(new Dessert(pri,name.getText(),d));
}
frameA.setVisible(false);
JDialog dial = new JDialog();
JLabel lab = new JLabel("plat ajout la carte");
dial.add(lab);
dial.setLocationRelativeTo(null);
dial.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dial.setVisible(true);
dishes.addItem(name.getText());
}
} | true |
ce5357750b882b086524f842cdd828c993894669 | Java | Mohamedj23/DummyWebProject | /eventhub-data-access-layer/src/main/java/org/eventhub/dal/aspects/EncryptPassword.java | UTF-8 | 1,463 | 2.34375 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.eventhub.dal.aspects;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.eventhub.common.model.entity.SystemUser;
import org.eventhub.dal.utils.EncryptionUtils;
/**
* this aspect class to encrypt password before insert it in DataBase
*
* @author Amr Elkady <amrelkady93@gmail.com>
*/
@Aspect
public class EncryptPassword {
EncryptionUtils passwordencryptionUtility;
/**
* encrypt password of {@link org.eventhub.common.model.entity.SystemUser}
*
* @param joinPoint
* @return Object the result of insert object
*
*/
@Around("execution(* com.eventhub.model.dal.daos.SystemUserRepository.save(..))")
public Object beforeInsert(ProceedingJoinPoint joinPoint) {
Object[] arg = joinPoint.getArgs();
SystemUser systemUser = (SystemUser) arg[0];
String plainPassword = systemUser.getPassword();
String newPassword = EncryptionUtils.hash(plainPassword);
systemUser.setPassword(newPassword);
try {
return joinPoint.proceed();
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
}
| true |
232249777cba6d953308fe2099cdfed653de56b4 | Java | simunovic/ExerciseLeapwise | /src/main/java/com/rss/feed/logging/LoggerAspect.java | UTF-8 | 4,848 | 2.90625 | 3 | [] | no_license | package com.rss.feed.logging;
import java.lang.reflect.Method;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.logging.LogLevel;
import org.springframework.stereotype.Component;
import com.rss.feed.logging.annotation.LogEntryExit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
@Aspect
public class LoggerAspect {
/**
* Method is used for logging on entry and exit from methods annotated with
* LogEntryExit
*
* @param point Joint point, method that is annotated with LogEntryExit
* annotation
* @return Object that intercepted method returns
* @throws Throwable Throws propagated exception of intercepted method if one
* occurs
*/
@Around("@annotation(com.rss.feed.logging.annotation.LogEntryExit)")
public Object log(ProceedingJoinPoint point) throws Throwable {
CodeSignature codeSignature = (CodeSignature) point.getSignature();
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
Logger logger = LoggerFactory.getLogger(method.getDeclaringClass());
LogEntryExit annotation = method.getAnnotation(LogEntryExit.class);
LogLevel level = annotation.value();
ChronoUnit unit = annotation.unit();
boolean showArgs = annotation.showArgs();
boolean showResult = annotation.showResult();
boolean showExecutionTime = annotation.showExecutionTime();
String methodName = method.getName();
Object[] methodArgs = point.getArgs();
String[] methodParams = codeSignature.getParameterNames();
log(logger, level, entry(methodName, showArgs, methodParams, methodArgs));
Instant start = Instant.now();
Object response = point.proceed();
Instant end = Instant.now();
String duration = String.format("%s %s", unit.between(start, end), unit.name().toLowerCase());
log(logger, level, exit(methodName, duration, response, showResult, showExecutionTime));
return response;
}
/**
* Logging message with appropriated log level
*
* @param logger Logger instance that is responsible for logging
* @param level Log level
* @param message Message that needs to be logged
*/
static void log(Logger logger, LogLevel level, String message) {
switch (level) {
case DEBUG:
logger.debug(message);
case TRACE:
logger.trace(message);
case WARN:
logger.warn(message);
case ERROR:
logger.error(message);
default:
logger.info(message);
}
}
/**
* Method is used for logging method invocation and arguments intercepted on
* entry
*
* @param methodName Name of intercepted method
* @param showArgs Flag to toggle whether to display the arguments received by
* a method
* @param params Parameter names that intercepted method is invoked with
* @param args Parameter values that intercepted method is invoked with
* @return Message that needs to be logged
*/
static String entry(String methodName, boolean showArgs, String[] params, Object[] args) {
StringBuilder message = new StringBuilder().append("Started ").append(methodName).append(" method");
if (showArgs && Objects.nonNull(params) && Objects.nonNull(args) && params.length == args.length) {
Map<String, Object> values = new HashMap<>(params.length);
for (int i = 0; i < params.length; i++) {
values.put(params[i], args[i]);
}
message.append(" with args: ").append(values.toString());
}
return message.toString();
}
/**
* Method is used for logging method invocation and arguments intercepted on
* exit
*
* @param methodName Name of intercepted method
* @param duration Execution duration of intercepted method
* @param result Result that intercepted method returns
* @param showResult Flag to toggle whether to display the result
* returned by the method
* @param showExecutionTime Flag to toggle whether you want to log the time it
* takes the method to finish executing
* @return Message that needs to be logged
*/
static String exit(String methodName, String duration, Object result, boolean showResult,
boolean showExecutionTime) {
StringBuilder message = new StringBuilder().append("Finished ").append(methodName).append(" method");
if (showExecutionTime) {
message.append(" in ").append(duration);
}
if (showResult) {
message.append(" with return: ").append(result.toString());
}
return message.toString();
}
}
| true |
c285567073a16b2b7999c613cafd97d5c7bb779c | Java | duolagong/EAI_Adapter | /src/com/longtop/Util/PostMan/JmsUtil.java | UTF-8 | 1,896 | 2.4375 | 2 | [] | no_license | package com.longtop.Util.PostMan;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;
public class JmsUtil {
public String SendMessage(String message, String targetUrl, String targetFactoryName, String targetName,int time) {
boolean transacted = false;
int acknowledgementMode = Session.AUTO_ACKNOWLEDGE;
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, targetUrl);
try {
Context context = new InitialContext(properties);
Object obj = context.lookup(targetFactoryName);
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) obj;
obj = context.lookup(targetName);
Queue queue = (Queue) obj;
QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();// 产生连接
queueConnection.start();
QueueSession queueSession = queueConnection.createQueueSession(transacted, acknowledgementMode);
TextMessage textMessage = queueSession.createTextMessage();
textMessage.clearBody();
textMessage.setText(message);
QueueSender queueSender = queueSession.createSender(queue);
queueSender.setTimeToLive(time*1000);
queueSender.send(textMessage);
if (transacted) queueSession.commit();
if (queueSender != null) queueSender.close();
if (queueSession != null) queueSession.close();
if (queueConnection != null) queueConnection.close();
return "M0001发送成功";
} catch (Exception ex) {
ex.printStackTrace();
return "E9999发送失败" + ex.getMessage();
}
}
}
| true |
6d1713c2f70c9df525dc87d656c5f333f2366a36 | Java | CodeLpea/MicroPrc | /lpautosize/src/main/java/com/example/lp/lpautosize/AutoSizeUtils/Desity.java | UTF-8 | 2,162 | 2.4375 | 2 | [] | no_license | package com.example.lp.lpautosize.AutoSizeUtils;
import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
/**
* Desity
* 今日头条适配方案
* 简单,低成本
* */
public class Desity {
private static final float WIDTH=360;//参考设备的宽,单位是dp
private static float appDesity=0;//表示屏幕密度
private static float appScaleDensity=0;//字体缩放比例,默认为appDesity
//直接使用在BaseActivity中
public static void setAppDesity(final Application application, final Activity activity){
//获取到当前app的屏幕信息
DisplayMetrics displayMetrics=application.getResources().getDisplayMetrics();
if(appDesity==0){//初始化操作
appDesity=displayMetrics.density;
appScaleDensity=displayMetrics.scaledDensity;
//添加字体变化回调
application.registerComponentCallbacks(new ComponentCallbacks() {
@Override
public void onConfigurationChanged(Configuration newConfig) {
if(newConfig!=null&&newConfig.fontScale>0){
//字体变化,重新赋值,下次启动的时候就会改变
appScaleDensity=application.getResources().getDisplayMetrics().scaledDensity;
}
}
@Override
public void onLowMemory() {
}
});
}
float targetDensity=displayMetrics.widthPixels/WIDTH;//比如适配的设备是1080,那就是1080/360,目标desity=3;
float targetScaleDensity=targetDensity*(appScaleDensity/appDesity);//目标字体缩放比例
int targetDensityDpi=(int)(targetDensity*160);//目标DPi
//替换Activity的density,scaleDensity,desityDpi
DisplayMetrics dm=activity.getResources().getDisplayMetrics();
dm.density=targetDensity;
dm.scaledDensity=targetScaleDensity;
dm.densityDpi=targetDensityDpi;
}
}
| true |
7eb2a611e5efd548e76c25b3907952f7f0e0eb55 | Java | xiaoHzhuang/redisJwt | /src/main/java/com/inspur/goods/dao/GoodsMapper.java | UTF-8 | 516 | 1.984375 | 2 | [] | no_license | package com.inspur.goods.dao;
import com.inspur.goods.DO.Goods;
import com.inspur.goods.DO.GoodsQueryModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface GoodsMapper {
int insert(Goods record);
int insertSelective(Goods record);
void update(Goods record);
List<Goods> listGoods(GoodsQueryModel goodsQueryModel);
void deleteById(@Param("id") String id);
Goods getById(@Param("id") String id);
} | true |
eade87cb9ae217da2a89e4c08f0bfd98f9b6556e | Java | stolser/netty-http-server | /nettyserver/src/main/java/com/stolser/nettyserver/server/data/FullStatisticsData.java | UTF-8 | 8,478 | 2.34375 | 2 | [] | no_license | package com.stolser.nettyserver.server.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import com.google.common.base.Preconditions;
import com.stolser.nettyserver.server.handlers.MainHttpHandler;
public class FullStatisticsData implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(FullStatisticsData.class);
private static final Marker connectionCounterMarker = MarkerFactory.getMarker("connectionCounter");
private static final long serialVersionUID = 1236547L;
private static final String HTML_FILE_NAME = "response.html";
private static final int INITIAL_BUFFER_CAPACITY = 500;
private static final int LOG_ENTRY_MAX_NUMBER = 16;
private static final String DATE_FORMAT_PATTERN = "dd MMM kk:mm:ss";
transient private ConnectionData newData;
transient private String redirect;
private int numberOfUniqueRequests;
private List<IpAddressData> ipAddressDatas;
private ConcurrentNavigableMap<Date, ConnectionData> connectionDatas;
private ConcurrentNavigableMap<String, Integer> redirects;
private int totalNumberOfRequests;
private Integer numberOfActiveConn;
public FullStatisticsData() {
this.ipAddressDatas = new CopyOnWriteArrayList<IpAddressData>();
this.connectionDatas = new ConcurrentSkipListMap<Date, ConnectionData>();
this.redirects = new ConcurrentSkipListMap<String, Integer>();
this.totalNumberOfRequests = 0;
this.numberOfActiveConn = 0;
}
public void update(ConnectionData newData, int number, String redirect) {
Preconditions.checkNotNull(newData, "connection data may not be null.");
Preconditions.checkArgument(number >= 0, "number of active connections cannot be less than zero bytes.)");
this.newData = newData;
this.numberOfActiveConn = number;
this.redirect = redirect;
totalNumberOfRequests++;
logger.debug(connectionCounterMarker, "totalNumberOfRequests = {}", totalNumberOfRequests);
updateIpAddressData();
updateConnectionData();
updateRedirects();
}
public String generateHtmlContent() {
StringBuffer result = new StringBuffer(INITIAL_BUFFER_CAPACITY);
String[] htmlStrings = readHtmlStringsFromFile();
numberOfUniqueRequests = calculateUniqueRequestsNumber();
result.append(htmlStrings[0]).append(numberOfActiveConn)
.append(htmlStrings[1]).append(totalNumberOfRequests)
.append(htmlStrings[2]).append(numberOfUniqueRequests)
.append(htmlStrings[3]).append(generateHtmlForRequestsTable())
.append(htmlStrings[4]).append(generateHtmlForRedirectsTable())
.append(htmlStrings[5]).append(generateHtmlForLogTable())
.append(htmlStrings[6]);
return result.toString();
}
private int calculateUniqueRequestsNumber() {
AtomicInteger accumulator = new AtomicInteger(0);
ipAddressDatas.forEach(e -> {
accumulator.accumulateAndGet(e.getUniqueRequests().size(), ( a, b ) -> a + b);
});
return accumulator.intValue();
}
private String[] readHtmlStringsFromFile() {
String[] htmlStrings = new String[7];
File file = new File(HTML_FILE_NAME);
try(BufferedReader out = new BufferedReader(new FileReader(file))) {
for (int i = 0; i < htmlStrings.length; i++) {
htmlStrings[i] = out.readLine();
}
} catch (Exception e) {
logger.debug("exception during reading a file {}", HTML_FILE_NAME, e);
}
return htmlStrings;
}
private String generateHtmlForRequestsTable() {
final int rowNumber = 3;
List<String[]> data = new ArrayList<String[]>();
String result = null;
ipAddressDatas.forEach(e -> {
String[] column = new String[rowNumber];
column[0] = ((InetSocketAddress)e.getIpAddress()).toString();
column[1] = "" + e.getTotalRequests();
column[2] = new SimpleDateFormat(DATE_FORMAT_PATTERN).format(e.getTimeOfLastRequest());
data.add(column);
});
result = generateHtmlForTable(data);
return result;
}
private String generateHtmlForRedirectsTable() {
final int rowNumber = 2;
List<String[]> data = new ArrayList<String[]>();
String result = null;
redirects.entrySet().forEach(e -> {
String[] column = new String[rowNumber];
column[0] = e.getKey();
column[1] = "" + e.getValue();
data.add(column);
});
result = generateHtmlForTable(data);
return result;
}
private String generateHtmlForLogTable() {
final int rowNumber = 7;
List<String[]> data = new ArrayList<String[]>();
String result = null;
AtomicInteger counter = new AtomicInteger(1);
connectionDatas.descendingMap().entrySet().forEach(e -> {
String[] column = new String[rowNumber];
ConnectionData conn = e.getValue();
column[0] = "" + counter.getAndIncrement();
column[1] = new SimpleDateFormat(DATE_FORMAT_PATTERN).format(e.getKey());
column[2] = ((InetSocketAddress)conn.getSourceIp()).toString();
column[3] = conn.getUri();
column[4] = "" + conn.getSentBytes();
column[5] = "" + conn.getReceivedBytes();
column[6] = "" + conn.getSpeed();
data.add(column);
});
result = generateHtmlForTable(data);
return result;
}
private void updateIpAddressData() {
SocketAddress newIp = newData.getSourceIp();
String newURI = newData.getUri();
Date newDate = newData.getTimestamp();
Optional<IpAddressData> existing = ipAddressDatas.stream()
.filter(e -> newIp.equals(e.getIpAddress()))
.findAny();
if (existing.isPresent()) {
IpAddressData ipData = existing.get();
ipData.increaseTotalRequestsBy(1);
ipData.setTimeOfLastRequest(newDate);
ipData.addRequestIfUnique(newURI);
} else {
IpAddressData newIpAddressData = new IpAddressData(newIp, 1, Arrays.asList(newURI), newDate);
ipAddressDatas.add(newIpAddressData);
}
}
private void updateConnectionData() {
Date newDate = newData.getTimestamp();
if (connectionDatas.size() >= LOG_ENTRY_MAX_NUMBER) {
Date lastDate = connectionDatas.firstKey();
if (newDate.after(lastDate)) {
connectionDatas.remove(lastDate);
connectionDatas.put(newDate, newData);
}
} else {
connectionDatas.put(newDate, newData);
}
}
private void updateRedirects() {
if (redirect != null) {
Integer oldCounter = redirects.get(redirect);
Integer newCounter;
if (oldCounter != null) {
newCounter = oldCounter + 1;
} else {
newCounter = 1;
}
redirects.put(redirect, newCounter);
}
}
private String generateHtmlForTable(List<String[]> data) {
int visibleRowsLimit = 20;
StringBuffer result = new StringBuffer(INITIAL_BUFFER_CAPACITY);
int dataSize = data.size();
if (dataSize > visibleRowsLimit) {
result.append("<tfoot><tr><td colspan='10'>The total number of rows (unique ip): " + dataSize +
" <button id='toggle'>Show all</button></td></tr></tfoot>");
}
for (int i = 0; i < data.size(); i++) {
if (i < visibleRowsLimit) {
result.append("<tr>");
} else {
result.append("<tr class='beyondLimit'>");
}
String[] row = data.get(i);
for (int j = 0; j < row.length; j++) {
result.append("<td>" + row[j] + "</td>");
}
result.append("</tr>");
}
return result.toString();
}
public void fillWithRandomDummyData() {
ipAddressDatas = new ArrayList<>();
redirects = new ConcurrentSkipListMap<>();
redirects.put("localhost", 101);
redirects.put("ukr.net", 10);
redirects.put("oracle.com", 3);
numberOfActiveConn = 10025;
}
@Override
public String toString() {
return "FullStatisticsData:\n\tipAddressDatas = " + ipAddressDatas + ";\n\tconnectionDatas = "
+ connectionDatas + ";\n\tredirects = " + redirects + ";\n\tnumberOfActiveConn = "
+ numberOfActiveConn + "\n";
}
}
| true |
dc24678f602231e6d483c937490ddc996b9d2a74 | Java | Smail-ssm/myFamily | /app/src/main/java/com/emna/myfamily/member.java | UTF-8 | 1,872 | 2.34375 | 2 | [] | no_license | package com.emna.myfamily;
public class member {
String name;
String lastname;
String age;
String relation;
String email;
String phone;
String latit;
String longtit, Id;
public member() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getRelation() {
return relation;
}
public void setRelation(String relation) {
this.relation = relation;
}
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 getLatit() {
return latit;
}
public void setLatit(String latit) {
this.latit = latit;
}
public String getLongtit() {
return longtit;
}
public void setLongtit(String longtit) {
this.longtit = longtit;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public member(String name, String lastname, String age, String relation, String email, String phone, String latit, String longtit, String id) {
this.name = name;
this.lastname = lastname;
this.age = age;
this.relation = relation;
this.email = email;
this.phone = phone;
this.latit = latit;
this.longtit = longtit;
Id = id;
}
}
| true |
2298a16b4ded8dcab12c76089fe47dc01821574c | Java | vivemeno/minibase_repo | /src/global/NodeTable.java | UTF-8 | 300 | 2.046875 | 2 | [] | no_license | package global;
import global.IntervalType;
//adding NodeTable schema
public class NodeTable {
public String nodename;
public IntervalType interval;
public NodeTable (String _nodeName, IntervalType _interval) {
nodename = _nodeName;
interval = _interval;
}
public NodeTable() {
}
} | true |
97740b0ed29ba64d46a8ca9f346ef22b2772117d | Java | yongfeiuall/zheyi-taotao | /zheyi-rest/src/main/java/com/izheyi/rest/service/impl/ItemServiceImpl.java | UTF-8 | 2,372 | 1.984375 | 2 | [] | no_license | package com.izheyi.rest.service.impl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.izheyi.common.pojo.TaotaoResult;
import com.izheyi.common.utils.JsonUtils;
import com.izheyi.mapper.TbItemDescMapper;
import com.izheyi.mapper.TbItemMapper;
import com.izheyi.pojo.TbItem;
import com.izheyi.pojo.TbItemDesc;
import com.izheyi.rest.redis.RedisUtils;
import com.izheyi.rest.service.ItemService;
@Service
public class ItemServiceImpl implements ItemService {
@Value("${REDIS_ITEM_KEY}")
private String REDIS_ITEM_KEY;
@Value("${REDIS_ITEM_EXPIRE}")
private Integer REDIS_ITEM_EXPIRE;
@Autowired
private TbItemMapper itemMapper;
@Autowired
private TbItemDescMapper itemDescMapper;
@Autowired
private RedisUtils redisUtils;
@Override
public TaotaoResult getItemBasicInfo(long itemId) {
//get cache
try {
String cache = redisUtils.get(REDIS_ITEM_KEY + ":" + itemId + ":basic");
if (!StringUtils.isBlank(cache)) {
TbItem item = JsonUtils.jsonToPojo(cache, TbItem.class);
return TaotaoResult.ok(item);
}
} catch (Exception e) {
e.printStackTrace();
}
TbItem item = itemMapper.selectByPrimaryKey(itemId);
//add cache
try {
redisUtils.set(REDIS_ITEM_KEY + ":" + itemId + ":basic", JsonUtils.objectToJson(item));
redisUtils.expire(REDIS_ITEM_KEY + ":" + itemId + ":basic", REDIS_ITEM_EXPIRE);
} catch (Exception e) {
e.printStackTrace();
}
return TaotaoResult.ok(item);
}
@Override
public TaotaoResult getItemDesc(long itemId) {
//get cache
try {
String cache = redisUtils.get(REDIS_ITEM_KEY + ":" + itemId + ":desc");
if (!StringUtils.isBlank(cache)) {
TbItemDesc itemDesc = JsonUtils.jsonToPojo(cache, TbItemDesc.class);
return TaotaoResult.ok(itemDesc);
}
} catch (Exception e) {
// TODO: handle exception
}
TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(itemId);
//add cache
try {
redisUtils.set(REDIS_ITEM_KEY + ":" + itemId + ":desc", JsonUtils.objectToJson(itemDesc));
redisUtils.expire(REDIS_ITEM_KEY + ":" + itemId + ":desc", REDIS_ITEM_EXPIRE);
} catch (Exception e) {
e.printStackTrace();
}
return TaotaoResult.ok(itemDesc);
}
}
| true |
65caca55dadea47358049702e0f9333bf20a9213 | Java | vaibhavjain11/youtubeApp | /app/src/main/java/com/example/vaibhav/model/VideoList.java | UTF-8 | 497 | 2.546875 | 3 | [] | no_license | package com.example.vaibhav.model;
/**
* Created by Vaibhav on 7/15/2015.
*/
public class VideoList {
String videoId;
String title;
String url;
public VideoList(String id, String title, String url){
this.videoId = id;
this.title = title;
this.url = url;
}
public String getVideoId(){
return this.videoId;
}
public String getTitle(){
return this.title;
}
public String getUrl(){
return this.url;
}
}
| true |
6c60cec4e1f29a93a944dc3f8a94ff15941acc99 | Java | CindoddCindy/oneToManyDto | /dtoonetomany/src/main/java/com/dtoonetomany/dtoonetomany/service/ShelfService.java | UTF-8 | 292 | 1.960938 | 2 | [] | no_license | package com.dtoonetomany.dtoonetomany.service;
import com.dtoonetomany.dtoonetomany.dto.ShelfDto;
import java.util.List;
public interface ShelfService {
ShelfDto findById(Long id);
List<ShelfDto> findAll();
ShelfDto save(ShelfDto shelfDto);
void deleteById(Long id);
}
| true |
3ee5af9e4472cd314805e7a9651fbe5f492c0558 | Java | Randi07/Systeme-d-information | /src/OtherFolder/FormMenuPrincipale.java | UTF-8 | 42,882 | 1.78125 | 2 | [
"Apache-2.0"
] | permissive | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package OtherFolder;
import Connexion.ConnexionBase;
import District.FormDistrict;
import Fokontany.FormPopulation1;
import Fokontany.FormSanitaire;
import Fokontany.FormScolaire;
import Fokontany.FormSecurite;
import Fokontany.FormSportive;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/*import static java.lang.Thread.sleep;
import java.text.DateFormat;
import java.util.Date;*/
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
/**
*
* @author JAHYA
*/
public class FormMenuPrincipale extends javax.swing.JFrame {
/**
* Creates new form FormMenuPrincipale
*/
public Connection con;
public Statement st;
public DefaultTableModel dt;
public ResultSet rs;
public Integer radioG = 0;
public Integer radioD;
private String ID = "";
private String DESIGN= "";
public FormMenuPrincipale() {
initComponents();
DefaultTableModel dt = new DefaultTableModel();
dt.addColumn("CODE");
dt.addColumn("DESIGNATION");
TableRecherche.setModel(dt);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup4 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jPanel6 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
txtHistoriqueCom = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txtAnneeDebut = new javax.swing.JTextField();
txtAnneeFin = new javax.swing.JTextField();
radio01 = new javax.swing.JRadioButton();
radio02 = new javax.swing.JRadioButton();
radio03 = new javax.swing.JRadioButton();
radio00 = new javax.swing.JRadioButton();
jButton8 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
TableRecherche = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
txtRecherche = new javax.swing.JTextField();
jPanel7 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
txtHistoriqueCom1 = new javax.swing.JLabel();
txtAnneeDebut1 = new javax.swing.JTextField();
jButton7 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBackground(new java.awt.Color(153, 153, 255));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icone/LogoPrint.png"))); // NOI18N
jLabel3.setToolTipText("");
jLabel3.setOpaque(true);
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 720, 120));
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
jPanel4.setBackground(new java.awt.Color(153, 153, 255));
jPanel4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("VOIR CES DISTRICT");
jButton1.setToolTipText("Acceuil");
jButton1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 51, 255), 1, true));
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel5.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 130, 40));
jButton2.setText("POPULATION");
jButton2.setToolTipText("Appuyer pour voir les differents Fokontany");
jButton2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 51, 255), 1, true));
jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel5.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 130, 40));
jButton3.setText("SANTE");
jButton3.setToolTipText("Appuyer pour voir les differentes communes");
jButton3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 51, 255), 1, true));
jButton3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel5.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, 130, 40));
jButton4.setText("EDUCATION");
jButton4.setToolTipText("Appuyer pour voir l'information sur la region");
jButton4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 51, 255), 1, true));
jButton4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jPanel5.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, 130, 40));
jButton5.setText("SECURITE");
jButton5.setToolTipText("Appuyer pour voir les differents dossiers");
jButton5.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 51, 255), 1, true));
jButton5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jPanel5.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 250, 130, 40));
jButton6.setText("SPORT");
jButton6.setToolTipText("Appuyer pour deconnecter");
jButton6.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 51, 255), 1, true));
jButton6.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jPanel5.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 310, 130, 40));
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "REPRESENTATION GRAPHIQUE DE DONNEES DE LA POPULATION", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel6.setText("Année début :");
jPanel6.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 20, 80, 20));
txtHistoriqueCom.setText(".....");
txtHistoriqueCom.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jPanel6.add(txtHistoriqueCom, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 20, 260, 50));
jLabel8.setText("Année fin :");
jPanel6.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 20, 70, 20));
txtAnneeDebut.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txtAnneeDebutKeyReleased(evt);
}
});
jPanel6.add(txtAnneeDebut, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 20, 80, -1));
txtAnneeFin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txtAnneeFinKeyReleased(evt);
}
});
jPanel6.add(txtAnneeFin, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 20, 70, -1));
radio01.setText("District");
radio01.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
radio01MouseClicked(evt);
}
});
jPanel6.add(radio01, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, -1, -1));
radio02.setText("Commune");
radio02.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
radio02MouseClicked(evt);
}
});
jPanel6.add(radio02, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
radio03.setText("Fokontany");
radio03.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
radio03MouseClicked(evt);
}
});
jPanel6.add(radio03, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, -1, -1));
radio00.setSelected(true);
radio00.setText("Region");
radio00.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
radio00MouseClicked(evt);
}
});
jPanel6.add(radio00, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, -1));
jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icone/print.png"))); // NOI18N
jButton8.setText("Sortir (pdf)");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jPanel6.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 60, 160, 30));
TableRecherche.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
TableRecherche.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
TableRechercheMouseClicked(evt);
}
});
jScrollPane1.setViewportView(TableRecherche);
jPanel6.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 100, 310, 120));
jLabel1.setText("Rechercher:");
jPanel6.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 60, 70, 20));
txtRecherche.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txtRechercheKeyReleased(evt);
}
});
jPanel6.add(txtRecherche, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 60, 190, 30));
jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "MONOGRAPHIE", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jPanel7.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel7.setText("Année :");
jPanel7.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 40, 50, 20));
txtHistoriqueCom1.setText(".....");
txtHistoriqueCom1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jPanel7.add(txtHistoriqueCom1, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 20, 260, 50));
txtAnneeDebut1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txtAnneeDebut1KeyReleased(evt);
}
});
jPanel7.add(txtAnneeDebut1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 40, 80, -1));
jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icone/print.png"))); // NOI18N
jButton7.setText("Sortir (pdf)");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jPanel7.add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 30, 160, 30));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icone/important.gif"))); // NOI18N
jLabel2.setText("Attention: Cette operation requiere beaucoup de puissance, donc ca peut prendre quelque minutes");
jPanel7.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, 520, 40));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 546, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
getContentPane().add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 120, 720, 380));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
FormPopulation1 a = new FormPopulation1();
a.first();
a.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
FormSportive a = new FormSportive();
a.first();
a.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
FormDistrict a = new FormDistrict();
a.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
private void radio01MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_radio01MouseClicked
// TODO add your handling code here:
radioG=1;
radio00.setSelected(false);
radio01.setSelected(true);
radio02.setSelected(false);
radio03.setSelected(false);
TableRecherche.removeAll();
}//GEN-LAST:event_radio01MouseClicked
private void radio02MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_radio02MouseClicked
// TODO add your handling code here:
radioG=2;
radio00.setSelected(false);
radio02.setSelected(true);
radio01.setSelected(false);
radio03.setSelected(false);
TableRecherche.removeAll();
}//GEN-LAST:event_radio02MouseClicked
private void radio03MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_radio03MouseClicked
// TODO add your handling code here:
radioG=3;
radio00.setSelected(false);
radio03.setSelected(true);
radio01.setSelected(false);
radio02.setSelected(false);
TableRecherche.removeAll();
}//GEN-LAST:event_radio03MouseClicked
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
// TODO add your handling code here:
if(ID.equals("") && radioG!=0)
{
JOptionPane.showMessageDialog(null, "Veuillez selectionner une ligne!");
}
else{
DESIGN = radioG==0 ? "Amorin'i mania":DESIGN;
String anneeDebut = txtAnneeDebut.getText();
String anneeFin = txtAnneeFin.getText();
if(!anneeFin.equals("") && !anneeDebut.equals("") && Integer.parseInt(anneeDebut)<=Integer.parseInt(anneeDebut) && Integer.parseInt(anneeDebut)>=1990 && Integer.parseInt(anneeDebut)<=2020 && (Integer.parseInt(anneeFin)-Integer.parseInt(anneeDebut))<5)
{
try {
ConnexionBase c = new ConnexionBase();
ResultSet rs0 = c.executeQuery("select * from population where ID_FKT like '"+ ID +"%' and (ANNEE>='"+ anneeDebut +"' and ANNEE<='"+ anneeFin +"') order by ANNEE");
DefaultCategoryDataset dataset= new DefaultCategoryDataset();
while(rs0.next()){
dataset.setValue(rs0.getInt("ZERO"),"[0-5]", rs0.getString("ANNEE"));
dataset.setValue(rs0.getInt("SIX"),"[6-17]", rs0.getString("ANNEE"));
dataset.setValue(rs0.getInt("DIXHUIT"),"[18-59]", rs0.getString("ANNEE"));
dataset.setValue(rs0.getInt("SOIXANTE"),"[60-Et plus]", rs0.getString("ANNEE"));
dataset.setValue(rs0.getInt("EFFECTIF_FEMININ"),"Femme", rs0.getString("ANNEE"));
dataset.setValue(rs0.getInt("EFFECTIF_MASCULAIN"),"Homme", rs0.getString("ANNEE"));
dataset.setValue(rs0.getInt("EFFECTIF_TOTAL"),"Total", rs0.getString("ANNEE"));
}
String titre1 = "Démographe: '"+ DESIGN +"'";
JFreeChart chart = ChartFactory.createBarChart(titre1, "1 ANNEE:[0;5],[6;17],[18;59],[60;+], Femme, Homme, Total",anneeDebut+" - "+anneeFin, dataset, PlotOrientation.VERTICAL, false, true, false);
// pour diagramm en bar ecrit createBarChart createLineChart
CategoryPlot p=chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.black);
ChartFrame frame= new ChartFrame("Representation graphique de la population", chart);
frame.setVisible(true);
frame.setSize(600,500);int dRes = JOptionPane.showConfirmDialog(null, "Voulez-vous sortir un pdf aussi?","Traitement en cours",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(dRes == JOptionPane.YES_OPTION){
final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
final File f = new File("Diagramme.png");
String rep = f.getAbsolutePath();
ChartUtilities.saveChartAsPNG(f, chart, 500, 400, info);
try {
Document document = new Document();
PdfWriter Writer = PdfWriter.getInstance(document, new FileOutputStream("Diagramme.pdf"));
document.open();
Image image = Image.getInstance("Diagramme.png");
document.add((Element) image);
document.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erreur lors de la creation du fichier: \n" + e);
}
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.OPEN)) {
try {
desktop.open(new File("Diagramme.pdf"));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erreur: vous ne disposez pas une application qui ouvre un pdf:\n"+e+"Le fichier se trouve dans '" +rep+"'");
}
}
}
} catch (Exception e)
{System.err.println(e.getMessage()); //e.getMessage est pour afficher ou se trouve l'erreur
}
}
else
{
JOptionPane.showMessageDialog(null, "Veuillez respecter le format suivant: 1989 < annee debut <=! annee fin+4 < 2021 !");
txtAnneeFin.setText("");
txtAnneeDebut.setText("");
}}
}//GEN-LAST:event_jButton8ActionPerformed
private void txtAnneeDebutKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAnneeDebutKeyReleased
// TODO add your handling code here:
String ChampCodeDoss = txtAnneeDebut.getText();
int CCD = ChampCodeDoss.length();
int valeur = 4;
if (ChampCodeDoss.matches("[0-9]*")) {
if (CCD > valeur) {
ChampCodeDoss = ChampCodeDoss.substring(0, CCD - 1);
JOptionPane.showMessageDialog(null, "Cet enregistrement doit etre egale a 4 chiffres, merci!");
}
} else {
ChampCodeDoss = ChampCodeDoss.substring(0, CCD - 1);
JOptionPane.showMessageDialog(null, "Cet enregistrement doit etre un nombre entier a 4 chiffre, merci!");
}
txtAnneeDebut.setText(ChampCodeDoss);
}//GEN-LAST:event_txtAnneeDebutKeyReleased
private void txtAnneeDebut1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAnneeDebut1KeyReleased
// TODO add your handling code here:
String ChampCodeDoss = txtAnneeDebut1.getText();
int CCD = ChampCodeDoss.length();
int valeur = 4;
if (ChampCodeDoss.matches("[0-9]*")) {
if (CCD > valeur) {
ChampCodeDoss = ChampCodeDoss.substring(0, CCD - 1);
JOptionPane.showMessageDialog(null, "Cet enregistrement doit etre egale a 4 chiffres, merci!");
}
} else {
ChampCodeDoss = ChampCodeDoss.substring(0, CCD - 1);
JOptionPane.showMessageDialog(null, "Cet enregistrement doit etre un nombre entier a 4 chiffre, merci!");
}
txtAnneeDebut1.setText(ChampCodeDoss);
}//GEN-LAST:event_txtAnneeDebut1KeyReleased
private void txtAnneeFinKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAnneeFinKeyReleased
// TODO add your handling code here:
String ChampCodeDoss = txtAnneeFin.getText();
int CCD = ChampCodeDoss.length();
int valeur = 4;
if (ChampCodeDoss.matches("[0-9]*")) {
if (CCD > valeur) {
ChampCodeDoss = ChampCodeDoss.substring(0, CCD - 1);
JOptionPane.showMessageDialog(null, "Cet enregistrement doit etre egale a 4 chiffres, merci!!");
}
} else {
ChampCodeDoss = ChampCodeDoss.substring(0, CCD - 1);
JOptionPane.showMessageDialog(null, "Cet enregistrement doit etre un nombre entier a 4 chiffre, merci!!");
}
txtAnneeFin.setText(ChampCodeDoss);
}//GEN-LAST:event_txtAnneeFinKeyReleased
private void radio00MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_radio00MouseClicked
// TODO add your handling code here:
radioG=0;
radio01.setSelected(false);
radio00.setSelected(true);
radio02.setSelected(false);
radio03.setSelected(false);
TableRecherche.removeAll();
}//GEN-LAST:event_radio00MouseClicked
private void txtRechercheKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtRechercheKeyReleased
// TODO add your handling code here:
if(radioG!=0){
String q = txtRecherche.getText();
String p = radioG==1 ? "DIST": radioG==2 ? "COM":"FKT";
String t = radioG==1 ? "district": radioG==2 ? "commune":"fokontany";
try {
ConnexionBase c = new ConnexionBase();
DefaultTableModel dt = new DefaultTableModel();
dt.addColumn("CODE");
dt.addColumn("DESIGNATION");
TableRecherche.setModel(dt);
rs = c.executeQuery("Select ID_"+p+", NOM_"+p+" From "+t+" where NOM_"+p+" like '%"+q+"%'");
while (rs.next()) {
String ID = rs.getString("ID_"+p);
String DESIGN = rs.getString("NOM_"+p);
Object[] ligne = {ID,DESIGN};
dt.addRow(ligne);
}
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
} catch (Exception ex) {
Logger.getLogger(FormMenuPrincipale.class.getName()).log(Level.SEVERE, null, ex);
}}
else{
txtRecherche.setText("");
JOptionPane.showMessageDialog(null,"Vous pouvez tout de suite cliquer sur ''Sortir pdf''");
}
}//GEN-LAST:event_txtRechercheKeyReleased
private void TableRechercheMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableRechercheMouseClicked
// TODO add your handling code here:
ID = String.valueOf(TableRecherche.getValueAt(TableRecherche.getSelectedRow(), 0));
DESIGN = String.valueOf(TableRecherche.getValueAt(TableRecherche.getSelectedRow(), 1));
}//GEN-LAST:event_TableRechercheMouseClicked
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
// TODO add your handling code here:
String anneeMon = txtAnneeDebut1.getText();
if(!anneeMon.equals("") && Integer.parseInt(anneeMon)>=1990 && Integer.parseInt(anneeMon)<=2020)
{
try {
// Step 1
Rectangle rec = new Rectangle(1300, 2000);
Document document = new Document(rec);
// step 2
PdfWriter.getInstance(document, new FileOutputStream("Monographie_"+anneeMon+".pdf"));
// step 3
document.open();
// step 4
PdfPTable table = new PdfPTable(3);
table.addCell("DISTRICT");
table.addCell("HISTORIQUE");
table.addCell("SUPERFICIE");
ConnexionBase c = new ConnexionBase();
rs = c.executeQuery("Select NOM_DIST, HISTORIQUE_DIST, SUPERFICIE from district");
while (rs.next()) {
table.addCell(rs.getString("NOM_DIST"));
table.addCell(rs.getString("HISTORIQUE_DIST"));
table.addCell(rs.getString("SUPERFICIE"));
}
rs.close();
// Step 5
Font a = new Font(Font.FontFamily.TIMES_ROMAN, 14);
document.add(new Paragraph(" MONOGRAPHIE DE L'ANNEE "+anneeMon,new Font(Font.FontFamily.TIMES_ROMAN, 22)));
document.add(new Paragraph(" \n",a));
document.add(new Paragraph(" REGION AMORIN'I MANIA",a));
document.add(new Paragraph(" \n",a));
document.add(table);
Integer i=0,j=0,k=0;
ResultSet rs1 = c.executeQuery("Select ID_DIST, NOM_DIST from district");
while (rs1.next()) {
i++;k=0;
document.add(new Paragraph(" \n",a));
document.add(new Paragraph(i+") DISTRICT DE "+rs1.getString("NOM_DIST"),a));
document.add(new Paragraph(" \n",a));
PdfPTable table1 = new PdfPTable(8);
table1.addCell("COMMUNE");
table1.addCell("HISTORIQUE");
table1.addCell("DRN7");
table1.addCell("DRN35");
table1.addCell("DRN41");
table1.addCell("DDIST");
table1.addCell("DREG");
table1.addCell("SUPERFICIE");
ConnexionBase c1 = new ConnexionBase();
ResultSet rs2 = c1.executeQuery("Select * from commune where ID_COM like '"+ rs1.getString("ID_DIST") +"%'");
while (rs2.next()) {
table1.addCell(rs2.getString("NOM_COM"));
table1.addCell(rs2.getString("HISTORIQUE_COM"));
table1.addCell(rs2.getString("DRN7"));
table1.addCell(rs2.getString("DRN35"));
table1.addCell(rs2.getString("DRN41"));
table1.addCell(rs2.getString("DDIST"));
table1.addCell(rs2.getString("DREG"));
table1.addCell(rs2.getString("SUPERFICIE"));
}
rs2.close();
c1.close();
document.add(table1);
ConnexionBase c3 = new ConnexionBase();
ResultSet rs3 = c3.executeQuery("Select ID_COM, NOM_COM from commune");
while (rs3.next()) {
k++;j=0;
document.add(new Paragraph(" \n",a));
document.add(new Paragraph(" "+i+"."+k+") COMMUNE DE "+rs3.getString("NOM_COM"),a));
document.add(new Paragraph(" \n",a));
PdfPTable table2 = new PdfPTable(3);
table2.addCell("FOKONTANY");
table2.addCell("HISTORIQUE");
table2.addCell("SUPERFICIE");
ConnexionBase c4 = new ConnexionBase();
ResultSet rs4 = c4.executeQuery("Select * from fokontany where ID_FKT like '"+ rs3.getString("ID_COM") +"%'");
while (rs4.next()) {
table2.addCell(rs4.getString("NOM_FKT"));
table2.addCell(rs4.getString("HISTORIQUE_FKT"));
table2.addCell(rs4.getString("SUPERFICIE"));
}
rs4.close();
c4.close();
document.add(table2);
ConnexionBase c5 = new ConnexionBase();
ResultSet rs5= c5.executeQuery("Select ID_FKT, NOM_FKT from fokontany");
while (rs5.next()) {
j++;
document.add(new Paragraph(" \n",a));
document.add(new Paragraph(" "+i+"."+k+"."+j+") FOKONTANY DE "+rs5.getString("NOM_FKT"),a));
document.add(new Paragraph(" \n",a));
PdfPTable table3 = new PdfPTable(5);
table3.addCell("POPULATION");
table3.addCell("SANITAIRE");
table3.addCell("SCOLAIRE");
table3.addCell("SECURITE");
table3.addCell("SPORTIVE");
ConnexionBase c6 = new ConnexionBase();
ResultSet rs6 = c6.executeQuery("Select * from population where ID_FKT = '"+ rs5.getString("ID_FKT") +"' and ANNEE='"+anneeMon+"'");
String tmp1 = "";
if(rs6.next()) {
tmp1="[0-5]: "+rs6.getString("ZERO")+"\n[6-17]: "+rs6.getString("SIX")+"\n[18-59]: "+rs6.getString("DIXHUIT")+"\n[60-Plus]: "+rs6.getString("SOIXANTE")+"\nHomme: "+rs6.getString("EFFECTIF_MASCULAIN")+"\nFemme: "+rs6.getString("EFFECTIF_FEMININ")+"\nTotal: "+rs6.getString("EFFECTIF_TOTAL");
}
table3.addCell(tmp1);
rs6.close();
c6.close();
ConnexionBase c7 = new ConnexionBase();
ResultSet rs7 = c7.executeQuery("Select * from sanitaire where ID_FKT = '"+ rs5.getString("ID_FKT") +"' and ANNEE='"+anneeMon+"'");
if(rs7.next()) {
tmp1="INFRASTRUCTURE: "+rs7.getString("INFRAS_SANITAIRE")+"\nNOMBRE: "+rs7.getString("NOMBRE_INFRAS_SANITAIRE")+"\nNATURE: "+rs7.getString("NATURE_INFRAS_SANITAIRE")+"\nEMPLOYES: "+rs7.getString("EMPLOYES")+"\nNOMBRE: "+rs7.getString("NOMBRE_EMPLOYES")+"\nETAT: "+rs7.getString("ETAT_INFRAS_SANITAIRE")+"\nREMARQUE: "+rs7.getString("REMARQUE");
}
table3.addCell(tmp1);
rs7.close();
c7.close();
ConnexionBase c8 = new ConnexionBase();
ResultSet rs8 = c8.executeQuery("Select * from scolaire where ID_FKT = '"+ rs5.getString("ID_FKT") +"' and ANNEE='"+anneeMon+"'");
if(rs8.next())
{
tmp1="CATEGORIE: "+rs8.getString("CATEG_SCOLAIRE")+"\nNATURE: "+rs8.getString("NATURE_SCOLAIRE")+"\nNOMBRE: "+rs8.getString("NOMBRE_SCOLAIRE")+"\nETAT: "+rs8.getString("ETAT_SCOLAIRE")+"\nGARCON: "+rs8.getString("ELEVE_MASCULAIN")+"\nFILLE: "+rs8.getString("ELEVE_FEMININ")+"\nTOTAL: "+rs8.getString("EFFECTIF_TOTAL")+"\nANNEE SCOLAIRE: "+rs8.getString("ANNEE_SCOLAIRE");
}
table3.addCell(tmp1);
rs8.close();
c8.close();
ConnexionBase c9 = new ConnexionBase();
ResultSet rs9 = c9.executeQuery("Select * from securite where ID_FKT = '"+ rs5.getString("ID_FKT") +"' and ANNEE='"+anneeMon+"'");
if(rs9.next())
{
tmp1="CATEGORIE: "+rs9.getString("CATEG_SEC")+"\nNOMBRE: "+rs9.getString("NOMBRE")+"\nREMARQUE: "+rs9.getString("REMARQUE");
}
table3.addCell(tmp1);
rs9.close();
c9.close();
ConnexionBase c10 = new ConnexionBase();
ResultSet rs10 = c10.executeQuery("Select * from sportive where ID_FKT = '"+ rs5.getString("ID_FKT") +"' and ANNEE='"+anneeMon+"'");
if(rs10.next())
{
tmp1="CATEGORIE: "+rs10.getString("CATEG_SPORT")+"\nTERRAIN: "+rs10.getString("EXISTANCE_TERRAIN")+"\nETAT: "+rs10.getString("ETAT_TERRAIN")+"\nNOMBRE: "+rs10.getString("NOMBRE_TERRAIN")+"\nREMARQUE: "+rs10.getString("REMARQUE_SPORT");
}
table3.addCell(tmp1);
rs10.close();
c10.close();
document.add(table3);
}
rs5.close();
c5.close();
}
}
rs1.close();
c.close();
// step 6
document.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
final File f = new File("tmp.txt");
String rep = f.getAbsolutePath();
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.OPEN)) {
try {
desktop.open(new File("Monographie_"+ anneeMon +".pdf"));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erreur: vous ne disposez pas une application qui ouvre un pdf:\n"+e+"Le fichier se trouve dans '" +rep+"'");
}
}}
else
{
JOptionPane.showMessageDialog(null, "Veuillez respecter le format suivant: 1989 < annee < 2021 !");
txtAnneeDebut1.setText("");
}
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
FormSanitaire a = new FormSanitaire();
a.first();
a.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
FormScolaire a = new FormScolaire();
a.first();
a.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
FormSecurite a = new FormSecurite();
a.first();
a.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton5ActionPerformed
/**
* @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(FormMenuPrincipale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormMenuPrincipale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormMenuPrincipale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormMenuPrincipale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FormMenuPrincipale().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable TableRecherche;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.ButtonGroup buttonGroup4;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JRadioButton radio00;
private javax.swing.JRadioButton radio01;
private javax.swing.JRadioButton radio02;
private javax.swing.JRadioButton radio03;
private javax.swing.JTextField txtAnneeDebut;
private javax.swing.JTextField txtAnneeDebut1;
private javax.swing.JTextField txtAnneeFin;
private javax.swing.JLabel txtHistoriqueCom;
private javax.swing.JLabel txtHistoriqueCom1;
private javax.swing.JTextField txtRecherche;
// End of variables declaration//GEN-END:variables
}
| true |
04f9e27f9cc515adf12211b0ea208dda6f58c33d | Java | lucascraft/ubq_wip | /net.sf.smbt.dxxp/src-model/net/sf/smbt/ezdxxp/impl/DaapAplyImpl.java | UTF-8 | 746 | 1.554688 | 2 | [] | no_license | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.sf.smbt.ezdxxp.impl;
import net.sf.smbt.ezdxxp.DaapAply;
import net.sf.smbt.ezdxxp.EzdxxpPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Daap Aply</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class DaapAplyImpl extends DaapQueryCmdImpl implements DaapAply {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DaapAplyImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return EzdxxpPackage.Literals.DAAP_APLY;
}
} //DaapAplyImpl
| true |
24d7cbfc623f16ffec4209e76da1aa2f0da9ef38 | Java | stealth-17/Calculator-app | /src/com/stealth/calculator/.svn/text-base/Global.java.svn-base | UTF-8 | 1,101 | 2.640625 | 3 | [] | no_license | package com.stealth.calculator;
public class Global {
private static String expression;
private static int drg;
private static String ans;
private static int sum;
private static double start,end,step;
public static String getVar()
{
if(expression.length()>0)
return expression;
else
return "";
}
public static void setVar(String var)
{
expression = var;
}
public static void setDRG(int val)
{
drg=val;
}
public static int checkDRG()
{
return drg;
}
public static void setAns(String val)
{
ans=val;
}
public static String getAns()
{
if(ans.length()>0)
return ans;
else
return "0";
}
public static void setSum(int val)
{
sum=val;
}
public static int getSum()
{
return sum;
}
public static void setstart(double val)
{
start=val;
}
public static double getstart()
{
return start;
}
public static void setend(double val)
{
end=val;
}
public static double getend()
{
return end;
}
public static void setstep(double val)
{
step=val;
}
public static double getstep()
{
return step;
}
}
| true |
bbe8be62d41e95f957500c5f7596ae5b8154c44c | Java | FRC-4277/2019DeepSpace | /src/main/java/frc/robot/map/XboxControllerMap.java | UTF-8 | 1,304 | 1.695313 | 2 | [] | no_license | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.map;
/**
* Add your docs here.
*/
public class XboxControllerMap {
public static final int XBOX_LEFT_STICK_AXIS_Y = 1;
public static final int XBOX_LEFT_STICK_AXIS_X = 2;
public static final int XBOX_TRIGGER = 3;
public static final int XBOX_RIGHT_STICK_AXIS_X = 4;
public static final int XBOX_RIGHT_STICK_AXIS_Y = 5;
public static final int XBOX_BUTTON_A = 1;
public static final int XBOX_BUTTON_B = 2;
public static final int XBOX_BUTTON_X = 3;
public static final int XBOX_BUTTON_Y = 4;
public static final int XBOX_BUTTON_LB = 5;
public static final int XBOX_BUTTON_RB = 6;
public static final int XBOX_BUTTON_BACK = 7;
public static final int XBOX_BUTTON_START = 8;
public static final int XBOX_JOY_LEFT_BUTTON = 9;
public static final int XBOX_JOY_RIGHT_BUTTON = 10;
}
| true |
55032aa887d2f8f28af83b7c01c84b292e255664 | Java | Jesiel99/DBVendas | /src/venda/Pessoa.java | UTF-8 | 360 | 2.4375 | 2 | [] | no_license | package venda;
public class Pessoa {
private int codigo;
private String nomeCompleto;
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNomeCompleto() {
return nomeCompleto;
}
public void setNomeCompleto(String nomeCompleto) {
this.nomeCompleto = nomeCompleto;
}
}
| true |
d946cf5097a3fc7e6fd18478a6434589d03e8574 | Java | YisongZou/Risc-Game | /Evolution3/risc/hostmaster/src/main/java/edu/duke/ece651/hostmaster/HostClient.java | UTF-8 | 3,793 | 2.875 | 3 | [] | no_license | package edu.duke.ece651.hostmaster;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import edu.duke.ece651.shared.Message;
public class HostClient extends Thread {
private Socket skt; // socket with player
private InputStream inStr;
private OutputStream outStr;
private boolean isInGame;
private static ArrayList<Message> serverInfo = new ArrayList<>();
public static synchronized void setServerInfo(ArrayList<Message> serverInfosArr) {
serverInfo = serverInfosArr;
}
public HostClient(Socket socket) throws IOException {
this.skt = socket;
inStr = skt.getInputStream();
outStr = skt.getOutputStream();
this.isInGame = false;
}
private void sendMessage(Message msg) throws IOException {
ObjectOutputStream objOutS = new ObjectOutputStream(outStr);
objOutS.writeObject(msg);
}
private void sendMessageArr(ArrayList<Message> msgs) throws IOException {
ObjectOutputStream objOutS = new ObjectOutputStream(outStr);
objOutS.writeObject(msgs);
}
private Message getMessage() throws IOException, ClassNotFoundException {
System.out.println(Thread.currentThread().getName() + ": WAIT FOR MESSAGE");
ObjectInputStream objInS = new ObjectInputStream(inStr);
Message msgRecved = (Message) objInS.readObject();
System.out.println(Thread.currentThread().getName() + ": Message received");
return msgRecved;
}
private ArrayList<Message> getMessageArr() throws IOException, ClassNotFoundException {
System.out.println(Thread.currentThread().getName() + ": WAIT FOR MESSAGEARR");
ObjectInputStream objInS = new ObjectInputStream(inStr);
ArrayList<Message> msgRecved = (ArrayList<Message>) objInS.readObject();
System.out.println(Thread.currentThread().getName() + ": MessageARR received");
return msgRecved;
}
private void sendAvailableGames() {
// display available games
synchronized (serverInfo) {
try {
sendMessageArr(serverInfo);
}
catch(Exception exp) {
exp.printStackTrace();
}
}
}
private void updateServerInfo(Message msg) {
synchronized (serverInfo) {
Message choosed = null;
for (Message info : serverInfo) {
if (info.getGameServerIP().equals(msg.getGameServerIP()) && info.getGameServerPort().equals(msg.getGameServerPort())) {
choosed = info;
}
}
choosed.setCurPlyNum(choosed.getCurPlyNum()+1);
this.isInGame = true;
}
}
private void removeFinishedGame(Message msg) {
synchronized (serverInfo) {
Message choosed = null;
for (Message info : serverInfo) {
if (info.getGameServerIP().equals(msg.getGameServerIP())
&& info.getGameServerPort().equals(msg.getGameServerPort())) {
choosed = info;
}
}
serverInfo.remove(choosed);
}
}
public void run() {
while (true) {
try {
Message msg = getMessage();
if (msg.getContent() != null && msg.getContent().equals("Ask for available games")) {
sendAvailableGames();
Message playerChoice = getMessage();
// for test
System.out.println("playerchoice receive content: " + playerChoice.getContent());
if (playerChoice.getContent().equals("I will keep ask")) {
continue;
}
updateServerInfo(playerChoice);
}
if (msg.getContent() != null && msg.getContent().equals("this game ends")) {
removeFinishedGame(msg);
}
}
catch(Exception exp) {
exp.printStackTrace();
break;
}
}
}
}
| true |
e89a56954076672e42f2d087d1dd902670823211 | Java | shumin1027/JPSON | /src/main/java/com/jpson/internal/ArrayUtils.java | UTF-8 | 1,080 | 3.265625 | 3 | [] | no_license | package com.jpson.internal;
public final class ArrayUtils {
public static void reverse(final byte[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return;
}
int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;//等同与上面第二段代码中的head变量
int j = Math.min(array.length, endIndexExclusive) - 1;//等同与上面第二段代码中的tail变量
byte tmp;//等同与上面第二段代码中的temp变量
while (j > i) {//使用while循环判断首尾的大小关系
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
public static void reverse(final byte[] array) {
if (array == null) {
return;
}
for (int i = 0; i <= array.length / 2 - 1; i++) {
byte temp1 = array[i];
byte temp2 = array[array.length - i - 1];
array[i] = temp2;
array[array.length - i - 1] = temp1;
}
}
} | true |
aacbb28d56513b20e58f5087cde20a476554220c | Java | FlashChenZhi/exercise | /wms/WEB-INF/src/jp/co/daifuku/wms/base/common/WMSConstants.java | UTF-8 | 2,320 | 2.234375 | 2 | [] | no_license | // $Id: WMSConstants.java 2512 2009-01-06 02:18:46Z kishimoto $
/*
* Copyright 2000-2001 DAIFUKU Co.,Ltd. All Rights Reserved.
*
* This software is the proprietary information of DAIFUKU Co.,Ltd.
* Use is subject to license terms.
*/
package jp.co.daifuku.wms.base.common;
import jp.co.daifuku.Constants;
import jp.co.daifuku.bluedog.util.ControlColor;
/**
* WMS用の定数定義インターフェイスです。
*
* <BR>
* <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0">
* <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"><TD>Date</TD><TD>Name</TD><TD>Comment</TD></TR>
* <TR><TD>2004/06/26</TD><TD>M.Kawashima</TD><TD>created this class</TD></TR>
* </TABLE>
* <BR>
* @version $Revision: 2512 $, $Date: 2009-01-06 11:18:46 +0900 (火, 06 1 2009) $
* @author $Author: kishimoto $
*/
public interface WMSConstants
extends Constants
{
// Class fields --------------------------------------------------
/**
* WMSで使用するデータソース名
*/
public static final String DATASOURCE_NAME = "wms";
/**
* RFTで使用するデータソース名
*/
public static final String DATASOURCE_RFT_NAME = "rft";
/**
* WMSで使用するスケジュールパラメータに渡す日付フォーマット
*/
public static final String PARAM_DATE_FORMAT = "yyyyMMdd";
/**
* 印刷画面でCSV出力を指定するためのキーワード
*/
public static final int CSV = 1;
/**
* 印刷画面でXLS出力を指定するためのキーワード
*/
public static final int XLS = 2;
/**
* リストセルの警告行の色(標準は黄色)
*/
public static final jp.co.daifuku.bluedog.util.ControlColorSupport LISTCELL_WARN_COLOR = ControlColor.Yellow;
// Class variables -----------------------------------------------
// Class method --------------------------------------------------
// Constructors --------------------------------------------------
// Public methods ------------------------------------------------
// Package methods -----------------------------------------------
// Protected methods ---------------------------------------------
// Private methods -----------------------------------------------
}
//end of class
| true |
b69d20105477dc8736cfa4e5a8233d45e6222c6d | Java | leechaean7714/Academy_java | /Java05_Switch/src/com/test03/MTest.java | UTF-8 | 806 | 3.59375 | 4 | [] | no_license | package com.test03;
import com.test02.Season;
public class MTest {
public static void main(String[] args) {
/* Score 클래스를 완성하자.
* getAvg 메서드는, 국어 영어 수학 점수를 전달하면
* 평균을 리턴해준다.
* getGrade 메서드는, 평균을 전달하면
* 90~100 : A
* 80~89 : B
* 70~79 : C
* 60~79 : D
* 0 ~59 : F를 리턴해준다.
*
* "xxx님의 평균은 xx.xx점이고, 등급은 'ㅁ'입니다. 라고 출력."
*/
Score sc = new Score();
double avg = sc.getAvg(100, 68, 75);
//System.out.println(avg);
String grade = sc.getGrade(avg);
System.out.printf("전영태 님의 평균은 %.2f점이고," + "등급은 '%s'입니다.", avg, grade);
}
}
| true |
0f917024a2fb21fce022d0da38b19a64357834cd | Java | luthfitabey/Koor_Yuk | /app/src/main/java/com/anjilibey/kooryuk/viewModel/TLAdapterUser.java | UTF-8 | 2,560 | 2.078125 | 2 | [] | no_license | package com.anjilibey.kooryuk.viewModel;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anjilibey.kooryuk.R;
import com.anjilibey.kooryuk.model.Rapat;
import com.anjilibey.kooryuk.view.MeetingUser.ViewMeetingUser;
import com.anjilibey.kooryuk.view.MeetingUser.ViewTL;
import java.util.ArrayList;
public class TLAdapterUser extends RecyclerView.Adapter<TLAdapterUser.ViewHolder> {
private ArrayList<Rapat> result;
public TLAdapterUser(ArrayList<Rapat> result) {
this.result = result;
}
@Override
public TLAdapterUser.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.card_row_meeting, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull TLAdapterUser.ViewHolder viewHolder, int i) {
viewHolder.topik.setText(result.get(i).topik);
viewHolder.waktuM.setText(result.get(i).waktu_mulai);
viewHolder.waktuS.setText(result.get(i).waktu_selesai);
viewHolder.tgl.setText(result.get(i).tanggal);
viewHolder.tempat.setText(result.get(i).tempat);
viewHolder.poin.setText(result.get(i).poin1);
final String idRapat = result.get(i).getId();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent mIntent = new Intent(view.getContext(), ViewTL.class);
mIntent.putExtra("id_rapat", idRapat);
view.getContext().startActivity(mIntent);
}
});
}
public int getItemCount(){
return result.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView topik, waktuM, waktuS, tgl, tempat, poin;
public ViewHolder(View view) {
super(view);
topik = (TextView)view.findViewById(R.id.tvTopik);
tgl = (TextView)view.findViewById(R.id.tvTgl);
waktuM = (TextView)view.findViewById(R.id.tvWaktuM);
waktuS = (TextView)view.findViewById(R.id.tvWaktuS);
tempat = (TextView)view.findViewById(R.id.tvPlace);
poin = (TextView)view.findViewById(R.id.tvPoin1);
}
}
}
| true |
a5cdb259258fbf8f4d59cc6b748f566078cb09fb | Java | RomanovskijAlexandr/JavaTweetProject | /src/com/company/Parser_States.java | UTF-8 | 1,402 | 3.109375 | 3 | [] | no_license | package com.company;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Parser_States {
public static ArrayList<State> parse (String stateCoordinate){
Pattern nameState = Pattern.compile("[A-Z]{2}");
ArrayList<State> stateCollectionCoordinate = new ArrayList<>();
String[] arr=stateCoordinate.split(", \"");
for(int i = 0; i<arr.length; i++){
Matcher m1 = nameState.matcher(arr[i]);
m1.find();
State state = getState(m1.group(),arr[i]);
stateCollectionCoordinate.add(state);
}
return stateCollectionCoordinate;
}
public static State getState(String name, String str){
State state = new State(name);
Pattern coordinates = Pattern.compile("(\\-?[0-9]+\\.[0-9]+)");
Matcher m2 = coordinates.matcher(str);
Polygon polygon = new Polygon();
while(m2.find()) {
Point2D.Double point = new Point2D.Double();
point.x = Double.parseDouble(m2.group());
m2.find();
point.y = Double.parseDouble(m2.group());
state.addCoordinate(point);
polygon.addPoint((int)(point.x * 10 + 1750),(int)(-1 * point.y * 10 + 800));
}
state.setPolygon(polygon);
return state;
}
}
| true |
3276dbc7de6b0e720ef04ae69aa38c0a6ac56ce7 | Java | m-shayanshafi/FactRepositoryProjects | /FruitWar/src/fruitwar/IFruitWarRobot.java | UTF-8 | 913 | 3.046875 | 3 | [] | no_license | package fruitwar;
/**
* This is the base of Fruit War robot. Implement this interface
* to create your own robot.
*
* @author wangnan
*
*/
public interface IFruitWarRobot {
/**
* This method is used to set actions in the next round. Customize
* this method to set action of each thrower in the current round.
*
* @param throwers Array with dynamic length
* {max @code fruitwar.core.Rules.BASKET_CNT}, which contains only
* active throwers. If at position n the thrower is out of play,
* it will not be included in this array.
*/
public void strategy(IFruitThrower[] throwers);
/**
* The enemy info of the last round. The length of parameter
* "enemies" is fixed value: {@code fruitwar.Rules.BASKET_CNT}.
* If there's no enemy thrower at a position, the element in
* the array is null.
*
*/
public void result(EnemyInfo[] enemies);
}
| true |
3f45330c7942e0da5a40d3eb30b4aa2ff5d6ca49 | Java | Gigaspaces/xap-openspaces | /src/main/java/org/openspaces/events/notify/NotifyType.java | UTF-8 | 2,197 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openspaces.events.notify;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Controls which type of notifications will be sent.
*
* @author kimchy
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotifyType {
/**
* Should this listener be notified when write occurs and it matches the given template.
*/
boolean write() default false;
/**
* Should this listener be notified when take occurs and it matches the given template.
*/
boolean take() default false;
/**
* Should this listener be notified when update occurs and it matches the given template.
*/
boolean update() default false;
/**
* Should this listener be notified when lease expiration occurs and it matches the given template.
*/
boolean leaseExpire() default false;
/**
* Should this listener be notified when entries that no longer match the provided template be notified.
*/
boolean unmatched() default false;
/**
* Should this listener be notified when entries that weren't match to a provided template become match after an update occurs.
* @since 9.1
*/
boolean matchedUpdate() default false;
/**
* Should this listener be notified when entries that were already match to a provided template stays match after an update occurs.
* @since 9.1
*/
boolean rematchedUpdate() default false;
}
| true |
afdbe4eb24973cdecb2d43a71df106be87729b57 | Java | slikhaar/WebStudyPoint2702 | /src/java/rest/PersonResource.java | UTF-8 | 1,744 | 2.46875 | 2 | [] | no_license | package rest;
import com.google.gson.Gson;
import exception.PersonNotFoundException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import model.IPersonFacade;
import model.MockPersonFacade;
import model.Person;
@Path("person")
public class PersonResource {
static IPersonFacade facade = MockPersonFacade.getFacade(false, true);
static Gson gson = new Gson();
@Context
private UriInfo context;
public PersonResource() {
}
@GET
@Produces("application/json")
public String getAll() {
return gson.toJson(facade.getPersons());
}
@GET
@Produces("application/json")
@Path("/{id}")
public String getPerson(@PathParam("id") int id) throws PersonNotFoundException {
return gson.toJson(facade.getPerson(id));
}
@POST
@Produces("application/json")
@Consumes("application/json")
public String AddPerson(String jsonPerson) {
Person p = gson.fromJson(jsonPerson, Person.class);
return gson.toJson(facade.addPerson(p));
}
@PUT
@Produces("application/json")
@Consumes("application/json")
public String EditPerson(String jsonPerson) throws PersonNotFoundException {
Person p = gson.fromJson(jsonPerson, Person.class);
return gson.toJson(facade.editPerson(p));
}
@DELETE
@Consumes("text/plain")
@Path("/{id}")
public String deletePerson(@PathParam("id") int id) throws PersonNotFoundException {
return gson.toJson(facade.deletePerson(id));
}
}
| true |
b05c208e27b82af04266a3e10766ef3d1fce63ac | Java | ioreskovic/CrackingTheCodingInterview | /src/com/lopina/exercises/chapter8/question2/EmployeeResourcePools.java | UTF-8 | 1,149 | 3.328125 | 3 | [] | no_license | package com.lopina.exercises.chapter8.question2;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
public class EmployeeResourcePools {
private static Map<Rank, Deque<Employee>> queues;
static {
queues = new HashMap<Rank, Deque<Employee>>();
createRespondents();
createManagers();
createDirectors();
}
public static Employee getFirstAvailable(Rank rank) {
Deque<Employee> employees = queues.get(rank);
for (Employee employee : employees) {
if (employee.isAvailable()) {
return employee;
}
}
return null;
}
private static void createRespondents() {
createEmployees(Rank.RESPONDENT);
}
private static void createManagers() {
createEmployees(Rank.MANAGER);
}
private static void createDirectors() {
createEmployees(Rank.DIRECTOR);
}
private static void createEmployees(Rank rank) {
ArrayDeque<Employee> employees = new ArrayDeque<Employee>(rank.getNumberOf());
for (int i = 0; i < rank.getNumberOf(); i++) {
employees.offerLast(Employee.create(rank, rank + "[" + i + "]", true));
}
queues.put(rank, employees);
}
}
| true |
b292131577c4b9e79bf5332ef9481b23fc29a894 | Java | spring-projects/spring-data-examples | /jpa/deferred/src/main/java/example/service/Customer244Service.java | UTF-8 | 221 | 1.671875 | 2 | [
"Apache-2.0"
] | permissive | package example.service;
import example.repo.Customer244Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer244Service {
public Customer244Service(Customer244Repository repo) {}
}
| true |
2892305235a1c75170bba12183fd0ed184040783 | Java | liu-liang15/huo_shen_shan | /src/main/java/com/example/model/dao/inpatient/ExpCalDao.java | UTF-8 | 341 | 1.875 | 2 | [] | no_license | package com.example.model.dao.inpatient;
import com.example.model.pojos.inpatient.ExpCal;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ExpCalDao {
//查看消费记录
public List<ExpCal> selExpCal(String param);
//新增消费记录
public void addExpCal(ExpCal expCal);
}
| true |
49fe7137b251e8d2c25c7173b4bcdabf860e908b | Java | hq666666/java-basic | /src/tests/java/com/person/test/AnnotationTest.java | UTF-8 | 3,697 | 3.0625 | 3 | [] | no_license | package com.person.test;
import com.person.annotations.*;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
public class AnnotationTest {
/**
* 反射对于注解的应用;
*
* 注意:
*/
@Test
public void test(){
//通过isAnnotationPresent方法判断指定注解类型是否应用到当前类对象
boolean flag = Example.class.isAnnotationPresent(Auth.class);
if(flag){
//通过getAnnotation方法获取指定注解的对象;
Auth annotation = Example.class.getAnnotation(Auth.class);
System.out.println("id="+annotation.id());
System.out.println("msg="+annotation.msg());
}
}
@Test
public void test2() throws ClassNotFoundException {
String className = "com.person.annotations.Member";
String result = createTableSql(className);
System.out.println("Table Creation SQL for "+className+"is:\n"+result);
}
private String createTableSql(String className) throws ClassNotFoundException {
Class<?> acl = Class.forName(className);
DBTable dbTable = acl.getAnnotation(DBTable.class);
if(null == dbTable){
System.out.println("NO DBTable Annotation in class"+className);
return null;
}
String tableName = dbTable.name();
//判断是否有值,可以使用当前类名作为表明
if(tableName.length()<1)
tableName = acl.getName().toUpperCase();
ArrayList<String> strings = new ArrayList<String>();
//获取该类的所有字段
for(Field field:acl.getDeclaredFields()){
String cloumnName = null;
Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
System.out.println(declaredAnnotations);
if(declaredAnnotations.length<1)continue;
if(declaredAnnotations[0] instanceof SQLInteger){
SQLInteger cloumnInteger = (SQLInteger) declaredAnnotations[0];
//获取字段名称
if(cloumnInteger.name().length()<1)
cloumnName=field.getName().toUpperCase();
else
cloumnName=cloumnInteger.name();
strings.add(cloumnName+" INT "+getConstraint(cloumnInteger.CONSTRAINT()));
}
if(declaredAnnotations[0] instanceof SQLString){
SQLString cloumnString = (SQLString) declaredAnnotations[0];
if(cloumnString.name().length()<1)
cloumnName =field.getName().toUpperCase();
else
cloumnName = cloumnString.name();
strings.add(cloumnName+" VARCHAR("+cloumnString.value()+") "+getConstraint(cloumnString.CONSTRAINT()));
}
}
//数据库表构建语句
StringBuilder createCommand = new StringBuilder("CREATE TABLE"+tableName+"(");
for(String str:strings){
createCommand.append("\n "+str+",");
}
String tableCreate = createCommand.substring(0,createCommand.length()-1)+")";
return tableCreate;
}
/**
* 判断该字段是否有其他约束
* @param constraint
* @return
*/
private String getConstraint(Constraint constraint) {
String constraints ="";
if(!constraint.allowNull())
constraints+="NOT NULL";
else
constraints+="NULL";
if(constraint.primaryKey())constraints+="PRIMARY KEY";
if(constraint.unique())constraints+="UNIQUE";
return constraints;
}
}
| true |
23a4170811e578b789c78b56ead04ba4e2bbcdde | Java | jpreciadom/OptiTransmi | /ShippingData/src/Information/News.java | UTF-8 | 654 | 2.265625 | 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 Information;
import Base.BasePackage;
/**
*
* @author Juan Diego
*/
public class News extends BasePackage {
private final String title;
private final String content;
public News(String title, String content, int idRequest) {
super(10, idRequest);
this.title = title;
this.content = content;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
}
| true |
02eccd8c69892b636f2ad02742012bd92e78773d | Java | luolian0/wust-AIStation | /container-scheduler-service/src/main/java/com/wust/pojo/kubernetes/Rbd.java | UTF-8 | 1,680 | 1.921875 | 2 | [] | no_license | /**
* Copyright 2019 bejson.com
*/
package com.wust.pojo.kubernetes;
import java.util.List;
/**
* Auto-generated: 2019-02-20 21:8:53
*
* @author bejson.com (i@bejson.com)
* @website http://www.bejson.com/java2pojo/
*/
public class Rbd {
private List<String> monitors;
private String image;
private String fsType;
private String pool;
private String user;
private String keyring;
private SecretRef secretRef;
private boolean readOnly;
public void setMonitors(List<String> monitors) {
this.monitors = monitors;
}
public List<String> getMonitors() {
return monitors;
}
public void setImage(String image) {
this.image = image;
}
public String getImage() {
return image;
}
public void setFsType(String fsType) {
this.fsType = fsType;
}
public String getFsType() {
return fsType;
}
public void setPool(String pool) {
this.pool = pool;
}
public String getPool() {
return pool;
}
public void setUser(String user) {
this.user = user;
}
public String getUser() {
return user;
}
public void setKeyring(String keyring) {
this.keyring = keyring;
}
public String getKeyring() {
return keyring;
}
public void setSecretRef(SecretRef secretRef) {
this.secretRef = secretRef;
}
public SecretRef getSecretRef() {
return secretRef;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public boolean getReadOnly() {
return readOnly;
}
} | true |
231e6f1ecfba0636de5b5d29f517cbbfde2a4ffc | Java | OtabO/main.template | /dao.template/src/main/java/dao/template/RoleDAO.java | UTF-8 | 227 | 1.507813 | 2 | [] | no_license | package dao.template;
import bean.template.RoleDO;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by zhangsx on 2017/6/15.
*/
public interface RoleDAO extends JpaRepository<RoleDO, Integer> {
}
| true |
7eb7c4ccc842e509959ba86f5e633fb13c99aa4b | Java | orbeon/saxon | /src/main/java/org/orbeon/saxon/sort/DoubleSortComparer.java | UTF-8 | 4,262 | 2.90625 | 3 | [] | no_license | package org.orbeon.saxon.sort;
import org.orbeon.saxon.expr.XPathContext;
import org.orbeon.saxon.om.StandardNames;
import org.orbeon.saxon.value.AtomicValue;
import org.orbeon.saxon.value.NumericValue;
/**
* An AtomicComparer used for sorting values that are known to be numeric.
* It also supports a separate method for getting a collation key to test equality of items.
* This comparator treats NaN values as equal to each other, and less than any other value.
*
* @author Michael H. Kay
*
*/
public class DoubleSortComparer implements AtomicComparer {
private static DoubleSortComparer THE_INSTANCE = new DoubleSortComparer();
/**
* Get the singular instance of this class
* @return the singular instance
*/
public static DoubleSortComparer getInstance() {
return THE_INSTANCE;
}
private DoubleSortComparer() {
}
/**
* Supply the dynamic context in case this is needed for the comparison
*
* @param context the dynamic evaluation context
* @return either the original AtomicComparer, or a new AtomicComparer in which the context
* is known. The original AtomicComparer is not modified
*/
public AtomicComparer provideContext(XPathContext context) {
return this;
}
/**
* Compare two AtomicValue objects according to the rules for their data type.
* @param a the first object to be compared. It is intended that this should normally be an instance
* of AtomicValue, though this restriction is not enforced. If it is a StringValue, the
* collator is used to compare the values, otherwise the value must implement the java.util.Comparable
* interface.
* @param b the second object to be compared. This must be comparable with the first object: for
* example, if one is a string, they must both be strings.
* @return <0 if a<b, 0 if a=b, >0 if a>b
* @throws ClassCastException if the objects are not comparable
*/
public int compareAtomicValues(AtomicValue a, AtomicValue b) {
if (a == null) {
if (b == null) {
return 0;
} else {
return -1;
}
} else if (b == null) {
return +1;
}
NumericValue an = (NumericValue)a;
NumericValue bn = (NumericValue)b;
if (an.isNaN()) {
return (bn.isNaN() ? 0 : -1);
} else if (bn.isNaN()) {
return +1;
}
return an.compareTo(bn);
}
/**
* Test whether two values compare equal. Note that for this comparer, NaN is considered equal to itself
*/
public boolean comparesEqual(AtomicValue a, AtomicValue b) {
return compareAtomicValues(a, b) == 0;
}
/**
* Get a comparison key for an object. This must satisfy the rule that if two objects are equal as defined
* by the XPath eq operator, then their comparison keys are equal as defined by the Java equals() method,
* and vice versa. There is no requirement that the comparison keys should reflect the ordering of the
* underlying objects.
*/
public ComparisonKey getComparisonKey(AtomicValue a) {
if (((NumericValue)a).isNaN()) {
// Deal with NaN specially. For sorting and similar operations, NaN is considered equal to itself
return new ComparisonKey(StandardNames.XS_NUMERIC, AtomicSortComparer.COLLATION_KEY_NaN);
} else {
return new ComparisonKey(StandardNames.XS_NUMERIC, a);
}
}
}
//
// The contents of this file are subject to the Mozilla Public License Version 1.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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is: all this file.
//
// The Initial Developer of the Original Code is Michael H. Kay
//
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
//
// Contributor(s): none
// | true |
2340bc3ce688f6974120ac0fe9bd049e0a2f003f | Java | liuboyan69/openmessaging-connect | /connector/src/main/java/io/openmessaging/connector/api/data/SinkDataEntry.java | UTF-8 | 3,765 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.openmessaging.connector.api.data;
import io.openmessaging.connector.api.header.Headers;
/**
* SinkDataEntry is read from message queue and includes the queueOffset of the data in message queue.
*
* @version OMS 0.1.0
* @since OMS 0.1.0
*/
public class SinkDataEntry extends DataEntry {
/**
* Offset in the message queue.
*/
private Long queueOffset;
public SinkDataEntry(Long queueOffset,
Long timestamp,
String queueName,
String shardingKey,
EntryType entryType,
MetaAndData key,
MetaAndData value,
Headers headers) {
super(timestamp, queueName, shardingKey, entryType, key, value, headers);
this.queueOffset = queueOffset;
}
public SinkDataEntry(Long queueOffset,
String queueName,
String shardingKey,
EntryType entryType,
MetaAndData key,
MetaAndData value,
Headers headers) {
this(queueOffset, null, queueName, shardingKey, entryType, key, value, headers);
}
public SinkDataEntry(Long queueOffset,
Long timestamp,
String queueName,
String shardingKey,
EntryType entryType,
MetaAndData key,
MetaAndData value) {
this(queueOffset, timestamp, queueName, shardingKey, entryType, key, value, null);
}
public SinkDataEntry newRecord(Long queueOffset,
Long timestamp,
String queueName,
String shardingKey,
EntryType entryType,
MetaAndData key,
MetaAndData value) {
return new SinkDataEntry(queueOffset, timestamp, queueName, shardingKey, entryType, key, value,
getHeaders().duplicate());
}
public SinkDataEntry newRecord(Long queueOffset,
Long timestamp,
String queueName,
String shardingKey,
EntryType entryType,
MetaAndData key,
MetaAndData value,
Headers headers) {
return new SinkDataEntry(queueOffset, timestamp, queueName, shardingKey, entryType, key, value, headers);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
SinkDataEntry that = (SinkDataEntry)o;
return queueOffset.equals(that.queueOffset);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + Long.hashCode(queueOffset);
return result;
}
@Override
public String toString() {
return "SinkDataEntry{" +
"queueOffset=" + queueOffset +
"} " + super.toString();
}
public Long getQueueOffset() {
return queueOffset;
}
public void setQueueOffset(Long queueOffset) {
this.queueOffset = queueOffset;
}
}
| true |
250b50a910ab1c9c56cbffe73b772fee78585e17 | Java | fe-lsc/PrimeiroExercicioPOO2 | /Atividades/primeiro_exercicio_poo/src/main/java/com/primeiro/exercicio/primeiro_exercicio_poo/Controller/EmployeeController.java | UTF-8 | 917 | 2.0625 | 2 | [] | no_license | package com.primeiro.exercicio.primeiro_exercicio_poo.Controller;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import com.primeiro.exercicio.primeiro_exercicio_poo.DTOs.EmployeeDTO;
import com.primeiro.exercicio.primeiro_exercicio_poo.Services.ServiceEmployee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private ServiceEmployee serviceEmployee;
@GetMapping()
public ResponseEntity<List<EmployeeDTO>> getEmployees() {
List<EmployeeDTO> employeesDTO = serviceEmployee.getEmployeesDTO();
return ResponseEntity.ok().body(employeesDTO);
}
}
| true |
3b0ec5d933e54c574e1d3012578e393644a9e73a | Java | daniel-va/Jei | /src/jei/collections/Array.java | UTF-8 | 1,110 | 2.78125 | 3 | [
"MIT"
] | permissive | package jei.collections;
import jei.functional.Predicate;
public interface Array<T> extends FinalArray<T>
{
public static <T> Array<T> withSize(int size) {
return new DefaultArray<>(size);
}
@SafeVarargs
public static <T> Array<T> of(T... values) {
Array<T> array = new DefaultArray<>(values.length);
array.addAll(values);
return array;
}
public static <T> Array<T> empty() {
return new DefaultArray<>(10);
}
public static <T> Array<T> from(Iterable<T> iterable) {
Array<T> array = new DefaultArray<>(0);
array.addAll(iterable);
return array;
}
void add(T entry);
void add(int index, T entry);
void addAll(T[] entry);
void addAll(Iterable<T> entries);
T set(int index, T entry);
boolean set(T occurence, T replacement);
boolean setWhere(T entry, Predicate<T> predicate);
boolean setFirst(T occurence, T replacement);
boolean setLast(T occurence, T replacement);
T remove(int index);
boolean remove(T entry);
boolean removeWhere(Predicate<T> predicate);
T first();
T last();
void clear();
FinalArray<T> readOnly();
T[] toNativeArray(Class<T> clazz);
}
| true |
4989c48f384172629a2c92376f3436b7ac4e6c18 | Java | 1210040004/-offer- | /src/面试/算法/leetcode/Q77Combinations/Solution2.java | UTF-8 | 1,296 | 3.4375 | 3 | [] | no_license | package 面试.算法.leetcode.Q77Combinations;
import java.util.ArrayList;
import java.util.List;
/**
* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
*
* 示例:
*
* 输入: n = 4, k = 2
* 输出:
* [
* [2,4],
* [3,4],
* [2,3],
* [1,2],
* [1,3],
* [1,4],
* ]
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/combinations
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Solution2 {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> combineList = new ArrayList<>();
backtracking(combineList, combinations, 1, k, n);
return combinations;
}
private void backtracking(List<Integer> combineList, List<List<Integer>> combinations, int start, int k, final int n) {
if (k == 0) {
combinations.add(new ArrayList<>(combineList));
return;
}
for (int i = start; i <= n - k + 1; i++) { // 剪枝
combineList.add(i);
backtracking(combineList, combinations, i + 1, k - 1, n);
combineList.remove(combineList.size() - 1);
}
}
}
| true |
ec872651d5a387278b9da80a52f268ffe95d20df | Java | BorderTech/webfriends | /webfriends-api/src/main/java/com/github/bordertech/webfriends/api/idiom/widget/HDisclosure.java | UTF-8 | 295 | 1.609375 | 2 | [
"MIT"
] | permissive | package com.github.bordertech.webfriends.api.idiom.widget;
import com.github.bordertech.webfriends.api.element.Element;
/**
* Disclosure element.
* <p>
* https://www.w3.org/TR/wai-aria-practices/#disclosure
* </p>
*/
public interface HDisclosure extends Element {
// TODO
}
| true |
97c42568bb1e8449bc9ed3371fbfef19284fb52e | Java | koloheohana/MyMap | /app/src/main/java/com/koloheohana/mymap/MapStreetView.java | UTF-8 | 1,438 | 2.15625 | 2 | [] | no_license | package com.koloheohana.mymap;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback;
import com.google.android.gms.maps.StreetViewPanorama;
import com.google.android.gms.maps.StreetViewPanoramaFragment;
import com.google.android.gms.maps.model.LatLng;
import com.koloheohana.mymap.util.Scene;
/**
* Created by User on 2017/06/02.
*/
public class MapStreetView extends FragmentActivity implements OnStreetViewPanoramaReadyCallback{
public static LatLng latLng;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Scene.set(this);
setContentView(R.layout.street_view);
StreetViewPanoramaFragment streetViewPanoramaFragment = (StreetViewPanoramaFragment)getFragmentManager().findFragmentById(R.id.streetviewpanorama);
streetViewPanoramaFragment.getStreetViewPanoramaAsync(this);
Intent intent = getIntent();
Double latitude = (Double) intent.getSerializableExtra("latitude");
Double longitude = (Double) intent.getSerializableExtra("longitude");
latLng = new LatLng(latitude,longitude);
}
//ストリートビューの取得
@Override
public void onStreetViewPanoramaReady(StreetViewPanorama streetViewPanorama) {
streetViewPanorama.setPosition(latLng);
}
}
| true |
582a034a53f6549657e3531571cd310bd84d09fc | Java | Kylem92/FYP | /src/main/java/scrapers/Render.java | UTF-8 | 2,079 | 2.703125 | 3 | [] | no_license | package scrapers;
/**
* Created by Amanda on 06/03/2017.
*/
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Render extends Application {
public static void main(String[] args) throws InterruptedException {
launch(args);
compile();
System.out.println("stop");
}
public static void compile() throws InterruptedException {
Thread t = new Thread() {
@Override
public void run() {
new Render().start(new Stage());
}
};
Platform.runLater(t);
t.join(); // never get here!
}
public void start(final Stage primaryStage) {
final WebView webView = new WebView();
final WebEngine engine = webView.getEngine();
//final WebEngine engine = new WebEngine();
//engine.documentProperty().addListener( new ChangeListener<Document>() { @Override public void changed(ObservableValue<? extends Document> prop, Document oldDoc, Document newDoc) {
engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
if (newState == Worker.State.SUCCEEDED) {
System.out.println(engine.getDocument());
primaryStage.close();
//Platform.setImplicitExit(true);
Platform.exit(); // platform will not exit ... it will exit if I use Application.launch(), but throws an error: java.lang.IllegalStateException: Attempt to call defer when toolkit not running
System.out.println("after exit");
}
}
});
engine.load("https://www.bet365.com");
System.out.println(engine.getDocument());
}
} | true |
737b6cc3d3b7688bd7cb6449d3f6859ccb20789a | Java | Phantoms007/zhihuAPK | /src/main/java/org/conscrypt/NativeLibraryLoader.java | UTF-8 | 13,488 | 1.9375 | 2 | [] | no_license | package org.conscrypt;
import com.ali.auth.third.core.model.Constants;
import com.zhihu.android.apm.traffic.p1007b.HttpURLWrapper;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.MessageFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/* access modifiers changed from: package-private */
/* renamed from: org.conscrypt.ad */
/* compiled from: NativeLibraryLoader */
public final class NativeLibraryLoader {
/* renamed from: a */
private static final Logger f114705a = Logger.getLogger(NativeLibraryLoader.class.getName());
/* renamed from: b */
private static final File f114706b;
/* renamed from: c */
private static final boolean f114707c = Boolean.valueOf(System.getProperty("org.conscrypt.native.deleteLibAfterLoading", Constants.SERVICE_SCOPE_FLAG_VALUE)).booleanValue();
static {
File a = m154595a();
if (a == null) {
a = HostProperties.m155016c();
}
f114706b = a;
m154609b("-D{0}: {1}", "org.conscrypt.native.workdir", f114706b);
}
/* renamed from: a */
private static File m154595a() {
String property = System.getProperty("org.conscrypt.native.workdir");
if (property == null) {
return null;
}
File file = new File(property);
if (file.mkdirs() || file.exists()) {
try {
return file.getAbsoluteFile();
} catch (Exception unused) {
return file;
}
} else {
m154600a("Unable to find or create working directory: {0}", property);
return null;
}
}
/* renamed from: a */
static boolean m154606a(ClassLoader classLoader, List<C33237a> list, String... strArr) {
for (String str : strArr) {
if (m154607a(str, classLoader, list)) {
return true;
}
}
return false;
}
/* access modifiers changed from: package-private */
/* renamed from: org.conscrypt.ad$a */
/* compiled from: NativeLibraryLoader */
public static final class C33237a {
/* renamed from: a */
final String f114714a;
/* renamed from: b */
final boolean f114715b;
/* renamed from: c */
final boolean f114716c;
/* renamed from: d */
final boolean f114717d;
/* renamed from: e */
final Throwable f114718e;
/* access modifiers changed from: private */
/* renamed from: b */
public static C33237a m154616b(String str, boolean z, boolean z2) {
return new C33237a(str, z, true, z2, null);
}
/* access modifiers changed from: private */
/* renamed from: b */
public static C33237a m154617b(String str, boolean z, boolean z2, Throwable th) {
return new C33237a(str, z, false, z2, th);
}
private C33237a(String str, boolean z, boolean z2, boolean z3, Throwable th) {
this.f114714a = str;
this.f114715b = z;
this.f114716c = z2;
this.f114717d = z3;
this.f114718e = th;
}
/* access modifiers changed from: package-private */
/* renamed from: a */
public void mo134164a() {
if (this.f114718e != null) {
NativeLibraryLoader.m154610b("Unable to load the library {0} (using helper classloader={1})", this.f114714a, Boolean.valueOf(this.f114717d), this.f114718e);
} else {
NativeLibraryLoader.m154609b("Successfully loaded library {0} (using helper classloader={1})", this.f114714a, Boolean.valueOf(this.f114717d));
}
}
}
/* renamed from: a */
private static boolean m154607a(String str, ClassLoader classLoader, List<C33237a> list) {
return m154611b(str, classLoader, list) || m154605a(classLoader, str, false, list);
}
/* renamed from: b */
private static boolean m154611b(String str, ClassLoader classLoader, List<C33237a> list) {
String mapLibraryName = System.mapLibraryName(str);
String str2 = "META-INF/native/" + mapLibraryName;
URL resource = classLoader.getResource(str2);
if (resource == null && HostProperties.m155015b()) {
if (str2.endsWith(".jnilib")) {
resource = classLoader.getResource("META-INF/native/lib" + str + ".dynlib");
} else {
resource = classLoader.getResource("META-INF/native/lib" + str + ".jnilib");
}
}
boolean z = false;
if (resource == null) {
return false;
}
int lastIndexOf = mapLibraryName.lastIndexOf(46);
String substring = mapLibraryName.substring(0, lastIndexOf);
String substring2 = mapLibraryName.substring(lastIndexOf, mapLibraryName.length());
File file = null;
try {
File a = C33246aw.m154702a(substring, substring2, f114706b);
if (a.isFile() && a.canRead()) {
if (!C33246aw.m154724a(a)) {
throw new IOException(MessageFormat.format("{0} exists but cannot be executed even when execute permissions set; check volume for \"noexec\" flag; use -D{1}=[path] to set native working directory separately.", a.getPath(), "org.conscrypt.native.workdir"));
}
}
m154604a(resource, a);
boolean a2 = m154605a(classLoader, a.getPath(), true, list);
if (a != null) {
if (f114707c) {
z = a.delete();
}
if (!z) {
a.deleteOnExit();
}
}
return a2;
} catch (IOException e) {
list.add(C33237a.m154617b(str, true, false, new UnsatisfiedLinkError(MessageFormat.format("Failed creating temp file ({0})", null)).initCause(e)));
if (0 != 0) {
if (!(f114707c ? file.delete() : false)) {
file.deleteOnExit();
}
}
return false;
} catch (Throwable th) {
if (0 != 0) {
if (f114707c) {
z = file.delete();
}
if (!z) {
file.deleteOnExit();
}
}
throw th;
}
}
/* renamed from: a */
private static void m154604a(URL url, File file) throws IOException {
Throwable th;
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = HttpURLWrapper.m56770a(url);
try {
fileOutputStream = new FileOutputStream(file);
} catch (Throwable th2) {
th = th2;
fileOutputStream = null;
m154599a(inputStream);
m154599a(fileOutputStream);
throw th;
}
try {
byte[] bArr = new byte[8192];
while (true) {
int read = inputStream.read(bArr);
if (read > 0) {
fileOutputStream.write(bArr, 0, read);
} else {
fileOutputStream.flush();
m154599a(inputStream);
m154599a(fileOutputStream);
return;
}
}
} catch (Throwable th3) {
th = th3;
m154599a(inputStream);
m154599a(fileOutputStream);
throw th;
}
} catch (Throwable th4) {
th = th4;
inputStream = null;
fileOutputStream = null;
m154599a(inputStream);
m154599a(fileOutputStream);
throw th;
}
}
/* renamed from: a */
private static boolean m154605a(ClassLoader classLoader, String str, boolean z, List<C33237a> list) {
try {
C33237a a = m154597a(m154596a(classLoader, NativeLibraryUtil.class), str, z);
list.add(a);
if (a.f114716c) {
return true;
}
} catch (Exception unused) {
}
C33237a a2 = m154598a(str, z);
list.add(a2);
return a2.f114716c;
}
/* renamed from: a */
private static C33237a m154597a(final Class<?> cls, final String str, final boolean z) {
return (C33237a) AccessController.doPrivileged(new PrivilegedAction<C33237a>() {
/* class org.conscrypt.NativeLibraryLoader.C332351 */
/* renamed from: a */
public C33237a run() {
try {
Method method = cls.getMethod("loadLibrary", String.class, Boolean.TYPE);
method.setAccessible(true);
method.invoke(null, str, Boolean.valueOf(z));
return C33237a.m154616b(str, z, true);
} catch (InvocationTargetException e) {
return C33237a.m154617b(str, z, true, e.getCause());
} catch (Throwable th) {
return C33237a.m154617b(str, z, true, th);
}
}
});
}
/* renamed from: a */
private static C33237a m154598a(String str, boolean z) {
try {
NativeLibraryUtil.m154619a(str, z);
return C33237a.m154616b(str, z, false);
} catch (Throwable th) {
return C33237a.m154617b(str, z, false, th);
}
}
/* renamed from: a */
private static Class<?> m154596a(final ClassLoader classLoader, final Class<?> cls) throws ClassNotFoundException {
try {
return classLoader.loadClass(cls.getName());
} catch (ClassNotFoundException unused) {
final byte[] a = m154608a(cls);
return (Class) AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
/* class org.conscrypt.NativeLibraryLoader.C332362 */
/* renamed from: a */
public Class<?> run() {
try {
Method declaredMethod = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE);
declaredMethod.setAccessible(true);
return (Class) declaredMethod.invoke(classLoader, cls.getName(), a, 0, Integer.valueOf(a.length));
} catch (Exception e) {
throw new IllegalStateException("Define class failed!", e);
}
}
});
}
}
/* renamed from: a */
private static byte[] m154608a(Class<?> cls) throws ClassNotFoundException {
String name = cls.getName();
int lastIndexOf = name.lastIndexOf(46);
if (lastIndexOf > 0) {
name = name.substring(lastIndexOf + 1);
}
URL resource = cls.getResource(name + ".class");
if (resource != null) {
byte[] bArr = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(4096);
try {
InputStream a = HttpURLWrapper.m56770a(resource);
while (true) {
int read = a.read(bArr);
if (read != -1) {
byteArrayOutputStream.write(bArr, 0, read);
} else {
byte[] byteArray = byteArrayOutputStream.toByteArray();
m154599a(a);
m154599a(byteArrayOutputStream);
return byteArray;
}
}
} catch (IOException e) {
throw new ClassNotFoundException(cls.getName(), e);
} catch (Throwable th) {
m154599a((Closeable) null);
m154599a(byteArrayOutputStream);
throw th;
}
} else {
throw new ClassNotFoundException(cls.getName());
}
}
/* renamed from: a */
private static void m154599a(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException unused) {
}
}
}
private NativeLibraryLoader() {
}
/* renamed from: a */
private static void m154600a(String str, Object obj) {
f114705a.log(Level.FINE, str, obj);
}
/* access modifiers changed from: private */
/* renamed from: b */
public static void m154609b(String str, Object obj, Object obj2) {
f114705a.log(Level.FINE, str, new Object[]{obj, obj2});
}
/* access modifiers changed from: private */
/* renamed from: b */
public static void m154610b(String str, Object obj, Object obj2, Throwable th) {
m154603a(MessageFormat.format(str, obj, obj2), th);
}
/* renamed from: a */
private static void m154603a(String str, Throwable th) {
f114705a.log(Level.FINE, str, th);
}
}
| true |
4d456a244379cb217219547f835f20b2bf445d89 | Java | KristinaPak/java_group_8_homework_28_kristina_pak | /src/com/company/ACTION.java | UTF-8 | 629 | 2.875 | 3 | [] | no_license | package com.company;
public enum ACTION {
USUAL_DAY( "Обычный день"),
RAIN( "Дождь"),
GOOD_ROAD( "Ровная дорога"),
WHEEL_IS_BROKEN( "Сломалось колесо"),
RIVER( "Река"),
MEET_LOCAL( "Встретил местного"),
BANDITS_ON_THE_ROAD("Разбойники большой дороги"),
SHOP("Придорожный трактир"),
GOOD_IS_GONE("Товар испортился");
private String description;
ACTION( String description){this.description = description;}
public String getDescription(){return description;}
}
| true |
9912e15d704aaea30ca842b766d6591784bd8d9a | Java | maniert/ile_interdite2.0 | /src/PasDefaultPackage/Message.java | UTF-8 | 1,436 | 2.625 | 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 PasDefaultPackage;
import java.util.ArrayList;
/**
*
* @author maniert
*/
public class Message {
public TypesMessages type; // type de message
public Tuile t;
private int indiceTuile;
private int indiceMain;
private int nbj;
private ArrayList<String> nomsJoueurs;
public Message() {
nomsJoueurs = new ArrayList<>();
}
/**
* @return the indiceTuile
*/
public int getIndiceTuile() {
return indiceTuile;
}
/**
* @param assechingeFrstTuile the indiceTuile to set
*/
public void setIndiceTuile(int i) {
this.indiceTuile = i;
}
/**
* @return the nbj
*/
public int getNbj() {
return nbj;
}
/**
* @param nbj the nbj to set
*/
public void setNbj(int nbj) {
this.nbj = nbj;
}
/**
* @return the nomsJoueursBase
*/
public ArrayList<String> getNomsJoueurs() {
return nomsJoueurs;
}
/**
* @return the indiceMain
*/
public int getIndiceMain() {
return indiceMain;
}
/**
* @param indiceMain the indiceMain to set
*/
public void setIndiceMain(int indiceMain) {
this.indiceMain = indiceMain;
}
}
| true |
5416277565ee1694784529038e02e49b60f7fa4d | Java | yql1999/yql_hotel | /src/com/ASH/service/visitorSelServlet.java | UTF-8 | 1,190 | 2.09375 | 2 | [] | no_license | package com.ASH.service;
import com.ASH.dao.visitorDao;
import com.ASH.entity.Visitor;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
/*
返回所有访客信息
*/
@WebServlet("/SelAllVisitors.do")
public class visitorSelServlet extends HttpServlet {
public visitorSelServlet(){
super();
}
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");
visitorDao visitorDao=new visitorDao();
ArrayList<Visitor> arrayList=visitorDao.selectAll();
request.getSession().setAttribute("allVisitors",arrayList);
response.setCharacterEncoding("utf-8");
response.sendRedirect("pages/forms/visitor_select.jsp");
}
}
| true |
f1349279d0fab8956185e03993a49ceb34307610 | Java | poxiaozheng/ImageDealWith | /app/src/main/java/com/example/imagedealwith/Model/ImageState.java | UTF-8 | 389 | 2.578125 | 3 | [] | no_license | package com.example.imagedealwith.Model;
public class ImageState {
private int StateID;
private int StateImageRes;
public ImageState(int stateID, int stateImageRes) {
StateID = stateID;
StateImageRes = stateImageRes;
}
public int getStateID() {
return StateID;
}
public int getStateImageRes() {
return StateImageRes;
}
} | true |
b26a113f769bca314dc6e44180aac5ccd94664f9 | Java | lazarow/chain-panic-button | /app/src/main/java/pl/nowakowski_arkadiusz/chain_panic_button/activities/AlarmChainActivity.java | UTF-8 | 5,620 | 1.96875 | 2 | [] | no_license | package pl.nowakowski_arkadiusz.chain_panic_button.activities;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import pl.nowakowski_arkadiusz.chain_panic_button.R;
import pl.nowakowski_arkadiusz.chain_panic_button.activities.forms.CallChainLinkFormActivity;
import pl.nowakowski_arkadiusz.chain_panic_button.activities.forms.EmailChainLinkFormActivityChain;
import pl.nowakowski_arkadiusz.chain_panic_button.activities.forms.SMSChainLinkFormActivityChain;
import pl.nowakowski_arkadiusz.chain_panic_button.adapters.ChainLinksAdapter;
import pl.nowakowski_arkadiusz.chain_panic_button.dao.ChainLinkDAO;
import pl.nowakowski_arkadiusz.chain_panic_button.models.ChainLink;
import pl.nowakowski_arkadiusz.chain_panic_button.models.ChainLinkType;
public class AlarmChainActivity extends AppCompatActivity {
private Menu menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.alarm_chain);
actionBar.setDisplayHomeAsUpEnabled(true);
}
setContentView(R.layout.activity_alarm_chain);
registerForContextMenu(findViewById(R.id.chain));
}
@Override
protected void onResume() {
ChainLinkDAO dao = new ChainLinkDAO(this);
List<ChainLink> chainLinks = dao.findAll();
dao.close();
if (chainLinks.size() == 0) {
Toast.makeText(AlarmChainActivity.this, R.string.no_chain_links, Toast.LENGTH_SHORT).show();
}
ListView chain = (ListView) findViewById(R.id.chain);
ChainLinksAdapter adapter = new ChainLinksAdapter(this, -1, chainLinks);
chain.setAdapter(adapter);
updateOptionsMenu();
super.onResume();
}
private void updateOptionsMenu() {
ChainLinkDAO dao = new ChainLinkDAO(this);
boolean callLinkExisting = dao.hasCallChainLink();
dao.close();
if (menu != null) {
if (callLinkExisting) {
menu.getItem(0).getSubMenu().getItem(1).setEnabled(false);
} else {
menu.getItem(0).getSubMenu().getItem(1).setEnabled(true);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_alarm_chain, menu);
this.menu = menu;
updateOptionsMenu();
return super.onCreateOptionsMenu(menu);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
ListView chain = (ListView) findViewById(R.id.chain);
final ChainLink chainLink = (ChainLink) chain.getItemAtPosition(info.position);
final MenuItem editItem = menu.add(R.string.edit);
editItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = null;
if (chainLink.getType().equals(ChainLinkType.SMS)) {
intent = new Intent(AlarmChainActivity.this, SMSChainLinkFormActivityChain.class);
} else if (chainLink.getType().equals(ChainLinkType.EMAIL)) {
intent = new Intent(AlarmChainActivity.this, EmailChainLinkFormActivityChain.class);
} else if (chainLink.getType().equals(ChainLinkType.CALL)) {
intent = new Intent(AlarmChainActivity.this, CallChainLinkFormActivity.class);
}
intent.putExtra("chainLink", chainLink);
startActivity(intent);
return false;
}
});
final MenuItem removeItem = menu.add(R.string.remove);
removeItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
ChainLinkDAO dao = new ChainLinkDAO(AlarmChainActivity.this);
dao.delete(chainLink);
dao.close();
AlarmChainActivity.this.onResume();
Toast.makeText(AlarmChainActivity.this, R.string.chain_link_removed, Toast.LENGTH_SHORT).show();
return false;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = null;
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.add_alarm_call:
intent = new Intent(this, CallChainLinkFormActivity.class);
intent.putExtra("chainLink", ChainLink.createCallChainLink(null, "", ""));
break;
case R.id.add_alarm_sms:
intent = new Intent(this, SMSChainLinkFormActivityChain.class);
intent.putExtra("chainLink", ChainLink.createSMSChainLink(null, "", "", false, false, ""));
break;
}
if (intent != null) {
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
| true |
d2fe83b12dc0253248afb579ae686dd77a102bf9 | Java | jhkim105/tutorials | /utils/src/main/java/utils/ReflectionUtils.java | UTF-8 | 611 | 2.328125 | 2 | [] | no_license | package utils;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.util.Set;
import org.reflections.Reflections;
public class ReflectionUtils {
public static Set<Class<?>> getAnnotatedClass(String packageName, Class<? extends Annotation> annotation) {
Reflections reflections = new Reflections(packageName);
return reflections.getTypesAnnotatedWith(annotation);
}
public static Class<?> extractGenericType(Class<?> target, int index) {
return (Class<?>) ((ParameterizedType) target.getGenericSuperclass()).getActualTypeArguments()[index];
}
}
| true |
d72fa36752157117cbd9b4c8918e14722b822c4e | Java | Tschierv/MemoryProject | /src/main/java/com/github/tschierv/memorygame/domain/player/usecase/RemovePlayer.java | UTF-8 | 887 | 2.671875 | 3 | [] | no_license | package com.github.tschierv.memorygame.domain.player.usecase;
import com.github.tschierv.memorygame.domain.player.Player;
import com.github.tschierv.memorygame.domain.player.PlayerRepositoryService;
import com.github.tschierv.memorygame.domain.player.exception.PlayerNotExistException;
public class RemovePlayer implements IRemovePlayer {
private final PlayerRepositoryService playerRepositoryService;
public RemovePlayer(PlayerRepositoryService playerRepositoryService) {
this.playerRepositoryService = playerRepositoryService;
}
@Override
public void execute(String player_name) throws PlayerNotExistException {
if (!playerRepositoryService.doesPlayerNameExists(player_name)) {
throw new PlayerNotExistException("Player : " + player_name + " not found");
}
playerRepositoryService.removePlayer(player_name);
}
} | true |
99a81503a3cdb431e057a1db2ffa98d76f66b40b | Java | ClickerMonkey/ship | /Courses/DBMS Final Project/src/dbms/commands/AddGroup.java | UTF-8 | 2,239 | 3.203125 | 3 | [] | no_license | package dbms.commands;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import dbms.Database;
import dbms.common.InputPrompt;
import dbms.menu.MenuCommand;
import dbms.validator.BooleanValidator;
import dbms.validator.NameValidator;
/**
* =============================================================================
* Add a row to one or more tables (no foreign keys).
* =============================================================================
*
* The MenuCommand which adds a group to a database.
*
* @author Philip Diffenderfer
*
*/
public class AddGroup implements MenuCommand
{
// The SQL query used to insert a group to the database.
private static final String SQL_COMMAND =
"INSERT INTO pd6407.groups " +
"(name, modify_root, modify_owner, modify_member) " +
"VALUES (?, ?, ?, ?)";
/**
* {@inheritDoc}
*/
@Override
public void execute()
{
// Prompt for name, modify_root, modify_owner, modify_member
InputPrompt<String> namePrompt = new InputPrompt<String>(
"Name: ", new NameValidator());
InputPrompt<Boolean> rootPrompt = new InputPrompt<Boolean>(
"Modify Root (t/f): ", new BooleanValidator());
InputPrompt<Boolean> ownerPrompt = new InputPrompt<Boolean>(
"Modify Owners (t/f): ", new BooleanValidator());
InputPrompt<Boolean> memberPrompt = new InputPrompt<Boolean>(
"Modify Members (t/f): ", new BooleanValidator());
String name = namePrompt.getInput();
Boolean root = rootPrompt.getInput();
Boolean owner = ownerPrompt.getInput();
Boolean member = memberPrompt.getInput();
// Get the live connection to the database.
Connection conn = Database.get().getConnection();
try
{
// Create a statement to process the SQL command.
PreparedStatement query = conn.prepareStatement(SQL_COMMAND);
query.setString(1, name);
query.setBoolean(2, root);
query.setBoolean(3, owner);
query.setBoolean(4, member);
// Execute and display success if the group was added.
if (query.executeUpdate() == 1) {
System.out.println("Successful insertion");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
| true |
36ab709f805f2bb6726e514d0d8da70f69388c53 | Java | professorik/Jaconet | /src/UI/SortImage.java | UTF-8 | 6,956 | 2.375 | 2 | [] | no_license | package UI;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
public class SortImage implements Initializable {
@FXML
private Button kar;
@FXML
private AnchorPane anchor;
@FXML
private HBox frameBox;
@FXML
private ImageView mainFrameImageView;
@FXML
private Button backFrameButton;
@FXML
private Button nextFrameButton;
@FXML
private MenuItem uploadFiles;
@FXML
private MenuItem addFiles;
@FXML
private MenuItem run;
@FXML
private MenuItem runAuto;
public static ArrayList<File> inputFiles = new ArrayList<>();
private int currentElem = 0;
private final FileChooser fileChooser = new FileChooser();
@Override
public void initialize(URL location, ResourceBundle resources) {
//Подготовил FileChooser для загрузки файлов, установив фильры
fileChooser.setTitle("Select Files");
fileChooser.setInitialDirectory(new File("C:/Users/Tony/Desktop/TUI-2019(2)"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Photo", "*.jpg", "*.png"));
Parent node = null;
try {
node = FXMLLoader.load(getClass().getResource("/UI/filesUI.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
node.setPickOnBounds(true);
anchor.getChildren().add(node);
backFrameButton.setDisable(true);
nextFrameButton.setDisable(true);
backFrameButton.setOnAction(event -> {
if (currentElem > 0) {
--currentElem;
mainFrameImageView.setImage(new Image(inputFiles.get(currentElem).toURI().toString()));
}
});
nextFrameButton.setOnAction(event -> {
if (currentElem < inputFiles.size() - 2) {
++currentElem;
mainFrameImageView.setImage(new Image(inputFiles.get(currentElem).toURI().toString()));
}
});
//Menu analyzing
uploadFiles.setOnAction(event -> FilesUIController.uploadFilesAndUpdate(false));
addFiles.setOnAction(event -> FilesUIController.uploadFilesAndUpdate(true));
run.setOnAction(event -> startPlay());
runAuto.setOnAction(event -> startPlayWith());
}
//TODO : проверка , что все входящие файлы ТОЛЬКО фото
private void startPlay(){
if (!inputFiles.isEmpty()) {
// inputFiles = new ArrayList<>(Arrays.asList(new File("src/DronePhotos").listFiles()));
currentElem = 0;
Collections.sort(inputFiles, new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
return (int) (getImageDate(lhs).getTime() - getImageDate(rhs).getTime());
}
});
//Инициализирую первым фрэймом image view
mainFrameImageView.setImage(new Image(inputFiles.get(currentElem).toURI().toString()));
//Делаю доступными кнопки переключения фрэймов (файлы уже загружены)
backFrameButton.setDisable(false);
nextFrameButton.setDisable(false);
for (File file : inputFiles) {
VBox vBox = new VBox();
Image image = new Image(file.toURI().toString(), (100 * 4032) / 3024, 100, true, true, true);
ImageView iv = new ImageView();
iv.setImage(image);
iv.setPreserveRatio(true);
iv.setSmooth(true);
iv.setCache(true);
vBox.getChildren().addAll(iv);
frameBox.getChildren().add(vBox);
}
}
}
private void startPlayWith(){
if (!inputFiles.isEmpty()) {
// inputFiles = new ArrayList<>(Arrays.asList(new File("src/DronePhotos").listFiles()));
//currentElem = 0;
Collections.sort(inputFiles, new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
return (int) (getImageDate(lhs).getTime() - getImageDate(rhs).getTime());
}
});
Timeline timeline = new Timeline();
Duration totalDelay = Duration.ZERO;
for (File file : inputFiles) {
KeyFrame frame = new KeyFrame(totalDelay, e -> mainFrameImageView.setImage(new Image(file.toURI().toString(), (400 * 4032) / 3024, 400, true, true, true)));
timeline.getKeyFrames().add(frame);
totalDelay = totalDelay.add(new Duration(1500));
}
timeline.play();
//Инициализирую первым фрэймом image view
// mainFrameImageView.setImage(new Image(inputFiles.get(currentElem).toURI().toString()));
//Делаю доступными кнопки переключения фрэймов (файлы уже загружены)
// backFrameButton.setDisable(false);
// nextFrameButton.setDisable(false);
for (File file : inputFiles) {
VBox vBox = new VBox();
Image image = new Image(file.toURI().toString(), (100 * 4032) / 3024, 100, true, true, true);
ImageView iv = new ImageView();
iv.setImage(image);
iv.setPreserveRatio(true);
iv.setSmooth(true);
iv.setCache(true);
vBox.getChildren().addAll(iv);
frameBox.getChildren().add(vBox);
}
}
}
private Date getImageDate(File file) {
Metadata metadata = null;
try {
metadata = ImageMetadataReader.readMetadata(file);
} catch (ImageProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ExifSubIFDDirectory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
return date;
}
}
| true |
e45166e67ea60cb4ed81c765ad2eae418c12a228 | Java | FL0RlAN/android-tchap-1.0.35 | /sources/org/matrix/androidsdk/crypto/cryptostore/db/RealmCryptoStore$setKeyBackupVersion$1.java | UTF-8 | 1,571 | 1.898438 | 2 | [] | no_license | package org.matrix.androidsdk.crypto.cryptostore.db;
import io.realm.Realm;
import io.realm.RealmQuery;
import kotlin.Metadata;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.internal.Intrinsics;
import kotlin.jvm.internal.Lambda;
import org.matrix.androidsdk.crypto.cryptostore.db.model.CryptoMetadataEntity;
@Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u000e\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\u0010\u0000\u001a\u00020\u00012\u0006\u0010\u0002\u001a\u00020\u0003H\n¢\u0006\u0002\b\u0004"}, d2 = {"<anonymous>", "", "it", "Lio/realm/Realm;", "invoke"}, k = 3, mv = {1, 1, 13})
/* compiled from: RealmCryptoStore.kt */
final class RealmCryptoStore$setKeyBackupVersion$1 extends Lambda implements Function1<Realm, Unit> {
final /* synthetic */ String $keyBackupVersion;
RealmCryptoStore$setKeyBackupVersion$1(String str) {
this.$keyBackupVersion = str;
super(1);
}
public /* bridge */ /* synthetic */ Object invoke(Object obj) {
invoke((Realm) obj);
return Unit.INSTANCE;
}
public final void invoke(Realm realm) {
Intrinsics.checkParameterIsNotNull(realm, "it");
RealmQuery where = realm.where(CryptoMetadataEntity.class);
Intrinsics.checkExpressionValueIsNotNull(where, "this.where(T::class.java)");
CryptoMetadataEntity cryptoMetadataEntity = (CryptoMetadataEntity) where.findFirst();
if (cryptoMetadataEntity != null) {
cryptoMetadataEntity.setBackupVersion(this.$keyBackupVersion);
}
}
}
| true |
e8e86651869a8a1870dcb80b9f6e1b6bb3887178 | Java | juank9225/backend-solution-main | /src/main/java/co/com/sofka/questions/usecasebusiness/ModifyAnswerUseCase.java | UTF-8 | 1,549 | 2.1875 | 2 | [] | no_license | package co.com.sofka.questions.usecasebusiness;
import co.com.sofka.questions.mapper.AnswerModificadaMapper;
import co.com.sofka.questions.model.AnswerDTO;
import co.com.sofka.questions.reposioties.AnswerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.util.function.Function;
@Service
public class ModifyAnswerUseCase /*implements Function<AnswerDTO, Mono<AnswerDTO>>*/ {
private final AnswerRepository answerRepository;
private final AnswerModificadaMapper answerModificadaMapper;
@Autowired
public ModifyAnswerUseCase(AnswerRepository answerRepository, AnswerModificadaMapper answerModificadaMapper) {
this.answerRepository = answerRepository;
this.answerModificadaMapper = answerModificadaMapper;
}
// @Override
public Mono<AnswerDTO> apply(AnswerDTO answerDTO) {
return answerRepository.findByIdAndUserId(answerDTO.getId(),answerDTO.getUserId())
.flatMap(
answer -> {
answer.setAnswer(answerDTO.getAnswer());
answer.setModificada(true);
answer.setVecesModificada(answer.getVecesModificada() + 1);
return answerRepository.save(answer);
}
).map(answerModificadaMapper.answerToAnswerDTOModificada())
.switchIfEmpty(Mono.error(new IllegalAccessError()));
}
} | true |
1d07c454f6d4bf4c12f4bdfd0723d46854654d08 | Java | paulken12/iGrave | /app/src/main/java/com/secure/paulken/igrave/DBHelper/OwnerProvider.java | UTF-8 | 1,297 | 2.671875 | 3 | [] | no_license | package com.secure.paulken.igrave.DBHelper;
import com.secure.paulken.igrave.Model.OwnerItems;
import java.util.ArrayList;
import java.util.List;
public class OwnerProvider {
private static List<OwnerItems> data = new ArrayList<>();
public static List<OwnerItems> getData() {
return data;
}
static {
data.add(new OwnerItems("Princess"," Mapanao"," Marquez","","093828391"));
data.add(new OwnerItems("Magdalena"," Tores"," Danao","","093828391"));
data.add(new OwnerItems("Jonathan"," Anes"," Spera","","093828391"));
data.add(new OwnerItems("France"," Reyes"," Delos Reyes","","093828391"));
data.add(new OwnerItems("Christian"," Matias"," Alvarado","","093828391"));
data.add(new OwnerItems("Jasmine"," Macauras"," Cruz","","093828391"));
data.add(new OwnerItems("Johnny"," Cabay"," Areliano","","093828391"));
data.add(new OwnerItems("Josephine"," Rimano"," Quinto","","093828391"));
data.add(new OwnerItems("Elena"," Almoite"," Guia","","093828391"));
data.add(new OwnerItems("Marie"," Baging"," Navaroo","","093828391"));
data.add(new OwnerItems("Daniel"," Anzo"," Rillera","","093828391"));
data.add(new OwnerItems("Joseph"," Orodio"," Matilde","","093828391"));
}
} | true |
6f224594b5b9578109267879391df444e0fb465d | Java | swaraliGujrathi/JAVA_Assignment | /Assignment2/Circle.java | UTF-8 | 585 | 3.40625 | 3 | [] | no_license | public class Circle extends Shape implements Calculatable {
private int radius;
public Circle(){
super("Circle");
this.radius = 50;
}
public Circle(int radius){
super("Circle");
this.radius = radius;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
// TODO Auto-generated method stub
return (3.14*radius*radius);
}
@Override
public double perimeter() {
// TODO Auto-generated method stub
return 0;
}
}
| true |
577b64a281bd7f9ec8be71e461771a1b5d0a92a7 | Java | mlc0202/j2ee_v2 | /spring_jdbc/src/main/java/spring_jdbc/dao/impl/StudentDAOImpl.java | UTF-8 | 3,259 | 2.875 | 3 | [] | no_license | package spring_jdbc.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import spring_jdbc.dao.StudentDAO;
import spring_jdbc.entity.Student;
/**
* 2014年5月19日 09:44:34 通过注解提供Spring自动依赖注入,因此需要@Component
*/
@Component
public class StudentDAOImpl implements StudentDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public void insert(Student student) throws SQLException {
// jdbcTemplate.update("insert into student(id,name,age) values(?,?,?)",
// student.getId(), student.getName(), student.getAge());
// 最后3个参数这样也行:new Object[] { student.getId(), student.getName(),
// student.getAge() });
// jdbcTemplate不支持save(Object obj)这样的类似hibernate的ORM方法
// jdbcTemplate也支持name参数,这样就不用维护参数的顺序了
Map<String, Object> params = new HashMap<String, Object>();
params.put("id", student.getId());
params.put("name", student.getName());
params.put("age", student.getAge());
namedParameterJdbcTemplate.update(
"insert into student(id,name,age) values(:id,:name,:age)",
params);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Student getById(long id) throws SQLException {
Student student = (Student) jdbcTemplate.queryForObject(
"select * from student where id=?", new BeanPropertyRowMapper(
Student.class), id);
return student;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Student> getByName(String name) throws SQLException {
List<Student> list = (List<Student>) jdbcTemplate.query(
"select * from student where name=?",
new BeanPropertyRowMapper(Student.class), name);
return list;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Student> getAll() throws SQLException {
List<Student> list = jdbcTemplate.query("select * from student",
/* 这里可以用BeanPropertyRowMapper,也可以自己实现 */
new RowMapper() {
public Object mapRow(ResultSet rs, int index) throws SQLException {
Student student = new Student();
student.setId(rs.getLong("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
});
return list;
}
/**
* 这里使用@Transactional注解,使得这个方法的执行是原子性的,会自动安排好事务
*/
@Transactional
public void insertAtomicity(List<Student> students) throws SQLException {
if(students == null || students.isEmpty()) {
return;
}
for(Student student : students) {
jdbcTemplate.update("insert into student(id,name,age) values(?,?,?)",
student.getId(), student.getName(), student.getAge());
}
}
}
| true |
e360e6f42998c38fa58972426551f68209bfc2de | Java | wangyue-whaty/mpen-test | /src/main/java/com/mpen/api/domain/DdbUserPraiseRelationship.java | UTF-8 | 1,002 | 2.0625 | 2 | [] | no_license | package com.mpen.api.domain;
import java.util.Date;
/**
* 点赞与被点赞关系
* 涉及:教师端以及app2.0点赞相关
*
*/
public class DdbUserPraiseRelationship {
private String id;
// 点赞者
private String praiseLoginId;
// 被点赞者
private String byPraiseLoginId;
private Date createTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPraiseLoginId() {
return praiseLoginId;
}
public void setPraiseLoginId(String praiseLoginId) {
this.praiseLoginId = praiseLoginId;
}
public String getByPraiseLoginId() {
return byPraiseLoginId;
}
public void setByPraiseLoginId(String byPraiseLoginId) {
this.byPraiseLoginId = byPraiseLoginId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| true |
9ac5f8d80b469e7d705096f49070cf55986ffe04 | Java | hooke72/CityChat | /app/src/main/java/com/hooke/citychat/DatabaseUtil.java | UTF-8 | 421 | 2.09375 | 2 | [] | no_license | package com.hooke.citychat;
import com.google.firebase.database.FirebaseDatabase;
/**
* Just make firebase cashed
*/
public class DatabaseUtil {
private static FirebaseDatabase mDatabase;
public static void setPersistenceEnabled() {
if (mDatabase == null) {
mDatabase = FirebaseDatabase.getInstance();
mDatabase.setPersistenceEnabled(true);
}
}
}
| true |
e47e3e6931c6b59b9d8bf73c21b4a0ae6c2c2e7c | Java | AkhileshCovetus13/Access4MiiAndroid | /app/src/main/java/ABS_GET_SET/SideMenu.java | UTF-8 | 560 | 2.0625 | 2 | [] | no_license | package ABS_GET_SET;
/**
* Created by admin1 on 15/3/18.
*/
public class SideMenu {
Integer mSideMenuIconActive;
String mSideMenuTitle;
public Integer getmSideMenuIconActive() {
return mSideMenuIconActive;
}
public void setmSideMenuIconActive(Integer mSideMenuIconActive) {
this.mSideMenuIconActive = mSideMenuIconActive;
}
public String getmSideMenuTitle() {
return mSideMenuTitle;
}
public void setmSideMenuTitle(String mSideMenuTitle) {
this.mSideMenuTitle = mSideMenuTitle;
}
}
| true |
6db23369748c24463f6ef363c550ab7fdc36e090 | Java | yhuihu/Java-Study | /leetcode/src/main/java/com/study/leetcode/Question9.java | UTF-8 | 1,533 | 3.6875 | 4 | [
"Apache-2.0"
] | permissive | package com.study.leetcode;
/**
* @author Tiger
* @date 2020-06-09
* @see com.study.leetcode
**/
public class Question9 {
/**
* 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
* <p>
* 示例 1:
* <p>
* 输入: 121
* 输出: true
* 示例 2:
* <p>
* 输入: -121
* 输出: false
* 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
* 示例 3:
* <p>
* 输入: 10
* 输出: false
* 解释: 从右向左读, 为 01 。因此它不是一个回文数。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/palindrome-number
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
String str = String.valueOf(x);
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - i - 1)) {
return false;
}
}
return true;
}
public boolean isPalindrome1(int x) {
if (x < 0) {
return false;
}
int target = x;
int ans = 0;
while (target > 0) {
ans = ans * 10 + target % 10;
target /= 10;
}
return ans == x;
}
}
| true |
4b959188a281e9877fcf8bebbf4ed57dd14c8de5 | Java | chenlanlan/leetcodeJava | /KthSmallestElementInABST.java | UTF-8 | 1,117 | 3.578125 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
//inorder recursive
public int kthSmallest(TreeNode root, int k) {
ArrayList<Integer> list = new ArrayList<Integer>();
inorderSearch(root, list, k);
return list.get(k - 1);
}
public void inorderSearch(TreeNode node, ArrayList<Integer> list, int k) {
if (list.size() >= k) return;
if (node.left != null) inorderSearch(node.left, list, k);
list.add(node.val);
if (node.right != null) inorderSearch(node.right, list, k);
}
//binary search
public int kthSmallest(TreeNode root, int k) {
int count = countNodes(root.left);
if (k <= count) return kthSmallest(root.left, k);
else if (k > count + 1) return kthSmallest(root.right, k - count - 1);
return root.val;
}
public int countNodes(TreeNode node) {
if (node == null) return 0;
return 1 + countNodes(node.left) + countNodes(node.right);
}
} | true |
de81967434ef32f2e7f1430850b79328a8153433 | Java | kubavation/Interest-matcher | /TagService/src/main/java/io/duryskuba/interestmatcher/TagService/utils/CollectionUtils.java | UTF-8 | 646 | 2.734375 | 3 | [] | no_license | package io.duryskuba.interestmatcher.TagService.utils;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectionUtils {
@SafeVarargs
public static <T> HashSet<T> of(T... items) {
return Stream.of(items)
.collect(Collectors.toCollection(HashSet::new));
}
@SafeVarargs
public static <T> HashSet<T> merge(HashSet<T>... sets) {
HashSet<T> result = new HashSet<>();
for(HashSet<T> set : sets) {
result.addAll(set);
}
System.out.println(result);
return result;
}
} | true |
93f24022eb10a4a082070d272df95a27e6547dd8 | Java | alexmuratidi/UrChallenge | /app/src/main/java/com/hotstavropol/urchallenge1/VK.java | UTF-8 | 3,393 | 1.9375 | 2 | [] | no_license | package com.hotstavropol.urchallenge1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.Toast;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKCallback;
import com.vk.sdk.VKScope;
import com.vk.sdk.VKSdk;
import com.vk.sdk.api.VKError;
/**
* Created by maximgran on 13.01.2018.
*/
public class VK extends AppCompatActivity {
private String[] scope = new String[]{VKScope.MESSAGES, VKScope.FRIENDS, VKScope.WALL, VKScope.PHOTOS};
private ListView listView;
public String id;
public static VKAccessToken vkAccessToken;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.vkapi);
VKSdk.login(this, scope);
}
@Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
if (!VKSdk.onActivityResult(requestCode, resultCode, data, new VKCallback<VKAccessToken>() {
@Override
public void onResult(VKAccessToken res) {
vkAccessToken = res;
DataBase.vk_permission = true;
Toast.makeText(getApplicationContext(), "Авторизация прошла успешно", Toast.LENGTH_LONG).show();
Update.update();
finish();
//Intent intent = new Intent(VK.this, MenuActivity.class);
//startActivity(intent);
}
@Override
public void onError(VKError error) {
Toast.makeText(getApplicationContext(), "Ошибка авторизации!", Toast.LENGTH_LONG).show();
finish();
//Intent intent = new Intent(VK.this, MenuActivity.class);
//startActivity(intent);
}
})) {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
/*VKRequest vkRequest = VKApi.users().get(VKParameters.from(VKApiConst.USER_IDS, id));
vkRequest.executeWithListener(new VKRequest.VKRequestListener() {
@SuppressLint("SetTextI18n")
@Override
public void onComplete(VKResponse response) {
final VKApiUser vkApiUser = ((VKList<VKApiUser>) response.parsedModel).get(0);
new Thread() {
public void run() {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
final TextView textView = findViewById(R.id.profile_name);
textView.setText(vkApiUser.first_name + " " + vkApiUser.last_name);
Log.d("NAME", textView.getText().toString());
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
*/ | true |
0e048512845ba7b55867ab775858ed9098fb65cb | Java | kirsong/KirChat | /KirChatServer/src/main/java/com/chat/mobile/controller/ChattingController.java | UTF-8 | 3,385 | 2.21875 | 2 | [] | no_license | package com.chat.mobile.controller;
import com.chat.mobile.Define;
import com.chat.mobile.model.*;
import com.chat.mobile.service.ChattingService;
import com.chat.mobile.service.UserService;
import com.chat.mobile.util.FcmUtil;
import com.chat.mobile.util.Util;
import com.chat.mobile.vo.ChattingVO;
import com.chat.mobile.vo.PushVO;
import com.chat.mobile.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.testng.annotations.IFactoryAnnotation;
import java.util.List;
@RestController
@RequestMapping("/mobile")
public class ChattingController {
@Autowired
public ChattingService chattingService;
@Autowired
public UserService userService;
private FcmUtil fcmUtil;
//채팅 보내기
@RequestMapping("/submitChatting")
public ResultCommon submitChatting(@RequestBody ChattingVO chattingVO){
if (fcmUtil==null){
fcmUtil=new FcmUtil();
}
ResultCommon result=new ResultCommon();
try{
if (chattingVO!=null){
//상대방 아이디의 정보를 가져온다
UserVO userVO=userService.userSelect(chattingVO.getReceiveUserId());
//상대방 아이디의 토큰을 가져온다
PushVO pushVO=userService.pushSearch(chattingVO.getReceiveUserId());
//채팅 푸시에 필요한 데이터
FcmRequest fcmRequest=new FcmRequest();
fcmRequest.setTo(pushVO.getPushToken());
FcmData fcmData=new FcmData();
fcmData.setName(userVO.getName());
fcmData.setDate(chattingVO.getSubmitDate());
fcmData.setContent(chattingVO.getContent());
fcmRequest.setData(fcmData);
FcmResult fcmResult=fcmUtil.sendFcmPush(fcmRequest);
//채팅 저장
if (chattingService.submitChatting(chattingVO)>0){
result.setCode(Define.SUCCESS_CODE);
//푸시 보내기 성공
if (fcmResult.getSuccess()>0){
}
//푸시 보내기 실패
else{
result.setCode(Define.PUSH_FAILD_CODE);
}
return result;
}
}
}catch (Exception e){
}
result.setCode(Define.FAILD_CODE);
return result;
}
/**
* 채팅 히스토리 가져오기
* @param roomId
* @param lastStartIndex
* @param itemSize
* @return
*/
@RequestMapping("/chattingHistory ")
public ResultInDataModel chattingHistory(@RequestParam("roomId")String roomId,@RequestParam("lastStartIndex")String lastStartIndex,@RequestParam("itemSize")String itemSize){
ResultInDataModel result=new ResultInDataModel();
List<ChattingVO> chattingVOList= chattingService.selectChatting(roomId,Integer.valueOf(lastStartIndex),Integer.valueOf(itemSize));
result.setResult(chattingVOList);
return result;
}
}
| true |
d809fc2ad0e4f0c7cf47f5f45c558945b52ffb48 | Java | teasingmonkey/PollEvApplication | /Mileston2/client/voter/SingleVote.java | UTF-8 | 1,796 | 2.859375 | 3 | [] | no_license | package voter;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.junit.Test;
public class SingleVote {
private int votePort = 7778;
@Test
public void test() {
String pollId = "45550";
for(int i=0; i <200; i++)
{
vote(Integer.toString(i), pollId, 1);
try {
Thread.sleep(45);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=200; i <250; i++)
{
vote(Integer.toString(i), pollId, 2);
try {
Thread.sleep(45);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void vote(String id, String pollId, long selection)
{
String newId = "";
if(id != null)
{
newId += id + " " + pollId;
}
else
{
newId = pollId;
}
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
} catch (SocketException e1) {
e1.printStackTrace();
}
try {
sendSocket.send(generateVotePacket(newId, selection));
} catch (IOException e1) {
e1.printStackTrace();
}
sendSocket.close();
}
private DatagramPacket generateVotePacket(String pollId, long selection)
{
String message = pollId + " " + Long.toString(selection);
DatagramPacket sendPacket = null;
try {
sendPacket = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getLocalHost() , this.votePort);
} catch (UnknownHostException e2) {
e2.printStackTrace();
}
return sendPacket;
}
}
| true |
db90dc357b06146342d9bc9f2f5515491d81cb01 | Java | ohmkunz/Proj | /src/fields/RentDvd.java | UTF-8 | 190 | 2.21875 | 2 | [] | no_license | package fields;
public interface RentDvd {
public boolean returnDVD(String name, int stock)throws MyException;
public double rentDVD(String name,int day,int stock) throws MyException ;
}
| true |
0d8495b738e42f17f7da251c72674752c5fcbacb | Java | zhangyanrui/car4s | /app/src/main/java/cn/car4s/app/bean/WebviewBean.java | UTF-8 | 415 | 1.984375 | 2 | [
"Apache-2.0"
] | permissive | package cn.car4s.app.bean;
/**
* Description:
* Author: Alex
* Email: xuebo.chang@langtaojin.com
* Time: 2015/4/22.
*/
public class WebviewBean extends BaseBean {
public String webTitle;
public String loadUrl;
public boolean isShare;
public WebviewBean(String webTitle, String loadUrl, boolean isShare) {
this.webTitle = webTitle;
this.loadUrl = loadUrl;
this.isShare = isShare;
}
}
| true |
3cca74e99e003126b231bdb7bfcb07ee2fcfbe71 | Java | q01201203/Solution | /src/Solution8.java | UTF-8 | 913 | 3.578125 | 4 | [] | no_license | /**
* Created by Administrator on 2018/3/30.
* 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
*/
public class Solution8 {
int count = 0; //跳法
public int JumpFloor(int target) {
if (target == 1){
return 1;
}
if (target == 2){
return 2;
}
int f = 1, g = 2;
while (target-- > 2) {
g += f;
f = g - f;
}
return g;
}
/*public int JumpFloor(int target) {
canJump(target);
return count;
}*/
void canJump(int start){
if (start - 2 == 0){
count++;
}else if (start - 2>0){
canJump(start - 2);
}
if (start - 1 == 0){
count++;
}else if (start - 1>0){
canJump(start - 1);
}
}
}
| true |
4707735505f04e68efe46d433ad27c3c2e0c199b | Java | doGe-personal/sign_up_svr | /src/main/java/com/el/util/WebResultUtils.java | UTF-8 | 2,294 | 2.46875 | 2 | [] | no_license | package com.el.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* web 返回值整理
* @author Danfeng
* @since 2018/6/29
*/
public class WebResultUtils {
private static final Logger log = LoggerFactory.getLogger(WebResultUtils.class);
private static final String OP_RESULT_OK = "OK";
private static final String OP_RESULT_NG = "NG";
private static ResponseEntity.BodyBuilder opBuilder(OpResult result) {
return ResponseEntity.status(HttpStatus.OK).header("el-result-code", result == null ? OP_RESULT_OK : OP_RESULT_NG);
}
private static ResponseEntity.BodyBuilder okBuilder() {
return ResponseEntity.status(HttpStatus.OK).header("el-result-code", OP_RESULT_OK);
}
public static ResponseEntity.BodyBuilder ngBuilder() {
return ResponseEntity.status(HttpStatus.OK).header("el-result-code", OP_RESULT_NG);
}
private static ResponseEntity.BodyBuilder badReqBuilder(OpResult result) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).header("el-result-code", result == null ? OP_RESULT_NG : result.getCode());
}
public static ResponseEntity toResponseEntity(OpResult result) {
return opBuilder(result).build();
}
public static ResponseEntity toResponseEntity() {
return okBuilder().build();
}
/**
* 语义有误,当前请求无法被服务器理解 | 请求参数有误
* @param result 自定义code 与 前端code 一一对应
* @return ResponseEntity status 404
*/
public static ResponseEntity tobadReqEntity(OpResult result) {
return badReqBuilder(result).build();
}
/**
* 前端错误码对接
* @param result
* @return
*/
public static ResponseEntity toNgReqEntity(OpResult result) {
return opBuilder(result).build();
}
/**
* 校验错误
* @param body
* @return
*/
public static ResponseEntity toNgValidateEntity(Object body) {
return ngBuilder().body(body);
}
/**
* 前端错误码对接
* @return
*/
public static ResponseEntity toOkReqEntity(Object body) {
return okBuilder().body(body);
}
}
| true |
df14b5db9913e14b63ba7f9919be442d93e47cef | Java | Anunindale/DGD | /Office/EMCClientSys/.svn/pristine/df/df14b5db9913e14b63ba7f9919be442d93e47cef.svn-base | UTF-8 | 569 | 2.234375 | 2 | [] | no_license | package emc.menus.hr.menuitems.display;
import emc.enums.enumMenuItems;
import emc.forms.hr.display.absscarcity.HRAbsScarcityForm;
import emc.framework.EMCMenuItem;
/**
*
* @author claudette
*/
public class HRAbsScarcityMI extends EMCMenuItem {
/** Creates a new instance of HRAbsScarcityMI. */
public HRAbsScarcityMI() {
this.setClassPath(HRAbsScarcityForm.class.getName());
this.setMenuItemType(enumMenuItems.DISPLAY);
this.setMenuItemName("Abs Scarcity");
this.setToolTipText("View and Edit Abs Scarcity data");
}
} | true |
96a13617fc11a3f093f89a73e4fb8244bcb1a76a | Java | coolutkarshraj/Choozo_ecommerce | /app/src/main/java/com/io/choozo/model/dataModel/todayDealsModel/Store.java | UTF-8 | 3,617 | 1.773438 | 2 | [
"Apache-2.0"
] | permissive | package com.io.choozo.model.dataModel.todayDealsModel;
import com.google.gson.annotations.SerializedName;
public class Store{
@SerializedName("description")
private String description;
@SerializedName("isOtpVerify")
private Object isOtpVerify;
@SerializedName("isActive")
private boolean isActive;
@SerializedName("addressId")
private int addressId;
@SerializedName("arabicName")
private String arabicName;
@SerializedName("availableForOnlineSale")
private boolean availableForOnlineSale;
@SerializedName("offerPercentage")
private String offerPercentage;
@SerializedName("lastLogged")
private Object lastLogged;
@SerializedName("phoneCode")
private String phoneCode;
@SerializedName("addedByUserId")
private int addedByUserId;
@SerializedName("arabicDescription")
private String arabicDescription;
@SerializedName("isApproved")
private boolean isApproved;
@SerializedName("availableForDelivery")
private boolean availableForDelivery;
@SerializedName("email")
private String email;
@SerializedName("offerName")
private String offerName;
@SerializedName("avatarPath")
private String avatarPath;
@SerializedName("otp")
private Object otp;
@SerializedName("deliveryPrice")
private String deliveryPrice;
@SerializedName("storeId")
private int storeId;
@SerializedName("avatarName")
private String avatarName;
@SerializedName("registrationToken")
private String registrationToken;
@SerializedName("createdDate")
private String createdDate;
@SerializedName("phone")
private String phone;
@SerializedName("registrationNumber")
private String registrationNumber;
@SerializedName("name")
private String name;
@SerializedName("offerExpiryDate")
private String offerExpiryDate;
@SerializedName("isPremium")
private boolean isPremium;
@SerializedName("categoryId")
private int categoryId;
@SerializedName("addedById")
private int addedById;
public String getDescription(){
return description;
}
public Object getIsOtpVerify(){
return isOtpVerify;
}
public boolean isIsActive(){
return isActive;
}
public int getAddressId(){
return addressId;
}
public String getArabicName(){
return arabicName;
}
public boolean isAvailableForOnlineSale(){
return availableForOnlineSale;
}
public String getOfferPercentage(){
return offerPercentage;
}
public Object getLastLogged(){
return lastLogged;
}
public String getPhoneCode(){
return phoneCode;
}
public int getAddedByUserId(){
return addedByUserId;
}
public String getArabicDescription(){
return arabicDescription;
}
public boolean isIsApproved(){
return isApproved;
}
public boolean isAvailableForDelivery(){
return availableForDelivery;
}
public String getEmail(){
return email;
}
public String getOfferName(){
return offerName;
}
public String getAvatarPath(){
return avatarPath;
}
public Object getOtp(){
return otp;
}
public String getDeliveryPrice(){
return deliveryPrice;
}
public int getStoreId(){
return storeId;
}
public String getAvatarName(){
return avatarName;
}
public String getRegistrationToken(){
return registrationToken;
}
public String getCreatedDate(){
return createdDate;
}
public String getPhone(){
return phone;
}
public String getRegistrationNumber(){
return registrationNumber;
}
public String getName(){
return name;
}
public String getOfferExpiryDate(){
return offerExpiryDate;
}
public boolean isIsPremium(){
return isPremium;
}
public int getCategoryId(){
return categoryId;
}
public int getAddedById(){
return addedById;
}
} | true |
386656ecc3587f73582b97a0e4a371f425f0d748 | Java | haoranleo/Online-shopping-store | /app/models/productStatus/OrderedStatus.java | UTF-8 | 414 | 2.265625 | 2 | [
"CC0-1.0"
] | permissive | package models.productStatus;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
//@Entity
//public class OrderedStatus extends ProductStatus{
// public String getStatus(){
// return "Ordered";
// }
//
// /**
// * Generic query helper for entity Product with id Long
// */
// public static Finder<String,OrderedStatus> find = new Finder<>(OrderedStatus.class);
//}
| true |
c747a37ba1cbb97b2e295ab645398e5cd558c197 | Java | jmalue/virtual-pet-2 | /src/VirtualPet.java | UTF-8 | 1,279 | 2.65625 | 3 | [] | no_license | //cookie cutter template (blueprint)
public class VirtualPet {
private int thirst = 0;
private int hunger = 0;
private int boredom=0;
private int appearance = 0;
private int health = 0;
private int energy = 0;
private String petsName = "";
private String petDescription = "";
public VirtualPet (int thirst, int hunger, int bordom, int apperance, int health, int enegry, String petsName) {
this.thirst = thirst;
this.hunger = hunger;
}
public VirtualPet(String petsName, String petDescription) {
// TODO Auto-generated constructor stub
}
public VirtualPet(int thirst, int hunger, int boredom) {//math random constructor
this.thirst = thirst++;
this.hunger = hunger++;
this.boredom = boredom++;
}
public int getHunger() {
// TODO Auto-generated method stub
return 0;
}
public int getBoredom() {
// TODO Auto-generated method stub
return 0;
}
public int getEnergy() {
// TODO Auto-generated method stub
return 0;
}
public void play() {
// TODO Auto-generated method stub
}
public void eat() {
// TODO Auto-generated method stub
}
public int getThirst() {
// TODO Auto-generated method stub
return 0;
}
public int getBoredome() {
// TODO Auto-generated method stub
return 0;
}
}
| true |
294f39040d001567b7d7d02387ee2f6398cf20c7 | Java | OnlyCastiel/BaseUtil | /src/main/java/com/train/bianchengzhimei/CFlapjackSorting2.java | UTF-8 | 4,788 | 3.671875 | 4 | [] | no_license | package com.train.bianchengzhimei;
/**
* 有一些服务员会把上面的一摞饼子放在自己头顶上(放心,他们都戴着洁白的帽子),
* 然后再处理其他饼子,在这个条件下,我们的算法能有什么改进?
*
*一堆烙饼分成两堆,分别有序即可,无需合并两个饼堆
* 可以分成两段来进行翻转;
* 复杂问题分解:对于n块饼,分的方案共有 n-1钟,假设头顶上的为K,盘子里的为n-k
* 对两摞饼分别进行翻转(两堆饼各自的最少翻转次数),找到翻转次数之和最小的
*
*
* 2.事实上,饭店的师傅经常把烙饼烤得一面非常焦,另一面则是金黄色。这时,服务员还得考虑让烙饼大小有序,并且金黄色的一面都要向上。这样要怎么翻呢?
*/
public class CFlapjackSorting2 {
private int[] m_p_Array;//原饼堆,记录原饼堆是为了记录饼的翻饼顺序
private int maxSort; //翻饼次数上界限,动态记录最小次数
private int[] sortArrayStep; //当前翻饼步骤,长度最多为2*n
private int[] sortArrayStepFinal; //翻饼最终步骤
private int[] sortArrayResult; //当前翻饼结果
private void init(int[] p_Array){
maxSort = p_Array.length * 2 - 2;
sortArrayStep = new int[maxSort];
sortArrayStepFinal = new int[maxSort];
sortArrayResult = new int[p_Array.length];
for(int i=0;i<p_Array.length; i++){
m_p_Array[i] = p_Array[i];//缓存原始饼堆,后续输出时,可以根据此来输出每一次的翻转过程
sortArrayResult[i] = p_Array[i];//初始化操作饼堆
}
}
/**
* 核心递归方法
*
* 出口:已经有序:
* 判断排序次数是否超过maxSort,如果没超过则替换当前翻饼序列
*
* 逻辑处理:
* 在每一个位置 n ,都进行反转,然后递归每一个位置 n;
* 实现树的深度优先搜索,返回后,反转回来,尝试另外一个分支;
*
*
* @param step 当前递归层级
*/
private void reserch(int step){
if(isSorted(sortArrayResult)){
//判断排序次数是否超过maxSort,如果没超过则替换当前翻饼序列
//sortArray 翻饼序列已经保存在这个数组中
if(step < maxSort){
for(int i=0;i<sortArrayStep.length;i++){
sortArrayStepFinal[i] = sortArrayStep[i];
}
maxSort = step;
}
return;
}
int remainTimes = lastMinSortNum(sortArrayResult);
if(step + remainTimes >= maxSort){
return;
}
//从0-1开始,对每一摞子饼进行反转
for(int i = 1; i<m_p_Array.length; i++){
if(step > 0 && i == sortArrayStep[step-1]){
continue;//优化思路,连续两次翻转不可翻转同一段区间,如果翻转区间相同则为无效反转,即相邻的翻转操作,必定为翻转不同的区间
}
reverse(i);
sortArrayStep[step] = i;
reserch(step + 1);//递归第二层
sortArrayStep[step] = 0;
reverse(i);//反转回来,再下一次循环搜索另外一颗子树
}
}
//反转饼堆
private void reverse(int n){
int temp;
for(int i = 0,j=n; i<j ; i++,j--){
temp = sortArrayResult[j];
sortArrayResult[j] = sortArrayResult[i];
sortArrayResult[i] = temp;
}
}
//堆当前至少还需要翻多少次,为当前相邻饼中,需要分开的间隔数
private int lastMinSortNum(int[] sortArrayResult){
int count = 0;
for(int i =0;i<sortArrayResult.length-1;i++){
int num = sortArrayResult[i] - sortArrayResult[i + 1];
if(num != 1 && num != -1){
count ++;
}
}
return count;
}
//判断是否已经有序
private boolean isSorted(int[] sortArrayResult){
for(int i=0;i<sortArrayResult.length - 1;i++){
if(sortArrayResult[i] > sortArrayResult[i+1]){
return false;
}
}
return true;
}
//输出翻饼步骤
private void output(){
for(int i=0;i<maxSort;i++ ){
System.out.println(sortArrayStepFinal[i]);
}
}
//运行主方法
private void run(int[] p_Array){
init(p_Array);
reserch(0);
}
public static void main(String[] args) {
CFlapjackSorting2 sorting = new CFlapjackSorting2();
int[] pCakeArray = new int[]{3,2,1,5,4};
sorting.run(pCakeArray);
sorting.output();
}
}
| true |
7139f57d4cab3465df34b130ec538038b90d8a11 | Java | JerryLi912/CMSC204Projects | /Project4/CourseDBManager.java | UTF-8 | 4,911 | 3.28125 | 3 | [] | no_license | import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
/**
* This is the Data Manager class.
* This class has add(), get(int crn), readFile(), and showAll() methods
* @author jerry
*
*/
public class CourseDBManager implements CourseDBManagerInterface {
//set hashTable size to 10
CourseDBStructure structure = new CourseDBStructure(20);
CourseDBElement element;
/**
* This method adds the Course Information by user input in the GUI
*/
@Override
public void add(String id, int crn, int credits, String roomNum, String instructor) {
element = new CourseDBElement(id, crn, credits, roomNum, instructor);
String stringCRN = Integer.toString(element.getCRN());
int index = structure.getHashIndex(stringCRN);
ListIterator<CourseDBElement> iterator = structure.hashTable[index].listIterator();
//comparing hashCode to see if the object already existed in the list
//if the object already existed, don't add it
while(iterator.hasNext()) {
if(iterator.next().compareTo(element) == 0) {
return;
}
}
structure.hashTable[index].addLast(element);
return;
}
/**
* This method gets the Course CRN in type integer
*/
@Override
public CourseDBElement get(int crn) {
String stringCRN = Integer.toString(crn);
int hashedKey = structure.getHashIndex(stringCRN);
ListIterator<CourseDBElement> iterator = (ListIterator<CourseDBElement>) structure.hashTable[hashedKey].listIterator();
while(iterator.hasNext()) {
element = iterator.next();
if(element.compareTo(element) == 0) {
return element;
}
}
return null;
}
/**
* This method reads file that contains course information
* and adds them to hashTable
*/
@Override
public void readFile(File input) throws FileNotFoundException {
Scanner inputFile = new Scanner(input);
int t = 0;
int count_whiteSpaces = 0;
while (inputFile.hasNext()) {
String temp;
String courseID = null;
int course_CRN = 0;
int course_credits = 0;
String course_room = null;
String course_instructor = null;
String course_content = inputFile.nextLine();
temp = course_content;
System.out.println(course_content);
//extract string content from the file
for(int i = 0; i < course_content.length(); i++) {
if(temp.charAt(i) == ' ') {
count_whiteSpaces++;
if(count_whiteSpaces == 1) {
courseID = temp.substring(0, i);
System.out.println("extracted courseID: " + courseID);
}
else if(count_whiteSpaces == 2) {
course_CRN = Integer.parseInt(temp.substring(i-5, i));
System.out.println("extracted courseCRN: " + course_CRN);
}
else if(count_whiteSpaces == 3) {
course_credits = Integer.parseInt(temp.substring(i-1, i));
System.out.println("extracted courseCredits: " + course_credits);
}
else if(count_whiteSpaces == 4) {
t = i;
if(temp.charAt(i-1) == 'g') {
course_room = temp.substring(i-17, i);
}
else {
course_room = temp.substring(i-5, i);
}
System.out.println("extracted room number: " + course_room);
}
if(count_whiteSpaces == 4 && temp.charAt(i+1) != ' ') {
course_instructor = temp.substring(t+1, course_content.length());
System.out.println("extracted instructor's name: " + course_instructor);
}
}
}//end for loop
add(courseID, course_CRN, course_credits, course_room, course_instructor);
count_whiteSpaces = 0;
}//end while loop
inputFile.close();
}
/**
* This method displays every thing added to the hashTable in ArrayList
*/
@Override
public ArrayList<String> showAll() {
ArrayList<String> list = new ArrayList<>();
String course;
for(int i = 0; i < structure.hashTable.length; i++) {
ListIterator<CourseDBElement> iterator = structure.hashTable[i].listIterator();
while(iterator.hasNext()) {
course = iterator.next().toString();
list.add("\n" + course);
}
}
return list;
}
//test for class
public static void main(String[] agrs) {
File input = new File("courses.txt");
CourseDBManager manager = new CourseDBManager();
manager.add("M1201", 39999, 4, "R33", "weweG");
manager.add("M1113", 40000, 4, "R13", "wsdG");
manager.add("M1231", 50000, 4, "R35", "wgwfG");
manager.add("M4532", 39999, 4, "R89", "wfG");
System.out.println(manager.get(39999));
System.out.println(manager.get(40000));
System.out.println(manager.get(50000));
try {
manager.readFile(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(manager.showAll());
}
}
| true |
be0161ed8ad6c0a4ecf141b92095b62a3597be6d | Java | samhay2u/EMP | /src/emp/pojo/Employee.java | UTF-8 | 2,337 | 2.890625 | 3 | [
"MIT"
] | permissive | package emp.pojo;
import java.io.Serializable;
public class Employee implements Serializable {
/**
* Serialization Id FOR PORTABILITY Java provides a mechanism, called object
* serialization where an object can be represented as a sequence of bytes that
* includes the object's data as well as information about the object's type and
* the types of data stored in the object.
*/
private static final long serialVersionUID = 1L;
String emp_No, dob, f_Name, l_Name, gender, hire_Date, salary;
public Employee(String emp_No, String dob, String f_Name, String l_Name, String gender, String hire_Date,
String salary) {
super();
this.emp_No = emp_No;
this.dob = dob;
this.f_Name = f_Name;
this.l_Name = l_Name;
this.gender = gender;
this.hire_Date = hire_Date;
this.salary = salary;
}
public String getEmp_No() {
return emp_No;
}
public void setEmp_No(String emp_No) {
this.emp_No = emp_No;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getF_Name() {
return f_Name;
}
public void setF_Name(String f_Name) {
this.f_Name = f_Name;
}
public String getL_Name() {
return l_Name;
}
public void setL_Name(String l_Name) {
this.l_Name = l_Name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHire_Date() {
return hire_Date;
}
public void setHire_Date(String hire_Date) {
this.hire_Date = hire_Date;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [emp_No=" + emp_No + ", dob=" + dob + ", f_Name=" + f_Name + ", l_Name=" + l_Name + ", gender="
+ gender + ", hire_Date=" + hire_Date + ", salary=" + salary + "]";
}
// RC --source
// lc ---Generate constructors using fields
// lc ---ok
/*
* CREATE TABLE `employees` ( `emp_no` varchar(10) NOT NULL PRIMARY KEY,
* `birth_date` DATE NOT NULL, `first_name` varchar(225) NOT NULL, `last_name`
* varchar(225) NOT NULL, `gender` char(1) DEFAULT 'U' NOT NULL, `hire_date`
* DATETIME DEFAULT NOW() NOT NULL )
*
*/
}
| true |
a8fef49b4a2c54a62e99db69c0aea9f3ec84a110 | Java | YeroMing/GitPractise | /xokhttp/src/main/java/com/loction/xokhttp/response/GsonResponseHandler.java | UTF-8 | 2,748 | 2.359375 | 2 | [] | no_license | package com.loction.xokhttp.response;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loction.xokhttp.BaseResponse;
import com.loction.xokhttp.XOkhttpClient;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Created by localadmin on 2017/11/13.
*
* update 2018/8/28
* 适配WanAndroid体系结构
* 这里填的泛型
* 为wanAndroid返回数据data内容所生成的实体类
* errCode为0是回调onSuccful方法
* 不为0时回调失败方法 onFail方法 并且返回错误码和失败原因
*
*/
public abstract class GsonResponseHandler<T> implements IResponse,ParameterizedType {
private String bodyStr;
public abstract void onSuccful(T response);
@Override
public void onSuccful(final Response response) {
final ResponseBody body = response.body();
try {
bodyStr = body.string();
} catch (IOException e) {
e.printStackTrace();
XOkhttpClient.handler.post(new Runnable() {
@Override
public void run() {
onFail(response.code(), "error read msg");
}
});
return;
} finally {
response.close();
}
final Type gsonType = this;
XOkhttpClient.handler.post(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
// onSuccful(new Responseer<T>((T) gson.fromJson(bodyStr, mType), response));
TypeToken<BaseResponse<T>> typeToken = new TypeToken<BaseResponse<T>>() {
};
BaseResponse<T> baseResponse = gson.fromJson(bodyStr, gsonType);
if(baseResponse.getErrorCode()==0){
onSuccful(baseResponse.getData());
}else{
onFail(baseResponse.getErrorCode(),baseResponse.getErrorMsg());
}
}
});
}
@Override
public void onFail(int errorCode, String errorMessage) {
}
@Override
public Type[] getActualTypeArguments() {
Class clz = this.getClass();
Type superclass = clz.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments();
}
@Override
public Type getOwnerType() {
return null;
}
@Override
public Type getRawType() {
return BaseResponse.class;
}
}
| true |
635f096a1c56e97b953af14c10b022f1e429c5d8 | Java | Andreas237/AndroidPolicyAutomation | /ExtractedJars/PACT_com.pactforcure.app/javafiles/com/itextpdf/text/pdf/parser/LocationTextExtractionStrategy$1.java | UTF-8 | 1,455 | 1.929688 | 2 | [
"MIT"
] | permissive | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.itextpdf.text.pdf.parser;
// Referenced classes of package com.itextpdf.text.pdf.parser:
// LocationTextExtractionStrategy, LineSegment, TextRenderInfo
class LocationTextExtractionStrategy$1
implements xtChunkLocationStrategy
{
public xtChunkLocation createLocation(TextRenderInfo textrenderinfo, LineSegment linesegment)
{
return ((xtChunkLocation) (new xtChunkLocationDefaultImp(linesegment.getStartPoint(), linesegment.getEndPoint(), textrenderinfo.getSingleSpaceWidth())));
// 0 0:new #17 <Class LocationTextExtractionStrategy$TextChunkLocationDefaultImp>
// 1 3:dup
// 2 4:aload_2
// 3 5:invokevirtual #23 <Method Vector LineSegment.getStartPoint()>
// 4 8:aload_2
// 5 9:invokevirtual #26 <Method Vector LineSegment.getEndPoint()>
// 6 12:aload_1
// 7 13:invokevirtual #32 <Method float TextRenderInfo.getSingleSpaceWidth()>
// 8 16:invokespecial #35 <Method void LocationTextExtractionStrategy$TextChunkLocationDefaultImp(Vector, Vector, float)>
// 9 19:areturn
}
LocationTextExtractionStrategy$1()
{
// 0 0:aload_0
// 1 1:invokespecial #12 <Method void Object()>
// 2 4:return
}
}
| true |
4517c38b3a06280a8a02e7614a5d21596e698220 | Java | f981545521/iblog-data | /src/main/java/cn/acyou/iblogdata/commons/AbstractService.java | UTF-8 | 2,092 | 2.203125 | 2 | [] | no_license | package cn.acyou.iblogdata.commons;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 基于通用MyBatis Mapper插件的Service接口的实现
*
* @author youfang
*/
@Transactional(timeout = 120, rollbackFor = Exception.class)
public abstract class AbstractService<T extends Po, PK extends Serializable> implements Service<T, PK> {
@Autowired
protected Mapper<T,PK> mapper;
protected Class<T> poClazz;
protected Logger logger;
public AbstractService() {
TypeToken<T> poType = new TypeToken<T>(getClass()) {
};
logger = LoggerFactory.getLogger(getClass().getName());
poClazz = (Class<T>) poType.getRawType();
}
@Override
public int saveSelective(T model) {
return mapper.insertSelective(model);
}
@Override
public int save(List<T> models) {
return mapper.insertList(models);
}
@Override
public int deleteByIds(String ids) {
return mapper.deleteByIds(ids);
}
@Override
public int updateByPrimaryKeySelective(T model) {
return mapper.updateByPrimaryKeySelective(model);
}
@Override
public int updateByPrimaryKey(T model) {
return mapper.updateByPrimaryKey(model);
}
@Override
public List<T> findByIds(String ids) {
return mapper.selectByIds(ids);
}
@Override
public List<T> findAll() {
return mapper.selectAll();
}
@Override
public int selectCount(T v) {
return mapper.selectCount(v);
}
@Override
public int deleteById(PK id) {
return mapper.deleteByIds(String.valueOf(id));
}
@Override
public T findById(PK id) {
return mapper.selectByPrimaryKey(String.valueOf(id));
}
}
| true |
1c0ca26b878633199eba24b083d502b56037564f | Java | VA-NI/Springboot_Microservices_Sample_Code | /src/main/java/com/census/zipcode/data/dao/ZipCodeRepository.java | UTF-8 | 2,772 | 2.578125 | 3 | [] | no_license | package com.census.zipcode.data.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ZipCodeRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
private static final String fetchZipcodesForPopulationRange = "SELECT zipcode FROM census_population WHERE total_population BETWEEN ? AND ? ";
private static final String fetchZipcodesForMedianAgeRange = "SELECT zipcode FROM census_population WHERE median_age BETWEEN ? AND ? ";
private static final String fetchZipcodesForTopMostPopulatedRegion = "SELECT zipcode FROM census_population order by total_population desc LIMIT ? " ;
private static final String fetchZipcodesForPopulationWhereFemaleAreMoreThanMale
= " SELECT zipcode "
+ " FROM census_population WHERE 1 = "
+ " CASE WHEN total_females > total_males THEN 1 "
+ " ELSE 0 "
+ " END order by total_females - total_males desc "
;
public List<Long> fetchZipCodesForPopulationWithinGivenRange(Long start, Long end) {
List<Long> zipCodes = jdbcTemplate.queryForList(fetchZipcodesForPopulationRange, new Object[] { start, end }, Long.class);
if(zipCodes == null) {
return new ArrayList<>();
}
return zipCodes;
}
public List<Long> fetchZipCodesMedianInGivenRange(Double start, Double end) {
List<Long> zipCodes = jdbcTemplate.queryForList(fetchZipcodesForMedianAgeRange, new Object[] { start, end }, Long.class);
if(zipCodes == null) {
return new ArrayList<>();
}
return zipCodes;
}
public List<Long> fetchTopMostPopulatedZipCodes(Long top ) {
List<Long> zipCodes = jdbcTemplate.queryForList(fetchZipcodesForTopMostPopulatedRegion, new Object[] { top }, Long.class);
if(zipCodes == null) {
return new ArrayList<>();
}
return zipCodes;
}
public List<Long> fetchZipCodesWithMoreFemales() {
List<Long> zipCodes = jdbcTemplate.queryForList(fetchZipcodesForPopulationWhereFemaleAreMoreThanMale, Long.class);
if(zipCodes == null) {
return new ArrayList<>();
}
return zipCodes;
}
}
| true |
9a96a55e3fb93dfcbd60dfd22ef71e2c2c5c7324 | Java | mcrowder65/settlers-of-catan | /Project/test/communication/PollerTests.java | UTF-8 | 1,929 | 2.328125 | 2 | [] | no_license | package communication;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import client.communication.HTTPProxy;
import client.communication.MockProxy;
import client.communication.Poller;
import client.data.GameManager;
public class PollerTests {
GameManager gameManager;
//HTTPProxy httpProxy;
MockProxy mockProxy;
@Before
public void setUp() throws Exception {
//httpProxy = new HTTPProxy(3, "localhost", 8001);
mockProxy = new MockProxy();
}
@After
public void tearDown() throws Exception {
}
@Test
public void intervalTest() {
try
{
gameManager = new GameManager(mockProxy, 0);
fail("Should have thrown an exception.");
}
catch (IllegalArgumentException ex) {}
gameManager = new GameManager(mockProxy, 1);
}
@Test
public void startStopTest() {
gameManager = new GameManager(mockProxy, 1);
assertFalse(gameManager.getPoller().isPolling());
gameManager.getPoller().stopPolling();
assertFalse(gameManager.getPoller().isPolling());
gameManager.getPoller().startPolling();
assertTrue(gameManager.getPoller().isPolling());
gameManager.getPoller().startPolling();
assertTrue(gameManager.getPoller().isPolling());
gameManager.getPoller().stopPolling();
assertFalse(gameManager.getPoller().isPolling());
gameManager.getPoller().startPolling();
assertTrue(gameManager.getPoller().isPolling());
}
@Test
public void updateModelTest() {
final int INTERVAL = 2;
gameManager = new GameManager(mockProxy, INTERVAL);
assertTrue(gameManager.getModel() == null);
gameManager.getPoller().startPolling();
try {
Thread.sleep((INTERVAL *2) * 1000);
assertTrue(gameManager.getModel() != null);
} catch (InterruptedException e) {
fail("Shouldn't have thrown an exception.");
}
}
}
| true |
8cf213dd535050e0ca70486968e359f64efb6318 | Java | ningwy/GooglePlay | /src/main/java/io/github/ningwy/googleplay/http/protocol/RecommendProtocol.java | UTF-8 | 738 | 2.203125 | 2 | [] | no_license | package io.github.ningwy.googleplay.http.protocol;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import io.github.ningwy.googleplay.utils.GsonUtils;
/**
* 推荐页面网络请求
* Created by ningwy on 2016/9/6.
*/
public class RecommendProtocol extends BaseProtocol<List<String>> {
@Override
public String getParams() {
return "";
}
@Override
public String getKey() {
return "recommend";
}
@Override
public List<String> parseData(String json) {
Gson gson = GsonUtils.getGson();
Type type = new TypeToken<List<String>>(){}.getType();
return gson.fromJson(json, type);
}
}
| true |
587ef3d051f7bafb50038e3ee69e4ef601779357 | Java | stripe/stripe-java | /src/main/java/com/stripe/model/billingportal/Session.java | UTF-8 | 12,145 | 2 | 2 | [
"MIT"
] | permissive | // File generated from our OpenAPI spec
package com.stripe.model.billingportal;
import com.google.gson.annotations.SerializedName;
import com.stripe.exception.StripeException;
import com.stripe.model.ExpandableField;
import com.stripe.model.HasId;
import com.stripe.model.StripeObject;
import com.stripe.net.ApiMode;
import com.stripe.net.ApiRequestParams;
import com.stripe.net.ApiResource;
import com.stripe.net.BaseAddress;
import com.stripe.net.RequestOptions;
import com.stripe.net.StripeResponseGetter;
import com.stripe.param.billingportal.SessionCreateParams;
import java.util.List;
import java.util.Map;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* The Billing customer portal is a Stripe-hosted UI for subscription and billing management.
*
* <p>A portal configuration describes the functionality and features that you want to provide to
* your customers through the portal.
*
* <p>A portal session describes the instantiation of the customer portal for a particular customer.
* By visiting the session's URL, the customer can manage their subscriptions and billing details.
* For security reasons, sessions are short-lived and will expire if the customer does not visit the
* URL. Create sessions on-demand when customers intend to manage their subscriptions and billing
* details.
*
* <p>Learn more in the <a
* href="https://stripe.com/docs/billing/subscriptions/integrating-customer-portal">integration
* guide</a>.
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public class Session extends ApiResource implements HasId {
/** The configuration used by this session, describing the features available. */
@SerializedName("configuration")
@Getter(lombok.AccessLevel.NONE)
@Setter(lombok.AccessLevel.NONE)
ExpandableField<Configuration> configuration;
/** Time at which the object was created. Measured in seconds since the Unix epoch. */
@SerializedName("created")
Long created;
/** The ID of the customer for this session. */
@SerializedName("customer")
String customer;
/**
* Information about a specific flow for the customer to go through. See the <a
* href="https://stripe.com/docs/customer-management/portal-deep-links">docs</a> to learn more
* about using customer portal deep links and flows.
*/
@SerializedName("flow")
Flow flow;
/** Unique identifier for the object. */
@Getter(onMethod_ = {@Override})
@SerializedName("id")
String id;
/**
* Has the value {@code true} if the object exists in live mode or the value {@code false} if the
* object exists in test mode.
*/
@SerializedName("livemode")
Boolean livemode;
/**
* The IETF language tag of the locale Customer Portal is displayed in. If blank or auto, the
* customer’s {@code preferred_locales} or browser’s locale is used.
*
* <p>One of {@code auto}, {@code bg}, {@code cs}, {@code da}, {@code de}, {@code el}, {@code en},
* {@code en-AU}, {@code en-CA}, {@code en-GB}, {@code en-IE}, {@code en-IN}, {@code en-NZ},
* {@code en-SG}, {@code es}, {@code es-419}, {@code et}, {@code fi}, {@code fil}, {@code fr},
* {@code fr-CA}, {@code hr}, {@code hu}, {@code id}, {@code it}, {@code ja}, {@code ko}, {@code
* lt}, {@code lv}, {@code ms}, {@code mt}, {@code nb}, {@code nl}, {@code pl}, {@code pt}, {@code
* pt-BR}, {@code ro}, {@code ru}, {@code sk}, {@code sl}, {@code sv}, {@code th}, {@code tr},
* {@code vi}, {@code zh}, {@code zh-HK}, or {@code zh-TW}.
*/
@SerializedName("locale")
String locale;
/**
* String representing the object's type. Objects of the same type share the same value.
*
* <p>Equal to {@code billing_portal.session}.
*/
@SerializedName("object")
String object;
/**
* The account for which the session was created on behalf of. When specified, only subscriptions
* and invoices with this {@code on_behalf_of} account appear in the portal. For more information,
* see the <a
* href="https://stripe.com/docs/connect/separate-charges-and-transfers#on-behalf-of">docs</a>.
* Use the <a
* href="https://stripe.com/docs/api/accounts/object#account_object-settings-branding">Accounts
* API</a> to modify the {@code on_behalf_of} account's branding settings, which the portal
* displays.
*/
@SerializedName("on_behalf_of")
String onBehalfOf;
/**
* The URL to redirect customers to when they click on the portal's link to return to your
* website.
*/
@SerializedName("return_url")
String returnUrl;
/** The short-lived URL of the session that gives customers access to the customer portal. */
@SerializedName("url")
String url;
/** Get ID of expandable {@code configuration} object. */
public String getConfiguration() {
return (this.configuration != null) ? this.configuration.getId() : null;
}
public void setConfiguration(String id) {
this.configuration = ApiResource.setExpandableFieldId(id, this.configuration);
}
/** Get expanded {@code configuration}. */
public Configuration getConfigurationObject() {
return (this.configuration != null) ? this.configuration.getExpanded() : null;
}
public void setConfigurationObject(Configuration expandableObject) {
this.configuration =
new ExpandableField<Configuration>(expandableObject.getId(), expandableObject);
}
/** Creates a session of the customer portal. */
public static Session create(Map<String, Object> params) throws StripeException {
return create(params, (RequestOptions) null);
}
/** Creates a session of the customer portal. */
public static Session create(Map<String, Object> params, RequestOptions options)
throws StripeException {
String path = "/v1/billing_portal/sessions";
return getGlobalResponseGetter()
.request(
BaseAddress.API,
ApiResource.RequestMethod.POST,
path,
params,
Session.class,
options,
ApiMode.V1);
}
/** Creates a session of the customer portal. */
public static Session create(SessionCreateParams params) throws StripeException {
return create(params, (RequestOptions) null);
}
/** Creates a session of the customer portal. */
public static Session create(SessionCreateParams params, RequestOptions options)
throws StripeException {
String path = "/v1/billing_portal/sessions";
ApiResource.checkNullTypedParams(path, params);
return getGlobalResponseGetter()
.request(
BaseAddress.API,
ApiResource.RequestMethod.POST,
path,
ApiRequestParams.paramsToMap(params),
Session.class,
options,
ApiMode.V1);
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class Flow extends StripeObject {
@SerializedName("after_completion")
AfterCompletion afterCompletion;
/** Configuration when {@code flow.type=subscription_cancel}. */
@SerializedName("subscription_cancel")
SubscriptionCancel subscriptionCancel;
/** Configuration when {@code flow.type=subscription_update}. */
@SerializedName("subscription_update")
SubscriptionUpdate subscriptionUpdate;
/** Configuration when {@code flow.type=subscription_update_confirm}. */
@SerializedName("subscription_update_confirm")
SubscriptionUpdateConfirm subscriptionUpdateConfirm;
/**
* Type of flow that the customer will go through.
*
* <p>One of {@code payment_method_update}, {@code subscription_cancel}, {@code
* subscription_update}, or {@code subscription_update_confirm}.
*/
@SerializedName("type")
String type;
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class AfterCompletion extends StripeObject {
/** Configuration when {@code after_completion.type=hosted_confirmation}. */
@SerializedName("hosted_confirmation")
HostedConfirmation hostedConfirmation;
/** Configuration when {@code after_completion.type=redirect}. */
@SerializedName("redirect")
Redirect redirect;
/**
* The specified type of behavior after the flow is completed.
*
* <p>One of {@code hosted_confirmation}, {@code portal_homepage}, or {@code redirect}.
*/
@SerializedName("type")
String type;
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class HostedConfirmation extends StripeObject {
/** A custom message to display to the customer after the flow is completed. */
@SerializedName("custom_message")
String customMessage;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class Redirect extends StripeObject {
/** The URL the customer will be redirected to after the flow is completed. */
@SerializedName("return_url")
String returnUrl;
}
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class SubscriptionCancel extends StripeObject {
/** The ID of the subscription to be canceled. */
@SerializedName("subscription")
String subscription;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class SubscriptionUpdate extends StripeObject {
/** The ID of the subscription to be updated. */
@SerializedName("subscription")
String subscription;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class SubscriptionUpdateConfirm extends StripeObject {
/**
* The coupon or promotion code to apply to this subscription update. Currently, only up to
* one may be specified.
*/
@SerializedName("discounts")
List<Session.Flow.SubscriptionUpdateConfirm.Discount> discounts;
/**
* The <a href="https://stripe.com/docs/api/subscription_items">subscription item</a> to be
* updated through this flow. Currently, only up to one may be specified and subscriptions
* with multiple items are not updatable.
*/
@SerializedName("items")
List<Session.Flow.SubscriptionUpdateConfirm.Item> items;
/** The ID of the subscription to be updated. */
@SerializedName("subscription")
String subscription;
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class Discount extends StripeObject {
/** The ID of the coupon to apply to this subscription update. */
@SerializedName("coupon")
String coupon;
/** The ID of a promotion code to apply to this subscription update. */
@SerializedName("promotion_code")
String promotionCode;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class Item extends StripeObject implements HasId {
/**
* The ID of the <a
* href="https://stripe.com/docs/api/subscriptions/object#subscription_object-items-data-id">subscription
* item</a> to be updated.
*/
@Getter(onMethod_ = {@Override})
@SerializedName("id")
String id;
/**
* The price the customer should subscribe to through this flow. The price must also be
* included in the configuration's <a
* href="docs/api/customer_portal/configuration#portal_configuration_object-features-subscription_update-products">{@code
* features.subscription_update.products}</a>.
*/
@SerializedName("price")
String price;
/**
* <a href="https://stripe.com/docs/subscriptions/quantities">Quantity</a> for this item
* that the customer should subscribe to through this flow.
*/
@SerializedName("quantity")
Long quantity;
}
}
}
@Override
public void setResponseGetter(StripeResponseGetter responseGetter) {
super.setResponseGetter(responseGetter);
trySetResponseGetter(configuration, responseGetter);
trySetResponseGetter(flow, responseGetter);
}
}
| true |
aba5d21467950fec45a360bbbda5178097e95ba4 | Java | a5221985/algorithms | /BitArray.java | UTF-8 | 2,639 | 3.640625 | 4 | [] | no_license | public class BitArray {
private int[] bitArray;
private int size;
public void init(int size) {
int arraySize = size / 32;
if (size % 32 > 0)
arraySize++;
bitArray = new int [arraySize];
this.size = size;
print();
}
public void set(int i, int val) {
if (val != 1 && val != 0) {
System.out.println("val should be 1 or 0");
return;
}
if (i < 0 || i >= size) {
System.out.println("i should be in the range [0, " + (size - 1) + "]");
}
int arrayIndex = i / 32;
int bitIndex = i % 32;
System.out.println("array index: " + arrayIndex + ", bit index: " + bitIndex);
setBit(arrayIndex, bitIndex, val);
}
public int get(int i) {
if (i < 0 || i >= size) {
System.out.println("i should be in the range [0, " + (size - 1) + "]");
}
int arrayIndex = i / 32;
int bitIndex = i % 32;
System.out.println("array index: " + arrayIndex + ", bit index: " + bitIndex);
return getBit(arrayIndex, bitIndex);
}
void setBit(int arrayIndex, int bitIndex, int val) {
int mask = -1;
int bit = 1 << bitIndex;
mask ^= bit;
bitArray[arrayIndex] = bitArray[arrayIndex] & mask;
val <<= bitIndex;
bitArray[arrayIndex] = bitArray[arrayIndex] | val;
print();
}
int getBit(int arrayIndex, int bitIndex) {
int mask = 1 << bitIndex;
return (bitArray[arrayIndex] & mask) >> bitIndex;
}
public void print() {
for (int i = 0; i < bitArray.length; i++)
System.out.print(bitArray[i] + " ");
System.out.println();
}
public void printAsBinary() {
StringBuilder sb = new StringBuilder();
int val = 0;
int count = 0;
for (int i = 0; i < bitArray.length; i++) {
val = bitArray[i];
count = 32;
while (count > 0) {
sb.append("" + (val & 1));
val >>= 1;
count--;
}
sb.append(" ");
}
System.out.println(sb.toString());
}
public static void main(String[] args) {
BitArray ba = new BitArray();
int size = 1200;
int i = 37;
int val = 1;
ba.init(size);
ba.set(i, val);
i = 37;
ba.set(i, val);
i = 67;
ba.set(i, val);
i = 7;
ba.set(i, val);
i = 107;
ba.set(i, val);
System.out.println(ba.get(i));
ba.printAsBinary();
}
}
| true |
641b770eb2bf632e98feeedf744c3f67fc4356bd | Java | SM-Tiwari/Spring-Security | /old/vnm-selfcare-webapps-mega2-master/vnm-selfcare-core-2.0/src/main/java/com/gnv/vnm/selfcare/core/adapter/rtbs/ws/CancelReservationResponse.java | UTF-8 | 1,524 | 1.960938 | 2 | [] | no_license |
package com.gnv.vnm.selfcare.core.adapter.rtbs.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="CancelReservationResult" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cancelReservationResult"
})
@XmlRootElement(name = "CancelReservationResponse")
public class CancelReservationResponse {
@XmlElement(name = "CancelReservationResult")
protected boolean cancelReservationResult;
/**
* Gets the value of the cancelReservationResult property.
*
*/
public boolean isCancelReservationResult() {
return cancelReservationResult;
}
/**
* Sets the value of the cancelReservationResult property.
*
*/
public void setCancelReservationResult(boolean value) {
this.cancelReservationResult = value;
}
}
| true |
3203fc6d29954ba0f5cc73cbc545c3d9d651e733 | Java | KervinHjw/android-spain | /app/src/main/java/com/en/scian/entity/MyFriend_Message.java | UTF-8 | 958 | 2.046875 | 2 | [] | no_license | package com.en.scian.entity;
/**
* 我的好友留言
*
* @author jiyx
*
*/
public class MyFriend_Message {
private int friendsMessageId;// 留言消息ID
private String friendsRealName;// 姓名
private String messageContent;// 留言内容
private String messageTime;// 留言时间
public int getFriendsMessageId() {
return friendsMessageId;
}
public void setFriendsMessageId(int friendsMessageId) {
this.friendsMessageId = friendsMessageId;
}
public String getFriendsRealName() {
return friendsRealName;
}
public void setFriendsRealName(String friendsRealName) {
this.friendsRealName = friendsRealName;
}
public String getMessageContent() {
return messageContent;
}
public void setMessageContent(String messageContent) {
this.messageContent = messageContent;
}
public String getMessageTime() {
return messageTime;
}
public void setMessageTime(String messageTime) {
this.messageTime = messageTime;
}
}
| true |
552d390a87abc9d71af1e96c6bb8a5ab6567b4fc | Java | fitsense/BeaconsLocalisation-Triangulation | /app/src/main/java/com/example/a1716342/beaconslocalisation2/Localisation.java | UTF-8 | 11,535 | 2.140625 | 2 | [] | no_license | package com.example.a1716342.beaconslocalisation2;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.RemoteException;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
public class Localisation extends Activity implements BeaconConsumer {
/*
This class is the one where the localisation is using
It uses Triangulation with distance as data to predict areas
*/
private static final String TAG = "Localisation";
private static final String FILE_NAME = "ignored_beacons_list2.dat";
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private static final int NUMBER_BEACONS = 4;
//Layout components
TextView resultText;
TabLayout bar;
Button scan, stopScan;
//Beacon Manager
BeaconManager beaconManager;
//HashTable containing beacons' information
//KEY : {UUID, Major, Minor}
//VALUE : RSSI
Hashtable<ArrayList<String>, Double> beaconsList;
Triangulation3D triangulation3D;
Mapmaker map;
ArrayList<Double> coordinates;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_localisation);
//Checking the state of the required permissions
//See : https://altbeacon.github.io/android-beacon-library/requesting_permission.html
//See : https://developer.android.com/training/permissions/requesting
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check...
//... for coarse location
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect beacons in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
//getting beaconManager instance (object) for Main Activity class
beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconsList = new Hashtable<ArrayList<String>, Double>();
//Setting the navigate bar
bar = findViewById(R.id.bar);
bar.addTab(bar.newTab().setText("Localisation"));
bar.addTab(bar.newTab().setText("Beacons"));
bar.addTab(bar.newTab().setText("ReferencePosition"));
bar.getTabAt(0).select();
bar.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
beaconManager.unbind(Localisation.this);
if (bar.getSelectedTabPosition()==1){
Intent selection = new Intent(Localisation.this, Beacons.class);
startActivity(selection);
}
else if (bar.getSelectedTabPosition()==2){
Intent position = new Intent(Localisation.this, ReferencePosition.class);
startActivity(position);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//Setting components
scan = findViewById(R.id.scan_localisation);
stopScan = findViewById(R.id.stopScan_localisation);
scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Binding activity to the BeaconService
beaconManager.bind(Localisation.this);
stopScan.setEnabled(true);
scan.setEnabled(false);
}
});
stopScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Unbinding activity to the BeaconService
beaconManager.unbind(Localisation.this);
scan.setEnabled(true);
stopScan.setEnabled(false);
}
});
resultText = findViewById(R.id.result);
//Class for triangulation
triangulation3D = new Triangulation3D(this);
map = new Mapmaker();
coordinates = new ArrayList<>();
}
@Override
public void onBeaconServiceConnect() {
beaconManager.removeAllRangeNotifiers();
//Specifies a class that should be called each time the BeaconService gets ranging data,
// which is nominally once per second when beacons are detected.
beaconManager.addRangeNotifier(new RangeNotifier() {
/*
This Override method tells us all the collections of beacons and their details that
are detected within the range by device
*/
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
Log.i(TAG, "Current activity : " + this.toString());
//Updating the hashtable
if (beacons.size() > 0) {
// Iterating through all Beacons from Collection of Beacons
for (Beacon b : beacons) {
ArrayList<String> beaconID = new ArrayList<String>();
beaconID.add(b.getId1().toString());
beaconID.add(b.getId2().toString());
beaconID.add(b.getId3().toString());
if (!isIgnored(beaconID)) {
//If the beacon is not in the hashtable, then adding it
if (beaconsList.get(beaconID) == null) {
beaconsList.put(beaconID, b.getDistance());
}
//Else change his RSSI in the hashtable
else {
beaconsList.replace(beaconID, b.getDistance());
}
}
}
if (beaconsList.size() >= NUMBER_BEACONS) { //This number has to be change
coordinates = triangulation3D.compute(beaconsList, 3, 2, 1, 0);
try {
Localisation.this.runOnUiThread(new Runnable() {
@Override
public void run() {
resultText.setText(Integer.toString(map.getArea(coordinates.get(0), coordinates.get(1), coordinates.get(2))));
}
});
} catch (Exception e) { }
}
}
}
});
try {
//Tells the BeaconService to start looking for beacons that match the passed Region object.
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) {
Log.e(TAG, "ERROR : " + e.getMessage());
}
}
public boolean isIgnored(ArrayList<String> beacon) {
/*
this method allows to know if a beacon is ignored (see the activity Selection)
*/
FileInputStream fis;
ObjectInputStream ois;
ArrayList<ArrayList<String>> listBeacons;
try {
fis = openFileInput(FILE_NAME);
ois = new ObjectInputStream(fis);
listBeacons = (ArrayList<ArrayList<String>>) ois.readObject();
ois.close();
fis.close();
if (listBeacons.contains(beacon)) return true;
else return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
//Unbinds an Android Activity or Service to the BeaconService to avoid leak.
beaconManager.unbind(this);
}
@Override
protected void onPause() {
super.onPause();
if (beaconManager.isBound(this)) {
beaconManager.unbind(this);
beaconManager.setBackgroundMode(true);
}
}
@Override
protected void onResume() {
super.onResume();
if (beaconManager.isBound(this)) {
beaconManager.setBackgroundMode(false);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
break;
}
}
}
}
| true |
e97003e00acde80053f0d235ab51185f091201c6 | Java | Konhaque/Vivendo-o-Parque | /app/src/main/java/com/projetobeta/vidanoparque/Criar_Publicacao.java | UTF-8 | 7,202 | 1.945313 | 2 | [] | no_license | package com.projetobeta.vidanoparque;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.projetobeta.vidanoparque.bd.Conexao;
import com.projetobeta.vidanoparque.bd.Publicacao;
import com.projetobeta.vidanoparque.bd.Repository;
import com.projetobeta.vidanoparque.bd.Usuario;
import com.projetobeta.vidanoparque.generalfunctions.Fullscreen;
public class Criar_Publicacao extends AppCompatActivity {
private Toolbar toolbar;
private EditText texto;
private ImageView imageView;
private TextView addImagem;
private Publicacao publicacao;
private AlertDialog dialog;
private Usuario usuario;
private Button publicar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Fullscreen(this);
setContentView(R.layout.activity_criar__publicacao);
iniciarObjetos();
setAddImagem();
setPublicar();
}
private void iniciarObjetos(){
toolbar = (Toolbar) findViewById(R.id.tb);
texto = (EditText) findViewById(R.id.mensagem);
imageView = (ImageView) findViewById(R.id.imagem);
addImagem = (TextView) findViewById(R.id.addMidia);
publicar = (Button) findViewById(R.id.publicar);
publicacao = new Publicacao();
usuario = new Repository(this).getPerfil();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
default: return super.onOptionsItemSelected(item);
}
}
private void setAddImagem(){
addImagem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent,10);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode){
case 10:
if(resultCode == RESULT_OK){
imageView.setVisibility(View.VISIBLE);
Glide.with(this).load(data.getData()).into(imageView);
publicacao.setMidia(data.getDataString());
ContentResolver cR = this.getContentResolver();
publicacao.setTipo(cR.getType(data.getData()));
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setPublicar(){
publicar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
verificarPublicacoa();
}
});
}
private void verificarPublicacoa(){
if(publicacao.getMidia() == null && texto.getText().toString().length() == 0) erro();
else publicar();
}
private void publicar(){
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Publicacao");
final String id = databaseReference.push().getKey();
publicacao.setId_usuario(new Repository(Criar_Publicacao.this).getIdUsuario());
publicacao.setTexto(texto.getText().toString());
publicacao.setFtPerfil(usuario.getFoto_perfil());
publicacao.setNome(usuario.getNome());
AlertDialog.Builder builder = new AlertDialog.Builder(Criar_Publicacao.this);
LayoutInflater inflater = getLayoutInflater();
builder.setView(inflater.inflate(R.layout.activity_main, null));
builder.setCancelable(true);
dialog = builder.create();
dialog.show();
if (publicacao.getMidia() != null) {
final StorageReference storageReference = FirebaseStorage.getInstance().getReference("Publicacao").child(id);
storageReference.putFile(Uri.parse(publicacao.getMidia())).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
publicacao.setMidia(uri.toString());
databaseReference.child(id).setValue(publicacao).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(Criar_Publicacao.this,Funcionalidades.class);
intent.putExtra("pub","pub");
startActivity(intent);
}
});
}
});
}
});
}else{
databaseReference.child(id).setValue(publicacao).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(Criar_Publicacao.this,Funcionalidades.class);
intent.putExtra("pub","pub");
startActivity(intent);
}
});
}
}
private void erro(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Algo deu Errado :(");
builder.setMessage("Você não pode fazer uma publicação vazia. Adicione um texto, uma imagem, um vídeo");
builder.setNeutralButton("Ok!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog = builder.create();
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnim;
dialog.show();
}
} | true |
c1b049527f7e8ed0c892d99929c5c7b7b8976143 | Java | ciphercrunch1919/JavaBoisHome | /FamilyTree/BuildFamilyTree.java | UTF-8 | 3,037 | 3.5625 | 4 | [] | no_license | import java.util.Scanner;
public class BuildFamilyTree
{
public static void mainMenu()
{
System.out.println("1. Load from file");
System.out.println("2. Find siblings");
System.out.println("3. Find children");
System.out.println("4. Find parents");
System.out.println("5. List family members");
System.out.println("6. Exit");
}
public static int getUserSelection()
{
Scanner scanner = new Scanner(System.in);
int selection = scanner.nextInt();
return selection;
}
public static String[] readNameFromUser()
{
System.out.println("Enter name: LAST, FIRST");
Scanner in = new Scanner(System.in);
String fullName = in.nextLine();
String [] firstLastNames = fullName.split(",");
for (int i = 0; i < firstLastNames.length; i++)
{
firstLastNames[i] = firstLastNames[i].trim();
}
return firstLastNames;
}
public static void loadFromCSV(FamilyTree family)
{
System.out.println("Enter CSV file name: ");
Scanner in = new Scanner(System.in);
String fileName = in.nextLine();
family.fromCSV(fileName);
}
public static void printFamilyMembers(FamilyMember []relatives)
{
for (int i = 0; i < relatives.length; i++)
{
System.out.println(relatives[i]);
}
}
public static void findSiblings(FamilyTree family)
{
String [] firstLastNames = readNameFromUser();
FamilyMember []siblings = family.getSiblings(firstLastNames[1], firstLastNames[0]);
System.out.println("Siblings:");
printFamilyMembers(siblings);
}
public static void findChildren(FamilyTree family)
{
String [] firstLastNames = readNameFromUser();
FamilyMember []siblings = family.getChildren(firstLastNames[1], firstLastNames[0]);
System.out.println("Children:");
printFamilyMembers(siblings);
}
public static void findParents(FamilyTree family)
{
String [] firstLastNames = readNameFromUser();
FamilyMember []parents = {family.getFather(firstLastNames[1], firstLastNames[0]),
family.getMother(firstLastNames[1], firstLastNames[0])};
System.out.println("Parents:");
printFamilyMembers(parents);
}
public static void main(String []args)
{
boolean quit = false;
FamilyTree family = new FamilyTree();
while (!quit)
{
mainMenu();
int selection = getUserSelection();
switch (selection)
{
case 1:
loadFromCSV(family);
break;
case 2:
findSiblings(family);
break;
case 3:
findChildren(family);
break;
case 4:
findParents(family);
break;
case 5:
printFamilyMembers(family.list());
break;
case 6:
quit = true;
break;
}
}
}
}
| true |
2e5db5d700cc90ef3774882231603a3956424ecf | Java | Bedrock-Addons/Android | /app/src/main/java/com/mcres/octarus/utils/PermissionUtil.java | UTF-8 | 2,747 | 2.25 | 2 | [
"MIT"
] | permissive | package com.mcres.octarus.utils;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.List;
public abstract class PermissionUtil {
public static final String STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
/* Permission required for application */
public static final String[] PERMISSION_ALL = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void goToPermissionSettingScreen(Activity activity) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", activity.getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
public static boolean isAllPermissionGranted(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] permission = PERMISSION_ALL;
if (permission.length == 0) return false;
for (String s : permission) {
if (ActivityCompat.checkSelfPermission(activity, s) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public static String[] getDeniedPermission(Activity act) {
List<String> permissions = new ArrayList<>();
for (int i = 0; i < PERMISSION_ALL.length; i++) {
int status = act.checkSelfPermission(PERMISSION_ALL[i]);
if (status != PackageManager.PERMISSION_GRANTED) {
permissions.add(PERMISSION_ALL[i]);
}
}
return permissions.toArray(new String[permissions.size()]);
}
public static boolean isGranted(Activity act, String permission) {
if (!Tools.needRequestPermission()) return true;
return (act.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
public static boolean isStorageGranted(Activity act) {
return isGranted(act, Manifest.permission.READ_EXTERNAL_STORAGE);
}
public static void showSystemDialogPermission(Fragment fragment, String perm) {
fragment.requestPermissions(new String[]{perm}, 200);
}
public static void showSystemDialogPermission(Activity act, String perm) {
act.requestPermissions(new String[]{perm}, 200);
}
public static void showSystemDialogPermission(Activity act, String perm, int code) {
act.requestPermissions(new String[]{perm}, code);
}
}
| true |