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
335b361828132712817027c6b506cb43fac78676
Java
0x8801/commit
/contributions/gblake707/java/Fundamentals/2016-09-24.java
UTF-8
183
1.703125
2
[]
no_license
Common mistake on switch statements Catch multiple exceptions in a single `catch` block Metadata: creating a user-defined file attribute Measuring time Using `synchronized` statements
true
c482f6fc46c2eb37b4aa55c5eaea2d08e505eb5b
Java
DavidCThames/MobileMemento
/app/src/main/java/org/mitre/mobilememento/util/HttpIO.java
UTF-8
4,278
2.65625
3
[]
no_license
package org.mitre.mobilememento.util; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Static class that handles all Web and HTTP operations. * Created by wes on 12/3/14. */ public final class HttpIO { public static final String MOBILE_REGEX[] = {"", "m.", "mobile.", "wap.", "touch.", "mweb."}; public static final String WWW_REGEX[][] = { {"http://", "http://www.", "http://www2."}, {"https://", "https://www.", "https://www2."} }; /** * Queries the Los Alamos National Laboratory Memento server for the list of Mementos of a specific url. * * @param urlToRead The resource URL to query the server for. * @return A string containing the entire document HTML text */ public static final String getMementoHTML(String urlToRead) { URL url; HttpURLConnection conn; BufferedReader rd; String line; StringBuilder result = new StringBuilder(); try { Log.d("MEMENTO_URL", urlToRead); url = new URL("http://mobilemink.davidcthames.com/?n=10&url=" + urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result.append(line).append("\n"); } rd.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); } /** * Determines if a resource described by a URL is accessible to the live web. * * @param urlToCheck URL to check * @return True if the resource exists and is accessible. (If HTTP request returns < 400) */ public static final boolean exists(String urlToCheck) { try { HttpURLConnection.setFollowRedirects(true); HttpURLConnection connection = (HttpURLConnection) new URL(urlToCheck).openConnection(); connection.setRequestMethod("HEAD"); Log.d("Response Code for " + urlToCheck, connection.getResponseCode() + ""); return (connection.getResponseCode() < 400); } catch (MalformedURLException e) { e.printStackTrace(); return false; } catch (IOException e) { return false; } } /** * Uses regex matching to get the URL of the desktop version of a given mobile site. If the * * @param url URL of the mobile site. If this is a * @return * @throws URISyntaxException */ public static final String getDesktopURL(String url) throws URISyntaxException { String modUrl = url; for (String regex : MOBILE_REGEX) { if (url.contains(regex)) modUrl = url.replace(regex, ""); } return modUrl; } public static final String getDomainName(String url) throws URISyntaxException { URI uri = new URI(url); String host = uri.getHost(); return host.startsWith("www.") ? host.substring(4) : host; } public static final List<String> getMobileDomains(String url) throws URISyntaxException { Log.d("URL:", url); url = getDesktopURL(url); Log.d("URL:", url); String domain = getDomainName(url); List<String> domains = new ArrayList<String>(); for (String regex : MOBILE_REGEX) { String wwwRegeces[]; if (url.contains("https://")) wwwRegeces = WWW_REGEX[1]; else wwwRegeces = WWW_REGEX[0]; for (String wwwRegex : wwwRegeces) { String modDomain = regex + domain; String[] split = url.split(domain); String modURL = wwwRegex + modDomain + split[1]; domains.add(modURL); } } return domains; } }
true
88c3f922f4373d1aed64caa7b54dca0414d6291d
Java
zarnowsk/secretAgentInterface
/src/main/java/com/michzarnowski/michal_zarnowski_a3/model/MissionList.java
UTF-8
1,046
3
3
[]
no_license
package com.michzarnowski.michal_zarnowski_a3.model; import java.io.Serializable; import java.util.ArrayList; /** * Java bean class modeling Agent's list of missions. * Allows the user to set and retrieve agent assigned to a set * of missions, set and retrieve the list of missions and add * a mission to Agent's list. * @author Michal Zarnowski */ public class MissionList implements Serializable { private String agent; private ArrayList<Mission> missions; public MissionList() { } public MissionList(String agent, ArrayList<Mission> missions) { this.agent = agent; this.missions = missions; } public String getAgent() { return agent; } public void setAgent(String agent) { this.agent = agent; } public ArrayList<Mission> getMissions() { return missions; } public void setMissions(ArrayList<Mission> missions) { this.missions = missions; } public void addMission(Mission mission) { missions.add(mission); } }
true
8420a81a8ab1e31a3c668d7d03718f5ff378c78f
Java
METS-Programme/openmrs-module-ugandaemr-sync
/api/src/main/java/org/openmrs/module/ugandaemrsync/tasks/SendFHIRDataToCentralServerTask.java
UTF-8
713
2.265625
2
[]
no_license
package org.openmrs.module.ugandaemrsync.tasks; import org.openmrs.module.ugandaemrsync.api.UgandaEMRHttpURLConnection; import org.openmrs.module.ugandaemrsync.server.SyncDataRecord; import org.openmrs.module.ugandaemrsync.server.SyncFHIRRecord; import org.openmrs.scheduler.tasks.AbstractTask; /** * A Task to Sync all data to the central server. */ public class SendFHIRDataToCentralServerTask extends AbstractTask { public void execute() { UgandaEMRHttpURLConnection ugandaEMRHttpURLConnection = new UgandaEMRHttpURLConnection(); if (!ugandaEMRHttpURLConnection.isConnectionAvailable()) { return; } SyncFHIRRecord syncFHIRRecord = new SyncFHIRRecord(); syncFHIRRecord.syncFHIRData(); } }
true
4cfce683b9152a7dc26a5b3194fd7809ecf270f2
Java
DN-Pixel/TalesOfABlinWorld-Zelda_Like_Game
/src/sample/modele/items/Armes/EpeeLongue.java
UTF-8
147
1.898438
2
[]
no_license
package sample.modele.items.Armes; public class EpeeLongue extends Melee{ public EpeeLongue() { super("EpeeLongue", 5, 1000); } }
true
6912c75315963b49328fb19423f1ef9c6552391b
Java
crazykamal631/java_android
/TestBindingAndViewModel/app/src/main/java/web/com/testbinding3/MainActivity.java
UTF-8
1,197
2.234375
2
[]
no_license
package web.com.testbinding3; import android.arch.lifecycle.ViewModelProviders; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import web.com.testbinding3.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); user = ViewModelProviders.of(this).get(User.class); ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); activityMainBinding.setLifecycleOwner(this); activityMainBinding.setUser(user); activityMainBinding.setClickHandler(new DoMagic()); } public class DoMagic { public void doClick(View view) { Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show(); user.getName().postValue("pavan"); user.getEmail().postValue("pavan@gmail.com"); } } }
true
b16f46326e46b2b901d3365833e5fc723024a5a0
Java
wensheng930729/platform
/bee-platform-system/platform-common-api/src/main/java/com/bee/platform/common/dto/IndustryDTO.java
UTF-8
677
1.914063
2
[]
no_license
package com.bee.platform.common.dto; import com.bee.platform.common.entity.IndustryInfo; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; /** * @author dell * @version 1.0.0 * @ClassName IndustryDTO * @Description 功能描述 * @Date 2019/4/24 16:33 **/ @Data @NoArgsConstructor @Accessors(chain = true) public class IndustryDTO implements Serializable { private static final long serialVersionUID = 1L; /** * 获取到父级行业信息 */ private IndustryInfo parentIndustry; /** * 获取到子级行业信息 */ private IndustryInfo childIndustry; }
true
512ba3ad07f5ef54a6d7d6674a1c0d378678420b
Java
showmeeb/GameBase
/src/com/gamebase/config/SpringWebSocketJavaConfig.java
UTF-8
2,023
2.25
2
[]
no_license
package com.gamebase.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; import com.gamebase.config.websocket.SpringWebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration //註解開啟使用STOMP協議來傳輸基於代理(message broker)的訊息,這時控制器支援使用@MessageMapping,就像使用@RequestMapping一樣 @EnableWebSocketMessageBroker public class SpringWebSocketJavaConfig implements WebSocketMessageBrokerConfigurer { //MessageBroker 是交換訊息的中間程序區塊; registry=註冊 @Override public void configureMessageBroker(MessageBrokerRegistry registry) { //topic=預設的廣播channel;queue=預設的一對一channel;regist=自己開一個讓大家知道自己上線的channel registry.enableSimpleBroker("/topic/","/queue/","/regist/"); registry.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/chat").addInterceptors(new HttpSessionHandshakeInterceptor()) // for catching attribute in session scope .setHandshakeHandler(new SpringWebSocketHandler()).withSockJS(); } //tomcat config @Bean public ServletServerContainerFactoryBean createWebSocketContainer() { ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean(); container.setMaxTextMessageBufferSize(8192); //for tomcat memory config container.setMaxBinaryMessageBufferSize(8192); return container; } }
true
f6934607362d51574e0644cd16d92bdb557b275c
Java
dnef/sensors
/sensor-gtes/src/main/java/gtes/dao/impl/FirmDAOImpl.java
UTF-8
345
1.929688
2
[]
no_license
package gtes.dao.impl; import gtes.dao.FirmDAO; import gtes.dao.common.AbstractHibernateDAO; import gtes.entity.Firm; import org.springframework.stereotype.Repository; @Repository public class FirmDAOImpl extends AbstractHibernateDAO<Firm> implements FirmDAO { public FirmDAOImpl() { super(); setClazz(Firm.class); } }
true
7c717e57b5911bc8b447c2ddde6606b681528a02
Java
Srvndo/Six-Men-s-Morrys
/Six Men's Morris/src/sixMensMorris/Ficha.java
UTF-8
1,549
2.75
3
[]
no_license
package sixMensMorris; import javax.swing.*; import org.jpl7.Query; import java.awt.*; public class Ficha extends JComponent { private int x, y; private Color color; private String nombre; private boolean uso; Ficha(String nombre, int x, int y, Color color){ this.nombre = nombre; this.x = x; this.y = y; this.color = color; uso = false; } public String getNombre(){ return nombre; } public void setNombre(String nombre){ this.nombre = nombre; } public int getX(){ return x; } public void setX(int x){ this.x = x; } public int getY(){ return y; } public void setY(int y){ this.y = y; } public boolean getUso(){ return uso; } public void setUso(Boolean ocupado){ uso = ocupado; } public Color getColor(){ return color; } public boolean movimientoLegal(String s) { Query q = new Query("consult('Six Mens Morris.pl')"); q.hasSolution(); System.out.println("trans(" + nombre + "," + s + ")"); Query q1 = new Query("trans(" + nombre + "," + s + ")"); if(q1.hasSolution()) return true; else return false; } public void paint(Graphics gg){ super.paint(gg); if (gg instanceof Graphics2D){ Graphics2D g2 = (Graphics2D)gg; g2.setStroke(new BasicStroke(5.0f)); // grosor de 5.0 pixels g2.setColor(color); g2.setColor(Color.BLACK); g2.drawOval(x-10, y-10, 30, 30); g2.setColor(color); g2.fillOval(x-10, y-10, 30, 30); } } }
true
bce2306e228f1e19af32e3f37b6bc79c04cc94f7
Java
zhudaydayup/yjbawechat
/src/main/java/yjbd/yjbawechat/Service/PdfThreeService.java
UTF-8
52,463
1.859375
2
[]
no_license
package yjbd.yjbawechat.Service; import com.alibaba.fastjson.JSON; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import com.itextpdf.text.pdf.draw.LineSeparator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import yjbd.yjbawechat.Dao.PdfThreeDal; import yjbd.yjbawechat.Util.MsgUtil; import yjbd.yjbawechat.Util.MsgUtils; import javax.annotation.Resource; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Path; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author: 随心的小新 * @Date: 2019/4/7 9:22 */ @Service public class PdfThreeService { @Resource PdfThreeDal pdfThreeDal; static final Logger logger = LoggerFactory.getLogger(PdfThreeService.class); /** * 获取被执法单位名称 */ public String getZhiFaRenById(String zeLingId){ String responseText = ""; try { List<Map> mapList = pdfThreeDal.getZhiFaRenById(zeLingId); // String CHECKED_UNIT = mapList.get ( 0 ).get ( "CHECKED_UNIT" ).toString ();//被执法单位 responseText = JSON.toJSONString ( mapList); responseText = "[" + responseText + "]"; }catch (Exception e){ logger.info ( e.toString () ); } return responseText; } /** * 获取存在的问题列表 */ public String getProblemById(String zeLingId){ String responseText = ""; try { List<Map> mapList = pdfThreeDal.getProblemById(zeLingId); // for (int i = 0;i<mapList.size ();i++) // { // if (i == mapList.size ()-1){ // String CHECKE_DETAIL = mapList.get ( i ).get ( "CHECKE_DETAIL" ).toString (); // responseText = JSON.toJSONString ( CHECKE_DETAIL); // } // } // String CHECKE_DETAIL = mapList.get ( 0 ).get ( "CHECK_STATE" ).toString (); // if (CHECK_STATE.equals ( "不合格" )) // String CHECKE_DETAIL = mapList.get ( 0 ).get ( "CHECKE_DETAIL" ).toString (); // break // String CHECKE_DETAIL = mapList.get ( i ).get ( "CHECKE_DETAIL" ).toString (); responseText = JSON.toJSONString ( mapList); responseText = "[" + responseText + "]"; }catch (Exception e){ logger.info ( e.toString () ); } return responseText; } /** * 获取PDF预览信息 */ public String createZeLingBiao(String TIME_IDS,String EXECUTE_PEOPLE2,String CARD_NUMBER2,String CHECKE_UNIT, String EXECUTE_PEOPLE,String CARD_NUMBER,String CHECKE_PROBLEM_IDS ,String CHECKED_END_TIME,String RECORD_ID,String ZF_ORDER_DEADLINE_AREA,String ZF_ORDER_DEADLINE_RECORD) { String responseText=""; int count = 0; try { count= pdfThreeDal.getCreatePaperInfoCount(RECORD_ID); if (count>0){ int flag = pdfThreeDal.createPaperInfo1(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKE_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,ZF_ORDER_DEADLINE_AREA,ZF_ORDER_DEADLINE_RECORD,RECORD_ID); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }else { int flag = pdfThreeDal.createPaperInfo(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKE_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,RECORD_ID,ZF_ORDER_DEADLINE_AREA,ZF_ORDER_DEADLINE_RECORD); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } } } catch (Exception e){ e.printStackTrace(); logger.info ( e.toString () ); return MsgUtils.errorMsg("数值异常,无法上传"); } return responseText; } /** * 上传执法者1签名 */ public String UpdateCheck(String CHECKE_SIGH, String RecordId) { String responseText=""; try { int flag = pdfThreeDal.UpdateCheck(CHECKE_SIGH, RecordId); if (flag > 0) { responseText = MsgUtils.successMsg(); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }catch (Exception e){ logger.info ( e.toString () ); responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } return responseText; } /** * 上传执法者2签名 */ public String UpdateCheckTwoSign(String CHECKETWO_SIGH, String RecordId) { String responseText=""; try { int flag = pdfThreeDal.UpdateCheckTwoSign(CHECKETWO_SIGH, RecordId); if (flag > 0) { responseText = MsgUtils.successMsg(); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }catch (Exception e){ logger.info ( e.toString () ); responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } return responseText; } /** * 上传被执法单位签名 */ public String UpdateRepresent(String REPRESENR_SIGN, String RecordId) { String responseText=""; try { int flag = pdfThreeDal.UpdateRepresent(REPRESENR_SIGN, RecordId); if (flag > 0) { responseText = MsgUtils.successMsg(); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }catch (Exception e){ logger.info ( e.toString ()); responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } return responseText; } /** * 上传见证人签名 */ public String UpdateJianZhengRen(String WITNESS_SIGH, String RecordId) { String responseText=""; try { int flag = pdfThreeDal.UpdateJianZhengRen(WITNESS_SIGH, RecordId); if (flag > 0) { responseText = MsgUtils.successMsg(); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }catch (Exception e){ logger.info ( e.toString () ); } return responseText; } /** * 最后生成PDF页面 */ public String getIdRecord(String recordId) { String responseText=""; try { List<Map> list=pdfThreeDal.getIdRecord(recordId); responseText = MsgUtils.successMsg("RecordInfo", list); }catch (Exception e){ logger.info ( e.toString () ); responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } return responseText; } /** * 记录专家责令整改信息 */ public String setExZeLingInfo(String TIME_IDS,String EXECUTE_PEOPLE2,String CARD_NUMBER2,String CHECKED_UNIT, String EXECUTE_PEOPLE,String CARD_NUMBER,String CHECKE_PROBLEM_IDS ,String CHECKED_END_TIME,String RECORD_ID) { String responseText=""; int count=0; try { count=pdfThreeDal.checkTemporaryRecordIdCount(RECORD_ID); if (count>0){ int flag = pdfThreeDal.setExZeLingInfo1(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKED_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,RECORD_ID); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }else { int flag = pdfThreeDal.setExZeLingInfo(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKED_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,RECORD_ID); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } } } catch (Exception e){ e.printStackTrace(); logger.info ( e.toString () ); return MsgUtils.errorMsg("数值异常,无法上传"); } return responseText; } /** * 缓存更新记录专家责令整改信息 */ public String temporarySetExZeLingInfo(String TIME_IDS,String EXECUTE_PEOPLE2,String CARD_NUMBER2,String CHECKED_UNIT, String EXECUTE_PEOPLE,String CARD_NUMBER,String CHECKE_PROBLEM_IDS ,String CHECKED_END_TIME,String URL,String RECORD_ID) { String responseText=""; int count=0; try { count=pdfThreeDal.checkTemporaryRecordIdCount(RECORD_ID); if (count>0){ int flag = pdfThreeDal.temporarySetExZeLingInfo(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKED_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,URL,RECORD_ID); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }else { int flag = pdfThreeDal.temporarySetExZeLingInfo1(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKED_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,RECORD_ID,URL); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } } } catch (Exception e){ e.printStackTrace(); logger.info ( e.toString () ); return MsgUtils.errorMsg("数值异常,无法上传"); } return responseText; } /** * 缓存更新记录专家责令整改信息 */ public String getTemporarySetExZeLingInfo(String RecordId) { String responseText=""; List<Map> mapList=pdfThreeDal.getTemporarySetExZeLingInfo(RecordId); responseText = JSON.toJSONString ( mapList); return responseText; } public String getExRecord(String recordId) { String responseText=""; try { List<Map> list=pdfThreeDal.getExRecord(recordId); responseText = MsgUtils.successMsg("RecordInfo", list); }catch (Exception e){ e.printStackTrace (); logger.info ( e.toString () ); } return responseText; } /** * 缓存政府执法责令限期表格信息 */ public String createTemporaryZeLingBiao(String TIME_IDS,String EXECUTE_PEOPLE2,String CARD_NUMBER2,String CHECKE_UNIT, String EXECUTE_PEOPLE,String CARD_NUMBER,String CHECKE_PROBLEM_IDS ,String CHECKED_END_TIME,String URL,String RECORD_ID) { String responseText=""; int count = 0; try { count= pdfThreeDal.getCreatePaperInfoCount(RECORD_ID); if (count>0){ int flag = pdfThreeDal.createTemporaryZeLingBiao1(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKE_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,URL,RECORD_ID); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } }else { int flag = pdfThreeDal.createTemporaryZeLingBiao(TIME_IDS,EXECUTE_PEOPLE2, CARD_NUMBER2,CHECKE_UNIT, EXECUTE_PEOPLE, CARD_NUMBER, CHECKE_PROBLEM_IDS,CHECKED_END_TIME,URL,RECORD_ID); if (flag > 0) { responseText = MsgUtils.successMsg("recordId",RECORD_ID); } else { responseText = MsgUtils.errorMsg("网络繁忙,请稍后再试..."); } } } catch (Exception e){ e.printStackTrace(); logger.info ( e.toString () ); return MsgUtils.errorMsg("数值异常,无法上传"); } return responseText; } /** * 专家责令整改PDF */ public String createExZeLingPdf (String ID) throws IOException { Document document = new Document( PageSize.A4); String pdfPath="D:/zfbdzl/pdf/expert_zeling/"; String qrCodePath="D:/zfbdzl/qrcode/expert_zeling/"; String url="D:/zfbdzl/images/"; String pdfAbsolutePath="http://zfxc.njyjgl.cn/yjbd2/pdf/getPdf?url=expert_zeling/"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String date1=sdf.format(new Date ()); int random=(int)(Math.random()*10000); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式 // new Date()为获取当前系统时间 String nowTime=df.format(new Date()); String pdfName = date1+"/"+nowTime+ random+".pdf";//包含时间的文件夹 //设置日期格式 List<Map<String,Object>> list=pdfThreeDal.getExZeLingById(ID); String CHECKE_PROBLEM_IDS= "";//整改隐患 if(list.get(0).get("CHECKE_PROBLEM_IDS")!=null) CHECKE_PROBLEM_IDS=list.get(0).get("CHECKE_PROBLEM_IDS").toString(); String[] PROBLEM_ID=CHECKE_PROBLEM_IDS.split("\\|"); /* //从表格中拉取证件号信息 List<Map>mapList2=pdfThreeDal.searchCareId(ID); String AREA="";//检查单位所属辖区 if(mapList2.get(0).get("AREA")!=null) AREA = mapList2.get(0).get("AREA").toString (); */ String CHECKED_UNIT="";//被检查单位 String TIME_IDS=""; //问题的整改期限 if(list.get(0).get("TIME_IDS")!=null) TIME_IDS=list.get(0).get("TIME_IDS").toString(); String[] TIME_IDSL_ARRAY = TIME_IDS.split ( "\\|" ); String UPID="";//责令整改自增id if(list.get(0).get("UPID")!=null) UPID=list.get(0).get("UPID").toString(); String CHECKED_END_TIME="";//检查结束时间 String CHECKE_SIGH="";//检查人员签字图片 String REPRESENR_SIGN="";//被检查代表签字图片 String WITNESS_SIGH="";//见证者签名图片 if(list.get(0).get("CHECKED_UNIT")!=null) CHECKED_UNIT=list.get(0).get("CHECKED_UNIT").toString(); if(list.get(0).get("CHECKED_END_TIME")!=null) CHECKED_END_TIME=list.get(0).get("CHECKED_END_TIME").toString(); if(list.get(0).get("SIGNATURE4_PATH")!=null) REPRESENR_SIGN=list.get(0).get("SIGNATURE4_PATH").toString(); if(list.get(0).get("SIGNATURE3_PATH")!=null) CHECKE_SIGH=list.get(0).get("SIGNATURE3_PATH").toString(); if(list.get(0).get("SIGNATURE5_PATH")!=null) WITNESS_SIGH=list.get(0).get("SIGNATURE5_PATH").toString(); String[] REPRESENR_SIGN_ARRAY= REPRESENR_SIGN.split("\\|"); String[] CHECKE_SIGH_ARRAY= CHECKE_SIGH.split("\\|"); String[] JIANZHENG_SIGH_ARRAY= WITNESS_SIGH.split("\\|"); try { File file1 =new File(pdfPath+date1); if(!file1 .exists() && !file1 .isDirectory()){ file1 .mkdir(); } File file2 =new File(qrCodePath+date1); if(!file2 .exists() && !file2 .isDirectory()){ file2 .mkdir(); } PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(pdfPath+pdfName)); BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); Font titleFont = new Font(bfChinese, 20, Font.BOLD,BaseColor.BLACK);//加入document: Font para = new Font(bfChinese, 12, Font.NORMAL,BaseColor.BLACK); Font lineFont=new Font(bfChinese,2, Font.NORMAL,BaseColor.BLACK); Paragraph paragraph; float leading=20f; //补全下划线至行尾 LineSeparator lineSeparator=new LineSeparator(); lineSeparator.setOffset(-1f); lineSeparator.setLineWidth(0.1F); Chunk chunk; document.addTitle("example of PDF"); document.open(); //副标题:现场检查记录 Paragraph subTitle=new Paragraph("责令限期整改指令书",titleFont); subTitle.setAlignment(Element.ALIGN_CENTER); document.add(subTitle); //应急检记 //Paragraph subTitle2=new Paragraph("("+AREA+" )应急责改[2019]("+UPID+")号",para); Paragraph subTitle2=new Paragraph("(宁)应急责改[2019]("+UPID+")号",para); subTitle2.setAlignment(Element.ALIGN_CENTER); document.add(subTitle2); //time //设置行距,该处会影响后面所有的chunk的行距 paragraph=new Paragraph("",para); paragraph.setLeading(25f); document.add(paragraph); //被检查单位 chunk = new Chunk("",para); document.add(chunk); chunk = new Chunk(CHECKED_UNIT+"有限公司:"+"",para); chunk.setUnderline(0.1f, -1f); document.add(chunk); // document.add(new Chunk(lineSeparator)); document.add(Chunk.NEWLINE); //段落1 chunk = new Chunk(" 现责令你单位对下述:",para); document.add(chunk); chunk = new Chunk(""+PROBLEM_ID.length,para); chunk.setUnderline(0.1f, -1f); document.add(chunk); chunk = new Chunk("项问题按",para); document.add(chunk); chunk = new Chunk("下述规定的时间期限整改完毕,达到有关法律法规规章和标准规定的要求。由此造成事故的,依法追究有关人员的责任。",para); document.add(chunk); document.add(Chunk.NEWLINE); /*//问题和整改时间 chunk = new Chunk(" "+"整改完成时限:",para); document.add(chunk); chunk = new Chunk(MODIFY_TIME,para); chunk.setUnderline(0.1f, -1f); document.add(chunk); document.add(new Chunk(lineSeparator)); document.add(Chunk.NEWLINE); chunk = new Chunk(" "+"整改隐患:",para); document.add(chunk); document.add(Chunk.NEWLINE); for (int i = 0;i<PROBLEM_ID.length;i++){ chunk = new Chunk(" "+(i+1)+"." ,para); document.add(chunk); chunk = new Chunk(PROBLEM_ID[i],para); chunk.setUnderline(0.1f, -1f); document.add(chunk); document.add(new Chunk(lineSeparator)); document.add(Chunk.NEWLINE); }*/ //问题和整改时间 for (int i = 0;i<PROBLEM_ID.length;i++){ chunk = new Chunk(" "+(i+1)+"." ,para); document.add(chunk); chunk = new Chunk(PROBLEM_ID[i],para); chunk.setUnderline(0.1f, -1f); document.add(chunk); chunk = new Chunk(" "+"整改完成时限:",para); document.add(chunk); chunk = new Chunk(TIME_IDSL_ARRAY[i],para); chunk.setUnderline(0.1f, -1f); document.add(chunk); document.add(new Chunk(lineSeparator)); document.add(Chunk.NEWLINE); } //段落2 chunk = new Chunk(" 整改期间,你单位应当采取措施,确保安全生产。对安全生产违法行为,将依法予以行政处罚。",para); document.add(chunk); document.add(Chunk.NEWLINE); //段落3 chunk = new Chunk(" 如果不服从本指令,可以依法在60日内向南京市人民政府或者江苏省应急管理厅申请行政复议,或者在6个月内依法向",para); document.add(chunk); chunk = new Chunk("南京铁路运输法院",para); chunk.setUnderline(0.1f, -1f); document.add(chunk); chunk = new Chunk("提起行政诉讼,但本指令不停止执行,法律另有规定的除外。",para); document.add(chunk); document.add(Chunk.NEWLINE); PdfContentByte cb = writer.getDirectContent(); BaseFont bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); if (!WITNESS_SIGH.equals("")){ cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "见证人(签名):", 25f, 200f, 0); cb.endText(); } cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "被检查单位现场负责人(签名):", 25f, 250f, 0); cb.endText(); cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "检查人(签名):", 25f, 300f, 0); cb.endText(); String inscribe="南京市应急管理局";//'宁','江北', '玄', '秦','建','鼓','栖','经开','雨','江','浦','六','溧','高' /* if (AREA.equals("宁")) { inscribe=""; } else if (AREA.equals("江北")) { inscribe="南京市江北新区应急管理局"; } else if (AREA.equals("玄")) { inscribe="南京市玄武区应急管理局"; }else if (AREA.equals("秦")) { inscribe="南京市秦淮区应急管理局"; }else if (AREA.equals("建")) { inscribe="南京市建邺区应急管理局"; }else if (AREA.equals("鼓")) { inscribe="南京市鼓楼区应急管理局"; }else if (AREA.equals("栖")) { inscribe="南京市栖霞区应急管理局"; }else if (AREA.equals("经开")) { inscribe="南京市经济开发区应急管理局"; }else if (AREA.equals("雨")) { inscribe="南京市雨花台区应急管理局"; }else if (AREA.equals("江")) { inscribe="南京市江宁区应急管理局"; }else if (AREA.equals("浦")) { inscribe="南京市浦口区应急管理局"; }else if (AREA.equals("六")) { inscribe="南京市六合区应急管理局"; }else if (AREA.equals("溧")) { inscribe="南京市溧水区应急管理局"; }else if (AREA.equals("高")) { inscribe="南京市高淳区应急管理局"; }*/ cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, inscribe, 390f, 110f, 0); cb.endText(); //时间 cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, CHECKED_END_TIME, 470f, 90f, 0); cb.endText(); /* if(AREA.equals("宁")){ //印章图片 Image image = Image.getInstance ( "C:/zfbdmoban/images/zz.png" ); image.setAbsolutePosition ( 400f, 70f ); image.scaleAbsolute ( 140, 140 ); document.add ( image ); }*/ //检查人员签名图片 for(int i=0;i<CHECKE_SIGH_ARRAY.length;i++){ Image image1 = Image.getInstance(url+CHECKE_SIGH_ARRAY[i]); image1.setAbsolutePosition(220f+105*i, 280f); //Scale to new height and new width of image image1.scaleAbsolute(48, 48); //Add to document document.add(image1); } //被检查人单位现场负责人签名图片 for(int i=0;i<REPRESENR_SIGN_ARRAY.length;i++){ Image image1 = Image.getInstance(url+REPRESENR_SIGN_ARRAY[i]); //Fixed Positioning image1.setAbsolutePosition(220f+105*i, 230f); //Scale to new height and new width of image image1.scaleAbsolute(48, 48); //Add to document document.add(image1); } if (!WITNESS_SIGH.equals("")){ //见证人签名图片 for(int i=0;i<JIANZHENG_SIGH_ARRAY.length;i++){ Image image1 = Image.getInstance(url+JIANZHENG_SIGH_ARRAY[i]); //Fixed Positioning image1.setAbsolutePosition(140f+105*i, 180f); //Scale to new height and new width of image image1.scaleAbsolute(48, 48); //Add to document document.add(image1); } } document.newPage(); //地址 paragraph=new Paragraph("",para); paragraph.setLeading(20f); document.add(paragraph); //预览二维码 String content=pdfAbsolutePath+pdfName; String qrCodeName=date1+"/"+nowTime+ random+".png"; try{ Map<EncodeHintType, Object> hints = new HashMap<> (); //编码 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //边框距 hints.put(EncodeHintType.MARGIN, 0); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bm = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 199, 199, hints); Path file=new File(qrCodePath+qrCodeName).toPath(); MatrixToImageWriter.writeToPath(bm, "png", file); }catch (Exception e){ System.out.println ( e.toString () ); e.printStackTrace(); logger.info ( e.toString () ); } pdfThreeDal.updateExPdfAndQrcode(pdfName,qrCodeName,ID); } catch (FileNotFoundException e) { e.printStackTrace(); logger.info ( e.toString () ); return MsgUtil.errorMsg(e.toString()); } catch (DocumentException e) { e.printStackTrace(); logger.info ( e.getLocalizedMessage () ); return MsgUtil.errorMsg(e.toString()); } finally { document.close(); } return MsgUtil.successMsg(); } /** * 获取PDF页面 * @param ID * @return * @throws IOException */ public String createThreePDF (String ID) throws IOException { Document document = new Document( PageSize.A4); String pdfPath="D:/zfbdzl/pdf/zeling/"; String qrCodePath="D:/zfbdzl/qrcode/zeling/"; String url="D:/zfbdzl/images/"; String pdfAbsolutePath="http://zfxc.njyjgl.cn/yjbd2/pdf/getPdf?url=zeling/"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String date1=sdf.format(new Date ()); int random=(int)(Math.random()*10000); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式 // new Date()为获取当前系统时间 String nowTime=df.format(new Date()); String pdfName = date1+"/"+nowTime+ random+".pdf";//包含时间的文件夹 //设置日期格式 List<Map<String,Object>> list=pdfThreeDal.getThreeById(ID); String CHECKE_PROBLEM_IDS= "";//获取问题的唯一标识ID String CHECKE_DETAIL ="";//获取问题 String CHECKED_START_TIME="";//检查开始时间 if(list.get(0).get("CHECKE_PROBLEM_IDS")!=null) CHECKE_PROBLEM_IDS=list.get(0).get("CHECKE_PROBLEM_IDS").toString(); String[] PROBLEM_ID=CHECKE_PROBLEM_IDS.split("\\|"); try { for (int i=0;i<PROBLEM_ID.length;i++){ String problemId = PROBLEM_ID[i]; List<Map>mapList = pdfThreeDal.searchProblemById(problemId); if(mapList.get(0).get("CHECKE_DETAIL")!=null) CHECKE_DETAIL += mapList.get(0).get("CHECKE_DETAIL").toString()+"|"; if(mapList.get(0).get("CHECKED_END_TIME")!=null) CHECKED_START_TIME=mapList.get(0).get("CHECKED_END_TIME").toString(); } }catch (Exception e){ System.out.println ( e.toString () ); e.printStackTrace(); } //从表格中拉取证件号信息 List<Map>mapList2=pdfThreeDal.searchCareId(ID); String AREA="";//检查单位所属辖区 if(mapList2.get(0).get("AREA")!=null) AREA = mapList2.get(0).get("AREA").toString (); String[] CHECKE_DETAIL_ARRAY = CHECKE_DETAIL.split ( "\\|" ); String RECORD_ID=ID; //现场检查记录的自增id String CHECKE_UNIT="";//被检查单位 String TIME_IDS=""; //问题的整改期限 if(list.get(0).get("TIME_IDS")!=null) TIME_IDS=list.get(0).get("TIME_IDS").toString(); String[] TIME_IDSL_ARRAY = TIME_IDS.split ( "\\|" ); String UPID="";//责令整改自增id if(list.get(0).get("UPID")!=null) UPID=list.get(0).get("UPID").toString(); // String CHECKE_PROBLEM="";//问题 // String REPRESENT_PEOPLE="";//代表人 // String REPRESENT_JOB="";//代表人职务 // String MOBILE="";//手机号码 // String CHECKED_LOCATION="";//检查场所 // String EXECUTE_UNIT="";//执法单位 // String EXECUTE_PEOPLE="";//执法人员 // String CHECKE_DETAIL="";//检查情况 // String CREATE_TIME="";//记录创建时间 // String LOCATION_IMG="";//现场图片 String CHECKED_END_TIME="";//检查结束时间 String CARD_NUMBER1="";//证件号1 String CARD_NUMBER2 ="";//证件号2 String REPRESENR_SIGN="";//被检查代表签字图片 String CHECKE_SIGH="";//检查人员签字图片 String CHECKETWO_SIGH="";//检查人员2签字图片 String WITNESS_SIGH="";//见证者签名图片 String ENFORCE_PAPER="";//最终执法文书 String OTHER_IMG="";//其他图片 String SELECTED_MODEL=""; String NOT_SELECTED_MODEL=""; String ZF_ORDER_DEADLINE_AREA="";//所属地区 String ZF_ORDER_DEADLINE_RECORD="";//文书编号 if(list.get(0).get("ZF_ORDER_DEADLINE_AREA")!=null) ZF_ORDER_DEADLINE_AREA=list.get(0).get("ZF_ORDER_DEADLINE_AREA").toString(); if(list.get(0).get("ZF_ORDER_DEADLINE_RECORD")!=null) ZF_ORDER_DEADLINE_RECORD=list.get(0).get("ZF_ORDER_DEADLINE_RECORD").toString(); if(list.get(0).get("RECORD_ID")!=null) RECORD_ID=list.get(0).get("RECORD_ID").toString(); if(list.get(0).get("CHECKE_UNIT")!=null) CHECKE_UNIT=list.get(0).get("CHECKE_UNIT").toString(); // if(list.get(0).get("CHECKE_PROBLEM")!=null) CHECKE_PROBLEM=list.get(0).get("CHECKE_PROBLEM").toString(); // if(list.get(0).get("REPRESENT_PEOPLE")!=null) REPRESENT_PEOPLE=list.get(0).get("REPRESENT_PEOPLE").toString(); // if(list.get(0).get("REPRESENT_JOB")!=null) REPRESENT_JOB=list.get(0).get("REPRESENT_JOB").toString(); // if(list.get(0).get("MOBILE")!=null) MOBILE=list.get(0).get("MOBILE").toString(); // if(list.get(0).get("CHECKED_LOCATION")!=null) CHECKED_LOCATION=list.get(0).get("CHECKED_LOCATION").toString(); if(list.get(0).get("CHECKED_END_TIME")!=null) CHECKED_END_TIME=list.get(0).get("CHECKED_END_TIME").toString(); // if(list.get(0).get("EXECUTE_UNIT")!=null) EXECUTE_UNIT=list.get(0).get("EXECUTE_UNIT").toString(); // if(list.get(0).get("EXECUTE_PEOPLE")!=null) EXECUTE_PEOPLE=list.get(0).get("EXECUTE_PEOPLE").toString(); if(mapList2.get(0).get("CARD_NUMBER1")!=null) CARD_NUMBER1=mapList2.get(0).get("CARD_NUMBER1").toString(); if(mapList2.get(0).get("CARD_NUMBER2")!=null) CARD_NUMBER2=mapList2.get(0).get("CARD_NUMBER2").toString(); // if(list.get(0).get("CHECKE_DETAIL")!=null) CHECKE_DETAIL=list.get(0).get("CHECKE_DETAIL").toString(); if(list.get(0).get("REPRESENR_SIGN")!=null) REPRESENR_SIGN=list.get(0).get("REPRESENR_SIGN").toString(); if(list.get(0).get("CHECKE_SIGH")!=null) CHECKE_SIGH=list.get(0).get("CHECKE_SIGH").toString(); if(list.get(0).get("CHECKETWO_SIGH")!=null) CHECKETWO_SIGH=list.get(0).get("CHECKETWO_SIGH").toString(); // if(list.get(0).get("CREATE_TIME")!=null) CREATE_TIME=list.get(0).get("CREATE_TIME").toString(); // if(list.get(0).get("LOCATION_IMG")!=null) LOCATION_IMG=list.get(0).get("LOCATION_IMG").toString(); if(list.get(0).get("ENFORCE_PAPER")!=null) ENFORCE_PAPER=list.get(0).get("ENFORCE_PAPER").toString(); if(list.get(0).get("OTHER_IMG")!=null) OTHER_IMG=list.get(0).get("OTHER_IMG").toString(); if(list.get(0).get("SELECTED_MODEL")!=null) SELECTED_MODEL=list.get(0).get("SELECTED_MODEL").toString(); if(list.get(0).get("NOT_SELECTED_MODEL")!=null) NOT_SELECTED_MODEL=list.get(0).get("NOT_SELECTED_MODEL").toString(); if(list.get(0).get("WITNESS_SIGH")!=null) WITNESS_SIGH=list.get(0).get("WITNESS_SIGH").toString(); // String[] LOCATION_IMG_ARRAY= LOCATION_IMG.split("\\|"); String[] OTHER_IMG_ARRAY= OTHER_IMG.split("\\|"); String[] REPRESENR_SIGN_ARRAY= REPRESENR_SIGN.split("\\|"); String[] CHECKE_SIGH_ARRAY= CHECKE_SIGH.split("\\|"); String[] CHECKE_TWO_SIGH_ARRAY= CHECKETWO_SIGH.split("\\|"); String[] JIANZHENG_SIGH_ARRAY= WITNESS_SIGH.split("\\|"); String[] selectedArray=SELECTED_MODEL.split("\\|"); String[] unselectedArray=NOT_SELECTED_MODEL.split("\\|"); // String[] problem=CHECKE_PROBLEM.split("\\|"); try { File file1 =new File(pdfPath+date1); if(!file1 .exists() && !file1 .isDirectory()){ file1 .mkdir(); } File file2 =new File(qrCodePath+date1); if(!file2 .exists() && !file2 .isDirectory()){ file2 .mkdir(); } PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(pdfPath+pdfName)); //BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); Font titleFont = new Font(bfChinese, 20, Font.BOLD,BaseColor.BLACK);//加入document: Font para = new Font(bfChinese, 12, Font.NORMAL,BaseColor.BLACK); Font lineFont=new Font(bfChinese,2, Font.NORMAL,BaseColor.BLACK); Paragraph paragraph; float leading=20f; //补全下划线至行尾 LineSeparator lineSeparator=new LineSeparator(); lineSeparator.setOffset(-1f); lineSeparator.setLineWidth(0.1F); Chunk chunk; document.addTitle("example of PDF"); document.open(); /* //主标题:安全生产行政执法文书现场检查记录 Paragraph title=new Paragraph("安全生产行政执法文书",titleFont); title.setAlignment(Element.ALIGN_CENTER); document.add(title); //直线 Paragraph line = new Paragraph("",lineFont); line.add(new Chunk(lineSeparator)); line.add(""); document.add(line); //直线 Paragraph line2 = new Paragraph("",lineFont); LineSeparator lineSeparator2=new LineSeparator(); lineSeparator2.setLineWidth(0.5F); line2.add(new Chunk(lineSeparator2)); line2.add(""); document.add(line2);*/ //副标题:现场检查记录 Paragraph subTitle=new Paragraph("责令限期整改指令书",titleFont); subTitle.setAlignment(Element.ALIGN_CENTER); document.add(subTitle); // //应急检记 Paragraph subTitle2=new Paragraph("("+ZF_ORDER_DEADLINE_AREA+" )应急责改[2019]("+ZF_ORDER_DEADLINE_RECORD+")号",para); subTitle2.setAlignment(Element.ALIGN_CENTER); document.add(subTitle2); //time //设置行距,该处会影响后面所有的chunk的行距 paragraph=new Paragraph("",para); paragraph.setLeading(25f); document.add(paragraph); //被检查单位 chunk = new Chunk("",para); document.add(chunk); chunk = new Chunk(CHECKE_UNIT+"有限公司:"+"",para); chunk.setUnderline(0.1f, -1f); document.add(chunk); // document.add(new Chunk(lineSeparator)); document.add(Chunk.NEWLINE); //事由和目的 /*chunk = new Chunk(" 经查,你单位存在下列问题:",para); document.add(chunk); document.add(Chunk.NEWLINE); for (int i = 0;i<CHECKE_DETAIL_ARRAY.length;i++){ chunk = new Chunk(" "+(i+1)+"." ,para); document.add(chunk); chunk = new Chunk(CHECKE_DETAIL_ARRAY[i],para); chunk.setUnderline(0.1f, -1f); document.add(chunk); document.add(new Chunk(lineSeparator)); document.add(Chunk.NEWLINE); } chunk = new Chunk(" (此栏不够,可另附页)。",para); document.add(chunk); document.add(Chunk.NEWLINE);*/ //段落1 chunk = new Chunk(" 现责令你单位对下述:",para); document.add(chunk); chunk = new Chunk(""+CHECKE_DETAIL_ARRAY.length,para); chunk.setUnderline(0.1f, -1f); document.add(chunk); chunk = new Chunk("项问题按",para); document.add(chunk); /* chunk = new Chunk(CHECKED_END_TIME,para); chunk.setUnderline(0.1f, -1f); document.add(chunk);*/ chunk = new Chunk("下述规定的时间期限整改完毕,达到有关法律法规规章和标准规定的要求。由此造成事故的,依法追究有关人员的责任。",para); document.add(chunk); document.add(Chunk.NEWLINE); //问题和整改时间 for (int i = 0;i<CHECKE_DETAIL_ARRAY.length;i++){ chunk = new Chunk(" "+(i+1)+"." ,para); document.add(chunk); chunk = new Chunk(CHECKE_DETAIL_ARRAY[i],para); chunk.setUnderline(0.1f, -1f); document.add(chunk); chunk = new Chunk(" "+"整改完成时限:",para); document.add(chunk); chunk = new Chunk(TIME_IDSL_ARRAY[i],para); chunk.setUnderline(0.1f, -1f); document.add(chunk); document.add(new Chunk(lineSeparator)); document.add(Chunk.NEWLINE); } //段落2 chunk = new Chunk(" 整改期间,你单位应当采取措施,确保安全生产。对安全生产违法行为,将依法予以行政处罚。",para); document.add(chunk); document.add(Chunk.NEWLINE); //段落3 chunk = new Chunk(" 如果不服从本指令,可以依法在60日内向南京市人民政府或者江苏省应急管理厅申请行政复议,或者在6个月内依法向",para); document.add(chunk); chunk = new Chunk("南京铁路运输法院",para); chunk.setUnderline(0.1f, -1f); document.add(chunk); chunk = new Chunk("提起行政诉讼,但本指令不停止执行,法律另有规定的除外。",para); document.add(chunk); document.add(Chunk.NEWLINE); PdfContentByte cb = writer.getDirectContent(); BaseFont bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); if (!WITNESS_SIGH.equals("")){ cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "见证人(签名):", 25f, 150f, 0); cb.endText(); } cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "被检查单位现场负责人(签名):", 25f, 200f, 0); cb.endText(); cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "检查人1(签名):", 25f, 300f, 0); cb.endText(); cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "检查人2(签名):", 25f, 250f, 0); cb.endText(); /*cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "证号:", 320f, 300f, 0); cb.endText(); cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, CARD_NUMBER, 360f, 300f, 0); cb.endText(); if(!CARD_NUMBER2.equals("")){ cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, CARD_NUMBER2, 450f, 300f, 0); cb.endText(); }*/ String inscribe="";//'宁','江北', '玄', '秦','建','鼓','栖','经开','雨','江','浦','六','溧','高' if (AREA.equals("宁")) { inscribe=""; } else if (AREA.equals("江北")) { inscribe="南京市江北新区应急管理局"; } else if (AREA.equals("玄")) { inscribe="南京市玄武区应急管理局"; }else if (AREA.equals("秦")) { inscribe="南京市秦淮区应急管理局"; }else if (AREA.equals("建")) { inscribe="南京市建邺区应急管理局"; }else if (AREA.equals("鼓")) { inscribe="南京市鼓楼区应急管理局"; }else if (AREA.equals("栖")) { inscribe="南京市栖霞区应急管理局"; }else if (AREA.equals("经开")) { inscribe="南京市经济开发区应急管理局"; }else if (AREA.equals("雨")) { inscribe="南京市雨花台区应急管理局"; }else if (AREA.equals("江")) { inscribe="南京市江宁区应急管理局"; }else if (AREA.equals("浦")) { inscribe="南京市浦口区应急管理局"; }else if (AREA.equals("六")) { inscribe="南京市六合区应急管理局"; }else if (AREA.equals("溧")) { inscribe="南京市溧水区应急管理局"; }else if (AREA.equals("高")) { inscribe="南京市高淳区应急管理局"; } cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, inscribe, 390f, 110f, 0); cb.endText(); //时间 cb = writer.getDirectContent(); bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, CHECKED_START_TIME, 470f, 90f, 0); cb.endText(); if(AREA.equals("宁")){ //印章图片 Image image = Image.getInstance ( "C:/zfbdmoban/images/zz.png" ); image.setAbsolutePosition ( 400f, 70f ); image.scaleAbsolute ( 140, 140 ); document.add ( image ); } //检查人员签名图片 for(int i=0;i<CHECKE_SIGH_ARRAY.length;i++){ Image image1 = Image.getInstance(url+CHECKE_SIGH_ARRAY[i]); image1.setAbsolutePosition(220f+105*i, 290f); //Scale to new height and new width of image image1.scaleAbsolute(48, 48); //Add to document document.add(image1); PdfContentByte cb4 = writer.getDirectContent(); BaseFont bf2= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb4.beginText(); cb4.setFontAndSize(bf2, 12); cb4.showTextAligned(PdfContentByte.ALIGN_LEFT, "证号:"+CARD_NUMBER1, 350f, 300-40*i, 0); cb4.endText(); } for(int i=0;i<CHECKE_TWO_SIGH_ARRAY.length;i++){ Image image1 = Image.getInstance(url+CHECKE_TWO_SIGH_ARRAY[i]); image1.setAbsolutePosition(220f+105*i, 240f); //Scale to new height and new width of image image1.scaleAbsolute(48, 48); //Add to document document.add(image1); PdfContentByte cb4 = writer.getDirectContent(); BaseFont bf2= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); cb4.beginText(); cb4.setFontAndSize(bf2, 12); cb4.showTextAligned(PdfContentByte.ALIGN_LEFT, "证号:"+CARD_NUMBER2, 350f, 250-40*i, 0); cb4.endText(); } //专家签名图片 // for(int i=0;i<2;i++){ // Image image1 = Image.getInstance(url+"1554599827797.png"); // //Fixed Positioning // image1.setAbsolutePosition(400f+105*i, 150f); // //Scale to new height and new width of image // image1.scaleAbsolute(48, 48); // //Add to document // document.add(image1); // } //被检查人单位现场负责人签名图片 for(int i=0;i<REPRESENR_SIGN_ARRAY.length;i++){ Image image1 = Image.getInstance(url+REPRESENR_SIGN_ARRAY[i]); //Fixed Positioning image1.setAbsolutePosition(220f+105*i, 180f); //Scale to new height and new width of image image1.scaleAbsolute(48, 48); //Add to document document.add(image1); } if (!WITNESS_SIGH.equals("")){ //见证人签名图片 for(int i=0;i<JIANZHENG_SIGH_ARRAY.length;i++){ Image image1 = Image.getInstance(url+JIANZHENG_SIGH_ARRAY[i]); //Fixed Positioning image1.setAbsolutePosition(140f+105*i, 150f); //Scale to new height and new width of image image1.scaleAbsolute(48, 48); //Add to document document.add(image1); } } document.newPage(); //地址 paragraph=new Paragraph("",para); paragraph.setLeading(20f); document.add(paragraph); //表格 PdfPTable table=new PdfPTable(2); table.setTotalWidth(new float[]{100,500}); for(int i=0;i<selectedArray.length;i++){ table.addCell(getPDFCell("√",para,Element.ALIGN_CENTER,Element.ALIGN_MIDDLE)); table.addCell(getPDFCell(selectedArray[i],para,Element.ALIGN_LEFT,Element.ALIGN_MIDDLE)); } for(int i=0;i<unselectedArray.length;i++){ table.addCell(getPDFCell("",para,Element.ALIGN_CENTER,Element.ALIGN_MIDDLE)); table.addCell(getPDFCell(unselectedArray[i],para,Element.ALIGN_LEFT,Element.ALIGN_MIDDLE)); } //预览二维码 String content=pdfAbsolutePath+pdfName; String qrCodeName=date1+"/"+nowTime+ random+".png"; try{ Map<EncodeHintType, Object> hints = new HashMap<> (); //编码 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //边框距 hints.put(EncodeHintType.MARGIN, 0); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bm = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 199, 199, hints); Path file=new File(qrCodePath+qrCodeName).toPath(); MatrixToImageWriter.writeToPath(bm, "png", file); }catch (Exception e){ System.out.println ( e.toString () ); e.printStackTrace(); logger.info ( e.toString () ); } pdfThreeDal.updatePdfAndQrcode(pdfName,qrCodeName,ID); } catch (FileNotFoundException e) { e.printStackTrace(); logger.info ( e.toString () ); return MsgUtil.errorMsg(e.toString()); } catch (DocumentException e) { e.printStackTrace(); logger.info ( e.getLocalizedMessage () ); return MsgUtil.errorMsg(e.toString()); } finally { document.close(); } return MsgUtil.successMsg(); } public static PdfPCell getPDFCell(String string, Font font, int HorizontalAlignment, int VerticalAlignment) { //创建单元格对象,将内容与字体放入段落中作为单元格内容 PdfPCell cell=new PdfPCell(new Paragraph(string,font)); cell.setHorizontalAlignment(HorizontalAlignment); cell.setVerticalAlignment(VerticalAlignment); //设置最小单元格高度 //cell.setMinimumHeight(25); return cell; } }
true
e304443cc0bf73647102b6fab5e3f55c5234649a
Java
leapframework/framework
/base/lang/src/main/java/leap/lang/value/Page.java
UTF-8
3,076
2.78125
3
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
/* * Copyright 2013 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 leap.lang.value; import leap.lang.tostring.ToStringBuilder; public class Page extends Limit { /** * Creates a new {@link Page} instance of the given limit size. * * @param size the limit size, starts from 1. * * @see #startFrom(int, int) */ public static Page limit(int size){ return startFrom(1, size); } /** * Creates a new {@link Page} instance of the given limit size and starts from offset. * * <p/> * The offset is starts from 0. */ public static Page limit(int limit, int offset) { return startFrom(offset + 1, limit); } /** * Creates a new {@link Page} instance from the given start row index. * * @param start the start index , starts from 1. * @param size the page size, starts from 1. */ public static Page startFrom(int start,int size){ int index = start < size ? 1 : start / size; int end = start + size - 1; return new Page(index,size,start,end); } /** * Creates a new {@link Page} instance with the start and end row index. */ public static Page startEnd(int start,int end) { return startFrom(start, end - start + 1); } /** * Creates a new {@link Page} instance of the given page index and size. * * @see #Page(int, int) */ public static Page indexOf(int index, int size){ return new Page(index,size); } protected final int index; protected final int size; /** * Creates a new {@link Page} instance use the given page index and page size. * * @param index page index,start from 1 * @param size page size,start from 1 */ public Page(int index,int size){ super((index - 1) * size + 1,size * index); this.index = index; this.size = size; } protected Page(int index,int size,int start,int end){ super(start,end); this.index = index; this.size = size; } /** * Returns page index, starts from 1. */ public int getIndex(){ return index; } /** * Returns page size, starts form 1. */ public int getSize(){ return size; } @Override public String toString() { return new ToStringBuilder(this) .append("index", index) .append("size",size) .append("start",start) .append("end",end) .toString(); } }
true
cf5cebeabf1b46bce64325a848420d286e8f3d4f
Java
asatulsinha4/interviewbit-solutions
/Tree Data Structure/2-Sum Binary Tree/2-SumBinaryTree.java
UTF-8
1,397
3.703125
4
[]
no_license
/* Given a binary search tree T, where each node contains a positive integer, and an integer K, you have to find whether or not there exist two different nodes A and B such that A.value + B.value = K. Return 1 to denote that two such nodes exist. Return 0, otherwise. Notes Your solution should run in linear time and not take memory more than O(height of T). Assume all values in BST are distinct. Example : Input 1: T : 10 / \ 9 20 K = 19 Return: 1 Input 2: T: 10 / \ 9 20 K = 40 Return: 0 */ /** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public ArrayList<Integer> t = new ArrayList<>(); public int t2Sum(TreeNode A, int B) { inOrder(A); Collections.sort(t); int l=0 , r = t.size()-1; while(l<r){ int sum = t.get(l) + t.get(r); if(sum == B) return 1; if(sum < B){ l++; }else{ r--; } } return 0; } public void inOrder(TreeNode root){ if(root!=null){ inOrder(root.left); t.add(root.val); inOrder(root.right); } } }
true
88cd3e2bcec0be298a40c5d2cef35a5a39dbdc79
Java
fillipiv/aulasjava
/aula04/exercicios/exercicio03/Veiculo.java
UTF-8
568
3.546875
4
[]
no_license
package exercicios.exercicio03; public class Veiculo { private String modelo; private String marca; private double consumo; public Veiculo(String modelo, String marca, double consumo){ this.modelo = modelo; this.marca = marca; this.consumo = consumo; } public void carro(){ System.out.println("Carro é um "+ modelo +" da marca " + marca + "."); } void consumo(){ System.out.printf("Seu consumo é de %.2f km/L.\n", consumo); } //double consumo(){ // return consumo; //} }
true
d7fddf076e9cc378ae0088fe42e870fa9110efdf
Java
kohry/Backjoon-Algo
/11657.java
UTF-8
2,186
3.28125
3
[]
no_license
package b11657; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static int N; static int M; static int INF = 200000000; static ArrayList<ArrayList<City>> list = new ArrayList<>(); static int[] dist = new int[501]; public static void main(String[] args) throws Throwable { System.setIn(new FileInputStream("11657.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); for (int i = 0; i <= M; i++) { list.add(new ArrayList<City>()); } for (int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); list.get(a).add(new City(a, b, c)); } boolean minus = false; Arrays.fill(dist, INF); dist[0] = 0; dist[1] = 0; for (int i = 0; i < N; i++) { for (int j = 1; j < N; j++) { for (City city : list.get(j)) { int next = city.b; int d = city.c; if (dist[j] != INF && dist[next] > dist[j] + d) { dist[next] = dist[j] + d; if (i == N - 1) minus = true; } } } } if(minus) System.out.println("-1"); else { for (int i = 2; i <= N; i++) { System.out.printf("%d\n", dist[i] != INF ? dist[i] : -1); } } } } class City { int a; int b; int c; public City(int a, int b, int c) { super(); this.a = a; this.b = b; this.c = c; } }
true
c2cb1348c6a33d7afe28820e0e32aae6e171cc1c
Java
johnfourpeople/numbusterWeatherTest
/app/src/main/java/com/test/jb/numbusterweathertest/Network/AsyncForecastConnection.java
UTF-8
4,405
2.40625
2
[]
no_license
package com.test.jb.numbusterweathertest.Network; import android.content.ContentValues; import android.os.AsyncTask; import android.util.Log; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.test.jb.numbusterweathertest.Database.Contract; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by JB on 18.09.2015. */ public class AsyncForecastConnection extends AsyncTask<Void,Void,List<ContentValues>> { private final static String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?units=metric&count=16&lang=ru&q="; private List<String> mCityNames = new ArrayList<>(); private ForecastResponseHandler mHandler; public AsyncForecastConnection(ForecastResponseHandler handler, String cityName) { mCityNames.add(cityName); mHandler = handler; } public AsyncForecastConnection(ForecastResponseHandler handler,List<String> cityNames) { mCityNames.addAll(cityNames); mHandler = handler; } @Override protected List<ContentValues> doInBackground(Void... params) { List<ContentValues> data = new ArrayList<>(); try { for (String city : mCityNames) { URL url = new URL(BASE_URL + URLEncoder.encode(city, "UTF-8")); HttpURLConnection connection = (HttpURLConnection) (url).openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); StringBuffer buffer = new StringBuffer(); InputStream stream; stream = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); String line = null; while ((line = br.readLine()) != null){ buffer.append(line + "\r\n"); } JsonParser parser = new JsonParser(); JsonElement root = parser.parse(buffer.toString()); if(root.isJsonObject()) { if (root.getAsJsonObject().get("cod").getAsInt() == 200) { int cityId = root.getAsJsonObject().get("city").getAsJsonObject().get("id").getAsInt(); Iterator<JsonElement> iterator = root.getAsJsonObject().get("list").getAsJsonArray().iterator(); while(iterator.hasNext()) { JsonElement item = iterator.next(); int dt = item.getAsJsonObject().get("dt").getAsInt(); JsonObject weather = item.getAsJsonObject().get("weather").getAsJsonArray().get(0).getAsJsonObject(); String descr = weather.get("description").getAsString(); int humidity = item.getAsJsonObject().get("humidity").getAsInt(); int temp = item.getAsJsonObject().get("temp").getAsJsonObject().get("day").getAsInt(); ContentValues cv = new ContentValues(); cv.put(Contract.Weather.TEMPERATURE, temp); cv.put(Contract.Weather.HUMIDITY, humidity); cv.put(Contract.Weather.DESCRIPTION, descr); cv.put(Contract.Weather.DATE, dt); cv.put(Contract.Weather.CITY_ID, cityId); cv.put(Contract.City._ID, cityId); cv.put(Contract.City.NAME, city); data.add(cv); } } else { Log.d("error", root.getAsJsonObject().get("message").getAsString()); } } } } catch (IOException e) { e.printStackTrace(); } return data; } @Override protected void onPostExecute(List<ContentValues> contentValues) { super.onPostExecute(contentValues); mHandler.handleResponse(contentValues); } }
true
1472c7e81f3aac31e200e07c5aa4fa02889caf26
Java
a2en/Zenly_re
/src/app.zenly.locator_4.8.0_base_source_from_JADX/sources/com/google/common/collect/C10899m0.java
UTF-8
449
1.96875
2
[]
no_license
package com.google.common.collect; import java.util.ListIterator; /* renamed from: com.google.common.collect.m0 */ public abstract class C10899m0<E> extends C10897l0<E> implements ListIterator<E> { protected C10899m0() { } @Deprecated public final void add(E e) { throw new UnsupportedOperationException(); } @Deprecated public final void set(E e) { throw new UnsupportedOperationException(); } }
true
7f6efdbfeea228078004bd00f36cacbbd1781ad6
Java
piotrgiedziun/university
/java_xml/lab9/src/task1/controller/MainController.java
UTF-8
1,087
2.640625
3
[ "MIT" ]
permissive
package task1.controller; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; 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 task1.model.Host; @WebServlet("/") public class MainController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Host.hosts.clear(); Host.hosts.add(new Host("localhost", "127.0.0.1", "Piotr")); Host.hosts.add(new Host("google.com", "173.194.65.139", "Bob")); Host host = new Host(request.getRemoteHost(), request.getRemoteAddr()); if(!Host.hosts.contains(host)) Host.hosts.add(host); request.setAttribute("hostsList", Host.hosts); RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp"); rd.forward(request, response); } }
true
54a167dfd6bc717a4befc00dc9e5d907eb38e9a8
Java
veev520/AndLua
/app/src/main/java/club/veev/andluademo/entity/Test1.java
UTF-8
743
2.640625
3
[]
no_license
package club.veev.andluademo.entity; public class Test1 { private String title; private String subTitle; private String content; public Test1(String title, String subTitle, String content) { this.title = title; this.subTitle = subTitle; this.content = content; } @Override public String toString() { return "Test1{" + "title='" + title + '\'' + ", subTitle='" + subTitle + '\'' + ", content='" + content + '\'' + '}'; } public String getTitle() { return title; } public String getSubTitle() { return subTitle; } public String getContent() { return content; } }
true
fa645d94edf41d1bde1e1ebed9ecb08a166d60d9
Java
pfista/Curfew
/Curfew/src/main/java/com/curfew/CurfewQueryAdapter.java
UTF-8
2,195
2.078125
2
[]
no_license
package com.curfew; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.parse.GetCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQueryAdapter; import com.parse.ParseUser; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by pfister on 11/24/13. */ public class CurfewQueryAdapter<T> extends ParseQueryAdapter { private final String TAG = "com.curfew.adapter"; public CurfewQueryAdapter(Context context, QueryFactory queryFactory) { super(context, queryFactory); } @Override public View getItemView(ParseObject object, View v, ViewGroup parent) { View vi = v; if (vi == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); vi = inflater.inflate(R.layout.curfewtextview, null); } Date dateTime = (Date) object.get("Curfew"); DateFormat df = new SimpleDateFormat("hh:mm"); final String time = df.format(dateTime); final TextView text = (TextView) vi.findViewById(R.id.curfew_item_text); final ImageView image = (ImageView) vi.findViewById(R.id.curfew_item_image); object.getParseUser("toUser").fetchIfNeededInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject parseObject, ParseException e) { if (e == null) { ParseUser user = (ParseUser) parseObject; int hour = Integer.parseInt(time.split(":")[0]); int minute = Integer.parseInt(time.split(":")[1]); // Create appropriate clock drawables here ClockDrawable cd = new ClockDrawable(40, R.color.black); cd.setTime(hour, minute, 0); image.setBackground(cd); text.setText(user.getString("username")); } } }); return vi; } }
true
2eaa0e4c723200ae622100755a49001dfcd5fb2e
Java
jensen-liu/jeeProject
/JeeProject/src/main/java/com/jensen/jeeproject/system/service/PermissionService.java
UTF-8
517
1.804688
2
[]
no_license
package com.jensen.jeeproject.system.service; import java.util.List; import com.jensen.jeeproject.common.exception.ServiceException; import com.jensen.jeeproject.system.entity.Permission; public interface PermissionService { Permission getPermById(String id); List<Permission> getList(); List<Permission> getListByRole(); int insert(Permission perm) throws ServiceException; int update(Permission perm) throws ServiceException;; int delete(String id) throws ServiceException;; }
true
27e49aaaa2fe180c9991ef7bfb14d958d9fe611b
Java
bellmit/AyjrFiance
/src/main/java/com/hengxin/platform/fund/service/FinancierBreachFundClearingService.java
UTF-8
2,347
1.992188
2
[]
no_license
package com.hengxin.platform.fund.service; import java.math.BigDecimal; import java.util.Date; import java.util.List; import com.hengxin.platform.common.exception.BizServiceException; import com.hengxin.platform.fund.dto.biz.req.atom.FreezeReq; import com.hengxin.platform.fund.dto.biz.req.atom.TransferInfo; import com.hengxin.platform.fund.dto.biz.req.atom.UnFreezeReq; import com.hengxin.platform.fund.dto.biz.req.atom.UnReserveReq; import com.hengxin.platform.fund.exception.AvlBalNotEnoughException; /** * FinancierBreachFundClearingService. * */ public interface FinancierBreachFundClearingService { /** * 查询会员子账户可用余额(忽略冻结金额,适用于违约还款场景). * * @param userId * @param subAcctType * @return * @throws BizServiceException */ BigDecimal getUserCurrentAvlAmtIgnoreFrzAmt(String userId, boolean isAddXwb) throws BizServiceException; /** * 退还借款履约保证金. * @param req * @return * @throws BizServiceException */ BigDecimal refundLoadnHonourAgtDeposit(UnReserveReq req)throws BizServiceException; /** * 还款违约资金解冻. * @param req * @return * @throws BizServiceException */ BigDecimal unFreezeLateFee(UnFreezeReq req)throws BizServiceException; /** * 冻结欠款金额. * @param req * @return * @throws BizServiceException */ String freezeArrearageAmt(FreezeReq req)throws BizServiceException; /** * 违约还款,资金清分. * * @param eventId * @param payerList * @param payeeList * @param isAddXwbPay * @param bizId * @param currOpId * @param workDate * @throws AvlBalNotEnoughException * @throws BizServiceException */ void breachRepaymentFundClearing(String eventId, List<TransferInfo> payerList, List<TransferInfo> payeeList, boolean isAddXwbPay, String bizId, String pkgId, String seqId, String currOpId, Date workDate)throws BizServiceException, AvlBalNotEnoughException; /** * 投资人付利息、罚金收益部分金额给平台. * @param eventId * @param payerList * @param exchangePayee * @param bizId * @param currOpId * @param workDate */ void payInvsIntrProfitToExchange(String eventId, List<TransferInfo> payerList, List<TransferInfo> payeeList, String bizId, String pkgId, String seqId, String currOpId, Date workDate); }
true
81af37ef9e8f34d43e327a85f69830c3bb6fc9cc
Java
Winely/ElecTongji
/app/src/main/java/me/donggu/electongji/LoucengActivity.java
UTF-8
4,090
2.015625
2
[]
no_license
package me.donggu.electongji; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import me.donggu.model.ListItem; import me.donggu.model.ListIthemAdapter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; public class LoucengActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_louceng); loucengView = (ListView)findViewById(R.id.list_louceng); viewState = getIntent().getStringExtra("viewState"); try { viewState= URLEncoder.encode(viewState, "gb2312"); }catch (IOException e){ e.printStackTrace(); } postBody = "__EVENTTARGET=" + "&__VIEWSTATE="+viewState + "&drlouming="+getIntent().getStringExtra("xiaoqu") + "&drceng="+getIntent().getStringExtra("loudong"); new Thread(getLouceng).start(); loucengView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent = new Intent(FANGJIAN); intent.putExtra("viewState",viewState); intent.putExtra("louceng", loucengList.get(i).getValue()); intent.putExtra("url", getIntent().getStringExtra("url")); intent.putExtra("xiaoqu", getIntent().getStringExtra("xiaoqu")); intent.putExtra("loudong",getIntent().getStringExtra("loudong")); startActivity(intent); } }); } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==LOUDONG){ loucengView.setAdapter(loucengAdapter); } } }; private Runnable getLouceng = new Runnable() { @Override public void run() { try{ Document doc = Jsoup.connect(getIntent().getStringExtra("url")) .requestBody(postBody) .post(); Element element = doc.select("#dr_ceng").first(); for(Element e:element.children()){ if(e.hasAttr("selected"))continue; loucengList.add(new ListItem(e.val(),e.text())); } viewState = doc.select("#__VIEWSTATE").first().val(); }catch (IOException e){ e.printStackTrace(); } if(loucengList.isEmpty()){ Intent intent = new Intent(FANGJIAN); intent.putExtra("viewState",viewState); intent.putExtra("louceng", ""); intent.putExtra("url", getIntent().getStringExtra("url")); intent.putExtra("xiaoqu", getIntent().getStringExtra("xiaoqu")); intent.putExtra("loudong",getIntent().getStringExtra("loudong")); startActivity(intent); Log.d("Louceng", "没有楼层"); } else{ loucengAdapter = new ListIthemAdapter( LoucengActivity.this, R.layout.list_item_layout, loucengList); handler.sendEmptyMessage(LOUDONG); } } }; private ListView loucengView; private ArrayList<ListItem> loucengList = new ArrayList<>(); private ListIthemAdapter loucengAdapter; private final String FANGJIAN = "me.donggu.electongji.FANGJIAN"; private final int LOUDONG = 2; private String postBody; private String viewState=""; private String loucengValue; }
true
77b480481ee08ca0db02dc4794fa5b2ca2a31f93
Java
lennerd/TwitterGraph
/src/com/lennerd/processing/twitter_graph/status_collector/request/AbstractRequest.java
UTF-8
456
2.125
2
[ "MIT" ]
permissive
package com.lennerd.processing.twitter_graph.status_collector.request; import com.lennerd.processing.twitter_graph.status_collector.DataCollector; abstract public class AbstractRequest implements Request { protected DataCollector dataCollector; public AbstractRequest(DataCollector dataCollector) { this.dataCollector = dataCollector; } @Override public String getName() { return this.getClass().getName(); } }
true
9fea532de3aa3c294a64419ee8c0841861702256
Java
julioarriagada82/springboot-proyecto-final
/src/main/java/my/condominium/service/IIntegranteService.java
UTF-8
289
1.765625
2
[]
no_license
package my.condominium.service; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import my.condominium.model.Integrante; public interface IIntegranteService extends ICRUD<Integrante> { Page<Integrante> listarPageable(Pageable pageable); }
true
ec54e50deda036a7ce5dc790a46dc72374ef874f
Java
rahulaga/irahul.com
/xst/xst01/com/irahul/XST/XSTConstants.java
UTF-8
4,480
2.25
2
[]
no_license
/* * XML Schema Tree * * Copyright (c) 2002 Rahul * All rights reserved. * http://www.irahul.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.irahul.XST; /** * XML Schema Tree Constants, Document describes current implementation * restrictions. All cases for all objects are NOT supported. * @author Rahul * @version Since v0.1 * */ public class XSTConstants { //Node //these represent the structures curently understood /** Annotation - can occur in almost any tag */ public static final int TYPE_ANNOTATION = 0; /** Only in Annotaion */ public static final int TYPE_APPINFO = 1; /** Global -> Schema and Local -> Currently in attributeGroup and Complex Type */ public static final int TYPE_ATTRIBUTE = 2; /** Global -> Currently in Schema and * Local -> Currently in Complex Type */ public static final int TYPE_ATTRIBUTE_GROUP = 3; /** Global -> Currently in Schema and Local -> Element */ public static final int TYPE_COMPLEX = 4;//local and global /** In annotation only */ public static final int TYPE_DOCUMENTATION = 5; /** Global -> Schema and Local -> Currently sequence */ public static final int TYPE_ELEMENT = 6;//local and global /** Facet, Currently in simple type restriction */ public static final int TYPE_ENUMERATION = 7; /** Simple Type only */ public static final int TYPE_RESTRICTION = 8; /** MUST! */ public static final int TYPE_SCHEMA = 9; /** Currently in Complex Type only */ public static final int TYPE_SEQUENCE = 10; /** Global -> Currently Schema and Local -> Currently * attribute, element */ public static final int TYPE_SIMPLE = 11; //Attr //these are used to identify node attrs like minOccurs, name, type etc // public static final int ATTR_NAME = 1001; public static final int ATTR_TYPE = 1002; public static final int ATTR_MINOCCURS = 1003; public static final int ATTR_MAXOCCURS = 1004; public static final int ATTR_REF = 1005; public static final int ATTR_DEFAULT = 1006; public static final int ATTR_XMLNS = 1007; public static final int ATTR_VALUE = 1008; public static final int ATTR_BASE = 1009; // Data // these are the datatypes, a valid datatype would have // to be one of these //PRIMITIVES public static final int DATA_STRING = 2001; public static final int DATA_BOOLEAN = 2002; public static final int DATA_BASE64BINARY = 2003; public static final int DATA_HEXBINARY = 2004; public static final int DATA_FLOAT = 2005; public static final int DATA_DECIMAL = 2006; public static final int DATA_DOUBLE = 2007; public static final int DATA_ANYURI = 2008; public static final int DATA_QNAME = 2009; public static final int DATA_NOTATION = 2010; public static final int DATA_DURATION = 2011; public static final int DATA_DATETIME = 2012; public static final int DATA_TIME = 2013; public static final int DATA_DATE = 2014; public static final int DATA_GYEARMONTH = 2015; public static final int DATA_GYEAR = 2016; public static final int DATA_GMONTHDAY = 2017; public static final int DATA_GDAY = 2018; public static final int DATA_GMONTH = 2019; //DERIVED //note that values same as base primitive }
true
2e17eb6c925a2708331cdc4774b6df3a827a6f58
Java
avaness/hoolah.co-challenge-java
/src/main/java/co/hoolah/challenge_java/CliProcessor.java
UTF-8
2,660
2.78125
3
[]
no_license
package co.hoolah.challenge_java; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.time.LocalDateTime; import java.time.format.DateTimeParseException; import java.util.concurrent.Callable; import picocli.CommandLine.Command; import picocli.CommandLine.ITypeConverter; import picocli.CommandLine.Option; import picocli.CommandLine.TypeConversionException; /** * Main CLI processor and business app runner */ @Command(mixinStandardHelpOptions = true, version = "version 0.1", description = "Prints transactions statistic for csv stdin stream") public class CliProcessor implements Callable<Integer> { @Option(names = {"-f", "--file"}, description = ".csv fileStream with transactions", converter = FileStreamConverter.class) InputStream file; @Option(names= "--fromDate", required =true, description = "'" + Formatter.DATE_TIME_FORMAT + "' format", converter = TimeConverter.class) LocalDateTime from; @Option(names = "--toDate", required = true, description = "'" + Formatter.DATE_TIME_FORMAT + "' format", converter = TimeConverter.class) LocalDateTime to; @Option(names = "--merchant", required = true, description = "merchant name") String merchant; private HoolahApp hoolahApp; CliProcessor(HoolahApp hoolahApp) { this.hoolahApp = hoolahApp; } public Integer call() throws IOException { InputStream csvStream = file == null? System.in: file; TxStatistic stats = hoolahApp.execute(csvStream, from, to, merchant); System.out.println(String .format("Number of transactions: %d\nAverage Transaction Value: %.2f\n", stats.transactions, stats.avgValue)); return 0; } private static class TimeConverter implements ITypeConverter<LocalDateTime> { @Override public LocalDateTime convert(String value) throws Exception { try { return LocalDateTime.parse(value, Formatter.DATE_TIME); } catch (DateTimeParseException e) { throw new TypeConversionException(String.format("bad format %s, should be %s", value, Formatter.DATE_TIME_FORMAT)); } } } private static class FileStreamConverter implements ITypeConverter<InputStream> { @Override public InputStream convert(String value) throws Exception { try { return new BufferedInputStream(new FileInputStream(value)); } catch (FileNotFoundException e) { throw new TypeConversionException(String.format("bad fileStream name '%s'", value)); } } } }
true
619ee0094512b0b03bdfbe00a66da32bf006a8d0
Java
AutoGraphQL/APIJSON
/APIJSONORM/src/main/java/apijson/orm/Operation.java
UTF-8
2,537
2.859375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. This source code is licensed under the Apache License Version 2.0.*/ package apijson.orm; /**对请求 JSON 的操作 * @author Lemon */ public enum Operation { /** * 必须传的字段,结构是 * "key0,key1,key2..." */ MUST, /** * 不允许传的字段,结构是 * "key0,key1,key2..." */ REFUSE, /**TODO 是否应该把数组类型写成 BOOLEANS, NUMBERS 等复数单词,以便抽取 enum ?扩展用 VERIFY 或 INSERT/UPDATE 远程函数等 * 验证是否符合预设的类型: * BOOLEAN, NUMBER, DECIMAL, STRING, URL, DATE, TIME, DATETIME, OBJECT, ARRAY * 或它们的数组 * BOOLEAN[], NUMBER[], DECIMAL[], STRING[], URL[], DATE[], TIME[], DATETIME[], OBJECT[], ARRAY[] * 结构是 * { * key0: value0, * key1: value1, * key2: value2 * ... * } * 例如 * { * "id": "NUMBER", //id 类型必须为 NUMBER * "pictureList": "URL[]", //pictureList 类型必须为 URL[] * } * @see {@link AbstractVerifier#verifyType(String, String, Object, boolean)} */ TYPE, /** * 验证是否符合预设的条件,结构是 * { * key0: value0, * key1: value1, * key2: value2 * ... * } * 例如 * { * "phone~": "PHONE", //phone 必须满足 PHONE 的格式,配置见 {@link AbstractVerifier#COMPILE_MAP} * "status{}": [1,2,3], //status 必须在给出的范围内 * "balance&{}":">0,<=10000" //必须满足 balance>0 & balance<=10000 * } */ VERIFY, /**TODO 格式改为 id;version,tag 兼容多个字段联合主键。 ["id", "version,tag"] 也行 * 验证是否存在,结构是 * "key0,key1,key2..." */ EXIST, /**TODO 格式改为 id;version,tag 兼容多个字段联合主键。 ["id", "version,tag"] 也行 * 验证是否不存在,除了本身的记录,结构是 * "key0,key1,key2..." */ UNIQUE, /** * 添加,当要被添加的对象不存在时,结构是 * { * key0: value0, * key1: value1, * key2: value2 * ... * } */ INSERT, /** * 强行放入,不存在时就添加,存在时就修改,结构是 * { * key0: value0, * key1: value1, * key2: value2 * ... * } */ UPDATE, /** * 替换,当要被替换的对象存在时,结构是 * { * key0: value0, * key1: value1, * key2: value2 * ... * } */ REPLACE, /** * 移除,当要被移除的对象存在时,结构是 * "key0,key1,key2..." */ REMOVE; }
true
facd2e8f7da771b66112766336cd00fa7e665f18
Java
YamidDev/multi-tenancy-oauth
/src/main/java/com/yamidev/multitenancy/security/UserTenantInformation.java
UTF-8
322
1.625
2
[]
no_license
package com.yamidev.multitenancy.security; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.HashMap; import java.util.Map; @Data @NoArgsConstructor @AllArgsConstructor public class UserTenantInformation { private Map<String, String> map = new HashMap<>(); }
true
b4a56e2318e9faffc608f73b9d53e3e27ae61fc9
Java
whl-1998/JavaStudyFromWhl
/src/com/whl/dataStructuresAndAlgorithms/dfsAndBfs/InvertBinaryTree.java
UTF-8
1,636
4.0625
4
[]
no_license
package com.whl.dataStructuresAndAlgorithms.dfsAndBfs; import com.whl.dataStructuresAndAlgorithms.TreeNode; import java.util.LinkedList; import java.util.Queue; /** * @author whl * @version V1.0 * @Title: 226. 翻转二叉树 * @Description: easy */ public class InvertBinaryTree { /** * 1. 递归 * 思路:将root.left指向递翻转之后的right节点, root.right指向指向翻转之后的left节点 * 时间复杂度:O(n) * 空间复杂度:O(1) * 执行用时:0ms * @param root * @return */ public TreeNode invertTree1(TreeNode root) { if (root == null) return root; TreeNode left = root.left; TreeNode right = root.right; root.left = invertTree1(right); root.right = invertTree1(left); return root; } /** * 2. BFS * 思路:按层遍历, 把当前层的所有节点的左右子树交换 * 时间复杂度:O(n) * 空间复杂度:O(1) * 执行用时:0ms * @param root * @return */ public TreeNode invertTree2(TreeNode root) { if (root == null) return null; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode curr = queue.poll(); TreeNode leftTemp = curr.left; curr.left = curr.right; curr.right = leftTemp; if (curr.left != null) { queue.offer(curr.left); } if (curr.right != null) { queue.offer(curr.right); } } return root; } }
true
47f9cd41b15c27568b660eb1755687b028a58cff
Java
Crush-on-IT/algorithm-study
/src/Dynamic Programming/12865_평범한배낭/백준_12865_평범한배낭2_saeumi.java
UTF-8
1,072
3.171875
3
[]
no_license
package Dynamic_programming; import java.io.*; import java.util.*; public class 백준_12865_평범한배낭2_saeumi { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); // 물품의 수 int K = Integer.parseInt(st.nextToken()); // 준서가 버틸수 있는 무게 int arr[][] = new int[N + 1][K + 1]; int W[] = new int[N + 1]; int V[] = new int[N + 1]; for (int i = 1; i <= N; i++) { st = new StringTokenizer(br.readLine()); W[i] = Integer.parseInt(st.nextToken()); // 각 물건의 무게 V[i] = Integer.parseInt(st.nextToken()); // 해당 물건의 가치 } for (int i = 1; i <= N; i++) { for (int j = 1; j <= K; j++) { if (W[i] > j) { arr[i][j] = arr[i - 1][j]; } else { arr[i][j] = Math.max(arr[i - 1][j], arr[i - 1][j - W[i]] + V[i]); } } } System.out.println(arr[N][K]); } }
true
a3119e0aa0e74e781284f0d4fb758a649b50e56d
Java
njmube/CSE_PL-SQL
/RastreoMx/src/touchesbegan/rastreomx/database/MySQLiteHelper.java
UTF-8
3,588
2.53125
3
[]
no_license
package touchesbegan.rastreomx.database; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class MySQLiteHelper extends SQLiteOpenHelper { public static final String TABLE_PAQUETES = "paquetes"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_CLAVE = "clave"; public static final String COLUMN_ORIGEN = "origen"; public static final String COLUMN_DESTINO = "destino"; public static final String COLUMN_FECHA = "fecha"; public static final String COLUMN_SITUACION = "situacion"; public static final String COLUMN_RECIBIO = "recibio"; public static final String COLUMN_PAQUETERIA ="paqueteria"; public static final String DATABASE_NAME = "paquetes.db"; public static final int DATABASE_VERSION = 3; public static final String DATABASE_CREATE = "create table " + TABLE_PAQUETES + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_CLAVE + " text, " + COLUMN_PAQUETERIA + " text, " + COLUMN_ORIGEN + " text, " + COLUMN_DESTINO + " text, " + COLUMN_FECHA + " text, " + COLUMN_SITUACION + " text, " + COLUMN_RECIBIO + " text)"; public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_PAQUETES); onCreate(db); } public List<Paquete> verTodos() { SQLiteDatabase db = getReadableDatabase(); List<Paquete> paquetes = new ArrayList<Paquete>(); String[] valores = { "_id", COLUMN_CLAVE,COLUMN_PAQUETERIA, COLUMN_ORIGEN, COLUMN_DESTINO, COLUMN_FECHA, COLUMN_SITUACION, COLUMN_RECIBIO }; Cursor c = db.query(TABLE_PAQUETES, valores, null, null, null, null, null, null); c.moveToFirst(); while (!c.isAfterLast()) { Paquete paquete = cursorToComment(c); paquetes.add(paquete); c.moveToNext(); } c.close(); db.close(); return paquetes; } private Paquete cursorToComment(Cursor cursor){ Paquete paquete= new Paquete(); paquete.setClave(cursor.getString(1)); paquete.setPaqueteria(cursor.getString(2)); paquete.setOrigen(cursor.getString(3)); paquete.setDestino(cursor.getString(4)); paquete.setFecha(cursor.getString(5)); paquete.setSituacion(cursor.getString(6)); paquete.setQuien(cursor.getString(7)); return paquete; } public void insertaPaquete(String clave,String paqueteria, String origen, String destino, String fecha, String situacion, String recibio) { SQLiteDatabase db = getWritableDatabase(); if (db != null) { ContentValues values = new ContentValues(); values.put(COLUMN_CLAVE, clave); values.put(COLUMN_PAQUETERIA, paqueteria); /*values.put(COLUMN_ORIGEN, origen); values.put(COLUMN_DESTINO, destino); values.put(COLUMN_FECHA, fecha); values.put(COLUMN_SITUACION, situacion); values.put(COLUMN_RECIBIO, recibio);*/ db.insert(TABLE_PAQUETES, null, values); } } public void deleteAll(){ SQLiteDatabase db = getWritableDatabase(); db.delete(TABLE_PAQUETES, null, null); db.close(); } }
true
a38f1dff019b18ee5758407f1fd2bd6b174041be
Java
stephengold/Minie
/MinieLibrary/src/test/java/jme3utilities/minie/test/TestClonePhysicsControls.java
UTF-8
17,426
1.648438
2
[ "BSD-3-Clause" ]
permissive
/* Copyright (c) 2018-2023, Stephen Gold All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package jme3utilities.minie.test; import com.jme3.anim.util.AnimMigrationUtils; import com.jme3.asset.AssetManager; import com.jme3.asset.DesktopAssetManager; import com.jme3.asset.ModelKey; import com.jme3.asset.plugins.ClasspathLocator; import com.jme3.bullet.RotationOrder; import com.jme3.bullet.animation.CenterHeuristic; import com.jme3.bullet.animation.DacConfiguration; import com.jme3.bullet.animation.DynamicAnimControl; import com.jme3.bullet.animation.LinkConfig; import com.jme3.bullet.animation.MassHeuristic; import com.jme3.bullet.animation.RangeOfMotion; import com.jme3.bullet.animation.ShapeHeuristic; import com.jme3.bullet.collision.shapes.SphereCollisionShape; import com.jme3.bullet.control.AbstractPhysicsControl; import com.jme3.bullet.control.BetterCharacterControl; import com.jme3.bullet.control.CharacterControl; import com.jme3.bullet.control.SoftBodyControl; import com.jme3.bullet.objects.PhysicsCharacter; import com.jme3.export.binary.BinaryExporter; import com.jme3.export.binary.BinaryLoader; import com.jme3.material.plugins.J3MLoader; import com.jme3.math.Vector3f; import com.jme3.scene.Spatial; import com.jme3.system.NativeLibraryLoader; import com.jme3.texture.plugins.AWTLoader; import jme3utilities.Heart; import org.junit.Assert; import org.junit.Test; /** * Test cloning/saving/loading abstract physics controls. * * @author Stephen Gold sgold@sonic.net */ public class TestClonePhysicsControls { // ************************************************************************* // fields /** * AssetManager required by the BinaryImporter */ final private static AssetManager assetManager = new DesktopAssetManager(); // ************************************************************************* // new methods exposed /** * Test cloning/saving/loading abstract physics controls. */ @Test public void testClonePhysicsControls() { NativeLibraryLoader.loadNativeLibrary("bulletjme", true); assetManager.registerLoader(AWTLoader.class, "jpg", "png"); assetManager.registerLoader(BinaryLoader.class, "j3o"); assetManager.registerLoader(J3MLoader.class, "j3m", "j3md"); assetManager.registerLocator(null, ClasspathLocator.class); // BetterCharacterControl float radius = 1f; float height = 3f; float mass = 1f; BetterCharacterControl bcc = new BetterCharacterControl(radius, height, mass); setParameters(bcc, 0f); verifyParameters(bcc, 0f); BetterCharacterControl bccClone = Heart.deepCopy(bcc); cloneTest(bcc, bccClone); // CharacterControl SphereCollisionShape shape = new SphereCollisionShape(2f); CharacterControl cc = new CharacterControl(shape, 0.5f); setParameters(cc, 0f); verifyParameters(cc, 0f); CharacterControl ccClone = Heart.deepCopy(cc); cloneTest(cc, ccClone); // DynamicAnimControl DynamicAnimControl dac = new DynamicAnimControl(); setParameters(dac, 0f); verifyParameters(dac, 0f); DynamicAnimControl dacClone = Heart.deepCopy(dac); cloneTest(dac, dacClone); /* * GhostControl is tested in TestCloneGhost. * RigidBodyControl and VehicleControl are tested in TestCloneBody. * * SoftBodyControl */ SoftBodyControl sbc = new SoftBodyControl(); setParameters(sbc, 0f); verifyParameters(sbc, 0f); SoftBodyControl sbcClone = Heart.deepCopy(sbc); cloneTest(sbc, sbcClone); /* * Test cloning/saving/loading abstract physics controls * that have been added to a Spatial: * * DAC without PreComposer (old animation system) */ ModelKey key = new ModelKey("Models/Jaime/Jaime.j3o"); dac = createDac(); Spatial jaime = assetManager.loadModel(key); jaime.addControl(dac); setParameters(dac, 0f); verifyParameters(dac, 0f); Spatial jaimeClone = Heart.deepCopy(jaime); cloneTest(jaime, jaimeClone); // DAC with PreComposer (new animation system) dac = createDac(); Spatial newJaime = assetManager.loadModel(key); AnimMigrationUtils.migrate(newJaime); newJaime.addControl(dac); setParameters(dac, 0f); verifyParameters(dac, 0f); Spatial newJaimeClone = Heart.deepCopy(newJaime); cloneTest(newJaime, newJaimeClone); // TODO more types: JoinedBodyControl } // ************************************************************************* // private methods private static void cloneTest(AbstractPhysicsControl control, AbstractPhysicsControl controlClone) { Assert.assertNotSame(control, controlClone); Assert.assertSame(control.getClass(), controlClone.getClass()); verifyParameters(control, 0f); verifyParameters(controlClone, 0f); setParameters(control, 0.3f); verifyParameters(control, 0.3f); verifyParameters(controlClone, 0f); setParameters(controlClone, 0.6f); verifyParameters(control, 0.3f); verifyParameters(controlClone, 0.6f); AbstractPhysicsControl controlCopy = BinaryExporter.saveAndLoad(assetManager, control); verifyParameters(controlCopy, 0.3f); AbstractPhysicsControl controlCloneCopy = BinaryExporter.saveAndLoad(assetManager, controlClone); verifyParameters(controlCloneCopy, 0.6f); AbstractPhysicsControl xmlCopy = Utils.saveAndLoadXml(assetManager, control); verifyParameters(xmlCopy, 0.3f); } private static void cloneTest(Spatial spatial, Spatial spatialClone) { AbstractPhysicsControl control = spatial.getControl(AbstractPhysicsControl.class); AbstractPhysicsControl controlClone = spatialClone.getControl(AbstractPhysicsControl.class); verifyParameters(control, 0f); verifyParameters(controlClone, 0f); setParameters(control, 0.3f); verifyParameters(control, 0.3f); verifyParameters(controlClone, 0f); setParameters(controlClone, 0.6f); verifyParameters(control, 0.3f); verifyParameters(controlClone, 0.6f); Spatial spatialCopy = BinaryExporter.saveAndLoad(assetManager, spatial); AbstractPhysicsControl controlCopy = spatialCopy.getControl(AbstractPhysicsControl.class); verifyParameters(controlCopy, 0.3f); Spatial spatialCloneCopy = BinaryExporter.saveAndLoad(assetManager, spatialClone); AbstractPhysicsControl controlCloneCopy = spatialCloneCopy.getControl(AbstractPhysicsControl.class); verifyParameters(controlCloneCopy, 0.6f); } /** * Generate a DynamicAnimControl for Jaime. * * @return a new instance, not added to any Spatial */ private static DynamicAnimControl createDac() { DynamicAnimControl result = new DynamicAnimControl(); LinkConfig hull = new LinkConfig(0.005f, MassHeuristic.Mass, ShapeHeuristic.VertexHull, new Vector3f(1f, 1f, 1f), CenterHeuristic.Mean, RotationOrder.XZY); result.setConfig(DacConfiguration.torsoName, hull); result.link("spine", hull, new RangeOfMotion(1f)); result.link("ribs", hull, new RangeOfMotion(0.6f, 0.4f, 0.4f)); result.link("head", hull, new RangeOfMotion(0.3f, -0.6f, 0.5f, -0.5f, 0.5f, -0.5f)); result.link("eye.L", hull, new RangeOfMotion(0.5f, 0f, 0.5f)); result.link("eye.R", hull, new RangeOfMotion(0.5f, 0f, 0.5f)); result.link("tail.001", hull, new RangeOfMotion(0.5f, 0.2f, 0.5f)); result.link("tail.002", hull, new RangeOfMotion(0.5f, 0.2f, 0.5f)); result.link("tail.003", hull, new RangeOfMotion(0.5f, 0.2f, 0.5f)); result.link("tail.004", hull, new RangeOfMotion(0.5f, 0.2f, 0.5f)); result.link("tail.005", hull, new RangeOfMotion(0.5f, 0.2f, 0.5f)); result.link("tail.007", hull, new RangeOfMotion(0.5f, 0.2f, 0.5f)); result.link("tail.009", hull, new RangeOfMotion(0.5f, 0.2f, 0.5f)); return result; } private static void setParameters(AbstractPhysicsControl control, float b) { boolean flag = (b > 0.15f && b < 0.45f); if (!(control instanceof DynamicAnimControl)) { control.setApplyPhysicsLocal(!flag); } control.setEnabled(flag); if (control instanceof BetterCharacterControl) { setBcc((BetterCharacterControl) control, b); } else if (control instanceof CharacterControl) { setCc((CharacterControl) control, b); } else if (control instanceof DynamicAnimControl) { setDac((DynamicAnimControl) control, b); } else if (control instanceof SoftBodyControl) { setSbc((SoftBodyControl) control, b); } else { throw new IllegalArgumentException(control.getClass().getName()); } } /** * Modify BetterCharacterControl parameters based on the specified key * value. * * @param bcc the control to modify (not null) * @param b the key value */ private static void setBcc(BetterCharacterControl bcc, float b) { bcc.setDuckedFactor(b + 0.01f); bcc.setJumpForce(new Vector3f(b + 0.05f, b + 0.06f, b + 0.07f)); bcc.setPhysicsDamping(b + 0.08f); bcc.setViewDirection(new Vector3f(b + 0.10f, b + 0.11f, b + 0.12f)); bcc.setWalkDirection(new Vector3f(b + 0.13f, b + 0.14f, b + 0.15f)); } private static void setCc(CharacterControl cc, float b) { Vector3f upDirection = new Vector3f(b - 0.2f, b + 0.8f, b - 0.6f).normalize(); Vector3f viewDirection = new Vector3f(b + 0.1f, b + 0.5f, b + 0.7f).normalizeLocal(); // Walk offset must be perpendicular to "up" direction. Vector3f walkOffset = new Vector3f(b + 0.6f, b + 0.2f, b + 0.4f) .cross(upDirection); PhysicsCharacter ch = cc.getCharacter(); ch.setAngularDamping(b + 0.01f); ch.setAngularVelocity(new Vector3f(b + 0.04f, b + 0.05f, b + 0.06f)); ch.setCcdMotionThreshold(b + 0.07f); ch.setCcdSweptSphereRadius(b + 0.08f); ch.setContactDamping(b + 0.084f); ch.setContactProcessingThreshold(b + 0.0845f); ch.setContactStiffness(b + 0.085f); ch.setDeactivationTime(b + 0.087f); cc.setFallSpeed(b + 0.01f); ch.setFriction(b + 0.095f); cc.setGravity(b + 0.015f); cc.setJumpSpeed(b + 0.02f); ch.setLinearDamping(b + 0.03f); ch.setMaxPenetrationDepth(b + 0.281f); ch.setMaxSlope(b + 0.282f); ch.setPhysicsLocation(new Vector3f(b + 0.18f, b + 0.19f, b + 0.20f)); ch.setRestitution(b + 0.25f); ch.setRollingFriction(b + 0.26f); ch.setSpinningFriction(b + 0.27f); ch.setStepHeight(b + 0.29f); ch.setUp(upDirection); cc.setViewDirection(viewDirection); cc.setWalkDirection(walkOffset); } private static void setDac(DynamicAnimControl dac, float b) { dac.setDamping(b + 0.01f); dac.setEventDispatchImpulseThreshold(b + 0.02f); dac.setGravity(new Vector3f(b + 0.03f, b + 0.04f, b + 0.05f)); } private static void setSbc(SoftBodyControl sbc, float b) { // TODO } private static void verifyParameters( AbstractPhysicsControl control, float b) { boolean flag = (b > 0.15f && b < 0.45f); if (!(control instanceof DynamicAnimControl)) { Assert.assertEquals(!flag, control.isApplyPhysicsLocal()); } Assert.assertEquals(flag, control.isEnabled()); if (control instanceof BetterCharacterControl) { verifyBcc((BetterCharacterControl) control, b); } else if (control instanceof CharacterControl) { verifyCc((CharacterControl) control, b); } else if (control instanceof DynamicAnimControl) { verifyDac((DynamicAnimControl) control, b); } else if (control instanceof SoftBodyControl) { verifySbc((SoftBodyControl) control, b); } else { throw new IllegalArgumentException(control.getClass().getName()); } } /** * Verify that all BetterCharacterControl parameters have their expected * values for the specified key value. * * @param bcc the control to verify (not null, unaffected) * @param b the key value */ private static void verifyBcc(BetterCharacterControl bcc, float b) { Assert.assertEquals(b + 0.01f, bcc.getDuckedFactor(), 0f); Utils.assertEquals( b + 0.05f, b + 0.06f, b + 0.07f, bcc.getJumpForce(null), 0f); Assert.assertEquals(b + 0.08f, bcc.getPhysicsDamping(), 0f); Utils.assertEquals(b + 0.10f, b + 0.11f, b + 0.12f, bcc.getViewDirection(null), 0f); Utils.assertEquals(b + 0.13f, b + 0.14f, b + 0.15f, bcc.getWalkDirection(null), 0f); } private static void verifyCc(CharacterControl cc, float b) { Vector3f upDirection = new Vector3f(b - 0.2f, b + 0.8f, b - 0.6f).normalizeLocal(); Vector3f viewDirection = new Vector3f(b + 0.1f, b + 0.5f, b + 0.7f).normalizeLocal(); // Walk offset must be perpendicular to "up" direction. Vector3f walkOffset = new Vector3f(b + 0.6f, b + 0.2f, b + 0.4f) .cross(upDirection); PhysicsCharacter ch = cc.getCharacter(); Assert.assertEquals(b + 0.01f, ch.getAngularDamping(), 0f); Utils.assertEquals(b + 0.04f, b + 0.05f, b + 0.06f, ch.getAngularVelocity(null), 0f); Assert.assertEquals(b + 0.07f, ch.getCcdMotionThreshold(), 0f); Assert.assertEquals(b + 0.08f, ch.getCcdSweptSphereRadius(), 0f); Assert.assertEquals(b + 0.084f, ch.getContactDamping(), 0f); Assert.assertEquals(b + 0.0845f, ch.getContactProcessingThreshold(), 0f); Assert.assertEquals(b + 0.085f, ch.getContactStiffness(), 0f); Assert.assertEquals(b + 0.087f, ch.getDeactivationTime(), 0f); Assert.assertEquals(b + 0.01f, ch.getFallSpeed(), 0f); Assert.assertEquals(b + 0.095f, ch.getFriction(), 0f); Assert.assertEquals(b + 0.015f, ch.getGravity(null).length(), 1e-5f); Assert.assertEquals(b + 0.02f, ch.getJumpSpeed(), 0f); Assert.assertEquals(b + 0.03f, ch.getLinearDamping(), 0f); Assert.assertEquals(b + 0.281f, ch.getMaxPenetrationDepth(), 0f); Assert.assertEquals(b + 0.282f, ch.getMaxSlope(), 0f); Utils.assertEquals(b + 0.18f, b + 0.19f, b + 0.20f, ch.getPhysicsLocation(null), 0f); Assert.assertEquals(b + 0.25f, ch.getRestitution(), 0f); Assert.assertEquals(b + 0.26f, ch.getRollingFriction(), 0f); Assert.assertEquals(b + 0.27f, ch.getSpinningFriction(), 0f); Assert.assertEquals(b + 0.29f, ch.getStepHeight(), 0f); Utils.assertEquals(upDirection, ch.getUpDirection(null), 1e-5f); Utils.assertEquals(viewDirection, cc.getViewDirection(null), 0f); Utils.assertEquals(walkOffset, ch.getWalkDirection(null), 1e-5f); } private static void verifyDac(DynamicAnimControl dac, float b) { Assert.assertEquals(b + 0.01f, dac.damping(), 0f); Assert.assertEquals(b + 0.02f, dac.eventDispatchImpulseThreshold(), 0f); Utils.assertEquals( b + 0.03f, b + 0.04f, b + 0.05f, dac.gravity(null), 0f); } private static void verifySbc(SoftBodyControl sbc, float b) { // TODO } }
true
319d5324a19b1e6200e8cd7d8d6f0031d1017511
Java
theHeimes/schedoscope
/schedoscope-metascope/src/main/java/org/schedoscope/metascope/model/key/FieldEntityKey.java
UTF-8
2,395
2.078125
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2015 Otto (GmbH & Co KG) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.schedoscope.metascope.model.key; import org.schedoscope.metascope.model.FieldEntity; import javax.persistence.Column; import javax.persistence.Embeddable; import java.io.Serializable; @Embeddable public class FieldEntityKey implements Serializable { private static final long serialVersionUID = 6389851840855124146L; @Column(name = FieldEntity.FQDN) private String fqdn; @Column(name = FieldEntity.NAME) private String name; public FieldEntityKey() { } public FieldEntityKey(String fqdn, String name) { this.fqdn = fqdn; this.name = name; } public String getFqdn() { return fqdn; } public void setFqdn(String fqdn) { this.fqdn = fqdn; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fqdn == null) ? 0 : fqdn.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FieldEntityKey other = (FieldEntityKey) obj; if (fqdn == null) { if (other.fqdn != null) return false; } else if (!fqdn.equals(other.fqdn)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
true
4c5e2df9f6800ff290e83692a8097650b6988660
Java
joshuajWallace/Tetris
/src/app/ScorePanel.java
UTF-8
2,774
2.96875
3
[]
no_license
package app; import java.awt.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.security.CodeSource; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; public class ScorePanel extends JPanel { /** * */ private static final long serialVersionUID = 7730153057695726313L; private static JLabel highScore = new JLabel("0"); private static int score = 0; private static JLabel currentScore = new JLabel("0"); private Font defaultFont = new Font("TimesRoman", Font.BOLD, 30); public ScorePanel() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); final JLabel SCORE = new JLabel("Score:"); SCORE.setFont(defaultFont); add(SCORE); updateScore(score); currentScore.setFont(defaultFont); currentScore.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); add(currentScore); final JLabel HIGH_SCORE = new JLabel("High Score:"); HIGH_SCORE.setFont(defaultFont); add(HIGH_SCORE); highScore.setFont(defaultFont); highScore.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); getHighScore(); add(highScore); setPreferredSize(new Dimension(200,20)); } public static void rowsCleared(int numberOfRows) { switch(numberOfRows) { case 1: updateScore(40); break; case 2: updateScore(100); break; case 3: updateScore(400); break; case 4: updateScore(1200); break; default: return; } } public static void updateScore(int add) { score += add; currentScore.setText(Integer.toString(score)); } public static void resetScore() { int test = Integer.parseInt(highScore.getText()); if(test < score) { highScore.setText(Integer.toString(score)); setHighScore(); } score = 0; currentScore.setText(Integer.toString(score)); } public void getHighScore() { BufferedReader rd; try { CodeSource codeSource = App.class.getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String file = jarFile.getParentFile().getPath(); rd = new BufferedReader(new FileReader(new File(file + "\\highScore.txt"))); highScore.setText(rd.readLine()); rd.close(); } catch (Exception e) { e.printStackTrace(); } } public static void setHighScore() { BufferedWriter bw; try { CodeSource codeSource = App.class.getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); String file = jarFile.getParentFile().getPath(); bw = new BufferedWriter(new FileWriter(new File(file + "\\highScore.txt"))); bw.write(highScore.getText()); bw.close(); } catch (Exception e) { e.printStackTrace(); } } }
true
b10d117591b29f3ed6e97aa75b5000e7d2716716
Java
siminabratianu/CTS
/seminar5/src/ro/ase/acs/simpleFactory/Medic.java
UTF-8
430
2.390625
2
[]
no_license
package ro.ase.acs.simpleFactory; public class Medic extends PersonalSpital{ public Medic(String nume, int salariul) { super(nume, salariul); // TODO Auto-generated constructor stub } @Override public String toString() { return "Medic [getNume()=" + getNume() + ", getSalariul()=" + getSalariul() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
true
583ae32bb2d637f5b470e1a7e4b7069b5b15607f
Java
mabuthraa/EasyFlow-Android
/easyflow/src/main/java/com/apipas/easyflow/android/Event.java
UTF-8
4,598
2.5
2
[ "Apache-2.0" ]
permissive
package com.apipas.easyflow.android; import android.util.Log; import com.apipas.easyflow.android.call.EventHandler; import com.apipas.easyflow.android.err.DefinitionError; import com.apipas.easyflow.android.err.ExecutionError; import com.apipas.easyflow.android.err.LogicViolationError; import java.util.HashMap; import java.util.Map; public class Event<C extends StatefulContext> { private static final String TAG = Event.class.getSimpleName(); private static long idCounter = 1; private String id; private Map<State<C>, State<C>> transitions = new HashMap<State<C>, State<C>>(); private EasyFlow<C> runner; private EventHandler<C> onTriggeredHandler; public Event() { this.id = "Event_" + (idCounter++); } public Event(String id) { this.id = id; } public TransitionBuilder<C> to(State<C> stateTo) { return new TransitionBuilder<C>(this, stateTo); } public TransitionBuilder<C> finish(State<C> stateTo) { stateTo.setFinal(true); return new TransitionBuilder<C>(this, stateTo); } public Event<C> whenTriggered(EventHandler<C> onTriggered) { onTriggeredHandler = onTriggered; return this; } public void trigger(final C context) { try { if (null == runner) { throw new LogicViolationError("Invalid Event: " + Event.this.toString() + " triggered while in State: " + context.getState() + " for " + context); } } catch (LogicViolationError logicViolationError) { Log.e(TAG, String.format("Event has no State to map to. You must define event %s transition in map Flow!", this), logicViolationError); return; } if (runner.isTrace()) Log.d(TAG, String.format("trigger %s for %s", this, context)); if (context.isTerminated()) { return; } runner.execute(new Runnable() { @Override public void run() { State<C> stateFrom = context.getState(); State<C> stateTo = transitions.get(stateFrom); try { if (stateTo == null) { throw new LogicViolationError("Invalid Event: " + Event.this.toString() + " triggered while in State: " + context.getState() + " for " + context); } else { callOnTriggered(context, stateFrom, stateTo); runner.callOnEventTriggered(Event.this, stateFrom, stateTo, context); runner.setCurrentState(stateTo, context); } } catch (Exception e) { runner.callOnError(new ExecutionError(stateFrom, Event.this, e, "Execution Error in [Event.trigger]", context)); } } }); } protected void addTransition(State<C> from, State<C> to) { State<C> existingTransitionState = transitions.get(from); if (existingTransitionState != null) { if (existingTransitionState == to) { throw new DefinitionError("Duplicate transition[" + this + "] from " + from + " to " + to); } else { throw new DefinitionError("Ambiguous transition[" + this + "] from " + from + " to " + to + " and " + existingTransitionState); } } transitions.put(from, to); } protected void setFlowRunner(EasyFlow<C> runner) { this.runner = runner; } private void callOnTriggered(C context, State<C> from, State<C> to) throws Exception { if (onTriggeredHandler != null) { onTriggeredHandler.call(Event.this, from, to, context); } } @Override public String toString() { return id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Event<C> other = (Event<C>) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
true
e11a00e73bd5c99eb4b4255b23c61d0950f14c43
Java
coinexchain/dex-api-java
/src/main/java/org/coinex/dex/client/model/InlineResponse20037Result.java
UTF-8
6,241
1.90625
2
[ "BSD-2-Clause" ]
permissive
/* * CET-Lite for CoinEx Chain * A REST interface for state queries, transaction generation and broadcasting. * * OpenAPI spec version: 3.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package org.coinex.dex.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * InlineResponse20037Result */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-05-09T11:28:51.986+08:00") public class InlineResponse20037Result { @SerializedName("issue_token_fee") private String issueTokenFee = null; @SerializedName("issue_rare_token_fee") private String issueRareTokenFee = null; @SerializedName("issue_3char_token_fee") private String issue3charTokenFee = null; @SerializedName("issue_4char_token_fee") private String issue4charTokenFee = null; @SerializedName("issue_5char_token_fee") private String issue5charTokenFee = null; @SerializedName("issue_6char_token_fee") private String issue6charTokenFee = null; public InlineResponse20037Result issueTokenFee(String issueTokenFee) { this.issueTokenFee = issueTokenFee; return this; } /** * Get issueTokenFee * @return issueTokenFee **/ @ApiModelProperty(value = "") public String getIssueTokenFee() { return issueTokenFee; } public void setIssueTokenFee(String issueTokenFee) { this.issueTokenFee = issueTokenFee; } public InlineResponse20037Result issueRareTokenFee(String issueRareTokenFee) { this.issueRareTokenFee = issueRareTokenFee; return this; } /** * Get issueRareTokenFee * @return issueRareTokenFee **/ @ApiModelProperty(value = "") public String getIssueRareTokenFee() { return issueRareTokenFee; } public void setIssueRareTokenFee(String issueRareTokenFee) { this.issueRareTokenFee = issueRareTokenFee; } public InlineResponse20037Result issue3charTokenFee(String issue3charTokenFee) { this.issue3charTokenFee = issue3charTokenFee; return this; } /** * Get issue3charTokenFee * @return issue3charTokenFee **/ @ApiModelProperty(value = "") public String getIssue3charTokenFee() { return issue3charTokenFee; } public void setIssue3charTokenFee(String issue3charTokenFee) { this.issue3charTokenFee = issue3charTokenFee; } public InlineResponse20037Result issue4charTokenFee(String issue4charTokenFee) { this.issue4charTokenFee = issue4charTokenFee; return this; } /** * Get issue4charTokenFee * @return issue4charTokenFee **/ @ApiModelProperty(value = "") public String getIssue4charTokenFee() { return issue4charTokenFee; } public void setIssue4charTokenFee(String issue4charTokenFee) { this.issue4charTokenFee = issue4charTokenFee; } public InlineResponse20037Result issue5charTokenFee(String issue5charTokenFee) { this.issue5charTokenFee = issue5charTokenFee; return this; } /** * Get issue5charTokenFee * @return issue5charTokenFee **/ @ApiModelProperty(value = "") public String getIssue5charTokenFee() { return issue5charTokenFee; } public void setIssue5charTokenFee(String issue5charTokenFee) { this.issue5charTokenFee = issue5charTokenFee; } public InlineResponse20037Result issue6charTokenFee(String issue6charTokenFee) { this.issue6charTokenFee = issue6charTokenFee; return this; } /** * Get issue6charTokenFee * @return issue6charTokenFee **/ @ApiModelProperty(value = "") public String getIssue6charTokenFee() { return issue6charTokenFee; } public void setIssue6charTokenFee(String issue6charTokenFee) { this.issue6charTokenFee = issue6charTokenFee; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InlineResponse20037Result inlineResponse20037Result = (InlineResponse20037Result) o; return Objects.equals(this.issueTokenFee, inlineResponse20037Result.issueTokenFee) && Objects.equals(this.issueRareTokenFee, inlineResponse20037Result.issueRareTokenFee) && Objects.equals(this.issue3charTokenFee, inlineResponse20037Result.issue3charTokenFee) && Objects.equals(this.issue4charTokenFee, inlineResponse20037Result.issue4charTokenFee) && Objects.equals(this.issue5charTokenFee, inlineResponse20037Result.issue5charTokenFee) && Objects.equals(this.issue6charTokenFee, inlineResponse20037Result.issue6charTokenFee); } @Override public int hashCode() { return Objects.hash(issueTokenFee, issueRareTokenFee, issue3charTokenFee, issue4charTokenFee, issue5charTokenFee, issue6charTokenFee); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse20037Result {\n"); sb.append(" issueTokenFee: ").append(toIndentedString(issueTokenFee)).append("\n"); sb.append(" issueRareTokenFee: ").append(toIndentedString(issueRareTokenFee)).append("\n"); sb.append(" issue3charTokenFee: ").append(toIndentedString(issue3charTokenFee)).append("\n"); sb.append(" issue4charTokenFee: ").append(toIndentedString(issue4charTokenFee)).append("\n"); sb.append(" issue5charTokenFee: ").append(toIndentedString(issue5charTokenFee)).append("\n"); sb.append(" issue6charTokenFee: ").append(toIndentedString(issue6charTokenFee)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
2d95f3714006e28bfe904d4461f43bd184871b1d
Java
karunas1/receipt-service
/src/main/java/com/verifone/receipt/enums/TransactionTypeEnumForCBA.java
UTF-8
1,303
2.03125
2
[]
no_license
package com.verifone.receipt.enums; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum TransactionTypeEnumForCBA { PREAUTH("PREAUTH"), EXTEND_TRANSACTION("EXTEND_TRANSACTION"), SALE("PURCHASE"), NON_FINANCIAL("NON_FINANCIAL"), REFUND("REFUND"), PREAUTH_INCREMENT("PREAUTH_INCREMENT"), LOAD("LOAD"), UNLOAD("UNLOAD"), NO_SHOW("NO_SHOW"), BALANCE("BALANCE"), CARD_DEACTIVATION("CARD_DEACTIVATION"), CASH_ADVANCE("CASH_ADVANCE"), CARD_ACTIVATION("CARD_ACTIVATION"), CASH_DEPOSIT("CASH_DEPOSIT"), AUTHORISATION("AUTHORISATION"), CANCEL("CANCEL"), COMPLETION("COMPLETION"), DELAYED_CHARGE("DELAYED_CHARGE"), VOID("VOID"), CARD_VERIFICATION("CARD_VERIFICATION"); private String value; TransactionTypeEnumForCBA(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static TransactionTypeEnumForCBA fromValue(String text) { for (TransactionTypeEnumForCBA b : TransactionTypeEnumForCBA.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } }
true
3f8cb29c76ce8cc24ee0456458ae111549b92f24
Java
tozzr/reqif-hub
/src/main/java/com/tozzr/reqif/domain/Identifiable.java
UTF-8
903
2.484375
2
[]
no_license
package com.tozzr.reqif.domain; import org.w3c.dom.Element; public abstract class Identifiable extends ReqIFElement { public String identifier; public String lastChange; public String longName; protected Identifiable(final String name) { super(name); } protected Identifiable(final String name, final boolean selfClosing) { super(name, selfClosing); } @Override public String toXml(int indent) { setAttribute("IDENTIFIER", identifier); setAttribute("LAST-CHANGE", lastChange); setAttribute("LONG-NAME", longName); return super.toXml(indent); } @Override protected void handleElement(Element e) { if (e.getNodeName().equals(getName())) { identifier = e.getAttribute("IDENTIFIER"); lastChange = e.getAttribute("LAST-CHANGE"); longName = e.getAttribute("LONG-NAME"); handleExtraAttributes(e); } } protected void handleExtraAttributes(Element e) { } }
true
e62e59b0b64dbbb5ed4be2ef20a9f81b7aad6daf
Java
Colinwielga/DataMining
/Can I Eat it/src/com/example/can/i/eat/it/MainActivity.java
UTF-8
14,023
1.914063
2
[]
no_license
package com.example.can.i.eat.it; import java.util.HashMap; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; public class MainActivity extends Activity { RadioGroup rg1_cap_shape; RadioGroup rg2_cap_surface; RadioGroup rg3_cap_color; RadioGroup rg4_bruises; RadioGroup rg5_odor; RadioGroup rg6_gill_attachment; RadioGroup rg7_gill_spacing; RadioGroup rg8_gill_size; RadioGroup rg9_gill_color; RadioGroup rg10_stalk_shape; RadioGroup rg11_stalk_root; RadioGroup rg12_stalk_surface_above; RadioGroup rg13_stalk_surface_below; RadioGroup rg14_stalk_color_above; RadioGroup rg15_stalk_color_below; RadioGroup rg16_veil_type; RadioGroup rg17_veil_color; RadioGroup rg18_ring_number; RadioGroup rg19_ring_type; RadioGroup rg20_spore_print_color; RadioGroup rg21_population; RadioGroup rg22_habitat; HashMap<String,String> hm_cap_shape; HashMap<String,String> hm_cap_surface; HashMap<String,String> hm_cap_color; HashMap<String,String> hm_bruises; HashMap<String,String> hm_odor; HashMap<String,String> hm_gill_attachment; HashMap<String,String> hm_gill_spacing; HashMap<String,String> hm_gill_size; HashMap<String,String> hm_gill_color; HashMap<String,String> hm_stalk_shape; HashMap<String,String> hm_stalk_root; HashMap<String,String> hm_stalk_surface_above; HashMap<String,String> hm_stalk_surface_below; HashMap<String,String> hm_stalk_color_above; HashMap<String,String> hm_stalk_color_below; HashMap<String,String> hm_veil_type; HashMap<String,String> hm_veil_color; HashMap<String,String> hm_ring_number; HashMap<String,String> hm_ring_type; HashMap<String,String> hm_spore_print_color; HashMap<String,String> hm_population; HashMap<String,String> hm_habitat; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rg1_cap_shape = (RadioGroup) findViewById(R.id.rg1_cap_shape); rg2_cap_surface = (RadioGroup) findViewById(R.id.rg2_cap_surface); rg3_cap_color = (RadioGroup) findViewById(R.id.rg3_cap_color); rg4_bruises = (RadioGroup) findViewById(R.id.rg4_bruises); rg5_odor = (RadioGroup) findViewById(R.id.rg5_odor); rg6_gill_attachment = (RadioGroup) findViewById(R.id.rg6_gill_attachment); rg7_gill_spacing = (RadioGroup) findViewById(R.id.rg7_gill_spacing); rg8_gill_size = (RadioGroup) findViewById(R.id.rg8_gill_size); rg9_gill_color = (RadioGroup) findViewById(R.id.rg9_gill_color); rg10_stalk_shape = (RadioGroup) findViewById(R.id.rg10_stalk_shape); rg11_stalk_root = (RadioGroup) findViewById(R.id.rg11_stalk_root); rg12_stalk_surface_above = (RadioGroup) findViewById(R.id.rg12_stalk_surface_above_ring); rg13_stalk_surface_below = (RadioGroup) findViewById(R.id.rg13_stalk_surface_below_ring); rg14_stalk_color_above = (RadioGroup) findViewById(R.id.rg14_stalk_color_above_ring); rg15_stalk_color_below = (RadioGroup) findViewById(R.id.rg15_stalk_color_below_ring); rg16_veil_type = (RadioGroup) findViewById(R.id.rg16_veil_type); rg17_veil_color = (RadioGroup) findViewById(R.id.rg17_veil_color ); rg18_ring_number = (RadioGroup) findViewById(R.id.rg18_ring_number); rg19_ring_type = (RadioGroup) findViewById(R.id.rg19_ring_type); rg20_spore_print_color = (RadioGroup) findViewById(R.id.rg20_spore_print_color); rg21_population = (RadioGroup) findViewById(R.id.rg21_population); rg22_habitat = (RadioGroup) findViewById(R.id.rg22_habitat); hm_cap_shape = new HashMap<String,String>(); hm_cap_shape.put("Bell","b"); hm_cap_shape.put("Conical","c"); hm_cap_shape.put("Convex","x"); hm_cap_shape.put("Flat","f"); hm_cap_shape.put("Knobbed","k"); hm_cap_shape.put("Sunken","s"); hm_cap_surface = new HashMap<String,String>(); hm_cap_surface.put("Fibrous","f"); hm_cap_surface.put("Grooves","g"); hm_cap_surface.put("Scaly","y"); hm_cap_surface.put("Smooth","s"); hm_cap_color = new HashMap<String,String>(); hm_cap_color.put("Brown","n"); hm_cap_color.put("Buff","b"); hm_cap_color.put("Cinnamon","c"); hm_cap_color.put("Gray","g"); hm_cap_color.put("Green","r"); hm_cap_color.put("Pink","p"); hm_cap_color.put("Purple","u"); hm_cap_color.put("Red","e"); hm_cap_color.put("White","w"); hm_cap_color.put("Yellow","y" ); hm_bruises = new HashMap<String,String>(); hm_bruises.put("Yes","t"); hm_bruises.put("No","f" ); hm_odor = new HashMap<String,String>(); hm_odor.put("Almond","a"); hm_odor.put("Anise","l"); hm_odor.put("Creosote","c"); hm_odor.put("Fishy","y"); hm_odor.put("Foul","f"); hm_odor.put("Musty","m"); hm_odor.put("None","n"); hm_odor.put("Pungent","p"); hm_odor.put("Spicy","s" ); hm_gill_attachment = new HashMap<String,String>(); hm_gill_attachment.put("Attached","a"); hm_gill_attachment.put( "Descending","d"); hm_gill_attachment.put("Free","f"); hm_gill_attachment.put("Notched","n" ); hm_gill_spacing = new HashMap<String,String>(); hm_gill_spacing.put("Close","c"); hm_gill_spacing.put("Crowded","w"); hm_gill_spacing.put("Distant","d" ); hm_gill_size = new HashMap<String,String>(); hm_gill_size.put("Broad","b"); hm_gill_size.put("Narrow","n" ); hm_gill_color = new HashMap<String,String>(); hm_gill_color.put("Black","k"); hm_gill_color.put("Brown","n"); hm_gill_color.put("Buff","b"); hm_gill_color.put("Chocolate","c"); hm_gill_color.put("Gray","g"); hm_gill_color.put("Green","r"); hm_gill_color.put("Orange","o"); hm_gill_color.put("Pink","p"); hm_gill_color.put("Purple","u"); hm_gill_color.put("Red","e"); hm_gill_color.put("White","w"); hm_gill_color.put("Yellow","y" ); hm_stalk_shape = new HashMap<String,String>(); hm_stalk_shape.put("Enlarging","e"); hm_stalk_shape.put("Tapering","t" ); hm_stalk_root = new HashMap<String,String>(); hm_stalk_root.put("Bulbous","b"); hm_stalk_root.put("Club","c"); hm_stalk_root.put("Cup","u"); hm_stalk_root.put("Equal","e"); hm_stalk_root.put("Rhizomorphs","z"); hm_stalk_root.put("Rooted","r"); hm_stalk_root.put("Missing","?" ); hm_stalk_surface_above = new HashMap<String,String>(); hm_stalk_surface_above.put("Fibrous","f"); hm_stalk_surface_above.put("Grooves","g"); hm_stalk_surface_above.put("Scaly","y"); hm_stalk_surface_above.put("Smooth","s"); hm_stalk_surface_below = new HashMap<String,String>(); hm_stalk_surface_below.put("Fibrous","f"); hm_stalk_surface_below.put("Grooves","g"); hm_stalk_surface_below.put("Scaly","y"); hm_stalk_surface_below.put("Smooth","s"); hm_stalk_color_above = new HashMap<String,String>(); hm_stalk_color_above.put("Brown","n"); hm_stalk_color_above.put("Buff","b"); hm_stalk_color_above.put("Cinnamon","c"); hm_stalk_color_above.put("Gray","g"); hm_stalk_color_above.put("Orange","r"); hm_stalk_color_above.put("Pink","p"); hm_stalk_color_above.put("Red","e"); hm_stalk_color_above.put("White","w"); hm_stalk_color_above.put("Yellow","y" ); hm_stalk_color_below = new HashMap<String,String>(); hm_stalk_color_below.put("Brown","n"); hm_stalk_color_below.put("Buff","b"); hm_stalk_color_below.put("Cinnamon","c"); hm_stalk_color_below.put("Gray","g"); hm_stalk_color_below.put("Orange","r"); hm_stalk_color_below.put("Pink","p"); hm_stalk_color_below.put("Red","e"); hm_stalk_color_below.put("White","w"); hm_stalk_color_below.put("Yellow","y" ); hm_veil_type = new HashMap<String,String>(); hm_veil_type.put("Partial","p"); hm_veil_type.put("Universal","u"); hm_veil_color = new HashMap<String,String>(); hm_veil_color.put("Brown","n"); hm_veil_color.put("Orange","r"); hm_veil_color.put("White","w"); hm_veil_color.put( "Yellow","y"); hm_ring_number = new HashMap<String,String>(); hm_ring_number.put("None","n"); hm_ring_number.put("One","o"); hm_ring_number.put("Two","t" ); hm_ring_type = new HashMap<String,String>(); hm_ring_type.put("Cobwebby","c"); hm_ring_type.put("Evanesent","e"); hm_ring_type.put("Flaring","f"); hm_ring_type.put("Large","l"); hm_ring_type.put("None","n"); hm_ring_type.put("Pendant","p"); hm_ring_type.put("Sheathing","s"); hm_ring_type.put("Zone","z" ); hm_spore_print_color = new HashMap<String,String>(); hm_spore_print_color.put("Black","k"); hm_spore_print_color.put("Brown","n"); hm_spore_print_color.put("Buff","b"); hm_spore_print_color.put("Chocolate","c"); hm_spore_print_color.put("Green","r"); hm_spore_print_color.put("Orange","o"); hm_spore_print_color.put("Purple","u"); hm_spore_print_color.put("White","w"); hm_spore_print_color.put("Yellow","y" ); hm_population = new HashMap<String,String>(); hm_population.put("Abundant","a"); hm_population.put("Clustered","c"); hm_population.put("Numerous","n"); hm_population.put( "Scattered","s"); hm_population.put("Several","v"); hm_population.put("Solitary","y" ); hm_habitat = new HashMap<String,String>(); hm_habitat.put("Grasses","g"); hm_habitat.put("Leaves","l"); hm_habitat.put("Meadows","m"); hm_habitat.put("Paths","p"); hm_habitat.put("Urban","u"); hm_habitat.put("Waste","w"); hm_habitat.put("Woods","d"); Button go = (Button) findViewById(R.id.go); go.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String instanceString = getInstanceString(); Log.i("test",instanceString); // NominalInstance ni = new NominalInstance(getInstanceString()); Intent openFinder = new Intent(MainActivity.this, Ok.class); MainActivity.this.startActivity(openFinder); } }); } public String getInstanceString(){ String result = ""; result += hm_cap_shape.get(((RadioButton) findViewById(rg1_cap_shape.getCheckedRadioButtonId())).getText()) + ","; result += hm_cap_surface.get(((RadioButton) findViewById(rg2_cap_surface.getCheckedRadioButtonId())).getText()) + ","; result += hm_cap_color.get(((RadioButton) findViewById(rg3_cap_color.getCheckedRadioButtonId())).getText()) + ","; result += hm_bruises.get(((RadioButton) findViewById(rg4_bruises.getCheckedRadioButtonId())).getText()) + ","; result += hm_odor.get(((RadioButton) findViewById(rg5_odor.getCheckedRadioButtonId())).getText()) + ","; result += hm_gill_attachment.get(((RadioButton) findViewById(rg6_gill_attachment.getCheckedRadioButtonId())).getText()) + ","; result += hm_gill_spacing.get(((RadioButton) findViewById(rg7_gill_spacing.getCheckedRadioButtonId())).getText()) + ","; result += hm_gill_size.get(((RadioButton) findViewById(rg8_gill_size.getCheckedRadioButtonId())).getText()) + ","; result += hm_gill_color.get(((RadioButton) findViewById(rg9_gill_color.getCheckedRadioButtonId())).getText()) + ","; result += hm_stalk_shape.get(((RadioButton) findViewById(rg10_stalk_shape.getCheckedRadioButtonId())).getText()) + ","; result += hm_stalk_root.get(((RadioButton) findViewById(rg11_stalk_root.getCheckedRadioButtonId())).getText()) + ","; result += hm_stalk_surface_above.get(((RadioButton) findViewById(rg12_stalk_surface_above.getCheckedRadioButtonId())).getText()) + ","; result += hm_stalk_surface_below.get(((RadioButton) findViewById(rg13_stalk_surface_below.getCheckedRadioButtonId())).getText()) + ","; result += hm_stalk_color_above.get(((RadioButton) findViewById(rg14_stalk_color_above.getCheckedRadioButtonId())).getText()) + ","; result += hm_stalk_color_below.get(((RadioButton) findViewById(rg15_stalk_color_below.getCheckedRadioButtonId())).getText()) + ","; result += hm_veil_type.get(((RadioButton) findViewById(rg16_veil_type.getCheckedRadioButtonId())).getText()) + ","; result += hm_veil_color.get(((RadioButton) findViewById(rg17_veil_color.getCheckedRadioButtonId())).getText()) + ","; result += hm_ring_number.get(((RadioButton) findViewById(rg18_ring_number.getCheckedRadioButtonId())).getText()) + ","; result += hm_ring_type.get(((RadioButton) findViewById(rg19_ring_type.getCheckedRadioButtonId())).getText()) + ","; result += hm_spore_print_color.get(((RadioButton) findViewById(rg20_spore_print_color.getCheckedRadioButtonId())).getText()) + ","; result += hm_population.get(((RadioButton) findViewById(rg21_population.getCheckedRadioButtonId())).getText()) + ","; result += hm_habitat.get(((RadioButton) findViewById(rg22_habitat.getCheckedRadioButtonId())).getText()); return result; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
true
2b3933fcaa80c48c4ca43e203002ae0e53feabdc
Java
failgoddess/dq
/server/src/main/java/dq/core/enums/VizVisiblityEnum.java
UTF-8
551
2.796875
3
[]
no_license
package dq.core.enums; public enum VizVisiblityEnum { PORTAL("portal"), DASHBOARD("dashboard"), DISPLAY("display"), SLIDE("slide"), ; private String viz; VizVisiblityEnum(String viz) { this.viz = viz; } VizVisiblityEnum() { } public static VizVisiblityEnum vizOf(String viz) { for (VizVisiblityEnum visiblityEnum : VizVisiblityEnum.values()) { if (viz.equals(visiblityEnum.viz)) { return visiblityEnum; } } return null; } }
true
2083f73243e41930cc6021aa70657b7966c1977b
Java
wzzcanoe/cm
/src/main/java/com/ma/cm/mapper/UserMapper.java
UTF-8
974
2.078125
2
[]
no_license
package com.ma.cm.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.ma.cm.entity.User; public interface UserMapper { @Select("SELECT * FROM user") List<User> getAll(); @Select("SELECT * FROM user WHERE id = #{id}") User getOne(long id); @Insert("<script>" + "<if test='id == 0'>" + "INSERT INTO user(name) VALUES(#{name})" + "</if>" + "<if test='id != 0'>" + "INSERT INTO user(id, name) VALUES(#{id}, #{name})" + "</if>" + "</script>") @Options(useGeneratedKeys = true, keyProperty="id", keyColumn="id") void insert(User user); @Update("UPDATE user SET name=#{name} WHERE id = #{id}") void update(User user); @Delete("DELETE FROM user WHERE id = #{id}") void delete(long id); }
true
cc4dd5f4b25144127f8397c41ea22e9dc33f5942
Java
adminDavin/hanfu
/hanfu-user-center/src/main/java/com/hanfu/user/center/dao/HfMemberLevelMapper.java
UTF-8
3,137
1.898438
2
[]
no_license
package com.hanfu.user.center.dao; import com.hanfu.user.center.model.HfMemberLevel; import com.hanfu.user.center.model.HfMemberLevelExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface HfMemberLevelMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ long countByExample(HfMemberLevelExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int deleteByExample(HfMemberLevelExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int insert(HfMemberLevel record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int insertSelective(HfMemberLevel record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ List<HfMemberLevel> selectByExample(HfMemberLevelExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ HfMemberLevel selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int updateByExampleSelective(@Param("record") HfMemberLevel record, @Param("example") HfMemberLevelExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int updateByExample(@Param("record") HfMemberLevel record, @Param("example") HfMemberLevelExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int updateByPrimaryKeySelective(HfMemberLevel record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hf_member_level * * @mbg.generated Wed May 20 09:39:53 CST 2020 */ int updateByPrimaryKey(HfMemberLevel record); }
true
601c243f874c8e75c02e895a5dba62ac0b7e5c2d
Java
cammette/DBus
/dbus-commons/src/main/java/com/creditease/dbus/commons/log/processor/rule/IRule.java
UTF-8
359
1.710938
2
[ "Apache-2.0" ]
permissive
package com.creditease.dbus.commons.log.processor.rule; import com.creditease.dbus.commons.log.processor.parse.RuleGrammar; import com.creditease.dbus.commons.log.processor.rule.impl.Rules; import java.util.List; public interface IRule { public List<String> transform(List<String> data, List<RuleGrammar> grammar, Rules ruleType) throws Exception; }
true
5f3508efd14a7f345509b05f248107c6921f3452
Java
sep35/Simulation
/src/simulations/TriangularGrid.java
UTF-8
2,430
3.421875
3
[ "MIT" ]
permissive
package simulations; import javafx.scene.shape.Polygon; import javafx.scene.shape.Shape; /** * Class used in Triangular grid simulation * @author allankiplagat * */ public class TriangularGrid extends Grid { private double triBase; private double triHeight; // coordinates of triangle at top left grid location (upright) // used as reference for all other triangles private double[] lBaseCoord; private double[] rBaseCoord; private double[] topCoord; public TriangularGrid () { super(); } public TriangularGrid (int xCount, int yCount) { super(xCount, yCount); } @Override public void setDefaultGridDimensions () { // constant adjustments to triBase to have all triangles visible triBase = (TWO * gridWidth) / (xElementsCount + 1); triHeight = gridHeight / yElementsCount; lBaseCoord = new double[] { ZERO, triHeight }; rBaseCoord = new double[] { triBase, triHeight }; topCoord = new double[] { triBase * HALF, ZERO }; placeDefaultGridElements(); } @Override public Shape createShape (int x, int y) { Polygon triangle = new Polygon(); triangle.getPoints().addAll(calculateCoordinates(x, y)); triangle.setLayoutX(x * triBase * HALF); triangle.setLayoutY(y * triHeight); return triangle; } /** * Method returns either the coordinates of an upright or inverted triangle * based on the x and y entry * * @param x * @param y * @return */ public Double[] calculateCoordinates (int x, int y) { // upright triangle double[] lBase = new double[] { lBaseCoord[0], lBaseCoord[1] }; double[] rBase = new double[] { rBaseCoord[0], rBaseCoord[1] }; double[] top = new double[] { topCoord[0], topCoord[1] }; // inverted triangle if (((x + y) % 2) == 1) { lBase[1] = lBase[1] - triHeight; rBase[1] = rBase[1] - triHeight; top[1] = top[1] + triHeight; System.out.println("Flipped\n"); } return new Double[] { lBase[0], lBase[1], rBase[0], rBase[1], top[0], top[1] }; } @Override protected void callSetNeighborDeltas () { int[] deltaX = { -1, 0, 1, -1, 1, -1, 0, 1 }; int[] deltaY = { -1, -1, -1, 0, 0, 1, 1, 1 }; super.setNeighborDeltas(deltaX, deltaY); } }
true
ee507ffe21b39bd114648c4520dd9f186122bffc
Java
GuilhermeAquino01/Java
/fibonacci.java
UTF-8
752
3.421875
3
[]
no_license
package exercicios; import javax.swing.JOptionPane; public class fibonacci { public static void main(String [] args){ String sn = JOptionPane.showInputDialog("Informe a quantidade de valor desejado"); int n = Integer.parseInt(sn); JOptionPane.showMessageDialog(null, fibonacci(n)); } public static long fibonacci(int n){ long anterior = 1, proximo = 1, resultado = 0; if (n == 0 || n ==1){ return 1; }else{ for(int cont = 2; cont <=n; cont++){ resultado = proximo + anterior; anterior = proximo; proximo = resultado; } } return resultado; } }
true
d0a4daab62bab8313359234efac658b041fbfcb2
Java
youshallnotpass-dev/java-inspections
/lib/src/main/java/dev/youshallnotpass/javaparser/NodePath.java
UTF-8
2,568
2.75
3
[ "MIT" ]
permissive
package dev.youshallnotpass.javaparser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.PackageDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.body.TypeDeclaration; import com.github.javaparser.ast.expr.ObjectCreationExpr; import java.util.Optional; public final class NodePath implements Path { private final Node node; public NodePath(final Node node) { this.node = node; } @Override public String asString() { final StringBuilder path = new StringBuilder(); if (node instanceof TypeDeclaration) { path.insert(0, ((TypeDeclaration<?>) node).getNameAsString()); path.insert(0, '$'); } if (node instanceof ObjectCreationExpr) { path.insert(0, ((ObjectCreationExpr) node).getType().getNameAsString()); path.insert(0, '$'); } if (node instanceof MethodDeclaration) { path.insert(0, ((MethodDeclaration) node).getNameAsString()); path.insert(0, '.'); } if (node instanceof CompilationUnit) { final Optional<PackageDeclaration> pkg = ((CompilationUnit) node).getPackageDeclaration(); if (pkg.isPresent()) { path.replace(0, 1, "."); path.insert(0, pkg.get().getNameAsString()); } } node.walk(Node.TreeTraversal.PARENTS, (final Node node) -> { if (node instanceof TypeDeclaration) { path.insert(0, ((TypeDeclaration<?>) node).getNameAsString()); path.insert(0, '$'); } if (node instanceof ObjectCreationExpr) { path.insert(0, ((ObjectCreationExpr) node).getType().getNameAsString()); path.insert(0, '$'); } if (node instanceof MethodDeclaration) { path.insert(0, ((MethodDeclaration) node).getNameAsString()); path.insert(0, '.'); } if (node instanceof CompilationUnit) { final Optional<PackageDeclaration> pkg = ((CompilationUnit) node).getPackageDeclaration(); if (pkg.isPresent()) { path.replace(0, 1, "."); path.insert(0, pkg.get().getNameAsString()); } } }); if (path.length() > 0 && path.charAt(0) == '$') { path.delete(0, 1); } return path.toString(); } }
true
ea9dacc069afcf0de279baf711bd63d452acec8a
Java
anotheria/ano-prise
/src/main/java/net/anotheria/anoprise/fs/FSSaveable.java
UTF-8
615
2.3125
2
[ "MIT" ]
permissive
package net.anotheria.anoprise.fs; import java.io.Serializable; /** * Interface of the file system service. * * @author abolbat * @version 1.0, 2010/02/11 */ public interface FSSaveable extends Serializable { /** * Returns the owner id of the {@link FSSaveable} object. * * @return {@link String} */ String getOwnerId(); /** * Returns the owner file name of the {@link FSSaveable} object. * * @return {@link String} */ String getFileOwnerId(); /** * Returns the owner directory path of the {@link FSSaveable} object. * * @return {@link String} */ String getDirOwnerId(); }
true
2614f83b5defb30f289aacc83f91aa5a3202841a
Java
mytaowu/leetcode
/串/_151_翻转字符串里的单词.java
UTF-8
1,665
3.828125
4
[]
no_license
package 串; import java.awt.CardLayout; import javax.lang.model.element.VariableElement; /** * https://leetcode-cn.com/problems/reverse-words-in-a-string/ * @author 涛宝宝 * */ public class _151_翻转字符串里的单词 { public String reverseWords(String s) { char[] array = s.toCharArray(); //第一步:去除多余的空格; //标志上一个位置是否为空格; boolean flag = true; //去除空格之后,剩下的元素的实际长度; int len = 0; for (int i = 0; i < array.length; i++) { if (array[i] == ' ') { //前面是空格的情况,什么都不做。 if (flag) { continue; }else { array[len++] = ' '; flag = true; } }else { array[len++] = array[i]; flag = false; } } //去除最后一个空格 System.out.println(new String(array,0,len)); if (len == 0) { return ""; } if (array[len - 1] == ' ') { len--; } //进行整体的翻转; reverse(array,0,len); //进行局部的翻转; int cur = 0; for (int i = 0; i < len; i++) { if (array[i] == ' ') { reverse(array,cur,i); cur = i + 1; } } reverse(array,cur,len); return new String(array,0,len); } private void reverse(char[] array, int start, int end) { end--; while (start < end) { char temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } } public static void main(String[] args) { new _151_翻转字符串里的单词().reverseWords(" "); } }
true
9f65aac8b747e09a19996f92ec1861b746497c9e
Java
olegfkl/FizzBuzz_Java
/test/FizzBuzzTest.java
UTF-8
598
2.609375
3
[]
no_license
import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class FizzBuzzTest { private FizzBuzz test; @Before public void initObjects() { test = new FizzBuzz(); } @Test public void testFizz() { assertEquals("Fizz", test.play(3)); } @Test public void testBuzz() { assertEquals("Buzz", test.play(5)); } @Test public void testFizzBuzz() { assertEquals("FizzBuzz", test.play(15)); } @Test public void testDefault() { assertEquals("17", test.play(17)); } }
true
907ef3f68236b924fb121cf5b9dce4c56bd90330
Java
SSubPPaRR/Practicum_Advaced_Java
/src/week7/client/Controller.java
UTF-8
1,736
2.96875
3
[]
no_license
package week7.client; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import java.beans.EventHandler; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class Controller { public Button send; public TextArea ta; public TextField tf; private static DataInputStream isFromServer; private static DataOutputStream osToServer; public static void Start(){ try { Socket connectToServer = new Socket("localhost",8000); isFromServer = new DataInputStream( connectToServer.getInputStream() ); osToServer = new DataOutputStream( connectToServer.getOutputStream() ); System.out.println("connection successful"); } catch (IOException e){ System.out.println(e.getMessage()); } } public void PressedEnter(KeyEvent event){ if (event.getCode() == KeyCode.ENTER){ sendMessage(); } } public void sendMessage(){ String message = tf.getText(); try { tf.clear(); osToServer.writeUTF(message); osToServer.flush(); String response = isFromServer.readUTF(); ta.setText(response); System.out.println(response); } catch (IOException e) { tf.setText(message); System.out.println(e.getMessage()); System.out.println("Something went wrong attempting to send message"); } } }
true
1583d1e4b185df997c4ecdf1e48cb57c8d01aca4
Java
mafsan786git/PROGRAMMING_WITH_JAVA
/CONTEST/Unit-1/I-Contest-2/src/Duplicate.java
UTF-8
538
3.21875
3
[]
no_license
import java.util.HashSet; import java.util.Scanner; public class Duplicate { public static void main(String[] arg){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(0 < t--){ int n = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) set.add(sc.nextInt()); if(n == set.size()) System.out.println("NO"); else System.out.println("YES"); } } }
true
bc4d8c4a7666d87f51fa2b570255ea3c7aee39ab
Java
cortezvinicius/links-aplicativos-android
/app/src/main/java/com/cortezvinicius/exemplo/projeto_exemplo/MainActivity.java
UTF-8
4,513
2.015625
2
[]
no_license
package com.cortezvinicius.exemplo.projeto_exemplo; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.cortezvinicius.linksaplicativos.LinksAplicativos; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { private Button paginaWeb, whatsapp, email, maps, telefone, galeria, camera; private ImageView imageView; private Bitmap foto; private Bundle extras; private static final int SELECAO_GALERIA = 200; private static final int SELECAO_CAMERA = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); paginaWeb = findViewById(R.id.abrirPaginaWeb); whatsapp = findViewById(R.id.abriWhatsapp); email = findViewById(R.id.abrirEmail); maps = findViewById(R.id.maps); telefone = findViewById(R.id.telefone); galeria = findViewById(R.id.galeria); camera = findViewById(R.id.camera); imageView = findViewById(R.id.imageView); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},0); } final LinksAplicativos linksAplicativos = new LinksAplicativos(this); paginaWeb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linksAplicativos.abrirPaginaWeb("https://www.google.com.br"); } }); whatsapp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linksAplicativos.abrirWhatsapp("3592610903", "Olá Mundo"); } }); email.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String[] email = {"cortezvinicius881@gmail.com"}; linksAplicativos.abrirEmail(email, "olá Mundo", "Título"); } }); maps.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linksAplicativos.abrirMapas("-20.916493","-46.983915", false); } }); telefone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linksAplicativos.abrirChamada("992610903"); } }); galeria.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linksAplicativos.abrirGaleria(SELECAO_GALERIA); } }); camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { linksAplicativos.abrirCamera(SELECAO_CAMERA); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { foto = null; try { switch (requestCode) { case SELECAO_GALERIA: Uri localImagemSelecionada = data.getData(); foto = MediaStore.Images.Media.getBitmap(getContentResolver(), localImagemSelecionada); break; case SELECAO_CAMERA: extras = data.getExtras(); foto = (Bitmap) extras.get("data"); break; } if (foto != null) { imageView.setImageBitmap(foto); Log.d("IMAGEM_VIEW", "Deu Certo"); } }catch (Exception e) { e.printStackTrace(); } } } }
true
58763d33a68625e31a7b497f1901a5b920e02bfc
Java
RaissaDavinha/AndroidCam
/Objects/src/b4a/example/clseditablegrid.java
UTF-8
26,030
1.984375
2
[]
no_license
package b4a.example; import anywheresoftware.b4a.BA; import anywheresoftware.b4a.B4AClass; import anywheresoftware.b4a.BALayout; import anywheresoftware.b4a.debug.*; public class clseditablegrid extends B4AClass.ImplB4AClass implements BA.SubDelegator{ private static java.util.HashMap<String, java.lang.reflect.Method> htSubs; private void innerInitialize(BA _ba) throws Exception { if (ba == null) { ba = new BA(_ba, this, htSubs, "b4a.example.clseditablegrid"); if (htSubs == null) { ba.loadHtSubs(this.getClass()); htSubs = ba.htSubs; } } if (BA.isShellModeRuntimeCheck(ba)) this.getClass().getMethod("_class_globals", b4a.example.clseditablegrid.class).invoke(this, new Object[] {null}); else ba.raiseEvent2(null, true, "class_globals", false); } public anywheresoftware.b4a.keywords.Common __c = null; public b4a.example.clseditablegrid._textaligntype _textalign = null; public b4a.example.clseditablegrid._controltype _edittype = null; public b4a.example.clseditablegrid._inputtypes _inputtype = null; public anywheresoftware.b4a.objects.collections.Map _columns = null; public anywheresoftware.b4a.objects.ConcreteViewWrapper _dummyview = null; public int _fontsize = 0; public anywheresoftware.b4a.objects.collections.Map _rows = null; public int _rowheight = 0; public b4a.example.customlistview _cv = null; public anywheresoftware.b4a.objects.PanelWrapper _pnl = null; public anywheresoftware.b4a.objects.collections.Map _clist = null; public b4a.example.main _main = null; public b4a.example.starter _starter = null; public b4a.example.connection _connection = null; public b4a.example.maps _maps = null; public static class _textaligntype{ public boolean IsInitialized; public String Right; public String Left; public String Center; public void Initialize() { IsInitialized = true; Right = ""; Left = ""; Center = ""; } @Override public String toString() { return BA.TypeToString(this, false); }} public static class _controltype{ public boolean IsInitialized; public String IsLabel; public String IsTextBox; public String IsSpinner; public String IsSave; public String IsDelete; public String IsClone; public void Initialize() { IsInitialized = true; IsLabel = ""; IsTextBox = ""; IsSpinner = ""; IsSave = ""; IsDelete = ""; IsClone = ""; } @Override public String toString() { return BA.TypeToString(this, false); }} public static class _inputtypes{ public boolean IsInitialized; public String Decimal; public String None; public String Numbers; public String Text; public void Initialize() { IsInitialized = true; Decimal = ""; None = ""; Numbers = ""; Text = ""; } @Override public String toString() { return BA.TypeToString(this, false); }} public String _addcolumn(String _columnname,String _caption,String _width,String _format,String _alignment,String _cedittype,String _cinputtype) throws Exception{ anywheresoftware.b4a.objects.collections.Map _m = null; //BA.debugLineNum = 40;BA.debugLine="Public Sub AddColumn(ColumnName As String, Caption"; //BA.debugLineNum = 41;BA.debugLine="Dim m As Map"; _m = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 42;BA.debugLine="m.Initialize"; _m.Initialize(); //BA.debugLineNum = 43;BA.debugLine="m.Put(\"ColumnName\", ColumnName)"; _m.Put((Object)("ColumnName"),(Object)(_columnname)); //BA.debugLineNum = 44;BA.debugLine="m.Put(\"Caption\", Caption)"; _m.Put((Object)("Caption"),(Object)(_caption)); //BA.debugLineNum = 45;BA.debugLine="m.Put(\"Width\", Width)"; _m.Put((Object)("Width"),(Object)(_width)); //BA.debugLineNum = 46;BA.debugLine="m.Put(\"Format\", Format)"; _m.Put((Object)("Format"),(Object)(_format)); //BA.debugLineNum = 47;BA.debugLine="m.Put(\"Alignment\", Alignment)"; _m.Put((Object)("Alignment"),(Object)(_alignment)); //BA.debugLineNum = 48;BA.debugLine="m.Put(\"EditType\", cEditType)"; _m.Put((Object)("EditType"),(Object)(_cedittype)); //BA.debugLineNum = 49;BA.debugLine="m.Put(\"InputType\", cInputType)"; _m.Put((Object)("InputType"),(Object)(_cinputtype)); //BA.debugLineNum = 50;BA.debugLine="Columns.Put(ColumnName, m)"; _columns.Put((Object)(_columnname),(Object)(_m.getObject())); //BA.debugLineNum = 51;BA.debugLine="End Sub"; return ""; } public String _addcolumnlist(String _columnname,anywheresoftware.b4a.objects.collections.List _columnlist) throws Exception{ //BA.debugLineNum = 53;BA.debugLine="Public Sub AddColumnList(ColumnName As String, Col"; //BA.debugLineNum = 54;BA.debugLine="cList.Put(ColumnName, ColumnList)"; _clist.Put((Object)(_columnname),(Object)(_columnlist.getObject())); //BA.debugLineNum = 55;BA.debugLine="End Sub"; return ""; } public String _addrow(String _rowid,String[] _rowitems) throws Exception{ anywheresoftware.b4a.objects.collections.Map _m = null; int _i = 0; String _scolumnname = ""; //BA.debugLineNum = 58;BA.debugLine="Public Sub AddRow(rowID As String, rowItems() As S"; //BA.debugLineNum = 59;BA.debugLine="Dim m As Map"; _m = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 60;BA.debugLine="m.Initialize"; _m.Initialize(); //BA.debugLineNum = 61;BA.debugLine="For i = 0 To Columns.Size - 1"; { final int step3 = 1; final int limit3 = (int) (_columns.getSize()-1); _i = (int) (0) ; for (;_i <= limit3 ;_i = _i + step3 ) { //BA.debugLineNum = 62;BA.debugLine="Dim sColumnName As String"; _scolumnname = ""; //BA.debugLineNum = 63;BA.debugLine="sColumnName = Columns.GetKeyAt(i)"; _scolumnname = BA.ObjectToString(_columns.GetKeyAt(_i)); //BA.debugLineNum = 64;BA.debugLine="m.Put(sColumnName, rowItems(i))"; _m.Put((Object)(_scolumnname),(Object)(_rowitems[_i])); } }; //BA.debugLineNum = 66;BA.debugLine="Rows.Put(rowID, m)"; _rows.Put((Object)(_rowid),(Object)(_m.getObject())); //BA.debugLineNum = 67;BA.debugLine="End Sub"; return ""; } public String _addrowmap(String _rowid,anywheresoftware.b4a.objects.collections.Map _rowmap) throws Exception{ //BA.debugLineNum = 70;BA.debugLine="Public Sub AddRowMap(rowID As String, rowMap As Ma"; //BA.debugLineNum = 71;BA.debugLine="Rows.put(rowID, rowMap)"; _rows.Put((Object)(_rowid),(Object)(_rowmap.getObject())); //BA.debugLineNum = 72;BA.debugLine="End Sub"; return ""; } public String _class_globals() throws Exception{ //BA.debugLineNum = 2;BA.debugLine="Sub Class_Globals"; //BA.debugLineNum = 3;BA.debugLine="Type TextAlignType (Right As String, Left As Stri"; ; //BA.debugLineNum = 4;BA.debugLine="Type ControlType (IsLabel As String, IsTextBox As"; ; //BA.debugLineNum = 5;BA.debugLine="Type InputTypes(Decimal As String, None As String"; ; //BA.debugLineNum = 6;BA.debugLine="Public TextAlign As TextAlignType"; _textalign = new b4a.example.clseditablegrid._textaligntype(); //BA.debugLineNum = 7;BA.debugLine="Public EditType As ControlType"; _edittype = new b4a.example.clseditablegrid._controltype(); //BA.debugLineNum = 8;BA.debugLine="Public InputType As InputTypes"; _inputtype = new b4a.example.clseditablegrid._inputtypes(); //BA.debugLineNum = 9;BA.debugLine="Public Columns As Map"; _columns = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 10;BA.debugLine="Dim dummyView As View ' bug fix"; _dummyview = new anywheresoftware.b4a.objects.ConcreteViewWrapper(); //BA.debugLineNum = 11;BA.debugLine="Public FontSize As Int"; _fontsize = 0; //BA.debugLineNum = 12;BA.debugLine="Public Rows As Map"; _rows = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 13;BA.debugLine="Public RowHeight As Int"; _rowheight = 0; //BA.debugLineNum = 14;BA.debugLine="Public cv As CustomListView"; _cv = new b4a.example.customlistview(); //BA.debugLineNum = 15;BA.debugLine="Public pnl As Panel"; _pnl = new anywheresoftware.b4a.objects.PanelWrapper(); //BA.debugLineNum = 16;BA.debugLine="Public cList As Map"; _clist = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 17;BA.debugLine="End Sub"; return ""; } public String _drawgrid() throws Exception{ int _intl = 0; String _scolumname = ""; String _swidth = ""; String _scaption = ""; String _sformat = ""; String _salignment = ""; String _cedittype = ""; String _cinputtype = ""; int _intw = 0; int _i = 0; anywheresoftware.b4a.objects.collections.Map _cm = null; anywheresoftware.b4a.objects.LabelWrapper _lbl = null; int _r = 0; String _rowid = ""; anywheresoftware.b4a.objects.collections.Map _rd = null; anywheresoftware.b4a.objects.PanelWrapper _rp = null; anywheresoftware.b4a.objects.EditTextWrapper _txt = null; //BA.debugLineNum = 80;BA.debugLine="Sub DrawGrid()"; //BA.debugLineNum = 81;BA.debugLine="Dim intL As Int: intL = 10"; _intl = 0; //BA.debugLineNum = 81;BA.debugLine="Dim intL As Int: intL = 10"; _intl = (int) (10); //BA.debugLineNum = 82;BA.debugLine="Dim sColumName As String: sColumName = \"\""; _scolumname = ""; //BA.debugLineNum = 82;BA.debugLine="Dim sColumName As String: sColumName = \"\""; _scolumname = ""; //BA.debugLineNum = 83;BA.debugLine="Dim sWidth As String: sWidth = \"\""; _swidth = ""; //BA.debugLineNum = 83;BA.debugLine="Dim sWidth As String: sWidth = \"\""; _swidth = ""; //BA.debugLineNum = 84;BA.debugLine="Dim sCaption As String: sCaption = \"\""; _scaption = ""; //BA.debugLineNum = 84;BA.debugLine="Dim sCaption As String: sCaption = \"\""; _scaption = ""; //BA.debugLineNum = 85;BA.debugLine="Dim sFormat As String: sFormat = \"\""; _sformat = ""; //BA.debugLineNum = 85;BA.debugLine="Dim sFormat As String: sFormat = \"\""; _sformat = ""; //BA.debugLineNum = 86;BA.debugLine="Dim sAlignment As String: sAlignment = \"\""; _salignment = ""; //BA.debugLineNum = 86;BA.debugLine="Dim sAlignment As String: sAlignment = \"\""; _salignment = ""; //BA.debugLineNum = 87;BA.debugLine="Dim cEditType As String: cEditType = \"\""; _cedittype = ""; //BA.debugLineNum = 87;BA.debugLine="Dim cEditType As String: cEditType = \"\""; _cedittype = ""; //BA.debugLineNum = 88;BA.debugLine="Dim cInputType As String: cInputType = \"\""; _cinputtype = ""; //BA.debugLineNum = 88;BA.debugLine="Dim cInputType As String: cInputType = \"\""; _cinputtype = ""; //BA.debugLineNum = 89;BA.debugLine="Dim intW As Int: intW = 0"; _intw = 0; //BA.debugLineNum = 89;BA.debugLine="Dim intW As Int: intW = 0"; _intw = (int) (0); //BA.debugLineNum = 91;BA.debugLine="pnl.Color = Colors.Black 'aqui muda a cor das"; _pnl.setColor(__c.Colors.Black); //BA.debugLineNum = 92;BA.debugLine="For i = 0 To Columns.Size - 1"; { final int step20 = 1; final int limit20 = (int) (_columns.getSize()-1); _i = (int) (0) ; for (;_i <= limit20 ;_i = _i + step20 ) { //BA.debugLineNum = 93;BA.debugLine="Dim cm As Map"; _cm = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 94;BA.debugLine="cm.Initialize"; _cm.Initialize(); //BA.debugLineNum = 95;BA.debugLine="cm = Columns.GetValueAt(i)"; _cm.setObject((anywheresoftware.b4a.objects.collections.Map.MyMap)(_columns.GetValueAt(_i))); //BA.debugLineNum = 96;BA.debugLine="sColumName = cm.Get(\"ColumnName\")"; _scolumname = BA.ObjectToString(_cm.Get((Object)("ColumnName"))); //BA.debugLineNum = 97;BA.debugLine="sCaption = cm.Get(\"Caption\")"; _scaption = BA.ObjectToString(_cm.Get((Object)("Caption"))); //BA.debugLineNum = 98;BA.debugLine="sWidth = cm.Get(\"Width\")"; _swidth = BA.ObjectToString(_cm.Get((Object)("Width"))); //BA.debugLineNum = 99;BA.debugLine="sAlignment = cm.Get(\"Alignment\")"; _salignment = BA.ObjectToString(_cm.Get((Object)("Alignment"))); //BA.debugLineNum = 100;BA.debugLine="cEditType = cm.Get(\"EditType\")"; _cedittype = BA.ObjectToString(_cm.Get((Object)("EditType"))); //BA.debugLineNum = 101;BA.debugLine="intW = sWidth"; _intw = (int)(Double.parseDouble(_swidth)); //BA.debugLineNum = 103;BA.debugLine="Dim lbl As Label"; _lbl = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 104;BA.debugLine="lbl.Initialize(\"h\" & sColumName)"; _lbl.Initialize(ba,"h"+_scolumname); //BA.debugLineNum = 105;BA.debugLine="Select Case sAlignment"; switch (BA.switchObjectToInt(_salignment,_textalign.Center /*String*/ ,_textalign.Left /*String*/ ,_textalign.Right /*String*/ )) { case 0: { //BA.debugLineNum = 106;BA.debugLine="Case TextAlign.Center: lbl.Gravity = Bit.Or(Gra"; _lbl.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.CENTER)); break; } case 1: { //BA.debugLineNum = 107;BA.debugLine="Case TextAlign.Left: lbl.Gravity = Bit.Or(Gravi"; _lbl.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.LEFT)); break; } case 2: { //BA.debugLineNum = 108;BA.debugLine="Case TextAlign.Right: lbl.Gravity = Bit.Or(Grav"; _lbl.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.RIGHT)); break; } } ; //BA.debugLineNum = 110;BA.debugLine="lbl.Text = sCaption"; _lbl.setText(BA.ObjectToCharSequence(_scaption)); //BA.debugLineNum = 111;BA.debugLine="lbl.TextSize = FontSize"; _lbl.setTextSize((float) (_fontsize)); //BA.debugLineNum = 112;BA.debugLine="lbl.TextColor = Colors.Red"; _lbl.setTextColor(__c.Colors.Red); //BA.debugLineNum = 113;BA.debugLine="pnl.AddView(lbl, intL, 0dip, intW, 60)"; _pnl.AddView((android.view.View)(_lbl.getObject()),_intl,__c.DipToCurrent((int) (0)),_intw,(int) (60)); //BA.debugLineNum = 114;BA.debugLine="intL = intL + intW + 10"; _intl = (int) (_intl+_intw+10); } }; //BA.debugLineNum = 117;BA.debugLine="pnl.Width = intL"; _pnl.setWidth(_intl); //BA.debugLineNum = 118;BA.debugLine="cv.AsView.Width = intL"; _cv._asview /*anywheresoftware.b4a.objects.ConcreteViewWrapper*/ ().setWidth(_intl); //BA.debugLineNum = 121;BA.debugLine="cv.clear"; _cv._clear /*String*/ (); //BA.debugLineNum = 122;BA.debugLine="For r = 0 To Rows.Size - 1"; { final int step49 = 1; final int limit49 = (int) (_rows.getSize()-1); _r = (int) (0) ; for (;_r <= limit49 ;_r = _r + step49 ) { //BA.debugLineNum = 124;BA.debugLine="Dim rowID As String"; _rowid = ""; //BA.debugLineNum = 125;BA.debugLine="Dim rd As Map"; _rd = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 126;BA.debugLine="rd.Initialize"; _rd.Initialize(); //BA.debugLineNum = 127;BA.debugLine="rowID = Rows.GetKeyAt(r)"; _rowid = BA.ObjectToString(_rows.GetKeyAt(_r)); //BA.debugLineNum = 128;BA.debugLine="rd = Rows.GetValueAt(r)"; _rd.setObject((anywheresoftware.b4a.objects.collections.Map.MyMap)(_rows.GetValueAt(_r))); //BA.debugLineNum = 130;BA.debugLine="Dim rp As Panel"; _rp = new anywheresoftware.b4a.objects.PanelWrapper(); //BA.debugLineNum = 131;BA.debugLine="rp.Initialize(\"\")"; _rp.Initialize(ba,""); //BA.debugLineNum = 132;BA.debugLine="rp.Color = Colors.White 'esse aqui muda o fund"; _rp.setColor(__c.Colors.White); //BA.debugLineNum = 134;BA.debugLine="intL = 10"; _intl = (int) (10); //BA.debugLineNum = 135;BA.debugLine="For i = 0 To Columns.Size - 1"; { final int step59 = 1; final int limit59 = (int) (_columns.getSize()-1); _i = (int) (0) ; for (;_i <= limit59 ;_i = _i + step59 ) { //BA.debugLineNum = 136;BA.debugLine="Dim cm As Map"; _cm = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 137;BA.debugLine="cm.Initialize"; _cm.Initialize(); //BA.debugLineNum = 138;BA.debugLine="cm = Columns.GetValueAt(i)"; _cm.setObject((anywheresoftware.b4a.objects.collections.Map.MyMap)(_columns.GetValueAt(_i))); //BA.debugLineNum = 139;BA.debugLine="sColumName = cm.Get(\"ColumnName\")"; _scolumname = BA.ObjectToString(_cm.Get((Object)("ColumnName"))); //BA.debugLineNum = 140;BA.debugLine="sWidth = cm.Get(\"Width\")"; _swidth = BA.ObjectToString(_cm.Get((Object)("Width"))); //BA.debugLineNum = 141;BA.debugLine="sFormat = cm.Get(\"Format\")"; _sformat = BA.ObjectToString(_cm.Get((Object)("Format"))); //BA.debugLineNum = 142;BA.debugLine="sAlignment = cm.Get(\"Alignment\")"; _salignment = BA.ObjectToString(_cm.Get((Object)("Alignment"))); //BA.debugLineNum = 143;BA.debugLine="cEditType = cm.Get(\"EditType\")"; _cedittype = BA.ObjectToString(_cm.Get((Object)("EditType"))); //BA.debugLineNum = 144;BA.debugLine="cInputType = cm.Get(\"InputType\")"; _cinputtype = BA.ObjectToString(_cm.Get((Object)("InputType"))); //BA.debugLineNum = 145;BA.debugLine="intW = sWidth"; _intw = (int)(Double.parseDouble(_swidth)); //BA.debugLineNum = 146;BA.debugLine="Select Case cEditType"; switch (BA.switchObjectToInt(_cedittype,_edittype.IsLabel /*String*/ ,_edittype.IsTextBox /*String*/ )) { case 0: { //BA.debugLineNum = 148;BA.debugLine="Dim lbl As Label"; _lbl = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 149;BA.debugLine="lbl.Initialize(sColumName)"; _lbl.Initialize(ba,_scolumname); //BA.debugLineNum = 150;BA.debugLine="Select Case sAlignment"; switch (BA.switchObjectToInt(_salignment,_textalign.Center /*String*/ ,_textalign.Left /*String*/ ,_textalign.Right /*String*/ )) { case 0: { //BA.debugLineNum = 151;BA.debugLine="Case TextAlign.Center: lbl.Gravity = Bit.Or(Gr"; _lbl.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.CENTER)); break; } case 1: { //BA.debugLineNum = 152;BA.debugLine="Case TextAlign.Left: lbl.Gravity = Bit.Or(Grav"; _lbl.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.LEFT)); break; } case 2: { //BA.debugLineNum = 153;BA.debugLine="Case TextAlign.Right: lbl.Gravity = Bit.Or(Gra"; _lbl.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.RIGHT)); break; } } ; //BA.debugLineNum = 155;BA.debugLine="lbl.Text = rd.Get(sColumName)"; _lbl.setText(BA.ObjectToCharSequence(_rd.Get((Object)(_scolumname)))); //BA.debugLineNum = 156;BA.debugLine="lbl.TextSize = FontSize"; _lbl.setTextSize((float) (_fontsize)); //BA.debugLineNum = 157;BA.debugLine="lbl.TextColor = Colors.Black"; _lbl.setTextColor(__c.Colors.Black); //BA.debugLineNum = 158;BA.debugLine="rp.AddView(lbl, intL, 80, intW, 70)"; _rp.AddView((android.view.View)(_lbl.getObject()),_intl,(int) (80),_intw,(int) (70)); break; } case 1: { //BA.debugLineNum = 160;BA.debugLine="Dim txt As EditText"; _txt = new anywheresoftware.b4a.objects.EditTextWrapper(); //BA.debugLineNum = 161;BA.debugLine="txt.Initialize(sColumName)"; _txt.Initialize(ba,_scolumname); //BA.debugLineNum = 162;BA.debugLine="Select Case sAlignment"; switch (BA.switchObjectToInt(_salignment,_textalign.Center /*String*/ ,_textalign.Left /*String*/ ,_textalign.Right /*String*/ )) { case 0: { //BA.debugLineNum = 163;BA.debugLine="Case TextAlign.Center: txt.Gravity = Bit.Or(Gr"; _txt.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.CENTER)); break; } case 1: { //BA.debugLineNum = 164;BA.debugLine="Case TextAlign.Left: txt.Gravity = Bit.Or(Grav"; _txt.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.LEFT)); break; } case 2: { //BA.debugLineNum = 165;BA.debugLine="Case TextAlign.Right: txt.Gravity = Bit.Or(Gra"; _txt.setGravity(__c.Bit.Or(__c.Gravity.CENTER_VERTICAL,__c.Gravity.RIGHT)); break; } } ; //BA.debugLineNum = 167;BA.debugLine="txt.Text = rd.Get(sColumName)"; _txt.setText(BA.ObjectToCharSequence(_rd.Get((Object)(_scolumname)))); //BA.debugLineNum = 168;BA.debugLine="txt.TextSize = FontSize"; _txt.setTextSize((float) (_fontsize)); //BA.debugLineNum = 169;BA.debugLine="txt.TextColor = Colors.Black"; _txt.setTextColor(__c.Colors.Black); //BA.debugLineNum = 170;BA.debugLine="txt.SingleLine = True"; _txt.setSingleLine(__c.True); //BA.debugLineNum = 171;BA.debugLine="Select Case cInputType"; switch (BA.switchObjectToInt(_cinputtype,_inputtype.Decimal /*String*/ ,_inputtype.None /*String*/ ,_inputtype.Numbers /*String*/ ,_inputtype.Text /*String*/ )) { case 0: { //BA.debugLineNum = 172;BA.debugLine="Case InputType.Decimal: txt.InputType = txt.IN"; _txt.setInputType(_txt.INPUT_TYPE_DECIMAL_NUMBERS); break; } case 1: { //BA.debugLineNum = 173;BA.debugLine="Case InputType.None: txt.InputType = txt.INPUT"; _txt.setInputType(_txt.INPUT_TYPE_NONE); break; } case 2: { //BA.debugLineNum = 174;BA.debugLine="Case InputType.Numbers: txt.InputType = txt.IN"; _txt.setInputType(_txt.INPUT_TYPE_NUMBERS); break; } case 3: { //BA.debugLineNum = 175;BA.debugLine="Case InputType.Text: txt.InputType = txt.INPUT"; _txt.setInputType(_txt.INPUT_TYPE_TEXT); break; } } ; //BA.debugLineNum = 177;BA.debugLine="rp.AddView(txt, intL, 80, intW, 110)"; _rp.AddView((android.view.View)(_txt.getObject()),_intl,(int) (80),_intw,(int) (110)); break; } } ; //BA.debugLineNum = 179;BA.debugLine="intL = intL + intW + 10"; _intl = (int) (_intl+_intw+10); } }; //BA.debugLineNum = 181;BA.debugLine="cv.Add(rp, RowHeight, rowID)"; _cv._add /*String*/ (_rp,_rowheight,(Object)(_rowid)); } }; //BA.debugLineNum = 183;BA.debugLine="End Sub"; return ""; } public anywheresoftware.b4a.objects.collections.Map _getrow(int _index) throws Exception{ anywheresoftware.b4a.objects.collections.Map _mout = null; String _cedittype = ""; String _ccolumnname = ""; int _i = 0; anywheresoftware.b4a.objects.collections.Map _cm = null; anywheresoftware.b4a.objects.LabelWrapper _lbl = null; anywheresoftware.b4a.objects.EditTextWrapper _txt = null; //BA.debugLineNum = 186;BA.debugLine="Sub GetRow(Index As Int) As Map"; //BA.debugLineNum = 187;BA.debugLine="Dim mOut As Map"; _mout = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 188;BA.debugLine="mOut.Initialize"; _mout.Initialize(); //BA.debugLineNum = 189;BA.debugLine="Dim cEditType As String"; _cedittype = ""; //BA.debugLineNum = 190;BA.debugLine="Dim cColumnName As String"; _ccolumnname = ""; //BA.debugLineNum = 191;BA.debugLine="Dim pnl As Panel"; _pnl = new anywheresoftware.b4a.objects.PanelWrapper(); //BA.debugLineNum = 192;BA.debugLine="pnl = cv.GetPanel(Index)"; _pnl = _cv._getpanel /*anywheresoftware.b4a.objects.PanelWrapper*/ (_index); //BA.debugLineNum = 193;BA.debugLine="For i = 0 To Columns.Size - 1"; { final int step7 = 1; final int limit7 = (int) (_columns.getSize()-1); _i = (int) (0) ; for (;_i <= limit7 ;_i = _i + step7 ) { //BA.debugLineNum = 194;BA.debugLine="Dim cm As Map"; _cm = new anywheresoftware.b4a.objects.collections.Map(); //BA.debugLineNum = 195;BA.debugLine="cm.Initialize"; _cm.Initialize(); //BA.debugLineNum = 196;BA.debugLine="cm = Columns.GetValueAt(i)"; _cm.setObject((anywheresoftware.b4a.objects.collections.Map.MyMap)(_columns.GetValueAt(_i))); //BA.debugLineNum = 197;BA.debugLine="cColumnName = cm.Get(\"ColumnName\")"; _ccolumnname = BA.ObjectToString(_cm.Get((Object)("ColumnName"))); //BA.debugLineNum = 198;BA.debugLine="cEditType = cm.Get(\"EditType\")"; _cedittype = BA.ObjectToString(_cm.Get((Object)("EditType"))); //BA.debugLineNum = 199;BA.debugLine="Select Case cEditType"; switch (BA.switchObjectToInt(_cedittype,_edittype.IsLabel /*String*/ ,_edittype.IsTextBox /*String*/ )) { case 0: { //BA.debugLineNum = 201;BA.debugLine="Dim lbl As Label"; _lbl = new anywheresoftware.b4a.objects.LabelWrapper(); //BA.debugLineNum = 202;BA.debugLine="lbl = pnl.GetView(i)"; _lbl.setObject((android.widget.TextView)(_pnl.GetView(_i).getObject())); //BA.debugLineNum = 204;BA.debugLine="mOut.Put(cColumnName, lbl.Text)"; _mout.Put((Object)(_ccolumnname),(Object)(_lbl.getText())); break; } case 1: { //BA.debugLineNum = 206;BA.debugLine="Dim txt As EditText"; _txt = new anywheresoftware.b4a.objects.EditTextWrapper(); //BA.debugLineNum = 207;BA.debugLine="txt = pnl.GetView(i)"; _txt.setObject((android.widget.EditText)(_pnl.GetView(_i).getObject())); //BA.debugLineNum = 209;BA.debugLine="mOut.Put(cColumnName, txt.Text)"; _mout.Put((Object)(_ccolumnname),(Object)(_txt.getText())); break; } } ; } }; //BA.debugLineNum = 212;BA.debugLine="Return mOut"; if (true) return _mout; //BA.debugLineNum = 213;BA.debugLine="End Sub"; return null; } public String _initialize(anywheresoftware.b4a.BA _ba) throws Exception{ innerInitialize(_ba); //BA.debugLineNum = 20;BA.debugLine="Public Sub Initialize()"; //BA.debugLineNum = 21;BA.debugLine="cList.Initialize"; _clist.Initialize(); //BA.debugLineNum = 22;BA.debugLine="Columns.Initialize"; _columns.Initialize(); //BA.debugLineNum = 23;BA.debugLine="Rows.Initialize"; _rows.Initialize(); //BA.debugLineNum = 24;BA.debugLine="TextAlign.Initialize"; _textalign.Initialize(); //BA.debugLineNum = 25;BA.debugLine="TextAlign.Center = \"Center\""; _textalign.Center /*String*/ = "Center"; //BA.debugLineNum = 26;BA.debugLine="TextAlign.Left = \"Left\""; _textalign.Left /*String*/ = "Left"; //BA.debugLineNum = 27;BA.debugLine="TextAlign.Right = \"Right\""; _textalign.Right /*String*/ = "Right"; //BA.debugLineNum = 28;BA.debugLine="EditType.Initialize"; _edittype.Initialize(); //BA.debugLineNum = 29;BA.debugLine="EditType.IsLabel = \"Label\""; _edittype.IsLabel /*String*/ = "Label"; //BA.debugLineNum = 30;BA.debugLine="EditType.IsTextBox = \"EditText\""; _edittype.IsTextBox /*String*/ = "EditText"; //BA.debugLineNum = 31;BA.debugLine="InputType.Initialize"; _inputtype.Initialize(); //BA.debugLineNum = 32;BA.debugLine="InputType.Decimal = \"Decimal\""; _inputtype.Decimal /*String*/ = "Decimal"; //BA.debugLineNum = 33;BA.debugLine="InputType.None = \"None\""; _inputtype.None /*String*/ = "None"; //BA.debugLineNum = 34;BA.debugLine="InputType.Numbers = \"Numbers\""; _inputtype.Numbers /*String*/ = "Numbers"; //BA.debugLineNum = 35;BA.debugLine="InputType.Text = \"Text\""; _inputtype.Text /*String*/ = "Text"; //BA.debugLineNum = 36;BA.debugLine="FontSize = 12"; _fontsize = (int) (12); //BA.debugLineNum = 37;BA.debugLine="End Sub"; return ""; } public String _removerow(String _rowid) throws Exception{ //BA.debugLineNum = 75;BA.debugLine="Public Sub RemoveRow(rowID As String)"; //BA.debugLineNum = 76;BA.debugLine="If Rows.ContainsKey(rowID) Then Rows.Remove(rowID"; if (_rows.ContainsKey((Object)(_rowid))) { _rows.Remove((Object)(_rowid));}; //BA.debugLineNum = 77;BA.debugLine="End Sub"; return ""; } public Object callSub(String sub, Object sender, Object[] args) throws Exception { BA.senderHolder.set(sender); return BA.SubDelegator.SubNotFound; } }
true
63c9664c08ae1dab5294a90c81dbfd0c56af6c0d
Java
JasonFromSAGE/Lorinthios-RpgMobs
/me/Lorinth/LRM/Objects/MythicDrops/MythicDropsData.java
UTF-8
1,157
2.8125
3
[]
no_license
package me.Lorinth.LRM.Objects.MythicDrops; import me.Lorinth.LRM.Util.ConfigHelper; import me.Lorinth.LRM.Util.TryParse; import org.bukkit.configuration.file.FileConfiguration; import java.util.HashMap; public class MythicDropsData { private HashMap<Integer, MythicDropsLevelData> tierData = new HashMap<>(); public void loadData(FileConfiguration config, String prefix) { prefix += ".MythicDrops"; if(ConfigHelper.ConfigContainsPath(config, prefix)){ for(String levelKey: config.getConfigurationSection(prefix).getKeys(false)){ if(TryParse.parseInt(levelKey)){ int level = Integer.parseInt(levelKey); tierData.put(level, new MythicDropsLevelData(config, prefix + "." + levelKey)); } } } } public String getNextTierName(int level){ int highest = 0; for(Integer key : tierData.keySet()){ if(key >= highest && key <= level) highest = key; } if(highest > 0){ return tierData.get(highest).getTierName(); } return null; } }
true
c766a28e2bd6102c4b9da72ff88c0b753763d7e3
Java
undiscovered-genius/Scanner
/app/src/main/java/com/example/scanner/MainActivity.java
UTF-8
3,353
2.109375
2
[]
no_license
package com.example.scanner; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.zxing.Result; import me.dm7.barcodescanner.zxing.ZXingScannerView; import static android.Manifest.permission.CAMERA; public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{ private ZXingScannerView zXingScannerView ; private static final int REQUEST_CAMERA = 1; private Button generate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); generate = findViewById(R.id.generate); zXingScannerView = new ZXingScannerView(this); if(checkPermission()) { Toast.makeText(MainActivity.this, "PERMISSION is granted!", Toast.LENGTH_LONG).show(); } else { requestPermission(); } generate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, GenerateActivity.class); startActivity(intent); } }); } private boolean checkPermission() { return (ContextCompat.checkSelfPermission(MainActivity.this, CAMERA) == PackageManager.PERMISSION_GRANTED); } private void requestPermission() { ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA); } public void scan(View view){ zXingScannerView =new ZXingScannerView(getApplicationContext()); setContentView(zXingScannerView); zXingScannerView.setResultHandler(this); zXingScannerView.startCamera(); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } @Override protected void onPause() { super.onPause(); zXingScannerView.stopCamera(); } @Override public void handleResult(Result result) { final String scanResult = result.getText(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Scan Result"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { zXingScannerView.resumeCameraPreview(MainActivity.this); } }); builder.setNeutralButton("VISIT", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse(scanResult)); startActivity(intent); } }); builder.setMessage(scanResult); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }
true
2277a8072be1629bbd30198e01882b04ef5224b8
Java
qlmgg/AA2.0
/src/com/voole/epg/view/mymagic/.svn/text-base/ConsumerCenterView.java.svn-base
UTF-8
8,972
1.984375
2
[]
no_license
package com.voole.epg.view.mymagic; import java.util.List; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.util.AttributeSet; import android.widget.LinearLayout; import com.voole.epg.R; import com.voole.epg.base.BaseLinearLayout; import com.voole.epg.base.common.DisplayManager; import com.voole.epg.base.common.ID; import com.voole.epg.corelib.model.account.ConsumeListInfo; import com.voole.epg.corelib.model.account.OrderListInfo; import com.voole.epg.corelib.model.account.Product; import com.voole.epg.corelib.model.account.RechargeListInfo; import com.voole.epg.corelib.model.account.RechargeResult; import com.voole.epg.corelib.model.auth.AuthManager; import com.voole.epg.view.mymagic.OrderView.GotoRechargeListener; import com.voole.epg.view.mymagic.UserCenterLeftView.UserCenterLeftItemSelectedListener; import com.voole.epg.view.mymagic.UserCenterLeftView.UserCenterLeftItemView; import com.voole.tvutils.BitmapUtil; public class ConsumerCenterView extends BaseLinearLayout{ private static final int RECHARGE = 0; private static final int ORDER = 1; private static final int ORDER_HISTORY = 2; private static final int RECHARGE_HISTORY = 3; private UserCenterLeftView leftView = null; private OrderView orderView = null; private OrderHistoryView orderHistoryView = null; private RechargeView rechargeView = null; private RechargeHistoryView rechargeHistoryView = null; public void showAli(){ if(rechargeView!=null){ rechargeView.showAli(); } } private LinearLayout layout_right = null; private static final String[] itemNames = { "我要充值", "我要订购", "订购记录", "充值记录"}; public ConsumerCenterView(Context context) { super(context); init(context); } public ConsumerCenterView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } public ConsumerCenterView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public void setOrderListener(OrderListener listener){ if (listener != null) { orderView.setOrderListener(listener); } } public void setGotoRechargeListener(GotoRechargeListener listener){ if (listener != null) { orderView.setGotoRechargeListener(listener); } } public void setRechargeListener(RechargeListener listener){ if (listener != null) { rechargeView.setRechargeListener(listener); } } private ConsumerCenterUpdataListner listner = null; public void setConsumerCenterUpdataListner(ConsumerCenterUpdataListner listner){ this.listner = listner; } private void init(Context context){ setOrientation(HORIZONTAL); leftView = new UserCenterLeftView(context); leftView.setId(ID.MyMagicActivity.CC_LEFT_VIEW_NAVIGATION_ID); leftView.setData(itemNames); LinearLayout.LayoutParams param_left = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,43); param_left.leftMargin = DisplayManager.GetInstance() .changeWidthSize(35); param_left.bottomMargin = DisplayManager.GetInstance().changeHeightSize(55); leftView.setLayoutParams(param_left); addView(leftView); layout_right = new LinearLayout(context); LinearLayout.LayoutParams param_right = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,10); param_right.rightMargin = DisplayManager.GetInstance().changeWidthSize( 30); param_right.bottomMargin = DisplayManager.GetInstance().changeHeightSize(55); BitmapDrawable drawable = new BitmapDrawable(getResources(),BitmapUtil.readBitmap(context, R.drawable.cs_mymagic_consumer_right_bg)); layout_right.setBackgroundDrawable(drawable); layout_right.setLayoutParams(param_right); orderView = new OrderView(context); LinearLayout.LayoutParams param_orderView = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); param_orderView.topMargin = 15; param_orderView.leftMargin = 20; param_orderView.rightMargin = 30; orderView.setLayoutParams(param_orderView); orderView.setGotoRechargeListener(new GotoRechargeListener() { @Override public void gotoRecharge() { gotoRechargeView(); } }); layout_right.addView(orderView); orderHistoryView = new OrderHistoryView(context); LinearLayout.LayoutParams param_historyView = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); param_historyView.topMargin = 15; orderHistoryView.setLayoutParams(param_historyView); layout_right.addView(orderHistoryView); rechargeView = new RechargeView(context); layout_right.addView(rechargeView); rechargeHistoryView = new RechargeHistoryView(context); rechargeHistoryView.setLayoutParams(param_historyView); layout_right.addView(rechargeHistoryView); addView(layout_right); showRightView(RECHARGE); addViewListener(); } public void gotoRechargeView(){ setLeftViewPosition(RECHARGE); leftView.requestFocus(); } public void gotoOrderView(){ setLeftViewPosition(ORDER); leftView.requestFocus(); } private void addViewListener(){ if (leftView != null) { leftView.setUserCenterLeftItemSelectedListener(new UserCenterLeftItemSelectedListener() { @Override public void onItemSelected( UserCenterLeftItemView leftItemView) { int currentPosition = (Integer)leftItemView.getTag(); showRightView(currentPosition); if (listner != null) { listner.getData(currentPosition); } } }); } } public void setLeftViewPosition(int currentSelected){ leftView.setSelectedIndex(currentSelected); showRightView(currentSelected); } public void setOrderViewProductData(List<Product> products){ orderView.setProductDate(products); // leftView.requestFocus(); } public void setOrderViewUserInfo(OrderListInfo orderListInfo){ orderView.setOrderInfo(orderListInfo); rechargeView.setMoney(orderListInfo); } /*public void updateOrderResultUI(Product product){ orderView.updateOrderResultUI(product); }*/ public void setOrderHistoryViewData(ConsumeListInfo consumeListInfo){ orderHistoryView.setDate(consumeListInfo); } public void setRechargeViewData(RechargeResult rechargeResult){ rechargeView.setData(rechargeResult); } public void setRechargeViewData(String uid){ rechargeView.setData(uid); } public void setRechargeHistoryViewData(RechargeListInfo rechargeListInfo){ rechargeHistoryView.setDate(rechargeListInfo); } private void showRightView(int currentPosition){ switch (currentPosition) { case RECHARGE: showRechargeView(); leftView.setNextFocusRightId(ID.MyMagicActivity.CC_RECHARGEVIEW_TITLE_ID); break; case ORDER: showOrderView(); break; case ORDER_HISTORY: showOrderHistoryView(); break; case RECHARGE_HISTORY: showRechargeHistoryView(); break; default: break; } } private void showOrderView(){ /*orderView.setVisibility(VISIBLE); orderHistoryView.setVisibility(GONE); rechargeView.setVisibility(GONE); rechargeHistoryView.setVisibility(GONE);*/ layout_right.removeAllViews(); if (orderView == null) { orderView = new OrderView(getContext()); orderView.setGotoRechargeListener(new GotoRechargeListener() { @Override public void gotoRecharge() { setLeftViewPosition(RECHARGE); } }); } layout_right.addView(orderView); } private void showOrderHistoryView(){ /*orderHistoryView.setVisibility(VISIBLE); orderView.setVisibility(GONE); rechargeView.setVisibility(GONE); rechargeHistoryView.setVisibility(GONE);*/ layout_right.removeAllViews(); if (orderHistoryView == null) { orderHistoryView = new OrderHistoryView(getContext()); } layout_right.addView(orderHistoryView); } private void showRechargeView(){ /*rechargeView.setVisibility(VISIBLE); orderView.setVisibility(GONE); orderHistoryView.setVisibility(GONE); rechargeHistoryView.setVisibility(GONE);*/ layout_right.removeAllViews(); if (rechargeView == null) { rechargeView = new RechargeView(getContext()); } if (rechargeView.getUid() == null || "".equals(rechargeView.getUid())) { if (AuthManager.GetInstance().getUser() != null && AuthManager.GetInstance().getUser().getUid() != null) { rechargeView.setData(AuthManager.GetInstance().getUser().getUid()); } } layout_right.addView(rechargeView); } private void showRechargeHistoryView(){ /*rechargeHistoryView.setVisibility(VISIBLE); orderView.setVisibility(GONE); orderHistoryView.setVisibility(GONE); rechargeView.setVisibility(GONE);*/ layout_right.removeAllViews(); if (rechargeHistoryView == null) { rechargeHistoryView = new RechargeHistoryView(getContext()); } layout_right.addView(rechargeHistoryView); } public void requestLeftView(){ leftView.requestFocus(); } public interface ConsumerCenterUpdataListner{ public void getData(int currentPosition); } }
true
76db1a426eab688a8b79a17909a2aac0825f5884
Java
ogg21/gyb
/src/main/java/com/gyb/utils/JacksonObjectMapper.java
UTF-8
944
2.34375
2
[]
no_license
package com.gyb.utils; import java.io.IOException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.SerializerProvider; public class JacksonObjectMapper extends ObjectMapper{ @SuppressWarnings("deprecation") public JacksonObjectMapper() { super(); this.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); //避免IE执行AJAX时,返回JSON出现下载文件 //属性为null时输出空字符串 this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){ @Override public void serialize(Object obj, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { jg.writeString(""); } }); } }
true
62281a06ac88697a1269b5669f62e5c60e69c38d
Java
h3c-beijing/kai-core-code
/juzz4web/app/lib/dao/AuditLogDao.java
UTF-8
991
2.0625
2
[]
no_license
package lib.dao; import java.util.Date; import java.util.List; import lib.util.exceptions.ApiException; import models.AuditLog; import models.User; /** * * @author Tan Yee Fan */ public interface AuditLogDao { public class Result { public long count; public List<AuditLog> logs; } public AuditLog get(Long id, User invoker); public List<AuditLog> getByUser(User user, User invoker); public List<AuditLog> getByTime(Date startTime, Date endTime, User invoker); public List<AuditLog> getAll(User invoker); public void deleteByUser(User user, User invoker) throws ApiException; public void deleteByTime(Date startTime, Date endTime, User invoker) throws ApiException; public List<AuditLog> filter(List<String> criteria, List<Object> params, User invoker); public Result filter(List<String> criteria, List<Object> params, int search_offset, int search_length, User invoker); public void delete(List<String> criteria, List<Object> params, User invoker) throws ApiException; }
true
08ab87a66dc76882a9b2d750d5abba7038b6f357
Java
henriquefps/CinEasy-Plex
/CinEasy Plex/src/interfaces/IFachada.java
UTF-8
2,255
2.21875
2
[]
no_license
package interfaces; import java.util.ArrayList; import beans.Conta; import beans.Filme; import beans.Ingresso; import beans.Sala; import beans.Sessao; import beans.Venda; public interface IFachada { //Conta public void cadastrarConta(Conta c) throws Exception; public void alterarConta(Conta c) throws Exception; public void removerConta(Conta c) throws Exception; public Conta buscarConta(int i) throws Exception; public ArrayList<Conta> listarTodasConta(); public boolean existe(Conta c); public Conta buscarContaPorNome(String s); //Filme public void cadastrarFilme(Filme c) throws Exception; public void alterarFilme(Filme c) throws Exception; public void removerFilme(Filme c) throws Exception; public Filme buscarFilme(int id) throws Exception; public ArrayList<Filme> listarTodasFilme(); public boolean existe(Filme c); //Ingresso public void cadastrarIngresso(Ingresso c) throws Exception; public void alterarIngresso(Ingresso c) throws Exception; public void removerIngresso(Ingresso c) throws Exception; public Ingresso buscarIngresso(int id) throws Exception; public ArrayList<Ingresso> listarTodasIngresso(); public boolean existe(Ingresso c); //Sala public void cadastrarSala(Sala c) throws Exception; public void alterarSala(Sala c) throws Exception; public void removerSala(Sala c) throws Exception; public Sala buscarSala(int id) throws Exception; public ArrayList<Sala> listarTodasSala(); public boolean existe(Sala c); //Sessao public void cadastrarSessao(Sessao c) throws Exception; public void alterarSessao(Sessao c) throws Exception; public void removerSessao(Sessao c) throws Exception; public Sessao buscarSessao(int id) throws Exception; public ArrayList<Sessao> listarTodasSessao(); public boolean existe(Sessao c); ArrayList<Sessao> buscarSessaoPorTitulo(String titulo); ArrayList<Sessao> buscarSessaoPorSala(byte id); //Venda public void cadastrarVenda(Venda c) throws Exception; public void alterarVenda(Venda c) throws Exception; public void removerVenda(Venda c) throws Exception; public Venda buscarVenda(int id) throws Exception; public ArrayList<Venda> listarTodasVenda(); public boolean existe(Venda c); }
true
511bdf35e809d9cf5886f8d0c61020e812504325
Java
msfj/msjf-pas
/pas-api/src/main/java/com/msjf/finance/pas/facade/act/ProStepAuditFacade.java
UTF-8
435
1.765625
2
[]
no_license
package com.msjf.finance.pas.facade.act; import com.msjf.finance.msjf.core.response.Response; import com.msjf.finance.pas.facade.act.domain.ProStepAuDomain; import com.msjf.finance.pas.facade.act.domain.ProStepAuditDomain; public interface ProStepAuditFacade { Response setSetAudit(ProStepAuditDomain stepAuditDomain) throws RuntimeException; Response queryAudit(ProStepAuDomain proStepAuDomain) throws RuntimeException; }
true
1f8a4db6c6fd9b15fece40d4b98affb950810cb6
Java
chengmaotao/rew
/src/main/java/com/zkr/rew/common/utils/UtilsFns.java
UTF-8
20,145
1.664063
2
[]
no_license
package com.zkr.rew.common.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.thinkgem.jeesite.common.utils.CacheUtils; import com.thinkgem.jeesite.common.utils.SpringContextHolder; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.sys.dao.OfficeDao; import com.thinkgem.jeesite.modules.sys.entity.Office; import com.thinkgem.jeesite.modules.sys.entity.Role; import com.thinkgem.jeesite.modules.sys.entity.User; import com.thinkgem.jeesite.modules.sys.utils.UserUtils; import com.zkr.rew.dict.dao.RewFsdatasrcDao; import com.zkr.rew.dict.dao.RewProgressDao; import com.zkr.rew.dict.dao.RewResDao; import com.zkr.rew.dict.dao.RewawardlevelDao; import com.zkr.rew.dict.dao.RewcategoryDao; import com.zkr.rew.dict.dao.RewdmlbDao; import com.zkr.rew.dict.dao.RewgroupDao; import com.zkr.rew.dict.dao.RewprojectDao; import com.zkr.rew.dict.dao.RewscopekpiDao; import com.zkr.rew.dict.dao.RewsysvalDao; import com.zkr.rew.dict.entity.Dmlb; import com.zkr.rew.dict.entity.RewFsdatasrc; import com.zkr.rew.dict.entity.RewRes; import com.zkr.rew.dict.entity.Rewawardlevel; import com.zkr.rew.dict.entity.Rewcategory; import com.zkr.rew.dict.entity.Rewgroup; import com.zkr.rew.dict.entity.Rewproject; import com.zkr.rew.dict.entity.Rewscopekpi; import com.zkr.rew.dict.entity.Rewsysval; import com.zkr.rew.fs.entity.fsdyl.Rewfsdyl; import com.zkr.rew.zszj.dao.RewideaDao; import com.zkr.rew.zszj.entity.Rewidea; public class UtilsFns { public static final String CACHE_LISE = "LIST_"; // 奖励级别 private static RewawardlevelDao awardlevelDao = SpringContextHolder.getBean(RewawardlevelDao.class); public static final String AWARD_CACHE = "AWARD_CACHE"; public static final String AWARD_CACHE_ID = "AWARD_"; /** * @Description:奖励级别List * @param @return * @return List<Rewawardlevel> * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:04:04 */ public static List<Rewawardlevel> getAwardLevelList() { List<Rewawardlevel> awardLevelList = (List<Rewawardlevel>) CacheUtils.get(AWARD_CACHE, CACHE_LISE); if (awardLevelList == null || awardLevelList.size() == 0) { awardLevelList = awardlevelDao.findList(null); if (awardLevelList == null) { return null; } } CacheUtils.put(AWARD_CACHE, CACHE_LISE, awardLevelList); return awardLevelList; } /** * @Description:根据Id获得奖励级别对象 * @param @param id * @param @return * @return Rewawardlevel * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:06:36 */ public static Rewawardlevel getAwardLevelById(String id) { Rewawardlevel awardLevel = (Rewawardlevel) CacheUtils.get(AWARD_CACHE, AWARD_CACHE_ID + id); if (awardLevel == null) { awardLevel = awardlevelDao.get(id); if (awardLevel == null) { awardLevel = new Rewawardlevel(); return awardLevel; } } CacheUtils.put(AWARD_CACHE, AWARD_CACHE_ID + id, awardLevel); return awardLevel; } // 类别 private static RewcategoryDao categoryDao = SpringContextHolder.getBean(RewcategoryDao.class); public static final String CATEGORY_CACHE = "CATEGORY_CACHE"; public static final String CATEGORY_CACHE_ID = "CATEGORY_"; /** * @Description:类别List * @param @return * @return List<Rewcategory> * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:04:04 */ public static List<Rewcategory> getCagegoryList() { List<Rewcategory> categoryList = (List<Rewcategory>) CacheUtils.get(CATEGORY_CACHE, CACHE_LISE); if (categoryList == null || categoryList.size() == 0) { categoryList = categoryDao.findList(null); if (categoryList == null) { return null; } } CacheUtils.put(CATEGORY_CACHE, CACHE_LISE, categoryList); return categoryList; } /** * @Description:根据Id获得类别对象 * @param @param id * @param @return * @return Rewcategory * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:06:36 */ public static Rewcategory getCagegoryById(String id) { Rewcategory category = (Rewcategory) CacheUtils.get(CATEGORY_CACHE, CATEGORY_CACHE_ID + id); if (category == null) { category = categoryDao.get(id); if (category == null) { category = new Rewcategory(); return category; } } CacheUtils.put(CATEGORY_CACHE, CATEGORY_CACHE_ID + id, category); return category; } // 项目 private static RewprojectDao projectDao = SpringContextHolder.getBean(RewprojectDao.class); public static final String PROJECT_CACHE = "PROJECT_CACHE"; public static final String PROJECT_CACHE_ID = "PROJECT_"; public static final String PROJECT_CACHE_PROJECTID = "CACHE_PROJECT_"; public static final String PROJECT_CACHE_GROUP = "PROJECT_CACHE_GROUP"; /** * @Description:项目List * @param @return * @return List<Rewproject> * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:04:04 */ public static List<Rewproject> getProjectList() { Rewproject p = new Rewproject(); p.setCurrentYear(UtilsFns.selectCurrentYear()); List<Rewproject> projectList = projectDao.findList(p); if (projectList == null) { return null; } return projectList; } /** * @Description:根据当前用户所在的专业组, 获得项目List * @param @return * @return List<Rewproject> * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:04:04 */ public static List<Rewproject> getProjectListByGroup() { User user = UserUtils.getUser(); user.setCurrentYear(UtilsFns.selectCurrentYear()); List<Rewproject> projectList = projectDao.findProjectListByGroup(user); return projectList; } /** * @Description:根据Id获得项目对象 * @param @param id * @param @return * @return Rewcategory * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:06:36 */ public static Rewproject getProjectById(String id) { Rewproject project = (Rewproject) CacheUtils.get(PROJECT_CACHE, PROJECT_CACHE_ID + id); if (project == null) { project = projectDao.get(id); if (project == null) { project = new Rewproject(); return project; } } CacheUtils.put(PROJECT_CACHE, PROJECT_CACHE_ID + id, project); return project; } /** * @Description:根据projectId获得项目对象 * @param @param projectId * @param @return * @return Rewcategory * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:06:36 */ public static Rewproject getProjectByProjectId(String projectId) { Rewproject p = new Rewproject(); p.setProjectid(projectId); p.setCurrentYear(UtilsFns.selectCurrentYear()); Rewproject project = (Rewproject) CacheUtils.get(PROJECT_CACHE, PROJECT_CACHE_PROJECTID + projectId + p.getCurrentYear()); if (project == null) { project = projectDao.getProjectByProjectId(p); if (project == null) { return null; // 不要改 其他地方用到了 } } CacheUtils.put(PROJECT_CACHE, PROJECT_CACHE_PROJECTID + projectId + p.getCurrentYear(), project); return project; } // 专业组 private static RewgroupDao groupDao = SpringContextHolder.getBean(RewgroupDao.class); public static final String GROUP_CACHE = "GROUP_CACHE"; public static final String GROUP_CACHE_ID = "GROUP_"; /** * @Description:专业组List * @param @return * @return List<Rewgroup> * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:04:04 */ public static List<Rewgroup> getEnableGroupList() { String currentYear = UtilsFns.selectCurrentYear(); List<Rewgroup> groupList = (List<Rewgroup>) CacheUtils.get(GROUP_CACHE + currentYear, CACHE_LISE); if (groupList == null || groupList.size() == 0) { Rewgroup rewgroup = new Rewgroup(); rewgroup.setCurrentYear(currentYear); groupList = groupDao.findAllList(rewgroup); if (groupList == null) { return null; } } CacheUtils.put(GROUP_CACHE + currentYear, CACHE_LISE, groupList); return groupList; } public static List<SelectEntity> isAgree() { List<SelectEntity> list = new ArrayList<SelectEntity>(); SelectEntity entity1 = new SelectEntity(1, "同意"); SelectEntity entity2 = new SelectEntity(0, "不同意"); list.add(entity1); list.add(entity2); return list; } /** * @Description:根据Id获得专业组对象 * @param @param id * @param @return * @return Rewgroup * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:06:36 */ public static Rewgroup getGroupById(String id) { Rewgroup group = (Rewgroup) CacheUtils.get(GROUP_CACHE, GROUP_CACHE_ID + id); if (group == null) { group = groupDao.get(id); if (group == null) { group = new Rewgroup(); return group; } } CacheUtils.put(GROUP_CACHE, GROUP_CACHE_ID + id, group); return group; } /** * @description: 清空缓存 * @param cacheName * @param key * @author:chengMaotao * @date : 2016年8月12日 下午1:13:28 */ public static void clearCacheById(String cacheName, String key) { Object object = CacheUtils.get(cacheName, key); if (object != null) { CacheUtils.remove(cacheName, key); } } // 评价指标 private static RewscopekpiDao scopekpiDao = SpringContextHolder.getBean(RewscopekpiDao.class); public static final String SCOPEKPI_CACHE = "SCOPEKPI_CACHE"; public static final String SCOPEKPI_CACHE_ID = "SCOPEKPI_"; public static final String CACHE_LISE_CATEGORY = "CACHE_LISE_CATEGORY"; /** * @Description:评价指标List * @param @return * @return List<Rewscopekpi> * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:04:04 */ public static List<Rewscopekpi> getScopeKpiList() { List<Rewscopekpi> scopeKpiList = (List<Rewscopekpi>) CacheUtils.get(SCOPEKPI_CACHE, CACHE_LISE); if (scopeKpiList == null || scopeKpiList.size() == 0) { scopeKpiList = scopekpiDao.findList(null); if (scopeKpiList == null) { return null; } } CacheUtils.put(SCOPEKPI_CACHE, CACHE_LISE, scopeKpiList); return scopeKpiList; } /** * @Description:评价指标List * @param @return * @return List<Rewscopekpi> * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:04:04 */ public static List<Rewscopekpi> getScopeKpiListByCategoryId(String id) { List<Rewscopekpi> scopeKpiList = (List<Rewscopekpi>) CacheUtils.get(SCOPEKPI_CACHE, CACHE_LISE_CATEGORY + id); if (scopeKpiList == null || scopeKpiList.size() == 0) { scopeKpiList = scopekpiDao.findObjListByCategoryId(id); if (scopeKpiList == null) { return null; } } CacheUtils.put(SCOPEKPI_CACHE, CACHE_LISE_CATEGORY + id, scopeKpiList); return scopeKpiList; } /** * @Description:根据Id获得评价指标对象 * @param @param id * @param @return * @return Rewscopekpi * @throws * @autohr 成茂涛 * @date 2016-8-13 上午11:06:36 */ public static Rewscopekpi getScopeKpiById(String id) { Rewscopekpi scopeKpi = (Rewscopekpi) CacheUtils.get(SCOPEKPI_CACHE, SCOPEKPI_CACHE_ID + id); if (scopeKpi == null) { scopeKpi = scopekpiDao.get(id); if (scopeKpi == null) { scopeKpi = new Rewscopekpi(); return scopeKpi; } } CacheUtils.put(SCOPEKPI_CACHE, SCOPEKPI_CACHE_ID + id, scopeKpi); return scopeKpi; } /** * 根据userID 获得角色列表 * * @param id * @return */ public static String getRolesByUserId(String id) { List<Role> roleList = UserUtils.getRoleListByUserId(id); if (roleList == null || roleList.isEmpty()) { return ""; } StringBuffer sbuffer = new StringBuffer(); for (Role r : roleList) { sbuffer.append(r.getName() + ","); } // 返回 去掉 最后一个 逗号的 return sbuffer.deleteCharAt(sbuffer.toString().length() - 1).toString(); } public static final String CACH_COMPANY = "CACH_COMPANY"; public static final String CACH_COMPANY_ID = "COMPANY_"; private static OfficeDao officeDao = SpringContextHolder.getBean(OfficeDao.class); // 获得所有的公司列表 public static List<Office> findAllCompany() { List<Office> officeList = (List<Office>) CacheUtils.get(CACH_COMPANY, CACHE_LISE); if (officeList == null) { officeList = officeDao.findAllList(new Office()); if (officeList == null) { return null; } } CacheUtils.put(CACH_COMPANY, CACHE_LISE, officeList); return officeList; } public static Office getOfficeById(String id) { Office office = (Office) CacheUtils.get(CACH_COMPANY, CACH_COMPANY_ID + id); if (office == null) { office = officeDao.get(id); if (office == null) { return new Office(); } } CacheUtils.put(CACH_COMPANY, CACH_COMPANY_ID + id, office); return office; } // 获得评审意见 public static String getRewIdea(String rewIdea) { int ideaLen = Integer.valueOf(UtilsMessage.getValueByKey("rewIdeaLen")); if (rewIdea == null || ideaLen < 1 || rewIdea.length() <= ideaLen) { return rewIdea; } else { return rewIdea.substring(0, ideaLen) + "…"; } } /** * @description: 替换掉 回车符 * @param bz * @return * @author:chengMaotao * @date : 2016年1月6日 上午11:19:38 */ public static String replaceRn(String bz) { return bz.replace("\r\n", " ").replace("\r", " ").replace("\n", " "); } // 评审意见 private static RewideaDao ideaDao = SpringContextHolder.getBean(RewideaDao.class); private static final String IDEA_CACHE = "IDEA_CACHE"; public static final String IDEA_CACHE_PROJECTID = "IDEA__PROJECT"; /** * 根据projectid 获得评审意见 * * @param id * @return */ public static Rewidea getIdeaByProjectId(String id) { Rewidea idea = (Rewidea) CacheUtils.get(IDEA_CACHE, IDEA_CACHE_PROJECTID + id); if (idea == null) { idea = ideaDao.getrewIdeaByProjectId(id); if (idea == null) { return null; } } CacheUtils.put(IDEA_CACHE, IDEA_CACHE_PROJECTID + id, idea); return idea; } public static String getKpiScope(String scope) { if (scope == null || "".equals(scope)) { return ""; } return new StringBuffer(scope).append("分").toString(); } private static RewdmlbDao dmlbDao = SpringContextHolder.getBean(RewdmlbDao.class); // 菜单可用 返回 true public static boolean isMenuEnable(Dmlb dmlb) { dmlb.setCurrentYear(UtilsFns.selectCurrentYear()); // 管理员 if (UtilsMessage.isGlyRole()) { return true; } Dmlb dmlbRes = dmlbDao.selectMenuById(dmlb); if (dmlbRes != null && "1".equals(dmlbRes.getEnable())) { return true; } return false; } public static List<Rewproject> selectZszjProjectList(Rewproject rewproject) { return projectDao.selectZszjProjectList(rewproject); } public static List<Rewproject> getProjects(String kbn) { List<Rewproject> list = new ArrayList<Rewproject>(); // 是管理员 查看所有的项目 || 初审的时候也是查询所有的项目, 不是管理员 只能查看本组的项目 if (UtilsMessage.isGlyRole() || "cstp".equals(kbn)) { list = UtilsFns.getProjectList(); } else if ("fsdeltp".equals(kbn)) { list = projectDao.findProjectListNotInparametes(UtilsFns.selectCurrentYear()); } else { list = UtilsFns.getProjectListByGroup(); } return list; } private static RewFsdatasrcDao fsdatasrcDao = SpringContextHolder.getBean(RewFsdatasrcDao.class); public static final String FS_CACHE = "fs_cache"; public static final String FS_CACHE_ID = "fs_cache_id"; // 复审第一轮下拉框 public static List<RewFsdatasrc> getFsdylProjects() { List<RewFsdatasrc> list = (List<RewFsdatasrc>) CacheUtils.get(FS_CACHE, FS_CACHE_ID + "1"); if(list == null){ RewFsdatasrc entity = new RewFsdatasrc(); entity.setCurrentYear(UtilsFns.selectCurrentYear()); entity.setRecomidea("1"); list = fsdatasrcDao.findList(entity); CacheUtils.put(FS_CACHE, FS_CACHE_ID + "1"); } return list; } // 复审第二轮下拉框 (*********) public static List<RewFsdatasrc> getFsdelProjects(List<Rewfsdyl> tdjs) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("list", tdjs); parameters.put("currentYear", UtilsFns.selectCurrentYear()); List<RewFsdatasrc> list = fsdatasrcDao.findList2(parameters); return list; } // 复审第三轮下拉框 public static List<RewFsdatasrc> getFsdslProjects(List<Rewfsdyl> tdjs) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("list", tdjs); parameters.put("currentYear", UtilsFns.selectCurrentYear()); List<RewFsdatasrc> list = fsdatasrcDao.findList3(parameters); return list; } public static List<SelectEntity> getKPIList(String KPIWeight) { List<SelectEntity> list = new ArrayList<SelectEntity>(); int scope = Integer.parseInt(KPIWeight); SelectEntity entity = null; for (int i = 1; i <= scope; i++) { entity = new SelectEntity(i, i + "分"); list.add(entity); } return list; } public static final String SYS_VAL = "SYS_VAL"; public static final String SYS_VAL_YEAR = "SYS_VAL_YEAR"; public static final String SYS_FS_DATASRC = "SYS_FS_DATASRC"; // 当前年 public static String selectCurrentYear() { String res = (String) CacheUtils.get(SYS_VAL, SYS_VAL_YEAR + "currentyear"); if (res == null) { res = dmlbDao.selectCurrentYear(); } CacheUtils.put(SYS_VAL, SYS_VAL_YEAR + "currentyear",res); return res; } private static RewsysvalDao rewsysvalDao = SpringContextHolder.getBean(RewsysvalDao.class); // 当前年的 特等 一等 总共 复审 投票数 public static Rewsysval selectRewSysvalByCurrentYear() { List<Rewsysval> res = (List<Rewsysval>) CacheUtils.get(SYS_VAL, SYS_VAL_YEAR + selectCurrentYear()); if (res == null) { Rewsysval r = new Rewsysval(); r.setCurrentYear(selectCurrentYear()); res = rewsysvalDao.findList(r); } if (res != null && !res.isEmpty()) { CacheUtils.put(SYS_VAL, SYS_VAL_YEAR + selectCurrentYear()); return res.get(0); } return new Rewsysval(); } // 初审 复审结果 0初审显示 1 复审显示 其他都显示 public static String selectcfvalue() { return dmlbDao.selectcfvalue(); } public static List<SelectEntity> selectYearList() { return dmlbDao.selectYearList(); } // 1 复审第一轮 2复审第二轮 (enable 1补投可用 0不可用) public static boolean getmenucontroltp(String id) { Dmlb getmenucontroltpById = dmlbDao.getmenucontroltpById(id); if ("1".equals(getmenucontroltpById.getEnable())) { return true; } return false; } private static RewProgressDao rewProgressDao = SpringContextHolder.getBean(RewProgressDao.class); public static final String RPOGERSS_REW = "RPOGERSS_REW"; public static final String RPOGERSS_REW_VAVLE = "RPOGERSS_REW_VAVLE"; public static final String RPOGERSS_REW_RESULT = "RPOGERSS_REW_RESULT"; // 项目流程 public static String getProgerss(){ String res = (String) CacheUtils.get(RPOGERSS_REW, RPOGERSS_REW_VAVLE); if (res == null) { res = rewProgressDao.selectprogerss(); } CacheUtils.put(RPOGERSS_REW, RPOGERSS_REW_VAVLE,res); return res; } private static RewResDao rewResDao = SpringContextHolder.getBean(RewResDao.class); // 项目流程 结果 public static RewRes getProgerssRes(){ String currentYear = selectCurrentYear(); RewRes res = (RewRes) CacheUtils.get(RPOGERSS_REW, RPOGERSS_REW_RESULT + currentYear); if (res == null) { res = rewResDao.selectprogerssRes(currentYear); } CacheUtils.put(RPOGERSS_REW, RPOGERSS_REW_RESULT + currentYear,res); return res; } // 初审流程结果 // ture 初审可用 false 初审不可用 public static boolean getCsProgressResIsEnable(){ RewRes rewRes = getProgerssRes(); if(rewRes == null){ return false; } if(StringUtils.equals("0", rewRes.getCsres())){ return true; }else{ return false; } } // 复审流程结果 // ture 复审可用 false 复审不可用 public static boolean getFsProgressResIsEnable(){ RewRes rewRes = getProgerssRes(); if(StringUtils.equals("0", rewRes.getFsres())){ return true; }else{ return false; } } public static Rewproject getProjectByProjectName(String projectName) { Rewproject p = new Rewproject(); p.setProjectname(projectName); p.setCurrentYear(UtilsFns.selectCurrentYear()); return projectDao.getProjectByProjectName(p); } }
true
c474c03159b55224431239571bb54d64e931fa9d
Java
palava/palava-security
/src/main/java/de/cosmocode/palava/security/IsPermitted.java
UTF-8
2,695
2.25
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2010 CosmoCode GmbH * * 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 de.cosmocode.palava.security; import java.util.Map; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import de.cosmocode.palava.ipc.IpcArguments; import de.cosmocode.palava.ipc.IpcCall; import de.cosmocode.palava.ipc.IpcCommand; import de.cosmocode.palava.ipc.IpcCommand.Description; import de.cosmocode.palava.ipc.IpcCommand.Param; import de.cosmocode.palava.ipc.IpcCommand.Return; import de.cosmocode.palava.ipc.IpcCommandExecutionException; /** * See below. * * @author Willi Schoenborn */ @Description("Checks whether the current user has a specific permission.") @Param(name = IsPermitted.PERMISSION, description = "The permission to check against") @Return(name = IsPermitted.IS_PERMITTED, description = "A boolean, true if the user is permitted, false otherwise") @Singleton public final class IsPermitted implements IpcCommand { public static final String PERMISSION = "permission"; public static final String IS_PERMITTED = "isPermitted"; private static final Logger LOG = LoggerFactory.getLogger(IsPermitted.class); private final Provider<Subject> provider; @Inject public IsPermitted(Provider<Subject> provider) { this.provider = Preconditions.checkNotNull(provider, "Provider"); } @Override public void execute(IpcCall call, Map<String, Object> result) throws IpcCommandExecutionException { final IpcArguments arguments = call.getArguments(); final String permission = arguments.getString(PERMISSION); final Subject currentUser = provider.get(); LOG.trace("Checking user against {}", permission); final boolean isPermitted = currentUser.isPermitted(permission); LOG.trace("{} has {}: {}", new Object[] { currentUser, permission, Boolean.valueOf(isPermitted) }); result.put(IS_PERMITTED, isPermitted); } }
true
41714bce5b1589ae92f0348f287470aaf9070d69
Java
hoditac068/LucianMS
/lucian-channel/src/com/lucianms/events/PlayerBeholderEvent.java
UTF-8
1,278
2.5
2
[]
no_license
package com.lucianms.events; import com.lucianms.client.MapleCharacter; import com.lucianms.constants.skills.DarkKnight; import com.lucianms.events.PacketEvent; import com.lucianms.nio.receive.MaplePacketReader; import com.lucianms.server.maps.MapleSummon; /** * @author BubblesDev * @author izarooni */ public class PlayerBeholderEvent extends PacketEvent { private int objectID; private int skillID; private MapleSummon summon; @Override public void processInput(MaplePacketReader reader) { MapleCharacter player = getClient().getPlayer(); objectID = reader.readInt(); summon = player.getSummons().values().stream().filter(s -> s.getObjectId() == objectID).findFirst().orElse(null); if (summon != null) { skillID = reader.readInt(); if (skillID == DarkKnight.AURA_OF_THE_BEHOLDER) { // reader.readShort(); //Not sure. } else if (skillID == DarkKnight.HEX_OF_THE_BEHOLDER) { // reader.readByte(); //Not sure. } } } @Override public Object onPacket() { MapleCharacter player = getClient().getPlayer(); if (summon == null) { player.getSummons().clear(); } return null; } }
true
af6a121a11547fe1a346456ed5e2f05d1fd2abb6
Java
MrDimitrio/practical-tasks-for-a-trainee-test-automation-engineer-1
/src/main/java/io/github/valentyn/nahai/basics/oop/recursion/FibonacciNumber.java
UTF-8
831
4.28125
4
[ "Apache-2.0" ]
permissive
package io.github.valentyn.nahai.basics.oop.recursion; /** * Task: * Create a method that calculates fibonacci number using recursion. * The base formula is F(n) = F(n - 1) + F(n - 2). * * Задача: * Создайте метод, который вычисляет число Фибоначчи с помощью рекурсии. * Базовая формула: F (n) = F (n - 1) + F (n - 2). */ public class FibonacciNumber { public static void main(String[] args) { int number = 0; while(true) { System.out.println(fibo(number)); number++; } } public static int fibo(int n) { if (n == 0) { return 0; } if (n <= 2) { return 1; } int f = fibo(n - 1) + fibo(n - 2); return f; } }
true
15ccd7941914440b529bc7fe06ddf9264904f3dd
Java
Weefle/AlphaLibaryModules
/ALM-Schematic/src/main/java/de/alphahelix/almschematic/serializer/LocationDiffSerializer.java
UTF-8
1,936
2.578125
3
[]
no_license
package de.alphahelix.almschematic.serializer; import com.google.gson.*; import de.alphahelix.almschematic.Schematic; import org.bukkit.Material; import java.lang.reflect.Type; public class LocationDiffSerializer implements JsonSerializer<Schematic.LocationDiff>, JsonDeserializer<Schematic.LocationDiff> { @Override public Schematic.LocationDiff deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject obj = (JsonObject) jsonElement; Material mat = Material.getMaterial(obj.getAsJsonPrimitive("type").getAsString()); byte data = obj.getAsJsonPrimitive("data").getAsByte(); int x = obj.getAsJsonPrimitive("x").getAsInt(); int y = obj.getAsJsonPrimitive("y").getAsInt(); int z = obj.getAsJsonPrimitive("z").getAsInt(); return new Schematic.LocationDiff() { @Override public Material getBlockType() { return mat; } @Override public byte getBlockData() { return data; } @Override public int getX() { return x; } @Override public int getY() { return y; } @Override public int getZ() { return z; } }; } @Override public JsonElement serialize(Schematic.LocationDiff locationDiff, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject obj = new JsonObject(); obj.addProperty("type", locationDiff.getBlockType().name()); obj.addProperty("data", locationDiff.getBlockData()); obj.addProperty("x", locationDiff.getX()); obj.addProperty("y", locationDiff.getY()); obj.addProperty("z", locationDiff.getZ()); return obj; } }
true
d2e16c8333de0ef2d71ee73fb5a1fbf953d3a1e4
Java
stropa/jdbcdslog
/jdbcdslog/src/main/java/org/jdbcdslog/ConfigurationParameters.java
UTF-8
3,389
2.546875
3
[]
no_license
package org.jdbcdslog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.*; public class ConfigurationParameters { static Logger logger = LoggerFactory.getLogger(ConfigurationParameters.class); static long slowQueryThreshold = Long.MAX_VALUE; static boolean printStackTrace = true; static boolean logText = false; static Map<String, List<Class>> proxyClassesForTypes = new HashMap<String, List<Class>>(); static { ClassLoader loader = ConfigurationParameters.class.getClassLoader(); InputStream in = null; try { in = loader.getResourceAsStream("jdbcdslog.properties"); Properties props = new Properties(System.getProperties()); if (in != null) props.load(in); String sSlowQueryThreshold = props.getProperty("jdbcdslog.slowQueryThreshold"); if (sSlowQueryThreshold != null && isLong(sSlowQueryThreshold)) slowQueryThreshold = Long.parseLong(sSlowQueryThreshold); if (slowQueryThreshold == -1) slowQueryThreshold = Long.MAX_VALUE; String sLogText = props.getProperty("jdbcdslog.logText"); if ("true".equalsIgnoreCase(sLogText)) logText = true; String sprintStackTrace = props.getProperty("jdbcdslog.printStackTrace"); if ("true".equalsIgnoreCase(sprintStackTrace)) printStackTrace = true; readCustomProxiesConfig(props); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (in != null) try { in.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } private static void readCustomProxiesConfig(Properties props) { for (String name : props.stringPropertyNames()) { String prefix = "jdbcdslog.proxies.for."; if (name.startsWith(prefix)) { String forTypeName = name.substring(name.lastIndexOf(".") + 1); String proxiesStr = props.getProperty(name); String[] proxyClassesNames = proxiesStr.split(","); List<Class> classes = new ArrayList<Class>(); for (String proxyClassName : proxyClassesNames) { try { Class<?> aClass = Class.forName(proxyClassName.trim()); classes.add(aClass); } catch (ClassNotFoundException e) { logger.error("Failed to find class by name " + proxyClassName, e); } } proxyClassesForTypes.put(forTypeName, classes); } } } public static void setSlowQueryThreshold(Long threshold) { slowQueryThreshold = threshold; } public static void setLogText(boolean alogText) { logText = alogText; } private static boolean isLong(String sSlowQueryThreshold) { try { Long.parseLong(sSlowQueryThreshold); return true; } catch (Exception e) { return false; } } }
true
27b3008307caa7c26583ab8a9498f7e1486bd503
Java
BlueBambooStudios/react-native-track-player
/android/src/main/java/guichaguri/trackplayer/player/players/ExoPlayback.java
UTF-8
7,753
1.804688
2
[ "Apache-2.0" ]
permissive
package guichaguri.trackplayer.player.players; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.media.session.PlaybackStateCompat; import com.facebook.react.bridge.Promise; import com.google.android.exoplayer2.*; import com.google.android.exoplayer2.ExoPlayer.EventListener; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.source.dash.DashMediaSource; import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource; import com.google.android.exoplayer2.source.hls.HlsMediaSource; import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource; import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultAllocator; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.upstream.cache.Cache; import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory; import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor; import com.google.android.exoplayer2.upstream.cache.SimpleCache; import com.google.android.exoplayer2.util.Util; import guichaguri.trackplayer.logic.MediaManager; import guichaguri.trackplayer.logic.Utils; import guichaguri.trackplayer.logic.track.Track; import guichaguri.trackplayer.logic.track.TrackType; import guichaguri.trackplayer.player.Playback; import java.io.File; import static com.google.android.exoplayer2.DefaultLoadControl.*; /** * Feature-rich player using {@link SimpleExoPlayer} * * @author Guilherme Chaguri */ public class ExoPlayback extends Playback implements EventListener { private final SimpleExoPlayer player; private final long cacheMaxSize; private Promise loadCallback = null; private boolean playing = false; public ExoPlayback(Context context, MediaManager manager, Bundle options) { super(context, manager); int minBuffer = (int)Utils.toMillis(options.getDouble("minBuffer", Utils.toSeconds(DEFAULT_MIN_BUFFER_MS))); int maxBuffer = (int)Utils.toMillis(options.getDouble("maxBuffer", Utils.toSeconds(DEFAULT_MAX_BUFFER_MS))); long playBuffer = Utils.toMillis(options.getDouble("playBuffer", Utils.toSeconds(DEFAULT_BUFFER_FOR_PLAYBACK_MS))); int multiplier = DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS / DEFAULT_BUFFER_FOR_PLAYBACK_MS; DefaultAllocator allocator = new DefaultAllocator(true, 0x10000); LoadControl control = new DefaultLoadControl(allocator, minBuffer, maxBuffer, playBuffer, playBuffer * multiplier); player = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(context), new DefaultTrackSelector(), control); player.setAudioStreamType(C.STREAM_TYPE_MUSIC); player.addListener(this); cacheMaxSize = (long)(options.getDouble("maxCacheSize", 0) * 1024); } @Override public void load(Track track, Promise callback) { loadCallback = callback; Uri url = track.url; String userAgent = Util.getUserAgent(context, "react-native-track-player"); DataSource.Factory factory = new DefaultDataSourceFactory(context, userAgent); MediaSource source; if(cacheMaxSize > 0 && !track.urlLocal) { File cacheDir = new File(context.getCacheDir(), "TrackPlayer"); Cache cache = new SimpleCache(cacheDir, new LeastRecentlyUsedCacheEvictor(cacheMaxSize)); factory = new CacheDataSourceFactory(cache, factory, 0, cacheMaxSize); } if(track.type == TrackType.DASH) { source = new DashMediaSource(url, factory, new DefaultDashChunkSource.Factory(factory), null, null); } else if(track.type == TrackType.HLS) { source = new HlsMediaSource(url, factory, null, null); } else if(track.type == TrackType.SMOOTH_STREAMING) { source = new SsMediaSource(url, factory, new DefaultSsChunkSource.Factory(factory), null, null); } else { source = new ExtractorMediaSource(url, factory, new DefaultExtractorsFactory(), null, null); } player.prepare(source); } @Override public void reset() { super.reset(); player.stop(); } @Override public void play() { player.setPlayWhenReady(true); } @Override public void pause() { player.setPlayWhenReady(false); } @Override public void stop() { player.stop(); } @Override public int getState() { return getState(player.getPlaybackState()); } private int getState(int playerState) { switch(playerState) { case SimpleExoPlayer.STATE_BUFFERING: return PlaybackStateCompat.STATE_BUFFERING; case SimpleExoPlayer.STATE_ENDED: return PlaybackStateCompat.STATE_STOPPED; case SimpleExoPlayer.STATE_IDLE: return PlaybackStateCompat.STATE_NONE; case SimpleExoPlayer.STATE_READY: return playing ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED; } return PlaybackStateCompat.STATE_NONE; } @Override public long getPosition() { return player.getCurrentPosition(); } @Override public long getBufferedPosition() { return player.getBufferedPosition(); } @Override public long getDuration() { return player.getDuration(); } @Override public void seekTo(long ms) { player.seekTo(ms); } @Override public float getSpeed() { return player.getPlaybackParameters().speed; } @Override public float getVolume() { return player.getVolume(); } @Override public void setVolume(float volume) { player.setVolume(volume); } @Override public boolean isRemote() { return false; } @Override public void destroy() { player.release(); } @Override public void onTimelineChanged(Timeline timeline, Object manifest) { } @Override public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { } @Override public void onLoadingChanged(boolean loading) { updateState(loading ? PlaybackStateCompat.STATE_BUFFERING : getState()); } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { playing = playWhenReady; updateState(getState(playbackState)); if(playbackState == SimpleExoPlayer.STATE_READY) { Utils.resolveCallback(loadCallback); loadCallback = null; } else if(playbackState == SimpleExoPlayer.STATE_ENDED) { if(hasNext()) { updateCurrentTrack(currentTrack + 1, null); } else { onEnd(); } } } @Override public void onPlayerError(ExoPlaybackException error) { Utils.rejectCallback(loadCallback, error); loadCallback = null; manager.onError(error); } @Override public void onPositionDiscontinuity() { } @Override public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { } }
true
31c4b4aae42578ca01d3ccd02497de6f4a8bbd23
Java
jenkinsci/github-plugin
/src/test/java/org/jenkinsci/plugins/github/util/JobInfoHelpersTest.java
UTF-8
3,330
2.203125
2
[ "MIT", "Apache-2.0" ]
permissive
package org.jenkinsci.plugins.github.util; import com.cloudbees.jenkins.GitHubPushTrigger; import hudson.model.FreeStyleProject; import hudson.model.Item; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.junit.ClassRule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.jenkinsci.plugins.github.util.JobInfoHelpers.isAlive; import static org.jenkinsci.plugins.github.util.JobInfoHelpers.isBuildable; import static org.jenkinsci.plugins.github.util.JobInfoHelpers.triggerFrom; import static org.jenkinsci.plugins.github.util.JobInfoHelpers.withTrigger; /** * @author lanwen (Merkushev Kirill) */ public class JobInfoHelpersTest { @ClassRule public static JenkinsRule jenkins = new JenkinsRule(); @Test public void shouldMatchForProjectWithTrigger() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(new GitHubPushTrigger()); assertThat("with trigger", withTrigger(GitHubPushTrigger.class).apply(prj), is(true)); } @Test public void shouldSeeProjectWithTriggerIsAliveForCleaner() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(new GitHubPushTrigger()); assertThat("with trigger", isAlive().apply(prj), is(true)); } @Test public void shouldNotMatchProjectWithoutTrigger() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); assertThat("without trigger", withTrigger(GitHubPushTrigger.class).apply(prj), is(false)); } @Test public void shouldNotMatchNullProject() throws Exception { assertThat("null project", withTrigger(GitHubPushTrigger.class).apply(null), is(false)); } @Test public void shouldReturnNotBuildableOnNullProject() throws Exception { assertThat("null project", isBuildable().apply(null), is(false)); } @Test public void shouldSeeProjectWithoutTriggerIsNotAliveForCleaner() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); assertThat("without trigger", isAlive().apply(prj), is(false)); } @Test public void shouldGetTriggerFromAbstractProject() throws Exception { GitHubPushTrigger trigger = new GitHubPushTrigger(); FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(trigger); assertThat("with trigger in free style job", triggerFrom((Item) prj, GitHubPushTrigger.class), is(trigger)); } @Test public void shouldGetTriggerFromWorkflow() throws Exception { GitHubPushTrigger trigger = new GitHubPushTrigger(); WorkflowJob job = jenkins.getInstance().createProject(WorkflowJob.class, "Test Workflow"); job.addTrigger(trigger); assertThat("with trigger in workflow", triggerFrom((Item) job, GitHubPushTrigger.class), is(trigger)); } @Test public void shouldNotGetTriggerWhenNoOne() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); assertThat("without trigger in project", triggerFrom((Item) prj, GitHubPushTrigger.class), nullValue()); } }
true
423ac54c1ed824fa276e94d62308aa5514b9bf8a
Java
EnzoCorrales/LabPApps
/NetBeansProjects/programacion-de-aplicaciones/UyTube/src/main/java/Entidades/uytube/Main.java
UTF-8
1,801
2.515625
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 Entidades.uytube; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * * @author gabrixstar */ public class Main { public static void main(String[] args) { new Inicio(); /*DtCanal dtc = new DtCanal("El Canal De Enzo", "Videos De Naruto",true); Canal c=new Canal(dtc); Usuario u; Fecha f = new Fecha(9, 4, 1998); u = new Usuario("Gabe", "Enzo", "Corrales", "gabrixstar@gmail.com",f); Categoria cat = new Categoria("Anime"); Video v = new Video("RockLeeVsGaara", "Pelea de Naruto Epica", 5, f, "www.youtube.com/watch?v=ltn2YITCdFw", true); Comentario com = new Comentario("Enzo","Muy buen video guacho"); DtLR datalr = new DtLR("Lista de Enzo", true, true, cat); ListaDeReproduccion Ldr = new ListaDeReproduccion(datalr); EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU"); EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); em.persist(f); em.persist(u); em.persist(v); em.persist(c); em.persist(Ldr); em.persist(cat); em.persist(com); em.getTransaction().commit(); System.out.println("Los Datos han sido ingresados!"); } catch(Exception e) { System.out.println(e); } em.close(); System.out.println("Adios!");*/ } }
true
da261fbc1569d885be5f6809fa5176f9bfa561a0
Java
wanghu110119/chen_mi
/src/main/java/com/mht/modules/sys/web/SysConfigController.java
UTF-8
3,711
1.914063
2
[]
no_license
package com.mht.modules.sys.web; import java.io.IOException; import java.util.List; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.mht.common.json.AjaxJson; import com.mht.modules.ident.service.SysProjectService; import com.mht.modules.sys.entity.Dict; import com.mht.modules.sys.entity.SysConfig; import com.mht.modules.sys.service.SysConfigService; /** * @ClassName: SysConfigController * @Description: 系统参数配置管理 * @author com.mhout.xyb * @date 2017年5月15日 上午11:02:05 * @version 1.0.0 */ @Controller @RequestMapping(value = "${adminPath}/sys/config") public class SysConfigController { @Autowired private SysConfigService sysConfigService; @Autowired private SysProjectService sysProjectService; /** * @Title: index * @Description: 跳转到备份页面 * @return * @author com.mhout.xyb */ @RequiresPermissions("sys:config:index") @RequestMapping(value = {"index", ""}) public String index(Model model) { model.addAttribute("projects", sysProjectService.findAll()); return "modules/sys/sysConfig"; } /** * @Title: getTypeList * @Description: 类型 * @param sysConfig * @param model * @return * @author com.mhout.xyb */ @ResponseBody @RequiresPermissions("sys:config:index") @RequestMapping(value = {"getTypeList"}) public List<SysConfig> getTypeList(SysConfig sysConfig, Model model){ return sysConfigService.findTypeList(sysConfig); } /** * @Title: list * @Description: 列表 * @param safeStrategy * @param model * @return * @author com.mhout.xyb */ @ResponseBody @RequiresPermissions("sys:config:index") @RequestMapping(value = {"list"}) public List<SysConfig> list(SysConfig sysConfig, String did, Model model) { sysConfig.setDict(new Dict(did)); return sysConfigService.findList(sysConfig); } /** * @Title: save * @Description: 编辑/保存配置 * @param safeStrategy * @param model * @return * @author com.mhout.xyb */ @ResponseBody @RequiresPermissions(value={"sys:config:add","sys:config:edit"},logical=Logical.OR) @RequestMapping(value = "save", method = RequestMethod.POST) public AjaxJson save(@RequestBody List<SysConfig> list, Model model){ sysConfigService.saveSafe(list); AjaxJson json = new AjaxJson(); json.setSuccess(true); json.setCode("0"); json.setMsg("操作成功"); return json; } /** * @Title: saveLogo * @Description: logo上传 * @param file * @return * @author com.mhout.xyb */ @ResponseBody @RequiresPermissions(value={"sys:config:add","sys:config:edit"},logical=Logical.OR) @RequestMapping(value = "saveLogo", method = RequestMethod.POST) public AjaxJson saveLogo(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam(value = "id", required = false) String id) { AjaxJson json = new AjaxJson(); try { sysConfigService.saveFile(file, id); json.setSuccess(true); json.setCode("0"); json.setMsg("操作成功"); } catch (IOException e) { json.setSuccess(false); json.setCode("1"); json.setMsg("操作失败"); } return json; } }
true
f506b7a0c233bf569ac2c5618a65981a570c9ce2
Java
xiaofud/stu_syllabus
/app/src/main/java/com/hjsmallfly/syllabus/parsers/OAParser.java
UTF-8
1,740
2.3125
2
[]
no_license
package com.hjsmallfly.syllabus.parsers; import com.hjsmallfly.syllabus.syllabus.OAObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.util.ArrayList; import java.util.List; /** * Created by smallfly on 15-11-27. */ public class OAParser { /* "DOCUMENTS": [ { "date": "2015-11-27", "department": "\u7406\u5b66\u9662", "title": "2015\u5e74\u6c55\u5934\u5927\u5b66\u6570\u503c\u4ee3\u6570\u9ad8\u7ea7\u7814\u8ba8\u4f1a\u901a\u77e5", "url": "http://notes.stu.edu.cn/page/maint/template/news/newstemplateprotal.jsp?templatetype=1&templateid=3&docid=4968" }, { */ public List<OAObject> parse_oa(String raw_data){ if (raw_data.isEmpty()){ return null; } JSONTokener jsonTokener = new JSONTokener(raw_data); List<OAObject> all_oa = new ArrayList<>(); try { JSONObject outter_most_obj = (JSONObject) jsonTokener.nextValue(); JSONArray document_array = outter_most_obj.getJSONArray("DOCUMENTS"); for(int i = 0 ; i < document_array.length() ; ++i){ JSONObject oa_json = (JSONObject) document_array.get(i); OAObject oaObject = new OAObject(); oaObject.title = oa_json.getString("title"); oaObject.date = oa_json.getString("date"); oaObject.url = oa_json.getString("url"); oaObject.department = oa_json.getString("department"); all_oa.add(oaObject); } return all_oa; } catch (JSONException e) { e.printStackTrace(); return null; } } }
true
85c0cf7de6675e6ec66f48d832908ea2c4a92c47
Java
shortcutssoftware/sc-ols-examples
/v2-examples/java/src/main/java/com/shortcuts/example/java/services/site/GetSitesResponse.java
UTF-8
342
1.828125
2
[ "ISC" ]
permissive
package com.shortcuts.example.java.services.site; import com.shortcuts.example.java.services.Paging; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; @Data @EqualsAndHashCode(callSuper = false) public class GetSitesResponse { private List<Site> sites; private Paging paging; private String href; }
true
db8e9a5dc5c3eb15fbdae3ecf7bfaa26764368e3
Java
chr1shaefn3r/talk-contract-tests
/motivation/src/test/java/interactions/ConsumerTest.java
UTF-8
963
2.53125
3
[]
no_license
package interactions; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; /** * There is <a href="https://github.com/robindanzinger/chadojs/blob/master/example/example.md">chado.js</a> for javascript * to perform these checks on unit test level. * * I do not know about a similar tool for java. */ class ConsumerTest { private final Provider provider = mock(Provider.class); private int input = anyInput(); @Test void returnTheProviderResultInUpperCase() { when(provider.interact(input)).thenReturn(new Result("mocked")); assertThat(consumerResult().message).isEqualTo("consumer(MOCKED)"); } private Result consumerResult() { Consumer consumer = new Consumer(provider); return consumer.upperCaseResult(input); } private int anyInput() { return -12; } }
true
e0b079aab203a0c3666b7caf594545548721615a
Java
alaminsheikh0/Angularjs-Restfull-project
/src/java/com/resources/WebServiceEmp.java
UTF-8
1,540
2.3125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.resources; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.pojo.Employee; import com.service.EmployeeService; @Path("/emp") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class WebServiceEmp { EmployeeService employeeService = new EmployeeService(); @GET public List<Employee> getAllEmployee() { return employeeService.getAllEmployee(); } @POST public Employee addEmployee(Employee e) { return employeeService.addEmployee(e); } @PUT @Path("/up/{employeeId}") public Employee updateEmployee(@PathParam("employeeId") int id, Employee e) { e.setId(id); return employeeService.updateEmployee(e); } @DELETE @Path("/del/{employeeId}") public void deleteEmployee(@PathParam("employeeId") int id) { employeeService.removeEmployee(id); } @GET @Path("/{employeeId}") public Employee getEmployeeById(@PathParam("employeeId") int id) { return employeeService.findEmployeeById(id); } }
true
d38dfbf12ed8146003e1a5fb11405dfb7de90305
Java
hm-quinn/A3Prj
/GameObjectCollection.java
UTF-8
1,332
3.1875
3
[]
no_license
package com.mycompany.a3; import java.util.ArrayList; public class GameObjectCollection implements ICollection{ private ArrayList<GameObject> gameObj; public GameObjectCollection() { gameObj = new ArrayList<GameObject>(); } @Override public void add(GameObject object) { // TODO Auto-generated method stub gameObj.add(object); } @Override public IIterator getIterator() { // TODO Auto-generated method stub return new ObjectIterator(); } @Override public void remove(GameObject object) { // TODO Auto-generated method stub gameObj.remove(object); } @Override public int getSize() { return gameObj.size(); } public void clear() { // TODO Auto-generated method stub gameObj.clear(); } private class ObjectIterator implements IIterator { private int index; public ObjectIterator() { index = -1; } @Override public boolean hasNext() { if (gameObj.size() <= 0) return false; if (index == gameObj.size() - 1) { return false; } return true; } @Override public void remove() { gameObj.remove(index); index--; } @Override public GameObject getNext() { // TODO Auto-generated method stub index++; return gameObj.get(index); } } }
true
5bb84d947915b98595b793e1015173e01d760287
Java
MightyDuckD/HTLSTPExercise
/Lab07/src/main/java/at/mightyduck/isbn/ISBNLib.java
UTF-8
4,654
2.296875
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 at.mightyduck.isbn; import at.mightyduck.isbn.ISBNException; import at.mightyduck.isbn.ISBN; import at.mightyduck.isbn.xml.EAN_UCC; import at.mightyduck.isbn.xml.Group; import at.mightyduck.isbn.xml.RangeMessage; import at.mightyduck.isbn.xml.Rule; import java.io.InputStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.*; /** * https://www.isbn-international.org/sites/default/files/ISBN%20Manual%202012%20-corr.pdf * * @author Simon */ public class ISBNLib { private static ISBNLib instance; private RangeMessage lib; private ISBNLib() { try { JAXBContext jc = JAXBContext.newInstance(RangeMessage.class); Unmarshaller un = jc.createUnmarshaller(); InputStream in = ISBNLib.class.getResourceAsStream("/ISBNRangeMessage.xml"); lib = (RangeMessage) un.unmarshal(in); } catch (JAXBException ex) { Logger.getLogger(ISBNLib.class.getName()).log(Level.SEVERE, null, ex); } } public static synchronized ISBNLib getInstance() { return (instance == null) ? (instance = new ISBNLib()) : instance; } public static Rule find(List<Rule> rules, String isbn) { for (Rule r : rules) { if (r.matches(isbn)) { return r; } } return null; } public static Group find(List<Group> groups, ISBN isbn) { for (Group g : groups) { if (g.matches(isbn)) { return g; } } return null; } public ISBN clean(String input) { ISBN result = new ISBN(); boolean calculateChecksum = false; //is the input valid String isbn = input.replace("-", ""); if (!isbn.matches("\\d{12}[\\dXx]{1}")) { throw new ISBNException("Falsche Länge oder ungültige Zeichen"); } //should checksum be calculated afterwards? if (isbn.endsWith("x") || isbn.endsWith("X")) { System.out.println("i should calc the checksum"); isbn = isbn.replaceAll("[xX]", "0"); calculateChecksum = true; } for (EAN_UCC ean : lib.getEan_ucc()) { if (isbn.startsWith(ean.getPrefix())) { //Set the Prefix result.setPrefix(ean.getPrefix()); result.setRegistrationGroupAgency(ean.getAgency()); isbn = isbn.substring(ean.getPrefix().length()); //Find the registration group Rule r1 = find(ean.getRules(), isbn); if (r1 == null || r1.isInvalid()) { throw new ISBNException("Unbekannte Registration Group"); } //Set the registration group result.setRegistrationGroup(isbn.substring(0, r1.getLength())); isbn = isbn.substring(r1.getLength()); //Find the rules of the registration group Group g = find(lib.getRegistrationGroups(), result); if (g == null) { throw new ISBNException("Definition der Registration Group konnte nicht gefunden werden"); } //Find the registrant Rule r2 = find(g.getRules(), isbn); if (r2 == null || r2.isInvalid()) { throw new ISBNException("Unbekannter Registrant"); } //Set the remaining parts result.setRegistrant(isbn.substring(0, r2.getLength())); result.setRegistrantAgency(g.getAgency()); result.setPublication(isbn.substring(r2.getLength(), isbn.length() - 1)); result.setCheckDigit(isbn.substring(isbn.length() - 1, isbn.length())); System.out.println("done with isbn cleaning"); System.out.println(isbn); System.out.println(calculateChecksum); //Calculated the checksum if necessary if(calculateChecksum) { result.setCheckDigit(result.calculateCheckDigit()); } return result; } } throw new ISBNException("Unbekanntes EAN Prefix"); } }
true
191b4806b0f982596197e4e70012c1ec18b46e32
Java
NthPortal/uhc-plugin
/src/main/java/com/github/nthportal/uhc/events/UHCMinuteEvent.java
UTF-8
204
2
2
[ "Apache-2.0" ]
permissive
package com.github.nthportal.uhc.events; public class UHCMinuteEvent { public final int minuteNumber; public UHCMinuteEvent(int minuteNumber) { this.minuteNumber = minuteNumber; } }
true
7625efd177f8b4d08c625787a6ed5448b179bb78
Java
bagasap10/OOADLabProject
/src/view/RegisterFrame.java
UTF-8
5,163
2.53125
3
[]
no_license
package view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import java.util.Vector; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JTextArea; import javax.swing.JTextField; import controller.UserController; public class RegisterFrame extends JFrame implements ActionListener{ JPanel mainPanel, northPanel, southPanel, centerPanel, genderPanel; JLabel registerLabel, nameLabel, addressLabel, genderLabel, ageLabel, profileLabel, profileImageLabel; JTextField nameField; JTextArea addressArea; JRadioButton maleBtn, femaleBtn; ButtonGroup genderGrup; JComboBox ageBox; // ImageIcon profileIcon; JCheckBox tnc; //Add new field JLabel usernameLabel, passwordLabel, confirmPasswordLabel; JTextField usernameField; JPasswordField passwordField, confirmPasswordField; JButton registerbtn; Vector<Integer> age = new Vector<>(); public RegisterFrame() { mainPanel = new JPanel(new BorderLayout()); northPanel = new JPanel(); southPanel = new JPanel(); //Change grid Layout to 9 centerPanel = new JPanel(new GridLayout(9, 2)); genderPanel = new JPanel(new FlowLayout()); genderGrup = new ButtonGroup(); //NORTH PANEL registerLabel = new JLabel("Register"); registerLabel.setForeground(Color.BLUE); registerLabel.setFont(new Font("Calibri", Font.BOLD, 25)); northPanel.add(registerLabel); //CENTER PANEL nameLabel = new JLabel("Name: "); nameField = new JTextField(); addressLabel = new JLabel("Address"); addressArea = new JTextArea(); genderLabel = new JLabel("Gender"); maleBtn = new JRadioButton("Male"); femaleBtn = new JRadioButton("Female"); //Add kedalam Button Group genderGrup.add(femaleBtn); genderGrup.add(maleBtn); genderPanel.add(maleBtn); genderPanel.add(femaleBtn); ageLabel = new JLabel("Age"); for (int i = 1; i < 101; i++) { age.add(i); } ageBox = new JComboBox(age); usernameLabel = new JLabel("Username: "); usernameField = new JTextField(); passwordLabel = new JLabel("Password: "); passwordField = new JPasswordField(); confirmPasswordLabel = new JLabel("Confirm Password: "); confirmPasswordField = new JPasswordField(); // profileLabel = new JLabel("Profile"); // //image icon harus di masukan kedalam label // profileIcon = new ImageIcon("IU.png"); // profileImageLabel = new JLabel(profileIcon); tnc = new JCheckBox("Terms and Condition"); centerPanel.add(nameLabel); centerPanel.add(nameField); //Add usernameField centerPanel.add(usernameLabel); centerPanel.add(usernameField); centerPanel.add(addressLabel); centerPanel.add(addressArea); centerPanel.add(genderLabel); centerPanel.add(genderPanel); centerPanel.add(ageLabel); centerPanel.add(ageBox); //Add password field centerPanel.add(passwordLabel); centerPanel.add(passwordField); centerPanel.add(confirmPasswordLabel); centerPanel.add(confirmPasswordField); //IMAGE // centerPanel.add(profileLabel); // centerPanel.add(profileImageLabel); centerPanel.add(tnc); //SOUTH registerbtn = new JButton("Register"); registerbtn.addActionListener(this); southPanel.add(registerbtn); //SET MAIN PANEL mainPanel.add(northPanel, BorderLayout.NORTH); mainPanel.add(southPanel, BorderLayout.SOUTH); mainPanel.add(centerPanel, BorderLayout.CENTER); add(mainPanel); //SET JFrame setSize(new Dimension(600,600)); setResizable(false); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource().equals(registerbtn)) { String name = nameField.getText(); String username = usernameField.getText(); String password = String.valueOf(passwordField.getPassword()); String address = addressArea.getText(); String confirmsPassword = String.valueOf(confirmPasswordField.getPassword()); int age = Integer.parseInt(ageBox.getSelectedItem().toString()); String gender = null; if(femaleBtn.isSelected() == true) { gender = femaleBtn.getText(); }else if(maleBtn.isSelected()== true ) { gender = maleBtn.getText(); } //Coba untuk register try { UserController.getInstance().registerUser(username, name, password, address, age, gender, confirmsPassword); JOptionPane.showMessageDialog(null, "Registered successfully!", "Register", JOptionPane.INFORMATION_MESSAGE); } catch (IllegalArgumentException e1) { JOptionPane.showMessageDialog(null, e1.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }
true
79064d43019e3aa54fc13d3ec95e85e1cb492aab
Java
00liberty00/ml_start
/src/ml/controller/ReportsGeneralController.java
UTF-8
27,092
1.640625
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 ml.controller; import java.math.BigDecimal; import java.net.URL; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.ResourceBundle; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import ml.dialog.DialogAlert; import ml.model.Arrival; import ml.model.ArrivalList; import ml.model.CaseRecord; import ml.model.CategoryGoods; import ml.model.Check; import ml.model.CheckList; import ml.model.GeneralReportsModel; import ml.model.Goods; import ml.model.Writeoff; import ml.model.WriteoffList; import ml.query.arrival.BetweenDatesArrival; import ml.query.cancellation.BetweenDatesCancellation; import ml.query.caserecord.BetweenDatesCaseRecords; import ml.query.categoryGood.CategoryGoodList; import ml.query.categoryGood.CategoryGoodsByName; import ml.query.check.BetweenDatesCheck; import ml.query.check.CheckListByIdGood; import ml.query.goods.GoodsListByCategory; import ml.table.ReportsGeneralTable; /** * FXML Controller class * * @author Dave */ public class ReportsGeneralController implements Initializable { @FXML private TableView<ReportsGeneralTable> tableReportsGeneral; @FXML private TableColumn<ReportsGeneralTable, String> nameColumn; @FXML private TableColumn<ReportsGeneralTable, BigDecimal> sumPriceAmountColumn; @FXML private TableColumn<ReportsGeneralTable, BigDecimal> sumProfitColumn; @FXML private TableColumn<ReportsGeneralTable, BigDecimal> quantitySoldColumn; @FXML private TableColumn<ReportsGeneralTable, BigDecimal> quantityArrivalColumn; @FXML private TableColumn<ReportsGeneralTable, BigDecimal> quantityCancelColumn; @FXML private TableColumn<ReportsGeneralTable, BigDecimal> balanceColumn; @FXML private ComboBox<String> categoryGood; @FXML private DatePicker dateFrom; @FXML private DatePicker dateTo; @FXML private Button okReports; @FXML private Label sumSalesLabel; @FXML private Label sumArrivalLabel; @FXML private Label sumCancellLabel; @FXML private Label sumGoodSalesLabel; @FXML private Label sumGoodArrivalLabel; @FXML private Label sumGoodCancellLabel; @FXML private Label sumProfitLabel; @FXML private Label sumProfitPeriodLabel; @FXML private TabPane tabPane; @FXML private Tab reportOfGoodsTabPane; @FXML private Tab reportOfMoneyTabPane; @FXML private Tab reportMoveOfGoodsTabPane; private String textComboBox; private List<CategoryGoods> categoryList; private CheckList chl; private List<CheckList> checkList; private List<Check> check; private List<Arrival> arrival; private List<ArrivalList> arrivalList; private List<WriteoffList> cancellation; private List<WriteoffList> cancellationList; private List<CaseRecord> caseRecords; private BigDecimal sumProfitFromTable = new BigDecimal(0.00); private CategoryGoodList categoryGoodList = new CategoryGoodList(); private ObservableList<String> options = FXCollections.observableArrayList(); private CategoryGoodsByName categoryGoodsByName = new CategoryGoodsByName(); private CheckListByIdGood checkListByIdGood = new CheckListByIdGood(); private CategoryGoods categoryGoods = new CategoryGoods(); private Goods goods = new Goods(); private List<Goods> listGoods; private GoodsListByCategory goodsListByCategory = new GoodsListByCategory(); private ObservableList<ReportsGeneralTable> reportsGeneralData = FXCollections.observableArrayList(); private BetweenDatesCheck betweenDatesCheck = new BetweenDatesCheck(); private BetweenDatesArrival betweenDatesArrival = new BetweenDatesArrival(); private BetweenDatesCancellation betweenDatesCancellation = new BetweenDatesCancellation(); private BetweenDatesCaseRecords betweenDatesCaseRecords = new BetweenDatesCaseRecords(); private DialogAlert dialogAlert = new DialogAlert(); private GeneralReportsModel generalReportsModel = new GeneralReportsModel(); @FXML private void getCategoryGood(ActionEvent event) { //возврат выбранной из списка id_category textComboBox = categoryGood.getValue(); if (textComboBox != null) { categoryGoodsByName.setCode(textComboBox); categoryGoods = categoryGoodsByName.displayResult(); } } @FXML private void getDateFrom(ActionEvent event) { //getDate(dateFrom.getValue()); } @FXML private void getDateTo(ActionEvent event) { //getDate(dateTo.getValue()); } @FXML private void getOk(ActionEvent event) { if (reportOfGoodsTabPane.isSelected()) { if (textComboBox == null) { dialogAlert.alert("Внимание!!!", "", "Выберите категорию товара"); } else { reportsOfGoods(); } } if (reportOfMoneyTabPane.isSelected()) { } if (reportMoveOfGoodsTabPane.isSelected()) { reportsMoveOfGoods(); } } //Отчет по движению товара private void reportsMoveOfGoods() { BigDecimal sumCheck = new BigDecimal(0.00); BigDecimal sumArrival = new BigDecimal(0.00); BigDecimal sumCancellation = new BigDecimal(0.00); Arrival a; Writeoff w; //список CaseRecords по дате betweenDatesCaseRecords.setDate(dateFrom.getValue().toString(), dateTo.getValue().toString()); betweenDatesCaseRecords.setDates(dateFrom.getValue(), dateTo.getValue()); caseRecords = betweenDatesCaseRecords.displayResult(); //список чеков по дате betweenDatesCheck.setDateMoveGoods(dateFrom.getValue(), dateTo.getValue()); for (int i = 0; i < caseRecords.size(); i++) { a = caseRecords.get(i).getArrival(); w = caseRecords.get(i).getWriteOff(); if (a != null) { sumArrival = sumArrival.add(a.getSumArrival()); } if (w != null) { sumCancellation = sumCancellation.add(w.getSum()); } } sumSalesLabel.setText(betweenDatesCheck.displayResult().toString()); sumArrivalLabel.setText(sumArrival.toString()); sumCancellLabel.setText(sumCancellation.toString()); sumProfitPeriodLabel.setText(betweenDatesCaseRecords.displayResultX().toString()); } //Добавить 00:00:00 private Date addStartDay(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); return cal.getTime(); } //Добавить 23:59:59 private Date addEndDay(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); return cal.getTime(); } //Отчет по товару private void reportsOfGoods() { List<String> nameCheck = new ArrayList<String>(); List<BigDecimal> amountCheck = new ArrayList<BigDecimal>(); List<String> nameNewCheck = new ArrayList<String>(); List<BigDecimal> amountNewCheck = new ArrayList<BigDecimal>(); List<String> nameArrival = new ArrayList<String>(); List<BigDecimal> amountArrival = new ArrayList<BigDecimal>(); List<String> nameNewArrival = new ArrayList<String>(); List<BigDecimal> amountNewArrival = new ArrayList<BigDecimal>(); List<String> nameCancell = new ArrayList<String>(); List<BigDecimal> amountCancell = new ArrayList<BigDecimal>(); List<String> nameNewCancell = new ArrayList<String>(); List<BigDecimal> amountNewCancell = new ArrayList<BigDecimal>(); List<BigDecimal> balance = new ArrayList<BigDecimal>(); List<BigDecimal> balanceArrival = new ArrayList<BigDecimal>(); List<BigDecimal> balanceCancell = new ArrayList<BigDecimal>(); List<BigDecimal> balanceNew = new ArrayList<BigDecimal>(); List<BigDecimal> profit = new ArrayList<BigDecimal>(); List<BigDecimal> profitNew = new ArrayList<BigDecimal>(); BigDecimal sumCheck = new BigDecimal(0.00); BigDecimal sumArrival = new BigDecimal(0.00); BigDecimal sumCancellation = new BigDecimal(0.00); String nCheck; BigDecimal amCheck; String nArrival; BigDecimal amArrival; String nCancell; BigDecimal amCancell; BigDecimal pr; BigDecimal b; //удаление строк в таблице for (int i = -1; i < tableReportsGeneral.getItems().size(); i++) { tableReportsGeneral.getItems().clear(); } //Convert LocalDate to Date Date dateStart = Date.from(dateFrom.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant()); Date dateEnd = Date.from(dateTo.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant()); //System.out.println("Start:"); //System.out.println("Fin:"); //список чеков по дате betweenDatesCheck.setDate(dateFrom.getValue(), dateTo.getValue(), categoryGoods); checkList = betweenDatesCheck.displayResultPlus(); //список прихода по дате betweenDatesArrival.setDate(dateFrom.getValue(), dateTo.getValue(), categoryGoods); arrivalList = betweenDatesArrival.displayResultPlus(); //список списания по дате betweenDatesCancellation.setDate(dateFrom.getValue(), dateTo.getValue(), categoryGoods); cancellationList = betweenDatesCancellation.displayResultPlus(); //Вывод списка проданного товара по категории for (int i = 0; i < checkList.size(); i++) { //checkList.getGoods().getCategoryGoods(); //Вывод на экран если категориии одинаковы с выбранной категорией if (categoryGoods == checkList.get(i).getGoods().getCategoryGoods()) { nameCheck.add(checkList.get(i).getGoods().getName()); amountCheck.add(checkList.get(i).getAmount()); profit.add(checkList.get(i).getProfit()); balance.add(checkList.get(i).getGoods().getResidue()); } } //Сумма проданного товара по категории sumCheck = betweenDatesCheck.displayResultSumCheck(); //Сумма приходного товара по категории sumArrival = betweenDatesArrival.displayResultSumArrival(); //Сумма списанного товара по категории sumCancellation = betweenDatesCancellation.displayResultSumCancellation(); //Вывод списка приходного товара по категории for (int i = 0; i < arrivalList.size(); i++) { //checkList.getGoods().getCategoryGoods(); //Вывод на экран если категориии одинаковы с выбранной категорией if (categoryGoods == arrivalList.get(i).getGoods().getCategoryGoods()) { nameArrival.add(arrivalList.get(i).getGoods().getName()); amountArrival.add(arrivalList.get(i).getAmount()); balanceArrival.add(arrivalList.get(i).getGoods().getResidue()); //Сумма приходного товара по категории //sumArrival = sumArrival.add(arrivalList.get(i).getGoods().getPriceOpt().multiply(arrivalList.get(i).getAmount())); } } /*for (Arrival ar : arrival) { Set<ArrivalList> s = ar.getArrivalLists(); Iterator<ArrivalList> it = s.iterator(); while (it.hasNext()) { ArrivalList arrivalList = it.next(); arrivalList.getGoods().getCategoryGoods(); //Вывод на экран если категориии одинаковы с выбранной категорией if (categoryGoods == arrivalList.getGoods().getCategoryGoods()) { nameArrival.add(arrivalList.getGoods().getName()); amountArrival.add(arrivalList.getAmount()); balanceArrival.add(arrivalList.getGoods().getResidue()); //Сумма приходного товара по категории sumArrival = sumArrival.add(arrivalList.getGoods().getPriceOpt().multiply(arrivalList.getAmount())); } } };*/ //Вывод списка списанного товара по категории for (int i = 0; i < cancellationList.size(); i++) { //checkList.getGoods().getCategoryGoods(); //Вывод на экран если категориии одинаковы с выбранной категорией if (categoryGoods == cancellationList.get(i).getGoods().getCategoryGoods()) { nameCancell.add(cancellationList.get(i).getGoods().getName()); amountCancell.add(cancellationList.get(i).getAmount()); balanceCancell.add(cancellationList.get(i).getGoods().getResidue()); //Сумма приходного товара по категории //sumArrival = sumArrival.add(arrivalList.get(i).getGoods().getPriceOpt().multiply(arrivalList.get(i).getAmount())); } } /*for (Writeoff wr : cancellation) { Set<WriteoffList> s = wr.getWriteoffLists(); Iterator<WriteoffList> it = s.iterator(); while (it.hasNext()) { WriteoffList writeoffList = it.next(); writeoffList.getGoods().getCategoryGoods(); //Вывод на экран если категориии одинаковы с выбранной категорией if (categoryGoods == writeoffList.getGoods().getCategoryGoods()) { nameCancell.add(writeoffList.getGoods().getName()); amountCancell.add(writeoffList.getAmount()); balanceCancell.add(writeoffList.getGoods().getResidue()); //Сумма списанного товара по категории sumCancellation = sumCancellation.add(writeoffList.getGoods().getPrice().multiply(writeoffList.getAmount())); } } };*/ //Запись в новый список названия проданного товара for (int i = 0; i < nameCheck.size(); i++) { nCheck = nameCheck.get(i); //amCheck = amountCheck.get(i); b = balance.get(i); //если новый список пуст, то записать в него первое название товара и кол-во 0 if (nameNewCheck.isEmpty()) { nameNewCheck.add(nCheck); amountNewCheck.add(new BigDecimal(0.00)); amountNewArrival.add(new BigDecimal(0.00)); amountNewCancell.add(new BigDecimal(0.00)); profitNew.add(new BigDecimal(0.00)); balanceNew.add(b); } //Запись в новый List не одинаковых названий продуктов for (int j = 0; j < nameNewCheck.size(); j++) { if (!nameNewCheck.contains(nCheck)) { nameNewCheck.add(nCheck); amountNewCheck.add(new BigDecimal(0.00)); amountNewArrival.add(new BigDecimal(0.00)); amountNewCancell.add(new BigDecimal(0.00)); profitNew.add(new BigDecimal(0.00)); balanceNew.add(b); } } } //Запись в новый список названия приходного товара for (int i = 0; i < nameArrival.size(); i++) { nArrival = nameArrival.get(i); //amArrival = amountArrival.get(i); b = balanceArrival.get(i); //если новый список пуст, то записать в него первое название товара и кол-во 0 if (nameNewCheck.isEmpty()) { nameNewCheck.add(nArrival); amountNewCheck.add(new BigDecimal(0.00)); amountNewArrival.add(new BigDecimal(0.00)); amountNewCancell.add(new BigDecimal(0.00)); profitNew.add(new BigDecimal(0.00)); balanceNew.add(b); } //Запись в новый List не одинаковых названий продуктов for (int j = 0; j < nameNewCheck.size(); j++) { if (!nameNewCheck.contains(nArrival)) { nameNewCheck.add(nArrival); amountNewCheck.add(new BigDecimal(0.00)); amountNewArrival.add(new BigDecimal(0.00)); amountNewCancell.add(new BigDecimal(0.00)); profitNew.add(new BigDecimal(0.00)); balanceNew.add(b); } } } //Запись в новый список названия списанного товара for (int i = 0; i < nameCancell.size(); i++) { nCancell = nameCancell.get(i); //amCancell = amountCancell.get(i); b = balanceCancell.get(i); //если новый список пуст, то записать в него первое название товара и кол-во 0 if (nameNewCheck.isEmpty()) { nameNewCheck.add(nCancell); amountNewCheck.add(new BigDecimal(0.00)); amountNewArrival.add(new BigDecimal(0.00)); amountNewCancell.add(new BigDecimal(0.00)); profitNew.add(new BigDecimal(0.00)); balanceNew.add(b); } //Запись в новый List не одинаковых названий продуктов for (int j = 0; j < nameNewCheck.size(); j++) { if (!nameNewCheck.contains(nCancell)) { nameNewCheck.add(nCancell); amountNewCheck.add(new BigDecimal(0.00)); amountNewArrival.add(new BigDecimal(0.00)); amountNewCancell.add(new BigDecimal(0.00)); profitNew.add(new BigDecimal(0.00)); balanceNew.add(b); } } } //подссчет кол-ва и остатка товара по названию for (int i = 0; i < nameNewCheck.size(); i++) { String nn = nameNewCheck.get(i); for (int j = 0; j < nameCheck.size(); j++) { if (nn.equals(nameCheck.get(j))) { BigDecimal soldGood; BigDecimal soldProfit; BigDecimal arrivalGood; BigDecimal cancellGood; soldGood = amountNewCheck.get(i); soldGood = soldGood.add(amountCheck.get(j)); soldProfit = profitNew.get(i); soldProfit = soldProfit.add(profit.get(j)); arrivalGood = amountNewArrival.get(i); arrivalGood = arrivalGood.add(new BigDecimal(0.00)); cancellGood = amountNewCancell.get(i); cancellGood = cancellGood.add(new BigDecimal(0.00)); amountNewCheck.set(i, soldGood); profitNew.set(i, soldProfit); amountNewArrival.set(i, arrivalGood); } } for (int j = 0; j < nameArrival.size(); j++) { if (nn.equals(nameArrival.get(j))) { BigDecimal arrivalGood; arrivalGood = amountNewArrival.get(i); arrivalGood = arrivalGood.add(amountArrival.get(j)); amountNewArrival.set(i, arrivalGood); } } for (int j = 0; j < nameCancell.size(); j++) { if (nn.equals(nameCancell.get(j))) { BigDecimal cancellGood; cancellGood = amountNewCancell.get(i); cancellGood = cancellGood.add(amountCancell.get(j)); amountNewCancell.set(i, cancellGood); } } } sumGoodSalesLabel.setText(sumCheck.toString()); sumGoodArrivalLabel.setText(sumArrival.toString()); sumGoodCancellLabel.setText(sumCancellation.toString()); //Расчет суммы прибыли sumProfitFromTable = profitNew.stream().reduce(BigDecimal.ZERO, BigDecimal::add); sumProfitLabel.setText(sumProfitFromTable.toString()); //запись в таблицу for (int i = 0; i < nameNewCheck.size(); i++) { generalReportsModel.setNameColumn(nameNewCheck.get(i)); generalReportsModel.setQuantitySoldColumn(new BigDecimal(amountNewCheck.get(i).toString())); generalReportsModel.setQuantityArrivalColumn(new BigDecimal(amountNewArrival.get(i).toString())); generalReportsModel.setQuantityCancelColumn(new BigDecimal(amountNewCancell.get(i).toString())); generalReportsModel.setBalanceColumn(balanceNew.get(i)); generalReportsModel.setSumProfitColumn(new BigDecimal(profitNew.get(i).toString())); displayResult(generalReportsModel); } } /** * Метод для просмотра результатов в "JTable". */ private void displayResult(GeneralReportsModel generalReportsModel) { nameColumn.setCellValueFactory(new PropertyValueFactory<ReportsGeneralTable, String>("name")); sumPriceAmountColumn.setCellValueFactory(new PropertyValueFactory<ReportsGeneralTable, BigDecimal>("sumPriceAmount")); sumProfitColumn.setCellValueFactory(new PropertyValueFactory<ReportsGeneralTable, BigDecimal>("sumProfit")); quantitySoldColumn.setCellValueFactory(new PropertyValueFactory<ReportsGeneralTable, BigDecimal>("quantitySold")); quantityArrivalColumn.setCellValueFactory(new PropertyValueFactory<ReportsGeneralTable, BigDecimal>("quantityArrival")); quantityCancelColumn.setCellValueFactory(new PropertyValueFactory<ReportsGeneralTable, BigDecimal>("quantityCancel")); balanceColumn.setCellValueFactory(new PropertyValueFactory<ReportsGeneralTable, BigDecimal>("balance")); ReportsGeneralTable reports = new ReportsGeneralTable(); for (int i = 0; i < 1; i++) { reports.setName(generalReportsModel.getNameColumn()); reports.setQuantitySold(generalReportsModel.getQuantitySoldColumn()); reports.setQuantityArrival(generalReportsModel.getQuantityArrivalColumn()); reports.setQuantityCancel(generalReportsModel.getQuantityCancelColumn()); reports.setBalance(generalReportsModel.getBalanceColumn()); reports.setSumProfit(generalReportsModel.getSumProfitColumn()); // заполняем таблицу данными reportsGeneralData.add(reports); } tableReportsGeneral.setItems(reportsGeneralData); } /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO dateFrom.setValue(LocalDate.now()); dateTo.setValue(LocalDate.now()); //Список всего товара System.out.println("Start: Список категорий всего товара"); categoryList = categoryGoodList.getList(); categoryList.forEach((cg) -> { options.add(cg.getName()); }); categoryGood.setItems(options); System.out.println("Fin: Список категорий всего товара"); System.out.println(""); //Заполнение ComboBox в зависимости от выбраного Tab tabPane.getSelectionModel().selectedItemProperty().addListener( new ChangeListener<Tab>() { @Override public void changed(ObservableValue<? extends Tab> ov, Tab t, Tab t1) { String nameTab = ov.getValue().getId(); switch (nameTab) { case "reportOfGoodsTabPane": categoryGood.getItems().clear(); //Список всего товара categoryList = categoryGoodList.getList(); categoryList.forEach((cg) -> { options.add(cg.getName()); }); categoryGood.setItems(options); break; case "reportOfMoneyTabPane": categoryGood.getItems().clear(); break; case "reportMoveOfGoodsTabPane": categoryGood.getItems().clear(); break; default: break; } } }); } }
true
e1ea56271c56a228453f02acc13e1647e70ffcc5
Java
psun2/Korea-IT-Academy
/(back up) _ 오전/study_a/jj_work/javaProj/src/oops_p/MethodMain.java
UHC
1,149
3.75
4
[]
no_license
package oops_p; class MethodCla{ int a = 10; //param X, ret X void meth_1() { //޼ҵ System.out.println("meth_1() "); } //param O, ret X void meth_2(int b, String c) {//Ű System.out.println("meth_2() :"+b+","+c); //return 123; return; } //param X, ret O //int, int meth_3() { int meth_3() { System.out.println("meth_3() "); //return 100, 200; return 100; //ϰ ϳ Ȥ //return 100; return ѹ } //param O, ret O int meth_4(int b, int c) { System.out.println("meth_4() :"+b+","+c); return b*c; } } public class MethodMain { public static void main(String[] args) { MethodCla mc = new MethodCla(); //int r1 = mc.meth_1(); //޼ҵ ȣ ޼ҵ忡 Ұ mc.meth_1(); //mc.meth_2(); mc.meth_2(100,"Ʊ"); int r3 = mc.meth_3(); System.out.println("r3:"+r3); int r4 = mc.meth_4(5,6); System.out.println("r4:"+r4); System.out.println("r5:"+mc.meth_4(10,6)); } }
true
a82f60d27ec5ac9011af12db7536e17e227be799
Java
patrickdamery/AudioStreamer
/src/main/java/Services/ConnectionListener.java
UTF-8
5,370
3.109375
3
[]
no_license
package Services; import Custom.Attributes; import org.w3c.dom.Attr; import java.io.IOException; import java.io.InputStreamReader; import java.net.*; /** * Class that handles connection requests. * Property of Cabalry Limited. * Author: Robert Patrick Damery */ public class ConnectionListener implements Runnable { private int listenPort = 50010; private DatagramSocket serverSocket; private DatagramPacket packet; private byte[] data; public void run() { // Set up Server Sockets. try { serverSocket = new DatagramSocket(listenPort); } catch(IOException io) { io.printStackTrace(); } while(Attributes.active) { try { // Listen for any incoming connections. data = new byte[1024]; packet = new DatagramPacket(data, data.length); serverSocket.receive(packet); System.out.println("Connected to client"); // Extract port and ip. InetAddress ip = packet.getAddress(); int port = packet.getPort(); String received = new String(packet.getData()); received = received.trim(); int clientLocalPort = Integer.parseInt(received); // Declare clientAddress for later use. InetSocketAddress clientAddress = new InetSocketAddress(ip, portSelector(ip, port, clientLocalPort)); // Prepare new port to communicate with client and send dedicatedPort to client. DatagramSocket dedicatedSocket = new DatagramSocket(); dedicatedSocket.setSoTimeout(3000); String dedicatedPort = Integer.toString(dedicatedSocket.getLocalPort()); data = dedicatedPort.getBytes(); System.out.println("Dedicated Port: "+dedicatedPort); packet = new DatagramPacket(data, data.length, clientAddress); serverSocket.send(packet); System.out.println("Sent Client Dedicated Port."); // Now wait for client to establish contact with dedicated Datagram socket. data = new byte[1024]; packet = new DatagramPacket(data, data.length); dedicatedSocket.receive(packet); System.out.println("Received pack."); // Now add socket to listener Sockets. Attributes.listenerSocket.add(dedicatedSocket); // Now add Socket Address to the listener Addresses. Attributes.listenerAddress.add(clientAddress); System.out.println("Added to listenerSocket and listenerAddress. "); } catch(IOException io) { io.printStackTrace(); } } } /** * Function picks which port to use when communicating with client. This is done in case client is behind * a NAT firewall. * @param ip IP Address of client. * @param port Port received from Packet. * @param localPort Port received from client Data. * @return Selected Port to use for Data transmission. */ private int portSelector(InetAddress ip, int port, int localPort) { // Define default value for selected port. int selectedPort = port; // Compare ports, if not the same test each one. if (port != localPort) { System.out.println("Ports don't match."); // Receive Reply. boolean decision = false; int counter = 1; while(!decision) { if(counter == 3) { return selectedPort; } try { // Reply to clientLocalPort. String reply = "TEST"; data = reply.getBytes(); if(counter == 1) { InetSocketAddress clientAddress = new InetSocketAddress(ip, localPort); packet = new DatagramPacket(data, data.length, clientAddress); serverSocket.send(packet); System.out.println("Testing clientLocalPort."); } else { InetSocketAddress clientAddress = new InetSocketAddress(ip, port); packet = new DatagramPacket(data, data.length, clientAddress); serverSocket.send(packet); System.out.println("Testing port."); } byte[] confirmationData = new byte[1024]; DatagramPacket confirmationPacket = new DatagramPacket(confirmationData, confirmationData.length); serverSocket.receive(confirmationPacket); String received = new String(packet.getData()); received = received.trim(); if(received.equalsIgnoreCase("GOOD")) { decision = true; if(counter == 2) { selectedPort = localPort; } } } catch (IOException io) { System.out.println("Port check failed."); counter++; } } } return selectedPort; } }
true
1d07d5fafaa45361c815cf0517027d0fc29741d4
Java
JoyPanda/wangxian_server
/server/src/com/fy/engineserver/newtask/prizes/TaskPrizeOfPneuma.java
UTF-8
1,703
2.703125
3
[]
no_license
package com.fy.engineserver.newtask.prizes; import com.fy.engineserver.newtask.Task; import com.fy.engineserver.newtask.service.TaskConfig; import com.fy.engineserver.newtask.service.TaskSubSystem; import com.fy.engineserver.sprite.Player; /** * 任务奖励-修法值 * * */ public class TaskPrizeOfPneuma extends TaskPrize implements TaskConfig { private TaskPrizeOfPneuma() { setPrizeType(PrizeType.PNEUMA); setPrizeByteType(getPrizeType().getIndex()); } public static TaskPrize createTaskPrize(int pneumaNum) { TaskPrizeOfPneuma prize = new TaskPrizeOfPneuma(); prize.setPrizeNum(new long[] { pneumaNum }); prize.setPrizeName(new String[] { prize.getPrizeType().getName() }); return prize; } @Override public void doPrize(Player player, int[] index, Task task) { // TODO 上限判断 player.setEnergy(player.getEnergy() + (int) getPrizeNum()[0]); if (TaskSubSystem.logger.isWarnEnabled()) { TaskSubSystem.logger.warn(player.getLogString() + "[完成任务:{}] [获得修法值:{}] [增加后修法值:{}]", new Object[] { task.getName(), getPrizeNum()[0], player.getEnergy() }); } } @Override public String toHtmlString(String cssClass) { StringBuffer sbf = new StringBuffer("<table class='"); sbf.append(cssClass).append("'>"); sbf.append("<tr>"); sbf.append("<td>"); sbf.append(getPrizeType().getName()); sbf.append("</td>"); sbf.append("<td>"); ; sbf.append("修法值数量[").append(getPrizeNum()[0]).append("]"); sbf.append("</tr>"); sbf.append("</table>"); return sbf.toString(); } public static void main(String[] args) { TaskPrize prize = createTaskPrize(333); // System.out.println(prize.toHtmlString("GG")); } }
true
5fe3fddf41ab8f9c154037d187294cb8ae33b111
Java
itlenergy/itlenergy
/itlenergy-webclient/src/main/java/com/itl_energy/webclient/profile/visualisation/LineGraphControl.java
UTF-8
3,649
2.671875
3
[ "MIT" ]
permissive
package com.itl_energy.webclient.profile.visualisation; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; /** * Class for representing simple functional relationship. * * @author bstephen * @version 10th May 2011 */ public class LineGraphControl extends BivariateScatterControl { private static final long serialVersionUID = 6325286058338449731L; protected boolean haslines; protected boolean haspoints; protected boolean hasimpulses; public LineGraphControl() { super(); this.haslines = true; this.haspoints = true; this.hasimpulses = false; this.resetControl(); } public void setAsLines(boolean set) { this.haslines = set; this.hasimpulses = false; } public void setHasPoints(boolean set) { this.haspoints = set; } public void setAsImpulses(boolean set) { this.hasimpulses = set; this.haslines = !set; } protected void drawData(Graphics2D g) { BasicStroke bs = new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); double xinc = this.grid.getBounds().getWidth() / (this.grid.getMaxX() - this.grid.getMinX()); double yinc = this.grid.getBounds().getHeight() / (this.grid.getMaxY() - this.grid.getMinY()); Line2D l2 = new Line2D.Double(); Ellipse2D ep2 = new Ellipse2D.Double(); double x, y; Stroke s = g.getStroke(); g.setStroke(bs); for (int i = 0; i < this.series.size(); i++) { Color srsClr; //need to set the colour according to class... if (!this.labels.isEmpty()) { float frac =/*360.0F**/ ((float) this.labels.get(i).intValue() / (float) this.ulabels.size()); srsClr = Color.getHSBColor(frac, 1.0F, 1.0F); } else { srsClr = Color.red; } g.setColor(srsClr); x = this.grid.getBounds().getMinX() + ((this.series.get(i)[0][0] - this.grid.getMinX()) * xinc); y = this.grid.getBounds().getMinY() + this.grid.getBounds().getHeight() - (((this.series.get(i)[0][1] - this.grid.getMinY()) * yinc)); l2.setLine(0, 0, x, y); if (this.haspoints) { ep2.setFrame(x - 2.0, y - 2.0, 4.0, 4.0); g.fill(ep2); if (this.hasimpulses) { l2.setLine(x, this.grid.getBounds().getMaxY(), x, y); g.draw(l2); } } for (int j = 1; j < this.series.get(i).length; j++) { //scale points then draw... x = this.grid.getBounds().getMinX() + ((this.series.get(i)[j][0] - this.grid.getMinX()) * xinc); y = this.grid.getBounds().getMinY() + this.grid.getBounds().getHeight() - ((this.series.get(i)[j][1] - this.grid.getMinY()) * yinc); if (this.hasimpulses) { l2.setLine(x, this.grid.getBounds().getMaxY(), x, y); g.draw(l2); } if (this.haspoints) { ep2.setFrame(x - 2.0, y - 2.0, 4.0, 4.0); g.fill(ep2); } if (this.haslines) { l2.setLine(l2.getX2(), l2.getY2(), x, y); g.draw(l2); } } } g.setStroke(s); } }
true
8fa4cb9be345889655f101bd0eefa8496906305b
Java
shravanAngadi/temp-odb
/java/mono/android/view/View_OnDragListenerImplementor.java
UTF-8
1,962
1.65625
2
[]
no_license
/* * Decompiled with CFR 0_110. * * Could not load the following classes: * android.view.DragEvent * android.view.View * android.view.View$OnDragListener * java.lang.Class * java.lang.Object * java.lang.String * java.lang.Throwable * java.util.ArrayList */ package mono.android.view; import android.view.DragEvent; import android.view.View; import java.util.ArrayList; import mono.android.IGCUserPeer; import mono.android.Runtime; import mono.android.TypeManager; public class View_OnDragListenerImplementor implements View.OnDragListener, IGCUserPeer { public static final String __md_methods = "n_onDrag:(Landroid/view/View;Landroid/view/DragEvent;)Z:GetOnDrag_Landroid_view_View_Landroid_view_DragEvent_Handler:Android.Views.View/IOnDragListenerInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n"; private ArrayList refList; static { Runtime.register("Android.Views.View+IOnDragListenerImplementor, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", View_OnDragListenerImplementor.class, __md_methods); } public View_OnDragListenerImplementor() throws Throwable { if (this.getClass() == View_OnDragListenerImplementor.class) { TypeManager.Activate("Android.Views.View+IOnDragListenerImplementor, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", "", this, new Object[0]); } } private native boolean n_onDrag(View var1, DragEvent var2); @Override public void monodroidAddReference(Object object) { if (this.refList == null) { this.refList = new ArrayList(); } this.refList.add(object); } @Override public void monodroidClearReferences() { if (this.refList != null) { this.refList.clear(); } } public boolean onDrag(View view, DragEvent dragEvent) { return super.n_onDrag(view, dragEvent); } }
true
566d7b1a4a87edf6a994c1a9a0eeac785e6797e0
Java
LiLinXiang/Picbox
/app/src/main/java/ml/puredark/hviewer/libraries/swipeback/common/SwipeBackApplication.java
UTF-8
604
1.929688
2
[ "MIT" ]
permissive
package ml.puredark.hviewer.libraries.swipeback.common; import android.app.Activity; import android.app.Application; import android.view.View; /** * Created by fhf11991 on 2016/7/18. */ public class SwipeBackApplication extends Application { private ActivityLifecycleHelper mActivityLifecycleHelper; @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(mActivityLifecycleHelper = new ActivityLifecycleHelper()); } public ActivityLifecycleHelper getActivityLifecycleHelper() { return mActivityLifecycleHelper; } }
true
ccd91f6b7890c7016450894532f9ec108d29f643
Java
winhbb/rustyclipse
/rustyclipse/src/org/rustyclipse/RustLaunchConfigurationDelegate.java
UTF-8
574
1.632813
2
[]
no_license
package org.rustyclipse; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.LaunchConfigurationDelegate; public class RustLaunchConfigurationDelegate extends LaunchConfigurationDelegate { @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { super.saveBeforeLaunch(configuration, mode, monitor); } }
true
77c4fdaab28a63fbc11fc216cc76f93e24130c02
Java
sunjian666/java.lang.reflect
/src/main/java/Array/GetByteAndArrayAndIndex.java
UTF-8
461
3.21875
3
[]
no_license
package Array; import java.lang.reflect.Array; //以字节形式返回指定数组对象中的索引组件的值。 public class GetByteAndArrayAndIndex { public static void main(String[] args) { byte[] array = new byte[]{1,2,3}; System.out.println("array[0] = " + Array.getByte(array, 0)); System.out.println("array[1] = " + Array.getByte(array, 1)); System.out.println("array[2] = " + Array.getByte(array, 2)); } }
true
4d49632c8a057b9bab7345ffd1b29d64a348afaf
Java
ihmcrobotics/ihmc-open-robotics-software
/ihmc-robotics-toolkit/src/main/java/us/ihmc/robotics/kinematics/ReNumericalInverseKinematicsCalculator.java
UTF-8
8,659
1.984375
2
[ "Apache-2.0" ]
permissive
package us.ihmc.robotics.kinematics; import java.util.Random; import org.ejml.data.DMatrixRMaj; import org.ejml.dense.row.CommonOps_DDRM; import org.ejml.dense.row.NormOps_DDRM; import org.ejml.dense.row.factory.LinearSolverFactory_DDRM; import org.ejml.interfaces.linsol.LinearSolverDense; import us.ihmc.commons.MathTools; import us.ihmc.commons.RandomNumbers; import us.ihmc.euclid.axisAngle.AxisAngle; import us.ihmc.euclid.geometry.Pose3D; import us.ihmc.euclid.matrix.RotationMatrix; import us.ihmc.euclid.transform.RigidBodyTransform; import us.ihmc.euclid.transform.interfaces.RigidBodyTransformReadOnly; import us.ihmc.euclid.tuple3D.Vector3D; import us.ihmc.mecano.multiBodySystem.interfaces.OneDoFJointBasics; import us.ihmc.mecano.spatial.SpatialVector; import us.ihmc.mecano.spatial.Twist; import us.ihmc.mecano.tools.MultiBodySystemStateIntegrator; import us.ihmc.mecano.tools.MultiBodySystemTools; import us.ihmc.robotics.screwTheory.GeometricJacobian; /** * @author twan * Date: 6/1/13 */ public class ReNumericalInverseKinematicsCalculator implements InverseKinematicsCalculator { private final GeometricJacobian jacobian; private final LinearSolverDense<DMatrixRMaj> solver; private final OneDoFJointBasics[] oneDoFJoints; private final OneDoFJointBasics[] oneDoFJointsSeed; private final double tolerance; private final int maxIterations; private final double maxStepSize; private final Random random = new Random(1251253L); private int iterationNumber; private double errorScalar; private double bestErrorScalar; private final RigidBodyTransform actualTransform = new RigidBodyTransform(); private final RigidBodyTransform errorTransform = new RigidBodyTransform(); private final AxisAngle errorAxisAngle = new AxisAngle(); private final RotationMatrix errorRotationMatrix = new RotationMatrix(); private final Vector3D errorRotationVector = new Vector3D(); private final Vector3D axis = new Vector3D(); private final Vector3D errorTranslationVector = new Vector3D(); private final DMatrixRMaj error = new DMatrixRMaj(SpatialVector.SIZE, 1); private final DMatrixRMaj correction; private final DMatrixRMaj current; private final DMatrixRMaj best; private final double minRandomSearchScalar; private final double maxRandomSearchScalar; private int counter; private boolean useSeed; public ReNumericalInverseKinematicsCalculator(GeometricJacobian jacobian, double tolerance, int maxIterations, double maxStepSize, double minRandomSearchScalar, double maxRandomSearchScalar) { if (jacobian.getJacobianFrame() != jacobian.getEndEffectorFrame()) throw new RuntimeException("jacobian.getJacobianFrame() != jacobian.getEndEffectorFrame()"); this.jacobian = jacobian; this.solver = LinearSolverFactory_DDRM.leastSquares(SpatialVector.SIZE, jacobian.getNumberOfColumns()); // new DampedLeastSquaresSolver(jacobian.getNumberOfColumns()); this.oneDoFJoints = MultiBodySystemTools.filterJoints(jacobian.getJointsInOrder(), OneDoFJointBasics.class); oneDoFJointsSeed = oneDoFJoints.clone(); if (oneDoFJoints.length != jacobian.getJointsInOrder().length) throw new RuntimeException("Can currently only handle OneDoFJoints"); int nDoF = MultiBodySystemTools.computeDegreesOfFreedom(oneDoFJoints); correction = new DMatrixRMaj(nDoF, 1); current = new DMatrixRMaj(nDoF, 1); best = new DMatrixRMaj(nDoF, 1); this.tolerance = tolerance; this.maxIterations = maxIterations; this.maxStepSize = maxStepSize; this.minRandomSearchScalar = minRandomSearchScalar; this.maxRandomSearchScalar = maxRandomSearchScalar; counter = 0; } public boolean solve(RigidBodyTransformReadOnly desiredTransform) { iterationNumber = 0; bestErrorScalar = Double.POSITIVE_INFINITY; do { computeError(desiredTransform); updateBest(); computeCorrection(); applyCorrection(); iterationNumber++; } while ((errorScalar > tolerance) && (iterationNumber < maxIterations)); updateBest(); setJointAngles(best); if (iterationNumber < maxIterations) { useSeed = false; return true; } if (iterationNumber >= maxIterations && counter++ < 100) { introduceRandomArmePose(desiredTransform); } counter = 0; return false; } public void introduceRandomArmePose(RigidBodyTransformReadOnly desiredTransform) { for (int i = 0; i < oneDoFJoints.length; i++) { oneDoFJoints[i].setQ(random.nextDouble()); } solve(desiredTransform); } private void getJointAngles(DMatrixRMaj angles) { for (int i = 0; i < angles.getNumRows(); i++) { angles.set(i, 0, oneDoFJoints[i].getQ()); } } private void setJointAngles(DMatrixRMaj angles) { for (int i = 0; i < angles.getNumRows(); i++) { oneDoFJoints[i].setQ(angles.get(i, 0)); } } private void updateBest() { getJointAngles(current); if (errorScalar < bestErrorScalar) { best.set(current); bestErrorScalar = errorScalar; } } private void computeError(RigidBodyTransformReadOnly desiredTransform) { /* * B is base E is end effector D is desired end effector * * H^D_E = H^D_B * H^B_E = (H^B_D)^-1 * H^B_E * * convert rotation matrix part to rotation vector */ jacobian.getEndEffectorFrame().getTransformToDesiredFrame(actualTransform, jacobian.getBaseFrame()); errorTransform.setAndInvert(desiredTransform); errorTransform.multiply(actualTransform); errorRotationMatrix.set(errorTransform.getRotation()); errorAxisAngle.set(errorRotationMatrix); axis.set(errorAxisAngle.getX(), errorAxisAngle.getY(), errorAxisAngle.getZ()); errorRotationVector.set(axis); errorRotationVector.scale(errorAxisAngle.getAngle()); errorTranslationVector.set(errorTransform.getTranslation()); errorRotationVector.get(0, error); errorTranslationVector.get(3, error); errorScalar = NormOps_DDRM.normP2(error); assert (exponentialCoordinatesOK()); } private boolean exponentialCoordinatesOK() { Twist twist = new Twist(jacobian.getEndEffectorFrame(), jacobian.getBaseFrame(), jacobian.getJacobianFrame(), error); Pose3D poseCheck = new Pose3D(); new MultiBodySystemStateIntegrator(1.0).integrate(twist, poseCheck); RigidBodyTransform transformCheck = new RigidBodyTransform(poseCheck.getOrientation(), poseCheck.getPosition()); return transformCheck.epsilonEquals(errorTransform, 1e-5); } private void computeCorrection() { jacobian.compute(); DMatrixRMaj dampenedJ = jacobian.getJacobianMatrix().copy(); for (int i = 0; i < dampenedJ.getNumCols(); i++) { dampenedJ.add(i, i, 0.0); } // solver.setAlpha(errorScalar + dampedLeastSquaresAlphaMin); if (!solver.setA(dampenedJ)) { // do something here intelligent if it fails // System.err.println("IK solver internal solve failed!"); } solver.solve(error, correction); double correctionScale = RandomNumbers.nextDouble(random, minRandomSearchScalar, maxRandomSearchScalar); CommonOps_DDRM.scale(correctionScale, correction); for (int i = 0; i < correction.getNumRows(); i++) { correction.set(i, 0, MathTools.clamp(correction.get(i, 0), -maxStepSize, maxStepSize)); } } private void applyCorrection() { for (int i = 0; i < oneDoFJoints.length; i++) { OneDoFJointBasics oneDoFJoint; if (useSeed) { oneDoFJoint = oneDoFJointsSeed[i]; } else { oneDoFJoint = oneDoFJoints[i]; } double newQ = oneDoFJoint.getQ() - correction.get(i, 0); newQ = MathTools.clamp(newQ, oneDoFJoint.getJointLimitLower(), oneDoFJoint.getJointLimitUpper()); oneDoFJoint.setQ(newQ); oneDoFJoint.getFrameAfterJoint().update(); } } public int getNumberOfIterations() { return iterationNumber; } public double getErrorScalar() { return errorScalar; } @Override public void attachInverseKinematicsStepListener(InverseKinematicsStepListener stepListener) { } @Override public void setLimitJointAngles(boolean limitJointAngles) { } }
true
25adb1d3a2c025b0f70cacc2bc5c977480b3e6f0
Java
orb1t/FYzx
/src/physics/links/Particle.java
UTF-8
7,489
2.25
2
[]
no_license
/* * Copyright (C) 2014 F(Y)zx : * Authored by : Jason Pollastrini aka jdub1581, * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package physics.links; import java.util.HashMap; import java.util.List; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.geometry.Point3D; import javafx.scene.paint.Color; import javafx.scene.paint.Material; import javafx.scene.paint.PhongMaterial; import javafx.scene.shape.CullFace; import javafx.scene.shape.DrawMode; import javafx.scene.shape.Sphere; import javafx.scene.transform.Affine; import physics.constraints.Constraint; import physics.integrators.Integrator; import physics.integrators.VerletIntegrator; import physics.physicsobjects.Body; import physics.physicsobjects.PhysicalState; /** * * @author Jason Pollastrini aka jdub1581 */ public class Particle extends Body<Sphere> { private final Sphere sphere; private Point3D pinPos; private boolean pinned; public Particle(Point3D position) { this(2.5, 5.0, position, true); } public Particle(double radius, Point3D position) { this(radius, 5.0, position, true); } public Particle(Point3D position, boolean forceAffected) { this(2.5, 5.0, position, forceAffected); } public Particle(double radius, Point3D position, boolean forceAffected) { this(radius, 5.0, position, forceAffected); } public Particle(Point3D position, double mass, boolean forceAffected) { this(2.5, mass, position, forceAffected); } public Particle(double radius, double mass, Point3D position, boolean forceAffected) { super(mass, position, forceAffected); this.setIntegrator(new VerletIntegrator(getState(), 1)); this.sphere = new Sphere(radius); this.sphere.setMaterial(new PhongMaterial(Color.CHARTREUSE)); this.getChildren().add(sphere); this.getAffine().setTx(getState().getPosition().getX()); this.getAffine().setTy(getState().getPosition().getY()); this.getAffine().setTz(getState().getPosition().getZ()); } @Override public Sphere getNode() { return sphere; } @Override public void updateUI() { if (!isPinned()) { getAffine().appendTranslation( getState().getPosition().getX(), getState().getPosition().getY(), getState().getPosition().getZ() ); } } /* Delegate Methods */ public final void setRadius(double value) { sphere.setRadius(value); } public final double getRadius() { return sphere.getRadius(); } public final DoubleProperty radiusProperty() { return sphere.radiusProperty(); } public int getDivisions() { return sphere.getDivisions(); } public final void setMaterial(Material value) { sphere.setMaterial(value); } public final Material getMaterial() { return sphere.getMaterial(); } public final ObjectProperty<Material> materialProperty() { return sphere.materialProperty(); } public final void setDrawMode(DrawMode value) { sphere.setDrawMode(value); } public final DrawMode getDrawMode() { return sphere.getDrawMode(); } public final ObjectProperty<DrawMode> drawModeProperty() { return sphere.drawModeProperty(); } public final void setCullFace(CullFace value) { sphere.setCullFace(value); } public final CullFace getCullFace() { return sphere.getCullFace(); } public final ObjectProperty<CullFace> cullFaceProperty() { return sphere.cullFaceProperty(); } public Point3D getPinPos() { return pinPos; } public void pinTo(Point3D pinPos) { this.pinPos = pinPos; setPinned(true); } public void unPin() { setPinned(false); } public boolean isPinned() { return pinned; } public void setPinned(boolean pinned) { this.pinned = pinned; } @Override public final Affine getAffine() { return super.getAffine(); //To change body of generated methods, choose Tools | Templates. } @Override public void clearForces() { super.clearForces(); //To change body of generated methods, choose Tools | Templates. } @Override public void setForceAffected(boolean b) { super.setForceAffected(b); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isForceAffected() { return super.isForceAffected(); //To change body of generated methods, choose Tools | Templates. } @Override public Point3D getNetForce() { return super.getNetForce(); //To change body of generated methods, choose Tools | Templates. } @Override public void addForce(Point3D f) { super.addForce(f); //To change body of generated methods, choose Tools | Templates. } @Override public final void setIntegrator(Integrator i) { super.setIntegrator(i); //To change body of generated methods, choose Tools | Templates. } @Override public Integrator getIntegrator() { return super.getIntegrator(); //To change body of generated methods, choose Tools | Templates. } @Override public void checkCollisions() { super.checkCollisions(); //To change body of generated methods, choose Tools | Templates. } @Override public List<Body> getCollidableObjects() { return super.getCollidableObjects(); //To change body of generated methods, choose Tools | Templates. } @Override public void solveConstraints() { super.solveConstraints(); //To change body of generated methods, choose Tools | Templates. } @Override public void addConstraint(Constraint c) { super.addConstraint(c); //To change body of generated methods, choose Tools | Templates. } @Override public HashMap<Body, Constraint> getConstraints() { return super.getConstraints(); //To change body of generated methods, choose Tools | Templates. } @Override public final PhysicalState getState() { return super.getState(); //To change body of generated methods, choose Tools | Templates. } @Override public double getMass() { return super.getMass(); //To change body of generated methods, choose Tools | Templates. } @Override public void setMass(double m) { super.setMass(m); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isResting() { return super.isResting(); //To change body of generated methods, choose Tools | Templates. } }
true
5adf82d67446a0f7d985fac8adc727f2f9f76877
Java
zhubinsheng/chongwujinghua
/chongWuKongJing/app/src/main/java/com/sim/chongwukongjing/ui/bean/MQTTResult.java
UTF-8
1,863
1.984375
2
[]
no_license
package com.sim.chongwukongjing.ui.bean; import com.google.gson.annotations.SerializedName; public class MQTTResult { /** * uid : 94 * rssi : -51 * type : 5678 * 0 : 0 * 1 : 1 * 2 : 1 * 3 : 3 * 4 : 3 * 5 : 0 * 6 : 0 */ private int uid; private int rssi; private int type; @SerializedName("0") private int _$0; @SerializedName("1") private int _$1; @SerializedName("2") private int _$2; @SerializedName("3") private int _$3; @SerializedName("4") private int _$4; @SerializedName("5") private int _$5; @SerializedName("6") private int _$6; public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public int getRssi() { return rssi; } public void setRssi(int rssi) { this.rssi = rssi; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int get_$0() { return _$0; } public void set_$0(int _$0) { this._$0 = _$0; } public int get_$1() { return _$1; } public void set_$1(int _$1) { this._$1 = _$1; } public int get_$2() { return _$2; } public void set_$2(int _$2) { this._$2 = _$2; } public int get_$3() { return _$3; } public void set_$3(int _$3) { this._$3 = _$3; } public int get_$4() { return _$4; } public void set_$4(int _$4) { this._$4 = _$4; } public int get_$5() { return _$5; } public void set_$5(int _$5) { this._$5 = _$5; } public int get_$6() { return _$6; } public void set_$6(int _$6) { this._$6 = _$6; } }
true
5d093086713f293e4f3fcf065fc78bf30af274c4
Java
igorqueirozzz/colab
/app/src/main/java/br/com/app/colab/enumeration/PointUpdateRequestStatus.java
UTF-8
587
2.328125
2
[]
no_license
package br.com.app.colab.enumeration; import br.com.app.colab.enumeration.api.IEnumModel; public enum PointUpdateRequestStatus implements IEnumModel { PENDENTE(0,"PENDENTE"), VERIFICADA(1,"VERIFICADA"); private String description; private Integer value; PointUpdateRequestStatus(int value, String description) { this.value = value; this.description = description; } @Override public String getDescription() { return this.description; } @Override public Integer getValue() { return this.value; } }
true
295a7ec6ae392482b6a704ee93d24eaa9f2b12af
Java
IomHamstro/Software-Engineering
/src/Main.java
UTF-8
163
2.28125
2
[]
no_license
public class Main { public static void main(String[] args) { for(int i=0; i < 13; i++) System.out.println("I’m watching you"); } }
true
0f6d7f8c98294a79a422ce9a826e8ee630f23089
Java
rly73/Job-App-MotiTracker
/app/src/main/java/com/example/jobappmotitracker/view/JobApplicationList.java
UTF-8
2,580
2.1875
2
[]
no_license
package com.example.jobappmotitracker.view; import android.os.AsyncTask; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.jobappmotitracker.R; import com.example.jobappmotitracker.database.DBManager; import com.example.jobappmotitracker.model.JobApplication; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; public class JobApplicationList extends AppCompatActivity { private List<JobApplication> appList = new ArrayList<>(); private RecyclerView recyclerView; private TextView noAppView; TextView InspirationalQuote; private JobAdapter adapter; private DBManager dbManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.job_app_list); recyclerView = findViewById(R.id.job_app_recycler_list); InspirationalQuote =(TextView)findViewById(R.id.list_quote); new MyTask().execute(); dbManager = new DBManager(this); dbManager.open(); appList.addAll(dbManager.getAllJobApp()); adapter = new JobAdapter(this,appList); LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } private class MyTask extends AsyncTask<Void, Void, Void> { Elements words; String quote; @Override protected Void doInBackground(Void... params) { Document doc; try { Random number = new Random(); doc = Jsoup.connect("https://content.wisestep.com/motivational-inspirational-quotes-job-seekers/").get(); words = doc.select("p:nth-of-type("+ number.nextInt(11) +")"); System.out.println("Text== " + words); quote = words.eq(number.nextInt(11)).text(); String arr[] = quote.split(" ",2); quote = arr[1]; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void Avoid) { InspirationalQuote.setText(quote); } } }
true
6f9c75130725c22216928e966838a950a1dba942
Java
Yuziquan/NewsBrief
/NewsBrief/app/src/main/java/com/scnu/newsbrief/activity/SearchPageActivity.java
UTF-8
1,271
2.046875
2
[]
no_license
package com.scnu.newsbrief.activity; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.scnu.newsbrief.R; public class SearchPageActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_page); initTransparentStatusBar(); findViewById(R.id.back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } /** * 初始化透明状态栏 */ private void initTransparentStatusBar() { // 实现透明状态栏效果 if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; decorView.setSystemUiVisibility(option); getWindow().setStatusBarColor(Color.TRANSPARENT); } if (getSupportActionBar() != null) { getSupportActionBar().hide(); } } }
true
037ae38b543ce2a94d4fd1d3586f3db7975f167a
Java
aisyahozami97/Final-Year-Project
/app/src/main/java/com/example/preloveditemandevent/VolunteerAdapter.java
UTF-8
2,770
2.03125
2
[]
no_license
package com.example.preloveditemandevent; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.android.material.bottomnavigation.BottomNavigationView; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class VolunteerAdapter extends RecyclerView.Adapter<VolunteerAdapter.MyViewHolder>{ private Context context; BottomNavigationView bottomNavigationView; List<String> key; ArrayList<SpecificEvent> listUser; public VolunteerAdapter(ArrayList<SpecificEvent> listUser){ this.listUser = listUser; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_holder_listvolunteer, viewGroup, false); context = viewGroup.getContext(); return new VolunteerAdapter.MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) { myViewHolder.firstName.setText(listUser.get(i).getVolFirstName()); myViewHolder.lastName.setText(listUser.get(i).getVolLastName()); myViewHolder.phone.setText(listUser.get(i).getVolPhone()); myViewHolder.eventName.setText(listUser.get(i).getVolEventName()); // // myViewHolder.itemView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // String key = list.get(i).getArtistId(); // // // // Intent intent = new Intent(context,DetailsHistoryAdminActivity.class); // intent.putExtra("key",key); //// intent.putExtra("price",price); //// intent.putExtra("location",player); //// intent.putExtra("country",price); //// intent.putExtra("location",player); //// intent.putExtra("country",price); // context.startActivity(intent); // } // }); } @Override public int getItemCount() { return listUser.size(); } class MyViewHolder extends RecyclerView.ViewHolder { TextView firstName,lastName, phone, eventName; public MyViewHolder(@NonNull View itemView) { super(itemView); eventName = itemView.findViewById(R.id.volEventName); firstName = itemView.findViewById(R.id.volFirstName); lastName = itemView.findViewById(R.id.volLastName); phone = itemView.findViewById(R.id.volPhone); } } }
true
833404a908aa99a678487002c53899447e411196
Java
adamfils/SchoolAssistant
/app/src/main/java/com/adamapps/coursealert/model/SearchModel.java
UTF-8
1,164
2.453125
2
[]
no_license
package com.adamapps.coursealert.model; public class SearchModel { private String userImage; private String userName; private String userDescription; private String userLevel; public SearchModel() { } public SearchModel(String userImage, String userName, String userDescription, String userLevel) { this.userImage = userImage; this.userName = userName; this.userDescription = userDescription; this.userLevel = userLevel; } public String getUserImage() { return userImage; } public void setUserImage(String userImage) { this.userImage = userImage; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserDescription() { return userDescription; } public void setUserDescription(String userDescription) { this.userDescription = userDescription; } public String getUserLevel() { return userLevel; } public void setUserLevel(String userLevel) { this.userLevel = userLevel; } }
true
fe44077e8cb6ce2fe8e7cb05e313c69d56b31956
Java
gpruim/semic-pilot-jobmatching
/esco-job-cv-matching/src/main/java/eu/esco/demo/jobcvmatching/web/controller/JobCvMatchingController.java
UTF-8
4,515
2.203125
2
[ "Apache-2.0" ]
permissive
package eu.esco.demo.jobcvmatching.web.controller; import com.google.common.collect.Sets; import eu.esco.demo.jobcvmatching.root.graph.Edge; import eu.esco.demo.jobcvmatching.root.graph.Graph; import eu.esco.demo.jobcvmatching.root.graph.GraphHelper; import eu.esco.demo.jobcvmatching.root.graph.Node; import eu.esco.demo.jobcvmatching.root.graph.Type; import eu.esco.demo.jobcvmatching.root.model.CV; import eu.esco.demo.jobcvmatching.root.model.Job; import eu.esco.demo.jobcvmatching.root.model.Occupation; import eu.esco.demo.jobcvmatching.root.model.Skill; import eu.esco.demo.jobcvmatching.root.service.DataService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @Controller public class JobCvMatchingController { @Inject private DataService dataService; @RequestMapping("/graph") public String getGraph(org.springframework.ui.Model model, HttpServletRequest request, @RequestParam("cvUri") String cvUri, @RequestParam("jvUri") String jvUri) { CV cv = dataService.getCV(cvUri, request.getLocale().getLanguage()); Job jv = dataService.getJV(jvUri, request.getLocale().getLanguage()); model.addAttribute("json", buildGraphJson(jv, cv)); model.addAttribute("jvUri", jv.getUri()); model.addAttribute("rootUri", "#" + GraphHelper.idizeUri(jv.getUri())); return "jv_cv_graph"; } private String buildGraphJson(Job job, CV cv) { Graph graph = new Graph(); Node jobNode = new Node(Type.Job, job.getUri(), job.getLabel()); graph.addNodes(jobNode); Node cvNode = new Node(Type.CV, cv.getUri(), cv.getDescription()); graph.addNodes(cvNode); for (Occupation occupation : job.getOccupations()) { Node occupationNode = new Node(Type.Occupation, occupation.getUri(), occupation.getLabel()); graph.addNodes(occupationNode); graph.addEdges(new Edge(jobNode, occupationNode)); Map<String, Skill> occupationSkillMap = occupation.getSkillMap(); Map<String, Skill> cvSkillMap = cv.getSkillMap(); Sets.SetView<String> matches = Sets.intersection(occupationSkillMap.keySet(), cvSkillMap.keySet()); Map<String, Skill> fullSkillMap = new HashMap<>(); fullSkillMap.putAll(occupationSkillMap); fullSkillMap.putAll(cvSkillMap); for (Map.Entry<String, Skill> entry : fullSkillMap.entrySet()) { String uri = entry.getKey(); boolean isMatch = matches.contains(uri); Node skillNode = new Node(Type.Skill, entry.getValue().getUri(), entry.getValue().getLabel(), isMatch); graph.addNodes(skillNode); if (occupationSkillMap.containsKey(uri)) { graph.addEdges(new Edge(occupationNode, skillNode)); } if (cvSkillMap.containsKey(uri)) { graph.addEdges(new Edge(skillNode, cvNode)); } } } return graph.asJson(); } // private String buildGraphJson(Job job, CV cv) { // Graph graph = new Graph(); // // Node jobNode = new Node(Type.Job, "" + job.getDocumentId(), job.getLabel()); // Node occupationNode = new Node(Type.Occupation, job.getOccupation(), job.getOccupation()); // // graph.addNodes(jobNode, occupationNode); // graph.addEdges(new Edge(jobNode, occupationNode)); // // Node cvNode = new Node(Type.CV, "" + cv.getDocumentId(), cv.getDescription()); // graph.addNodes(cvNode); // // // Map<String, Skill> jobSkillMap = job.getSkillMap(); // Map<String, Skill> cvSkillMap = cv.getSkillMap(); // // Sets.SetView<String> matches = Sets.intersection(jobSkillMap.keySet(), cvSkillMap.keySet()); // // Map<String, Skill> fullSkillMap = new HashMap<>(); // fullSkillMap.putAll(jobSkillMap); // fullSkillMap.putAll(cvSkillMap); // // // for (Map.Entry<String, Skill> entry : fullSkillMap.entrySet()) { // String uri = entry.getKey(); // boolean isMatch = matches.contains(uri); // // Node skillNode = new Node(Type.Skill, entry.getValue().getUri(), entry.getValue().getDescription(), isMatch); // graph.addNodes(skillNode); // // if (jobSkillMap.containsKey(uri)) { // graph.addEdges(new Edge(occupationNode, skillNode)); // } // if (cvSkillMap.containsKey(uri)) { // graph.addEdges(new Edge(skillNode, cvNode)); // } // } // return graph.asJson(); // } }
true
b84813761aabc80865bd9f27f6c26ae0e040e6b7
Java
wesihun/ARCGIS-FOR-MEIKUANG-ZYP
/app/src/main/java/com/winto/develop/ShenBao/activity/HistoryActivity.java
UTF-8
1,754
2.03125
2
[]
no_license
package com.winto.develop.ShenBao.activity; import android.widget.ImageView; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; import com.winto.develop.ShenBao.R; import com.winto.develop.ShenBao.adapter.MyPagerAdapter; import com.winto.develop.ShenBao.base.BaseActivity; import com.winto.develop.ShenBao.base.BaseFragment; import com.winto.develop.ShenBao.fragment.CheckedHistoryFragment; import com.winto.develop.ShenBao.fragment.NoticedHistoryFragment; import java.util.ArrayList; import java.util.List; /** * Created by zyp on 2019/8/20 0020. * class note:历史记录 */ public class HistoryActivity extends BaseActivity { private ImageView iv_back; private TabLayout tl_tab; private ViewPager vp_pager; @Override protected void initView() { iv_back = findViewById(R.id.iv_back); tl_tab = findViewById(R.id.tl_tab); vp_pager = findViewById(R.id.vp_pager); initFragment(); } private void initFragment() { List<BaseFragment> fragmentList = new ArrayList<>(); List<String> list_Title = new ArrayList<>(); fragmentList.add(new NoticedHistoryFragment()); fragmentList.add(new CheckedHistoryFragment()); list_Title.add("已下发通知"); list_Title.add("已复查"); vp_pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), context, fragmentList, list_Title)); tl_tab.setupWithViewPager(vp_pager); } @Override protected void initData() { } @Override protected void initClick() { iv_back.setOnClickListener(v -> finish()); } @Override protected int setLayout() { return R.layout.activity_history; } }
true