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
fdba0ba08ac67c27ef7223e3864275b27814f20e
Java
QiuDongMing/blog
/blog-service/src/main/java/com/codermi/blog/article/data/po/ArticleCategory.java
UTF-8
519
1.664063
2
[]
no_license
package com.codermi.blog.article.data.po; import com.codermi.blog.common.data.po.BaseInfo; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * @author qiudm * @date 2018/7/30 10:54 * @desc 文章分类 */ @Document(collection = "t_article_category") @Data public class ArticleCategory extends BaseInfo { /** * 分类名称 */ private String name; /** * 用户id */ private String userId; }
true
5e11393f4f6a0d2221cdd1ba3644ac5bd9da0f6e
Java
bburdick-code/furniture-donations
/src/main/java/org/hospitalityprogram/furnituredonations/data/DonationBatchRepository.java
UTF-8
343
1.742188
2
[ "MIT" ]
permissive
package org.hospitalityprogram.furnituredonations.data; import org.hospitalityprogram.furnituredonations.models.DonationBatch; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface DonationBatchRepository extends CrudRepository<DonationBatch, Integer> { }
true
819f96119692a2e41f2eabf58264aa6d3e06810a
Java
Falconier/JavaConcepts
/TemperatureConversion_JacobBullin.java
UTF-8
3,503
3.671875
4
[]
no_license
package javaconcepts; import java.util.Scanner; public class TemperatureConversion_JacobBullin { public static void tempConverter() { double farhenheit = 212; double celsius = 100; double kelvin = 373.15; Scanner in = new Scanner(System.in); Scanner fin = new Scanner(System.in); Scanner cin = new Scanner(System.in); Scanner kin = new Scanner(System.in); System.out.println("This converter currently supports conversions form the following:"); System.out.println("farhenheit, celsius, kelvin"); System.out.println("rankine is currently not supported"); System.out.println(""); System.out.print("What unit are you converting from (farhenheit 'f', celsius 'c', or kelvin 'k'): "); String unit = in.nextLine(); if (unit.equals("F") || unit.equals("f") || unit.equals("farhenheit") || unit.equals("Farhenheit")) { System.out.print("Please enter the temperature: "); farhenheit = fin.nextDouble(); celsius = (farhenheit - 32.0) * 5.0 / 9.0; kelvin = (celsius + 273.15); } else if (unit.equals("c") || unit.equals("C") || unit.equals("celsius") || unit.equals("Celsius")) { System.out.print("Please enter the temperature: "); celsius = cin.nextDouble(); farhenheit = (celsius / (5.0 / 9.0)) + 32; kelvin = (celsius + 273.15); } else if (unit.equals("k") || unit.equals("K") || unit.equals("kelvin") || unit.equals("Kelvin")) { System.out.print("Please enter the temperature: "); kelvin = kin.nextDouble(); celsius = (kelvin - 273.15); farhenheit = (celsius / (5.0 / 9.0)) + 32; } else if (!unit.equals("F") || !unit.equals("f") || !unit.equals("farhenheit") || !unit.equals("Farhenheit") || !unit.equals("c") || !unit.equals("C") || !unit.equals("celsius") || !unit.equals("Celsius") || !unit.equals("k") || !unit.equals("K") || !unit.equals("kelvin") || !unit.equals("Kelvin")) { tempConverter(); } System.out.println(farhenheit + " F"); System.out.println(celsius + " C"); System.out.println(kelvin + " K"); System.exit(0); } /** * Converts farhenheit to celsius and kelvin * * @return a double for the temperature in celsius and kelvin */ public static void convFarhenheit() { Scanner fin = new Scanner(System.in); double farhenheit = 212; double celsius = 100; double kelvin = 373.15; System.out.print("Please enter the farhenheit temperature: "); farhenheit = fin.nextDouble(); celsius = (farhenheit - 32.0) * 5.0 / 9.0; kelvin = (celsius + 273.15); System.out.println(farhenheit + " F = "); System.out.println(celsius + " C"); System.out.println(kelvin + " K"); } public static void convCelsius() { Scanner cin = new Scanner(System.in); double farhenheit = 212; double celsius = 100; double kelvin = 373.15; System.out.print("Please enter the celsius temperature: "); celsius = cin.nextDouble(); farhenheit = (celsius / (5.0 / 9.0)) + 32; kelvin = (celsius + 273.15); System.out.println(celsius + " C = "); System.out.println(farhenheit + " F"); System.out.println(kelvin + " K"); } public static void convKelvin() { Scanner kin = new Scanner(System.in); double farhenheit = 212; double celsius = 100; double kelvin = 373.15; System.out.print("Please enter the kelvin temperature: "); kelvin = kin.nextDouble(); celsius = (kelvin - 273.15); farhenheit = (celsius / (5.0 / 9.0)) + 32; System.out.println(kelvin + " K = "); System.out.println(farhenheit + " F"); System.out.println(celsius + " C"); } }
true
4b209ccf0ea91cf288d294c45188e81a6b1028a3
Java
crackHu/hhw
/server/src/main/java/com/vds/app/order/service/impl/OrderPayKindServiceImpl.java
UTF-8
741
1.882813
2
[]
no_license
package com.vds.app.order.service.impl; import javax.inject.Inject; import com.vds.app.exception.Msg; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.vds.app.base.BaseServiceImpl; import com.vds.app.order.model.OrderPayKind; import com.vds.app.order.jpa.OrderPayKindJpa; import com.vds.app.order.service.OrderPayKindService; @Service public class OrderPayKindServiceImpl extends BaseServiceImpl<OrderPayKind> implements OrderPayKindService{ @Inject private OrderPayKindJpa orderPayKindJpa; public Msg findAll(Pageable pageable) { Page<OrderPayKind> list = orderPayKindJpa.findAll(pageable); return Msg.MsgSuccess(list); } }
true
81f763d3dee484b135d5f73be170dcc14e7788a0
Java
argggh/one-jar
/sdk/src/main/com/simontuffs/onejar/hello/Main.java
UTF-8
149
1.5625
2
[]
no_license
package com.simontuffs.onejar.hello; public class Main { public static void main(String args[]) { new Hello().sayHello(); } }
true
cc041be64912b5f4d7480b4264a24069dafb17ad
Java
xiaohei-maker/aaa
/src/main/java/com/example/demo/Service/UserService.java
UTF-8
4,493
2.25
2
[]
no_license
package com.example.demo.Service; import com.example.demo.Mapper.UserMapper; import com.example.demo.Model.User; import com.example.demo.Model.UserExample; import com.example.uitils.EmailUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; //GitHub 登录和修改 public void cerateOrupdata(User user) { UserExample userExample = new UserExample(); userExample.createCriteria() .andAccountIdEqualTo(user.getAccountId()); List<User> users = userMapper.selectByExample(userExample); if (users.size() == 0) { // 插入 user.setGmtCreate(System.currentTimeMillis()); user.setGmtModified(user.getGmtCreate()); userMapper.insert(user); } else { //更新 User dbUser = users.get(0); User updateUser = new User(); updateUser.setGmtModified(System.currentTimeMillis()); updateUser.setAvatarUrl(user.getAvatarUrl()); updateUser.setName(user.getName()); updateUser.setToken(user.getToken()); UserExample example = new UserExample(); example.createCriteria() .andIdEqualTo(dbUser.getId()); userMapper.updateByExampleSelective(updateUser, example); } } public String createUser(User user) { UserExample userExample = new UserExample(); userExample.createCriteria(). andNameEqualTo(user.getName()); List<User> users = userMapper.selectByExample(userExample); EmailUtils.sendEmail(user); if(users.size() != 0){ return null; } user.setGmtCreate(System.currentTimeMillis()); user.setGmtModified(user.getGmtCreate()); user.setStatus(0); String a= String.valueOf(userMapper.insert(user)); return a; } public User LoginUser(String username) { UserExample userExample = new UserExample(); userExample.createCriteria(). andNameEqualTo(username); List<User> users = userMapper.selectByExample(userExample); for (User user1:users) { if(user1.getName().equals(username)){ if (user1.getStatus()==null){ UserExample example = new UserExample(); user1.setStatus(1); example.createCriteria() .andIdEqualTo(user1.getId()); userMapper.updateByExampleSelective(user1, example); } if (user1.getStatus().equals(0)){ return user1; }else { UserExample example = new UserExample(); user1.setGmtModified(System.currentTimeMillis()); example.createCriteria() .andIdEqualTo(user1.getId()); userMapper.updateByExampleSelective(user1, example); return user1; } } } return null; } public Integer selectCode(String c) { UserExample userExample = new UserExample(); userExample.createCriteria(). andCodeEqualTo(c); List<User> users = userMapper.selectByExample(userExample); if(users.size() != 0){ for (User user1:users) { if(user1.getCode().equals(c)){ //更新 UserExample example = new UserExample(); user1.setStatus(1); example.createCriteria() .andIdEqualTo(user1.getId()); userMapper.updateByExampleSelective(user1, example); return 1; } } } return 0; } public String selectUsername(String username) { UserExample userExample = new UserExample(); userExample.createCriteria(). andNameEqualTo(username); List<User> users = userMapper.selectByExample(userExample); if(users.size() != 0){ return "1"; }else { return "0"; } } }
true
4bdf298951f5a6dd6a3b549d431b26c566f872d3
Java
AlexBolot/MultiThreading
/src/main/java/multiThreading/seance1/App.java
UTF-8
1,171
2.96875
3
[]
no_license
package multiThreading.seance1; import java.util.ArrayList; import java.util.Random; /*................................................................................................................................ . Copyright (c) . . The App Class was Coded by : Alexandre BOLOT . . Last Modified : 11/04/17 23:51 . . Contact : bolotalex06@gmail.com ...............................................................................................................................*/ public class App { public static void main (String[] args) throws InterruptedException { long t1 = System.nanoTime(); final Random rand = new Random(); ArrayList<Thread> threadList = new ArrayList<Thread>(); for (int i = 0; i < 100; i++) { threadList.add(new MyThread()); } for (Thread tread : threadList) { tread.start(); } for (Thread tread : threadList) { tread.join(); } long t2 = System.nanoTime(); System.out.println(MyThread.c.get() + " - " + (t2 - t1) / 1000000); } }
true
46cc9ccd29ec92e203f30664b8662e07c7d7fa79
Java
pumpkinliquor/loveDiary
/src/main/java/com/plushih/entities/common/CommonResultEntity.java
UTF-8
1,547
1.789063
2
[]
no_license
package com.plushih.entities.common; import java.io.Serializable; import java.util.List; public class CommonResultEntity implements Serializable { private static final long serialVersionUID = -8264804965208752968L; private int resultPrimaryKey; private String resultCode; private String resultMessage; private String resultUrl; private String resultAction; private Object resultValue; private List<?> resultList; public int getResultPrimaryKey() { return resultPrimaryKey; } public void setResultPrimaryKey(int resultPrimaryKey) { this.resultPrimaryKey = resultPrimaryKey; } public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getResultMessage() { return resultMessage; } public void setResultMessage(String resultMessage) { this.resultMessage = resultMessage; } public String getResultUrl() { return resultUrl; } public void setResultUrl(String resultUrl) { this.resultUrl = resultUrl; } public String getResultAction() { return resultAction; } public void setResultAction(String resultAction) { this.resultAction = resultAction; } public Object getResultValue() { return resultValue; } public void setResultValue(Object resultValue) { this.resultValue = resultValue; } public List<?> getResultList() { return resultList; } public void setResultList(List<?> resultList) { this.resultList = resultList; } }
true
97fb510045898249da38ffd0f6eddbf0fb45673c
Java
justyce2/HotellookDagger
/app/src/main/java/com/hotellook/ui/screen/hotel/reviews/HotelReviewsItemView.java
UTF-8
1,700
1.992188
2
[ "Apache-2.0" ]
permissive
package com.hotellook.ui.screen.hotel.reviews; import android.annotation.SuppressLint; import android.content.Context; import android.databinding.DataBindingUtil; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.hotellook.C1178R; import com.hotellook.core.api.pojo.hoteldetail.TipData; import com.hotellook.databinding.HotelReviewsItemViewBinding; import com.hotellook.utils.ValueFormat; import me.zhanghai.android.materialprogressbar.BuildConfig; public class HotelReviewsItemView extends RelativeLayout { private HotelReviewsItemViewBinding binding; public HotelReviewsItemView(Context context, AttributeSet attrs) { super(context, attrs); } @NonNull public static HotelReviewsItemView create(@NonNull ViewGroup parent) { return (HotelReviewsItemView) LayoutInflater.from(parent.getContext()).inflate(C1178R.layout.hotel_reviews_item_view, parent, false); } protected void onFinishInflate() { super.onFinishInflate(); if (!isInEditMode()) { this.binding = (HotelReviewsItemViewBinding) DataBindingUtil.bind(this); } } @SuppressLint({"SetTextI18n"}) public void bindTo(@NonNull TipData review) { this.binding.name.setText(review.getUsername() + (TextUtils.isEmpty(review.getUserlastname()) ? BuildConfig.FLAVOR : " " + review.getUserlastname()) + ","); this.binding.date.setText(ValueFormat.reviewDateToString(getContext(), review.getCreatedAt())); this.binding.text.setText(review.getText()); } }
true
a24038775e2946d4a81ec01eb8f7e35289462cb7
Java
hexinatgithub/skeleton-sp18
/lab11/lab11/graphs/MazeCycles.java
UTF-8
1,459
3.28125
3
[]
no_license
package lab11.graphs; import edu.princeton.cs.algs4.Queue; import edu.princeton.cs.algs4.Stack; /** * @author Josh Hug */ public class MazeCycles extends MazeExplorer { /* Inherits public fields: public int[] distTo; public int[] edgeTo; public boolean[] marked; */ private boolean cycleFound; public MazeCycles(Maze m) { super(m); cycleFound = false; } @Override public void solve() { // TODO: Your code here! if (maze.N() == 0) return; dfs2(0); } // Helper methods go here private void dfs2(int v) { marked[v] = true; announce(); for (int u : maze.adj(v)) { if (marked[u] && edgeTo[v] != u) { edgeTo[u] = v; cycleFound = true; clearPath(u); announce(); break; } if (!marked[u]) { edgeTo[u] = v; announce(); dfs2(u); } if (cycleFound) break; } } private void clearPath(int cycleV) { int[] tmp = new int[maze.V()]; for (int i = 0; i < maze.V(); i += 1) { tmp[i] = Integer.MAX_VALUE; } int tv = cycleV; while (edgeTo[tv] != cycleV) { tmp[tv] = edgeTo[tv]; tv = edgeTo[tv]; } tmp[tv] = cycleV; edgeTo = tmp; } }
true
4ff73fa6d05bf6dc049ebe0b2a4501377bb5d343
Java
alexTrifonov/atrifonov
/chapter_003/src/test/java/ru/job4j/controlTask/TestSortSubdivision.java
UTF-8
1,540
2.8125
3
[ "Apache-2.0" ]
permissive
package ru.job4j.controlTask; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author atrifonov. * @since 12.08.2017. * @version 1. */ public class TestSortSubdivision { /** * Test sortAscendingCodes. */ @Test public void whenListHaveAbsentCodesAndNotSortedThenAddAbsentCodesAndAscendingSort() { SortSubdivision sortSubdivision = new SortSubdivision(); String[] strings = {"K1\\SK1", "K1\\SK2", "K1\\SK1\\SSK1", "K1\\SK1\\SSK2", "K2", "K2\\SK1\\SSK1", "K2\\SK1\\SSK2"}; String[] resultStrings = sortSubdivision.sortAscendingCodes(strings); String[] expectedStrings = {"K1", "K1\\SK1", "K1\\SK1\\SSK1", "K1\\SK1\\SSK2", "K1\\SK2", "K2", "K2\\SK1", "K2\\SK1\\SSK1", "K2\\SK1\\SSK2"}; assertThat(resultStrings, is(expectedStrings)); } /** * Test sortDecreaseCodes. */ @Test public void whenListHaveAbsentCodesAndNotSortedThenAddAbsentCodesAndDecreaseSort() { SortSubdivision sortSubdivision = new SortSubdivision(); String[] strings = {"K1\\SK1", "K1\\SK2", "K1\\SK1\\SSK1", "K1\\SK1\\SSK2", "K2", "K2\\SK1\\SSK1", "K2\\SK1\\SSK2"}; String[] resultStrings = sortSubdivision.sortDecreaseCodes(strings); String[] expectedStrings = {"K2", "K2\\SK1", "K2\\SK1\\SSK2", "K2\\SK1\\SSK1", "K1", "K1\\SK2", "K1\\SK1", "K1\\SK1\\SSK2", "K1\\SK1\\SSK1"}; assertThat(resultStrings, is(expectedStrings)); } }
true
420a7be90a96d5c19129aef3006d3267e0f718d5
Java
cc2013001/spring-cqrs
/src/main/java/net/exacode/example/application/query/querydsl/QPgDatabase.java
UTF-8
2,079
1.734375
2
[]
no_license
package net.exacode.example.application.query.querydsl; import static com.mysema.query.types.PathMetadataFactory.*; import com.mysema.query.types.path.*; import com.mysema.query.types.PathMetadata; import javax.annotation.Generated; import com.mysema.query.types.Path; /** * QPgDatabase is a Querydsl query type for QPgDatabase */ @Generated("com.mysema.query.sql.codegen.MetaDataSerializer") public class QPgDatabase extends com.mysema.query.sql.RelationalPathBase<QPgDatabase> { private static final long serialVersionUID = -2098580010; public static final QPgDatabase pgDatabase = new QPgDatabase("pg_database"); public final SimplePath<Object[]> datacl = createSimple("datacl", Object[].class); public final BooleanPath datallowconn = createBoolean("datallowconn"); public final StringPath datcollate = createString("datcollate"); public final NumberPath<Integer> datconnlimit = createNumber("datconnlimit", Integer.class); public final StringPath datctype = createString("datctype"); public final NumberPath<Long> datdba = createNumber("datdba", Long.class); public final SimplePath<Object> datfrozenxid = createSimple("datfrozenxid", Object.class); public final BooleanPath datistemplate = createBoolean("datistemplate"); public final NumberPath<Long> datlastsysoid = createNumber("datlastsysoid", Long.class); public final StringPath datname = createString("datname"); public final NumberPath<Long> dattablespace = createNumber("dattablespace", Long.class); public final NumberPath<Integer> encoding = createNumber("encoding", Integer.class); public QPgDatabase(String variable) { super(QPgDatabase.class, forVariable(variable), "pg_catalog", "pg_database"); } @SuppressWarnings("all") public QPgDatabase(Path<? extends QPgDatabase> path) { super((Class)path.getType(), path.getMetadata(), "pg_catalog", "pg_database"); } public QPgDatabase(PathMetadata<?> metadata) { super(QPgDatabase.class, metadata, "pg_catalog", "pg_database"); } }
true
017199b68db9a5b68ee26c25ab5807ca25554a8e
Java
yanglfm/Idea
/src/StudentMS/com/bochy/util/Matches.java
GB18030
1,763
2.921875
3
[]
no_license
package StudentMS.com.bochy.util; public class Matches { public static boolean matchesTel(String tel){ String regexTel="(13|15|18|17)\\d{9}"; boolean flag=tel.matches(regexTel); return flag; } public static boolean matchesEmail(String email){ String regexEmail="\\w+@\\w{2,4}(\\.)[comn]{2,3}"; boolean flag=email.matches(regexEmail); return flag; } public static String matchesTel1(String tel){ String regexTel="[1][3587]\\d{9}"; if(tel.matches(regexTel)){ return tel; }else { return null; } } public static String matchesTellphone(String tel){//ѡֻ֤ String regexTel="^[1][34587]\\d{9}$";//^$ֱʾпͷнβ if (tel.matches(regexTel)){ return tel; }else { return null; } } public static String matchesEmail1(String email){ String regexEmail="\\w+@\\w{2,4}(\\.)[comn]{2,3}"; if(email.matches(regexEmail)){ return email; }else { return null; } } public static int matchesAge(int age){ if(age>=1 && age<=120){ return age; }else { return 0; } } public static boolean matchesEmailX(String email){ String regexEmail="\\w+@\\w{2,4}(\\.)[comn]{2,3}(\\.)[comn]{2,3}"; boolean flag=email.matches(regexEmail); return flag; } public static void main(String[] args) { matchesEmail("sina@sina.com"); System.out.println(matchesEmail("sina@sina.com")); System.out.println(matchesTel1("15555173209")); System.out.println(matchesTellphone("15555173209")); } }
true
d3e6fcfddf47d863e97b0f9ce829a7281f28e0eb
Java
alcortesacerta/visor
/iecisa-commons-0.0.1-20170117.085307-900/src/main/java/mx/com/iecisa/commons/utils/StringFormatter.java
UTF-8
1,489
2.140625
2
[]
no_license
/* */ package mx.com.iecisa.commons.utils; /* */ /* */ import java.util.Collection; /* */ import org.apache.commons.lang.StringUtils; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class StringFormatter /* */ { /* 16 */ public static <T> String leftPad(T cad, char padding, int size) { return String.format("%" + size + "s", new Object[] { cad }).replace(' ', padding); } /* */ /* */ /* */ public static <T> String join(Collection<T> list, String separator, String startEndDelimiter) { /* 20 */ String result = null; /* */ /* 22 */ if (list != null && !list.isEmpty()) { /* 23 */ result = ""; /* 24 */ result = result + ((startEndDelimiter != null) ? startEndDelimiter : ""); /* */ /* 26 */ if (list.size() > 1) { /* 27 */ result = result + StringUtils.join(list, separator); /* */ } else { /* 29 */ result = result + list.toArray()[0]; /* */ } /* */ /* 32 */ result = result + ((startEndDelimiter != null) ? startEndDelimiter : ""); /* */ } /* */ /* */ /* 36 */ return result; /* */ } /* */ } /* Location: C:\Users\Alejandro Cortés\Desktop\VersionesVisor\saie-visor-2017ene17_1233.war!\WEB-INF\lib\iecisa-commons-0.0.1-20170117.085307-900.jar!\mx\com\iecisa\common\\utils\StringFormatter.class * Java compiler version: 7 (51.0) * JD-Core Version: 1.0.7 */
true
bab9775f076596340d55c401415ef68ba5f6ce14
Java
LeonidasB/payment-system-poc
/payment-system-core/src/main/java/com/intuit/paymentsystem/core/handler/PaymentHandler.java
UTF-8
1,826
2.40625
2
[]
no_license
package com.intuit.paymentsystem.core.handler; import com.intuit.paymentsystem.api.Payment; import com.intuit.paymentsystem.api.ProcessedPayment; import com.intuit.paymentsystem.core.exceptionHandling.exceptions.ServerInternalException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Component; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import java.util.UUID; import static com.intuit.paymentsystem.api.Consts.QUEUE_NAME; /** * business logic handler * @author leonidb * @date 21/02/2020 * @since {version} */ @Component @Slf4j public class PaymentHandler { private JmsTemplate jmsTemplate; @Autowired public PaymentHandler(JmsTemplate jmsTemplate){ this.jmsTemplate = jmsTemplate; } //method to send payment to queue public ProcessedPayment handle(Payment payment){ ProcessedPayment processedPayment = new ProcessedPayment(payment, UUID.randomUUID()); try{ sendMessage(processedPayment); }catch (Exception e){ log.error("Exception on send message to queue", e); throw new ServerInternalException("Exception on send payment to queue"); } return processedPayment; } private void sendMessage(final ProcessedPayment processedPayment) { log.info("sending payment to queue {} ", processedPayment); jmsTemplate.send(QUEUE_NAME, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createObjectMessage(processedPayment); } }); } }
true
7a11cfdde304355d0a7d8ed36f50ec309ea86741
Java
Raghuram0704/metSpr
/src/java/com/tm/pro/dao/FeedbackDAOImpl.java
UTF-8
2,937
2.328125
2
[]
no_license
package com.tm.pro.dao; import com.tm.pro.bean.FeedbackBean; import com.tm.pro.bean.MetrochennaiLocation; import com.tm.pro.bean.MetrodelhiLocation; import com.tm.pro.bean.MetrokolkataLocation; import com.tm.pro.bean.MetromumbaiLocation; import com.tm.pro.bean.ReqBean; import java.util.Iterator; import java.util.List; import org.springframework.orm.hibernate3.HibernateTemplate; public class FeedbackDAOImpl implements FeedbackDAO{ private HibernateTemplate ht; String bookingId="",status="",city,flag; int carId,count=0; public String feedback(FeedbackBean bean) { List li=ht.find("from ReqBean where booking_id=?",bean.getBookingId()); Iterator itr=li.iterator(); System.out.println("getting booking id"); if(itr.hasNext()) { ReqBean b=(ReqBean)itr.next(); bookingId=b.getBookingId(); status=b.getStatus(); city=b.getCity(); } else{ flag="invalid booking id"; } if(bookingId.equals(bean.getBookingId()) && status.equals("paid")) { ht.save(bean); List list=ht.find("from Metro"+city+"Location where booking_id=?", bean.getBookingId()); Iterator itr1=list.iterator(); System.out.println("getting booking id"); if(city.equals("mumbai")){ if(itr1.hasNext()) { MetromumbaiLocation ml=(MetromumbaiLocation)itr1.next(); carId=ml.getCarId(); } } else if(city.equals("chennai")){ if(itr1.hasNext()) { MetrochennaiLocation ml=(MetrochennaiLocation)itr1.next(); carId=ml.getCarId(); } } else if(city.equals("kolkata")){ if(itr1.hasNext()) { MetrokolkataLocation ml=(MetrokolkataLocation)itr1.next(); carId=ml.getCarId(); } } else if(city.equals("delhi")){ if(itr1.hasNext()) { MetrodelhiLocation ml=(MetrodelhiLocation)itr1.next(); carId=ml.getCarId(); } } count=ht.bulkUpdate("update FeedbackBean set city=?,car_id=? where booking_id=?",city,carId,bookingId); if(count==1){ flag="Thank you for your feedback"; }else{ flag="Sorry cannot update your feedback"; } } else if(bookingId.equals(bean.getBookingId()) && status.equals("not paid")){ flag="Feedback available only for paid users"; }else if(bookingId.equals(bean.getBookingId()) && status.equals("cancelled")){ flag="You have already cancelled your cab<br>Feedback available only for paid users"; } return flag; } public void setHt(HibernateTemplate ht) { this.ht = ht; } }
true
d4c4fcf176663d32ebf1686c77e7911556091e9f
Java
maxer028/cpu-monitor
/src/main/java/com/gsww/Application.java
UTF-8
760
1.828125
2
[]
no_license
package com.gsww; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; /** * @Description 初始化 * @author Xander * @Date 2017/12/27 下午5:32 * @see com.gsww * The word 'impossible' is not in my dictionary. */ @EnableAutoConfiguration @ComponentScan @Configuration @EnableScheduling public class Application { public static void main(String[] args){ SpringApplication.run(Application.class,args); } }
true
180ee07e2912fd6e6594c811d5247ac34994b6cb
Java
ericshen90/hello-spring-cloud-alibaba
/hello-spring-cloud-alibaba-provider/src/main/java/com/eric/spring/cloud/alibaba/provider/controller/EchoController.java
UTF-8
708
2.078125
2
[]
no_license
package com.eric.spring.cloud.alibaba.provider.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * @author EricShen * @date 2019-11-19 */ @RestController public class EchoController { @Value("${server.port}") private int port; @GetMapping(value = "/echo/{name}") public String echo(@PathVariable String name) { return "Hello Alibaba Nacos Provider " + name; } @GetMapping(value = "loadBalance") public String lb(){ return "The port of Nacos Provider is " + port; } }
true
cef8ddc0f2697bd0a2857a5ccc05cfcafbf2fa89
Java
plusoneky/monolithicDemo
/src/main/java/com/qq183311108/config/shiro/MySessionIdGenerator.java
UTF-8
758
2.234375
2
[]
no_license
package com.qq183311108.config.shiro; import java.io.Serializable; import java.util.UUID; import org.apache.commons.lang3.RandomStringUtils; import org.apache.shiro.crypto.hash.Md5Hash; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.eis.SessionIdGenerator; public class MySessionIdGenerator implements SessionIdGenerator{ private static final String SESSION_SIGN_KEY="183311108@qq.com"; @Override public Serializable generateId(Session session) { String uuid = UUID.randomUUID().toString(); String pwdSalt = RandomStringUtils.randomAlphabetic(6); return new StringBuilder(pwdSalt).append(uuid).append(new Md5Hash(uuid.toUpperCase(),SESSION_SIGN_KEY+pwdSalt,2).toHex()).toString(); } }
true
f4ce26bb710d7e74ad350f78b9e61eadfb060733
Java
Pallavijoshii/Zen_Training
/test/day3assignment/src/com/zensar/pack2/Batch.java
UTF-8
425
2.453125
2
[]
no_license
package com.zensar.pack2; public class Batch { private String courseName; private int batchStregth; public Batch() { super(); } public Batch(String courseName, int batchStregth) { super(); this.courseName = courseName; this.batchStregth = batchStregth; } public void display() { System.out.println("Course name is"+courseName+" and batch strength"+batchStregth); } public static void fun() { } }
true
3e96658bcdd9ec294327ec72304d82b0fbf5723d
Java
miruna599/Java-Applications
/Orders Management/model/Produs.java
UTF-8
982
3.421875
3
[]
no_license
package model; /** * "Produs" este clasa ce reprezinta elementele ce alcatuiesc tabela "Produs". * Tabela contine produsele ce pot fi comandate de catre clienti. * Clasa contine ca metode cate un getter pentru fiecare variabila, cate un setter * pentru fiecare variabila si metoda toString(). * @author Stefanovici Miruna * */ public class Produs { /** * Numele produsului */ private String nume; /** * Pretul produsului */ private float pret; public Produs(String nume, float pret) { this.nume = nume; this.pret = pret; } public String getNume() { return nume; } public float getPret() { return pret; } public void setNume(String nume) { this.nume = nume; } public void setPret(float pret) { this.pret = pret; } public String toString() { return "Produs : nume=" + nume + ", pret=" + pret; } }
true
76d7919ec54d418bb0675fb47640c502b37f60ab
Java
VovoZozo/JD1_HomeWork1
/src/by/htp/homework1/branch/main/Task23.java
UTF-8
1,308
3.515625
4
[]
no_license
package by.htp.homework1.branch.main; import java.util.Scanner; public class Task23 { /* 23. Определить правильность даты, введенной с клавиатуры (число — от 1 до 31, месяц — от 1 до 12). Если введены некорректные данные, то сообщить об этом. */ public static void main(String[] args) { System.out.println("task23"); int a = check(1, 31, "число"); int b = check(1, 12, "месяц"); System.out.println("Введенные данные корректны"); System.out.println(b + "-й месяц, " + a + "-ое число"); } public static int check(int a, int b, String s) { int c = 0; while (c<a||c>b) { c = scan(a,b, s); if (c<a||c>b) { System.out.println("Введенно некоректное значение."); } } return c; } public static int scan(int a, int b, String s) { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); System.out.println("Введите " + s + " — от " + a + " до " + b); while (!sc.hasNextInt()) { System.out.println("Введите число — от " + a + " до " + b); sc.next(); } int c = sc.nextInt(); return c; } }
true
6b03b797376e0331e7903a3995aad99b0cb72194
Java
1906jun10java/shyam-vasanjee
/src/animals/Animal.java
UTF-8
301
2.515625
3
[]
no_license
package animals; public abstract class Animal { public Animal() { super(); } private int numLegs = 4; //getters and setters public int getNumLegs() { return numLegs; } public void setNumLegs(int numLegs) { this.numLegs = numLegs; } public abstract void playDead(); }
true
0b275174951ffb5e8bc6a75dd2a221d53d2928f9
Java
ksenyakom/spring_boot_web_service
/web-service/src/main/java/com/epam/esm/facade/TagFacade.java
UTF-8
487
2.234375
2
[]
no_license
package com.epam.esm.facade; import com.epam.esm.dto.JsonResult; import com.epam.esm.model.Tag; /** * Defines methods for facade layout for Tag class. * Methods supposed to wrap results in JsonResult class. */ public interface TagFacade { JsonResult<Tag> getTag(int id); JsonResult<Tag> save(Tag tag); JsonResult<Tag> delete(int id); JsonResult<Tag> getAllTags(int page, int perPage, boolean includeMetadata); JsonResult<Tag> getBestBuyerMostWidelyTag(); }
true
12baaa41f6d9f3a5f6369dd7dd9f2ffc3676a981
Java
rodrigoords/Cursos
/JF11/fj11-contas/src/br/com/caelum/contas/modelo/Ano.java
UTF-8
561
2.890625
3
[]
no_license
package br.com.caelum.contas.modelo; public class Ano{ private int ano; public Ano(int ano){ this.ano = ano; } public int getAno(){ return this.ano; } public boolean isBissexto(){ if((ano % 400 == 0) || ((ano % 4 == 0) && (ano % 100 != 0))){ return true; } else{ return false; } } public boolean isDiaMesValidoParaAno(Dia dia, Mes mes){ if(dia.isValidoParaMes(mes)){ if (!this.isBissexto() && mes.getMes() == 2){ return dia.getDia() > 28; } return true; }else{ return false; } } }
true
878c8c616f644d41a2738b08e842aeee7d39a8c4
Java
alexnguyen1606/order-chicken
/src/main/java/com/order/service/DishService.java
UTF-8
1,177
2.234375
2
[]
no_license
package com.order.service; import com.order.entities.Dish; import com.order.entities.QDish; import com.order.repository.DishRepository; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAUpdateClause; import org.springframework.stereotype.Service; import java.util.List; @Service public class DishService extends CommonRepository<Dish, DishRepository> { public DishService(DishRepository repo) { super(repo); } private final QDish Q = QDish.dish; public String getNameById(Long id) { JPAQuery<Dish> query = new JPAQuery<>(em); return query.select(Q.name).from(Q).where(Q.id.eq(id)).fetchFirst(); } public List<Dish> findByCategoryAndStatus(Long categoryId, String status) { return repo.findByIdCategoryAndStatus(categoryId, status); } public void updateStatus(Long id,String status){ JPAUpdateClause update = new JPAUpdateClause(em,Q); update.set(Q.status,status); update.where(Q.id.eq(id)).execute(); } public void updateAllStatus(List<Long> ids,String status){ JPAUpdateClause update = new JPAUpdateClause(em,Q); update.set(Q.status,status); update.where(Q.id.in(ids)).execute(); } }
true
128686cc3887c75e4656a1966c19d362796c665d
Java
akarshkumar0101/EE-360C
/Assignment 2/starter_files/HuffmanTree.java
UTF-8
369
2.359375
2
[]
no_license
package starter_files; import java.util.ArrayList; public class HuffmanTree { TreeNode root; HuffmanTree() { root = null; } public void constructHuffmanTree(ArrayList<String> characters, ArrayList<Integer> freq) { } public String encode(String humanMessage) { return ""; } public String decode(String encodedMessage) { return ""; } }
true
5efe5fa6474640c5714e874b2c0757a1a48bc9cd
Java
fzhedu/CalciteServer
/src/main/java/com/ginkgo/calcite/server/Server.java
UTF-8
1,582
2.265625
2
[]
no_license
package com.ginkgo.calcite.server; import com.thrift.calciteserver.CalciteServer; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadedSelectorServer; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TNonblockingServerSocket; public class Server { public final static int SERVER_PORT = 8099; private static String SERVER_IP = "localhost"; public void startServer() { try { System.out.println("HelloWorld Server start..."); // user specific TProcessor tprocessor = new CalciteServer.Processor(new CalciteServerHandler()); CalciteServerHandler.createSchema(); TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(SERVER_PORT); TThreadedSelectorServer.Args tArgs = new TThreadedSelectorServer.Args(serverTransport); tArgs.processor(tprocessor); tArgs.transportFactory(new TFramedTransport.Factory()); tArgs.protocolFactory(new TBinaryProtocol.Factory()); TServer server = new TThreadedSelectorServer(tArgs); System.out.println("HelloTThreadedSelectorServer start...."); server.serve(); } catch (Exception e) { System.out.println("Server start error"); e.printStackTrace(); } } public static void main(String[] args) { Server server = new Server(); server.startServer(); } }
true
dc52b91e59d8026b29316dba79a5dfa728e1206e
Java
alcides/ParGA
/src/aeminum/parga/examples/nbody/NBodyGA.java
UTF-8
3,197
2.734375
3
[]
no_license
package aeminum.parga.examples.nbody; import java.util.Arrays; import java.util.Random; import aeminium.runtime.futures.RuntimeManager; import aeminum.parga.GeneticAlgorithm; import aeminum.parga.executors.GAExecutor; import aeminum.parga.executors.GAJParExecutor; import aeminum.parga.sorters.JParSorter; public class NBodyGA implements GeneticAlgorithm<NBodyIndividual> { public static int N = 5000; public static int ITERATIONS = 3; public static NBody[] data = NBodySystem.generateRandomBodies(N, 1L); String version = "sequential"; public NBodyGA(String v) { version = v; } @Override public NBodyIndividual createRandomIndividual(Random r) { NBodyIndividual ind = new NBodyIndividual(); for (int i=0; i<6; i++) ind.data[i] = NBody.getRandomCoordinate(r); return ind; } @Override public NBodyIndividual mutate(NBodyIndividual original, Random r) { NBodyIndividual ind = new NBodyIndividual(); int o = r.nextInt(6); for (int i=0; i<6; i++) { if (i == o) { ind.data[i] = NBody.getRandomCoordinate(r); } else { ind.data[i] = original.data[i]; } } return ind; } @Override public NBodyIndividual[] recombine(NBodyIndividual i1, NBodyIndividual i2, Random r) { NBodyIndividual[] pair = new NBodyIndividual[2]; pair[0] = new NBodyIndividual(); pair[1] = new NBodyIndividual(); int cutPoint = r.nextInt(6); for (int i=0; i<6; i++) { if (i < cutPoint) { pair[0].data[i] = i1.data[i]; pair[1].data[i] = i2.data[i]; } else { pair[0].data[i] = i2.data[i]; pair[1].data[i] = i1.data[i]; } } return pair; } @Override public double fitness(NBodyIndividual ind) { NBody[] bodies = Arrays.copyOf(data, N); bodies[0].x = ind.data[0]; bodies[0].y = ind.data[1]; bodies[0].z = ind.data[2]; bodies[0].vx = ind.data[3]; bodies[0].vy = ind.data[4]; bodies[0].vz = ind.data[5]; NBodySystem s = null; if (version.equals("sequential")) s = new NBodySystem(bodies); if (version.equals("parallel")) s = new ParallelNBodySystem(bodies); if (version.equals("forkjoin")) s = new ForkJoinNBodySystem(bodies); if (version.equals("aeminium")) s = new AeminiumNBodySystem(bodies); if (version.equals("jpar")) s = new JParNBodySystem(bodies); for (int i=0; i<ITERATIONS; i++) s.advance(0.5); return s.energy(); } @Override public double getMutationProbability() { return 0.2; } @Override public double getRecombinationProbability() { return 0.9; } @Override public int getPopulationSize() { return 64; } @Override public int getNumberOfIterations() { return 10; } @Override public int getElitismSize() { return 10; } @Override public int getTournamentSize() { return 2; } @Override public NBodyIndividual[] createArray(int n) { return new NBodyIndividual[n]; } public static void main(String[] args) { RuntimeManager.init(); NBodyGA min = new NBodyGA("jpar"); GAExecutor<NBodyIndividual> ex = new GAJParExecutor<NBodyIndividual>(); ex.setSorter(new JParSorter<NBodyIndividual>()); ex.evolve(min); System.out.println(ex.getBestIndividual() + " => " + ex.getBestIndividual().fitness); RuntimeManager.shutdown(); } }
true
2c88398ef299286a6fe89443427b37bac1f344e0
Java
ramon284/Mooc-Java-2020
/mooc-java-programming-ii/Part 9/part09-Part09_04.DifferentKindsOfBoxes/src/main/java/BoxWithMaxWeight.java
UTF-8
819
3.203125
3
[]
no_license
import java.util.ArrayList; public class BoxWithMaxWeight extends Box { private int max; private ArrayList<Item> list = new ArrayList(); public BoxWithMaxWeight(int capacity){ super(); this.max = capacity; this.list = new ArrayList(); } @Override public void add(Item item) { if(getTotalWeight() +item.getWeight() > max){ return; } list.add(item); } public int getTotalWeight(){ if(list.isEmpty()){ return 0; } int z = 0; for(Item x:list){ z += x.getWeight(); } return z; } @Override public boolean isInBox(Item item) { return list.contains(item); //To change body of generated methods, choose Tools | Templates. } }
true
ae350781f96f28f3ba10d3a52bf55dceca7c4c44
Java
nicetoseeyou/Fibonacci-painter
/src/main/java/lab/quantum/kevin/App.java
UTF-8
1,453
2.859375
3
[]
no_license
package lab.quantum.kevin; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; import lab.quantum.kevin.fibonacci.Fibonacci; import lab.quantum.kevin.fibonacci.ImageSettings; import lab.quantum.kevin.fibonacci.Painter; import lab.quantum.kevin.util.PropHandler; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; public class App { public static void main(String[] args) { Properties settings = PropHandler.readResources("settings.properties"); Fibonacci fibonacci = new Fibonacci(Integer.parseInt(settings.getProperty("fibonacci.length"))); Painter painter = new Painter(settings); painter.drawSpiral(fibonacci.getFibonacciSequence()); saveImage(painter.getImage(), settings.getProperty("image.name")); } public static void saveImage(BufferedImage image, String fullName) { try (OutputStream outputStream = new FileOutputStream(fullName)) { JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream); encoder.encode(image); } catch (FileNotFoundException e) { System.out.println(fullName); e.printStackTrace(); } catch (IOException e) { System.out.println(fullName); e.printStackTrace(); } } }
true
faa30e297738f0e0c8ec37c8f0b152ee8f142beb
Java
ardiwahyu/movie-catalogue-android
/favoriteapp/src/main/java/com/example/favoriteapp/favorite/tvShow/LoadTvShowCallback.java
UTF-8
218
1.726563
2
[]
no_license
package com.example.favoriteapp.favorite.tvShow; import com.example.favoriteapp.Film; import java.util.ArrayList; interface LoadTvShowCallback { void preExecute(); void postExecute(ArrayList<Film> films); }
true
65a7b7e30612cbfcf635d51c22adaa2f10e31ebb
Java
mateohi/obligatorio-dsdm
/FindMeServer/src/main/java/com/findme/service/dataaccess/UsuarioDao.java
UTF-8
363
1.828125
2
[]
no_license
package com.findme.service.dataaccess; import com.findme.service.model.Usuario; import java.util.List; public interface UsuarioDao { public List<Usuario> getUsuarios(); public Usuario getUsuarioById(long id); public void deleteUsuario(long id); public void addUsuario(Usuario usuario); public Usuario getUsuarioByGcmId(String gcmId); }
true
1b742fd6737339720648e372d28f2d3758772513
Java
alexandrerosseto/g2glite
/src/main/java/com/arosseto/g2glite/dto/ClientNewDTO.java
UTF-8
3,006
2.140625
2
[]
no_license
package com.arosseto.g2glite.dto; import java.io.Serializable; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import org.hibernate.validator.constraints.Length; import com.arosseto.g2glite.services.validation.ClientInsert; @ClientInsert public class ClientNewDTO implements Serializable { private static final long serialVersionUID = 1L; @NotEmpty(message="Required field") @Length(min=5, max=150, message="Size must be between 5 and 150 characters") private String name; @NotEmpty(message="Required field") @Email(message="Invalid email") private String email; @NotEmpty(message="Required field") private String clientPersonalIdNumber; private Integer clientType; @NotEmpty(message="Required field") private String password; @NotEmpty(message="Required field") private String street; @NotEmpty(message="Required field") private String number; private String observation; private String address; @NotEmpty(message="Required field") private String postal; @NotEmpty(message="Required field") private String phone1; private String phone2; private String phone3; private Long cityId; public ClientNewDTO() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getClientPersonalIdNumber() { return clientPersonalIdNumber; } public void setClientPersonalIdNumber(String clientPersonalIdNumber) { this.clientPersonalIdNumber = clientPersonalIdNumber; } public Integer getClientType() { return clientType; } public void setClientType(Integer clientType) { this.clientType = clientType; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getObservation() { return observation; } public void setObservation(String observation) { this.observation = observation; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPostal() { return postal; } public void setPostal(String postal) { this.postal = postal; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public String getPhone3() { return phone3; } public void setPhone3(String phone3) { this.phone3 = phone3; } public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
true
4eb74f1d925be1a1138edce35749d5819d6700b2
Java
xtrui/apistore
/src/main/java/cn/xtrui/database/util/MyStringUtil.java
UTF-8
564
2.390625
2
[]
no_license
package cn.xtrui.database.util; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; public class MyStringUtil { public static Map paramToMap(@NotNull String param){ HashMap<Object, Object> map = new HashMap<>(); String[] kvs = param.split("&"); if(param.length() >= 1){ for(String p:kvs){ String[] kv = p.split("="); String k = kv[0]; String v = kv[1]; map.put(k,v); } } return map; } }
true
dd811046dd7a5c57fb016b166e195f90a6c13a32
Java
niteshch/InterviewBit
/LinkedList/RemoveDuplicatesSortedListI.java
UTF-8
573
3.640625
4
[]
no_license
package LinkedList; /* Remove Duplicates from Sorted List Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. */ public class RemoveDuplicatesSortedListI { public ListNode deleteDuplicates(ListNode a) { ListNode current = a; while (current != null) { ListNode runner = current.next; while (runner != null && runner.val == current.val) { runner = runner.next; } current.next = runner; current = current.next; } return a; } }
true
379cffb470698fd479907657f01e0b2c28ce061d
Java
pierrealainkeyser/evolution
/evolution-back/src/test/java/fr/keyser/fsm/json/TestJsonDataMapAdapter.java
UTF-8
2,772
2.03125
2
[]
no_license
package fr.keyser.fsm.json; import java.util.Arrays; import java.util.Collections; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import fr.keyser.evolution.model.CardId; import fr.keyser.evolution.model.SpecieId; import fr.keyser.evolution.summary.FeedSummary; import fr.keyser.evolution.summary.FeedingActionSummaries; import fr.keyser.fsm.InstanceId; import fr.keyser.fsm.State; import fr.keyser.fsm.impl.AutomatInstanceContainerValue; import fr.keyser.fsm.impl.AutomatInstanceValue; public class TestJsonDataMapAdapter { private final static Logger logger = LoggerFactory.getLogger(TestJsonDataMapAdapter.class); @Test void automatInstanceValue() throws JsonProcessingException { JsonDataMapAdapter adapter = new JsonDataMapAdapter(Arrays.asList(InstanceId.class)); AutomatInstanceValue in = AutomatInstanceValue.create(new InstanceId("root"), new State("yes", "no"), null, 1, Arrays.asList(new InstanceId("i1"), new InstanceId("i2")), Map.of("first", new InstanceId("i1"), "card", new CardId(56))); ObjectMapper om = new ObjectMapper().registerModule(adapter.asModule()); String json = om.writerWithDefaultPrettyPrinter().writeValueAsString(in); logger.info("in\n{}", json); AutomatInstanceValue out = om.readValue(json, AutomatInstanceValue.class); String jsonOut = om.writerWithDefaultPrettyPrinter().writeValueAsString(out); Assertions.assertThat(jsonOut).isEqualTo(json); } @Test void automatInstanceContainerValue() throws JsonProcessingException { JsonDataMapAdapter adapter = new JsonDataMapAdapter( Arrays.asList(InstanceId.class, FeedingActionSummaries.class)); AutomatInstanceValue aiv = AutomatInstanceValue.create(new InstanceId("root"), new State("yes", "no"), new InstanceId("parent"), 1, Collections.emptyList(), Map.of("first", new InstanceId("i1"))); AutomatInstanceContainerValue in = AutomatInstanceContainerValue.create(Arrays.asList(aiv), Map.of("actions", new FeedingActionSummaries( Arrays.asList(new FeedSummary(false, new SpecieId(0, 0), Arrays.asList()))))); ObjectMapper om = new ObjectMapper().registerModule(adapter.asModule()); String json = om.writerWithDefaultPrettyPrinter().writeValueAsString(in); logger.info("in\n{}", json); AutomatInstanceContainerValue out = om.readValue(json, AutomatInstanceContainerValue.class); String jsonOut = om.writerWithDefaultPrettyPrinter().writeValueAsString(out); Assertions.assertThat(jsonOut).isEqualTo(json); } }
true
d3a26398073a81cb131e1a129d26dec797d550db
Java
youngjee/SP
/src/http/server/MyServlet.java
UTF-8
1,696
2.796875
3
[]
no_license
package http.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.http.HttpResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpMethod; public class MyServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("GET"); Object obj = req.getParameter("param"); System.out.println((String) obj); res.setStatus(200); res.getWriter().write("Hello!"); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("POST"); Object obj = req.getParameter("param"); System.out.println((String) obj); res.setStatus(200); res.getWriter().write("Hello!"); } // protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // res.setStatus(200); // // System.out.println(readBody(req)); // // res.getWriter().write("Hello World!"); // } // public String readBody(HttpServletRequest request) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder builder = new StringBuilder(); String buffer; while ((buffer = input.readLine()) != null) { if (builder.length() > 0) { builder.append("\n"); } builder.append(buffer); } return builder.toString(); } }
true
78e3f775f63109df7c3d2d65924770b10fc77a79
Java
sssiegmeister/Forbidden-Island
/src/ForbiddenIsland.java
UTF-8
38,255
3.484375
3
[]
no_license
// Assignment 9 // partner1-Siegmeister partner1-Samuel // partner1-sss13gm31st3r import tester.*; import javalib.impworld.*; import java.awt.Color; import javalib.worldimages.*; import java.util.*; //Represents a single square of the game area class Cell { // represents absolute height of this cell, in feet double height; // In logical coordinates, with the origin at the top-left corner of the screen int x; int y; // the four adjacent cells to this one Cell left; Cell top; Cell right; Cell bottom; // reports whether this cell is flooded or not boolean isFlooded; // constructor to allow for OceanCell constructor Cell() { this.isFlooded = true; } // constructor for a Cell Cell(int x, int y, double height, boolean isFlooded) { this.x = x; this.y = y; this.height = height; this.isFlooded = false; } //EFFECT: if the the given cell has not been // set this.left to the given Cell // and set left.right to this void setLeft(Cell left) { if (this.left == null) { this.left = left; this.left.setRight(this); } } //EFFECT: if the the given cell has not been set // set this.right to the given Cell // and set right.left to this void setRight(Cell right) { if (this.right == null) { this.right = right; this.right.setLeft(this); } } //EFFECT: if the the given cell has not been set // set this.top to the given Cell // and set top.bottom to this void setTop(Cell top) { if (this.top == null) { this.top = top; this.top.setBottom(this); } } //EFFECT: if the the given cell has not been set // set this.bottom to the given Cell // and set bottom.top to this void setBottom(Cell bottom) { if (this.bottom == null) { this.bottom = bottom; this.bottom.setTop(this); } } //does this cell have any adjacent cells that are flooded? boolean nextFlooded() { return (this.left.isFlooded || this.right.isFlooded || this.top.isFlooded || this.bottom.isFlooded); } //EFFECT: floods all adjacent cells to this cell void floodFill() { if (this.isFlooded) { if (this.left.height < this.height && !this.left.isFlooded) { this.left.isFlooded = true; this.left.floodFill(); } if (this.right.height < this.height && !this.right.isFlooded) { this.right.isFlooded = true; this.right.floodFill(); } if (this.top.height < this.height && !this.top.isFlooded) { this.top.isFlooded = true; this.top.floodFill(); } if (this.bottom.height < this.height && !this.bottom.isFlooded) { this.bottom.isFlooded = true; this.bottom.floodFill(); } } } //EFFECT: draw this cell on the given background void drawCell(WorldScene background, int level) { background.placeImageXY(new RectangleImage(10, 10, OutlineMode.SOLID, this.chooseColor(level)), ((this.x + 1) * 10) - 5, ((this.y + 1) * 10) - 5); } // returns the color of a Cell Color chooseColor(int level) { if (this.isFlooded) { return new Color(0, 0, (int) Math.max(0.0, (128 - ((level - this.height) * 2)))); } else if (this.height < level) { return new Color((int) ((level - this.height) * 5), 127 - level, 0); } else { return new Color(Math.min(255, (int) ((this.height - level) * (255 / ForbiddenIslandWorld.MAX_HEIGHT))), Math.min(255, (int) ((this.height - level) * (128 / ForbiddenIslandWorld.MAX_HEIGHT) + 127)), Math.min(255, (int) ((this.height - level) * (255 / ForbiddenIslandWorld.MAX_HEIGHT)))); } } // is this Cell the same as that Cell boolean sameCell(Cell that) { return (this.x == that.x) && (this.y == that.y) && (this.height == that.height); } } //Represents a single square of the ocean part of the game area class OceanCell extends Cell { // constructor for an OceanCell OceanCell(int x, int y) { this.x = x; this.y = y; } // returns the color of an OceanCell Color chooseColor(int level) { return new Color(0, 0, 128); } } //Represents an item in the world class Item { Cell cell; IList<Cell> land; int x; int y; //constructor for an item Item(IList<Cell> land) { //the cells availible for this to spawn on this.land = land; //the cell that this will spawn on this.cell = this.setStart(this.land); //the x coordinate of this this.x = cell.x; //the y coordinate of this this.y = cell.y; } //set the spawn point of an item Cell setStart(IList<Cell> loc) { int r = new Random().nextInt(loc.length()); for (int i = 0; i < r; i += 1) { loc = loc.asCons().rest; } return loc.asCons().first; } //EFFECT: draw this item on the given background void drawItem(WorldScene background) { background.placeImageXY(new FromFileImage("mountaindew.png"), ((this.x + 1) * 10) - 5, ((this.y + 1) * 10) - 5); } //can this item be collected right now? // (is it both at the given position // and ready to be collected?) boolean collectable(Item that, int l) { return this.cell.sameCell(that.cell); } } //class to represent the player class Player extends Item { boolean aquatic; //constructor for a player Player(IList<Cell> land) { super(land); this.cell = this.setStart(this.land); this.x = cell.x; this.y = cell.y; this.aquatic = false; } void drawItem(WorldScene background) { if (this.aquatic) { background.placeImageXY(new FromFileImage("natduck.png"), ((this.x + 1) * 10) - 5, ((this.y + 1) * 10) - 5); } else { background.placeImageXY(new FromFileImage("nattuck.png"), ((this.x + 1) * 10) - 5, ((this.y + 1) * 10) - 5); } } } class PowerUp extends Item { PowerUp(IList<Cell> land) { super(land); this.cell = this.setStart(this.land); this.x = cell.x; this.y = cell.y; } void drawItem(WorldScene background) { background.placeImageXY(new FromFileImage("feather.png"), ((this.x + 1) * 10) - 5, ((this.y + 1) * 10) - 5); } } //class to represent a helicopter class Helicopter extends Item { //constructor for a helicopter Helicopter(IList<Cell> land) { super(land); this.cell = this.setStart(this.land); this.x = cell.x; this.y = cell.y; } Cell setStart(IList<Cell> loc) { Cell result = this.land.asCons().first; for (Cell c : this.land) { if (c.height == ForbiddenIslandWorld.MAX_HEIGHT) { result = c; } } return result; } void drawItem(WorldScene background) { background.placeImageXY(new FromFileImage("helicopter.png"), ((this.x + 1) * 10) - 5, ((this.y + 1) * 10) - 5); } boolean collectable(Item that, int l) { return this.cell.sameCell(that.cell) && l <= 1; } } // represents the world class ForbiddenIslandWorld extends World { // All the cells of the game, including the ocean IList<Cell> board; // the current height of the ocean int waterHeight; // random number generator Player player; // the items that need to be collected IList<Item> targets; // duck powerup PowerUp duck; // does the player have the duck powerup? boolean duckAvailible; // how much time left int duckTimeLeft; // generates random number Random rand = new Random(); // constant for size of island static final int ISLAND_SIZE = 64; // constant for maximum height of the world static final double MAX_HEIGHT = (double) ISLAND_SIZE; // Field to represent which island is used // 0 for mountain // 1 for random height // 2 for random terrain int mode; // number of ticks passed int ticks; // number of cells traversed int score; // has the game been won? boolean gameWon; // has the game been lost? boolean gameLost; // constructor for world ForbiddenIslandWorld(int mode) { this.mode = mode; if (this.mode == 0) { this.constructMountain(); } else if (this.mode == 1) { this.constructRandom(); } else if (this.mode == 2) { this.constructTerrain(); } } // EFFECT: sets conditions for mountain mode void constructMountain() { ArrayList<ArrayList<Cell>> c = makeCells(allHeights()); this.board = convert(c); this.player = new Player(convertLand(this.board)); this.targets = new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Helicopter(convertLand(this.board)), new Empty<Item>()))))); this.duck = new PowerUp(convertLand(this.board)); this.duckAvailible = false; this.waterHeight = 0; this.ticks = 1; this.score = 0; this.gameWon = false; this.gameLost = false; } // EFFECT: sets conditions for random mode void constructRandom() { ArrayList<ArrayList<Cell>> c = makeCells(allHeightsRand()); this.board = convert(c); this.player = new Player(convertLand(this.board)); this.targets = new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Helicopter(convertLand(this.board)), new Empty<Item>()))))); this.duck = new PowerUp(convertLand(this.board)); this.duckAvailible = false; this.waterHeight = 0; this.ticks = 1; this.score = 0; this.gameWon = false; this.gameLost = false; } // EFFECT: sets conditions for terrain mode void constructTerrain() { ArrayList<ArrayList<Cell>> c = makeCellsRand(allHeightsZero()); this.board = convert(c); this.player = new Player(convertLand(this.board)); this.targets = new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Item(convertLand(this.board)), new Cons<Item>(new Helicopter(convertLand(this.board)), new Empty<Item>()))))); this.duck = new PowerUp(convertLand(this.board)); this.duckAvailible = false; this.waterHeight = 0; this.ticks = 1; this.score = 0; this.gameWon = false; this.gameLost = false; } // make a list of all heights for a perfectly rectangular mountain ArrayList<ArrayList<Double>> allHeights() { ArrayList<ArrayList<Double>> alisty = new ArrayList<ArrayList<Double>>(); for (int y = 0; y < ISLAND_SIZE + 1; y += 1) { ArrayList<Double> alistx = new ArrayList<Double>(); for (int x = 0; x < ISLAND_SIZE + 1; x += 1) { alistx.add((double) MAX_HEIGHT - (Math.abs(x - ISLAND_SIZE / 2) + Math.abs(y - ISLAND_SIZE / 2))); } alisty.add(alistx); } return alisty; } // make a list of all heights for a diamond island of random heights ArrayList<ArrayList<Double>> allHeightsRand() { ArrayList<ArrayList<Double>> alisty = new ArrayList<ArrayList<Double>>(); for (int y = 0; y < ISLAND_SIZE + 1; y += 1) { ArrayList<Double> alistx = new ArrayList<Double>(); for (int x = 0; x < ISLAND_SIZE + 1; x += 1) { alistx.add((double) this.rand.nextInt((int) MAX_HEIGHT)); } alisty.add(alistx); } return alisty; } // make a list of all heights set as zero ArrayList<ArrayList<Double>> allHeightsZero() { ArrayList<ArrayList<Double>> alisty = new ArrayList<ArrayList<Double>>(); for (int y = 0; y < ISLAND_SIZE + 1; y += 1) { ArrayList<Double> alistx = new ArrayList<Double>(); for (int x = 0; x < ISLAND_SIZE + 1; x += 1) { if ((x == 0 && y == ISLAND_SIZE / 2) || (x == ISLAND_SIZE / 2 && y == 0) || (x == ISLAND_SIZE && y == ISLAND_SIZE / 2) || (x == ISLAND_SIZE / 2 && y == ISLAND_SIZE)) { alistx.add(1.0); } else if (x == ISLAND_SIZE / 2 && y == ISLAND_SIZE / 2) { alistx.add(MAX_HEIGHT); } else if (x == 0 || x == ISLAND_SIZE || y == 0 || (y == ISLAND_SIZE)) { alistx.add(0.0); } else { alistx.add(null); } } alisty.add(alistx); } setHeights(alisty, alisty.get(0).get(0), alisty.get(0).get(ISLAND_SIZE / 2), alisty.get(ISLAND_SIZE / 2).get(0), alisty.get(ISLAND_SIZE / 2).get(ISLAND_SIZE / 2), 0, ISLAND_SIZE / 2, 0, ISLAND_SIZE / 2); setHeights(alisty, alisty.get(0).get(ISLAND_SIZE / 2), alisty.get(0).get(ISLAND_SIZE), alisty.get(ISLAND_SIZE / 2).get(ISLAND_SIZE / 2), alisty.get(ISLAND_SIZE / 2).get(ISLAND_SIZE), ISLAND_SIZE / 2, ISLAND_SIZE, 0, ISLAND_SIZE / 2); setHeights(alisty, alisty.get(ISLAND_SIZE / 2).get(0), alisty.get(ISLAND_SIZE / 2).get(ISLAND_SIZE / 2), alisty.get(ISLAND_SIZE).get(0), alisty.get(ISLAND_SIZE).get(ISLAND_SIZE / 2), 0, ISLAND_SIZE / 2, ISLAND_SIZE / 2, ISLAND_SIZE); setHeights(alisty, alisty.get(ISLAND_SIZE / 2).get(ISLAND_SIZE / 2), alisty.get(ISLAND_SIZE / 2).get(ISLAND_SIZE), alisty.get(ISLAND_SIZE).get(ISLAND_SIZE / 2), alisty.get(ISLAND_SIZE).get(ISLAND_SIZE), ISLAND_SIZE / 2, ISLAND_SIZE, ISLAND_SIZE / 2, ISLAND_SIZE); return alisty; } // EFFECT: set the heights for a randomly generated terrain void setHeights(ArrayList<ArrayList<Double>> h, double tl, double tr, double bl, double br, int lowx, int highx, int lowy, int highy) { double t; if (h.get(lowy).get((lowx + highx) / 2) == null) { t = Math.min(MAX_HEIGHT, this.randomInt((highx - lowx) + (highy - lowy)) + (tl + tr) / 2); h.get(lowy).set((lowx + highx) / 2, t); } else { t = h.get(lowy).get((lowx + highx) / 2); } double b; if (h.get(highy).get((lowx + highx) / 2) == null) { b = Math.min(MAX_HEIGHT, this.randomInt((highx - lowx) + (highy - lowy)) + (bl + br) / 2); h.get(highy).set((lowx + highx) / 2, b); } else { b = h.get(highy).get((lowx + highx) / 2); } double l; if (h.get((lowy + highy) / 2).get(lowx) == null) { l = Math.min(MAX_HEIGHT, this.randomInt((highx - lowx) + (highy - lowy)) + (tl + bl) / 2); h.get((lowy + highy) / 2).set(lowx, l); } else { l = h.get((lowy + highy) / 2).get(lowx); } double r; if (h.get((lowy + highy) / 2).get(highx) == null) { r = Math.min(MAX_HEIGHT, this.randomInt((highx - lowx) + (highy - lowy)) + (tr + br) / 2); h.get((lowy + highy) / 2).set(highx, r); } else { r = h.get((lowy + highy) / 2).get(highx); } double m; if (h.get((lowy + highy) / 2).get((lowx + highx) / 2) == null) { m = Math.min(MAX_HEIGHT, this.randomInt((highx - lowx) + (highy - lowy)) + (tl + tr + bl + br) / 4); h.get((lowy + highy) / 2).set((lowx + highx) / 2, m); } else { m = h.get((lowy + highy) / 2).get((lowx + highx) / 2); } if (highx - lowx > 1) { setHeights(h, tl, t, l, m, lowx, (lowx + highx) / 2, lowy, (lowy + highy) / 2); setHeights(h, t, tr, m, r, (lowx + highx) / 2, highx, lowy, (lowy + highy) / 2); setHeights(h, l, m, bl, b, lowx, (lowx + highx) / 2, (lowy + highy) / 2, highy); setHeights(h, m, r, b, br, (lowx + highx) / 2, highx, (lowy + highy) / 2, highy); } } // make a list of Cells in a diamond island formation ArrayList<ArrayList<Cell>> makeCells(ArrayList<ArrayList<Double>> h) { ArrayList<ArrayList<Cell>> alisty = new ArrayList<ArrayList<Cell>>(); for (int y = 0; y < ISLAND_SIZE + 1; y += 1) { ArrayList<Cell> alistx = new ArrayList<Cell>(); for (int x = 0; x < ISLAND_SIZE + 1; x += 1) { if ((Math.abs(x - ISLAND_SIZE / 2) + Math.abs(y - ISLAND_SIZE / 2)) < (ISLAND_SIZE / 2)) { alistx.add(new Cell(x, y, h.get(y).get(x), false)); } else { alistx.add(new OceanCell(x, y)); } } alisty.add(alistx); } setNeibs(alisty); return alisty; } // make a list of Cells in a random formation ArrayList<ArrayList<Cell>> makeCellsRand(ArrayList<ArrayList<Double>> h) { ArrayList<ArrayList<Cell>> alisty = new ArrayList<ArrayList<Cell>>(); for (int y = 0; y < ISLAND_SIZE + 1; y += 1) { ArrayList<Cell> alistx = new ArrayList<Cell>(); for (int x = 0; x < ISLAND_SIZE + 1; x += 1) { if (h.get(y).get(x) > 0) { alistx.add(new Cell(x, y, h.get(y).get(x), false)); } else { alistx.add(new OceanCell(x, y)); } } alisty.add(alistx); } setNeibs(alisty); return alisty; } // EFFECT: set the neighbors for each Cell void setNeibs(ArrayList<ArrayList<Cell>> c) { for (Integer y = 0; y < ISLAND_SIZE + 1; y += 1) { for (Integer x = 0; x < ISLAND_SIZE + 1; x += 1) { if (y == 0 && x == 0) { c.get(y).get(x).setTop(c.get(y).get(x)); c.get(y).get(x).setBottom(c.get(y + 1).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x)); c.get(y).get(x).setRight(c.get(y).get(x + 1)); } else if (y == 0 && x == ISLAND_SIZE) { c.get(y).get(x).setTop(c.get(y).get(x)); c.get(y).get(x).setBottom(c.get(y + 1).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x - 1)); c.get(y).get(x).setRight(c.get(y).get(x)); } else if (y == ISLAND_SIZE && x == 0) { c.get(y).get(x).setTop(c.get(y - 1).get(x)); c.get(y).get(x).setBottom(c.get(y).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x)); c.get(y).get(x).setRight(c.get(y).get(x + 1)); } else if (y == ISLAND_SIZE && x == ISLAND_SIZE) { c.get(y).get(x).setTop(c.get(y - 1).get(x)); c.get(y).get(x).setBottom(c.get(y).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x - 1)); c.get(y).get(x).setRight(c.get(y).get(x)); } else if (y == 0) { c.get(y).get(x).setTop(c.get(y).get(x)); c.get(y).get(x).setBottom(c.get(y + 1).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x - 1)); c.get(y).get(x).setRight(c.get(y).get(x + 1)); } else if (x == 0) { c.get(y).get(x).setTop(c.get(y - 1).get(x)); c.get(y).get(x).setBottom(c.get(y + 1).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x)); c.get(y).get(x).setRight(c.get(y).get(x + 1)); } else if (y == ISLAND_SIZE) { c.get(y).get(x).setTop(c.get(y - 1).get(x)); c.get(y).get(x).setBottom(c.get(y).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x - 1)); c.get(y).get(x).setRight(c.get(y).get(x + 1)); } else if (x == ISLAND_SIZE) { c.get(y).get(x).setTop(c.get(y - 1).get(x)); c.get(y).get(x).setBottom(c.get(y + 1).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x - 1)); c.get(y).get(x).setRight(c.get(y).get(x)); } else { c.get(y).get(x).setTop(c.get(y - 1).get(x)); c.get(y).get(x).setBottom(c.get(y + 1).get(x)); c.get(y).get(x).setLeft(c.get(y).get(x - 1)); c.get(y).get(x).setRight(c.get(y).get(x + 1)); } } } } // convert the given ArrayList<ArrayList<Cell>> to an IList<Cell> IList<Cell> convert(ArrayList<ArrayList<Cell>> c) { IList<Cell> base = new Empty<Cell>(); for (int y = 0; y < ISLAND_SIZE + 1; y += 1) { for (int x = 0; x < ISLAND_SIZE + 1; x += 1) { base = new Cons<Cell>(c.get(y).get(x), base); } } return base; } // convert the given ArrayList<ArrayList<Cell>> to an IList<Cell> // excluding the flooded cells IList<Cell> convertLand(IList<Cell> loc) { IList<Cell> base = new Empty<Cell>(); for (Cell c : loc) { if (!c.isFlooded) { base = new Cons<Cell>(c, base); } } return base; } // helper method to generate a random number in the range -n to n int randomInt(int n) { return -n + (new Random().nextInt(2 * n + 1)); } //EFFECT: update the world each tick public void onTick() { if (this.ticks % 10 == 0) { this.waterHeight += 1; if (player.aquatic) { this.duckTimeLeft -= 1; if (this.duckTimeLeft == 0) { player.aquatic = false; } } } if (this.ticks % 50 == 0) { this.duck = new PowerUp(convertLand(this.board)); } if (!gameWon && !gameLost) { this.ticks += 1; } for (Cell c : this.board) { if (c.nextFlooded() && this.waterHeight >= c.height) { c.isFlooded = true; c.left.floodFill(); c.right.floodFill(); c.bottom.floodFill(); c.top.floodFill(); } } if ((this.player.cell.isFlooded && !player.aquatic) || this.ticks >= 640) { this.gameLost = true; } else if (this.targets.length() == 0) { this.gameWon = true; } } //EFFECT: update the world with the appropriate keys public void onKeyEvent(String k) { if (k.equals("m")) { this.constructMountain(); } else if (k.equals("r")) { this.constructRandom(); } else if (k.equals("t")) { this.constructTerrain(); } else if (this.targets.length() == 0) { this.gameWon = true; } else if (this.player.cell.isFlooded && !player.aquatic) { this.gameLost = true; } else if (k.equals("up") && (!this.player.cell.top.isFlooded || player.aquatic)) { moveHelper(this.player.cell.top, 0, -1); } else if (k.equals("down") && (!this.player.cell.bottom.isFlooded || player.aquatic)) { moveHelper(this.player.cell.bottom, 0, 1); } else if (k.equals("left") && (!this.player.cell.left.isFlooded || player.aquatic)) { moveHelper(this.player.cell.left, -1, 0); } else if (k.equals("right") && (!this.player.cell.right.isFlooded || player.aquatic)) { moveHelper(this.player.cell.right, 1, 0); } else if (k.equals("s") && this.duckAvailible) { player.aquatic = true; this.duckAvailible = false; this.duckTimeLeft = 5; } } //helper method to move the player public void moveHelper(Cell c, int x, int y) { this.player.cell = c; this.player.x += x; this.player.y += y; this.score += 1; IList<Item> t = new Empty<Item>(); for (Item i : this.targets) { if (!i.collectable(player, this.targets.length())) { t = new Cons<Item>(i, t); } if (duck.collectable(player, 0)) { this.duckAvailible = true; this.duck = new PowerUp(convertLand(this.board)); } } this.targets = t; } // displays the scene public WorldScene makeScene() { WorldScene bg = this.getEmptyScene(); for (Cell c : this.board) { c.drawCell(bg, this.waterHeight); } for (Item i : this.targets) { i.drawItem(bg); } if (!this.duckAvailible && !player.aquatic) { duck.drawItem(bg); } player.drawItem(bg); if (this.gameWon) { bg.placeImageXY(new TextImage("You Win!", ISLAND_SIZE, Color.red), (ISLAND_SIZE / 2) * 10, (ISLAND_SIZE / 2) * 10); bg.placeImageXY(new TextImage("Total steps taken: " + Integer.toString(this.score), ISLAND_SIZE / 4, Color.red), (ISLAND_SIZE / 2) * 10, ISLAND_SIZE * 7); } else if (this.gameLost) { bg.placeImageXY(new TextImage("You Drowned", ISLAND_SIZE, Color.red), (ISLAND_SIZE / 2) * 10, (ISLAND_SIZE / 2) * 10); } else if (player.aquatic) { bg.placeImageXY(new TextImage(String.format("%02d:%02d", (ISLAND_SIZE - 1 - ticks / 10) % 3600 / 60, (ISLAND_SIZE - 1 - ticks / 10) % 60), ISLAND_SIZE / 4, Color.red), ISLAND_SIZE * 9, ISLAND_SIZE / 4); bg.placeImageXY(new TextImage(Integer.toString(duckTimeLeft), ISLAND_SIZE / 4, Color.green), ISLAND_SIZE * 9, ISLAND_SIZE / 2); } else { bg.placeImageXY(new TextImage(String.format("%02d:%02d", (ISLAND_SIZE - 1 - ticks / 10) % 3600 / 60, (ISLAND_SIZE - 1 - ticks / 10) % 60), ISLAND_SIZE / 4, Color.red), ISLAND_SIZE * 9, ISLAND_SIZE / 4); } return bg; } } //class to make an IList iterable class IListIterator<T> implements Iterator<T> { IList<T> items; IListIterator(IList<T> items) { this.items = items; } public boolean hasNext() { return this.items.isCons(); } public T next() { Cons<T> itemsAsCons = this.items.asCons(); T answer = itemsAsCons.first; this.items = itemsAsCons.rest; return answer; } public void remove() { throw new UnsupportedOperationException("Don't do this!"); } } // interface representing an IList interface IList<T> extends Iterable<T> { boolean isCons(); Cons<T> asCons(); Iterator<T> iterator(); int length(); } // represents an empty list class Empty<T> implements IList<T> { public Iterator<T> iterator() { return new IListIterator<T>(this); } public boolean isCons() { return false; } public Cons<T> asCons() { return null; } public int length() { return 0; } } // represents a non empty list class Cons<T> implements IList<T> { T first; IList<T> rest; // constructor for Cons<T> Cons(T first, IList<T> rest) { this.first = first; this.rest = rest; } public Iterator<T> iterator() { return new IListIterator<T>(this); } public boolean isCons() { return true; } public Cons<T> asCons() { return this; } public int length() { return 1 + this.rest.length(); } } // examples class class ExamplesWorld { ForbiddenIslandWorld world1; ForbiddenIslandWorld world2; ForbiddenIslandWorld world3; ArrayList<ArrayList<Cell>> alist1; ArrayList<ArrayList<Cell>> alist2; ArrayList<ArrayList<Cell>> alist3; void initTestConditions() { world1 = new ForbiddenIslandWorld(0); world2 = new ForbiddenIslandWorld(1); world3 = new ForbiddenIslandWorld(2); alist1 = world1.makeCells(world1.allHeights()); alist2 = world2.makeCells(world2.allHeightsRand()); alist3 = world3.makeCellsRand(world3.allHeightsZero()); } // tester method void testConditions(Tester t) { this.initTestConditions(); t.checkExpect(alist1.get(1).get(3).right.sameCell(alist1.get(1).get(4)), true); t.checkExpect(alist1.get(1).get(3).left.sameCell(alist1.get(1).get(2)), true); t.checkExpect(alist1.get(1).get(3).top.sameCell(alist1.get(0).get(3)), true); t.checkExpect(alist1.get(1).get(3).bottom.sameCell(alist1.get(2).get(3)), true); t.checkExpect(alist1.get(0).get(3).top.sameCell(alist1.get(0).get(3)), true); t.checkExpect(alist1.get(64).get(3).bottom.sameCell(alist1.get(64).get(3)), true); t.checkExpect(alist1.get(32).get(0).left.sameCell(alist1.get(32).get(0)), true); t.checkExpect(alist1.get(32).get(64).right.sameCell(alist1.get(32).get(64)), true); t.checkExpect(alist1.get(64).get(3).bottom.bottom.sameCell(alist1.get(64).get(3)), true); t.checkExpect(alist1.get(4).get(4).sameCell(alist1.get(8).get(8)), false); t.checkExpect(new Cell(4, 4, 30.0, false).sameCell(new Cell(4, 4, 30.0, false)), true); t.checkExpect(new Cell(4, 4, 30.0, false).sameCell(new Cell(1, 4, 30.0, false)), false); t.checkExpect(new Cell(4, 4, 30.0, false).sameCell(new Cell(4, 1, 30.0, false)), false); t.checkExpect(new Cell(4, 4, 30.0, false).sameCell(new Cell(4, 4, 32.0, false)), false); t.checkExpect(alist1.get(32).get(32).height, 64.0); t.checkExpect(alist1.get(32).get(32).chooseColor(0), Color.WHITE); t.checkExpect(alist1.get(0).get(0).chooseColor(0), new Color(0, 0, 128)); t.checkExpect(alist2.get(1).get(3).right.sameCell(alist2.get(1).get(4)), true); t.checkExpect(alist2.get(1).get(3).left.sameCell(alist2.get(1).get(2)), true); t.checkExpect(alist2.get(1).get(3).top.sameCell(alist2.get(0).get(3)), true); t.checkExpect(alist2.get(1).get(3).bottom.sameCell(alist2.get(2).get(3)), true); t.checkExpect(alist2.get(0).get(3).top.sameCell(alist2.get(0).get(3)), true); t.checkExpect(alist2.get(64).get(3).bottom.sameCell(alist2.get(64).get(3)), true); t.checkExpect(alist2.get(32).get(0).left.sameCell(alist2.get(32).get(0)), true); t.checkExpect(alist2.get(32).get(64).right.sameCell(alist2.get(32).get(64)), true); t.checkExpect(alist2.get(64).get(3).bottom.bottom.sameCell(alist2.get(64).get(3)), true); t.checkNumRange(alist2.get(32).get(32).height, 0.0, 64.0); t.checkNumRange(alist2.get(43).get(24).height, 0.0, 64.0); t.checkExpect(alist3.get(1).get(3).right.sameCell(alist3.get(1).get(4)), true); t.checkExpect(alist3.get(1).get(3).left.sameCell(alist3.get(1).get(2)), true); t.checkExpect(alist3.get(1).get(3).top.sameCell(alist3.get(0).get(3)), true); t.checkExpect(alist3.get(1).get(3).bottom.sameCell(alist3.get(2).get(3)), true); t.checkExpect(alist3.get(0).get(3).top.sameCell(alist3.get(0).get(3)), true); t.checkExpect(alist3.get(64).get(3).bottom.sameCell(alist3.get(64).get(3)), true); t.checkExpect(alist3.get(32).get(0).left.sameCell(alist3.get(32).get(0)), true); t.checkExpect(alist3.get(32).get(64).right.sameCell(alist3.get(32).get(64)), true); t.checkExpect(alist3.get(64).get(3).bottom.bottom.sameCell(alist3.get(64).get(3)), true); t.checkExpect(alist3.get(4).get(4).sameCell(alist3.get(8).get(8)), false); t.checkExpect(alist1.get(1).get(1).isFlooded, true); t.checkExpect(alist1.get(32).get(32).isFlooded, false); t.checkExpect(alist1.get(30).get(10).isFlooded, false); for (Cell c: world1.board) { if (c.height == 64.0) { c.isFlooded = true; c.floodFill(); } } for (Cell c: world1.board) { t.checkExpect(c.isFlooded, true); } this.initTestConditions(); world1.player.y = 10; world1.onKeyEvent("up"); t.checkExpect(world1.player.y, 9); world1.player.y = 10; world1.onKeyEvent("down"); t.checkExpect(world1.player.y, 11); world1.player.x = 10; world1.onKeyEvent("left"); t.checkExpect(world1.player.x, 9); world1.player.x = 10; world1.onKeyEvent("right"); t.checkExpect(world1.player.x, 11); world1.player.y = 10; world1.player.x = 10; world1.moveHelper(world1.player.cell, 30, 5); t.checkExpect(world1.player.y, 15); t.checkExpect(world1.player.x, 40); this.initTestConditions(); for (Cell c : world1.board) { if (c.height == 64.0) { world1.player.cell = c; world1.player.x = c.x; world1.player.y = c.y; } } t.checkExpect(world1.waterHeight, 0); for (int i = 0; i < 10; i += 1) { this.world1.onTick(); } t.checkExpect(world1.waterHeight, 1); for (int i = 0; i < 590; i += 1) { this.world1.onTick(); } t.checkExpect(world1.waterHeight, 60); for (Cell c : world1.board) { if (c.height > 60) { t.checkExpect(c.isFlooded, false); } else { t.checkExpect(c.isFlooded, true); } } t.checkExpect(world1.duckAvailible, false); for (Cell c : world1.board) { if (c.height == 64.0) { world1.duck.cell = c; world1.duck.x = c.x; world1.duck.y = c.y; } } world1.onKeyEvent("up"); world1.onKeyEvent("down"); t.checkExpect(world1.score, 2); t.checkExpect(world1.duckAvailible, true); t.checkExpect(world1.player.aquatic, false); world1.onKeyEvent("s"); t.checkExpect(world1.player.aquatic, true); for (int i = 0; i < 10; i += 1) { world1.onKeyEvent("left"); } t.checkExpect(world1.gameLost, false); for (int i = 0; i < 50; i += 1) { world1.onTick(); } t.checkExpect(world1.gameLost, true); t.checkExpect(world1.score, 12); } // runs the game void testWorld(Tester t) { ForbiddenIslandWorld w = new ForbiddenIslandWorld(2); w.bigBang((ForbiddenIslandWorld.ISLAND_SIZE + 1) * 10, (ForbiddenIslandWorld.ISLAND_SIZE + 1) * 10, .1); } }
true
798a51b45cdddba3389293921294882dc07b07ec
Java
zhourihu5/wujiaBack
/core/src/main/java/com/wj/core/service/op/BannerService.java
UTF-8
1,974
2.09375
2
[]
no_license
package com.wj.core.service.op; import com.wj.core.entity.op.OpBanner; import com.wj.core.entity.op.OpBannerType; import com.wj.core.repository.op.BannerRepository; import com.wj.core.repository.op.BannerTypeRepository; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class BannerService { @Autowired private BannerRepository bannerRepository; @Autowired private BannerTypeRepository bannerTypeRepository; @Value("${wj.oss.access}") private String url; public void saveBanner(OpBanner banner) { banner.setCreateDate(new Date()); if (banner.getId() != null) { if (StringUtils.isNotBlank(banner.getCover()) && !banner.getCover().startsWith("http")) { banner.setCover(url + banner.getCover()); } } else { if (StringUtils.isNotBlank(banner.getCover())) { banner.setCover(url + banner.getCover()); } } bannerRepository.save(banner); } public void delBanner(OpBanner banner) { bannerRepository.delete(banner); } public List<OpBanner> findByModuleTypeList(Integer type) { return bannerRepository.findByModuleTypeList(type); } public Page<OpBanner> findAll(Integer type, Pageable pageable) { Page<OpBanner> page = null; if (type != null) { page = bannerRepository.findByType(type, pageable); } else { bannerRepository.findAll(pageable); } return page; } public List<OpBannerType> findBannerTypeList() { return bannerTypeRepository.findAll(); } }
true
e70427343a34a388bb25e25f489fd08b7532fb56
Java
Thue/FreeCol
/src/net/sf/freecol/server/ai/WorkLocationPlan.java
UTF-8
4,370
2.1875
2
[]
no_license
/** * Copyright (C) 2002-2013 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.server.ai; import java.util.logging.Logger; import javax.xml.stream.XMLStreamException; import net.sf.freecol.common.io.FreeColXMLWriter; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.Specification; import net.sf.freecol.common.model.WorkLocation; import net.sf.freecol.common.util.Utils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Objects of this class contains AI-information for a single * {@link net.sf.freecol.common.model.WorkLocation}. */ public class WorkLocationPlan extends AIObject { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(WorkLocationPlan.class.getName()); /** The work location the plan is for. */ private WorkLocation workLocation; /** The goods to produce. */ private GoodsType goodsType; /** * Creates a new <code>WorkLocationPlan</code>. * * @param aiMain The main AI-object. * @param workLocation The <code>WorkLocation</code> to create * a plan for. * @param goodsType The goodsType to be produced on the * <code>workLocation</code> using this plan. */ public WorkLocationPlan(AIMain aiMain, WorkLocation workLocation, GoodsType goodsType) { super(aiMain); this.workLocation = workLocation; this.goodsType = goodsType; uninitialized = false; } /** * Creates a new <code>WorkLocationPlan</code>. * * @param aiMain The main AI-object. * @param element An <code>Element</code> containing an * XML-representation of this object. */ public WorkLocationPlan(AIMain aiMain, Element element) { super(aiMain, element); } /** * Gets the <code>WorkLocation</code> this * <code>WorkLocationPlan</code> controls. * * @return The <code>WorkLocation</code>. */ public WorkLocation getWorkLocation() { return workLocation; } /** * Gets the type of goods which should be produced at the * <code>WorkLocation</code>. * * @return The type of goods. * @see net.sf.freecol.common.model.Goods * @see net.sf.freecol.common.model.WorkLocation */ public GoodsType getGoodsType() { return goodsType; } /** * Sets the type of goods to be produced at the <code>WorkLocation</code>. * * @param goodsType The type of goods. * @see net.sf.freecol.common.model.Goods * @see net.sf.freecol.common.model.WorkLocation */ public void setGoodsType(GoodsType goodsType) { this.goodsType = goodsType; } /** * Is this a food producing plan? * * @return True if this plan produces food. */ public boolean isFoodPlan() { return goodsType.isFoodType(); } // Serialization // WorkLocationPlans are not currently saved so this is a no-op. /** * {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(32); sb.append("[").append(getId()) .append(" ").append(goodsType.getSuffix()) .append(" at ").append(workLocation.getId()) .append("]"); return sb.toString(); } /** * {@inheritDoc} */ public String getXMLTagName() { return getXMLElementTagName(); } /** * Gets the tag name of the root element representing this object. * * @return "workLocationPlan" */ public static String getXMLElementTagName() { return "workLocationPlan"; } }
true
fc1ed39746f23c7f0b15df82d222d817861a3a6e
Java
fofi/Test
/TEST_TRLYX/src/com/teralyx/test/client/widgets/ge/plugin/KmlBalloonStyle.java
UTF-8
1,071
1.984375
2
[]
no_license
package com.teralyx.test.client.widgets.ge.plugin; import com.google.gwt.core.client.JavaScriptObject; public class KmlBalloonStyle extends KmlObject { public KmlBalloonStyle(JavaScriptObject impl) { super(impl); // TODO Auto-generated constructor stub } public KmlColor getBgColor () { return new KmlColor(getBgColorImpl(getImpl())); } public native JavaScriptObject getBgColorImpl(JavaScriptObject impl) /*-{ return impl.getBgColor(); }-*/; public KmlColor getTextColor () { return new KmlColor(getTextColorImpl(getImpl())); } public native JavaScriptObject getTextColorImpl(JavaScriptObject impl) /*-{ return impl.getTextColor(); }-*/; public String getText () { return getTextImpl(getImpl()); } public native String getTextImpl(JavaScriptObject impl) /*-{ return impl.getText(); }-*/; public void setText (String text){ setTextImpl(getImpl(), text); } public native void setTextImpl(JavaScriptObject impl, String text) /*-{ impl.setText(text); }-*/; }
true
f7e3b4f303c874ff43de03607f2324bd04a827c1
Java
iinow/algorithm
/0290-word-pattern/0290-word-pattern.java
UTF-8
1,045
3.234375
3
[]
no_license
class Solution { public boolean wordPattern(String pattern, String str) { HashMap<Character,String>h=new HashMap<>(); String [] s=str.split("\\ "); char c='a'; String b=""; if(s.length!=pattern.length())return false; for(int i=0;i<s.length;i++) { c=pattern.charAt(i); b=s[i]; if(!h.containsKey(c) && !h.containsValue(b)) { h.put(c,b); } else if(h.containsKey(c)) { if(!h.get(c).equals(b)) { return false; } } else if(h.containsValue(b)) { int x=0; for(Map.Entry<Character,String> m:h.entrySet()) { if(m.getValue()==b) { x=m.getKey(); } } if(x!=c)return false; } } return true; } }
true
c7dba419ba77a2978e697ba9f77b033da10dd2aa
Java
chrismoroney/Bellevue-College-CS-210
/Illusion-1.java
UTF-8
7,237
3.734375
4
[]
no_license
// CS210 Assignment #3 "Circles" // Chris Moroney // This is the illuion project. This project is mainly composed of functions that // contain a lot of inputs. These inputs are especially important because they // are the parameters of how each method will be executed in drawing their shapes. // Within each method are loops, calculations to find points, and coded lines from the // drawing panel to assist in the artistic perspecting (such as color, shape types, etc.). // The hardest part for me was to algorithimically figure out each function so // that the shapes could be well drawn and proportonal. However, once I figured it // out, the easiest part was simply just inputing numbers that fit the variables, // which consisted of coordinates and lengths. import java.awt.*; public class Illusion { //calls the drawFigures method public static void main(String[] args) { drawFigures(); } // This is the order that all of the methods are executed. Additionally, what // is most important are the values that are inputed into each method. Each statement // below contains coordinates and lengths for the dimensions that each shape // needs to hold in order to be drawn out to proper length, inscribed, or simply // put to scale. public static void drawFigures() { DrawingPanel dp = new DrawingPanel(500,400); dp.setBackground(Color.cyan); Graphics g = dp.getGraphics(); drawDiamondInCircles(0, 0, 90, 3, g); drawDiamondInCircles(120, 10, 90, 3, g); drawDiamondInCircles(250, 50, 80, 5, g); drawCirclesInBox(350, 20, 40, 5, 3, g); drawCirclesInBox(10, 120, 100, 10, 2, g); drawCirclesInBox(240, 160, 50, 5, 4, g); } // This method will draw the number of circles in each "area". It starts with // the base circle, which is just given an (x,y), and a width r. However, if // there are more circles that are wanted inside of the largest circle, then // by using a nested loop, there will be another circle printed inside, which // is proportional to the largest most circle. The circles are spaced with the // intervals that are calculated in relation to the radius, which then effects the amount // of circles. Finally, a diamond is drawn to be inscribed inside of the largest circle. public static void drawDiamondInCircles(int x, int y, int r, int numCircles, Graphics g){ // This part is where all of the variables are defined. I named the diamter (r) // of all the circles to be the diamter divided by the total number of circles. // The center was given by moving the location of the original (x,y), which // was in the top left-most corner of a square, in relation to the next x and // y coordinates. The coordinates always move inwards by the same incrament // beacuse the shape is a circle, as shown in the for loop. // x, y, and r are the x coordinate, y coordinate, and the diameter of the circles. int radiusStepSize = r / numCircles; int centerStepSize = radiusStepSize / 2; int thisX = x; int thisY = y; int thisR = r; // this is the foreloop that creates the circles within circles. I set it up // with the variables so that the center will always remain the same. It will // first draw the circles, then outline all of them black. for(int thisStep=0; thisStep<numCircles; thisStep++){ g.setColor(Color.yellow); g.fillOval(thisX, thisY, thisR, thisR); g.setColor(Color.black); g.drawOval(thisX, thisY, thisR, thisR); thisX = thisX + centerStepSize; thisY = thisY + centerStepSize; thisR = thisR - radiusStepSize; } // This is the inscribed diamond, which is given by the drawDiamond method. // The inputs are the x-coordinate, y-coordinate, and the diameter that the // Diamond needs to have in order to be inscribed. g.setColor(Color.black); drawDiamond(x, y, r, g); } // This method draws all of the subfigure circles, which are the circles that // are inside of a Gray Square. The method is able to figure out how many // subfigures should be inside of the box with the numbers above, then where // to place them (evenly along the x and y axis). public static void drawCirclesInBox(int x, int y, int sizeOfCircle, int subCircles, int rowsCols, Graphics g){ // This will draw the gray box, which is given with an x and y coordinate, and then // the sizes, which are given in the main method. int sideSize = sizeOfCircle * rowsCols; drawGrayBox(x, y, sideSize, sideSize, g); // this nested loop will produce the number of squares according to the // parameters listed in the main method. It will start at the coordinates, //(x,y), then move to the next subfigure by the incraments that fits another // whole Circle without overlapping or gapping. The circles will stop being //produced when it fills the square, otherwise being equal to or greater than //the size of the circles times the rows and columns. for(int ix = x; ix<x+(sizeOfCircle*rowsCols); ix+=sizeOfCircle){ for(int iy = y; iy<y+(sizeOfCircle * rowsCols); iy+=sizeOfCircle){ drawDiamondInCircles(ix,iy,sizeOfCircle,subCircles,g); } } } // this method draws all of the large gray squares. In this method, the input // to get the, "rectangle" or square, is a starting x and y, then inputing a width and height. public static void drawGrayBox(int x, int y, int w, int h, Graphics g){ //sets the color to light_gray, and then fills the square rectangle. g.setColor(Color.LIGHT_GRAY); g.fillRect(x, y, w, h); //sets the color to red, and then outlines the square or rectangle. g.setColor(Color.red); g.drawRect(x, y, w, h); } // this method draws out the diamond, or the tilted square. Each endpoint of this // diamond is at the midpoint of a regular square. This is how a square can be // tilted and remain the same shape. I use the variable r to define the distance of an // original square. The original square starts at (x,y), meaning that // r is the distance from one point to another. public static void drawDiamond(int x, int y, int r, Graphics g){ g.setColor(Color.BLACK); // these are the the coordinates of drawing the lines. The textbook states that in //order to draw a line, you must state where the line is being drawn from // x1,y1 to x2,y2. With the above statements in relation to r, if there is a point // that is the midpoint of an original square, then the int r/2 will split // the distance. g.drawLine(x+(r/2), y, x+r, y+(r/2)); g.drawLine(x+r, y+(r/2), x+(r/2), y+r); g.drawLine(x+(r/2), y+r, x, y+(r/2)); g.drawLine(x, y+(r/2), x+(r/2), y); } }
true
c25d50292232ce4af8cfbbbe7025ed7faa080ac2
Java
KingCjy/jwp-aop
/src/main/java/core/jdbc/TransactionManager.java
UTF-8
1,305
2.859375
3
[]
no_license
package core.jdbc; import java.sql.Connection; /** * @author KingCjy */ public class TransactionManager { private static ThreadLocal<Connection> holdConnections = new ThreadLocal<>(); private static ThreadLocal<Connection> connections = new ThreadLocal<>(); private static ThreadLocal<Boolean> actives = new ThreadLocal<>(); public static void startTransaction() { if(isTransactionActive()) { throw new IllegalStateException("Cannot activate transaction synchronization - already actives"); } actives.set(true); } public static boolean isTransactionActive() { return (actives.get() != null && actives.get() == true); } public static void registerConnection(Connection connection) { connections.set(connection); } public static Connection getHoldConnection() { return holdConnections.get(); } public static void holdConnection(Connection connection) { holdConnections.set(connection); } public static Connection getConnection() { return connections.get(); } public static void releaseConnection() { holdConnections.set(null); } public static void finishTransaction() { connections.set(null); actives.set(false); } }
true
3249f2166854a05f9e25ced527f529dc98ce6a85
Java
rafaelpeguero/Proyecto-BD
/Fabrica de quesos/src/visual/listadequesos.java
ISO-8859-1
5,111
2.40625
2
[]
no_license
package visual; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import logico.Fabrica; import logico.Queso; import logico.Queso_Cilindrico; import logico.Queso_esfera; import logico.Queso_hueco; import javax.swing.border.TitledBorder; import javax.swing.JScrollPane; import javax.swing.JTable; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.border.BevelBorder; import javax.swing.border.EtchedBorder; import java.awt.Toolkit; import javax.swing.ImageIcon; public class listadequesos extends JDialog { private final JPanel contentPanel = new JPanel(); private static Object[] row; private static DefaultTableModel model; private JTable table; private JComboBox cbxTip; /** * Launch the application. */ /** * Create the dialog. */ public listadequesos() { setIconImage(Toolkit.getDefaultToolkit().getImage(listadequesos.class.getResource("/imagenes/icons8-mostrar-propiedad-25.png"))); setTitle("Lista de quesos"); setResizable(false); setBounds(100, 100, 458, 539); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new TitledBorder(null, "Informaci\u00F3n", TitledBorder.LEADING, TitledBorder.TOP, null, null)); getContentPane().add(contentPanel, BorderLayout.CENTER); setLocationRelativeTo(null); contentPanel.setLayout(null); JPanel panel = new JPanel(); panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); panel.setBounds(10, 51, 424, 371); contentPanel.add(panel); panel.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); panel.add(scrollPane, BorderLayout.CENTER); String[] header = {"Codigo", "Precio"}; table = new JTable(); table.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(table.getSelectedRow() >= 0) { int index = table.getSelectedRow(); } } }); model = new DefaultTableModel(); model.setColumnIdentifiers(header); table.setModel(model); loadtable(0); scrollPane.setViewportView(table); JLabel lblTipo = new JLabel("Tipo:"); lblTipo.setFont(new Font("Microsoft JhengHei Light", Font.BOLD, 13)); lblTipo.setBounds(124, 26, 48, 14); contentPanel.add(lblTipo); cbxTip = new JComboBox(); cbxTip.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadtable(cbxTip.getSelectedIndex()); } }); cbxTip.setModel(new DefaultComboBoxModel(new String[] {"<Seleccione>", "Cilndrico", "Esfrico", "Hueco"})); cbxTip.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 13)); cbxTip.setBounds(182, 23, 112, 22); contentPanel.add(cbxTip); { JPanel buttonPane = new JPanel(); buttonPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton cancelButton = new JButton("Cancel"); cancelButton.setIcon(new ImageIcon(listadequesos.class.getResource("/imagenes/icons8-eliminar-30.png"))); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } } public static void loadtable(int index) { model.setRowCount(0); row = new Object[model.getColumnCount()]; switch(index) { case 0: for (Queso aux : Fabrica.getInstance().getMisquesos()) { if(aux instanceof Queso_Cilindrico && !(aux instanceof Queso_hueco)) { row[0] = aux.getCodigo()+"-Cilndrico"; }else if(aux instanceof Queso_esfera) { row[0] = aux.getCodigo()+"-Esfrico"; }else if(aux instanceof Queso_hueco) { row[0] = aux.getCodigo()+"-Hueco"; } row[1] = aux.precio(); model.addRow(row); } break; case 1: for (Queso aux : Fabrica.getInstance().getMisquesos()) { if(aux instanceof Queso_Cilindrico && !(aux instanceof Queso_hueco)) { row[0] = aux.getCodigo()+"-Cilndrico"; row[1] = aux.precio(); model.addRow(row); } } break; case 2: for (Queso aux : Fabrica.getInstance().getMisquesos()) { if(aux instanceof Queso_esfera) { row[0] = aux.getCodigo()+"-Esfrico"; row[1] = aux.precio(); model.addRow(row); } } break; case 3: for (Queso aux : Fabrica.getInstance().getMisquesos()) { if(aux instanceof Queso_hueco) { row[0] = aux.getCodigo()+"-Hueco"; row[1] = aux.precio(); model.addRow(row); } } break; } } }
true
b9c53385ead9ae02acd71b1d38b8d9beaf12a5ef
Java
Kiaorra/DIMIMEAL
/app/src/main/java/kr/hs/dimigo/meal/utility/ApiService.java
UTF-8
353
1.976563
2
[ "MIT" ]
permissive
package kr.hs.dimigo.meal.utility; import kr.hs.dimigo.meal.model.GetMealInfoResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; public interface ApiService { String API_URL = "https://dev-api.dimigo.in"; @GET("/dimibobs/{date}") Call<GetMealInfoResponse> getMealContent(@Path("date") String dates); }
true
85151d13485cc06d1d4b8983f580b18f8a82bee8
Java
svetanis/data-structures
/src/main/java/com/svetanis/datastructures/graph/unionfind/impl/QuickFind.java
UTF-8
2,309
3.171875
3
[]
no_license
package com.svetanis.datastructures.graph.unionfind.impl; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.Lists.newArrayList; import java.util.List; import com.google.common.collect.ImmutableList; import com.svetanis.java.base.Pair; public final class QuickFind { // dynamic connectivity with // quick-find is O(n^2) private int[] id; private int count; // num of components public QuickFind(int n) { this.count = n; this.id = new int[n]; for (int i = 0; i < n; i++) { this.id[i] = i; } } public int count() { return count; } public boolean areConnected(int p, int q) { validate(p); validate(q); return find(p) == find(q); } public int find(int p) { validate(p); return id[p]; } private void validate(int p) { int n = id.length; if (p < 0 || p >= n) { throw new IndexOutOfBoundsException(); } } public void union(int p, int q) { validate(p); validate(q); // put p and q into the same components int pId = find(p); int qId = find(q); if (pId == qId) { return; } // rename p's component to q's name for (int i = 0; i < id.length; i++) { if (id[i] == pId) { id[i] = qId; } } count--; } public static void main(String[] args) { int n = 10; QuickFind uf = new QuickFind(n); List<Pair<Integer, Integer>> pairs = init(); for (Pair<Integer, Integer> pair : pairs) { int p = pair.getLeft(); int q = pair.getRight(); // ignore if connected if (uf.areConnected(p, q)) { continue; } // combine components uf.union(p, q); System.out.println(pair); } System.out.println(uf.count() + " components"); } private static ImmutableList<Pair<Integer, Integer>> init() { List<Pair<Integer, Integer>> list = newArrayList(); list.add(Pair.build(4, 3)); list.add(Pair.build(3, 8)); list.add(Pair.build(6, 5)); list.add(Pair.build(9, 4)); list.add(Pair.build(2, 1)); list.add(Pair.build(8, 9)); list.add(Pair.build(5, 0)); list.add(Pair.build(7, 2)); list.add(Pair.build(6, 1)); list.add(Pair.build(1, 0)); list.add(Pair.build(6, 7)); return copyOf(list); } }
true
dd2716ab1ea30d86c0c247c866794a7db493d02a
Java
goyourfly/FreeWeather
/library/src/main/java/com/goyourfly/weather_library/Urls.java
UTF-8
1,508
2.140625
2
[ "Artistic-2.0" ]
permissive
package com.goyourfly.weather_library; import android.util.Log; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * Created by gaoyf on 14/12/27. */ public class Urls { public static final String CODE = "utf-8"; public static final String APPID = "04855f5e0cf44a9433ffd7b191a0650b63aebb66"; public static final String GET_WOEID = "http://where.yahooapis.com/v1/places.q('XXX')?appid=" + APPID + "&format=json"; public static final String GET_WEATHER = "https://query.yahooapis.com/v1/public/yql?q=WOEID&appid=" + APPID + "&format=json"; public static final String GET_WORD_PER_DAY = "http://open.iciba.com/dsapi/"; public static String getWoeidUrl(String cityName) { try { String result = GET_WOEID.replace("XXX", URLEncoder.encode(cityName, CODE)); Log.d("", "WoeidUrl:" + result); return result; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String getWeatherUrl(int woeid) { try { String result = GET_WEATHER.replace("WOEID", URLEncoder.encode("select * from weather.forecast where woeid=" + woeid, CODE)); Log.d("", "WeatherUrl:" + result); return result; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String getWordPerDayUrl() { return GET_WORD_PER_DAY; } }
true
76bacec629f81a0a00d56e570bcf017c0accffc9
Java
OnrHng/JavaAcademy
/src/academy/everyonecodes/java/week9/set1/exercise1/animals/amphibians/Frog.java
UTF-8
309
2.75
3
[]
no_license
package academy.everyonecodes.java.week9.set1.exercise1.animals.amphibians; public class Frog extends Amphibians { private boolean hasLegs; public Frog() { super("frog", "walk,jump,swim"); this.hasLegs = true; } public boolean isHasLegs() { return hasLegs; } }
true
544fa0ac0c90eb34a0a1c8c9671b63dc5a9b1ea0
Java
731942771/KnockoffLongyuan
/src/com/cuiweiyou/knockofflongyuan/fragment/CollectionFragment.java
UTF-8
5,158
2.1875
2
[]
no_license
package com.cuiweiyou.knockofflongyuan.fragment; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.cuiweiyou.knockofflongyuan.R; import com.cuiweiyou.knockofflongyuan.activity.InformationActivity; import com.cuiweiyou.knockofflongyuan.adapter.LVCollectionAdapter; import com.cuiweiyou.knockofflongyuan.back.ICollectionListBack; import com.cuiweiyou.knockofflongyuan.bean.CollectionBean; import com.cuiweiyou.knockofflongyuan.model.UrlModel; import com.cuiweiyou.knockofflongyuan.task.CollectionAsyncTask; /** * 收藏fmg,使用本地数据 * @author Administrator */ public class CollectionFragment extends Fragment implements ICollectionListBack { /** fmg布局 **/ private View mView; /** 收藏列表 **/ private ListView mLV; /** 收藏条目集合 **/ private List<CollectionBean> list; /** 列表适配器 **/ private LVCollectionAdapter adapter; /** 条目清空消息处理 **/ private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if(1 == msg.what) mView.findViewById(R.id.iv_warning_colfmg).setVisibility(View.VISIBLE); }; }; /** 收音机。接收从InfAty发来的收藏广播信息 **/ private BroadcastReceiver br = new BroadcastReceiver() { /** * 如果系统一直运行中,多次运行此应用: * 本地打开此应用,首先会接收到上次应用运行时发出的延时粘滞广播 * 就算被接收过了,粘滞广播仍然一直驻留在系统里 */ @Override public void onReceive(Context context, Intent intent) { String title = intent.getStringExtra("title"); String titleid = intent.getStringExtra("titleid"); if(title == null || title.length()<1) return; if(titleid == null || titleid.length()<1) return; /* 系统:原生5.1.1。 不重启的情况下,非第一次启动运行应用都会受到上次最后发出的广播内容 * 接收到广播一般早于异步数据回调 * 既然每次启动应用都这样,那么就根据adaper初始化情况操作: * null说明回调尚未结束 * 非null说明回调已经结束 */ if(adapter == null) {// 适配器是回调之后初始化的 list = new ArrayList<CollectionBean>(); adapter = new LVCollectionAdapter(getActivity(), list); mLV.setAdapter(adapter); return; } mView.findViewById(R.id.iv_warning_colfmg).setVisibility(View.GONE); CollectionBean cb = new CollectionBean(titleid, title); if("true".equals(intent.getStringExtra("do"))){ adapter.addItemAndNotifyChanged(cb); } else { adapter.delItemAndNotifyChanged(cb, handler); } } }; /** * 当Fmg关联Aty时 */ @Override public void onAttach(Activity activity) { // 注册收音机 IntentFilter ifr = new IntentFilter("collection"); // action:频道 /** 一旦注册,br的onReceive就接收一次,不管其它aty有没有发广播 * 大概是应对粘滞广播 */ activity.registerReceiver(br, ifr); super.onAttach(activity); }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.view_collection_fmg, container, false); mLV = (ListView) mView.findViewById(R.id.lv_col_colfmg); mLV.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CollectionBean item = (CollectionBean) adapter.getItem(position); String title = item.getTitle(); String titleID = item.getTitleID(); String infUrl = UrlModel.informationUrl + "titleid=" + titleID + "&fromtype=2"; //&categoryid=9"; // 进入正文Aty Intent intent=new Intent(getActivity(), InformationActivity.class); intent.putExtra("title", title); intent.putExtra("infUrl", infUrl); startActivity(intent); } }); new CollectionAsyncTask(this).execute(); return mView; } /** * asyncTask发回 */ @Override public void setColsList(List<CollectionBean> colList) { mView.findViewById(R.id.pb_isLoading_colfmg).setVisibility(View.GONE); if(colList == null || colList.size() < 1){ mView.findViewById(R.id.iv_warning_colfmg).setVisibility(View.VISIBLE); return; } if(adapter != null){ adapter.addItemAndNotifyChanged(colList); } else{ adapter = new LVCollectionAdapter(getActivity(), colList); mLV.setAdapter(adapter); } } /** * 和Aty的生命周期绑定的 */ @Override public void onDestroy() { super.onDestroy(); // 拆除收音机 getActivity().unregisterReceiver(br); } }
true
c56d1246233d8202277b28c09fae5ddda28cd227
Java
anokata/AllInOne
/java/2019/pat/mvc/BeatController.java
UTF-8
1,153
3.03125
3
[]
no_license
class BeatController implements ControllerInterface { public static void main(String[] args) { BeatController app = new BeatController(new BeatModel()); } BeatModelInterface model; DJView view; BeatController (BeatModelInterface model) { this.model = model; view = new DJView(this, model); view.createView(); view.createControls(); view.disableStopMenuItem(); view.enableStartMenuItem(); model.initialize(); } public void start() { model.on(); view.disableStartMenuItem(); view.enableStopMenuItem(); } public void stop() { model.off(); view.disableStopMenuItem(); view.enableStartMenuItem(); } public void increaseBPM() { int bpm = model.getBPM(); model.setBPM(bpm + 1); System.out.println("Set bpm to " + model.getBPM()); } public void decreaseBPM() { int bpm = model.getBPM(); model.setBPM(bpm - 1); System.out.println("Set bpm to " + model.getBPM()); } public void setBPM(int bpm) { model.setBPM(bpm); } }
true
78e8ab88d74ed15fd539ee3f6f0ae485973ef79f
Java
MrJasonss/mavenbos
/src/main/java/cn/itcast/bos/service/qp/NoticeBillService.java
UTF-8
649
1.890625
2
[]
no_license
package cn.itcast.bos.service.qp; import java.util.List; import cn.itcast.bos.domain.qp.NoticeBill; /** * 业务通知单 业务接口 * @author Mr_Jc * */ public interface NoticeBillService { /** * 新增业务员通知单 * @param noticeBill */ public void saveNoticeBill(NoticeBill noticeBill); /** * 人工调度查找出未自动分单的工单 * @return */ public List<NoticeBill> findnoassociations(); /** * 调度方法 * @param noticeBill */ public void saveOrUpdate(NoticeBill noticeBill); /** * 查出所有的工单 人工转台 * @return */ public List<NoticeBill> findassociations(); }
true
7cee589604c6b14b6d8f48fbd5713cf5967be2d6
Java
shatian114/laqun-springboot
/src/main/java/com/laqun/laqunserver/entity/Sn.java
UTF-8
670
1.929688
2
[]
no_license
package com.laqun.laqunserver.entity; import lombok.Data; import javax.persistence.*; @Data @Entity @Table(name = "sn") public class Sn { public Sn() { } public Sn(String sn) { this.sn = sn; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(unique = true) private String sn = ""; private String currentState = ""; private String jobName = ""; private String jobContent = ""; private String lastHttpTime = ""; private String appVer = ""; private int goodWxNum = 0; private int badWxNum = 0; private String currentWx = ""; private String remark = ""; }
true
9b295fc00fed40c8796d06dd6adeb5ce77816b07
Java
dtbinh/robotSoccer-2
/src/controllers/FieldController.java
UTF-8
6,541
2.734375
3
[]
no_license
package controllers; import bot.Robots; import communication.ReceiverListener; import data.VisionData; import strategy.Action; import ui.*; import utils.Geometry; import vision.KalmanFilter; import vision.VisionListener; import java.awt.*; import java.util.List; public class FieldController implements ReceiverListener, AreaListener, VisionListener { private Field field; private Ball ball; private Robots bots; private Robots opponentBots; private SituationArea selectedArea; public FieldController(Field field) { this.field = field; bots = field.getRobots(); ball = field.getBall(); opponentBots = field.getOpponentRobots(); //kFilter = new KalmanFilter(); field.setBackground(Color.green); } /** * Removes all components added to field which contains a situation area. */ public void removeAllSituationArea() { for (Component c : field.getComponents()) { if (c instanceof SituationArea) { field.remove(c); } } } public void toggleVisibilityForGlassPanels(boolean visible) { for (Component c : field.getComponents()) { if (c instanceof SituationArea) { c.setVisible(visible); } } } @Override public void action(List<String> chunks) { for (String s : chunks) { // -1 doesn't exist. if (s.indexOf("Robot") != -1) { int idIndex = s.indexOf("id="); int xIndex = s.indexOf("x="); int yIndex = s.indexOf("y="); int thetaIndex = s.indexOf("theta="); // id must be 0 - 9. so length must be 1. int id = Integer.parseInt(s.substring(idIndex + 3, idIndex + 4)); double x = Double.parseDouble(s.substring(xIndex + 2, yIndex - 1)); double y = Double.parseDouble(s.substring(yIndex + 2, thetaIndex - 1)); double theta = Double.parseDouble(s.substring(thetaIndex + 6, s.length())); bots.setIndividualBotPosition(id, x, y, theta); } else if (s.indexOf("Ball") != -1) { int xIndex = s.indexOf("x="); int yIndex = s.indexOf("y="); double x = Double.parseDouble(s.substring(xIndex + 2, yIndex - 1)); double y = Double.parseDouble(s.substring(yIndex + 2, s.length())); ball.setX(Math.round(x * 100)); ball.setY(Field.OUTER_BOUNDARY_HEIGHT - (int) Math.round(y * 100)); } } field.repaint(); } public double getBallX() { return ball.getXPosition(); } public double getBallY() { return ball.getYPosition(); } public void kickBall(double linearVelocity, double theta) { ball.setLinearVelocity(linearVelocity); ball.setTheta(theta); } @Override public void moveArea(int x, int y) { int newX = selectedArea.getX()-x; int newY = selectedArea.getY()-y; selectedArea.setBounds(newX, newY, selectedArea.getWidth(), selectedArea.getHeight()); field.repaint(); } @Override public void resizeArea(int w, int h, int x, int y) { //positive to the left //negative to the right int newWidth = selectedArea.getWidth() + w; int newHeight = selectedArea.getHeight() + h; selectedArea.setBounds(x, y, newWidth, newHeight); field.repaint(); } @Override public void redrawArea() { field.revalidate(); field.repaint(); } public void setSelectedArea(SituationArea a) { bringComponentToTheTop(a); selectedArea = a; } public void addArea(SituationArea area) { field.add(area); } public void removeArea(SituationArea area) { field.remove(area); } public void repaintField() { field.repaint(); } /** * <p>Brings the component to top level</p> * @param comp */ public void bringComponentToTheTop(Component comp) { if (comp != null && field.getComponentZOrder(comp) != -1) { for (Component c : field.getComponents()) { field.setComponentZOrder(c, field.getComponentCount()-1); } field.setComponentZOrder(comp, 0); } } /** * <p>Visibility of the situation area on the field</p> * @param show boolean variable */ public void showArea(boolean show) { for (Component c : field.getComponents()) { if (c.getClass().equals(SituationArea.class)){ c.setVisible(show); } } } /** * <p>Updates the ball or robots x, y, theta positions from the vision data</p> * <p>{@link data.VisionData}</p> * @param VisionData data */ @Override public void receive(VisionData data) { if (data.getType().equals("ball")) { //org.opencv.core.Point p = VisionController.imagePosToActualPos(data.getCoordinate()); //Point2D p = VisionController.imagePosToActualPos(ballCoord.x, ballCoord.y); ball.setX(data.getCoordinate().x); //hardcoded for now ball.setY(data.getCoordinate().y); } else if (data.getType().startsWith("robot")) { /* org.opencv.core.Point p = VisionController.imagePosToActualPos(data.getCoordinate()); //Point2D p = VisionController.imagePosToActualPos(robotCoord.x, robotCoord.y); int index = Math.abs(Integer.parseInt(data.getType().split(":")[1])) - 1; double correctTheta = VisionController.imageThetaToActualTheta(data.getTheta()); bots.getRobot(index).setX(p.x); bots.getRobot(index).setY(p.y); bots.getRobot(index).setTheta(Math.toDegrees(correctTheta)); */ //Point2D p = VisionController.imagePosToActualPos(robotCoord.x, robotCoord.y); int index = Math.abs(Integer.parseInt(data.getType().split(":")[1])) - 1; double correctTheta = VisionController.imageThetaToActualTheta(data.getTheta()); bots.getRobot(index).setX(data.getCoordinate().x); bots.getRobot(index).setY(data.getCoordinate().y); bots.getRobot(index).setTheta(Math.toDegrees(correctTheta)); } else if (data.getType().startsWith("opponent")) { org.opencv.core.Point p = VisionController.imagePosToActualPos(data.getCoordinate()); int index = Math.abs(Integer.parseInt(data.getType().split(":")[1])) - 1; opponentBots.getRobot(index).setX(p.x); opponentBots.getRobot(index).setY(p.y); opponentBots.getRobot(index).setTheta(0); } } public void executeStrategy() { field.executeStrategy(); } public void executeSetPlay() { field.executeSetPlay(); } public void executeManualControl() { field.executeManualControl(); } public Ball getBall() { return ball; } public Robots getRobots() { return bots; } public void setPredPoint(double x, double y) { field.setPredPoint(x, y); } public void setDrawAction(boolean draw) { field.setDrawAction(draw); field.repaint(); } public void setAction(Action action) { field.setAction(action); field.repaint(); } public void resetActiveSituation() { field.resetActiveSituation(); } }
true
8ac51c0609a2043570ae0864e17006c4897dc8cc
Java
usmetanina/Server
/src/main/java/server/service/schedule/WeekService.java
UTF-8
673
2.3125
2
[]
no_license
package server.service.schedule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import server.entity.schedule.Week; import server.repository.schedule.WeekRepository; import java.util.List; @Service public class WeekService { @Autowired private WeekRepository weekRepository; public List<Week> getAll() { return weekRepository.findAll(); } public Week getByID(int id) { return weekRepository.findOne(id); } public Week save(Week week) { return weekRepository.saveAndFlush(week); } public void remove(int id) {weekRepository.delete(id); } }
true
9de2ddc9503239f4a676e1458d7ebe12131a8c49
Java
tventurer/CA106G6
/src/com/spo/model/SpoVO.java
UTF-8
2,731
2.078125
2
[]
no_license
package com.spo.model; import java.io.Serializable; public class SpoVO implements Serializable{ private static final long serialVersionUID = 8320299842477944258L; private String spono; private String sponame; private String spoclass; private String spocon; private String spocity; private Double spolat; private Double spolong; private String spoaddr; private String spocontent; private byte[] spopic; private Integer spoattribute; public SpoVO() { } public String getSpono() { return spono; } public void setSpono(String spono) { this.spono = spono; } public String getSponame() { return sponame; } public void setSponame(String sponame) { this.sponame = sponame; } public String getSpoclass() { return spoclass; } public void setSpoclass(String spoclass) { this.spoclass = spoclass; } public String getSpocon() { return spocon; } public void setSpocon(String spocon) { this.spocon = spocon; } public String getSpocity() { return spocity; } public void setSpocity(String spocity) { this.spocity = spocity; } public Double getSpolat() { return spolat; } public void setSpolat(Double spolat) { this.spolat = spolat; } public Double getSpolong() { return spolong; } public void setSpolong(Double spolong) { this.spolong = spolong; } public String getSpoaddr() { return spoaddr; } public void setSpoaddr(String spoaddr) { this.spoaddr = spoaddr; } public String getSpocontent() { return spocontent; } public void setSpocontent(String spocontent) { this.spocontent = spocontent; } public byte[] getSpopic() { return spopic; } public void setSpopic(byte[] spopic) { this.spopic = spopic; } public Integer getSpoattribute() { return spoattribute; } public void setSpoattribute(Integer spoattribute) { this.spoattribute = spoattribute; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((sponame == null) ? 0 : sponame.hashCode()); result = prime * result + ((spono == null) ? 0 : spono.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SpoVO other = (SpoVO) obj; if (sponame == null) { if (other.sponame != null) return false; } else if (!sponame.equals(other.sponame)) return false; if (spono == null) { if (other.spono != null) return false; } else if (!spono.equals(other.spono)) return false; return true; } }
true
ddcb5af6db289af42b62bf5af7092b01a858f9e5
Java
PennFosterAutomation/SiteCoreSmokeChecklist
/SiteCoreSmoke/src/test/java/com/jav/SiteCore/pageobjects/URM_URL_Link_UI.java
UTF-8
6,015
2.03125
2
[]
no_license
package com.jav.SiteCore.pageobjects; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Reporter; import com.jav.SiteCore.tests.SelectedCourse_SmokeCheckpoint_Test; import com.jav.SiteCore.util.Utilities; public class URM_URL_Link_UI extends AbstractClass { WebDriver driver; public URM_URL_Link_UI(WebDriver driver) { super(driver); this.driver = driver; } @FindBy(xpath = "//a[contains(text(),'Home')]") protected WebElement globalPennFosterImage; @FindBy(xpath = "//a[@class='btn-blue btn-gloss large phonenumber']") protected WebElement globalPhoneNumer; @FindBy(xpath = "//div[@id='page-logo']") protected WebElement pennFosterLogo; public void verifyHomePageSiteCore() { WebDriverWait wait = new WebDriverWait(driver, 50); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='page-logo']"))); Assert.assertTrue(pennFosterLogo.isDisplayed()); Reporter.log(Utilities.logOutputFile(" Penn Foster logo displays on Landing Page - Pass")); } public void verifyPhoneNumbersGlobal() { String PhoneNumber = Utilities.getYamlValue("URMPhoneNumber.Global"); globalPennFosterImage.click(); Utilities.hardWait(3); WebDriverWait wait = new WebDriverWait(driver, 50); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//i[@class='icon-custom icon-client-caret-large-right']"))); Assert.assertTrue(globalPhoneNumer.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(globalPhoneNumer.getText()); List <WebElement> str = driver.findElements(By.xpath("//a[@class='phonenumber']")); System.out.println(str.size()); for(WebElement foo:str){ Assert.assertTrue(foo.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(foo.getText()); } } public void verifyPhoneNumbersCollege(){ String PhoneNumber = Utilities.getYamlValue("URMPhoneNumber.College"); driver.findElement(By.xpath("(//a[contains(text(),'Programs ')])[2]")).click(); driver.findElement(By.xpath("//a[@id='phcontent_0_rptT2Pages_rptFeaturedItems_6_lnkFeaturedItem_0']")).click(); WebDriverWait wait = new WebDriverWait(driver, 50); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(text(),'Overview ')]"))); Utilities.hardWait(3); Assert.assertTrue(globalPhoneNumer.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(globalPhoneNumer.getText()); List <WebElement> str = driver.findElements(By.xpath("//a[@class='phonenumber']")); System.out.println(str.size()); for(WebElement foo:str){ Assert.assertTrue(foo.getText().equalsIgnoreCase(PhoneNumber)); } } public void verifyPhoneNumberHighSchool(){ // driver.navigate().to(Utilities.getYamlValue("appurl")); // // WebDriverWait wait = new WebDriverWait(driver, 50); // wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//i[@class='icon-custom icon-client-caret-large-right']"))); navigatetohome(); System.out.println("finally Out"); String PhoneNumber = Utilities.getYamlValue("URMPhoneNumber.High School"); driver.findElement(By.xpath("(//a[contains(text(),'Programs ')])[2]")).click(); driver.findElement(By.xpath("//a[@id='phcontent_0_rptT2Pages_rptFeaturedItems_3_lnkFeaturedItem_0']")).click(); WebDriverWait wait = new WebDriverWait(driver, 50); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(text(),'Overview ')]"))); Assert.assertTrue(globalPhoneNumer.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(globalPhoneNumer.getText()); List <WebElement> str = driver.findElements(By.xpath("//a[@class='phonenumber']")); System.out.println(str.size()); for(WebElement foo:str){ Assert.assertTrue(foo.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(foo.getText()); } } public void navigatetohome() { driver.findElement(By.xpath("//ul[@class='breadcrumb hidden-tablet hidden-phone']/li[1]/a")).click(); WebDriverWait wait = new WebDriverWait(driver, 50); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//i[@class='icon-custom icon-client-caret-large-right']"))); } public void verifyPhoneNumberMedicalAssistant(){ System.out.println("finally Out"); String PhoneNumber = Utilities.getYamlValue("URMPhoneNumber.Medical Assistant Associate Degree"); Assert.assertTrue(globalPhoneNumer.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(globalPhoneNumer.getText()); List <WebElement> str = driver.findElements(By.xpath("//a[@class='phonenumber']")); System.out.println(str.size()); for(WebElement foo:str){ Assert.assertTrue(foo.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(foo.getText()); } } public void verifyPhoneNumberMilitary(){ System.out.println("finally Out"); driver.findElement(By.xpath("(//a[contains(text(),'Military')])[2]")).click(); WebDriverWait wait = new WebDriverWait(driver, 50); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h1[contains(text(),'Military')]"))); String PhoneNumber = Utilities.getYamlValue("URMPhoneNumber.Military"); Assert.assertTrue(globalPhoneNumer.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(globalPhoneNumer.getText()); List <WebElement> str = driver.findElements(By.xpath("//a[@class='phonenumber']")); System.out.println(str.size()); for(WebElement foo:str){ Assert.assertTrue(foo.getText().equalsIgnoreCase(PhoneNumber)); System.out.println(foo.getText()); } } }
true
eedd41dac47d334f1dd593f9577dbef6ab2c3c0f
Java
felixalguzman/programacion-2
/Practicas/Practica #2/Problema1/src/logical/Productor.java
UTF-8
388
2.375
2
[]
no_license
package logical; public class Productor extends Thread { private Correo correo; public Productor(Correo correo) { this.correo = correo; } public void run() { String [] mensajes = {"primer mensaje", "segundo mensaje", "tercer mensaje"}; for (String men:mensajes) { correo.enviar(men); } } }
true
a4f3f366e765f64f4f846119b2262d41c70ebd05
Java
artem70323/javaProjects
/dz5/src/tehnika/Indesit.java
UTF-8
425
2.21875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tehnika; public class Indesit extends Stiralka { private boolean shum; //шумная ли? public boolean isShum() { return shum; } public void setShum(boolean shum) { this.shum = shum; } }
true
082d4b8f3a5cefa0861eab1a2b6f9182b0a28384
Java
ivyxjc/pojo-generator
/src/main/java/xyz/ivyxjc/pojogenerator/model/DBColumn.java
UTF-8
143
1.789063
2
[ "Apache-2.0" ]
permissive
package xyz.ivyxjc.pojogenerator.model; public @interface DBColumn { Class javaType(); int columnType(); String columnName(); }
true
90b15ab93447176c550281567a08722a1999bd27
Java
balaganivenkatasubbaiah/MyApplication
/app/src/main/java/com/lyrebirdstudio/svg/Svg5Circle4.java
UTF-8
2,948
2.203125
2
[]
no_license
package com.lyrebirdstudio.svg; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; public class Svg5Circle4 extends Svg { private static final Matrix f1462m = new Matrix(); private static float od; private static final Paint f1463p = new Paint(); private static final Paint ps = new Paint(); private static final Path f1464t = new Path(); public void draw(Canvas c, int w, int h) { draw(c, (float) w, (float) h, 0.0f, 0.0f, false); } public void draw(Canvas c, float w, float h, float dx, float dy, boolean clearMode) { od = w / 508.0f < h / 513.0f ? w / 508.0f : h / 513.0f; m1525r(new Integer[0]); c.save(); c.translate((((w - (od * 508.0f)) / 2.0f) + dx) - 4.0f, (((h - (od * 513.0f)) / 2.0f) + dy) - 1.0f); f1462m.reset(); f1462m.setScale(od, od); c.save(); ps.setColor(Color.argb(0, 0, 0, 0)); ps.setStrokeCap(Cap.BUTT); ps.setStrokeJoin(Join.MITER); ps.setStrokeMiter(4.0f * od); c.translate(0.0f, 0.33f * od); c.scale(1.0f, 1.0f); c.save(); f1464t.reset(); f1464t.moveTo(0.0f, 0.0f); f1464t.lineTo(508.9f, 0.0f); f1464t.cubicTo(508.9f, 0.0f, 433.43f, 102.55f, 446.98f, 185.27f); f1464t.cubicTo(403.92f, 175.6f, 384.57f, 306.21f, 322.17f, 332.81f); f1464t.cubicTo(255.42f, 379.25f, 166.41f, 448.91f, 168.34f, 449.4f); f1464t.cubicTo(128.77f, 443.95f, 31.44f, 475.03f, 0.97f, 513.25f); f1464t.lineTo(0.0f, 0.0f); f1464t.transform(f1462m); c.drawPath(f1464t, f1463p); c.drawPath(f1464t, ps); c.restore(); m1525r(Integer.valueOf(3), Integer.valueOf(2), Integer.valueOf(0), Integer.valueOf(1)); c.restore(); m1525r(new Integer[0]); c.restore(); } private static void m1525r(Integer... o) { f1463p.reset(); ps.reset(); if (cf != null) { f1463p.setColorFilter(cf); ps.setColorFilter(cf); } f1463p.setAntiAlias(true); ps.setAntiAlias(true); f1463p.setStyle(Style.FILL); ps.setStyle(Style.STROKE); for (Integer i : o) { switch (i.intValue()) { case 0: ps.setStrokeJoin(Join.MITER); break; case 1: ps.setStrokeMiter(4.0f * od); break; case 2: ps.setStrokeCap(Cap.BUTT); break; case 3: ps.setColor(Color.argb(0, 0, 0, 0)); break; default: break; } } } }
true
4c9f04622eea6ca3548c37291494427f0c8c7e44
Java
ChristineNJU/HotelWorld
/src/main/java/hotel/controller/PlanController.java
UTF-8
2,342
2.265625
2
[]
no_license
package hotel.controller; import hotel.Util.MyDate; import hotel.model.Room; import hotel.service.PlanService; import hotel.service.RoomService; import hotel.vo.CheckIn; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.websocket.server.PathParam; import java.util.*; /** * Created by christine on 2017/3/20. */ @Controller @RequestMapping("/plans") public class PlanController { @Autowired private RoomService roomService; @Autowired private PlanService planService; @RequestMapping(method = RequestMethod.GET,params = {"hotelId", "begin", "end"}) public @ResponseBody List<Room> getPlans(@RequestParam(value = "hotelId") int id, @RequestParam(value = "begin") String begin, @RequestParam(value = "end") String end) throws Exception{ List<Room> rooms = roomService.getRoomByPlan(id,begin,end); return rooms; } @RequestMapping(value="/{id}",method = RequestMethod.GET) public @ResponseBody Map getHotelCheckIns(@PathVariable("id") Integer id) throws Exception{ Map<String,Object > result = new HashMap<String,Object>(); List<CheckIn> checkIns = planService.getHotelCheckIns(id); List<String> dates = new ArrayList<String>(); List<Integer> counts = new ArrayList<Integer>(); int size = checkIns.size(); for(int i = 0; i < checkIns.size();i++){ CheckIn current = checkIns.get(i); dates.add(MyDate.getFormatedDate(current.getDate())); counts.add(current.getCount()); if(i < size -1){ CheckIn next = checkIns.get(i+1); List<Date> gaps = MyDate.getDuring(MyDate.getFormatedDate(current.getDate()), MyDate.getFormatedDate(next.getDate())); //如果天数大于1的话,才会执行循环体(开始的那天也算在during里) for(int j = 1;j < gaps.size();j++){ dates.add(MyDate.getFormatedDate(gaps.get(j))); counts.add(0); } } } result.put("dates",dates); result.put("counts",counts); return result; } }
true
bcfcac0906be1e6b83df1adda9cddf63e29127c9
Java
onyourhead/jianzhiOffer
/src/niukewang/Match.java
UTF-8
1,955
3.28125
3
[]
no_license
package niukewang; import java.util.ArrayList; /** * title: Match * projectName: jianzhiOffer * author: 张政淇 * date: 2019/5/9 * time: 9:49 */ public class Match { public static void main(String[] args) { char[] str={'a'}; char[] pattern={'.','*'}; Match ex=new Match(); System.out.println(ex.solution(str,pattern)); } public boolean solution(char[] str, char[] pattern) { ArrayList<Character> strList=new ArrayList<>(); ArrayList<Character> patternList=new ArrayList<>(); for (char c:str) { strList.add(c); } for (char c:pattern) { patternList.add(c); } return isMatch(strList,patternList); } private boolean isMatch(ArrayList<Character> strList, ArrayList<Character> patternList) { if (strList.size()==0) { if (patternList.size() == 2 && patternList.get(1) == '*') return true; else return patternList.size() == 0; } if (patternList.size() == 0) { return false; } if (patternList.size()>=2 && patternList.get(1)=='*') { if (strList.get(0)!=patternList.get(0)) { if (patternList.get(0)=='.') { patternList.set(0,strList.get(0)); isMatch(strList,patternList); } patternList.remove(1); patternList.remove(0); return isMatch(strList,patternList); } else { strList.remove(0); return isMatch(strList,patternList); } } else { if (strList.get(0) == patternList.get(0) || patternList.get(0)=='.') { strList.remove(0); patternList.remove(0); return isMatch(strList,patternList); } else { return false; } } } }
true
bd93efda9efa9a22a6c5c77eb7f72683bd7ef4e4
Java
shubham-deb/Leetcode
/Programs/Leetcode_Problems/src/majority_element.java
UTF-8
663
3.3125
3
[]
no_license
import java.util.HashMap; import java.util.LinkedHashMap; public class majority_element { public static int majorityElement(int[] nums) { int max=nums[0]; HashMap<Integer,Integer> hmap = new LinkedHashMap<Integer,Integer>(); int threshold = nums.length/2; for(int num:nums){ if(hmap.get(num)!=null){ hmap.put(num, hmap.get(num)+1); if(hmap.get(num)>threshold) return num; }else{ hmap.put(num, 1); } } return max; } public static void main(String[] args) { int[] nums = {1}; System.out.println(majorityElement(nums)); } }
true
1a1d344ad9744a7a529515aa2377d8b97d374975
Java
Pranav-Sukumar/ElectoralMaps
/src/ElectoralMap.java
UTF-8
5,431
2.953125
3
[]
no_license
/* * Pranav Sukumar * ElectoralMap.java * This class contains the Electoral Map Class for the Red vs. Blue Project * No Revisions */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ElectoralMap { public void visualize(String string, int year) { if (!string.equals("USA-county")) { visualizeState(string, year, true); } else { visualizeCountryMap(string, year); } } private void visualizeState(String string, int year, boolean resize) throws NullPointerException { try { FileReader geoFile = new FileReader("./input/" + string + ".txt"); BufferedReader geoBr = new BufferedReader(geoFile); // Scaling Canvas Size String[] minCoords = geoBr.readLine().split(" "); double minX = Double.parseDouble(minCoords[0]); double minY = Double.parseDouble(minCoords[1]); String[] maxCoords = geoBr.readLine().split(" "); double maxX = Double.parseDouble(maxCoords[0]); double maxY = Double.parseDouble(maxCoords[1]); double xDiff = (maxX - minX); double yDiff = (maxY - minY); if (resize){ int scaleWidth = (int) ((xDiff * 512) / (yDiff)); StdDraw.setCanvasSize(scaleWidth, 512); StdDraw.setXscale(minX, maxX); StdDraw.setYscale(minY, maxY); } StdDraw.enableDoubleBuffering(); Map<String, RegionData> map = new HashMap<String, RegionData>(); FileReader electionFr = new FileReader("./input/" + string + year + ".txt"); BufferedReader electionBr = new BufferedReader(electionFr); electionBr.readLine(); String line = electionBr.readLine(); while (line != null) { String[] data = line.split(","); RegionData rd = new RegionData(Integer.parseInt(data[2]), Integer.parseInt(data[1]), Integer.parseInt(data[3])); String name = data[0].toLowerCase(); map.put(name, rd); line = electionBr.readLine(); } electionFr.close(); electionBr.close(); int n = Integer.parseInt(geoBr.readLine()); for (int i = 0; i < n; i++) { geoBr.readLine(); String countyName = geoBr.readLine(); geoBr.readLine(); int countySize = Integer.parseInt(geoBr.readLine()); double[] xCoords = new double[countySize]; double[] yCoords = new double[countySize]; for (int j = 0; j < countySize; j++) { String[] individualPoint = geoBr.readLine().split(" "); xCoords[j] = Double.parseDouble(individualPoint[0]); yCoords[j] = Double.parseDouble(individualPoint[1]); } countyName = countyName.replace(" Parish", ""); countyName = countyName.replace(" city", ""); if (string.equals("FL")){ countyName = countyName.replace("Dade", "Miami-Dade"); } countyName = countyName.toLowerCase(); if (map.containsKey(countyName)) { StdDraw.setPenColor(StdDraw.BLACK); StdDraw.setPenRadius(.005); StdDraw.polygon(xCoords, yCoords); int dVotes = map.get(countyName).getD(); int rVotes = map.get(countyName).getR(); int iVotes = map.get(countyName).getI(); int largest = Math.max(dVotes, Math.max(rVotes, iVotes)); if (largest == dVotes) { StdDraw.setPenColor(StdDraw.BLUE); StdDraw.filledPolygon(xCoords, yCoords); } else if (largest == rVotes) { StdDraw.setPenColor(StdDraw.RED); StdDraw.filledPolygon(xCoords, yCoords); } else if (largest == iVotes) { StdDraw.setPenColor(StdDraw.GREEN); StdDraw.filledPolygon(xCoords, yCoords); } } } StdDraw.show(); } catch (FileNotFoundException e) { System.out.println("FileNotFound Error"); e.printStackTrace(); } catch (NumberFormatException e) { System.out.println("FileNotFoundError"); e.printStackTrace(); } catch (IOException e) { System.out.println("IOException Error"); e.printStackTrace(); } } private void visualizeCountryMap(String string, int year) throws NullPointerException { try { FileReader geoFile = new FileReader("./input/" + string + ".txt"); BufferedReader geoBr = new BufferedReader(geoFile); // Scaling Canvas Size String[] minCoords = geoBr.readLine().split(" "); double minX = Double.parseDouble(minCoords[0]); double minY = Double.parseDouble(minCoords[1]); String[] maxCoords = geoBr.readLine().split(" "); double maxX = Double.parseDouble(maxCoords[0]); double maxY = Double.parseDouble(maxCoords[1]); double xDiff = (maxX - minX); double yDiff = (maxY - minY); int scaleWidth = (int) ((xDiff * 512) / (yDiff)); StdDraw.setCanvasSize(scaleWidth, 512); StdDraw.setXscale(minX, maxX); StdDraw.setYscale(minY, maxY); StdDraw.enableDoubleBuffering(); String[] states = { "AL", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" }; for (String s : states) { visualizeState(s, year, false); } StdDraw.show(); } catch (FileNotFoundException e) { System.out.println("FileNotFound Error"); e.printStackTrace(); } catch (NumberFormatException e) { System.out.println("FileNotFoundError"); e.printStackTrace(); } catch (IOException e) { System.out.println("IOException Error"); e.printStackTrace(); } } }
true
b77ee970d85c38115f69a257ddc48896d3d8e75b
Java
rnjswngus275/OpenSourceAndroid
/app/src/main/java/com/example/yoony/opensourceandroidproject/db/CommonDAO.java
UTF-8
1,101
2.625
3
[]
no_license
package com.example.yoony.opensourceandroidproject.db; import android.database.sqlite.SQLiteDatabase; import com.example.yoony.opensourceandroidproject.L; public class CommonDAO { //공통 private final SQLiteDatabase mDatabase; public CommonDAO(SQLiteDatabase mDatabase) { this.mDatabase = mDatabase; } public boolean createTables() throws Exception { //데이터베이스를 만든다, 유저정보 테이블과,자동차 관련 테이블이다. boolean pass = false; String createTables[][] = { DBConst.createGoalDataTable(), DBConst.createGoalSubTable() }; try { for (int i = 0; i < createTables.length; ++i) { for (int j = 0; j < createTables[i].length; ++j) { mDatabase.execSQL(createTables[i][j]); } } pass = true; } catch (Exception e) { L.e(":::::CREATE Exception ==> createTables() : CREATE Tables"); L.d(e.getMessage()); } return pass; } }
true
67c0a6246066bd1ec9c17ee61a7dc69cfc9d5a43
Java
Nikitosh/News-Searcher
/src/main/java/com/nikitosh/spbau/parser/PermissionsParserImpl.java
UTF-8
6,696
2.171875
2
[]
no_license
package com.nikitosh.spbau.parser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.html.HtmlParser; import org.apache.tika.sax.TeeContentHandler; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.*; public class PermissionsParserImpl implements PermissionsParser { private static final Logger LOGGER = LogManager.getLogger(); private static final String USER_AGENT = "User-Agent"; private static final String ROBOTS = "robots"; private static final String NOFOLLOW = "nofollow"; private static final String NOINDEX = "noindex"; private static final String NONE = "none"; private Map<String, RobotsTxtPermissions> domainPermissions = new HashMap<>(); @Override public Permissions getPermissions(String url) { addRobotsTxtPermissions(url); if (!isAllowedLink(url)) { return new Permissions(false, false); } boolean follow = true; boolean index = true; try { URL newUrl = new URL(url); URLConnection connection = newUrl.openConnection(); connection.setRequestProperty(USER_AGENT, ParserHelper.CRAWLER_BOT); connection.setConnectTimeout(ParserHelper.TIMEOUT); connection.connect(); InputStream input = connection.getInputStream(); Metadata metadata = new Metadata(); HtmlParser parser = new HtmlParser(); TeeContentHandler teeHandler = new TeeContentHandler(); parser.parse(input, teeHandler, metadata); String[] metadataNames = metadata.names(); ArrayList<String> allRules = new ArrayList<>(); for (String name : metadataNames) { if (name.equals(ROBOTS)) { String content = metadata.get(name); allRules.addAll(Arrays.asList(content.split(","))); } } if (allRules.contains(NOFOLLOW) || allRules.contains(NONE)) { follow = false; } if (allRules.contains(NOINDEX) || allRules.contains(NONE)) { index = false; } } catch (Exception e) { LOGGER.error("Failed to get meta data from url: " + url + " " + e.getMessage() + "\n"); } return new Permissions(index, follow); } @Override public double getDelay(String url) { addRobotsTxtPermissions(url); try { RobotsTxtPermissions permissions = domainPermissions.get(ParserHelper.getDomainName(url)); return permissions.getDelayInSeconds(); } catch (URISyntaxException exception) { LOGGER.error("Failed to get domain name from url: " + url + " due to exception: " + exception.getMessage() + "\n"); } return 0; } private void addRobotsTxtPermissions(String url) { try { String domainUrl = ParserHelper.getDomainName(url); if (!domainPermissions.containsKey(domainUrl)) { domainPermissions.put(domainUrl, RobotsTxtPermissions.from(domainUrl)); } } catch (URISyntaxException e) { LOGGER.error("Failed to get domain name from url: " + url + " due to exception: " + e.getMessage() + "\n"); } } private boolean isAllowedLink(String url) { try { RobotsTxtPermissions permissions = domainPermissions.get(ParserHelper.getDomainName(url)); List<String> allowedMasks = permissions.getAllowedUrlMasks(); List<String> disallowedMasks = permissions.getDisallowedUrlMasks(); int disallowMatchLength = 0; int allowMatchLength = 1; for (String mask : disallowedMasks) { if (ruleMatches(url, mask)) { disallowMatchLength = Math.max(disallowMatchLength, mask.length()); } } for (String mask : allowedMasks) { if (ruleMatches(url, mask)) { allowMatchLength = Math.max(allowMatchLength, mask.length()); } } return allowMatchLength > disallowMatchLength; } catch (URISyntaxException e) { LOGGER.error("Failed to get domain name from url: " + url + " due to exception: " + e.getMessage() + "\n"); } return false; } private boolean ruleMatches(String text, String pattern) { int patternPos = 0; int textPos = 0; int patternEnd = pattern.length(); int textEnd = text.length(); boolean containsEndChar = pattern.endsWith("$"); if (containsEndChar) { patternEnd -= 1; } while ((patternPos < patternEnd) && (textPos < textEnd)) { int wildcardPos = pattern.indexOf('*', patternPos); if (wildcardPos == -1) { wildcardPos = patternEnd; } if (wildcardPos == patternPos) { patternPos += 1; if (patternPos >= patternEnd) { return true; } int patternPieceEnd = pattern.indexOf('*', patternPos); if (patternPieceEnd == -1) { patternPieceEnd = patternEnd; } boolean matched = false; int patternPieceLen = patternPieceEnd - patternPos; while ((textPos + patternPieceLen <= textEnd) && !matched) { matched = true; for (int i = 0; i < patternPieceLen && matched; i++) { if (text.charAt(textPos + i) != pattern.charAt(patternPos + i)) { matched = false; } } if (!matched) { textPos += 1; } } if (!matched) { return false; } } else { while ((patternPos < wildcardPos) && (textPos < textEnd)) { if (text.charAt(textPos++) != pattern.charAt(patternPos++)) { return false; } } } } while ((patternPos < patternEnd) && (pattern.charAt(patternPos) == '*')) { patternPos += 1; } return (patternPos == patternEnd) && ((textPos == textEnd) || !containsEndChar); } }
true
92deeef8fdc3866004079d99f2301bb78bc7d463
Java
tsuzcx/qq_apk
/com.tencent.mm/classes.jar/com/tencent/mm/plugin/welab/e/b.java
UTF-8
4,070
1.53125
2
[]
no_license
package com.tencent.mm.plugin.welab.e; import android.content.SharedPreferences; import android.text.TextUtils; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.mm.aa.c; import com.tencent.mm.kernel.f; import com.tencent.mm.kernel.h; import com.tencent.mm.sdk.platformtools.Log; import com.tencent.mm.sdk.platformtools.MMApplicationContext; import com.tencent.mm.sdk.platformtools.Util; import com.tencent.mm.storage.aq; import com.tencent.mm.storage.at.a; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public final class b { private static final b Xzq; public Map<String, Integer> XyG; public String tag; static { AppMethodBeat.i(146307); Xzq = new b(); AppMethodBeat.o(146307); } private b() { AppMethodBeat.i(146299); this.XyG = new HashMap(); this.tag = ""; iDP(); AppMethodBeat.o(146299); } private boolean bnx(String paramString) { AppMethodBeat.i(146302); if ((this.XyG.containsKey(paramString)) && (((Integer)this.XyG.get(paramString)).intValue() == 1)) { AppMethodBeat.o(146302); return true; } AppMethodBeat.o(146302); return false; } public static b iDO() { return Xzq; } private void iDP() { AppMethodBeat.i(146300); this.tag = ((String)h.baE().ban().get(at.a.acRL, null)); Log.i("WeLabRedPointMgr", "load red tag " + this.tag); if (!TextUtils.isEmpty(this.tag)) { String[] arrayOfString = this.tag.split("&"); int j = arrayOfString.length; int i = 0; while (i < j) { Object localObject = arrayOfString[i]; if (!TextUtils.isEmpty((CharSequence)localObject)) { localObject = ((String)localObject).split("="); if ((localObject != null) && (localObject.length == 2)) { this.XyG.put(localObject[0], Integer.valueOf(Util.safeParseInt(localObject[1]))); } } i += 1; } } AppMethodBeat.o(146300); } public static void iDQ() { AppMethodBeat.i(146304); Object localObject = com.tencent.mm.plugin.welab.b.iDA().iDB(); if ((localObject != null) && (((List)localObject).isEmpty())) {} localObject = ((List)localObject).iterator(); com.tencent.mm.plugin.welab.d.a.a locala; do { if (!((Iterator)localObject).hasNext()) { break; } locala = (com.tencent.mm.plugin.welab.d.a.a)((Iterator)localObject).next(); } while ((locala == null) || (!Xzq.e(locala))); for (int i = 0;; i = 1) { if (i != 0) { c.aYo().dX(266267, 266241); } AppMethodBeat.o(146304); return; } } public static boolean iDR() { AppMethodBeat.i(146305); boolean bool = c.aYo().dW(266267, 266241); AppMethodBeat.o(146305); return bool; } public static boolean iDS() { AppMethodBeat.i(146306); boolean bool = MMApplicationContext.getDefaultPreference().getBoolean("key_has_enter_welab", false); AppMethodBeat.o(146306); return bool; } public final boolean e(com.tencent.mm.plugin.welab.d.a.a parama) { AppMethodBeat.i(146301); if ((parama.field_RedPoint != 1) || (parama.isOffline())) { AppMethodBeat.o(146301); return false; } if (bnx(parama.field_LabsAppId)) { AppMethodBeat.o(146301); return false; } AppMethodBeat.o(146301); return true; } public final void f(com.tencent.mm.plugin.welab.d.a.a parama) { AppMethodBeat.i(146303); if ((parama.field_RedPoint == 1) && (!bnx(parama.field_LabsAppId)) && (parama.MX())) { c.aYo().R(266267, true); } AppMethodBeat.o(146303); } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes4.jar * Qualified Name: com.tencent.mm.plugin.welab.e.b * JD-Core Version: 0.7.0.1 */
true
3a2ff69023d43801c54decca7a6ae3a72a92385e
Java
kerrywang/User-Interface-design
/CS160project1/app/src/main/java/com/example/kaiyuewang/cs160project1/WorkOutConversion.java
UTF-8
2,227
2.53125
3
[]
no_license
package com.example.kaiyuewang.cs160project1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.HashMap; public class WorkOutConversion extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setTitle("Personal Trainer"); setContentView(R.layout.activity_work_out_conversion); Intent intent = getIntent(); Bundle b = intent.getExtras(); double targetcalburn = b.getDouble("targetCal"); TextView output = (TextView)findViewById(R.id.outputTargetWorkout); //create conversion data base HashMap<String,Double> repPerCal = new HashMap<>(); HashMap<String,Double> MinPerCal = new HashMap<>(); repPerCal.put("Push Up",3.5); repPerCal.put("Sit Up",2.0); repPerCal.put("Squats",2.25); repPerCal.put("Pullup",1.0); MinPerCal.put("Cycling",0.12); MinPerCal.put("Walking",0.2); MinPerCal.put("Swimming",0.13); MinPerCal.put("Stair-Climbing",0.15); MinPerCal.put("Plank",0.25); MinPerCal.put("Leg-lift",0.25); MinPerCal.put("Jumping Jacks",0.1); MinPerCal.put("Jogging",0.12); //https://darkwebnews.com/deep-web-links/ String tablestring = ""; //traverse repPerCall for(String key:repPerCal.keySet()){ double val = repPerCal.get(key); double convert = targetcalburn*val; tablestring =tablestring + "You need to do: " + Long.toString(Math.round(convert)) + " Rep " + key +"\n"; } for(String key:MinPerCal.keySet()){ double val = MinPerCal.get(key); double convert = targetcalburn*val; String result = String.format("%.2f", convert); tablestring =tablestring + "You need to do: " + result + " Min " + key +"\n"; } output.setText(tablestring); } public void backtoFront(View view){ Intent intent = new Intent(this,MainActivity.class); startActivity(intent); } }
true
94311563f89bcf1bbec63c7fcb57262413fb945b
Java
rsx491/NARMS
/NARMSNetbeans/NARMSServer/narms-web/src/main/java/com/aurotech/db/dao/NarmsCenterDAO.java
UTF-8
4,376
2.28125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.aurotech.db.dao; import com.aurotech.controller.rest.NarmsSampleController; import java.util.List; import javax.annotation.PreDestroy; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.springframework.stereotype.Component; import com.aurotech.db.entities.NarmsCenter; import com.aurotech.init.AppContextListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Muazzam */ @Component public class NarmsCenterDAO { private static final Logger logger = LoggerFactory.getLogger(NarmsCenterDAO.class); private EntityManager em; public <T> void persist(T t) { em = AppContextListener.getEmf().createEntityManager(); em.getTransaction().begin(); em.persist(t); em.getTransaction().commit(); if(em != null && em.isOpen()){ em.close(); } } public <T> T update(T t) { em = AppContextListener.getEmf().createEntityManager(); em.getTransaction().begin(); t = em.merge(t); em.getTransaction().commit(); if(em != null && em.isOpen()){ em.close(); } return t; } public void deleteByID(Long recordID) { em = AppContextListener.getEmf().createEntityManager(); NarmsCenter record = em.find(NarmsCenter.class, recordID); if( record != null) { em.getTransaction().begin(); em.remove(record); em.getTransaction().commit(); } } public NarmsCenter getCenterById(Long id) { em = AppContextListener.getEmf().createEntityManager(); em.getTransaction().begin(); NarmsCenter narmsCenter = em.find(NarmsCenter.class, id); em.getTransaction().commit(); if(em != null && em.isOpen()){ em.close(); } return narmsCenter; } public NarmsCenter getCenterWithState(String narmsState) { em = AppContextListener.getEmf().createEntityManager(); em.getTransaction().begin(); Query query = em.createNamedQuery( "findCenterByState").setParameter("centerState", narmsState); em.getTransaction().commit(); NarmsCenter narmsCenter = null; try { narmsCenter = (NarmsCenter)query.getSingleResult(); } catch(NoResultException e){ } if(em != null && em.isOpen()){ em.close(); } return narmsCenter; } public NarmsCenter getCenterByID(String centerid) { em = AppContextListener.getEmf().createEntityManager(); em.getTransaction().begin(); Query query = em.createNamedQuery( "getcenterbymonthandid"); //query.setParameter("monthVal", monthVal ); query.setParameter("center_id", Long.parseLong(centerid) ); em.getTransaction().commit(); NarmsCenter narmsCenter = null; try { narmsCenter = (NarmsCenter)query.getSingleResult(); /* List<NarmsCenter> result = query.getResultList(); for(NarmsCenter center : result){ logger.debug("centercound := " + center.getCenterName()); }*/ } catch(NoResultException e){ } if(em != null && em.isOpen()){ em.close(); } return narmsCenter; } public List<NarmsCenter> getAllCenters() { List<NarmsCenter> result = null; em = AppContextListener.getEmf().createEntityManager(); em.getTransaction().begin(); TypedQuery<NarmsCenter> query = em.createNamedQuery( "findAllCenters", NarmsCenter.class); em.getTransaction().commit(); try { result = query.getResultList(); } catch(NoResultException e){ } if(em != null && em.isOpen()){ em.close(); } return result; } @PreDestroy public void beforeGoing() { if(em != null && em.isOpen()){ em.close(); } } }
true
e5502caf07010d199ba5053609204437e37a0d9f
Java
ohdoking/lazyTripperRemakeAndroid
/app/src/main/java/com/yapp/lazitripper/views/PlaceInfoItem.java
UTF-8
1,647
2.078125
2
[]
no_license
package com.yapp.lazitripper.views; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.yapp.lazitripper.R; /** * Created by clock on 2017-02-26. */ public class PlaceInfoItem extends LinearLayout { TextView title, location, tel; ImageView thumbnail; TextView number; public PlaceInfoItem(Context context) { super(context); init(context); } public PlaceInfoItem(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context){ LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.place_info_item,this,true); thumbnail = (ImageView) findViewById(R.id.thumbnail); title = (TextView) findViewById(R.id.place_title); location = (TextView) findViewById(R.id.place_location); tel = (TextView) findViewById(R.id.place_tel); number = (TextView) findViewById(R.id.number); } public void setImage(String url){ Glide.with(getContext()).load(url).into(this.thumbnail); } public void setTitle(String name){ this.title.setText(name); } public void setLocatioin(String lat){ this.location.setText(lat); } public void setel(String lng){ this.tel.setText(lng); } public void setNumber(String t){ this.number.setText(t); } }
true
7229f9636418bf846bd408fa2ad32ed0e10499eb
Java
vanche1212/auth-permission
/auth-spring-boot-autoconfigure/src/main/java/com/zrtg/auth/annotation/EnableAuth.java
UTF-8
341
1.726563
2
[]
no_license
//package com.zrtg.auth.annotation; // //import com.zrtg.auth.AuthAutoConfiguration; //import org.springframework.context.annotation.Import; // //import java.lang.annotation.*; // // //@Retention(RetentionPolicy.RUNTIME) //@Target(ElementType.TYPE) //@Documented //@Import({AuthAutoConfiguration.class}) //public @interface EnableAuth { //}
true
1897e12c8728cf4183a5ea29a40cdd6cdcef3c3d
Java
YunaiV/netty
/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java
UTF-8
15,430
2
2
[ "Apache-2.0", "CC-PDDC", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "LGPL-2.1-only" ]
permissive
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.http; import io.netty.handler.codec.CharSequenceValueConverter; import io.netty.handler.codec.DateFormatter; import io.netty.handler.codec.DefaultHeaders; import io.netty.handler.codec.DefaultHeaders.NameValidator; import io.netty.handler.codec.DefaultHeadersImpl; import io.netty.handler.codec.HeadersUtils; import io.netty.handler.codec.ValueConverter; import io.netty.util.AsciiString; import io.netty.util.ByteProcessor; import io.netty.util.internal.PlatformDependent; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER; import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER; /** * Default implementation of {@link HttpHeaders}. */ public class DefaultHttpHeaders extends HttpHeaders { private static final int HIGHEST_INVALID_VALUE_CHAR_MASK = ~15; private static final ByteProcessor HEADER_NAME_VALIDATOR = new ByteProcessor() { @Override public boolean process(byte value) throws Exception { validateHeaderNameElement(value); return true; } }; static final NameValidator<CharSequence> HttpNameValidator = new NameValidator<CharSequence>() { @Override public void validateName(CharSequence name) { if (name == null || name.length() == 0) { throw new IllegalArgumentException("empty headers are not allowed [" + name + "]"); } if (name instanceof AsciiString) { try { ((AsciiString) name).forEachByte(HEADER_NAME_VALIDATOR); } catch (Exception e) { PlatformDependent.throwException(e); } } else { // Go through each character in the name for (int index = 0; index < name.length(); ++index) { validateHeaderNameElement(name.charAt(index)); } } } }; private final DefaultHeaders<CharSequence, CharSequence, ?> headers; public DefaultHttpHeaders() { this(true); } public DefaultHttpHeaders(boolean validate) { this(validate, nameValidator(validate)); } protected DefaultHttpHeaders(boolean validate, NameValidator<CharSequence> nameValidator) { this(new DefaultHeadersImpl<CharSequence, CharSequence>(CASE_INSENSITIVE_HASHER, valueConverter(validate), nameValidator)); } protected DefaultHttpHeaders(DefaultHeaders<CharSequence, CharSequence, ?> headers) { this.headers = headers; } @Override public HttpHeaders add(HttpHeaders headers) { if (headers instanceof DefaultHttpHeaders) { this.headers.add(((DefaultHttpHeaders) headers).headers); return this; } else { return super.add(headers); } } @Override public HttpHeaders set(HttpHeaders headers) { if (headers instanceof DefaultHttpHeaders) { this.headers.set(((DefaultHttpHeaders) headers).headers); return this; } else { return super.set(headers); } } @Override public HttpHeaders add(String name, Object value) { headers.addObject(name, value); return this; } @Override public HttpHeaders add(CharSequence name, Object value) { headers.addObject(name, value); return this; } @Override public HttpHeaders add(String name, Iterable<?> values) { headers.addObject(name, values); return this; } @Override public HttpHeaders add(CharSequence name, Iterable<?> values) { headers.addObject(name, values); return this; } @Override public HttpHeaders addInt(CharSequence name, int value) { headers.addInt(name, value); return this; } @Override public HttpHeaders addShort(CharSequence name, short value) { headers.addShort(name, value); return this; } @Override public HttpHeaders remove(String name) { headers.remove(name); return this; } @Override public HttpHeaders remove(CharSequence name) { headers.remove(name); return this; } @Override public HttpHeaders set(String name, Object value) { headers.setObject(name, value); return this; } @Override public HttpHeaders set(CharSequence name, Object value) { headers.setObject(name, value); return this; } @Override public HttpHeaders set(String name, Iterable<?> values) { headers.setObject(name, values); return this; } @Override public HttpHeaders set(CharSequence name, Iterable<?> values) { headers.setObject(name, values); return this; } @Override public HttpHeaders setInt(CharSequence name, int value) { headers.setInt(name, value); return this; } @Override public HttpHeaders setShort(CharSequence name, short value) { headers.setShort(name, value); return this; } @Override public HttpHeaders clear() { headers.clear(); return this; } @Override public String get(String name) { return get((CharSequence) name); } @Override public String get(CharSequence name) { return HeadersUtils.getAsString(headers, name); } @Override public Integer getInt(CharSequence name) { return headers.getInt(name); } @Override public int getInt(CharSequence name, int defaultValue) { return headers.getInt(name, defaultValue); } @Override public Short getShort(CharSequence name) { return headers.getShort(name); } @Override public short getShort(CharSequence name, short defaultValue) { return headers.getShort(name, defaultValue); } @Override public Long getTimeMillis(CharSequence name) { return headers.getTimeMillis(name); } @Override public long getTimeMillis(CharSequence name, long defaultValue) { return headers.getTimeMillis(name, defaultValue); } @Override public List<String> getAll(String name) { return getAll((CharSequence) name); } @Override public List<String> getAll(CharSequence name) { return HeadersUtils.getAllAsString(headers, name); } @Override public List<Entry<String, String>> entries() { if (isEmpty()) { return Collections.emptyList(); } List<Entry<String, String>> entriesConverted = new ArrayList<Entry<String, String>>( headers.size()); for (Entry<String, String> entry : this) { entriesConverted.add(entry); } return entriesConverted; } @Deprecated @Override public Iterator<Map.Entry<String, String>> iterator() { return HeadersUtils.iteratorAsString(headers); } @Override public Iterator<Entry<CharSequence, CharSequence>> iteratorCharSequence() { return headers.iterator(); } @Override public Iterator<String> valueStringIterator(CharSequence name) { final Iterator<CharSequence> itr = valueCharSequenceIterator(name); return new Iterator<String>() { @Override public boolean hasNext() { return itr.hasNext(); } @Override public String next() { return itr.next().toString(); } @Override public void remove() { itr.remove(); } }; } @Override public Iterator<CharSequence> valueCharSequenceIterator(CharSequence name) { return headers.valueIterator(name); } @Override public boolean contains(String name) { return contains((CharSequence) name); } @Override public boolean contains(CharSequence name) { return headers.contains(name); } @Override public boolean isEmpty() { return headers.isEmpty(); } @Override public int size() { return headers.size(); } @Override public boolean contains(String name, String value, boolean ignoreCase) { return contains((CharSequence) name, (CharSequence) value, ignoreCase); } @Override public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) { return headers.contains(name, value, ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER); } @Override public Set<String> names() { return HeadersUtils.namesAsString(headers); } @Override public boolean equals(Object o) { return o instanceof DefaultHttpHeaders && headers.equals(((DefaultHttpHeaders) o).headers, CASE_SENSITIVE_HASHER); } @Override public int hashCode() { return headers.hashCode(CASE_SENSITIVE_HASHER); } @Override public HttpHeaders copy() { return new DefaultHttpHeaders(headers.copy()); } private static void validateHeaderNameElement(byte value) { switch (value) { case 0x00: case '\t': case '\n': case 0x0b: case '\f': case '\r': case ' ': case ',': case ':': case ';': case '=': throw new IllegalArgumentException( "a header name cannot contain the following prohibited characters: =,;: \\t\\r\\n\\v\\f: " + value); default: // Check to see if the character is not an ASCII character, or invalid if (value < 0) { throw new IllegalArgumentException("a header name cannot contain non-ASCII character: " + value); } } } private static void validateHeaderNameElement(char value) { switch (value) { case 0x00: case '\t': case '\n': case 0x0b: case '\f': case '\r': case ' ': case ',': case ':': case ';': case '=': throw new IllegalArgumentException( "a header name cannot contain the following prohibited characters: =,;: \\t\\r\\n\\v\\f: " + value); default: // Check to see if the character is not an ASCII character, or invalid if (value > 127) { throw new IllegalArgumentException("a header name cannot contain non-ASCII character: " + value); } } } static ValueConverter<CharSequence> valueConverter(boolean validate) { return validate ? HeaderValueConverterAndValidator.INSTANCE : HeaderValueConverter.INSTANCE; } @SuppressWarnings("unchecked") static NameValidator<CharSequence> nameValidator(boolean validate) { return validate ? HttpNameValidator : NameValidator.NOT_NULL; } private static class HeaderValueConverter extends CharSequenceValueConverter { static final HeaderValueConverter INSTANCE = new HeaderValueConverter(); @Override public CharSequence convertObject(Object value) { if (value instanceof CharSequence) { return (CharSequence) value; } if (value instanceof Date) { return DateFormatter.format((Date) value); } if (value instanceof Calendar) { return DateFormatter.format(((Calendar) value).getTime()); } return value.toString(); } } private static final class HeaderValueConverterAndValidator extends HeaderValueConverter { static final HeaderValueConverterAndValidator INSTANCE = new HeaderValueConverterAndValidator(); @Override public CharSequence convertObject(Object value) { CharSequence seq = super.convertObject(value); int state = 0; // Start looping through each of the character for (int index = 0; index < seq.length(); index++) { state = validateValueChar(seq, state, seq.charAt(index)); } if (state != 0) { throw new IllegalArgumentException("a header value must not end with '\\r' or '\\n':" + seq); } return seq; } private static int validateValueChar(CharSequence seq, int state, char character) { /* * State: * 0: Previous character was neither CR nor LF * 1: The previous character was CR * 2: The previous character was LF */ if ((character & HIGHEST_INVALID_VALUE_CHAR_MASK) == 0) { // Check the absolutely prohibited characters. switch (character) { case 0x0: // NULL throw new IllegalArgumentException("a header value contains a prohibited character '\0': " + seq); case 0x0b: // Vertical tab throw new IllegalArgumentException("a header value contains a prohibited character '\\v': " + seq); case '\f': throw new IllegalArgumentException("a header value contains a prohibited character '\\f': " + seq); } } // Check the CRLF (HT | SP) pattern switch (state) { case 0: switch (character) { case '\r': return 1; case '\n': return 2; } break; case 1: switch (character) { case '\n': return 2; default: throw new IllegalArgumentException("only '\\n' is allowed after '\\r': " + seq); } case 2: switch (character) { case '\t': case ' ': return 0; default: throw new IllegalArgumentException("only ' ' and '\\t' are allowed after '\\n': " + seq); } } return state; } } }
true
909d996bc41339fc92d49fa6464a56a10e78a018
Java
dragon9968/LongNguyen
/src/Utility/Constant.java
UTF-8
1,185
1.8125
2
[]
no_license
package Utility; public class Constant { public static final String exePath = "C:\\Automation Code\\driver\\chromedriver_win32\\chromedriver.exe"; public static final String URL = "https://www.donortiles.com/"; public static final String URL1 = "http://store.demoqa.com/"; public static final String Email = "longnguyen@gmail.com"; public static final String Username = "longnguyen"; public static final String Password ="Long1234@"; public static final int Col_TestCaseName = 0; public static final int Col_UserName =1 ; public static final int Col_Password = 2; public static final int Col_Browser = 3; public static final String Path_TestData = "E:\\WORK\\Automation Code\\SalesforceBAU\\src\\testData\\"; public static final String Path_ScreenShot = "C:\\Users\\longnguyen\\git\\repository\\SalesforceBAU\\src\\Screenshots\\"; public static final String File_TestData = "TestData.xlsx"; public static final String expectedMessage = "You've entered your email/password incorrectly. Please try again."; public static final String expectedMessage1 = "This field is required."; }
true
b4d80955fae78e685844201aa090eb3d5bcaefcc
Java
ChristianR007/practica1_G11
/Generallnterface/src/main/java/com/mycompany/session/local/PagoFacadeLocal.java
UTF-8
768
2.140625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.session.local; import javax.ejb.Local; import com.mycompany.entity.Pago; import java.util.List; /** * * @author Christian */ @Local public interface PagoFacadeLocal { Pago find(Object id); void create(Pago pago); void edit(Pago pago); void remove(Pago pago); long pago3(List<Pago> pagos); double pago2(double pago); double pago1(double cantidad); public double pago4(int num1, int num2, int num3); void pago5(double n,Pago pago); public void insertar(Pago pago) throws Exception; }
true
aab0164c16707e24cd5f24c4701cdd2d8b4b8875
Java
vloxomire/Masa_Corporal
/app/src/main/java/com/example/masa_corporal/Dao_BasedeDatos/SqlLite_masaCorporal.java
UTF-8
1,917
2.453125
2
[]
no_license
package com.example.masa_corporal.Dao_BasedeDatos; import android.content.ContentValues; import android.content.Context; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.Nullable; import com.example.masa_corporal.Models_getter_y_setters.MasaCorporalModels; public class SqlLite_masaCorporal extends SQLiteOpenHelper { private static final String DBNAME="MasaCorporal"; private static final Integer DBVERSION=1; private Context contexto; private SQLiteDatabase conectarse; public SqlLite_masaCorporal(@Nullable Context context) { super(context, DBNAME, null, DBVERSION); this.contexto = contexto; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String query="CREATE TABLE `MasaCorporal` ( `Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `Masa Corporal` INTEGER NOT NULL, `fecha y hora` INTEGER NOT NULL )"; sqLiteDatabase.execSQL(query); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { String query="CREATE TABLE `MasaCorporal` ( `Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `Masa Corporal` INTEGER NOT NULL, `fecha y hora` INTEGER NOT NULL )"; sqLiteDatabase.execSQL(query); } private void conectar(){ conectarse = getWritableDatabase(); } private void desconectarse(){ conectarse.close(); } public void guardarMasaCorporalSin(MasaCorporalModels masaObjeto){ //falta el model MasaCorporal this.conectar(); //metodo creado ContentValues fila = new ContentValues(); fila.put("Masa Corporal",masaObjeto.getMasaCorporal()); //es parte del models conectarse.insert("MasaCorporal",null,fila); this.desconectarse(); } }
true
692de5fac3799c663edf74904240e0960a844197
Java
equinor/neqsimweb
/src/neqsimserver2/Thermo/PVTdata.java
UTF-8
12,301
1.578125
2
[ "Apache-2.0" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package neqsimserver2.Thermo; import neqsim.PVTsimulation.util.parameterfitting.SaturationPressureFunction; import com.sun.data.provider.RowKey; import com.sun.data.provider.impl.CachedRowSetDataProvider; import com.sun.rave.web.ui.appbase.AbstractPageBean; import com.sun.rave.web.ui.component.StaticText; import com.sun.rave.web.ui.component.TextField; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import javax.faces.FacesException; import neqsimserver2.ApplicationBean1; import neqsimserver2.SessionBean1; import neqsimserver2.GasQuality.GasQualitySessionBean; import neqsim.statistics.parameterFitting.SampleSet; import neqsim.statistics.parameterFitting.SampleValue; import neqsim.statistics.parameterFitting.nonLinearParameterFitting.LevenbergMarquardt; /** * <p>Page bean that corresponds to a similarly named JSP page. This * class contains component definitions (and initialization code) for * all components that you have defined on this page, as well as * lifecycle methods and event handlers where you may add behavior * to respond to incoming events.</p> * * @version PVTdata.java * @version Created on 27.feb.2013, 22:07:40 * @author ESOL */ public class PVTdata extends AbstractPageBean { // <editor-fold defaultstate="collapsed" desc="Managed Component Definition"> /** * <p>Automatically managed component initialization. <strong>WARNING:</strong> * This method is automatically generated, so any user-specified code inserted * here is subject to being replaced.</p> */ private void _init() throws Exception { pvt_satptDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.pvt_satptRowSet}")); pvt_satptDataProvider1.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.pvt_satptRowSet}")); } private CachedRowSetDataProvider pvt_satptDataProvider = new CachedRowSetDataProvider(); public CachedRowSetDataProvider getPvt_satptDataProvider() { return pvt_satptDataProvider; } public void setPvt_satptDataProvider(CachedRowSetDataProvider crsdp) { this.pvt_satptDataProvider = crsdp; } private CachedRowSetDataProvider pvt_satptDataProvider1 = new CachedRowSetDataProvider(); public CachedRowSetDataProvider getPvt_satptDataProvider1() { return pvt_satptDataProvider1; } public void setPvt_satptDataProvider1(CachedRowSetDataProvider crsdp) { this.pvt_satptDataProvider1 = crsdp; } private TextField descriptionTextField = new TextField(); public TextField getDescriptionTextField() { return descriptionTextField; } public void setDescriptionTextField(TextField tf) { this.descriptionTextField = tf; } private TextField temperatureTextField = new TextField(); public TextField getTemperatureTextField() { return temperatureTextField; } public void setTemperatureTextField(TextField tf) { this.temperatureTextField = tf; } private TextField pressureTextField = new TextField(); public TextField getPressureTextField() { return pressureTextField; } public void setPressureTextField(TextField tf) { this.pressureTextField = tf; } private TextField weigthTextField = new TextField(); public TextField getWeigthTextField() { return weigthTextField; } public void setWeigthTextField(TextField tf) { this.weigthTextField = tf; } private StaticText statusTextField = new StaticText(); public StaticText getStatusTextField() { return statusTextField; } public void setStatusTextField(StaticText st) { this.statusTextField = st; } private TextField molarMassTextFiled = new TextField(); public TextField getMolarMassTextFiled() { return molarMassTextFiled; } public void setMolarMassTextFiled(TextField tf) { this.molarMassTextFiled = tf; } // </editor-fold> /** * <p>Construct a new Page bean instance.</p> */ public PVTdata() { } /** * <p>Callback method that is called whenever a page is navigated to, * either directly via a URL, or indirectly via page navigation. * Customize this method to acquire resources that will be needed * for event handlers and lifecycle methods, whether or not this * page is performing post back processing.</p> * * <p>Note that, if the current request is a postback, the property * values of the components do <strong>not</strong> represent any * values submitted with this request. Instead, they represent the * property values that were saved for this view when it was rendered.</p> */ @Override public void init() { // Perform initializations inherited from our superclass super.init(); // Perform application initialization that must complete // *before* managed components are initialized // TODO - add your own initialiation code here // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization"> // Initialize automatically managed components // *Note* - this logic should NOT be modified try { _init(); } catch (Exception e) { log("PVTdata Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e : new FacesException(e); } // </editor-fold> // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here try { getSessionBean1().getPvt_satptRowSet().setObject(1, Integer.toString(getSessionBean1().getActiveFluidID())); pvt_satptDataProvider.refresh(); pvt_satptDataProvider1.refresh(); log("ative fluid ID2 " + getSessionBean1().getActiveFluidID()); } catch (Exception e) { e.printStackTrace(); } } /** * <p>Callback method that is called after the component tree has been * restored, but before any event processing takes place. This method * will <strong>only</strong> be called on a postback request that * is processing a form submit. Customize this method to allocate * resources that will be required in your event handlers.</p> */ @Override public void preprocess() { } /** * <p>Callback method that is called just before rendering takes place. * This method will <strong>only</strong> be called for the page that * will actually be rendered (and not, for example, on a page that * handled a postback and then navigated to a different page). Customize * this method to allocate resources that will be required for rendering * this page.</p> */ @Override public void prerender() { } /** * <p>Callback method that is called after rendering is completed for * this request, if <code>init()</code> was called (regardless of whether * or not this was the page that was actually rendered). Customize this * method to release resources acquired in the <code>init()</code>, * <code>preprocess()</code>, or <code>prerender()</code> methods (or * acquired during execution of an event handler).</p> */ @Override public void destroy() { pvt_satptDataProvider.close(); pvt_satptDataProvider1.close(); } /** * <p>Return a reference to the scoped data bean.</p> * * @return reference to the scoped data bean */ protected ApplicationBean1 getApplicationBean1() { return (ApplicationBean1) getBean("ApplicationBean1"); } /** * <p>Return a reference to the scoped data bean.</p> * * @return reference to the scoped data bean */ protected ThermoSessionBean getThermo$ThermoSessionBean() { return (ThermoSessionBean) getBean("Thermo$ThermoSessionBean"); } /** * <p>Return a reference to the scoped data bean.</p> * * @return reference to the scoped data bean */ protected SessionBean1 getSessionBean1() { return (SessionBean1) getBean("SessionBean1"); } /** * <p>Return a reference to the scoped data bean.</p> * * @return reference to the scoped data bean */ protected GasQualitySessionBean getGasQuality$GasQualitySessionBean() { return (GasQualitySessionBean) getBean("GasQuality$GasQualitySessionBean"); } public String button1_action() { pvt_satptDataProvider1.cursorLast(); System.out.println("3"); RowKey rowKey = pvt_satptDataProvider1.appendRow(); System.out.println("4"); pvt_satptDataProvider1.setValue("pvt_satpt.TEXT", rowKey, descriptionTextField.getValue()); pvt_satptDataProvider1.setValue("pvt_satpt.Pressure", rowKey, pressureTextField.getValue()); pvt_satptDataProvider1.setValue("pvt_satpt.Temperature", rowKey, temperatureTextField.getValue()); pvt_satptDataProvider1.setValue("pvt_satpt.Weight", rowKey, weigthTextField.getValue()); pvt_satptDataProvider1.setValue("pvt_satpt.FLUID_ID", rowKey, Integer.toString(getSessionBean1().getActiveFluidID())); pvt_satptDataProvider1.commitChanges(); pvt_satptDataProvider1.refresh(); return null; } public String deleteButton_action() { RowKey rowKey2 = pvt_satptDataProvider1.getCursorRow(); pvt_satptDataProvider1.removeRow(rowKey2); pvt_satptDataProvider1.commitChanges(); pvt_satptDataProvider1.refresh(); return null; } public String button2_action() { // TODO: Process the button click action. Return value is a navigation // case name where null will return to the same page. statusTextField.setValue("tuning running..."); getThermo$ThermoSessionBean().getThermoSystem().setHeavyTBPfractionAsPlusFraction(); ArrayList sampleList = new ArrayList(); if (!pvt_satptDataProvider1.cursorFirst()) { statusTextField.setValue("missing input PVTdata"); return null; } getThermo$ThermoSessionBean().getThermoSystem().setMultiPhaseCheck(false); do { double pressure1 = Double.parseDouble(pvt_satptDataProvider1.getValue("pvt_satpt.Pressure").toString()); double temperature1 = 273.15 + Double.parseDouble(pvt_satptDataProvider1.getValue("pvt_satpt.Temperature").toString()); double sample1[] = {temperature1}; double satPres = pressure1; double standardDeviation1[] = {1.5}; SampleValue sample = new SampleValue(satPres, satPres / 100.0, sample1, standardDeviation1); SaturationPressureFunction function = new SaturationPressureFunction(); sample.setFunction(function); double molarmass = Double.parseDouble(molarMassTextFiled.getValue().toString()); double guess[] = {molarmass / 1000.0}; function.setInitialGuess(guess); sample.setThermodynamicSystem(getThermo$ThermoSessionBean().getThermoSystem()); sampleList.add(sample); } while (pvt_satptDataProvider1.cursorNext()); SampleSet sampleSet = new SampleSet(sampleList); LevenbergMarquardt optim = new LevenbergMarquardt(); optim.setMaxNumberOfIterations(10); optim.setSampleSet(sampleSet); optim.solve(); java.text.DecimalFormat decFormat = new java.text.DecimalFormat(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); decFormat.setDecimalFormatSymbols(symbols); decFormat.setMaximumFractionDigits(3); molarMassTextFiled.setValue(decFormat.format(optim.getSample(0).getFunction().getFittingParams(0) * 1000.0)); getThermo$ThermoSessionBean().setThermoSystem(optim.getSample(0).getFunction().getSystem()); getThermo$ThermoSessionBean().getThermoSystem().setMultiPhaseCheck(true); return null; } }
true
3382ca0de397d197d802ca410b264c5780d56472
Java
igit-cn/jmqtt
/jmqtt-broker/src/main/java/org/jmqtt/broker/processor/protocol/DisconnectProcessor.java
UTF-8
3,024
2.109375
2
[ "Apache-2.0" ]
permissive
package org.jmqtt.broker.processor.protocol; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.MqttMessage; import org.jmqtt.broker.BrokerController; import org.jmqtt.broker.common.log.JmqttLogger; import org.jmqtt.broker.common.log.LogUtil; import org.jmqtt.broker.common.model.Subscription; import org.jmqtt.broker.processor.RequestProcessor; import org.jmqtt.broker.remoting.session.ClientSession; import org.jmqtt.broker.remoting.session.ConnectManager; import org.jmqtt.broker.remoting.util.NettyUtil; import org.jmqtt.broker.store.MessageStore; import org.jmqtt.broker.store.SessionState; import org.jmqtt.broker.store.SessionStore; import org.jmqtt.broker.subscribe.SubscriptionMatcher; import org.slf4j.Logger; import java.util.Set; /** * 客户端主动发起断开连接:正常断连 * TODO mqtt5实现 */ public class DisconnectProcessor implements RequestProcessor { private static final Logger log = JmqttLogger.clientTraceLog; private SessionStore sessionStore; private MessageStore messageStore; private SubscriptionMatcher subscriptionMatcher; public DisconnectProcessor(BrokerController brokerController) { this.sessionStore = brokerController.getSessionStore(); this.messageStore = brokerController.getMessageStore(); this.subscriptionMatcher = brokerController.getSubscriptionMatcher(); } @Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { String clientId = NettyUtil.getClientId(ctx.channel()); if (!ConnectManager.getInstance().containClient(clientId)) { LogUtil.warn(log,"[DISCONNECT] -> {} hasn't connect before", clientId); } ClientSession clientSession = ConnectManager.getInstance().getClient(clientId); // 1. 清理会话 或 重新设置该客户端会话状态 clearSession(clientSession); // 3. 清理will消息 clearWillMessage(clientSession.getClientId()); // 4. 移除本节点上的连接 ConnectManager.getInstance().removeClient(clientId); ctx.close(); } private void clearSession(ClientSession clientSession) { if (clientSession.isCleanStart()) { Set<Subscription> subscriptions = sessionStore.getSubscriptions(clientSession.getClientId()); for (Subscription subscription : subscriptions) { this.subscriptionMatcher.unSubscribe(subscription.getTopic(), clientSession.getClientId()); } sessionStore.clearSession(clientSession.getClientId(),false); } else { SessionState sessionState = new SessionState(SessionState.StateEnum.OFFLINE, System.currentTimeMillis()); this.sessionStore.storeSession(clientSession.getClientId(), sessionState); } } private void clearWillMessage(String clientId) { messageStore.clearWillMessage(clientId); } }
true
bf66869f03211daa4ef305139b38f396358f8dca
Java
gdannyliao/algorithms
/src/com/ggdsn/algorithms/tree/Tree.java
UTF-8
1,103
3.609375
4
[]
no_license
package com.ggdsn.algorithms.tree; public class Tree<T extends Comparable> { T value; private Tree<T> right; private Tree<T> left; public Tree(T value) { this.value = value; } public void add(Tree<T> node) { if (node == null) { return; } int result = node.value.compareTo(value); if (result > 0) { if (right == null) right = node; else right.add(node); } else if (result < 0) { if (left == null) left = node; else left.add(node); } } public T getValue() { return value; } @Override public String toString() { return value.toString(); } public Tree<T> getRight() { return right; } public Tree<T> getLeft() { return left; } public boolean hasLeft() { return left != null; } public boolean hasRight() { return right != null; } public void setLeft(Tree<T> left) { this.left = left; } public void setRight(Tree<T> right) { this.right = right; } @Override public boolean equals(Object obj) { if (obj != null) { if (obj instanceof Tree) return value.equals(((Tree<T>) obj).value); } return false; } }
true
79ff900b28665422a88911fb29407adbeb4536cd
Java
dungchv13/day_3_array_function_module2
/src/Gop_mang.java
UTF-8
584
2.4375
2
[]
no_license
public class Gop_mang { public static void main(String[] args) { int[] array1 = {10,4,6,7,8,6,0,0,0,0}; int[] array2 = {10,4,6,7,8,0,0,0,0,0}; Them_phanTu_vaoMang.showArray(noiMang(array1,array2)); } public static int[] noiMang(int[] arr1,int[] arr2){ int[] newArr = new int[arr1.length+arr2.length]; for (int i = 0;i < arr1.length;i++){ newArr[i]=arr1[i]; } for (int i = arr1.length;i < arr1.length+arr2.length;i++){ newArr[i]=arr2[i-arr1.length]; } return newArr; } }
true
0c444427e2a26cad6e299513cc89d31f2d783479
Java
theapache64/livedata_transformation_example
/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/switch_map/SwitchMapActivityModule.java
UTF-8
1,197
1.96875
2
[ "Apache-2.0" ]
permissive
package com.theah64.livedata_transformation_example.ui.activities.switch_map; import android.content.Context; import com.theah64.livedata_transformation_example.data.remote.ApiRepository; import com.theah64.livedata_transformation_example.di.base.ActivityModule; import com.theah64.livedata_transformation_example.ui.adapters.recyclerview_adapters.UsersAdapter; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.ViewModelProviders; import dagger.Module; import dagger.Provides; @Module(includes = {ActivityModule.class}) public class SwitchMapActivityModule { @Provides UsersAdapter provideUsersAdapter(final Context context) { return new UsersAdapter(context); } @Provides SwitchMapViewModelFactory provideSwitchMapTransformationViewModelFactory(ApiRepository apiRepository) { return new SwitchMapViewModelFactory(apiRepository); } @Provides SwitchMapViewModel provideSwitchMapTransformationViewModel(FragmentActivity fragmentActivity, SwitchMapViewModelFactory factory) { return ViewModelProviders.of( fragmentActivity, factory ).get(SwitchMapViewModel.class); } }
true
0e0bee77f3813becdbc1eee6b4bd59892746a52f
Java
rachit2/Assignment
/33.java
UTF-8
554
3.15625
3
[]
no_license
class Cal extends Thread { private int a; private int n; Cal(int a,int n) { this.n=n; this.a=a; } public void run() { result(a,n); } synchronized public void result(int a,int n) { while(a<=n) { System.out.println("Square of"+a+" is:"+a*a); a++; } } } class Sq { public static void main(String ar[]) { Cal c1=new Cal(1,50); Cal c2=new Cal(51,100); c1.start(); try { c1.join(); } catch(Exception e) { System.out.println(e); } c2.start(); } }
true
46033f762a48836605189b6d7aa610ea262124ac
Java
xerZV/jdbc-lock-registry
/src/main/java/com/simitchiyski/lockregistry/core/trade/TradeService.java
UTF-8
532
1.890625
2
[]
no_license
package com.simitchiyski.lockregistry.core.trade; import com.simitchiyski.lockregistry.web.trade.dto.CreateTradeDTO; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.List; public interface TradeService { Trade findOneById(final Long id); List<Trade> findAll(); List<Trade> getQueuedTradesOrderByReleaseDateTime(final int batchSize); Trade create(final @Valid @NotNull CreateTradeDTO tradeDTO); void submit(final Long id); void submitOrQueue(final Long id); }
true
9333999983ec210a47594cabf8b1729f7f150e52
Java
chinmayjoshicj/study
/Temp/src/freshPractice/nthRarestElementInArray.java
UTF-8
854
3.46875
3
[]
no_license
package freshPractice; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class nthRarestElementInArray { public static int nthMostRare(int[] elements, int n) { Map<Integer, Long> map = Arrays.stream(elements).boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting())); Comparator<Map.Entry<Integer, Long>> comp = Comparator.comparing(entry -> entry.getValue()); List<Map.Entry<Integer, Long>> list = new ArrayList<>(map.entrySet()); list.sort(comp); return list.get(n-1).getKey(); } public static void main(String[] args) { // TODO Auto-generated method stub int x = nthMostRare(new int[] { 5, 4, 3, 2, 1, 5, 4, 3, 2, 5, 4, 3, 5, 4, 5 }, 2); System.out.println(x); } }
true
460f58e85fbd1f5f6729e28cd18219163ddb818e
Java
Hideo-Kudze/Yandex-Direct-Broker
/YndexDirectAPI/src/main/java/com/HideoKuzeGits/yndexDirectAPI/wrapClasses/PhrasePriceInfo.java
UTF-8
1,950
2.015625
2
[]
no_license
package com.HideoKuzeGits.yndexDirectAPI.wrapClasses; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @Generated("org.jsonschema2pojo") public class PhrasePriceInfo { @SerializedName("CampaignID") @Expose private Long campaignID; @SerializedName("PhraseID") @Expose private Long phraseID; @SerializedName("Price") @Expose private Double price; @SerializedName("ContextPrice") @Expose private Double contextPrice; @SerializedName("AutoBroker") @Expose private String autoBroker; @SerializedName("AutoBudgetPriority") @Expose private String autoBudgetPriority; @SerializedName("Currency") @Expose private String currency; public Long getCampaignID() { return campaignID; } public void setCampaignID(Long campaignID) { this.campaignID = campaignID; } public Long getPhraseID() { return phraseID; } public void setPhraseID(Long phraseID) { this.phraseID = phraseID; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Double getContextPrice() { return contextPrice; } public void setContextPrice(Double contextPrice) { this.contextPrice = contextPrice; } public String getAutoBroker() { return autoBroker; } public void setAutoBroker(String autoBroker) { this.autoBroker = autoBroker; } public String getAutoBudgetPriority() { return autoBudgetPriority; } public void setAutoBudgetPriority(String autoBudgetPriority) { this.autoBudgetPriority = autoBudgetPriority; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } }
true
5b8efeb644e74809dc5118695a7e6ef3f89130f5
Java
OrangeHarry/Chapter05_ReferenceType
/src/ch05_2_array/Arr외우자.java
UHC
358
2.875
3
[]
no_license
package ch05_2_array; public class Arrܿ { public static void main(String[] args) { int [][] arr = new int[3][4]; /* * Ÿ(ּҰ ) : Ŭ, 迭 * * 迭 ̸ 迭 ּ ̴. !!!ܿ * arrs[0] * arrs[1] * arrs[2] */ } }
true
e377031e9f6a3f9698e0bcabed529bc968ba436f
Java
MADGagnon/ColorPicker_Dialog
/app/src/main/java/com/example/colorpicker/MainActivity.java
UTF-8
1,409
2.640625
3
[]
no_license
package com.example.colorpicker; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button pickButton; View pickedColor; @Override protected void onCreate(Bundle savedInstanceState) { /* CETTE MÉTHODE DEVRA ÊTRE MODIFIÉE */ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ColorPickerDialog dialog = new ColorPickerDialog(this); dialog.setOnColorPickedListener(new MainActivityOnColorPickedListener()); pickButton = findViewById(R.id.button_pick); pickButton.setOnClickListener((View v) -> dialog.show()); } public class MainActivityOnColorPickedListener implements ColorPickerDialog.OnColorPickedListener{ public void onColorPicked(ColorPickerDialog colorPickerDialog, @ColorInt int color){ // on crée un drawable qu'on applique au foreground pour laisser le damier qui témoigne // de la composante alpha en background. ColorDrawable foreground = new ColorDrawable(color); findViewById(R.id.picked_color).setForeground(foreground); } } }
true
d032cec037c63bc88e12b1b4fde7c4586ddac9e2
Java
githubsebkun/pms-testing
/src/test/java/pms/packtpub/automation/testing/RunCukesTest.java
UTF-8
764
1.820313
2
[]
no_license
package pms.packtpub.automation.testing; import cucumber.junit.Cucumber; import org.junit.runner.RunWith; /** * Created by sindh on 18/03/2017. */ @RunWith(Cucumber.class) //@Cucumber.options(features="src\\test\\resources", glue={"src\\test\\java\\pms\\packtpub\\automation\\testing\\Steps"}) //did not work //printing reportsbin different formats @Cucumber.Options(format = { "junit:target/cucumber-junit.xml", "usage:target/cucumber-json-usage.json", "pretty:target/cucumber-pretty.txt", "html:target/cucumber-htmlreport", "json-pretty:target/cucumber-report.json"}) //@Cucumber.Options(format = {"pretty", "html:target/cucumber-htmlreport","json-pretty:target/cucumber-report.json"}) public class RunCukesTest { }
true
81845193057583b1f0b01812463c561af790a507
Java
NullExc/JBdiEmoV3
/src/main/java/sk/tuke/fei/bdi/emotionalengine/annotation/EmotionalPlan.java
UTF-8
526
2.1875
2
[]
no_license
package sk.tuke.fei.bdi.emotionalengine.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class or method annotated by EmotionalPlan is recognized as Emotional Plan for JBdiEmo * * @author Peter Zemianek */ @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR}) @Retention(RetentionPolicy.RUNTIME) public @interface EmotionalPlan { EmotionalParameter[] value() default {}; }
true
b705a2bb5a05780d835eb7d648372b78125545bc
Java
caizhengjun/shop_guli
/shop_services/shop_coupon/src/main/java/com/shanghai/shop/coupon/service/impl/SmsCouponSpuCategoryServiceImpl.java
UTF-8
642
1.585938
2
[]
no_license
package com.shanghai.shop.coupon.service.impl; import com.shanghai.shop.coupon.entity.SmsCouponSpuCategory; import com.shanghai.shop.coupon.mapper.SmsCouponSpuCategoryMapper; import com.shanghai.shop.coupon.service.ISmsCouponSpuCategoryService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 优惠券分类关联 服务实现类 * </p> * * @author caizhengjun * @since 2021-03-01 */ @Service public class SmsCouponSpuCategoryServiceImpl extends ServiceImpl<SmsCouponSpuCategoryMapper, SmsCouponSpuCategory> implements ISmsCouponSpuCategoryService { }
true
3ed7d996a0c2152e6c4d2ce70b59d1ca6c0ae376
Java
IonutCiuta/Internship-Trainings
/Training 10 - Design Patterns/ood-principles-and-patterns/src/com/endava/patterns/adapter/UsbToMicroUsb.java
UTF-8
353
2.65625
3
[]
no_license
package com.endava.patterns.adapter; /** * Created by Andra on 7/21/2016. */ public class UsbToMicroUsb implements MicroUsb { private Usb usb; public UsbToMicroUsb(Usb usb) { this.usb = usb; } @Override public void transferMicroUsb() { usb.transferUsb(); System.out.println(" ... to microUsb"); } }
true
b50deee179008f46b830d4af140551155a98cdbb
Java
VegaNan/FinalProject
/Final-Project/src/main/java/models/Item.java
UTF-8
765
3.046875
3
[]
no_license
package models; import java.io.Serializable; public abstract class Item implements Serializable{ private static final long serialVersionUID = 1L; public int value; public String name; public Item(String name, int value) { setName(name); setValue(value); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Item \t[name=").append(name).append(", \t\t\t\t\t\t\t\t\t\t\t\t\tvalue=").append(value) .append("]"); return builder.toString(); } }
true
572cd55e8eeda6922325a46ff2c7f7f649e2f6f8
Java
ScottWalkerAU/QAPES
/src/main/java/me/scottwalkerau/qapes/algorithm/AlgorithmTree.java
UTF-8
6,148
3.125
3
[ "MIT" ]
permissive
package me.scottwalkerau.qapes.algorithm; import me.scottwalkerau.qapes.block.Block; import me.scottwalkerau.qapes.block.BlockCatalogue; import me.scottwalkerau.qapes.block.ReturnType; import me.scottwalkerau.qapes.qap.Instance; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Class to store an entire algorithm in a tree structure. * The tree is a custom-built Abstract Data Type. * @author Scott Walker */ public class AlgorithmTree { /** How many times to run the algorithm */ private static final int RUNS = 4; /** The depth at which we start to prefer terminal nodes */ private static final int MAX_DEPTH = 5; /** Root node of the tree */ private AlgorithmNode root; /** The result from the last run of the algorithm. This is needed for persistent fitness */ private ResultSet resultSet; /** Runners in execution */ private transient List<AlgorithmRunner> runners; /** * Constructor to randomly generate a tree */ public AlgorithmTree() { root = new AlgorithmNode(null, BlockCatalogue.getRandomBlock(ReturnType.VOID)); generateChildren(root); } /** * Clone constructor * @param original Algorithm to clone */ private AlgorithmTree(AlgorithmTree original) { this.root = original.root.duplicate(); this.resultSet = original.resultSet; } /** * Constructor used in loading an algorithm from file * @param root Root of the tree */ public AlgorithmTree(AlgorithmNode root) { this.root = root; } /** * Call the clone constructor * @return New AlgorithmTree */ public AlgorithmTree duplicate() { return new AlgorithmTree(this); } // TODO Private or move into the AlgorithmNode? public void generateChildren(AlgorithmNode current) { List<ReturnType> types = current.getBlock().getParamTypes(); // For each of the children, set it to a random one of that type for (int i = 0; i < types.size(); i++) { ReturnType rt = types.get(i); Block block; if (current.getLevel() < MAX_DEPTH - 1) { block = BlockCatalogue.getRandomBlock(rt); } else { block = BlockCatalogue.getRandomBlockChildless(rt); } AlgorithmNode child = new AlgorithmNode(current, block); current.setChild(i, child); generateChildren(child); } } /** * Run the algorithm n times against the instance * @param instance Instance to use */ public void run(Instance instance) { runners = new ArrayList<>(); for (int run = 0; run < RUNS; run++) { AlgorithmRunner runner = new AlgorithmRunner(instance, this); runner.run(); runners.add(runner); } } /** * Wait for the execution to finish and return the result set * @return Result set * @throws InterruptedException Thread was interrupted */ public ResultSet join() throws InterruptedException { resultSet = new ResultSet(this); for (AlgorithmRunner runner : runners) { runner.join(); resultSet.addResult(runner.getResult()); } return resultSet; } /** * Cause mutations throughout the tree * @param chance Chance for a mutation out of 100 * @return True if at least one mutation occurred */ public boolean mutate(int chance) { return mutateRecursion(chance, root); } /** * Cause mutations throughout the tree * @param chance Chance for a mutation out of 100 * @param node The current node to operate on * @return True if at least one mutation occurred */ private boolean mutateRecursion(int chance, AlgorithmNode node) { if (new Random().nextInt(100) < chance) { generateChildren(node); return true; } boolean mutated = false; for (AlgorithmNode child : node.getChildren()) { if (mutateRecursion(chance, child)) mutated = true; } return mutated; } /** * Get a random node that matches the given type * @param type Type to choose * @return Node of chosen type */ public AlgorithmNode getRandomNodeOfType(ReturnType type) { List<AlgorithmNode> typeList = new ArrayList<>(); for (AlgorithmNode current : getAllNodes()) { if (current.getBlock().getReturnType() == type) typeList.add(current); } return (typeList.size() == 0) ? null : typeList.get(new Random().nextInt(typeList.size())); } /** * Get a random node from the tree * @return A randomly selected node from the tree */ public AlgorithmNode getRandomNode() { List<AlgorithmNode> all = getAllNodes(); return all.get(new Random().nextInt(all.size())); } /** * Get all the nodes of the tree as a list * @return Every node */ public List<AlgorithmNode> getAllNodes() { List<AlgorithmNode> list = new ArrayList<>(); getAllNodesRecursion(list, root); return list; } /** * Helper function for getAllNodes * @param list List to append to * @param current Current node */ private void getAllNodesRecursion(List<AlgorithmNode> list, AlgorithmNode current) { list.add(current); for (AlgorithmNode child : current.getChildren()) { getAllNodesRecursion(list, child); } } /** * Print the tree as a string over new lines */ public StringBuilder print() { StringBuilder builder = new StringBuilder(); new TreeMinimiser(this).run().getRoot().print(builder, ""); return builder; } // -- Getters -- public AlgorithmNode getRoot() { return root; } public ResultSet getResultSet() { return resultSet; } // -- Setters -- public void setRoot(AlgorithmNode root) { this.root = root; } }
true
fdf278bfdf5ff174523b0714653372eb7a67541f
Java
singhmp968/wipro-assignment-and-project
/InventoryAndSalesSystem/src/com/wipro/sale/util/DBUtil.java
UTF-8
490
2.453125
2
[]
no_license
package com.wipro.sale.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtil { private static Connection conn = null; public static Connection getDBConnection() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr12","root"); }catch(Exception e) { System.out.println("Could not establshed connection"); } return conn; } }
true
679bef325f726f08b63f1e228fb3266c55b4307e
Java
Gaganiith/code-hecks
/compiler/semantic-cool/solution/java/cool/Semantic.java
UTF-8
617
2.78125
3
[]
no_license
package cool; import java.util.*; public class Semantic{ private boolean errorFlag = false; public void reportError(String filename, int lineNo, String error){ errorFlag = true; System.err.println(filename+":"+lineNo+": "+error); } public boolean getErrorFlag(){ return errorFlag; } /* Don't change code above this line */ public Semantic(AST.program program){ //Write Semantic analyzer code here // ASTTraversal object to visit the program using Visitor Pattern ASTTraversal traverse = new ASTTraversal(); // traverse the program program.accept(traverse); } public Semantic(){ } }
true
95b8033263a93765ff2e8b2ce1f52870f7bfaf3f
Java
r1O1n2A1/EffectiveJavaThirdEdition
/src/main/java/creating/destroying/objects/StaticFactoryMethod.java
UTF-8
1,125
3.53125
4
[]
no_license
package creating.destroying.objects; import creating.destroying.objects.flyweight.IShape; /** * <b> Item1: Consider static factory method instead of constructors </b> * <p> * - unlike constructors, they have names * - unlike constructors, they are not required to create a new object * each time they re invoked (similar to the flyweight pattern) {@link IShape} * - unlike constructors, they can return any subtype of their return type * <p> * The main limitation: the class without public or protected constructors * can not be subclassed * Another limitation: They are hard to find for programmers * <p> * common names: from, valueOf, of, getInstance, create, getType, newType ... */ public class StaticFactoryMethod { private String option1; private String option2; // add getters && setters private StaticFactoryMethod(String option1, String option2) { this.option1 = option1; this.option2 = option2; } public static StaticFactoryMethod getInstance(String option1, String option2) { return new StaticFactoryMethod(option1, option2); } }
true
df7a606797f61456b1159d1ffecbb8faf86a8a4e
Java
shradej1/semver-vcs
/modules/api/src/main/java/org/ajoberstar/semver/vcs/Versioner.java
UTF-8
1,828
2.53125
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ajoberstar.semver.vcs; import com.github.zafarkhaja.semver.Version; import java.util.Objects; /** * Defines the contract of version inference. This is the core * interface by which a semantic version is calculated from a * VCS's state. */ @FunctionalInterface public interface Versioner { /** * Infers the project's version based on the parameters. * @param base the version to increment off of, unless * @param vcs the version control system holding the * current state of the project * @return the version to be used for the project or * passed into the next versioner */ Version infer(Version base, Vcs vcs); /** * Combines the given versioner with this one. The given * versioner will be executed first followed by this one. * The returned versioner will behave as {@code this.infer(before.infer(base, vcs), vcs)}. * @param before the versioner to compose with this one * @return a versioner representing the composition of the two */ default Versioner compose(Versioner before) { Objects.requireNonNull(before); return (base, vcs) -> infer(before.infer(base, vcs), vcs); } }
true
4b39562d3bf1845b694c7e29bfcfedbc545ca15d
Java
coding-eval-platform/commons
/commons-libraries/commons-executor-sdk/commons-executor-api/src/main/java/ar/edu/itba/cep/executor/api/ExecutionRequestSender.java
UTF-8
622
2.34375
2
[ "Apache-2.0" ]
permissive
package ar.edu.itba.cep.executor.api; import ar.edu.itba.cep.executor.models.ExecutionRequest; /** * Defines behaviour for an object that can send command messages to the executor service. */ public interface ExecutionRequestSender<I extends ExecutionResponseIdData> { /** * Requests an execution to the executor service. * * @param executionRequest The {@link ExecutionRequest} to be sent to the executor service. * @param idData Data indicating how the reply message must be identified. */ void requestExecution(final ExecutionRequest executionRequest, final I idData); }
true
ba63658a68580c0057e7e9f55c8717320b91c3fa
Java
sunli7758521/yy_admin
/ruoyi-system/src/main/java/com/ruoyi/sysusersystem/service/IJzSecurityTeamService.java
UTF-8
1,340
1.789063
2
[ "MIT" ]
permissive
package com.ruoyi.sysusersystem.service; import com.ruoyi.sysusersystem.domain.JzSecurityTeam; import java.util.List; /** * 安全小组Service接口 * * @author sunli * @date 2020-02-24 */ public interface IJzSecurityTeamService { /** * 查询安全小组 * * @param id 安全小组ID * @return 安全小组 */ public JzSecurityTeam selectJzSecurityTeamById(Long id); /** * 查询安全小组列表 * * @param jzSecurityTeam 安全小组 * @return 安全小组集合 */ public List<JzSecurityTeam> selectJzSecurityTeamList(JzSecurityTeam jzSecurityTeam); /** * 新增安全小组 * * @param jzSecurityTeam 安全小组 * @return 结果 */ public int insertJzSecurityTeam(JzSecurityTeam jzSecurityTeam); /** * 修改安全小组 * * @param jzSecurityTeam 安全小组 * @return 结果 */ public int updateJzSecurityTeam(JzSecurityTeam jzSecurityTeam); /** * 批量删除安全小组 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteJzSecurityTeamByIds(String ids); /** * 删除安全小组信息 * * @param id 安全小组ID * @return 结果 */ public int deleteJzSecurityTeamById(String id); }
true