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
ec327408cad34f94bd0a2dba13fe0087a40fa6fd
Java
ammeter/coinpurse-WorawatCh
/src/coinpurse/Coin.java
UTF-8
1,833
3.921875
4
[]
no_license
package coinpurse; import java.lang.Comparable; import java.util.ArrayList; import java.util.List; /** * Coin represents coinage (money) with a fixed value and currency. * * @author Worawat Chueajedton */ public class Coin implements Comparable<Coin> { private double value; private String currency; /** * * Make a coins with value and currency. * * @param value * value of coin * @param currency * currency of coin */ public Coin(double value, String currency) { this.value = value; this.currency = currency; } /** * * Get a coin's value. * * @return value of coin * */ public double getValue() { return value; } /** * * Get a coin's currency * * @return currency of coin */ public String getCurrenccy() { return currency; } /** * * Two coins are equal if they have the same value and same currency * * @param arg * An object you want to check, Is it equal? * @return if it equal return true, if not return false. */ public boolean equal(Object arg) { if (arg == null) return false; if (arg.getClass() != this.getClass()) return false; Coin other = (Coin) arg; if (other.getValue() == value && other.getCurrenccy().equalsIgnoreCase(currency)) { return true; } return false; } /** * * To compare which one is greater of less than another one. * * @param arg0 * coin that you want to check. * */ @Override public int compareTo(Coin arg0) { if (value < arg0.getValue()) { return -1; } else if (value > arg0.getValue()) { return 1; } else if (value == arg0.getValue()) { return 0; } return 0; } /** * * Show description of coin * * @return coin's description * */ public String toString() { return value + "-" + currency; } }
true
c3cb8fcdea99a5d9e8ba3049b268ab1c738c0bb0
Java
chaiguolong/JavaSE
/day24/src/cn/itcast/demo1/BufferedOutputStreamDemo_002.java
UTF-8
1,084
3.59375
4
[]
no_license
package cn.itcast.demo1; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; /* * 字节输出流的缓冲流 * java.io.BufferedOutputStream 作用: 提高原油输出流的写入效率 * BufferedOutputStream 继承 OutputStream * 方法,写入 write 字节 字节数组 * * 构造方法: * BufferedOutputStream(OutputStream out) * 可以传递任意的字节输出流,传递的是哪个字节流,就对哪个字节流提高效率 * * FileOutputStream */ public class BufferedOutputStreamDemo_002{ public static void main(String[] args) throws IOException{ //创建字节输出流,绑定文件 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/Users/mymac/Desktop/input.txt")); //写入数据 bos.write("你好".getBytes()); bos.write(65); //定义字节数组,写入字符数组 byte[] bytes = "hello World".getBytes(); bos.write(bytes,2,5); //关闭资源 bos.close(); } }
true
f336213e28fa927592b6f0eb98b91ec6db8764f4
Java
teratide/dremio-accelerated
/common/src/main/java/com/dremio/ssl/SSLConfig.java
UTF-8
9,708
1.898438
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.ssl; import java.security.KeyStore; import java.util.Optional; import java.util.Properties; import com.google.common.annotations.VisibleForTesting; /** * SSL configuration. * * Use the static factory methods, {@link #newBuilder} or {@link #of}, to create instances. */ public class SSLConfig { // SSL related connection properties public static final String ENABLE_SSL = "ssl"; public static final String TRUST_STORE_TYPE = "trustStoreType"; public static final String TRUST_STORE_PATH = "trustStore"; public static final String TRUST_STORE_PASSWORD = "trustStorePassword"; public static final String DISABLE_CERT_VERIFICATION = "disableCertificateVerification"; public static final String DISABLE_HOST_VERIFICATION = "disableHostVerification"; // if set to this value, default behavior is employed @VisibleForTesting public static final String UNSPECIFIED = ""; private final String keyStoreType; private final String keyStorePath; private final String keyStorePassword; private final String keyPassword; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; // Since a server always presents its certificate, for a client "true" means "do // not verify the server certificate". And for a server "true" means "do not require // the client to present a certificate". private final boolean disablePeerVerification; private final boolean disableHostVerification; // TODO(DX-12921): add other frequently used parameters (e.g. certificate alias) private SSLConfig( String keyStoreType, String keyStorePath, String keyStorePassword, String keyPassword, String trustStoreType, String trustStorePath, String trustStorePassword, boolean disablePeerVerification, boolean disableHostVerification ) { this.keyStoreType = keyStoreType; this.keyStorePath = keyStorePath; this.keyStorePassword = keyStorePassword; this.keyPassword = keyPassword; this.trustStoreType = trustStoreType; this.trustStorePath = trustStorePath; this.trustStorePassword = trustStorePassword; this.disablePeerVerification = disablePeerVerification; this.disableHostVerification = disableHostVerification; } public String getKeyStoreType() { return keyStoreType; } public String getKeyStorePath() { return keyStorePath; } public String getKeyStorePassword() { return keyStorePassword; } public String getKeyPassword() { return keyPassword; } public String getTrustStoreType() { return trustStoreType; } public String getTrustStorePath() { return trustStorePath; } public String getTrustStorePassword() { return trustStorePassword; } public boolean disablePeerVerification() { return disablePeerVerification; } public boolean disableHostVerification() { return disableHostVerification; } public static class Builder { private String keyStoreType = KeyStore.getDefaultType(); private String keyStorePath = UNSPECIFIED; // From https://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html // If there is no keystore password specified, it is assumed to be "". private String keyStorePassword = UNSPECIFIED; private String keyPassword = null; // defaults to 'keyStorePassword' private String trustStoreType = KeyStore.getDefaultType(); private String trustStorePath = UNSPECIFIED; // From https://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html // If there is no truststore password specified, it is assumed to be "". private String trustStorePassword = UNSPECIFIED; private boolean disablePeerVerification = false; private boolean disableHostVerification = false; private Builder() { } /** * Set key store type. Defaults to {@link KeyStore#getDefaultType}. * * @param keyStoreType key store type * @return this builder */ public Builder setKeyStoreType(String keyStoreType) { this.keyStoreType = keyStoreType; return this; } /** * Set key store path. Required on server-side. * * @param keyStorePath key store path * @return this builder */ public Builder setKeyStorePath(String keyStorePath) { this.keyStorePath = keyStorePath; return this; } /** * Set key store password. Very likely required on server-side. Defaults to empty string (""). * * @param keyStorePassword key store password * @return this builder */ public Builder setKeyStorePassword(String keyStorePassword) { this.keyStorePassword = keyStorePassword; return this; } /** * Set key password. Default to the value set by {@link #setKeyStorePassword}. * * @param keyPassword key password * @return this builder */ public Builder setKeyPassword(String keyPassword) { this.keyPassword = keyPassword; return this; } /** * Set trust store type. Defaults to {@link KeyStore#getDefaultType}. * * @param trustStoreType trust store type * @return this builder */ public Builder setTrustStoreType(String trustStoreType) { this.trustStoreType = trustStoreType; return this; } /** * Set trust store path. Very likely required on client-side. * * @param trustStorePath trust store password * @return this builder */ public Builder setTrustStorePath(String trustStorePath) { this.trustStorePath = trustStorePath; return this; } /** * Set trust store password. Very likely required on client-side. Defaults to empty string (""). * * @param trustStorePassword trust store password * @return this builder */ public Builder setTrustStorePassword(String trustStorePassword) { this.trustStorePassword = trustStorePassword; return this; } /** * Disable verifing the peer. Defaults to {@code false}. * * @param disable whether to disable * @return this builder */ public Builder setDisablePeerVerification(boolean disable) { this.disablePeerVerification = disable; return this; } /** * Disable host verification. Defaults to {@code false}. * * @param disable whether to disable * @return this builder */ public Builder setDisableHostVerification(boolean disable) { this.disableHostVerification = disable; return this; } /** * Build a new {@link SSLConfig} instance based on the parameters. * * @return SSL config */ public SSLConfig build() { return new SSLConfig( keyStoreType, keyStorePath, keyStorePassword, keyPassword == null ? keyStorePassword : keyPassword, trustStoreType, trustStorePath, trustStorePassword, disablePeerVerification, disableHostVerification); } } /** * Static factory method. * * @return new builder */ public static Builder newBuilder() { return new Builder(); } /** * Creates a {@link SSLConfig} from properties for a client. * * @param properties connection properties * @return SSL config, empty if not enabled */ public static Optional<SSLConfig> of(final Properties properties) { if (properties == null) { return Optional.empty(); } final Properties canonicalProperties = new Properties(); properties.stringPropertyNames() .forEach(s -> canonicalProperties.setProperty(s.toLowerCase(), properties.getProperty(s))); final Optional<Boolean> enabledOption = getBooleanProperty(canonicalProperties, ENABLE_SSL); return enabledOption.filter(Boolean::booleanValue) .map(ignored -> { final SSLConfig.Builder builder = SSLConfig.newBuilder(); getStringProperty(canonicalProperties, TRUST_STORE_TYPE) .ifPresent(builder::setTrustStoreType); getStringProperty(canonicalProperties, TRUST_STORE_PATH) .ifPresent(builder::setTrustStorePath); getStringProperty(canonicalProperties, TRUST_STORE_PASSWORD) .ifPresent(builder::setTrustStorePassword); getBooleanProperty(canonicalProperties, DISABLE_CERT_VERIFICATION) .ifPresent(builder::setDisablePeerVerification); getBooleanProperty(canonicalProperties, DISABLE_HOST_VERIFICATION) .ifPresent(builder::setDisableHostVerification); return builder.build(); }); } private static Optional<Boolean> getBooleanProperty(Properties canonicalProperties, String key) { return Optional.ofNullable(canonicalProperties.getProperty(key.toLowerCase())) .map(Boolean::parseBoolean); } private static Optional<String> getStringProperty(Properties canonicalProperties, String key) { return Optional.ofNullable(canonicalProperties.getProperty(key.toLowerCase())); } }
true
1b0732e22a9780afbe35df19a8de44841e0e81fa
Java
oumarxy/Android-Code-Demos
/CrashHandlerDemo/app/src/main/java/io/innofang/crashhandlerdemo/util/PermissionListener.java
UTF-8
315
2.015625
2
[ "Apache-2.0" ]
permissive
package io.innofang.crashhandlerdemo.util; import java.util.List; /** * Author: Inno Fang * Time: 2017/4/24 14:52 * Description: */ public interface PermissionListener { /* 授权 */ void onGranted(); /* 拒绝,并传入被拒绝的权限 */ void onDenied(List<String>deniedPermission); }
true
2677f79fabbf2b790c6adbbe65d7a20b2248be89
Java
tkurtovic98/Java-Course
/Project-10/src/main/java/hr/fer/zemris/java/webserver/workers/Home.java
UTF-8
806
2.640625
3
[]
no_license
package hr.fer.zemris.java.webserver.workers; import java.util.Set; import hr.fer.zemris.java.webserver.IWebWorker; import hr.fer.zemris.java.webserver.RequestContext; /** * {@link IWebWorker} that is used to add * background color if the color exists * in the server collections * @author Tomislav Kurtović * */ public class Home implements IWebWorker { @Override public void processRequest(RequestContext context) throws Exception { Set<String> params = context.getPersistentParameterNames(); String background = ""; if(params.contains("bgcolor")) { background = context.getPersistentParameter("bgcolor"); } else { background = "7F7F7F"; } context.setTemporaryParameter("background", background); context.getDispatcher().dispatchRequest("/private/pages/home.smscr"); } }
true
462a26b78932a1b8f2677bcaea07d7c36e5bddca
Java
nicolopomini/ProgettoWEB
/Progetto/src/main/java/dao/jdbc/JDBCPictureDAO.java
UTF-8
5,770
2.671875
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 dao.jdbc; import dao.PictureDAO; import dao.entities.Picture; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import persistence.utils.dao.exceptions.DAOException; import persistence.utils.dao.jdbc.JDBCDAO; /** * * @author Gabriele */ public class JDBCPictureDAO extends JDBCDAO<Picture, Integer> implements PictureDAO{ public JDBCPictureDAO(Connection con) { super(con); } @Override public Integer getCount() throws DAOException { try (PreparedStatement stm = CON.prepareStatement("SELECT COUNT(*) FROM Picture");) { ResultSet rs = stm.executeQuery(); if (rs.next()) { return rs.getInt(1); } } catch (SQLException ex) { throw new DAOException("Impossible to count pictures", ex); } return 0; } @Override public Picture getByPrimaryKey(Integer primaryKey) throws DAOException { if (primaryKey == null) { throw new DAOException("primaryKey is null"); } try (PreparedStatement stm = CON.prepareStatement("SELECT * FROM Picture WHERE pictureId = ?")) { stm.setInt(1, primaryKey); try (ResultSet rs = stm.executeQuery()) { rs.next(); Picture picture = new Picture(); picture.setPictureId(rs.getInt("pictureId")); picture.setPath(rs.getString("path")); picture.setItemId(rs.getInt("itemId")); return picture; } } catch (SQLException ex) { throw new DAOException("Impossible to get the picture for the passed primary key", ex); } } @Override public List<Picture> getAll() throws DAOException { try (PreparedStatement stm = CON.prepareStatement("SELECT * FROM Picture")) { try (ResultSet rs = stm.executeQuery()) { ArrayList<Picture> pictures = new ArrayList<>(); while(rs.next()) { Picture picture = new Picture(); picture.setPictureId(rs.getInt("pictureId")); picture.setPath(rs.getString("path")); picture.setItemId(rs.getInt("itemId")); pictures.add(picture); } return pictures; } } catch (SQLException ex) { throw new DAOException("Impossible to get pictures", ex); } } @Override public Picture update(Picture picture) throws DAOException { try (PreparedStatement stm = CON.prepareStatement("UPDATE Picture SET path = ?, ItemId = ? WHERE pictureId = ?;")) { stm.setString(1, picture.getPath()); stm.setInt(2, picture.getItemId()); stm.setInt(3, picture.getPictureId()); stm.executeUpdate(); return picture; } catch (SQLException ex) { throw new DAOException("Impossible to update the picture", ex); } } @Override public Picture add(Picture picture) throws DAOException { try (PreparedStatement stm = CON.prepareStatement("INSERT INTO Picture (path, itemId) VALUES (?, ?);", Statement.RETURN_GENERATED_KEYS)) { stm.setString(1, picture.getPath()); stm.setInt(2, picture.getItemId()); stm.executeUpdate(); ResultSet rs = stm.getGeneratedKeys(); if(rs.next()) { int pictureId = rs.getInt(1); picture.setPictureId(pictureId); } return picture; } catch (SQLException ex) { throw new DAOException("Impossible to add the picture", ex); } } @Override public void removeByPrimaryKey(Integer primaryKey) throws DAOException { if (primaryKey == null) { throw new DAOException("primaryKey is null"); } try (PreparedStatement stm = CON.prepareStatement("DELETE FROM Picture WHERE pictureId = ?")) { stm.setInt(1, primaryKey); stm.executeUpdate(); } catch (SQLException ex) { throw new DAOException("Impossible to remove the picture", ex); } } @Override public ArrayList<Picture> getByItemId(Integer itemId) throws DAOException { if (itemId == null) { throw new DAOException("itemId is null"); } try (PreparedStatement stm = CON.prepareStatement("SELECT * FROM Picture WHERE itemId = ?")) { stm.setInt(1, itemId); try (ResultSet rs = stm.executeQuery()) { ArrayList<Picture> pictures = new ArrayList<>(); while(rs.next()) { Picture picture = new Picture(); picture.setPictureId(rs.getInt("pictureId")); picture.setPath(rs.getString("path")); picture.setItemId(rs.getInt("itemId")); pictures.add(picture); } return pictures; } } catch (SQLException ex) { throw new DAOException("Impossible to get pictures for the passed itemId", ex); } } }
true
ed35b4cd73f47b0fab19434a8844ce249d290168
Java
Evergreen1992/leetcode_algorithm_solutions_in_java
/src/company/huawei/Main2.java
UTF-8
1,968
3.28125
3
[]
no_license
package company.huawei; import java.util.Scanner; public class Main2 { public static int[] rev(int[] init, char item){ int[] newA = new int[6]; if( item == 'L' ){ int t1 = init[0]; int t2 = init[1]; int t5 = init[4]; int t6 = init[5]; init[0] = t5; init[1] = t6; init[4] = t2; init[5] = t1; }else if(item == 'R'){ int t1 = init[0]; int t2 = init[1]; int t5 = init[4]; int t6 = init[5]; init[0] = t6; init[1] = t5; init[4] = t1; init[5] = t2; }else if(item == 'F'){ int t3 = init[2]; int t4 = init[3]; int t5 = init[4]; int t6 = init[5]; init[2]=t5; init[3]=t6; init[4]=t4; init[5]=t3; }else if(item == 'B'){ int t3 = init[2]; int t4 = init[3]; int t5 = init[4]; int t6 = init[5]; init[2]=t6; init[3]=t5; init[4]=t3; init[5]=t4; }else if(item == 'C'){ int t1 = init[0]; int t2 = init[1]; int t3 = init[2]; int t4 = init[3]; init[0]=t3; init[1]=t4; init[2]=t2; init[3]=t1; }else if(item == 'A'){ int t1 = init[0]; int t2 = init[1]; int t3 = init[2]; int t4 = init[3]; init[0]=t4; init[1]=t3; init[2]=t1; init[3]=t2; } for(int i = 0 ; i <6; i ++){ newA[i] = init[i]; } return newA; } //L.R向左。右旋转 //F.B 前后翻转 //A.C逆时针 顺时针 public static String reverse(String cmd){ if( cmd == null || cmd.equals("")) return null; String result = "" ; int[] init = new int[]{1,2,3,4,5,6}; for(int i = 0 ; i < cmd.length(); i ++){ char item = cmd.charAt(i); init = rev(init, item); } for(int ii = 0; ii < 6; ii ++) result += init[ii] + ""; return result ; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNextLine()){ String str = in.next(); System.out.println(reverse(str)); } } }
true
3be83d26314669bd903705574d30d8ba1960c2ed
Java
kvenLin/Algorithm
/JianzhiOffer/src/CloneRandomList.java
UTF-8
2,447
3.765625
4
[]
no_license
/** * @Author: clf * @Date: 18-12-10 * @Description: * 输入一个复杂链表 * (每个节点中有节点值,以及两个指针,一个指向下一个节点,一个特殊指针指向任意一个节点), * 返回结果为复制后复杂链表的head。 * (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) */ public class CloneRandomList { public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } public RandomListNode Clone(RandomListNode pHead){ CloneNodes(pHead); ConnectRandomNodes(pHead); return ReConnectNodes(pHead); } // 第一步:根据原始链表的每个结点N创建对应的结点N' private void CloneNodes(RandomListNode pHead){ RandomListNode node = pHead; while (node != null){ RandomListNode cloneNode = new RandomListNode(node.label); cloneNode.next = node.next; cloneNode.random = null; node.next = cloneNode; node = cloneNode.next; } } // 第二步:设置复制出来结点的random.假设原始结点的随机指向S,复制出来结点的random指向S后一个 private void ConnectRandomNodes(RandomListNode pHead){ RandomListNode node = pHead; while (node != null){ RandomListNode clone = node.next; if (node.random != null){ clone.random = node.random.next; } node = clone.next; } } // 第三步:把这个长链表拆分成两个链表,奇数位置连接起来就是原始链表,偶数结点连接起来就是复制结点 private RandomListNode ReConnectNodes(RandomListNode pHead){ RandomListNode node = pHead; RandomListNode cloneHead = null; RandomListNode cloneNode = null; // 设置第一个节点 if (node != null){ cloneHead = node.next; cloneNode = node.next; node.next = cloneNode.next; node = node.next; } while (node != null){ cloneNode.next = node.next; cloneNode = cloneNode.next; node.next = cloneNode.next; node = node.next; } return cloneHead; } }
true
0337b7ad8b50a89b620e6e73a56e14eccc0c9318
Java
saveunhappy/996
/src/test/java/com/imooc/zhangxiaoxi/lombok/LogTest.java
UTF-8
358
2.15625
2
[ "MIT" ]
permissive
package com.imooc.zhangxiaoxi.lombok; import lombok.extern.slf4j.Slf4j; import org.junit.Test; /** * 类名称:LogTest * ******************************** * <p> * 类描述:@Slf4j注解 * * @author zhangxiaoxi * @date 下午6:00 */ @Slf4j public class LogTest { @Test public void func() { log.error("日志!!!"); } }
true
c2eff3c059dad90c783d7c07240a52f70686d0a3
Java
SalmaAbuelnaga/DatabaseEngine
/src/main/java/page.java
UTF-8
1,516
2.234375
2
[]
no_license
import java.beans.Transient; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Hashtable; import java.util.Vector; public class page implements Serializable { String table; int pageno; Hashtable first; Hashtable last; int noOfRe; page prev; page next; Vector <page>overflow; public String getTable() { return table; } public void setTable(String table) { this.table = table; } public int getPageno() { return pageno; } public void setPageno(int pageno) { this.pageno = pageno; } public int getNoOfRe() { return noOfRe; } public void setNoOfRe(int noOfRe) { this.noOfRe = noOfRe; } public page getPrev() { return prev; } public void setPrev(page prev) { this.prev = prev; } public Hashtable getFirst() { return first; } public void setFirst(Hashtable first) { this.first = first; } public Hashtable getLast() { return last; } public void setLast(Hashtable last) { this.last = last; } String filepath; public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public page (String t,int pageNumber) { table=t; pageno=pageNumber; overflow = new Vector(); } public page getNext() { return next; } public void setNext(page next) { this.next = next; } public Vector getOverflow() { return overflow; } public void setOverflow(Vector overflow) { this.overflow = overflow; } }
true
3273d519786eb0082fda17d3547b2239f5e3d2de
Java
marvenhool/AndroidDemos
/ListViewEventDemo/src/com/example/listvieweventdemo/MySimpleAdapter.java
UTF-8
2,671
2.421875
2
[]
no_license
package com.example.listvieweventdemo; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; public class MySimpleAdapter extends BaseAdapter { private LayoutInflater mInflater; private List<Map<String, Object>> list; private int layoutID; private String flag[]; private int ItemIDs[]; public MySimpleAdapter(Context context, List<Map<String, Object>> list, int layoutID, String flag[], int ItemIDs[]) { this.mInflater = LayoutInflater.from(context); this.list = list; this.layoutID = layoutID; this.flag = flag; this.ItemIDs = ItemIDs; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return 0; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(layoutID, null); for (int i = 0; i < flag.length; i++) { if (convertView.findViewById(ItemIDs[i]) instanceof TextView) { TextView tv = (TextView) convertView.findViewById(ItemIDs[i]); tv.setText((String) list.get(position).get(flag[i])); }else{ //遍历所有控件,映射到每一个List中去设置数据 } } //存在监听事件的控件是不能直接映射的,在addListener方法中增加监听器就好了 addListener(convertView,position); return convertView; } public void addListener(View convertView, final int position) { Button btn_set = (Button)convertView.findViewById(R.id.view_btn); btn_set.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // new AlertDialog.Builder(MainActivity.ma) // .setMessage("当前点击的Item是"+ position) // .show(); //list.remove(position); MainActivity.dataList.remove(position); MainActivity.adapter.notifyDataSetChanged(); } }); } }
true
38a1da840990e9887b7be6e265f639f600060b72
Java
markusheikkinen/vaadin-aceeditor
/aceeditor-demo/src/main/java/org/vaadin/aceeditor/LeetSpeakerizer.java
UTF-8
738
2.5625
3
[ "Apache-2.0" ]
permissive
package org.vaadin.aceeditor; import com.vaadin.data.HasValue; @SuppressWarnings("serial") public class LeetSpeakerizer implements HasValue.ValueChangeListener<String> { private AceEditor editor; public void attachTo(AceEditor editor) { this.editor = editor; // editor.addValueChangeListener(this); correctText(editor.getValue()); } private void correctText(String text) { String text2 = text .replaceAll("l", "1") .replaceAll("e", "3") .replaceAll("k", "|<") .replaceAll("a", "4") .replaceAll("o", "0") .replaceAll("t", "7"); editor.setValue(text2); } @Override public void valueChange(HasValue.ValueChangeEvent<String> valueChangeEvent) { correctText(valueChangeEvent.getValue()); } }
true
99f2f0bafc0c004a915e7751ce592b97cb0bf81d
Java
jijiny/programmers
/src/P_200311_BruteForceSearch/PrimeNumberFinal.java
UTF-8
1,864
3.421875
3
[]
no_license
package P_200311_BruteForceSearch; import java.util.HashSet; import java.util.Set; public class PrimeNumberFinal { public static int solution(String numbers) { int answer = 0; Set<Integer> primeNo = new HashSet<>(); int[] number = new int[numbers.length()]; int n = number.length; for(int i=0; i<numbers.length(); i++) { number[i] = Integer.parseInt(numbers.substring(i,i+1)); } // for(int i=0; i<=numbers.length(); i++){ /*0이면 비어있어서 NumberFormatException*/ for(int i=1; i<=numbers.length(); i++){ perm(number, 0, n, i, primeNo); } answer = primeNo.size(); System.out.println(answer); return answer; } public static void perm(int[] arr, int depth, int n, int r, Set primeNo) { if(depth == r) { print(arr, r, primeNo); return; } for(int i=depth; i<n; i++) { swap(arr, depth, i); perm(arr, depth+1, n, r, primeNo); swap(arr, depth, i); } } public static void swap(int[] arr, int depth, int i) { int temp = arr[depth]; arr[depth] = arr[i]; arr[i] = temp; } public static void print(int[] arr, int r, Set primeNo) { StringBuilder num = new StringBuilder(); int count = 0; for(int i=0; i<r; i++) { num.append(arr[i]); } int no = Integer.parseInt(num.toString()); for(int i=2; i<no; i++) { if(no%i==0) { count++; break; } } if(count==0 && no != 0 && no != 1) { primeNo.add(no); } } public static void main(String[] args) { String number = "17"; // String number = "011"; solution(number); } }
true
c296e6d999d50f685fa37ddad86a83fcf4ca3330
Java
hisabimbola/andexpensecal
/com/expensemanager/tc.java
UTF-8
594
1.867188
2
[]
no_license
package com.expensemanager; import android.text.InputFilter; import android.text.Spanned; class tc implements InputFilter { final /* synthetic */ ExpenseGroupAddEdit f5286a; tc(ExpenseGroupAddEdit expenseGroupAddEdit) { this.f5286a = expenseGroupAddEdit; } public CharSequence filter(CharSequence charSequence, int i, int i2, Spanned spanned, int i3, int i4) { while (i < i2) { if (charSequence.charAt(i) == '\'' || charSequence.charAt(i) == ',') { return ""; } i++; } return null; } }
true
6300c90cf51ba3a4bb9c05ff5fd2cf550065667c
Java
xiexlp/DbAutoJavaFx
/src/com/js/cms/orm/CurrencyPrice.java
UTF-8
198
1.5
2
[]
no_license
package com.js.cms.orm; import com.js.cms.ormex.CurrencyPriceEx; import com.js.common.anno.TableAnno; @TableAnno(name="ex_currency_price") public class CurrencyPrice extends CurrencyPriceEx { }
true
5ecaec6c1bf62609351d45adbf8d5b9a0920cfbf
Java
HowieHai/Android_MobileAssistant
/app/src/main/java/com/example/shenhaichen/mobileassistant/ui/fragment/DownloadedFragment.java
UTF-8
1,305
1.984375
2
[]
no_license
package com.example.shenhaichen.mobileassistant.ui.fragment; import android.support.v7.widget.RecyclerView; import com.example.shenhaichen.mobileassistant.common.apkparset.AndroidApk; import com.example.shenhaichen.mobileassistant.dagger.component.AppComponent; import java.util.List; /** * 菜鸟窝http://www.cniao5.com 一个高端的互联网技能学习平台 * * @author Ivan * @version V1.0 * @Package com.cniao5.cniao5play.ui.fragment * @Description: ${TODO}(用一句话描述该文件做什么) * @date */ public class DownloadedFragment extends AppManagerFragment { // AndroidApkAdapter mAdapter; @Override public void init() { super.init(); mPresenter.getLocalApks(); } @Override public void setupActivityComponent(AppComponent appComponent) { // DaggerAppManagerComponent.builder() // .appComponent(appComponent) // .appManagerModule(new AppManagerModule(this)) // .build().injectDownloaded(this); } @Override protected RecyclerView.Adapter setupAdapter() { // mAdapter = new AndroidApkAdapter(AndroidApkAdapter.FLAG_APK); return null; } @Override public void showApps(List<AndroidApk> apps) { // mAdapter.addData(apps); } }
true
e57dffb679bbfc8e472109688c16a3ed1e30455b
Java
morristech/Spring-Two-Factor-Auth-Server
/src/main/java/springtemplate/services/UserService.java
UTF-8
254
2.1875
2
[]
no_license
package springtemplate.services; public interface UserService { boolean authenticate(String email, String password); boolean register(String fullName, String email, String password, String last_ip); String getUniqueKey(String user_email); }
true
5cc6cf29036eecee2beee9da016aec84b06ab973
Java
linshuguang/myspark
/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/parser/PlanParserSuite.java
UTF-8
50,883
1.867188
2
[]
no_license
package org.apache.spark.sql.catalyst.parser; import javafx.util.Pair; import org.apache.spark.sql.catalyst.analysis.AnalysisTest; import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute; import org.apache.spark.sql.catalyst.analysis.unresolved.*; import org.apache.spark.sql.catalyst.expressions.*; import org.apache.spark.sql.catalyst.expressions.arithmetic.Divide; import org.apache.spark.sql.catalyst.expressions.arithmetic.UnaryMinus; import org.apache.spark.sql.catalyst.expressions.complexTypeCreator.CreateStruct; import org.apache.spark.sql.catalyst.expressions.grouping.Cube; import org.apache.spark.sql.catalyst.expressions.grouping.Rollup; import org.apache.spark.sql.catalyst.expressions.literals.Literal; import org.apache.spark.sql.catalyst.expressions.namedExpressions.NamedExpression; import org.apache.spark.sql.catalyst.expressions.predicates.*; import org.apache.spark.sql.catalyst.expressions.subquery.ScalarSubquery; import org.apache.spark.sql.catalyst.expressions.windowExpressions.RowFrame; import org.apache.spark.sql.catalyst.expressions.windowExpressions.SpecifiedWindowFrame; import org.apache.spark.sql.catalyst.expressions.windowExpressions.UnspecifiedFrame; import org.apache.spark.sql.catalyst.expressions.windowExpressions.WindowSpecDefinition; import org.apache.spark.sql.catalyst.identifiers.FunctionIdentifier; import org.apache.spark.sql.catalyst.identifiers.TableIdentifier; import org.apache.spark.sql.catalyst.plans.joinTypes.*; import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan; import org.apache.spark.sql.catalyst.plans.logical.SubqueryAlias; import org.apache.spark.sql.catalyst.plans.logical.basicLogicalOperators.*; import org.apache.spark.sql.catalyst.plans.logical.hints.UnresolvedHint; import org.apache.spark.sql.types.IntegerType; import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import sun.rmi.runtime.Log; import org.apache.spark.sql.catalyst.expressions.namedExpressions.Alias; import java.lang.reflect.Array; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; /** * Created by kenya on 2019/3/26. */ @SuppressWarnings("ALL") @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext-test.xml"}) public class PlanParserSuite extends AnalysisTest { @Autowired CatalystSqlParser catalystSqlParser; void assertEqual( String sqlCommand, LogicalPlan plan){ comparePlans(catalystSqlParser.parsePlan(sqlCommand), plan, false); } void intercept(String sqlCommand, String...messages) { try { catalystSqlParser.parsePlan(sqlCommand); } catch (ParseException e) { for (String message : messages) { assert (e.getMessage().contains(message)); } } } private UnresolvedFunction function(String s, Expression...exprs){ return new UnresolvedFunction(s, Arrays.asList(exprs), false); } private LogicalPlan limit(LogicalPlan logicalPlan, Expression limitExpr ){ return Limit.build(limitExpr, logicalPlan); } private LogicalPlan insertInto(LogicalPlan logicalPlan,String tableName){ return insertInto(logicalPlan,tableName,false); } private LogicalPlan insertInto(LogicalPlan logicalPlan,String tableName, boolean overwrite){ return new InsertIntoTable( new UnresolvedRelation(new TableIdentifier(tableName)), new HashMap<>(), logicalPlan, overwrite, false ); } private LogicalPlan union(LogicalPlan logicalPlan, LogicalPlan otherPlan){ return new Union(logicalPlan,otherPlan); } private LogicalPlan intersect(LogicalPlan logicalPlan,LogicalPlan otherPlan,boolean isAll){ return new Intersect(logicalPlan, otherPlan, isAll); } private LogicalPlan except(LogicalPlan logicalPlan,LogicalPlan otherPlan,boolean isAll){ return new Except(logicalPlan, otherPlan, isAll); } private LogicalPlan where(LogicalPlan logicalPlan,Expression condition) { return new Filter(condition, logicalPlan); } private LogicalPlan groupBy(LogicalPlan logicalPlan, List<Expression>groupingExprs,List<Expression>aggregateExprs){ List<NamedExpression>aliasedExprs = new ArrayList<>(); for(Expression expr:aggregateExprs){ if(expr instanceof NamedExpression){ aliasedExprs.add((NamedExpression) expr); }else{ aliasedExprs.add(new Alias(expr,expr.toString())); } } return new Aggregate(groupingExprs, aliasedExprs, logicalPlan); } private LogicalPlan table(String db,String ref) { return new UnresolvedRelation(new TableIdentifier(ref,db)); } private LogicalPlan orderBy(LogicalPlan logicalPlan,SortOrder...sortExprs){ return new Sort(Arrays.asList(sortExprs), true,logicalPlan); } private LogicalPlan sortBy(LogicalPlan logicalPlan,SortOrder...sortExprs){ return new Sort(Arrays.asList(sortExprs), true,logicalPlan); } private LogicalPlan generate(LogicalPlan logicalPlan,Generator generator){ return generate(logicalPlan, generator, new ArrayList<>(),false,null,new ArrayList<>()); } private LogicalPlan generate( LogicalPlan logicalPlan, Generator generator, List<Integer>unrequiredChildIndex, boolean outer, String alias, List<String >outputNames){ List<Attribute> attributes = new ArrayList<>(); for(String name: outputNames){ attributes.add(new UnresolvedAttribute(name)); } return new Generate(generator, unrequiredChildIndex, outer, alias, attributes, logicalPlan); } private LogicalPlan as(LogicalPlan logicalPlan, String alias){ return new SubqueryAlias(alias, logicalPlan); } private LogicalPlan join( LogicalPlan logicalPlan, LogicalPlan otherPlan ){ return join(logicalPlan,otherPlan, new Inner(),null); } private LogicalPlan join( LogicalPlan logicalPlan, LogicalPlan otherPlan, JoinType joinType ){ return join(logicalPlan,otherPlan, joinType,null); } private LogicalPlan join( LogicalPlan logicalPlan, LogicalPlan otherPlan, JoinType joinType, Expression condition){ return new Join(logicalPlan, otherPlan, joinType, condition); } private LogicalPlan table(String ref) { return new UnresolvedRelation(new TableIdentifier(ref)); } private Expression star(String...names){ if(names.length==0){ return new UnresolvedStar(); }else{ return new UnresolvedStar(Arrays.asList(names)); } } // private LogicalPlan insertInto(LogicalPlan logicalPlan, String tableName, boolean overwrite) { // // // return new InsertIntoTable( // new UnresolvedRelation(new TableIdentifier(tableName)), // new HashMap<>(), logicalPlan, overwrite, false); // } private LogicalPlan select(LogicalPlan logicalPlan, Expression...exprs){ List<NamedExpression> namedExpressions = new ArrayList<>(); for(Expression expr:exprs){ if(expr instanceof NamedExpression){ namedExpressions.add((NamedExpression)expr); }else{ namedExpressions.add(new UnresolvedAlias(expr)); } } return new Project(namedExpressions, logicalPlan); } @Test public void testCaseInsensitive() { LogicalPlan plan = select(table("a"),star()); assertEqual("sELEct * FroM a", plan); assertEqual("select * fRoM a", plan); assertEqual("SELECT * FROM a", plan); } @Test public void testExplain() { intercept("EXPLAIN logical SELECT 1", "Unsupported SQL statement"); intercept("EXPLAIN formatted SELECT 1", "Unsupported SQL statement"); } @Test public void testSetOperations() { LogicalPlan a = select(table("a"),star()); LogicalPlan b = select(table("b"),star()); assertEqual("select * from a union select * from b", new Distinct(new Union(a,b))); assertEqual("select * from a union distinct select * from b", new Distinct(new Union(a,b))); assertEqual("select * from a union all select * from b", new Union(a,b)); assertEqual("select * from a except select * from b", new Except(a,b,false)); assertEqual("select * from a except distinct select * from b", new Except(a,b,false)); assertEqual("select * from a except all select * from b", new Except(a,b,true)); assertEqual("select * from a minus select * from b", new Except(a,b,false)); assertEqual("select * from a minus all select * from b", new Except(a,b,true)); assertEqual("select * from a minus distinct select * from b", new Except(a,b,false)); assertEqual("select * from a " + "intersect select * from b", new Intersect(a,b,false)); assertEqual("select * from a intersect distinct select * from b", new Intersect(a,b,false)); assertEqual("select * from a intersect all select * from b", new Intersect(a,b,true)); } private With cte(LogicalPlan plan, Pair<String, LogicalPlan>...namedPlans) { List<Pair<String, SubqueryAlias>> ctes = new ArrayList<>(); for (Pair<String, LogicalPlan> pair : namedPlans) { ctes.add(new Pair<>(pair.getKey(), new SubqueryAlias(pair.getKey(), pair.getValue()))); } return new With(plan, ctes); } @Test public void testCommonTableExpressions() { assertEqual( "with cte1 as (select * from a) select * from cte1", cte(select(table("cte1"),star()), new Pair<>("cte1",select(table("a"),(star()))))); assertEqual( "with cte1 (select 1) select * from cte1", cte(select(table("cte1"),star()), new Pair<>("cte1",select(new OneRowRelation(), Literal.build(new Integer(1)))))); assertEqual( "with cte1 (select 1), cte2 as (select * from cte1) select * from cte2", cte( select(table("cte2"),star()), new Pair<>("cte1", select(new OneRowRelation(), Literal.build(new Integer(1)))), new Pair<>("cte2" , select(table("cte1"),star())))); intercept( "with cte1 (select 1), cte1 as (select 1 from cte1) select * from cte1", "Found duplicate keys 'cte1'"); } @Test public void testSimpleSelectQuery() { assertEqual("select 1", select(new OneRowRelation(),Literal.build(new Integer(1)))); assertEqual("select a, b", select(new OneRowRelation(), new UnresolvedAttribute("a"), new UnresolvedAttribute("b"))); assertEqual("select a, b from db.c", select(table("db", "c"),new UnresolvedAttribute("a"), new UnresolvedAttribute("b"))); assertEqual("select a, b from db.c where x < 1", select( where( table("db", "c"), new LessThan(new UnresolvedAttribute("x"),Literal.build(new Integer(1)))), new UnresolvedAttribute("a"), new UnresolvedAttribute("b"))); assertEqual( "select a, b from db.c having x < 1", where( groupBy( table("db", "c"), null, Arrays.asList(new UnresolvedAttribute("a"),new UnresolvedAttribute("b")) ), new LessThan(new UnresolvedAttribute("x"),Literal.build(new Integer(1))))); assertEqual("select distinct a, b from db.c", new Distinct(select(table("db", "c"),new UnresolvedAttribute("a"), new UnresolvedAttribute("b")))); assertEqual("select all a, b from db.c", select(table("db", "c"),new UnresolvedAttribute("a"), new UnresolvedAttribute("b"))); assertEqual("select from tbl", select( new OneRowRelation(),new Alias(new UnresolvedAttribute("from"),"tbl"))); assertEqual("select a from 1k.2m", select (table("1k", "2m"),new UnresolvedAttribute("a"))); } @Test public void TestRreverseSelectQuery() { //assertEqual("from a", table("a")); // assertEqual("from a select b, c", select(table("a"),new UnresolvedAttribute("b"),new UnresolvedAttribute("c"))); assertEqual( "from db.a select b, c where d < 1", select (where(table("db", "a"), new LessThan(new UnresolvedAttribute("x"),Literal.build(new Integer(1)))),new UnresolvedAttribute("b"),new UnresolvedAttribute("c"))); assertEqual("from a select distinct b, c", new Distinct(select(table("a"),new UnresolvedAttribute("b"),new UnresolvedAttribute("c")))); assertEqual( "from (from a union all from b) c select *", select(new SubqueryAlias("c",union(table("a"),table("b"))),star())); } @Test public void testMultiSelectQuery() { assertEqual( "from a select * select * where s < 10", union(select(table("a"), star()), select(where(table("a"), new LessThan(new UnresolvedAttribute("s"), Literal.build(new Integer(10)))), star()))); intercept( "from a select * select * from x where a.s < 10", "Multi-Insert queries cannot have a FROM clause in their individual SELECT statements"); assertEqual( "from a insert into tbl1 select * insert into tbl2 select * where s < 10", union( insertInto(select(table("a"), star()), "tbl1"), insertInto( select(where(table("a"), new LessThan(new UnresolvedAttribute("s"), Literal.build(new Integer(10)))),star()), "tbl2"))); } @Test public void testQueryOrganization() { // Test all valid combinations of order by/sort by/distribute by/cluster by/limit/windows String baseSql = "select * from t"; LogicalPlan basePlan = select(table("t"),star()); Map<String,WindowSpecDefinition> ws = new HashMap<>(); ws.put("w1",new WindowSpecDefinition(new ArrayList<>(), new ArrayList<>(), new UnspecifiedFrame())); List<Pair<String,LogicalPlan>>orderSortDistrClusterClauses = new ArrayList<>(); orderSortDistrClusterClauses.add(new Pair<>("", basePlan)); orderSortDistrClusterClauses.add(new Pair<>(" order by a, b desc", orderBy(basePlan,new SortOrder(new UnresolvedAttribute("a"),new Ascending()),new SortOrder(new UnresolvedAttribute("b"),new Descending())))); orderSortDistrClusterClauses.add(new Pair<>(" sort by a, b desc", sortBy(basePlan,new SortOrder(new UnresolvedAttribute("a"),new Ascending()),new SortOrder(new UnresolvedAttribute("b"),new Descending())))); for(Pair<String,LogicalPlan>pair:orderSortDistrClusterClauses) { String s1 = pair.getKey(); LogicalPlan p1 = pair.getValue(); String s = baseSql + s1; assertEqual(s + " limit 10", limit(p1, Literal.build(new Integer(10)))); assertEqual(s + " window w1 as ()", new WithWindowDefinition(ws, p1)); assertEqual(s + " window w1 as () limit 10", limit(new WithWindowDefinition(ws, p1), Literal.build(new Integer(10)))); } String msg = "Combination of ORDER BY/SORT BY/DISTRIBUTE BY/CLUSTER BY is not supported"; intercept(baseSql +" order by a sort by a", msg); intercept(baseSql+" cluster by a distribute by a", msg); intercept(baseSql+" order by a cluster by a", msg); intercept(baseSql+" order by a distribute by a", msg); } private LogicalPlan insert( LogicalPlan plan, Map<String,String>partition, boolean overwrite, boolean ifPartitionNotExists){ return new InsertIntoTable(table("s"), partition, plan, overwrite, ifPartitionNotExists); } private LogicalPlan insert( LogicalPlan plan, Map<String,String>partition ){ return insert(plan,partition,false,false); } @Test public void testInsertInto() { String sql = "select * from t"; LogicalPlan plan = select(table("t"), star()); // Single inserts assertEqual("insert overwrite table s " + sql, insert(plan, new HashMap<>(), true, false)); Map<String, String> map = new HashMap<>(); map.put("e", "1"); assertEqual("insert overwrite table s partition (e = 1) if not exists " + sql, insert(plan, map, true, true)); assertEqual("insert into s " + sql, insert(plan, new HashMap<>())); map.put("e", "1"); map.put("c", "d"); assertEqual("insert into table s partition (c = 'd', e = 1) " + sql, insert(plan, map)); // Multi insert LogicalPlan plan2 = select( where( table("t"), new LessThan(new UnresolvedAttribute("x"), Literal.build(new Integer(5)))), star()); assertEqual("from t insert into s select * limit 1 insert into u select * where x > 5", union( new InsertIntoTable( table("s"), new HashMap<>(), limit(plan, Literal.build(new Integer(1))), false, false), new InsertIntoTable( table("u"), new HashMap<>(), plan2, false, false))); } @Test public void testInsertWithIfNotExists() { String sql = "select * from t"; intercept("insert overwrite table s partition (e = 1, x) if not exists "+sql, "Dynamic partitions do not support IF NOT EXISTS. Specified partitions with value: [x]"); intercept("insert overwrite table s if not exists "+sql,"mismatched input 'if' expecting {'(', 'SELECT', 'FROM', 'VALUES', 'TABLE', 'MAP', 'REDUCE'}"); } @Test public void testAggregation() { String sql = "select a, b, sum(c) as c from d group by a, b"; // // Normal // assertEqual(sql, // groupBy(table("d"), // Arrays.asList(new UnresolvedAttribute("a"),new UnresolvedAttribute("b")), // Arrays.asList(new UnresolvedAttribute("a"),new UnresolvedAttribute("b"), new Alias(function("sum",new UnresolvedAttribute("c")),"c")) // )); // // // Cube // assertEqual(sql+" with cube", // groupBy(table("d"), // Arrays.asList(new Cube(Arrays.asList(new UnresolvedAttribute("a"),new UnresolvedAttribute("b")))), // Arrays.asList(new UnresolvedAttribute("a"),new UnresolvedAttribute("b"), new Alias(function("sum",new UnresolvedAttribute("c")),"c")) // )); // // // // Rollup // assertEqual(sql+" with rollup", // groupBy(table("d"), // Arrays.asList(new Rollup(Arrays.asList(new UnresolvedAttribute("a"),new UnresolvedAttribute("b")))), // Arrays.asList(new UnresolvedAttribute("a"),new UnresolvedAttribute("b"), new Alias(function("sum",new UnresolvedAttribute("c")),"c")) // )); // Grouping Sets assertEqual(sql + " grouping sets((a, b), (a), ())", new GroupingSets( Arrays.asList( Arrays.asList(new UnresolvedAttribute("a"), new UnresolvedAttribute("b")), Arrays.asList(new UnresolvedAttribute("a")), new ArrayList<>() ), Arrays.asList(new UnresolvedAttribute("a"), new UnresolvedAttribute("b")), table("d"), Arrays.asList(new UnresolvedAttribute("a"), new UnresolvedAttribute("b"), new Alias(function("sum", new UnresolvedAttribute("c")), "c")) )); intercept("SELECT a, b, count(distinct a, distinct b) as c FROM d GROUP BY a, b", "extraneous input 'b'"); } @Test public void testLimit() { String sql = "select * from t"; LogicalPlan plan = select (table("t"),star()); assertEqual(sql+" limit 10", limit(plan,Literal.build(new Integer(10)))); assertEqual(sql+" limit cast(9 / 4 as int)", limit(plan, new Cast(new Divide(Literal.build(new Integer(9)), Literal.build(new Integer(4))), new IntegerType()))); } @Test public void testWindowSpec() { // Note that WindowSpecs are testing in the ExpressionParserSuite String sql = "select * from t"; LogicalPlan plan = select(table("t"),star()); WindowSpecDefinition spec = new WindowSpecDefinition( Arrays.asList(new UnresolvedAttribute("a"), new UnresolvedAttribute("b")), Arrays.asList( new SortOrder( new UnresolvedAttribute("c"), new Ascending(), new NullsFirst() )), new SpecifiedWindowFrame(new RowFrame(),new UnaryMinus(Literal.build(new Integer(1))), Literal.build(new Integer(1)))); Map<String ,WindowSpecDefinition>ws1 = new HashMap<>(); ws1.put("w1" , spec); ws1.put("w2" , spec); ws1.put("w3" , spec); assertEqual( sql + " window w1 as (partition by a, b order by c rows between 1 preceding and 1 following), w2 as w1, w3 as w1" , new WithWindowDefinition(ws1, plan)); // Fail with no reference. intercept(sql+" window w2 as w1", "Cannot resolve window reference 'w1'"); // Fail when resolved reference is not a window spec. intercept( sql+" window w1 as (partition by a, b order by c rows between 1 preceding and 1 following), w2 as w1, w3 as w2", "Window reference 'w2' is not a window specification" ); } @Test public void testLateralView() { UnresolvedGenerator explode = new UnresolvedGenerator(new FunctionIdentifier("explode"), Arrays.asList(new UnresolvedAttribute("x"))); UnresolvedGenerator jsonTuple = new UnresolvedGenerator(new FunctionIdentifier("json_tuple"), Arrays.asList(new UnresolvedAttribute("x"), new UnresolvedAttribute("y"))); // Single lateral view assertEqual( "select * from t lateral view explode(x) expl as x", select(generate(table("t"), explode, new ArrayList<>(), false, "expl", Arrays.asList("x")), star())); // Multiple lateral views assertEqual( "select * from t lateral view explode(x) expl lateral view outer json_tuple(x, y) jtup q, z", select(generate(generate(table("t"), explode, new ArrayList<>(), false, "expl", new ArrayList<>()) , jsonTuple, new ArrayList<>(), true, "jtup", Arrays.asList("q", "z")), star())); // Multi-Insert lateral views. LogicalPlan from = generate(table("t1"), explode, new ArrayList<>(), false, "expl", Arrays.asList("x")); assertEqual( "from t1 lateral view explode(x) expl as x insert into t2 select * lateral view json_tuple(x, y) jtup q, z insert into t3 select * where s < 10", new Union( insertInto(select(generate(from, jsonTuple, new ArrayList<>(), false, "jtup", Arrays.asList("q", "z")), star()), "t2"), insertInto(select(where(from, new LessThan(new UnresolvedAttribute("s"), Literal.build(new Integer(10)))), star()), "t3")) ); // Unresolved generator. LogicalPlan expected = select(generate( table("t"), new UnresolvedGenerator(new FunctionIdentifier("posexplode"), Arrays.asList(new UnresolvedAttribute("x"))), new ArrayList<>(), false, "posexpl", Arrays.asList("x")),star()); assertEqual( "select * from t lateral view posexplode(x) posexpl as x, y", expected); intercept( "select * from t lateral view explode(x) expl pivot ( sum(x) FOR y IN ('a', 'b') )", "LATERAL cannot be used together with PIVOT in FROM clause"); } private void testUnconditionalJoin(String sql, JoinType jt) { assertEqual( "select * from t as tt " + sql + " u", select(join(as(table("t"), "tt"), table("u"), jt, null), star())); } private void testConditionalJoin(String sql, JoinType jt){ assertEqual( "select * from t "+sql+" u as uu on a = b", select(join(table("t"),as(table("u"),"uu"), jt, new EqualTo(new UnresolvedAttribute("a"),new UnresolvedAttribute("b"))),star())); } private void testNaturalJoin(String sql, JoinType jt){ assertEqual( "select * from t tt natural "+sql+" u as uu", select(join(as(table("t"),"tt"),as(table("u"),"uu"), new NaturalJoin(jt), null),star())); } private void testUsingJoin(String sql,JoinType jt) { assertEqual( "select * from t " + sql + " u using(a, b)", select(join(table("t"), table("u"), new UsingJoin(jt, Arrays.asList("a", "b")), null), star())); } private void test(String sql, JoinType jt, List<BiFunction<String,JoinType,Void>> tests){ for(BiFunction<String,JoinType,Void> test:tests){ test.apply(sql,jt); } } @Test public void testJoins() { List<BiFunction<String,JoinType,Void>> testAll = Arrays.asList( (s,j)->{testUnconditionalJoin(s,j);return (Void)null;}, (s,j)->{testConditionalJoin(s,j);return (Void)null;}, (s,j)->{testNaturalJoin(s,j);return (Void)null;}, (s,j)->{testUsingJoin(s,j);return (Void)null;} ); List<BiFunction<String,JoinType,Void>> testExistence = Arrays.asList( (s,j)->{testUnconditionalJoin(s,j);return (Void)null;}, (s,j)->{testConditionalJoin(s,j);return (Void)null;}, (s,j)->{testUsingJoin(s,j);return (Void)null;} ); test("cross join", new Cross(), Arrays.asList( (s,j)->{testUnconditionalJoin(s,j);return (Void)null;} ) ); test(",", new Inner(), Arrays.asList( (s,j)->{testUnconditionalJoin(s,j);return (Void)null;} ) ); test("join", new Inner(), testAll); test("inner join", new Inner(), testAll); test("left join", new LeftOuter(), testAll); test("left outer join", new LeftOuter(), testAll); test("right join", new RightOuter(), testAll); test("right outer join", new RightOuter(), testAll); test("full join", new FullOuter(), testAll); test("full outer join", new FullOuter(), testAll); test("left semi join", new LeftSemi(), testExistence); test("left anti join",new LeftAnti(), testExistence); test("anti join", new LeftAnti(), testExistence); // Test natural cross join intercept("select * from a natural cross join b"); // Test natural join with a condition intercept("select * from a natural join b on a.id = b.id"); // Test multiple consecutive joins assertEqual( "select * from a join b join c right join d", select(join(join(join(table("a"),table("b")),table("c")),table("d"), new RightOuter()),star())); // SPARK-17296 assertEqual( "select * from t1 cross join t2 join t3 on t3.id = t1.id join t4 on t4.id = t1.id", select(join(join(join(table("t1"),table("t2"), new Cross()), table("t3"), new Inner(), new EqualTo(new UnresolvedAttribute("t3.id"), new UnresolvedAttribute("t1.id"))), table("t4"), new Inner(), new EqualTo(new UnresolvedAttribute("t4.id"), new UnresolvedAttribute("t1.id"))) ,star())); // Test multiple on clauses. intercept("select * from t1 inner join t2 inner join t3 on col3 = col2 on col3 = col1"); // Parenthesis assertEqual( "select * from t1 inner join (t2 inner join t3 on col3 = col2) on col3 = col1", select(join(join(table("t1"),table("t2")), table("t3"), new Inner(), new EqualTo(new UnresolvedAttribute("col3"), new UnresolvedAttribute("col2"))) ,star())); assertEqual( "select * from t1 inner join (t2 inner join t3) on col3 = col2", select( join(table("t1"), join(table("t2"),table("t3"), new Inner(), null), new Inner(),new EqualTo(new UnresolvedAttribute("col3"), new UnresolvedAttribute("col2"))) ,star() )); assertEqual( "select * from t1 inner join (t2 inner join t3 on col3 = col2)", select( join(table("t1"), join(table("t2"),table("t3"), new Inner(), new EqualTo(new UnresolvedAttribute("col3"), new UnresolvedAttribute("col2"))), new Inner(), null), star())); // Implicit joins. assertEqual( "select * from t1, t3 join t2 on t1.col1 = t2.col2", select( join( join(table("t1"),table("t3")) ,table("t2"), new Inner(), new EqualTo(new UnresolvedAttribute("t1.col1"), new UnresolvedAttribute("t2.col2"))),star())); } @Test public void testSampledRelations() { String sql = "select * from t"; assertEqual(sql+" tablesample(100 rows)", select(limit(table("t"),Literal.build(new Integer(100))),star())); assertEqual(sql+" tablesample(43 percent) as x", select(new Sample(0.0, 0.43, false, 10L, as(table("t"),"x")),star())); assertEqual(sql+" tablesample(bucket 4 out of 10) as x", select(new Sample(0.0, 0.4,false, 10L,as(table("t"),"x")),star())); intercept(sql+" tablesample(bucket 4 out of 10 on x) as x", "TABLESAMPLE(BUCKET x OUT OF y ON colname) is not supported"); // intercept(sql+" tablesample(bucket 11 out of 10) as x", // "Sampling fraction (${11.0/10.0}) must be on interval [0, 1]"); intercept("SELECT * FROM parquet_t0 TABLESAMPLE(300M) s", "TABLESAMPLE(byteLengthLiteral) is not supported"); intercept("SELECT * FROM parquet_t0 TABLESAMPLE(BUCKET 3 OUT OF 32 ON rand()) s", "TABLESAMPLE(BUCKET x OUT OF y ON function) is not supported"); } @Test public void testSubQuery() { LogicalPlan plan = select(table("t0"),new UnresolvedAttribute("id")); assertEqual("select id from (t0)", plan); assertEqual("select id from ((((((t0))))))", plan); assertEqual( "(select * from t1) union distinct (select * from t2)", new Distinct(union(select(table("t1"),star()),select(table("t2"),star())))); assertEqual( "select * from ((select * from t1) union (select * from t2)) t", select(as(new Distinct( union(select(table("t1"),star()),select(table("t2"),star()))),"t"),star())); assertEqual( "select id from (((select id from t0) union all (select id from t0)) union all (select id from t0)) as u_1", select(as(union(union(plan,plan),plan),"u_1"), new UnresolvedAttribute("id"))); } @Test public void testScalarSubQuery() { assertEqual( "select (select max(b) from s) ss from t", select(table("t"),new Alias(new ScalarSubquery(select(table("s"),function("max",new UnresolvedAttribute("b")))),"ss"))); assertEqual( "select * from t where a = (select b from s)", select( where( table("t"), new EqualTo(new UnresolvedAttribute("a"),new ScalarSubquery(select(table("s"), new UnresolvedAttribute("b"))))),star())); assertEqual( "select g from t group by g having a > (select b from s)", where(groupBy(table("t"), Arrays.asList(new UnresolvedAttribute("g")), Arrays.asList(new UnresolvedAttribute("g"))), new GreaterThan(new UnresolvedAttribute("a"),new ScalarSubquery(select(table("s"),new UnresolvedAttribute("b")))))); } @Test public void testTableReference() { assertEqual("table t", table("t")); assertEqual("table d.t", table("d", "t")); } @Test public void testTableValuedFunction() { assertEqual( "select * from range(2)", select(new UnresolvedTableValuedFunction("range", Arrays.asList(Literal.build(new Integer(2))), new ArrayList<>()),star())); } @Test public void testRangeAsAlias(){ //("SPARK-20311 range(N) as alias") assertEqual( "SELECT * FROM range(10) AS t", select(new SubqueryAlias("t", new UnresolvedTableValuedFunction("range", Arrays.asList(Literal.build(new Integer(10))),new ArrayList<>())),star())); assertEqual( "SELECT * FROM range(7) AS t(a)", select(new SubqueryAlias("t", new UnresolvedTableValuedFunction("range", Arrays.asList(Literal.build(new Integer(7))),Arrays.asList("a"))),star())); } @Test public void testAliasInFrom(){//("SPARK-20841 Support table column aliases in FROM clause") { assertEqual( "SELECT * FROM testData AS t(col1, col2)", select(new UnresolvedSubqueryColumnAliases( Arrays.asList("col1", "col2"), new SubqueryAlias("t", new UnresolvedRelation(new TableIdentifier("testData"))) ),star())); } @Test public void testSubQueryInFrom(){// ("SPARK-20962 Support subquery column aliases in FROM clause") { assertEqual( "SELECT * FROM (SELECT a AS x, b AS y FROM t) t(col1, col2)", select(new UnresolvedSubqueryColumnAliases( Arrays.asList("col1", "col2"), new SubqueryAlias( "t", select( new UnresolvedRelation(new TableIdentifier("t")), new Alias(new UnresolvedAttribute("a"),"x"), new Alias(new UnresolvedAttribute("b"),"y"))) ),star())); } @Test public void testAliasForJoinRelation(){//("SPARK-20963 Support aliases for join relations in FROM clause") { LogicalPlan src1 = as(new UnresolvedRelation(new TableIdentifier("src1")),"s1"); LogicalPlan src2 = as(new UnresolvedRelation(new TableIdentifier("src2")),"s2"); assertEqual( "SELECT * FROM (src1 s1 INNER JOIN src2 s2 ON s1.id = s2.id) dst(a, b, c, d)", select(new UnresolvedSubqueryColumnAliases( Arrays.asList("a", "b", "c", "d"), new SubqueryAlias( "dst", join(src1,src2, new Inner(), new EqualTo(new UnresolvedAttribute("s1.id"), new UnresolvedAttribute("s2.id")))) ),star())); } @Test public void testInlineTable() { assertEqual("values 1, 2, 3, 4", new UnresolvedInlineTable( Arrays.asList("col1"), Arrays.asList( Arrays.asList(Literal.build(new Integer(1))), Arrays.asList(Literal.build(new Integer(2))), Arrays.asList(Literal.build(new Integer(3))), Arrays.asList(Literal.build(new Integer(4))) ))); assertEqual( "values (1, 'a'), (2, 'b') as tbl(a, b)", new SubqueryAlias("tbl", new UnresolvedInlineTable( Arrays.asList("a", "b"), Arrays.asList( Arrays.asList(Literal.build(new Integer(1)), Literal.build(new String("a"))), Arrays.asList(Literal.build(new Integer(2)), Literal.build(new String("b"))) )))); } @Test public void testUnEqual() {//("simple select query with !> and !<") { // !< is equivalent to >= assertEqual("select a, b from db.c where x !< 1", select( where(table("db", "c"), new GreaterThanOrEqual(new UnresolvedAttribute("x"), Literal.build(new Integer(1)))), new UnresolvedAttribute("a"), new UnresolvedAttribute("b"))); // !> is equivalent to <= assertEqual("select a, b from db.c where x !> 1", select(where(table("db", "c"), new LessThanOrEqual(new UnresolvedAttribute("x"), Literal.build(new Integer(1)))), new UnresolvedAttribute("a"), new UnresolvedAttribute("b"))); } @Test public void testHint() { intercept("SELECT /*+ HINT() */ * FROM t","mismatched input"); intercept("SELECT /*+ INDEX(a b c) */ * from default.t","mismatched input 'b' expecting"); intercept("SELECT /*+ INDEX(a b c) */ * from default.t","mismatched input 'b' expecting"); assertEqual( "SELECT /*+ BROADCASTJOIN(u) */ * FROM t", new UnresolvedHint("BROADCASTJOIN", Arrays.asList(new UnresolvedAttribute("u")), select(table("t"),star())) ); assertEqual( "SELECT /*+ MAPJOIN(u) */ * FROM t", new UnresolvedHint("MAPJOIN", Arrays.asList(new UnresolvedAttribute("u")), select(table("t"),star())) ); assertEqual( "SELECT /*+ STREAMTABLE(a,b,c) */ * FROM t", new UnresolvedHint("STREAMTABLE", Arrays.asList( new UnresolvedAttribute("a"), new UnresolvedAttribute("b"), new UnresolvedAttribute("c") ), select(table("t"),star())) ); assertEqual( "SELECT /*+ INDEX(t, emp_job_ix) */ * FROM t", new UnresolvedHint("INDEX", Arrays.asList( new UnresolvedAttribute("t"), new UnresolvedAttribute("emp_job_ix") ), select(table("t"),star())) ); assertEqual( "SELECT /*+ MAPJOIN(`default.t`) */ * from `default.t`", new UnresolvedHint("MAPJOIN", Arrays.asList( UnresolvedAttribute.quoted("default.t") ), select(table("default.t"),star())) ); assertEqual( "SELECT /*+ MAPJOIN(t) */ a from t where true group by a order by a", orderBy( new UnresolvedHint("MAPJOIN", Arrays.asList( new UnresolvedAttribute("t") ), groupBy( where(table("t"), Literal.build(new Boolean(true))), Arrays.asList(new UnresolvedAttribute("a")), Arrays.asList(new UnresolvedAttribute("a")))), new SortOrder(new UnresolvedAttribute("a"), new Ascending()))); assertEqual( "SELECT /*+ COALESCE(10) */ * FROM t", new UnresolvedHint("COALESCE", Arrays.asList( Literal.build(new Integer(10)) ), select(table("t"),star())) ); assertEqual( "SELECT /*+ REPARTITION(100) */ * FROM t", new UnresolvedHint("REPARTITION", Arrays.asList( Literal.build(new Integer(100)) ), select(table("t"),star())) ); assertEqual( "INSERT INTO s SELECT /*+ REPARTITION(100), COALESCE(500), COALESCE(10) */ * FROM t", new InsertIntoTable( table("s"), new HashMap<String,String>(), new UnresolvedHint("REPARTITION", Arrays.asList( Literal.build(new Integer(100))), new UnresolvedHint("COALESCE", Arrays.asList( Literal.build(new Integer(500))), new UnresolvedHint("COALESCE", Arrays.asList( Literal.build(new Integer(10))), select(table("t"),star()) ) )),false,false)); assertEqual( "SELECT /*+ BROADCASTJOIN(u), REPARTITION(100) */ * FROM t", new UnresolvedHint("BROADCASTJOIN", Arrays.asList( new UnresolvedAttribute("u")), new UnresolvedHint("REPARTITION", Arrays.asList( Literal.build(new Integer(100))), select(table("t"),star()) ))); intercept("SELECT /*+ COALESCE(30 + 50) */ * FROM t", "mismatched input"); } @Test public void testHintWithExpr() {//("SPARK-20854: select hint syntax with expressions") assertEqual( "SELECT /*+ HINT1(a, array(1, 2, 3)) */ * from t", new UnresolvedHint("HINT1", Arrays.asList( new UnresolvedAttribute("a"), new UnresolvedFunction("array", Arrays.asList( Literal.build(new Integer(1)), Literal.build(new Integer(2)), Literal.build(new Integer(3)) ), false) ), select(table("t"), star())) ); assertEqual( "SELECT /*+ HINT1(a, 5, 'a', b) */ * from t", new UnresolvedHint("HINT1", Arrays.asList( new UnresolvedAttribute("a"), Literal.build(new Integer(5)), Literal.build(new String("a")), new UnresolvedAttribute("b") ), select(table("t"), star())) ); assertEqual( "SELECT /*+ HINT1('a', (b, c), (1, 2)) */ * from t", new UnresolvedHint("HINT1", Arrays.asList( Literal.build(new String("a")), CreateStruct.build(Arrays.asList(new UnresolvedAttribute("b"), new UnresolvedAttribute("c"))), CreateStruct.build(Arrays.asList(Literal.build(new Integer(1)), Literal.build(new Integer(2)))) ), select(table("t"), star())) ); } @Test public void testMultipleHints() {//("SPARK-20854: multiple hints") assertEqual( "SELECT /*+ HINT1(a, 1) hint2(b, 2) */ * from t", new UnresolvedHint("HINT1", Arrays.asList( new UnresolvedAttribute("a"), Literal.build(new Integer(1)) ), new UnresolvedHint("hint2", Arrays.asList( new UnresolvedAttribute("b"), Literal.build(new Integer(2)) ), select(table("t"),star()) ) ) ); assertEqual( "SELECT /*+ HINT1(a, 1) */ /*+ hint2(b, 2) */ * from t", new UnresolvedHint("HINT1", Arrays.asList( new UnresolvedAttribute("a"), Literal.build(new Integer(1)) ), new UnresolvedHint("hint2", Arrays.asList( new UnresolvedAttribute("b"), Literal.build(new Integer(2)) ), select(table("t"),star()) ) ) ); assertEqual( "SELECT /*+ HINT1(a, 1), hint2(b, 2) */ /*+ hint3(c, 3) */ * from t", new UnresolvedHint("HINT1", Arrays.asList( new UnresolvedAttribute("a"), Literal.build(new Integer(1)) ), new UnresolvedHint("hint2", Arrays.asList( new UnresolvedAttribute("b"), Literal.build(new Integer(2)) ), new UnresolvedHint("hint3", Arrays.asList( new UnresolvedAttribute("c"), Literal.build(new Integer(3)) ), select(table("t"),star()) ) ) ) ); } @Test public void TestTrim(){ intercept("select ltrim(both 'S' from 'SS abc S'", "missing ')' at '<EOF>'"); intercept("select rtrim(trailing 'S' from 'SS abc S'", "missing ')' at '<EOF>'"); assertEqual( "SELECT TRIM(BOTH '@$%&( )abc' FROM '@ $ % & ()abc ' )", select(new OneRowRelation(), new UnresolvedFunction("TRIM", Arrays.asList( Literal.build(new String("@$%&( )abc")), Literal.build(new String("@ $ % & ()abc ")) ),false ))); assertEqual( "SELECT TRIM(LEADING 'c []' FROM '[ ccccbcc ')", select(new OneRowRelation(), new UnresolvedFunction("ltrim", Arrays.asList( Literal.build(new String("c []")), Literal.build(new String("[ ccccbcc ")) ),false ))); assertEqual( "SELECT TRIM(TRAILING 'c&^,.' FROM 'bc...,,,&&&ccc')", select(new OneRowRelation(), new UnresolvedFunction("rtrim", Arrays.asList( Literal.build(new String("c&^,.")), Literal.build(new String("bc...,,,&&&ccc")) ) ,false ))); } @Test public void testPrecedenceOfSetOperations(){ LogicalPlan a = select(table("a"),star()); LogicalPlan b = select(table("b"),star()); LogicalPlan c = select(table("c"),star()); LogicalPlan d = select(table("d"),star()); String query1 =" SELECT * FROM a UNION SELECT * FROM b EXCEPT SELECT * FROM c INTERSECT SELECT * FROM d"; String query2 ="SELECT * FROM a UNION SELECT * FROM b EXCEPT ALL SELECT * FROM c INTERSECT ALL SELECT * FROM d"; assertEqual(query1, except( new Distinct(union(a,b)), intersect(c,d,false),false)); assertEqual(query2, except(new Distinct(union(a,b)), intersect(c,d, true), true)); //skip // // Now disable precedence enforcement to verify the old behaviour. // withSQLConf(SQLConf.LEGACY_SETOPS_PRECEDENCE_ENABLED.key -> "true") { // assertEqual(query1, // Distinct(a.union(b)).except(c, isAll = false).intersect(d, isAll = false)) // assertEqual(query2, Distinct(a.union(b)).except(c, isAll = true).intersect(d, isAll = true)) // } // // // Explicitly enable the precedence enforcement // withSQLConf(SQLConf.LEGACY_SETOPS_PRECEDENCE_ENABLED.key -> "false") { // assertEqual(query1, // Distinct(a.union(b)).except(c.intersect(d, isAll = false), isAll = false)) // assertEqual(query2, Distinct(a.union(b)).except(c.intersect(d, isAll = true), isAll = true)) // } } }
true
2cda0df4f0e5912835be476f7497af526aa9165c
Java
Heo0916/JAVA
/Chap09_UtilClass/src/Object/Student.java
UTF-8
682
3.390625
3
[]
no_license
package Object; /* * toString() 메서드 재정의 * - Object 클래스에서 상속해 준 메서드 원형을 * 유용한 정보가 리턴되도록 재정의한다. * - 클래스의 값을 가지고 있는데 값이 올바르게 담겼는지 * 확인할 때 toStirng() 메서드를 오버라이드를 통해서 * 값을 뽑아 낼 수 있다. */ public class Student { int hakbun; // 학생 학번 String name; // 학생 이름 public Student() { } public Student(int hakbun, String name) { this.hakbun = hakbun; this.name = name; } @Override public String toString() { return "학번 : " + hakbun + ", 이름 : " + name; } }
true
01718272f4582db84ba3a7177e7e0af878e08d00
Java
vvvladzagNine/BuySupply
/src/main/java/ru/zagshak/buySupply/util/UserUtil.java
UTF-8
869
2.265625
2
[]
no_license
package ru.zagshak.buySupply.util; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.util.StringUtils; import ru.zagshak.buySupply.domain.User; import ru.zagshak.buySupply.domain.to.UserTO.CurrentUserTO; public class UserUtil { public static User updateFromTo(User user, CurrentUserTO userTo) { user.setName(userTo.getName()); user.setEmail(userTo.getEmail().toLowerCase()); user.setPassword(userTo.getPassword()); user.setCity(userTo.getCity()); return user; } public static User prepareToSave(User user, PasswordEncoder passwordEncoder) { String password = user.getPassword(); user.setPassword(StringUtils.hasText(password) ? passwordEncoder.encode(password) : password); user.setEmail(user.getEmail().toLowerCase()); return user; } }
true
8edf627daa19e4ef7914b5b6c24a25a68e0b5b4c
Java
murbans1/location-reminder
/src/pl/mu/LocationSelectionActivity.java
UTF-8
3,465
2.171875
2
[]
no_license
package pl.mu; import java.util.List; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; public class LocationSelectionActivity extends MapActivity { private MapView mapView; private MapController mapController; private LocationManager locationManager; private LocationListener locationListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapController = mapView.getController(); mapController.setZoom(10); locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); locationListener = new MyLocationListener(); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); // GeoPoint initGeoPoint = new GeoPoint((int) (locationManager // .getLastKnownLocation(LocationManager.GPS_PROVIDER) // .getLatitude() * 1000000), (int) (locationManager // .getLastKnownLocation(LocationManager.GPS_PROVIDER) // .getLongitude() * 1000000)); // // mapController.animateTo(initGeoPoint); LocationMapOverlay mapOverlay = new LocationMapOverlay(); List<Overlay> listOfOverlays = mapView.getOverlays(); listOfOverlays.clear(); listOfOverlays.add(mapOverlay); mapView.invalidate(); } @Override protected boolean isRouteDisplayed() { return false; } public void sendResult(double lat, double lon) { Intent intent = new Intent(); intent.putExtra("lat", String.valueOf(lat)); intent.putExtra("lon", String.valueOf(lon)); if (getParent() == null) { setResult(007, intent); } else { getParent().setResult(007, intent); } finish(); } private class MyLocationListener implements LocationListener { public void onLocationChanged(Location argLocation) { // TODO Auto-generated method stub GeoPoint myGeoPoint = new GeoPoint( (int) (argLocation.getLatitude() * 1000000), (int) (argLocation.getLongitude() * 1000000)); mapController.animateTo(myGeoPoint); } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } public class LocationMapOverlay extends Overlay { @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { // TODO Auto-generated method stub return super.draw(canvas, mapView, shadow, when); } @Override public boolean onTap(GeoPoint point, MapView mapView) { Toast.makeText( mapView.getContext(), "Location: " + point.getLatitudeE6() / 1E6 + "," + point.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT) .show(); double lat = point.getLatitudeE6() / 1E6; double lon = point.getLongitudeE6() / 1E6; sendResult(lat, lon); return false; } } }
true
5279bf01590048297c23428d2f65f0785d5a3cfb
Java
hamzakhalem/IANNUAIRE
/NumTel.java
ISO-8859-1
2,401
3.359375
3
[]
no_license
public class NumTel { public static final char FIXE_PROF = 'T'; public static final char FIXE_DOM = 'D'; public static final char PORTABLE = 'P'; public static final char FAX = 'F'; public static final char INCONNU = '?'; // ---------------------------------------------- // attributs (variables de classes) // ---------------------------------------------- private int numero; private char type; // ---------------------------------------------- // Constructeurs // ---------------------------------------------- /** * cre un numro de tlphone d'un type donn. * * @param num * le numro de tlphone * @param type * son type (si ce type n'est pas 'T','D','P' ou 'F', la valeur * INCONNU ('?') sera associe ce numro). */ public NumTel(int num, char type) { this.numero = num; setType(type); } /** * cre un numro de tlphone de type inconnu * * @param num * le numro de tlphone */ public NumTel(int num) { this(num, INCONNU); } // ---------------------------------------------- // mthodes // ---------------------------------------------- // ---- accesseurs -------------------------------------- /** * retourne le numro de tlphone * * @return le numro. */ public int getNumero() { return numero; } /** * retourne le type de ce numro de tlphone * * @return le type. */ public char getType() { return type; } // ---- modifieurs -------------------------------------- /** * change le type de ce numro de tlphone * * @param type * le nouveau type pour ce numro. (si ce type n'est pas * 'T','D','P' ou 'F', la valeur INCONNU ('?') sera associe ce * numro). */ public void setType(char type) { switch (type) { case FIXE_PROF: case FIXE_DOM: case PORTABLE: case FAX: this.type = type; break; default: this.type = INCONNU; } } public String toString() { return numero + " (" + type + ")"; } public boolean equals(Object o) { if (!(o instanceof NumTel)) return false; NumTel num = (NumTel) o; return this.numero == num.numero; } public int hashCode() { return numero; } }// NumTel
true
5a65483020bcd4c55cbb056f6e36edc4de6399e9
Java
mrinal10/starter
/StarterPreperation/src/main/java/com/prep/tree/IsBST.java
UTF-8
409
3.1875
3
[]
no_license
package com.prep.tree; public class IsBST { boolean checkBST(Node root) { return isBSTree(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } boolean isBSTree(Node root, int min, int max) { if (root == null) { return true; } if (root.data > max || root.data < min) { return false; } return (isBSTree(root.left, min, root.data) && isBSTree(root.right, root.data, max)); } }
true
92312577983852d6ae05b8872e68777b77f59e3d
Java
sdgdsffdsfff/storm-examples
/twitter-topics/src/main/java/twitter/topics/dataStreams/dominio/Topic.java
UTF-8
530
2.421875
2
[]
no_license
package twitter.topics.dataStreams.dominio; public class Topic { private String hashtag; private String frecuency; public Topic() { // } public Topic(String hashtag, String frecuency) { super(); this.hashtag = hashtag; this.frecuency = frecuency; } public String getHashtag() { return hashtag; } public void setHashtag(String hashtag) { this.hashtag = hashtag; } public String getFrecuency() { return frecuency; } public void setFrecuency(String frecuency) { this.frecuency = frecuency; } }
true
1326cdc31b219b099beaffe8071d93f7c5de419d
Java
hyperskill/hs-test
/src/main/java/org/hyperskill/hstest/testing/expect/json/JsonChecker.java
UTF-8
6,194
2.328125
2
[]
no_license
package org.hyperskill.hstest.testing.expect.json; import org.hyperskill.hstest.testing.expect.base.checker.BooleanChecker; import org.hyperskill.hstest.testing.expect.base.checker.DoubleChecker; import org.hyperskill.hstest.testing.expect.base.checker.IntegerChecker; import org.hyperskill.hstest.testing.expect.base.checker.NumberChecker; import org.hyperskill.hstest.testing.expect.base.checker.StringChecker; import org.hyperskill.hstest.testing.expect.json.builder.JsonAnyBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonArrayBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonBaseBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonBooleanBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonDoubleBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonFinishedArrayBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonFinishedObjectBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonIntegerBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonNullBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonNumberBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonObjectBuilder; import org.hyperskill.hstest.testing.expect.json.builder.JsonStringBuilder; import java.util.regex.Pattern; public final class JsonChecker { private JsonChecker() { } public static JsonAnyBuilder any() { return new JsonAnyBuilder(); } public static JsonObjectBuilder isObject() { return new JsonObjectBuilder(); } public static JsonFinishedObjectBuilder isObject(JsonAnyBuilder unused) { return isObject().anyOtherValues(); } public static JsonArrayBuilder isArray() { return new JsonArrayBuilder(); } public static JsonArrayBuilder isArray(int length) { return isArray().length(length); } public static JsonArrayBuilder isArray(IntegerChecker lengthChecker) { return isArray().length(lengthChecker); } public static JsonArrayBuilder isArray(JsonBaseBuilder itemsTemplate) { return isArray().everyItem(itemsTemplate); } public static JsonArrayBuilder isArray(int length, JsonBaseBuilder itemsTemplate) { return isArray().length(length).everyItem(itemsTemplate); } public static JsonArrayBuilder isArray(IntegerChecker lengthChecker, JsonBaseBuilder itemsTemplate) { return isArray().length(lengthChecker).everyItem(itemsTemplate); } public static JsonFinishedArrayBuilder isArray(int... values) { return isArray().length(values.length).items(values); } public static JsonFinishedArrayBuilder isArray(double... values) { return isArray().length(values.length).items(values); } public static JsonFinishedArrayBuilder isArray(boolean... values) { return isArray().length(values.length).items(values); } public static JsonFinishedArrayBuilder isArray(String... values) { return isArray().length(values.length).items(values); } public static JsonStringBuilder isString() { return isString(v -> true); } public static JsonStringBuilder isString(String value) { return isString(v -> v.equals(value), "should equal to \"" + value + "\""); } public static JsonStringBuilder isString(Pattern regex) { return isString(regex, "should match pattern \"" + regex + "\""); } public static JsonStringBuilder isString(Pattern regex, String failFeedback) { return isString(v -> regex.matcher(v).matches(), failFeedback); } public static JsonStringBuilder isString(StringChecker checker) { return isString(checker, "is incorrect"); } public static JsonStringBuilder isString(StringChecker checker, String failFeedback) { return new JsonStringBuilder(checker, failFeedback); } public static JsonNumberBuilder isNumber() { return isNumber(v -> true); } public static JsonIntegerBuilder isNumber(int value) { return isInteger(value); } public static JsonDoubleBuilder isNumber(double value) { return isDouble(value); } public static JsonNumberBuilder isNumber(NumberChecker checker) { return isNumber(checker, "is incorrect"); } public static JsonNumberBuilder isNumber(NumberChecker checker, String failFeedback) { return new JsonNumberBuilder(checker, failFeedback); } public static JsonIntegerBuilder isInteger() { return isInteger(v -> true); } public static JsonIntegerBuilder isInteger(int value) { return isInteger(v -> v == value, "should equal to " + value); } public static JsonIntegerBuilder isInteger(IntegerChecker checker) { return isInteger(checker, "is incorrect"); } public static JsonIntegerBuilder isInteger(IntegerChecker checker, String failFeedback) { return new JsonIntegerBuilder(checker, failFeedback); } public static JsonDoubleBuilder isDouble() { return isDouble(v -> true); } public static JsonDoubleBuilder isDouble(double value) { return isDouble(v -> v - value < 1e-6, "should equal to " + value); } public static JsonDoubleBuilder isDouble(DoubleChecker checker) { return isDouble(checker, "is incorrect"); } public static JsonDoubleBuilder isDouble(DoubleChecker checker, String failFeedback) { return new JsonDoubleBuilder(checker, failFeedback); } public static JsonBooleanBuilder isBoolean() { return isBoolean(v -> true); } public static JsonBooleanBuilder isBoolean(boolean value) { return isBoolean(v -> v == value, "should equal to " + value); } public static JsonBooleanBuilder isBoolean(BooleanChecker checker) { return isBoolean(checker, "is incorrect"); } public static JsonBooleanBuilder isBoolean(BooleanChecker checker, String failFeedback) { return new JsonBooleanBuilder(checker, failFeedback); } public static JsonNullBuilder isNull() { return new JsonNullBuilder(); } }
true
7d633f9ba35ed85382cf4b5e65b067a8a77ea989
Java
bellmit/RAP_android
/app/src/main/java/net/example/paul/rapapp/widget/adapter/NewsAdapter.java
UTF-8
2,719
2.171875
2
[]
no_license
package net.example.paul.rapapp.widget.adapter; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import net.example.paul.rapapp.R; import net.example.paul.rapapp.domain.NewsInfo; import net.example.paul.rapapp.model.interfaces.GetImageCallbackByByte; import net.example.paul.rapapp.utils.OKManager; import java.util.List; import okhttp3.OkHttpClient; /** * Created by 牛谱乐 * Timer 2017/1/4 12:21 * E-mail niupuyue@togogo.net */ public class NewsAdapter extends BaseAdapter { private List<NewsInfo> newsInfos; private Activity activity; private OkHttpClient client; private OKManager manager; public NewsAdapter(List<NewsInfo> newsInfos, Activity activity) { this.newsInfos = newsInfos; this.activity = activity; } @Override public int getCount() { return newsInfos.size(); } @Override public Object getItem(int position) { return newsInfos.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final Item item = new Item(); convertView = activity.getLayoutInflater().inflate(R.layout.item_news_listview, null); item.imageView = (ImageView) convertView.findViewById(R.id.news_listview_img); item.title = (TextView) convertView.findViewById(R.id.news_listview_title); item.content = (TextView) convertView.findViewById(R.id.news_listview_content); item.time = (TextView) convertView.findViewById(R.id.news_listview_time); convertView.setTag(item); item.title.setText(newsInfos.get(position).getTitle()); item.content.setText(newsInfos.get(position).getAuthor_name()); item.time.setText(newsInfos.get(position).getDate()); convertView.setTag(newsInfos.get(position)); /** * 根据图片地址请求网络 */ String img_path = newsInfos.get(position).getThumbnail_pic_s(); manager = OKManager.getInstance(); manager.asyncGetByteByURL(img_path, new GetImageCallbackByByte() { @Override public void onResponse(byte[] result) { Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length); item.imageView.setImageBitmap(bitmap); } }); return convertView; } class Item { ImageView imageView; TextView title, content, time; } }
true
7b2962af05ff34ff7220a82ad1c757478b498577
Java
luansousa26/java8-default-crud-application
/src/main/java/com/luan/java8defaultcrudapplication/domain/User.java
UTF-8
1,550
2.4375
2
[]
no_license
package com.luan.java8defaultcrudapplication.domain; import java.io.Serializable; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "TB_USER") @SequenceGenerator(name = "sequency", initialValue = 1, allocationSize = 100) public class User implements Serializable { private static final long serialVersionUID = 1L; @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequency") @Id private Long id; @Column(name = "USER_NAME", nullable = false) private String name; @Column(name = "USER_JOB", nullable = false) private String job; @Column(name = "USER_AGE", nullable = false) private int age; @Column(name = "ALTER_DATE", nullable = false) private LocalDate alterationDate; public void setId(Long id) { this.id = id; } public Long getId() { return this.id; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setJob(String job) { this.job = job; } public String getJob() { return this.job; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public LocalDate getAlterationDate() { return this.alterationDate; } public void setAlterationDate(LocalDate alterationDate) { this.alterationDate = alterationDate; } }
true
e7fbb40348e9bd97d9dbe6157d817b454d4ab563
Java
imLance/Perfect
/app/src/main/java/com/lance/perfect/view/fragment/WXCircleVideoFragment.java
UTF-8
8,361
1.945313
2
[]
no_license
package com.lance.perfect.view.fragment; import android.content.res.AssetFileDescriptor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import com.lance.perfect.R; import com.lance.perfect.model.LocalWXVideoEntity; import com.lance.perfect.model.OnlineWXVideoEntity; import com.lance.perfect.model.WXVideoEntity; import com.lance.perfect.view.activity.base.BaseActivity; import com.lance.perfect.view.adapter.WXVideoAdapter; import com.volokh.danylo.video_player_manager.manager.PlayerItemChangeListener; import com.volokh.danylo.video_player_manager.manager.SingleVideoPlayerManager; import com.volokh.danylo.video_player_manager.manager.VideoPlayerManager; import com.volokh.danylo.video_player_manager.meta.MetaData; import com.volokh.danylo.visibility_utils.calculator.DefaultSingleItemCalculatorCallback; import com.volokh.danylo.visibility_utils.calculator.ListItemsVisibilityCalculator; import com.volokh.danylo.visibility_utils.calculator.SingleListViewItemActiveCalculator; import com.volokh.danylo.visibility_utils.scroll_utils.ItemsPositionGetter; import com.volokh.danylo.visibility_utils.scroll_utils.RecyclerViewItemPositionGetter; import java.io.IOException; import java.util.ArrayList; /** * 作用: 微信视频列表 * 作者: 张甲彪 * 时间: 2016/5/27. */ public class WXCircleVideoFragment extends Fragment{ private View mBaseView; private RecyclerView mRecyclerView; private BaseActivity mContext; public static final String VIDEO_TYPE_ARG = "me.chunyu.spike.video_list_fragment.video_type_arg"; // 网络视频地址 private static final String URL = "http://dn-chunyu.qbox.me/fwb/static/images/home/video/video_aboutCY_A.mp4"; // 本地资源文件名 private static final String[] LOCAL_NAMES = new String[]{ "chunyu-local-1.mp4", "chunyu-local-2.mp4", "chunyu-local-3.mp4", "chunyu-local-4.mp4" }; // 在线资源名 private static final String ONLINE_NAME = "chunyu-online"; private final ArrayList<WXVideoEntity> mList; // 视频项的列表 private final ListItemsVisibilityCalculator mVisibilityCalculator; // 可视估计器 private final VideoPlayerManager<MetaData> mVideoPlayerManager; private LinearLayoutManager mLayoutManager; // 布局管理器 private ItemsPositionGetter mItemsPositionGetter; // 位置提取器 private int mScrollState; // 滑动状态 // 创建实例, 添加类型 public static WXCircleVideoFragment newInstance(int type) { WXCircleVideoFragment simpleFragment = new WXCircleVideoFragment(); Bundle args = new Bundle(); args.putInt(VIDEO_TYPE_ARG, type); simpleFragment.setArguments(args); return simpleFragment; } public WXCircleVideoFragment(){ mList = new ArrayList<>(); mVisibilityCalculator = new SingleListViewItemActiveCalculator( new DefaultSingleItemCalculatorCallback(), mList); mVideoPlayerManager = new SingleVideoPlayerManager(new PlayerItemChangeListener() { @Override public void onPlayerItemChanged(MetaData metaData) { } }); mScrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE; // 暂停滚动状态 } public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mContext= (BaseActivity) getContext(); mBaseView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_wxcircle_video, container, false); initViews(); initData(); return mBaseView; } public void onResume() { super.onResume(); if (!mList.isEmpty()) { mRecyclerView.post(new Runnable() { @Override public void run() { // 判断一些滚动状态 mVisibilityCalculator.onScrollStateIdle( mItemsPositionGetter, mLayoutManager.findFirstVisibleItemPosition(), mLayoutManager.findLastVisibleItemPosition()); } }); } } @Override public void onStop() { super.onStop(); mVideoPlayerManager.resetMediaPlayer(); // 页面不显示时, 释放播放器 } private void initViews() { mRecyclerView= (RecyclerView) mBaseView.findViewById(R.id.mRecyclerView); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLayoutManager); } private void initData() { mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[0], R.drawable.cover, getFile(LOCAL_NAMES[0]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[1], R.drawable.cover, getFile(LOCAL_NAMES[1]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[2], R.drawable.cover, getFile(LOCAL_NAMES[2]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[3], R.drawable.cover, getFile(LOCAL_NAMES[3]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[0], R.drawable.cover, getFile(LOCAL_NAMES[0]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[1], R.drawable.cover, getFile(LOCAL_NAMES[1]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[2], R.drawable.cover, getFile(LOCAL_NAMES[2]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[3], R.drawable.cover, getFile(LOCAL_NAMES[3]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[0], R.drawable.cover, getFile(LOCAL_NAMES[0]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[1], R.drawable.cover, getFile(LOCAL_NAMES[1]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[2], R.drawable.cover, getFile(LOCAL_NAMES[2]))); mList.add(new LocalWXVideoEntity(mVideoPlayerManager, LOCAL_NAMES[3], R.drawable.cover, getFile(LOCAL_NAMES[3]))); final int count = 10; for (int i = 0; i < count; ++i) { mList.add(new OnlineWXVideoEntity(mVideoPlayerManager, ONLINE_NAME, R.drawable.cover, URL)); } WXVideoAdapter mAdapter=new WXVideoAdapter(mList,mContext); mRecyclerView.setAdapter(mAdapter); // 获取Item的位置 mItemsPositionGetter = new RecyclerViewItemPositionGetter(mLayoutManager, mRecyclerView); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) { mScrollState = scrollState; if (scrollState == RecyclerView.SCROLL_STATE_IDLE && !mList.isEmpty()) { mVisibilityCalculator.onScrollStateIdle( mItemsPositionGetter, mLayoutManager.findFirstVisibleItemPosition(), mLayoutManager.findLastVisibleItemPosition()); } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (!mList.isEmpty()) { mVisibilityCalculator.onScroll( mItemsPositionGetter, mLayoutManager.findFirstVisibleItemPosition(), mLayoutManager.findLastVisibleItemPosition() - mLayoutManager.findFirstVisibleItemPosition() + 1, mScrollState); } } }); } // 获取资源文件 private AssetFileDescriptor getFile(String name) { try { return mContext.getAssets().openFd(name); } catch (IOException e) { e.printStackTrace(); return null; } } }
true
dfd12f92dca05b483bf911456a7986c1b8f87686
Java
AmazingJoeZeng/DB_Practice
/Ward_management_system/src/DBConnection/Login_Patient.java
UTF-8
913
2.546875
3
[]
no_license
package DBConnection; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; public class Login_Patient { public void Login(String name,String sex,int age,String doctor,String bing,String department,int roomnum,int bednum) { Connection conn =null; CallableStatement st; try { conn=Conn.getconn(); st = conn.prepareCall("{CALL LOGIN_PATIENT(?,?,?,?,?,?,?,?)}"); st.setString(1,name); //姓名 st.setString(2, sex); //性别 st.setInt(3, age); //年龄 st.setString(4,doctor); //医生 st.setString(5,bing); //诊断 st.setString(6,department); //科室 st.setInt(7, roomnum); //病房号 st.setInt(8, bednum); //病床号 st.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Login Fail!"); } } }
true
456395065214ab2bed6de30e2546ee5300cba5e6
Java
Renan3M/Pizza-Delivery_android
/app/src/main/java/com/infnet/ads/projetodebloco/DataBase/PizzaDAO.java
UTF-8
3,778
2.609375
3
[]
no_license
package com.infnet.ads.projetodebloco.DataBase; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.infnet.ads.projetodebloco.Entity.Client; import com.infnet.ads.projetodebloco.Products.Product; public class PizzaDAO { // Only this class should have access to the pizza database private final String TABLE_PIZZA = "pizza_table"; private final String TABLE_CLIENT = "client_table"; private DBGateway gw; private Cursor cursor; public PizzaDAO(Context ctx){ gw = DBGateway.getInstance(ctx); } public long save(Product pizzaInstance){ ContentValues cv = new ContentValues(); cv.put("name", pizzaInstance.getName()); cv.put("price", pizzaInstance.getPrice()); cv.put("description", pizzaInstance.getDescription()); cv.put("category", pizzaInstance.getProductType()); cv.put("subCategory", pizzaInstance.getProductSubType()); return gw.getDatabase().insert(TABLE_PIZZA,null,cv); } public long save(Client clientInstance){ ContentValues cv = new ContentValues(); cv.put("name", clientInstance.getUserName()); cv.put("email", clientInstance.getEmail()); cv.put("street", clientInstance.getStreet()); cv.put("city", clientInstance.getCity()); cv.put("uf", clientInstance.getUf()); cv.put("phone", clientInstance.getPhone()); cv.put("password", clientInstance.getPassword()); return gw.getDatabase().insert(TABLE_CLIENT,null,cv); // The class which calls this method must store the returned value in the object ID (by using its own setId method) } public Cursor getPizzaCursor(){ cursor = gw.getDatabase().rawQuery("SELECT * FROM pizza_table", null); cursor.moveToFirst(); return cursor; } public Cursor getClientCursor(){ cursor = gw.getDatabase().rawQuery("SELECT * FROM client_table", null); cursor.moveToFirst(); return cursor; } public Integer remove(Product pizzaInstance){ Integer id = gw.getDatabase().delete(TABLE_PIZZA,"id=?", new String[]{pizzaInstance.getId()}); ContentValues cv = new ContentValues(); // Works but still not perfect cv.put("seq", 0); gw.getDatabase().update("sqlite_sequence",cv,"name=?",new String[]{TABLE_PIZZA}); return id; } public Integer remove(Client clientInstance){ Integer id = gw.getDatabase().delete(TABLE_CLIENT,"id=?", new String[]{String.valueOf(clientInstance.getClientID())}); return id; } public int update(Product pizzaInstance, String id){ ContentValues cv = new ContentValues(); cv.put("name", pizzaInstance.getName()); cv.put("price", pizzaInstance.getPrice()); cv.put("description", pizzaInstance.getDescription()); cv.put("category", pizzaInstance.getProductType()); cv.put("subCategory", pizzaInstance.getProductSubType()); return gw.getDatabase().update(TABLE_PIZZA,cv,"id=?",new String[]{id}); } public int update(Client clientInstance){ ContentValues cv = new ContentValues(); cv.put("name", clientInstance.getUserName()); cv.put("email", clientInstance.getEmail()); cv.put("street", clientInstance.getStreet()); cv.put("city", clientInstance.getCity()); cv.put("uf", clientInstance.getUf()); cv.put("phone", clientInstance.getPhone()); cv.put("password", clientInstance.getPassword()); return gw.getDatabase().update(TABLE_CLIENT,cv,"id=?",new String[]{String.valueOf(clientInstance.getClientID())}); } public void destroyTable(){ // Implement latter } }
true
649b6a77b1c86350e9090a3fd70267827775e505
Java
enterpriseih/jvm_lecture-1
/src/main/java/com/shengsiyuan/jvm/reference/MyTest1.java
UTF-8
1,130
3.625
4
[]
no_license
package com.shengsiyuan.jvm.reference; import java.lang.ref.SoftReference; import java.util.Date; /** * Reference实例的4中状态 Active Pending Enqueued Inactive * Active:新创建的引用实例都会处于Active状态 * Pending:未被注册到引用队列中的引用对象不可能处于该状态 * Enqueued:未被注册到引用队列中的引用对象不可能处于该状态 * Inactive:无法对该状态的引用对象执行任何操作,处于该状态下的对象状态不会再发生任何变化 */ public class MyTest1 { public static void main(String[] args) { Date date = new Date(); SoftReference<Date> reference = new SoftReference<>(date); Date date1 = reference.get(); //软引用指向的对象有可能被回收,需要非空判断 if(null != date1){ System.out.println("hello"); }else{ System.out.println("world"); } System.out.println("======"); reference.clear();//清理后再获取对象就为空 Date date2 = reference.get(); System.out.println(date2); } }
true
51739e2498e93b1cdcc5dfb88fe3414d0e4b549d
Java
bezda/xync
/src/test/java/net/kuujo/xync/MapTest.java
UTF-8
16,794
1.992188
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 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 net.kuujo.xync; import static org.vertx.testtools.VertxAssert.assertEquals; import static org.vertx.testtools.VertxAssert.assertNotNull; import static org.vertx.testtools.VertxAssert.assertNull; import static org.vertx.testtools.VertxAssert.assertTrue; import static org.vertx.testtools.VertxAssert.testComplete; import net.kuujo.xync.util.Cluster; import org.junit.Test; import org.vertx.java.core.AsyncResult; import org.vertx.java.core.Handler; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.json.JsonObject; import org.vertx.testtools.TestVerticle; /** * Map data tests. * * @author Jordan Halterman */ public class MapTest extends TestVerticle { @Test public void testMapPut() { Cluster.initialize(); container.deployWorkerVerticle(Xync.class.getName(), new JsonObject().putString("cluster", "test"), 3, false, new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { assertTrue(result.succeeded()); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-put") .putString("action", "put") .putString("key", "foo") .putString("value", "bar"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); testComplete(); } }); } }); } @Test public void testMapPutPut() { Cluster.initialize(); container.deployWorkerVerticle(Xync.class.getName(), new JsonObject().putString("cluster", "test"), 3, false, new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { assertTrue(result.succeeded()); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-put-put") .putString("action", "put") .putString("key", "foo") .putString("value", "bar"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-put-put") .putString("action", "put") .putString("key", "foo") .putString("value", "baz"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNotNull(result.result().body().getString("result")); assertEquals("bar", result.result().body().getString("result")); testComplete(); } }); } }); } }); } @Test public void testMapGet() { Cluster.initialize(); container.deployWorkerVerticle(Xync.class.getName(), new JsonObject().putString("cluster", "test"), 3, false, new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { assertTrue(result.succeeded()); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-get") .putString("action", "put") .putString("key", "foo") .putString("value", "bar"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-get") .putString("action", "get") .putString("key", "foo"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNotNull(result.result().body().getString("result")); assertEquals("bar", result.result().body().getString("result")); testComplete(); } }); } }); } }); } @Test public void testMapRemove() { Cluster.initialize(); container.deployWorkerVerticle(Xync.class.getName(), new JsonObject().putString("cluster", "test"), 3, false, new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { assertTrue(result.succeeded()); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-remove") .putString("action", "put") .putString("key", "foo") .putString("value", "bar"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-remove") .putString("action", "remove") .putString("key", "foo"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNotNull(result.result().body().getString("result")); assertEquals("bar", result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-remove") .putString("action", "get") .putString("key", "foo"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); testComplete(); } }); } }); } }); } }); } @Test public void testMapSize() { Cluster.initialize(); container.deployWorkerVerticle(Xync.class.getName(), new JsonObject().putString("cluster", "test"), 3, false, new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { assertTrue(result.succeeded()); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-size") .putString("action", "put") .putString("key", "foo") .putString("value", "bar"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-size") .putString("action", "put") .putString("key", "bar") .putString("value", "baz"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-size") .putString("action", "put") .putString("key", "baz") .putString("value", "foo"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-size") .putString("action", "size"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertTrue(result.result().body().getInteger("result") == 3); testComplete(); } }); } }); } }); } }); } }); } @Test public void testMapClear() { Cluster.initialize(); container.deployWorkerVerticle(Xync.class.getName(), new JsonObject().putString("cluster", "test"), 3, false, new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { assertTrue(result.succeeded()); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-clear") .putString("action", "put") .putString("key", "foo") .putString("value", "bar"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-clear") .putString("action", "put") .putString("key", "bar") .putString("value", "baz"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-clear") .putString("action", "put") .putString("key", "baz") .putString("value", "foo"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-clear") .putString("action", "size"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertTrue(result.result().body().getInteger("result") == 3); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-clear") .putString("action", "clear"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertNull(result.result().body().getString("result")); JsonObject message = new JsonObject() .putString("type", "map") .putString("name", "test-map-clear") .putString("action", "size"); vertx.eventBus().sendWithTimeout("test", message, 5000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { assertTrue(result.succeeded()); assertEquals("ok", result.result().body().getString("status")); assertTrue(result.result().body().getInteger("result") == 0); testComplete(); } }); } }); } }); } }); } }); } }); } }); } }
true
114aca811bbb5f473edd9b00c2e8b9ab0e830562
Java
feacerbi/Udacity-Nanodegree-PopularMovies
/app/src/main/java/br/com/felipeacerbi/popularmovies/dagger/MoviesComponent.java
UTF-8
530
1.992188
2
[]
no_license
package br.com.felipeacerbi.popularmovies.dagger; import javax.inject.Singleton; import br.com.felipeacerbi.popularmovies.activities.MainActivity; import br.com.felipeacerbi.popularmovies.activities.MovieDetailsActivity; import dagger.Component; @Singleton @Component(modules = { AppModule.class, MoviesModule.class, RetrofitModule.class, RoomModule.class}) public interface MoviesComponent { void injectMain(MainActivity activity); void injectDetails(MovieDetailsActivity activity); }
true
501bb1e10a3b318e04facd85696b8b8cbd7a8c97
Java
djhelbert/game-models
/game-models/src/main/java/com/game/model/common/CommonUtil.java
UTF-8
375
2.53125
3
[]
no_license
package com.game.model.common; import java.util.Random; /** * Common Utility Class * * @author dhelbert * */ public class CommonUtil { /** * Get Random Number * * @param max * * @return int */ public static int getRandomNumber(int max) { Random randomGenerator = new Random(); return randomGenerator.nextInt(max); } }
true
10db04dca85ea9d6024d0585799a8289ed5513ad
Java
potatophobe/CanUAffordToSmokeBot
/src/main/java/org/telegram/tomatophile/canuaffordtosmoke/bot/processed/textcommand/CanIAffordCommand.java
UTF-8
893
2.359375
2
[]
no_license
package org.telegram.tomatophile.canuaffordtosmoke.bot.processed.textcommand; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.tomatophile.canuaffordtosmoke.service.ReplyMessageService; @Component @RequiredArgsConstructor public class CanIAffordCommand implements TextCommand { private final ReplyMessageService replyMessageService; @Getter private final String text = "Что я могу себе позволить?"; @Override public SendMessage answer(String chatId) { return replyMessageService.getTextMessage(chatId, "Укажи свой бюджет (от-до) в формате: ***-***р\nИ я подскажу, на какие сигареты ты можешь рассчитывать."); } }
true
bfc9f39d29e3ad1cc8bb5f4c78948664188d0d9c
Java
wuyechun2018/baixiaosheng
/bxs-manager/bxs-manager-jdbc/src/main/java/com/bxs/jdbc/FloatWinDao.java
UTF-8
5,970
2.015625
2
[]
no_license
package com.bxs.jdbc; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback; import org.springframework.jdbc.support.lob.DefaultLobHandler; import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.stereotype.Repository; import com.bxs.common.dict.DataState; import com.bxs.common.vo.EUIPager; import com.bxs.pojo.FloatWin; @Repository public class FloatWinDao { @Autowired private JdbcTemplate jdbcTemplate; /** * * 获取条件筛选后的记录总数 * @author: wyc * @createTime: 2018年1月28日 上午10:13:36 * @history: * @param param * @return Long */ public Long getTotalCount(Map<String, Object> param) { String sql="SELECT COUNT(1) FROM t_float_win T WHERE 1=1 AND T.DATA_STATE='1'\n"+getParamSql(param); return jdbcTemplate.queryForObject(sql,Long.class); } /** * * 分页、条件 筛选列表 * @author: wyc * @createTime: 2018年1月28日 上午10:14:01 * @history: * @param ePager * @param param * @return List<?> */ public List<?> pagerList(EUIPager ePager,Map<String, Object> param) { String querySql="SELECT * FROM t_float_win T WHERE 1=1 AND T.DATA_STATE='1'\n"+getParamSql(param); String sql="SELECT * FROM ("+querySql+")S limit ?,?"; List<FloatWin> list = jdbcTemplate.query(sql,new Object[]{ePager.getStart(),ePager.getRows()},new BeanPropertyRowMapper(FloatWin.class)); return list; } /** * * 更新操作 * @author: wyc * @createTime: 2018年1月28日 下午2:12:33 * @history: * @param link void */ public void update(final FloatWin floatWin) { String sql= "UPDATE\n" + " t_float_win\n" + "SET\n" + " win_name = ?,\n" + " win_desc = ?,\n" + " link_url = ?,\n" + " link_target_type = ?,\n" + " link_image_url = ?,\n" + " display_order = ?,\n" + " show_state = ?,\n" + " data_state = ?\n" + "WHERE id = ?"; jdbcTemplate.execute(sql, new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setString(1, floatWin.getWinName()); ps.setString(2, floatWin.getWinDesc()); ps.setString(3, floatWin.getLinkUrl()); ps.setString(4, floatWin.getLinkTargetType()); ps.setString(5, floatWin.getLinkImageUrl()); ps.setInt(6, floatWin.getDisplayOrder()); ps.setString(7, floatWin.getShowState()); ps.setString(8, floatWin.getDataState()); ps.setString(9, floatWin.getId()); } } ); } /** * * 保存操作 * @author: wyc * @createTime: 2018年1月28日 下午2:12:44 * @history: * @param link void */ public void save(final FloatWin floatWin) { String sql="INSERT INTO t_float_win (\n" + " id,\n" + " win_name,\n" + " win_desc,\n" + " link_url,\n" + " link_target_type,\n" + " link_image_url,\n" + " display_order,\n" + " show_state,\n" + " data_state\n" + ")\n" + "VALUES\n" + " (\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?,\n" + " ?\n" + " )"; jdbcTemplate.execute(sql, new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setString(1, UUID.randomUUID().toString()); ps.setString(2, floatWin.getWinName()); ps.setString(3, floatWin.getWinDesc()); ps.setString(4, floatWin.getLinkUrl()); ps.setString(5, floatWin.getLinkTargetType()); ps.setString(6, floatWin.getLinkImageUrl()); ps.setInt(7, floatWin.getDisplayOrder()); ps.setString(8, floatWin.getShowState()); ps.setString(9, floatWin.getDataState()); } } ); } /** * * 删除 * @author: wyc * @createTime: 2018年4月9日 下午6:42:34 * @history: * @param id void */ public void delete(String id) { String sql = "UPDATE t_float_win SET DATA_STATE=? WHERE ID=?"; jdbcTemplate.update(sql,new Object[]{DataState.Delete.getCode(),id}); } /** * * 根据查询参数生成查询语句 * @author: wyc * @createTime: 2018年1月31日 下午4:35:08 * @history: * @param param * @return String */ private String getParamSql(Map<String, Object> param) { StringBuffer sqlBuff=new StringBuffer(); //显示状态 if(param.get("showState")!=null&&StringUtils.isNotBlank(param.get("showState").toString())){ sqlBuff.append(" AND T.show_state = '"+param.get("showState").toString()+"' \n"); } //链接名称 if(param.get("winName")!=null&&StringUtils.isNotBlank(param.get("winName").toString())){ sqlBuff.append(" AND T.win_name LIKE '%"+param.get("winName").toString()+"%' \n"); } //链接地址 if(param.get("linkUrl")!=null&&StringUtils.isNotBlank(param.get("linkUrl").toString())){ sqlBuff.append(" AND T.link_url LIKE '%"+param.get("linkUrl").toString()+"%' \n"); } sqlBuff.append(" ORDER BY DISPLAY_ORDER"); return sqlBuff.toString(); } }
true
164c0d0cb3729954cf95f4c35d4f1a4018c5fe85
Java
saumitramohan/Dev-Zot
/src/org/dev/multithreading/SyncronizationTest.java
UTF-8
1,131
3.46875
3
[]
no_license
package org.dev.multithreading; import java.util.concurrent.SynchronousQueue; class PrintDemo { public void printCount() { try { for (int i = 0; i < 5; i++) { System.out.println("Counter value - " + i); } } catch (Exception e) { System.out.println("Thread interrupted"); } } } class ThreadDemoTest implements Runnable { private Thread thread; private String name; PrintDemo pd; public ThreadDemoTest(String name, PrintDemo pd) { this.name = name; this.pd = pd; } @Override public void run() { synchronized (this.pd) { this.pd.printCount(); } System.out.println("ThreadExicted" + this.name); } public void start() { if (this.thread == null) { System.out.println("Starting thread - " + this.name); thread = new Thread(this, this.name); this.thread.start(); } } } public class SyncronizationTest { public static void main(String args[]) { PrintDemo pd = new PrintDemo(); ThreadDemoTest objectOne = new ThreadDemoTest("Thread-One",pd); objectOne.start(); ThreadDemoTest objectTwo = new ThreadDemoTest("Thread-Two",pd); objectTwo.start(); } }
true
b308693854bcdbfdb01df4e4cd95f0d0353a35c7
Java
databill86/ironySarcasmDetection
/IroniTAClassifier.java
UTF-8
16,202
2.1875
2
[ "MIT" ]
permissive
import it.uniroma2.sag.kelp.data.dataset.SimpleDataset; import it.uniroma2.sag.kelp.data.example.Example; import it.uniroma2.sag.kelp.data.label.Label; import it.uniroma2.sag.kelp.data.label.StringLabel; import it.uniroma2.sag.kelp.kernel.Kernel; import it.uniroma2.sag.kelp.kernel.cache.FixIndexKernelCache; import it.uniroma2.sag.kelp.kernel.cache.KernelCache; import it.uniroma2.sag.kelp.kernel.cache.StripeKernelCache; import it.uniroma2.sag.kelp.kernel.standard.LinearKernelCombination; import it.uniroma2.sag.kelp.kernel.standard.NormalizationKernel; import it.uniroma2.sag.kelp.kernel.standard.PolynomialKernel; import it.uniroma2.sag.kelp.kernel.standard.RbfKernel; import it.uniroma2.sag.kelp.kernel.tree.SubSetTreeKernel; import it.uniroma2.sag.kelp.kernel.vector.LinearKernel; import it.uniroma2.sag.kelp.learningalgorithm.classification.libsvm.BinaryCSvmClassification; import it.uniroma2.sag.kelp.learningalgorithm.classification.multiclassification.OneVsAllLearning; import it.uniroma2.sag.kelp.predictionfunction.classifier.BinaryMarginClassifierOutput; import it.uniroma2.sag.kelp.predictionfunction.classifier.ClassificationOutput; import it.uniroma2.sag.kelp.predictionfunction.classifier.Classifier; import it.uniroma2.sag.kelp.utils.JacksonSerializerWrapper; import it.uniroma2.sag.kelp.utils.evaluation.BinaryClassificationEvaluator; import it.uniroma2.sag.kelp.utils.evaluation.MulticlassClassificationEvaluator; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; public class IroniTAClassifier { public static void main(String[] args) throws Exception { //Parametri di settings per l'output Test boolean tuned = true; boolean ironyCorpus = true; float cIrony = 0.05f; float cSarcasm = 0.05f; // Reading the input parameters //String trainingSetFilePath = "data/dataset_ironia.klp"; String trainingSetFilePath = "data/train_dataset.klp"; float[] cs = {0.01f, 0.05f, 0.1f, 0.2f, 0.5f, 1, 5, 10}; Label positiveLabel = new StringLabel("Irony"); Label negativeLabel = new StringLabel("NOTIrony"); // Read the training and test dataset Label sarcasmPositiveLabel = new StringLabel("Sarcasmo"); SimpleDataset inputDatasetSet = new SimpleDataset(); inputDatasetSet.populate(trainingSetFilePath); SimpleDataset sarcasmDataset = new SimpleDataset(); for( Example ex : inputDatasetSet.getExamples()){ if(ex.isExampleOf(positiveLabel)){ sarcasmDataset.addExample(ex); } } SimpleDataset[] split = inputDatasetSet.split(0.8f); SimpleDataset trainingSet = split[0]; SimpleDataset testSet = split[1]; System.out.println("The training set is made of " + trainingSet.getNumberOfExamples() + " examples."); // print the number of train and test examples for each class for (Label l : trainingSet.getClassificationLabels()) { System.out.println("Positive training examples for the class " + l.toString() + " " + trainingSet.getNumberOfPositiveExamples(l)); System.out.println("Negative training examples for the class " + l.toString() + " " + trainingSet.getNumberOfNegativeExamples(l)); } // calculating the size of the gram matrix to store all the examples int cacheSize = trainingSet.getNumberOfExamples(); LinearKernelCombination combination = new LinearKernelCombination(); float charweight = 1; //0.51711822f; float dplweight = 1; //0.48288178f; float ironySpecific = 1; //0.50409571f; float wordSpace = 1; //0.49590429f; float bowweight = 1; //0.50396867f; float bigramsweight = 1; //0.49603133f; if(ironyCorpus) { combination.addKernel(bowweight, new NormalizationKernel(new LinearKernel("bowIC"))); combination.addKernel(bigramsweight, new NormalizationKernel(new LinearKernel("bowIC2gramSurface"))); combination.addKernel(bigramsweight, new NormalizationKernel(new LinearKernel("bowIC3gramSurface"))); combination.addKernel(bowweight, new NormalizationKernel(new LinearKernel("bowICBIN"))); combination.addKernel(bigramsweight, new NormalizationKernel(new LinearKernel("bowICBIN2gramSurface"))); combination.addKernel(bigramsweight, new NormalizationKernel(new LinearKernel("bowICBIN3gramSurface"))); combination.addKernel(bowweight, new RbfKernel(1, new NormalizationKernel(new LinearKernel("densUnigram")))); combination.addKernel(bigramsweight, new RbfKernel(1, new NormalizationKernel(new LinearKernel("densBigram")))); combination.addKernel(bigramsweight, new RbfKernel(1, new NormalizationKernel(new LinearKernel("densTrigram")))); } combination.addKernel(charweight, new NormalizationKernel(new LinearKernel("bow5gramChar"))); combination.addKernel(charweight, new NormalizationKernel(new LinearKernel("bow4gramChar"))); combination.addKernel(charweight, new NormalizationKernel(new LinearKernel("bow3gramChar"))); combination.addKernel(charweight, new NormalizationKernel(new LinearKernel("bow2gramChar"))); //combination.addKernel(dplweight, new NormalizationKernel(new LinearKernel("bowDPL"))); //combination.addKernel(dplweight, new RbfKernel(1, new NormalizationKernel(new LinearKernel("combDPL")))); combination.addKernel(ironySpecific, new NormalizationKernel(new LinearKernel("bowIronySpecific"))); combination.addKernel(ironySpecific, new NormalizationKernel(new LinearKernel("bowIronySpecificA"))); combination.addKernel(ironySpecific, new NormalizationKernel(new LinearKernel("bowIronySpecificS"))); combination.addKernel(ironySpecific, new NormalizationKernel(new LinearKernel("bowIronySpecificV"))); combination.addKernel(ironySpecific, new RbfKernel(1, new NormalizationKernel(new LinearKernel("VarMeanA")))); combination.addKernel(ironySpecific, new RbfKernel(1, new NormalizationKernel(new LinearKernel("VarMeanS")))); combination.addKernel(ironySpecific, new RbfKernel(1, new NormalizationKernel(new LinearKernel("VarMeanV")))); combination.addKernel(ironySpecific, new RbfKernel(1, new NormalizationKernel(new LinearKernel("VarMean")))); combination.addKernel(wordSpace, new RbfKernel(1, new NormalizationKernel(new LinearKernel("WSSurface")))); /* combination.addKernel(1, new NormalizationKernel(new LinearKernel("bowLemmi"))); combination.addKernel(1, new NormalizationKernel(new LinearKernel("bowBigramLemmi"))); combination.addKernel(1, new NormalizationKernel(new LinearKernel("bowBigramSurface"))); */ combination.addKernel(1, new RbfKernel(1, new NormalizationKernel(new LinearKernel("featPunt")))); // Setting the cache to speed up the computations KernelCache cache=new StripeKernelCache(inputDatasetSet); combination.setKernelCache(cache); int i; Map<Float, ArrayList<Float>> mappaC = new HashMap(); Map<Float, ArrayList<Float>> mappaSarcasm = new HashMap(); for (float c : cs) { mappaC.put(c, new ArrayList<Float>()); mappaSarcasm.put(c, new ArrayList<Float>()); } SimpleDataset trainingSetSarcasm = new SimpleDataset(); SimpleDataset testSetSarcasm = new SimpleDataset(); for(Example e: trainingSet.getExamples()){ if(e.isExampleOf(positiveLabel)) trainingSetSarcasm.addExample(e); } for(Example e: testSet.getExamples()){ if(e.isExampleOf(positiveLabel)) testSetSarcasm.addExample(e); } if (tuned == false) { PrintStream ps = new PrintStream("log.txt", "utf8"); PrintStream outvalIrony = new PrintStream("OutputIrony.txt", "utf8"); outvalIrony.println("C,F1-media,Sarcasm"); PrintStream outvalSarcasm = new PrintStream("OutputSarcasm.txt", "utf8"); outvalSarcasm.println("C,F1-media,Sarcasm"); for (i = 0; i < 10; i++) { Random random = new Random(); inputDatasetSet.shuffleExamples(random); split = inputDatasetSet.split(0.8f); trainingSet = split[0]; testSet = split[1]; trainingSetSarcasm = new SimpleDataset(); testSetSarcasm = new SimpleDataset(); for (Example e : trainingSet.getExamples()) { if (e.isExampleOf(positiveLabel)) trainingSetSarcasm.addExample(e); } for (Example e : testSet.getExamples()) { if (e.isExampleOf(positiveLabel)) testSetSarcasm.addExample(e); } ps.println(i + "-fold Validation"); for (float c : cs) { // Instantiate the SVM learning Algorithm. BinaryCSvmClassification svmSolver = new BinaryCSvmClassification(); svmSolver.setLabel(positiveLabel); //Set the kernel svmSolver.setKernel(combination); //Set the C parameter svmSolver.setCn(c); svmSolver.setCp(c); BinaryCSvmClassification svmSolver2 = new BinaryCSvmClassification(); svmSolver2.setLabel(sarcasmPositiveLabel); //Set the kernel svmSolver2.setKernel(combination); //Set the C parameter svmSolver2.setCn(c); svmSolver2.setCp(c); //Learn and get the prediction function svmSolver.learn(trainingSet); //Selecting the prediction function Classifier classifier = svmSolver.getPredictionFunction(); svmSolver2.learn(trainingSetSarcasm); //Selecting the prediction function Classifier classifier2 = svmSolver2.getPredictionFunction(); //Building the evaluation function BinaryClassificationEvaluator evaluator = new BinaryClassificationEvaluator(positiveLabel); BinaryClassificationEvaluator evaluator2 = new BinaryClassificationEvaluator(sarcasmPositiveLabel); BinaryClassificationEvaluator evaluatorDefaultSarcasm = new BinaryClassificationEvaluator(sarcasmPositiveLabel); for (Example ex : testSet.getExamples()) { ClassificationOutput p = classifier.predict(ex); evaluator.addCount(ex, p); if (p.isClassPredicted(positiveLabel)) { ClassificationOutput q = classifier2.predict(ex); evaluatorDefaultSarcasm.addCount(ex, q); } else { BinaryMarginClassifierOutput defaultNoSarcasm = new BinaryMarginClassifierOutput(sarcasmPositiveLabel, -1); evaluatorDefaultSarcasm.addCount(ex, defaultNoSarcasm); } } for (Example ex : testSetSarcasm.getExamples()) { ClassificationOutput p = classifier2.predict(ex); evaluator2.addCount(ex, p); } ps.println("Ironia: C[" + c + "]F1 Score, Precision, Recall \t" + "\t" + evaluator.getF1() + "\t" + evaluator.getPrecision() + "\t" + evaluator.getRecall()); mappaC.get(c).add(evaluator.getF1()); mappaSarcasm.get(c).add(evaluatorDefaultSarcasm.getF1()); ps.println("Sarcasmo: C[" + c + "]F1 Score, Precision, Recall \t" + "\t" + evaluator2.getF1() + "\t" + evaluator2.getPrecision() + "\t" + evaluator2.getRecall()); ps.println("Sarcasmo Default: C[" + c + "]F1 Score, Precision, Recall \t" + "\t" + evaluatorDefaultSarcasm.getF1() + "\t" + evaluatorDefaultSarcasm.getPrecision() + "\t" + evaluatorDefaultSarcasm.getRecall()); } } for (Float key : mappaC.keySet()) { ArrayList<Float> lisa = mappaC.get(key); float media = 0; float varianza = 0; for (Float f : lisa) { media = media + f; } media = media / lisa.size(); for (Float f : lisa) { float diff = f - media; varianza = varianza + (float) Math.pow(diff, 2); } varianza = varianza / (lisa.size() - 1); outvalIrony.println(key + "," + media + "," + varianza); ps.println("Irony: Media e Varianza per C pari a [" + key + "]: " + media + " " + varianza); } for (Float key : mappaSarcasm.keySet()) { ArrayList<Float> lisa = mappaSarcasm.get(key); float media = 0; float varianza = 0; for (Float f : lisa) { media = media + f; } media = media / lisa.size(); for (Float f : lisa) { float diff = f - media; varianza = varianza + (float) Math.pow(diff, 2); } varianza = varianza / (lisa.size() - 1); outvalSarcasm.println(key + "," + media + "," + varianza); ps.println("Sarcasm: Media e Varianza per C pari a [" + key + "]: " + media + " " + varianza); } ps.close(); } //Altrimenti faccio il test su tutto else{ String testSetFilePath = "data/test_dataset.klp"; SimpleDataset inputDatasetTestSet = new SimpleDataset(); inputDatasetTestSet.populate(testSetFilePath); PrintStream streamTestOut = new PrintStream("testOutput.tsv", "utf8"); // Instantiate the SVM learning Algorithm. BinaryCSvmClassification svmSolver = new BinaryCSvmClassification(); svmSolver.setLabel(positiveLabel); //Set the kernel svmSolver.setKernel(combination); //Set the C parameter svmSolver.setCn(cIrony); svmSolver.setCp(cIrony); BinaryCSvmClassification svmSolver2 = new BinaryCSvmClassification(); svmSolver2.setLabel(sarcasmPositiveLabel); //Set the kernel svmSolver2.setKernel(combination); //Set the C parameter svmSolver2.setCn(cSarcasm); svmSolver2.setCp(cSarcasm); //Learn and get the prediction function svmSolver.learn(inputDatasetSet); //Selecting the prediction function Classifier classifier = svmSolver.getPredictionFunction(); svmSolver2.learn(sarcasmDataset); //Selecting the prediction function Classifier classifier2 = svmSolver2.getPredictionFunction(); combination.disableCache(); System.out.println("Elaborazione del test set e scrittura dell'output su file in corso...."); for (Example ex : inputDatasetTestSet.getExamples()) { ClassificationOutput p = classifier.predict(ex); int ironia = 0; int sarcasmo = 0; if (p.isClassPredicted(positiveLabel)) { ClassificationOutput q = classifier2.predict(ex); //Allora è ironico ironia = 1; if (q.isClassPredicted(sarcasmPositiveLabel)) { sarcasmo = 1; } } streamTestOut.println(ex.getRepresentation("IDTweet") + "\t" + ironia + "\t" + sarcasmo); } } } }
true
5bb4cb01078648da2499dd109004039ee4b450ed
Java
dvjzero/ChileDenuncia
/src/orm/ContactoCriteria.java
UTF-8
1,612
2.375
2
[]
no_license
/** * "Visual Paradigm: DO NOT MODIFY THIS FILE!" * * This is an automatic generated file. It will be regenerated every time * you generate persistence class. * * Modifying its content may cause the program not work, or your work may lost. */ /** * Licensee: Universidad del Pais Vasco * License Type: Academic */ package orm; import org.hibernate.Criteria; import org.orm.PersistentException; import org.orm.PersistentSession; import org.orm.criteria.*; public class ContactoCriteria extends AbstractORMCriteria { public final IntegerExpression con_id; public final StringExpression con_nombre; public final StringExpression con_correo; public final StringExpression con_asunto; public final StringExpression con_mensaje; public ContactoCriteria(Criteria criteria) { super(criteria); con_id = new IntegerExpression("con_id", this); con_nombre = new StringExpression("con_nombre", this); con_correo = new StringExpression("con_correo", this); con_asunto = new StringExpression("con_asunto", this); con_mensaje = new StringExpression("con_mensaje", this); } public ContactoCriteria(PersistentSession session) { this(session.createCriteria(Contacto.class)); } public ContactoCriteria() throws PersistentException { this(orm.ChileDenunciaPersistentManager.instance().getSession()); } public Contacto uniqueContacto() { return (Contacto) super.uniqueResult(); } public Contacto[] listContacto() { java.util.List list = super.list(); return (Contacto[]) list.toArray(new Contacto[list.size()]); } }
true
20fdd69b73461e287dba4950811eea96ed689a86
Java
anagalacticRuby/AmbienceMockups
/src/sample/Main.java
UTF-8
961
2.609375
3
[]
no_license
package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * This entire program is a mockup for the Ambience application. All screens may be subject to * change if there is a desire, so nothing is 100% certain to be in the final just yet. Last edited * on: 12/1/2019. * * @author Nicholas Hansen */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("MainMenuDemo.fxml")); primaryStage.setTitle("Ambience Ui Mockup"); primaryStage.setResizable(false); Scene scene = new Scene(root, 335, 600); scene.getStylesheets().add(getClass().getResource("AmbienceStyle.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
true
55f08f22391e6e343fdb86ab55adaaf0eb04cc6c
Java
jorgeelucas/sociotorcedor
/src/main/java/com/desafio/sociotorcedor/service/SocioTorcedorService.java
UTF-8
4,455
2.171875
2
[]
no_license
package com.desafio.sociotorcedor.service; import java.time.LocalDate; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import com.desafio.sociotorcedor.client.CampanhaClient; import com.desafio.sociotorcedor.domain.SocioTorcedor; import com.desafio.sociotorcedor.dto.CampanhaDTO; import com.desafio.sociotorcedor.dto.SocioTorcedorDTO; import com.desafio.sociotorcedor.exception.ObjectNotFoundException; import com.desafio.sociotorcedor.exception.UsuarioJaExisteException; import com.desafio.sociotorcedor.repository.SocioTorcedorRepository; import com.desafio.sociotorcedor.utils.DateUtils; @Service public class SocioTorcedorService { @Autowired private SocioTorcedorRepository socioTorcedorRepository; @Autowired private CampanhaClient campanhaClient; @Cacheable(value = "socioTorcedorGetAll", unless = "#result==null") public List<SocioTorcedorDTO> getAll() { List<SocioTorcedor> all = socioTorcedorRepository.findAll(); return all.stream().map(st -> new SocioTorcedorDTO(st)).collect(Collectors.toList()); } @Caching(evict = {@CacheEvict(value = "socioTorcedorGetById", allEntries = true), @CacheEvict(value = "socioTorcedorGetAll", allEntries = true) }) public SocioTorcedor create(SocioTorcedor socioTorcedor) { if (socioTorcedor.getId() == null) { validarCadastro(socioTorcedor); } return socioTorcedorRepository.save(socioTorcedor); } @Cacheable(value = "socioTorcedorGetById", key = "#id", unless = "#result==null") public SocioTorcedorDTO findById(Integer id) { SocioTorcedor socioTorcedor = socioTorcedorRepository.findById(id) .orElseThrow(() -> new ObjectNotFoundException("Socio de id " + id + " não encontrado")); Set<CampanhaDTO> campanhas = campanhaClient.campanhasPorSocio(socioTorcedor); SocioTorcedorDTO dto = new SocioTorcedorDTO(socioTorcedor); dto.setCampanhas(campanhas); return dto; } public Page<SocioTorcedorDTO> getPagination(String nomeCompleto, String email, Integer time, String dataAniversario, PageRequest pageRequest) { LocalDate aniversario = DateUtils.parseDate(dataAniversario); Example<SocioTorcedor> exampleQuery = matcherCreator(nomeCompleto, email, time, aniversario); Page<SocioTorcedor> page = socioTorcedorRepository.findAll(exampleQuery, pageRequest); return page.map(p -> new SocioTorcedorDTO(p)); } @Caching(evict = {@CacheEvict(value = "socioTorcedorGetById", allEntries = true), @CacheEvict(value = "socioTorcedorGetAll", allEntries = true) }) public SocioTorcedorDTO update(SocioTorcedorDTO socioTorcedorDTO, Integer id) { SocioTorcedor socioTorcedor = new SocioTorcedor(socioTorcedorDTO); socioTorcedor.setId(id); SocioTorcedor socioTorcedorUpdated = socioTorcedorRepository.save(socioTorcedor); return new SocioTorcedorDTO(socioTorcedorUpdated); } @Caching(evict = {@CacheEvict(value = "socioTorcedorGetById", allEntries = true), @CacheEvict(value = "socioTorcedorGetAll", allEntries = true) }) public void deleteById(Integer id) { findById(id); socioTorcedorRepository.deleteById(id); } private Example<SocioTorcedor> matcherCreator(String nomeCompleto, String email, Integer idTime, LocalDate dataAniversario) { ExampleMatcher matcher = ExampleMatcher.matching() .withMatcher("nomeCompleto", ExampleMatcher.GenericPropertyMatchers.contains()) .withMatcher("email", ExampleMatcher.GenericPropertyMatchers.contains()).withIgnoreCase("nomeCompleto") .withIgnoreCase("email").withIgnoreNullValues(); SocioTorcedor SocioTorcedorSearch = new SocioTorcedor(nomeCompleto, email, dataAniversario, idTime); return Example.of(SocioTorcedorSearch, matcher); } private void validarCadastro(SocioTorcedor socioTorcedor) { String email = socioTorcedor.getEmail(); if (socioTorcedorRepository.existsByEmail(email)) { throw new UsuarioJaExisteException("email já cadastrado."); } } // private void validaTime(Time time) { // timeService.isTimeValido(time.getId()); // } }
true
74f128fcd93d3453fccf682679c36cb6e2a15d39
Java
paulduong222/development
/isuite-core-ui/src/main/java/gov/nwcg/isuite/framework/core/vo/PersistableVo.java
UTF-8
2,079
2.5625
3
[]
no_license
package gov.nwcg.isuite.framework.core.vo; import gov.nwcg.isuite.framework.core.domain.Persistable; import java.util.Date; /** * * @author ncollette * */ public interface PersistableVo { /** * Accessor id * * @see #setId(Long) * @return id */ public Long getId(); /** * Accessor id * * @see #getId() * @param id id of object */ public void setId(Long id); /** * Returns the user login name. * * @return * the userLoginName */ public String getUserLoginName(); /** * Sets the user login name. * * @param userLoginName * the userLoginName to set */ public void setUserLoginName(String userLoginName); /** * Sets the created by user. * * @param val * the created by user to set */ public void setCreatedBy(String val); /** * Returns the created by user. * * @return * the created by user to return */ public String getCreatedBy(); /** * Sets the created date. * * @param dt * the created date to set */ public void setCreatedDate(Date dt); /** * Returns the created date. * * @return * the created date to return */ public Date getCreatedDate(); /** * Returns an entity object populated with the values from the vo object. * * If the param entity is null, a new instance will be created and populated, * otherwise the entity passed will be populated with the vo values. * * @param entity * the entity to populate if it is available * @param cascadable * flag to indicate whether or not the entity instance * that is being returned should be treated as cascadable * object. If the flag is true, then the entire entity * will be built and returned, otherwise only the id is set * @return * the populated entity to return * @throws Exception */ @Deprecated public Persistable toEntity(Persistable entity) throws Exception; }
true
f76c0c8a7ec93ad5c85ffb29a80f63998e66e26f
Java
victorzaitev/iBanc-RM-Server
/src/main/java/md/ibanc/rm/read/message/MessageFactory.java
UTF-8
1,155
2.328125
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 md.ibanc.rm.read.message; import md.ibanc.rm.spring.service.MessageService; /** * * @author PC01017745 */ public class MessageFactory { private MessageService messageService; public MessageFactory() { } public MessageFactory(MessageService messageService) { this.messageService = messageService; } public Message getMessage(String messageType) { if (messageType == null) { return null; } if (messageType.equalsIgnoreCase("NewDevices")) { return new MessageTypeNewDevices(messageService); } else if (messageType.equalsIgnoreCase("WrongPassword")) { return new MessageTypeWrongPassword(messageService); } else if (messageType.equalsIgnoreCase("BlockAccount")) { return new MessageTypeBlockAccount(messageService); } return null; } }
true
3bff4accd936f3a98d178ca4bfcc79fbc92c382f
Java
harshithalingaraj/cucooo
/cucumber/src/main/java/package1/scenario1.java
UTF-8
217
2.40625
2
[]
no_license
package package1; import io.cucumber.java.en.Given; public class scenario1 { @Given("I enter 50 in the calculator") public void I_enter() { System.out.println("I enter 50 in the calculator"); } }
true
e6caaf3b6b83b5d1f4b652b2cbfe83dbb7903302
Java
Xycl/JSynthLib
/src/main/java/org/jsynthlib/synthdrivers/RolandMKS50/MKS50ToneSingleEditor.java
UTF-8
11,613
2.140625
2
[]
no_license
// written by Kenneth L. Martinez // @version $Id: MKS50ToneSingleEditor.java 895 2005-02-07 05:50:06Z hayashi $ package org.jsynthlib.synthdrivers.RolandMKS50; import java.awt.GridBagLayout; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import org.jsynthlib.device.model.handler.ParamModel; import org.jsynthlib.device.model.handler.SysexSender; import org.jsynthlib.device.viewcontroller.PatchEditorFrame; import org.jsynthlib.device.viewcontroller.widgets.CheckBoxWidget; import org.jsynthlib.device.viewcontroller.widgets.ComboBoxWidget; import org.jsynthlib.device.viewcontroller.widgets.EnvelopeWidget; import org.jsynthlib.device.viewcontroller.widgets.EnvelopeWidget.Node; import org.jsynthlib.device.viewcontroller.widgets.PatchNameWidget; import org.jsynthlib.device.viewcontroller.widgets.ScrollBarWidget; import org.jsynthlib.patch.model.impl.Patch; class MKS50ToneSingleEditor extends PatchEditorFrame { public MKS50ToneSingleEditor(Patch patch) { super("Roland MKS-50 Tone Single Editor", patch); JPanel leftPane = new JPanel(); leftPane.setLayout(new GridBagLayout()); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; scrollPane.add(leftPane, gbc); JPanel rightPane = new JPanel(); rightPane.setLayout(new GridBagLayout()); gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; scrollPane.add(rightPane, gbc); JPanel namePane = new JPanel(); addWidget(namePane, new PatchNameWidget(" Name", patch), 0, 0, 2, 1, 0); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; leftPane.add(namePane, gbc); JPanel oscPane = new JPanel(); oscPane.setLayout(new GridBagLayout()); addWidget(oscPane, new ComboBoxWidget("Range", patch, new ParamModel( patch, 13), new MKSToneSender(6), new String[] { "4'", "8'", "16'", "32'" }), 0, 0, 1, 1, 1); addWidget(oscPane, new ComboBoxWidget("ENV Mode", patch, new ParamModel(patch, 7), new MKSToneSender(0), new String[] { "Normal", "Inverted", "Norm-Dyn", "Inv-Dyn" }), 1, 0, 1, 1, 2); addWidget(oscPane, new ScrollBarWidget("Saw Wave", patch, 0, 5, 0, new ParamModel(patch, 11), new MKSToneSender(4)), 0, 1, 3, 1, 3); addWidget(oscPane, new ScrollBarWidget("Pulse Wave", patch, 0, 3, 0, new ParamModel(patch, 10), new MKSToneSender(3)), 0, 2, 3, 1, 4); addWidget(oscPane, new ScrollBarWidget("PW / PWM", patch, 0, 127, 0, new ParamModel(patch, 21), new MKSToneSender(14)), 0, 3, 3, 1, 5); addWidget(oscPane, new ScrollBarWidget("PWM Rate", patch, 0, 127, 0, new ParamModel(patch, 22), new MKSToneSender(15)), 0, 4, 3, 1, 6); addWidget(oscPane, new ScrollBarWidget("Sub Wave", patch, 0, 5, 0, new ParamModel(patch, 12), new MKSToneSender(5)), 0, 5, 3, 1, 7); addWidget(oscPane, new ScrollBarWidget("Sub Level", patch, 0, 3, 0, new ParamModel(patch, 14), new MKSToneSender(7)), 0, 6, 3, 1, 8); addWidget(oscPane, new ScrollBarWidget("Noise Level", patch, 0, 3, 0, new ParamModel(patch, 15), new MKSToneSender(8)), 0, 7, 3, 1, 9); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; oscPane.setBorder(new TitledBorder( new EtchedBorder(EtchedBorder.RAISED), "DCO Settings", TitledBorder.CENTER, TitledBorder.CENTER)); leftPane.add(oscPane, gbc); JPanel vcfPane = new JPanel(); vcfPane.setLayout(new GridBagLayout()); addWidget(vcfPane, new ScrollBarWidget("Cutoff Freq", patch, 0, 127, 0, new ParamModel(patch, 23), new MKSToneSender(16)), 0, 0, 3, 1, 10); addWidget(vcfPane, new ScrollBarWidget("Resonance", patch, 0, 127, 0, new ParamModel(patch, 24), new MKSToneSender(17)), 0, 1, 3, 1, 11); addWidget(vcfPane, new ScrollBarWidget("Key Follow", patch, 0, 15, 0, new MKSShiftModel(patch, 27), new MKSShiftSender(20)), 0, 2, 3, 1, 12); addWidget(vcfPane, new ComboBoxWidget("VCF ENV Mode", patch, new ParamModel(patch, 8), new MKSToneSender(1), new String[] { "Normal", "Inverted", "Norm-Dyn", "Inv-Dyn" }), 0, 3, 1, 1, 13); gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; vcfPane.setBorder(new TitledBorder( new EtchedBorder(EtchedBorder.RAISED), "VCF Settings", TitledBorder.CENTER, TitledBorder.CENTER)); leftPane.add(vcfPane, gbc); JPanel lfoPane = new JPanel(); lfoPane.setLayout(new GridBagLayout()); gbc.weightx = 1; addWidget(lfoPane, new ScrollBarWidget("LFO Speed", patch, 0, 127, 0, new ParamModel(patch, 31), new MKSToneSender(24)), 0, 0, 7, 1, 14); addWidget(lfoPane, new ScrollBarWidget("LFO Delay", patch, 0, 127, 0, new ParamModel(patch, 32), new MKSToneSender(25)), 0, 1, 7, 1, 15); addWidget(lfoPane, new ScrollBarWidget("DCO Mod Depth", patch, 0, 127, 0, new ParamModel(patch, 18), new MKSToneSender(11)), 0, 2, 7, 1, 16); addWidget(lfoPane, new ScrollBarWidget("VCF Mod Depth", patch, 0, 127, 0, new ParamModel(patch, 25), new MKSToneSender(18)), 0, 3, 7, 1, 17); gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; lfoPane.setBorder(new TitledBorder( new EtchedBorder(EtchedBorder.RAISED), "LFO Settings", TitledBorder.CENTER, TitledBorder.CENTER)); leftPane.add(lfoPane, gbc); JPanel envPane = new JPanel(); envPane.setLayout(new GridBagLayout()); addWidget(envPane, new EnvelopeWidget(" ", patch, new Node[] { new Node(0, 0, null, 0, 0, null, 0, false, null, null, null, null), new Node(0, 127, new ParamModel(patch, 33), 0, 127, new ParamModel(patch, 34), 10, false, new MKSToneSender(26), new MKSToneSender(27), " T1", " L1"), new Node(0, 127, new ParamModel(patch, 35), 0, 127, new ParamModel(patch, 36), 10, false, new MKSToneSender(28), new MKSToneSender(29), " T2", " L2"), new Node(0, 127, new ParamModel(patch, 37), 0, 127, new ParamModel(patch, 38), 10, false, new MKSToneSender(30), new MKSToneSender(31), " T3", " L3"), new Node(0, 127, new ParamModel(patch, 39), 0, 0, null, 0, false, new MKSToneSender(32), null, " T4", null), }), 3, 0, 3, 5, 18); addWidget(envPane, new ScrollBarWidget("Key Follow", patch, 0, 15, 0, new MKSShiftModel(patch, 40), new MKSShiftSender(33)), 3, 6, 3, 1, 25); addWidget(envPane, new ScrollBarWidget("DCO Mod Depth", patch, 0, 127, 0, new ParamModel(patch, 19), new MKSToneSender(12)), 3, 7, 3, 1, 26); addWidget(envPane, new ScrollBarWidget("VCF Mod Depth", patch, 0, 127, 0, new ParamModel(patch, 26), new MKSToneSender(19)), 3, 8, 3, 1, 27); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; envPane.setBorder(new TitledBorder( new EtchedBorder(EtchedBorder.RAISED), "Envelope", TitledBorder.CENTER, TitledBorder.CENTER)); rightPane.add(envPane, gbc); JPanel cmnPane = new JPanel(); cmnPane.setLayout(new GridBagLayout()); addWidget(cmnPane, new ScrollBarWidget("DCO Aftertouch LFO", patch, 0, 15, 0, new MKSShiftModel(patch, 20), new MKSShiftSender(13)), 0, 0, 3, 1, 28); addWidget(cmnPane, new ScrollBarWidget("VCF Aftertouch Depth", patch, 0, 15, 0, new MKSShiftModel(patch, 28), new MKSShiftSender(21)), 0, 1, 3, 1, 29); addWidget(cmnPane, new ScrollBarWidget("VCA Aftertouch Depth", patch, 0, 15, 0, new MKSShiftModel(patch, 30), new MKSShiftSender(23)), 0, 2, 3, 1, 30); addWidget(cmnPane, new ScrollBarWidget("VCA Level", patch, 0, 127, 0, new ParamModel(patch, 29), new MKSToneSender(22)), 0, 3, 3, 1, 31); addWidget(cmnPane, new ComboBoxWidget("VCA ENV Mode", patch, new ParamModel(patch, 9), new MKSToneSender(2), new String[] { "Env", "Gate", "Env-Dyn", "Gate-Dyn" }), 0, 4, 1, 1, 32); addWidget(cmnPane, new CheckBoxWidget("Chorus", patch, new ParamModel( patch, 17), new MKSToneSender(10)), 1, 4, 1, 1, -1); addWidget(cmnPane, new ScrollBarWidget("Chorus Rate", patch, 0, 127, 0, new ParamModel(patch, 41), new MKSToneSender(34)), 0, 5, 3, 1, 33); addWidget(cmnPane, new ScrollBarWidget("HPF", patch, 0, 3, 0, new ParamModel(patch, 16), new MKSToneSender(9)), 0, 6, 3, 1, 34); addWidget(cmnPane, new ScrollBarWidget("Bender Range", patch, 0, 12, 0, new ParamModel(patch, 42), new MKSToneSender(35)), 0, 7, 3, 1, 35); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; cmnPane.setBorder(new TitledBorder( new EtchedBorder(EtchedBorder.RAISED), "Common", TitledBorder.CENTER, TitledBorder.CENTER)); rightPane.add(cmnPane, gbc); pack(); } } class MKSToneSender extends SysexSender { byte b[] = { (byte) 0xF0, (byte) 0x41, (byte) 0x36, (byte) 0x00, (byte) 0x23, (byte) 0x20, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xF7 }; public MKSToneSender(int param) { b[7] = (byte) param; } @Override public byte[] generate(int value) { b[3] = (byte) (getChannel() - 1); b[8] = (byte) value; return b; } } // shift sender & model are for parms whose value must be shifted left // 3 bits (multiplied by 8) to arrive at the sysex parm value class MKSShiftModel extends ParamModel { public MKSShiftModel(Patch p, int o) { super(p, o); } @Override public void set(int i) { patch.sysex[offset] = (byte) (i << 3); } @Override public int get() { return patch.sysex[offset] >> 3; } } class MKSShiftSender extends SysexSender { byte b[] = { (byte) 0xF0, (byte) 0x41, (byte) 0x36, (byte) 0x00, (byte) 0x23, (byte) 0x20, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xF7 }; public MKSShiftSender(int param) { b[7] = (byte) param; } @Override public byte[] generate(int value) { b[3] = (byte) (getChannel() - 1); b[8] = (byte) (value << 3); return b; } }
true
8136841c95ef47504118f1d4bbd6794943bf2697
Java
schana/skillsusa-java
/game/internal/GameState.java
UTF-8
2,071
3.109375
3
[ "Apache-2.0" ]
permissive
package game.internal; import game.Board; import game.Cell; import game.MyMover; import java.util.HashSet; import java.util.Random; import java.util.Set; import static game.Board.COLUMNS; import static game.Board.ROWS; public class GameState { private Board board; private Snake snake; private Food food; private Set<Cell> cells; private int age = 0; public GameState(Board board) { this.board = board; cells = new HashSet<>(); for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLUMNS; c++) { cells.add(new Cell(r, c)); } } this.snake = new Snake(new Cell(new Random().nextInt(ROWS), new Random().nextInt(COLUMNS)), new MyMover(board)); this.food = new Food(getRandomFreeCell()); board.setBody(snake.getBody().getCells()); board.setFood(food.get()); } public boolean step() { age++; snake.move(food.get()); if (snake.hasConsumedFood()) { Cell nextFood = getRandomFreeCell(); if (nextFood != null) { food.update(nextFood); } else { return false; } } board.setBody(snake.getBody().getCells()); board.setFood(food.get()); return snake.isAlive(); } public boolean isAlive() { return snake.isAlive(); } public int getAge() { return age; } public int getScore() { return snake.getBody().getCells().size(); } public Board getBoard() { return board; } private Cell getRandomFreeCell() { HashSet<Cell> available = new HashSet<Cell>(cells); available.removeAll(snake.getBody().getCells()); if (available.size() > 0) { int item = new Random().nextInt(available.size()); int i = 0; for (Cell c : available) { if (i == item) { return c; } i++; } } return null; } }
true
d48e6b1c669013cb361058621c75a31039370af5
Java
tatjanamalic/vjezbanje
/src/ČetriOsamnaestKnjiga.java
UTF-8
836
3.34375
3
[]
no_license
import java.util.Scanner; public class ČetriOsamnaestKnjiga { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Unesite dva karaktera: "); String unos = "M1"; String odabir = ""; if(unos.startsWith("M")){ odabir += "Mathematica"; } if(unos.startsWith("C")){ odabir += "Computer"; } if(unos.startsWith("I")){ odabir += "Informatica"; } if (unos.endsWith("1")){ odabir += "Freshman"; } if (unos.endsWith("2")){ odabir += "Junior"; } if (unos.endsWith("3")){ odabir += "Senior"; } if (unos.endsWith("4")){ odabir += "Sophomore"; } } }
true
d34999e65d96a6e9041fbd52360cda9fac7f5298
Java
Bionex/AAComp2
/src/batalha/Escolta.java
ISO-8859-1
1,881
3.140625
3
[]
no_license
package batalha; import javax.swing.ImageIcon; import javax.swing.JButton; import telas.Tabuleiro; public class Escolta extends Navio { public static final int tamanho = 3; public static final int id = 3; // retorna verdadeiro se j tiver um navio nessas posicoes public static boolean checaNavio(int[][] vetor, int linha, int coluna) { int contador = 0; while(contador < Escolta.tamanho){ if(vetor[linha][coluna+contador] != 0) return true; contador++; } return false; } public static int getId(){ return Escolta.id; } public static void posicionarNavio(int[][] matriz, int linha, int coluna) { int contador = 0; while (contador < Escolta.tamanho) { matriz[linha][coluna+contador] = Escolta.id; contador++; } } public static void darTiro(int[][]valor_enemy, JButton[][] barcos_enemy, int linha, int coluna){ for(int i = 0; i < 2; i++){ coluna += i; if(coluna > 9) break; if(valor_enemy[linha][coluna] == 0){ barcos_enemy[linha][coluna].setIcon(new ImageIcon(Tabuleiro.class.getResource("/telas/water.png"))); barcos_enemy[linha][coluna].setDisabledIcon(new ImageIcon(Tabuleiro.class.getResource("/telas/water.png"))); barcos_enemy[linha][coluna].setEnabled(false); valor_enemy[linha][coluna] = -1; } else if(valor_enemy[linha][coluna] != 0 && valor_enemy[linha][coluna] != -1){ barcos_enemy[linha][coluna] .setIcon(new ImageIcon(Tabuleiro.class.getResource("/telas/explosao.png"))); // Configura a imagem para o Boto desabilitado barcos_enemy[linha][coluna] .setDisabledIcon(new ImageIcon(Tabuleiro.class.getResource("/telas/explosao.png"))); // Desabilita o boto j clicado para no continuar barcos_enemy[linha][coluna].setEnabled(false); valor_enemy[linha][coluna] = -1; } } } }
true
8665a52053b19452445898f00f5f83099e070538
Java
jLemmings/GastronomySoftware
/gastrosoftware-gui-service-leiter/src/main/java/ch/hslu/slgp/gastrosoftware/gui/controller/LoginController.java
UTF-8
3,980
2.09375
2
[]
no_license
package ch.hslu.slgp.gastrosoftware.gui.controller; import ch.hslu.slgp.gastrosoftware.model.Mitarbeiter; import ch.hslu.slgp.gastrosoftware.rmi.api.RMIPersonService; import ch.hslu.slgp.gastrosoftware.rmi.context.Context; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.Logger; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class LoginController implements Initializable { @FXML Button genLogi; @FXML private TextField genBenu; @FXML private TextField genPass; @FXML private Label genPwEr; private static RMIPersonService personService = Context.getInstance().getPersonService(); private static Logger logger = (Logger) LogManager.getLogger(LoginController.class); @Override public void initialize(URL location, ResourceBundle resources) { genLogi.defaultButtonProperty().bind(genLogi.focusedProperty()); } @FXML private void loginaction(ActionEvent event) throws Exception { if (personService.pruefeLogin(genBenu.getText(), genPass.getText())) { if ("Kuechenpersonal".equals(personService.getFunktionPerson(genBenu.getText(), genPass.getText()))) { Parent kueche_interface_parent = FXMLLoader.load(getClass().getResource("/fxml/KuecheInterface.fxml")); Scene kueche_interface_scene = new Scene(kueche_interface_parent); Stage kueche_stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); kueche_stage.setScene(kueche_interface_scene); kueche_stage.show(); } else if ("Servicepersonal".equals(personService.getFunktionPerson(genBenu.getText(), genPass.getText()))) { Parent ma_interface_parent = FXMLLoader.load(getClass().getResource("/fxml/MaInterface.fxml")); Scene ma_interface_scene = new Scene(ma_interface_parent); Stage ma_stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); Mitarbeiter mitarbeiter = personService.findMitarbeiterByUsername(genBenu.getText()); ContextMitarbeiter.getInstance().setMitarbeiter(mitarbeiter); ma_stage.setScene(ma_interface_scene); ma_stage.show(); } else if ("Barpersonal".equals(personService.getFunktionPerson(genBenu.getText(), genPass.getText()))) { Parent bar_interface_parent = FXMLLoader.load(getClass().getResource("/fxml/BarInterface.fxml")); Scene bar_interface_scene = new Scene(bar_interface_parent); Stage bar_stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); bar_stage.setScene(bar_interface_scene); bar_stage.show(); } else if ("Leiter".equals(personService.getFunktionPerson(genBenu.getText(), genPass.getText()))) { Parent leiter_interface_parent = FXMLLoader.load(getClass().getResource("/fxml/LeiterInterface.fxml")); Scene leiter_interface_scene = new Scene(leiter_interface_parent); Stage leiter_stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); leiter_stage.setScene(leiter_interface_scene); leiter_stage.show(); } else { genPwEr.setText("Bitte wenden Sie sich an den Administrator..."); } } else { genPwEr.setText("Benutzername oder Passwort falsch.."); } } @FXML private void exitaction(ActionEvent event) throws IOException { System.exit(0); } }
true
54f71217489c925e5bd8dff36bd4b6ce77bfe755
Java
Foreinyel/demo-java
/demo-concurrent/src/Bank.java
UTF-8
1,375
3.421875
3
[]
no_license
import java.util.HashMap; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Bank { private ReentrantLock bankLock = new ReentrantLock(); private HashMap<String, Integer> accounts = new HashMap(); private Condition sufficient = bankLock.newCondition();; public Bank() { accounts.put("a", 200); accounts.put("b", 300); accounts.put("c", 240); } public void transfer(String from, String to, int amount) { bankLock.lock(); try { Integer fromBalance = accounts.get(from); while (fromBalance < amount) { System.out.println("waiting " + from + " " + to); sufficient.await(); fromBalance = accounts.get(from); } System.out.println("start to transfer: " + from + ", " + to + " " + amount); accounts.put(from, fromBalance - amount); accounts.put(to, accounts.get(to) + amount); sufficient.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bankLock.unlock(); } } public void print() { accounts.keySet().forEach((String acc) -> { System.out.println("balance of " + acc + " is " + accounts.get(acc)); }); } }
true
c1968122a64dc5e325acceda8052ccc287e85fda
Java
javasrd/pivasBase
/src/com/zc/pivas/allowork/bean/AlloWorkCount.java
UTF-8
1,035
2.015625
2
[]
no_license
package com.zc.pivas.allowork.bean; import java.io.Serializable; /** * 对应配置费分类数量 * * @author jagger * @version 1.0 */ public class AlloWorkCount implements Serializable { /** * 注释内容 */ private static final long serialVersionUID = 1L; /** * 编码 */ private String configFeeID; /** * 分类名称 */ private String ruleName; /** * 统计数量 */ private String ststsCount; public String getConfigFeeID() { return configFeeID; } public void setConfigFeeID(String configFeeID) { this.configFeeID = configFeeID; } public String getRuleName() { return ruleName; } public void setRuleName(String ruleName) { this.ruleName = ruleName; } public String getStstsCount() { return ststsCount; } public void setStstsCount(String ststsCount) { this.ststsCount = ststsCount; } }
true
75cffc5a3042f2000a239d7e95b5b97d8e8e748a
Java
markzhang1986/TAR
/src/at/ac/tuwien/infosys/www/pixy/Dumper.java
UTF-8
36,594
2
2
[]
no_license
package at.ac.tuwien.infosys.www.pixy; import at.ac.tuwien.infosys.www.phpparser.ParseNode; import at.ac.tuwien.infosys.www.phpparser.ParseTree; import at.ac.tuwien.infosys.www.pixy.analysis.AbstractAnalysisNode; import at.ac.tuwien.infosys.www.pixy.analysis.AbstractLatticeElement; import at.ac.tuwien.infosys.www.pixy.analysis.LatticeElementBottom; import at.ac.tuwien.infosys.www.pixy.analysis.alias.*; import at.ac.tuwien.infosys.www.pixy.analysis.dependency.DependencyLatticeElement; import at.ac.tuwien.infosys.www.pixy.analysis.dependency.DependencySet; import at.ac.tuwien.infosys.www.pixy.analysis.inclusiondominator.InclusionDominatorAnalysis; import at.ac.tuwien.infosys.www.pixy.analysis.inclusiondominator.InclusionDominatorLatticeElement; import at.ac.tuwien.infosys.www.pixy.analysis.interprocedural.AbstractInterproceduralAnalysis; import at.ac.tuwien.infosys.www.pixy.analysis.interprocedural.AbstractInterproceduralAnalysisNode; import at.ac.tuwien.infosys.www.pixy.analysis.interprocedural.InterproceduralAnalysisInformation; import at.ac.tuwien.infosys.www.pixy.analysis.interprocedural.callstring.EncodedCallStrings; import at.ac.tuwien.infosys.www.pixy.analysis.intraprocedural.IntraproceduralAnalysisNode; import at.ac.tuwien.infosys.www.pixy.analysis.literal.DummyLiteralAnalysis; import at.ac.tuwien.infosys.www.pixy.analysis.literal.LiteralAnalysis; import at.ac.tuwien.infosys.www.pixy.analysis.literal.LiteralLatticeElement; import at.ac.tuwien.infosys.www.pixy.conversion.*; import at.ac.tuwien.infosys.www.pixy.conversion.cfgnodes.*; import java.io.*; import java.util.*; /** * @author Nenad Jovanovic <enji@seclab.tuwien.ac.at> */ public final class Dumper { // auxiliary HashMap: CfgNode -> Integer private static HashMap<AbstractCfgNode, Integer> node2Int; private static int idCounter; static final String linesep = System.getProperty("line.separator"); // ********************************************************************************* // CONSTRUCTORS ******************************************************************** // ********************************************************************************* // since this class is stateless, there is no need to create an instance of it private Dumper() { } // ********************************************************************************* // DOT: ParseTree ****************************************************************** // ********************************************************************************* // dumpDot(ParseTree, String, String) ********************************************** // dumps the parse tree in dot syntax to the directory specified // by "path" and the file specified by "filename" static public void dumpDot(ParseTree parseTree, String path, String filename) { // create directory (new File(path)).mkdir(); try { Writer outWriter = new FileWriter(path + '/' + filename); dumpDot(parseTree, outWriter); outWriter.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } // dumpDot(ParseTree, String, Writer) ********************************************** // dumps the parse tree in dot syntax using the specified Writer static void dumpDot(ParseTree parseTree, Writer outWriter) { try { outWriter.write("digraph parse_tree {\n"); dumpDot(parseTree.getRoot(), outWriter); outWriter.write("}\n"); } catch (Exception e) { System.out.println(e.getMessage()); } } // dumpDot(ParseNode, Writer) ****************************************************** // dumps the subtree starting at the given parse node in dot syntax static void dumpDot(ParseNode parseNode, Writer outWriter) throws java.io.IOException { outWriter.write(" n" + parseNode.getId() + " [label=\""); // print symbol String symbolName = parseNode.getName(); outWriter.write(escapeDot(symbolName, 0)); // print lexeme for token nodes if (parseNode.isToken()) { String lexeme = parseNode.getLexeme(); outWriter.write("\\n"); outWriter.write(escapeDot(lexeme, 10)); } outWriter.write("\"];\n"); // print edge to parent ParseNode parent = parseNode.getParent(); if (parent != null) { outWriter.write(" n" + parent.getId() + " -> n" + parseNode.getId() + ";\n"); } // recursion for (int i = 0; i < parseNode.getChildren().size(); i++) { dumpDot(parseNode.getChild(i), outWriter); } } // ********************************************************************************* // DOT: TacFunction **************************************************************** // ********************************************************************************* // dumpDot(TacFunction, String, boolean) ******************************************* // dumps the function's ControlFlowGraph in dot syntax public static void dumpDot(TacFunction function, String graphPath, boolean dumpParams) { dumpDot(function.getControlFlowGraph(), function.getName(), graphPath); if (dumpParams) { for (TacFormalParameter parameter : function.getParams()) { String paramString = parameter.getVariable().getName(); paramString = paramString.substring(1); // remove "$" if (parameter.hasDefault()) { dumpDot( parameter.getDefaultControlFlowGraph(), function.getName() + "_" + paramString, graphPath); } } } } // dumpDot(ControlFlowGraph, String) ************************************************************ static void dumpDot(ControlFlowGraph controlFlowGraph, String graphName, String graphPath) { dumpDot(controlFlowGraph, graphName, graphPath, graphName + ".dot"); } // dumpDot(ControlFlowGraph, String, String, String) ******************************************** // dumps the ControlFlowGraph in dot syntax to the directory specified by "path" and the // file specified by "filename" public static void dumpDot(ControlFlowGraph controlFlowGraph, String graphName, String path, String filename) { // create directory (new File(path)).mkdir(); try { Writer outWriter = new FileWriter(path + "/" + filename); dumpDot(controlFlowGraph, graphName, outWriter); outWriter.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } // dumpDot(ControlFlowGraph, String, Writer) **************************************************** // dumps the ControlFlowGraph in dot syntax using the specified Writer static void dumpDot(ControlFlowGraph controlFlowGraph, String graphName, Writer outWriter) { try { Dumper.node2Int = new HashMap<>(); Dumper.idCounter = 0; outWriter.write("digraph controlFlowGraph {\n label=\""); outWriter.write(escapeDot(graphName, 0)); outWriter.write("\";\n"); outWriter.write(" labelloc=t;\n"); dumpDot(controlFlowGraph.getHead(), outWriter); outWriter.write("}\n"); } catch (Exception e) { System.out.println(e.getMessage()); } } // dumpDot(CfgNode) **************************************************************** // recursively dumps the CfgNode in dot syntax // and returns the ID that is assigned to this node static int dumpDot(AbstractCfgNode cfgNode, Writer outWriter) throws java.io.IOException { // mark node as visited and store ID int nodeId = Dumper.idCounter; Dumper.node2Int.put(cfgNode, Dumper.idCounter++); // print node String name = makeCfgNodeName(cfgNode); outWriter.write(" n" + nodeId + " [label=\"" + name + "\"];\n"); // handle successors int succId; for (int i = 0; i < 2; i++) { CfgEdge outEdge = cfgNode.getOutEdge(i); if (outEdge != null) { AbstractCfgNode succNode = outEdge.getDestination(); // print successor Integer succIdInt = Dumper.node2Int.get(succNode); if (succIdInt == null) { succId = dumpDot(succNode, outWriter); } else { succId = succIdInt; } // print edge to successor outWriter.write(" n" + nodeId + " -> n" + succId); if (outEdge.getType() != CfgEdge.NORMAL_EDGE) { outWriter.write(" [label=\"" + outEdge.getName() + "\"]"); } outWriter.write(";\n"); } } return nodeId; } // ********************************************************************************* // OTHER *************************************************************************** // ********************************************************************************* // dump(TacFunction) *************************************************************** // dumps function information public static void dump(TacFunction function) { System.out.println("***************************************"); System.out.println("Function " + function.getName()); System.out.println("***************************************"); System.out.println(); if (function.isReference()) { System.out.println("isReference"); } for (TacFormalParameter param : function.getParams()) { String paramString = param.getVariable().getName(); System.out.print("Param: " + paramString); if (param.isReference()) { System.out.print(" (isReference)"); } if (param.hasDefault()) { System.out.print(" (hasDefault)"); } System.out.println(); } } // makeCfgNodeName(CfgNode) ******************************************************** // creates a string representation for the given cfg node public static String makeCfgNodeName(AbstractCfgNode cfgNodeX) { if (cfgNodeX instanceof BasicBlock) { BasicBlock cfgNode = (BasicBlock) cfgNodeX; StringBuilder label = new StringBuilder("basic block\\n"); for (AbstractCfgNode containedNode : cfgNode.getContainedNodes()) { label.append(makeCfgNodeName(containedNode)); label.append("\\n"); } return label.toString(); } else if (cfgNodeX instanceof AssignSimple) { AssignSimple cfgNode = (AssignSimple) cfgNodeX; String leftString = getPlaceString(cfgNode.getLeft()); String rightString = getPlaceString(cfgNode.getRight()); return (leftString + " = " + rightString); } else if (cfgNodeX instanceof AssignBinary) { AssignBinary cfgNode = (AssignBinary) cfgNodeX; String leftString = getPlaceString(cfgNode.getLeft()); String leftOperandString = getPlaceString(cfgNode.getLeftOperand()); String rightOperandString = getPlaceString(cfgNode.getRightOperand()); int op = cfgNode.getOperator(); return ( leftString + " = " + leftOperandString + " " + TacOperators.opToName(op) + " " + rightOperandString); } else if (cfgNodeX instanceof AssignUnary) { AssignUnary cfgNode = (AssignUnary) cfgNodeX; String leftString = getPlaceString(cfgNode.getLeft()); String rightString = getPlaceString(cfgNode.getRight()); int op = cfgNode.getOperator(); return ( leftString + " = " + " " + TacOperators.opToName(op) + " " + rightString); } else if (cfgNodeX instanceof AssignReference) { AssignReference cfgNode = (AssignReference) cfgNodeX; String leftString = getPlaceString(cfgNode.getLeft()); String rightString = getPlaceString(cfgNode.getRight()); return (leftString + " =& " + rightString); } else if (cfgNodeX instanceof If) { If cfgNode = (If) cfgNodeX; String leftOperandString = getPlaceString(cfgNode.getLeftOperand()); String rightOperandString = getPlaceString(cfgNode.getRightOperand()); int op = cfgNode.getOperator(); return ( "if " + leftOperandString + " " + TacOperators.opToName(op) + " " + rightOperandString); } else if (cfgNodeX instanceof Empty) { return ";"; } else if (cfgNodeX instanceof CfgEntry) { return "entry"; } else if (cfgNodeX instanceof CfgExit) { CfgExit cfgNode = (CfgExit) cfgNodeX; return "exit " + cfgNode.getEnclosingFunction().getName(); } else if (cfgNodeX instanceof Call) { Call cfgNode = (Call) cfgNodeX; String objectString = ""; Variable object = cfgNode.getObject(); if (object != null) { objectString = object + "->"; } return (objectString + cfgNode.getFunctionNamePlace().toString() + "(...)"); } else if (cfgNodeX instanceof CallPreparation) { CallPreparation cfgNode = (CallPreparation) cfgNodeX; // construct parameter list StringBuilder paramListStringBuf = new StringBuilder(); for (Iterator<TacActualParameter> iter = cfgNode.getParamList().iterator(); iter.hasNext(); ) { TacActualParameter param = iter.next(); if (param.isReference()) { paramListStringBuf.append("&"); } paramListStringBuf.append(getPlaceString(param.getPlace())); if (iter.hasNext()) { paramListStringBuf.append(", "); } } return ( "prepare " + cfgNode.getFunctionNamePlace().toString() + "(" + paramListStringBuf.toString() + ")"); } else if (cfgNodeX instanceof CallReturn) { CallReturn cfgNode = (CallReturn) cfgNodeX; return ("call-return (" + cfgNode.getTempVar() + ")"); } else if (cfgNodeX instanceof CallBuiltinFunction) { CallBuiltinFunction cfgNode = (CallBuiltinFunction) cfgNodeX; // construct parameter list StringBuilder paramListStringBuf = new StringBuilder(); for (Iterator<TacActualParameter> iter = cfgNode.getParamList().iterator(); iter.hasNext(); ) { TacActualParameter param = iter.next(); if (param.isReference()) { paramListStringBuf.append("&"); } paramListStringBuf.append(getPlaceString(param.getPlace())); if (iter.hasNext()) { paramListStringBuf.append(", "); } } return ( cfgNode.getFunctionName() + "(" + paramListStringBuf.toString() + ") " + "<" + getPlaceString(cfgNode.getTempVar()) + ">"); } else if (cfgNodeX instanceof CallUnknownFunction) { CallUnknownFunction cfgNode = (CallUnknownFunction) cfgNodeX; // construct parameter list StringBuilder paramListStringBuf = new StringBuilder(); for (Iterator<TacActualParameter> iter = cfgNode.getParamList().iterator(); iter.hasNext(); ) { TacActualParameter param = iter.next(); if (param.isReference()) { paramListStringBuf.append("&"); } paramListStringBuf.append(getPlaceString(param.getPlace())); if (iter.hasNext()) { paramListStringBuf.append(", "); } } return ("UNKNOWN: " + cfgNode.getFunctionName() + "(" + paramListStringBuf.toString() + ") " + "<" + getPlaceString(cfgNode.getTempVar()) + ">"); } else if (cfgNodeX instanceof AssignArray) { AssignArray cfgNode = (AssignArray) cfgNodeX; String leftString = getPlaceString(cfgNode.getLeft()); return (leftString + " = array()"); } else if (cfgNodeX instanceof Unset) { Unset cfgNode = (Unset) cfgNodeX; String unsetMe = cfgNode.getOperand().getVariable().toString(); return ("unset(" + unsetMe + ")"); } else if (cfgNodeX instanceof Echo) { Echo cfgNode = (Echo) cfgNodeX; String echoMe = getPlaceString(cfgNode.getPlace()); return ("echo(" + echoMe + ")"); } else if (cfgNodeX instanceof Global) { Global cfgNode = (Global) cfgNodeX; String globMe = cfgNode.getOperand().toString(); return ("global " + globMe); } else if (cfgNodeX instanceof Static) { Static cfgNode = (Static) cfgNodeX; String statMe = cfgNode.getOperand().getVariable().toString(); String initial; if (cfgNode.hasInitialPlace()) { initial = " = " + getPlaceString(cfgNode.getInitialPlace()); } else { initial = ""; } return ("static " + statMe + initial); } else if (cfgNodeX instanceof Isset) { Isset cfgNode = (Isset) cfgNodeX; String checkMe = cfgNode.getRight().getVariable().toString(); String leftString = cfgNode.getLeft().getVariable().toString(); return (leftString + " = " + "isset(" + checkMe + ")"); } else if (cfgNodeX instanceof EmptyTest) { EmptyTest cfgNode = (EmptyTest) cfgNodeX; String checkMe = cfgNode.getRight().getVariable().toString(); String leftString = cfgNode.getLeft().getVariable().toString(); return (leftString + " = " + "empty(" + checkMe + ")"); } else if (cfgNodeX instanceof Eval) { Eval cfgNode = (Eval) cfgNodeX; String evalMe = cfgNode.getRight().getVariable().toString(); String leftString = cfgNode.getLeft().getVariable().toString(); return (leftString + " = " + "eval(" + evalMe + ")"); } else if (cfgNodeX instanceof Define) { Define cfgNode = (Define) cfgNodeX; return ("define(" + cfgNode.getSetMe() + ", " + cfgNode.getSetTo() + ", " + cfgNode.getCaseInsensitive() + ")"); } else if (cfgNodeX instanceof Include) { Include cfgNode = (Include) cfgNodeX; String leftString = getPlaceString(cfgNode.getTemp()); String rightString = getPlaceString(cfgNode.getIncludeMe()); return (leftString + " = include " + rightString); } else if (cfgNodeX instanceof IncludeStart) { return ("incStart"); } else if (cfgNodeX instanceof IncludeEnd) { return ("incEnd"); } else { return "to-do: " + cfgNodeX.getClass(); } } // getPlaceString ****************************************************************** static String getPlaceString(AbstractTacPlace place) { if (place.isVariable()) { return place.toString(); } else if (place.isConstant()) { return place.toString(); } else { return escapeDot(place.toString(), 20); } } // escapeDot *********************************************************************** // escapes special characters in the given string, making it suitable for // dot output; if the string's length exceeds the given limit, "..." is // returned static public String escapeDot(String escapeMe, int limit) { if (limit > 0 && escapeMe.length() > limit) { return "..."; } StringBuilder escaped = new StringBuilder(escapeMe); for (int i = 0; i < escaped.length(); i++) { char inspectMe = escaped.charAt(i); if (inspectMe == '\n' || inspectMe == '\r') { // delete these control characters escaped.deleteCharAt(i); i--; } else if (inspectMe == '"' || inspectMe == '\\') { // escape this character by prefixing it with a backslash escaped.insert(i, '\\'); i++; } } return escaped.toString(); } // dump(ParseTree) ***************************************************************** // dumps the parse tree static void dump(ParseTree parseTree) { recursiveDump(parseTree.getRoot(), 0); } // dump(ParseNode) ***************************************************************** // dumps only the current parse node static public void dump(ParseNode parseNode, int level) { StringBuilder buf = new StringBuilder(level); for (int i = 0; i < level; i++) { buf.append(" "); } String spaces = buf.toString(); System.out.print(spaces + "Sym: " + parseNode.getSymbol() + ", Name: " + parseNode.getName()); if (parseNode.getLexeme() != null) { System.out.print(", Lex: " + parseNode.getLexeme() + ", lineno: " + parseNode.getLineno()); } System.out.println(); } // recursiveDump ******************************************************************* // dumps the subtree starting at the current parse node static public void recursiveDump(ParseNode parseNode, int level) { dump(parseNode, level); for (ParseNode child : parseNode.getChildren()) { recursiveDump(child, level + 1); } } // dump(SymbolTable) *************************************************************** static public void dump(SymbolTable symbolTable, String name) { System.out.println("***************************************"); System.out.println("Symbol Table: " + name); System.out.println("***************************************"); System.out.println(); for (Variable variable : symbolTable.getVariables().values()) { dump(variable); System.out.println(); } } // dump(Variable) ****************************************************************** static public void dump(Variable variable) { System.out.println(variable); // if it is an array if (variable.isArray()) { System.out.println("isArray: true"); List<Variable> elements = variable.getElements(); if (!elements.isEmpty()) { System.out.print("elements: "); for (Variable element : elements) { System.out.print(element.getName() + " "); } System.out.println(); } } // if it is an array element if (variable.isArrayElement()) { System.out.println("isArrayElement: true"); System.out.println("enclosingArray: " + variable.getEnclosingArray().getName()); System.out.println("topEnclosingArray: " + variable.getTopEnclosingArray().getName()); AbstractTacPlace indexPlace = variable.getIndex(); System.out.print("index type: "); if (indexPlace.isLiteral()) { System.out.println("literal"); } else if (indexPlace.isVariable()) { System.out.println("variable"); } else if (indexPlace.isConstant()) { System.out.println("constant"); } else { System.out.println("UNKNOWN!"); } System.out.print("indices: "); for (AbstractTacPlace index : variable.getIndices()) { System.out.print(index + " "); } System.out.println(); } // if it is a variable variable AbstractTacPlace depPlace = variable.getDependsOn(); if (depPlace != null) { System.out.println("dependsOn: " + depPlace.toString()); } // print array elements indexed by this variable List<Variable> indexFor = variable.getIndexFor(); if (!indexFor.isEmpty()) { System.out.print("indexFor: "); for (Variable indexed : indexFor) { System.out.print(indexed + " "); } System.out.println(); } } // dump(ConstantsTable) ************************************************************ static public void dump(ConstantsTable constantsTable) { System.out.println("***************************************"); System.out.println("Constants Table "); System.out.println("***************************************"); System.out.println(); for (Constant constant : constantsTable.getConstants().values()) { System.out.println(constant.getLabel()); } System.out.println(); System.out.println("Insensitive Groups:"); System.out.println(); for (List<Constant> insensitiveGroup : constantsTable.getInsensitiveGroups().values()) { System.out.print("* "); for (Constant anInsensitiveGroup : insensitiveGroup) { System.out.print(anInsensitiveGroup.getLabel() + " "); } System.out.println(); } System.out.println(); } static public void dump(InclusionDominatorAnalysis analysis) { for (Map.Entry<AbstractCfgNode, AbstractAnalysisNode> entry : analysis.getAnalysisInfo().getMap().entrySet()) { AbstractCfgNode cfgNode = entry.getKey(); IntraproceduralAnalysisNode analysisNode = (IntraproceduralAnalysisNode) entry.getValue(); System.out.println("dominators for cfg node " + cfgNode.toString() + ", " + cfgNode.getOriginalLineNumber()); Dumper.dump(analysisNode.getInValue()); } } static public void dump(AbstractInterproceduralAnalysis analysis, String path, String filename) { // create directory (new File(path)).mkdir(); try { Writer writer = new FileWriter(path + '/' + filename); // nothing to do for dummy analysis if (analysis instanceof DummyLiteralAnalysis || analysis instanceof DummyAliasAnalysis) { writer.write("Dummy Analysis" + linesep); writer.close(); return; } List<TacFunction> functions = analysis.getFunctions(); InterproceduralAnalysisInformation analysisInfoNew = analysis.getInterproceduralAnalysisInformation(); if (analysis instanceof LiteralAnalysis) { writer.write(linesep + "Default Lattice Element:" + linesep + linesep); dump(LiteralLatticeElement.DEFAULT, writer); } // for each function... for (TacFunction function : functions) { ControlFlowGraph controlFlowGraph = function.getControlFlowGraph(); writer.write(linesep + "****************************************************" + linesep); writer.write(function.getName() + linesep); writer.write("****************************************************" + linesep + linesep); // for each ControlFlowGraph node... for (Iterator<AbstractCfgNode> bft = controlFlowGraph.bfIterator(); bft.hasNext(); ) { AbstractCfgNode cfgNode = bft.next(); writer.write("----------------------------------------" + linesep); writer.write(cfgNode.getFileName() + ", " + cfgNode.getOriginalLineNumber() + ", " + makeCfgNodeName(cfgNode) + linesep); dump(analysisInfoNew.getAnalysisNode(cfgNode).getRecycledFoldedValue(), writer); } writer.write("----------------------------------------" + linesep); } writer.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } // dump(AnalysisNode) ************************************************************** static public void dump(AbstractInterproceduralAnalysisNode node) { System.out.print("Transfer Function: "); try { System.out.println(node.getTransferFunction().getClass().getName()); } catch (NullPointerException e) { System.out.println("<<null>>"); } // dump the lattice element for each context for (AbstractLatticeElement element : node.getPhi().values()) { System.out.println("~~~~~~~~~~~~~~~"); dump(element); } } static public void dump(AbstractLatticeElement elementX) { try { Writer writer = new OutputStreamWriter(System.out); dump(elementX, writer); writer.flush(); } catch (IOException e) { throw new RuntimeException("SNH:" + e.getStackTrace()); } } // dump(LatticeElement) ************************************************************ static public void dump(AbstractLatticeElement elementX, Writer writer) throws IOException { if (elementX instanceof AliasLatticeElement) { AliasLatticeElement element = (AliasLatticeElement) elementX; dump(element.getMustAliases(), writer); dump(element.getMayAliases(), writer); } else if (elementX instanceof LiteralLatticeElement) { LiteralLatticeElement element = (LiteralLatticeElement) elementX; // dump non-default literal mappings for (Map.Entry<AbstractTacPlace, Literal> entry : element.getPlaceToLit().entrySet()) { AbstractTacPlace place = entry.getKey(); Literal lit = entry.getValue(); writer.write(place + ": " + lit + linesep); } } else if (elementX instanceof DependencyLatticeElement) { dumpComplete((DependencyLatticeElement) elementX, writer); } else if (elementX instanceof InclusionDominatorLatticeElement) { InclusionDominatorLatticeElement element = (InclusionDominatorLatticeElement) elementX; List<AbstractCfgNode> dominators = element.getDominators(); if (dominators.isEmpty()) { System.out.println("<<empty>>"); } else { for (AbstractCfgNode dominator : dominators) { System.out.println(dominator.toString() + ", " + dominator.getOriginalLineNumber()); } } } else if (elementX instanceof LatticeElementBottom) { writer.write(linesep + "Bottom Element" + linesep + linesep); } else if (elementX == null) { writer.write(linesep + "<<null>>" + linesep + linesep); } else { throw new RuntimeException("SNH: " + elementX.getClass()); } writer.flush(); } // returns true if this variable should not be dumped, because it is a // - temporary // - shadow // - variable of a builtin function private static boolean doNotDump(Variable var) { // EFF: "endsWith" technique not too elegant; might also lead // to "rootkit effects"...; alternative would be: save additional // field for variables return var.isTemp() || var.getName().endsWith(InternalStrings.gShadowSuffix) || var.getName().endsWith(InternalStrings.gShadowSuffix) || BuiltinFunctions.isBuiltinFunction(var.getSymbolTable().getName()); } // ******************************************************************************** static public void dumpComplete(DependencyLatticeElement element, Writer writer) throws IOException { // dump non-default dependency mappings writer.write(linesep + "DEP MAPPINGS" + linesep + linesep); for (Map.Entry<AbstractTacPlace, DependencySet> entry : element.getPlaceToDep().entrySet()) { AbstractTacPlace place = entry.getKey(); DependencySet dependencySet = entry.getValue(); writer.write(place + ": " + dependencySet + linesep); } // dump non-default array labels writer.write(linesep + "ARRAY LABELS" + linesep + linesep); for (Map.Entry<Variable, DependencySet> entry : element.getArrayLabels().entrySet()) { Variable var = entry.getKey(); DependencySet arrayLabel = entry.getValue(); writer.write(var + ": " + arrayLabel + linesep); } } static public void dump(DependencyLatticeElement element) { try { Writer writer = new OutputStreamWriter(System.out); dump(element, writer); writer.flush(); } catch (IOException e) { throw new RuntimeException("SNH:" + e.getStackTrace()); } } // like dumpComplete, but only prints // - non-temporaries // - non-shadows // - variables of non-builtin functions static public void dump(DependencyLatticeElement element, Writer writer) throws IOException { // dump non-default taint mappings writer.write(linesep + "TAINT MAPPINGS" + linesep + linesep); for (Map.Entry<AbstractTacPlace, DependencySet> entry : element.getPlaceToDep().entrySet()) { AbstractTacPlace place = entry.getKey(); if (place.isVariable()) { Variable var = place.getVariable(); if (doNotDump(var)) { continue; } } writer.write(place + ": " + entry.getValue() + linesep); } // dump non-default array labels writer.write(linesep + "ARRAY LABELS" + linesep + linesep); for (Map.Entry<Variable, DependencySet> entry : element.getArrayLabels().entrySet()) { Variable variable = entry.getKey(); if (doNotDump(variable)) { continue; } writer.write(variable + ": " + entry.getValue() + linesep); } } static public void dump(MustAliases mustAliases, Writer writer) throws IOException { writer.write("u{ "); for (MustAliasGroup group : mustAliases.getGroups()) { dump(group, writer); writer.write(" "); } writer.write("}" + linesep); } static public void dump(MustAliasGroup mustAliasGroup, Writer writer) throws IOException { writer.write("( "); for (Variable variable : mustAliasGroup.getVariables()) { writer.write(variable + " "); } writer.write(")"); } static public void dump(MayAliases mayAliases, Writer writer) throws IOException { writer.write("a{ "); for (MayAliasPair pair : mayAliases.getPairs()) { dump(pair, writer); writer.write(" "); } writer.write("}" + linesep); } static public void dump(MayAliasPair mayAliasPair, Writer writer) throws IOException { Set<Variable> pair = mayAliasPair.getPair(); Object[] pairArray = pair.toArray(); writer.write("(" + pairArray[0] + " " + pairArray[1] + ")" + linesep); } static public void dumpFunction2ECS(Map<TacFunction, EncodedCallStrings> function2ECS) { for (Map.Entry<TacFunction, EncodedCallStrings> entry : function2ECS.entrySet()) { TacFunction function = entry.getKey(); EncodedCallStrings encodedCallStrings = entry.getValue(); System.out.println("EncodedCallStrings for Function " + function.getName() + ": "); System.out.println(encodedCallStrings); System.out.println(); } } }
true
9f8590ea0dac169600b3af2b8b952f1258e78fbd
Java
fax4ever/eap6-play
/eap6-principal-roles/src/main/java/it/redhat/demo/roles/model/PrincipalInfo.java
UTF-8
725
2.453125
2
[ "Apache-2.0" ]
permissive
package it.redhat.demo.roles.model; import java.util.HashSet; import java.util.Set; /** * Created by fabio.ercoli@redhat.com on 08/06/2017. */ public class PrincipalInfo { private boolean principal = false; private String username; private Set<String> roles; public PrincipalInfo() { } public PrincipalInfo(String username) { this.principal = true; this.username = username; this.roles = new HashSet<>(); } public boolean isPrincipal() { return principal; } public String getUsername() { return username; } public Set<String> getRoles() { return roles; } public void addRole(String role) { roles.add(role); } }
true
3232c1da2617de73ae8fecb393f097aab2bb2d36
Java
IRON-head-CWD/IDEA_coda
/javaDay02/Day02/src/com/itheima/test01/test06/Test.java
UTF-8
238
1.976563
2
[]
no_license
package com.itheima.test01.test06; public class Test { public static void main(String[] args) { smallSize s=new smallSize("3","3","动物类"); s.Animalshow(); s.Sizeshow(); s.smallSizeshow(); } }
true
cf77d6ff2cf03ff0f87fc6df5a8f960273227367
Java
XMUJ2EE/Fifcos
/src/main/java/xmu/crms/service/impl/FixGroupServiceImpl.java
UTF-8
4,395
2.15625
2
[]
no_license
package xmu.crms.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import xmu.crms.dao.impl.FixGroupDaoImpl; import xmu.crms.entity.*; import xmu.crms.exception.*; import xmu.crms.service.ClassService; import xmu.crms.service.FixGroupService; import xmu.crms.service.SeminarService; import xmu.crms.service.UserService; import java.math.BigInteger; import java.util.List; /** * @author zhangchubing */ @Service public class FixGroupServiceImpl implements FixGroupService { @Autowired private FixGroupDaoImpl fixGroupDao; @Autowired private UserService userService; @Autowired private SeminarService seminarService; @Autowired private ClassService classService; @Override public BigInteger insertFixGroupByClassId(FixGroup fixGroup) throws IllegalArgumentException, UserNotFoundException { User user=userService.getUserByUserId(fixGroup.getLeader().getId()); if(user==null) { throw new UserNotFoundException("找不到该id对应的学生"); } fixGroupDao.insertFixGroupByClassId(fixGroup); return fixGroup.getId(); } @Override public void deleteFixGroupMemberByFixGroupId(BigInteger fixGroupId) throws IllegalArgumentException, FixGroupNotFoundException { fixGroupDao.deleteFixGroupMemberByFixGroupId(fixGroupId); } @Override public void deleteFixGroupUserById(BigInteger fixGroupId, BigInteger userId) throws IllegalArgumentException, FixGroupNotFoundException, UserNotFoundException { fixGroupDao.deleteFixGroupUserById(fixGroupId,userId); } @Override public List<User> listFixGroupMemberByGroupId(BigInteger groupId) throws IllegalArgumentException, FixGroupNotFoundException { return fixGroupDao.listFixGroupMemberByGroupId(groupId); } @Override public List<FixGroup> listFixGroupByClassId(BigInteger classId) throws IllegalArgumentException, ClazzNotFoundException { return fixGroupDao.listFixGroupByClassId(classId); } @Override public void deleteFixGroupByClassId(BigInteger classId) throws IllegalArgumentException, ClazzNotFoundException { fixGroupDao.deleteFixGroupByClassId(classId); } @Override public void deleteFixGroupByGroupId(BigInteger groupId) throws IllegalArgumentException, FixGroupNotFoundException { fixGroupDao.deleteFixGroupByGroupId(groupId); } @Override public void updateFixGroupByGroupId(BigInteger groupId, FixGroup fixGroupBO) throws IllegalArgumentException, FixGroupNotFoundException { fixGroupDao.updateFixGroupByGroupId(groupId,fixGroupBO); } @Override public List<FixGroupMember> listFixGroupByGroupId(BigInteger groupId) throws IllegalArgumentException, FixGroupNotFoundException { return fixGroupDao.listFixGroupByGroupId(groupId); } @Override public BigInteger insertStudentIntoGroup(BigInteger userId, BigInteger groupId) throws IllegalArgumentException, FixGroupNotFoundException, UserNotFoundException, ClazzNotFoundException,InvalidOperationException { User user=userService.getUserByUserId(userId); if(user==null) { throw new UserNotFoundException("找不到该id对应的学生"); } return BigInteger.valueOf(fixGroupDao.insertStudentIntoGroup(userId,groupId)); } @Override public FixGroup getFixedGroupById(BigInteger userId, BigInteger classId) throws IllegalArgumentException, ClazzNotFoundException, UserNotFoundException { User user=userService.getUserByUserId(userId); if(user==null){ throw new UserNotFoundException("找不到该id对应的学生"); } ClassInfo classInfo = classService.getClassByClassId(classId); if(classInfo == null){ throw new ClazzNotFoundException("未找到固定小组的班级"); } return fixGroupDao.getFixedGroupById(userId,classId); } @Override public void fixedGroupToSeminarGroup(BigInteger seminarId, BigInteger fixedGroupId) throws IllegalArgumentException, FixGroupNotFoundException, SeminarNotFoundException { Seminar seminar=seminarService.getSeminarBySeminarId(seminarId); if(seminar!=null){ fixGroupDao.fixedGroupToSeminarGroup(seminarId,fixedGroupId); } } }
true
253392580ae1b946a3f127d5bb3bb513d71d2310
Java
jmcabandara/camel
/init/camel-bundle-plugin/src/main/java/org/apache/felix/bundleplugin/PatchedLog.java
UTF-8
3,065
1.945313
2
[ "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.felix.bundleplugin; import org.apache.maven.plugin.logging.Log; /** * Patched logger that is not noisy. */ public class PatchedLog implements Log { private final Log delegate; public PatchedLog(Log delegate) { this.delegate = delegate; } @Override public boolean isDebugEnabled() { return delegate.isDebugEnabled(); } @Override public void debug(CharSequence charSequence) { delegate.debug(charSequence); } @Override public void debug(CharSequence charSequence, Throwable throwable) { delegate.debug(charSequence, throwable); } @Override public void debug(Throwable throwable) { delegate.debug(throwable); } @Override public boolean isInfoEnabled() { return delegate.isInfoEnabled(); } @Override public void info(CharSequence charSequence) { delegate.info(charSequence); } @Override public void info(CharSequence charSequence, Throwable throwable) { delegate.info(charSequence, throwable); } @Override public void info(Throwable throwable) { delegate.info(throwable); } @Override public boolean isWarnEnabled() { return delegate.isWarnEnabled(); } @Override public void warn(CharSequence charSequence) { // skip some unwanted WARN logging String s = charSequence.toString(); if (s.startsWith("Include-Resource: overriding")) { return; } delegate.warn(charSequence); } @Override public void warn(CharSequence charSequence, Throwable throwable) { delegate.warn(charSequence, throwable); } @Override public void warn(Throwable throwable) { delegate.warn(throwable); } @Override public boolean isErrorEnabled() { return delegate.isErrorEnabled(); } @Override public void error(CharSequence charSequence) { delegate.error(charSequence); } @Override public void error(CharSequence charSequence, Throwable throwable) { delegate.error(charSequence, throwable); } @Override public void error(Throwable throwable) { delegate.error(throwable); } }
true
a9511b769e869218e94be6c10be3fff9963ac3db
Java
Hexatan/workspace
/Gestion/src/Compte.java
UTF-8
1,234
2.765625
3
[]
no_license
public class Compte { protected float solde; protected String nom; protected float soldeini; protected Client proprietaire; public Compte() { this.solde = 0; this.soldeini = 0; this.proprietaire = null; } public Compte(float solde, String nom,Client p) { if (solde < 0) { this.solde = 0; this.soldeini = 0; } else { this.solde = solde; this.soldeini = solde; } this.nom = nom; this.proprietaire = p; } public void setNom(String nom) { this.nom = nom; } public void setSoldeini(float soldeini) { this.soldeini = soldeini; } public String getNom() { return nom; } public float getSolde() { return solde; } public void setSolde(float solde) { this.solde = solde; } public float consulte() { return this.solde; } public void crediter(float credit) { if (credit > 0) { this.solde += credit; } } public void debiter(float debit) { if (debit > 0) { this.solde -= debit; } } public String toString() { return this.nom + "|" + this.solde; } public Client getProprietaire() { return proprietaire; } public void setProprietaire(Client proprietaire) { this.proprietaire = proprietaire; } public float getSoldeini() { return soldeini; } }
true
d7b928a5a8ec8825b2e271de0430f49162936c50
Java
zhongxingyu/Seer
/Diff-Raw-Data/10/10_60b0e0d8ae7e951a18aafea61241cf5ec0cc0d34/Main/10_60b0e0d8ae7e951a18aafea61241cf5ec0cc0d34_Main_s.java
UTF-8
14,296
2.15625
2
[]
no_license
package plusone; import plusone.utils.Dataset; import plusone.utils.Indexer; import plusone.utils.KNNGraphDistanceCache; import plusone.utils.KNNSimilarityCache; import plusone.utils.KNNSimilarityCacheLocalSVDish; import plusone.utils.MetadataLogger; import plusone.utils.PaperAbstract; import plusone.utils.PlusoneFileWriter; import plusone.utils.PredictionPaper; import plusone.utils.Terms; import plusone.utils.TrainingPaper; import plusone.utils.LocalSVDish; import java.util.Arrays; import plusone.clustering.Baseline; import plusone.clustering.ClusteringTest; import plusone.clustering.CommonNeighbors; import plusone.clustering.DTRandomWalkPredictor; import plusone.clustering.KNN; import plusone.clustering.KNNLocalSVDish; import plusone.clustering.KNNWithCitation; import plusone.clustering.LSI; //import plusone.clustering.SVDAndKNN; //import plusone.clustering.Lda; //import plusone.clustering.KNNRandomWalkPredictor; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Random; import java.util.Set; public class Main { private final static int nTrialsPerPaper = 12; private Indexer<String> wordIndexer; private Indexer<PaperAbstract> paperIndexer; private Terms terms; private KNNSimilarityCache knnSimilarityCache; private KNNGraphDistanceCache knnGraphDistanceCache; private static MetadataLogger metadataLogger; private static Random randGen; // Document sets public List<TrainingPaper> trainingSet; public List<PredictionPaper> testingSet; // Clustering Methods private Baseline baseline; private CommonNeighbors cn; private DTRandomWalkPredictor dtRWPredictor; private KNN knn; private KNNWithCitation knnc; private LSI lsi; //private SVDAndKNN svdKnn; //private KNNRandomWalkPredictor knnRWPredictor; public Main(long randomSeed) { randGen = new Random(randomSeed); metadataLogger = new MetadataLogger(); } public void load_data(String filename, double trainPercent) { Dataset dataset = Dataset.loadDatasetFromPath(filename); wordIndexer = dataset.getWordIndexer(); paperIndexer = dataset.getPaperIndexer(); splitByTrainPercent(trainPercent, dataset.getDocuments()); } /** * Splits all the documents into training and testing papers. * This function must be called before we can do execute any * clustering methods. */ private void splitByTrainPercent(double trainPercent, List<PaperAbstract> documents) { Random randGen = Main.getRandomGenerator(); trainingSet = new ArrayList<TrainingPaper>(); testingSet = new ArrayList<PredictionPaper>(); for (int i = 0; i < documents.size(); i ++) { if (randGen.nextDouble() < trainPercent) trainingSet.add((TrainingPaper)documents.get(i)); else testingSet.add((PredictionPaper)documents.get(i)); } System.out.println("trainingSet size: " + trainingSet.size()); System.out.println("testingSet size: " + testingSet.size()); } public void splitHeldoutWords(double testWordPercent) { Terms.Term[] terms = new Terms.Term[wordIndexer.size()]; for (int i = 0; i < wordIndexer.size(); i++) { terms[i] = new Terms.Term(i); } for (TrainingPaper a : trainingSet){ ((PaperAbstract)a).generateTf(testWordPercent, terms, false); } for (PredictionPaper a : testingSet){ ((PaperAbstract)a).generateTf(testWordPercent, null, true); } /* terms_sorted = new Term[terms.length]; for (int c = 0; c < terms.length; c ++) { terms_sorted[c] = terms[c]; } Arrays.sort(terms_sorted); */ this.terms = new Terms(terms); if (testIsEnabled("knn") || testIsEnabled("knnc")) knnSimilarityCache = new KNNSimilarityCache(trainingSet, testingSet); if (testIsEnabled("knnc")) knnGraphDistanceCache = new KNNGraphDistanceCache(trainingSet, testingSet, paperIndexer); } public static Random getRandomGenerator() { return randGen; } public static MetadataLogger getMetadataLogger() { return metadataLogger; } public double[] evaluate(PredictionPaper testingPaper, Integer[] prediction, int size, int k) { int predicted = 0, total = 0; double tfidfScore = 0.0, idfScore = 0.0, idf_top = Math.log(size); Set<Integer> givenWords = testingPaper.getTrainingWords(); Set<Integer> predictionWords = ((PaperAbstract)testingPaper). getTestingWords(); for (int j = 0; j < prediction.length && j < k; j ++) { Integer word = prediction[j]; if (predictionWords.contains(word)) { predicted ++; double logVal = Math.log(terms.get(word).idfRaw() + 1.0); tfidfScore += ((PaperAbstract)testingPaper). getTestingTf(word) * (idf_top - logVal); idfScore += (idf_top - logVal); } } /* FIXME: We probably should divide by k here, rather than the total * number of predictions made; otherwise we reward methods that make * less predictions. -James */ return new double[]{(double)predicted, idfScore, tfidfScore, (double)prediction.length}; } public static void printResults(double[] results) { System.out.println("Predicted: " + results[0]); System.out.println("idf score: " + results[1]); System.out.println("tfidf score: " + results[2]); } public static void printResults(File output, double[] results) { PlusoneFileWriter writer = new PlusoneFileWriter(output); writer.write("Predicted: " + results[0] + "\n"); writer.write("idf score: " + results[1] + "\n"); writer.write("tfidf score: " + results[2] + "\n"); writer.close(); } public void runClusteringMethods(File outputDir, int[] ks) { int size = trainingSet.size() + testingSet.size(); if (testIsEnabled("baseline")) { baseline = new Baseline(trainingSet, terms); runClusteringMethod(testingSet, baseline, outputDir, ks, size); } if (testIsEnabled("dtrw")) { int rwLength = Integer.getInteger("plusone.dtrw.walkLength", 4); boolean stoch = Boolean.getBoolean("plusone.dtrw.stochastic"); int nSampleWalks = Integer.getInteger("plusone.dtrw.nSampleWalks"); System.out.println("Random walk length: " + rwLength); if (stoch) System.out.println("Stochastic random walk: " + nSampleWalks + " samples."); boolean finalIdf = Boolean.getBoolean("plusone.dtrw.finalIdf"); boolean ndiw = Boolean.getBoolean("plusone.dtrw.normalizeDocsInWord"); Boolean nwid = Boolean.getBoolean("plusone.dtrw.normalizeWordsInDoc"); dtRWPredictor = new DTRandomWalkPredictor(trainingSet, terms, rwLength, stoch, nSampleWalks, finalIdf, nwid, ndiw); runClusteringMethod(testingSet, dtRWPredictor, outputDir, ks, size); } int[] closest_k = parseIntList(System.getProperty("plusone.closestKValues", "1,3,5,10,25,50,100,250,500,1000")); int[] closest_k_svdish = parseIntList(System.getProperty("plusone.closestKSVDishValues", "1,3,5,10,25,50,100,250,500,1000")); KNNSimilarityCacheLocalSVDish KNNSVDcache = null; LocalSVDish localSVD; KNNLocalSVDish knnSVD; if (testIsEnabled("svdishknn")){ int[] TODOpar = {50, 50, 50}; localSVD=new LocalSVDish(Integer.getInteger("plusone.svdishknn.nLevels"), parseIntList(System.getProperty("plusone.svdishknn.docEnzs")), parseIntList(System.getProperty("plusone.svdishknn.termEnzs")), parseIntList(System.getProperty("plusone.svdishknn.dtNs")), parseIntList(System.getProperty("plusone.svdishknn.tdNs")), parseIntList(System.getProperty("plusone.svdishknn.numLVecs")), trainingSet,terms.size()); KNNSVDcache = new KNNSimilarityCacheLocalSVDish(trainingSet,testingSet,localSVD); } for (int ck = 0; ck < closest_k.length; ck ++) { if (testIsEnabled("knn")) { knn = new KNN(closest_k[ck], trainingSet, paperIndexer, terms, knnSimilarityCache); runClusteringMethod(testingSet, knn, outputDir, ks, size); } if (testIsEnabled("knnc")) { knnc = new KNNWithCitation(closest_k[ck], trainingSet, paperIndexer, knnSimilarityCache, knnGraphDistanceCache, terms); runClusteringMethod(testingSet, knnc, outputDir, ks, size); } /* if (testIsEnabled("cn")) { cn = new CommonNeighbors(closest_k[ck], trainingSet, paperIndexer, knnSimilarityCache, knnGraphDistanceCache, terms); runClusteringMethod(testingSet, cn, outputDir, ks, size); } if (testIsEnabled("svdknn")) { svdKnn = new SVDAndKNN(closest_k[ck], trainingSet); runClusteringMethod(testingSet, knnc, outputDir, ks, size); } if (testIsEnabled("knnrw")) { knnRWPredictor = new KNNRandomWalkPredictor(closest_k[ck], trainingSet, wordIndexer, paperIndexer, 1, 0.5, 1); runClusteringMethod(trainingSet, testingSet, knnRWPredictor, outputDir, ks, usedWord); }*/ } for (int ck = 0; ck < closest_k_svdish.length; ck ++) { if (testIsEnabled("svdishknn")){ knnSVD= new KNNLocalSVDish(closest_k_svdish[ck],trainingSet, paperIndexer, terms, KNNSVDcache); runClusteringMethod(testingSet,knnSVD,outputDir,ks,size); } } int[] dimensions = parseIntList(System.getProperty("plusone.svdDimensions", "1,5,10,20")); for (int dk = 0; dk < dimensions.length; dk ++) { if (testIsEnabled("lsi")) { lsi = new LSI(dimensions[dk], trainingSet, terms); runClusteringMethod(testingSet, lsi, outputDir, ks, size); } } } public void runClusteringMethod(List<PredictionPaper> testingSet, ClusteringTest test, File outputDir, int[] ks, int size) { long t1 = System.currentTimeMillis(); System.out.println("[" + test.testName + "] starting test" ); for (int ki = 0; ki < ks.length; ki ++) { int k = ks[ki]; File kDir = null; try { kDir = new File(outputDir, k + ""); if (!kDir.exists()) kDir.mkdir(); } catch(Exception e) { e.printStackTrace(); } double[] results = {0.0, 0.0, 0.0, 0.0}; MetadataLogger.TestMetadata meta = getMetadataLogger().getTestMetadata("k=" + k + test.testName); test.addMetadata(meta); List<Double> predictionScores = new ArrayList<Double>(); for (PredictionPaper testingPaper : testingSet) { double [] thisPaperResults = {0.0, 0.0, 0.0, 0.0}; for (int i = 0; i < nTrialsPerPaper; ++i) { Integer[] predict = test.predict(k, testingPaper); double[] result = evaluate(testingPaper, predict, size, k); for (int j = 0; j < 4; ++j) thisPaperResults[j] += result[j]; } for (int j = 0; j < 4; ++j) results[j] += thisPaperResults[j]; predictionScores.add(thisPaperResults[0]); } meta.createListValueEntry("predictionScore", predictionScores.toArray()); meta.createSingleValueEntry("numPredict", k); File out = new File(kDir, test.testName + ".out"); Main.printResults(out, new double[]{results[0]/results[3], results[1], results[2]}); } System.out.println("[" + test.testName + "] took " + (System.currentTimeMillis() - t1) / 1000.0 + " seconds."); } static double[] parseDoubleList(String s) { String[] tokens = s.split(","); double[] ret = new double[tokens.length]; for (int i = 0; i < tokens.length; ++ i) { ret[i] = Double.valueOf(tokens[i]); } return ret; } static int[] parseIntList(String s) { String[] tokens = s.split(","); int[] ret = new int[tokens.length]; for (int i = 0; i < tokens.length; ++ i) { ret[i] = Integer.valueOf(tokens[i]); } return ret; } static Boolean testIsEnabled(String testName) { return Boolean.getBoolean("plusone.enableTest." + testName); } /* * data - args[0] * train percent - args[1] * test word percent - args[2] (currently ignored) */ public static void main(String[] args) { String data_file = System.getProperty("plusone.dataFile", ""); if (!new File(data_file).exists()) { System.out.println("Data file does not exist."); System.exit(0); } long randSeed = new Long(System.getProperty("plusone.randomSeed", "0")); Main main = new Main(randSeed); double trainPercent = new Double (System.getProperty("plusone.trainPercent", "0.95")); String experimentPath = System.getProperty("plusone.outPath", "experiment"); main.load_data(data_file, trainPercent); System.out.println("data file " + data_file); System.out.println("train percent " + trainPercent); //System.out.println("test word percent " + testWordPercent); /* These values can be set on the command line. For example, to set * testWordPercents to {0.4,0.5}, pass the command-line argument * -Dplusone.testWordPercents=0.4,0.5 to java (before the class name) */ double[] testWordPercents = parseDoubleList(System.getProperty("plusone.testWordPercents", "0.1,0.3,0.5,0.7,0.9")); int[] ks = parseIntList(System.getProperty("plusone.kValues", "1,5,10,15,20")); for (int twp = 0; twp < testWordPercents.length; twp++) { double testWordPercent = testWordPercents[twp]; File twpDir = null; try { twpDir = new File(new File(experimentPath), testWordPercent + ""); twpDir.mkdir(); } catch(Exception e) { e.printStackTrace(); } main.splitHeldoutWords(testWordPercent); System.out.println("processing testwordpercent: " + testWordPercent); main.runClusteringMethods(twpDir, ks); } if (Boolean.getBoolean("plusone.dumpMeta")) { PlusoneFileWriter writer = new PlusoneFileWriter(new File(new File(experimentPath), "metadata")); writer.write("var v = "); writer.write(Main.getMetadataLogger().getJson()); writer.close(); } } }
true
48a558f55d6f45e14caf427945fa6e7f4bd197e8
Java
sxysxys/JAVASE_Study
/ThinkinJava/src/test/InnerTest.java
UTF-8
310
2.140625
2
[]
no_license
package test; import innerclass.Test1; /** * @Author: shenge * @Date: 2020-04-02 00:24 * 测试内部类不同包下的访问。 */ public class InnerTest { public static void main(String[] args) { // Test1.Test1_1 test1 = new Test1.Test1_1(); // Test1.Test1_1 xx = test1.xx(); } }
true
7c80933721ed0e4eb744c2c07c25134fc5001cf4
Java
xSke/CoreServer
/src/org/apache/http/impl/nio/reactor/DefaultConnectingIOReactor.java
UTF-8
8,363
1.898438
2
[]
no_license
/* * Decompiled with CFR 0_129. */ package org.apache.http.impl.nio.reactor; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ThreadFactory; import org.apache.http.annotation.ThreadSafe; import org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor; import org.apache.http.impl.nio.reactor.ChannelEntry; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.impl.nio.reactor.SessionRequestHandle; import org.apache.http.impl.nio.reactor.SessionRequestImpl; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.params.HttpParams; import org.apache.http.util.Asserts; /* * This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6. */ @ThreadSafe public class DefaultConnectingIOReactor extends AbstractMultiworkerIOReactor implements ConnectingIOReactor { private final Queue<SessionRequestImpl> requestQueue = new ConcurrentLinkedQueue<SessionRequestImpl>(); private long lastTimeoutCheck = System.currentTimeMillis(); public DefaultConnectingIOReactor(IOReactorConfig config, ThreadFactory threadFactory) throws IOReactorException { super(config, threadFactory); } public DefaultConnectingIOReactor(IOReactorConfig config) throws IOReactorException { this(config, null); } public DefaultConnectingIOReactor() throws IOReactorException { this(null, null); } @Deprecated public DefaultConnectingIOReactor(int workerCount, ThreadFactory threadFactory, HttpParams params) throws IOReactorException { this(DefaultConnectingIOReactor.convert(workerCount, params), threadFactory); } @Deprecated public DefaultConnectingIOReactor(int workerCount, HttpParams params) throws IOReactorException { this(DefaultConnectingIOReactor.convert(workerCount, params), null); } @Override protected void cancelRequests() throws IOReactorException { SessionRequestImpl request; while ((request = this.requestQueue.poll()) != null) { request.cancel(); } } @Override protected void processEvents(int readyCount) throws IOReactorException { long currentTime; this.processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (SelectionKey key : selectedKeys) { this.processEvent(key); } selectedKeys.clear(); } if ((currentTime = System.currentTimeMillis()) - this.lastTimeoutCheck >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); this.processTimeouts(keys); } } private void processEvent(SelectionKey key) { block8 : { try { if (!key.isConnectable()) break block8; SocketChannel channel = (SocketChannel)key.channel(); SessionRequestHandle requestHandle = (SessionRequestHandle)key.attachment(); SessionRequestImpl sessionRequest = requestHandle.getSessionRequest(); try { channel.finishConnect(); } catch (IOException ex) { sessionRequest.failed(ex); } key.cancel(); key.attach(null); if (!sessionRequest.isCompleted()) { this.addChannel(new ChannelEntry(channel, sessionRequest)); } else { try { channel.close(); } catch (IOException ignore) {} } } catch (CancelledKeyException ex) { SessionRequestImpl sessionRequest; SessionRequestHandle requestHandle = (SessionRequestHandle)key.attachment(); key.attach(null); if (requestHandle == null || (sessionRequest = requestHandle.getSessionRequest()) == null) break block8; sessionRequest.cancel(); } } } private void processTimeouts(Set<SelectionKey> keys) { long now = System.currentTimeMillis(); for (SelectionKey key : keys) { int timeout; SessionRequestHandle handle; SessionRequestImpl sessionRequest; Object attachment = key.attachment(); if (!(attachment instanceof SessionRequestHandle) || (timeout = (sessionRequest = (handle = (SessionRequestHandle)key.attachment()).getSessionRequest()).getConnectTimeout()) <= 0 || handle.getRequestTime() + (long)timeout >= now) continue; sessionRequest.timeout(); } } @Override public SessionRequest connect(SocketAddress remoteAddress, SocketAddress localAddress, Object attachment, SessionRequestCallback callback) { Asserts.check(this.status.compareTo(IOReactorStatus.ACTIVE) <= 0, "I/O reactor has been shut down"); SessionRequestImpl sessionRequest = new SessionRequestImpl(remoteAddress, localAddress, attachment, callback); sessionRequest.setConnectTimeout(this.config.getConnectTimeout()); this.requestQueue.add(sessionRequest); this.selector.wakeup(); return sessionRequest; } private void validateAddress(SocketAddress address) throws UnknownHostException { InetSocketAddress endpoint; if (address == null) { return; } if (address instanceof InetSocketAddress && (endpoint = (InetSocketAddress)address).isUnresolved()) { throw new UnknownHostException(endpoint.getHostName()); } } private void processSessionRequests() throws IOReactorException { SessionRequestImpl request; while ((request = this.requestQueue.poll()) != null) { SocketChannel socketChannel; if (request.isCompleted()) continue; try { socketChannel = SocketChannel.open(); } catch (IOException ex) { throw new IOReactorException("Failure opening socket", ex); } try { socketChannel.configureBlocking(false); this.validateAddress(request.getLocalAddress()); this.validateAddress(request.getRemoteAddress()); if (request.getLocalAddress() != null) { Socket sock = socketChannel.socket(); sock.setReuseAddress(this.config.isSoReuseAddress()); sock.bind(request.getLocalAddress()); } this.prepareSocket(socketChannel.socket()); boolean connected = socketChannel.connect(request.getRemoteAddress()); if (connected) { ChannelEntry entry = new ChannelEntry(socketChannel, request); this.addChannel(entry); continue; } } catch (IOException ex) { DefaultConnectingIOReactor.closeChannel(socketChannel); request.failed(ex); return; } SessionRequestHandle requestHandle = new SessionRequestHandle(request); try { SelectionKey key = socketChannel.register(this.selector, 8, requestHandle); request.setKey(key); } catch (IOException ex) { DefaultConnectingIOReactor.closeChannel(socketChannel); throw new IOReactorException("Failure registering channel with the selector", ex); } } } }
true
a28396e06380feb1804eea53c213653fa9266f04
Java
wentjiang/leetcode
/src/test/java/com/wentjiang/leetcode/q1_100/Question20Test.java
UTF-8
936
2.296875
2
[]
no_license
package com.wentjiang.leetcode.q1_100; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * @author wentaojiang * * @date 2019/9/2 1:50 PM * * @description */ public class Question20Test { private Question20 question20; @Before public void setUp() throws Exception { question20 = new Question20(); } @Test public void isValid1() { assertTrue(question20.isValid("()")); } @Test public void isValid2() { assertTrue(question20.isValid("()[]{}")); } @Test public void isValid3() { assertFalse(question20.isValid("(]")); } @Test public void isValid4() { assertFalse(question20.isValid("([)]")); } @Test public void isValid5() { assertTrue(question20.isValid("{[]}")); } @Test public void isValid6() { assertFalse(question20.isValid("[")); } }
true
9eb5725fe66810c52f7116679ec31912f0239871
Java
Jeky/xun
/xuntemplate/src/main/java/org/xun/xuntemplate/ast/IntNodeFactory.java
UTF-8
720
2.625
3
[]
no_license
package org.xun.xuntemplate.ast; import java.util.LinkedList; import org.xun.xuntemplate.ASTNode; import org.xun.xuntemplate.EvalFunc; import org.xun.xuntemplate.RenderContext; import org.xun.xuntemplate.Type; /** * * @author Jeky */ public class IntNodeFactory extends ASTNodeFactory { @Override public ASTNode build(LinkedList<ASTNode> nodes) { ASTNode node = nodes.pollFirst(); node.setType(Type.INT); final int value = Integer.parseInt(node.getValue()); node.setEvalFunc(new EvalFunc() { @Override public Object eval(RenderContext context, ASTNode current) { return value; } }); return node; } }
true
f3e1e5dad0eb785c3f5426946d1c5ede2d7daf5a
Java
tianshouzhi/netty_tutorial
/netty/handler/src/main/java/com/tianshouzhi/handler/idle/HeartbeatServerHandler.java
UTF-8
1,384
2.671875
3
[]
no_license
package com.tianshouzhi.handler.idle; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import java.util.Date; /** * Created by tianshouzhi on 2018/4/22. */ public class HeartbeatServerHandler extends ChannelInboundHandlerAdapter { private int heartbeatCount = 0; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if ("PING".equals(msg)) { ByteBuf response = Unpooled.buffer(); response.writeBytes(Unpooled.buffer().writeBytes("PONG\n".getBytes())); ctx.writeAndFlush(response); // (1) heartbeatCount++; System.out.println(new Date().toLocaleString()+": receive heartbeat from " + ctx.channel().remoteAddress() + ",count:" + heartbeatCount); } else { heartbeatCount = 0; super.channelRead(ctx, msg); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; // 读超时,关闭连接 if (e.state() == IdleState.READER_IDLE) { ctx.close(); System.out.println(new Date().toLocaleString()+":READER_IDLE 读超时,关闭客户端连接"); } } } }
true
d161e92287875a4f12b161625f450e0623f565f3
Java
nehasoni05/HackerRank_solutions
/Java/Introduction/Java Loops/Solution1.java
UTF-8
1,469
3.5
4
[]
no_license
/*Task You are given q queries in the form of a, b, and n For each query, print the series corresponding to the given a, b, and n values as a single line of n space-separated integers. Input Format The first line contains an integer, q denoting the number of queries. Each line i of the q subsequent lines contains three space-separated integers describing the respective a-th b-th and n-th values for that query. Constraints 0<= q <= 500 0<= a,b <= 50 1<= n <= 15 Output Format For each query, print the corresponding series on a new line. Each series must be printed in order as a single line of n space-separated integers. Sample Input 2 0 2 10 5 3 5 Sample Output 2 6 14 30 62 126 254 510 1022 2046 8 14 26 50 98 SOLUTION-> // import java.util.*; import java.io.*; class Solution1 { public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int s=0,power,c=0; power=(int)Math.pow(2,c); s+=(a+power*b); System.out.print(s+" "); for(int j=1;j<n;j++) { c++; power=(int)Math.pow(2,c); s+=(power*b); System.out.print(s+" "); } System.out.println(); } in.close(); } }
true
0dade8e135e0405adaa0758839589d856dbdc2de
Java
luangs7/UtilsBase
/app/src/main/java/br/com/squarebits/utilsbase/MainActivity.java
UTF-8
2,951
2.328125
2
[]
no_license
package br.com.squarebits.utilsbase; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.github.rrsystems.utilsplus.android.UtilsPlus; import java.lang.reflect.Method; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showToast(); copy(); simplyNotification(); sharedPref(); showDebugDBAddressLogToast(this); } public void showToast(){ UtilsPlus.getInstance().toast("Teste de Toast!",5); } public void copy(){ UtilsPlus.getInstance().copyToClipboard("text to be copied"); } public void UtilsEdittext(){ UtilsPlus.getInstance().checkEmailIsValid("rakshithsj30@gmail.com"); // second parameter is country code UtilsPlus.getInstance().validatePhoneNumber("9480523270","91"); } public void simplyNotification(){ /* * Utility method which will help you to show notification in the status bar. * @param title title of the push notification * @param body content to be displayed in the notification * @param small_icon small icon which will be showed in the notification. should be of following format:R.drawable.imageName * @param large_icon Large icon which will be showed in the notification. should be of following format:R.drawable.imageName * @param class_name The activity which will open on clicking notification. Parameter format: activity_name.class * @param autoCancel true or false. if set to true, notification will be disappeared after clicking it otherwise it will remain in the status bar */ UtilsPlus.getInstance().displaySimplePushNotification("New Mesage","new message received",R.mipmap.ic_launcher,R.mipmap.ic_launcher,MainActivity.class,true); } public void getDeviceId(){ String id = UtilsPlus.getInstance().getDeviceID(); Log.e("",id); } public void checkService(){ // UtilsPlus.getInstance().checkServiceIsRunning(service1.class); } public void sharedPref(){ UtilsPlus.getInstance().put("teste", "some value"); //UtilsPlus.getInstance().getString("key", "default"); // UtilsPlus.getInstance().removeKey("key"); // UtilsPlus.getInstance().clear(); } public static void showDebugDBAddressLogToast(Context context) { if (BuildConfig.DEBUG) { try { Class<?> debugDB = Class.forName("com.amitshekhar.DebugDB"); Method getAddressLog = debugDB.getMethod("getAddressLog"); Object value = getAddressLog.invoke(null); UtilsPlus.getInstance().toast((String) value,10); } catch (Exception ignore) { } } } }
true
5f92da3fc6f7c63bd626965fffcd6725577d46da
Java
Zhuikov/HTTP-FTP-Proxy
/src/main/java/httpFtpProxy/Proxy.java
UTF-8
9,570
2.875
3
[]
no_license
package httpFtpProxy; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; public class Proxy { static class DataAndCode { private String code = null; private ArrayList<Character> data = null; public DataAndCode() {} public String getCode() { return code; } public ArrayList<Character> getData() { return data; } public void setCode(String code) { this.code = code; } public void setData(ArrayList<Character> data) { this.data = data; } } static class HTTPRequest { private Method method = null; private String path = null; private String hostName = null; private String login = null; private String password = null; private ArrayList<Character> body = null; private String param = null; private String ftpCommand = null; private boolean file = false; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getParam() { return param; } public void setParam(String param) { this.param = param; } public ArrayList<Character> getBody() { return body; } public void setBody(ArrayList<Character> body) { this.body = body; } public String getFtpCommand() { return ftpCommand; } public void setFtpCommand(String ftpCommand) { this.ftpCommand = ftpCommand; } public boolean isFile() { return file; } public void setFile(boolean file) { this.file = file; } } public enum Method { GET, PUT, DELETE }; private ServerSocket listeningSocket; private Socket clientSocket; private FTPClient ftpClient = new FTPClient(); public static void main(String[] args) { Proxy proxy = new Proxy(); try { proxy.start(7500); } catch (IOException e) { e.printStackTrace(); } } public Proxy() {} public void start(int port) throws IOException { HTTPHandler httpHandler = new HTTPHandler(); listeningSocket = new ServerSocket(port); while (true) { try { clientSocket = listeningSocket.accept(); } catch (SocketException e) { System.out.println("proxy stopped"); break; } HTTPRequest httpRequest = httpHandler.receiveRequest(clientSocket); // todo может быть добавить метод валидации пакета System.out.println("------Method = " + httpRequest.getMethod() + "\nHost = " + httpRequest.getHostName() + "\nPath = " + httpRequest.getPath() + "\nLogin = " + httpRequest.getLogin() + "\nPass = " + httpRequest.getPassword() + "\nFile = " + httpRequest.isFile() + "\nFtp command = " + httpRequest.getFtpCommand() + "\nParam = " + httpRequest.getParam()); if (!ftpClient.isConnected()) { try { String connectResponse = ftpClient.connect(httpRequest.path.substring(0, httpRequest.path.indexOf('/'))); if (!connectResponse.equals("220")) { sendResponse(clientSocket, "500", "Connection error"); continue; } } catch (Exception e) { sendResponse(clientSocket, "500", e.getMessage()); continue; } } if (!ftpClient.isAuth() || (httpRequest.getFtpCommand() != null && httpRequest.getFtpCommand().equals(FTPClient.authCommand))) { String authResponse = ftpClient.auth(httpRequest.login, httpRequest.password); System.out.println("authResponse = " + authResponse); if (!authResponse.equals("230")) { sendResponse(clientSocket, "400", "Authentication error"); continue; } } if (httpRequest.isFile()) { switch (httpRequest.getMethod()) { case GET: { DataAndCode response = processRequestGET(httpRequest); sendResponse(clientSocket, response); break; } case PUT: { String putResponse = processRequestPUT(httpRequest); if (putResponse.equals("226") || putResponse.equals("250")) { sendResponse(clientSocket, "200", "Ok"); } else { sendResponse(clientSocket, "500", "Cannot upload file"); } break; } case DELETE: { String deleteResponse = processRequestDelete(httpRequest); if (deleteResponse.equals("250")) { sendResponse(clientSocket, "200", "Ok"); } else { sendResponse(clientSocket, "500", "Cannot delete file"); } } } } else { switch (httpRequest.getFtpCommand()) { case FTPClient.pwdCommand: DataAndCode response = ftpClient.pwd(); if (response.getCode().equals("257")) { sendResponse(clientSocket, response); } else sendResponse(clientSocket, "500", "Cannot execute command"); break; case FTPClient.cwdCommand: String cwdResponseCode = ftpClient.cwd(httpRequest.getParam()); if (cwdResponseCode.equals("250")) { sendResponse(clientSocket, "200", "Ok"); } else sendResponse(clientSocket, "500", "Cannot change directory"); break; case FTPClient.quitCommand: String quitResponseCode = ftpClient.disconnect(); if (quitResponseCode.equals("221")) { sendResponse(clientSocket, "200", "Ok"); } else sendResponse(clientSocket, "500", "Cannot disconnect user"); break; default: sendResponse(clientSocket, "200", "Ok"); } } } } public void stop() throws IOException { listeningSocket.close(); } private DataAndCode processRequestGET(HTTPRequest httpRequest) throws IOException { DataAndCode dataAndCode; String path = httpRequest.getPath(); if (path.charAt(path.length() - 1) == '/') dataAndCode = ftpClient.sendDataCommand("list", path.substring(path.indexOf('/')), httpRequest.getParam().charAt(0)); else dataAndCode = ftpClient.sendDataCommand("retr", path.substring(path.indexOf('/')), httpRequest.getParam().charAt(0)); return dataAndCode; } private void sendResponse(Socket socket, String code, String message) throws IOException { OutputStream os = socket.getOutputStream(); os.write(("HTTP/1.1 " + code + ' ' + message + "\nContent-Length: 0" +"\n\n").getBytes()); } private void sendResponse(Socket socket, DataAndCode dataAndCode) throws IOException { OutputStream os = socket.getOutputStream(); os.write(("HTTP/1.1 200 Ok\nContent-Length: " + dataAndCode.data.size() + "\n\n").getBytes()); if (dataAndCode.data.size() != 0) { for (char c : dataAndCode.data) { os.write(c); } } } private String processRequestPUT(HTTPRequest httpRequest) throws IOException { String dir = httpRequest.path.substring(httpRequest.path.indexOf('/')); return ftpClient.stor(httpRequest.body, dir, httpRequest.getParam().charAt(0)); } private String processRequestDelete(HTTPRequest httpRequest) throws IOException { String dir = httpRequest.path.substring(httpRequest.path.indexOf('/')); return ftpClient.dele(dir); } }
true
8175d1edf0c1b593a1b8f48e48f1a6428c7d5fa5
Java
ncguy2/UMLEditor
/core/src/net/ncguy/uml/event/IEvent.java
UTF-8
164
1.773438
2
[]
no_license
package net.ncguy.uml.event; /** * Created by Nick on 30/09/2015 at 20:23, * Project: UMLEditor. */ public interface IEvent { void run(Object... args); }
true
33675da811435ea194939b423961fc22c82d80b7
Java
SimonWang1/design-pattern
/src/com/wsx/demo/factory/logger/serviceimpl/DatabaseLogger.java
GB18030
298
2.109375
2
[]
no_license
package com.wsx.demo.factory.logger.serviceimpl; import com.wsx.demo.factory.logger.service.Logger; // ݿ־Ʒҵʵ֣ public class DatabaseLogger implements Logger{ @Override public void writeLog() { System.out.println("record database log"); } }
true
d1e9371aa97815e00192b95106e59573cbef0f98
Java
AhmedBadrSayed/NewMoviesApp
/app/src/main/java/com/projects/brightcreations/moviesappmvp/web_service/RetrofitErrorCallbacks.java
UTF-8
943
2.390625
2
[]
no_license
package com.projects.brightcreations.moviesappmvp.web_service; import android.util.Log; import com.projects.brightcreations.moviesappmvp.movie.MoviesResponse; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; /** * @author ahmed on 26/03/18. */ public class RetrofitErrorCallbacks implements Consumer<Throwable> { private static final String TAG = RetrofitErrorCallbacks.class.getSimpleName(); private MoviesResponseErrorListener listener; @Override public void accept(@NonNull Throwable throwable) throws Exception { listener.onGetMoviesResponseError(throwable.getMessage()); Log.e(TAG, "Error "+throwable.getMessage()); } public void setMoviesResponseErrorListener(MoviesResponseErrorListener listener){ this.listener = listener; } public interface MoviesResponseErrorListener{ void onGetMoviesResponseError(String errorMsg); } }
true
a0b15ed46a12d1ea31eb03fcb0b338cc158d99b4
Java
ROJASCAPOTE/Peliculas
/AlquilerPeliculas/src/main/java/Vista/FrmStore.java
UTF-8
30,014
1.851563
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 Vista; import Modelo.dao.DAOManager; import Modelo.dao.StoreDAO; import Modelo.vo.AddressVO; /** * * @author ACER E5 */ public class FrmStore extends javax.swing.JFrame { private DAOManager manager; String codigo; public FrmStore(DAOManager manager) { initComponents(); this.manager = manager; radioSi.setSelected(true); getCodigoStore(); } private void getCodigoStore() { int codigo = manager.getStoreDAO().grtCodigoStore(); textCodigo.setText(codigo + ""); textCodigo.setEditable(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSpinField1 = new com.toedter.components.JSpinField(); GrpSiNo = new javax.swing.ButtonGroup(); jPanel3 = new javax.swing.JPanel(); jPanel14 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); textAdressStore = new javax.swing.JTextField(); jDateChooser1 = new com.toedter.calendar.JDateChooser(); jLabel4 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); textCodigo = new javax.swing.JTextField(); jPanel15 = new javax.swing.JPanel(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton11 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); textId = new javax.swing.JTextField(); textFirstName = new javax.swing.JTextField(); textLastName = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); textUsername = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); textPassword = new javax.swing.JPasswordField(); jLabel13 = new javax.swing.JLabel(); cmbRol = new javax.swing.JComboBox<>(); jLabel14 = new javax.swing.JLabel(); textLastUpdate = new com.toedter.calendar.JDateChooser(); textAddress = new javax.swing.JTextField(); textEmail = new javax.swing.JTextField(); textPicture = new javax.swing.JTextField(); radioSi = new javax.swing.JRadioButton(); radioNo = new javax.swing.JRadioButton(); jButton2 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); labelFotp = new javax.swing.JLabel(); jButton6 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setBackground(new java.awt.Color(102, 102, 102)); jPanel3.setBackground(new java.awt.Color(102, 102, 102)); jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel14.setBackground(new java.awt.Color(102, 102, 102)); jPanel14.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Registrar Store", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(255, 255, 255))); // NOI18N jLabel2.setBackground(new java.awt.Color(255, 255, 255)); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Address Store"); jLabel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Last Update"); jButton1.setText("......"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Codigo"); javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addGap(65, 65, 65) .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(46, 46, 46) .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(textCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(29, 29, 29) .addComponent(jLabel2) .addGap(26, 26, 26) .addComponent(textAdressStore, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 606, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jButton1) .addContainerGap(236, Short.MAX_VALUE)) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(textCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textAdressStore, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1) .addComponent(jLabel2))) .addGap(18, 18, 18) .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addContainerGap(42, Short.MAX_VALUE)) ); jPanel15.setBackground(new java.awt.Color(102, 102, 102)); jPanel15.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Mantenimiento", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(255, 255, 255))); // NOI18N jButton3.setText("NUEVO"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("GUARDAR"); jButton5.setText("MODIFICAR"); jButton11.setText("ELIMINAR"); jButton11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton11ActionPerformed(evt); } }); jButton7.setText("BUSCAR"); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton4) .addGap(18, 18, 18) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel15Layout.createSequentialGroup() .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel2.setBackground(new java.awt.Color(102, 102, 102)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Manager", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(255, 255, 255))); // NOI18N jPanel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Id"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("First name"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Last name"); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Address"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setText("Email "); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 255, 255)); jLabel9.setText("Picture"); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel10.setForeground(new java.awt.Color(255, 255, 255)); jLabel10.setText("Active"); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel11.setForeground(new java.awt.Color(255, 255, 255)); jLabel11.setText("Username"); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel12.setForeground(new java.awt.Color(255, 255, 255)); jLabel12.setText("Password"); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel13.setForeground(new java.awt.Color(255, 255, 255)); jLabel13.setText("Rol"); cmbRol.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel14.setForeground(new java.awt.Color(255, 255, 255)); jLabel14.setText("Last update"); radioSi.setBackground(new java.awt.Color(102, 102, 102)); GrpSiNo.add(radioSi); radioSi.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N radioSi.setForeground(new java.awt.Color(255, 255, 255)); radioSi.setSelected(true); radioSi.setText("Si"); radioNo.setBackground(new java.awt.Color(102, 102, 102)); GrpSiNo.add(radioNo); radioNo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N radioNo.setForeground(new java.awt.Color(255, 255, 255)); radioNo.setText("No"); jButton2.setText("....."); jPanel1.setBackground(new java.awt.Color(102, 102, 102)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Foto", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(255, 255, 255))); // NOI18N labelFotp.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelFotp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelFotp, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE) ); jButton6.setText("......"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(68, 68, 68) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel10) .addComponent(jLabel9) .addComponent(jLabel8) .addComponent(jLabel6) .addComponent(jLabel1) .addComponent(jLabel5) .addComponent(jLabel7)) .addGap(40, 40, 40) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textId) .addComponent(textLastName) .addComponent(textFirstName) .addComponent(textAddress) .addComponent(textEmail) .addComponent(textPicture, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jLabel14)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jButton2)))) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(radioSi) .addGap(29, 29, 29) .addComponent(radioNo)))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(2, 2, 2) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel12) .addComponent(jLabel11) .addComponent(jLabel13)) .addGap(40, 40, 40) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textUsername) .addComponent(textPassword) .addComponent(cmbRol, 0, 405, Short.MAX_VALUE)))) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textLastUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jButton6)) .addContainerGap(75, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(jLabel14)) .addComponent(textLastUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(textFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2)) .addComponent(jLabel7)) .addGap(19, 19, 19) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(textEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(textPicture, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(radioSi) .addComponent(radioNo)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(46, 46, 46) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmbRol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(jButton6))) .addContainerGap(37, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton3ActionPerformed private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed DialogAddress dialogAddress = new DialogAddress(this, true); dialogAddress.setLocationRelativeTo(null); dialogAddress.setVisible(true); }//GEN-LAST:event_jButton11ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed DialogListAddressStaff dialogListAddressStaff = new DialogListAddressStaff(this, true); dialogListAddressStaff.setLocationRelativeTo(null); dialogListAddressStaff.setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup GrpSiNo; private javax.swing.JComboBox<String> cmbRol; private javax.swing.JButton jButton1; private javax.swing.JButton jButton11; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private com.toedter.calendar.JDateChooser jDateChooser1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private com.toedter.components.JSpinField jSpinField1; private javax.swing.JLabel labelFotp; private javax.swing.JRadioButton radioNo; private javax.swing.JRadioButton radioSi; private javax.swing.JTextField textAddress; public static javax.swing.JTextField textAdressStore; private javax.swing.JTextField textCodigo; private javax.swing.JTextField textEmail; private javax.swing.JTextField textFirstName; private javax.swing.JTextField textId; private javax.swing.JTextField textLastName; private com.toedter.calendar.JDateChooser textLastUpdate; private javax.swing.JPasswordField textPassword; private javax.swing.JTextField textPicture; private javax.swing.JTextField textUsername; // End of variables declaration//GEN-END:variables }
true
264b9ef96eee256f13730224499f0c3bea618b4a
Java
hongyegong/photoShare_Android
/web/pic/src/com/ishare/conn/MyConnection.java
UTF-8
2,425
2.734375
3
[]
no_license
package com.ishare.conn; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; @SuppressWarnings("unused") public class MyConnection { private static MyConnection instance = null; private static String url = null; private static String drivername = null; private static String username = null; private static String password = null; private static Connection connection = null; static { Properties pro = null; InputStream fileInput = null; try { fileInput = MyConnection.class.getResourceAsStream("/datasource.properties"); pro = new Properties(); pro.load(fileInput); drivername = pro.getProperty("driver"); url = pro.getProperty("url"); username = pro.getProperty("username"); password = pro.getProperty("password"); }catch(Exception e){ e.printStackTrace(); }finally { if(fileInput != null){ try { fileInput.close(); } catch (IOException e) { e.printStackTrace(); } } } } private MyConnection(){ try { Class.forName(drivername); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection(){ if(instance == null){ instance = new MyConnection(); } try { connection = DriverManager.getConnection(url, username, password); } catch (SQLException e) { e.printStackTrace(); } return connection; } public static void main(String[] args) { try { Connection con = MyConnection.getConnection(); Statement st = con.createStatement(); st.execute("SELECT NOW() "); st.close(); con.close(); }catch (Exception e) { e.printStackTrace(); } } }
true
89b9af5dc9f1cd4f2934f71b856153862c407ba0
Java
ac-silva/desafio-pagarme
/src/test/java/PagarMe/api/SplitRuleHandlerTest.java
UTF-8
1,083
2.265625
2
[ "MIT" ]
permissive
package PagarMe.api; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import PagarMe.api.handler.SplitRuleHandler; import PagarMe.api.model.Recipient; import PagarMe.api.model.SplitRule; public class SplitRuleHandlerTest { @Mock private RestClient client; @Before public void setUp(){ MockitoAnnotations.initMocks(this); SplitRule result = new SplitRule(); result.setId(100); when(client.get(anyLong(), any(),eq(SplitRule.class))).thenReturn(result); } @Test public void testGetSplitRuleOfTransaction() { Recipient recipient = new Recipient(); SplitRule splitRule = new SplitRule(recipient); SplitRuleHandler handler = new SplitRuleHandler(client); splitRule = handler.getSplitRuleOfTransaction(45676l); assertEquals(100, splitRule.getId()); } }
true
ba40af5628fdfae2b889f852bfff641abd58294d
Java
bkvishal/ActiveMQ-InMemory
/src/main/java/com/jms/example/activemq_inmemory_jms/Controller/Subscriber.java
UTF-8
431
2.234375
2
[]
no_license
package com.jms.example.activemq_inmemory_jms.Controller; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; /** * @author : Vishal Srivastava * @Date : 11-07-2021 **/ @Component public class Subscriber { @JmsListener(destination = "inMemory.queue") public void subscriber(String message) { System.out.println("Subscriber 1 read the message -- " + message); } }
true
e4dfbba5e9bee8e3b04242c802acd5cbb327281b
Java
StarReider/microservices-practical
/gamification/src/main/java/microservices/book/gamification/controller/AdminController.java
UTF-8
835
2.03125
2
[]
no_license
package microservices.book.gamification.controller; import org.springframework.context.annotation.Profile; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import microservices.book.gamification.service.AdminService; @Profile("test") @RestController @RequestMapping("/gamification/admin") public class AdminController { private final AdminService adminService; public AdminController(final AdminService adminService) { this.adminService = adminService; } @PostMapping("/delete-db") public ResponseEntity<?> deleteDatabase() { adminService.deleteDatabaseContents(); return ResponseEntity.ok().build(); } }
true
cee8359cb73a0f0d818eac49a101237c60d6e25d
Java
erdnute/notes
/notes/src/main/java/de/erdnute/notes/NotesRepository.java
UTF-8
466
1.867188
2
[]
no_license
package de.erdnute.notes; import java.util.List; import de.erdnute.notes.filerep.FileFolder; public interface NotesRepository { List<Folder> findAllFolders(); List<Note> findNotesByFolder(String tagName); List<Note> findNotesByText(String searchtext); List<Note> findNotesByText(String searchtext, String folderName); void updateNote(Note note); void insertNote(Note note); Note createEmptyNote(Folder folder); void reloadAll(); }
true
783a808fc4264989ccd5187c828329626331134e
Java
SviatlanaYermalinskaya/ATC
/Task15/TestMassive4.java
UTF-8
2,568
2.484375
2
[]
no_license
package HomeWork; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.BeforeClass; import java.util.Arrays; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.AfterSuite; public class TestMassive4 { Massive mass; @DataProvider public Object[][] dp() { return new Object[][] { new Object[] { 0, 1, 6 }, new Object[] { 0, 2, 8 }, new Object[] { 1, 2, 12 } }; } @Test(dataProvider = "dp") public void testMultiplyMassiveNumbers(int a, int b, int c) { mass = new Massive(new int[] {2,3,4}); Assert.assertEquals(mass.multiplyMassiveNumbers(a, b), c); } @Test public void testsumAllNumbers() { mass = new Massive(new int[] {1, 2, 3, 4}); Assert.assertEquals(mass.sumAllNumbers(), 10); } @Test public void testReverseMassive() { mass = new Massive(new int[] {1, 2, 3, 4}); Assert.assertEquals(mass.reverseMassive()[0], 4); } @Test public void testReverseMassive2() { mass = new Massive(new int[] {1, 2, 3, 4}); Integer[] massInteger = Arrays.stream( mass.getMass() ).boxed().toArray( Integer[]::new ); Integer[] mass1Integer = Arrays.stream( mass.reverseMassive() ).boxed().toArray( Integer[]::new ); Assert.assertEqualsNoOrder(massInteger, mass1Integer); } @Test public void testMin() { mass = new Massive(new int[] {1, 2, -3, 4}); Assert.assertEquals(mass.min(), -3); } @Test public void testSortMassive() { mass = new Massive(new int[] {4, 5, 3, 2}); Integer[] massInteger = Arrays.stream( mass.getMass() ).boxed().toArray( Integer[]::new ); Integer[] mass1Integer = Arrays.stream( mass.sortMassive() ).boxed().toArray( Integer[]::new ); Assert.assertEqualsNoOrder(massInteger, mass1Integer); } @Test public void testSortMassive2() { mass = new Massive(new int[] {4, 5, 3, 2}); Assert.assertEquals(mass.sortMassive()[0], 2); } @BeforeMethod public void beforeMethod() { TestMassive.method_num++; mass = new Massive(new int[] {1,2,3}); System.out.println("Test 4 - BeforeMethod " + TestMassive.method_num); } @AfterMethod public void afterMethod() { System.out.println("Test 4 - AfterMethod " + TestMassive.method_num); } }
true
2fe3a1a1b1832bf8ed738bffccff7e39ae6f93b1
Java
itrenjunhua/MyMVP
/lib_android_utils/src/main/java/com/renj/utils/system/SystemUtils.java
UTF-8
10,055
2.03125
2
[]
no_license
package com.renj.utils.system; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.content.FileProvider; import android.text.TextUtils; import com.renj.utils.common.PackageUtils; import com.renj.utils.common.UIUtils; import com.renj.utils.res.StringUtils; import java.io.File; import java.util.List; /** * ====================================================================== * <p> * 作者:Renj * 邮箱:itrenjunhua@163.com * <p> * 创建时间:2018-04-04 14:07 * <p> * 描述:打开系统界面,获取系统信息等相关工具类 * <p> * 修订历史: * <p> * ====================================================================== */ public class SystemUtils { /** * 打开系统设置界面 */ public static void openSettingActivity(@NonNull String packageName) { Intent localIntent = new Intent(); localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= 9) { localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); localIntent.setData(Uri.fromParts("package", packageName, null)); } else if (Build.VERSION.SDK_INT <= 8) { localIntent.setAction(Intent.ACTION_VIEW); localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); localIntent.putExtra("com.android.settings.ApplicationPkgName", packageName); } UIUtils.getContext().startActivity(localIntent); } /** * 打开系统网络设置页面 */ public static void openNetWorkActivity() { Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); UIUtils.getContext().startActivity(intent); } /** * 重启APP */ public static void restartAPP() { Intent intent = UIUtils.getContext().getPackageManager().getLaunchIntentForPackage(PackageUtils.getPackageName()); if (intent == null) return; intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); UIUtils.getContext().startActivity(intent); android.os.Process.killProcess(android.os.Process.myPid()); } /** * 根据packageName 判断是否安装某应用 * * @param packageName 需要判断的包名 */ public static boolean isAppInstalled(String packageName) { final PackageManager packageManager = UIUtils.getContext().getPackageManager(); // 获取所有已安装程序的包信息 List<PackageInfo> pInfo = packageManager.getInstalledPackages(0); for (int i = 0; i < pInfo.size(); i++) { String pName = pInfo.get(i).packageName; if (TextUtils.equals(packageName, pName)) { return true; } } return false; } /** * 检查apk安装包是否可以安装 * * @param apkFilePath apk 文件路径 * @return true:可以 false:不可以 */ public static boolean isApkCanInstall(String apkFilePath) { if (StringUtils.isEmpty(apkFilePath)) return false; PackageManager pm = UIUtils.getContext().getPackageManager(); if (pm != null) { PackageInfo info = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES); return info != null; } return false; } /** * 获取apk文件中的 VersionCode * * @param apkFilePath apk 文件路径 * @return apk文件中的 VersionCode */ public static long getApkVersionCode(String apkFilePath) { if (StringUtils.isEmpty(apkFilePath)) return 0; PackageManager pm = UIUtils.getContext().getPackageManager(); if (pm != null) { PackageInfo info = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return info == null ? 0 : info.getLongVersionCode(); } else { return info == null ? 0 : info.versionCode; } } return 0; } /** * 获取apk文件中的 {@link PackageInfo} * * @param apkFilePath apk 文件路径 * @return apk文件中的 {@link PackageInfo},异常或解析失败时为 {@code null} */ public static PackageInfo getApkPackageInfo(String apkFilePath) { if (StringUtils.isEmpty(apkFilePath)) return null; PackageManager pm = UIUtils.getContext().getPackageManager(); if (pm != null) { PackageInfo info = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES); return info; } return null; } /** * 安装apk * * @param authority 主机地址,Android 7.0 权限适配需要,文件需要转换为 URI 进行访问(Android 7.0 以下可传 null) * @param apkFilePath apk 文件路径 */ public static void installApk(String authority, String apkFilePath) { File apkFile = new File(apkFilePath); if (!apkFile.exists()) { UIUtils.showToast("安装文件不存在!"); return; } if (!isApkCanInstall(apkFilePath)) { UIUtils.showToast("安装文件解析异常!"); apkFile.deleteOnExit(); return; } try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(getProvider(authority, apkFilePath), "application/vnd.android.package-archive"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 兼容8.0,判断是否有安装未知应用权限 android.permission.REQUEST_INSTALL_PACKAGES if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (!canRequestPackageInstalls(UIUtils.getContext())) { startInstallPermissionSettingActivity(UIUtils.getContext(), null); return; } } } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); UIUtils.getContext().startActivity(intent); } catch (Exception e) { UIUtils.showToast("安装失败!"); e.printStackTrace(); } } /** * 判断是否有 允许安装未知应用 权限 android.permission.REQUEST_INSTALL_PACKAGES * * @return true:有权限 false:无权限 */ @RequiresApi(api = Build.VERSION_CODES.O) public static boolean canRequestPackageInstalls(Context context) { return context.getPackageManager().canRequestPackageInstalls(); } /** * 跳转到 设置-允许安装未知来源-页面 * * @param packageName 当包名不为null时,跳转到具体的应用,否则打开所有应用列表 */ @RequiresApi(api = Build.VERSION_CODES.O) public static void startInstallPermissionSettingActivity(Context context, String packageName) { //注意这个是8.0新API Intent intent; if (StringUtils.notEmpty(packageName)) { Uri packageURI = Uri.parse("package:" + packageName); intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI); } else { intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES); } if (!(context instanceof Activity)) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } /** * 将路径转换为URI * * @param authority 主机地址,Android 7.0 权限适配需要,文件需要转换为 URI 进行访问 * @param path 转换路径 * @return Uri */ public static Uri getProvider(String authority, String path) { if (TextUtils.isEmpty(path)) return null; Uri uri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(UIUtils.getContext(), authority, new File(path)); } else { uri = Uri.fromFile(new File(path)); } return uri; } /** * 判断一个应用是否正在运行 * * @param packageName 包名 * @return true:正在运行状态 false:未运行状态 */ public static boolean isRunning(String packageName) { ActivityManager am = (ActivityManager) UIUtils.getContext().getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> infos = am.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo rapi : infos) { if (rapi.processName.equals(packageName)) return true; } return false; } /** * 打开浏览器,并跳转到指定页面。先判断是否有系统浏览器,有直接打开,没有就弹出选择浏览器框 * * @param context Context * @param url 页面链接 */ public static void openBrowser(Context context, String url) { if (context == null || StringUtils.isEmpty(url)) return; Intent intent = new Intent(); Uri uri = Uri.parse(url); intent.setAction(Intent.ACTION_VIEW); intent.setData(uri); if (!(context instanceof Activity)) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); } else { context.startActivity(Intent.createChooser(intent, "请选择浏览器")); } } }
true
363b087661160694ce0d317abbd9d6ced280bf7f
Java
srpraharaj/itupgrade
/src/main/java/com/ibm/itupgrade/restcontrollers/MiddlewareReadinessController.java
UTF-8
2,086
1.976563
2
[]
no_license
package com.ibm.itupgrade.restcontrollers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ibm.itupgrade.message.ReadinessStatus; import com.ibm.itupgrade.message.Response; import com.ibm.itupgrade.models.MiddlewareReadiness; import com.ibm.itupgrade.services.MiddlewareReadinessServices; @RestController @RequestMapping("api/middleware") public class MiddlewareReadinessController { @Autowired private MiddlewareReadinessServices dpServices; @GetMapping("/all") public Response getAllItems(){ Iterable<MiddlewareReadiness> dp = dpServices.getAllItems(); return new Response("Success",dp); } @GetMapping("/taskStatus") public ReadinessStatus middlewareReadinessDashboard(){ return dpServices.generateCompletedTaskDetails(); } @GetMapping("/{id}") public Response getItem(@PathVariable("id") int id){ MiddlewareReadiness dp = dpServices.getItem(id); return new Response("Success",dp); } @GetMapping("/byId/{id}") public MiddlewareReadiness getItemById(@PathVariable("id") int id){ return dpServices.getItem(id); } @PostMapping(value="/add") public void addItem(@RequestBody MiddlewareReadiness dp){ dpServices.addItem(dp); } //@RequestMapping(method=RequestMethod.PUT,value="/teams/{id}") @PutMapping(value="/{id}") public void updateItem(@RequestBody MiddlewareReadiness dp,@PathVariable int id){ dpServices.updateItem(dp,id); } //@RequestMapping(method=RequestMethod.DELETE,value="/teams/{id}") @DeleteMapping(value="/{id}") public void deleteItems(@PathVariable int id){ dpServices.removeItem(id); } }
true
9da20ee6cfc66ad0a0408f3175b828b26c2496b3
Java
nricci/YAWL2FSP
/src/fsp/model/FSP_TresholdOrJoin.java
UTF-8
1,260
2.796875
3
[]
no_license
package fsp.model; public class FSP_TresholdOrJoin extends FSPJoin { protected final String fsp_name() { return "TRSH_OR_JOIN"; } private int ins; private int treshold; public FSP_TresholdOrJoin(int n, int t) { ins = n; treshold = t; for(int i = 1; i <= n; i++) { this.input_names.put("in["+i+"]", null); } this.output_names.put("out", null); this.control_names.put("o_cond", null); } public FSP_TresholdOrJoin(String s, int n, int t) { super(s); treshold = t; ins = n; for(int i = 1; i <= n; i++) { this.input_names.put("in["+i+"]", null); } this.output_names.put("out", null); this.control_names.put("o_cond", null); } @Override public FSPProgram toFSP(FSPProgram p) { String def = ""; def += "TRSH_OR_JOIN(N=2,T=1) = TRSH_OR_JOIN_DEF[0],\n"; def += "TRSH_OR_JOIN_DEF[b:0..N] = (\n"; def += "\t o_cond -> TRSH_OR_JOIN\n"; def += "\t | in[1..N] -> TRSH_OR_JOIN_DEF[b+1]\n"; def += "\t | when (b>=T) out -> TRSH_OR_JOIN\n"; def += ").\n"; p.add_prelude_definition(this.fsp_name(), def); return p; } @Override public void accept(FSPSpecVisitor v) { v.visit(this); } @Override protected String fsp_name_w_mult() { return this.fsp_name() + "(" + ins +","+ treshold+")"; } }
true
859c1bbbdd3abda9a469bfc95455ab4416f1d333
Java
RyanRomano/JavaTest
/src/Kennel.java
UTF-8
1,172
4.28125
4
[ "MIT" ]
permissive
//Ryan Romano //4.2 ed7 //Instantiates dog objects and calls the methods //of the Dog class created in a separate file public class Kennel { public static void main(String[] args) { //create new Dog object from Dog.java with (name, age) parameter //dog objects can also be set name/age in first usage of //Dog dog = new Dog(**"name"**, ****age***) Dog dog = new Dog(); Dog dog2 = new Dog("Molly", 1); Dog dog3 = new Dog(); //setter methods called from Dog.java to accept age and name data dog.setName("Stanley"); dog.setAge(3); //toString method to print description of dog. System.out.println(dog.toString()); System.out.println(dog2.toString()); //with no data set for dog3, it will print the default values //of Lost Dog! with a age of 0 System.out.println(dog3.toString()); //computes and returns dog age in person years (age * 7)from method in Dog.java System.out.println(dog.getName() + " is " + dog.getPersonYears() + " in human years."); System.out.println(dog2.getName() + " is " + dog2.getPersonYears() + " in human years."); System.out.println(dog3.getName() + " is " + dog3.getPersonYears() + " in human years."); } }
true
6e6a9d169fb834a72ba018e11ef738716786c234
Java
souvikbachhar/Full_Stack
/Spring_Basics_Assignments/4/src/com/souvik/ass3/StudentMapper.java
UTF-8
404
2.515625
3
[]
no_license
package com.souvik.ass3; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class StudentMapper implements RowMapper<Student>{ @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student st = new Student(); st.setStudentName(rs.getString("NAME")); st.setStudentId(rs.getString("ID")); return st; } }
true
d9caad37b08189f544a2c6ea3aee11559b6604c1
Java
mygithubwork/ihmc-open-robotics-software
/ExampleSimulations/src/us/ihmc/exampleSimulations/skippy/SkippyICPBasedController.java
UTF-8
14,153
1.679688
2
[ "Apache-2.0" ]
permissive
package us.ihmc.exampleSimulations.skippy; import us.ihmc.euclid.matrix.RotationMatrix; import us.ihmc.euclid.tuple3D.Point3D; import us.ihmc.graphicsDescription.appearance.YoAppearance; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicPosition; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicPosition.GraphicType; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicVector; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry; import us.ihmc.robotics.controllers.PIDController; import us.ihmc.robotics.dataStructures.variable.DoubleYoVariable; import us.ihmc.robotics.dataStructures.variable.IntegerYoVariable; import us.ihmc.robotics.geometry.FramePoint; import us.ihmc.robotics.geometry.FrameVector; import us.ihmc.robotics.math.frames.YoFramePoint; import us.ihmc.robotics.math.frames.YoFrameVector; import us.ihmc.robotics.referenceFrames.ReferenceFrame; import us.ihmc.simulationConstructionSetTools.robotController.SimpleRobotController; public class SkippyICPBasedController extends SimpleRobotController { private static final ReferenceFrame worldFrame = ReferenceFrame.getWorldFrame(); private final SkippyRobot skippy; private final double dt; private final DoubleYoVariable kCapture = new DoubleYoVariable("kCapture", registry); private final DoubleYoVariable kMomentum = new DoubleYoVariable("kMomentum", registry); private final DoubleYoVariable kAngle = new DoubleYoVariable("kAngle", registry); private final DoubleYoVariable hipSetpoint = new DoubleYoVariable("hipSetpoint", registry); private final DoubleYoVariable shoulderSetpoint = new DoubleYoVariable("shoulderSetpoint", registry); private final IntegerYoVariable tickCounter = new IntegerYoVariable("tickCounter", registry); private final IntegerYoVariable ticksForDesiredForce = new IntegerYoVariable("ticksForDesiredForce", registry); private final PIDController hipAngleController = new PIDController("hipAngleController", registry); private final PIDController shoulderAngleController = new PIDController("shoulderAngleController", registry); private final FrameVector angularMomentum = new FrameVector(worldFrame); private final FramePoint com = new FramePoint(worldFrame); private final FrameVector comVelocity = new FrameVector(worldFrame); private final FramePoint icp = new FramePoint(worldFrame); private final FramePoint footLocation = new FramePoint(worldFrame); private final FramePoint desiredCMP = new FramePoint(worldFrame); private final FrameVector desiredGroundReaction = new FrameVector(worldFrame); private final FrameVector groundReaction = new FrameVector(worldFrame); private final FrameVector worldToHip = new FrameVector(worldFrame); private final FrameVector worldToShoulder = new FrameVector(worldFrame); private final FrameVector hipToFootDirection = new FrameVector(worldFrame); private final FrameVector shoulderToFootDirection = new FrameVector(worldFrame); private final FrameVector hipAxis = new FrameVector(worldFrame); private final FrameVector shoulderAxis = new FrameVector(worldFrame); private final YoFramePoint comViz = new YoFramePoint("CoM", worldFrame, registry); private final YoFramePoint icpViz = new YoFramePoint("ICP", worldFrame, registry); private final YoFramePoint desiredCMPViz = new YoFramePoint("DesiredCMP", worldFrame, registry); private final YoFramePoint footLocationViz = new YoFramePoint("FootLocation", worldFrame, registry); private final YoFramePoint hipLocationViz = new YoFramePoint("HipLocation", worldFrame, registry); private final YoFramePoint shoulderLocationViz = new YoFramePoint("ShoulderLocation", worldFrame, registry); private final YoFrameVector desiredGroundReactionViz = new YoFrameVector("DesiredGroundReaction", ReferenceFrame.getWorldFrame(), registry); private final YoFrameVector groundReachtionViz = new YoFrameVector("GroundReaction", ReferenceFrame.getWorldFrame(), registry); private final YoFrameVector hipToFootDirectionViz = new YoFrameVector("HipToFootDirection", ReferenceFrame.getWorldFrame(), registry); private final YoFrameVector hipAxisViz = new YoFrameVector("HipAxis", ReferenceFrame.getWorldFrame(), registry); private final YoFrameVector shoulderAxisViz = new YoFrameVector("ShoulderAxis", ReferenceFrame.getWorldFrame(), registry); private final YoFrameVector angularMomentumViz = new YoFrameVector("AngularMomentum", ReferenceFrame.getWorldFrame(), registry); public SkippyICPBasedController(SkippyRobot skippy, double dt, YoGraphicsListRegistry yoGraphicsListRegistries) { this.skippy = skippy; this.dt = dt; kCapture.set(7.5); kMomentum.set(0.3); kAngle.set(0.1); ticksForDesiredForce.set(10); hipAngleController.setProportionalGain(20.0); hipAngleController.setIntegralGain(10.0); shoulderAngleController.setProportionalGain(0.0); shoulderAngleController.setIntegralGain(0.0); tickCounter.set(ticksForDesiredForce.getIntegerValue() + 1); hipSetpoint.set(0.0); shoulderSetpoint.set(0.0); makeViz(yoGraphicsListRegistries); } private void makeViz(YoGraphicsListRegistry yoGraphicsListRegistries) { String listName = getClass().getSimpleName(); YoGraphicPosition comPositionYoGraphic = new YoGraphicPosition("CoM", comViz, 0.05, YoAppearance.Black(), GraphicType.BALL_WITH_CROSS); yoGraphicsListRegistries.registerYoGraphic(listName, comPositionYoGraphic); yoGraphicsListRegistries.registerArtifact(listName, comPositionYoGraphic.createArtifact()); YoGraphicPosition icpPositionYoGraphic = new YoGraphicPosition("ICP", icpViz, 0.05, YoAppearance.Blue(), GraphicType.BALL_WITH_ROTATED_CROSS); yoGraphicsListRegistries.registerYoGraphic(listName, icpPositionYoGraphic); yoGraphicsListRegistries.registerArtifact(listName, icpPositionYoGraphic.createArtifact()); YoGraphicPosition desiredCMPPositionYoGraphic = new YoGraphicPosition("DesiredCMP", desiredCMPViz, 0.05, YoAppearance.Magenta(), GraphicType.BALL_WITH_ROTATED_CROSS); yoGraphicsListRegistries.registerYoGraphic(listName, desiredCMPPositionYoGraphic); yoGraphicsListRegistries.registerArtifact(listName, desiredCMPPositionYoGraphic.createArtifact()); YoGraphicPosition footPositionYoGraphic = new YoGraphicPosition("FootLocation", footLocationViz, 0.025, YoAppearance.Black(), GraphicType.SOLID_BALL); yoGraphicsListRegistries.registerYoGraphic(listName, footPositionYoGraphic); yoGraphicsListRegistries.registerArtifact(listName, footPositionYoGraphic.createArtifact()); YoGraphicVector desiredGRFYoGraphic = new YoGraphicVector("desiredGRFYoGraphic", footLocationViz, desiredGroundReactionViz, 0.05, YoAppearance.Orange(), true); yoGraphicsListRegistries.registerYoGraphic("desiredReactionForce", desiredGRFYoGraphic); YoGraphicVector actualGRFYoGraphic = new YoGraphicVector("actualGRFYoGraphic", footLocationViz, groundReachtionViz, 0.05, YoAppearance.DarkGreen(), true); yoGraphicsListRegistries.registerYoGraphic("actualReactionForce", actualGRFYoGraphic); YoGraphicVector hipToFootPositionVectorYoGraphic = new YoGraphicVector("hipToFootPositionVector", hipLocationViz, hipToFootDirectionViz, 1.0, YoAppearance.Red(), true); yoGraphicsListRegistries.registerYoGraphic("hipToFootPositionVector", hipToFootPositionVectorYoGraphic); YoGraphicVector hipAxisVectorYoGraphic = new YoGraphicVector("hipAxis", hipLocationViz, hipAxisViz, 0.4, YoAppearance.Red(), true); yoGraphicsListRegistries.registerYoGraphic("hipAxis", hipAxisVectorYoGraphic); YoGraphicVector shoulderAxisVectorYoGraphic = new YoGraphicVector("shoulderAxis", shoulderLocationViz, shoulderAxisViz, 0.4, YoAppearance.Red(), true); yoGraphicsListRegistries.registerYoGraphic("shoulderAxis", shoulderAxisVectorYoGraphic); } @Override public void doControl() { skippy.computeComAndICP(com, comVelocity, icp, angularMomentum); skippy.computeFootContactForce(groundReaction.getVector()); footLocation.set(skippy.computeFootLocation()); cmpFromIcpDynamics(icp, footLocation, desiredCMP); if (tickCounter.getIntegerValue() > ticksForDesiredForce.getIntegerValue()) { double qHip = skippy.getHipJoint().getQ(); double q_dHip = skippy.getHipJoint().getQ() > 0.0 ? hipSetpoint.getDoubleValue() : -hipSetpoint.getDoubleValue(); double hipSetpointFeedback = kAngle.getDoubleValue() * (qHip - q_dHip); double shoulderSetpointFeedback = kAngle.getDoubleValue() * (skippy.getShoulderJoint().getQ() - shoulderSetpoint.getDoubleValue()); RotationMatrix rotationMatrix = new RotationMatrix(); skippy.getRootJoints().get(0).getRotationToWorld(rotationMatrix); double yaw = rotationMatrix.getYaw(); rotationMatrix.setYawPitchRoll(yaw, 0.0, 0.0); Point3D angleFeedback = new Point3D(hipSetpointFeedback, shoulderSetpointFeedback, 0.0); rotationMatrix.invert(); rotationMatrix.transform(angleFeedback); desiredCMP.setY(desiredCMP.getY() - kMomentum.getDoubleValue() * angularMomentum.getX() + angleFeedback.getX()); desiredCMP.setX(desiredCMP.getX() + kMomentum.getDoubleValue() * angularMomentum.getY() + angleFeedback.getY()); desiredGroundReaction.sub(com, desiredCMP); desiredGroundReaction.normalize(); double reactionModulus = Math.abs(skippy.getGravity()) * skippy.getMass() / desiredGroundReaction.getZ(); desiredGroundReaction.scale(reactionModulus); tickCounter.set(0); } tickCounter.increment(); skippy.getHipJoint().getTranslationToWorld(worldToHip.getVector()); skippy.getShoulderJoint().getTranslationToWorld(worldToShoulder.getVector()); skippy.getShoulderJointAxis(shoulderAxis); skippy.getHipJointAxis(hipAxis); // hip specific: hipToFootDirection.sub(footLocation, worldToHip); hipToFootDirection.normalize(); double balanceTorque = computeJointTorque(desiredGroundReaction, hipToFootDirection, hipAxis); double angleFeedback = computeAngleFeedbackHip(); if (Double.isNaN(angleFeedback + balanceTorque)) skippy.getHipJoint().setTau(0.0); else skippy.getHipJoint().setTau(angleFeedback + balanceTorque); // shoulder specific: shoulderToFootDirection.sub(footLocation, worldToShoulder); shoulderToFootDirection.normalize(); balanceTorque = -computeJointTorque(desiredGroundReaction, hipToFootDirection, shoulderAxis); angleFeedback = -computeAngleFeedbackShoulder(); if (Double.isNaN(angleFeedback + balanceTorque)) skippy.getShoulderJoint().setTau(0.0); else skippy.getShoulderJoint().setTau(angleFeedback + balanceTorque); updateViz(); } /** * CMP computed from ICP and CMP coupled dynamics according to: * CMP = ICP + kCapture * (ICP - foot) */ private void cmpFromIcpDynamics(FramePoint icp, FramePoint footLocation, FramePoint desiredCMPToPack) { FrameVector icpToFoot = new FrameVector(); icpToFoot.sub(icp, footLocation); desiredCMPToPack.scaleAdd(kCapture.getDoubleValue(), icpToFoot, icp); desiredCMPToPack.setZ(0.0); } private double computeJointTorque(FrameVector groundReactionForce, FrameVector jointToFoot, FrameVector jointAxis) { FrameVector torque = new FrameVector(worldFrame); torque.cross(jointToFoot, groundReactionForce); return -jointAxis.dot(torque); } private void updateViz() { comViz.set(com); icpViz.set(icp); desiredCMPViz.set(desiredCMP); footLocationViz.set(footLocation); desiredGroundReactionViz.set(desiredGroundReaction); groundReachtionViz.set(groundReaction); hipLocationViz.set(worldToHip); shoulderLocationViz.set(worldToShoulder); hipToFootDirectionViz.set(hipToFootDirection); hipAxisViz.set(hipAxis); shoulderAxisViz.set(shoulderAxis); angularMomentumViz.set(angularMomentum); } /** * Controller on the angle between desired and achieved ground reaction force in the hip plane. */ private double computeAngleFeedbackHip() { double hipAngleDifference = computeAngleDifferenceInPlane(desiredGroundReaction, groundReaction, hipAxis); return hipAngleController.compute(hipAngleDifference, 0.0, 0.0, 0.0, dt); } /** * Controller on the angle between desired and achieved ground reaction force in the shoulder plane. */ private double computeAngleFeedbackShoulder() { double shoulderAngleDifference = computeAngleDifferenceInPlane(desiredGroundReaction, groundReaction, shoulderAxis); return shoulderAngleController.compute(shoulderAngleDifference, 0.0, 0.0, 0.0, dt); } private double computeAngleDifferenceInPlane(FrameVector vectorA, FrameVector vectorB, FrameVector planeNormal) { FrameVector projectedVectorA = new FrameVector(); FrameVector projectedVectorB = new FrameVector(); projectVectorInPlane(vectorA, planeNormal, projectedVectorA); projectVectorInPlane(vectorB, planeNormal, projectedVectorB); FrameVector crosProduct = new FrameVector(); crosProduct.cross(planeNormal, projectedVectorA); double sign = Math.signum(crosProduct.dot(projectedVectorB)); double angle = sign * projectedVectorA.angle(projectedVectorB); if (Double.isNaN(angle)) return 0.0; return angle; } private void projectVectorInPlane(FrameVector vectorToProject, FrameVector planeNormal, FrameVector projectionToPack) { double modulus = vectorToProject.dot(planeNormal); projectionToPack.set(planeNormal); projectionToPack.scale(-modulus); projectionToPack.add(vectorToProject); } }
true
d40efb4963e74d31cda9fc12399c1de56787d523
Java
mmichaelis/antarctic
/src/test/java/org/arctic/ant/taskdefs/UpperTest.java
UTF-8
3,607
2.109375
2
[]
no_license
/* * Copyright (C) 2009 Mark Michaelis <thragor_at_gmx.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arctic.ant.taskdefs; import java.io.File; import java.net.URL; import java.util.Locale; import org.apache.tools.ant.BuildFileTest; import org.apache.tools.ant.Project; public class UpperTest extends BuildFileTest { private static final String BUILD_FILE = "build-upper.xml"; private String upperUmlauts; private String upperSimple; private String upperUmlautsExpected; private String upperSimpleExpected; /* * (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); final URL buildFileResource = getClass().getResource(BUILD_FILE); final File buildFileResourceFile = new File(buildFileResource.toURI()); configureProject(buildFileResourceFile.getAbsolutePath(), Project.MSG_DEBUG); upperSimple = getProject().getProperty("upper.simple"); upperSimpleExpected = upperSimple.toUpperCase(Locale.getDefault()); upperUmlauts = getProject().getProperty("upper.umlauts"); upperUmlautsExpected = upperUmlauts.toUpperCase(Locale.getDefault()); } public void testSimple() { executeTarget("upper-simple"); final String result = getProject().getProperty("upper.simple.result"); assertNotNull("Property \"upper.simple.result\" not set.", result); assertEquals("Upper should have converted all lowercase characters to uppercase.", upperSimpleExpected, result); } public void testUmlauts() { executeTarget("upper-umlauts"); final String result = getProject().getProperty("upper.umlauts.result"); assertNotNull("Property \"upper.umlauts.result\" not set.", result); assertEquals( "Upper should have converted all lowercase characters to uppercase including the umlauts.", upperUmlautsExpected, result); } public void testPropertysetNodot() { executeTarget("upper-propertyset-nodot"); final String resultUmlauts = getProject().getProperty("result.upper.umlauts"); final String resultSimple = getProject().getProperty("result.upper.simple"); assertNotNull("Property \"result.upper.umlauts\" not set.", resultUmlauts); assertNotNull("Property \"result.upper.simple\" not set.", resultSimple); assertEquals( "Upper should have correctly converted the string to uppercase - respecting the locale.", upperUmlautsExpected, resultUmlauts); assertEquals("Upper should have correctly converted the string to uppercase.", upperSimpleExpected, resultSimple); } public void testEmptyValue() { executeTarget("upper-empty-value"); final String result = getProject().getProperty("upper.empty"); assertNotNull("Property \"upper.empty\" not set.", result); assertEquals("Upper should not have modified the input string.", "", result); } }
true
c8b046b115615bf660e1e316a6c7feda0c8d51b0
Java
SiupangChoy/algorithm-structure
/src/coding_for_great_offer/class02/Code05_HashMapWithSetAll.java
UTF-8
317
2.265625
2
[]
no_license
package coding_for_great_offer.class02; /** * 数据结构设计题 * 设计一个HashMap,具有正常的put、get功能之外,具有setAll功能 * 调用setAll之后,所有的key get出来的value一样;setAll之后再put指定key,对应的value会更新 */ public class Code05_HashMapWithSetAll { }
true
e4f7cbb1396abf673754b88f2d3b7035432e8029
Java
PavanSaiSheshetti/PatientOnboardingApp_Web
/src/main/java/com/revature/poa/service/DoctorService.java
UTF-8
473
2.0625
2
[]
no_license
package com.revature.poa.service; import java.util.List; import com.revature.poa.model.Doctor; public interface DoctorService { public boolean addDoctor(Doctor doctor); public boolean updateDoctor(Doctor doctor); public Doctor getDoctorById(long doctorId); public boolean isDoctorExist(long doctorId); public boolean deleteDoctorById(long doctorId); public List<Doctor> getAllDoctorDetails(); public boolean authenticateDoctor(long doctorId,String Password); }
true
929eee385b3b9b2d4679734af8bb58c4e9395a24
Java
AndrewFanChina/Cyclone2D
/Android/src_c2d/c2d/mod/physic/C2D_Motion.java
GB18030
2,953
2.609375
3
[]
no_license
package c2d.mod.physic; import c2d.frame.base.C2D_Widget; import c2d.lang.obj.C2D_Object; public class C2D_Motion extends C2D_Object { //趨ƫ private float m_XOffset; private float m_YOffset; //ٶ private float m_a; //˶ʱ private int m_timeTotal; //ǰ˶ʱ private int m_timeCurrent; //ؼ private C2D_Widget m_widget; //ʼλ private float m_XBegin; private float m_YBegin; //Ƿ˶ private boolean m_isOver; //ǰ˶ƫܼ private float m_XOffsetSum; private float m_YOffsetSum; public C2D_Motion(C2D_Widget widget,float offX,float offY,float a,int timeTotal) { m_widget=widget; startMotion(offX,offY,a,timeTotal); } public C2D_Motion(C2D_Widget widget,int offX,int offY,int a,int timeTotal) { startMotion(widget,offX,offY,a,timeTotal); } public void startMotion(C2D_Widget widget,int offX,int offY,int a,int timeTotal) { m_widget=widget; startMotion(offX,offY,a,timeTotal); } /** * * @param offX * @param offY * @param a * @param timeTotal */ public void startMotion(float offX,float offY,float a,int timeTotal) { m_a=(a); m_XOffset=(offX); m_YOffset=(offY); m_timeTotal=timeTotal; restart(); } /** * ¿ʼ˶ */ public void restart() { if(m_widget!=null) { m_XBegin=m_widget.getX(); m_YBegin=m_widget.getY(); } m_XOffsetSum=0; m_YOffsetSum=0; m_timeCurrent=0; m_isOver=false; } /** * ִƶǷƶ * @param timePassed * @return Ƿƶ */ public boolean doMotion(int timePassed) { if(m_isOver) { return true; } if(m_widget==null||timePassed<=0) { return false; } if(m_timeCurrent+timePassed>=m_timeTotal) { m_widget.setPosTo(m_XOffset +m_XBegin, m_YOffset+m_YBegin); m_isOver=true; } else { float offsetX,offsetY; if(m_a==0) { offsetX=(m_XOffset*timePassed/m_timeTotal); offsetY=(m_YOffset*timePassed/m_timeTotal); } else { offsetX=acc_step(m_timeCurrent,m_timeTotal,timePassed,m_XOffset,m_a); offsetY=acc_step(m_timeCurrent,m_timeTotal,timePassed,m_YOffset,m_a); } m_XOffsetSum+=(offsetX); m_YOffsetSum+=(offsetY); m_widget.setPosTo(m_XOffsetSum+m_XBegin, m_YOffsetSum+m_YBegin); m_timeCurrent+=timePassed; } return m_isOver; } /** * TODO һ˶ָܾLʱttǰʱtc * ȥʱtdͼٶa㼴ƶIJ * @param tc ǰʱ * @param tt ʱ * @param td ȥʱ * @param L ܾ * @param a ٶ * @return ƶ */ public float acc_step(float tc,float tt,float td,float L,float a) { float ld=((L-a*tt*tt/2)/tt+a*tc)*td+a*td*td/2; return ld; } public boolean isOver() { return m_isOver; } public void onRelease() { m_widget=null; } }
true
b479a2a4d1c1aa1540c70e929e36544dd44b8cf0
Java
SeokJunHan/DJ-Delivery
/app/src/main/java/dj/sjn/djbaedal/Adapter/SearchAdapter.java
UTF-8
1,759
2.40625
2
[]
no_license
package dj.sjn.djbaedal.Adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import dj.sjn.djbaedal.DataClass.list_item; import dj.sjn.djbaedal.R; public class SearchAdapter extends BaseAdapter { private Context context; private List<list_item> list; private LayoutInflater inflater; private ViewHolder viewHolder; public SearchAdapter(List<list_item> list, Context context) { this.list = list; this.context = context; this.inflater = LayoutInflater.from(context); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = inflater.inflate(R.layout.search_item, null); viewHolder = new ViewHolder(); viewHolder.label = convertView.findViewById(R.id.label); viewHolder.label2 = convertView.findViewById(R.id.label2); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.label.setText(list.get(position).getName()); viewHolder.label2.setText(list.get(position).getType()); return convertView; } class ViewHolder { public TextView label, label2; } }
true
779a78b9c48ede4da321999354504514e5600564
Java
heaven6059/wms
/logistics-wms-city-1.1.3.44.5/logistics-wms-city-common/src/main/java/com/yougou/logistics/city/common/model/BillOmDirectLog.java
UTF-8
2,301
1.992188
2
[]
no_license
/* * 类名 com.yougou.logistics.city.common.model.BillOmDirectLog * @author su.yq * @date Tue Nov 05 09:32:53 CST 2013 * @version 1.0.0 * @copyright (C) 2013 YouGou Information Technology Co.,Ltd * All Rights Reserved. * * The software for the YouGou technology development, without the * company's written consent, and any other individuals and * organizations shall not be used, Copying, Modify or distribute * the software. * */ package com.yougou.logistics.city.common.model; public class BillOmDirectLog { private String locno; private String ownerNo; private String expNo; private String locateNo; private String itemNo; private String sizeNo; private String errorReason; /** * 用于页面展示 * @return */ private String itemName;//商品名称 private String colorName;//颜色名称 private String styleNo;//商品款号 private String brandNo;//品牌编码 public String getLocno() { return locno; } public void setLocno(String locno) { this.locno = locno; } public String getOwnerNo() { return ownerNo; } public void setOwnerNo(String ownerNo) { this.ownerNo = ownerNo; } public String getExpNo() { return expNo; } public void setExpNo(String expNo) { this.expNo = expNo; } public String getLocateNo() { return locateNo; } public void setLocateNo(String locateNo) { this.locateNo = locateNo; } public String getItemNo() { return itemNo; } public void setItemNo(String itemNo) { this.itemNo = itemNo; } public String getSizeNo() { return sizeNo; } public void setSizeNo(String sizeNo) { this.sizeNo = sizeNo; } public String getErrorReason() { return errorReason; } public void setErrorReason(String errorReason) { this.errorReason = errorReason; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getColorName() { return colorName; } public void setColorName(String colorName) { this.colorName = colorName; } public String getStyleNo() { return styleNo; } public void setStyleNo(String styleNo) { this.styleNo = styleNo; } public String getBrandNo() { return brandNo; } public void setBrandNo(String brandNo) { this.brandNo = brandNo; } }
true
db7c0db25388251780ef47a5ff2843126222ec9e
Java
hage1527/Daily-learning
/mybatistest/mybatis_annotation/src/main/java/com/hage/mybatis01/dao/IUserDao.java
UTF-8
1,206
2.21875
2
[]
no_license
package com.hage.mybatis01.dao; import com.hage.mybatis01.entity.User; import org.apache.ibatis.annotations.Many; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.mapping.FetchType; import java.util.List; /** * 用户的持久层接口 */ public interface IUserDao { /** * 查找所有的user并找出相关的account * @return */ @Select("select * from user") @Results(id = "userMap",value = { @Result(id = true,property = "id",column = "id"), @Result(property = "username",column = "username"), @Result(property = "birthday",column = "birthday"), @Result(property = "sex",column = "sex"), @Result(property = "address",column = "address"), @Result(property = "accounts",column = "id",many =@Many(select = "com.hage.mybatis01.dao.IAccountUserDao.findByUid",fetchType = FetchType.EAGER)) }) List<User> findAll(); /** * 根据id查询用 * @param userId * @return */ @Select("select * from user where id = #{id}") User findById(Integer userId); }
true
d2360c88135a2098fb9337e6adbe215a9a03aa03
Java
icepaule/kestra
/core/src/main/java/io/kestra/core/tasks/scripts/AbstractBash.java
UTF-8
10,886
1.945313
2
[ "Apache-2.0" ]
permissive
package io.kestra.core.tasks.scripts; import io.kestra.core.models.annotations.PluginProperty; import io.kestra.core.models.executions.AbstractMetricEntry; import io.kestra.core.models.tasks.Task; import io.kestra.core.runners.RunContext; import io.kestra.core.tasks.scripts.runners.DockerScriptRunner; import io.kestra.core.tasks.scripts.runners.ProcessBuilderScriptRunner; import io.kestra.core.tasks.scripts.runners.ScriptRunnerInterface; import io.micronaut.core.annotation.Introspected; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; import lombok.experimental.SuperBuilder; import org.slf4j.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import static io.kestra.core.utils.Rethrow.throwBiConsumer; @SuperBuilder @ToString @EqualsAndHashCode @Getter @NoArgsConstructor abstract public class AbstractBash extends Task { @Builder.Default @Schema( title = "Runner to use" ) @PluginProperty(dynamic = false) @NotNull @NotEmpty protected AbstractBash.Runner runner = Runner.PROCESS; @Schema( title = "Docker options when using runner `DOCKER`" ) protected DockerOptions dockerOptions; @Builder.Default @Schema( title = "Interpreter to used" ) @PluginProperty(dynamic = false) @NotNull @NotEmpty protected String interpreter = "/bin/sh"; @Builder.Default @Schema( title = "Interpreter args used" ) @PluginProperty(dynamic = false) protected String[] interpreterArgs = {"-c"}; @Builder.Default @Schema( title = "Exit if any non true return value", description = "This tells bash that it should exit the script if any statement returns a non-true return value. \n" + "The benefit of using -e is that it prevents errors snowballing into serious issues when they could " + "have been caught earlier." ) @PluginProperty(dynamic = false) @NotNull protected Boolean exitOnFailed = true; @Schema( title = "The list of files that will be uploaded to internal storage, ", description ="use `outputFiles` property instead", deprecated = true ) @PluginProperty(dynamic = true) @Deprecated protected List<String> files; @Schema( title = "Deprecated Output file", description = "use `outputFiles`", deprecated = true ) @PluginProperty(dynamic = false) @Deprecated protected List<String> outputsFiles; @Schema( title = "Output file list that will be uploaded to internal storage", description = "List of key that will generate temporary files.\n" + "On the command, just can use with special variable named `outputFiles.key`.\n" + "If you add a files with `[\"first\"]`, you can use the special vars `echo 1 >> {[ outputFiles.first }}`" + " and you used on others tasks using `{{ outputs.task-id.files.first }}`" ) @PluginProperty(dynamic = false) protected List<String> outputFiles; @Schema( title = "Input files are extra files supplied by user that make it simpler organize code.", description = "Describe a files map that will be written and usable in execution context. In python execution " + "context is in a temp folder, for bash scripts, you can reach files using a workingDir variable " + "like 'source {{workingDir}}/myfile.sh' " ) @PluginProperty( additionalProperties = String.class, dynamic = true ) protected Map<String, String> inputFiles; @Schema( title = "Additional environnements variable to add for current process." ) @PluginProperty( additionalProperties = String.class, dynamic = true ) protected Map<String, String> env; @Getter(AccessLevel.NONE) protected transient Path workingDirectory; @Builder.Default @Getter(AccessLevel.NONE) protected transient Map<String, Object> additionalVars = new HashMap<>(); protected Map<String, String> finalInputFiles() throws IOException { return this.inputFiles != null ? new HashMap<>(this.inputFiles) : new HashMap<>(); } protected List<String> finalCommandsWithInterpreter(String commandAsString) throws IOException { return BashService.finalCommandsWithInterpreter( this.interpreter, this.interpreterArgs, commandAsString, workingDirectory ); } @SuppressWarnings("deprecation") protected ScriptOutput run(RunContext runContext, Supplier<String> supplier) throws Exception { Logger logger = runContext.logger(); if (this.workingDirectory == null) { this.workingDirectory = runContext.tempDir(); } additionalVars.put("workingDir", workingDirectory.toAbsolutePath().toString()); List<String> allOutputs = new ArrayList<>(); // deprecated properties if (this.outputFiles != null && this.outputFiles.size() > 0) { allOutputs.addAll(this.outputFiles); } if (this.outputsFiles != null && this.outputsFiles.size() > 0) { allOutputs.addAll(this.outputsFiles); } if (files != null && files.size() > 0) { allOutputs.addAll(files); } Map<String, String> outputFiles = BashService.createOutputFiles( workingDirectory, allOutputs, additionalVars ); BashService.createInputFiles( runContext, workingDirectory, this.finalInputFiles(), additionalVars ); String commandAsString = supplier.get(); // run RunResult runResult = this.run( runContext, logger, workingDirectory, finalCommandsWithInterpreter(commandAsString), this.env, (inputStream, isStdErr) -> { AbstractLogThread thread = new LogThread(logger, inputStream, isStdErr, runContext); thread.setName("bash-log-" + (isStdErr ? "-err" : "-out")); thread.start(); return thread; } ); // upload output files Map<String, URI> uploaded = new HashMap<>(); outputFiles. forEach(throwBiConsumer((k, v) -> uploaded.put(k, runContext.putTempFile(new File(runContext.render(v, additionalVars)))))); Map<String, Object> outputsVars = new HashMap<>(); outputsVars.putAll(runResult.getStdOut().getOutputs()); outputsVars.putAll(runResult.getStdErr().getOutputs()); // output return ScriptOutput.builder() .exitCode(runResult.getExitCode()) .stdOutLineCount(runResult.getStdOut().getLogsCount()) .stdErrLineCount(runResult.getStdErr().getLogsCount()) .vars(outputsVars) .files(uploaded) .outputFiles(uploaded) .build(); } protected RunResult run(RunContext runContext, Logger logger, Path workingDirectory, List<String> commandsWithInterpreter, Map<String, String> env, LogSupplier logSupplier) throws Exception { ScriptRunnerInterface executor; if (this.runner == Runner.DOCKER) { executor = new DockerScriptRunner(runContext.getApplicationContext()); } else { executor = new ProcessBuilderScriptRunner(); } return executor.run( this, runContext, logger, workingDirectory, commandsWithInterpreter, env, logSupplier, additionalVars ); } @NoArgsConstructor @Data public static class BashCommand <T> { private Map<String, Object> outputs; private List<AbstractMetricEntry<T>> metrics; } @FunctionalInterface public interface LogSupplier { AbstractLogThread call(InputStream inputStream, boolean isStdErr) throws Exception; } public static class LogThread extends AbstractLogThread { private final Logger logger; private final boolean isStdErr; private final RunContext runContext; public LogThread(Logger logger, InputStream inputStream, boolean isStdErr, RunContext runContext) { super(inputStream); this.logger = logger; this.isStdErr = isStdErr; this.runContext = runContext; } protected void call(String line) { outputs.putAll(BashService.parseOut(line, logger, runContext)); if (isStdErr) { logger.warn(line); } else { logger.info(line); } } } @Getter @Builder public static class BashException extends Exception { private static final long serialVersionUID = 1L; private final int exitCode; private final int stdOutSize; private final int stdErrSize; public BashException(int exitCode, int stdOutSize, int stdErrSize) { super("Command failed with code " + exitCode); this.exitCode = exitCode; this.stdOutSize = stdOutSize; this.stdErrSize = stdErrSize; } } public enum Runner { PROCESS, DOCKER } @SuperBuilder @NoArgsConstructor @Getter @Introspected public static class DockerOptions { @Schema( title = "Docker api uri" ) @PluginProperty(dynamic = true) @Builder.Default private final String dockerHost = "unix:///var/run/docker.sock"; @Schema( title = "Docker config file", description = "Full file that can be used to configure private registries, ..." ) @PluginProperty(dynamic = true) private String dockerConfig; @Schema( title = "Docker image to use" ) @PluginProperty(dynamic = true) @NotNull @NotEmpty protected String image; @Schema( title = "Docker user to use" ) @PluginProperty(dynamic = true) protected String user; @Schema( title = "Docker entrypoint to use" ) @PluginProperty(dynamic = true) protected List<String> entryPoint; @Schema( title = "Docker extra host to use" ) @PluginProperty(dynamic = true) protected List<String> extraHosts; } }
true
7402de605c1d98bebaadffe4a6f9efe4916feb35
Java
OCHA-DAP/DAP-System
/HDX-System/src/main/java/org/ocha/hdx/validation/itemvalidator/IValidator.java
UTF-8
1,067
2.171875
2
[ "Unlicense" ]
permissive
/** * */ package org.ocha.hdx.validation.itemvalidator; import org.ocha.hdx.model.validation.ValidationStatus; import org.ocha.hdx.persistence.entity.curateddata.Indicator; import org.ocha.hdx.persistence.entity.curateddata.IndicatorImportConfig; import org.ocha.hdx.validation.Response; /** * @author alexandru-m-g * */ public interface IValidator { String getValidatorName(); /** * * @param preparedIndicator - the indicator that needs to be validated * @return {@link ValidationStatus#ERROR} if the validation fails and the indicator should not be allowed to pass to the curated set * {@link ValidationStatus#WARNING} if the validation fails but the indicator should still be allowed to pass to the curated set * {@link ValidationStatus#SUCCESS} if the validation succeeds * */ Response validate(Indicator indicator); void populateImportConfig(final IndicatorImportConfig importConfig, final Response response); /** * * @return true if it has all the necessary configuration data to run the validation */ boolean useable(); }
true
bde41189948e9f4b216b1e026fcbb5e70fb7e12c
Java
nice01qc/IdeaProjects
/algorithm/src/main/java/graphTheory/shortestpath/AcyclicSP.java
UTF-8
1,967
3.25
3
[]
no_license
package graphTheory.shortestpath; import edu.princeton.cs.algs4.Bag; import edu.princeton.cs.algs4.DepthFirstOrder; import edu.princeton.cs.algs4.Digraph; import edu.princeton.cs.algs4.Topological; /** * 无环加权有向图的最短路径算法 */ public class AcyclicSP { private DirectedEdge[] edgeTo; private double[] distTo; public AcyclicSP(EdgeWeightedDigraph G,int s){ //初始化 edgeTo = new DirectedEdge[G.V()]; distTo = new double[G.V()]; distTo[s] = 0.0; for (int v=0;v<G.V();v++){ distTo[v] = Double.POSITIVE_INFINITY; } //深度优先搜索搞成拓扑 Digraph digraph = new Digraph(G.V()); for (DirectedEdge directedEdge : G.edges()){ digraph.addEdge(directedEdge.from(),directedEdge.to()); } DepthFirstOrder depthFirstOrder = new DepthFirstOrder(digraph); Iterable<Integer> a = depthFirstOrder.reversePost(); for (int v:a){ // int pan=0; // if (v==s){ // relax(G,v); // pan = 1; // }else if (pan==1){ // relax(G,v); // } relax(G,v); //刚好利用了无穷大与无穷大比较为false的结果来跳过 } } private void relax(EdgeWeightedDigraph G,int v){ for (DirectedEdge e:G.adj(v)){ int w = e.to(); if (distTo[v]+e.weight()<distTo[w]){ distTo[w] = distTo[v]+e.weight(); edgeTo[w] = e; } } } public double distTo(int v){ return distTo[v]; } public boolean hasPathTo(int v){ return distTo[v]<Double.POSITIVE_INFINITY; } public Iterable<DirectedEdge> pathTo(int v){ Bag<DirectedEdge> bag = new Bag<DirectedEdge>(); for (DirectedEdge d = edgeTo[v];d!=null;d=edgeTo[d.from()]){ bag.add(d); } return bag; } }
true
94c12d191843977063be06d87654e7bbebddecaf
Java
ZhouRuiQing/Movie
/app/src/main/java/com/bw/movie/mvp/view/apdater/tabapdaters/MovieHotApdater.java
UTF-8
2,016
2.015625
2
[]
no_license
package com.bw.movie.mvp.view.apdater.tabapdaters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.bw.movie.R; import com.bw.movie.mvp.model.bean.Movieinfo; import java.util.List; public class MovieHotApdater extends RecyclerView.Adapter<MovieHotViewHoder> { Context context; List<Movieinfo.ResultBean> list; boolean guanzhu = false; public MovieHotApdater(Context context, List<Movieinfo.ResultBean> list) { this.context = context; this.list = list; } @NonNull @Override public MovieHotViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { MovieHotViewHoder hoder = new MovieHotViewHoder(LayoutInflater.from(context).inflate(R.layout.movie_hot_item,parent,false)); return hoder; } @Override public void onBindViewHolder(@NonNull final MovieHotViewHoder holder, int position) { Glide.with(context).load(list.get(position).getImageUrl()).into(holder.ivMovieImage); //holder.ivMovieImage.setImageURI(Uri.parse(list.get(position).getImageUrl())); holder.tvTitle.setText(list.get(position).getSummary()); holder.tvname.setText(list.get(position).getName()+""); holder.hot_btn_heart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(v==holder.hot_btn_heart){ if(guanzhu){ holder.hot_btn_heart.setImageResource(R.drawable.guanzhu); }else { holder.hot_btn_heart.setImageResource(R.drawable.guanzhu1); } guanzhu=!guanzhu; } } }); } @Override public int getItemCount() { return list.size(); } }
true
64a51f0d2aa49d0c826f54ca35e02b64c986c86c
Java
PuZZleDucK/aCrawler
/aCrawl/src/com/puzzleduck/crawler/ACrawlStarter.java
UTF-8
1,172
2.453125
2
[]
no_license
/** * (C)me & GPL3 * Webcrawl start/restart listener ... need i say more. */ package com.puzzleduck.crawler; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ForkJoinPool; /** * @author bminerds * */ public class ACrawlStarter implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent arg0) { //check for running instances first... and simply kill if found... would be nice to go through and resume someday... not today if(ACrawler.forkPool == null) { ACrawler.forkPool = new ForkJoinPool(4); }else{ ACrawler.forkPool = null; ACrawler.initDB(); ACrawler.forkPool = new ForkJoinPool(4); } String startUrl = (String) ACrawler.startingAddressComboBox.getSelectedItem(); try { System.out.println( "Crawl start: " + startUrl ); ACrawler.forkPool.invoke( new LinkSearch(startUrl, new AppData()) ); }catch(Exception e) { System.out.println( "Error starting crawl: " + e.toString() ); } }//action }//class
true
b36531b9637227ee8d011a8774d8db328cc73432
Java
Pinyk/study
/java进阶/多线程/src/com/two/Main.java
UTF-8
328
2.296875
2
[]
no_license
package com.two; public class Main { public static void main(String[] args) { MyThread a = new MyThread("线程一"); MyThread b = new MyThread("线程二"); MyThread c = new MyThread("线程三"); new Thread(a).start(); new Thread(b).start(); new Thread(c).start(); } }
true
1ab7666f9a63d41b6698bac8840a2379e5749fb0
Java
skyzzango/Study-Example-AOP-SpringBoot
/src/main/java/com/example/aop/history/domain/History.java
UTF-8
902
2.484375
2
[]
no_license
package com.example.aop.history.domain; import javax.persistence.*; import java.util.Date; @Entity public class History { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long idx; @Column private long userIdx; @Column private Date updateDate; public History() { } public History(long userIdx) { this.userIdx = userIdx; this.updateDate = new Date(); } public long getIdx() { return idx; } public void setIdx(long idx) { this.idx = idx; } public long getUserIdx() { return userIdx; } public void setUserIdx(long userIdx) { this.userIdx = userIdx; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } @Override public String toString() { return "History{" + "idx=" + idx + ", userIdx=" + userIdx + ", updateDate=" + updateDate + '}'; } }
true
dfb3af8b4f9f73e17f9815f5a986ae46ed23b15d
Java
Vinayabali5/Data-creation
/main/generated-sources/uk/ac/reigate/domain/academic/QIdentificationViolation.java
UTF-8
2,515
1.898438
2
[]
no_license
package uk.ac.reigate.domain.academic; import static com.querydsl.core.types.PathMetadataFactory.*; import com.querydsl.core.types.dsl.*; import com.querydsl.core.types.PathMetadata; import javax.annotation.Generated; import com.querydsl.core.types.Path; import com.querydsl.core.types.dsl.PathInits; /** * QIdentificationViolation is a Querydsl query type for IdentificationViolation */ @Generated("com.querydsl.codegen.EntitySerializer") public class QIdentificationViolation extends EntityPathBase<IdentificationViolation> { private static final long serialVersionUID = 62424121L; private static final PathInits INITS = PathInits.DIRECT2; public static final QIdentificationViolation identificationViolation = new QIdentificationViolation("identificationViolation"); public final uk.ac.reigate.domain.QBaseEntity _super = new uk.ac.reigate.domain.QBaseEntity(this); public final DateTimePath<java.util.Date> date = createDateTime("date", java.util.Date.class); //inherited public final NumberPath<Integer> id = _super.id; public final NumberPath<Integer> id_number = createNumber("id_number", Integer.class); public final BooleanPath lost = createBoolean("lost"); //inherited public final SimplePath<groovy.lang.MetaClass> metaClass = _super.metaClass; public final BooleanPath printed = createBoolean("printed"); public final BooleanPath returned = createBoolean("returned"); public final QStudent student; public final QAcademicYear year; public QIdentificationViolation(String variable) { this(IdentificationViolation.class, forVariable(variable), INITS); } public QIdentificationViolation(Path<? extends IdentificationViolation> path) { this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS)); } public QIdentificationViolation(PathMetadata metadata) { this(metadata, PathInits.getFor(metadata, INITS)); } public QIdentificationViolation(PathMetadata metadata, PathInits inits) { this(IdentificationViolation.class, metadata, inits); } public QIdentificationViolation(Class<? extends IdentificationViolation> type, PathMetadata metadata, PathInits inits) { super(type, metadata, inits); this.student = inits.isInitialized("student") ? new QStudent(forProperty("student"), inits.get("student")) : null; this.year = inits.isInitialized("year") ? new QAcademicYear(forProperty("year")) : null; } }
true
24d995cc735d9932012deaee3b9eccba92e363a9
Java
luoxiaoshan/lxs-repo
/WorkdayCalculator/src/workdaycalculator/Workday.java
UTF-8
6,691
2.984375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package workdaycalculator; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; /** * * @author Mike */ public class Workday { private static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private List<Date> workDay = new ArrayList<Date>(); private List<Date> festival = new ArrayList<Date>(); private File excel_file; //对应EXCEL文件 private Workbook work_book; //JXL接口对应的EXCEL文件 private Sheet main_sheet; //EXCEL文件中MAIN sheet private Cell cell; //单元格 public Workday(String file_name) { this.excel_file = new File(file_name); try { this.work_book = Workbook.getWorkbook(excel_file); } catch (BiffException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } main_sheet = this.work_book.getSheet(0); int row_num = main_sheet.getRows(); for (int i = 0; i < row_num; i++) { if (main_sheet.getCell(1, i).getContents().equals("w")) { try { workDay.add(sdf.parse(main_sheet.getCell(0, i).getContents())); } catch (ParseException ex) { Logger.getLogger(Workday.class.getName()).log(Level.SEVERE, null, ex); } } if (main_sheet.getCell(1, i).getContents().equals("f")) { try { festival.add(sdf.parse(main_sheet.getCell(0, i).getContents())); } catch (ParseException ex) { Logger.getLogger(Workday.class.getName()).log(Level.SEVERE, null, ex); } } } } public double getWorkdays(Date startdate, Date enddate) { try { Date tempdate = new Date(); Date f_sd = sdf.parse(sdf.format(startdate));//开始日期的零点 Date f_ed = sdf.parse(sdf.format(enddate));//结束日期的零点 long days = (f_ed.getTime() - f_sd.getTime()) / 86400000 + 1;//横跨多少天 long sttime = 0; long edtime = 0; long worktimes = 0; sttime = startdate.getTime(); for (int i = 0; i < days; i++) { tempdate.setTime(f_sd.getTime() + (long) 24 * 3600000 * i); //相对开始日期后i天零点的时间 if (this.isWorkDay(tempdate)) { edtime = tempdate.getTime() + (long) 24 * 3600000;//相对开始日期后i+1天零点的时间 if (edtime <= enddate.getTime()) { worktimes += edtime - sttime; sttime = edtime; } else { worktimes += enddate.getTime() - sttime; } } else { sttime = tempdate.getTime() + (long) 24 * 3600000; } } double res = round((double) worktimes / 3600000 / 24, 4, BigDecimal.ROUND_HALF_UP);//(double)worktimes/3600000/24); return res; //return 0; } catch (ParseException ex) { Logger.getLogger(Workday.class.getName()).log(Level.SEVERE, null, ex); return -1; } } public double getWorkdays(String startdate, String enddate) { try { return getWorkdays(sdf.parse(startdate), sdf.parse(enddate)); } catch (ParseException ex) { Logger.getLogger(Workday.class.getName()).log(Level.SEVERE, null, ex); return -1; } } public double getWorkdays(long startdate, long enddate) { Date sd = new Date(); Date ed = new Date(); sd.setTime(startdate); ed.setTime(enddate); return getWorkdays(sd, ed); } /*******************************************************************************/ public List getFestival() { return this.festival; } public List getSpecialWorkDay() { return this.workDay; } /** * 判断一个日期是否日节假日 * 法定节假日只判断月份和天,不判断年 * @param date * @return */ public boolean isFestival(Date date) { boolean festival = false; Calendar fcal = Calendar.getInstance(); Calendar dcal = Calendar.getInstance(); dcal.setTime(date); List<Date> list = this.getFestival(); for (Date dt : list) { fcal.setTime(dt); //法定节假日判断 if (fcal.get(Calendar.MONTH) == dcal.get(Calendar.MONTH) && fcal.get(Calendar.DATE) == dcal.get(Calendar.DATE)) { festival = true; } } return festival; } public boolean isWeekend(Date date) { boolean weekend = false; Calendar cal = Calendar.getInstance(); cal.setTime(date); if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { weekend = true; } return weekend; } public boolean isWorkDay(Date date) { boolean workday = true; if (this.isFestival(date) || this.isWeekend(date)) { workday = false; } /*特殊工作日判断*/ Calendar cal1 = Calendar.getInstance(); cal1.setTime(date); Calendar cal2 = Calendar.getInstance(); for (Date dt : this.workDay) { cal2.setTime(dt); if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DATE) == cal2.get(Calendar.DATE)) { //年月日相等为特殊工作日 workday = true; } } return workday; } private double round(double value, int scale, int roundingMode) { BigDecimal bd = new BigDecimal(value); bd = bd.setScale(scale, roundingMode); double d = bd.doubleValue(); bd = null; return d; } }
true
be30113f131be18ec4aa2181f02e027989ba1314
Java
KittehOrg/Spectastic
/src/main/java/org/kitteh/spectastic/data/gamemode/PastGameModeDataManipulatorBuilder.java
UTF-8
2,380
1.84375
2
[ "MIT" ]
permissive
/* * * Copyright (C) 2016 Matt Baxter http://kitteh.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.kitteh.spectastic.data.gamemode; import org.kitteh.spectastic.Spectastic; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataView; import org.spongepowered.api.data.manipulator.DataManipulatorBuilder; import org.spongepowered.api.data.persistence.InvalidDataException; import javax.annotation.Nonnull; import java.util.Optional; public class PastGameModeDataManipulatorBuilder implements DataManipulatorBuilder<PastGameModeData, ImmutablePastGameModeData> { @Nonnull @Override public PastGameModeData create() { return new PastGameModeData(); } @Nonnull @Override public Optional<PastGameModeData> createFrom(@Nonnull DataHolder dataHolder) { return Optional.of(dataHolder.get(PastGameModeData.class).orElse(new PastGameModeData())); } @Nonnull @Override public Optional<PastGameModeData> build(@Nonnull DataView container) throws InvalidDataException { // TODO check content version once bumped if (container.contains(Spectastic.PAST_GAMEMODE)) { return Optional.of(new PastGameModeData(container.getString(Spectastic.PAST_GAMEMODE.getQuery()).get())); } return Optional.empty(); } }
true
38a14e49bc5119f4a043e1a71d970c434f8f5ecf
Java
abinkh/reactSpringStaticHost
/src/main/java/com/backend/service/ProductServiceImpl.java
UTF-8
645
2.21875
2
[]
no_license
package com.backend.service; import com.backend.dao.ProductDao; import com.backend.model.Product; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; /** * Created by abin on 12/12/2017. */ @Service @Transactional public class ProductServiceImpl implements ProductService { @Autowired private ProductDao productDao; @Override public void insert(Product product) { productDao.insert(product); } @Override public List<Product> listAll() { return productDao.listAll(); } }
true