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 |
---|---|---|---|---|---|---|---|---|---|---|---|
a1c5d9e94ead7d5ce48988d12564658b540a9b56
|
Java
|
sadatc/synthscape
|
/src/com/synthverse/synthscape/core/EventStats.java
|
UTF-8
| 3,246 | 2.734375 | 3 |
[] |
no_license
|
package com.synthverse.synthscape.core;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Set;
import java.util.logging.Logger;
import com.synthverse.Main;
import com.synthverse.util.LogUtils;
public class EventStats {
@Override
public String toString() {
String result = "[";
for (Event event : events) {
result += event.name() + ":" + eventCounterMap.get(event) + " ";
}
result += "]";
return result;
}
private static Logger logger = Logger.getLogger(EventStats.class.getName());
static {
LogUtils.applyDefaultSettings(logger, Main.settings.REQUESTED_LOG_LEVEL);
}
private EnumMap<Event, Long> eventCounterMap = new EnumMap<Event, Long>(Event.class);
private EnumMap<EventType, Long> eventTypeCounterMap = new EnumMap<EventType, Long>(EventType.class);
private Set<Event> events = EnumSet.noneOf(Event.class);
private Set<EventType> eventTypes = EnumSet.noneOf(EventType.class);
public EventStats() {
eventCounterMap.clear();
eventTypeCounterMap.clear();
}
public void recordValue(Event event) {
if (eventCounterMap.containsKey(event)) {
eventCounterMap.put(event, eventCounterMap.get(event) + 1);
} else {
eventCounterMap.put(event, (long) 1);
events.add(event);
}
EventType type = event.getType();
if (eventTypeCounterMap.containsKey(type)) {
eventTypeCounterMap.put(type, eventTypeCounterMap.get(type) + 1);
} else {
eventTypeCounterMap.put(type, (long) 1);
eventTypes.add(type);
}
}
public Set<Event> getEvents() {
return events;
}
public Set<EventType> getEventTypes() {
return eventTypes;
}
public long getValue(Event event) {
long result = eventCounterMap.containsKey(event) ? eventCounterMap.get(event) : 0;
return result;
}
public long getTypeValue(EventType type) {
long result = eventTypeCounterMap.containsKey(type) ? eventTypeCounterMap.get(type) : 0;
return result;
}
public void clear() {
eventCounterMap.clear();
events.clear();
eventTypeCounterMap.clear();
eventTypes.clear();
}
/**
* This adds all values from this stat object to the one provided.
*
* @param accumulatingStats
*/
public void aggregateStatsTo(EventStats accumulatingStats) {
for (Event event : events) {
if (accumulatingStats.eventCounterMap.containsKey(event)) {
accumulatingStats.eventCounterMap.put(event,
accumulatingStats.eventCounterMap.get(event) + eventCounterMap.get(event));
} else {
accumulatingStats.eventCounterMap.put(event, eventCounterMap.get(event));
accumulatingStats.events.add(event);
}
}
for (EventType type : eventTypes) {
if (accumulatingStats.eventTypeCounterMap.containsKey(type)) {
accumulatingStats.eventTypeCounterMap.put(type,
accumulatingStats.eventTypeCounterMap.get(type) + eventTypeCounterMap.get(type));
} else {
accumulatingStats.eventTypeCounterMap.put(type, eventTypeCounterMap.get(type));
accumulatingStats.eventTypes.add(type);
}
}
}
public void printEventStats() {
for (Event event : events) {
D.p(event.name() + " = " + eventCounterMap.get(event));
}
}
public void printEventTypeStats() {
for (EventType type : eventTypes) {
D.p(type.name() + " = " + eventTypeCounterMap.get(type));
}
}
}
| true |
a26c21368869367fe83f7eabe156b732f69d1071
|
Java
|
vydra/cas
|
/webapp/cas-server-webapp-config/src/main/java/org/apereo/cas/config/CasMetricsConfiguration.java
|
UTF-8
| 3,927 | 1.804688 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
package org.apereo.cas.config;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.jvm.FileDescriptorRatioGauge;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
import com.codahale.metrics.servlets.MetricsServlet;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.mvc.ServletWrappingController;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* This is {@link CasMetricsConfiguration} that attempts to create Spring-managed beans
* backed by external configuration.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Configuration("casMetricsConfiguration")
@EnableMetrics
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasMetricsConfiguration extends MetricsConfigurerAdapter {
@Autowired
@Qualifier("handlerMapping")
private SimpleUrlHandlerMapping handlerMapping;
@Autowired
private CasConfigurationProperties casProperties;
/**
* Metric registry metric registry.
*
* @return the metric registry
*/
@Bean
public MetricRegistry metrics() {
final MetricRegistry metrics = new MetricRegistry();
metrics.register("jvm.gc", new GarbageCollectorMetricSet());
metrics.register("jvm.memory", new MemoryUsageGaugeSet());
metrics.register("thread-states", new ThreadStatesGaugeSet());
metrics.register("jvm.fd.usage", new FileDescriptorRatioGauge());
return metrics;
}
/**
* Health check metrics health check registry.
*
* @return the health check registry
*/
@Bean
public HealthCheckRegistry healthCheckMetrics() {
return new HealthCheckRegistry();
}
@Override
public MetricRegistry getMetricRegistry() {
return metrics();
}
@Override
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckMetrics();
}
@Override
public void configureReporters(final MetricRegistry metricRegistry) {
final Logger perfStatsLogger = LoggerFactory.getLogger(casProperties.getMetrics().getLoggerName());
registerReporter(Slf4jReporter
.forRegistry(metricRegistry)
.outputTo(perfStatsLogger)
.convertRatesTo(TimeUnit.MILLISECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build())
.start(casProperties.getMetrics().getRefreshInterval(), TimeUnit.SECONDS);
registerReporter(JmxReporter
.forRegistry(metricRegistry)
.build());
}
@PostConstruct
public void init() {
final ServletWrappingController w = new ServletWrappingController();
w.setServletName("metricsServlet");
w.setServletClass(MetricsServlet.class);
w.setSupportedMethods("GET");
final Map map = new HashMap<>(handlerMapping.getUrlMap());
map.put("/status/metrics", w);
handlerMapping.setUrlMap(map);
}
}
| true |
7c421031fa60d71313e92f8db4f0c1b0b8912f45
|
Java
|
mohak92/Home-Automation
|
/src/SE_spring2013_g8/hal/Intercom/AnnouncementView.java
|
UTF-8
| 675 | 2.234375 | 2 |
[] |
no_license
|
package SE_spring2013_g8.hal.Intercom;
import SE_spring2013_g8.hal.R;
import android.app.Activity;
import android.os.Bundle;
/**
* AnnouncementView class
*
* AnnouncementView is an activity class displays the view that is shown on the receiving device when
* an announcement is running
*
* @author Theophilus Mensah
*
*/
public class AnnouncementView extends Activity {
/**
* onCreate prepares and displays the Announcement view
* @param savedInstanceState an instance of the AnnouncementView activity class
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intercom_announcement);
}
}
| true |
a82addf7afe8a5ce0f6c39937e2e0af3b4fc4739
|
Java
|
OtusTeam/Spring
|
/2023-05/spring-07-advanced-config/test-configuration-solution-3/src/test/java/ru/otus/example/testconfigurationdemo/demo/TestSpringBootConfiguration.java
|
UTF-8
| 640 | 2.09375 | 2 |
[] |
no_license
|
package ru.otus.example.testconfigurationdemo.demo;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import ru.otus.example.testconfigurationdemo.family.parents.Father;
@ComponentScan({"ru.otus.example.testconfigurationdemo.family.parents",
"ru.otus.example.testconfigurationdemo.family.childrens"})
@SpringBootConfiguration
public class TestSpringBootConfiguration {
@Bean
FamilyMember father() {
return new Father();
}
}
| true |
198408ab502b42ff6ebc8e69e338c56525e3a757
|
Java
|
shashankkhochikar/Clickit
|
/app/src/main/java/com/clickitproduct/Beans/Cart.java
|
UTF-8
| 1,679 | 2.234375 | 2 |
[] |
no_license
|
package com.clickitproduct.Beans;
import java.io.Serializable;
public class Cart implements Serializable
{
String productId,userId,shopId, productImg, productNm, productPrice;
public String getProductImg() {
return productImg;
}
public void setProductImg(String productImg) {
this.productImg = productImg;
}
public String getProductNm() {
return productNm;
}
public void setProductNm(String productNm) {
this.productNm = productNm;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public int getIsLogClick() {
return isLogClick;
}
public void setIsLogClick(int isLogClick) {
this.isLogClick = isLogClick;
}
int isLogClick;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getShopId() {
return shopId;
}
public void setShopId(String shopId) {
this.shopId = shopId;
}
@Override
public String toString() {
return "{" +
"productId=" + productId +
", user_id=" + userId +
", shop_id=" + shopId +
", product_img=" + productImg +
", product_name=" + productNm +
", product_price=" + productPrice +
'}';
}
}
| true |
dfa8442c5486d23302363f07b7fb74c83d71de7b
|
Java
|
vishnu351/samplecode
|
/boot-drools/src/main/java/com/javainuse/controller/EscrowRemovalController.java
|
UTF-8
| 1,300 | 2.21875 | 2 |
[] |
no_license
|
package com.javainuse.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javainuse.model.FPIns;
import com.javainuse.model.Product;
import com.javainuse.model.Result;
import com.javainuse.service.EscrowRemovalService;
@RestController
public class EscrowRemovalController {
private final EscrowRemovalService escrowRemovalService;
@Autowired
public EscrowRemovalController(EscrowRemovalService escrowRemovalService) {
this.escrowRemovalService = escrowRemovalService;
}
@RequestMapping(value = "/guidlines", method = RequestMethod.GET, produces = "application/json")
public List<Result> getQuestions() {
Product product = new Product();
Result result= new Result();
product.setManufactured("08");
FPIns fpins = new FPIns();
List<FPIns> fplist = new ArrayList<FPIns>();
fpins.setFLOAN("458855");
fpins.setFLTEXT("flood ltr place");
fplist.add(fpins);
product.setfPInsList(fplist);
List<Result> resultlist =escrowRemovalService.getProductDiscount(product,result);
return resultlist;
}
}
| true |
b687b4a8422f3440fed1278853674df7ea58603d
|
Java
|
mahirrao/PageObjectModel_Basic
|
/src/main/java/prac/mda/pages/ZohoAppPage.java
|
UTF-8
| 542 | 1.773438 | 2 |
[] |
no_license
|
package prac.mda.pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import prac.mda.Base.Page;
import prac.mda.pages.crm.CRMhomePage;
public class ZohoAppPage extends Page
{
public void goToBooks()
{
driver.findElement(By.cssSelector("#zl-myapps div.ea-app-container div:nth-child(1)")).click();
}
public CRMhomePage goToCRM()
{
if (oldURL)
click("CRM_OldPage_CSS");
else
click("CRMpage_CSS");
return new CRMhomePage();
}
}
| true |
beb71c78eaee3076f482e71f4c6340052afdc9e4
|
Java
|
SergeyMatyushkin/Notes
|
/app/src/main/java/com/example/notes/NotesEntity.java
|
UTF-8
| 1,236 | 2.6875 | 3 |
[] |
no_license
|
package com.example.notes;
import android.os.Parcel;
import android.os.Parcelable;
public class NotesEntity implements Parcelable {
public String name;
public String date;
public String description;
@Override
public String toString() {
return name + ' ' + date + ' ' + description;
}
public NotesEntity(String name, String date, String description) {
this.name = name;
this.date = date;
this.description = description;
}
protected NotesEntity(Parcel in) {
name = in.readString();
date = in.readString();
description = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(date);
dest.writeString(description);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<NotesEntity> CREATOR = new Creator<NotesEntity>() {
@Override
public NotesEntity createFromParcel(Parcel in) {
return new NotesEntity(in);
}
@Override
public NotesEntity[] newArray(int size) {
return new NotesEntity[size];
}
};
}
| true |
c6db0bc0758243eaf08e375f9cbe55386194e111
|
Java
|
oliverchuaaus/History
|
/SE/MyJPA/src/main/java/jpql/PlayerDTO.java
|
UTF-8
| 677 | 2.84375 | 3 |
[] |
no_license
|
package jpql;
public class PlayerDTO {
private Long playerId;
private String playerName;
private Integer salary;
public PlayerDTO(Long playerId, String playerName, Integer salary) {
super();
this.playerId = playerId;
this.playerName = playerName;
this.salary = salary;
}
public Long getPlayerId() {
return playerId;
}
public void setPlayerId(Long playerId) {
this.playerId = playerId;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
}
| true |
2dec0c45df04a58ac83c56c5a1ee6bb77e8a17e7
|
Java
|
JonnyDaenen/Gumbo
|
/src/gumbo/compiler/linker/CalculationUnitGroup.java
|
UTF-8
| 8,796 | 2.84375 | 3 |
[] |
no_license
|
/**
* Created: 09 May 2014
*/
package gumbo.compiler.linker;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import gumbo.compiler.calculations.BasicGFCalculationUnit;
import gumbo.compiler.calculations.CalculationUnit;
import gumbo.structures.data.RelationSchema;
import gumbo.structures.gfexpressions.GFExistentialExpression;
/**
* Representation of a CalculationUnit DAG (may or may not be connected).
* This class is a wrapper for a set of {@link CalculationUnits},
* which contain their own dependencies. The aim of this class is to provide
* a collection of operations on the DAG.
*
* For example, it allows for the discovery of input/output/intermediate
* relation schemes, which in general cannot be discovered by solely looking at
* root/leaf calculations. This is the case when an intermediate calculation
* both depends on another calculation and at the same time needs a raw table.
*
* The structure also allows for easy discovery of
* leaf (depends on no other calculations) and root (no depending calculations)
* calculations.
*
* TODO #core separate schema logic
*
* @author Jonny Daenen
*
*/
public class CalculationUnitGroup implements Iterable<CalculationUnit> {
Set<CalculationUnit> calculations;
public CalculationUnitGroup() {
calculations = new HashSet<CalculationUnit>();
}
public void add(CalculationUnit c) {
calculations.add(c);
// TODO check for cyclic dependencies
}
public void addAll(CalculationUnitGroup calcSet) {
for (CalculationUnit cu : calcSet) {
calculations.add(cu);
// TODO check for cyclic dependencies
}
}
/**
* Calculates the set of independent calculations.
*
* @return set of CalculationsUnits that are not dependent of any other
* calculations
*/
public Collection<CalculationUnit> getLeafs() {
ArrayList<CalculationUnit> leafs = new ArrayList<CalculationUnit>();
for (CalculationUnit c : calculations) {
if (c.isLeaf())
leafs.add(c);
}
return leafs;
}
/**
* Calculates the set of calculations on which no others depend.
*
* @return set of CalculationsUnits on which no others depend
*/
public CalculationUnitGroup getRoots() {
CalculationUnitGroup roots = new CalculationUnitGroup();
// add to root set if applicable
for (CalculationUnit currentCalc : calculations) {
boolean isRoot = true;
for (CalculationUnit oldCalc : calculations) {
if (oldCalc.getDependencies().contains(currentCalc)) {
isRoot = false;
break;
}
}
if (isRoot) {
roots.add(currentCalc);
}
}
return roots;
}
/**
* Calculates the maximum height of the DAG(s). The entire set of calculations is traversed.
* @return the maximum height of the DAG(s)
*/
public int getHeight() {
int max = 0;
for (CalculationUnit c : calculations) {
max = Math.max(max, c.getHeight());
}
return max;
}
/**
* TODO levelwise?
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<CalculationUnit> iterator() {
return calculations.iterator();
}
/**
* @param height
* @return partition with all calculations of the specified height
*/
public CalculationUnitGroup getCalculationsByHeight(int height) {
CalculationUnitGroup cp = new CalculationUnitGroup();
for (CalculationUnit c : calculations) {
if (c.getHeight() == height)
cp.add(c);
}
return cp;
}
/**
* Calculates the set of calculation units on a specified depth
* (depth of root calculation units = 1).
*
* @param depth
* @return partition with all calculations of the specified depth
*/
public CalculationUnitGroup getCalculationsByDepth(int depth) {
// calculate roots (depth = 1)
CalculationUnitGroup currentLevel = getRoots();
// breadth first expansion
for (int level = 2; level <= depth; level++) {
CalculationUnitGroup newLevel = new CalculationUnitGroup();
// for each current cu
for (CalculationUnit c : currentLevel) {
// add all the children to the new level
for (CalculationUnit child : c.getDependencies()) {
newLevel.add(child);
}
}
// level complete -> shift
currentLevel = newLevel;
}
// return last calculated level
return currentLevel;
}
/**
* @return
*/
public int size() {
return calculations.size();
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String s = "{" + System.lineSeparator();
for (CalculationUnit c : calculations) {
s += c + System.lineSeparator();
}
s += "}";
return s;
}
public String toShortString() {
String s = "{";
for (CalculationUnit c : calculations) {
s += c.getId() + ",";
}
s += "}";
return s;
}
/**
* @return the set of relations that appear as output schema
*/
protected Set<RelationSchema> getAllOutputRelations() {
Set<RelationSchema> out = new HashSet<RelationSchema>();
for (CalculationUnit cu : calculations) {
out.add(cu.getOutputSchema());
}
return out;
}
/**
* @return the set of relations that appear as input schema
*/
protected Set<RelationSchema> getAllInputRelations() {
Set<RelationSchema> out = new HashSet<RelationSchema>();
for (CalculationUnit cu : calculations) {
out.addAll(cu.getInputRelations());
}
return out;
}
/**
* @return the set of relations that appear as input or output schema
*/
protected Set<RelationSchema> getAllRelations() {
Set<RelationSchema> out = new HashSet<RelationSchema>();
out.addAll(getAllInputRelations());
out.addAll(getAllOutputRelations());
return out;
}
/**
* @return the set of relations that cannot be obtained using a dependent
* calculation
*/
public Set<RelationSchema> getInputRelations() {
Set<RelationSchema> in = new HashSet<RelationSchema>();
in.addAll(getAllInputRelations());
in.removeAll(getAllOutputRelations());
return in;
}
/**
* @return the set of relations that cannot be obtained using a dependent
* calculation TODO what?
*/
public Set<RelationSchema> getOutputRelations() {
Set<RelationSchema> out = new HashSet<RelationSchema>();
out.addAll(getAllOutputRelations());
out.removeAll(getAllInputRelations());
return out;
}
/**
* Calculates the set of relations that will be calculated by calculations
* units.
* TODO #core is this "non-output"?
*
* @return the set of non-output relations
*/
public Set<RelationSchema> getIntermediateRelations() {
Set<RelationSchema> temp = new HashSet<RelationSchema>();
temp.addAll(getAllRelations());
temp.removeAll(getInputRelations());
temp.removeAll(getOutputRelations());
return temp;
}
/**
* Constructs a set containing all calculations.
* @return the set of calculations
*/
public Set<CalculationUnit> getCalculations() {
Set<CalculationUnit> out = new HashSet<CalculationUnit>();
out.addAll(calculations);
return out;
}
/**
* @param c
* @return
*/
public int getDepth(CalculationUnit c) {
// roots have depth 1
int maxDepth = 1;
for (CalculationUnit p : getCalculations()) {
// is parent?
if (p.getDependencies().contains(c)) {
maxDepth = Math.max(maxDepth, getDepth(p) + 1);
}
}
return maxDepth;
}
/**
* Constructs the union of dependencies of all calculations.
*
* @return the union of all dependencies
*/
public Collection<CalculationUnit> getAllDependencies() {
HashSet<CalculationUnit> deps = new HashSet<>();
for (CalculationUnit cu: calculations) {
deps.addAll(cu.getDependencies());
}
return deps;
}
@Override
public boolean equals(Object obj) {
// wrong object
if (!(obj instanceof CalculationUnitGroup)) {
return false;
}
// cast
CalculationUnitGroup cug = (CalculationUnitGroup) obj;
// wrong size
if (calculations.size() != cug.calculations.size())
return false;
// size is ok, so one-way comparison suffices
for(CalculationUnit cu : cug.calculations) {
if (!calculations.contains(cu))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for (CalculationUnit cu : calculations) {
hashcode ^= cu.hashCode();
}
return hashcode;
}
public String getCanonicalOutString() {
StringBuffer sb = new StringBuffer();
for (CalculationUnit cu : calculations) {
sb.append(cu.getOutputSchema());
}
return sb.toString();
}
public Set<GFExistentialExpression> getBSGFs() {
Set<GFExistentialExpression> calculations = new HashSet<>();
for (CalculationUnit cu : getCalculations()) {
BasicGFCalculationUnit bcu = (BasicGFCalculationUnit) cu;
calculations.add(bcu.getBasicExpression());
}
return calculations;
}
}
| true |
8f83b120d8de282216c1e1edf8686b8df6d5147c
|
Java
|
Nyaseeme/DOIT
|
/src/cn/itcast/dao/ItemDao.java
|
UTF-8
| 240 | 1.703125 | 2 |
[] |
no_license
|
package cn.itcast.dao;
import org.apache.solr.client.solrj.SolrQuery;
import cn.itcast.domain.SearchResult;
public interface ItemDao {
// 查询索引库,得到Pojo分页对象
public SearchResult solrSearch(SolrQuery solrQuery);
}
| true |
891ae154a89a80a8f127c0ac2e1ecacfa30b9df9
|
Java
|
leil1230/JavaThreadLearn
|
/src/com/littlestones/threadlocal/SimpleThreadLocalDemo.java
|
UTF-8
| 1,226 | 3.484375 | 3 |
[] |
no_license
|
package com.littlestones.threadlocal;
/**
* @program: JavaThreadLearn
* @description: ThreadLocal示例
* @author: Leil
* @create: 2019-12-25 15:26
*/
class Entity01 {
public SimpleThreadLocal<Integer> seqNum = new SimpleThreadLocal<Integer>() {
@Override
public Integer init() {
return 0;
}
};
public int getNextSeqNum() {
seqNum.set(seqNum.get() + 1);
return seqNum.get();
}
}
class ThreadDemo01 extends Thread {
private Entity01 entity;
public ThreadDemo01(Entity01 entity) {
this.entity = entity;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(getName() + "=====" + entity.getNextSeqNum());
}
}
}
public class SimpleThreadLocalDemo {
public static void main(String[] args) {
Entity01 entity = new Entity01();
ThreadDemo01 threadDemo01 = new ThreadDemo01(entity);
ThreadDemo01 threadDemo02 = new ThreadDemo01(entity);
threadDemo01.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadDemo02.start();
}
}
| true |
d45157576c69bfe834796891ce910a395df70839
|
Java
|
greggraham/techinar
|
/Inheritance/src/Person.java
|
UTF-8
| 215 | 2.40625 | 2 |
[] |
no_license
|
/**
* Person
*/
public class Person {
String name;
int yearBorn;
Person(String name, int yearBorn) {
this.name = name;
this.yearBorn = yearBorn;
}
Person() {
}
}
| true |
a503546a177dfa8478ce072334c46a0ef5212c16
|
Java
|
zywickib/beer-manager
|
/src/main/java/pl/zywickib/core/rs/v1/dto/BeerResultDto.java
|
UTF-8
| 316 | 1.78125 | 2 |
[] |
no_license
|
package pl.zywickib.core.rs.v1.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class BeerResultDto {
private String id;
private String name;
private String style;
private Integer ibu;
private Double abv;
private String description;
private BreweryDto brewery;
}
| true |
6e744cd20193a4d52bc7dfef38813fad1f62e76c
|
Java
|
xingfeng2010/kai-ji-wang
|
/src/com/wenyu/kaijiw/LoginActivity.java
|
GB18030
| 6,235 | 1.984375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.wenyu.kaijiw;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.baoyz.swipemenulistview.BaoyzApplication;
import com.example.mywork.util.NetWorkUtil;
import com.wenyu.Data.Customer;
import com.wenyu.Data.HttpP;
import com.wenyu.Data.Urls;
import com.wenyu.db.DBManager;
public class LoginActivity extends Activity {
public static LoginActivity sSingleton;
private EditText phonenumber,password;
private Button submit,login,forget;
private String jsonData,imID,imPwd;
private Map<String,String> paramsValue,loginResult;
private DBManager mgr;
private Customer customer;
private int customer_id,flag;
private ImageView quit;
private String message,type,url = Urls.Url_Logins;
private static LoginActivity mInstance = null;
public static LoginActivity getInstance(){
return mInstance;
}
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch(msg.what){
case 0:
Toast.makeText(LoginActivity.this, "쳣 ", 1000).show();
break;
case 1:
BaoyzApplication.getInstance().isLogined = true;
Intent it = new Intent(LoginActivity.this, MainActivity.class);
it.putExtra("imID", imID);
it.putExtra("imPwd",imPwd);
startActivity(it);
LoginActivity.this.finish();
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(LoginActivity.this, "ûڻ벻ȷ", Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(LoginActivity.this, "ϼ ", 1000).show();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.login);
sSingleton=this;
mInstance=this;
initView();
}
private void initView() {
phonenumber = (EditText)findViewById(R.id.login_phonenumber);
password = (EditText) findViewById(R.id.login_password);
submit = (Button) findViewById(R.id.login_submit);
login = (Button) findViewById(R.id.login_register);
forget = (Button) findViewById(R.id.login_forget);
quit = (ImageView)findViewById(R.id.filmonquit);
submit.setOnClickListener(ol);
login.setOnClickListener(ol);
forget.setOnClickListener(ol);
quit.setOnClickListener(ol);
}
private boolean checkEdit(){
if(phonenumber.getText().toString().trim().equals("")){
Toast.makeText(LoginActivity.this, "û绰Ϊ", Toast.LENGTH_SHORT).show();
}else if(password.getText().toString().trim().equals("")){
Toast.makeText(LoginActivity.this, "벻Ϊ", Toast.LENGTH_SHORT).show();
}else{
return true;
}
return false;
}
private void httpLogin() {
new Thread(new Runnable(){
@Override
public void run() {
try {
paramsValue=new HashMap<String, String>();
paramsValue.put("phoneNumber",phonenumber.getText().toString());
paramsValue.put("pwd",password.getText().toString());
if(NetWorkUtil.isNetAvailable(LoginActivity.this)){
jsonData = new HttpP().sendPOSTRequestHttpClient(url,paramsValue);
if(("").equals(jsonData)){
handler.sendEmptyMessage(0);
}else {
message = initying(jsonData);
if("".equals(message)){
handler.sendEmptyMessage(2);
}else{
handler.sendEmptyMessage(1);
}
}
}else {
handler.sendEmptyMessage(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
*
* @param json1
* @return
*/
private String initying(String json1) {
try {
JSONObject jo = new JSONObject(json1);
String message = jo.optString("message");
type = jo.optString("authentication_type");
customer_id = jo.optInt("customer_id");
imID = jo.optString("imsdk_customUserID");
imPwd = jo.optString("imsdk_password");
//жϸûҵû
if("û".equals(type)){
flag=1;
}else if("ҵû".equals(type)){
flag=2;
}else if("δ֤".equals(type)){
flag = 0;
}else if("".equals(type)){
flag = 3;
}
else if("ҵ".equals(type)){
flag = 4;
}
//жǷֻŲڻΪ
if("".equals(type)){
return "";
}else{
Customer queryItem = mgr.queryItem(phonenumber.getText().toString());
// if(queryItem!=null){
// queryItem.setPassword(password.getText().toString());
// queryItem.setCertify(flag);
// queryItem.setActive(1);
// mgr.updatePassword(queryItem);
// mgr.updateCertify(queryItem);
// mgr.updateActive(queryItem);
// }else{
customer = new Customer();
customer.setId(customer_id);
customer.setPhonenumber(phonenumber.getText().toString());
customer.setPassword(password.getText().toString());
customer.setCertify(flag);
customer.setActive(1);
mgr.add(customer);
}
// }
if(flag==0){
return message+",뾡֤";
}
return message;
} catch (JSONException e) {
e.printStackTrace();
}
return "ʧ";
}
OnClickListener ol = new OnClickListener() {
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.login_submit:
if(checkEdit()){
mgr = new DBManager(LoginActivity.this);
httpLogin();
}
break;
case R.id.login_register:
Intent it = new Intent(LoginActivity.this,RegisterActivity.class);
it.putExtra("title", "ע");
it.putExtra("submit", "ע");
startActivity(it);
// LoginActivity.this.finish();
break;
case R.id.login_forget:
Intent it1 = new Intent(LoginActivity.this,ResetPwdActivity.class);
startActivity(it1);
LoginActivity.this.finish();
break;
case R.id.filmonquit:
LoginActivity.this.finish();
break;
default:
break;
}
}
};
}
| true |
ce896e17a3bd88fe60f3122bf1e10e28aa360b49
|
Java
|
mohd-naushaaad/PrimeNoChecker
|
/app/src/main/java/com/example/primenochecker/MainActivity.java
|
UTF-8
| 2,352 | 3 | 3 |
[] |
no_license
|
package com.example.primenochecker;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button checkBtn;
private TextView answerTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.enter_prime_number_editText);
checkBtn = findViewById(R.id.prime_number_check_btn);
answerTextView = findViewById(R.id.prime_number_answer_textView);
checkBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isPrimeNo()){
answerTextView.setText(editText.getText().toString() + " is a Prime Number");
answerTextView.setTextColor(Color.GREEN);
}else {
answerTextView.setText(editText.getText().toString() + " is not a Prime Number");
answerTextView.setTextColor(Color.RED);
}
}
});
}
private boolean isPrimeNo() {
if (editText.getText().toString().equals("1")) {
return false;
} else if (editText.getText().toString().equals("2")) {
return true;
} else if (editText.getText().toString().equals("3")) {
return true;
} else {
return check();
}
}
private boolean check() {
String number = editText.getText().toString();
double num = Double.parseDouble(number);
double a = 1;
double b = 6;
double resultA = (num + a) / b;
double resultB = (num - a) / b;
String answerA = String.valueOf(resultA);
String answerB = String.valueOf(resultB);
if (answerA.contains(".0")) {
answerA = answerA.replaceAll(".0", "");
}
if (answerB.contains(".0")) {
answerB = answerB.replaceAll(".0", "");
}
return !answerA.contains(".") || !answerB.contains(".");
}
}
| true |
5c2c808b9504b5657098333e9efd698df62f5d1d
|
Java
|
xdj123456789/-
|
/src/edu/tinzel/lx/test/fruilt.java
|
UTF-8
| 119 | 1.664063 | 2 |
[] |
no_license
|
package edu.tinzel.lx.test;
public interface fruilt {
public String name="fruilt";
public String getname();
}
| true |
b739a4940b507894f5288ede2d51ac40abe0fda3
|
Java
|
EngineerBarsik/dev
|
/org.nb.home/src/org/nb/home/command/FileCreateCommand.java
|
UTF-8
| 4,640 | 2.75 | 3 |
[] |
no_license
|
package org.nb.home.command;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.origin.common.command.AbstractCommand;
import org.origin.common.command.CommandContext;
import org.origin.common.command.CommandException;
import org.origin.common.command.impl.CommandResult;
import org.origin.common.io.FileUtil;
import org.origin.common.io.IOUtil;
import org.origin.common.runtime.IStatus;
import org.origin.common.runtime.Status;
public class FileCreateCommand extends AbstractCommand {
public static String MSG1 = "File '%s' exists, but is a directory.";
public static String MSG2 = "File '%s' already exists.";
public static String MSG3 = "File '%s' is created.";
public static String MSG4 = "Cannot create new file '%s'.";
public static String MSG5 = "Cannot copy input stream to file '%s'.";
public static String MSG6 = "Cannot copy bytes array to file '%s'.";
protected File file;
protected InputStream inputStream;
protected boolean autoCloseInputStream = false;
protected byte[] bytes;
protected boolean throwExceptionWhenFileIsDirectory = true;
protected boolean throwExceptionWhenFileExists = false;
/**
*
* @param filePath
*/
public FileCreateCommand(String filePath) {
assert (filePath != null) : "filePath is null";
this.file = new File(filePath);
}
/**
*
* @param file
*/
public FileCreateCommand(File file) {
assert (file != null) : "file is null";
this.file = file;
}
public boolean throwExceptionWhenFileIsDirectory() {
return throwExceptionWhenFileIsDirectory;
}
public void setThrowExceptionWhenFileIsDirectory(boolean throwExceptionWhenFileIsDirectory) {
this.throwExceptionWhenFileIsDirectory = throwExceptionWhenFileIsDirectory;
}
public boolean throwExceptionWhenFileExists() {
return throwExceptionWhenFileExists;
}
public void setThrowExceptionWhenFileExists(boolean throwExceptionWhenFileExists) {
this.throwExceptionWhenFileExists = throwExceptionWhenFileExists;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public boolean isAutoCloseInputStream() {
return autoCloseInputStream;
}
public void setAutoCloseInputStream(boolean autoCloseInputStream) {
this.autoCloseInputStream = autoCloseInputStream;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public CommandResult execute(CommandContext context) throws CommandException {
String filePath = this.file.getAbsolutePath();
// File exists and is a directory
if (this.file.exists() && this.file.isDirectory()) {
if (throwExceptionWhenFileIsDirectory()) {
throw new CommandException(String.format(MSG1, filePath));
}
// Ignore creating new file
return new CommandResult(new Status(IStatus.WARNING, null, String.format(MSG1, filePath)));
}
// File exists
if (this.file.exists()) {
if (throwExceptionWhenFileExists()) {
return new CommandResult(new Status(IStatus.ERROR, null, String.format(MSG2, filePath)));
}
// Ignore creating new file
return new CommandResult(new Status(IStatus.OK, null, String.format(MSG2, filePath)));
}
boolean succeed = false;
try {
succeed = this.file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
// File is not created
throw new CommandException(String.format(MSG4, filePath), e);
}
if (!succeed) {
// File is not created
throw new CommandException(String.format(MSG4, filePath));
}
if (this.inputStream != null) {
// Copy input stream to the new file
try {
FileUtil.copyInputStreamToFile(this.inputStream, this.file);
} catch (IOException e) {
e.printStackTrace();
// Cannot copy input stream to file
throw new CommandException(String.format(MSG5, filePath), e);
} finally {
if (isAutoCloseInputStream()) {
IOUtil.closeQuietly(this.inputStream, true);
}
}
} else if (this.bytes != null && this.bytes.length > 0) {
// Copy bytes array input stream to the new file
ByteArrayInputStream bytesInputStream = new ByteArrayInputStream(bytes);
try {
FileUtil.copyInputStreamToFile(bytesInputStream, this.file);
} catch (IOException e) {
e.printStackTrace();
// Cannot copy bytes array to file
throw new CommandException(String.format(MSG6, filePath), e);
} finally {
IOUtil.closeQuietly(bytesInputStream, true);
}
}
return new CommandResult(new Status(IStatus.OK, null, String.format(MSG3, filePath)));
}
}
| true |
5e5c9fab39cec886e632976d1e98fdd06b760871
|
Java
|
shinestmt/stmt
|
/CodeStore/src/main/java/com/hanghang/codestore/mina/MinaTest2.java
|
UTF-8
| 1,728 | 2.15625 | 2 |
[] |
no_license
|
package com.hanghang.codestore.mina;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import com.hanghang.codestore.mina.cmd.Constants;
import com.hanghang.codestore.mina.cmd.impl.ExitCommand;
import com.hanghang.codestore.mina.cmd.impl.HelpCommand;
public class MinaTest {
private static void init() {
Constants.cmdMap.put("help", new HelpCommand());
Constants.cmdMap.put("exit", new ExitCommand());
// Constants.cmdMap.put("help", new HelpCommand());
}
public static void main(String[] args) {
IoAcceptor acceptor = null;
try{
acceptor = new NioSocketAcceptor();
LineDelimiter.WINDOWS.getValue();
acceptor.getFilterChain().addLast( "logger", new LoggingFilter());
acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS, LineDelimiter.WINDOWS)));
// acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 5);
acceptor.setHandler(new TelnetServerHandler());
acceptor.bind(new InetSocketAddress(9000));
init();
System.out.println("Finish");
}catch (Exception e){
e.printStackTrace();
System.out.println("Error"+e);
}
}
}
| true |
edcf4a0e101675dd02e52ca2fd18e23013635250
|
Java
|
bcraun/osgi.enroute.bundles
|
/osgi.enroute.iot.circuit/src/osgi/enroute/iot/toolkit/Toggle.java
|
UTF-8
| 966 | 2.28125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package osgi.enroute.iot.toolkit;
import aQute.bnd.annotation.component.Component;
import aQute.bnd.annotation.component.Reference;
import osgi.enroute.dto.api.DTOs;
import osgi.enroute.iot.gpio.api.CircuitBoard;
import osgi.enroute.iot.gpio.api.IC;
import osgi.enroute.iot.gpio.util.Digital;
import osgi.enroute.iot.gpio.util.ICAdapter;
import osgi.enroute.iot.toolkit.Toggle.FlipConfig;
@Component(designateFactory=FlipConfig.class, provide=IC.class, name="osgi.enroute.iot.toolkit.toggle")
public class Toggle extends ICAdapter<Digital, Digital> implements Digital {
interface FlipConfig {
String name();
}
boolean state;
@Override
public synchronized void set(boolean value) throws Exception {
if ( value == false ) {
state = !state;
}
out().set(state);
}
@Reference
protected void setDTOs(DTOs dtos) {
super.setDTOs(dtos);
}
@Reference
protected
void setCircuitBoard(CircuitBoard board) {
super.setCircuitBoard(board);
}
}
| true |
bfde7cd16e317f708227da23aa42c24fdfb3f62b
|
Java
|
huangyc00/hhh-cloud
|
/hhh-provider/hhh-order/src/main/java/com/hyc/order/service/impl/OrderTransferServiceImpl.java
|
UTF-8
| 631 | 1.773438 | 2 |
[] |
no_license
|
package com.hyc.order.service.impl;
import com.hyc.common.bean.BaseServiceImpl;
import com.hyc.order.service.OrderTransferService;
import com.order.model.entity.OrderTransfer;
import com.order.model.entity.OrderTransferHandleLog;
import com.order.model.mapper.OrderTransferMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class OrderTransferServiceImpl extends BaseServiceImpl<OrderTransferMapper, OrderTransfer> implements OrderTransferService {
@Override
public OrderTransfer manualTransfer(OrderTransferHandleLog recObj) {
return null;
}
}
| true |
0913c23b62c6056b7afe09d8de39ae6ad0857d00
|
Java
|
ticapix/DataSpaceConnector
|
/extensions/atlas/src/main/java/org/eclipse/dataspaceconnector/catalog/atlas/dto/AtlasClassificationDef.java
|
UTF-8
| 7,202 | 1.992188 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2020, 2021 Microsoft Corporation
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Microsoft Corporation - initial API and implementation
*
*/
package org.eclipse.dataspaceconnector.catalog.atlas.dto;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.*;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class AtlasClassificationDef extends AtlasStructDef implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Set<String> superTypes;
private Set<String> entityTypes;
// subTypes field below is derived from 'superTypes' specified in all AtlasClassificationDef
// this value is ignored during create & update operations
private Set<String> subTypes;
public AtlasClassificationDef() {
this(null, null, null, null, null, null);
}
public AtlasClassificationDef(String name, String description, String typeVersion,
List<AtlasAttributeDef> attributeDefs, Set<String> superTypes) {
this(name, description, typeVersion, attributeDefs, superTypes, null);
}
public AtlasClassificationDef(String name, String description, String typeVersion,
List<AtlasAttributeDef> attributeDefs, Set<String> superTypes,
Map<String, String> options) {
this(name, description, typeVersion, attributeDefs, superTypes, null, options);
}
public AtlasClassificationDef(String name, String description, String typeVersion,
List<AtlasAttributeDef> attributeDefs, Set<String> superTypes,
Set<String> entityTypes, Map<String, String> options) {
super(TypeCategory.CLASSIFICATION, name, description, typeVersion, attributeDefs, options);
setSuperTypes(superTypes);
setEntityTypes(entityTypes);
}
private static boolean hasSuperType(Set<String> superTypes, String typeName) {
return superTypes != null && typeName != null && superTypes.contains(typeName);
}
private static boolean hasEntityType(Set<String> entityTypes, String typeName) {
return entityTypes != null && typeName != null && entityTypes.contains(typeName);
}
public Set<String> getSuperTypes() {
return superTypes;
}
public void setSuperTypes(Set<String> superTypes) {
if (superTypes != null && this.superTypes == superTypes) {
return;
}
if (superTypes == null || superTypes.isEmpty()) {
this.superTypes = new HashSet<>();
} else {
this.superTypes = new HashSet<>(superTypes);
}
}
public Set<String> getSubTypes() {
return subTypes;
}
public void setSubTypes(Set<String> subTypes) {
this.subTypes = subTypes;
}
public boolean hasSuperType(String typeName) {
return hasSuperType(superTypes, typeName);
}
public void addSuperType(String typeName) {
Set<String> s = superTypes;
if (!hasSuperType(s, typeName)) {
s = new HashSet<>(s);
s.add(typeName);
superTypes = s;
}
}
public void removeSuperType(String typeName) {
Set<String> s = superTypes;
if (hasSuperType(s, typeName)) {
s = new HashSet<>(s);
s.remove(typeName);
superTypes = s;
}
}
/**
* Specifying a list of entityType names in the classificationDef, ensures that classifications can
* only be applied to those entityTypes.
* <ul>
* <li>Any subtypes of the entity types inherit the restriction</li>
* <li>Any classificationDef subtypes inherit the parents entityTypes restrictions</li>
* <li>Any classificationDef subtypes can further restrict the parents entityTypes restrictions by specifying a subset of the entityTypes</li>
* <li>An empty entityTypes list when there are no parent restrictions means there are no restrictions</li>
* <li>An empty entityTypes list when there are parent restrictions means that the subtype picks up the parents restrictions</li>
* <li>If a list of entityTypes are supplied, where one inherits from another, this will be rejected. This should encourage cleaner classificationsDefs</li>
* </ul>
*/
public Set<String> getEntityTypes() {
return entityTypes;
}
public void setEntityTypes(Set<String> entityTypes) {
if (entityTypes != null && this.entityTypes == entityTypes) {
return;
}
if (entityTypes == null || entityTypes.isEmpty()) {
this.entityTypes = new HashSet<>();
} else {
this.entityTypes = new HashSet<>(entityTypes);
}
}
public boolean hasEntityType(String typeName) {
return hasEntityType(entityTypes, typeName);
}
public void addEntityType(String typeName) {
Set<String> s = entityTypes;
if (!hasEntityType(s, typeName)) {
s = new HashSet<>(s);
s.add(typeName);
entityTypes = s;
}
}
public void removeEntityType(String typeName) {
Set<String> s = entityTypes;
if (hasEntityType(s, typeName)) {
s = new HashSet<>(s);
s.remove(typeName);
entityTypes = s;
}
}
@Override
public StringBuilder toString(StringBuilder sb) {
if (sb == null) {
sb = new StringBuilder();
}
sb.append("AtlasClassificationDef{");
super.toString(sb);
sb.append(", superTypes=[");
dumpObjects(superTypes, sb);
sb.append("], entityTypes=[");
dumpObjects(entityTypes, sb);
sb.append("]");
sb.append('}');
return sb;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
AtlasClassificationDef that = (AtlasClassificationDef) o;
return Objects.equals(superTypes, that.superTypes) && Objects.equals(entityTypes, that.entityTypes);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), superTypes);
}
@Override
public String toString() {
return toString(new StringBuilder()).toString();
}
}
| true |
e71e9c96adfebebd53aab1c7cf76e2995cd2b59b
|
Java
|
JeromeRGero/CreatureWar-Base
|
/Cyberdemon.java
|
UTF-8
| 877 | 3.140625 | 3 |
[] |
no_license
|
import java.util.Random;
/**
* Write a description of class Cyberdemon here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Cyberdemon extends Demon
{
// Out to Lunch
private int hp;
private int strength;
Random random = new Random();
/**
* Constructor
*/
public Cyberdemon()
{
super();
this.strength = strength;
this.hp = hp;
}
/**
* Set Health
*/
public void setHP()
{
hp = random.nextInt(10) + 5;
}
/**
* Set Strength
*/
public void setSTR()
{
strength = random.nextInt(15) + 8;
}
/**
* Check Health
*/
public int getHP()
{
return hp;
}
/**
* Check Strength
*/
public int getSTR()
{
return strength;
}
}
| true |
a5fa24bc34d213ec81809b5841e0c83eba86de7f
|
Java
|
sd-2019-30238/assignment-1-UrcanMiruna
|
/assignment1/src/model/Order.java
|
UTF-8
| 2,233 | 3.140625 | 3 |
[] |
no_license
|
package model;
import java.util.Objects;
public class Order {
private int id;
private UserAccount user; /// same for people who orderred more products.
private Product product;
private String state;
private int amountOrdered;
private static int incremnet=0;
public Order(UserAccount user, Product product, String state, int amountOrdered) {
//this.setId();
this.user = user;
this.product = product;
this.state = state;
this.amountOrdered = amountOrdered;
}
public Order(int id, UserAccount user,Product product, String state, int amountOrdered) {
this.id=id;
this.user = user;
this.product = product;
this.state = state;
this.amountOrdered = amountOrdered;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public UserAccount getUser() {
return user;
}
public void setUser(UserAccount user) {
this.user = user;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getAmountOrdered() {
return amountOrdered;
}
public void setAmountOrdered(int amountOrdered) {
this.amountOrdered = amountOrdered;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", user=" + user +
", product=" + product +
", state='" + state + '\'' +
", amountOrdered=" + amountOrdered +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Order)) return false;
Order order = (Order) o;
return
Objects.equals(getUser(), order.getUser()) &&
Objects.equals(getProduct(), order.getProduct()) ;
}
@Override
public int hashCode() {
return Objects.hash( getUser(), getProduct());
}
}
| true |
099f142910e5cfbc16a5f87a4a7af7c39049bef4
|
Java
|
sycinsider/SafeGuard
|
/mobileguard/src/main/java/com/example/mobileguard/utils/SpUtils.java
|
UTF-8
| 2,212 | 2.5 | 2 |
[] |
no_license
|
package com.example.mobileguard.utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* ClassName:SpUtils <br/>
* Function: TODO ADD FUNCTION. <br/>
* Date: 2016年8月6日 下午8:28:36 <br/>
*
* @author dell
* @version
*/
public class SpUtils {
public static boolean getBoolean(Context context, String key) {
return getBoolean(context, key, false);
}
public static boolean getBoolean(Context context, String key, boolean defaultvalue) {
SharedPreferences sp =
context.getSharedPreferences(Constantset.SP_FILE_NAME, Context.MODE_PRIVATE);
return sp.getBoolean(key, defaultvalue);
}
public static void putBoolean(Context context, String key, boolean value) {
SharedPreferences sp =
context.getSharedPreferences(Constantset.SP_FILE_NAME, Context.MODE_PRIVATE);
sp.edit().putBoolean(key, value).commit();
}
public static String getString(Context context, String key) {
return getString(context, key, null);
}
public static String getString(Context context, String key, String defValuevalue) {
SharedPreferences sp =
context.getSharedPreferences(Constantset.SP_FILE_NAME, Context.MODE_PRIVATE);
return sp.getString(key, defValuevalue);
}
public static void putString(Context context, String key, String value) {
SharedPreferences sp =
context.getSharedPreferences(Constantset.SP_FILE_NAME, Context.MODE_PRIVATE);
sp.edit().putString(key, value).commit();
}
public static int getInt(Context context, String key) {
return getInt(context, key, -1);
}
public static int getInt(Context context, String key, int defValuevalue) {
SharedPreferences sp =
context.getSharedPreferences(Constantset.SP_FILE_NAME, Context.MODE_PRIVATE);
return sp.getInt(key, defValuevalue);
}
public static void putInt(Context context, String key, int value) {
SharedPreferences sp =
context.getSharedPreferences(Constantset.SP_FILE_NAME, Context.MODE_PRIVATE);
sp.edit().putInt(key, value).commit();
}
}
| true |
91922ce7d6f962ba2d0aa5b0ca2800d442864791
|
Java
|
UnawareAlex/unit2Classes
|
/CityscapeLab/SkyNight.java
|
UTF-8
| 2,168 | 3.3125 | 3 |
[] |
no_license
|
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.URL;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/**
* Creates a background image for the Cityscape by randomly choosing a URL from an array, which is then
* passed into a draw method
*
* @author Alex Arnold
* @version (10/11/15)
*/
public class SkyNight
{
/** description of instance variable x (add comment for each instance variable) */
private BufferedImage img; //defines the image location (URL)
/**
* Default constructor for objects of class Sky
*/
public SkyNight()
{
// initialise instance variables
String[] nightArray;
nightArray = new String[6];
nightArray[0] = "https://upload.wikimedia.org/wikipedia/commons/3/37/Pinnacles_Night_Sky_-_Flickr_-_Joe_Parks.jpg";
nightArray[1] = "http://a.abcnews.go.com/images/Technology/ht_New_York_20_darkened_skies_ll_130307_wblog.jpg";
nightArray[2] = "http://img09.deviantart.net/4e58/i/2014/134/e/b/coruscant__2_by_daroz-d7idgv0.jpg";
nightArray[3] = "http://elephanttruths.com/wp-content/uploads/2015/07/night-sky-stars.jpeg";
nightArray[4] = "https://jacquierobinsonphotography.files.wordpress.com/2013/06/pretty-night-sky-428.jpg";
nightArray[5] = "http://www.siwallpaper.com/wp-content/uploads/2015/09/night_sky_wallpapers.jpg";
//creates random generator to choose a random URL to import as an image
Random generator = new Random();
int x = generator.nextInt(6);
String imgLoc = nightArray[x];
try {
URL url = new URL(imgLoc);
this.img = ImageIO.read(url);
} catch (IOException e) {
}
}
/**
* Draws a image pulled randomly from the array
* @param g2 the graphics context
*/
public void draw(Graphics2D g2)
{
g2.drawImage(img, 0, 0, 800, 475, null);
}
}
| true |
9ba64e2e65fbb3ecf6de4776578a09b1080e22bd
|
Java
|
JensMulder/BakerApp
|
/BakerApp/src/main/java/JensMulder/project/bakerapp/core/models/Pie.java
|
UTF-8
| 1,510 | 2.625 | 3 |
[] |
no_license
|
package JensMulder.project.bakerapp.core.models;
import JensMulder.project.bakerapp.core.models.base.DbModelBase;
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Collection;
@Entity
@Table(name = "Pies")
public class Pie extends DbModelBase {
@NotBlank
@Length(max = 50)
private String name;
@NotBlank
@Length(max = 250)
private String description;
private byte[] img;
private double price;
@OneToMany(
fetch = FetchType.EAGER,
mappedBy = "pie",
orphanRemoval = true,
cascade = CascadeType.PERSIST
)
private Collection<Order> orders;
public Pie() {}
public Pie(String name, String description, byte[] img, double price) {
this.name = name;
this.description = description;
this.img = img;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getImg() {
return img;
}
public void setImg(byte[] img) {
this.img = img;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
| true |
64742b720ede1fa4455e414f12f2cd4732a5d2e7
|
Java
|
dev-loic/exercices-cracking
|
/src/CallCenter/Call.java
|
UTF-8
| 891 | 3.203125 | 3 |
[] |
no_license
|
package CallCenter;
import CallCenter.Employee.Rank;
public class Call {
// Donnees membres
private Caller _Caller;
private Employee _CurrentHandler;
private Rank _MinRankEmployee;
// Constructors
public Call(Rank iRank)
{
_Caller = new Caller();
_MinRankEmployee=iRank;
}
public Call()
{
this(Rank.respondent);
}
// Caller : person who call
static private int countCallers = 0;
public class Caller {
String name;
public Caller()
{
countCallers++;
name = "Caller"+countCallers;
}
}
public Caller getCaller()
{
return _Caller;
}
// Handler
public Employee getCurrentHandler()
{
return _CurrentHandler;
}
// Who takes this call in charge
public void setHandler(Employee iHandler)
{
// we suppose handler has the right rank as it should be adressed in the CallsHandler the right way.
_CurrentHandler=iHandler;
}
}
| true |
92216e523b48b35845d63028270107af45987218
|
Java
|
twotwo/framework-java
|
/netty-server/src/main/java/com/li3huo/netty/service/snapshot/SumObjectMap.java
|
UTF-8
| 2,604 | 3.015625 | 3 |
[] |
no_license
|
/**
* Create at Feb 19, 2013
*/
package com.li3huo.netty.service.snapshot;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author liyan
*
*/
public class SumObjectMap {
private String reportTitle;
private Date reportStartDate = new Date();
private Map<String, SumObject> map = new HashMap<String, SumObject>();
public SumObjectMap(String title) {
this.reportTitle = title;
}
private class SumObject {
private String key;
AtomicLong accessCount;
AtomicLong costTime;
/**
* @return the key
*/
public String getKey() {
return key;
}
/**
* @param key
*/
public SumObject(String key) {
this.key = key;
this.accessCount = new AtomicLong();
this.costTime = new AtomicLong();
}
}
/**
*
* @param weight
* @param costNanoTime
*/
public void add(String key, int weight, long costNanoTime) {
if (null == map.get(key)) {
map.put(key, new SumObject(key));
}
// access time plus one
map.get(key).accessCount.addAndGet(weight);
// add cost nano time
map.get(key).costTime.addAndGet(costNanoTime);
}
DecimalFormat format = new DecimalFormat("#,##0.### ms");
private String formatLong(long number) {
return format.format(number);
}
/**
*
* @param format
* 0-plantext, 1-html
* @return
*/
public String toString(int format) {
// to html format
StringBuffer buf = new StringBuffer();
long totalCount = 0, totolCost = 0;
buf.append(
"<h3>" + this.reportTitle + "(start from "
+ this.reportStartDate + ")</h3>")
.append("<table border=\"1\">")
.append("<tr><td><b>Key</b>\t</td><td><b>Count</b></td><td><b>Average Cost(ms)</b></td></tr>\n");
// for (Entry<String, SumObject> record : map.entrySet()) {
for(SumObject record: map.values()) {
buf.append("<tr><td>").append(record.getKey());
buf.append("</td><td>").append(record.accessCount);
buf.append("</td><td>")
.append(formatLong(record.costTime.get() / 1000000))
.append("</td></tr>\n");
totalCount += record.accessCount.get();
totolCost += record.costTime.get();
}
buf.append("</table>");
buf.append("<h3>Report Summary</h3>");
buf.append("<br>Total Count: \n").append(totalCount);
buf.append("<br>Total Cost Time: \n").append(
formatLong(totolCost / 1000000));
if (totalCount != 0) {
buf.append("<br>Average Execute Cost Time: \n").append(
formatLong(totolCost / totalCount / 1000000));
}
buf.append("<hr>\n");
return buf.toString();
}
}
| true |
22e8c56b92c377f8e1aacaae8cda594b8dcee763
|
Java
|
vaibhavsabnis/problem_practise
|
/src/interview/prep/leetcode/aug20/RottenOranges.java
|
UTF-8
| 2,214 | 4.03125 | 4 |
[] |
no_license
|
package interview.prep.leetcode.aug20;
/*
* Rotting Oranges
Solution
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] is only 0, 1, or 2.
*/
import java.util.HashSet;
public class RottenOranges {
public int orangesRotting(int[][] grid) {
HashSet<String> fresh = new HashSet<>();
HashSet<String> rotten = new HashSet<>();
for(int i=0; i< grid.length;i++) {
for(int j=0; j<grid[i].length;j++) {
if(grid[i][j] ==1)
fresh.add(""+i+j);
if(grid[i][j] ==2)
rotten.add(""+i+j);
}
}
//performing BFS
int min = 0;
int[][] directions = {{1,0},{-1,0},{0,1},{0,-1}};
while(fresh.size()>0) {
HashSet<String> infected = new HashSet<>();
for(String rot: rotten) {
int i= Character.getNumericValue(rot.charAt(0));
int j= Character.getNumericValue(rot.charAt(1));
for(int[] direction: directions) {
int nextI = i+ direction[0];
int nextJ = j+ direction[1];
String coordinate = ""+nextI+nextJ;
if(fresh.contains(coordinate)) {
fresh.remove(coordinate);
infected.add(coordinate);
}
}
}
if(infected.size() ==0)
return -1;
rotten = infected;
min++;
}
return min;
}
public static void main(String[] args) {
int[][] grid = {{2,1,1},
{0,1,1},
{1,0,1},
};
RottenOranges ro = new RottenOranges();
ro.orangesRotting(grid);
}
}
| true |
0595d4e9895dc98fe6be4e65f2811e3dc4b6a194
|
Java
|
shawnHsx/spring-boot
|
/src/main/java/com/semion/example/sample/controller/FileUploadController.java
|
UTF-8
| 893 | 2.359375 | 2 |
[] |
no_license
|
package com.semion.example.sample.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Created by heshuanxu on 2018/7/27.
*/
@Slf4j
@RestController
public class FileUploadController {
public String singleUpload(@RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
String filename = file.getOriginalFilename();
Path path = Paths.get("./" + filename);
Files.write(path, bytes);
} catch (IOException e) {
log.error("文件上传失败:{}", e);
}
return "success";
}
}
| true |
6be8a5dace8cc06d963747f0291f2fa4e7d3439a
|
Java
|
Chubanova/Capstone
|
/app/src/main/java/moera/ermais/google/com/myplaces/OnClickListener.java
|
UTF-8
| 123 | 1.65625 | 2 |
[] |
no_license
|
package moera.ermais.google.com.myplaces;
public interface OnClickListener {
void onClick(double lat, double lng);
}
| true |
2615bafef582035f48c3e8b6b0e1bfdcd57cdb31
|
Java
|
thoughtsynapse/rtg-tools
|
/src/com/rtg/vcf/eval/AnnotatingEvalSynchronizer.java
|
UTF-8
| 4,985 | 1.859375 | 2 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
/*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.vcf.eval;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Set;
import com.rtg.util.io.FileUtils;
import com.rtg.vcf.VcfWriter;
import com.rtg.vcf.VcfWriterFactory;
import com.rtg.vcf.header.VcfHeader;
/**
* Outputs <code>baseline.vcf</code> and <code>calls.vcf</code>, each as original VCF records with additional status annotations.
*/
class AnnotatingEvalSynchronizer extends WithInfoEvalSynchronizer {
private final VcfWriter mBase;
protected final VcfWriter mCalls;
/**
* @param variants the set of variants to evaluate
* @param extractor extractor of ROC scores
* @param outdir the output directory into which result files are written
* @param zip true if output files should be compressed
* @param slope true to output ROC slope files
* @param dualRocs true to output additional ROC curves for allele-matches found in two-pass mode
* @param rocFilters which ROC curves to output
* @param rocCriteria criteria for selecting a favoured ROC point
* @throws IOException if there is a problem opening output files
*/
AnnotatingEvalSynchronizer(VariantSet variants,
RocSortValueExtractor extractor,
File outdir, boolean zip, boolean slope, boolean dualRocs, Set<RocFilter> rocFilters, RocPointCriteria rocCriteria) throws IOException {
super(variants, extractor, outdir, zip, slope, dualRocs, rocFilters, rocCriteria);
final String zipExt = zip ? FileUtils.GZ_SUFFIX : "";
final VcfHeader bh = variants.baselineHeader().copy();
final VcfWriterFactory vf = new VcfWriterFactory().zip(zip).addRunInfo(true);
CombinedEvalSynchronizer.addInfoHeaders(bh, VariantSetType.BASELINE);
mBase = vf.make(bh, new File(outdir, "baseline.vcf" + zipExt));
final VcfHeader ch = variants.calledHeader().copy();
CombinedEvalSynchronizer.addInfoHeaders(ch, VariantSetType.CALLS);
mCalls = vf.make(ch, new File(outdir, "calls.vcf" + zipExt));
}
@Override
protected void handleUnknownBaseline() throws IOException {
setNewInfoFields(mBrv, updateForBaseline(true, new LinkedHashMap<>()));
mBase.write(mBrv);
}
@Override
protected void handleUnknownCall() throws IOException {
setNewInfoFields(mCrv, updateForCall(true, new LinkedHashMap<>()));
mCalls.write(mCrv);
}
@Override
protected void handleUnknownBoth(boolean unknownBaseline, boolean unknownCall) throws IOException {
if (unknownBaseline) {
setNewInfoFields(mBrv, updateForBaseline(true, new LinkedHashMap<>()));
mBase.write(mBrv);
mBrv = null;
}
if (unknownCall) {
setNewInfoFields(mCrv, updateForCall(true, new LinkedHashMap<>()));
mCalls.write(mCrv);
mCrv = null;
}
}
@Override
protected void handleKnownBaseline() throws IOException {
setNewInfoFields(mBrv, updateForBaseline(false, new LinkedHashMap<>()));
mBase.write(mBrv);
}
@Override
protected void handleKnownCall() throws IOException {
setNewInfoFields(mCrv, updateForCall(false, new LinkedHashMap<>()));
mCalls.write(mCrv);
}
@Override
protected void handleKnownBoth() throws IOException {
// Just deal with the call side first, and let the baseline call take care of itself
handleKnownCall();
}
@Override
@SuppressWarnings("try")
public void close() throws IOException {
// Try-with-resources for nice closing side effects
try (VcfWriter ignored = mBase;
VcfWriter ignored2 = mCalls) {
super.close();
}
}
}
| true |
77d3afaaaf3756d1760690f7090c2a7934c248ac
|
Java
|
danvoss/Minicraft
|
/core/src/com/dvoss/MyGdxGame.java
|
UTF-8
| 6,319 | 2.40625 | 2 |
[] |
no_license
|
package com.dvoss;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import java.util.Random;
import static com.badlogic.gdx.Gdx.input;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
TextureRegion down, up, stand, right, left, tree, zombie_u, zombie_d, zombie_r, zombie_l, zombie_s, jelly1, jelly2;
float x, y, xv, yv, zom_x, zom_y, zom_xv, zom_yv, jel_y, jel_x, jel_yv, jel_xv;
BitmapFont font;
static final float MAX_VELOCITY = 100;
static final float DECELERATION = 0.5f;
static final int WIDTH = 16;
static final int HEIGHT = 16;
@Override
public void create () {
batch = new SpriteBatch();
Texture tiles = new Texture("tiles.png");
TextureRegion[][] treeGrid = TextureRegion.split(tiles, WIDTH / 2, HEIGHT / 2);
TextureRegion[][] grid = TextureRegion.split(tiles, 16, 16);
down = grid[6][0];
up = grid[6][1];
stand = grid[6][2];
right = grid[6][3];
left = new TextureRegion(right);
left.flip(true, false);
tree = treeGrid[1][0];
tree.setRegionWidth(WIDTH);
tree.setRegionHeight(HEIGHT);
zombie_s = grid[6][6];
zombie_u = grid[6][5];
zombie_d = grid[6][4];
zombie_r = grid[6][7];
zombie_l = new TextureRegion(zombie_r);
zombie_l.flip(true, false);
jelly1 = grid[7][4];
jelly2 = grid[7][5];
}
@Override
public void render () {
move();
TextureRegion img;
if (yv < 0) {
img = down;
}
else if (yv > 0) {
img = up;
}
else if (xv > 0) {
img = right;
}
else if (xv < 0) {
img = left;
}
else {
img = stand;
}
if (x < 0) {
x = 600;
}
if (x > 600) {
x = 0;
}
if (y < 0) {
y = 600;
}
if (y > 600) {
y = 0;
}
moveZombie();
TextureRegion z_img;
if (zom_yv < 0) {
z_img = zombie_d;
}
else if (zom_yv > 0) {
z_img = zombie_u;
}
else if (zom_xv > 0) {
z_img = zombie_r;
}
else if (zom_xv < 0) {
z_img = zombie_l;
}
else z_img = zombie_s;
if (zom_x < 0) {
zom_x = 600;
}
if (zom_x > 600) {
zom_x = 0;
}
if (zom_y < 0) {
zom_y = 600;
}
if (zom_y > 600) {
zom_y = 0;
}
moveJelly();
TextureRegion j_img;
if (jel_yv > 0) {
j_img = jelly1;
}
else {
j_img = jelly2;
}
if (jel_x < 0) {
jel_x = 600;
}
if (jel_x > 600) {
jel_x = 0;
}
if (jel_y < 0) {
jel_y = 600;
}
if (jel_y > 600) {
jel_y = 0;
}
Sound sound1 = Gdx.audio.newSound(Gdx.files.internal("death.wav"));
if ((Math.abs(x - zom_x) < 10) && (Math.abs(y - zom_y) < 10)) {
sound1.play(1.0f);
}
Sound sound2 = Gdx.audio.newSound(Gdx.files.internal("pickup.wav"));
if ((Math.abs(x - 300) < 8) && (Math.abs(y - 300) < 8) || (Math.abs(x - 195) < 8) && (Math.abs(y - 453) < 8)
|| (Math.abs(x - 547) < 8) && (Math.abs(y - 234) < 8) || (Math.abs(x - 222) < 8) && (Math.abs(y - 123)
< 8) || (Math.abs(x - 432) < 8) && (Math.abs(y - 564) < 8) || (Math.abs(x - 100) < 8) && (Math.abs(y
- 80) < 8) || (Math.abs(x - 80) < 8) && (Math.abs(y - 300) < 8) || (Math.abs(x - 520) < 8) &&
(Math.abs(y - 80) < 8)) {
sound2.play(1.0f);
}
Sound sound3 = Gdx.audio.newSound(Gdx.files.internal("playerhurt.wav"));
if ((Math.abs(x - jel_x) < 10) && (Math.abs(y - jel_y) < 10)) {
sound3.play(1.0f);
}
BitmapFont font = new BitmapFont();
CharSequence obj = "Run through the trees to power up, and avoid the dangerous Blob and deadly Zombie!";
Gdx.gl.glClearColor(0, 1, 0.4f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, obj, 25, 25);
batch.draw(img, x, y, WIDTH * 2, HEIGHT * 2);
batch.draw(z_img, zom_x, zom_y, WIDTH * 2, HEIGHT * 2);
batch.draw(j_img, jel_x, jel_y, WIDTH * 2, HEIGHT * 2);
batch.draw(tree, 300, 300, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.draw(tree, 195, 453, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.draw(tree, 547, 234, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.draw(tree, 222, 123, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.draw(tree, 432, 564, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.draw(tree, 100, 80, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.draw(tree, 80, 300, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.draw(tree, 520, 80, WIDTH * 1.5f, HEIGHT * 1.5f);
batch.end();
}
public void move() {
if (input.isKeyPressed(Input.Keys.UP)) {
yv = MAX_VELOCITY;
}
else if (input.isKeyPressed(Input.Keys.DOWN)) {
yv = -MAX_VELOCITY;
}
if (input.isKeyPressed(Input.Keys.RIGHT)) {
xv = MAX_VELOCITY;
}
else if (input.isKeyPressed((Input.Keys.LEFT))) {
xv = -MAX_VELOCITY;
}
if (input.isKeyPressed(Input.Keys.SPACE)) {
if (input.isKeyPressed(Input.Keys.UP)) {
yv = MAX_VELOCITY * 2;
}
else if (input.isKeyPressed(Input.Keys.DOWN)) {
yv = -MAX_VELOCITY * 2;
}
if (input.isKeyPressed(Input.Keys.RIGHT)) {
xv = MAX_VELOCITY * 2;
}
else if (input.isKeyPressed((Input.Keys.LEFT))) {
xv = -MAX_VELOCITY * 2;
}
}
float delta = Gdx.graphics.getDeltaTime();
y += yv * delta;
x += xv * delta;
yv = decelerate(yv);
xv = decelerate(xv);
}
public float decelerate(float velocity) {
velocity *= DECELERATION;
if (Math.abs(velocity) < 1) {
velocity = 0;
}
return velocity;
}
public void moveZombie() {
float delta = Gdx.graphics.getDeltaTime();
zom_y += zom_yv * delta;
zom_x += zom_xv * delta;
Random random = new Random();
if (random.nextBoolean()) {
zom_yv = MAX_VELOCITY/1.5f;
}
else if (!random.nextBoolean()) {
zom_yv = -MAX_VELOCITY/1.5f;
}
if (random.nextBoolean()) {
zom_xv = MAX_VELOCITY/1.5f;
}
else if (!random.nextBoolean()) {
zom_xv = -MAX_VELOCITY/1.5f;
}
}
public void moveJelly() {
float delta = Gdx.graphics.getDeltaTime();
jel_y += jel_yv * delta;
jel_x += jel_xv * delta;
Random random = new Random();
if (random.nextBoolean()) {
jel_yv = MAX_VELOCITY;
}
else if (!random.nextBoolean()) {
jel_yv = -MAX_VELOCITY;
}
if (random.nextBoolean()) {
jel_xv = MAX_VELOCITY;
}
else if (!random.nextBoolean()) {
jel_xv = -MAX_VELOCITY;
}
}
}
| true |
e5872c9e2145abfc88bbf16a38b17a5396439d0a
|
Java
|
roomanl/Aria
|
/Aria/src/main/java/com/arialyy/aria/core/inf/AbsGroupEntity.java
|
UTF-8
| 2,191 | 2.078125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arialyy.aria.core.inf;
import android.os.Parcel;
import android.os.Parcelable;
import com.arialyy.aria.orm.annotation.Unique;
import java.util.ArrayList;
import java.util.List;
/**
* Created by AriaL on 2017/6/3.
*/
public abstract class AbsGroupEntity extends AbsEntity implements Parcelable {
/**
* 组名,组名为任务地址相加的url的Md5
*/
@Unique protected String groupHash;
/**
* 任务组别名
*/
private String alias;
/**
* 任务组下载文件的文件夹地址
*/
@Unique private String dirPath;
/**
* 子任务url地址
*/
private List<String> urls = new ArrayList<>();
public String getDirPath() {
return dirPath;
}
public void setDirPath(String dirPath) {
this.dirPath = dirPath;
}
public List<String> getUrls() {
return urls;
}
public void setUrls(List<String> urls) {
this.urls = urls;
}
public String getGroupHash() {
return groupHash;
}
public String getAlias() {
return alias;
}
@Override public String getKey() {
return groupHash;
}
public void setAlias(String alias) {
this.alias = alias;
}
public AbsGroupEntity() {
}
@Override public int describeContents() {
return 0;
}
@Override public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(this.groupHash);
dest.writeString(this.alias);
}
protected AbsGroupEntity(Parcel in) {
super(in);
this.groupHash = in.readString();
this.alias = in.readString();
}
}
| true |
37cb17e9c522e25541d74deb12b3d0edb85cda8b
|
Java
|
kfeedu/GalleryWithAudioPlayer
|
/app/src/main/java/pl/kfeed/gallerywithmusicplayer/Constants.java
|
UTF-8
| 856 | 1.640625 | 2 |
[] |
no_license
|
package pl.kfeed.gallerywithmusicplayer;
public class Constants {
//Column ID's in Thumb/Image Cursor
public static final int CURSOR_THUMB_PATH = 0;
public static final int CURSOR_IMAGE_ID = 1;
public static final int CURSOR_IMAGE_TITLE = 2;
public static final int CURSOR_IMAGE_DESC = 3;
public static final int CURSOR_IMAGE_DATE = 4;
public static final int CURSOR_IMAGE_NAME = 5;
public static final int CURSOR_IMAGE_PATH = 6;
//Intent keys
public static final String PHOTO_FILTER_INTENT_PHOTO_PATH = "photoToEdit";
public static final String SONG_ACTIVITY_INTENT_POSITION = "songPosition";
//App directory
public static final String PHOTO_SAVING_DIRECTORY = "GalleryProcessedImages";
//GallerySavedStateKeys
public static final String POPUP_SAVE_STATE_POSITION_KEY = "popupPosition";
}
| true |
b822424575858fed9aaf2786585c5a579a1fdd47
|
Java
|
vldzm1015/javabasic
|
/GUI/src/a_sample/CardLayoutEx.java
|
UTF-8
| 863 | 3.171875 | 3 |
[] |
no_license
|
package a_sample;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutEx extends JFrame
{
PanA panA = new PanA();
PanB panB = new PanB();
JPanel pan = new JPanel();
CardLayout card;
JButton btn = new JButton("확인");
CardLayoutEx()
{
card = new CardLayout();
pan.setLayout( card );
pan.add("1", panA );
pan.add("2", panB );
add( pan, BorderLayout.CENTER );
add( btn, BorderLayout.NORTH );
setSize( 300, 400 );
setVisible( true );
btn.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent ev ){
card.show( pan, "2");
}
});
}
public static void main(String[] args)
{
new CardLayoutEx();
}
}
class PanA extends JPanel
{
PanA()
{
setBackground( Color.red );
}
}
class PanB extends JPanel
{
PanB()
{
setBackground( Color.yellow );
}
}
| true |
0fc7ffc32ce86033adb1e5c5b7571f115cd93d91
|
Java
|
kimseho91/homework
|
/bank/servicesimpl/MemberServiceImpl.java
|
UTF-8
| 3,635 | 2.625 | 3 |
[] |
no_license
|
package com.bitcamp.bank.servicesimpl;
import com.bitcamp.bank.domains.AdminBean;
import com.bitcamp.bank.domains.CustomerBean;
import com.bitcamp.bank.domains.MemberBean;
import com.bitcamp.bank.services.MemberService;
public class MemberServiceImpl implements MemberService {
private AdminBean admin = new AdminBean();
private CustomerBean customer = new CustomerBean();
private CustomerBean[] customers;
private AdminBean[] admins;
private int cusCount;
private int admCount;
public MemberServiceImpl() {
customers = new CustomerBean[10];
admins = new AdminBean[10];
cusCount = 0;
admCount = 0;
}
@Override
public void join(CustomerBean param) {
if (existId(param.getId()) == true) {
customers[cusCount] = param;
cusCount++;
}
}
@Override
public void resister(AdminBean param) {
// TODO Auto-generated method stub
}
@Override
public CustomerBean[] findAllCustomers() {
return customers;
}
@Override
public AdminBean[] findAllAdmins() {
return admins;
}
@Override
public MemberBean[] findByName(String name) {
int j = 0;
for (int i = 0; i < cusCount; i++) {
if (name.equals(customers[i].getName())) {
j++;
break;
}
}
int k = 0;
for (int i = 0; i < admCount; i++) {
if (name.equals(admins[i].getName())) {
k++;
break;
}
}
int count1 = 0, count2 = 0;
MemberBean[] members = new MemberBean[j + k];
for (int i = 0; i < cusCount; i++) {
if (name.equals(customers[i].getName())) {
members[i] = customers[i];
count1++;
if (count1 == j) {
break;
}
}
}
for (int i = 0; i < admCount; i++) {
if (name.equals(admins[i].getName())) {
members[j + i] = admins[i];
count2++;
if (count2 == k) {
break;
}
}
}
return members;
}
@Override
public MemberBean findById(String id) {
MemberBean members = new MemberBean();
for (int i = 0; i < cusCount; i++) {
if (id.equals(customers[i].getId())) {
members = customers[i];
break;
}
}
for (int i = 0; i < admCount; i++) {
if (id.equals(admins[i].getId())) {
members = admins[i];
break;
}
}
return members;
}
@Override
public boolean login(MemberBean param) {
boolean flag = false;
if (findById(param.getId()).equals(param.getPw())) {
flag = true;
}
return flag;
}
@Override
public int countMembers() {
return cusCount;
}
@Override
public int countAdmins() {
return admCount;
}
@Override
public boolean existId(String id) {
boolean flag = true;
for (int i = 0; i < cusCount; i++) {
if (id.equals(customers[i].getId())) {
flag = false;
}
}
return flag;
}
@Override
public void updatePass(MemberBean param) {
String loginId = param.getId();
String loginPw = param.getPw();
String[] arr = loginPw.split(",");
String oldPw = arr[0];
String newPw = arr[1];
System.out.println(arr[0] + arr[1]);
if (login(param)) {
for (int i = 0; i < cusCount; i++) {
if (loginId.equals(customers[i].getId())) {
customers[i].setPw(newPw);
break;
}
}
for (int i = 0; i < admCount; i++) {
if (loginId.equals(admins[i].getId())) {
admins[i].setPw(newPw);
break;
}
}
}
}
@Override
public void deleteMember(MemberBean param) {
if (login(param)) {
for (int i = 0; i < cusCount; i++) {
if (param.getId().equals(customers[i].getId())) {
customers[i] = customers[cusCount - 1];
cusCount--;
break;
}
}
for (int i = 0; i < admCount; i++) {
if (param.getId().equals(admins[i].getId())) {
admins[i] = admins[admCount - 1];
admCount--;
break;
}
}
}
}
}
| true |
f255e334271c7fdec29e375bffe91da964dab9a1
|
Java
|
yomea/javase
|
/enum/TestNume.java
|
UTF-8
| 627 | 2.703125 | 3 |
[] |
no_license
|
public class TestNume{
public enum MydoorOpen {me, myWife,myFather,myMother,mySister,mySon,myDaugter};
public static void main(String[] agrs) {
int i=0;
MydoorOpen m = MydoorOpen.myWife;
switch(m) {
case me : System.out.println("me");
break;
case myWife : System.out.println("myWife");
break;
case myFather : System.out.println("myFather");
break;
case myMother : System.out.println("myMother");
break;
case mySon : System.out.println("mySon");
break;
case myDaugter : System.out.println("myDaugter");
break;
default : System.out.println("null"); }
}
}
| true |
a8babd62f3ed25448c44b991042c3b08a85cac2a
|
Java
|
Jaramos2409/RunningGame
|
/core/src/cs3340/project/runninggame/UI/EndMenuOptions.java
|
UTF-8
| 5,208 | 2.984375 | 3 |
[] |
no_license
|
package cs3340.project.runninggame.UI;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import cs3340.project.runninggame.RunningGame;
import cs3340.project.runninggame.Screens.GameScreen;
import cs3340.project.runninggame.Screens.HighScoresScreen;
import cs3340.project.runninggame.Screens.MainMenuScreen;
/**
* Sets up all the buttons, messages, and pushes them onto a table
* for proper formatting.
* @author Jesus Ramos
* @version 0.1
* @since 11/28/2015
*/
public class EndMenuOptions {
final RunningGame game;
long raceFinalTime;
private Table endMenuOptionsTable;
private Skin skin;
private Label timeMsg;
private TextButton playAgainBtn;
private TextButton returnBtn;
private TextButton highScoresBtn;
private TextButton quitBtn;
/**
* Initializes all the materials needed for the menu options
* @param gam the single RunningGame instance.
* @param rFT the final race time.
*/
public EndMenuOptions(RunningGame gam, long rFT) {
this.game = gam;
this.raceFinalTime = rFT;
initSkin();
initLabels();
initButtons();
initTable();
}
/**
* @return the single RunningGame Instance
*/
public RunningGame getGame() {
return game;
}
/**
* @return the endMenuOptionsTable
*/
public Table getEndMenuOptionsTable() {
return endMenuOptionsTable;
}
/**
* Loads the skin style that will be used to style the buttons and messages
* to be rendered on the screen.
*/
public void initSkin () {
skin = new Skin(Gdx.files.internal("ui/uiskin.json")
,new TextureAtlas(Gdx.files.internal("ui/uiskin.atlas")));
}
/**
* Initializes all the labels which will be used to render messages on the screen.
*/
public void initLabels() {
timeMsg = new Label("Final Time: " + ((double)raceFinalTime/1000.0), skin, "default");
timeMsg.setAlignment(Align.center, Align.center);
timeMsg.setFontScale(5);
}
/**
* Initializes all buttons which will be used to give the player options to press
* on the screen.
*/
private void initButtons() {
playAgainBtn = new TextButton("Play Again", skin, "default");
playAgainBtn.setWidth(200f);
playAgainBtn.setHeight(20f);
playAgainBtn.getLabel().setFontScale(3);
playAgainBtn.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new GameScreen(game));
}
});
returnBtn = new TextButton("Return to Main Menu", skin, "default");
returnBtn.setWidth(200f);
returnBtn.setHeight(20f);
returnBtn.getLabel().setFontScale(3);
returnBtn.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new MainMenuScreen(game));
}
});
highScoresBtn = new TextButton("Check High Scores", skin, "default");
highScoresBtn.setWidth(200f);
highScoresBtn.setHeight(20f);
highScoresBtn.getLabel().setFontScale(3);
highScoresBtn.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new HighScoresScreen(game));
}
});
quitBtn = new TextButton("Quit", skin, "default");
quitBtn.setWidth(200f);
quitBtn.setHeight(20f);
quitBtn.getLabel().setFontScale(3);
quitBtn.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
}
/**
* Initializes the table that is used to format all the buttons and messages into a
* neat table format for the page.
*/
public void initTable() {
endMenuOptionsTable = new Table();
endMenuOptionsTable.setFillParent(true);
endMenuOptionsTable.defaults().width(600).height(100);
endMenuOptionsTable.add(timeMsg).expandX();
endMenuOptionsTable.row().fill();
endMenuOptionsTable.add().expandX();
endMenuOptionsTable.row().fill();
endMenuOptionsTable.add(playAgainBtn).expandX();
endMenuOptionsTable.row().fill();
endMenuOptionsTable.add(returnBtn).expandX();
endMenuOptionsTable.row().fill();
endMenuOptionsTable.add(highScoresBtn).expandX();
endMenuOptionsTable.row().fill();
endMenuOptionsTable.add(quitBtn).expandX();
endMenuOptionsTable.setDebug(false);
endMenuOptionsTable.setVisible(true);
}
}
| true |
f8f94fc5a8ccd838f8a140fa865c61de7fe1f62d
|
Java
|
SergioLH/CMU
|
/CMU/src/main/java/vista/ListarUsuariosController.java
|
UTF-8
| 9,481 | 2.3125 | 2 |
[] |
no_license
|
package main.java.vista;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import main.java.cmu.Usuario;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@SuppressWarnings("ALL")
public class ListarUsuariosController {
@FXML
private JFXButton botonEditar;
@FXML
private JFXButton botonEliminar;
@FXML
private JFXButton botonCrearFactura;
@FXML
private JFXButton botonVolverMenu;
@FXML
TableView<Usuario> tablaListarUsuario;
@FXML
TableColumn<Usuario, String> columnaDNI;
@FXML
TableColumn<Usuario, String> columnaNombre;
@FXML
TableColumn<Usuario, String> columnaApellidos;
@FXML
TableColumn<Usuario, String> columnaTipo;
private ObservableList<Usuario> data = FXCollections.observableArrayList(
);
public void setData(ObservableList<Usuario> data) {
this.data = data;
tablaListarUsuario.setItems(data);
}
@FXML
private void initialize() {
columnaDNI.setCellValueFactory(celda -> celda.getValue().dniProperty());
columnaNombre.setCellValueFactory(celda -> celda.getValue().nombreProperty());
columnaApellidos.setCellValueFactory(celda -> celda.getValue().apellidosProperty());
columnaTipo.setCellValueFactory(celda -> celda.getValue().tipoUsuarioProperty());
tablaListarUsuario.setItems(data);
}
@FXML
private void botonEditar() {
Task<Void> tarea = new Task<Void>() {
@Override
protected Void call() throws Exception {
editar();
return null;
}
};
tarea.setOnFailed(event -> {
event.getSource().getException().printStackTrace();
});
new Thread(tarea).start();
}
private void editar() throws IOException {
Usuario usuario = tablaListarUsuario.getSelectionModel().getSelectedItem();
if (usuario != null) {
Stage ventana = MainApp.primaryStage;
Platform.runLater(() -> {
Scene escena = ventana.getScene();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("Editar.fxml"));
Usuario seleccionado = tablaListarUsuario.getSelectionModel().getSelectedItem();
try {
Pane p = loader.load();
EditarController controlador = loader.getController();
controlador.setTipo(seleccionado.getTipoUsuario());
escena.setRoot(p);
} catch (IOException e) {
e.printStackTrace();
}
});
} else {
URL url = new URL("http://5b04451e0f8d4c001440b0df.mockapi.io/MensajeError");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error: HTTP codigo error: " + connection.getResponseCode());
}
JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject(jsonTokener);
System.out.println(jsonObject.get("mensaje"));
connection.disconnect();
}
}
@FXML
private void botonEliminar() throws IOException {
Task<Void> tarea = new Task<Void>() {
@Override
protected Void call() throws Exception {
eliminar();
Usuario usuario = tablaListarUsuario.getSelectionModel().getSelectedItem();
tablaListarUsuario.getItems().remove(usuario);
return null;
}
};
new Thread(tarea).start();
}
private void eliminar() throws IOException {
Usuario usuario = tablaListarUsuario.getSelectionModel().getSelectedItem();
int idEliminar = usuario.getId();
if (usuario == null) {
URL url = new URL("http://5b04451e0f8d4c001440b0df.mockapi.io/MensajeError");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error: HTTP codigo error: " + connection.getResponseCode());
}
JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject(jsonTokener);
System.out.println(jsonObject.get("mensaje"));
connection.disconnect();
} else {
URL url = new URL("http://5b04451e0f8d4c001440b0df.mockapi.io/ListaUsuarios/" + idEliminar);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() == 200) {
System.out.println("OK");
} else {
System.out.println(connection.getResponseCode());
System.out.println("ERROR");
}
JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject(jsonTokener);
connection.disconnect();
}
}
@FXML
private void botonCrearFactura() {
Task<Void> tarea = new Task<Void>() {
@Override
protected Void call() throws Exception {
crearFactura();
return null;
}
};
tarea.setOnFailed(event -> {
event.getSource().getException().printStackTrace();
});
tarea.setOnFailed(event -> {
event.getSource().getException().printStackTrace();
});
new Thread(tarea).start();
}
private void crearFactura() throws IOException {
Usuario usuario = tablaListarUsuario.getSelectionModel().getSelectedItem();
if (usuario != null) {
URL url = new URL("http://5b04451e0f8d4c001440b0df.mockapi.io/FacturaCreada");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error: HTTP codigo error: " + connection.getResponseCode());
}
JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject(jsonTokener);
System.out.println(jsonObject.get("mensaje"));
connection.disconnect();
} else {
URL url = new URL("http://5b04451e0f8d4c001440b0df.mockapi.io/MensajeError");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error: HTTP codigo error: " + connection.getResponseCode());
}
JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject(jsonTokener);
System.out.println(jsonObject.get("mensaje"));
connection.disconnect();
}
}
@FXML
private void botonVolverMenu() {
Task<Void> tarea = new Task<Void>() {
@Override
protected Void call() throws Exception {
Stage ventana = MainApp.primaryStage;
Platform.runLater(() -> {
Scene escena = ventana.getScene();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("MenuEncargado.fxml"));
try {
escena.setRoot(loader.load());
} catch (IOException e) {
e.printStackTrace();
}
});
return null;
}
};
tarea.setOnFailed(event -> {
event.getSource().getException().printStackTrace();
});
new Thread(tarea).start();
}
}
| true |
78b160c610c2352fcb58fbeb93c54ec0c0b1be7c
|
Java
|
BackupTheBerlios/opencad-org-svn
|
/trunk/org.opencad.core/src/org/opencad/ui/editor/DeleteActionDelegate.java
|
UTF-8
| 709 | 1.914063 | 2 |
[] |
no_license
|
package org.opencad.ui.editor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
public class DeleteActionDelegate implements IEditorActionDelegate {
private GLEditor editor;
public void setActiveEditor(IAction action, IEditorPart targetEditor) {
if (targetEditor instanceof GLEditor) {
editor = (GLEditor) targetEditor;
action.setEnabled(true);
} else {
action.setEnabled(false);
}
}
public void run(IAction action) {
new DeletePrimitiveState(editor).freshen();
}
public void selectionChanged(IAction action, ISelection selection) {
}
}
| true |
96a969122ae71b3d356398e49d12cb6f09dc2bae
|
Java
|
BoazTene/FileIndexing
|
/src/Score/Score.java
|
UTF-8
| 705 | 2.90625 | 3 |
[] |
no_license
|
package Score;
import Score.Filters.ScoreFilter;
import java.io.IOException;
/**
* @author Boaz Tene
*
*/
public class Score {
private final String path;
private final ScoreFilter[] scoreFilters;
public Score(ScoreFilter[] scoreFilters, String path) {
this.path = path;
this.scoreFilters = scoreFilters;
}
private int getFilterScore(ScoreFilter filter) throws IOException {
return filter.getScore(this.path);
}
public int getScore() throws IOException {
int scoreAverage = 0;
for (ScoreFilter filter : this.scoreFilters) {
scoreAverage += getFilterScore(filter);
System.out.println(scoreAverage);
}
scoreAverage /= this.scoreFilters.length;
return scoreAverage;
}
}
| true |
5b5d43ca9692dcfb6170c0c8643cf849786af798
|
Java
|
MelindaSW/relay-writer
|
/relay-writer-api/src/test/java/se/melindasw/relaywriter/user/UserControllerTests.java
|
UTF-8
| 5,624 | 2.0625 | 2 |
[] |
no_license
|
package se.melindasw.relaywriter.user;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import se.melindasw.relaywriter.role.RoleRepo;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc
public class UserControllerTests {
@Autowired private MockMvc mockMvc;
@Autowired private UserController controller;
@Autowired ObjectMapper objectMapper;
@MockBean UserService service;
@MockBean UserRepo userRepo;
@MockBean RoleRepo roleRepo;
LocalDateTime timeStampNow = LocalDateTime.now();
LocalDateTime stillTimeStamp = LocalDateTime.of(2000, 5, 11, 1, 2);
public UserControllerTests() {}
@Test
public void contextLoads() {
assertThat(controller).isNotNull();
}
@Test
public void testAddUser() throws Exception {
NewUserDTO newUser = new NewUserDTO(0L, "Username", "[email protected]", "pwdpwd", timeStampNow);
UserDTO expectedResponse = new UserDTO(1L, "Username", "[email protected]", timeStampNow);
doReturn(expectedResponse).when(service).addUser(any());
mockMvc
.perform(
post("/users/add")
.content(asJsonString(newUser))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.userName").exists())
.andExpect(jsonPath("$.email").exists())
.andExpect(jsonPath("$.createdAt").exists());
}
@Test
public void testAddUserWithIncorrectRequest() throws Exception {
// Any missing value in the new user should return status code 400
NewUserDTO newIncorrectUserNullName =
new NewUserDTO(0L, null, "[email protected]", "pwd", timeStampNow);
NewUserDTO newIncorrectUserNullEmail =
new NewUserDTO(0L, "username", null, "pwd", timeStampNow);
NewUserDTO newIncorrectUserNullPassword =
new NewUserDTO(0L, "username", "[email protected]", null, timeStampNow);
mockMvc
.perform(
post("/users/add")
.content(asJsonString(newIncorrectUserNullName))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
mockMvc
.perform(
post("/users/add")
.content(asJsonString(newIncorrectUserNullEmail))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
mockMvc
.perform(
post("/users/add")
.content(asJsonString(newIncorrectUserNullPassword))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
public void testGetAllUsers() throws Exception {
List<UserDTO> expectedResponse = new ArrayList<>();
UserDTO user1 = new UserDTO();
UserDTO user2 = new UserDTO();
expectedResponse.add(user1);
expectedResponse.add(user2);
doReturn(expectedResponse).when(service).getAllUsers();
MockHttpServletResponse response =
mockMvc.perform(get("/users/get-all")).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(asJsonString(expectedResponse));
}
@Test
public void testGetOneUser() throws Exception {
UserDTO expectedResponse = new UserDTO(1L, "useruser", "[email protected]", null);
when(service.getUserByID(1L)).thenReturn(expectedResponse);
MockHttpServletResponse response =
mockMvc.perform(get("/users/get-one/1")).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(asJsonString(expectedResponse));
}
@Test
public void testDeleteOneUser() throws Exception {
long userId = 1L;
String responseMsg = "User with id " + userId + " was deleted";
when(service.deleteUser(userId)).thenReturn(responseMsg);
MockHttpServletResponse response =
mockMvc.perform(delete("/users/delete/{id}", 1)).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(responseMsg);
}
@Test
public void testUpdateUser() {
}
static String asJsonString(final Object obj) {
try {
String json = new ObjectMapper().writeValueAsString(obj);
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| true |
9952c7fb42e841646b45e285a7f64c189204c9e0
|
Java
|
hyq1995/NettyStaging
|
/netty-common/src/main/java/com/tony/constants/EnumResponseState.java
|
UTF-8
| 199 | 1.726563 | 2 |
[] |
no_license
|
package com.tony.constants;
/**
* @author jiangwenjie 2019/10/22
*/
public enum EnumResponseState {
/**
* 请求成功
*/
success,
/**
* 请求失败
*/
fail
}
| true |
c66d66d60ff3d0025e4e3788ec28ffe20d4b20bd
|
Java
|
satand/Ldapper
|
/src/com/ldapper/data/LDAPPERBeanToXML.java
|
UTF-8
| 707 | 2.328125 | 2 |
[] |
no_license
|
package com.ldapper.data;
import java.io.OutputStream;
import org.w3c.dom.Document;
public interface LDAPPERBeanToXML extends LDAPPERBean {
/**
* Get object in xml format
*
* @return
* XML object format, possible object is {@link String}
*/
public String toXml();
/**
* Write object xml format on an OutputStream
*
* @param stream allowed object is {@link OutputStream}
*/
public void printXml(OutputStream stream);
/**
* Get object in document format
*
* @return
* Document object format, possible object is {@link Document}
*/
public Document toDocument();
}
| true |
cbbca46c9c5c3a258a68c91a1639f46bbee9ff68
|
Java
|
rkinsman/Farcebook
|
/src/main/webapp/WEB-INF/classes/farcebook/FriendRequest.java
|
UTF-8
| 2,452 | 3.28125 | 3 |
[] |
no_license
|
package farcebook;
import java.util.*;
import java.io.*;
/**
A FriendRequest listens for the receiving {@link farcebook.User} object response to another User object's request for friendship. After {@link farcebook.User#requestFriendship} is called, a {@link farcebook.Request} instance is instantiated added the User's ArrayList of Requests.
@author Kevin Cherniawski
*/
public class FriendRequest implements Request{
private User sender;
private User receiver;
private String text;
private String type;
public FriendRequest(User requestingUser, User targetUser){
this.sender = requestingUser;
this.receiver = targetUser;
text = ("<a href = profile.jsp?ID=" + sender.getID() + ">" + sender.getDisplayName() + "</a>" + " wants to be your friend!");
type = "FriendRequest";
}
public String getText(){
return text;
}
public void setText(String text){
this.text = text;
}
public String getType(){
return type;
}
/**
Invoked when the {@link farcebook.User} responds to a specific request. Given Farcebook design, the User has no choice but to accept the request, therefore the sender and receiver both add each other as subscribees and the Request is deleted in any ArrayLists holding requests it previously existed in.
*/
public void accept(){
update();
}
private void update() {
try {
receiver.subscribeTo(sender);
Date date = new Date();
receiver.post("<a href = profile.jsp?ID=" + sender.getID() + ">" + sender.getDisplayName() + "</a>" +
" is now friends with " + "<a href = profile.jsp?ID=" + receiver.getID() + ">" + receiver.getDisplayName() + "</a>", receiver, date);
sender.subscribeTo(receiver);
sender.post("<a href = profile.jsp?ID=" + sender.getID() + ">" + receiver.getDisplayName() + "</a>" +
" is now friends with " + "<a href = profile.jsp?ID=" + sender.getID() + ">" + sender.getDisplayName() +"</a>", sender, date);
}
catch(Exception e) { //Fix to later return some sort of bs
e.printStackTrace();
}
}
/**
Converts the contents of the FriendRequest to a {@link java.lang.String} in order to save it to file. The toString method will save the FriendRequest as follows:
Sender: senderID
Receiver: receiverID
Text: text
@return The string representation of the FriendRequest.
*/
public String toString(){
return ("Type:" + type + "\nSender:" + sender.getID() + "\nReceiver:" + receiver.getID() + "\n"); //Just for compile
}
}
| true |
6f551aeb5dffd77c948a89fa4da788e007a74514
|
Java
|
GClaes/Guillaume_Claes_Maxime_Claes_SalleFitnessProjet
|
/MaSalleFitness/src/presentation/vue/listing/listingCoachs/FormulaireListingCoach.java
|
UTF-8
| 1,897 | 2.8125 | 3 |
[] |
no_license
|
package presentation.vue.listing.listingCoachs;
import business.CoachService;
import business.impl.CandidatServiceImpl;
import business.impl.CoachServiceImpl;
import model.Candidat;
import model.Coach;
import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.util.List;
public class FormulaireListingCoach extends JPanel {
private JList<String>listeCoachs;
private List<Coach> coachs;
private JScrollPane scrollPane;
public FormulaireListingCoach() {
listeCoachs = new JList<>();
scrollPane = new JScrollPane(listeCoachs, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(400,500));
add(scrollPane);
}
public void rafraichir() {
CoachService coachService = CoachServiceImpl.getInstance();
coachs = coachService.listingCoachs();
DecimalFormat decimales = new DecimalFormat();
decimales.setMaximumFractionDigits(2);
String[]values = new String[coachs.size()];
int position = 0;
for(Coach coach : coachs){
values[position] = "<html>Coach: "+coach.getNom()+" "+coach.getPrenom()+"<br>" +
"Salaire hebdomadaire: "+decimales.format(coachService.calculSalaireHebdomadaire(coach.getMatricule()))+"€"+"<br><ul>";
for (Candidat candidat : CandidatServiceImpl.getInstance().candidatsDUnCoach(coach)){
values[position] += " <li>"+"Numéro d'inscription: "+candidat.getNumInscription()+" | "+candidat.getNom()+" "+candidat.getPrenom()+"</li></br>";
}
values[position]+="</ul></html>";
position++;
}
listeCoachs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listeCoachs.setListData(values);
listeCoachs.setFont(new Font("Gras",Font.BOLD,15));
}
}
| true |
f8a388a867de001dbc895704fe1512b59c4c2ebf
|
Java
|
led-os/XgimiAssistantv3.6.0
|
/app/src/main/java/com/xgimi/device/device/GMDevice.java
|
UTF-8
| 4,689 | 2.125 | 2 |
[] |
no_license
|
package com.xgimi.device.device;
import android.util.Log;
import com.xgimi.device.devicedetail.GMdeviceDetail;
import com.xgimi.device.utils.Consants;
/**
* 设备对象 class GMDevice
*
*/
public class GMDevice {
/**
* ip: 设备ip
*/
public String ip;
/**
* name: 设备名字
*/
public String name;
public String phoneIp;
/**
* 设备版本号
* @return
*/
public int version;
/**
* 设备类型
* @return
*/
public String type;
/**
* 机器的具体型号
* @return
*/
public String devicetype;
/**
* 机器的mac地址
* @return
*/
public String mac;
public String getMac(){
return mac;
}
public void setMac(String mac){
this.mac=mac;
}
public String getDevicetype() {
return devicetype;
}
public void setDevicetype(String devicetype) {
this.devicetype = devicetype;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getVersions() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getPhoneIp() {
return phoneIp;
}
public void setPhoneIp(String phoneIp) {
this.phoneIp = phoneIp;
}
public String getZiShengip() {
return ziShengip;
}
public void setZiShengip(String ziShengip) {
this.ziShengip = ziShengip;
}
public String ziShengip;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GMDevice(String ip, String gmdevice) {
this.ip = ip;
this.name = gmdevice;
}
public GMDevice() {
}
public boolean isZhiChi = false;
public boolean isFocusAble() {
if ("full_mstara3".equals(type) || "mango".equals(type) || "mstara3".equals(type) ||
"full_mango".equals(type) || "mstarnapoli".equals(type) || "full_mstarnapoli".equals(type) ||
"full_z4air_business".equals(type) || "z4air".equals(type) || "full_z4air".equals(type) || "z4air_business".equals(type)) {
return false;
} else {
return true;
}
}
/**
*
* @return ture 该设备可以调焦 false 该设备不可以调焦
*
*/
// public boolean isFocusEnabled() {
// for (int i = 0; i < Consants.gmdevicedetails.size(); i++) {
// GMdeviceDetail gMdeviceDetail = Consants.gmdevicedetails.get(i);
// if (gMdeviceDetail.getIp() != null && gMdeviceDetail.type != null) {
// if (getIp().equals(gMdeviceDetail.getIp())) {
// // if(gMdeviceDetail.type.equals("full_mstarnapoli_z4x")||gMdeviceDetail.type.equals("z4x")){
// // return true;
// // }else {
// // return false;
// // }
// Log.e("info", "gMdeviceDetail.type000000000"
// + gMdeviceDetail.type);
// if (getIp().equals(gMdeviceDetail.getIp())) {
// Log.e("info", "gMdeviceDetail.type"
// + gMdeviceDetail.type);
// if (gMdeviceDetail.type.equals("full_mstara3")
// || gMdeviceDetail.type.equals("mango")
// || gMdeviceDetail.type.equals("mstara3")
// || gMdeviceDetail.type.equals("full_mango")
// || gMdeviceDetail.type.equals("mstarnapoli")
// || gMdeviceDetail.type.equals("full_mstarnapoli")
// || gMdeviceDetail.type.equals("full_z4air_business")
// || gMdeviceDetail.type.equals("z4air")
// || gMdeviceDetail.type.equals("full_z4air")||gMdeviceDetail.type.equals("z4air_business")) {
// return false;
// } else {
// return true;
// }
// }
// }
// }
//
// }
// return true;
// }
/**
*
* @return ture 该设备支持一键3D false 该设备不支持一键3D
*
*/
// public boolean isThreeDEnbaled() {
// for (int i = 0; i < Consants.gmdevicedetails.size(); i++) {
// GMdeviceDetail gMdeviceDetail = Consants.gmdevicedetails.get(i);
// if (getIp() != null && gMdeviceDetail.type != null) {
// if (getIp().equals(gMdeviceDetail.getIp())) {
// if (gMdeviceDetail.type.equals("full_mstara3")
// || gMdeviceDetail.type.equals("mango")
// || gMdeviceDetail.type.equals("full_mango")
// || gMdeviceDetail.type.equals("mstarnapoli")) {
// return true;
// } else {
// return false;
// }
// }
// }
// }
// return false;
// }
@Override
public String toString() {
return "GMDevice{" +
"ip='" + ip + '\'' +
", name='" + name + '\'' +
", phoneIp='" + phoneIp + '\'' +
", version=" + version +
", type='" + type + '\'' +
", devicetype='" + devicetype + '\'' +
", mac='" + mac + '\'' +
", ziShengip='" + ziShengip + '\'' +
", isZhiChi=" + isZhiChi +
", isFocusAble = " + isFocusAble() +
'}';
}
}
| true |
f78d2965600491e944176c01775455629911bf34
|
Java
|
alexis779/Algo
|
/src/test/java/org/tech/vineyard/arithmetics/prime/squareroot/ModularSquareRootTest.java
|
UTF-8
| 1,074 | 2.90625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package org.tech.vineyard.arithmetics.prime.squareroot;
import org.junit.jupiter.api.Test;
import org.tech.vineyard.arithmetics.prime.squareroot.ModularSquareRoot;
import org.tech.vineyard.arithmetics.prime.squareroot.TonelliShanksModularSquareRoot;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class ModularSquareRootTest {
@Test
public void squareRoot() {
int p = 11;
ModularSquareRoot modularSquareRoot = new TonelliShanksModularSquareRoot(p);
assertEquals(0, modularSquareRoot.get(0).get());
assertEquals(1, modularSquareRoot.get(1).get());
assertEquals(2, modularSquareRoot.get(4).get());
assertEquals(3, modularSquareRoot.get(9).get());
assertEquals(4, modularSquareRoot.get(5).get());
assertEquals(5, modularSquareRoot.get(3).get());
assertFalse(modularSquareRoot.get(2).isPresent());
}
@Test
public void wikipediaExample() {
assertEquals(13, new TonelliShanksModularSquareRoot(41).get(5).get());
}
}
| true |
9a04702d4202a137a8d8e6db268034a156b950af
|
Java
|
indranilsharma/coreJava
|
/core-Java-Basic-WS/coreJavaBasicExample/src/com/JavaLang/systemClass/Manager2.java
|
UTF-8
| 1,123 | 3.53125 | 4 |
[] |
no_license
|
package com.JavaLang.systemClass;
/*
@param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
* @exception IndexOutOfBoundsException if copying would cause
* access of data outside array bounds.
* @exception ArrayStoreException if an element in the <code>src</code>
* array could not be stored into the <code>dest</code> array
* because of a type mismatch.
* @exception NullPointerException if either <code>src</code> or
* <code>dest</code> is <code>null</code>.
*
public static native void
arraycopy(Object src,int srcPos,Object dest,int destPos,int length);
*/
public class Manager2 {
public static void main(String args[]) {
byte a[] = { 65, 66, 67, 68, 69, 70 };
byte b[] = { 71, 72, 73, 74, 75, 76 };
System.arraycopy(a, 0, b, 0, a.length);
System.out.print(new String(a) + " " + new String(b));
}
}
| true |
2f1991ca73a679906473863b7a9c8a362dc8e145
|
Java
|
KolyasnikovKV/bank
|
/src/main/java/ru/kolyasnikovkv/bank/service/OperationServiceImpl.java
|
UTF-8
| 3,827 | 2.078125 | 2 |
[] |
no_license
|
package ru.kolyasnikovkv.bank.service;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
import ru.kolyasnikovkv.bank.critery.AccountCritery;
import ru.kolyasnikovkv.bank.critery.OperationCritery;
import ru.kolyasnikovkv.bank.entity.Account;
import ru.kolyasnikovkv.bank.entity.Operation;
import ru.kolyasnikovkv.bank.entity.QAccount;
import ru.kolyasnikovkv.bank.entity.QOperation;
import ru.kolyasnikovkv.bank.repository.AccountRepository;
import ru.kolyasnikovkv.bank.repository.OperationRepository;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service("operationservice")
@Transactional
public class OperationServiceImpl extends ACrudService<Operation, Long> implements OperationService{
@Autowired
OperationRepository operationRepository;
@Autowired
AccountRepository accountRepository;
@Override
public CrudRepository<Operation, Long> getRepository() {
return operationRepository;
}
@Override
public List<Operation> findByIdIn(Long[] ids){
OperationCritery critery = new OperationCritery();
critery.ids = Arrays.asList(ids);
return findByCritery(critery);
}
@Override
public List<Operation> findByCritery(OperationCritery critery){
//??? qOperation
QOperation qOperation = QOperation.operation;
List<BooleanExpression> predicates = new ArrayList<>();
if (critery.ids.size() > 0) {
predicates.add(qOperation.id.in(critery.ids));
}
if (critery.clientId != null) {
predicates.add(qOperation.ddate.goe(critery.fromDate));
}
if (critery.clientId != null) {
predicates.add(qOperation.ddate.loe(critery.toDate));
}
if (critery.srcAccountId != null) {
predicates.add(qOperation.srcAccount.id.eq(critery.srcAccountId));
}
if (critery.dstAccountId != null) {
predicates.add(qOperation.dstAccount.id.eq(critery.dstAccountId));
}
BooleanExpression expression = predicates.stream()
//??? optional
.reduce((predicate, accum) -> accum.and(predicate)).orElse(null);
Iterable<Operation> iterAccounts = operationRepository.findAll(expression, new Sort(Sort.Direction.ASC, "name"));
return iterableToList(iterAccounts);
}
public void correctBalance(Account srcAccount, Account dstAccount, BigDecimal amount){
srcAccount = accountRepository.findById(srcAccount.getId()).orElse(null);
dstAccount = accountRepository.findById(dstAccount.getId()).orElse(null);
srcAccount.setBalance(srcAccount.getBalance().subtract(amount));
srcAccount.setBalance(srcAccount.getBalance().add(amount));
}
@Override
public Operation save(Operation operation){
if(operation.getId() != null){
Operation oldOperation = findById(operation.getId());
correctBalance(operation.getSrcAccount(), operation.getDstAccount(), operation.getAmount());
}
correctBalance(operation.getDstAccount(), operation.getSrcAccount(), operation.getAmount());
return super.save(operation);
}
@Override
public void delete(Operation operation){
correctBalance(operation.getDstAccount(), operation.getSrcAccount(), operation.getAmount());
super.delete(operation);
}
@Override
public void delete(Long id){
Operation operation = findById(id);
super.delete(operation);
}
}
| true |
08f7264f06d16bb4801f2499a077ab018768eaa0
|
Java
|
adammurdoch/java-ipc
|
/src/main/java/net/rubygrapefruit/ipc/agent/AbstractAgent.java
|
UTF-8
| 3,698 | 2.71875 | 3 |
[] |
no_license
|
package net.rubygrapefruit.ipc.agent;
import net.rubygrapefruit.ipc.message.*;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public abstract class AbstractAgent {
protected final ExecutorService executorService;
private FlushStrategy flushStrategy;
public AbstractAgent() {
executorService = Executors.newCachedThreadPool();
}
protected void startReceiverLoop(final Serializer serializer, final Deserializer deserializer,
final Receiver receiver) {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
receiverLoop(deserializer, serializer, receiver);
} catch (IOException e) {
throw new RuntimeException("Failure in worker thread.", e);
}
}
});
}
protected void receiverLoop(Deserializer deserializer, Serializer serializer, Receiver receiver)
throws IOException {
int readCound = 0;
ReceiveContextImpl context = new ReceiveContextImpl(serializer, flushStrategy);
while (!context.done) {
Message message = Message.read(deserializer);
readCound++;
receiver.receive(message, context);
}
serializer.flush();
System.out.println("* Receiver handled " + readCound + " messages, sent " + context.writeCount + " messages.");
}
protected void generatorLoop(Serializer serializer, Generator generator) throws IOException {
SerializerBackedDispatch dispatch = new SerializerBackedDispatch(serializer, flushStrategy);
generator.generate(dispatch);
serializer.flush();
System.out.println("* Generated " + dispatch.writeCount + " messages.");
}
public void setFlushStrategy(FlushStrategy flushStrategy) {
this.flushStrategy = flushStrategy;
}
protected void waitForThreads() throws Exception {
executorService.shutdown();
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
throw new RuntimeException("Timeout waiting for completion.");
}
}
protected Serializer noSend() {
return new Serializer() {
@Override
public void writeString(String string) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void flush() throws IOException {
}
};
}
private static class SerializerBackedDispatch implements Dispatch {
private final Serializer serializer;
private final FlushStrategy flushStrategy;
int writeCount;
public SerializerBackedDispatch(Serializer serializer, FlushStrategy flushStrategy) {
this.serializer = serializer;
this.flushStrategy = flushStrategy;
writeCount = 0;
}
@Override
public void send(Message message) throws IOException {
Message.write(message, serializer);
if (flushStrategy == FlushStrategy.EachMessage) {
serializer.flush();
}
writeCount++;
}
}
private static class ReceiveContextImpl extends SerializerBackedDispatch implements ReceiveContext {
boolean done;
public ReceiveContextImpl(Serializer serializer, FlushStrategy flushStrategy) {
super(serializer, flushStrategy);
}
@Override
public void done() {
done = true;
}
}
}
| true |
7dffcbd9b00ecd68b09d9b15efd40dc265453518
|
Java
|
hsn74/testNGfraemwork
|
/src/test/java/com/techproed/DTseleniumpractice/day03/TestCase02.java
|
UTF-8
| 2,057 | 2.421875 | 2 |
[] |
no_license
|
package com.techproed.DTseleniumpractice.day03;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class TestCase02 {
WebDriver driver;
@BeforeMethod
public void setUp(){
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@Test
public void alert02(){
driver.get("http://webdriveruniversity.com/Popup-Alerts/index.html");
WebElement button4 = driver.findElement(By.id("button4"));
button4.click();
Alert popup = driver.switchTo().alert();
String popupText = popup.getText();
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(popupText,"Press a button");
popup.dismiss();
WebElement alertResultText = driver.findElement(By.id("confirm-alert-text"));
Assert.assertTrue(alertResultText.isDisplayed());
softAssert.assertAll();
}
@Test(dependsOnMethods = "alert02")
public void alert2(){
driver.get("http://webdriveruniversity.com/Popup-Alerts/index.html");
WebElement button4 = driver.findElement(By.id("button4"));
button4.click();
Alert popup = driver.switchTo().alert();
String popupText = popup.getText();
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(popupText,"Press a button!");
popup.dismiss();
WebElement alertResultText = driver.findElement(By.id("confirm-alert-text"));
Assert.assertTrue(alertResultText.isDisplayed());
softAssert.assertAll();
}
@AfterMethod
public void tearDown(){
driver.close();
}
}
| true |
7eb3125161b8debcd609f260354b51e418d1ff72
|
Java
|
giovaninovello/Android-Orientadas
|
/app/src/main/java/com/example/giovani/semipresencialtabwidget/MainActivity.java
|
UTF-8
| 984 | 2.3125 | 2 |
[] |
no_license
|
package com.example.giovani.semipresencialtabwidget;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TabHost;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabhost = (TabHost) findViewById(R.id.tabhost);
tabhost.setup();
TabHost.TabSpec aba1 =tabhost.newTabSpec("primeira");
aba1.setContent(R.id.tab1);
aba1.setIndicator("Primeira");
TabHost.TabSpec aba2 =tabhost.newTabSpec("segunda");
aba1.setContent(R.id.tab2);
aba1.setIndicator("Sefgunda");
TabHost.TabSpec aba3 =tabhost.newTabSpec("terceira");
aba1.setContent(R.id.tab3);
aba1.setIndicator("Terceira");
tabhost.addTab(aba1);
tabhost.addTab(aba2);
tabhost.addTab(aba3);
}
}
| true |
f0737fd912a8ab37a1bc624fd00ea988917d5ab8
|
Java
|
MarcinKrysinski/WSBexercises
|
/src/main/java/pl/krysinski/repo/Connector.java
|
UTF-8
| 3,880 | 3.109375 | 3 |
[] |
no_license
|
package pl.krysinski.repo;
import java.sql.*;
import java.util.Properties;
public class Connector {
static Connection CONNECTION;
static Statement STMT;
public static Connection JDBCConnection() {
try {
Properties properties = new Properties();
properties.setProperty("url", Configuration.DB_URL);
properties.setProperty("user", Configuration.USER);
properties.setProperty("password", Configuration.PASSWORD);
Class.forName("org.postgresql.Driver");
CONNECTION = DriverManager
.getConnection(Configuration.DB_URL, properties);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Connection database successfully");
return CONNECTION;
}
public static Statement getStatement() {
try {
STMT = CONNECTION.createStatement();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return STMT;
}
public static void executiveSQLReadAnimal(String sql) {
try {
System.out.println("Creating statement...");
STMT = getStatement();
ResultSet rs = STMT.executeQuery(sql);
while (rs.next()) {
//Retrieve by column name
int id = rs.getInt("id");
String species = rs.getString("species");
double weight = rs.getDouble("weight");
//Display values
System.out.print("ID: " + id);
System.out.print(", Species: " + species);
System.out.println(", Weight: " + weight);
}
rs.close();
} catch (Exception se) {
//Handle errors for JDBC
se.printStackTrace();
}//Handle errors for Class.forName
finally {
//finally block used to close resources
try {
if (STMT != null)
CONNECTION.close();
} catch (SQLException se) {
}// do nothing
try {
if (CONNECTION != null)
CONNECTION.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
public static void executiveSQLReadHuman(String sql) {
try {
STMT = getStatement();
ResultSet rs = STMT.executeQuery(sql);
System.out.println("Id Species Weight Name LastName Salary");
while (rs.next()) {
Integer id = rs.getInt("id");
String species = rs.getString("species");
double weight = rs.getDouble("weight");
String name = rs.getString("name");
String last_name = rs.getString("last_name");
double salary = rs.getDouble("salary");
System.out.println(id + " " + species + " " + weight+ " " + name+ " " +last_name+ " " +salary);
}
System.out.println("Results");
STMT.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void executiveSQL(String sql) {
try {
STMT = getStatement();
STMT.executeUpdate(sql);
STMT.close();
Connector.JDBCConnection().close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
}
}
| true |
650eb868b1fa60e14a9d0a3b1ea3e7e39387d6a9
|
Java
|
BennyZhang-Codes/AdaptiveMerging
|
/src/mergingBodies3D/MouseSpringForce.java
|
UTF-8
| 4,631 | 2.578125 | 3 |
[] |
no_license
|
package mergingBodies3D;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import mintools.parameters.DoubleParameter;
import mintools.swing.CollapsiblePanel;
import mintools.swing.VerticalFlowPanel;
/**
* Mouse spring for interacting with rigid bodies
* @author kry
*/
public class MouseSpringForce {
/** The selected body will be null if there is no mouse spring active */
RigidBody picked = null;
/** Grab point on body in body coords */
Point3d grabPointB = new Point3d();
/** Grab point on body in world coords */
Point3d grabPointBW = new Point3d();
/** Mouse point in world */
Point3d pointW = new Point3d();
/**
* Creates a new mouse spring, where the provided point will be updated with movement of the mouse
* @param point
*/
public MouseSpringForce( ) {
}
/**
* Sets the picked body and the point on that body
* @param picked
* @param grabPointB
*/
public void setPicked( RigidBody picked, Point3d grabPointB ) {
this.picked = picked;
this.grabPointB.set( grabPointB );
}
/**
* Gets the current picked body
* @return
*/
public RigidBody getPicked() {
return picked;
}
/** Temporary working variables */
private Vector3d grabPointV = new Vector3d();
private Vector3d force = new Vector3d();
private Vector3d direction = new Vector3d();
/**
* Applies the mouse spring force to the picked rigid body, or nohting if no body selected
*/
public void apply( boolean applyAtCOM ) {
if ( picked == null ) return;
picked.wake();
picked.picked = true;
picked.transformB2W.transform( grabPointB, grabPointBW );
double distance = grabPointBW.distance( pointW );
double k = stiffness.getValue();
double c = damping.getValue();
direction.sub( pointW, grabPointBW );
if ( direction.lengthSquared() < 1e-3 ) return;
direction.normalize();
force.scale( distance * k, direction );
if (picked.isInCollection()) {
picked.parent.applyForceW( grabPointBW, force );
}
if ( applyAtCOM ) {
picked.applyForceW( picked.x, force );
} else {
picked.applyForceW( grabPointBW, force );
}
// spring damping forces
picked.getSpatialVelocity( grabPointBW, grabPointV );
force.scale( - grabPointV.dot( direction ) * c, direction );
if (picked.isInCollection()) picked.parent.applyForceW( grabPointBW, force );
if ( applyAtCOM ) {
picked.applyForceW( picked.x, force );
} else {
picked.applyForceW( grabPointBW, force );
}
}
/**
* Stiffness of mouse spring
*/
public DoubleParameter stiffness = new DoubleParameter("mouse stiffness", 50, 1, 1e4 );
/**
* Viscous damping coefficient for the mouse spring
*/
public DoubleParameter damping = new DoubleParameter("mouse spring damping", 30, 0, 100 );
/**
* @return controls for the collision processor
*/
public JPanel getControls() {
VerticalFlowPanel vfp = new VerticalFlowPanel();
vfp.setBorder( new TitledBorder("Mouse Spring Controls") );
((TitledBorder) vfp.getPanel().getBorder()).setTitleFont(new Font("Tahoma", Font.BOLD, 18));
stiffness.setDefaultValue(stiffness.getValue());
vfp.add( stiffness.getSliderControls(true) );
damping.setDefaultValue(damping.getValue());
vfp.add( damping.getSliderControls(false) );
CollapsiblePanel cp = new CollapsiblePanel(vfp.getPanel());
return cp;
}
/**
* Draws a transparent line between the points connected by this spring.
* @param drawable
*/
public void display(GLAutoDrawable drawable) {
if ( picked == null ) return;
GL2 gl = drawable.getGL().getGL2();
gl.glDisable( GL2.GL_LIGHTING );
gl.glColor4d( 1, 0,0, 0.5 );
gl.glLineWidth(3);
gl.glBegin(GL.GL_LINES);
gl.glVertex3d( pointW.x, pointW.y, pointW.z );
picked.transformB2W.transform( grabPointB, grabPointBW );
gl.glVertex3d( grabPointBW.x, grabPointBW.y, grabPointBW.z);
gl.glEnd();
gl.glEnable( GL2.GL_LIGHTING );
}
}
| true |
c2c9cfec1f6236ccc9398ff35df3cba162bc907e
|
Java
|
adil-ansari/chat_applicatonRSA
|
/src/chat/message.java
|
UTF-8
| 573 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
package chat;
/**
* message.java
*
*
* Compile $javac message.java
*
*/
import java.io.Serializable;
/*
* public class message
*
* Creates an serializable object with contains the message
* to be exchanged between Client and Server.
*/
public class message implements Serializable{
private static final long serialVersionUID = 1L;
byte[] data;
message(byte[] data){
this.data = data;
}
/*
*getData method
* returns the byte array.
*/
byte[] getData(){
return data;
}
}
| true |
dedf747f71b855eb15a160f61cad765b29ec9a4d
|
Java
|
hiyzx/spring-boot
|
/rpc/hessian/hessian-server/src/main/java/org/zero/hessian/server/impl/WeatherServiceImpl.java
|
UTF-8
| 1,148 | 2.328125 | 2 |
[] |
no_license
|
package org.zero.hessian.server.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.springframework.stereotype.Service;
import org.zero.hessian.server.domain.WeatherVo;
import org.zero.hessian.server.inf.IWeatherService;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/**
* @author zero
* @since 2017/08/09
*/
@Service
public class WeatherServiceImpl implements IWeatherService {
private static final Map<String, WeatherVo> weatherMap = new HashMap<>();
static {
DateTime now = DateUtil.date();
weatherMap.put("beijing", new WeatherVo(1L, "北京", "30摄氏度", "雷阵雨", now, new BigDecimal(1)));
weatherMap
.put("shanghai", new WeatherVo(2L, "上海", "20摄氏度", "晴天", DateUtil.offsetDay(now, 1), new BigDecimal(1)));
weatherMap.put("shenzhen",
new WeatherVo(3L, "深圳", "25摄氏度", "大太阳", DateUtil.offsetDay(now, 2), new BigDecimal(1)));
}
@Override
public WeatherVo queryWeatherByCityName(String cityName) {
return weatherMap.get(cityName);
}
}
| true |
2f6d8958f2929f27e6219e9a7734dfec1432dc37
|
Java
|
preethi1991/Selenium-java
|
/src/main/java/day6/classrooom/erailList.java
|
UTF-8
| 1,787 | 2.484375 | 2 |
[] |
no_license
|
package day6.classrooom;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class erailList {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
// Initiate the ChromeBroswer
ChromeDriver driver=new ChromeDriver();
// Maximize the browser
driver.get("https://erail.in/");
driver.manage().window().maximize();
WebElement source=driver.findElementById("txtStationFrom");
source.clear();
source.sendKeys("MAS",Keys.TAB);
WebElement destination=driver.findElementById("txtStationTo");
destination.clear();
destination.sendKeys("SBC",Keys.TAB);
Thread.sleep(3000);
driver.findElementById("chkSelectDateOnly").click();
WebElement noTrains = driver.findElementByXPath("//div[@id='divMain']/div[1]");
System.out.println(noTrains.getText());
List<WebElement> tNames = driver.findElementsByXPath("//table[@class='DataTable TrainList TrainListHeader']//td[2]");
int tSize=tNames.size();
System.out.println("Sixe in list" +tSize);
Set<String> tnamesinset=new HashSet<>();
for (WebElement alltrains : tNames)
{
String eachtrainname=alltrains.getText();
tnamesinset.add(eachtrainname);
}
if(tnamesinset.size()==tSize)
{
System.out.println("Its not duplicated");
}
}
}
| true |
be11a1e44dce2b50e25e423c381adea70ad777ee
|
Java
|
kipo3195/WeWannaGoTrip
|
/src/main/java/net/wannago/board/vo/BoardVO.java
|
UTF-8
| 396 | 1.507813 | 2 |
[] |
no_license
|
package net.wannago.board.vo;
import java.util.Date;
import lombok.Data;
@Data
public class BoardVO {
private int bno;
private String title;
private String content;
private String writer;
private int origin;
private int depth;
private int seq;
private Date regdate;
private Date updatedate;
private int viewcnt;
private String showboard;
private int uno;
}
| true |
0a2362de63ce28d026b794c33ba4a0a13158e19e
|
Java
|
Liaelis/Padroes-de-Projeto
|
/exercicio6/src/exercicio62/EstadoTocando.java
|
UTF-8
| 616 | 2.9375 | 3 |
[] |
no_license
|
package exercicio62;
public class EstadoTocando implements EstadoAudioPlayer{
@Override
public EstadoAudioPlayer play() {
System.out.println("esta pausado");
return new EstadoEspera();
}
@Override
public EstadoAudioPlayer next() {
System.out.println("proxima musica");
return this;
}
@Override
public EstadoAudioPlayer previous() {
System.out.println("musica anterior");
return this;
}
@Override
public EstadoAudioPlayer lock() {
System.out.println("bloqueou");
return new EstadoBloqueado();
}
}
| true |
98b7183f14dbc087f4b665f4dcf42163fdcf4cf9
|
Java
|
snegrini/IngSw-Project-2020
|
/src/main/java/it/polimi/ingsw/network/message/MatchInfoMessage.java
|
UTF-8
| 1,679 | 2.484375 | 2 |
[
"MIT"
] |
permissive
|
package it.polimi.ingsw.network.message;
import it.polimi.ingsw.model.ReducedGod;
import it.polimi.ingsw.model.enumerations.Color;
import java.util.List;
/**
* Message which contains information about the current status of the match.
*/
public class MatchInfoMessage extends Message {
private static final long serialVersionUID = -9048130764283419918L;
private final List<String> activePlayers;
private final List<ReducedGod> activeGods;
private final List<Color> activeColors;
private final String activePlayerNickname;
public MatchInfoMessage(String senderNickname, MessageType messageType, List<String> activePlayers, List<ReducedGod> activeGods, List<Color> activeColors, String activePlayerNickname) {
super(senderNickname, messageType);
this.activePlayers = activePlayers;
this.activeGods = activeGods;
this.activeColors = activeColors;
this.activePlayerNickname = activePlayerNickname;
}
public String getActivePlayerNickname() {
return activePlayerNickname;
}
public List<String> getActivePlayers() {
return activePlayers;
}
public List<ReducedGod> getActiveGods() {
return activeGods;
}
public List<Color> getActiveColors() {
return activeColors;
}
@Override
public String toString() {
return "MatchInfoMessage{" +
"nickname=" + getNickname() +
", activePlayers=" + activePlayers +
", activeGods=" + activeGods +
", activeColors=" + activeColors +
", activePlayerNickname=" + activePlayerNickname +
'}';
}
}
| true |
b643312124f1fea69fcf73224e7d01ed92237447
|
Java
|
chenlingyx/currentlimiter
|
/src/main/java/com/example/currentlimiter/annotation/Limit.java
|
UTF-8
| 895 | 2.21875 | 2 |
[] |
no_license
|
package com.example.currentlimiter.annotation;
import com.example.currentlimiter.enums.LimitTypeEnum;
import java.lang.annotation.*;
/**
* @author : chenling
* @ClassName : Limit
* @Description : //TODO
* @Date : 2019/6/12 18:44
* @since : v1.0.0
**/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Limit {
/**
* 资源名称
*/
String name() default "";
/**
* 资源key
* @return
*/
String key() default "";
/**
* key的前缀
* @return
*/
String prefix() default "";
/**
* 给定的时间段
* @return
*/
int period();
/**
* 最多访问次数
* @return
*/
int count();
/**
* 类型
*
* @return
*/
LimitTypeEnum limitType() default LimitTypeEnum.CUSTOMER;
}
| true |
5ce5c082991149e9adb102a41eeb98f445eca0ae
|
Java
|
nikhi-suthar/formkiq-core
|
/lambda-api/src/test/java/com/formkiq/stacks/api/ApiDocumentsPublicDocumentsRequestTest.java
|
UTF-8
| 4,846 | 1.929688 | 2 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/**
* MIT License
*
* Copyright (c) 2018 - 2020 FormKiQ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.formkiq.stacks.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.formkiq.lambda.apigateway.ApiGatewayRequestEvent;
import com.formkiq.lambda.apigateway.util.GsonUtil;
/** Unit Tests for request POST /public/documents. */
public class ApiDocumentsPublicDocumentsRequestTest extends AbstractRequestHandler {
/**
* Post /public/documents without authentication.
*
* @throws Exception an error has occurred
*/
@SuppressWarnings("unchecked")
@Test
public void testPostPublicDocuments01() throws Exception {
// given
getMap().put("ENABLE_PUBLIC_URLS", "true");
createApiRequestHandler(getMap());
newOutstream();
ApiGatewayRequestEvent event = toRequestEvent("/request-post-public-documents03.json");
event.getRequestContext().setAuthorizer(new HashMap<>());
event.getRequestContext().setIdentity(new HashMap<>());
// when
String response = handleRequest(event);
// then
Map<String, String> m = fromJson(response, Map.class);
final int mapsize = 3;
assertEquals(mapsize, m.size());
assertEquals("201.0", String.valueOf(m.get("statusCode")));
assertEquals(getHeaders(), "\"headers\":" + GsonUtil.getInstance().toJson(m.get("headers")));
Map<String, Object> body = fromJson(m.get("body"), Map.class);
assertNotNull(body.get("documentId"));
assertNotNull(body.get("uploadUrl"));
List<Map<String, Object>> documents = (List<Map<String, Object>>) body.get("documents");
assertEquals(mapsize, documents.size());
assertNotNull(documents.get(0).get("documentId"));
assertNull(documents.get(0).get("uploadUrl"));
assertNotNull(documents.get(1).get("uploadUrl"));
assertNotNull(documents.get(1).get("documentId"));
assertNotNull(documents.get(2).get("uploadUrl"));
assertNotNull(documents.get(2).get("documentId"));
}
/**
* Post /public/documents with authentication.
*
* @throws Exception an error has occurred
*/
@SuppressWarnings("unchecked")
@Test
public void testPostPublicForms02() throws Exception {
// given
getMap().put("ENABLE_PUBLIC_URLS", "true");
createApiRequestHandler(getMap());
newOutstream();
ApiGatewayRequestEvent event = toRequestEvent("/request-post-public-documents03.json");
setCognitoGroup(event, "admins");
// when
String response = handleRequest(event);
// then
Map<String, String> m = fromJson(response, Map.class);
final int mapsize = 3;
assertEquals(mapsize, m.size());
assertEquals("201.0", String.valueOf(m.get("statusCode")));
assertEquals(getHeaders(), "\"headers\":" + GsonUtil.getInstance().toJson(m.get("headers")));
}
/**
* Post /public/documents with disabled PUBLIC_URLS.
*
* @throws Exception an error has occurred
*/
@SuppressWarnings("unchecked")
@Test
public void testPostPublicForms03() throws Exception {
// givens
newOutstream();
ApiGatewayRequestEvent event = toRequestEvent("/request-post-public-documents03.json");
event.getRequestContext().setAuthorizer(new HashMap<>());
event.getRequestContext().setIdentity(new HashMap<>());
// when
String response = handleRequest(event);
// then
Map<String, String> m = fromJson(response, Map.class);
final int mapsize = 3;
assertEquals(mapsize, m.size());
assertEquals("404.0", String.valueOf(m.get("statusCode")));
assertEquals(getHeaders(), "\"headers\":" + GsonUtil.getInstance().toJson(m.get("headers")));
}
}
| true |
0404bae0f339118e29f83e9dfcf0a10362cef4e9
|
Java
|
YokoMasa/SeriouslyLocal-server
|
/src/main/java/com/seriouslylocal/app/repository/ImageInfoRepository.java
|
UTF-8
| 244 | 1.648438 | 2 |
[] |
no_license
|
package com.seriouslylocal.app.repository;
import com.seriouslylocal.app.entity.ImageInfo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ImageInfoRepository extends JpaRepository<ImageInfo, Integer> {
}
| true |
852a980a8e611db14f124d839effd5ef92d29972
|
Java
|
zhouf/wther.diagram
|
/src/com/sunsheen/jfids/studio/wther/diagram/dialog/editor/VarMapPutEditor.java
|
UTF-8
| 7,531 | 1.945313 | 2 |
[] |
no_license
|
package com.sunsheen.jfids.studio.wther.diagram.dialog.editor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.TraverseEvent;
import com.sunsheen.jfids.studio.dialog.SDialog;
import com.sunsheen.jfids.studio.dialog.agilegrid.AgileGrid;
import com.sunsheen.jfids.studio.dialog.agilegrid.Cell;
import com.sunsheen.jfids.studio.dialog.agilegrid.EditorActivationEvent;
import com.sunsheen.jfids.studio.dialog.agilegrid.editors.TextCellEditor;
import com.sunsheen.jfids.studio.dialog.proposal.IProposalRender;
import com.sunsheen.jfids.studio.dialog.proposal.SSContentProposalAdapter;
import com.sunsheen.jfids.studio.logging.Log;
import com.sunsheen.jfids.studio.run.Constants;
import com.sunsheen.jfids.studio.run.core.extensionpoint.ResourcePromptManager;
import com.sunsheen.jfids.studio.run.core.resources.prompt.IResourcePrompt;
import com.sunsheen.jfids.studio.wther.diagram.compiler.util.TableHiddenType;
import com.sunsheen.jfids.studio.wther.diagram.dialog.listener.MouseActiveProposalListener;
import com.sunsheen.jfids.studio.wther.diagram.dialog.popup.ItemSelectDialog;
import com.sunsheen.jfids.studio.wther.diagram.dialog.popup.SqlidSelectDialog;
import com.sunsheen.jfids.studio.wther.diagram.dialog.proposal.ComponentInterfaceProposalRender;
import com.sunsheen.jfids.studio.wther.diagram.dialog.proposal.DefaultProposalRender;
import com.sunsheen.jfids.studio.wther.diagram.edit.util.InputDataValidate;
/**
* 这是一个对对话框中设置变量的单元格编辑器,包含变量自动提示
*
* @author zhoufeng
*/
public class VarMapPutEditor extends TextCellEditor {
static final org.apache.log4j.Logger log = com.sunsheen.jfids.studio.logging.LogFactory.getLogger(VarMapPutEditor.class.getName());
SSContentProposalAdapter adapter = null;
String rowType = "";
String dataName = "";
String tipRender = "";
private enum DialogType {
NONE, DEFAULT_DLG, SERVICE_COMPONENT, SQLID
}
DialogType dialogType = DialogType.NONE;
public VarMapPutEditor(AgileGrid agileGrid) {
this(agileGrid, SWT.SINGLE);
}
public VarMapPutEditor(AgileGrid agileGrid, int style) {
super(agileGrid, style);
this.text.addMouseListener(new MouseActiveProposalListener());
}
@Override
protected boolean dependsOnExternalFocusListener() {
// 不启用外部监听
return false;
}
@Override
protected void onTraverse(TraverseEvent e) {
if (e.keyCode == SWT.ARROW_LEFT) {
if (text.getCaretPosition() == 0 && text.getSelectionCount() == 0)
super.onTraverse(e);
} else if (e.keyCode == SWT.ARROW_UP || e.keyCode == SWT.ARROW_DOWN) {
// 屏蔽掉上下键的处理
return;
} else if (e.keyCode == SWT.ARROW_RIGHT) {
if (text.getCaretPosition() == text.getText().length() && text.getSelectionCount() == 0)
super.onTraverse(e);
// handle the event within the text widget!
} else {
if (e.detail == SWT.TRAVERSE_ESCAPE || e.detail == SWT.TRAVERSE_RETURN) {
e.doit = false;
} else {
super.onTraverse(e);
}
}
return;
}
@Override
protected void onKeyPressed(KeyEvent keyEvent) {
// 屏蔽掉key的响应,如果开启,则弹出提示框无法响应回车选中
// super.onKeyPressed(keyEvent);
// 对bean的对话框热键处理 Alt stateMask=65536
if (SWT.ALT == keyEvent.stateMask && 47 == keyEvent.keyCode) {
log.debug("VarTextCellEditor onKeyPressed()-> :Alt + /");
if (dialogType == DialogType.DEFAULT_DLG) {
// 如果是Alt+/ 激活对话框
// Log.debug("VarTextCellEditor.onKeyPressed()-> keyEvent.keyLocation:"
// + keyEvent.keyLocation);
keyEvent.doit = false;
ItemSelectDialog itemSelectDialog = new ItemSelectDialog(tipRender, text.getText());
this.text.setText(itemSelectDialog.getRetVal());
} else if (dialogType == DialogType.SERVICE_COMPONENT) {
keyEvent.doit = false;
IResourcePrompt prompt = ResourcePromptManager.getResourcePrompt(Constants.FILE_EXT_SIX);
if (prompt != null) {
String getComName = prompt.getComName();
if (getComName != null) {
this.text.setText(getComName);
}
}
} else if (dialogType == DialogType.SQLID) {
log.debug("VarTextCellEditor onKeyPressed()-> :DialogType.SQLID");
keyEvent.doit = false;
SqlidSelectDialog sqlDialog = new SqlidSelectDialog(text.getText());
String getVal = sqlDialog.getRetVal();
log.debug("VarTextCellEditor onKeyPressed()-> getVal:" + getVal);
if (getVal != null) {
this.text.setText(getVal);
// 设置值类型为常量
Cell thisCell = this.getAgileGrid().getFocusCell();
this.getAgileGrid().setContentAt(thisCell.row, thisCell.column + 1, "常量");
}
}
dialogType = DialogType.NONE;
// 该变量当作焦点移出后验证数据的一个标志位
}
}
@Override
protected void focusLost() {
if (this.adapter != null && !this.adapter.isProposalPopupOpen()) {
// 验证数据
agileGrid.applyEditorValue();
if ("Date".equalsIgnoreCase(rowType) || "".equalsIgnoreCase(rowType)) {
boolean dateFormatOk = InputDataValidate.checkDateStrValidate(text.getText());
if (dateFormatOk) {
// Log.debug("VarTextCellEditor.focusLost()-> 日期验证通过:" +
// text.getText());
} else {
Log.error("VarTextCellEditor.focusLost()-> 日期格式不正确:" + text.getText());
}
}
super.focusLost();
((SDialog) agileGrid.getParams().get("SDIALOG")).validate();
}
}
@Override
public void activate(EditorActivationEvent activationEvent) {
super.activate(activationEvent);
if (cell != null) {
// 获取该行数据类型
rowType = "java.lang.Object";
dataName = (String) this.agileGrid.getContentAt(cell.row, 2);
tipRender = (String) this.agileGrid.getContentAt(cell.row, TableHiddenType.TIP_RENDER);
}
rowType = (rowType == null ? "" : rowType.trim());
tipRender = (tipRender == null ? "" : tipRender.trim());
if (tipRender.toLowerCase().endsWith(".xml")) {
dialogType = DialogType.DEFAULT_DLG;
} else if ("component".equalsIgnoreCase(tipRender) || ("String".equalsIgnoreCase(rowType) && "serviceName".equalsIgnoreCase(dataName))) {
dialogType = DialogType.SERVICE_COMPONENT;
} else if ("comp_interface".equalsIgnoreCase(tipRender) || ("String".equalsIgnoreCase(rowType) && "interfaceName".equalsIgnoreCase(dataName))) {
ComponentInterfaceProposalRender render = new ComponentInterfaceProposalRender();
adapter = render.initAdapter(text);
return;
} else if ("sqlid".equalsIgnoreCase(tipRender)) {
dialogType = DialogType.SQLID;
} else {
dialogType = DialogType.NONE;
try {
if (tipRender == null || tipRender.length() == 0) {
// TODO 在未配置tipRender时,通过对rowType和dataName的判断,确定提示类型
// 参数提示
if ("String".equalsIgnoreCase(rowType) && "sqlid".equalsIgnoreCase(dataName)) {
dialogType = DialogType.SQLID;
} else {
// tipRender =
// "logic.diagram.dialog.proposal.DefaultProposalRender";
DefaultProposalRender render = new DefaultProposalRender();
render.setFilterStr(rowType);
adapter = render.initAdapter(text);
}
} else {
IProposalRender render = (IProposalRender) Class.forName(tipRender).newInstance();
adapter = render.initAdapter(text);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
| true |
3a1588f075a50b71879074ac02e54993f700e5ad
|
Java
|
DoubleDa/AndroidCodeFragment
|
/AndroidCodeFragment/app/src/main/java/com/dyx/acf/view/ui/DES3Act.java
|
UTF-8
| 1,446 | 2.15625 | 2 |
[] |
no_license
|
package com.dyx.acf.view.ui;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.dyx.acf.R;
import com.dyx.acf.view.base.BaseActivity;
import com.dyx.utils.library.common.DES3Utils;
import com.orhanobut.logger.Logger;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by dayongxin on 2016/8/10.
*/
public class DES3Act extends BaseActivity {
private static final String ENCRYPT_MSG = "中华人民共和国保守国家秘密法";
@Bind(R.id.btn_nothing)
Button btnNothing;
@Bind(R.id.btn_encrypt)
Button btnEncrypt;
@Bind(R.id.btn_decode)
Button btnDecode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_des3_layout);
ButterKnife.bind(this);
}
@OnClick({R.id.btn_nothing, R.id.btn_encrypt, R.id.btn_decode})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_nothing:
Logger.d(ENCRYPT_MSG);
break;
case R.id.btn_encrypt:
Logger.d(new String(DES3Utils.encryptMode(ENCRYPT_MSG.getBytes())));
break;
case R.id.btn_decode:
Logger.d(new String(DES3Utils.decryptMode(DES3Utils.encryptMode(ENCRYPT_MSG.getBytes()))));
break;
}
}
}
| true |
ce285e2a6a0633800e91e2fab8a1e4b145df6085
|
Java
|
pawar121/SmartCar_WebDevelopmentProject
|
/SmartCarrr/src/main/java/com/me/spring/pojo/Payment.java
|
UTF-8
| 850 | 2.140625 | 2 |
[] |
no_license
|
package com.me.spring.pojo;
public class Payment {
private String cardNumber;
private String cardName;
private String expiryDate;
private String cvvNo;
private String cardType;
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public String getCvvNo() {
return cvvNo;
}
public void setCvvNo(String cvvNo) {
this.cvvNo = cvvNo;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
}
| true |
28cb37f7692660887df7752b6d13f3302e29701b
|
Java
|
RandolphChin/springboot_intergration
|
/src/main/java/com/shaphar/service/elasticsearch/ElasticSearchService.java
|
UTF-8
| 2,609 | 1.789063 | 2 |
[] |
no_license
|
package com.shaphar.service.elasticsearch;
import com.mongodb.CommandResult;
import com.shaphar.domain.elasticsearch.Es;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
@Service
public class ElasticSearchService {
@Resource
TransportClient transportClient;//注入es操作对象
public String selectfromEsByid(Es es ,BigDecimal userId){
GetResponse response = transportClient.prepareGet(es.getIndex(),es.getType(),String.valueOf(userId))
.execute()
.actionGet();
String json = response.getSourceAsString();
return json;
}
public SearchHits selectfromEsByField(Es es,String fieldName,String fieldVal ,int page,int size){
//高亮配置
HighlightBuilder highlightBuilder = new HighlightBuilder()
.field("userName")
.preTags("<em>")
.postTags("</em>");
QueryBuilder qb = QueryBuilders.matchQuery(fieldName ,fieldVal);
SearchResponse response = transportClient.prepareSearch(es.getType()).setQuery(qb).setFrom(page).setSize(size).highlighter(highlightBuilder).get();
// SearchResponse response = transportClient.prepareSearch(es.getType()).setQuery(qb).get();
SearchHits searchHits = response.getHits();
// 一共文档数
long totalHits = searchHits.getTotalHits();
return searchHits;
}
public DeleteResponse deleteById(Es es,BigDecimal userId){
DeleteResponse dResponse = transportClient.prepareDelete(es.getIndex(),es.getType(), String.valueOf(userId)).execute().actionGet();
return dResponse;
}
}
| true |
207e91f16e5eb240bf00cd8351ea33f76dd36021
|
Java
|
BruceZhang0828/litespring
|
/src/main/java/org/litespring/context/support/ClassPathXmlApplicationContext.java
|
UTF-8
| 806 | 1.976563 | 2 |
[] |
no_license
|
package org.litespring.context.support;
import org.litespring.beans.BeanDefinition;
import org.litespring.beans.factory.support.DefaultBeanFactory;
import org.litespring.beans.factory.xml.XmlBeanDefinitionReader;
import org.litespring.context.ApplicationContext;
import org.litespring.core.io.ClassPathResource;
import org.litespring.core.io.FileSystemResource;
import org.litespring.core.io.Resource;
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {
private DefaultBeanFactory factory = null;
public ClassPathXmlApplicationContext(String configFile) {
super(configFile);
}
@Override
protected Resource getResourceByPath(String configFile) {
Resource resource = new ClassPathResource(configFile);
return resource;
}
}
| true |
a1dbfde36c77bf00b699a84f488e984a9f60e106
|
Java
|
EnrichEuropeana/apihack
|
/transcribathon-web/src/main/java/eu/transcribathon/europeana/web/serialization/TranscribathonXmlSerializer.java
|
UTF-8
| 1,220 | 2.25 | 2 |
[] |
no_license
|
package eu.transcribathon.europeana.web.serialization;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.transcribathon.europeana.definitions.model.TranscriptionPage;
import eu.transcribathon.europeana.web.app.AppConfigConstants;
@Component(AppConfigConstants.BEAN_XML_SERIALIZER)
public class TranscribathonXmlSerializer {
@Resource(name = AppConfigConstants.BEAN_XML_MAPPER)
ObjectMapper objectMapper;
// private final JAXBContext jaxbContext;
public TranscribathonXmlSerializer() {
// xmlModule = new JacksonXmlModule();
// xmlModule.setDefaultUseWrapper(true);
// objectMapper = new XmlMapper(xmlModule);
// objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
/**
* This method serializes Entity object to xml formats.
* @param page The Entity object
* @return The serialized entity in xml string format
* @throws JsonProcessingException, UnsupportedEntityTypeException
*/
public String serializeXml(TranscriptionPage page) throws Exception {
return objectMapper.writeValueAsString(page);
}
}
| true |
aac87f33ee94722d31531acfb549d83f74367353
|
Java
|
sunleesi/android-education-project
|
/HelloWebApp/src/org/tacademy/web/hellowebapp/GetUploadUrl.java
|
UTF-8
| 1,525 | 2.328125 | 2 |
[] |
no_license
|
package org.tacademy.web.hellowebapp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
public class GetUploadUrl extends HttpServlet {
private BlobstoreService blobstoreService =
BlobstoreServiceFactory.getBlobstoreService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String type = req.getParameter("type");
String uploadURL = null;
if (type.equals("test")) {
uploadURL = blobstoreService.createUploadUrl("/uploadfile");
} else if (type.equals("login")) {
uploadURL = blobstoreService.createUploadUrl("/logininfoupload");
} else if (type.equals("boardinsert")) {
uploadURL = blobstoreService.createUploadUrl("/boardinsert");
} else if (type.equals("boardupdate")) {
uploadURL = blobstoreService.createUploadUrl("/boardupdate");
} else { // default "test"
uploadURL = blobstoreService.createUploadUrl("/uploadfile");
}
resp.setContentType("text/xml");
PrintWriter writer = resp.getWriter();
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.println("<uploadUrl>"+uploadURL+"</uploadUrl>");
}
}
| true |
88f980a6b8ba7fe394a84fe6359ce3eacd3a2d8b
|
Java
|
denysLerroan/spring-mvc-thymeleaf
|
/src/main/java/com/dlerroan/course/boot/service/EmployeeService.java
|
UTF-8
| 473 | 2.1875 | 2 |
[] |
no_license
|
package com.dlerroan.course.boot.service;
import java.time.LocalDate;
import java.util.List;
import com.dlerroan.course.boot.domain.Employee;
public interface EmployeeService {
void save (Employee employee);
void update(Employee employee);
void delete(Long id);
Employee findById(Long id);
List<Employee> findAll();
List<Employee> findByName(String name);
List<Employee> findByRole(Long id);
List<Employee> findByDate(LocalDate in, LocalDate out);
}
| true |
35d2934a028a3bf5ac2ebb78be81caf1976ac80c
|
Java
|
NikolayNS/leetCode
|
/src/main/java/com/dmitrenko/leetcode/matrixsort/MatrixSortService.java
|
UTF-8
| 1,303 | 3.4375 | 3 |
[] |
no_license
|
package com.dmitrenko.leetcode.matrixsort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MatrixSortService {
public int[][] diagonalSort(int[][] matrix){
List<List<Integer>> tempMatrix = new ArrayList<>();
for (int j = 0; j < matrix[0].length; j++) {
tempMatrix.add(getReverseSortListFromMatrix(matrix, 0, j));
}
for (int i = 1; i < matrix.length; i++) {
tempMatrix.add(getReverseSortListFromMatrix(matrix, i, matrix[i].length - 1));
}
System.out.println(tempMatrix.toString());
int[][] result = new int[matrix.length][matrix[0].length];
int l = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
//result[i][j] = tempMatrix.get()
}
l++;
}
return result;
}
private List<Integer> getReverseSortListFromMatrix(int[][] matrix, int k, int l) {
List<Integer> tempList = new ArrayList<>();
while (l >= 0 && k < matrix.length) {
tempList.add(matrix[k][l]);
k++;
l--;
}
Collections.sort(tempList);
Collections.reverse(tempList);
return tempList;
}
}
| true |
199041ee67a43c6950aadde3073714493272630a
|
Java
|
mrhanhan/portal
|
/portal-example/portal-chat/portal-chat-server/src/main/java/com/example/chat/server/impl/ServerServiceImpl.java
|
UTF-8
| 1,328 | 2.40625 | 2 |
[] |
no_license
|
package com.example.chat.server.impl;
import com.example.chat.api.RegisterClientService;
import com.example.chat.api.SendMessageService;
import com.example.chat.model.Message;
import com.example.chat.model.MessageCallback;
import com.example.chat.model.UserInfo;
import java.util.ArrayList;
import java.util.List;
/**
* RegisterClientServiceImpl
*
* @author Mrhan
* @date 2021/7/4 12:47
*/
public class ServerServiceImpl implements RegisterClientService, SendMessageService {
private List<MessageCallback> callbackList;
public ServerServiceImpl() {
callbackList = new ArrayList<>();
}
@Override
public void register(UserInfo userInfo, MessageCallback callback) {
for (MessageCallback messageCallback : callbackList) {
messageCallback.userCallback(userInfo);
}
callbackList.add(callback);
Message message = new Message();
message.setContent("欢迎加入");
message.setUserInfo(new UserInfo("系统"));
send(message);
}
@Override
public void send(Message message) {
for (MessageCallback messageCallback : callbackList) {
try {
messageCallback.messageCallback(message);
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
| true |
34655259d3f56d855e15e22e6ea1f1b860fdd0ac
|
Java
|
vlady21/oz-ex-atm-desc
|
/src/main/java/com/oz/atm/service/Cajero.java
|
UTF-8
| 490 | 2.21875 | 2 |
[] |
no_license
|
package com.oz.atm.service;
public interface Cajero {
/**
* Retiro de efectivo por la cantidad solicitada
* @param idCustomer identificador del cliente
* @param amount importe a retirar
*/
void retirar(Integer idCustomer, double amount);
/**
* Transfiere el efectivo a otro Banco
* @param idCustomer identificador del cliente
* @param amount importe a transferir
*/
void transferir(Integer idCustomer, double amount);
}
| true |
4b18c3fd8b37c1694ef3606ba7dab5eb343fef88
|
Java
|
SpoorthiPalakshaiah/Bliss-Boost-Chatbot-to-trace-out-Anxiety-and-depression
|
/BlissBoost/app/src/main/java/com/example/bliss_boost/test2page3.java
|
UTF-8
| 2,897 | 2.15625 | 2 |
[] |
no_license
|
package com.example.bliss_boost;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
public class test2page3 extends AppCompatActivity {
static int ans;
static String a1;
private ScrollView Scroll1;
private RadioGroup radioGroup;
private RadioButton radioButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2page3);
final Handler handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
speak();
}
},40);
Scroll1=findViewById(R.id.tscroll1);
Scroll1.post(new Runnable() {
@Override
public void run() {
Scroll1.fullScroll(ScrollView.FOCUS_DOWN);
}
});
radioGroup=findViewById(R.id.trg1);
Button btnd1=findViewById(R.id.tbtna1);
btnd1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
int radioId=radioGroup.getCheckedRadioButtonId();
radioButton=findViewById(radioId);
// System.out.println("String is"+radioButton.getText().toString());
a1=radioButton.getText().toString();
if(radioButton.getText().toString().equals("Not at all")){
ans=1;
}
else if(radioButton.getText().toString().equals("Several days")){
ans=2;
}
else if(radioButton.getText().toString().equals("More than half the days")){
ans=3;
}
else{
ans=4;
}
// System.out.println("Answer is "+ans);
startActivity(new Intent(test2page3.this,test2page4.class));
}
});
}
private void speak(){
TextView tv=findViewById(R.id.ttvq1);
String text=tv.getText().toString();
AnxietyTest.mTTS.setPitch((float)1.0);
AnxietyTest.mTTS.setSpeechRate((float)1.0);
AnxietyTest.mTTS.speak(text, TextToSpeech.QUEUE_FLUSH,null);
}
@Override
protected void onDestroy(){
if(AnxietyTest.mTTS!=null){
AnxietyTest.mTTS.stop();
AnxietyTest.mTTS.shutdown();
}
super.onDestroy();
}
@Override
public void onBackPressed(){
startActivity(new Intent(test2page3.this,Home.class));
}
}
| true |
1fa4e56ef5d51371f68a8da7a9f394da111642fe
|
Java
|
HashbrownBurger/Unit-4-Turn-in-Luke-Hashbarger
|
/DieTester.java
|
UTF-8
| 286 | 3.5625 | 4 |
[] |
no_license
|
public class DieTester {
public static void main(String[] args) {
System.out.println("Good you're finally awake");
Die d1 = new Die();
System.out.println("Die 1 = " + d1.getFace());
d1.roll();
System.out.println("Die 1 is " + d1);
}
}
| true |
11fe3d45bb63bf5a48014a3dbe79e48af70f2ee3
|
Java
|
Ibratan/kikaha-caffeine
|
/tests/kikaha/caffeine/CaffeineSessionStoreTest.java
|
UTF-8
| 4,331 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package kikaha.caffeine;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import kikaha.core.modules.security.DefaultSession;
import kikaha.core.modules.security.Session;
import kikaha.core.modules.security.SessionCookie;
import kikaha.core.test.HttpServerExchangeStub;
import kikaha.core.test.KikahaRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import static org.junit.Assert.*;
/**
* Unit tests for {@link CaffeineSessionStoreTest}.
* Created by miere.teixeira on 30/10/2017.
*/
@RunWith(KikahaRunner.class)
public class CaffeineSessionStoreTest {
final static String
SESSION_ID = "123",
MSG_NO_SESSION_REQUIRED_BEFORE_CREATION = "Should there be no session stored on the cache before it can be created",
MSG_NO_SESSION_REQUIRED_AFTER_INVALIDATION = "Should there be no session stored on the cache after it is invalidated"
;
@Inject CaffeineSessionStore sessionStore;
@Inject SessionCookie sessionIdManager;
@Before
public void cleanUpSession(){
sessionStore.sessionCache.invalidateAll();
}
@Test( timeout = 3000 )
public void createSession() throws Exception {
assertNull(MSG_NO_SESSION_REQUIRED_BEFORE_CREATION, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
final Session session = sessionStore.createOrRetrieveSession( createExchange(), sessionIdManager );
assertNotNull( session );
assertEquals( SESSION_ID, session.getId() );
assertEquals( session, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
}
@Test
public void retrieveSession() throws Exception {
assertNull(MSG_NO_SESSION_REQUIRED_BEFORE_CREATION, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
final Session session = new DefaultSession( SESSION_ID );
sessionStore.sessionCache.put( SESSION_ID, session );
final Session foundSession = sessionStore.createOrRetrieveSession( createExchange(), sessionIdManager );
assertEquals( session, foundSession );
}
@Test
public void invalidateSession() throws Exception {
assertNull(MSG_NO_SESSION_REQUIRED_BEFORE_CREATION, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
final Session session = new DefaultSession( SESSION_ID );
sessionStore.sessionCache.put( SESSION_ID, session );
sessionStore.invalidateSession( session );
assertNull(MSG_NO_SESSION_REQUIRED_AFTER_INVALIDATION, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
}
@Test
public void flush() throws Exception {
assertNull(MSG_NO_SESSION_REQUIRED_BEFORE_CREATION, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
final Session session = new DefaultSession( SESSION_ID );
sessionStore.sessionCache.put( SESSION_ID, session );
session.setAttribute( "a", "b" );
sessionStore.flush( session );
final Session found = sessionStore.sessionCache.getIfPresent( SESSION_ID );
assertNotNull( found );
assertEquals( "b", found.getAttribute( "a" ) );
}
@Test
public void getSessionFromCache() throws Exception {
assertNull(MSG_NO_SESSION_REQUIRED_BEFORE_CREATION, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
final Session session = new DefaultSession( SESSION_ID );
sessionStore.sessionCache.put( SESSION_ID, session );
final Session found = sessionStore.getSessionFromCache( SESSION_ID );
assertEquals( session, found );
}
@Test
public void storeSession() throws Exception {
assertNull(MSG_NO_SESSION_REQUIRED_BEFORE_CREATION, sessionStore.sessionCache.getIfPresent( SESSION_ID ) );
final Session session = new DefaultSession( SESSION_ID );
sessionStore.storeSession( SESSION_ID, session );
final Session found = sessionStore.sessionCache.getIfPresent( SESSION_ID );
assertNotNull( found );
assertEquals( session, found );
}
static HttpServerExchange createExchange(){
final HttpServerExchange exchange = HttpServerExchangeStub.createHttpExchange();
exchange.getRequestHeaders().put( Headers.COOKIE, "JSESSIONID=" + SESSION_ID );
return exchange;
}
}
| true |
5418aa1fc8d5c2a69bec90f3fc092c84cd7585f4
|
Java
|
DipasDam107/Colecciones
|
/src/main/java/dam107t9e7/Main.java
|
UTF-8
| 6,183 | 3.671875 | 4 |
[] |
no_license
|
/*
Realizar un programa que tenga un HashMap que almacene una plantilla de jugadores de un
equipo (Nombre, salario). La plantilla tiene un máximo de 25 jugadores. El programa dispondrá de
menú que permita: añadir jugador, eliminar jugador, lista jugadores con su salario y que tenga
también opción que permita introducir un salario y muestre los jugadores que tiene un salario
parecido al introducido (por “parecido” entendemos que el salario del jugador esté en un rango de
6000 euros arriba o abajo respecto al introducido).
ado.
*/
package dam107t9e7;
import dam107t9e6.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
static Scanner teclado;
static Plantilla plantel;
public static void main(String [] args){
teclado=new Scanner(System.in);
plantel = new Plantilla();
int opcion;
do{
menu();
opcion=teclado.nextInt();
teclado.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if(opcion==1)aniadirJugador();
if(opcion==2)eliminarJugador();
if(opcion==3)ConsultarJugador();
if(opcion==4)incrementoSalario();
if(opcion==5)mostrarJugadores();
if(opcion==6)mostrarSalariosParecidos();
}while(opcion!=0 || (opcion<0 || opcion>6));
}
public static void menu(){
System.out.println("---------------------------");
System.out.println("MENU");
System.out.println("---------------------------");
System.out.println("1 - Añadir jugador");
System.out.println("2 - Eliminar Jugador");
System.out.println("3 - Consultar Informacion");
System.out.println("4 - Incrementar Salario");
System.out.println("5 - Listar Plantilla");
System.out.println("6 - Listar Salarios similares");
System.out.println("0 - Salir");
System.out.println("---------------------------");
System.out.println("Dime opcion: ");
}
public static void aniadirJugador(){
System.out.println("Dime nombre: ");
String nombre = teclado.nextLine();
System.out.println("Dime numero: ");
int numero = teclado.nextInt();
teclado.nextLine();
System.out.println("Dime posicion: ");
String posicion = teclado.nextLine();
System.out.println("Dime altura: ");
float altura = teclado.nextFloat();
System.out.println("Dime pie: ");
String pie = teclado.nextLine();
System.out.println("Dime salario: ");
float salario = teclado.nextFloat();
teclado.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n");
if(plantel.aniadirJugador(nombre, new Jugador(numero, posicion, altura, pie, salario)))
System.out.println("Jugador " + nombre + " añadido con exito");
else System.out.println("El jugador ya existe");
}
public static void eliminarJugador(){
System.out.println("Dime nombre: ");
String nombre = teclado.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n");
if(plantel.borrarJugador(nombre))
System.out.println("El jugador " + nombre + " borrado");
else
System.out.println("El jugador " + nombre + " no existe");
}
public static void ConsultarJugador(){
System.out.println("Dime nombre: ");
String nombre = teclado.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n");
Jugador jugador = plantel.getJugador(nombre);
if(jugador!=null){
System.out.println("-------------------");
System.out.println("Nombre: " + nombre);
System.out.println("-------------------");
System.out.println(jugador);
}
else
System.out.println("El jugador " + nombre + " no existe");
}
public static void incrementoSalario(){
System.out.println("Dime nombre: ");
String nombre = teclado.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n");
double salario=plantel.incrementarSalario(nombre);
if(salario!=-1)
System.out.println("Salario del jugador " + nombre + " incrementado. Nuevo Salario: " + salario);
else
System.out.println("El jugador " + nombre + " no existe");
}
public static void mostrarSalariosParecidos(){
System.out.println("Dime Salario:");
float salario = teclado.nextFloat();
teclado.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n");
HashMap<String, Jugador> plantilla = plantel.getPlantilla();
Iterator<String> nombres = plantilla.keySet().iterator();
System.out.println("---------------------------");
System.out.println("Salarios Similares");
System.out.println("---------------------------");
while(nombres.hasNext()){
String nombre = nombres.next();
if( Math.abs(plantilla.get(nombre).salario - salario) < 2000)
System.out.println("Nombre: " + nombre + " Salario: " + plantilla.get(nombre).salario);
}
System.out.println("---------------------------");
}
public static void mostrarJugadores(){
HashMap<String, Jugador> plantilla = plantel.getPlantilla();
Iterator<String> nombres = plantilla.keySet().iterator();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("---------------------------");
System.out.println("PLANTILLA");
System.out.println("---------------------------");
while(nombres.hasNext()){
String nombre = nombres.next();
System.out.println("Nombre: " + nombre + " Salario: " + plantilla.get(nombre).salario);
}
System.out.println("---------------------------");
}
}
| true |
2524e9031288d9614f22b0cb79c6101d70c51cc9
|
Java
|
chriscasola/cs3041
|
/Man2Oh/src/ccasola/man2oh/view/ISliderUpdated.java
|
UTF-8
| 396 | 2.375 | 2 |
[] |
no_license
|
package ccasola.man2oh.view;
import javax.swing.JSlider;
/**
* An interface to be implemented by all classes that need to be notified
* when the position of the {@link HelpLevelSlider} changes.
*/
public interface ISliderUpdated {
/**
* The method called when the help level slider changes
* @param slider the slider that was changed
*/
public void sliderChanged(JSlider slider);
}
| true |
ccf81d0e9b20ff1ec0cd87ab5724754fd6aea2c8
|
Java
|
dengyuanyou/crm
|
/crm12/src/main/java/cn/wolfcode/crm/service/impl/SystemDictionaryItemServiceImpl.java
|
UTF-8
| 2,161 | 2.09375 | 2 |
[] |
no_license
|
package cn.wolfcode.crm.service.impl;
import cn.wolfcode.crm.domain.SystemDictionaryItem;
import cn.wolfcode.crm.mapper.SystemDictionaryItemMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.ISystemDictionaryItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SystemDictionaryItemServiceImpl implements ISystemDictionaryItemService {
@Autowired
private SystemDictionaryItemMapper systemDictionaryItemMapper;
@Override
public void save(SystemDictionaryItem systemDictionaryItem) {
systemDictionaryItemMapper.insert(systemDictionaryItem);
}
@Override
public void update(SystemDictionaryItem systemDictionaryItem) {
systemDictionaryItemMapper.updateByPrimaryKey(systemDictionaryItem);
}
@Override
public void delete(Long id) {
systemDictionaryItemMapper.deleteByPrimaryKey(id);
}
@Override
public SystemDictionaryItem get(Long id) {
return systemDictionaryItemMapper.selectByPrimaryKey(id);
}
@Override
public List<SystemDictionaryItem> listAll() {
return systemDictionaryItemMapper.selectAll();
}
@Override
public PageInfo<SystemDictionaryItem> query(QueryObject qo) {
//在这行代码下面的第一个SQL中会拼接分页的SQL片段
PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
List<SystemDictionaryItem> list = systemDictionaryItemMapper.selectForList(qo);
return new PageInfo<>(list);
}
@Override
public List<SystemDictionaryItem> listJobs() {
return systemDictionaryItemMapper.selectItemByDicSn("job");
}
@Override
public List<SystemDictionaryItem> listSources() {
return systemDictionaryItemMapper.selectItemByDicSn("source");
}
@Override
public List<SystemDictionaryItem> listTypes() {
return systemDictionaryItemMapper.selectItemByDicSn("communicationMethod");
}
}
| true |
91ca44ccf48a9b0f4a48a3cfc55a8159fbd001fc
|
Java
|
kunjut/task_Calc_for_JM
|
/src/Main.java
|
UTF-8
| 3,861 | 3.75 | 4 |
[] |
no_license
|
import java.util.Scanner;
import mylib.Parser;
import mylib.Dictionary;
import mylib.SimpleException;
public class Main {
public static void main(String[] args) throws SimpleException {
System.out.println("Введите что посчитать: ");
String userInput = "";
while (userInput.equals("")) {
// Scanner считывает ввод пользователя, пока не будет что-то передано
Scanner in = new Scanner(System.in);
userInput = in.nextLine();
}
// Передать выражение для парсинга
Parser parser = new Parser(userInput);
// Если был введен оператор отличный от + - / *
if(parser.getOperator().equals("Invalid operator") || parser.getOperands().length > 2) {
//Кинуть исключение
throw new SimpleException("Введен не валидный оператор");
}
System.out.println("Результат: ");
// Если калькулятор работает в режиме счета арабских чисел
if (parser.modeOfCalc().equals("arabic")) {
// Если введенные арабские числа не соответствую диапазону от 1 до 10
if (Integer.parseInt(parser.leftOperand()) < 1 || Integer.parseInt(parser.leftOperand()) > 10 ||
Integer.parseInt(parser.rightOperand()) < 1 || Integer.parseInt(parser.rightOperand()) > 10) {
// Кинуть исключение
throw new SimpleException("Цифры только от 1 до 10");
}
// Получить арабские операнды
int l_operand = Integer.parseInt(parser.leftOperand());
int r_operand = Integer.parseInt(parser.rightOperand());
// Получить результат арабскими числами
switch (parser.getOperator()) {
case "\\+":
System.out.println(l_operand + r_operand);
break;
case "\\*":
System.out.println(l_operand * r_operand);
break;
case "/":
System.out.println(l_operand / r_operand);
break;
case "-":
System.out.println(l_operand - r_operand);
break;
}
// Если калькулятор работает в режиме счета римских чисел
} else if (parser.modeOfCalc().equals("rome")) {
// Отправить римские операнды на перевод в арабские
Dictionary translate = new Dictionary(parser.leftOperand(), parser.rightOperand());
translate.RomeToArabic();
// Получить арабские числа римских операндов
int l_operand = Integer.parseInt(translate.leftOperand);
int r_operand = Integer.parseInt(translate.rightOperand);
// Получить результат римскими числами
switch (parser.getOperator()) {
case "\\+":
translate.ArabicToRome(l_operand + r_operand);
break;
case "\\*":
translate.ArabicToRome(l_operand * r_operand);
break;
case "/":
translate.ArabicToRome(l_operand / r_operand);
break;
case "-":
translate.ArabicToRome(l_operand - r_operand);
break;
}
}
}
}
| true |
de5f79e1235344fa5230426169a32b10329db473
|
Java
|
wuyufei2019/JSLYG
|
/src/main/java/com/cczu/model/dao/BisYgxxDao2.java
|
UTF-8
| 431 | 1.898438 | 2 |
[] |
no_license
|
package com.cczu.model.dao;
import org.springframework.stereotype.Repository;
import com.cczu.model.entity.BIS_Employee2Entity;
import com.cczu.util.dao.BaseDao;
@Repository("BisYgxxDao2")
public class BisYgxxDao2 extends BaseDao<BIS_Employee2Entity, Long> {
/**
* 删除表中所有数据
* @param id
*/
public void deleteInfo() {
String sql=" delete from bis_employee_second where 1=1";
updateBySql(sql);
}
}
| true |
daef5b57db078119d066099c4d3cd5947c7c7f33
|
Java
|
2016-Software-Reuse-Group-7/chat-room
|
/src/main/java/TeamSeven/common/message/server/GroupMemberLoginMessage.java
|
UTF-8
| 833 | 1.960938 | 2 |
[
"MIT"
] |
permissive
|
package TeamSeven.common.message.server;
import TeamSeven.common.entity.Account;
import TeamSeven.common.enumerate.TransMessageTypeEnum;
import TeamSeven.common.message.BaseMessage;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.util.HashMap;
import java.util.List;
/**
* Created by zhao on 2016/5/17.
*/
public class GroupMemberLoginMessage extends BaseMessage {
protected Account account;
protected List<HashMap<String,Boolean>> groupMembers;
public GroupMemberLoginMessage(Account account){
this.account = account;
}
@Override
public TransMessageTypeEnum getType() {
return TransMessageTypeEnum.LOGIN_STATUS;
}
public Account getAccount(){return this.account;}
public List<HashMap<String,Boolean>> getGroupMembers(){return this.groupMembers;}
}
| true |
527100984aec850337f35a497af83fc694ca4fbb
|
Java
|
Hillrunner2008/igb-fx
|
/org.lorainelab.igb.data.model/src/main/java/org/lorainelab/igb/data/model/glyph/GraphGlyph.java
|
UTF-8
| 6,071 | 2.21875 | 2 |
[
"MIT"
] |
permissive
|
package org.lorainelab.igb.data.model.glyph;
import static com.google.common.base.Preconditions.*;
import com.vividsolutions.jts.geom.Coordinate;
import java.awt.Rectangle;
import java.util.List;
import java.util.Optional;
import javafx.geometry.Rectangle2D;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import org.lorainelab.igb.data.model.Chromosome;
import org.lorainelab.igb.data.model.View;
import static org.lorainelab.igb.data.model.chart.GraphXAxis.drawXAxisGridLines;
import org.lorainelab.igb.data.model.chart.GraphYAxis;
import org.lorainelab.igb.data.model.chart.IntervalChart;
import org.lorainelab.igb.data.model.util.Palette;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author dcnorris
*/
public class GraphGlyph implements Glyph {
private static final Logger LOG = LoggerFactory.getLogger(GraphGlyph.class);
private final Rectangle2D boundingRect;
private IntervalChart data;
private GraphYAxis yAxis;
public GraphGlyph(IntervalChart data, Chromosome chromosome) {
checkNotNull(data);
checkNotNull(chromosome);
this.data = data;
this.boundingRect = new Rectangle2D(0, data.getDataBounds().y, chromosome.getLength(), data.getDataBounds().height);
yAxis = new GraphYAxis();
}
@Override
public Color getFill() {
return Palette.GRAPH_FILL.get();
}
@Override
public Color getStrokeColor() {
return Palette.DEFAULT_GLYPH_FILL.get();
}
@Override
public Rectangle2D getBoundingRect() {
return boundingRect;
}
@Override
public void draw(GraphicsContext gc, View view, double slotMinY) {
try {
gc.save();
drawXAxisGridLines(gc, view, boundingRect);
yAxis.drawYAxisGridLines(gc, view, boundingRect);
drawChartData(gc, view);
yAxis.drawYAxis(gc, view, boundingRect);
} finally {
gc.restore();
}
}
@Override
public Optional<Rectangle.Double> calculateDrawRect(View view, double slotMinY) {
SHARED_RECT.setRect(view.getMutableCoordRect());
return Optional.of(SHARED_RECT);
}
@Override
public GlyphAlignment getGlyphAlignment() {
return GlyphAlignment.BOTTOM;
}
@Override
public void setGlyphAlignment(GlyphAlignment alignment) {
LOG.warn("Graphs do not support multiple glyphAlignments yet, ignoring setter call");
}
private void drawChartData(GraphicsContext gc, View view) {
try {
gc.save();
java.awt.geom.Rectangle2D.Double modelCoordRect = view.getMutableCoordRect();
final List<Coordinate> dataInRange = data.getDataInRange(modelCoordRect, view.getXpixelsPerCoordinate());
if (!dataInRange.isEmpty()) {
drawGraphFill(gc, view, dataInRange);
drawGrawLine(gc, view, dataInRange);
}
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
} finally {
gc.restore();
}
}
private void drawGraphFill(GraphicsContext gc, View view, final List<Coordinate> dataInRange) {
java.awt.geom.Rectangle2D.Double modelCoordRect = view.getMutableCoordRect();
final Rectangle2D canvasCoordRect = view.getCanvasContext().getBoundingRect();
double minTrackY = 0; //already translated to canvas rect minY
double maxTrackY = canvasCoordRect.getHeight() / view.getYfactor();
double trackHeightInModelCoords = maxTrackY;
double cutOffAmount = boundingRect.getHeight() - modelCoordRect.getHeight();
double topCutOff = modelCoordRect.getMinY();
double bottomCutOff = cutOffAmount - topCutOff;
double minGraphY = boundingRect.getMinY() + bottomCutOff;
double maxGraphY = boundingRect.getMaxY() - topCutOff;
final double zeroPosition = maxGraphY - boundingRect.getMinY();
gc.setFill(getFill());
gc.beginPath();
gc.moveTo(0, zeroPosition);
for (Coordinate c : dataInRange) {
double width = c.z;
final double minX = Math.max(c.x - modelCoordRect.x, 0);
final double y = maxGraphY - c.y;
gc.moveTo(minX, zeroPosition);
gc.lineTo(minX, y);
gc.lineTo(minX + width, y);
gc.lineTo(minX + width, zeroPosition);//would not needed if there were no gaps in intervals, but I don't know if that can be assumed safely
}
gc.setGlobalAlpha(.4);
gc.fill();
gc.setGlobalAlpha(1);
}
private void drawGrawLine(GraphicsContext gc, View view, final List<Coordinate> dataInRange) {
gc.setStroke(getFill());
gc.setLineWidth(2);
java.awt.geom.Rectangle2D.Double modelCoordRect = view.getMutableCoordRect();
final Rectangle2D canvasCoordRect = view.getCanvasContext().getBoundingRect();
double minTrackY = 0; //already translated to canvas rect minY
double maxTrackY = canvasCoordRect.getHeight() / view.getYfactor();
double trackHeightInModelCoords = maxTrackY;
double cutOffAmount = boundingRect.getHeight() - modelCoordRect.getHeight();
double topCutOff = modelCoordRect.getMinY();
double bottomCutOff = cutOffAmount - topCutOff;
double minGraphY = boundingRect.getMinY() + bottomCutOff;
double maxGraphY = boundingRect.getMaxY() - topCutOff;
final double firstY = Math.floor((modelCoordRect.getMaxY() - dataInRange.get(0).y));
final double startX = Math.max((dataInRange.get(0).x - 0.5 - modelCoordRect.x), 0);
gc.beginPath();
gc.moveTo(startX, firstY);
for (Coordinate c : dataInRange) {
double width = c.z;
final double minX = c.x - modelCoordRect.x;
final double y = maxGraphY - c.y;
gc.lineTo(minX, y);
gc.lineTo((minX + width), y);
}
gc.scale(1 / view.getXfactor(), 1 / view.getYfactor());
gc.stroke();
}
}
| true |
bd4e3c05c78f6ccea92d72139fee17c1df227240
|
Java
|
minuk8932/Algorithm_BaekJoon
|
/src/common/CSVFileModifider.java
|
UTF-8
| 1,745 | 2.96875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
public class CSVFileModifider {
public static void main(String[] args) {
try{
File file = new File("/Users/exponential-e/Desktop/SWM_Proj/crawling/game.csv");
BufferedWriter bw = Files.newBufferedWriter(Paths.get("/Users/exponential-e/Desktop/SWM_Proj/crawling/temp.csv"),Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(new FileReader(file));
String input = "";
while ((input = br.readLine()) != null) {
String[] token = input.split(",");
String[] dummy = new String[6];
for(int i =0; i < 6; i++) {
if(i == 3 && !token[i].equals("time")) token[i] = "\"" + token[i] + "\"";
dummy[i] = token[i];
}
String result = "";
for(int i=0; i < 6; i++) {
result += dummy[i] + (i == 5 ? "": ",");
}
System.out.println(result);
bw.write(result + "\n");
}
br.close();
bw.close();
}
catch (FileNotFoundException e){
System.out.println("파일 없음");
e.printStackTrace();
}
catch (IOException e){
System.out.println("I/O 에러");
e.printStackTrace();
}
}
}
| true |
88dd3c81101145d18a9c3824465a23219c42f6bb
|
Java
|
baigx-git/test
|
/src/main/java/com/luxondata/test/component/response/ResponseBody.java
|
UTF-8
| 1,722 | 2.046875 | 2 |
[] |
no_license
|
package com.luxondata.test.component.response;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luxondata.test.common.enums.ErrorEnum;
import com.luxondata.test.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice(basePackages = "com.luxondata.test")
@Slf4j
public class ResponseBody implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getParameterType() != Result.class;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
Result<Object> result = new Result<>();
result.setCode(200);
result.setMessage("操作成功");
result.setData(body);
if (body instanceof String) {
ObjectMapper o = new ObjectMapper();
try {
return o.writeValueAsString(result);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return result;
}
}
| true |
98d57736961d6ccabf55a68c71de9c4e347f0296
|
Java
|
dyguests/HBookerAuthor
|
/app/src/main/java/com/fanhl/hbookerauthor/ui/common/BaseActivity.java
|
UTF-8
| 684 | 1.882813 | 2 |
[] |
no_license
|
package com.fanhl.hbookerauthor.ui.common;
import android.support.v7.app.AppCompatActivity;
import com.fanhl.hbookerauthor.App;
import com.umeng.analytics.MobclickAgent;
/**
* Created by fanhl on 2017/4/7.
*/
public abstract class BaseActivity extends AppCompatActivity {
protected App getApp() {
return (App) getApplication();
}
public void onResume() {
super.onResume();
MobclickAgent.onResume(this);
MobclickAgent.onPageStart(this.getClass().getSimpleName());
}
public void onPause() {
super.onPause();
MobclickAgent.onPause(this);
MobclickAgent.onPageEnd(this.getClass().getSimpleName());
}
}
| true |
2e58e4c95141ba4209ee9501692ae20b9ec31fd7
|
Java
|
peops/Readoholic
|
/src/com/readoholic/dblayer/DBConnection.java
|
UTF-8
| 1,476 | 2.84375 | 3 |
[] |
no_license
|
package com.readoholic.dblayer;
import java.sql.*;
public class DBConnection {
private static String db_url;
private static String db_port;
private static String db_name;
private static String db_user;
private static String db_password;
private static Connection connection;
private DBConnection() {
db_url = "jdbc:postgresql://localhost";
db_port = "5432";
db_name = "postgres";
db_user = "postgres";
db_password = "postgres";
connection = setConnection();
}
private static Connection setConnection() {
try {
String url = "" + db_url + ":" + db_port + "/" + db_name + "";
Class.forName("org.postgresql.Driver");
java.sql.Connection conn = DriverManager.getConnection(url, db_user, db_password);
return conn;
} catch (SQLException ex) {
System.out.println(ex.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
return null;
}
private static class DbSingletonManagerHolder {
private final static DBConnection instance = new DBConnection();
}
public static DBConnection getInstance() {
try {
return DbSingletonManagerHolder.instance;
} catch (ExceptionInInitializerError ex) {
}
return null;
}
public static Connection getStatement() {
return connection;
}
}
| true |
b6751ca0813ff72d078ab0bc9d69f208e4fb2ed1
|
Java
|
zhangweilin8080/io
|
/src/main/java/com/zwl/backend/one/ObjectInputStreamAndObjectOutputStream.java
|
UTF-8
| 4,298 | 3.90625 | 4 |
[] |
no_license
|
package com.zwl.backend.one;
import com.zwl.backend.entity.SerializableClass;
import java.io.*;
import java.util.ArrayList;
/**
* @author zwl
* @date 2020/10/6 11:49
* @describe 对象的序列化和反序列化...
*/
public class ObjectInputStreamAndObjectOutputStream {
public static void main(String[] args) throws Exception {
int methodCode = 4;
switch (methodCode) {
case 1:
System.out.println("序列化对象");
objectOutputStream();
break;
case 2:
System.out.println("反序列化对象");
objectInputStream();
break;
case 3:
System.out.println("序列化集合对象");
objectOutputStreamList();
break;
case 4:
System.out.println("反序列化集合对象");
objectInputStreamList();
break;
}
}
/**
* 将Java对象的原始数据类型写出到文件,实现对象的持久存储。
* public final void writeObject (Object obj) : 将指定的对象写出。
* @throws Exception
*/
public static void objectOutputStream()throws Exception{
SerializableClass e = new SerializableClass();
e.name = "zwl";
e.address = "好好学习,天天向上";
e.age = 88;
//创建序列化流对象
ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("./src/main/resources/output/SerializableClass.txt"));
// 写出对象
objectOutputStream.writeObject(e);
// 释放资源
objectOutputStream.close();
System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。
}
/**
* 将之前使用ObjectOutputStream序列化的原始数据恢复为对象。
* 对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出一个 ClassNotFoundException 异常。
* @throws Exception
*/
public static void objectInputStream()throws Exception{
SerializableClass e = null;
// 创建反序列化流
FileInputStream fileIn = new FileInputStream("./src/main/resources/output/SerializableClass.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileIn);
// 读取一个对象
e = (SerializableClass) objectInputStream.readObject();
// 释放资源
objectInputStream.close();
fileIn.close();
// 无异常,直接打印输出
System.out.println("Name: " + e.name); // zhangsan
System.out.println("Address: " + e.address); // beiqinglu
System.out.println("age: " + e.age); // 0
}
/**
* 序列化集合
* @throws Exception
*/
public static void objectOutputStreamList()throws Exception{
// 创建 学生对象
SerializableClass student = new SerializableClass("老王", "laow");
SerializableClass student2 = new SerializableClass("老张", "laoz");
SerializableClass student3 = new SerializableClass("老李", "laol");
ArrayList<SerializableClass> arrayList = new ArrayList();
arrayList.add(student);
arrayList.add(student2);
arrayList.add(student3);
// 创建 序列化流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./src/main/resources/output/SerializableClassList.txt"));
// 写出对象
oos.writeObject(arrayList);
// 释放资源
oos.close();
}
/**
* 反序列化集合
* @throws Exception
*/
public static void objectInputStreamList()throws Exception{
// 反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/main/resources/output/SerializableClassList.txt"));
// 读取对象,强转为ArrayList类型
ArrayList<SerializableClass> list = (ArrayList<SerializableClass>)ois.readObject();
for (int i = 0; i < list.size(); i++ ){
SerializableClass s = list.get(i);
System.out.println(s.getName()+"--"+ s.getAddress());
}
}
}
| true |
14b79b3b1f859651f6f1072ffb83f79f6631c812
|
Java
|
skyemin/learncode
|
/src/main/java/com/wei/learncode/lambda/Test5.java
|
UTF-8
| 2,077 | 3.75 | 4 |
[] |
no_license
|
package com.wei.learncode.lambda;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author: weizz
* @Date: 2019/8/29 11:30
* @Description:
* @Version:1.0
*/
public class Test5 {
/* 要求:实现抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致!
方法引用:使用操作符“::”将类与方法分隔开来。
对象::实例方法名
类::静态方法名
类::实例方法名*/
public static void test9(){
Comparator<Integer> comparator = (x, y)->Integer.compare(x,y);
Comparator<Integer> comparator1 = Integer::compare;
int compare = comparator.compare(1,2);
int compare1 = comparator1.compare(1,2);
System.out.println("compare:"+compare);
System.out.println("compare1:"+compare1);
List<String> list = Arrays.asList("java","c#","javascript");
//遍历
for (String str:list){
System.out.println("before java8,"+str);
}
list.forEach(x-> System.out.println("after java8,"+x));
//map 把对象编程另一个
List<Double> list2 = Arrays.asList(10.0,20.0,30.0);
list2.stream().map(x->x+x*0.05).forEach(x-> System.out.println(x));
//reduce 把对象合并
List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
double sum = 0;
for(double each:cost) {
each += each * 0.05;
sum += each;
}
System.out.println("before java8,"+sum);
//after java8
List<Double> list3 = Arrays.asList(10.0,20.0,30.0);
double sum2 = list3.stream().map(x->x+x*0.05).reduce((sum1,x)->sum1+x).get();
System.out.println("after java8,"+sum2);
//filter
List<Double> cost1 = Arrays.asList(10.0, 20.0,30.0,40.0);
List<Double> filteredCost = cost1.stream().filter(x -> x > 25.0).collect(Collectors.toList());
filteredCost.forEach(x -> System.out.println(x));
}
}
| true |
031fb8708575d2340ce5aee9cb8121a18ee5026d
|
Java
|
curtys/webprotege-attestation
|
/webprotege-server-core/src/main/java/edu/stanford/bmir/protege/web/server/inject/DbModule.java
|
UTF-8
| 2,464 | 1.867188 | 2 |
[
"BSD-2-Clause"
] |
permissive
|
package edu.stanford.bmir.protege.web.server.inject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoDatabase;
import dagger.Module;
import dagger.Provides;
import edu.stanford.bmir.protege.web.server.app.WebProtegeProperties;
import edu.stanford.bmir.protege.web.server.persistence.DbName;
import edu.stanford.bmir.protege.web.server.persistence.MorphiaDatastoreProvider;
import edu.stanford.bmir.protege.web.server.persistence.MorphiaProvider;
import edu.stanford.bmir.protege.web.shared.inject.ApplicationSingleton;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import java.util.Optional;
/**
* Matthew Horridge
* Stanford Center for Biomedical Informatics Research
* 04/03/15
*/
@Module
public class DbModule {
@Provides
@DbHost
public String provideDbHost(DbHostProvider dbHostProvider) {
return dbHostProvider.get();
}
@Provides
@DbPort
public int provideDbPort(DbPortProvider dbPortProvider) {
return dbPortProvider.get();
}
@Provides
@DbUsername
public String provideDbUserName(WebProtegeProperties webProtegeProperties) {
return webProtegeProperties.getDBUserName().orElse("");
}
@Provides
@DbPassword
char [] provideDbPassword(WebProtegeProperties webProtegeProperties) {
return webProtegeProperties.getDBPassword().orElse("").toCharArray();
}
@Provides
@DbAuthenticationSource
String provideDbAuthenticationSource(WebProtegeProperties webProtegeProperties) {
return webProtegeProperties.getDBAuthenticationSource().orElse("");
}
@Provides
public Optional<MongoCredential> provideMongoCredentials(MongoCredentialProvider credentialsProvider) {
return credentialsProvider.get();
}
@Provides
@ApplicationSingleton
public MongoClient provideMongoClient(MongoClientProvider provider) {
return provider.get();
}
@Provides
@ApplicationSingleton
public MongoDatabase provideMongoDatabase(MongoDatabaseProvider provider) {
return provider.get();
}
@Provides
public Morphia providesMorphia(MorphiaProvider provider) {
return provider.get();
}
@Provides
public Datastore provideDatastore(MorphiaDatastoreProvider provider) {
return provider.get();
}
@Provides
@DbName
public String provideDbName() {
return "webprotege";
}
}
| true |
6e634dd7d02eb0afffe17f443f816849354f2b7f
|
Java
|
RuslanKrasnov/geekbrainshomework
|
/src/main/java/ru/geekbrains/lesson1stage2/Track.java
|
UTF-8
| 288 | 2.8125 | 3 |
[] |
no_license
|
package ru.geekbrains.lesson1stage2;
public class Track implements Obstacle{
private int lenght;
Track(int lenght) {
this.lenght = lenght;
}
@Override
public boolean overcomeObstacle(Object object) {
return ((Runnable) object).run(lenght);
}
}
| true |
477621b1da79d97622f2da1f519f477424670af9
|
Java
|
BercyW/FurnitureWayfair
|
/app/src/main/java/security/bercy/com/furniturewayfair/view/activities/SplashActivity.java
|
UTF-8
| 5,092 | 1.867188 | 2 |
[] |
no_license
|
package security.bercy.com.furniturewayfair.view.activities;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.zhy.autolayout.AutoLinearLayout;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import security.bercy.com.furniturewayfair.R;
public class SplashActivity extends AppCompatActivity {
ViewPager mLeaderImg;
AutoLinearLayout mLeaderCircle;
ImageView mLeaderRed;
private List<View> mViewList;
private View mView;
private int left;
public static SplashActivity instance = null;
private ImageView simple;
private TextView continueAsGuest;
private View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mLeaderImg = findViewById(R.id.leader_img);
mLeaderCircle = findViewById(R.id.leader_circle);
mLeaderRed = findViewById(R.id.leader_red);
continueAsGuest = findViewById(R.id.leader_continue_as_guest);
instance = this;
mLeaderImg.setOffscreenPageLimit(1);
init();
}
private void init() {
initCircles();
simple = mViewList.get(0).findViewById(R.id.leader_img);
simple.setImageResource(R.drawable.splash0);
mLeaderImg.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
float leftMargin = left * (position + positionOffset);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLeaderRed.getLayoutParams();
params.leftMargin = Math.round(leftMargin);
mLeaderRed.setLayoutParams(params);
}
@Override
public void onPageSelected(int position) {
simple = mViewList.get(position).findViewById(R.id.leader_img);
switch (position) {
case 0:
simple.setImageResource(R.drawable.splash0);
break;
case 1:
simple.setImageResource(R.drawable.splash2);
break;
case 2:
simple.setImageResource(R.drawable.splash3);
break;
default:
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
mLeaderImg.setAdapter(new LeaderAdapter());
}
private void initCircles() {
mViewList = new ArrayList<>();
for (int i = 0; i < 4; i++) {
mView = LayoutInflater.from(this).inflate(R.layout.item_leader_viewpager, null);
mViewList.add(mView);
}
mLeaderRed.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
left = mLeaderCircle.getChildAt(1).getLeft() - mLeaderCircle.getChildAt(0).getLeft();
}
});
}
private class LeaderAdapter extends PagerAdapter {
@Override
public int getCount() {
return 3;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(mViewList.get(position));
Log.d("create", "instantiateItem: ");
return mViewList.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.d("abc", "destroyItem: ");
container.removeView(mViewList.get(position));
}
}
@OnClick({R.id.leader_register, R.id.leader_login, R.id.leader_continue_as_guest})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.leader_register:
Log.d("main", "onViewClicked: ");
break;
case R.id.leader_login:
break;
case R.id.leader_continue_as_guest:
Log.d("splash", "onViewClicked: ");
startActivity(new Intent(SplashActivity.this,MainActivity.class));
break;
default:
break;
}
}
}
| true |
d48d9610b23b067555304dcd009e246272eb6263
|
Java
|
srinivasan-bala/uds
|
/hbaseclient/MinprocParser.java
|
UTF-8
| 24,269 | 2.03125 | 2 |
[] |
no_license
|
package procstats;
import java.io.*;
import java.util.ArrayList;
import java.util.Set;
import java.util.Iterator;
import java.util.HashMap;
import java.util.List;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.text.DecimalFormat;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
public class MinprocParser
{
/*
{"region":17,"isLearning":0,"aggregatorId":6,"bids":[{"bidAmount":0.001612715,"creativeHeight":72,"creativeWidth":100,"advId":6006,"matchingUserSegmentId":2010494,"advIoId":11286,"matchingPageCategoryId":10303,"advLiId":19772}],"pageCategories":[{"categoryId":10303,"categoryWeight":0.0}],"learningPercentage":0.2364742504,"foldPosition":1,"country":100,"city":21,"timestamp":1387020021,"urid":"0ae1a26d08e52f211b86a6e06b442ec950bdc5d569ba9aba46087","siteId":3513,"eligibleLisByType":[{"eligibleLis":[{"eligibleLiId":19772}],"eligibleLiType":2},{"eligibleLis":[],"eligibleLiType":1}],"bidInfoListSize":1,"invalidLL":0,"userCookie":"0010a674-c2db-4b49-be2e-694a64a20da6}
*/
/*
public static HashMap getAdvIdAndBids(File f)
{
byte[] rawData = new byte[(int) f.length()];
try
{
DataInputStream dis = new DataInputStream(new FileInputStream(f));
dis.readFully(rawData);
dis.close();
return getAdvIdAndBids(rawData);
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
public static HashMap getAdvIdAndBids(byte[] rawData)
{
try
{
CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
String minProcJsonData=utf8Decoder.decode(ByteBuffer.wrap(rawData)).toString();
return getAdvIdAndBids(minProcJsonData);
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
//This DS returns a map where key is URID and the value is stats object which contains advid:bidprice,clicks,imps,convs and auctions.
public static HashMap getAdvIdAndBids(String jsonData)
{
HashMap<String,URIDCounter> ret=new HashMap<String,URIDCounter>();
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode ;
//read JSON like DOM Parser
try
{
rootNode = objectMapper.readTree(jsonData);
}catch(java.io.IOException e)
{
System.out.println(e.getMessage());
return null;
}
Iterator<JsonNode> records=rootNode.getElements();
while(records.hasNext())
{
JsonNode record = records.next();
JsonNode urIdNode=record.path("urid");
String urId=urIdNode.getValueAsText();
long timeStamp=(record.path("timestamp")).getLongValue();
if(urId.length()<=3)
{
urId=new String("NAC");
}
//System.out.println("urid="+urId+"len="+urId.length());
JsonNode bidsNode = record.path("bids");
Iterator<JsonNode> elements = bidsNode.getElements();
if(elements.hasNext())
{
while(elements.hasNext())
{
JsonNode bid = elements.next();
JsonNode bidAmount = bid.path("bidAmount");
JsonNode advId = bid.path("advId");
DecimalFormat df = new DecimalFormat("0.00000");
//String advIdAndBid=new String(advId.getValueAsText()+":"+bidAmount.getValueAsText());
String advIdAndBid=advId+":"+df.format(bidAmount.getDoubleValue());
URIDCounter uc=ret.get(urId);
if(uc==null)
{
uc=new URIDCounter(urId,advIdAndBid,timeStamp);
ret.put(urId,uc);
}
uc.addAucs(1);
uc.addBids(1);
//System.out.println("advId:BidAmount= "+advId.toString()+":"+bidAmount.toString());
}
}else
{
//We didnt participate in so many auctions
URIDCounter uc=ret.get(urId);
if(uc==null)
{
uc=new URIDCounter(urId,"0:0",timeStamp);
ret.put(uc.getUrid(),uc);
}
uc.addAucs(1);
}
}
return ret;
}
public static HashMap<String,StatsCounter> getBidLandScapeObject(byte[] minproc,byte[] rtb,
HashMap<String,StatsCounter> bidMap)
{
HashMap<String,URIDCounter> procMap=MinprocParser.getAdvIdAndBids(minproc);
HashMap<String,URIDCounter> userLs=RtbParser.getAdvIdAndBids(rtb,procMap);
if(bidMap==null)
{
bidMap=new HashMap<String,StatsCounter>();
}
if(procMap==null || userLs==null)
{
return bidMap;
}
Iterator<String> keyIter=userLs.keySet().iterator();
while(keyIter.hasNext())
{
String key=keyIter.next();
URIDCounter uc=userLs.get(key);
//System.out.println(key+"..>"+uc.toString());
String bidString=((uc.getWinningBidPrice()==null)?uc.getBidPrice():uc.getWinningBidPrice());
StatsCounter sc=bidMap.get(bidString);
if(sc==null)
{
sc=new StatsCounter();
bidMap.put(bidString,sc);
}
String segment=String.valueOf(uc.getDayPart());
sc.addAucs(segment,uc.getAucs());
sc.addImps(segment,uc.getImps());
sc.addClicks(segment,uc.getClicks());
sc.addConvs(segment,uc.getConvs());
//sc.addAllConvs(segment,uc.getAllConvs());
sc.addBids(segment,uc.getBids());
sc.addWinPercentage(uc.getWinPercent(),1);
sc.addBidPercentage(uc.getBidPercent(),1);
//System.out.println(key+"..>"+c.toString());
}
return bidMap;
}
public static String getBidLandScapeAsJsonString(HashMap<String,StatsCounter> bidMap)
{
if(bidMap==null)
return null;
Iterator<String> bidMapKeyIter=bidMap.keySet().iterator();
JsonNodeFactory nf=JsonNodeFactory.instance;
ArrayNode bidLs=new ArrayNode(nf);
while(bidMapKeyIter.hasNext())
{
String bidPrice=bidMapKeyIter.next();
StatsCounter sc=bidMap.get(bidPrice);
ObjectNode data=sc.toJson();
data.put("advid:bidprice",bidPrice);
String s[]=bidPrice.split(":");
data.put("advid",s[0]);
data.put("bidprice",s[1]);
bidLs.add(data);
}
return bidLs.toString();
}
public static String getBidLandScapeAsJsonString(byte[] minproc,byte[] rtb)
{
HashMap<String,URIDCounter> procMap=MinprocParser.getAdvIdAndBids(minproc);
HashMap<String,URIDCounter> userLs=RtbParser.getAdvIdAndBids(rtb,procMap);
if(procMap==null || userLs==null)
{
return "";
}
HashMap<String,StatsCounter> bidMap=new HashMap<String,StatsCounter>();
Iterator<String> keyIter=userLs.keySet().iterator();
while(keyIter.hasNext())
{
String key=keyIter.next();
URIDCounter uc=userLs.get(key);
//System.out.println(key+"..>"+uc.toString());
String bidString=((uc.getWinningBidPrice()==null)?uc.getBidPrice():uc.getWinningBidPrice());
//if(uc.getWinningBidPrice()!=null)
//{
//System.out.println("BidPrice="+uc.getBidPrice()+" WinPrice="+uc.getWinningBidPrice());
//}
StatsCounter sc=bidMap.get(bidString);
if(sc==null)
{
sc=new StatsCounter();
bidMap.put(bidString,sc);
}
String segment=String.valueOf(uc.getDayPart());
sc.addAucs(segment,uc.getAucs());
sc.addImps(segment,uc.getImps());
sc.addClicks(segment,uc.getClicks());
sc.addConvs(segment,uc.getConvs());
sc.addBids(segment,uc.getBids());
//System.out.println(key+"..>"+c.toString());
}
Iterator<String> bidMapKeyIter=bidMap.keySet().iterator();
JsonNodeFactory nf=JsonNodeFactory.instance;
ArrayNode bidLs=new ArrayNode(nf);
while(bidMapKeyIter.hasNext())
{
String bidPrice=bidMapKeyIter.next();
StatsCounter sc=bidMap.get(bidPrice);
ObjectNode data=sc.toJson();
data.put("advid:bidprice",bidPrice);
String s[]=bidPrice.split(":");
data.put("advid",s[0]);
data.put("bidprice",s[1]);
bidLs.add(data);
}
return bidLs.toString();
}
*/
public static HashMap getAuctionHistogram(File f, List<Integer> tshwhr,List<ShoppingWindow> shwl)
{
byte[] rawData = new byte[(int) f.length()];
try
{
DataInputStream dis = new DataInputStream(new FileInputStream(f));
dis.readFully(rawData);
dis.close();
return getAuctionHistogram(rawData,tshwhr,shwl);
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
public static HashMap getAuctionHistogram(byte[] rawData, List<Integer> tshwhr,List<ShoppingWindow> shwl)
{
try
{
CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
String minProcJsonData=utf8Decoder.decode(ByteBuffer.wrap(rawData)).toString();
return getAuctionHistogram(minProcJsonData,tshwhr,shwl);
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
//This DS returns a map where key is URID and the value is stats object which contains clicks,imps,convs and auctions.
public static HashMap getAuctionHistogram(String jsonData,List<Integer> tshwhr,List<ShoppingWindow> shwl)
{
HashMap<String,URIDCounter> ret=new HashMap<String,URIDCounter>();
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode ;
//read JSON like DOM Parser
try
{
rootNode = objectMapper.readTree(jsonData);
}catch(java.io.IOException e)
{
System.out.println(e.getMessage());
return null;
}
//boolean hasNotSetAllAucs=true;
Iterator<JsonNode> records=rootNode.getElements();
while(records.hasNext())
{
JsonNode record = records.next();
JsonNode urIdNode=record.path("urid");
String urId=urIdNode.getValueAsText();
long timeStamp=(record.path("timestamp")).getLongValue();
List<String> segments=ShoppingWindow.getShwSegments(timeStamp,tshwhr,shwl);
if(segments==null || segments.size()<=0)
continue;
//System.out.println("minproc timestamp="+timeStamp);
if(urId.length()<=3)
{
urId=new String("NAC");
}
//System.out.println("urid="+urId+"len="+urId.length());
JsonNode bidsNode = record.path("bids");
Iterator<JsonNode> elements = bidsNode.getElements();
if(elements.hasNext())
{
while(elements.hasNext())
{
JsonNode bid = elements.next();
JsonNode bidAmount = bid.path("bidAmount");
JsonNode advId = bid.path("advId");
DecimalFormat df = new DecimalFormat("0.00000");
//String advIdAndBid=new String(advId.getValueAsText()+":"+bidAmount.getValueAsText());
String advIdAndBid=advId+":"+df.format(bidAmount.getDoubleValue());
URIDCounter uc=ret.get(urId);
if(uc==null)
{
uc=new URIDCounter(urId,advIdAndBid,timeStamp);
ret.put(urId,uc);
uc.setSegments(segments);
}
uc.addAucs(1);
uc.addBids(1);
/*
if(hasNotSetAllAucs)
{
uc.addAllConvs(shwl.size());
hasNotSetAllAucs=false;
}
*/
//System.out.println("advId:BidAmount= "+advId.toString()+":"+bidAmount.toString());
}
}else
{
//We didnt participate in so many auctions
URIDCounter uc=ret.get(urId);
if(uc==null)
{
uc=new URIDCounter(urId,"0:0",timeStamp);
ret.put(uc.getUrid(),uc);
uc.setSegments(segments);
}
uc.addAucs(1);
/*
if(hasNotSetAllAucs)
{
uc.addAllConvs(shwl.size());
hasNotSetAllAucs=false;
}
*/
}
}
return ret;
}
public static HashMap getAuctionHistObject(byte[] minproc,byte[] rtb, List<Integer> tshwhr,
List<ShoppingWindow> shwl)
{
HashMap<String,URIDCounter> procMap=MinprocParser.getAuctionHistogram(minproc,tshwhr,shwl);
HashMap<String,URIDCounter> userLs=RtbParser.getAuctionHistogram(rtb,tshwhr,shwl,procMap);
HashMap<String,StatsCounter> auctMap=new HashMap<String,StatsCounter>();
//System.out.println("procMapSize="+procMap.size()+"\tuserLs="+userLs.size());
if(procMap==null || userLs==null )
{
System.out.println("procMap or userLs is null");
return auctMap;
}
Iterator<String> keyIter=userLs.keySet().iterator();
while(keyIter.hasNext())
{
String key=keyIter.next();
URIDCounter uc=userLs.get(key);
//System.out.println(key+"..>"+uc.toString());
//String advId=uc.getBidPrice().split(":");
/*
if(uc.getWinningBidPrice()!=null)
{
System.out.println("BidPrice="+uc.getBidPrice()+" WinPrice="+uc.getWinningBidPrice());
}
*/
List<String> segl=uc.getSegments();
if(segl==null || segl.size()<=0)
continue;
Iterator<String> segIter=segl.iterator();
while(segIter.hasNext())
{
String segment=segIter.next();
StatsCounter sc=auctMap.get(segment);
if(sc==null)
{
sc=new StatsCounter();
auctMap.put(segment,sc);
}
sc.addAucs(uc.getAucs());
sc.addImps(uc.getImps());
sc.addClicks(uc.getClicks());
sc.addConvs(uc.getConvs());
sc.addBids(uc.getBids());
}
//System.out.println(key+"..>"+c.toString());
}
//Add All conversions and uniques
Iterator<String> auctMapIter=auctMap.keySet().iterator();
while(auctMapIter.hasNext())
{
String segment=auctMapIter.next();
StatsCounter sc=auctMap.get(segment);
sc.setShwhr(segment);
double winPercent=(double)sc.mImps/(double)sc.mBids;
double bidPercent=(double)sc.mBids/(double)sc.mAucs;
sc.addWinPercentage(winPercent,1);
sc.addBidPercentage(bidPercent,1);
//sc.addUniques(segment,1);
sc.addUniques(1);
Iterator<ShoppingWindow> shwlIter=shwl.iterator();
while(shwlIter.hasNext())
{
ShoppingWindow shw=shwlIter.next();
if(shw.shwhr<=Integer.parseInt(segment))
{
sc=auctMap.get(segment);
sc.addAllConvs(1);
}
}
}
return auctMap;
}
//Merge two stats counter objects. Modifies m2
public static HashMap mergeStatsCounter(HashMap<String,StatsCounter> m1,HashMap<String,StatsCounter> m2)
{
Iterator<String> m1Iter=m1.keySet().iterator();
while(m1Iter.hasNext())
{
String m1Key=m1Iter.next();
StatsCounter m1Sc=m1.get(m1Key);
StatsCounter sc=null;
if(m2.containsKey(m1Key))
{
sc=m2.get(m1Key);
}else
{
sc=new StatsCounter();
}
sc.addAucs(m1Sc.mAucs);
sc.addImps(m1Sc.mImps);
sc.addClicks(m1Sc.mClicks);
sc.addConvs(m1Sc.mConvs);
sc.addAllConvs(m1Sc.mAllConvs);
sc.addUniques(m1Sc.mUniques);
sc.addBids(m1Sc.mBids);
if(sc.mShwhr==null && m1Sc.mShwhr!=null)
{
sc.setShwhr(m1Sc.mShwhr);
}
/*
sc.addAucs(m1Key,m1Sc.mAucs);
sc.addImps(m1Key,m1Sc.mImps);
sc.addClicks(m1Key,m1Sc.mClicks);
sc.addConvs(m1Key,m1Sc.mConvs);
sc.addAllConvs(m1Key,m1Sc.mAllConvs);
sc.addUniques(m1Key,m1Sc.mUniques);
sc.addBids(m1Key,m1Sc.mBids);
*/
Iterator<Double> winIter=m1Sc.mWinPercent.keySet().iterator();
while(winIter.hasNext())
{
Double threshold=winIter.next();
sc.addWinPercentage(threshold,m1Sc.mWinPercent.get(threshold));
}
Iterator<Double> bidIter=m1Sc.mBidPercent.keySet().iterator();
while(bidIter.hasNext())
{
Double threshold=bidIter.next();
sc.addBidPercentage(threshold,m1Sc.mBidPercent.get(threshold));
}
m2.put(m1Key,sc);
}
return m2;
}
public static String getAuctHistAsJsonString(HashMap<String,StatsCounter> auctMap)
{
if(auctMap==null)
return null;
Iterator<String> auctMapKeyIter=auctMap.keySet().iterator();
JsonNodeFactory nf=JsonNodeFactory.instance;
ArrayNode bidLs=new ArrayNode(nf);
while(auctMapKeyIter.hasNext())
{
String shwhr=auctMapKeyIter.next();
StatsCounter sc=auctMap.get(shwhr);
ObjectNode data=sc.toJson();
//data.put("shwhr",shwhr);
bidLs.add(data);
}
return bidLs.toString();
}
public static void main(String[] args) throws JsonParseException, IOException
{
byte[] minproc = null,minproc1=null;
byte[] rtb = null,rtb1=null;
//String shwjson=new String("[{\"start\":1385721390,\"end\":1385721629,\"shwhr\":1},{\"start\":1385993383,\"end\":1386179007,\"shwhr\":52},{\"start\":1387056093,\"end\":1387216706,\"shwhr\":45}]");
//String shwjson=new String("[{\"start\":1385894358,\"end\":1385896295,\"shwhr\":1}]");
String shwjson=new String("[{\"start\":1385518779,\"end\":1385534290,\"shwhr\":5},{\"start\":1386115146,\"end\":1386483059,\"shwhr\":103}]");
String shwjson1=new String("[{\"start\":1385721390,\"end\":1385721629,\"shwhr\":1},{\"start\":1385993383,\"end\":1386179007,\"shwhr\":52},{\"start\":1387056093,\"end\":1387216706,\"shwhr\":45}]");
try
{
File minProcFile = new File("/tmp/minproc.json");
File rtbFile = new File("/tmp/rtb.json");
minproc = new byte[(int) minProcFile.length()];
rtb = new byte[(int) rtbFile.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(minProcFile));
dis.readFully(minproc);
dis.close();
dis = new DataInputStream(new FileInputStream(rtbFile));
dis.readFully(rtb);
dis.close();
File minProc1File = new File("/tmp/minproc1.json");
File rtb1File = new File("/tmp/rtb1.json");
minproc1 = new byte[(int) minProc1File.length()];
rtb1 = new byte[(int) rtb1File.length()];
dis = new DataInputStream(new FileInputStream(minProc1File));
dis.readFully(minproc1);
dis.close();
dis = new DataInputStream(new FileInputStream(rtb1File));
dis.readFully(rtb1);
dis.close();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
List<ShoppingWindow> shwl=new ArrayList<ShoppingWindow>();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode=null;
//read JSON like DOM Parser
try
{
rootNode = objectMapper.readTree(shwjson);
}catch(java.io.IOException e)
{
System.out.println(e.getMessage());
}
Iterator<JsonNode> records=rootNode.getElements();
while(records.hasNext())
{
JsonNode record = records.next();
long start=record.path("start").getLongValue();
long end=record.path("end").getLongValue();
int shwhr=record.path("shwhr").getIntValue();
ShoppingWindow shw=new ShoppingWindow();
shw.start=start;
shw.end=end;
shw.shwhr=shwhr;
shwl.add(shw);
}
List<ShoppingWindow> shwl1=new ArrayList<ShoppingWindow>();
rootNode=null;
//read JSON like DOM Parser
try
{
rootNode = objectMapper.readTree(shwjson1);
}catch(java.io.IOException e)
{
System.out.println(e.getMessage());
}
records=rootNode.getElements();
while(records.hasNext())
{
JsonNode record = records.next();
long start=record.path("start").getLongValue();
long end=record.path("end").getLongValue();
int shwhr=record.path("shwhr").getIntValue();
ShoppingWindow shw=new ShoppingWindow();
shw.start=start;
shw.end=end;
shw.shwhr=shwhr;
shwl1.add(shw);
}
List<Integer> segments=new ArrayList<Integer>();
segments.add(1);
segments.add(3);
segments.add(5);
segments.add(24);
segments.add(48);
segments.add(30*24);
HashMap<String,StatsCounter> auctMap= getAuctionHistObject(minproc,rtb,segments,shwl);
HashMap<String,StatsCounter> auctMap1= getAuctionHistObject(minproc1,rtb1,segments,shwl1);
//String auctLs=getAuctHistAsJsonString(minproc,rtb,segments,shwl);
String auctLs=getAuctHistAsJsonString(auctMap);
System.out.println("----hist1----");
System.out.println(auctLs);
System.out.println("----hist1----");
String auctLs1=getAuctHistAsJsonString(auctMap1);
System.out.println("----hist2----");
System.out.println(auctLs1);
System.out.println("----hist2----");
HashMap<String,StatsCounter> overallAuct=new HashMap<String,StatsCounter>();
overallAuct=mergeStatsCounter(auctMap,overallAuct);
overallAuct=mergeStatsCounter(auctMap1,overallAuct);
System.out.println(getAuctHistAsJsonString(overallAuct));
//HashMap<String,StatsCounter> bidMap=getBidLandScapeObject(minproc,rtb,null);
//String bls=getBidLandScapeAsJsonString(bidMap);
//System.out.println(bls);
}
}
| true |
5d018c344f68674c2f3a98ddd06a96062b080741
|
Java
|
newmane/401Assignments
|
/CompAssignments/Assignment5/src/comp401/sushi/Eel.java
|
UTF-8
| 152 | 2.0625 | 2 |
[] |
no_license
|
package comp401.sushi;
public class Eel extends IngredientImpl {
public Eel(double amount) {
super(amount, 1.25, false, false, false, "eel");
}
}
| true |
235c4915986c60c9b4a4f1956be38b96bf736f77
|
Java
|
STAMP-project/dspot-experiments
|
/benchmark/test/org/javaee7/websocket/chat/ChatTest.java
|
UTF-8
| 1,714 | 2.09375 | 2 |
[] |
no_license
|
package org.javaee7.websocket.chat;
import ChatClientEndpoint1.TEXT;
import ChatClientEndpoint1.latch;
import ChatClientEndpoint1.response;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.websocket.DeploymentException;
import javax.websocket.Session;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static ChatClientEndpoint1.latch;
/**
*
*
* @author Arun Gupta
*/
@RunWith(Arquillian.class)
public class ChatTest {
@ArquillianResource
URI base;
@Test
@RunAsClient
public void testConnect() throws IOException, InterruptedException, URISyntaxException, DeploymentException {
latch = new CountDownLatch(1);
final Session session1 = connectToServer(ChatClientEndpoint1.class);
Assert.assertNotNull(session1);
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
Assert.assertEquals(TEXT, response);
latch = new CountDownLatch(1);
ChatClientEndpoint2.latch = new CountDownLatch(1);
final Session session2 = connectToServer(ChatClientEndpoint2.class);
Assert.assertNotNull(session2);
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
Assert.assertTrue(ChatClientEndpoint2.latch.await(2, TimeUnit.SECONDS));
Assert.assertEquals(ChatClientEndpoint2.TEXT, response);
Assert.assertEquals(ChatClientEndpoint2.TEXT, ChatClientEndpoint2.response);
}
}
| true |
a61fa7c4ab5f2fcfd2d46b0dcdde6081d0de7f82
|
Java
|
sovannotychea/wtf
|
/src/main/java/com/example/wtf/repo/ItemRepository.java
|
UTF-8
| 488 | 1.96875 | 2 |
[
"MIT"
] |
permissive
|
package com.example.wtf.repo;
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.example.wtf.model.Item;
/**
* @author sovannoty
*
*/
@RepositoryRestResource(collectionResourceRel = "item", path = "item")
public interface ItemRepository extends PagingAndSortingRepository<Item, Long> {
List<Item> findByNameContainingIgnoreCase( String name);
}
| true |