blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0f8bbd4d6997a0439ff25ce8ee3151d52fb6f850 | 0299bb56554ba9cc075ca24c1dc347b135276be3 | /FFC/src/FFC.java | 5bb1f908ad9d40e0ae90164d79d3e7522db6df18 | [] | no_license | NabajitSaha/Git_Repos | bab6a934c2dccb1c67feba5a86dbb0641d350b75 | f6ba07953a3b5a70fec1d1f382e5272ba92be27b | refs/heads/master | 2021-01-12T05:10:52.933343 | 2017-11-26T06:38:17 | 2017-11-26T06:38:17 | 77,882,159 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,123 | java | import java.util.Scanner;
abstract class furniture
{
double length,width,price;
public void dis(double l,double w, double p)
{
this.length=l;
this.width=w;
this.price=p;
System.out.println("Lenght = "+length);
System.out.println("Width = "+width);
System.out.println("Price = "+price);
}
}
public class FFC extends furniture
{
public int n;
public void input()
{
Scanner x = new Scanner(System.in);
System.out.println("Welcome to Furnture and Fitings Company (FFC) ");
System.out.println("Please Select From The Following Furnitures To Get Details");
System.out.println("1. Chair");
System.out.println("2. Table");
System.out.println("3. BookShelves");
System.out.println("Enter Your Choice - ");
n = x.nextInt();
}
public void display()
{
switch(n)
{
case 1: dis(10,5,250);
break;
case 2: dis(15,7,350);
break;
case 3: dis(20,15,500);
int s =13;
System.out.println("The No Of Shelves are = "+s);
break;
default:
System.out.println("Wrong Input..!! Try Again..!!");
}
}
public static void main(String[] args)
{
FFC f = new FFC();
f.input();
f.display();
}
}
| [
"n4b4jit@gmail.com"
] | n4b4jit@gmail.com |
4f047dfbb8f2c225d48f7879619fab52cce67e2e | 7948969bb631cd3a852f0756978f019194c4fac3 | /code/activitiOA/src/main/java/com/cypher/activiti/model/Leave.java | 4df8a1f3e7b16dec273e1288541c156fa0bbde26 | [] | no_license | biliou/activitiOA | 2e5653bc099c4ec72156b917d0aea3a6250d6d94 | ffe9754fe35d7d774bcdf4037a98aaab604d3e01 | refs/heads/master | 2021-09-07T16:23:20.678873 | 2018-02-26T03:25:46 | 2018-02-26T03:25:46 | 105,358,241 | 0 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,720 | java | package com.cypher.activiti.model;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Leave {
private Long leaveId;
private Long leaveUserId;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date leaveDate;
private Integer leaveDays;
private String leaveReason;
private String remark;
private Integer leaveState;
private String processInstanceId;
public Long getLeaveId() {
return leaveId;
}
public void setLeaveId(Long leaveId) {
this.leaveId = leaveId;
}
public Long getLeaveUserId() {
return leaveUserId;
}
public void setLeaveUserId(Long leaveUserId) {
this.leaveUserId = leaveUserId;
}
public Date getLeaveDate() {
return leaveDate;
}
public void setLeaveDate(Date leaveDate) {
this.leaveDate = leaveDate;
}
public Integer getLeaveDays() {
return leaveDays;
}
public void setLeaveDays(Integer leaveDays) {
this.leaveDays = leaveDays;
}
public String getLeaveReason() {
return leaveReason;
}
public void setLeaveReason(String leaveReason) {
this.leaveReason = leaveReason == null ? null : leaveReason.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public Integer getLeaveState() {
return leaveState;
}
public void setLeaveState(Integer leaveState) {
this.leaveState = leaveState;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
} | [
"644495757@qq.com"
] | 644495757@qq.com |
35c8b70c5d3a38f2d13bbd5de6c2b8972c40dcf4 | 2633fb1280a23e747162d44ae7e8694401b4da54 | /VidyoPortal/src/com/vidyo/portal/admin/v1_1/TransferParticipantResponse.java | da18399307ce3fabe993194d06eaa06f5691b3c1 | [] | no_license | rahitkumar/VidyoPortal | 2159cc515acd22471f484867805cd4a4105f209f | 60101525c0e2cb1a50c55cbb94deb7c44685f1ab | refs/heads/master | 2020-06-16T20:16:33.920559 | 2019-07-07T19:47:47 | 2019-07-07T19:47:47 | 195,687,237 | 4 | 3 | null | null | null | null | UTF-8 | Java | false | false | 18,691 | java |
/**
* TransferParticipantResponse.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST)
*/
package com.vidyo.portal.admin.v1_1;
/**
* TransferParticipantResponse bean class
*/
@SuppressWarnings({"unchecked","unused"})
public class TransferParticipantResponse
implements org.apache.axis2.databinding.ADBBean{
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName(
"http://portal.vidyo.com/admin/v1_1",
"TransferParticipantResponse",
"ns1");
/**
* field for OK
*/
protected com.vidyo.portal.admin.v1_1.OK_type0 localOK ;
/**
* Auto generated getter method
* @return com.vidyo.portal.admin.v1_1.OK_type0
*/
public com.vidyo.portal.admin.v1_1.OK_type0 getOK(){
return localOK;
}
/**
* Auto generated setter method
* @param param OK
*/
public void setOK(com.vidyo.portal.admin.v1_1.OK_type0 param){
this.localOK=param;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME);
return factory.createOMElement(dataSource,MY_QNAME);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://portal.vidyo.com/admin/v1_1");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":TransferParticipantResponse",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"TransferParticipantResponse",
xmlWriter);
}
}
if (localOK==null){
throw new org.apache.axis2.databinding.ADBException("OK cannot be null!!");
}
localOK.serialize(new javax.xml.namespace.QName("http://portal.vidyo.com/admin/v1_1","OK"),
xmlWriter);
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://portal.vidyo.com/admin/v1_1")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(new javax.xml.namespace.QName("http://portal.vidyo.com/admin/v1_1",
"OK"));
if (localOK==null){
throw new org.apache.axis2.databinding.ADBException("OK cannot be null!!");
}
elementList.add(localOK);
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static TransferParticipantResponse parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
TransferParticipantResponse object =
new TransferParticipantResponse();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"TransferParticipantResponse".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (TransferParticipantResponse)com.vidyo.portal.admin.v1_1.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://portal.vidyo.com/admin/v1_1","OK").equals(reader.getName())){
object.setOK(com.vidyo.portal.admin.v1_1.OK_type0.Factory.parse(reader));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| [
"rahitkumar@crap.com"
] | rahitkumar@crap.com |
f278265157b43d13b57e807c7cfe6a39570520dc | d971587646d8a3814b6cd066cc4006045098cef6 | /src/Student.java | f37c116cc30a937162b5c8f2354c8257a6f97ac1 | [] | no_license | phoonjoe/P4Q2 | 8ef2931b12e615c8e8a6082cfb02e5cf9bff2893 | 3b8fa44c2c925c3f7f5be825d90fb5d485a8188d | refs/heads/master | 2022-11-19T09:49:18.962491 | 2020-07-16T02:43:58 | 2020-07-16T02:43:58 | 280,021,313 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,782 | java |
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Missing One
*/
public class Student {
private String studentID;
private String name;
private int quizzesTaken;
private int totalScore;
private static double contribution;
public Student() {
this("","");
}
public Student(String studentID, String name) {
this.studentID = studentID;
this.name = name;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuizzesTaken() {
return quizzesTaken;
}
public int getTotalScore() {
return totalScore;
}
public void addQuiz(int score) {
Scanner scan = new Scanner(System.in);
while (score < 0 || score > 10) {
System.out.println("Invalid score!(Max 10)");
System.out.println("Enter score: ");
score = scan.nextInt();
}
totalScore += score;
quizzesTaken++;
}
public double getAverageScore() {
double avg = (double) totalScore / quizzesTaken;
return avg;
}
public static double getContribution() {
return contribution;
}
public static void setContribution(double contribution) {
Student.contribution = contribution;
}
}
| [
"Missing One@DESKTOP-MI1RHTP"
] | Missing One@DESKTOP-MI1RHTP |
7c0e4a973f7f61deff56e60a5c6aa3dd77950e18 | 884684fb03344ae63f904597af75433e7dae95c4 | /src/test/java/com/cybertek/tests/day8_windows_javafaker/JavaFakerPractice.java | 3a288fd7127b1b2c3adfb5ffb3d65d68ff633882 | [] | no_license | ma9985/SeleniumPrjctB22 | b5917f4b2aa16d5f16bde0e80780307bb525234a | c59e73b2082a2483720450ce5729270d7de52600 | refs/heads/master | 2023-06-01T12:53:10.524273 | 2021-06-27T21:42:08 | 2021-06-27T21:42:08 | 370,317,932 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 468 | java | package com.cybertek.tests.day8_windows_javafaker;
import com.github.javafaker.Faker;
import org.testng.annotations.Test;
public class JavaFakerPractice {
@Test
public void test1() {
Faker faker = new Faker();
String fullName = faker.name().fullName();
System.out.println("FullName = " + fullName);
String chuckNorris = faker.chuckNorris().fact();
System.out.println("chuckNorris = " + chuckNorris);
}
}
| [
"moeq24@yahoo.com"
] | moeq24@yahoo.com |
45961038f1fe0b8a11e7c53deabe1093639b03aa | 1fb3b6485c756f7485329f759c2cf32b5f3c7902 | /android/app/src/main/java/com/instadog/MainApplication.java | 091e17c106684ac659ceaf2e72d06718af4faf6d | [] | no_license | jeflucas/InstaDog | 9a478358ddade2575ff2bd7aceaad10ee552ba33 | 4296c8b067fa1e3ed30f3893378fdafa74189c6c | refs/heads/main | 2023-08-07T08:24:01.146019 | 2021-10-02T21:10:45 | 2021-10-02T21:10:45 | 412,812,138 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,863 | java | package com.instadog;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.instadog.generated.BasePackageList;
import org.unimodules.adapters.react.ReactAdapterPackage;
import org.unimodules.adapters.react.ModuleRegistryAdapter;
import org.unimodules.adapters.react.ReactModuleRegistryProvider;
import org.unimodules.core.interfaces.Package;
import org.unimodules.core.interfaces.SingletonModule;
import expo.modules.updates.UpdatesController;
import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
public class MainApplication extends Application implements ReactApplication {
private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
new BasePackageList().getPackageList()
);
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new ModuleRegistryAdapter(mModuleRegistryProvider));
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
@Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();
}
@Override
protected @Nullable String getJSBundleFile() {
if (BuildConfig.DEBUG) {
return super.getJSBundleFile();
} else {
return UpdatesController.getInstance().getLaunchAssetFile();
}
}
@Override
protected @Nullable String getBundleAssetName() {
if (BuildConfig.DEBUG) {
return super.getBundleAssetName();
} else {
return UpdatesController.getInstance().getBundleAssetName();
}
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
if (!BuildConfig.DEBUG) {
UpdatesController.initialize(this);
}
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.instadog.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
| [
"jef.lucas@hotmail.co.uk"
] | jef.lucas@hotmail.co.uk |
ab31d3c3890f261a821093e37896cdf9131be272 | eadf55dc30736da98086fe1e4d7db46eee210792 | /methods/Inventory.java | 5d67f5ded7e26cd410ab1b501856644c9cda6223 | [] | no_license | smithtrenton/DynaMac | df7d2fe6ce8550ffd22f9addaf8b87ca19d34926 | 4ae23cddee8f2cb24aef70b7c2f1d02693a93190 | refs/heads/master | 2021-01-25T00:29:08.521788 | 2012-09-16T09:40:24 | 2012-09-16T09:40:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,123 | java | package org.dynamac.bot.api.methods;
import java.util.ArrayList;
import org.dynamac.bot.api.wrappers.Interface;
import org.dynamac.bot.api.wrappers.InterfaceChild;
import org.dynamac.bot.api.wrappers.InterfaceItem;
public class Inventory {
public static int getCount(){
return getItems().length;
}
public static InterfaceItem[] getItems(){
ArrayList<InterfaceItem> items = new ArrayList<InterfaceItem>();
Interface inventory = Client.getInterfaceCache()[763];
if(inventory!=null && inventory.getChildren().length>0){
InterfaceChild inventoryItems = inventory.getChildren()[0];
if(inventoryItems!=null){
for(InterfaceChild slot : inventoryItems.getChildren()){
if(slot!=null){
if(slot.getComponentID()!=-1){
items.add(new InterfaceItem(slot));
}
}
}
}
}
else{
inventory = Client.getInterfaceCache()[679];
if(inventory!=null && inventory.getChildren().length>0){
InterfaceChild inventoryItems = inventory.getChildren()[0];
if(inventoryItems!=null){
for(InterfaceChild slot : inventoryItems.getChildren()){
if(slot!=null){
if(slot.getComponentID()!=-1){
items.add(new InterfaceItem(slot));
}
}
}
}
}
}
return items.toArray(new InterfaceItem[]{});
}
public static InterfaceItem getSelectedItem(){
for(InterfaceItem i : getItems())
if(i.isSelected())
return i;
return null;
}
public static boolean isInventoryFull(){
return getCount()>27;
}
/**
*@author VelvetRevolver
*@param ID of the InterfaceItem
*@return InterfaceItem in the Inventory
**/
public static InterfaceItem getItemById(final int itemId) {
for (InterfaceItem i : Inventory.getItems()) {
if (i != null) {
if (i.getID() == itemId) {
return i;
}
}
}
return null;
}
/**
*@author VelvetRevolver
*@param ID of the InterfaceItem
*@return true if Inventory contains the InterfaceItem, false if not
**/
public static boolean containsItemId(final int itemId) {
return getItemById(itemId) != null;
}
/**
*@author VelvetRevolver
*@param Name of the InterfaceItem
*@return InterfaceItem in the Inventory
**/
public static InterfaceItem getItemByName(String itemName) {
for (InterfaceItem i : Inventory.getItems()) {
if(i != null && i.getName().length() > 0) {
if (i.getName().toLowerCase().equals(itemName.toString().toLowerCase())) {
return i;
}
}
}
return null;
}
/**
*@author VelvetRevolver
*@param Name of the InterfaceItem
*@return true if Inventory contains the InterfaceItem, false if not
**/
public static boolean containsItemName(String itemName) {
return getItemByName(itemName) != null;
}
/**
*@author VelvetRevolver , Marneus901
*@param Ids of the InterfaceItems you want to look for
*@return InterfaceItems with the Selected Ids
**/
public static InterfaceItem[] getItemsByIds(int... ids){
ArrayList<InterfaceItem> items = new ArrayList<InterfaceItem>();
for(InterfaceItem item : getItems()){
for(int i : ids){
if(i==item.getID()){
items.add(item);
break;
}
}
}
return items.toArray(new InterfaceItem[]{});
}
/**
*@author VelvetRevolver, Marneus901
*@param Ids of the InterfaceItems you want to count
*@param true, if you want to get the InterfaceItems of the selected ids. false, if you want the InterfaceItems EXCEPT the selected ids.
*@return amount of InterfaceItems
**/
public static InterfaceItem[] getItems(boolean selected, int...ids){
ArrayList<InterfaceItem> items = new ArrayList<InterfaceItem>();
for(InterfaceItem item : getItems())
items.add(item);
for(InterfaceItem item : items){
boolean isListed=false;
for(int i : ids){
if(i==item.getID()){
isListed=true;
break;
}
}
if((isListed && !selected) || (!isListed && selected)){
items.remove(item);
}
}
return items.toArray(new InterfaceItem[]{});
}
public static int getCount(final int... ids){
return getItems(true, ids).length;
}
public static int getCountExcept(final int... ids) {
return getItems(false, ids).length;
}
}
| [
"circadian@live.com"
] | circadian@live.com |
c045361a1d41be7c38d097acecc12d399c80b935 | d98fdd2d9f5f58d24fc7f675e0096982aa70fc02 | /sbbocianazercustomstarter/bocianazer-spring-boot-autoconfigure/src/main/java/com/mbojanow/bocianazer/autoconfigure/BocianazerAutoConfiguration.java | 6afbf6a258be26f439de8f5f73418e9a09942343 | [] | no_license | Mbojanow/CustomSpringBootStarter | 70ced370c645b0ccb4cb5c772515bf6b393a0719 | fb6510c50c9ea6b582f9eeb72cf16d0324c697f5 | refs/heads/master | 2020-03-18T08:53:57.068301 | 2018-05-23T08:06:26 | 2018-05-23T08:06:26 | 134,533,462 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,157 | java | package com.mbojanow.bocianazer.autoconfigure;
import com.mbojanow.BocianConfiguration;
import com.mbojanow.BocianType;
import com.mbojanow.Bocianazer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static com.mbojanow.BocianazerConfigurationParameters.BOCIAN_NUM;
import static com.mbojanow.BocianazerConfigurationParameters.BOCIAN_SEED;
import static com.mbojanow.BocianazerConfigurationParameters.BOCIAN_TYPE;
@Configuration
@ConditionalOnClass(Bocianazer.class)
@EnableConfigurationProperties(BocianazerProperties.class)
public class BocianazerAutoConfiguration {
private final BocianazerProperties bocianazerProperties;
@Autowired
public BocianazerAutoConfiguration(BocianazerProperties bocianazerProperties) {
this.bocianazerProperties = bocianazerProperties;
}
@Bean
@ConditionalOnMissingBean
public BocianConfiguration bocianConfiguration() {
final String bocianType = bocianazerProperties.getBocianType() == null ? BocianType.WHITE.name() : bocianazerProperties.getBocianType();
final String bocianNumber = bocianazerProperties.getBocianNumber() == null ? "5": bocianazerProperties.getBocianNumber();
final String bocianSeed = bocianazerProperties.getBocianSeed() == null ? "1337" : bocianazerProperties.getBocianSeed();
final BocianConfiguration bocianConfiguration = new BocianConfiguration();
bocianConfiguration.put(BOCIAN_TYPE, bocianType);
bocianConfiguration.put(BOCIAN_NUM, bocianNumber);
bocianConfiguration.put(BOCIAN_SEED, bocianSeed);
return bocianConfiguration;
}
@Bean
@ConditionalOnMissingBean
public Bocianazer bocianazer(final BocianConfiguration bocianConfiguration) {
return new Bocianazer(bocianConfiguration);
}
}
| [
"michal.bojanowski@misys.com"
] | michal.bojanowski@misys.com |
c3b1d93e62dc8668479a1a4c07e9126483e72542 | 3d797df3c50b5a0ada67a7031baa32a284b5b9c8 | /Clase11/src/clase11/test/PruebaDAO.java | 7174892395fc9e9656ec6b173b3053c475f65f2a | [] | no_license | martindapol/java-intermedio-2020 | 75db918028c4ec04d9333604b8b5981b4490e883 | 0fa291027a600243635c8ab4ad71bb6fcca5d6bb | refs/heads/master | 2022-11-19T09:44:55.573238 | 2020-07-18T17:34:26 | 2020-07-18T17:34:26 | 255,714,434 | 0 | 3 | null | null | null | null | UTF-8 | Java | false | false | 754 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clase11.test;
import clase11.dao.DAOException;
import clase11.dao.VehiculoDAO;
import clase11.dao.VehiculoDAOFileImpl;
import clase11.entidades.Vehiculo;
/**
*
* @author george
*/
public class PruebaDAO {
public static void main(String[] args) {
VehiculoDAO dao = new VehiculoDAOFileImpl();
try {
for (Vehiculo v : dao.findAll()) {
System.out.println(v);
}
} catch (DAOException de) {
System.err.println("Error en DAO");
de.printStackTrace();
}
}
}
| [
"Jorge.harach@gmail.com"
] | Jorge.harach@gmail.com |
d0f8e2a3aea7d0b5971cccbfa30f4cdddc9cbca8 | 35fb2db5257933cbe07eb48b46211552700d7fce | /src/main/java/hayden/applogger/type/TransactionFieldType.java | b27a89e05f946da8c6b5b86df4dc0f6896285fc9 | [] | no_license | tomhaydenss/hayden-applogger | 0b49736ecc0d2597accd59b9be3cdb8077f2f4ad | 3809b48a44c9e808523627561b325526640c70fa | refs/heads/master | 2021-01-17T12:03:50.845914 | 2014-08-25T21:14:16 | 2014-08-25T21:14:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 251 | java | package hayden.applogger.type;
public enum TransactionFieldType {
CUSTOM_TYPE,
CUSTOMER,
RECEIVER,
AMOUNT,
CC_TOKEN,
CC_LAST4DIGISTS,
CC_BRAND,
CHANNEL,
TRANSACTION_ID,
TID,
AUTH_CODE,
NSU,
DTLOG,
OBS
}
| [
"tomhaydenss@gmail.com"
] | tomhaydenss@gmail.com |
9e595e6dbd33035f90ac2e3f84dda549cc70e0c2 | e22cb5601e836c60d7b5ebbbe9821ab1aee2a1be | /app/src/test/java/com/example/testinglab6/ExampleUnitTest.java | 0ff6fc50f9958757272170c9a8a8a7d104b56bdb | [] | no_license | vglinca/Testing_Android | 8eb524c6de66cccec166ba4520c90f62fceeec33 | f8a72969b3ac58cea206280cff7dbc332168340f | refs/heads/master | 2022-05-24T14:05:01.902672 | 2020-05-02T21:23:38 | 2020-05-02T21:23:38 | 260,743,257 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 374 | java | package com.example.testinglab6;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"vitalii.glinka@yahoo.com"
] | vitalii.glinka@yahoo.com |
e03efaa153844c2d90d9eaee32b6f17fd7f6eb1d | 0580305dfdfadedfbdc63926af330afb7f5cb0a5 | /src/test/java/com/anizzzz/sfmovies/controller/MovieDataControllerTest.java | b6569c683b40d33379fe74cf1b7ae76d2ec022b3 | [] | no_license | anizzzzzzzz/SF-Movie-Backend | 57768030a829ae5dc6a57db57b50bf7af7b750e4 | e61352905b0f9c4610b3aee4a3a8abe193807ca3 | refs/heads/master | 2022-11-22T23:41:27.046809 | 2020-07-21T06:39:12 | 2020-07-21T06:39:12 | 280,471,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,196 | java | package com.anizzzz.sfmovies.controller;
import com.anizzzz.sfmovies.dto.DataQuery;
import com.anizzzz.sfmovies.model.MovieData;
import com.anizzzz.sfmovies.service.IMovieDataService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.servlet.MockMvc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class MovieDataControllerTest {
private MockMvc mockMvc;
@Mock
private IMovieDataService movieDataService;
@InjectMocks
private MovieDataController movieDataController;
private List<MovieData> movieDatas;
@Before
public void setup(){
movieDatas = new ArrayList<>();
movieDatas.add(new MovieData("Harry Potter", "2002", "USA", "Madan Bahadur",
"H.P.Prod", "", "JK Rowlings", "Daniel Radcliffe", "Ema Watson", "Rupert Grint"));
movieDatas.add(new MovieData("Always Be My Maybe", "2019", "Heart of the City Farmers Market at UN Plaza", "",
"Isla Productions, LLC", "Netflix",
"Michael Golamco, Randall Park, Ali Wong", "Ali Wong", "Randall Park", "Keanu Reeves"));
movieDatas.add(new MovieData("Ant-Man", "2015", "Grant between Bush and Broadway", "Driving shots",
"PYM Particles Productions, LLC", "Walt Disney Studios Motion Pictures",
"Gabriel Ferrari", "Michael Douglas", "Paul Rudd", ""));
}
@Test
public void testAutocomplete_WhenAutocompletionListEmpty() {
DataQuery query = new DataQuery();
when(movieDataService.autocompleteData(query)).thenReturn(Collections.emptyList());
ResponseEntity<List<MovieData>> responseEntity = (ResponseEntity<List<MovieData>>) movieDataController.autocompleteData(query);
Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
Assert.assertNotNull(responseEntity.getBody());
Assert.assertTrue(responseEntity.getBody().isEmpty());
}
@Test
public void testAutocomplete_WhenAutocompletionListNotEmpty(){
DataQuery query = new DataQuery();
when(movieDataService.autocompleteData(query)).thenReturn(movieDatas);
ResponseEntity<List<MovieData>> responseEntity = (ResponseEntity<List<MovieData>>) movieDataController.autocompleteData(query);
Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
Assert.assertNotNull(responseEntity.getBody());
Assert.assertFalse(responseEntity.getBody().isEmpty());
List<MovieData> responses = responseEntity.getBody();
Assert.assertEquals(movieDatas.size(), responses.size());
Assert.assertEquals(movieDatas.get(0).getTitle(), responses.get(0).getTitle());
}
}
| [
"anish.maharjan@infotmt.com"
] | anish.maharjan@infotmt.com |
097deaab19e0bb305ed3d7b2abd427ad3bb7868b | 1fcb62696ec7413cc6a2e5c8c67d430d51a665c7 | /src/iso-tc211-xml/src/generated/java/org/isotc211/iso19139/gts/impl/GTSFactoryImpl.java | b95eb2e8997ccbb4a5e0390e46f661ac6eb5af6d | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | florianesser/excel-adapter | cd1836dad969e6b481396997a3f4abd4e38029e9 | 16b98486da3702ee958c5c0155a77520a0722906 | refs/heads/master | 2021-01-08T08:11:40.938728 | 2019-05-24T10:02:34 | 2019-05-24T10:02:34 | 241,966,970 | 0 | 0 | NOASSERTION | 2020-02-20T19:06:34 | 2020-02-20T19:06:34 | null | UTF-8 | Java | false | false | 2,812 | java | /**
*/
package org.isotc211.iso19139.gts.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.isotc211.iso19139.gts.*;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class GTSFactoryImpl extends EFactoryImpl implements GTSFactory
{
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static GTSFactory init()
{
try
{
GTSFactory theGTSFactory = (GTSFactory)EPackage.Registry.INSTANCE.getEFactory(GTSPackage.eNS_URI);
if (theGTSFactory != null)
{
return theGTSFactory;
}
}
catch (Exception exception)
{
EcorePlugin.INSTANCE.log(exception);
}
return new GTSFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public GTSFactoryImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass)
{
switch (eClass.getClassifierID())
{
case GTSPackage.TM_PERIOD_DURATION_PROPERTY_TYPE: return createTMPeriodDurationPropertyType();
case GTSPackage.TM_PRIMITIVE_PROPERTY_TYPE: return createTMPrimitivePropertyType();
case GTSPackage.DOCUMENT_ROOT: return createDocumentRoot();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TMPeriodDurationPropertyType createTMPeriodDurationPropertyType()
{
TMPeriodDurationPropertyTypeImpl tmPeriodDurationPropertyType = new TMPeriodDurationPropertyTypeImpl();
return tmPeriodDurationPropertyType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TMPrimitivePropertyType createTMPrimitivePropertyType()
{
TMPrimitivePropertyTypeImpl tmPrimitivePropertyType = new TMPrimitivePropertyTypeImpl();
return tmPrimitivePropertyType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DocumentRoot createDocumentRoot()
{
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public GTSPackage getGTSPackage()
{
return (GTSPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static GTSPackage getPackage()
{
return GTSPackage.eINSTANCE;
}
} //GTSFactoryImpl
| [
"fe@bespire.de"
] | fe@bespire.de |
8d6c8a8ef4b23243696a518b57ae6902458d53be | 2dec8224aa52e977cc51712ddd347748cffc2b37 | /jetcd-spring-boot-starter/src/main/java/com/technology/config/EnableJetcd.java | 1ec3ca85bcf30de7b6168a1abf60e5e7a07d6903 | [] | no_license | smile-monkey/jetcd-spring-boot-starter | fa4a98bdf5eb9883103a73fcd2275b688d59af82 | 2bb012bae1fe448ad2a3789a9f2f0d29dea68c2b | refs/heads/master | 2020-06-04T00:24:54.148228 | 2019-08-18T06:48:52 | 2019-08-18T06:48:52 | 191,794,043 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 414 | java | package com.technology.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(JetcdAutoConfiguration.class) //采用导入方式,将JetcdAutoConfiguration托管。用户手动开启starter包的自动配置功能; 等价于spring.factories
public @interface EnableJetcd {
}
| [
"x52technology@foxmail.com"
] | x52technology@foxmail.com |
36a47fd35d793199c6cc8c29f12e980fd4b4897e | 7ed824516fdd7a15511a7a5bb930a544103eb1d4 | /app/src/main/java/com/yz/yzdemo/mvvmbase/BaseRepository.java | 294d9bbcab630c816475644c91420e7fb424fe7f | [] | no_license | Yzdream/YzDemo | f49002c83e114bdc49726723e6f4d82b9f535d94 | 7d47fa06c60c684d3256ac4bb461a0a0f052d34a | refs/heads/master | 2020-05-26T07:29:48.436604 | 2019-12-05T07:42:41 | 2019-12-05T07:42:41 | 188,150,953 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 620 | java | package com.yz.yzdemo.mvvmbase;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
public class BaseRepository {
private CompositeSubscription mCompositeSubscription;
protected void addSubscribe(Subscription subscription) {
if (mCompositeSubscription == null) {
mCompositeSubscription = new CompositeSubscription();
}
mCompositeSubscription.add(subscription);
}
public void unSubscribe() {
if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
mCompositeSubscription.clear();
}
}
}
| [
"yizheng@ipubtrans.com"
] | yizheng@ipubtrans.com |
28e32c046a0d17c7c0ca8a70b4cd7b6feedd564e | 14b0d82ebbcc4f5df413ff2f8203845c021b1f24 | /app/src/main/java/com/kangzhan/student/Teacher/person_data/Mydata.java | d7d87af0ab8df9345ec490f817d0f02fd32cb820 | [] | no_license | jianghe314/Demo | be2917c17a11b33d7d4cb8fdf90204f7fde56acb | a0e105094b9a696e4daf4550066f6be244cb217a | refs/heads/master | 2020-04-07T18:50:21.310619 | 2018-11-22T01:23:46 | 2018-11-22T01:23:46 | 158,625,681 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 30,220 | java | package com.kangzhan.student.Teacher.person_data;
import android.Manifest;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.kangzhan.student.BuildConfig;
import com.kangzhan.student.Debug.mLog;
import com.kangzhan.student.ForgotPasswordActivity;
import com.kangzhan.student.R;
import com.kangzhan.student.ShowUI.mToast;
import com.kangzhan.student.ShowUI.showMessage;
import com.kangzhan.student.ShowUI.showProgress;
import com.kangzhan.student.Student.person_data_activity.PersondataActivity;
import com.kangzhan.student.Teacher.bean.TeacherInfo;
import com.kangzhan.student.com.BaseActivity;
import com.kangzhan.student.mInterface.StudentInterface.student;
import com.kangzhan.student.mInterface.TeacherInterface.teacher;
import com.kangzhan.student.utils.FileUtils;
import com.kangzhan.student.utils.ImageCompress;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import de.hdodenhof.circleimageview.CircleImageView;
public class Mydata extends BaseActivity implements View.OnClickListener{
private EditText phone_Num,address,qq,wechat,email,id,carInfo,price;
private CircleImageView header;
private TextView name,sex,train,evolu,school;
private Button save;
private Gson gson;
private String mmsg,msex;
private TeacherInfo info;
//
//更换头像
private File mTmpFile;
private File mCropImageFile;
private static final int REQUEST_CAMERA = 100;
private static final int REQUEST_GALLERY = 101;
private static final int REQUEST_CROP = 102;
private BottomSheetDialog dialog;
private String[] strSex={"男","女"};
//
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0000:
runOnUiThread(new Runnable() {
@Override
public void run() {
showProgress.showProgress(Mydata.this,"加载中...");
}
});
break;
case 0011:
runOnUiThread(new Runnable() {
@Override
public void run() {
showProgress.showProgress(Mydata.this,"发送中...");
}
});
break;
case 1122:
runOnUiThread(new Runnable() {
@Override
public void run() {
showProgress.closeProgress();
mToast.showText(getApplicationContext(),mmsg);
}
});
break;
case 1111:
runOnUiThread(new Runnable() {
@Override
public void run() {
showProgress.closeProgress();
name.setText(info.getName());
sex.setText(info.getSex());
phone_Num.setText(info.getMobile());
address.setText(info.getAddress());
qq.setText(info.getQqnum());
wechat.setText(info.getWechatnum());
email.setText(info.getEmail());
id.setText(info.getOccupationno());
carInfo.setText(info.getBrand()+"-"+info.getLicnum());
train.setText(info.getSubject_name());
price.setText(info.getSubject_price()+"元/时");
evolu.setText(info.getScore());
school.setText(info.getInst_name());
Glide.with(Mydata.this).load(teacher.teacherPhoto(Mydata.this)).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).error(R.drawable.header).crossFade().into(header);
}
});
break;
case 2222:
runOnUiThread(new Runnable() {
@Override
public void run() {
showProgress.showProgress(Mydata.this,"上传中...");
}
});
break;
case 3333:
runOnUiThread(new Runnable() {
@Override
public void run() {
showProgress.closeProgress();
Toast.makeText(getApplicationContext(),mmsg,Toast.LENGTH_SHORT).show();
}
});
break;
case 9999:
runOnUiThread(new Runnable() {
@Override
public void run() {
showProgress.closeProgress();
showMessage.showMsg(Mydata.this,"网络连接异常,请检查网络连接");
}
});
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mydata);
Toolbar toolbar= (Toolbar) findViewById(R.id.teacher_mydata_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar=getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
gson=new Gson();
initView();
}
private void initView() {
header= (CircleImageView) findViewById(R.id.teacher_mydata_header);
header.setOnClickListener(this);
name= (TextView) findViewById(R.id.teacher_mydata_name);
sex= (TextView) findViewById(R.id.teacher_mydata_sex);
phone_Num= (EditText) findViewById(R.id.teacher_mydata_Phone);
address= (EditText) findViewById(R.id.teacher_mydata_address);
qq= (EditText) findViewById(R.id.teacher_mydata_qq);
wechat= (EditText) findViewById(R.id.teacher_mydata_wechat);
email= (EditText) findViewById(R.id.teacher_mydata_email);
id= (EditText) findViewById(R.id.teacher_mydata_ID);
carInfo= (EditText) findViewById(R.id.teacher_mydata_carInfo);
train= (TextView) findViewById(R.id.teacher_mydata_train);
price= (EditText) findViewById(R.id.teacher_mydata_price);
evolu= (TextView) findViewById(R.id.teacher_mydata_eval);
school= (TextView) findViewById(R.id.teacher_mydata_school);
save= (Button) findViewById(R.id.teacher_mydata_save);
save.setOnClickListener(this);
sex.setOnClickListener(this);
Message msg=new Message();
msg.what=0000;
handler.sendMessage(msg);
new Thread(new Runnable() {
@Override
public void run() {
sendRequest();
}
}).start();
}
private void sendRequest() {
Request<JSONObject> request=NoHttp.createJsonObjectRequest(teacher.teacherMydata(), RequestMethod.GET);
request.add("key",teacher.teacherKey(getApplicationContext()));
getRequestQueue().add(1, request, new OnResponseListener<JSONObject>() {
@Override
public void onStart(int what) {
}
@Override
public void onSucceed(int what, Response<JSONObject> response) {
mLog.i("response","->"+response.get().toString());
try {
JSONObject object=new JSONObject(response.get().toString());
String code=object.getString("code");
if(code.equals("200")){
String data=object.getString("data");
JSONArray array=new JSONArray(data);
if(array.length()>0){
for (int i = 0; i <array.length(); i++) {
JSONObject obj=array.getJSONObject(i);
info=gson.fromJson(obj.toString(),TeacherInfo.class);
}
handler.sendEmptyMessage(1111);
}
}else {
Message msg=new Message();
msg.what=9999;
handler.sendMessage(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
handler.sendEmptyMessage(9999);
}
@Override
public void onFinish(int what) {
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
case R.id.teacher_mydata_edit:
chanceEdit();
break;
}
return true;
}
private void chanceEdit() {
sex.setEnabled(true);
phone_Num.setEnabled(true);
address.setEnabled(true);
qq.setEnabled(true);
wechat.setEnabled(true);
email.setEnabled(true);
id.setEnabled(true);
carInfo.setEnabled(true);
price.setEnabled(true);
save.setEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.teacher_mydata_edit,menu);
return true;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.teacher_mydata_save:
if(isRight()){
final Dialog dialog=new Dialog(Mydata.this);
View view=LayoutInflater.from(Mydata.this).inflate(R.layout.item_change_mydata,null);
final EditText phoneNum= (EditText) view.findViewById(R.id.item_change_mydata_phone);
final EditText code= (EditText) view.findViewById(R.id.item_change_mydata_getCode);
Button send= (Button) view.findViewById(R.id.item_change_mydata_sure);
final TextView getCode= (TextView) view.findViewById(R.id.item_change_mydata_code);
getCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(phoneNum.getText().toString().trim().equals("")){
mToast.showText(getApplicationContext(),"手机号码不能为空");
}else {
getCode.setEnabled(false);
TimeCount(getCode,60*1000,1000);
mToast.showText(getApplicationContext(),"已发送");
new Thread(new Runnable() {
@Override
public void run() {
getRequestCode(phoneNum.getText().toString().trim());
}
}).start();
}
}
});
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(phoneNum.getText().toString().trim().equals("")){
mToast.showText(getApplicationContext(),"手机号码不能为空");
}else {
if(code.getText().toString().trim().equals("")){
mToast.showText(getApplicationContext(),"验证码不能为空");
}else {
new Thread(new Runnable() {
@Override
public void run() {
sendInfoToServer(code.getText().toString().trim());
}
}).start();
dialog.dismiss();
}
}
}
});
dialog.setContentView(view);
dialog.show();
}
break;
case R.id.teacher_mydata_header:
//修改头像
addMenu();
break;
case R.id.take_photo:
//打开相机
if(mcheckPermission()){
camera();
}
break;
case R.id.open_gallery:
//打开相册
gallery();
break;
case R.id.teacher_mydata_sex:
AlertDialog.Builder builder=new AlertDialog.Builder(Mydata.this);
builder.setItems(strSex, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
sex.setText("男");
msex="1";
dialog.dismiss();
}else if(which==1){
sex.setText("女");
msex="2";
dialog.dismiss();
}
}
});
builder.setCancelable(false);
builder.create().show();
break;
}
}
private boolean mcheckPermission() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
int checkPermission_WR= ContextCompat.checkSelfPermission(Mydata.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int checkPermission_CAMERA=ContextCompat.checkSelfPermission(Mydata.this,Manifest.permission.CAMERA);
if(checkPermission_WR!= PackageManager.PERMISSION_GRANTED && checkPermission_CAMERA!=PackageManager.PERMISSION_GRANTED){
//没有授权,请求授权
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},1);
return false;
}else {
return true;
}
}else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1:
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
camera();
}else {
mcheckPermission();
mToast.showText(getApplicationContext(),"没有权限使用相机和存储文件!");
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
private void getRequestCode(String phoneNum) {
Request<JSONObject> getcode=NoHttp.createJsonObjectRequest(student.getCode(),RequestMethod.GET);
getcode.add("type",2);
getcode.add("id",teacher.teacherId(Mydata.this));
getcode.add("phone",phoneNum);
getRequestQueue().add(3, getcode, new OnResponseListener<JSONObject>() {
@Override
public void onStart(int what) {
}
@Override
public void onSucceed(int what, Response<JSONObject> response) {
try {
JSONObject object=new JSONObject(response.get().toString());
mmsg=object.getString("msg");
Message msg=new Message();
msg.what=1122;
handler.sendMessage(msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
handler.sendEmptyMessage(9999);
}
@Override
public void onFinish(int what) {
}
});
}
private void TimeCount (final TextView getCode, long TotalTime, long intervalTime){
CountDownTimer time=new CountDownTimer(TotalTime,intervalTime) {
@Override
public void onTick(long millisUntilFinished) {
getCode.setText((millisUntilFinished/1000)+"秒");
}
@Override
public void onFinish() {
getCode.setEnabled(true);
getCode.setText("获取验证码");
}
};
time.start();
}
private void sendInfoToServer(String mcode) {
Request<JSONObject> request=NoHttp.createJsonObjectRequest(teacher.teacherChangeData(),RequestMethod.POST);
request.add("key",teacher.teacherKey(getApplicationContext()));
request.add("code",mcode);
request.add("mobile",phone_Num.getText().toString().trim());
request.add("address",address.getText().toString().trim());
request.add("qqnum",qq.getText().toString().trim());
request.add("wechatnum",wechat.getText().toString().trim());
request.add("email",email.getText().toString().trim());
request.add("occupationno",id.getText().toString().trim());
request.add("car_id",carInfo.getText().toString().trim());
String[] ele=price.getText().toString().trim().split("元");
request.add("subject_price",ele[0]);
request.add("sex",msex);
//上传头像,报错
request.add("file", ImageCompress.bitmapToString(mCropImageFile));
getRequestQueue().add(2, request, new OnResponseListener<JSONObject>() {
@Override
public void onStart(int what) {
}
@Override
public void onSucceed(int what, Response<JSONObject> response) {
mLog.e("response","->"+response.get().toString());
try {
JSONObject object=new JSONObject(response.get().toString().trim());
mmsg=object.getString("msg");
handler.sendEmptyMessage(3333);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(int what, Response<JSONObject> response) {
Message msg=new Message();
msg.what=9999;
handler.sendMessage(msg);
}
@Override
public void onFinish(int what) {
}
});
}
private boolean isRight() {
boolean mphone=false,madd=false,mqq=false,mwc=false,mema=false,mid=false,mcar=false,mtrain=false;
if(phone_Num.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"手机号码不能为空",Toast.LENGTH_SHORT).show();
}else {
mphone=true;
}
if(address.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"家庭地址不能为空",Toast.LENGTH_SHORT).show();
}else {
madd=true;
}
if(qq.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"QQ不能为空",Toast.LENGTH_SHORT).show();
}else {
mqq=true;
}
if(wechat.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"微信不能为空",Toast.LENGTH_SHORT).show();
}else {
mwc=true;
}
if(email.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"e-mail不能为空",Toast.LENGTH_SHORT).show();
}else {
mema=true;
}
if(id.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"教练证不能为空",Toast.LENGTH_SHORT).show();
}else {
mid=true;
}
if(carInfo.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"车辆信息不能为空",Toast.LENGTH_SHORT).show();
}else {
mcar=true;
}
if(price.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(),"课程单价不能为空",Toast.LENGTH_SHORT).show();
}else {
mtrain=true;
}
if(mphone&&madd&&mqq&&mwc&&mema&&mid&&mcar&&mtrain){
return true;
}else {
return false;
}
};
private void addMenu() {
dialog=new BottomSheetDialog(this,R.style.ChoiceHeadTheme);
View menu=getLayoutInflater().inflate(R.layout.item_choice_headerphoto_menu,null);
Button takePhoto= (Button) menu.findViewById(R.id.take_photo);
takePhoto.setOnClickListener(this);
Button open_gallery= (Button) menu.findViewById(R.id.open_gallery);
open_gallery.setOnClickListener(this);
dialog.setContentView(menu);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(true);
dialog.show();
}
private void camera(){
dialog.dismiss();
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
mTmpFile = new File(FileUtils.createRootPath(getBaseContext()) + "/" + System.currentTimeMillis() + ".jpg");
FileUtils.createFile(mTmpFile);
if(Build.VERSION.SDK_INT < 24){
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(mTmpFile));
startActivityForResult(cameraIntent, REQUEST_CAMERA);
}else {
//适配安卓7.0
ContentValues contentValues=new ContentValues(1);
contentValues.put(MediaStore.Images.Media.DATA,mTmpFile.getAbsolutePath());
Uri uri= getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
grantUriPermission("com.kangzhan.student",uri,Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
startActivityForResult(cameraIntent, REQUEST_CAMERA);
}
}
}
private void gallery(){
dialog.dismiss();
Intent intent = new Intent();
//打开能打开相册的应用
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==REQUEST_CAMERA){
if (resultCode == RESULT_OK){
crop(mTmpFile.getAbsolutePath());
}else {
Toast.makeText(getApplicationContext(), "拍照失败", Toast.LENGTH_SHORT).show();
}
}else if(requestCode==REQUEST_CROP){
if (resultCode == RESULT_OK){
mLog.e("设置头像","->OK");
header.setImageURI(Uri.fromFile(mCropImageFile));
}else {
Toast.makeText(getApplicationContext(), "截图失败", Toast.LENGTH_SHORT).show();
}
}else if(requestCode==REQUEST_GALLERY){
if (resultCode == RESULT_OK && data != null){
String imagePath = handleImage(data);
crop(imagePath);
}else {
Toast.makeText(getApplicationContext(), "打开图库失败", Toast.LENGTH_SHORT).show();
}
}
}
private void crop(String imagePath){
//mCropImageFile = FileUtils.createTmpFile(getBaseContext());
mCropImageFile = getmCropImageFile();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*");
intent.putExtra("crop", true);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 500);
intent.putExtra("outputY", 500);
intent.putExtra("scale", true);
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCropImageFile));
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, REQUEST_CROP);
}
//把fileUri转换成ContentUri
public Uri getImageContentUri(File imageFile){
String filePath = imageFile.getAbsolutePath();
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
private String handleImage(Intent data) {
Uri uri = data.getData();
String imagePath = null;
if (Build.VERSION.SDK_INT >= 19) {
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("" +
"content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equals(uri.getScheme())) {
imagePath = getImagePath(uri, null);
}
} else {
imagePath = getImagePath(uri, null);
}
return imagePath;
}
private String getImagePath(Uri uri, String seletion) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, seletion, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
//获取裁剪的图片保存地址
private File getmCropImageFile(){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),"temp.jpg");
File file = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
return file;
}
return null;
}
}
| [
"zheng-xuan@szreach.com"
] | zheng-xuan@szreach.com |
836da615c705b1ee60b47812f08b93eefd400668 | 60e5928f0bf835449136f85d0983370716b3ab5d | /Work/Test/Test3.java | e474972e9685e3a8e60c93ee9723a8fec1a47126 | [] | no_license | FiveKilogram/java | adae4d0407000ce89fea004f699da8f4e4dce727 | d13fe9a02038f27755539fc8b0085f25d7542277 | refs/heads/master | 2022-05-13T00:09:05.708289 | 2022-05-01T08:01:56 | 2022-05-01T08:01:56 | 195,714,346 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 458 | java | import java.io.File;
import java.util.List;
public class Test3 {
public static void main(String[] args) {
File obj = new File("/java/system");
System.out.println(obj.getParent());
System.out.println(" " + obj.isFile());
String str = "ttttt";
String str2 = new String("ttttt");
String str3 = new String(str2);
System.out.println(str.equals(str2));
System.out.println(str2==str3);
}
}
| [
"xushijin0421@163.com"
] | xushijin0421@163.com |
85948c0db1eaa12d7c75bec8e2b65fd0bcc71a45 | ca93f14393dc0c5a761c715ebcd33b6550817e12 | /XP/junit4-legacy-app-master/src/test/java/guru/springframework/domain/CategoryTest.java | da4fb310e0c77401c93d8cce6ec390e773804a9d | [
"Apache-2.0"
] | permissive | hlibman-kc/Training | 263cc158934f333d2b19bdd8e652dccabeaca96d | bd880dd8fe3f122808bb07f1502b9a1a6c1afd16 | refs/heads/main | 2023-03-12T23:30:57.302744 | 2021-03-05T21:36:55 | 2021-03-05T21:36:55 | 333,829,195 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 621 | java | package guru.springframework.domain;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CategoryTest {
Category category;
@BeforeEach
public void setUp() {
category = new Category();
}
@Test
public void getId() throws Exception {
Long idValue = 4L;
category.setId(idValue);
assertEquals(idValue, category.getId());
}
@Test
public void getDescription() throws Exception {
}
@Test
public void getRecipes() throws Exception {
}
} | [
"henry.libman@kinandcarta.com"
] | henry.libman@kinandcarta.com |
3448ad6a473e1b5f4312e8c3310f7366523c086b | 83a213744b00b8cf10413b025402bdeb540a9076 | /homeWorks1211/src/homeWorks1211/mailCheck.java | 70aab41b4c439384b5e51d67608643a647a1090f | [] | no_license | MRong138/java.shangke | 4d6931519cd7eeb5d0b50fe75f6ee5916fb47aee | 12ed66a788e91ac1a949607ba39b5f77ff9aa1eb | refs/heads/master | 2021-01-13T14:07:05.025550 | 2016-12-23T06:43:31 | 2016-12-23T06:43:31 | 76,161,742 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,697 | java | package homeWorks1211;
//1、邮箱校验
//解析一个邮箱地址是否合法,如果合法则打印
//出用户名部分和该邮箱所属的网站域名,如果邮
//箱地址不合法则显示不合法的原因 [选做题]
//• 提示:邮箱地址不合法的因素:
//• 邮箱地址中不包含@或.
//• 邮箱地址中含有多了@或.
//• 邮箱地址中.出现在@的前面
//• 用户名里有其他字符
public class mailCheck {
public static void main(String[] args){
String mail="1234567@qq.com";
if(check(mail)&&checkduo(mail)&&checkorder(mail)&&checkorther(mail))
System.out.println("校验通过");
else
System.out.println("校验未通过");
}
public static boolean check(String s){
boolean flag1=false;
boolean flag2=false;
char[] a=s.toCharArray();
for (int i = 0; i < a.length; i++) {
if(a[i]=='@')
flag1=true;
if(a[i]=='.')
flag2=true;
}
if(flag1==true&&flag2==true)
return true;
else
return false;
}
public static boolean checkduo(String s){
if((s.indexOf('@')==s.lastIndexOf('@'))&&(s.indexOf('.')==s.lastIndexOf('.')))
return true;
else
return false;
}
public static boolean checkorder(String s){
char[] a=s.toCharArray();
if(s.indexOf('@')<s.indexOf('.'))
return true;
else
return false;
}
public static boolean checkorther(String s){
boolean flag1,flag2=true;
char[]a=s.toCharArray();
for (int i = 0; i < a.length; i++) {
if((a[i]>='a'&&a[i]<='z')||(a[i]>='A'&&a[i]<='Z')||(a[i]>='0'&&a[i]<='9')||a[i]=='@'||a[i]=='.')
flag1=true;
else
flag2=false;
}
return flag2;
}
}
| [
"m13897998967@163.com"
] | m13897998967@163.com |
3000b2f5a583e611102e144fefa0992aeafddc67 | 95b2696ec8effb94796f27aa94083d57834e6a4a | /src/br/com/senac/lojashowmusical/entity/EnderecoEntity.java | 87791a6bb4fa2bc7753393f8905abd27f45baf83 | [] | no_license | Julio3Cesar/Pi4_atual | fb088b33b6cc7bddc57a3710877bbffe619b9d98 | dd5df7c99f2be589a85031f2a7dfc20481d16b4b | refs/heads/master | 2021-08-29T12:06:16.097121 | 2017-12-13T23:05:08 | 2017-12-13T23:05:08 | 111,028,786 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,606 | java | package br.com.senac.lojashowmuscial.entity;
public class EnderecoEntity {
private Integer idEndereco;
private String cep;
private String logradouro;
private String numero;
private String bairro;
private String cidade;
private String uf;
public EnderecoEntity(String cep, String logradouro, String numero, String bairro, String cidade, String uf) {
this.cep = cep;
this.logradouro = logradouro;
this.numero = numero;
this.bairro = bairro;
this.cidade = cidade;
this.uf = uf;
}
public EnderecoEntity() {
}
public Integer getIdEndereco() {
return idEndereco;
}
public void setIdEndereco(Integer idEndereco) {
this.idEndereco = idEndereco;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
}
| [
"bob-cesar@hotmail.com.br"
] | bob-cesar@hotmail.com.br |
b107a9eefb96ae01c201236548cee3bedf9db43c | aeea89a1f02eac04f84849aa266edbd70e9aa0e6 | /java/se/sics/mspsim/chip/RFListener.java | c4040b95ff8acbc687005a2765ea66e2a153f24a | [
"BSD-3-Clause"
] | permissive | nfi/cooja | 3f14872a110e5e9f5fc4a2a9b3b6d4ec3925baaf | 866bcf5bb7ad1125e1425c74e6339b4f63385f82 | refs/heads/master | 2023-09-04T10:57:54.931878 | 2023-01-08T18:10:46 | 2023-01-08T18:10:46 | 109,292,453 | 0 | 0 | NOASSERTION | 2022-05-23T19:02:18 | 2017-11-02T16:40:22 | Java | UTF-8 | Java | false | false | 2,342 | java | /*
* Copyright (c) 2007-2012, Swedish Institute of Computer Science.
* 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.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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.
*
* This file is part of MSPSim.
*
* -----------------------------------------------------------------
*
* RFListener
*
* Author : Joakim Eriksson
* Created : Sep 06 22:00:00 2008
*
*/
package se.sics.mspsim.chip;
import se.sics.mspsim.util.ProxySupport;
public interface RFListener {
// A byte has been received via the "air"
void receivedByte(byte data);
class Proxy extends ProxySupport<RFListener> implements RFListener {
public static final Proxy INSTANCE = new Proxy();
@Override
public void receivedByte(byte data) {
RFListener[] listeners = this.listeners;
for(RFListener listener : listeners) {
listener.receivedByte(data);
}
}
}
}
| [
"jonsson.peter.a@gmail.com"
] | jonsson.peter.a@gmail.com |
fee9937d5951a7366ae4429e0da6e89030869f42 | 606d036fd119ca0cbce5692f8cfa4933ad1e6119 | /src/communication/Server.java | 1a02e7df90fd46595f2986449b62dc2121f343f7 | [] | no_license | sonnenfeld269/DSLAB2 | 9180a9e1f228c8d9a39c8dbb1dca898f96c75e34 | 346bc497d22004f50f80d7e6c8c56a7befca995b | refs/heads/master | 2020-04-09T10:37:35.176595 | 2012-12-11T01:02:18 | 2012-12-11T01:02:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,063 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package communication;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.io.OutputStream;
import java.io.PrintWriter;
import MyLogger.Log;
/**
*
* @author sanker
*/
public class Server implements Runnable{
private final ServerSocket serversocket;
private final ExecutorService pool;
private Server.Handler handler;
private Log errorlog;
public Server(int port,Server.Handler Handler,Log error)throws ServerException
{
try{
serversocket = new ServerSocket(port);
pool = Executors.newCachedThreadPool();
handler=Handler;
errorlog=error;
errorlog.output("TCP Server created....", 2);
}catch(IOException e){
throw new ServerException("IOException::",e);
}
}
public Server(int port,Server.Handler Handler,ExecutorService exservice,Log error)throws ServerException
{
try{
serversocket = new ServerSocket(port);
pool = exservice;
handler=Handler;
errorlog=error;
errorlog.output("TCP Server created....", 2);
}catch(IOException e){
throw new ServerException("IOException::",e);
}
}
public void shutdown()throws ServerException
{
try {
if(!pool.isShutdown())
pool.shutdown();
if(!serversocket.isClosed())
serversocket.close();
errorlog.output("TCP Server closed....", 2);
} catch (IOException e) {
throw new ServerException("IOException::",e);
}
}
public void shutdownServerThread(Thread t)
{
t.interrupt();
}
public void run()
{
errorlog.output("TCPListenServerThread started....", 2);
while(!(Thread.currentThread().isInterrupted()))
{
try{
if(this.handler==null)
throw (new ServerException("Handler not initialized."));
this.handler.setClient(serversocket.accept());
pool.execute(this.handler);
}catch(IOException e)
{
this.errorlog.output("Server error:"+e.getMessage());
}catch(ServerException e)
{
this.errorlog.output("Server error:"+e.getMessage());
Thread.currentThread().interrupt();
}
}
try {
this.shutdown();
} catch (ServerException e) {
this.errorlog.output("Server error:"+e.getMessage());
}
}
//A user defined Handler must inherit this class and must
//override the run method
//
static public class Handler implements Runnable
{
private Client client;
public Handler()
{
//client must be initialized with the socket
//from established connection
this.client=null;
}
@Override
public void run()
{
}
protected void setClient(Socket sock)
{
this.client=new Client(sock);
}
protected void setClient(Client client)
{
this.client=client;
}
public Client getClient()
{
return this.client;
}
}
}
| [
"delta458@hotmail.com"
] | delta458@hotmail.com |
5636a475255a88a9f1839422593af79e0130e7dc | 9eaa2480c7625ab50b47cf1962f8cfc79dda69bf | /contextawareness-android-sdk/src/main/java/io/github/contextawareness/accessibility/WindowChangeEventProvider.java | 3b09fc8777315e3c297afcc2e3ce17fc0a8271c5 | [] | no_license | xinyu1118/ContextAwareness | 8991cd553ffacfd8adcb9a1bc022a9df260e7a45 | 097a9d65d73ddf6d63332af9a96c7cc97389b87f | refs/heads/master | 2020-04-17T20:32:52.425327 | 2019-07-25T09:53:53 | 2019-07-25T09:53:53 | 166,385,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 761 | java | package io.github.contextawareness.accessibility;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
class WindowChangeEventProvider extends AccEventProvider {
public void handleAccessibilityEvent(AccessibilityEvent event, AccessibilityNodeInfo rootNode){
int eventType = event.getEventType();
if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
|| eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
|| eventType == AccessibilityEvent.TYPE_WINDOWS_CHANGED
|| eventType == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED)
{
this.output(new AccEvent(event, rootNode));
}
}
}
| [
"yangxycl@163.com"
] | yangxycl@163.com |
5749f61e0d3594152a9bae2acaea71aa62b3be7a | ed6ce1134af61207ec0c33d9c050508ab344a518 | /backend/src/main/java/br/gov/rr/segad/dscatalog/repositories/CategoryRepository.java | de882692fab725bb45691a362cfe26133b9d98ca | [] | no_license | henriquelavor/dscatalog-bootcamp-devsuperior | 573b924bd45329ecd684b0f63bff5e7149da717c | 2c72a463744164dd6005a6fc6d33e0e02e714a9e | refs/heads/master | 2023-03-02T11:10:53.074742 | 2021-02-08T21:43:01 | 2021-02-08T21:43:01 | 330,500,054 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 308 | java | package br.gov.rr.segad.dscatalog.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.gov.rr.segad.dscatalog.entities.Category;
@Repository
public interface CategoryRepository extends JpaRepository<Category, Long> {
}
| [
"henriquelavor@gmail.com"
] | henriquelavor@gmail.com |
364e6dca15fe1bc352432a71bc1671aadbf794fb | 595e81006d568c0af6bf770646520845f113e607 | /our_subs_java/Projects/AmLibTech.com/com/amlibtech/web/common_list/US_States.java | a39a7404f7d3725f4761417d19d1470187b719e9 | [] | no_license | TheDoctorDan/glsn_my_projects | 8224dfacde95f1cbffe4f009cbe105a0aacaaa9e | 72af4b1a3a63249f6234f7337c94ac189f842ca3 | refs/heads/master | 2023-02-14T15:51:28.524818 | 2021-01-07T18:32:23 | 2021-01-07T18:32:23 | 327,695,629 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,414 | java | /* US_States.java.h */
/* State abbreviations */
/*
|------------------------------------------------------------------------------|
| Copyright (c) 1985 thru 1998, 1999, 2000, 2001, 2002, 2003, 2004 |
| American Liberator Technologies |
| All Rights Reserved |
| |
| THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF |
| American Liberator Technologies |
| The copyright notice above does not evidence any |
| actual or intended publication of such source code. |
|------------------------------------------------------------------------------|
*/
package com.amlibtech.web.common_list;
import javax.servlet.http.*;
import com.amlibtech.web.data.*;
public class US_States {
private static final String[] Copyright= {
"| Copyright (c) 1985 thru 2001, 2002, 2003, 2004, 2005, 2006, 2007 |",
"| American Liberator Technologies |",
"| All Rights Reserved |",
"| |",
"| THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF |",
"| American Liberator Technologies |",
"| The copyright notice above does not evidence any |",
"| actual or intended publication of such source code. |"
};
public static final int ABBR_MAX_LEN = 2;
public static final String[][] values = {
{"AL", "Alabama", "1"},
{"AK", "Alaska", "2"},
{"AZ", "Arizona", "3"},
{"AR", "Arkansas", "4"},
{"CA", "California", "5"},
{"CZ", "Canal Zone", "0"},
{"CO", "Colorado", "6"},
{"CT", "Connecticut", "7"},
{"DE", "Delaware", "8"},
{"DC", "District of Columbia", "9"},
{"FL", "Florida", "10"},
{"GA", "Georgia", "11"},
{"GU", "Guam", "0"},
{"HI", "Hawaii", "12"},
{"ID", "Idaho", "13"},
{"IL", "Illinois", "14"},
{"IN", "Indiana", "15"},
{"IA", "Iowa", "16"},
{"KS", "Kansas", "17"},
{"KY", "Kentucky", "18"},
{"LA", "Louisiana", "19"},
{"ME", "Maine", "20"},
{"MD", "Maryland", "21"},
{"MA", "Massachusetts", "22"},
{"MI", "Michigan", "23"},
{"MN", "Minnesota", "24"},
{"MS", "Mississippi", "25"},
{"MO", "Missouri", "26"},
{"MT", "Montana", "27"},
{"NE", "Nebraska", "28"},
{"NV", "Nevada", "29"},
{"NH", "New Hampshire", "30"},
{"NJ", "New Jersey", "31"},
{"NM", "New Mexico", "32"},
{"NY", "New York", "33"},
{"NC", "North Carolina", "34"},
{"ND", "North Dakota", "35"},
{"OH", "Ohio", "36"},
{"OK", "Oklahoma", "37"},
{"OR", "Oregon", "38"},
{"PA", "Pennsylvania", "39"},
{"PR", "Puerto Rico", "0"},
{"RI", "Rhode Island", "40"},
{"SC", "South Carolina", "41"},
{"SD", "South Dakota", "42"},
{"TN", "Tennesse", "43"},
{"TX", "Texas", "44"},
{"UT", "Utah", "45"},
{"VT", "Vermont", "46"},
{"VA", "Virginia", "47"},
{"VI", "Virgin Islands", "0"},
{"WA", "Washington", "48"},
{"WV", "West Virginia", "49"},
{"WI", "Wisconsin", "50"},
{"WY", "Wyoming", "51"},
{"AA", "Armed Forces America", "0"},
{"AE", "ArmedForces AfEuMECa", "0"},
{"AP", "Armed Forces Pacific", "0"},
{"__", "NOT USA", "52"},
{"AB", "Alberta", "0"},
{"BC", "British Columbia", "0"},
{"MB", "Manitoba", "0"},
{"NF", "Newfoundland", "0"},
{"NB", "New Brunswick", "0"},
{"NT", "Northwest Territory", "0"},
{"NS", "Nova Scotia", "0"},
{"NU", "Nunavut", "0"},
{"ON", "Ontario", "0"},
{"PE", "Prince Edward Island", "0"},
{"QC", "Quebec", "0"},
{"SK", "Saskatchewan", "0"},
{"YT", "Yukon", "0"}
};
public static String[] state_Names_List = new String[US_States.values.length];
public static String[] state_Abbr_List = new String[US_States.values.length];
private static US_States us_States_Instance= new US_States();
US_States() {
for(int i=0; i< values.length; i++){
state_Abbr_List[i] = values[i][0];
state_Names_List[i] = values[i][1];
}
}
public static String getValid_State_Abbr(HttpServletRequest request, String field_Name, Field_Description_List field_Description_List, String field_Value)
throws Field_Validation_Exception {
Field_Description_Node field_Description_Node = field_Description_List.getField_Node(field_Name);
if(field_Description_Node==null){
String message ="No Field_Description_Node for field :" + field_Name + ":";
throw new Field_Validation_Exception(message);
}
if(field_Description_Node.getType() != "String"){
String message ="Field_Description_Node is not of Type String for field :" + field_Description_Node.getField_Title() + ":.";
throw new Field_Validation_Exception(message);
}
String state_Abbr_Value;
String parameter_Value = request.getParameter(field_Name);
if(parameter_Value == null){
// no parameter passed, use default.
parameter_Value = field_Value;
}
if(parameter_Value==null)
parameter_Value="";
int length = parameter_Value.length();
if(length!=2){
// convert name to abbr
for(int i=0; i< state_Names_List.length; i++){
if(parameter_Value.equalsIgnoreCase(state_Names_List[i])){
state_Abbr_Value = state_Abbr_List[i];
return state_Abbr_Value;
}
}
String message ="Answer :" + parameter_Value + ": for field :" + field_Description_Node.getField_Title() + ": is not a valid State.";
throw new Field_Validation_Exception(message);
}
for(int i=0; i< state_Abbr_List.length; i++){
if(parameter_Value.equalsIgnoreCase(state_Abbr_List[i])){
state_Abbr_Value = state_Abbr_List[i];
return state_Abbr_Value;
}
}
String message ="Answer :" + parameter_Value + ": for field :" + field_Description_Node.getField_Title() + ": is not a valid State.";
throw new Field_Validation_Exception(message);
}
public static String get_State_Name(String abbr){
for(int i=0; i< state_Abbr_List.length; i++){
if(abbr.equalsIgnoreCase(state_Abbr_List[i])){
return state_Names_List[i];
}
}
return "";
}
}
| [
"dgleeson1721@gmail.com"
] | dgleeson1721@gmail.com |
d88d1cc46c72a331d3dddcb66b447df9a83073f8 | f5472dbd8b35b99e068addb2a5e3b5a1499d40f9 | /image-viewer/src/main/java/com/liyi/viewer/view/ImagePreviewActivity.java | 2074c9d1b801dcb6f006c1e0c87426c1712914fa | [] | no_license | imxiaopeng/ImagePlayer | 073d5fc21b19f82d78c6bd9795984f9fccf33cd8 | 339c020e51b29b51d662a4af513727665ed567f0 | refs/heads/master | 2021-08-26T07:07:41.865625 | 2017-11-22T03:20:28 | 2017-11-22T03:20:28 | 111,524,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,000 | java | package com.liyi.viewer.view;
import android.animation.FloatEvaluator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.liyi.viewer.ImageDefine;
import com.liyi.viewer.ImageViewer;
import com.liyi.viewer.R;
import com.liyi.viewer.data.ViewData;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
public class ImagePreviewActivity extends Activity implements IImagePreview {
private final String TAG = this.getClass().getSimpleName();
private View v_bg;
private ViewPagerr viewpager;
private ImageView iv_show;
private TextView tv_index;
private ArrayList<View> mViewList;
private ArrayList<ViewData> mViewDataList;
private ArrayList<Object> mImageSrcList;
private HashMap<Integer, SoftReference<Bitmap>> mImageCache;
private ViewData mCurViewData;
private Point mScreenSize;
private int mBeginIndex;
private int mIndexPos;
private boolean isShowProgress;
// Determine if the first picture you need to display is loaded
private boolean isBeginLoaded;
// Determines whether the ImageView executing the animation has loaded the picture
private boolean isShowLoaded;
private LinkedList<String> mLoadFailArray;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_preview);
initUI();
addListener();
handleIntent(getIntent());
}
@Override
public void initUI() {
v_bg = findViewById(R.id.v_preview_bg);
viewpager = (ViewPagerr) findViewById(R.id.vp_preview);
iv_show = (ImageView) findViewById(R.id.iv_preview_show);
tv_index = (TextView) findViewById(R.id.tv_preview_index);
v_bg.setAlpha(0f);
}
@Override
public void addListener() {
viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (position < mViewDataList.size()) {
mCurViewData = mViewDataList.get(position);
// Prevent click event failure
PhotoView photoView = (PhotoView) mViewList.get(position).findViewById(R.id.photoVi_item_imgViewer);
if (mImageCache.get(position) != null && mImageCache.get(position).get() != null) {
photoView.setImageBitmap(mImageCache.get(position).get());
} else {
loadImage(position, mImageSrcList.get(position), photoView, false);
}
photoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
@Override
public void onViewTap(View view, float x, float y) {
restoreImage();
}
});
tv_index.setText((position + 1) + "/" + mImageSrcList.size());
if (mLoadFailArray.contains(position + "")) {
Toast.makeText(ImagePreviewActivity.this, "图片加载失败", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
@Override
public void handleIntent(Intent intent) {
if (intent == null) {
Log.w(TAG, "The intent is null");
return;
}
mViewDataList = (ArrayList<ViewData>) intent.getSerializableExtra(ImageDefine.VIEW_ARRAY);
mImageSrcList = (ArrayList<Object>) intent.getSerializableExtra(ImageDefine.IMAGE_ARRAY);
mBeginIndex = intent.getIntExtra(ImageDefine.BEGIN_INDEX, 0);
mIndexPos = intent.getIntExtra(ImageDefine.INDEX_GRAVITY, Gravity.TOP);
isShowProgress = intent.getBooleanExtra(ImageDefine.SHOW_PROGRESS, true);
mScreenSize = getScreenSize(this);
mCurViewData = mViewDataList.get(mBeginIndex);
isBeginLoaded = false;
isShowLoaded = false;
mImageCache = new HashMap<Integer, SoftReference<Bitmap>>();
mLoadFailArray = new LinkedList<String>();
mViewList = new ArrayList<View>();
iv_show.setLayoutParams(new FrameLayout.LayoutParams((int) mCurViewData.width, (int) mCurViewData.height));
iv_show.setX(mCurViewData.x);
iv_show.setY(mCurViewData.y);
iv_show.setVisibility(View.GONE);
for (int i = 0; i < mImageSrcList.size(); i++) {
View view = LayoutInflater.from(this).inflate(R.layout.item_image_viewer, null);
final PhotoView photoView = (PhotoView) view.findViewById(R.id.photoVi_item_imgViewer);
if (mImageCache.get(i) != null && mImageCache.get(i).get() != null) {
photoView.setImageBitmap(mImageCache.get(i).get());
} else {
loadImage(i, mImageSrcList.get(i), photoView, false);
}
photoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
@Override
public void onViewTap(View view, float x, float y) {
restoreImage();
}
});
mViewList.add(view);
}
viewpager.setAdapter(new SimpleAdapter(mViewList));
viewpager.setCurrentItem(mBeginIndex);
viewpager.setVisibility(View.GONE);
tv_index.setText((mBeginIndex + 1) + "/" + mImageSrcList.size());
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) tv_index.getLayoutParams();
lp.gravity = mIndexPos;
tv_index.setLayoutParams(lp);
if (mImageCache.get(mBeginIndex) != null && mImageCache.get(mBeginIndex).get() != null) {
iv_show.setImageBitmap(mImageCache.get(mBeginIndex).get());
isShowLoaded = true;
fullScreen();
} else {
loadImage(mBeginIndex, mImageSrcList.get(mBeginIndex), iv_show, true);
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (!isShowLoaded) {
if (ImageViewer.getBeginImage() != null) {
iv_show.setImageBitmap(ImageViewer.getBeginImage());
}
isShowLoaded = true;
fullScreen();
}
}
}, 300);
}
@Override
public void fullScreen() {
// The width and height of the original image
float ori_w = 1280;
float ori_h = 720;
Drawable d = iv_show.getDrawable();
if (d != null) {
ori_w = d.getIntrinsicWidth();
ori_h = d.getIntrinsicHeight();
} else if (mImageCache.get(mBeginIndex) != null && mImageCache.get(mBeginIndex).get() != null) {
iv_show.setImageBitmap(mImageCache.get(mBeginIndex).get());
d = iv_show.getDrawable();
ori_w = d.getIntrinsicWidth();
ori_h = d.getIntrinsicHeight();
} else {
Log.w(TAG, "The width and length of the image were not obtained");
}
// Scale of the original image
float scale = Math.min((mScreenSize.x / ori_w), (mScreenSize.y / ori_h));
// The width and height of the ImageView now
final float cur_w = mCurViewData.width;
final float cur_h = mCurViewData.height;
// The width and height of the zoomed ImageView
final float img_w = ori_w * scale;
final float img_h = ori_h * scale;
// Initial coordinates of the ImageView
final float from_x = mCurViewData.x;
final float from_y = mCurViewData.y;
// Destination coordinates of ImageView
final float to_x = (mScreenSize.x - img_w) / 2;
final float to_y = (mScreenSize.y - img_h) / 2;
ValueAnimator animator = ValueAnimator.ofFloat(0, 100);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
FloatEvaluator evaluator = new FloatEvaluator();
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float currentValue = (float) animation.getAnimatedValue();
float fraction = currentValue / 100f;
if (fraction == 0) {
iv_show.setScaleType(ImageView.ScaleType.FIT_XY);
iv_show.setVisibility(View.VISIBLE);
}
float width = evaluator.evaluate(fraction, cur_w, img_w);
float height = evaluator.evaluate(fraction, cur_h, img_h);
float x = evaluator.evaluate(fraction, from_x, to_x);
float y = evaluator.evaluate(fraction, from_y, to_y);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) iv_show.getLayoutParams();
layoutParams.width = (int) width;
layoutParams.height = (int) height;
iv_show.setLayoutParams(layoutParams);
iv_show.setX(x);
iv_show.setY(y);
v_bg.setAlpha(fraction);
if (fraction == 1) {
viewpager.setVisibility(View.VISIBLE);
tv_index.setVisibility(View.VISIBLE);
iv_show.setVisibility(View.GONE);
}
}
});
animator.setDuration(200);
animator.start();
}
@Override
public void restoreImage() {
PhotoView photoView = (PhotoView) mViewList.get(viewpager.getCurrentItem()).findViewById(R.id.photoVi_item_imgViewer);
Drawable d = photoView.getDrawable();
// The width and height of the original image
float ori_w = d.getIntrinsicWidth();
float ori_h = d.getIntrinsicHeight();
// Scale of the original image
float scale = Math.min((mScreenSize.x / ori_w), (mScreenSize.y / ori_h));
// The width and height of the ImageView now
final float cur_w = ori_w * scale;
final float cur_h = ori_h * scale;
// The width and height of the zoomed ImageView
final float img_w = mCurViewData.width;
final float img_h = mCurViewData.height;
// Initial coordinates of the ImageView
final float from_x = (mScreenSize.x - cur_w) / 2;
final float from_y = (mScreenSize.y - cur_h) / 2;
// Destination coordinates of ImageView
final float to_x = mCurViewData.x;
final float to_y = mCurViewData.y;
iv_show.setImageDrawable(d);
viewpager.setVisibility(View.GONE);
iv_show.setVisibility(View.VISIBLE);
ValueAnimator animator = ValueAnimator.ofFloat(0, 100);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
FloatEvaluator evaluator = new FloatEvaluator();
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float currentValue = (float) animation.getAnimatedValue();
float fraction = currentValue / 100f;
if (fraction == 0) {
tv_index.setVisibility(View.GONE);
iv_show.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
float width = evaluator.evaluate(fraction, cur_w, img_w);
float height = evaluator.evaluate(fraction, cur_h, img_h);
float x = evaluator.evaluate(fraction, from_x, to_x);
float y = evaluator.evaluate(fraction, from_y, to_y);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) iv_show.getLayoutParams();
lp.width = (int) width;
lp.height = (int) height;
iv_show.setLayoutParams(lp);
iv_show.setX(x);
iv_show.setY(y);
v_bg.setAlpha(1 - fraction);
if (fraction == 1) {
finish();
}
}
});
animator.setDuration(200);
animator.start();
}
@Override
public void clear() {
if (mImageCache != null && mImageCache.size() > 0) {
mImageCache.clear();
}
mImageCache = null;
ImageViewer.setBeginImage(null);
}
private void loadImage(final int index, Object src, final ImageView view, final boolean isShow) {
final RequestBuilder builder = Glide.with(this).asBitmap().load(src).transition(BitmapTransitionOptions.withCrossFade());
if (ImageViewer.getOptions() != null) {
if (index == mBeginIndex && isShow) {
builder.apply(ImageViewer.getOptions().priority(Priority.IMMEDIATE));
} else {
builder.apply(ImageViewer.getOptions().priority(Priority.NORMAL));
}
builder.apply(ImageViewer.getOptions());
}
builder.into(new ImageViewTarget<Bitmap>(view) {
@Override
protected void setResource(@Nullable Bitmap resource) {
}
@Override
public void onLoadStarted(@Nullable Drawable placeholder) {
super.onLoadStarted(placeholder);
ProgressBar progressBar = (ProgressBar) mViewList.get(index).findViewById(R.id.proBar_item_imgViewer);
if (isShowProgress) {
if (ImageViewer.getProgressDrawable() != null) {
progressBar.setIndeterminateDrawable(ImageViewer.getProgressDrawable());
}
progressBar.setVisibility(View.VISIBLE);
} else {
progressBar.setVisibility(View.GONE);
}
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
mImageCache.put(index, new SoftReference<Bitmap>(drawableToBitmap(errorDrawable)));
mViewList.get(index).findViewById(R.id.proBar_item_imgViewer).setVisibility(View.GONE);
if (index == mBeginIndex) {
if (isShow) {
isShowLoaded = true;
if (!isBeginLoaded) {
PhotoView photoView = (PhotoView) mViewList.get(index).findViewById(R.id.photoVi_item_imgViewer);
Glide.with(ImagePreviewActivity.this).clear(photoView);
photoView.setImageDrawable(errorDrawable);
}
fullScreen();
} else {
isBeginLoaded = true;
}
}
mLoadFailArray.add(index + "");
}
@Override
public void onResourceReady(Bitmap resource, @Nullable Transition transition) {
super.onResourceReady(resource, transition);
mImageCache.put(index, new SoftReference<Bitmap>(resource));
mViewList.get(index).findViewById(R.id.proBar_item_imgViewer).setVisibility(View.GONE);
if (index == mBeginIndex) {
if (isShow) {
isShowLoaded = true;
if (!isBeginLoaded) {
PhotoView photoView = (PhotoView) mViewList.get(index).findViewById(R.id.photoVi_item_imgViewer);
Glide.with(ImagePreviewActivity.this).clear(photoView);
photoView.setImageBitmap(resource);
}
fullScreen();
} else {
isBeginLoaded = true;
}
}
if (mLoadFailArray.contains(index + "")) {
mLoadFailArray.remove(index + "");
}
}
});
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
@Override
public void startActivity(Intent intent) {
super.startActivity(intent);
overridePendingTransition(0, 0);
}
@Override
public void finish() {
super.finish();
clear();
overridePendingTransition(0, 0);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
iv_show.setVisibility(View.VISIBLE);
viewpager.setVisibility(View.GONE);
restoreImage();
}
return true;
}
@Override
protected void onDestroy() {
clear();
super.onDestroy();
}
private Point getScreenSize(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return new Point(outMetrics.widthPixels, outMetrics.heightPixels);
}
private Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
// canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
}
| [
"chenxp@mxth.com"
] | chenxp@mxth.com |
fe27644a88dde344661bc7812e585d326f58ed09 | 5b20006bfeeb578a73699371b4eb8ee26f4db928 | /ovirt-engine-reports/ChartsCustomizers/src/main/java/com/ovirt/reports/jasper/BarChartCustomizer.java | 3903d8daf4f88f018825e215b5fe017fd55a9008 | [] | no_license | minqf/ovirt-reports | 3b472d68abf8139f7cd7da279c1f717e43ea1fad | 1b6f1d50ca7caedc98a97667cff91244f2d69ffd | refs/heads/master | 2021-04-20T02:27:30.012149 | 2016-04-03T13:32:32 | 2016-04-04T06:06:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,752 | java | package com.ovirt.reports.jasper;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import net.sf.jasperreports.engine.JRChart;
import net.sf.jasperreports.engine.JRChartCustomizer;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
public class BarChartCustomizer implements JRChartCustomizer {
@Override
public void customize(JFreeChart chart, JRChart jasperChart) {
BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
CategoryPlot categoryPlot = renderer.getPlot();
renderer.setBaseItemLabelsVisible(false);
categoryPlot.setNoDataMessage("No Data Available");
categoryPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
// Widen the categories so those dots won't show up in the category.
CategoryAxis domainaxis = categoryPlot.getDomainAxis();
domainaxis.setMaximumCategoryLabelWidthRatio(1.5f);
domainaxis.setTickMarksVisible(true);
LegendItemCollection chartLegend = categoryPlot.getLegendItems();
LegendItemCollection res = new LegendItemCollection();
Shape square = new Rectangle2D.Double(0,0,5,5);
for (int i = 0; i < chartLegend.getItemCount(); i++) {
LegendItem item = chartLegend.get(i);
String label = item.getLabel();
if (label.length() > 18)
{
label = label.substring(0,10).concat("...").concat(label.substring(label.length() - 5, label.length()));
}
if (label.trim() != "" && item.getDescription().trim() != "")
{
res.add(new LegendItem(label, item.getDescription(), item.getToolTipText(), item.getURLText(), true, square, true, item.getFillPaint(), item.isShapeOutlineVisible(), item.getOutlinePaint(), item.getOutlineStroke(), false, item.getLine(), item.getLineStroke(), item.getLinePaint()));
}
}
categoryPlot.setFixedLegendItems(res);
chart.getLegend().setFrame(BlockBorder.NONE);
ValueAxis rangeAxis = categoryPlot.getRangeAxis();
if (rangeAxis instanceof NumberAxis) {
NumberAxis axis = (NumberAxis) rangeAxis;
axis.setNumberFormatOverride(new DecimalFormat("###,###,###.#"));
axis.setUpperBound(axis.getUpperBound()+1);
axis.setAutoRangeMinimumSize(1.0);
}
}
}
| [
"ydary@redhat.com"
] | ydary@redhat.com |
892b32cd501de061c011f60516df8aa69666f262 | 8108db0cf84fdbd0a489b11eac4b64c0aaeb1547 | /day_7/InstanceCounter.java | 7a30554ec0274427274432503add874daf08c1a6 | [] | no_license | RyanDur/Java-class | 6707e54b5993929ae4d2dacc877b937d2ee6e2b1 | 45835a01127595528f012285b97e75c44b03520a | refs/heads/master | 2021-01-02T09:34:11.574277 | 2014-11-06T22:40:25 | 2014-11-06T22:40:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 436 | java | public class InstanceCounter {
public static int spy;
public InstanceCounter() {
spy++;
}
public static void main(String []args) {
InstanceCounter ic1 = new InstanceCounter();
System.out.println(ic1.spy);
InstanceCounter ic2 = new InstanceCounter();
System.out.println(ic1.spy);
InstanceCounter ic3 = new InstanceCounter();
System.out.println(ic1.spy);
}
}
| [
"ryan.p.durling@gmail.com"
] | ryan.p.durling@gmail.com |
9cd7f42a857b3acba5ba0bc12bc64c810ae53310 | 29ef246e7e9030611f5d9d35122791badb9426b9 | /src/com/sopiana/yang/javaDecompiler/instruction/byteCodes/l2f.java | 9b4dfec68087752a3d3ba259f409394a756c5305 | [] | no_license | sopiana/javaDecompiler | c6085f36d04100dca80c9eec2062b951b7620aec | 4c09b7db1fd87f24d56dadee4fd9e6b552b93714 | refs/heads/master | 2021-05-31T15:58:37.607374 | 2016-04-27T16:13:31 | 2016-04-27T16:13:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 813 | java | package com.sopiana.yang.javaDecompiler.instruction.byteCodes;
import com.sopiana.yang.javaDecompiler.instruction.instruction;
import com.sopiana.yang.javaDecompiler.instruction.instructionException;
import com.sopiana.yang.javaDecompiler.instruction.opcodeTable;
public class l2f extends instruction
{
public static final opcodeTable ins = opcodeTable._l2f;
public static l2f getInstance(byte[]codes, int offset) throws instructionException
{
if(codes[offset]!=ins.opcode)
throw new instructionException("supplied code is not valid "+ins.mnemonic+" opcode");
l2f res = new l2f();
res.offset = offset;
res.opcode = codes[offset];
return res;
}
public byte[] getData() { return new byte[]{opcode}; }
public int getSize() { return 1; }
public String getMnemonic() { return ins.mnemonic; }
}
| [
"yang.sopiana@gmail.com"
] | yang.sopiana@gmail.com |
204d7484652cf38e43130e99bfa98adc6233b56c | 7415cae888d0cfade52b7681be1f069c1681c7c1 | /app/src/androidTest/java/com/zlgspace/msgpraser/demo/ExampleInstrumentedTest.java | d1885f611c393e6b78261d1f3b4b283e5f16008d | [
"Apache-2.0"
] | permissive | zlgspace/msgpraser | 935b9e0e62cb3baa3265d0fdabb7d8e01049d9ea | 6ab29c91a5739a578a0556a938d43a36e9c53466 | refs/heads/master | 2023-07-19T02:09:09.850831 | 2021-08-30T05:51:06 | 2021-08-30T05:51:06 | 280,086,156 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | package com.zlgspace.msgpraser.demo;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.zlgspace.msgpraser.demo", appContext.getPackageName());
}
}
| [
"zl130127@foxmail.com"
] | zl130127@foxmail.com |
55fd4fd9374a3d34954256525706a051abafbab4 | cb861865b079a37763262e8a7dd5e17080d04177 | /1201-1300/leetcode 1228 Missing Number In Arithmetic Progression.java | 108244b4219c40bd059ca30c33338486ac08323a | [] | no_license | xhyzzZ/leetcode | 7a6148db495aac9c6fc916ba79e818bdbf4b93c1 | 5039de0f20d064698bc627985c26da8856410d7a | refs/heads/master | 2022-05-16T09:21:58.826767 | 2022-04-24T16:53:01 | 2022-04-24T16:53:01 | 164,738,916 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 568 | java | // leetcode 1228 Missing Number In Arithmetic Progression
/*
time: O(n)
space: O(1)
*/
class Solution {
public int missingNumber(int[] arr) {
int len = arr.length; // total length of the given array
int sum = 0; // the sum of the given array
int totalSum = (arr[0] + arr[len - 1]) * (len + 1) / 2; // the actual sum from the start to the end
for (int i = 0; i < len; ++i) {
sum += arr[i];
}
// return the difference
return totalSum - sum;
}
} | [
"xhy@bu.edu"
] | xhy@bu.edu |
0cc719035fa5d50ae7194f406b1d784b9920eb9b | 88f0524f0a06c11647d385318bd45fbdecfd54a5 | /src/main/java/com/afagoal/entity/UuidEntity.java | ddb41e16c3d8fdf2f1d0e2d0ab82fb7a094fec05 | [] | no_license | surewingoal/afagoal-core | 928be67fa6db907d623075f340e2dbc582192903 | 323402f3d568943cc2a952acbb3b4f506e520fb3 | refs/heads/master | 2018-10-05T13:52:49.514556 | 2018-05-27T01:45:26 | 2018-05-27T01:45:26 | 118,316,547 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,081 | java | package com.afagoal.entity;
import org.hibernate.annotations.GenericGenerator;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import lombok.Getter;
import lombok.Setter;
/**
* Created by BaoCai on 17/10/25.
* Description:
*/
@Getter
@Setter
@MappedSuperclass
public class UuidEntity implements Serializable {
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "hibernate-uuid", strategy = "uuid")
private String id;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private String createdBy;
private String updatedBy;
private byte state;
@PrePersist
public void prePersist() {
this.setCreatedAt(LocalDateTime.now());
this.setUpdatedAt(LocalDateTime.now());
}
@PreUpdate
public void preUpdate() {
this.setUpdatedAt(LocalDateTime.now());
}
}
| [
"xiaxi@jianbaolife.com"
] | xiaxi@jianbaolife.com |
a2a8c7c74b93c99498b0aa294fcad1457bcb9e73 | d1ef93899f5a5264e26000043c8388b200b9a19f | /src/test/java/de/detecmedia/checkaccountnumber/Method63Test.java | eab4529cf0696db7b144e786158e4e44b72ad800 | [] | no_license | detecmedia/check-account-number | 7ebc298a9ce6f7cec8c55a152c10cebfe091bc77 | d9c463217fc073ade33bac1b326f854c5e73e2dd | refs/heads/develop | 2021-06-25T14:00:20.253824 | 2017-09-12T18:39:19 | 2017-09-12T18:39:19 | 90,244,415 | 0 | 0 | null | 2017-09-12T18:39:20 | 2017-05-04T09:16:43 | Java | UTF-8 | Java | false | false | 1,724 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.detecmedia.checkaccountnumber;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Markus Potthast <mpt@detecmedia.de>
*/
public class Method63Test {
public Method63Test() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of check method, of class Method63.
*/
@Test
public void testTest() {
System.out.println("check");
Method63 instance = new Method63();
instance.setAccountNumber("123456600");
boolean expResult = true;
boolean result = instance.test();
assertEquals(expResult, result);
}
@Test
public void testCheck1() {
System.out.println("check");
Method63 instance = new Method63();
instance.setAccountNumber("0001234566");
boolean expResult = true;
boolean result = instance.test();
assertEquals(expResult, result);
}
/**
* Test of getFlag method, of class Method63.
*/
@Test
public void testGetFlag() {
System.out.println("getFlag");
Method63 instance = new Method63();
char[] expResult = "63".toCharArray();
char[] result = instance.getFlag();
assertArrayEquals(expResult, result);
}
}
| [
"potthast@bestit-online.de"
] | potthast@bestit-online.de |
938890b6a129778350218491771be460a539c8f0 | 3a59bd4f3c7841a60444bb5af6c859dd2fe7b355 | /sources/kotlin/experimental/ExperimentalTypeInference.java | 9881d90cd83b0a96a4243498e7fffa54a7965495 | [] | no_license | sengeiou/KnowAndGo-android-thunkable | 65ac6882af9b52aac4f5a4999e095eaae4da3c7f | 39e809d0bbbe9a743253bed99b8209679ad449c9 | refs/heads/master | 2023-01-01T02:20:01.680570 | 2020-10-22T04:35:27 | 2020-10-22T04:35:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,137 | java | package kotlin.experimental;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import kotlin.Experimental;
import kotlin.Metadata;
import kotlin.SinceKotlin;
import kotlin.annotation.AnnotationRetention;
import kotlin.annotation.AnnotationTarget;
import kotlin.annotation.MustBeDocumented;
import kotlin.annotation.Retention;
import kotlin.annotation.Target;
@MustBeDocumented
@SinceKotlin(version = "1.3")
@Target(allowedTargets = {AnnotationTarget.ANNOTATION_CLASS})
@Retention(AnnotationRetention.BINARY)
@Documented
@java.lang.annotation.Target({ElementType.ANNOTATION_TYPE})
@Experimental(level = Experimental.Level.ERROR)
@Metadata(mo39784bv = {1, 0, 3}, mo39785d1 = {"\u0000\n\n\u0002\u0018\u0002\n\u0002\u0010\u001b\n\u0000\b\u0002\u0018\u00002\u00020\u0001B\u0000¨\u0006\u0002"}, mo39786d2 = {"Lkotlin/experimental/ExperimentalTypeInference;", "", "kotlin-stdlib"}, mo39787k = 1, mo39788mv = {1, 1, 15})
@java.lang.annotation.Retention(RetentionPolicy.CLASS)
/* compiled from: inferenceMarker.kt */
public @interface ExperimentalTypeInference {
}
| [
"joshuahj.tsao@gmail.com"
] | joshuahj.tsao@gmail.com |
2a06c6c170a310551ba228f557076e464d2c89af | e0c826d2ace0af2f503a1270f310047caa1940ab | /app/src/main/java/net/majorkernelpanic/http/ModSSL.java | c8a1f9eacde105375d9f9b69ee2438e5d77bfe59 | [] | no_license | EliottDo/SpyDroid | e986a7f5e71a23bbe21157b35ce2d639773b8fee | 8219603310ddcb2fa61089b6bd884616a9a1304b | refs/heads/main | 2023-01-23T04:09:10.154888 | 2020-11-30T10:06:27 | 2020-11-30T10:06:27 | 317,182,106 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,066 | java | /*
* Copyright (C) 2011-2013 GUIGUI Simon, fyhertz@gmail.com
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Based on that: http://hc.apache.org/httpcomponents-core-ga/examples.html.
*
*/
package net.majorkernelpanic.http;
import android.util.Log;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.DERSequence;
import org.spongycastle.asn1.x500.X500NameBuilder;
import org.spongycastle.asn1.x500.style.BCStyle;
import org.spongycastle.asn1.x509.BasicConstraints;
import org.spongycastle.asn1.x509.ExtendedKeyUsage;
import org.spongycastle.asn1.x509.KeyPurposeId;
import org.spongycastle.cert.X509CertificateHolder;
import org.spongycastle.cert.X509v3CertificateBuilder;
import org.spongycastle.cert.jcajce.JcaX509CertificateConverter;
import org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.spongycastle.jce.X509KeyUsage;
import org.spongycastle.jce.provider.JDKKeyStore;
import org.spongycastle.operator.ContentSigner;
import org.spongycastle.operator.OperatorCreationException;
import org.spongycastle.operator.jcajce.JcaContentSignerBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.security.auth.x500.X500Principal;
/**
*
* Contains two classes, one for generating certificates for the HTTPS server,
* and the other is a KeyStore that is handed to the SSLContext before creating a SSLSocket.
*
* If you do not need SSL support (you only need an HTTP server) delete this class and the Songy Castle library.
*
*/
public final class ModSSL {
public final static class X509KeyManager implements javax.net.ssl.X509KeyManager {
public final static String TAG = "X509KeyManager";
private char[] mPassword;
private final JDKKeyStore.BouncyCastleStore mKeyStore;
static {
// Adds the the Spongy Castle security provider
// If you have another lib using Spoongy Castle in your project,
// check that the provider is not added more than once
Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
}
public X509KeyManager(char[] password, String CN) throws Exception {
mPassword = password;
mKeyStore = new JDKKeyStore.BouncyCastleStore();
try {
Log.d(TAG, "Generation of CA certificate...");
KeyPair keys = CertificateFactory.generateRSAKeyPair(CertificateFactory.DEFAULT_KEY_SIZE);
X509Certificate rootCertificate = CertificateFactory.generateRootCertificate(keys,CN);
mKeyStore.engineSetKeyEntry("root", keys.getPrivate(), mPassword, new Certificate[]{rootCertificate});
} catch (Exception e) {
Log.e(TAG, "Failed to generate certificate !");
e.printStackTrace();
throw e;
}
}
private X509KeyManager() {
mKeyStore = new JDKKeyStore.BouncyCastleStore();
}
/** This method will not be called. Client authentication has not been implemented. */
@Override
public synchronized String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
// Will not be used in our case
Log.d(TAG, "chooseClientAlias");
return null;
}
@Override
public synchronized String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
String localAddress = socket!=null ? socket.getLocalAddress().getHostAddress() : "0.0.0.0";
if (keyType.equals("RSA")) {
// If no certificate have been generated for this address so far, we generate one
if (!mKeyStore.engineContainsAlias(localAddress)) {
try {
// We get the CA certificate and private key
X509Certificate caCertificate = (X509Certificate) mKeyStore.engineGetCertificate("root");
PrivateKey caPrivateKey = (PrivateKey) mKeyStore.engineGetKey("root",mPassword);
// Generates the pair of keys for the new certificate
KeyPair keys = CertificateFactory.generateRSAKeyPair(CertificateFactory.DEFAULT_KEY_SIZE);
// We use the localAddress for the CN of the certificate
Certificate certificate = CertificateFactory.generateSignedCertificate(caCertificate, caPrivateKey, keys.getPublic(), localAddress);
// Adds the new certificate in the KeyStore
mKeyStore.engineSetKeyEntry(localAddress, keys.getPrivate(), mPassword, new Certificate[]{certificate});
} catch (Exception e) {
// The certificate could not be generated for some reason
Log.e(TAG, "Failed to generate certificate for CN: "+localAddress);
e.printStackTrace();
return null;
}
}
// We use the address the socket is locally bound to as the alias in the KeyManager
return localAddress;
}
return null;
}
@Override
public synchronized X509Certificate[] getCertificateChain(String alias) {
Certificate caCertificate = mKeyStore.engineGetCertificate("root");
Certificate leafCertificate = mKeyStore.engineGetCertificate(alias);
return new X509Certificate[] {(X509Certificate) leafCertificate, (X509Certificate) caCertificate};
}
/** This method will not be called. Client authentication has not been implemented. */
@Override
public synchronized String[] getClientAliases(String arg0, Principal[] arg1) {
// Will not be used in our case
Log.d(TAG, "getClientAliases");
return null;
}
/**
* Returns the private key of the certificate corresponding to the alias.
* @param alias The alias
* @return The private key
*/
@Override
public synchronized PrivateKey getPrivateKey(String alias) {
try {
return (PrivateKey) mKeyStore.engineGetKey(alias, mPassword);
} catch (Exception e) {
Log.d(TAG, "Alias: \""+alias+"\" not found in the keystore !");
return null;
}
}
@Override
public synchronized String[] getServerAliases(String keyType, Principal[] issuers) {
Log.d(TAG, "getServersAliases");
if (keyType.equals("RSA")) {
int i = 0;
Enumeration<String> aliases = mKeyStore.engineAliases();
String[] list = new String[mKeyStore.engineSize()];
while (aliases.hasMoreElements()) {
list[i++] = aliases.nextElement();
}
return list;
} else return null;
}
public synchronized static X509KeyManager loadFromKeyStore(InputStream is, char[] password) throws IOException {
Log.d(TAG,"Loading certificates from file...");
X509KeyManager manager = new X509KeyManager();
manager.mKeyStore.engineLoad(is, password);
manager.mPassword = password;
return manager;
}
/**
* Saves all the certificates generated and their private key in a JKS file
* @param file The file where the certificate will be saved
* @param password The password to access the private key
*/
public synchronized void saveToKeyStore(OutputStream os, char[] password)
throws InvalidKeyException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidParameterSpecException,
InvalidKeySpecException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException,
KeyStoreException,
CertificateException,
IOException {
mKeyStore.engineStore(os, password);
}
}
/**
*
* Contains some methods to create v3 X509 certificates for the HTTPS server.
* It uses the lib Spongy Castle, which actually is the lib Bouncy Castle repackaged
* for Android.
*
* All certificates generated here uses RSA for the key pair and SHA-1/SHA256 for
* checksums.
*
* If you don't need HTTPS support, you can remove the class {@link ModSSL}
*
*/
public final static class CertificateFactory {
/** The default length of RSA keys */
public final static int DEFAULT_KEY_SIZE = 1024;
private final static String BC = org.spongycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME;
public static KeyPair generateRSAKeyPair(int keySize) throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(keySize);
KeyPair keyPair = keyGen.genKeyPair();
return keyPair;
}
public static X509Certificate generateSignedCertificate(X509Certificate caCertificate, PrivateKey caPrivateKey, PublicKey publicKey, String CN)
throws NoSuchAlgorithmException, OperatorCreationException, CertificateException,
KeyStoreException, UnrecoverableKeyException, IOException,
InvalidKeyException, NoSuchPaddingException, InvalidParameterSpecException,
InvalidKeySpecException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
builder.addRDN(BCStyle.CN, CN);
// We want this root certificate to be valid for one year
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, 1);
ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider(BC).build(caPrivateKey);
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
caCertificate,
new BigInteger(80, new Random()),
new Date(System.currentTimeMillis() - 50000),
calendar.getTime(),
new X500Principal(builder.build().getEncoded()),
publicKey);
// Those are the extensions needed for the certificate to be a leaf certificate that authenticates a SSL server
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, new X509KeyUsage(X509KeyUsage.keyEncipherment));
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, new DERSequence(KeyPurposeId.id_kp_serverAuth));
X509CertificateHolder certificateHolder = certGen.build(sigGen);
X509Certificate certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateHolder);
return certificate;
}
public static X509Certificate generateRootCertificate(KeyPair keys, String CN)
throws NoSuchAlgorithmException, OperatorCreationException, CertificateException,
KeyStoreException, UnrecoverableKeyException, IOException,
InvalidKeyException, NoSuchPaddingException, InvalidParameterSpecException,
InvalidKeySpecException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
builder.addRDN(BCStyle.CN, CN);
// We want this root certificate to be valid for one year
Calendar calendar = Calendar.getInstance();
calendar.add( Calendar.YEAR, 1 );
ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider(BC).build(keys.getPrivate());
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
builder.build(),
new BigInteger(80, new Random()),
new Date(System.currentTimeMillis() - 50000),
calendar.getTime(),
builder.build(),
keys.getPublic());
// Those are the extensions needed for a CA certificate
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true));
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, new X509KeyUsage(X509KeyUsage.digitalSignature));
certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
X509CertificateHolder certificateHolder = certGen.build(sigGen);
X509Certificate certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateHolder);
return certificate;
}
}
} | [
"thanhlongny@gmail.com"
] | thanhlongny@gmail.com |
839754e1038214e8cd4a716537565caa383d4727 | f07f41cbe1f3cc8a7d039f1d1e794f46cf269dec | /src/com/coretronic/BluetoothChat/BluetoothChatService.java | 126da6364170a492d35cd86acafb8d47ee8d84b2 | [] | no_license | Momia88/CoreBluetoothChat | d6477879cfe8f5f7edffe1d9f49d65383ba440fd | 43168192a7c858589d02a416025e8a54b274022b | refs/heads/master | 2021-05-28T12:06:02.425093 | 2014-03-20T02:08:46 | 2014-03-20T02:08:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,496 | java | /*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.coretronic.BluetoothChat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for incoming
* connections, a thread for connecting with a device, and a thread for
* performing data transmissions when connected.
*/
public class BluetoothChatService {
// Debugging
private static final String TAG = "BluetoothChatService";
private static final boolean D = true;
// Name for the SDP record when creating server socket
private static final String NAME_SECURE = "BluetoothChatSecure";
private static final String NAME_INSECURE = "BluetoothChatInsecure";
// Unique UUID for this application
private static final UUID MY_UUID_SECURE = UUID
.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE = UUID
.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
private boolean isDestory = false;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming
// connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing
// connection
public static final int STATE_CONNECTED = 3; // now connected to a remote
// device
/**
* Constructor. Prepares a new BluetoothChat session.
*
* @param context
* The UI Activity Context
* @param handler
* A Handler to send messages back to the UI Activity
*/
public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}
/**
* Set the current state of the chat connection
*
* @param state
* An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D)
Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1)
.sendToTarget();
}
/**
* Return the current connection state.
*/
public synchronized int getState() {
return mState;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
if (D)
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
setState(STATE_LISTEN);
// Start the thread to listen on a BluetoothServerSocket
if (mSecureAcceptThread == null) {
mSecureAcceptThread = new AcceptThread(true);
mSecureAcceptThread.start();
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread(false);
mInsecureAcceptThread.start();
}
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
*
* @param device
* The BluetoothDevice to connect
* @param secure
* Socket Security type - Secure (true) , Insecure (false)
*/
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D)
Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
*
* @param socket
* The BluetoothSocket on which the connection was made
* @param device
* The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket,
BluetoothDevice device, final String socketType) {
if (D)
Log.d(TAG, "connected, Socket Type:" + socketType);
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Cancel the accept thread because we only want to connect to one
// device
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop(boolean isDestory) {
if (D)
Log.d(TAG, "stop");
this.isDestory = isDestory;
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
*
* @param out
* The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED)
return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
Log.e(TAG, "+ FAIL ... + ");
BluetoothChatService.this.start();
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
// Send a failure message back to the Activity
Log.e(TAG, "+ LOST ... + isDestory = " + isDestory);
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
if (!isDestory)
BluetoothChatService.this.start();
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted (or
* until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private String mSocketType;
public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Create a new listening server socket
try {
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(
NAME_SECURE, MY_UUID_SECURE);
} else {
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
}
mmServerSocket = tmp;
}
public void run() {
if (D)
Log.d(TAG, "Socket Type: " + mSocketType
+ "BEGIN mAcceptThread" + this);
setName("AcceptThread" + mSocketType);
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType
+ "accept() failed", e);
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice(),
mSocketType);
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate
// new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D)
Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);
}
public void cancel() {
if (D)
Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Socket Type" + mSocketType
+ "close() of server failed", e);
}
}
}
/**
* This thread runs while attempting to make an outgoing connection with a
* device. It runs straight through; the connection either succeeds or
* fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device
.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device
.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType
+ " socket during connection failure", e2);
}
connectionFailed();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType
+ " socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device. It handles all
* incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
-1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
Log.i(TAG, "ConnectedThread isDestory = " + isDestory);
if (!isDestory)
BluetoothChatService.this.start();
break;
}
}
}
/**
* Write to the connected OutStream.
*
* @param buffer
* The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
| [
"morris.chen@coretronic.com"
] | morris.chen@coretronic.com |
59c728915cc4ce3a9b3f997d9465bf40af208f19 | 1b26f637385cdd43f0d2303093262f5cb0776153 | /usaco/circlecross1.java | 944be21fab2953dbae04f435ef33bc9d7fea2c5e | [] | no_license | ArvinDing/competitive | 2c19b6708fed8a90ffa50940542d16fe490c041d | 4dffc3b0a89adb0e93e38d822bad320d7cb738db | refs/heads/master | 2022-08-23T03:41:36.634290 | 2020-05-23T20:01:42 | 2020-05-23T20:01:42 | 266,403,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,174 | java |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
public class circlecross1 {
public static void main(String[] argv) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("circlecross.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("circlecross.out")));
String read = in.readLine();
boolean[] info = new boolean[26];
int total = 0;
boolean[] done = new boolean[52];
for (int i = 0; i < 52; i++) {
if (!done[i]) {
int curr = read.charAt(i) - 65;
int add = 0;
boolean[] isntNew = new boolean[26];
for (int k = i + 1; k < 52; k++) {
int current = read.charAt(k) - 65;
if (current == curr) {
done[k] = true;
total += add;
}
if (!isntNew[current]) {
add++;
isntNew[current] = true;
} else {
add--;
}
}
}
}
out.print(total / 2);
in.close();
out.close();
}
} | [
"dingarvin@gmail.com"
] | dingarvin@gmail.com |
44a268f593823cf8ef44e79dd98ffcfbafcdbac5 | b98bb0485a891af340140d1e5faf0ac0b211eeea | /modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkAttachmentDescription2KHR.java | 37bd716b4b112de9e865fc95448e6e4f435b9697 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-khronos"
] | permissive | Sorenon/lwjgl3 | 0041393d0a391f59d3f728fb0b30e59df2871829 | 9c1e8140ba0a94b01c12b6ac0efe6eb5957045f3 | refs/heads/master | 2023-06-24T14:15:04.898275 | 2021-07-08T16:07:06 | 2021-07-08T16:07:06 | 340,156,574 | 0 | 1 | BSD-3-Clause | 2021-07-08T16:07:07 | 2021-02-18T19:31:31 | Java | UTF-8 | Java | false | false | 15,637 | java | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* See {@link VkAttachmentDescription2}.
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkAttachmentDescription2KHR {
* VkStructureType sType;
* void const * pNext;
* VkAttachmentDescriptionFlags flags;
* VkFormat format;
* VkSampleCountFlagBits samples;
* VkAttachmentLoadOp loadOp;
* VkAttachmentStoreOp storeOp;
* VkAttachmentLoadOp stencilLoadOp;
* VkAttachmentStoreOp stencilStoreOp;
* VkImageLayout initialLayout;
* VkImageLayout finalLayout;
* }</code></pre>
*/
public class VkAttachmentDescription2KHR extends VkAttachmentDescription2 {
/**
* Creates a {@code VkAttachmentDescription2KHR} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VkAttachmentDescription2KHR(ByteBuffer container) {
super(container);
}
/** Sets the specified value to the {@code sType} field. */
@Override
public VkAttachmentDescription2KHR sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
/** Sets the specified value to the {@code pNext} field. */
@Override
public VkAttachmentDescription2KHR pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; }
/** Sets the specified value to the {@code flags} field. */
@Override
public VkAttachmentDescription2KHR flags(@NativeType("VkAttachmentDescriptionFlags") int value) { nflags(address(), value); return this; }
/** Sets the specified value to the {@code format} field. */
@Override
public VkAttachmentDescription2KHR format(@NativeType("VkFormat") int value) { nformat(address(), value); return this; }
/** Sets the specified value to the {@code samples} field. */
@Override
public VkAttachmentDescription2KHR samples(@NativeType("VkSampleCountFlagBits") int value) { nsamples(address(), value); return this; }
/** Sets the specified value to the {@code loadOp} field. */
@Override
public VkAttachmentDescription2KHR loadOp(@NativeType("VkAttachmentLoadOp") int value) { nloadOp(address(), value); return this; }
/** Sets the specified value to the {@code storeOp} field. */
@Override
public VkAttachmentDescription2KHR storeOp(@NativeType("VkAttachmentStoreOp") int value) { nstoreOp(address(), value); return this; }
/** Sets the specified value to the {@code stencilLoadOp} field. */
@Override
public VkAttachmentDescription2KHR stencilLoadOp(@NativeType("VkAttachmentLoadOp") int value) { nstencilLoadOp(address(), value); return this; }
/** Sets the specified value to the {@code stencilStoreOp} field. */
@Override
public VkAttachmentDescription2KHR stencilStoreOp(@NativeType("VkAttachmentStoreOp") int value) { nstencilStoreOp(address(), value); return this; }
/** Sets the specified value to the {@code initialLayout} field. */
@Override
public VkAttachmentDescription2KHR initialLayout(@NativeType("VkImageLayout") int value) { ninitialLayout(address(), value); return this; }
/** Sets the specified value to the {@code finalLayout} field. */
@Override
public VkAttachmentDescription2KHR finalLayout(@NativeType("VkImageLayout") int value) { nfinalLayout(address(), value); return this; }
/** Initializes this struct with the specified values. */
@Override
public VkAttachmentDescription2KHR set(
int sType,
long pNext,
int flags,
int format,
int samples,
int loadOp,
int storeOp,
int stencilLoadOp,
int stencilStoreOp,
int initialLayout,
int finalLayout
) {
sType(sType);
pNext(pNext);
flags(flags);
format(format);
samples(samples);
loadOp(loadOp);
storeOp(storeOp);
stencilLoadOp(stencilLoadOp);
stencilStoreOp(stencilStoreOp);
initialLayout(initialLayout);
finalLayout(finalLayout);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VkAttachmentDescription2KHR set(VkAttachmentDescription2KHR src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VkAttachmentDescription2KHR} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VkAttachmentDescription2KHR malloc() {
return wrap(VkAttachmentDescription2KHR.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VkAttachmentDescription2KHR} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VkAttachmentDescription2KHR calloc() {
return wrap(VkAttachmentDescription2KHR.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VkAttachmentDescription2KHR} instance allocated with {@link BufferUtils}. */
public static VkAttachmentDescription2KHR create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VkAttachmentDescription2KHR.class, memAddress(container), container);
}
/** Returns a new {@code VkAttachmentDescription2KHR} instance for the specified memory address. */
public static VkAttachmentDescription2KHR create(long address) {
return wrap(VkAttachmentDescription2KHR.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkAttachmentDescription2KHR createSafe(long address) {
return address == NULL ? null : wrap(VkAttachmentDescription2KHR.class, address);
}
/**
* Returns a new {@link VkAttachmentDescription2KHR.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VkAttachmentDescription2KHR.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VkAttachmentDescription2KHR.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VkAttachmentDescription2KHR.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkAttachmentDescription2KHR.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Returns a new {@code VkAttachmentDescription2KHR} instance allocated on the thread-local {@link MemoryStack}. */
public static VkAttachmentDescription2KHR mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@code VkAttachmentDescription2KHR} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static VkAttachmentDescription2KHR callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@code VkAttachmentDescription2KHR} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VkAttachmentDescription2KHR mallocStack(MemoryStack stack) {
return wrap(VkAttachmentDescription2KHR.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VkAttachmentDescription2KHR} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VkAttachmentDescription2KHR callocStack(MemoryStack stack) {
return wrap(VkAttachmentDescription2KHR.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VkAttachmentDescription2KHR.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link VkAttachmentDescription2KHR.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link VkAttachmentDescription2KHR.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer mallocStack(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VkAttachmentDescription2KHR.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkAttachmentDescription2KHR.Buffer callocStack(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** An array of {@link VkAttachmentDescription2KHR} structs. */
public static class Buffer extends VkAttachmentDescription2.Buffer {
private static final VkAttachmentDescription2KHR ELEMENT_FACTORY = VkAttachmentDescription2KHR.create(-1L);
/**
* Creates a new {@code VkAttachmentDescription2KHR.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VkAttachmentDescription2KHR#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VkAttachmentDescription2KHR getElementFactory() {
return ELEMENT_FACTORY;
}
/** Sets the specified value to the {@code sType} field. */
@Override
public VkAttachmentDescription2KHR.Buffer sType(@NativeType("VkStructureType") int value) { VkAttachmentDescription2KHR.nsType(address(), value); return this; }
/** Sets the specified value to the {@code pNext} field. */
@Override
public VkAttachmentDescription2KHR.Buffer pNext(@NativeType("void const *") long value) { VkAttachmentDescription2KHR.npNext(address(), value); return this; }
/** Sets the specified value to the {@code flags} field. */
@Override
public VkAttachmentDescription2KHR.Buffer flags(@NativeType("VkAttachmentDescriptionFlags") int value) { VkAttachmentDescription2KHR.nflags(address(), value); return this; }
/** Sets the specified value to the {@code format} field. */
@Override
public VkAttachmentDescription2KHR.Buffer format(@NativeType("VkFormat") int value) { VkAttachmentDescription2KHR.nformat(address(), value); return this; }
/** Sets the specified value to the {@code samples} field. */
@Override
public VkAttachmentDescription2KHR.Buffer samples(@NativeType("VkSampleCountFlagBits") int value) { VkAttachmentDescription2KHR.nsamples(address(), value); return this; }
/** Sets the specified value to the {@code loadOp} field. */
@Override
public VkAttachmentDescription2KHR.Buffer loadOp(@NativeType("VkAttachmentLoadOp") int value) { VkAttachmentDescription2KHR.nloadOp(address(), value); return this; }
/** Sets the specified value to the {@code storeOp} field. */
@Override
public VkAttachmentDescription2KHR.Buffer storeOp(@NativeType("VkAttachmentStoreOp") int value) { VkAttachmentDescription2KHR.nstoreOp(address(), value); return this; }
/** Sets the specified value to the {@code stencilLoadOp} field. */
@Override
public VkAttachmentDescription2KHR.Buffer stencilLoadOp(@NativeType("VkAttachmentLoadOp") int value) { VkAttachmentDescription2KHR.nstencilLoadOp(address(), value); return this; }
/** Sets the specified value to the {@code stencilStoreOp} field. */
@Override
public VkAttachmentDescription2KHR.Buffer stencilStoreOp(@NativeType("VkAttachmentStoreOp") int value) { VkAttachmentDescription2KHR.nstencilStoreOp(address(), value); return this; }
/** Sets the specified value to the {@code initialLayout} field. */
@Override
public VkAttachmentDescription2KHR.Buffer initialLayout(@NativeType("VkImageLayout") int value) { VkAttachmentDescription2KHR.ninitialLayout(address(), value); return this; }
/** Sets the specified value to the {@code finalLayout} field. */
@Override
public VkAttachmentDescription2KHR.Buffer finalLayout(@NativeType("VkImageLayout") int value) { VkAttachmentDescription2KHR.nfinalLayout(address(), value); return this; }
}
} | [
"iotsakp@gmail.com"
] | iotsakp@gmail.com |
2e29cda4e9b57b5e4698ab7cdc395776e3d736a7 | 947c4ba5392c751df1a51c28d80b946bf13e0fe5 | /src/main/java/csl/pay/thinkingInJava/typeinfo/GenericClass.java | dbf52eaf1782f477ac1a6a59ab9f61f4211181e6 | [] | no_license | chensaili/pay_test | 2ffbcad9ac6a3d832b9f8cf11d3fbfa98e6a8616 | dc44ac24bc7dbf39f331d7259e94e968bc31dd8c | refs/heads/master | 2021-01-16T13:56:28.187692 | 2020-03-09T06:41:51 | 2020-03-09T06:41:51 | 243,145,088 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,647 | java | package csl.pay.thinkingInJava.typeinfo;
//泛化的Class
public class GenericClass {
public static void main(String[] args) {
/**
* int.class和Integer.class指向的不是同一个Class对象引用,但是它们基本类型和包装类的关系,
* int可以自动包装为Integer,
* 所以编译器可以编译通过
*/
Class<Integer>c1=int.class;
c1=Integer.class;
//c1=Double.class;报错
/**
* 泛型中的类型可以持有其子类的引用吗?不行
* 虽然Integer继承自Number,但是编译器无法编译通过。
*/
//Class<Number>c2=Integer.class;
/**
* 为了使用泛化的Class引用放松限制,我们还可以使用通配符,
* 它是Java泛型的一部分。
* 通配符的符合是”?“,表示“任何事物“:
*/
Class<?>c3=int.class;
c3=double.class;
/**
* 通配符?可以与extend结合
* 表示被限定为某种类型,或该类型的任何子类型
*/
Class<? extends Number> c4 = Integer.class;
c4 = Number.class;
c4 = Double.class;
//c4=String.class;报错,String不属于Number类及其子类
/**
* 通配符?不仅可以与extend结合,而且还可以与super关键字相结合,
* 表示被限定为某种类型,或该类型的任何父类型:
*/
Class<? super Integer> c5 = Integer.class;
c5 = Number.class;
c5 = Object.class;
c5=Integer.class.getSuperclass();
}
}
| [
"903928398@qq.com"
] | 903928398@qq.com |
a08d8e1fe0c0af05ca4b98d05dee92c87c0c3c78 | 5e5f49e64a3ddc8d69ad8cbc4accaead5ffdb168 | /src/ch2_section1/Code06_Polynomial2.java | bd0a2bf0a13e8affed0992afe41274a28dc2060d | [] | no_license | 85jbboy/DataStructureW-Java | bcfa73c1dc8306f767fe52a61651cb0f4c96f175 | dc308a23ba4a1d39407c4ed1ecfeb26b5695ffab | refs/heads/master | 2021-05-14T00:46:53.860790 | 2018-01-23T14:21:52 | 2018-01-23T14:21:52 | 116,549,021 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 257 | java | package ch2_section1;
public class Code06_Polynomial2 {
public char name; // 다항식 이름
public Code06_Term[] terms; // 각 항의 차수와 지수를 저장하는 Term 배열
public int nTerms; // 항의 총 개수
}
| [
"85jbb@ManAbov"
] | 85jbb@ManAbov |
2b4dd85abad6f99f0fad942a82f90a900f7d26c0 | 759589cac56e0da3b1b5daf81ce98847d378cb34 | /ShopSharing/src/main/java/model/ShareResult.java | 2786addcb3e8e36726885728261105335816e94f | [] | no_license | sksj317/ShopSharing | 358a80b55d9467df7ec0966d72a72cb38e4f2a9c | eb4abf10fc8be81a4e13201dc2f09cab11f8dbe2 | refs/heads/master | 2020-04-14T23:12:09.749037 | 2019-01-05T10:02:21 | 2019-01-05T10:02:21 | 164,193,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,352 | java | package model;
import java.io.Serializable;
@SuppressWarnings("serial")
public class ShareResult implements Serializable{
private Long shareResultNum;
private Long shareResultDeposit;
private Long shareResultAssure;
private Long shareResultRepay;
public ShareResult () {}
public ShareResult(Long shareResultNum, Long shareResultDeposit, Long shareResultAssure, Long shareResultRepay) {
super();
this.shareResultNum = shareResultNum;
this.shareResultDeposit = shareResultDeposit;
this.shareResultAssure = shareResultAssure;
this.shareResultRepay = shareResultRepay;
}
public Long getShareResultNum() {
return shareResultNum;
}
public void setShareResultNum(Long shareResultNum) {
this.shareResultNum = shareResultNum;
}
public Long getShareResultDeposit() {
return shareResultDeposit;
}
public void setShareResultDeposit(Long shareResultDeposit) {
this.shareResultDeposit = shareResultDeposit;
}
public Long getShareResultAssure() {
return shareResultAssure;
}
public void setShareResultAssure(Long shareResultAssure) {
this.shareResultAssure = shareResultAssure;
}
public Long getShareResultRepay() {
return shareResultRepay;
}
public void setShareResultRepay(Long shareResultRepay) {
this.shareResultRepay = shareResultRepay;
}
}
| [
"sksj345@gmail.com"
] | sksj345@gmail.com |
63ab6d0bc16c9d2785aa3e3dba3e195e43fb99cf | ef2f39752bf50771deb4b00551158e0e60190e53 | /src/main/java/us/codecraft/tinyioc/aop/MethodMatcher.java | ff75213b550894f244517163ac1477cf1ddac76d | [
"Apache-2.0"
] | permissive | pzandsz/tiny-spring | df47b33b09baa787fb22a83b91f82e42e1f69438 | a464d994817fa4a1ca8d67bb9ee30ae1632863d3 | refs/heads/master | 2021-07-20T01:46:01.472171 | 2020-09-07T11:46:25 | 2020-09-07T11:46:25 | 213,795,276 | 0 | 0 | Apache-2.0 | 2019-10-09T01:48:04 | 2019-10-09T01:48:03 | null | UTF-8 | Java | false | false | 249 | java | package us.codecraft.tinyioc.aop;
import java.lang.reflect.Method;
/**
* @author yihua.huang@dianping.com
*/
/**
* 匹配方法
* @author tengyu
*
*/
public interface MethodMatcher {
boolean matches(Method method, Class targetClass);
}
| [
"tengyu@shawn-PC"
] | tengyu@shawn-PC |
ed343d34d487d209ecf3faa43253fd9f13d442db | 5bc9ac8249e9d99403a765855203a5138d3c58fb | /src/main/java/com/vitor/homework/cashregister/barcode/BarcodeInfoParser.java | 020c396da706296f47bb1c9989128a1b180cc066 | [] | no_license | ExenVitor/CashRegister | dd8ec2474a80abfe675238f3e798e056931a0ef5 | 74219cfb376a48c0deeb38c2ac6b8a89ba78ccb5 | refs/heads/master | 2021-01-10T17:14:54.810400 | 2016-03-12T15:29:48 | 2016-03-12T15:29:48 | 53,677,975 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,439 | java | package com.vitor.homework.cashregister.barcode;
import com.google.gson.Gson;
import com.vitor.homework.cashregister.utils.Utils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Vitor Chen on 16-3-12.
* mail: exen3995@gmail.com
*/
public class BarcodeInfoParser {
private static final String BARCODE_REGEX = "(^ITEM\\d+)(-(\\d+))?";
private static final String INVALID_INPUT_MSG = "Barcode data invalid!!" +
" Please check your input and try again.";
private Pattern mPattern;
public BarcodeInfoParser() {
mPattern = Pattern.compile(BARCODE_REGEX);
}
public ArrayList<BarcodeInfo> parse(String barcodeJson)
throws IllegalArgumentException {
String[] itemArray = parseFromJson(barcodeJson);
if (itemArray == null || itemArray.length == 0) {
throw new IllegalArgumentException(INVALID_INPUT_MSG);
}
LinkedHashMap<String, BarcodeInfo> barcodeMap = genBarcodeMap(itemArray);
return new ArrayList<>(barcodeMap.values());
}
private String[] parseFromJson(String barcodeJson) {
Gson gson = new Gson();
String[] itemArray;
try {
itemArray = gson.fromJson(barcodeJson,
String[].class);
} catch (Exception e) {
throw new IllegalArgumentException(INVALID_INPUT_MSG);
}
return itemArray;
}
private LinkedHashMap<String, BarcodeInfo> genBarcodeMap(String[] barcodeData) {
LinkedHashMap<String, BarcodeInfo> barcodeMap =
new LinkedHashMap<>();
for (String data : barcodeData) {
Matcher matcher = mPattern.matcher(data);
if (matcher.matches()) {
String productID = matcher.group(1);
String num = matcher.group(3);
if (Utils.isStringEmpty(num)) {
num = "1";
}
BarcodeInfo info = barcodeMap.get(productID);
if (info == null) {
info = new BarcodeInfo(productID);
}
info.increaseNum(Integer.parseInt(num));
barcodeMap.put(productID, info);
} else {
throw new IllegalArgumentException(INVALID_INPUT_MSG);
}
}
return barcodeMap;
}
}
| [
"exen3995@gmail.com"
] | exen3995@gmail.com |
dfe42cbfa1b083e528de415122af08878764ed08 | b93710e99609f7feb00d938dc620ff74411e414e | /gwt-archetype-resources/frontend/src/main/java/gwt/client/Application.java | 7c418e3c8bc1db0389b4e42b70748c4be06e731f | [] | no_license | stswoon/projectForLessons | 5418b9c1a0d28b839fbb3525537f3ba6fe1b72f8 | 746f3850261b09c140f9a75ee9debf87b04f7afb | refs/heads/master | 2023-01-11T09:52:24.693488 | 2020-12-29T07:18:27 | 2020-12-29T07:18:27 | 39,725,722 | 0 | 0 | null | 2022-12-29T11:38:44 | 2015-07-26T13:04:06 | JavaScript | UTF-8 | Java | false | false | 2,795 | java | package gwt.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.http.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
/**
* Application entry point
*
*/
public class Application implements EntryPoint
{
static final String JSON_URL = "/hello/";
private VerticalPanel vp = new VerticalPanel();
public void onModuleLoad()
{
RootPanel.get().add(new Label("Hello"));
final TextBox tb = new TextBox();
tb.setTitle("Enter your username");
tb.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event)
{
if(event.getCharCode()==13)
{
sendRequest(tb.getText());
}
}
});
Button button = new Button("Send", new ClickHandler() {
public void onClick(ClickEvent event)
{
sendRequest(tb.getText());
}
});
FlowPanel fp = new FlowPanel();
fp.add(tb);
fp.add(button);
vp.setSpacing(5);
vp.add(fp);
RootPanel.get().add(vp);
}
void sendRequest(String name)
{
Greet greet = new Greet();
greet.setName(name);
greet.setStatus(Greet.Status.NEW);
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, JSON_URL);
try
{
builder.setHeader("Content-Type", "application/json");
//builder.sendRequest(new JSONObject(greet).toString(), new RequestCallback() {
builder.sendRequest(greet.toString(), new RequestCallback() {
public void onError(Request request, Throwable exception)
{
displayError("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response)
{
if (response.getStatusCode() == 200)
showGreet(Greet.parse(response.getText()));
else
displayError("Couldn't retrieve JSON");
}
});
} catch (RequestException e) {
displayError("Couldn't retrieve JSON");
}
}
void showGreet(Greet greet)
{
vp.add(new Label("Greet #" + greet.getId() + ": " + greet.getMessage() + " | " /*+ greet.getStatus().getNumber()*/));
}
static void displayError(String error)
{
Window.alert(error);
}
}
| [
"stswoon@yandex.ry"
] | stswoon@yandex.ry |
7643e2978d36ef68786582d76249333a9be8e93e | 7c29eb22c9d4a55b87c1cb4c9e31b04c2a9b2b31 | /dwp/cimiss2-decode/src/main/java/cma/cimiss2/dpc/decoder/bean/agme/Soilchn.java | 4a0909613eb7447b0b72571a2c7ab3908b7aa1d0 | [] | no_license | 523499159/kettle-web | afa9f60958c86a3119bba406edf434d63a3d3c4a | d55c8a38c572cf58d34d3fee243a9026bb4b5b69 | refs/heads/master | 2023-03-17T22:50:28.851262 | 2020-08-31T07:02:53 | 2020-08-31T07:02:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,820 | java | package cma.cimiss2.dpc.decoder.bean.agme;
import lombok.Data;
import java.math.BigDecimal;
import java.sql.Timestamp;
@Data
public class Soilchn {
private String dRecordId;//记录标识
private Timestamp dIymdhm;//入库时间
private String cname;//站名
private String countryname;//国家名称
private String provincename;//省名
private String cityname;//地市名
private String cntyname;//区县名
private String townname;//乡镇名
private BigDecimal q71110;//田间持水量质控码
private BigDecimal q71655010;//10cm重量含水率质控码
private BigDecimal q71655020;//20cm重量含水率质控码
private BigDecimal q71655030;//30cm重量含水率质控码
private BigDecimal q71655040;//40cm重量含水率质控码
private Timestamp dRymdhm;//收到时间
private BigDecimal q71655060;//60cm重量含水率质控码
private Timestamp dUpdateTime;//更新时间
private BigDecimal q71655080;//80cm重量含水率质控码
private Timestamp dDatetime;//资料时间
private String vFileNameSource;//原文件名
private BigDecimal q71655100;//100cm重量含水率质控码
private String qr71110;//田间持水量质控过程码
private String v01301;//区站号/观测平台标识(字符)
private String qr71655010;//10cm重量含水率质控过程码
private BigDecimal v01300;//区站号/观测平台标识(数字)
private String qr71655020;//20cm重量含水率质控过程码
private BigDecimal v05001;//纬度
private BigDecimal v06001;//经度
private String qr71655030;//30cm重量含水率质控过程码
private String qr71655040;//40cm重量含水率质控过程码
private BigDecimal v07001;//测站高度
private BigDecimal v07031;//气压传感器海拔高度
private String qr71655060;//60cm重量含水率质控过程码
private String qr71655080;//80cm重量含水率质控过程码
private BigDecimal v02001;//测站类型
private String qr71655100;//100cm重量含水率质控过程码
private BigDecimal v02301;//测站级别
private String vAcode;//中国行政区划代码
private Short v04001;//年
private Short v04002;//月
private Short v04003;//日
private Short v04004;//时
private BigDecimal v71110;//田间持水量
private BigDecimal v71655010;//10cm重量含水率
private BigDecimal v71655020;//20cm重量含水率
private BigDecimal v71655030;//30cm重量含水率
private BigDecimal v71655040;//40cm重量含水率
private BigDecimal v71655050;//60cm重量含水率
private BigDecimal v71655080;//80cm重量含水率
private BigDecimal v71655100;//100cm重量含水率
private String vBbb;//更正报标志
}
| [
"18309292271@163.com"
] | 18309292271@163.com |
6f9758ebb4105d1f6a7fe148554534ec7b9af1fb | 39d78f9092d6662858844618995e275e788aa1e5 | /src/main/java/products/instruments/Piano.java | 6447fdbf5abecd1f1fb6e75e0772552ddc1489da | [] | no_license | marekboro/MusicShop | f49cc5368d2a690fee9338daca94afa239a14ecd | 6b082c40e0c5ad311979188e7b8f7fc4a4f3b28f | refs/heads/master | 2022-12-22T11:56:07.880546 | 2020-10-03T08:35:42 | 2020-10-03T08:35:42 | 300,571,654 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 607 | java | package products.instruments;
public class Piano extends Instrument {
private final int keyCount;
public Piano(String brand, String model, Double buyPrice, Double sellPrice, String colour) {
super(brand, model, buyPrice, sellPrice, colour);
this.keyCount = 88;
Type stringType = Type.STRING;
Type percussion = Type.PERCUSSION;
addType(stringType);
addType(percussion);
}
public int getKeyCount() {
return keyCount;
}
public String play(){
return getBrand() +" Piano "+ getModel() + " makes a nice sound";
}
}
| [
"marek.borowicz83@gmail.com"
] | marek.borowicz83@gmail.com |
6503f44d028ae36a202dc71c3ad2c30c76cf5deb | cfa9557cc5231333679735348cc2569dc2a28dcf | /friends-orm-newTask/src/com/enigmacamp/friends/db/repositories/PostRepository.java | a6a2be6a5e099c54389a03694d8b0e905a90d07f | [] | no_license | siamsubekti/RepoGitEnigma-Java | 2c8ac33b97382ac256daa2b50dc504f36a20eea1 | bf03ebee415d902db914c20fe5eb0e9d56295952 | refs/heads/master | 2022-04-14T06:59:25.918627 | 2020-02-24T11:01:16 | 2020-02-24T11:01:16 | 242,713,679 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,664 | java | package com.enigmacamp.friends.db.repositories;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import com.enigmacamp.friends.db.entities.Person;
import com.enigmacamp.friends.db.entities.Post;
public class PostRepository extends Repository<Post> {
public PostRepository() {
this.entity = this.query.from(Post.class);
}
public List<Post> findAll(Predicate... predicates) {
CriteriaQuery<Post> cq = this.query.select(this.entity);
cq.where(predicates);
return this.executeQuery(cq).getResultList();
}
public Post find (Integer id) {
return (Post) session.get(Post.class, id);
}
public Post findTitle (String title) {
Query query = session.createQuery("FROM Post WHERE title = :title");
query.setParameter("title", title);
List<Post> result = query.list();
return result.get(0);
}
public List<Post> findByPostDate () {
List<Post> post = new ArrayList<Post>();
Query query = session.createQuery("FROM Post order by post_date desc");
return query.list();
}
public List<Post> findByPostToday () {
List<Post> post = new ArrayList<Post>();
Query query = session.createQuery("FROM Post where day(post_date) = day(now())");
return query.list();
}
@SuppressWarnings({ "deprecation", "unchecked" })
public List<Post> listPostName(String post, String name) {
Criteria postx = session.createCriteria(Post.class);
postx.createAlias("categorys", "pr", Criteria.INNER_JOIN,
Restrictions.eq("pr.name", post));
postx.createAlias("person", "fr", Criteria.INNER_JOIN,
Restrictions.eq("fr.name", name));
return postx.list();
}
public Post create (Post post) {
Transaction trx = this.session.beginTransaction();
session.save(post);
session.getTransaction().commit();
System.out.println("Insert done" + "\n");
return post;
}
public Post update (Post post) {
Transaction trx = this.session.beginTransaction();
session.merge(post);
session.getTransaction().commit();
System.out.println("update done" + "\n");
return post;
}
public void delete (Post post) {
Transaction trx = this.session.beginTransaction();
this.session.delete(post);
session.getTransaction().commit();
System.out.println("delete done"+ "\n");
}
}
| [
"trisiam4@gmail.com"
] | trisiam4@gmail.com |
3dcb30a7766e491a8e0b03a9d398d2dcf716ee06 | 6d665f397081b6da35d6c6ce5a21d2b73d3054b2 | /TeaOrder/app/src/test/java/com/as/atlas/teaorder/ExampleUnitTest.java | d162cf1ab9629cdbeffb8992ba40a46cf88fb5ea | [] | no_license | Atlas0904/Class_Android_Learning | 9fb47cb65b5f89668f17129df2c155d47a197f3a | 9b0e429a67176b59b8a44f11fb028ee6d5072341 | refs/heads/master | 2020-04-06T07:06:34.806107 | 2016-08-31T03:47:14 | 2016-08-31T03:47:14 | 60,006,003 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 314 | java | package com.as.atlas.teaorder;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"u920243@gmail.com"
] | u920243@gmail.com |
9480de1badb74fbfa3c90b3c2962c2d226690c67 | 8c8a8c449ea396bf6f216c0e786fae205055d32b | /LibAsync/src/main/java/com/mar/lib/async/rxjava/internal/operators/maybe/MaybeCallbackObserver.java | 527bd6596fe286812d56f67c4296de5d1fbe038b | [] | no_license | malibo1123/MarLib | 2bf59c9205b0574673b85929dbd077318be4839f | a72c5fd5e127cd6c490c8f043e7ea1fabea5b1da | refs/heads/master | 2022-01-07T09:07:10.035811 | 2019-05-29T09:48:49 | 2019-05-29T09:48:49 | 106,175,567 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,177 | java | /**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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.mar.lib.async.rxjava.internal.operators.maybe;
import java.util.concurrent.atomic.AtomicReference;
import com.mar.lib.async.rxjava.MaybeObserver;
import com.mar.lib.async.rxjava.disposables.Disposable;
import com.mar.lib.async.rxjava.exceptions.*;
import com.mar.lib.async.rxjava.functions.*;
import com.mar.lib.async.rxjava.internal.disposables.DisposableHelper;
import com.mar.lib.async.rxjava.internal.functions.Functions;
import com.mar.lib.async.rxjava.observers.LambdaConsumerIntrospection;
import com.mar.lib.async.rxjava.plugins.RxJavaPlugins;
/**
* MaybeObserver that delegates the onSuccess, onError and onComplete method calls to callbacks.
*
* @param <T> the value type
*/
public final class MaybeCallbackObserver<T>
extends AtomicReference<Disposable>
implements MaybeObserver<T>, Disposable, LambdaConsumerIntrospection {
private static final long serialVersionUID = -6076952298809384986L;
final Consumer<? super T> onSuccess;
final Consumer<? super Throwable> onError;
final Action onComplete;
public MaybeCallbackObserver(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError,
Action onComplete) {
super();
this.onSuccess = onSuccess;
this.onError = onError;
this.onComplete = onComplete;
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this, d);
}
@Override
public void onSuccess(T value) {
lazySet(DisposableHelper.DISPOSED);
try {
onSuccess.accept(value);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
RxJavaPlugins.onError(ex);
}
}
@Override
public void onError(Throwable e) {
lazySet(DisposableHelper.DISPOSED);
try {
onError.accept(e);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
RxJavaPlugins.onError(new CompositeException(e, ex));
}
}
@Override
public void onComplete() {
lazySet(DisposableHelper.DISPOSED);
try {
onComplete.run();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
RxJavaPlugins.onError(ex);
}
}
@Override
public boolean hasCustomOnError() {
return onError != Functions.ON_ERROR_MISSING;
}
}
| [
"malibo@douyu.tv"
] | malibo@douyu.tv |
ffdadf015fa1f1ff1d25ac8202c25a6762f989aa | 2ec499d803462b87edc62e549de425fa5076894d | /yougo-web/src/main/java/com/ineatconseil/yougo/security/CORSFilter.java | 1b34ee911aa01e947c8557e9dd9445c186218c7f | [] | no_license | fdescamps/YouGo-back | 3906d7c9af26112e1d8cc2f5cfa5a4de4b2e5281 | 94804b5b8702a98822f5837109301a7b994e8f67 | refs/heads/master | 2021-01-19T11:49:18.982787 | 2013-04-21T13:34:40 | 2013-04-21T13:34:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,905 | java | package com.ineatconseil.yougo.security;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class CORSFilter implements Filter {
public CORSFilter() { }
// Request headers
private static final String ORIGIN_HEADER = "Origin";
private static final String ACCESS_CONTROL_REQUEST_METHOD_HEADER = "Access-Control-Request-Method";
private static final String ACCESS_CONTROL_REQUEST_HEADERS_HEADER = "Access-Control-Request-Headers";
// Response headers
private static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin";
private static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods";
private static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers";
private static final String ACCESS_CONTROL_MAX_AGE_HEADER = "Access-Control-Max-Age";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER = "Access-Control-Allow-Credentials";
// Implementation constants
private static final String ALLOWED_ORIGINS_PARAM = "allowedOrigins";
private static final String ALLOWED_METHODS_PARAM = "allowedMethods";
private static final String ALLOWED_HEADERS_PARAM = "allowedHeaders";
private static final String PREFLIGHT_MAX_AGE_PARAM = "preflightMaxAge";
private static final String ALLOWED_CREDENTIALS_PARAM = "allowCredentials";
private static final String ANY_ORIGIN = "*";
private static final List<String> SIMPLE_HTTP_METHODS = Arrays.asList("GET", "POST", "HEAD");
private boolean anyOriginAllowed = false;
private List<String> allowedOrigins = new ArrayList<String>();
private List<String> allowedMethods = new ArrayList<String>();
private List<String> allowedHeaders = new ArrayList<String>();
private int preflightMaxAge = 0;
private boolean allowCredentials = true;
public void init(FilterConfig config) throws ServletException
{
String allowedOriginsConfig = config.getInitParameter(ALLOWED_ORIGINS_PARAM);
if (allowedOriginsConfig == null) allowedOriginsConfig = "*";
String[] allowedOrigins = allowedOriginsConfig.split(",");
for (String allowedOrigin : allowedOrigins)
{
allowedOrigin = allowedOrigin.trim();
if (allowedOrigin.length() > 0)
{
if (ANY_ORIGIN.equals(allowedOrigin))
{
anyOriginAllowed = true;
this.allowedOrigins.clear();
break;
}
else
{
this.allowedOrigins.add(allowedOrigin);
}
}
}
String allowedMethodsConfig = config.getInitParameter(ALLOWED_METHODS_PARAM);
if (allowedMethodsConfig == null) allowedMethodsConfig = "GET,POST,OPTIONS";
allowedMethods.addAll(Arrays.asList(allowedMethodsConfig.split(",")));
String allowedHeadersConfig = config.getInitParameter(ALLOWED_HEADERS_PARAM);
if (allowedHeadersConfig == null) allowedHeadersConfig = "authorization,X-Requested-With,Content-Type,Accept,Origin";
allowedHeaders.addAll(Arrays.asList(allowedHeadersConfig.split(",")));
String preflightMaxAgeConfig = config.getInitParameter(PREFLIGHT_MAX_AGE_PARAM);
if (preflightMaxAgeConfig == null) preflightMaxAgeConfig = "1800"; // Default is 30 minutes
try
{
preflightMaxAge = Integer.parseInt(preflightMaxAgeConfig);
}
catch (NumberFormatException x)
{
System.out.println("Cross-origin filter, could not parse '{}' parameter as integer: {}"+ PREFLIGHT_MAX_AGE_PARAM+ preflightMaxAgeConfig);
}
String allowedCredentialsConfig = config.getInitParameter(ALLOWED_CREDENTIALS_PARAM);
if (allowedCredentialsConfig == null) allowedCredentialsConfig = "true";
allowCredentials = Boolean.parseBoolean(allowedCredentialsConfig);
System.out.println("Cross-origin filter configuration: " +
ALLOWED_ORIGINS_PARAM + " = " + allowedOriginsConfig + ", " +
ALLOWED_METHODS_PARAM + " = " + allowedMethodsConfig + ", " +
ALLOWED_HEADERS_PARAM + " = " + allowedHeadersConfig + ", " +
PREFLIGHT_MAX_AGE_PARAM + " = " + preflightMaxAgeConfig + ", " +
ALLOWED_CREDENTIALS_PARAM + " = " + allowedCredentialsConfig);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
handle((HttpServletRequest)request, (HttpServletResponse)response, chain);
}
private void handle(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
{
String origin = request.getHeader(ORIGIN_HEADER);
// Is it a cross origin request ?
if (origin != null && isEnabled(request))
{
if (originMatches(origin))
{
if (isSimpleRequest(request))
{
System.out.println("Cross-origin request to {} is a simple cross-origin request");
handleSimpleResponse(request, response, origin);
}
else
{
System.out.println("Cross-origin request to {} is a preflight cross-origin request");
handlePreflightResponse(request, response, origin);
}
}
else
{
System.out.println("Cross-origin request to " + request.getRequestURI() + " with origin " + origin + " does not match allowed origins " + allowedOrigins);
}
}
chain.doFilter(request, response);
}
protected boolean isEnabled(HttpServletRequest request)
{
// WebSocket clients such as Chrome 5 implement a version of the WebSocket
// protocol that does not accept extra response headers on the upgrade response
if ("Upgrade".equalsIgnoreCase(request.getHeader("Connection")) &&
"WebSocket".equalsIgnoreCase(request.getHeader("Upgrade")))
{
return false;
}
return true;
}
private boolean originMatches(String origin)
{
if (anyOriginAllowed) return true;
for (String allowedOrigin : allowedOrigins)
{
if (allowedOrigin.equals(origin)) return true;
}
return false;
}
private boolean isSimpleRequest(HttpServletRequest request)
{
String method = request.getMethod();
if (SIMPLE_HTTP_METHODS.contains(method))
{
// TODO: implement better section 6.1
// Section 6.1 says that for a request to be simple, custom request headers must be simple.
// Here for simplicity I just check if there is a Access-Control-Request-Method header,
// which is required for preflight requests
return request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER) == null;
}
return false;
}
private void handleSimpleResponse(HttpServletRequest request, HttpServletResponse response, String origin)
{
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, origin);
if (allowCredentials) response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
}
private void handlePreflightResponse(HttpServletRequest request, HttpServletResponse response, String origin)
{
// Implementation of section 5.2
// 5.2.3 and 5.2.5
boolean methodAllowed = isMethodAllowed(request);
if (!methodAllowed) return;
// 5.2.4 and 5.2.6
boolean headersAllowed = areHeadersAllowed(request);
if (!headersAllowed) return;
// 5.2.7
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, origin);
if (allowCredentials) response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
// 5.2.8
if (preflightMaxAge > 0) response.setHeader(ACCESS_CONTROL_MAX_AGE_HEADER, String.valueOf(preflightMaxAge));
// 5.2.9
response.setHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER, commify(allowedMethods));
// 5.2.10
response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_HEADER, commify(allowedHeaders));
}
private boolean isMethodAllowed(HttpServletRequest request)
{
String accessControlRequestMethod = request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER);
System.out.println("{} is {}"+ ACCESS_CONTROL_REQUEST_METHOD_HEADER+ accessControlRequestMethod);
boolean result = false;
if (accessControlRequestMethod != null)
{
result = allowedMethods.contains(accessControlRequestMethod);
}
System.out.println("Method {} is" + (result ? "" : " not") + " among allowed methods {}"+ accessControlRequestMethod+ allowedMethods);
return result;
}
private boolean areHeadersAllowed(HttpServletRequest request)
{
String accessControlRequestHeaders = request.getHeader(ACCESS_CONTROL_REQUEST_HEADERS_HEADER);
System.out.println("{} is {}" + ACCESS_CONTROL_REQUEST_HEADERS_HEADER + accessControlRequestHeaders);
boolean result = true;
if (accessControlRequestHeaders != null)
{
String[] headers = accessControlRequestHeaders.split(",");
for (String header : headers)
{
boolean headerAllowed = false;
for (String allowedHeader : allowedHeaders)
{
if (header.trim().equalsIgnoreCase(allowedHeader.trim()))
{
headerAllowed = true;
break;
}
}
if (!headerAllowed)
{
result = false;
break;
}
}
}
System.out.println("Headers [{}] are" + (result ? "" : " not") + " among allowed headers {}"+ accessControlRequestHeaders+ allowedHeaders);
return result;
}
private String commify(List<String> strings)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < strings.size(); ++i)
{
if (i > 0) builder.append(",");
String string = strings.get(i);
builder.append(string);
}
return builder.toString();
}
public void destroy()
{
anyOriginAllowed = false;
allowedOrigins.clear();
allowedMethods.clear();
allowedHeaders.clear();
preflightMaxAge = 0;
allowCredentials = false;
}
} | [
"francois.descamps@gmail.com"
] | francois.descamps@gmail.com |
449317cbffd87f2b7da51a333bb2cabc7bdbe9d5 | 4ec3bf36837420a2cb84bec4adb772d2664f6e92 | /FrameworkDartesESP_alunosSDIS/brokerOM2M/org.eclipse.om2m/org.eclipse.om2m.commons/src/main/java/org/eclipse/om2m/commons/resource/flexcontainerspec/LiquidLevelFlexContainer.java | eee5a72ac2bbd0acdb218b28c9031f3e1a316efc | [] | no_license | BaltasarAroso/SDIS_OM2M | 1f2ce310b3c1bf64c2a95ad9d236c64bf672abb0 | 618fdb4da1aba5621a85e49dae0442cafef5ca31 | refs/heads/master | 2020-04-08T19:08:22.073674 | 2019-01-20T15:42:48 | 2019-01-20T15:42:48 | 159,641,777 | 0 | 2 | null | 2020-03-06T15:49:51 | 2018-11-29T09:35:02 | C | UTF-8 | Java | false | false | 1,721 | java | /*
********************************************************************************
* Copyright (c) 2014, 2017 Orange.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
********************************************************************************
ModuleClass : LiquidLevel
This ModuleClass manages a level of liquid.
Created: 2017-09-28 17:26:40
*/
package org.eclipse.om2m.commons.resource.flexcontainerspec;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.eclipse.om2m.commons.resource.AbstractFlexContainer;
import org.eclipse.om2m.commons.resource.AbstractFlexContainerAnnc;
@XmlRootElement(name = LiquidLevelFlexContainer.SHORT_NAME, namespace = "http://www.onem2m.org/xml/protocols/homedomain")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = LiquidLevelFlexContainer.SHORT_NAME, namespace = "http://www.onem2m.org/xml/protocols/homedomain")
public class LiquidLevelFlexContainer extends AbstractFlexContainer {
public static final String LONG_NAME = "liquidLevel";
public static final String SHORT_NAME = "liqLl";
public LiquidLevelFlexContainer () {
setContainerDefinition("org.onem2m.home.moduleclass." + LiquidLevelFlexContainer.LONG_NAME);
setLongName(LONG_NAME);
setShortName(SHORT_NAME);
}
public void finalizeSerialization() {
}
public void finalizeDeserialization() {
}
} | [
"ba_aroso@icloud.com"
] | ba_aroso@icloud.com |
9dec02c81d5e2989766acbd791d438f642c64fa5 | e95e8b2d272f136c1886ee100894bfdfbb677afd | /core/src/main/java/io/github/mmm/ui/api/datatype/UiSizeUnit.java | 69a9c3569d5c5c921144e9636897bb87846ae4e6 | [
"Apache-2.0"
] | permissive | safibarri/ui-api | 6b3443bc9f89fa9bf4d493be15ab88cb60e1c0db | d85b6ad5a45f7cc345b47294a8a476cf7cfbcefd | refs/heads/master | 2022-11-22T17:37:03.760197 | 2020-06-29T08:01:37 | 2020-06-29T08:01:37 | 270,618,639 | 0 | 0 | Apache-2.0 | 2020-06-08T10:04:30 | 2020-06-08T10:04:30 | null | UTF-8 | Java | false | false | 1,605 | java | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package io.github.mmm.ui.api.datatype;
/**
* This enum contains the available units for size measures.
*
* @since 1.0.0
*/
// absolute units 1in = 2.54cm = 25.4mm = 72pt = 12pc
// for font-size ~ 1em = 12pt = 16px = 100%
public enum UiSizeUnit {
/** Unit for pixels. */
PIXEL("px", "pixel"),
/** Unit for percent, relative to the parent container. At topmost the entire window. */
PERCENT("%", "percent"),
/** Unit for <em>em</em> meaning a factor relative to the current font-size. */
EM("em", "font-size");
/** @see #getArgb() */
private final String key;
/** @see #toString() */
private final String title;
/**
* The constructor.
*
* @param value - see {@link #getArgb()}.
* @param title - see {@link #toString()}.
*/
private UiSizeUnit(String value, String title) {
this.key = value;
this.title = title;
}
/**
* @return the shorthand key of this unit.
*/
public String getKey() {
return this.key;
}
/**
* @return the display title of this unit (long form).
*/
public String getTitle() {
return this.title;
}
/**
* Creates a new {@link UiSize} with this {@link UiSizeUnit} as {@link UiSize#getUnit() unit}.
*
* @param amount is the {@link UiSize#getAmount() amount}.
* @return the new {@link UiSize}.
*/
public UiSize newSize(double amount) {
return new UiSize(amount, this);
}
@Override
public String toString() {
return this.key;
}
}
| [
"hohwille@users.sourceforge.net"
] | hohwille@users.sourceforge.net |
76cceadee4130ad959556d6860459b5840efd245 | fe0184aea2e874dad369c0d49996fc5490717f58 | /src/main/java/com/scaffy/dao/hibernate/HibernateRESTDao.java | 02867cbbee88a5e125e0ebe1f95e155c41d5b75d | [
"Apache-2.0"
] | permissive | smeduru/spring-scaffy | 142e540aaecb5b5410957494d479988608279903 | 47895378477abc0ca1c07dbb0792db88afbbe04c | refs/heads/master | 2020-12-25T22:48:38.948477 | 2016-01-14T20:07:09 | 2016-01-14T20:07:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,957 | java | /**
*
*/
package com.scaffy.dao.hibernate;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.scaffy.controller.MultipartResponse;
import com.scaffy.dao.BasicRESTDao;
import com.scaffy.dao.DaoOperationException;
import com.scaffy.dao.bean.BeanMethod;
import com.scaffy.dao.bean.BeanMethod.Method;
import com.scaffy.dao.bean.BeanTraversalException;
import com.scaffy.dao.bean.BeanVisitor;
import com.scaffy.entity.attachment.Attachment;
/**
* @author Sherief Shawky
* @Email mcrakens@gmail.com
*/
public class HibernateRESTDao extends BasicRESTDao {
@Autowired
private Session session;
@PostConstruct
public void init() {
addVisitor(BeanMethod.Method.POST, new BeanVisitor() {
public void visit(Object bean) {
session.save(bean);
}
});
addVisitor(BeanMethod.Method.PUT, new BeanVisitor() {
public void visit(Object bean) {
session.merge(bean);
}
});
addVisitor(BeanMethod.Method.DELETE, new BeanVisitor() {
public void visit(Object bean) {
bean = session.merge(bean);
session.delete(bean);
}
});
}
/* (non-Javadoc)
* @see com.scaffy.dao.RESTDao#read(java.lang.Object, java.lang.Class)
*/
public Object read(Object key, Class<?> type) throws DaoOperationException {
Transaction t = session.beginTransaction();
Object model;
try {
t.begin();
model = session.get(type, (Serializable)key);
t.commit();
return model;
} catch(RuntimeException e) {
t.rollback();
throw new DaoOperationException(e);
}
}
/* (non-Javadoc)
* @see com.scaffy.dao.BasicRESTDao#execute(java.lang.Object, com.scaffy.dao.bean.BeanMethod.Method)
*/
@Override
protected void execute(Object model, Method method)
throws BeanTraversalException, DaoOperationException {
Transaction t = session.getTransaction();
try {
t.begin();
traverse(model, method);
t.commit();
} catch(BeanTraversalException e) {
t.rollback();
throw e;
} catch (RuntimeException e) {
t.rollback();
throw new DaoOperationException(e);
}
}
/* (non-Javadoc)
* @see com.scaffy.dao.BasicRESTDao#execute(com.scaffy.controller.MultipartResponse, com.scaffy.dao.bean.BeanMethod.Method)
*/
@Override
protected void execute(MultipartResponse request, Method method)
throws BeanTraversalException, DaoOperationException {
Transaction t = session.getTransaction();
try {
t.begin();
traverse(request.getModel(), method);
for(Attachment attachment : request.getAttachments()){
traverse(attachment, method);
}
t.commit();
} catch(BeanTraversalException e) {
t.rollback();
throw e;
} catch (RuntimeException e) {
t.rollback();
throw new DaoOperationException(e);
}
}
}
| [
"mcrakens@gmail.com"
] | mcrakens@gmail.com |
f0851f281c6806672e50c60eef211606ff7b927f | 1402f7401f7ae4fa8d15878d174f617b89afb5d6 | /LeetCode279.java | 403ea32c22b1f4849ca6e4e4dd560fb04537a418 | [] | no_license | gzou107/LeetCode | 62cec015b669ce2fdca67981db3ab3ec37b3476b | a0a9e70e3ba342ff0819676e38b02d9996f3ab1f | refs/heads/master | 2021-01-10T11:01:48.401828 | 2016-03-21T06:39:47 | 2016-03-21T06:39:47 | 47,909,611 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,006 | java | /*
279. Perfect Squares My Submissions Question
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
*/
public class Solution {
public int numSquares(int n) {
// return helper1(n);
return helper2(n);
}
public int helper2(int n){
int [] dp = new int[n+1];
Arrays.fill(dp, Integer.MAX_VALUE);
for(int i = 1; i * i <=n; i++){
dp[i*i] = 1;
}
// update the value on the fly, not necesary in order
for(int i = 1; i <=n; i++){
for(int j = 1; i + j*j <= n; j++){
dp[i + j*j] = Math.min(dp[i + j *j], dp[i]+1);
}
}
return dp[n];
}
public int helper1(int n){
if(n <= 0){
return 0;
}
if(n <=3) return n;
int [] ans = new int[n+1];
Arrays.fill(ans, Integer.MAX_VALUE);
for(int i = 1; i<=3; i++){
ans[i] = i;
}
int i = 4;
while(i <= n){
if(isPerfect(i)){
ans[i] = 1;
i++;
continue;
}
for(int j = 1; j<= i/2; j++){
if(ans[j] + ans[i-j] < ans[i]){
ans[i] = ans[j] + ans[i-j];
}
}
i++;
}
return ans[n];
}
private boolean isPerfect(int num){
int l = 1;
int h = (int)Math.sqrt(num);
while(l <= h){
int m = l + (h-l)/2;
if(m == (double)num/m){
return true;
}else if(m < num/m){
l = m + 1;
}else{
h = m - 1;
}
}
return false;
}
} | [
"guixiz@microsoft.com"
] | guixiz@microsoft.com |
919f64562e63e70741cdb1322d249b99d73aecc6 | 696e9e03c97bce3fbe6a647438d0a9ef3db1c3be | /src/main/java/pl/bykowski/springboothibernate/twowaybinding/Plates.java | 5a92dd926007da9c9979a69b2c47240a47ba61f1 | [] | no_license | bykowski/sda-poz12-13-springboot-hibernate | 69dfe1f97042a0e6683788adbbe34def3b299961 | 145f16c59fbc65547662f7f2d59e5014f1a172ef | refs/heads/master | 2020-05-05T07:50:47.371953 | 2019-04-06T14:00:20 | 2019-04-06T14:00:20 | 179,840,154 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 762 | java | package pl.bykowski.springboothibernate.twowaybinding;
import javax.persistence.*;
@Entity
public class Plates {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String number;
@OneToOne(mappedBy = "plates")
private Car car;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Plates(String number) {
this.number = number;
}
public Plates() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
| [
"p.bykowski@sdacademy.pl"
] | p.bykowski@sdacademy.pl |
7fe5ed9851e2487b5d2653aa8933016212eaf2f5 | 41650d800965e07477d46e5161dd18b541067e5a | /src/main/java/com/dmatek/zgb/setting/directly/node/set/pack/SetNodeServerIpUdpPack.java | ed686ab025c0753675f958cf444e98695b2107f9 | [] | no_license | 287396159/ZGBWEBSSM | 7a9a0a53fb8423f48bbbb80c1e5bd18cc2ba95ee | 90eccec48e2fc6bf8db9254f62ac296608d7e781 | refs/heads/master | 2022-07-15T11:54:47.976581 | 2019-08-27T09:01:41 | 2019-08-27T09:01:41 | 204,664,275 | 0 | 0 | null | 2022-06-21T01:45:24 | 2019-08-27T09:08:42 | JavaScript | UTF-8 | Java | false | false | 943 | java | package com.dmatek.zgb.setting.directly.node.set.pack;
import com.dmatek.zgb.setting.pack.abstract_.BaseDirectlyNodeSettingUdpPack;
public class SetNodeServerIpUdpPack extends BaseDirectlyNodeSettingUdpPack {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String KEY_NAME = "SetNodeServerIp";
private static final int SIZE = 10;
private static final byte TYPE = 0x01;
@Override
public String keyName() {
// TODO Auto-generated method stub
return KEY_NAME;
}
@Override
protected int size() {
// TODO Auto-generated method stub
return SIZE;
}
@Override
protected byte type() {
// TODO Auto-generated method stub
return TYPE;
}
@Override
protected void initBytes(byte[] bytes) {
if(null != bytes && bytes.length == 4) {
System.arraycopy(bytes, 0, getBytes(), 4, 4);
}
}
@Override
public int obtainDelayMs() {
// TODO Auto-generated method stub
return 4000;
}
}
| [
"admin@qq.com"
] | admin@qq.com |
7bced1643fff5f8e7e0e8e9ded10a1f65ff035ea | 12d3a75121ef8b40d1cfff7a3a7eef470fdeda42 | /src/main/java/com/example/controller/FileController.java | e5dd09e300ea88ef6738424ace3387d2cfa9a892 | [] | no_license | 43244733/xiaochengxu | 7a1af72483a32ec076ddff647a7b882c9549268d | b59a521f460b357ab34de5f67d1f648c8137cab2 | refs/heads/master | 2023-08-02T04:44:03.660557 | 2021-10-06T14:57:09 | 2021-10-06T14:57:09 | 380,129,235 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 763 | java | package com.example.controller;
import com.example.service.ShopService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;
/**
* 文件上传
*/
@Api(tags = "FileController", description = "文件上传")
@Controller
public class FileController {
@Autowired
private ShopService shopService;
}
| [
"1093958707@qq.com"
] | 1093958707@qq.com |
5e0af653fd3f23a34e4db1fcb02e418b35b1c30e | b39dddd3cd99802ee8578a8c611c97a7365f449a | /src/main/java/it/ts/dotcom/demo/graphqlspringbootstarter/service/schema/parser/GraphQLSchemaParser.java | ea73beff868dc8a6ecb58cc4a8b5c57a54c877f7 | [] | no_license | dasko88/graphql-spring-boot-starter | 00830f180b5e857b7af54c9e4860463c9ef262cf | 2c6d92b8f77107a90699a64c90be5b50175a8ae6 | refs/heads/master | 2020-06-15T19:42:01.030461 | 2019-07-05T15:22:30 | 2019-07-05T15:22:30 | 195,378,069 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,781 | java | package it.ts.dotcom.demo.graphqlspringbootstarter.service.schema.parser;
import it.ts.dotcom.demo.graphqlspringbootstarter.service.schema.GraphQLType;
import it.ts.dotcom.demo.graphqlspringbootstarter.service.schema.SchemaHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GraphQLSchemaParser {
private Map<Class, String> classMap;
public GraphQLSchemaParser() {
this.classMap = new HashMap<>();
classMap.put(Integer.class, "Int");
classMap.put(String.class, "String");
}
public String parseGraphQLTypeList(List<GraphQLType> graphQLTypeList) {
List<String> types = new ArrayList<>();
graphQLTypeList.forEach(type -> {
StringBuilder typeSB = new StringBuilder();
typeSB.append("type");
typeSB.append(" ");
typeSB.append(type.getName());
typeSB.append(" ");
typeSB.append("{");
typeSB.append("\n\t");
List<String> fields = new ArrayList<>();
type.getFieldList().forEach(field -> {
StringBuilder fieldSB = new StringBuilder();
fieldSB.append(field.getName());
fieldSB.append(":");
fieldSB.append(" ");
fieldSB.append(classMap.get(field.getClazz()));
fields.add(fieldSB.toString());
});
typeSB.append(fields.stream().collect(Collectors.joining("\n\t")));
typeSB.append("\n");
typeSB.append("}");
types.add(typeSB.toString());
});
return types.stream().collect(Collectors.joining("\n\n"));
}
public String parseGraphQLQueryList(List<GraphQLType> graphQLTypeList) {
List<String> queries = new ArrayList<>();
queries.add("type Query {");
graphQLTypeList.forEach(type -> {
StringBuilder gueryGetSB = new StringBuilder();
gueryGetSB.append("\t");
gueryGetSB.append(SchemaHelper.applyTrasformation(type.getName(), SchemaHelper.getEntityTrasformation()));
gueryGetSB.append("(");
gueryGetSB.append(type.getIdField().getName());
gueryGetSB.append(":");
gueryGetSB.append(" ");
gueryGetSB.append(classMap.get(type.getIdField().getClazz()));
gueryGetSB.append("!");
gueryGetSB.append(")");
gueryGetSB.append(":");
gueryGetSB.append(" ");
gueryGetSB.append(type.getName());
queries.add(gueryGetSB.toString());
StringBuilder queryAllSB = new StringBuilder();
queryAllSB.append("\t");
queryAllSB.append(SchemaHelper.applyTrasformation(type.getName(), SchemaHelper.allEntityTrasformation()));
queryAllSB.append(":");
queryAllSB.append(" ");
queryAllSB.append("[");
queryAllSB.append(type.getName());
queryAllSB.append("]");
queries.add(queryAllSB.toString());
});
queries.add("}");
return queries.stream().collect(Collectors.joining("\n"));
}
public String parseGraphQLMutationList(List<GraphQLType> graphQLTypeList) {
List<String> mutations = new ArrayList<>();
mutations.add("type Mutation {");
graphQLTypeList.forEach(type -> {
StringBuilder mutationNewSB = new StringBuilder();
mutationNewSB.append("\t");
mutationNewSB.append(SchemaHelper.applyTrasformation(type.getName(), SchemaHelper.newEntityTrasformation()));
mutationNewSB.append("(");
List<String> fields = new ArrayList<>();
type.getFieldList().stream()
.filter(field -> field.getName() != "id")
.forEach(field -> {
StringBuilder fieldSB = new StringBuilder();
fieldSB.append(field.getName());
fieldSB.append(":");
fieldSB.append(" ");
fieldSB.append(classMap.get(field.getClazz()));
fields.add(fieldSB.toString());
});
mutationNewSB.append(fields.stream().collect(Collectors.joining(", ")));
mutationNewSB.append(")");
mutationNewSB.append(":");
mutationNewSB.append(" ");
mutationNewSB.append(type.getName());
mutationNewSB.append("!");
mutations.add(mutationNewSB.toString());
StringBuilder mutationUpdateSB = new StringBuilder();
mutationUpdateSB.append("\t");
mutationUpdateSB.append(SchemaHelper.applyTrasformation(type.getName(), SchemaHelper.updateEntityTrasformation()));
mutationUpdateSB.append("(");
List<String> updateFields = new ArrayList<>();
type.getFieldList().forEach(field -> {
StringBuilder fieldSB = new StringBuilder();
fieldSB.append(field.getName());
fieldSB.append(":");
fieldSB.append(" ");
fieldSB.append(classMap.get(field.getClazz()));
updateFields.add(fieldSB.toString());
});
mutationUpdateSB.append(updateFields.stream().collect(Collectors.joining(", ")));
mutationUpdateSB.append(")");
mutationUpdateSB.append(":");
mutationUpdateSB.append(" ");
mutationUpdateSB.append(type.getName());
mutationUpdateSB.append("!");
mutations.add(mutationUpdateSB.toString());
});
mutations.add("}");
return mutations.stream().collect(Collectors.joining("\n"));
}
}
| [
"dskorjanc@dotcom.ts.it"
] | dskorjanc@dotcom.ts.it |
738236100a573dbdebfe082c2d3476c37450d400 | 0806b6e826cea71deb37950203b89b8b37e5e0dd | /connecta-core/src/main/java/br/com/cds/connecta/framework/core/bean/common/AbstractBaseBean.java | a3c5fb617ee909d8365f89422e6b7f3c6fd54aac | [] | no_license | natanielpaiva/connecta-framework | 7d158517808fe433b49c6bc7da6304458145649a | 92791256fa93dbad6ad531183b46737e2440aa5d | refs/heads/master | 2022-12-22T09:14:42.970862 | 2017-02-24T19:02:58 | 2017-02-24T19:02:58 | 83,743,741 | 1 | 1 | null | 2022-12-16T05:21:46 | 2017-03-03T01:37:32 | Java | UTF-8 | Java | false | false | 209 | java | package br.com.cds.connecta.framework.core.bean.common;
import java.io.Serializable;
public abstract class AbstractBaseBean implements Serializable {
private static final long serialVersionUID = 1L;
}
| [
"ryan.thuin@7041b7d6-f801-4286-9b3d-420f2f459141"
] | ryan.thuin@7041b7d6-f801-4286-9b3d-420f2f459141 |
ccd7378f17e0d77b5787a771544e3a894091c541 | ffb047baab4dc0f559d28a6e7e455a267eb4b984 | /app/src/main/java/and/htetarkarzaw/tuntravel/Show_Activity/GuideShow.java | 0fa2997d1dd23feb138f021a65f33e444d801f87 | [] | no_license | htetarkarzaw/Traveller | f6a7bac3939b56a0fe3c719208e95aac8077388b | d2e0b93fd09a36aadf82276a7eb8b7adbc8f06d9 | refs/heads/master | 2021-01-19T19:41:01.111096 | 2017-08-23T16:57:12 | 2017-08-23T16:57:12 | 101,203,968 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,227 | java | package and.htetarkarzaw.tuntravel.Show_Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import and.htetarkarzaw.tuntravel.Add_Activity.AddActivity;
import and.htetarkarzaw.tuntravel.Model.ConductorModel;
import and.htetarkarzaw.tuntravel.Model.GuideModel;
import and.htetarkarzaw.tuntravel.R;
import and.htetarkarzaw.tuntravel.TunTravel;
/**
* Created by Htet Arkar Zaw on 6/29/2017.
*/
public class GuideShow extends Fragment implements View.OnClickListener {
public static final String KEY = "key";
private static final String ITEMS_COUNT = "items_count";
private String key;
private long itemsCount = 0;
TextView tvGName,tvGNRCNo,tvGLicenceNo,tvGAddress,tvGPhNo,tvGRemark,currentTrip,startDate,endDate,tvGuideFree;
Button btnShowGuideEdit,btnShowGuideDelete,btnShowGuideCancel;
LinearLayout guideLoadingLayout;
private ValueEventListener valueEventListener;
private StorageReference storageReference;
private String imageFolder;
private DatabaseReference databaseReference, databaseReference2;
ImageView ivGuideShow;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guide_show, container, false);
guideLoadingLayout = (LinearLayout) v.findViewById(R.id.guideLoadingLayout);
tvGName= (TextView) v.findViewById(R.id.tvGName);
tvGNRCNo= (TextView) v.findViewById(R.id.tvGNRCNo);
tvGLicenceNo= (TextView) v.findViewById(R.id.tvGLicenceNo);
tvGAddress= (TextView) v.findViewById(R.id.tvGAddress);
tvGPhNo= (TextView) v.findViewById(R.id.tvGPhNo);
tvGRemark= (TextView) v.findViewById(R.id.tvGRemark);
btnShowGuideEdit= (Button) v.findViewById(R.id.btnShowGuideEdit);
btnShowGuideDelete= (Button) v.findViewById(R.id.btnShowGuideDelete);
btnShowGuideCancel= (Button) v.findViewById(R.id.btnShowGuideCancel);
ivGuideShow = (ImageView) v.findViewById(R.id.ivGuide);
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String driverName=tvGName.getText().toString();
String driverNRC=tvGNRCNo.getText().toString();
String driverLicence=tvGLicenceNo.getText().toString();
String driverAddress=tvGAddress.getText().toString();
String driverPh=tvGPhNo.getText().toString();
String driverRemark=tvGRemark.getText().toString();
outState.putString(TunTravel.Guides.Keys.GUIDE_NAME,driverName);
outState.putString(TunTravel.Guides.Keys.GUIDE_NRC,driverNRC);
outState.putString(TunTravel.Guides.Keys.GUIDE_LICENCE_NO,driverLicence);
outState.putString(TunTravel.Guides.Keys.GUIDE_ADDRESS,driverAddress);
outState.putString(TunTravel.Guides.Keys.GUIDE_PH_NO,driverPh);
outState.putString(TunTravel.Guides.Keys.GUIDE_REMARK,driverRemark);
outState.putString(KEY, key);
outState.putLong(ITEMS_COUNT, itemsCount);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
tvGName.setText(savedInstanceState.getString(TunTravel.Guides.Keys.GUIDE_NAME));
tvGNRCNo.setText(savedInstanceState.getString(TunTravel.Guides.Keys.GUIDE_NRC));
tvGLicenceNo.setText(savedInstanceState.getString(TunTravel.Guides.Keys.GUIDE_LICENCE_NO));
tvGAddress.setText(savedInstanceState.getString(TunTravel.Guides.Keys.GUIDE_ADDRESS));
tvGPhNo.setText(savedInstanceState.getString(TunTravel.Guides.Keys.GUIDE_PH_NO));
tvGRemark.setText(savedInstanceState.getString(TunTravel.Guides.Keys.GUIDE_REMARK));
this.key = savedInstanceState.getString(KEY);
this.itemsCount = savedInstanceState.getLong(ITEMS_COUNT);
this.imageFolder = savedInstanceState.getString(TunTravel.Guides.Keys.GUIDE_NRC);
}else{
guideLoadingLayout.setVisibility(View.GONE);
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnShowGuideDelete.setEnabled(false);
btnShowGuideEdit.setOnClickListener(this);
btnShowGuideDelete.setOnClickListener(this);
btnShowGuideCancel.setOnClickListener(this);
valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
GuideModel guideModel = dataSnapshot.getValue(GuideModel.class);
tvGName.setText(guideModel.getGuideName());
tvGNRCNo.setText(guideModel.getGuideNRC());
tvGLicenceNo.setText(guideModel.getGuideLicenceNo());
tvGAddress.setText(guideModel.getGuideAddress());
tvGPhNo.setText(guideModel.getGuidePhNo());
tvGRemark.setText(guideModel.getGuideRemark());
guideLoadingLayout.setVisibility(View.VISIBLE);
imageFolder = guideModel.getGuideNRC();
listImageFiles();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference = FirebaseDatabase.getInstance().getReference(TunTravel.Guides.GUIDES);
if (savedInstanceState == null) {
databaseReference.child(key).addValueEventListener(valueEventListener);
} else {
if (imageFolder == null) {
databaseReference.child(key).addValueEventListener(valueEventListener);
} else {
listImageFiles();
}
}
}
public void listImageFiles() {
storageReference = FirebaseStorage.getInstance().getReference(TunTravel.Guides.GUIDE_IMAGES);
if (imageFolder == null) {
databaseReference.child(key).addValueEventListener(valueEventListener);
} else {
storageReference.child(imageFolder).child(TunTravel.Conductor.Image_Names.IMAGE_ONE).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
adaptAndDownload();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
}
private void adaptAndDownload() {
btnShowGuideDelete.setEnabled(true);
try {
Glide.with(getActivity()).using(new FirebaseImageLoader()).load(storageReference.child(imageFolder).child(TunTravel.Conductor.Image_Names.IMAGE_ONE)).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).into(ivGuideShow);
}catch (NullPointerException ne){
}
}
public void setKey(String key, long itemsCount) {
this.key = key;
this.itemsCount = itemsCount;
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (valueEventListener != null) {
databaseReference.child(key).removeEventListener(valueEventListener);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnShowGuideEdit:
Intent intent = new Intent(getActivity(), AddActivity.class);
intent.putExtra(AddActivity.FRAG_TYPE, AddActivity.GUIDE_FRAG);
intent.putExtra(AddActivity.BEHAVIOR_TYPE, AddActivity.GUIDE_EDIT);
intent.putExtra(AddActivity.KEY, key);
intent.putExtra(AddActivity.IMAGE_NAME,TunTravel.Guides.Image_Names.IMAGE_ONE);
startActivity(intent);
getActivity().finish();
break;
case R.id.btnShowGuideDelete:
if (valueEventListener != null) {
databaseReference.child(key).removeEventListener(valueEventListener);
}
databaseReference.child(key).removeValue();
databaseReference2 = FirebaseDatabase.getInstance().getReference(TunTravel.Guides.GUIDE_COUNTS);
databaseReference2.setValue(itemsCount - 1);
if (storageReference == null) {
storageReference = FirebaseStorage.getInstance().getReference(TunTravel.Guides.GUIDE_IMAGES);
}
storageReference.child(imageFolder).child(TunTravel.Conductor.Image_Names.IMAGE_ONE).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
getActivity().finish();
break;
case R.id.btnShowGuideCancel:
getActivity().finish();
break;
}
}
}
| [
"nnhl.mgk@gmail.com"
] | nnhl.mgk@gmail.com |
b48ad79af8d643b13d7e93516c32a95827191647 | ef40d1743a166d9cfe0029f4b065bf1dc1c95c8b | /src/main/java/life/majiang/community/dto/AccessTokenDTO.java | bb6d30b2555b6b2dd9dc71846280bce223f323e4 | [] | no_license | yuanzhi-Zhang/community | f3f4711d8190f3e50c1f984907400941305b4e31 | 40647a2658e8e68beeccdbcdcdf09e1fb22ed581 | refs/heads/master | 2022-06-29T15:24:12.956035 | 2019-09-21T01:56:17 | 2019-09-21T01:56:17 | 209,787,596 | 0 | 0 | null | 2022-06-17T02:32:12 | 2019-09-20T12:39:31 | Java | UTF-8 | Java | false | false | 1,108 | java | package life.majiang.community.dto;
/**
* @Author: yuanzhi...
* @Description:
* @Date: created in 2019/9/20 23:25
* @Modified By:
*/
public class AccessTokenDTO {
private String client_id;
private String client_secret;
private String code;
private String redirect_uri;
private String state;
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public String getClient_secret() {
return client_secret;
}
public void setClient_secret(String client_secret) {
this.client_secret = client_secret;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRedirect_uri() {
return redirect_uri;
}
public void setRedirect_uri(String redirect_uri) {
this.redirect_uri = redirect_uri;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
| [
"2625221623@qq.com"
] | 2625221623@qq.com |
580d29eb44935031f0e1c793adf918c1b35830dc | 7aeace6f380bf09d8c821b00e4eea397f3ec6523 | /Chalenges/src/codingfor30days/day21generics/Main.java | 905c79d57b7cfb1d210e89d5b5b897666ae6d05b | [] | no_license | marom/TinkeringSandbox | 04d5de0ce8e35df2e1aaa566bef02b67348135bc | e266285dade9c987ace830e53f6f020f4d1cff69 | refs/heads/master | 2020-05-02T04:44:39.247401 | 2019-06-09T09:28:31 | 2019-06-09T09:28:31 | 177,757,037 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,324 | java | package codingfor30days.day21generics;
import java.util.Scanner;
public class Main {
static class Printer <T> {
public void printArray(T[] param) {
for (T element : param) {
System.out.println(element);
}
}
/**
* Method Name: printArray
* Print each element of the generic array on a new line. Do not return anything.
* @param A generic array
**/
// Write your code here
}
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Integer[] intArray = new Integer[n];
for (int i = 0; i < n; i++) {
intArray[i] = scanner.nextInt();
}
n = scanner.nextInt();
String[] stringArray = new String[n];
for (int i = 0; i < n; i++) {
stringArray[i] = scanner.next();
}
Printer<Integer> intPrinter = new Printer<>();
Printer<String> stringPrinter = new Printer<>();
intPrinter.printArray( intArray );
stringPrinter.printArray( stringArray );
if(Printer.class.getDeclaredMethods().length > 1){
System.out.println("The Printer class should only have 1 method named printArray.");
}
}
}
| [
"maro.muszynski@gmail.com"
] | maro.muszynski@gmail.com |
6c0b8b133d8e473cc29056fb12e41ae168e6be11 | 43c012a9cdea1df74ddeaf16f7850ccaaedf0782 | /CCP/plugin/network_service/fermat-ccp-plugin-network-service-crypto-addresses-bitdubai/src/main/java/com/bitdubai/fermat_ccp_plugin/layer/network_service/crypto_addresses/developer/bitdubai/version_1/exceptions/CantReceiveRequestException.java | 8366edb323cb4244dc07adec421bf85689092408 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | franklinmarcano1970/fermat | ef08d8c46740ac80ebeec96eca85936ce36d3ee8 | c5239a0d4c97414881c9baf152243e6311c9afd5 | refs/heads/develop | 2020-04-07T04:12:39.745585 | 2016-05-23T21:20:37 | 2016-05-23T21:20:37 | 52,887,265 | 1 | 22 | null | 2016-08-23T12:58:03 | 2016-03-01T15:26:55 | Java | UTF-8 | Java | false | false | 1,149 | java | package com.bitdubai.fermat_ccp_plugin.layer.network_service.crypto_addresses.developer.bitdubai.version_1.exceptions;
import com.bitdubai.fermat_api.FermatException;
/**
* The exception <code>com.bitdubai.fermat_ccp_plugin.layer.network_service.crypto_addresses.developer.bitdubai.version_1.exceptions.CantReceiveRequestException</code>
* is thrown when there is an error trying to receive a, address exchange request.
* <p>
* Created by Leon Acosta - (laion.cj91@gmail.com) on 17/10/2015.
*/
public class CantReceiveRequestException extends FermatException {
private static final String DEFAULT_MESSAGE = "CANT' RECEIVE REQUEST EXCEPTION";
public CantReceiveRequestException(String message, Exception cause, String context, String possibleReason) {
super(message, cause, context, possibleReason);
}
public CantReceiveRequestException(Exception cause, String context, String possibleReason) {
this(DEFAULT_MESSAGE, cause, context, possibleReason);
}
public CantReceiveRequestException(String context, String possibleReason) {
this(DEFAULT_MESSAGE, null, context, possibleReason);
}
}
| [
"laion.cj91@gmail.com"
] | laion.cj91@gmail.com |
8ec8c0d621117128b8730337c4badf05b4d74949 | df0c85f631c4084719e5e7c7caa92c0bfa559f16 | /Java In 21 Days/src/d16p6/ClassType.java | 212f2b71cabe07749b49c2413c61a5e651c8ea0e | [] | no_license | swiftandquick/Java-in-21-Days-7th-Edition- | 5027947be7fa9036a74a642890b8191f8a831cf9 | d36aac485e87c2100c1c5fe44c1cf2649977105f | refs/heads/master | 2022-12-29T19:58:19.943310 | 2020-10-11T23:07:16 | 2020-10-11T23:07:16 | 295,561,740 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 661 | java | package d16p6;
public class ClassType {
public static void main(String[] args) {
/* Creates an object of String type. */
Class c = String.class;
try {
/* newInstance() is used to create a new instance of that class.
* Object is the superclass of String, so I instantiate o as
* String type as well. */
Object o = c.newInstance();
/* Tests whether the object is an instance of the specified type
* (class, subclass, or interface). */
if (o instanceof String) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
} | [
"chenyMA16@gmail.com"
] | chenyMA16@gmail.com |
e587d49f474125831742ab43bc3e8659373e84fe | 1c9fd1cff1b959adbc0f1ece8274506b51750710 | /Fun/src/practice/RaceRocketFuel.java | 3d371dc0129ef8fe397cfab8e315f98fa0b33503 | [] | no_license | rogercallster/Fun | ca57f711e26fdf2b59e0a525d2080d1102b29255 | 6c82d9b604a0d059eef360b7fb1926bbc0372874 | refs/heads/master | 2016-09-06T19:10:06.562973 | 2014-10-10T03:48:19 | 2014-10-10T03:48:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 872 | java | package practice;
public class RaceRocketFuel {
public static void main(String[] st){
int[] set= {4,2,6,1,6,23,7,22,25,233,3,24,1};
//for(int i:set)System.out.println(i);
//PRINT
quickSort(set,0,set.length-1);
for(int i:set)System.out.println(i);
}
static void quickSort(int [] set, int l,int h){
if(l<h){
int i=l;
int j=h;
long pivot = set[h];
while(j>=i){
while(set[i]<pivot) {
i++;
}
while(set[j]>pivot){
j--;
}
if(i<=j){
swap(set,i,j);
i++;j--;
}
else break;
}
if(l<j)
quickSort(set,l,i-1);
if(h>i)
quickSort(set,i,h);
}
}
private static void swap(int[] ar ,int i, int j) {
int temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
}
class Set{
long start;
long end;
int id;
} | [
"rogercallster@gmail.com"
] | rogercallster@gmail.com |
bee2917f1051ddd66c741be6fe739f89c4087a01 | df6eff70229b5a5fa16207d9f9ef610203cde5bb | /src/ru/geekbrains/firstproject/MainClass.java | aedebdca1e7a745453d70ad53a58e15f52f01a94 | [] | no_license | temnoed/J1L1 | 54d630caf4cb2a55c0d0c37455e240128b1564be | 41c37cb860b7c14762ad2cb7236fe8d1ead5ab64 | refs/heads/master | 2021-01-13T15:56:52.324496 | 2016-12-24T22:44:57 | 2016-12-24T22:44:57 | 76,805,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,775 | java | package ru.geekbrains.firstproject;
public class MainClass {
// Создаём простой метод main
public static void main (String[] args) {
System.out.println("Hellow, Programmer!");
// Инициализируем переменные всех типов
final byte a = 1;
short b = 2000;
int c = 300000;
long d = 400000L;
float e = 5.0f;
double f = 6.5346563;
boolean g = false;
char h = 'x';
// выводим результаты
System.out.println("Задание 3:");
System.out.println("При a,b,c,d = 1,2,3,4, a*(b+(c/d))=" + result(1,2,3,4));
System.out.println("Задание 4:");
System.out.println("Сумма 2 + 9 входит между 10 и 20 ? - " + vnutri_10_20(2,9));
System.out.println("Задание 5:");
numberSign(-4);
System.out.println("Задание 6:");
System.out.println("Посылаем число 20, результат - " + isNegative(20));
System.out.println("Задание 7:");
helloName("Агафон");
System.out.println("Задание 8:");
bissextus(2017);
}
// методом вычисляем a * (b + (c / d)
public static float result (float a, float b, float c, float d) {
return (a * (b + (c / d)));
}
// методом вычисляем входит ли сумма a и b между 10 и 20 вкл.
public static boolean vnutri_10_20 (int a, int b) {
if ((a + b) >= 10 && (a + b) <= 20) {
return true;
} else {
return false;
}
}
// метод определяет знак числа
public static void numberSign (int a) {
if (a < 0) {
System.out.println("Число " + a + " отрицательное.");
} else {
System.out.println("Число " + a + " положительное.");
}
}
// метод возвращает true если число отрицательное
public static boolean isNegative (int a) {
if (a < 0) {
return true;
} else {
return false;
}
}
//метод выводит Привет, Имя!
public static void helloName (String name) {
System.out.println("Привет, " + name);
}
// високосный ?
public static void bissextus(int year) {
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
System.out.println("Год " + year + " - високосный.");
} else {
System.out.println("Год " + year + " - НЕвисокосный.");
}
}
} | [
"dc9257351633@gmail.com"
] | dc9257351633@gmail.com |
7e8795476704967d2180d28818c5ee6d2338950e | e502b19ad55ca0f7db2d81cae58d49ec735e4295 | /library_base/common/src/main/java/com/hubertyoung/common/base/AbsLifecycleActivity.java | 906efbd3611ec54587073d340fbd282c8ef7dbef | [] | no_license | zyl-me/AcFun-Android | 9887ebd274dae7d58daedd4c771ff2d6ba7d9927 | f243f834e9ce85f9926e6545870c7dfe61a5cd3d | refs/heads/master | 2020-06-09T13:13:05.339157 | 2018-12-20T01:18:53 | 2018-12-20T01:18:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,223 | java | package com.hubertyoung.common.base;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import com.hubertyoung.common.stateview.StateConstants;
import com.hubertyoung.common.utils.TUtil;
/**
* AbsLifecycleActivity
*/
public abstract class AbsLifecycleActivity< VM extends AbsViewModel > extends BaseActivity {
protected VM mViewModel;
public AbsLifecycleActivity() {
}
@Override
public void initView( Bundle savedInstanceState ) {
mViewModel = VMProviders( this, TUtil.getInstance( this, 0 ) );
dataObserver();
}
protected < T extends ViewModel > VM VMProviders( AppCompatActivity activity, @NonNull Class modelClass ) {
if ( modelClass == null ) {
return null;
}
return ( VM ) ViewModelProviders.of( activity ).get( modelClass );
}
protected void dataObserver() {
}
protected void showLoading( String title ) {
}
// @Override
// protected void onStateRefresh() {
// showLoading();
// }
// protected void showError( Class<? extends BaseStateControl > stateView, Object tag) {
// loadManager.showStateView(stateView, tag);
// }
//
// protected void showError(Class<? extends BaseStateControl> stateView) {
// showError(stateView, null);
// }
//
// protected void showSuccess() {
// loadManager.showSuccess();
// }
//
// protected void showLoading() {
// loadManager.showStateView(LoadingState.class);
// }
/**
* show error layout
*/
protected Observer observer = new Observer< String >() {
@Override
public void onChanged( @Nullable String state ) {
if ( !TextUtils.isEmpty( state ) ) {
if ( StateConstants.ERROR_STATE.equals( state ) ) {
showErrorLayout();
} else if ( StateConstants.NET_WORK_STATE.equals( state ) ) {
} else if ( StateConstants.LOADING_STATE.equals( state ) ) {
showLoading( "" );
} else if ( StateConstants.SUCCESS_STATE.equals( state ) ) {
stopLoading();
}
}
}
};
}
| [
"cnbjyangjian@gmail.com"
] | cnbjyangjian@gmail.com |
40b624179cf26c62cd4c3b26c722dd7ad6bb1256 | 460cb5b4e42f83f92a41181712fc34b047542ec5 | /core/src/main/java/com/github/edgar615/sql/InsertBuilder.java | 989d08d80777f22a8d7b50df7c98fc2e252cf284 | [] | no_license | edgar615/jdbc | 87dae7b17ce6957a217f245392a0a76ee90b65f9 | a86af37b3da05b0c557f3e1358a972ceafc38ae5 | refs/heads/master | 2022-07-01T18:12:38.146174 | 2021-03-08T09:05:03 | 2021-03-08T09:05:03 | 230,420,090 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,341 | java | package com.github.edgar615.sql;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class InsertBuilder implements SqlBuilder {
private final String table;
private List<Entry<String, Object>> columns = new ArrayList<>();
private InsertBuilder(String table) {
this.table = table;
}
@Override
public SQLBindings build() {
List<String> prepare = columns.stream()
.map(c -> "?")
.collect(Collectors.toList());
List<String> fields = columns.stream()
.map(c -> c.getKey())
.collect(Collectors.toList());
List<Object> values = columns.stream()
.map(c -> c.getValue())
.collect(Collectors.toList());
StringBuilder sql = new StringBuilder("insert into ").append(table).append("(")
.append(Joiner.on(",").join(fields))
.append(") values(")
.append(Joiner.on(",").join(prepare))
.append(")");
return SQLBindings.create(sql.toString(), values);
}
public static InsertBuilder create(String table) {
return new InsertBuilder(table);
}
public InsertBuilder set(String column, Object value) {
columns.add(Maps.immutableEntry(column, value));
return this;
}
}
| [
"edgar615@gmail.com"
] | edgar615@gmail.com |
76551d834062e3cba5c0c491467bcc89281f9fd7 | e414a9b753b954de8d11425f8f282e314e330740 | /src/main/java/com/impactsure/artnook/service/config/LoggingConfiguration.java | 9deef084f667d1c7e2f7723582917125159037e3 | [] | no_license | infinitysiddhu/artnook-service | 0a2cf39eb5ccc670219e843ba14c981647e12cb2 | bbbb2c1595ca54447f7f1aef021a8f42006dac1a | refs/heads/master | 2022-03-22T01:50:05.750633 | 2020-03-27T14:28:31 | 2020-03-27T14:28:31 | 250,555,840 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,332 | java | package com.impactsure.artnook.service.config;
import static io.github.jhipster.config.logging.LoggingUtils.*;
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.jhipster.config.JHipsterProperties;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.info.BuildProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
/*
* Configures the console and Logstash log appenders from the app properties
*/
@Configuration
@RefreshScope
public class LoggingConfiguration {
public LoggingConfiguration(
@Value("${spring.application.name}") String appName,
@Value("${server.port}") String serverPort,
JHipsterProperties jHipsterProperties,
ObjectProvider<BuildProperties> buildProperties,
ObjectMapper mapper
)
throws JsonProcessingException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Map<String, String> map = new HashMap<>();
map.put("app_name", appName);
map.put("app_port", serverPort);
buildProperties.ifAvailable(it -> map.put("version", it.getVersion()));
String customFields = mapper.writeValueAsString(map);
JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging();
JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash();
if (loggingProperties.isUseJsonFormat()) {
addJsonConsoleAppender(context, customFields);
}
if (logstashProperties.isEnabled()) {
addLogstashTcpSocketAppender(context, customFields, logstashProperties);
}
if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) {
addContextListener(context, customFields, loggingProperties);
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
setMetricsMarkerLogbackFilter(context, loggingProperties.isUseJsonFormat());
}
}
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
dfa962521c86b681fdd145cc59e69ffcca8f1407 | f8056ea9a7eec50f8b9f61d90c706722d23f7b65 | /src/main/java/com/example/springboot/controller/EmployeeRestController.java | ade8785685b442d1ee786c4d406e46c89b00aa5e | [] | no_license | nsshylaja/SpringBootSample | 19cb698c6b338de7fa9a48da4fbb7e16dd17b89e | 6fe0187fb6d7ab5f34ec18ad617b1e01160089e3 | refs/heads/master | 2021-07-08T17:47:13.931947 | 2017-10-05T02:59:33 | 2017-10-05T02:59:33 | 105,843,674 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,897 | java | package com.example.springboot.controller;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.springboot.entity.Employee;
import com.example.springboot.service.EmployeeService;
@RestController
@RequestMapping("/employee")
public class EmployeeRestController {
final static Logger logger = Logger.getLogger(EmployeeRestController.class);
@Autowired
EmployeeService employeeService;
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee) {
employeeService.addEmployee(employee);
logger.debug("Added:: " + employee);
return new ResponseEntity<Employee>(employee, HttpStatus.CREATED);
}
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<Employee>> getAllEmployees() {
List<Employee> employees = employeeService.getEmployees();
if (employees.isEmpty()) {
logger.debug("Employees does not exists");
return new ResponseEntity<List<Employee>>(HttpStatus.NO_CONTENT);
}
logger.debug("Found " + employees.size() + " Employees");
logger.debug(employees);
logger.debug(Arrays.toString(employees.toArray()));
return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
}
@RequestMapping(value = "/{Id}", method = RequestMethod.DELETE)
public ResponseEntity<Employee> deleteEmployee(@PathVariable Long Id) {
int val = employeeService.deleteEmployee(Id);
if(val == 0){
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
logger.debug("Deleted:: " + Id);
return new ResponseEntity<Employee>(HttpStatus.OK);
}
@RequestMapping(value = "/{Id}", method = RequestMethod.PUT)
public ResponseEntity<Employee> updateEmployee(@PathVariable Long Id, @RequestBody Employee employee) {
int val = employeeService.updateEmployee(employee, Id);
logger.debug("Updated:: " + Id);
if(val == 0){
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<Employee>(HttpStatus.OK);
}
@RequestMapping(value = "/{Id}", method = RequestMethod.GET)
public ResponseEntity<Employee> getEmployee(@PathVariable Long Id) {
Employee employee = employeeService.getEmployee(Id);
if(employee == null){
return new ResponseEntity<Employee>(HttpStatus.NO_CONTENT);
}
logger.debug("Selected:: " + Id);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
}
| [
"32357327+nsshylaja@users.noreply.github.com"
] | 32357327+nsshylaja@users.noreply.github.com |
08fd4a743de4cadfde02b02ffd48e5bcf5e821e4 | 98be63bae374bc835360632d0d6a45baa1fd00ea | /src/test/java/Com/pages/NextPage_page.java | 00548f5f439f60181d1616f80e56182947099a7b | [] | no_license | svsnarasimharao123/demoproject | a2f81a94bddeea369b6d77116583d7548bd9a276 | 50aa5fe1e45ee790d07d1ea6c16fb2eaa35bea40 | refs/heads/master | 2021-07-18T19:09:45.000160 | 2020-03-14T12:37:57 | 2020-03-14T12:37:57 | 247,273,371 | 0 | 0 | null | 2021-04-26T20:03:17 | 2020-03-14T12:35:11 | Java | UTF-8 | Java | false | false | 1,891 | java | package Com.pages;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class NextPage_page {
WebDriver driver;
WebElement textbox;
public void url()
{
System.setProperty("webdriver.chrome.driver", "D:\\SeleniumJars\\Chrome Driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.get("https://google.com");
System.out.println(driver.getTitle());
}
public void demoblaze_homePage()
{
driver.get("https://demoblaze.com/index.html");
System.out.println(driver.getTitle());
}
public void Scrollby() throws InterruptedException
{
WebElement a=driver.findElement(By.id("next2"));
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0,8000)");
driver.findElement(By.xpath("//html//body//div[5]//div//div[2]//form//ul//li[2]//button")).click();
driver.findElement(By.xpath("//*[@id=\"tbodyid\"]//div[4]//div//div//h4//a")).click();
}
public void click() throws InterruptedException, IOException
{
driver.findElement(By.xpath("//*[@id=\"tbodyid\"]/div[4]/div/div/h4/a")).click();
Thread.sleep(5000);
screenshot2("D:\\adh\\Project\\srceen\\abdg.png");
}
public void screenshot2(String path) throws IOException
{
TakesScreenshot ts =(TakesScreenshot)driver;//To take Screenshot
File Source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(Source, new File(path));
}
}
| [
"svss.narasimharao123@gmail.com"
] | svss.narasimharao123@gmail.com |
f3848b6c33ff35790d5f4765f94145890d1feeff | 5eb150a6644f61316fcf02aedfefb0726b392e67 | /vertx-blog-demo/src/main/java/stu/vertx/web/route/HttpServerWithRoute.java | 4b19749fc5c628096361e23b22e4d0654a5c2052 | [] | no_license | yrj2011/vertx | c1ed52ed8911b1025bf594d839c6dec7070937a9 | 1be6e6a6e056f8d24bb61f1d403d5f3c35193f74 | refs/heads/master | 2020-06-17T18:41:31.886868 | 2019-07-10T14:13:34 | 2019-07-10T14:13:34 | 196,011,686 | 0 | 0 | null | 2019-07-09T13:12:47 | 2019-07-09T13:12:46 | null | UTF-8 | Java | false | false | 2,741 | java | package stu.vertx.web.route;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
/**
* Vertx的路由,需要引入Vertx-Web模块
*
* @author lenovo
*
*/
public class HttpServerWithRoute extends AbstractVerticle {
@Override
public void start() throws Exception {
// 创建一个HttpServer
HttpServer server = vertx.createHttpServer();
// 创建路由对象
Router router = Router.router(vertx);
// 这里可以处理post请求的body体数据
router.route().handler(BodyHandler.create());
// 创建路由规则,当在浏览器中输入 localhost:8888/index时匹配
router.route("/index/*").order(2).handler(request -> {
// request.response().end("Index");
System.out.println(1);
request.next(); // 调下一个匹配规则
});
router.route("/index/main").order(-1).handler(request -> {
// request.response().end("IndexMain");
System.out.println("2");
request.next(); // 调下一个匹配规则
});
// 通过route的参数限定请求的方法
router.route(HttpMethod.GET, "/method").handler(request -> {
String param = request.request().getParam("param");
System.out.println("接收到用户传递的参数为:" + param);
request.response().end("method");
});
// 获取参数
router.route(HttpMethod.GET, "/method/:user/:pass").handler(request -> {
String user = request.request().getParam("user");
String pass = request.request().getParam("pass");
request.response().putHeader("Content-type", "text/html;charset=utf-8")
.end("接收到的用户名为:" + user + " 接收到的密码为:" + pass);
});
// 限制使用post方法
router.post("/post").handler(request -> {
String res = request.getBodyAsString();
System.out.println(res);
request.response().end("post");
});
// 使用正则表达式匹配
router.routeWithRegex("/index/aaa/*").handler(request -> {
request.response().end("Regex");
});
// 创建路由规则,当在浏览器中输入 localhost:8888/hello时匹配
router.route("/hello").handler(request -> {
request.response().end("Hello");
});
// 把请求交给路由处理
// server.requestHandler(router::accept);
server.requestHandler(new Handler<HttpServerRequest>() {
@Override
public void handle(HttpServerRequest event) {
router.accept(event);
}
});
server.listen(8881);
}
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new HttpServerWithRoute());
}
}
| [
"18366131816@163.com"
] | 18366131816@163.com |
34b45c2ce9e3c27e4bc1d5b43888089f27995865 | 36e9fa883d65a61cdf3f4e861e14e2bf21046a6e | /src/NumbersAndStrings/Numbers/FPAdder.java | f88238e4586075aaf8964dafc4e95740140c3e75 | [] | no_license | electrosalaf/UltimateJavaDocumentation | 83513bd5ba9401ca22b873243d3c0711f58488bc | 922cc38bb7722364074458656a49620f311a9d43 | refs/heads/master | 2023-03-06T14:13:44.221602 | 2021-02-11T12:47:52 | 2021-02-11T12:47:52 | 309,182,075 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 776 | java | package NumbersAndStrings.Numbers;
import java.text.DecimalFormat;
public class FPAdder {
public static void main(String[] args) {
int numArgs = args.length;
// This program requires at least two arguments on the command line
if (numArgs < 2) {
System.out.println("This program requires two command-line arguements.");
} else {
double sum = 0.0;
for (int i = 0; i < numArgs; i++) {
sum += Double.valueOf(args[i]).doubleValue();
}
// Format the sum
DecimalFormat myFormatter = new DecimalFormat("###,###.##");
String output = myFormatter.format(sum);
// Print sum
System.out.println(sum);
}
}
}
| [
"51977981+electrosalaf@users.noreply.github.com"
] | 51977981+electrosalaf@users.noreply.github.com |
c1db7fa228e87310f2173c26ad331d8fe46d9ee7 | 57b5b1c8fd6b4abc3e6881ddead2c75a21447ff3 | /src/main/java/com/ming/springboottext/LambdaStudy.java | 99bd12056b4915f27bc4dd62bd4dcf753e2733ca | [] | no_license | rateyu/spring-boot-text | f14ffd72108af7a909eb7184de5579331386480a | 931f3a313c7d80c62ee3bb4714d99e270637073e | refs/heads/master | 2021-06-20T07:08:30.115694 | 2019-11-16T03:02:36 | 2019-11-16T03:02:36 | 222,039,104 | 0 | 0 | null | 2021-06-04T02:18:58 | 2019-11-16T03:05:44 | Java | UTF-8 | Java | false | false | 1,018 | java | package com.ming.springboottext;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
public class LambdaStudy {
@Test
public static void main(String[] args) {
List list = Arrays.asList("hello", "word", "你好", "世界");
//初始版本
list.stream().filter(str -> "hello".equals(str)).map(str -> str = "你好").forEach(str -> System.out.println(str));
//最简洁版本
list.stream().filter(str -> "hello".equals(str)).map(str -> str = "你好").forEach(System.out::println);
//线程
new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}).start();
//lambda 实现接口
Ilike ilike = (a) -> {
System.out.println("实现接口" + a);
};
ilike.lambda(99);
//TODO 断言使用
//Assert.assertEquals(a,2);
//TODO mock使用
}
interface Ilike {
void lambda(int a);
}
}
| [
"rateyu@gmail.com"
] | rateyu@gmail.com |
eb073bc7d3ecb39c5955f3088e0d5796ae3c9fe4 | ab8598fcd71b666eaadb010c26be6d91b15392dc | /src/main/java/com/model/Book.java | cacf5e4b42d329f9c9903e1c0de79bb4a6dc22ce | [] | no_license | Vallalanikhil/codealong-bookstore-backend | 2ad9b01b2c91a94cbfd729cb8dbe9888a0a924d2 | 05f172b0aa4f9ffea0268fae123d162e1168bb7a | refs/heads/master | 2022-04-22T09:25:07.812245 | 2020-04-17T18:13:12 | 2020-04-17T18:13:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,034 | java | package com.model;
import javax.persistence.*;
@Entity
@Table(name = "books")
public class Book {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "author")
private String author;
@Column(name = "price")
private String price;
@Column(name = "picByte", length = 1000)
private byte[] picByte;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public byte[] getPicByte() {
return picByte;
}
public void setPicByte(byte[] picByte) {
this.picByte = picByte;
}
}
| [
"12venkat21@gmail.com"
] | 12venkat21@gmail.com |
34c812f121f26469f5a22a7ce97f7c5741e30184 | 94be114d4f9824ff29b0a3be7114f6f4bf66e187 | /axis2-generated/src/mil/dod/metadata/mdr/ns/ddms/_2_0/ResourceType.java | a5450836342b18fa6febba1baf03091068ddfc7f | [] | no_license | CSTARS/uicds | 590b120eb3dcc24a2b73986bd32018e919c4af6a | b4095b7a33cc8af6e8a1b40ab8e83fc280d2d31a | refs/heads/master | 2016-09-11T12:58:01.097476 | 2013-05-09T22:42:38 | 2013-05-09T22:42:38 | 9,942,515 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 28,258 | java | /*
* XML Type: ResourceType
* Namespace: http://metadata.dod.mil/mdr/ns/DDMS/2.0/
* Java type: mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType
*
* Automatically generated - do not modify.
*/
package mil.dod.metadata.mdr.ns.ddms._2_0;
/**
* An XML ResourceType(@http://metadata.dod.mil/mdr/ns/DDMS/2.0/).
*
* This is a complex type.
*/
public interface ResourceType extends org.apache.xmlbeans.XmlObject
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ResourceType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sB10C9499E0DFBB636176E7D7114A9D4F").resolveHandle("resourcetypeaafetype");
/**
* Gets array of all "identifier" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundResourceIdentifierType[] getIdentifierArray();
/**
* Gets ith "identifier" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundResourceIdentifierType getIdentifierArray(int i);
/**
* Returns number of "identifier" element
*/
int sizeOfIdentifierArray();
/**
* Sets array of all "identifier" element
*/
void setIdentifierArray(mil.dod.metadata.mdr.ns.ddms._2_0.CompoundResourceIdentifierType[] identifierArray);
/**
* Sets ith "identifier" element
*/
void setIdentifierArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.CompoundResourceIdentifierType identifier);
/**
* Inserts and returns a new empty value (as xml) as the ith "identifier" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundResourceIdentifierType insertNewIdentifier(int i);
/**
* Appends and returns a new empty value (as xml) as the last "identifier" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundResourceIdentifierType addNewIdentifier();
/**
* Removes the ith "identifier" element
*/
void removeIdentifier(int i);
/**
* Gets array of all "title" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TitleType[] getTitleArray();
/**
* Gets ith "title" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TitleType getTitleArray(int i);
/**
* Returns number of "title" element
*/
int sizeOfTitleArray();
/**
* Sets array of all "title" element
*/
void setTitleArray(mil.dod.metadata.mdr.ns.ddms._2_0.TitleType[] titleArray);
/**
* Sets ith "title" element
*/
void setTitleArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.TitleType title);
/**
* Inserts and returns a new empty value (as xml) as the ith "title" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TitleType insertNewTitle(int i);
/**
* Appends and returns a new empty value (as xml) as the last "title" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TitleType addNewTitle();
/**
* Removes the ith "title" element
*/
void removeTitle(int i);
/**
* Gets array of all "subtitle" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SubtitleType[] getSubtitleArray();
/**
* Gets ith "subtitle" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SubtitleType getSubtitleArray(int i);
/**
* Returns number of "subtitle" element
*/
int sizeOfSubtitleArray();
/**
* Sets array of all "subtitle" element
*/
void setSubtitleArray(mil.dod.metadata.mdr.ns.ddms._2_0.SubtitleType[] subtitleArray);
/**
* Sets ith "subtitle" element
*/
void setSubtitleArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.SubtitleType subtitle);
/**
* Inserts and returns a new empty value (as xml) as the ith "subtitle" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SubtitleType insertNewSubtitle(int i);
/**
* Appends and returns a new empty value (as xml) as the last "subtitle" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SubtitleType addNewSubtitle();
/**
* Removes the ith "subtitle" element
*/
void removeSubtitle(int i);
/**
* Gets the "description" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.DescriptionType getDescription();
/**
* True if has "description" element
*/
boolean isSetDescription();
/**
* Sets the "description" element
*/
void setDescription(mil.dod.metadata.mdr.ns.ddms._2_0.DescriptionType description);
/**
* Appends and returns a new empty "description" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.DescriptionType addNewDescription();
/**
* Unsets the "description" element
*/
void unsetDescription();
/**
* Gets array of all "language" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundLanguageIdentifierType[] getLanguageArray();
/**
* Gets ith "language" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundLanguageIdentifierType getLanguageArray(int i);
/**
* Returns number of "language" element
*/
int sizeOfLanguageArray();
/**
* Sets array of all "language" element
*/
void setLanguageArray(mil.dod.metadata.mdr.ns.ddms._2_0.CompoundLanguageIdentifierType[] languageArray);
/**
* Sets ith "language" element
*/
void setLanguageArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.CompoundLanguageIdentifierType language);
/**
* Inserts and returns a new empty value (as xml) as the ith "language" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundLanguageIdentifierType insertNewLanguage(int i);
/**
* Appends and returns a new empty value (as xml) as the last "language" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundLanguageIdentifierType addNewLanguage();
/**
* Removes the ith "language" element
*/
void removeLanguage(int i);
/**
* Gets the "dates" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.DatesType getDates();
/**
* True if has "dates" element
*/
boolean isSetDates();
/**
* Sets the "dates" element
*/
void setDates(mil.dod.metadata.mdr.ns.ddms._2_0.DatesType dates);
/**
* Appends and returns a new empty "dates" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.DatesType addNewDates();
/**
* Unsets the "dates" element
*/
void unsetDates();
/**
* Gets the "rights" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.RightsType getRights();
/**
* True if has "rights" element
*/
boolean isSetRights();
/**
* Sets the "rights" element
*/
void setRights(mil.dod.metadata.mdr.ns.ddms._2_0.RightsType rights);
/**
* Appends and returns a new empty "rights" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.RightsType addNewRights();
/**
* Unsets the "rights" element
*/
void unsetRights();
/**
* Gets array of all "source" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundSourceIdentifierType[] getSourceArray();
/**
* Gets ith "source" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundSourceIdentifierType getSourceArray(int i);
/**
* Returns number of "source" element
*/
int sizeOfSourceArray();
/**
* Sets array of all "source" element
*/
void setSourceArray(mil.dod.metadata.mdr.ns.ddms._2_0.CompoundSourceIdentifierType[] sourceArray);
/**
* Sets ith "source" element
*/
void setSourceArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.CompoundSourceIdentifierType source);
/**
* Inserts and returns a new empty value (as xml) as the ith "source" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundSourceIdentifierType insertNewSource(int i);
/**
* Appends and returns a new empty value (as xml) as the last "source" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundSourceIdentifierType addNewSource();
/**
* Removes the ith "source" element
*/
void removeSource(int i);
/**
* Gets array of all "type" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundTypeIdentifierType[] getTypeArray();
/**
* Gets ith "type" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundTypeIdentifierType getTypeArray(int i);
/**
* Returns number of "type" element
*/
int sizeOfTypeArray();
/**
* Sets array of all "type" element
*/
void setTypeArray(mil.dod.metadata.mdr.ns.ddms._2_0.CompoundTypeIdentifierType[] typeArray);
/**
* Sets ith "type" element
*/
void setTypeArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.CompoundTypeIdentifierType type);
/**
* Inserts and returns a new empty value (as xml) as the ith "type" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundTypeIdentifierType insertNewType(int i);
/**
* Appends and returns a new empty value (as xml) as the last "type" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CompoundTypeIdentifierType addNewType();
/**
* Removes the ith "type" element
*/
void removeType(int i);
/**
* Gets array of all "creator" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CreatorType[] getCreatorArray();
/**
* Gets ith "creator" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CreatorType getCreatorArray(int i);
/**
* Returns number of "creator" element
*/
int sizeOfCreatorArray();
/**
* Sets array of all "creator" element
*/
void setCreatorArray(mil.dod.metadata.mdr.ns.ddms._2_0.CreatorType[] creatorArray);
/**
* Sets ith "creator" element
*/
void setCreatorArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.CreatorType creator);
/**
* Inserts and returns a new empty value (as xml) as the ith "creator" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CreatorType insertNewCreator(int i);
/**
* Appends and returns a new empty value (as xml) as the last "creator" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.CreatorType addNewCreator();
/**
* Removes the ith "creator" element
*/
void removeCreator(int i);
/**
* Gets array of all "publisher" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PublisherType[] getPublisherArray();
/**
* Gets ith "publisher" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PublisherType getPublisherArray(int i);
/**
* Returns number of "publisher" element
*/
int sizeOfPublisherArray();
/**
* Sets array of all "publisher" element
*/
void setPublisherArray(mil.dod.metadata.mdr.ns.ddms._2_0.PublisherType[] publisherArray);
/**
* Sets ith "publisher" element
*/
void setPublisherArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.PublisherType publisher);
/**
* Inserts and returns a new empty value (as xml) as the ith "publisher" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PublisherType insertNewPublisher(int i);
/**
* Appends and returns a new empty value (as xml) as the last "publisher" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PublisherType addNewPublisher();
/**
* Removes the ith "publisher" element
*/
void removePublisher(int i);
/**
* Gets array of all "contributor" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.ContributorType[] getContributorArray();
/**
* Gets ith "contributor" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.ContributorType getContributorArray(int i);
/**
* Returns number of "contributor" element
*/
int sizeOfContributorArray();
/**
* Sets array of all "contributor" element
*/
void setContributorArray(mil.dod.metadata.mdr.ns.ddms._2_0.ContributorType[] contributorArray);
/**
* Sets ith "contributor" element
*/
void setContributorArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.ContributorType contributor);
/**
* Inserts and returns a new empty value (as xml) as the ith "contributor" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.ContributorType insertNewContributor(int i);
/**
* Appends and returns a new empty value (as xml) as the last "contributor" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.ContributorType addNewContributor();
/**
* Removes the ith "contributor" element
*/
void removeContributor(int i);
/**
* Gets array of all "pointOfContact" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PointOfContactType[] getPointOfContactArray();
/**
* Gets ith "pointOfContact" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PointOfContactType getPointOfContactArray(int i);
/**
* Returns number of "pointOfContact" element
*/
int sizeOfPointOfContactArray();
/**
* Sets array of all "pointOfContact" element
*/
void setPointOfContactArray(mil.dod.metadata.mdr.ns.ddms._2_0.PointOfContactType[] pointOfContactArray);
/**
* Sets ith "pointOfContact" element
*/
void setPointOfContactArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.PointOfContactType pointOfContact);
/**
* Inserts and returns a new empty value (as xml) as the ith "pointOfContact" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PointOfContactType insertNewPointOfContact(int i);
/**
* Appends and returns a new empty value (as xml) as the last "pointOfContact" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.PointOfContactType addNewPointOfContact();
/**
* Removes the ith "pointOfContact" element
*/
void removePointOfContact(int i);
/**
* Gets the "format" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.FormatType getFormat();
/**
* True if has "format" element
*/
boolean isSetFormat();
/**
* Sets the "format" element
*/
void setFormat(mil.dod.metadata.mdr.ns.ddms._2_0.FormatType format);
/**
* Appends and returns a new empty "format" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.FormatType addNewFormat();
/**
* Unsets the "format" element
*/
void unsetFormat();
/**
* Gets the "subjectCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SubjectCoverageType getSubjectCoverage();
/**
* Sets the "subjectCoverage" element
*/
void setSubjectCoverage(mil.dod.metadata.mdr.ns.ddms._2_0.SubjectCoverageType subjectCoverage);
/**
* Appends and returns a new empty "subjectCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SubjectCoverageType addNewSubjectCoverage();
/**
* Gets array of all "virtualCoverage" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.VirtualCoverageType[] getVirtualCoverageArray();
/**
* Gets ith "virtualCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.VirtualCoverageType getVirtualCoverageArray(int i);
/**
* Returns number of "virtualCoverage" element
*/
int sizeOfVirtualCoverageArray();
/**
* Sets array of all "virtualCoverage" element
*/
void setVirtualCoverageArray(mil.dod.metadata.mdr.ns.ddms._2_0.VirtualCoverageType[] virtualCoverageArray);
/**
* Sets ith "virtualCoverage" element
*/
void setVirtualCoverageArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.VirtualCoverageType virtualCoverage);
/**
* Inserts and returns a new empty value (as xml) as the ith "virtualCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.VirtualCoverageType insertNewVirtualCoverage(int i);
/**
* Appends and returns a new empty value (as xml) as the last "virtualCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.VirtualCoverageType addNewVirtualCoverage();
/**
* Removes the ith "virtualCoverage" element
*/
void removeVirtualCoverage(int i);
/**
* Gets array of all "temporalCoverage" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TemporalCoverageType[] getTemporalCoverageArray();
/**
* Gets ith "temporalCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TemporalCoverageType getTemporalCoverageArray(int i);
/**
* Returns number of "temporalCoverage" element
*/
int sizeOfTemporalCoverageArray();
/**
* Sets array of all "temporalCoverage" element
*/
void setTemporalCoverageArray(mil.dod.metadata.mdr.ns.ddms._2_0.TemporalCoverageType[] temporalCoverageArray);
/**
* Sets ith "temporalCoverage" element
*/
void setTemporalCoverageArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.TemporalCoverageType temporalCoverage);
/**
* Inserts and returns a new empty value (as xml) as the ith "temporalCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TemporalCoverageType insertNewTemporalCoverage(int i);
/**
* Appends and returns a new empty value (as xml) as the last "temporalCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.TemporalCoverageType addNewTemporalCoverage();
/**
* Removes the ith "temporalCoverage" element
*/
void removeTemporalCoverage(int i);
/**
* Gets array of all "geospatialCoverage" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.GeospatialCoverageType[] getGeospatialCoverageArray();
/**
* Gets ith "geospatialCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.GeospatialCoverageType getGeospatialCoverageArray(int i);
/**
* Returns number of "geospatialCoverage" element
*/
int sizeOfGeospatialCoverageArray();
/**
* Sets array of all "geospatialCoverage" element
*/
void setGeospatialCoverageArray(mil.dod.metadata.mdr.ns.ddms._2_0.GeospatialCoverageType[] geospatialCoverageArray);
/**
* Sets ith "geospatialCoverage" element
*/
void setGeospatialCoverageArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.GeospatialCoverageType geospatialCoverage);
/**
* Inserts and returns a new empty value (as xml) as the ith "geospatialCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.GeospatialCoverageType insertNewGeospatialCoverage(int i);
/**
* Appends and returns a new empty value (as xml) as the last "geospatialCoverage" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.GeospatialCoverageType addNewGeospatialCoverage();
/**
* Removes the ith "geospatialCoverage" element
*/
void removeGeospatialCoverage(int i);
/**
* Gets array of all "relatedResources" elements
*/
mil.dod.metadata.mdr.ns.ddms._2_0.RelatedResourcesType[] getRelatedResourcesArray();
/**
* Gets ith "relatedResources" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.RelatedResourcesType getRelatedResourcesArray(int i);
/**
* Returns number of "relatedResources" element
*/
int sizeOfRelatedResourcesArray();
/**
* Sets array of all "relatedResources" element
*/
void setRelatedResourcesArray(mil.dod.metadata.mdr.ns.ddms._2_0.RelatedResourcesType[] relatedResourcesArray);
/**
* Sets ith "relatedResources" element
*/
void setRelatedResourcesArray(int i, mil.dod.metadata.mdr.ns.ddms._2_0.RelatedResourcesType relatedResources);
/**
* Inserts and returns a new empty value (as xml) as the ith "relatedResources" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.RelatedResourcesType insertNewRelatedResources(int i);
/**
* Appends and returns a new empty value (as xml) as the last "relatedResources" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.RelatedResourcesType addNewRelatedResources();
/**
* Removes the ith "relatedResources" element
*/
void removeRelatedResources(int i);
/**
* Gets the "security" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SecurityDocument.Security getSecurity();
/**
* Sets the "security" element
*/
void setSecurity(mil.dod.metadata.mdr.ns.ddms._2_0.SecurityDocument.Security security);
/**
* Appends and returns a new empty "security" element
*/
mil.dod.metadata.mdr.ns.ddms._2_0.SecurityDocument.Security addNewSecurity();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType newInstance() {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (mil.dod.metadata.mdr.ns.ddms._2_0.ResourceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
| [
"jrmerz@gmail.com"
] | jrmerz@gmail.com |
7e5e08938026dc8d620855b095f0f3cbc77b62c6 | 1c08b1b5a9d5efb1e82a5d57abaa1b2551c20d01 | /oauth-client-user/src/test/java/com/md/saas/oauthclientuser/OauthClientUserApplicationTests.java | f877bba0d03ef1e2f7187990c4ea499592bb893c | [] | no_license | afterchj/spring-cloud-demo | 15b95f8bf15f2f369bb7949e205889f3c636c08e | a3cb72e3f11d21da6aa7be5b4095de1fbf8d205d | refs/heads/master | 2023-04-14T19:27:18.580602 | 2023-03-30T13:37:30 | 2023-03-30T13:37:30 | 160,455,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 228 | java | package com.md.saas.oauthclientuser;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class OauthClientUserApplicationTests {
@Test
void contextLoads() {
}
}
| [
"766256898@qq.com"
] | 766256898@qq.com |
a78256d16cf6fa4f232c8170d47843427d4cf16b | 169e3dfa068125b78fdfaecd41d02b182098499e | /docker/ops-playground-image/java/explore-flink/src/main/java/org/sense/flink/examples/stream/edgent/MultiSensorMultiStationsJoinMqtt.java | 0396bf25042ae91f8e73cc762a3e4838084a38c9 | [] | no_license | robertsilvatech/explore-flink | f0cbe5828cac32ad1445888c173144105b61cded | 4d023704120ef1e9981667390965b6d790676336 | refs/heads/master | 2023-08-03T23:12:20.760889 | 2021-09-14T15:27:40 | 2021-09-14T15:27:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,806 | java | package org.sense.flink.examples.stream.edgent;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.flink.api.common.functions.JoinFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.sense.flink.mqtt.MqttSensor;
import org.sense.flink.mqtt.MqttSensorConsumer;
public class MultiSensorMultiStationsJoinMqtt {
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public MultiSensorMultiStationsJoinMqtt() throws Exception {
// Start streaming from fake data source sensors
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// obtain execution environment, run this example in "ingestion time"
env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime);
// @formatter:off
DataStream<MqttSensor> streamStation01People = env.addSource(new MqttSensorConsumer("topic-station-01-people"));
DataStream<MqttSensor> streamStation01Trains = env.addSource(new MqttSensorConsumer("topic-station-01-trains"));
DataStream<MqttSensor> streamStation01Tickets = env.addSource(new MqttSensorConsumer("topic-station-01-tickets"));
DataStream<MqttSensor> streamStation02People = env.addSource(new MqttSensorConsumer("topic-station-02-people"));
DataStream<MqttSensor> streamStation02Trains = env.addSource(new MqttSensorConsumer("topic-station-02-trains"));
DataStream<MqttSensor> streamStation02Tickets = env.addSource(new MqttSensorConsumer("topic-station-02-tickets"));
// Join sensor counter from PEOPLE and TICKETS from the same PLATFORM
streamStation01People.join(streamStation01Tickets)
.where(new PlatformTypeKeySelector())
.equalTo(new PlatformTypeKeySelector())
.window(TumblingEventTimeWindows.of(Time.seconds(10)))
.apply(new PeopleAndTicketOnSamePlatformJoinFunction())
.print();
// Join sensor counter from TICKETS and TRAINs from the same PLATFORM in order to discover if we need a bigger train
streamStation01Tickets.join(streamStation01Trains)
.where(new PlatformTypeKeySelector())
.equalTo(new PlatformTypeKeySelector())
.window(TumblingEventTimeWindows.of(Time.seconds(10)))
.apply(new TicketAndTrainOnSamePlatformJoinFunction())
.print();
// @formatter:on
String executionPlan = env.getExecutionPlan();
System.out.println("ExecutionPlan ........................ ");
System.out.println(executionPlan);
System.out.println("........................ ");
env.execute("MultiSensorMultiStationsReadingMqtt2");
}
/**
* Key Selector by platform ID
*/
public static class PlatformTypeKeySelector implements KeySelector<MqttSensor, Integer> {
private static final long serialVersionUID = 3696259925817763986L;
@Override
public Integer getKey(MqttSensor value) throws Exception {
return value.getKey().f2;
}
}
/**
* Join function to People and Ticket sensor readings
*/
public static class PeopleAndTicketOnSamePlatformJoinFunction
implements JoinFunction<MqttSensor, MqttSensor, String> {
private static final long serialVersionUID = -4817380281365483097L;
@Override
public String join(MqttSensor people, MqttSensor tickets) throws Exception {
String ids = people.getKey().f0 + "," + tickets.getKey().f0;
String sensorType = people.getKey().f1 + ", " + tickets.getKey().f1;
String platformId = people.getKey().f2 + ", " + tickets.getKey().f2;
String platformType = people.getKey().f3 + ", " + tickets.getKey().f3;
String stations = people.getKey().f4 + ", " + tickets.getKey().f4;
String timestampTickets = sdf.format(new Date(tickets.getTimestamp()));
String timestampPeople = sdf.format(new Date(people.getTimestamp()));
String result = "ID[" + ids + "] sensorTypes[" + sensorType + "] platformId[" + platformId
+ "] platformType[" + platformType + "] stations[" + stations + "] people[" + people.getValue()
+ "] time[" + timestampPeople + "] tickets[" + tickets.getValue() + "] time[" + timestampTickets
+ "]";
if (people.getValue() > tickets.getValue()) {
// people are not paying tickets
return "People are not paying for tickets. " + result;
} else if (people.getValue() < tickets.getValue()) {
// there are more tickets than people
return "There are more tickets than people. " + result;
} else {
// everything is fine
return "Nice. Nobody is frauding. " + result;
}
}
}
/**
* Join TICKETS and TRAINS from the same platform in order to discover if it is
* necessary to send a bigger train. Let's suppose that each train has the
* capacity of 200 people.
*/
public static class TicketAndTrainOnSamePlatformJoinFunction
implements JoinFunction<MqttSensor, MqttSensor, String> {
private static final long serialVersionUID = -857500653881800605L;
private final Integer trainCapacity = 200;
@Override
public String join(MqttSensor tickets, MqttSensor trains) throws Exception {
String ids = tickets.getKey().f0 + "," + trains.getKey().f0;
String sensorType = tickets.getKey().f1 + ", " + trains.getKey().f1;
String platformId = tickets.getKey().f2 + ", " + trains.getKey().f2;
String platformType = tickets.getKey().f3 + ", " + trains.getKey().f3;
String stations = tickets.getKey().f4 + ", " + trains.getKey().f4;
String timestampTickets = sdf.format(new Date(tickets.getTimestamp()));
String timestampTrains = sdf.format(new Date(trains.getTimestamp()));
String result = "ID[" + ids + "] sensorTypes[" + sensorType + "] tickets[" + tickets.getValue() + "] time["
+ timestampTickets + "] trains[" + trains.getValue() + "] time[" + timestampTrains + "] platformId["
+ platformId + "] platformType[" + platformType + "] stations[" + stations + "]";
Double totalCapacity = trains.getValue() * trainCapacity;
Double almostOverflowing = totalCapacity - ((totalCapacity / 100) * 10);
Double almostEmpty = totalCapacity - ((totalCapacity / 100) * 90);
if (tickets.getValue() > almostOverflowing && tickets.getValue() <= totalCapacity) {
return "The trains are almost overflowing of people (between 90% and 100%). " + result;
}
if (tickets.getValue() > totalCapacity) {
return "The trains are overflowing of people (>100%). " + result;
}
if (tickets.getValue() <= almostEmpty) {
return "The trains are almost empty (<10%). " + result;
}
return "The trains are running on a good capacity (betwen 10% and 90%). " + result;
}
}
}
| [
"felipe.gutierrez@tu-berlin.de"
] | felipe.gutierrez@tu-berlin.de |
0a49e792cbd465f49aa11fdfb60f979018bd3ac5 | a393ccc490caffa543303bc9ce4c54d6574b42d1 | /play-multithreading/src/main/java/com/play/multithreading/AutoIncream.java | 6ac54f9de5f63fde444067a668ded868c4a21a5a | [] | no_license | luoyedaren/KongKong | 56c86cb19a4299e9444adb255aec3fad972d3d6e | d4c1ddf3c60f93a132c88f3a3873a85f61b8f938 | refs/heads/master | 2022-11-22T14:56:15.871047 | 2019-11-05T02:39:39 | 2019-11-05T02:39:39 | 183,532,142 | 0 | 0 | null | 2022-11-16T11:45:49 | 2019-04-26T01:05:25 | Java | UTF-8 | Java | false | false | 777 | java | package com.play.multithreading;
import java.util.concurrent.atomic.AtomicInteger;
/**
* project KongKong
*
* @author chenghai on 2019/4/28 0028. - 星期日
* nickName louyedaren
*/
public class AutoIncream {
private Integer anInt = 0;
public static void main(String[] args) {
new AutoIncream().oneThread();
}
private void oneThread() {
Runnable task1 = () -> {
AtomicInteger atomicInteger = new AtomicInteger();
int i = atomicInteger.incrementAndGet();
System.out.println(Thread.currentThread().getName() + " i is " + i);
synchronized (anInt) {
System.out.println(Thread.currentThread().getName() + " anInt is " + anInt++);
}
};
for (int i = 0; i < 1000; i++) {
new Thread(task1).start();
new Thread(task1).start();
}
}
}
| [
"287623909@qq.com"
] | 287623909@qq.com |
b4130c7faca4bbb403b84d05f684f49ae230c675 | 43df20f6300fb898d800ad3cd2ae47845d8a1d76 | /src/com/ittr/services/FileManager.java | 905a1f6de51167bb8c1c1532ba03de710d9dd001 | [] | no_license | xcdincay/NorthwindWithGson | a8e64b211fab8a49aa94ecd207aa93cf4051f663 | ffe08667ff755ec58d8cf7fdc88dcc29e2f547c8 | refs/heads/master | 2021-05-11T05:44:54.546521 | 2018-02-15T13:57:58 | 2018-02-15T13:57:58 | 117,967,635 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,514 | java | package com.ittr.services;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class FileManager {
File excelFile = new File("C:\\Excel Upload\\PurchaseOrder.xls");
int row;
int col;
public List<Map<String, String>> getExcelSheet() throws BiffException, IOException {
Workbook excelWorkbook = Workbook.getWorkbook(excelFile);
Sheet excelSheet = excelWorkbook.getSheet(0);
row = excelSheet.getRows();
col = excelSheet.getColumns();
List<Map<String, String>> listForExcelData = new ArrayList<Map<String, String>>();
for (int i = 1; i < row; i++) {
Map<String, String> excelData = new HashMap<>();
for (int j = 0; j < col; j++) {
Cell excelCell = excelSheet.getCell(j, i);
if (j == 0) {
excelData.put("ExternalOrderID", excelCell.getContents());
} else if (j == 1) {
excelData.put("ExternalItemID", excelCell.getContents());
} else if (j == 2) {
excelData.put("UnitPrice", excelCell.getContents());
} else if (j == 3) {
excelData.put("Quantity", excelCell.getContents());
} else if (j == 4) {
excelData.put("Discount", excelCell.getContents());
} else {
excelData.put("ProductID", excelCell.getContents());
}
}
listForExcelData.add(excelData);
}
return listForExcelData;
}
}
| [
"TR23207@ISTN23207.SOLCO.GLOBAL.NTTDATA.COM"
] | TR23207@ISTN23207.SOLCO.GLOBAL.NTTDATA.COM |
ed98255d8e5350ffc0b444cbe328cd6f3996cc98 | 8f188a1009fb2f4a68906d205443f79394b68406 | /thread/src/main/java/algorithm/coding/third/Main.java | 7cec5cb69e29ee3616995cb538c8214174638f25 | [] | no_license | porsche911/apollo | 8506d175426efd61db072e5058a781c5b7908c9d | 3dc06e20ac531f3cd271bac2ab4188665a7bbdea | refs/heads/master | 2023-01-10T23:01:53.661020 | 2020-11-15T01:05:55 | 2020-11-15T01:05:55 | 312,845,333 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,630 | java | package algorithm.coding.third;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
S22 bind No3
S22 bind No4
U22 scan No3
U22 scan No4
-1
S22 bind success
S22 bind fail
U22 pay to S22
U22 scan fail
S22 bind No3
S23 bind No4
U22 scan No3
U22 scan No4
S22 unbind No3
U22 scan No3
U22 scan No4
U21 bind No3
-1
S22 bind success
S23 bind success
U22 pay to S22
U22 pay to S23
S22 unbind success
U22 scan fail
U22 pay to S23
unknown command
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if (br == null) return;
List<String> res = new ArrayList<>();//存放结果
HashMap<String, String> bindMap = new HashMap<>(16);//一个商家只能绑定一个二维码 商家与二维码的对应
HashMap<String, String> codebindMap = new HashMap<>(16);//二维码与商家进行对应
while (true){
String s = br.readLine().trim();
if ("-1".equals(s)){
break;
}
String[] split = s.split(" ");
String key = split[0];
String opt = split[1];
String value = split[2];
String result = "";
//S1 bind success
//S1 bind fail
if ("bind".equals(opt)){
if (key.startsWith("U")){
//用户进行绑定操作,输出unknown command
result = "unknown command";
res.add(result);
continue;
}
if (bindMap.containsKey(key)){
//该商户已绑定二维码,不能再重新绑定
result = key + " "+"bind fail";
res.add(result);
continue;
}
/*if (bindMap.containsValue(value)){
//该二维码已被绑定,不能再被其它商家绑定
continue;
}*/
bindMap.put(key,value);
codebindMap.put(value,key);
result = key + " "+ "bind success";
res.add(result);
continue;
}
//S1 unbind success
//S1 unbind fail
if ("unbind".equals(opt)){
if (bindMap.containsKey(key)){
result = key + " unbind success";
res.add(result);
//解绑成功后,将信息移除
bindMap.remove(key);
codebindMap.remove(bindMap.get(key));
continue;
}else {
result = key + " unbind fail";
res.add(result);
continue;
}
}
//U1 pay to S22 #可以扫码付款给对应商家
//U1 scan fail #任意错误导致的不能执行付款
if ("scan".equals(opt)){
if (bindMap.containsValue(value)){
result = key+" pay to "+codebindMap.get(value);
res.add(result);
continue;
}else {
result = key + " scan fail";
res.add(result);
continue;
}
}
}
br.close();
for (String re : res) {
System.out.println(re);
}
}
}
| [
"597217639@qq.com"
] | 597217639@qq.com |
aadf418772d4d74b7c811e8f7c66283fcbfaae7a | ed3cb95dcc590e98d09117ea0b4768df18e8f99e | /project_1_2/src/e/e/g/Calc_1_2_4469.java | 49e3fe07aa2e0af288b00eaeec6247bfc3376069 | [] | no_license | chalstrick/bigRepo1 | ac7fd5785d475b3c38f1328e370ba9a85a751cff | dad1852eef66fcec200df10083959c674fdcc55d | refs/heads/master | 2016-08-11T17:59:16.079541 | 2015-12-18T14:26:49 | 2015-12-18T14:26:49 | 48,244,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 131 | java | package e.e.g;
public class Calc_1_2_4469 {
/** @return the sum of a and b */
public int add(int a, int b) {
return a+b;
}
}
| [
"christian.halstrick@sap.com"
] | christian.halstrick@sap.com |
eb02ca885d48e02dc8aa85732ed8abf9fefdbb5a | 5b8d6dc12696e334f1c563c6aa4669ab7eb82dd8 | /src/main/java/com/example/search/entity/KeywordEntity.java | d49618da9941ac37c4293166a26a0875301c8113 | [] | no_license | dew2jy/SearchApplication | 74778261e8a112e285a34ccd280af2fe711acd3c | aefdb8b733953904e89ba3b495061c4cd5297086 | refs/heads/master | 2020-06-14T13:55:17.040591 | 2019-07-03T12:30:39 | 2019-07-03T12:30:39 | 195,020,528 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 595 | java | package com.example.search.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;
@Entity
@Table(name="keyword",indexes = {@Index(columnList="cnt")})
public class KeywordEntity {
@Id
private String keyword;
@Column(nullable = false)
private int cnt = 1;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
}
| [
"jylee@LeeJi-Yeonui-MacBook-Pro.local"
] | jylee@LeeJi-Yeonui-MacBook-Pro.local |
d030b70f56a449453d7708ce156a42ba873a6d85 | 0e383d8f8e0809c4e3cef9cfdce49ba67e59b5ba | /crackcode/src/main/java/arrays/orderStatistics/LongestConsecutiveSubsequence.java | 334c204c10bf6ab16035c30f065e9022f2e2daf4 | [] | no_license | kishoramudala/practice | d4573bfc7a3b490f10ab68a0764c75681b5e3f0a | 1ee2e7dcd98a34dd5e7e6eca102607e7f49a4518 | refs/heads/master | 2023-02-24T09:52:21.832724 | 2021-01-19T14:00:04 | 2021-01-19T14:00:04 | 330,987,887 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,574 | java | package arrays.orderStatistics;
import java.util.HashSet;
import java.util.Set;
/**
* Given an array of integers, find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.
*
* Examples:
*
* Input: arr[] = {1, 9, 3, 10, 4, 20, 2}
* Output: 4
* Explanation:
* The subsequence 1, 3, 4, 2 is the longest
* subsequence of consecutive elements
*
* Input: arr[] = {36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42}
* Output: 5
* Explanation:
* The subsequence 36, 35, 33, 34, 32 is the longest
* subsequence of consecutive elements.
*/
public class LongestConsecutiveSubsequence {
/**
* Complexity Analysis:
* Time complexity: O(n).
* Only one traversal is needed and the time complexity is O(n) under the assumption that hash insert and search take O(1) time.
* Auxiliary space: O(n).
* To store every element in hashmap O(n) space is needed.
* @param a
* @return
*/
public static int largestConsecutiveSubSequence(int[] a) {
Set<Integer> set = new HashSet<>();
int ans = 0;
for (int i : a) {
set.add(i);
}
for (int i = 0; i < a.length; i++) {
if (!set.contains(a[i] - 1)) {
int j = a[i];
while (set.contains(j)) {
j++;
}
if (ans < j - a[i]) {
ans = j - a[i];
}
}
}
return ans;
}
public static void main(String[] args) {
int[] a = new int[]{1, 9, 3, 10, 4, 20, 2};
System.out.println(largestConsecutiveSubSequence(a));
}
}
| [
"kishor.amudala@oracle.com"
] | kishor.amudala@oracle.com |
320597e7019bb6c0f1309b5791065b93d673e0ab | f3de99b9e19b1cdc40f5f7344b5520904ccbc617 | /src/main/java/core/SavingControl.java | 61165a807efe8ec7d21d5afeda7de9708cb3bef2 | [] | no_license | NicoVisci/BJ-e-squillo-di-lusso | fad36cca5eb5e9e5d6e89bb8f6f0f8e581135e70 | 6bb292f4606de747fa0580cc80284ad4f4852175 | refs/heads/master | 2022-11-11T22:14:28.880880 | 2020-07-11T03:25:18 | 2020-07-11T03:25:18 | 278,721,293 | 0 | 0 | null | 2020-07-11T02:55:30 | 2020-07-10T19:52:34 | Java | ISO-8859-10 | Java | false | false | 3,147 | java | package core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JOptionPane;
/**
* Classe che gestisce il controllo del salvataggio di partita e del caricamento della partita salvata
*
* <p>Classe di tipo Control
*
* <p>Questa classe gestisce il controllo del salvataggio dello stato di partita corrente e del caricamento sull'applicazione di una partita
* precedentemente salvata. La classe non viene istanziata ed i metodi devono essere invocati in maniera statica.
*
* @author Nico Visci
*/
public class SavingControl {
private static File fileSav = null;
private static ObjectOutputStream outStream = null;
private static ObjectInputStream inStream = null;
private static String dir = "Salvataggi The Heist";
private static Player bufferPlayer = null;
private static StatusScenario bufferScenario = null;
private SavingControl() {
//Not called
}
public static void saveErrorPrint() {
JOptionPane.showMessageDialog(null, "Non č stato possibile salvare la partita!");
}
public static void saveSuccessPrint() {
JOptionPane.showMessageDialog(null, "Partita salvata con successo!");
}
public static void loadErrorPrint() {
JOptionPane.showMessageDialog(null, "Non č stato possibile caricare la partita salvata!");
}
protected static void setSaveDir(String path) {
dir = path;
}
/*
* Metodo scritto in maniera generica, cosė da poter essere usato per ogni tipo di scenario compatibile
*/
public static synchronized void salvaPartita (String nomeFile, Player player) {
File f = new File("\\"+dir);
f.mkdirs();
fileSav = new File(f, nomeFile);
//if(fileSav.exists() && fileSav.delete()) {
try {
//fileSav = new File(f, nomeFile);
outStream = new ObjectOutputStream(new FileOutputStream(fileSav));
StatusScenario status = new StatusScenario();
outStream.writeObject(player);
outStream.writeObject(status);
outStream.close();
saveSuccessPrint();
}
catch (IOException e) {
SavingControl.saveErrorPrint();
e.printStackTrace();
}
}
/*else {
SavingControl.saveErrorPrint();
}
}*/
public static void caricaPartita(String nomeFile) {
File f = new File("\\"+dir);
f.mkdirs();
fileSav = new File(f, nomeFile);
try {
if(fileSav.exists()) {
inStream = new ObjectInputStream(new FileInputStream(fileSav));
bufferPlayer = (Player) inStream.readObject();
bufferScenario = (StatusScenario) inStream.readObject();
inStream.close();
AppMain.newGame();
AppMain.getGame().setPlayer(bufferPlayer);
//AppMain.getGame().newScenario();
bufferScenario.setStatus();
System.out.println("\nPartita caricata con successo!");
System.out.println("\nTi trovi in " + AppMain.currentAmbiente());
}
else {
loadErrorPrint();
}
}
catch (ClassNotFoundException | IOException es) {
SavingControl.loadErrorPrint();
es.printStackTrace();
}
}
}
| [
"nicovisci99uni@libero.it"
] | nicovisci99uni@libero.it |
d7b83d86ac2a71071507ed46ef0351fa31a4d03a | 0917a6cefcc3c3d6766080e58e83cd027522d0a8 | /src/main/java/leetcode/MoveZeroes.java | ea0d55798880164bb10ddbaa446a66a8edaa4e35 | [] | no_license | lyk4411/untitled1_intellij | 19bb583c8e631c4fab5826573fe30a61dff9d2d4 | 7a3e9ff784faa03c04a40cfdc0ba53af3344bb09 | refs/heads/master | 2022-12-22T13:58:32.218291 | 2020-01-22T08:58:04 | 2020-01-22T08:58:04 | 62,300,156 | 0 | 0 | null | 2022-12-16T03:16:30 | 2016-06-30T09:56:05 | Java | UTF-8 | Java | false | false | 826 | java | package leetcode;
import java.util.stream.Stream;
/**
* Created by lyk on 2017/2/23.
* Package name: leetcode
* Porject name: untitled1
*/
public class MoveZeroes {
public static void main(String[] args){
MoveZeroes mz = new MoveZeroes();
int[] a = new int[]{1,0,3,0,9,8,0,0,0,6,5,4};
mz.moveZeroes(a);
Integer[] ll = new Integer[a.length];
for(int i=0;i<a.length;i++){
ll[i] = a[i];
}
Stream.of(ll).forEach(System.out::println);
}
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int insertPos = 0;
for (int num: nums) {
if (num != 0) nums[insertPos++] = num;
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}}
| [
"moneyflying_2006@hotmail.com"
] | moneyflying_2006@hotmail.com |
dd46a018de5b284cad1dda5f8f07f3609a7f4406 | ca030864a3a1c24be6b9d1802c2353da4ca0d441 | /classes7.dex_source_from_JADX/com/facebook/api/graphql/leadgen/LeadGenDeepLinkUserInfoCreateMutationModels.java | 378f2185865356562d722fa7efcd7f5240a4b5a8 | [] | no_license | pxson001/facebook-app | 87aa51e29195eeaae69adeb30219547f83a5b7b1 | 640630f078980f9818049625ebc42569c67c69f7 | refs/heads/master | 2020-04-07T20:36:45.758523 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,709 | java | package com.facebook.api.graphql.leadgen;
import com.facebook.api.graphql.leadgen.LeadGenDeepLinkUserInfoCreateMutationParsers.LeadGenDeepLinkUserInfoCoreMutationFieldsParser;
import com.facebook.api.graphql.leadgen.LeadGenDeepLinkUserInfoCreateMutationParsers.LeadGenDeepLinkUserInfoCoreMutationFieldsParser.LeadGenDeepLinkUserStatusParser;
import com.facebook.common.json.FbJsonDeserializer;
import com.facebook.common.json.FbSerializerProvider;
import com.facebook.common.json.GlobalAutoGenDeserializerCache;
import com.facebook.common.json.Postprocessable;
import com.facebook.flatbuffers.FlatBuffer;
import com.facebook.flatbuffers.FlatBufferBuilder;
import com.facebook.flatbuffers.FragmentModelWithoutBridge;
import com.facebook.flatbuffers.ModelWithFlatBufferFormatHash;
import com.facebook.flatbuffers.MutableFlatBuffer;
import com.facebook.graphql.modelutil.BaseModel;
import com.facebook.graphql.modelutil.ModelHelper;
import com.facebook.graphql.visitor.ConsistencyTuple;
import com.facebook.graphql.visitor.GraphQLModelMutatingVisitor;
import com.facebook.graphql.visitor.GraphQLPersistableNode;
import com.facebook.graphql.visitor.GraphQLVisitableConsistentModel;
import com.facebook.graphql.visitor.GraphQLVisitableModel;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.nio.ByteBuffer;
import javax.annotation.Nullable;
/* compiled from: video_editing_zoom_interactions */
public class LeadGenDeepLinkUserInfoCreateMutationModels {
@JsonDeserialize(using = Deserializer.class)
@ModelWithFlatBufferFormatHash(a = -1523163635)
@JsonSerialize(using = Serializer.class)
@FragmentModelWithoutBridge
/* compiled from: video_editing_zoom_interactions */
public final class LeadGenDeepLinkUserInfoCoreMutationFieldsModel extends BaseModel implements GraphQLVisitableModel {
@Nullable
private LeadGenDeepLinkUserStatusModel f573d;
/* compiled from: video_editing_zoom_interactions */
public final class Builder {
@Nullable
public LeadGenDeepLinkUserStatusModel f564a;
}
/* compiled from: video_editing_zoom_interactions */
public class Deserializer extends FbJsonDeserializer {
static {
GlobalAutoGenDeserializerCache.a(LeadGenDeepLinkUserInfoCoreMutationFieldsModel.class, new Deserializer());
}
public Object m593a(JsonParser jsonParser, DeserializationContext deserializationContext) {
MutableFlatBuffer a = LeadGenDeepLinkUserInfoCoreMutationFieldsParser.m613a(jsonParser);
Object leadGenDeepLinkUserInfoCoreMutationFieldsModel = new LeadGenDeepLinkUserInfoCoreMutationFieldsModel();
((BaseModel) leadGenDeepLinkUserInfoCoreMutationFieldsModel).a(a, FlatBuffer.a(a.a), jsonParser);
if (leadGenDeepLinkUserInfoCoreMutationFieldsModel instanceof Postprocessable) {
return ((Postprocessable) leadGenDeepLinkUserInfoCoreMutationFieldsModel).a();
}
return leadGenDeepLinkUserInfoCoreMutationFieldsModel;
}
}
@JsonDeserialize(using = Deserializer.class)
@ModelWithFlatBufferFormatHash(a = 1063199559)
@JsonSerialize(using = Serializer.class)
@FragmentModelWithoutBridge
/* compiled from: video_editing_zoom_interactions */
public final class LeadGenDeepLinkUserStatusModel extends BaseModel implements GraphQLPersistableNode, GraphQLVisitableConsistentModel {
private boolean f569d;
@Nullable
private String f570e;
@Nullable
private String f571f;
@Nullable
private String f572g;
/* compiled from: video_editing_zoom_interactions */
public final class Builder {
public boolean f565a;
@Nullable
public String f566b;
@Nullable
public String f567c;
@Nullable
public String f568d;
}
/* compiled from: video_editing_zoom_interactions */
public class Deserializer extends FbJsonDeserializer {
static {
GlobalAutoGenDeserializerCache.a(LeadGenDeepLinkUserStatusModel.class, new Deserializer());
}
public Object m594a(JsonParser jsonParser, DeserializationContext deserializationContext) {
FlatBufferBuilder flatBufferBuilder = new FlatBufferBuilder(128);
flatBufferBuilder.d(LeadGenDeepLinkUserStatusParser.m611a(jsonParser, flatBufferBuilder));
ByteBuffer wrap = ByteBuffer.wrap(flatBufferBuilder.e());
wrap.position(0);
MutableFlatBuffer mutableFlatBuffer = new MutableFlatBuffer(wrap, null, null, true, null);
mutableFlatBuffer.a(4, Boolean.valueOf(true));
MutableFlatBuffer mutableFlatBuffer2 = mutableFlatBuffer;
Object leadGenDeepLinkUserStatusModel = new LeadGenDeepLinkUserStatusModel();
((BaseModel) leadGenDeepLinkUserStatusModel).a(mutableFlatBuffer2, FlatBuffer.a(mutableFlatBuffer2.a), jsonParser);
if (leadGenDeepLinkUserStatusModel instanceof Postprocessable) {
return ((Postprocessable) leadGenDeepLinkUserStatusModel).a();
}
return leadGenDeepLinkUserStatusModel;
}
}
/* compiled from: video_editing_zoom_interactions */
public class Serializer extends JsonSerializer<LeadGenDeepLinkUserStatusModel> {
public final void m595a(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
LeadGenDeepLinkUserStatusModel leadGenDeepLinkUserStatusModel = (LeadGenDeepLinkUserStatusModel) obj;
if (leadGenDeepLinkUserStatusModel.w_() == null) {
FlatBufferBuilder flatBufferBuilder = new FlatBufferBuilder(128);
flatBufferBuilder.d(leadGenDeepLinkUserStatusModel.m598a(flatBufferBuilder));
ByteBuffer wrap = ByteBuffer.wrap(flatBufferBuilder.e());
wrap.position(0);
MutableFlatBuffer mutableFlatBuffer = new MutableFlatBuffer(wrap, null, null, true, null);
leadGenDeepLinkUserStatusModel.a(mutableFlatBuffer, FlatBuffer.a(mutableFlatBuffer.a));
}
LeadGenDeepLinkUserStatusParser.m612a(leadGenDeepLinkUserStatusModel.w_(), leadGenDeepLinkUserStatusModel.u_(), jsonGenerator);
}
static {
FbSerializerProvider.a(LeadGenDeepLinkUserStatusModel.class, new Serializer());
}
}
public LeadGenDeepLinkUserStatusModel() {
super(4);
}
public LeadGenDeepLinkUserStatusModel(MutableFlatBuffer mutableFlatBuffer) {
super(4);
a(mutableFlatBuffer, FlatBuffer.a(mutableFlatBuffer.a));
}
public final void m602a(String str, ConsistencyTuple consistencyTuple) {
if ("has_shared_info".equals(str)) {
consistencyTuple.a = Boolean.valueOf(m604b());
consistencyTuple.b = u_();
consistencyTuple.c = 0;
return;
}
consistencyTuple.a();
}
public final void m603a(String str, Object obj, boolean z) {
if ("has_shared_info".equals(str)) {
m596a(((Boolean) obj).booleanValue());
}
}
public final boolean m604b() {
a(0, 0);
return this.f569d;
}
private void m596a(boolean z) {
this.f569d = z;
if (this.b != null && this.b.d) {
this.b.a(this.c, 0, z);
}
}
@Nullable
private String m597j() {
this.f570e = super.a(this.f570e, 1);
return this.f570e;
}
@Nullable
public final String m605c() {
this.f571f = super.a(this.f571f, 2);
return this.f571f;
}
@Nullable
public final String m606d() {
this.f572g = super.a(this.f572g, 3);
return this.f572g;
}
@Nullable
public final String m600a() {
return m597j();
}
public final int jK_() {
return 771298455;
}
public final GraphQLVisitableModel m599a(GraphQLModelMutatingVisitor graphQLModelMutatingVisitor) {
h();
i();
return this;
}
public final int m598a(FlatBufferBuilder flatBufferBuilder) {
h();
int b = flatBufferBuilder.b(m597j());
int b2 = flatBufferBuilder.b(m605c());
int b3 = flatBufferBuilder.b(m606d());
flatBufferBuilder.c(4);
flatBufferBuilder.a(0, this.f569d);
flatBufferBuilder.b(1, b);
flatBufferBuilder.b(2, b2);
flatBufferBuilder.b(3, b3);
i();
return flatBufferBuilder.d();
}
public final void m601a(MutableFlatBuffer mutableFlatBuffer, int i, Object obj) {
super.a(mutableFlatBuffer, i, obj);
this.f569d = mutableFlatBuffer.a(i, 0);
}
}
/* compiled from: video_editing_zoom_interactions */
public class Serializer extends JsonSerializer<LeadGenDeepLinkUserInfoCoreMutationFieldsModel> {
public final void m607a(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
MutableFlatBuffer mutableFlatBuffer;
LeadGenDeepLinkUserInfoCoreMutationFieldsModel leadGenDeepLinkUserInfoCoreMutationFieldsModel = (LeadGenDeepLinkUserInfoCoreMutationFieldsModel) obj;
if (leadGenDeepLinkUserInfoCoreMutationFieldsModel.w_() == null) {
FlatBufferBuilder flatBufferBuilder = new FlatBufferBuilder(128);
flatBufferBuilder.d(leadGenDeepLinkUserInfoCoreMutationFieldsModel.m608a(flatBufferBuilder));
ByteBuffer wrap = ByteBuffer.wrap(flatBufferBuilder.e());
wrap.position(0);
mutableFlatBuffer = new MutableFlatBuffer(wrap, null, null, true, null);
leadGenDeepLinkUserInfoCoreMutationFieldsModel.a(mutableFlatBuffer, FlatBuffer.a(mutableFlatBuffer.a));
}
mutableFlatBuffer = leadGenDeepLinkUserInfoCoreMutationFieldsModel.w_();
int u_ = leadGenDeepLinkUserInfoCoreMutationFieldsModel.u_();
jsonGenerator.f();
int g = mutableFlatBuffer.g(u_, 0);
if (g != 0) {
jsonGenerator.a("lead_gen_deep_link_user_status");
LeadGenDeepLinkUserStatusParser.m612a(mutableFlatBuffer, g, jsonGenerator);
}
jsonGenerator.g();
}
static {
FbSerializerProvider.a(LeadGenDeepLinkUserInfoCoreMutationFieldsModel.class, new Serializer());
}
}
public LeadGenDeepLinkUserInfoCoreMutationFieldsModel() {
super(1);
}
public LeadGenDeepLinkUserInfoCoreMutationFieldsModel(MutableFlatBuffer mutableFlatBuffer) {
super(1);
a(mutableFlatBuffer, FlatBuffer.a(mutableFlatBuffer.a));
}
@Nullable
public final LeadGenDeepLinkUserStatusModel m609a() {
this.f573d = (LeadGenDeepLinkUserStatusModel) super.a(this.f573d, 0, LeadGenDeepLinkUserStatusModel.class);
return this.f573d;
}
public final int jK_() {
return -1047825250;
}
public final GraphQLVisitableModel m610a(GraphQLModelMutatingVisitor graphQLModelMutatingVisitor) {
GraphQLVisitableModel graphQLVisitableModel = null;
h();
if (m609a() != null) {
LeadGenDeepLinkUserStatusModel leadGenDeepLinkUserStatusModel = (LeadGenDeepLinkUserStatusModel) graphQLModelMutatingVisitor.b(m609a());
if (m609a() != leadGenDeepLinkUserStatusModel) {
graphQLVisitableModel = (LeadGenDeepLinkUserInfoCoreMutationFieldsModel) ModelHelper.a(null, this);
graphQLVisitableModel.f573d = leadGenDeepLinkUserStatusModel;
}
}
i();
return graphQLVisitableModel == null ? this : graphQLVisitableModel;
}
public final int m608a(FlatBufferBuilder flatBufferBuilder) {
h();
int a = ModelHelper.a(flatBufferBuilder, m609a());
flatBufferBuilder.c(1);
flatBufferBuilder.b(0, a);
i();
return flatBufferBuilder.d();
}
}
}
| [
"son.pham@jmango360.com"
] | son.pham@jmango360.com |
18b1f8bc7bfeae973831015cb2fdaf9db694c381 | 6ed84379c5556194b3ab619233474299226fdddb | /shuffle-my-music-app/app/src/main/java/com/frozen_foo/shuffle_my_music_app/ui/AbstractListController.java | fa18006be257ffddb98e043142943890181a3ec4 | [] | no_license | FrankStephan/backup | c9c4249ff827143473bfa02be3b2870dfcca71a4 | 663968ef660f4a74b689157e5080683eef8c93c7 | refs/heads/master | 2020-04-16T02:11:52.416762 | 2019-07-11T20:52:01 | 2019-07-11T20:52:01 | 62,912,247 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,299 | java | package com.frozen_foo.shuffle_my_music_app.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.widget.ListAdapter;
import com.frozen_foo.shuffle_my_music_2.IndexEntry;
import com.frozen_foo.shuffle_my_music_app.Logger;
import com.frozen_foo.shuffle_my_music_app.R;
import com.frozen_foo.shuffle_my_music_app.settings.SettingsAccessException;
import com.frozen_foo.shuffle_my_music_app.shuffle.ShuffleAccess;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* Created by Frank on 31.10.2017.
*/
public abstract class AbstractListController {
protected RowModel[] rowsFrom(final ListAdapter adapter) {
RowModel[] rows = new RowModel[adapter.getCount()];
for (int i = 0; i < rows.length; i++) {
rows[i] = (RowModel) adapter.getItem(i);
}
return rows;
}
protected void alertException(Activity activity, Exception e) {
Logger.logException(activity, e);
AlertDialog.Builder builder = new AlertDialog.Builder(activity).setTitle(e.getClass().getSimpleName())
.setMessage(e.getMessage());
AlertDialog dialog = builder.create();
dialog.show();
}
protected List<IndexEntry> localIndex(Activity activity) {
return new ShuffleAccess().getLocalIndex(activity);
}
}
| [
"fr.stephan@hotmail.de"
] | fr.stephan@hotmail.de |
feae9caf2a9b8bd236da76f6643edabd4ce5a8f3 | e8460dcc86caa482f373b3f43c5334025d457975 | /app/src/main/java/com/example/matthausen/stickynotes/DBHelper.java | cb9f0c85bafe7406bcb80c158cfecd4d5e77d816 | [] | no_license | matthausen/Android-StickyNotes | 472eb48bb88aed6f9ecf1401d33c9b60d9448703 | 7e27561db33a72c36c3ca4c05afa2ad6a7c80d53 | refs/heads/master | 2020-03-19T03:25:56.946339 | 2018-08-26T12:01:44 | 2018-08-26T12:01:44 | 135,727,277 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,136 | java | package com.example.matthausen.stickynotes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "SQLiteExample.db";
private static final int DATABASE_VERSION = 1;
public static final String INPUT_TABLE_NAME = "input";
public static final String INPUT_COLUMN_ID = "_id";
public static final String INPUT_COLUMN_Text = "text";
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + INPUT_TABLE_NAME + "(" +
INPUT_COLUMN_ID + " INTEGER PRIMARY KEY, " +
INPUT_COLUMN_Text + " TEXT )"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + INPUT_TABLE_NAME);
onCreate(db);
}
public boolean insertPerson(String title,String text) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INPUT_COLUMN_Text, text);
db.insert(INPUT_TABLE_NAME, null, contentValues);
return true;
}
public Cursor getAllPersons() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + INPUT_TABLE_NAME, null );
return res;
}
public Cursor getPerson(String id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + INPUT_TABLE_NAME + " WHERE " +
INPUT_COLUMN_ID + "=?", new String[] { id } );
return res;
}
public void deleteSingleContact(String id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(INPUT_TABLE_NAME, INPUT_COLUMN_ID + "=?", new String[]{id});
//KEY_NAME is a column name
}
}
| [
"32019118+matthausen@users.noreply.github.com"
] | 32019118+matthausen@users.noreply.github.com |
d792af78f6526d8171d4049f78d886a1c0b1dd75 | 547c393b59ec2e1a4879c204cfb86ce47b60ec64 | /enterprise-spring-4.2.a.RELEASE/rewards/src/main/java/rewards/internal/account/JdbcAccountRepository.java | b129d0e958e09795763fd692134ff14d72a84238 | [] | no_license | vinodhkumarg/enterprise-spring | aa54868684fbb0ceff41b6fce6e07d324bedf901 | b1f6463416975db10b414c10166302fab952e16a | refs/heads/master | 2020-04-07T15:45:31.278330 | 2016-11-22T22:33:01 | 2016-11-22T22:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,115 | java | package rewards.internal.account;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import common.money.MonetaryAmount;
import common.money.Percentage;
/**
* Loads accounts from a data source using the JDBC API.
*/
public class JdbcAccountRepository implements AccountRepository {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
/**
* Extracts an Account object from rows returned from a join of T_ACCOUNT and T_ACCOUNT_BENEFICIARY.
*/
private ResultSetExtractor<Account> accountExtractor = new AccountExtractor();
@Override
public Account findByCreditCard(String creditCardNumber) {
String sql = "select a.ID as ID, a.NUMBER as ACCOUNT_NUMBER, a.NAME as ACCOUNT_NAME, a.EMAIL as EMAIL, c.NUMBER as CREDIT_CARD_NUMBER, b.NAME as BENEFICIARY_NAME, b.ALLOCATION_PERCENTAGE as BENEFICIARY_ALLOCATION_PERCENTAGE, b.SAVINGS as BENEFICIARY_SAVINGS " +
"from T_ACCOUNT a, T_ACCOUNT_BENEFICIARY b, T_ACCOUNT_CREDIT_CARD c where a.ID = b.ACCOUNT_ID and a.ID = c.ACCOUNT_ID and c.NUMBER = ?";
return jdbcTemplate.query(sql, accountExtractor, creditCardNumber);
}
@Override
public Account findByAccountNumber(String accountNumber) {
String sql = "select a.ID as ID, a.NUMBER as ACCOUNT_NUMBER, a.NAME as ACCOUNT_NAME, a.EMAIL as EMAIL, c.NUMBER as CREDIT_CARD_NUMBER, b.NAME as BENEFICIARY_NAME, b.ALLOCATION_PERCENTAGE as BENEFICIARY_ALLOCATION_PERCENTAGE, b.SAVINGS as BENEFICIARY_SAVINGS " +
"from T_ACCOUNT a, T_ACCOUNT_BENEFICIARY b, T_ACCOUNT_CREDIT_CARD c where a.ID = b.ACCOUNT_ID and a.ID = c.ACCOUNT_ID and a.NUMBER = ?";
return jdbcTemplate.query(sql, accountExtractor, accountNumber);
}
@Override
public void updateBeneficiaries(Account account) {
String sql = "update T_ACCOUNT_BENEFICIARY SET SAVINGS = ? where ACCOUNT_ID = ? and NAME = ?";
for (Beneficiary b : account.getBeneficiaries()) {
jdbcTemplate.update(sql, b.getSavings().asBigDecimal(), account.getEntityId(), b.getName());
}
}
private static class AccountExtractor implements ResultSetExtractor<Account> {
/**
* Map the rows returned from the join of T_ACCOUNT and T_ACCOUNT_BENEFICIARY to an fully-reconstituted Account
* aggregate.
*
* @param rs the set of rows returned from the query
* @return the mapped Account aggregate
* @throws SQLException an exception occurred extracting data from the result set
*/
public Account extractData(ResultSet rs) throws SQLException, DataAccessException {
if (!rs.next()) {
throw new EmptyResultDataAccessException(1);
}
Account account = null;
// build out the account object graph from the returned rows
do {
if (account == null) {
String number = rs.getString("ACCOUNT_NUMBER");
String name = rs.getString("ACCOUNT_NAME");
String email = rs.getString("EMAIL");
account = new Account(number, name);
account.setEmail(email);
// set internal entity identifier (primary key)
account.setEntityId(rs.getLong("ID"));
}
account.restoreBeneficiary(mapBeneficiary(rs));
} while (rs.next());
return account;
}
/**
* Maps the beneficiary columns in a single row to an AllocatedBeneficiary object.
*
* @param rs the result set with its cursor positioned at the current row
* @return an allocated beneficiary
* @throws SQLException an exception occurred extracting data from the result set
*/
private Beneficiary mapBeneficiary(ResultSet rs) throws SQLException {
String name = rs.getString("BENEFICIARY_NAME");
MonetaryAmount savings = MonetaryAmount.valueOf(rs.getString("BENEFICIARY_SAVINGS"));
Percentage allocationPercentage = Percentage.valueOf(rs.getString("BENEFICIARY_ALLOCATION_PERCENTAGE"));
return new Beneficiary(name, allocationPercentage, savings);
}
}
} | [
"sullivang@CAR03-03992.corp.monitise.net"
] | sullivang@CAR03-03992.corp.monitise.net |
cb4b13eeb8241b0b84e372cb63648da20c982cc7 | f05dfcc33bc96a12aeb160420a3653318644fe39 | /src/main/java/sec/project/service/MainService.java | 8d01364b991f8535c75eeb6f1f5ca616ec7704c3 | [] | no_license | Jhoneagle/cybersecuritybase-project | 2a428d2ae59946da08617fbdd14e99a711419385 | 579241349cfbdf8a982268879cc9b04023d4c3be | refs/heads/master | 2020-09-29T00:47:57.289999 | 2019-12-28T09:26:02 | 2019-12-28T09:26:02 | 226,905,368 | 0 | 0 | null | 2019-12-09T15:33:59 | 2019-12-09T15:33:58 | null | UTF-8 | Java | false | false | 8,163 | java | package sec.project.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sec.project.domain.entities.Account;
import sec.project.domain.entities.Likes;
import sec.project.domain.entities.Post;
import sec.project.domain.models.*;
import sec.project.repository.AccountRepository;
import sec.project.repository.LikesRepository;
import sec.project.repository.PostRepository;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class MainService {
@Autowired
private AccountRepository accountRepository;
@Autowired
private PostRepository postRepository;
@Autowired
private LikesRepository likesRepository;
public List<UserModel> findPeopleWithParam(String search) {
// Parse the parameter in the actual parameter and get the result as raw data from database.
String[] parts = search.split(" ");
List<Account> users;
if (parts.length > 1) {
StringBuilder firstName = new StringBuilder(parts[0]);
String lastName = parts[parts.length - 1];
for (int i = 1; i < parts.length - 1; i++) {
firstName.append(" ").append(parts[i]);
}
users = this.accountRepository.findAllByFirstNameContainingIgnoreCaseOrLastNameContainingIgnoreCase(firstName.toString(), lastName);
} else {
String name = parts[0];
users = this.accountRepository.findAllByFirstNameContainingIgnoreCaseOrLastNameContainingIgnoreCase(name, name);
}
return users.stream().map(user -> new UserModel(user.toString(), user.getId())).collect(Collectors.toList());
}
public List<BlogPost> findPostsWithParam(String searchField) {
Pageable pageable = PageRequest.of(0, 50, Sort.by("timestamp").descending());
List<Post> posts = this.postRepository.findAllByLabelContainingIgnoreCase(searchField, pageable);
return getBlogPosts(posts);
}
public List<BlogPost> getUsersRecentPosts(Account user) {
Pageable pageable = PageRequest.of(0, 25, Sort.by("timestamp").descending());
List<Post> posts = this.postRepository.findAllByCreator(user, pageable);
return getBlogPosts(posts);
}
private List<BlogPost> getBlogPosts(List<Post> posts) {
List<BlogPost> models = new ArrayList<>();
posts.forEach(post -> {
BlogPost t = new BlogPost();
t.setAuthor(post.getCreator().toString());
t.setId(post.getId());
t.setLabel(post.getLabel());
t.setTimestamp(post.getTimestamp());
t.setLikes(post.getLikes().size());
models.add(t);
});
return models;
}
private Account getUser(Long id) {
return this.accountRepository.getOne(id);
}
public BlogInfo getBlogDetails(Long id) {
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
Account user = getUser(id);
List<BlogPost> posts = getUsersRecentPosts(user);
String name = user.toString();
Set<Account> followers = user.getFollowers();
int amountFollows = followers.size();
boolean canFollow;
if (byUsername.getUsername().equals(user.getUsername())) {
canFollow = false;
} else {
canFollow = followers.stream().noneMatch(t -> byUsername.getUsername().equals(t.getUsername()));
}
return new BlogInfo(name, amountFollows, canFollow, posts);
}
public BlogPostModel getFullPost(Long postId) {
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
Post post = this.postRepository.getOne(postId);
BlogPostModel result = new BlogPostModel();
result.setAuthor(post.getCreator().toString());
result.setId(post.getId());
result.setLabel(post.getLabel());
result.setTimestamp(post.getTimestamp());
result.setContent(post.getContent());
List<Likes> likes = post.getLikes();
result.setLikes(likes.size());
likes.stream().filter(like -> like.getUser().getUsername().equals(byUsername.getUsername())).map(like -> true).forEach(result::setLikedAlready);
result.setOwnsPost(post.getCreator().getUsername().equals(byUsername.getUsername()));
return result;
}
public void removePost(Long postId) {
Post post = this.postRepository.getOne(postId);
this.likesRepository.deleteAllByLikedPost(post);
this.postRepository.delete(post);
}
public void removeAll(String username) {
Account user = this.accountRepository.findByUsername(username);
this.likesRepository.deleteAllByLikedPostIn(this.postRepository.findAllByCreator(user));
this.likesRepository.deleteAllByUser(user);
this.postRepository.deleteAllByCreator(user);
}
public void likePost(Long postId) {
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
Post post = this.postRepository.getOne(postId);
Likes like = new Likes(byUsername, post);
this.likesRepository.save(like);
}
public void unlikePost(Long postId) {
Post post = this.postRepository.getOne(postId);
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
Likes like = this.likesRepository.findByUserAndLikedPost(byUsername, post);
this.likesRepository.delete(like);
}
public void createPost(PostValidator postValidator) {
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
Post post = new Post();
post.setContent(postValidator.getContent());
post.setCreator(byUsername);
post.setLabel(postValidator.getLabel());
post.setTimestamp(LocalDateTime.now());
this.postRepository.save(post);
}
public List<BlogPost> getAllPosts() {
Pageable pageable = PageRequest.of(0, 50, Sort.by("timestamp").descending());
Page<Post> posts = this.postRepository.findAll(pageable);
return getBlogPosts(posts.getContent());
}
public Long getCreatorId(Long postId) {
return this.postRepository.getOne(postId).getCreator().getId();
}
public boolean isOwnerOfBlog(Long id) {
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
return id.equals(byUsername.getId());
}
@Transactional
public void followPerson(Long id) {
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
Account one = getUser(id);
one.getFollowers().add(byUsername);
}
@Transactional
public void unFollowPerson(Long id) {
String loggedInPerson = SecurityContextHolder.getContext().getAuthentication().getName();
Account byUsername = this.accountRepository.findByUsername(loggedInPerson);
Account one = getUser(id);
one.getFollowers().remove(byUsername);
}
}
| [
"eaglekjohn@gmail.com"
] | eaglekjohn@gmail.com |
34d31902790ff406763b5fe4b7d0631693bc177b | e977c424543422f49a25695665eb85bfc0700784 | /benchmark/icse15/150132/buggy-version/lucene/java/trunk/src/java/org/apache/lucene/store/RAMDirectory.java | 783b5b7ba889ea2bd011e12d1db270e2964e7372 | [] | no_license | amir9979/pattern-detector-experiment | 17fcb8934cef379fb96002450d11fac62e002dd3 | db67691e536e1550245e76d7d1c8dced181df496 | refs/heads/master | 2022-02-18T10:24:32.235975 | 2019-09-13T15:42:55 | 2019-09-13T15:42:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,343 | java | package org.apache.lucene.store;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Lucene" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* "Apache Lucene", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.IOException;
import java.io.File;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.InputStream;
import org.apache.lucene.store.OutputStream;
/**
* A memory-resident {@link Directory} implementation.
*
* @version $Id$
*/
public final class RAMDirectory extends Directory {
Hashtable files = new Hashtable();
/** Constructs an empty {@link Directory}. */
public RAMDirectory() {
}
/**
* Creates a new <code>RAMDirectory</code> instance from a different
* <code>Directory</code> implementation. This can be used to load
* a disk-based index into memory.
* <P>
* This should be used only with indices that can fit into memory.
*
* @param dir a <code>Directory</code> value
* @exception IOException if an error occurs
*/
public RAMDirectory(Directory dir) throws IOException {
final String[] ar = dir.list();
for (int i = 0; i < ar.length; i++) {
// make place on ram disk
OutputStream os = createFile(ar[i]);
// read current file
InputStream is = dir.openFile(ar[i]);
// and copy to ram disk
int len = (int) is.length();
byte[] buf = new byte[len];
is.readBytes(buf, 0, len);
os.writeBytes(buf, len);
// graceful cleanup
is.close();
os.close();
}
}
/**
* Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}.
*
* @param dir a <code>File</code> specifying the index directory
*/
public RAMDirectory(File dir) throws IOException {
this(FSDirectory.getDirectory(dir, false));
}
/**
* Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}.
*
* @param dir a <code>String</code> specifying the full index directory path
*/
public RAMDirectory(String dir) throws IOException {
this(FSDirectory.getDirectory(dir, false));
}
/** Returns an array of strings, one for each file in the directory. */
public final String[] list() {
String[] result = new String[files.size()];
int i = 0;
Enumeration names = files.keys();
while (names.hasMoreElements())
result[i++] = (String)names.nextElement();
return result;
}
/** Returns true iff the named file exists in this directory. */
public final boolean fileExists(String name) {
RAMFile file = (RAMFile)files.get(name);
return file != null;
}
/** Returns the time the named file was last modified. */
public final long fileModified(String name) throws IOException {
RAMFile file = (RAMFile)files.get(name);
return file.lastModified;
}
/** Set the modified time of an existing file to now. */
public void touchFile(String name) throws IOException {
// final boolean MONITOR = false;
int count = 0;
RAMFile file = (RAMFile)files.get(name);
long ts2, ts1 = System.currentTimeMillis();
do {
try {
Thread.sleep(0, 1);
} catch (InterruptedException e) {}
ts2 = System.currentTimeMillis();
// if (MONITOR) {
// count++;
// }
} while(ts1 == ts2);
file.lastModified = ts2;
// if (MONITOR)
// System.out.println("SLEEP COUNT: " + count);
}
/** Returns the length in bytes of a file in the directory. */
public final long fileLength(String name) {
RAMFile file = (RAMFile)files.get(name);
return file.length;
}
/** Removes an existing file in the directory. */
public final void deleteFile(String name) {
files.remove(name);
}
/** Removes an existing file in the directory. */
public final void renameFile(String from, String to) {
RAMFile file = (RAMFile)files.get(from);
files.remove(from);
files.put(to, file);
}
/** Creates a new, empty file in the directory with the given name.
Returns a stream writing this file. */
public final OutputStream createFile(String name) {
RAMFile file = new RAMFile();
files.put(name, file);
return new RAMOutputStream(file);
}
/** Returns a stream reading an existing file. */
public final InputStream openFile(String name) {
RAMFile file = (RAMFile)files.get(name);
return new RAMInputStream(file);
}
/** Construct a {@link Lock}.
* @param name the name of the lock file
*/
public final Lock makeLock(final String name) {
return new Lock() {
public boolean obtain() throws IOException {
synchronized (files) {
if (!fileExists(name)) {
createFile(name).close();
return true;
}
return false;
}
}
public void release() {
deleteFile(name);
}
public boolean isLocked() {
return fileExists(name);
}
};
}
/** Closes the store to future operations. */
public final void close() {
}
}
final class RAMInputStream extends InputStream implements Cloneable {
RAMFile file;
int pointer = 0;
public RAMInputStream(RAMFile f) {
file = f;
length = file.length;
}
/** InputStream methods */
public final void readInternal(byte[] dest, int destOffset, int len) {
int remainder = len;
int start = pointer;
while (remainder != 0) {
int bufferNumber = start/InputStream.BUFFER_SIZE;
int bufferOffset = start%InputStream.BUFFER_SIZE;
int bytesInBuffer = InputStream.BUFFER_SIZE - bufferOffset;
int bytesToCopy = bytesInBuffer >= remainder ? remainder : bytesInBuffer;
byte[] buffer = (byte[])file.buffers.elementAt(bufferNumber);
System.arraycopy(buffer, bufferOffset, dest, destOffset, bytesToCopy);
destOffset += bytesToCopy;
start += bytesToCopy;
remainder -= bytesToCopy;
}
pointer += len;
}
public final void close() {
}
/** Random-access methods */
public final void seekInternal(long pos) {
pointer = (int)pos;
}
}
final class RAMOutputStream extends OutputStream {
RAMFile file;
int pointer = 0;
public RAMOutputStream(RAMFile f) {
file = f;
}
/** output methods: */
public final void flushBuffer(byte[] src, int len) {
int bufferNumber = pointer/OutputStream.BUFFER_SIZE;
int bufferOffset = pointer%OutputStream.BUFFER_SIZE;
int bytesInBuffer = OutputStream.BUFFER_SIZE - bufferOffset;
int bytesToCopy = bytesInBuffer >= len ? len : bytesInBuffer;
if (bufferNumber == file.buffers.size())
file.buffers.addElement(new byte[OutputStream.BUFFER_SIZE]);
byte[] buffer = (byte[])file.buffers.elementAt(bufferNumber);
System.arraycopy(src, 0, buffer, bufferOffset, bytesToCopy);
if (bytesToCopy < len) { // not all in one buffer
int srcOffset = bytesToCopy;
bytesToCopy = len - bytesToCopy; // remaining bytes
bufferNumber++;
if (bufferNumber == file.buffers.size())
file.buffers.addElement(new byte[OutputStream.BUFFER_SIZE]);
buffer = (byte[])file.buffers.elementAt(bufferNumber);
System.arraycopy(src, srcOffset, buffer, 0, bytesToCopy);
}
pointer += len;
if (pointer > file.length)
file.length = pointer;
file.lastModified = System.currentTimeMillis();
}
public final void close() throws IOException {
super.close();
}
/** Random-access methods */
public final void seek(long pos) throws IOException {
super.seek(pos);
pointer = (int)pos;
}
public final long length() throws IOException {
return file.length;
}
}
final class RAMFile {
Vector buffers = new Vector();
long length;
long lastModified = System.currentTimeMillis();
}
| [
"durieuxthomas@hotmail.com"
] | durieuxthomas@hotmail.com |
09ef1af1aebca618d2e1331817fa59a57341cf7b | 03b3400a3ab71032033029858d093839dda56e59 | /src/tugasenkap4/Bus3.java | 24c7496b8c7de9aa66ee73d7ffc15b92dd0ab5c3 | [] | no_license | mzaidanf/Enkapsulasi4 | b35d77d5c023996d48792a71b47ffd87c7217aab | 8581ccca3a7d2ab9da27a408359542d926ba54e0 | refs/heads/master | 2023-03-24T15:38:15.954736 | 2021-03-23T06:23:33 | 2021-03-23T06:23:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,123 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tugasenkap4;
public class Bus3 {
public int penumpang;
public int maxpenumpang;
public Bus3(int maxpenumpang) {
this.maxpenumpang = maxpenumpang;
penumpang = 0;
}
public void addpenumpang(int penumpang) {
int temp;
temp = this.penumpang + penumpang;
if (temp > maxpenumpang) {
System.out.println("Penumpang melebihi kuota");
} else {
this.penumpang = temp;
}
}
public void getpenumpang(int password) {
if (password == 24) {
System.out.println("Password Benar");
} else {
System.out.println("Password Salah");
}
}
public void cetakpenumpang() {
System.out.println("Penumpang Bus Sekarang = " + penumpang);
System.out.println("Maksimum penumpang yang seharusnya adalah = " + maxpenumpang);
}
} | [
"muhammad_zaidan_29rpl@student.smktellkom-mlg.sch.id"
] | muhammad_zaidan_29rpl@student.smktellkom-mlg.sch.id |
3102a61d2841f2d4b1a7e74a9741212b5ddb1a73 | 64421eb8306129fb349922dfaccf1923ba443ac9 | /src/main/java/cn/jxnu/blog/service/IMenuService.java | b05decc234f62b8b74863cd7aea3fe4a25672532 | [] | no_license | Litjxnu/blog | 95bd261d94c1901a14b4c652a59af0a0df9ddb43 | d16834c4e3b8b3954f74c5423403a8454e7a146c | refs/heads/master | 2020-04-06T10:49:38.040594 | 2018-11-23T10:48:20 | 2018-11-23T10:48:20 | 157,393,294 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | package cn.jxnu.blog.service;
import java.util.List;
import cn.jxnu.blog.entity.Menu;
public interface IMenuService {
/**
* 根据标签id删除标签
* @param menuId
* @return
*/
Integer deleteById(Integer menuId);
/**
* 添加标签
* @param record
* @return
*/
Integer insert(Menu record);
/**
* 查找多个标签
* @param
* @return
*/
List<Menu> selectMenus();
/**
* 根据id查找menu
* @param menuId
* @return
*/
Menu selectMenuById(Integer menuId);
/**
* 修改便签
* @param menuId
* @return
*/
Integer updateById(Integer menuId);
}
| [
"Liteng_jxnu@126.com"
] | Liteng_jxnu@126.com |
bef283264aa7b7566e64dff31f39188f7e0c0690 | 88184902d5958cea997b87846b8c6142c003875a | /app/src/main/java/com/ormediagroup/xproject/BottomNavigationViewHelper.java | c759e424c955dd34bbce8590fb200ed13327f56c | [] | no_license | laujason/TownHealth | f54ea15acf71985ab1bfaca79c98fb7d3b92b19b | 8eb917e8c3ab677611f0cc77ef649061ffa66bf5 | refs/heads/master | 2020-03-11T17:18:22.923197 | 2018-04-26T02:01:39 | 2018-04-26T02:01:39 | 130,143,432 | 0 | 0 | null | 2018-04-26T02:01:40 | 2018-04-19T01:43:37 | Java | UTF-8 | Java | false | false | 1,276 | java | package com.ormediagroup.xproject;
import android.annotation.SuppressLint;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import java.lang.reflect.Field;
/**
* Created by YQ04 on 2018/4/11.
*/
public class BottomNavigationViewHelper {
@SuppressLint("RestrictedApi")
public static void disableShiftMode(BottomNavigationView navigationView) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) navigationView.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(i);
itemView.setShiftingMode(false);
itemView.setChecked(itemView.getItemData().isChecked());
}
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
| [
"jwlau@efortunetech.com"
] | jwlau@efortunetech.com |
adae7e282b41820caec3f95981e354af386e5168 | f0b78c5f8f04a38c8329d35497ed99b94c328fec | /liferay-training/modules/salesforce/salesforce-service/src/main/java/com/liferay/salesforce/service/impl/SalesforceLeadLocalServiceImpl.java | 80e5a77e2835fb6976da4611d56e9b747cb91752 | [] | no_license | dimplekoticha/workspace | 1d7087be8edfb3c8b571dafd459dec99073af574 | 958e73e25e11e5dc8a69173ae76653f51f9e716c | refs/heads/master | 2020-04-02T05:47:04.266750 | 2016-09-23T19:59:55 | 2016-09-23T19:59:55 | 65,832,974 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,800 | java | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.salesforce.service.impl;
import com.liferay.portal.kernel.dao.orm.ObjectNotFoundException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.messaging.MessageBatch;
import com.liferay.salesforce.query.Condition;
import com.liferay.salesforce.query.ConditionImpl;
import com.liferay.salesforce.query.builder.SelectQuery;
import com.liferay.salesforce.service.base.SalesforceLeadLocalServiceBaseImpl;
import com.liferay.salesforce.util.SalesforceObjectNames;
import java.util.Arrays;
import java.util.List;
import aQute.bnd.annotation.ProviderType;
/**
* The implementation of the salesforce lead local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link com.liferay.salesforce.service.SalesforceLeadLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
* </p>
*
* @author Brian Wing Shun Chan
* @see SalesforceLeadLocalServiceBaseImpl
* @see com.liferay.salesforce.service.SalesforceLeadLocalServiceUtil
*/
@ProviderType
public class SalesforceLeadLocalServiceImpl
extends SalesforceLeadLocalServiceBaseImpl {
public MessageBatch getLeadsByCountry(
long companyId, String country, List<String> fieldNames, long ownerId)
throws SystemException {
Condition condition = ConditionImpl.EQUALS("Country", country);
return executeQuery(companyId, fieldNames, condition, ownerId);
}
public MessageBatch getLeadsBySource(
long companyId, String source, List<String> fieldNames, long ownerId)
throws SystemException {
Condition condition = ConditionImpl.EQUALS("LeadSource", source);
return executeQuery(companyId, fieldNames, condition, ownerId);
}
public MessageBatch getLeadsByStatus(
long companyId, String status, List<String> fieldNames, long ownerId)
throws SystemException {
Condition condition = ConditionImpl.EQUALS("Status", status);
return executeQuery(companyId, fieldNames, condition, ownerId);
}
public MessageBatch getLeadsByUserId(
long companyId, String userId, List<String> fieldNames, long ownerId)
throws ObjectNotFoundException, SystemException {
Condition condition = ConditionImpl.EQUALS("OwnerId", userId);
return executeQuery(companyId, fieldNames, condition, ownerId);
}
public MessageBatch getLeadsByUserName(
long companyId, String userName, List<String> fieldNames, long ownerId)
throws ObjectNotFoundException, SystemException {
Condition condition = ConditionImpl.EQUALS("Owner.Username", userName);
return executeQuery(companyId, fieldNames, condition, ownerId);
}
protected MessageBatch executeQuery(
long companyId, List<String> fieldNames, Condition condition, long ownerId)
throws SystemException {
String query = SelectQuery.build(
SalesforceObjectNames.LEAD, fieldNames, condition,
_orderByFieldNames);
return salesforceLocalService.executeQuery(companyId, query, ownerId);
}
private static List<String> _orderByFieldNames = Arrays.asList(
"LastActivityDate");
} | [
"dimple.koticha@liferay.com"
] | dimple.koticha@liferay.com |
d755af466615bc3dbbf89128e36381f381ae27d3 | d73693c8d806aa0597aa64d6954b86704e1c4afa | /src/main/java/by/kizin/konstantin/resttask/entity/errorModel/ValidationErrorObject.java | 29c2b9e6111288d3cf6b9f96b4ac5279d1f164e6 | [] | no_license | KonstantinKizin/Simple-Rest-api | e0076f01e0727cfc51d9a87dfa2100776e00373f | 28b55c89a865cd66802534646bd920ca706bc01f | refs/heads/master | 2020-03-21T21:00:27.447532 | 2018-07-18T22:08:18 | 2018-07-18T22:08:18 | 139,040,699 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,034 | java | package by.kizin.konstantin.resttask.entity.errorModel;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class ValidationErrorObject extends SubError {
private String object;
private String field;
private Object rejectedValue;
private String message;
public ValidationErrorObject(String object, String message) {
this.object = object;
this.message = message;
}
public ValidationErrorObject(String object, String field, Object rejectedValue, String message) {
this.object = object;
this.field = field;
this.rejectedValue = rejectedValue;
this.message = message;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ValidationErrorObject that = (ValidationErrorObject) o;
if (object != null ? !object.equals(that.object) : that.object != null) return false;
if (field != null ? !field.equals(that.field) : that.field != null) return false;
if (rejectedValue != null ? !rejectedValue.equals(that.rejectedValue) : that.rejectedValue != null)
return false;
return message != null ? message.equals(that.message) : that.message == null;
}
@Override
public int hashCode() {
int result = object != null ? object.hashCode() : 0;
result = 31 * result + (field != null ? field.hashCode() : 0);
result = 31 * result + (rejectedValue != null ? rejectedValue.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ValidationErrorObject{" +
"object='" + object + '\'' +
", field='" + field + '\'' +
", rejectedValue=" + rejectedValue +
", message='" + message + '\'' +
'}';
}
}
| [
"KostyKizin@gmail.com"
] | KostyKizin@gmail.com |
11e0df4691bc0955b526c80234cfe113fbde31f1 | 646226dda8aab3e6a60225fe98bedfbcef4beea6 | /src/main/java/week11/d02/Ride.java | 417df516ca826302caebef238950d3505820b7fd | [] | no_license | dudikpal/training-solutions | 88d5130f7745fcaeeb0045c49b9c3eb40b9a1168 | 75f6bb268ea87526b22e3203361151fa76dd40eb | refs/heads/master | 2023-04-28T05:20:13.522278 | 2021-05-02T17:40:43 | 2021-05-02T17:40:43 | 307,834,663 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 806 | java | package week11.d02;
public class Ride implements Comparable<Ride>{
private int day;
private int task;
private int distance;
public Ride(int day, int task, int distance) {
this.day = day;
this.task = task;
this.distance = distance;
}
public int getDay() {
return day;
}
public int getTask() {
return task;
}
public int getDistance() {
return distance;
}
@Override
public int compareTo(Ride o) {
return (this.getDay() * 100 + this.getTask()) - (o.getDay() * 100 + o.getTask());
}
@Override
public String toString() {
return "Ride{" +
"day=" + day +
", task=" + task +
", distance=" + distance +
'}';
}
}
| [
"dudikpal@gmail.com"
] | dudikpal@gmail.com |
e92479026adff15da86252a718bef3f92c2cd413 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/3/3_c8db0512527433f18accb2077731accab397a55f/GACurveFitter/3_c8db0512527433f18accb2077731accab397a55f_GACurveFitter_s.java | 147f4020ee59c25352d67876c7684165aabf410d | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 18,538 | java | //
// GACurveFitter.java
//
/*
SLIM Plotter application and curve fitting library for
combined spectral lifetime visualization and analysis.
Copyright (C) 2006-@year@ Curtis Rueden and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.slim.fit;
import java.util.Random;
/**
* Genetic algorithm for exponential curve fitting.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java">SVN</a></dd></dl>
*
* @author Eric Kjellman egkjellman at wisc.edu
*/
public class GACurveFitter extends CurveFitter {
// -- Fields --
protected int components;
protected double[][][] geneticData;
protected double[] fitness;
protected double currentRCSE;
protected int stallGenerations;
private double mutationFactor;
private static final boolean DEBUG = false;
private static final int STALL_GENERATIONS = 3;
private static final double STALLED_FACTOR = 2.0d;
private static final double MUTATION_CHANCE = .25d;
private static final int SPECIMENS = 25;
// Must be 0 < x < 1
private static final double INITIAL_MUTATION_FACTOR = .5;
// Must be 0 < x < 1
private static final double MUTATION_FACTOR_REDUCTION = .99;
// -- Constructor --
public GACurveFitter() {
initialize();
}
public void initialize() {
curveData = null;
components = 1;
curveEstimate = new double[components][3];
geneticData = null;
fitness = null;
currentRCSE = Double.MAX_VALUE;
stallGenerations = 0;
mutationFactor = INITIAL_MUTATION_FACTOR;
}
// -- CurveFitter methods --
/**
* iterate() runs through one iteration of whatever curve fitting
* technique this curve fitter uses. This will generally update the
* information returned by getCurve and getChiSquaredError
**/
public void iterate() {
if (currentRCSE == Double.MAX_VALUE) estimate();
// TODO: Move these out, reuse them. Synchronized?
double[][][] newGeneration = new double[SPECIMENS][components][3];
Random r = new Random();
// First make the new generation.
// If we don't have generation or fitness data, generate it from whatever
// the current estimate is.
// Additionally, if we haven't improved for a number of generations,
// shake things up.
if (geneticData == null || fitness == null ||
stallGenerations > STALL_GENERATIONS)
{
stallGenerations = 0;
mutationFactor *= MUTATION_FACTOR_REDUCTION;
for (int i = 1; i < newGeneration.length; i++) {
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
double factor = r.nextDouble() * STALLED_FACTOR;
newGeneration[i][j][k] = curveEstimate[j][k] * factor;
}
}
}
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
newGeneration[0][j][k] = curveEstimate[j][k];
}
}
}
else {
// The fitness array is determined in the previous generation. It is
// actually a marker for a range for a single random number, scaled to
// 0.0-1.0. For example, if the raw fitness was {4, 3, 2, 1}, the
// fitness array would contain {.4, .7, .9, 1.0}
for (int q = 0; q < newGeneration.length; q++) {
int mother = 0;
int father = 0;
double fchance = r.nextDouble();
double mchance = r.nextDouble();
for (int i = 0; i < fitness.length; i++) {
if (fitness[i] > fchance) {
father = i;
break;
}
}
for (int i = 0; i < fitness.length; i++) {
if (fitness[i] > mchance) {
mother = i;
break;
}
}
double minfluence = r.nextDouble();
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
newGeneration[q][j][k] =
geneticData[mother][j][k] * minfluence +
geneticData[father][j][k] * (1.0 - minfluence);
}
}
}
for (int i = 0; i < newGeneration.length; i++) {
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
// mutate, if necessary
if (r.nextDouble() < MUTATION_CHANCE) {
newGeneration[i][j][k] *= ((1.0 - mutationFactor) +
r.nextDouble() * (2.0 * mutationFactor));
}
}
}
}
}
geneticData = newGeneration;
double total = 0.0d;
double best = Double.MAX_VALUE;
int bestindex = -1;
stallGenerations++;
for (int i = 0; i < geneticData.length; i++) {
fitness = new double[geneticData.length];
fitness[i] = getReducedChiSquaredError(geneticData[i]);
if (fitness[i] < best) {
best = fitness[i];
bestindex = i;
}
fitness[i] = 1.0 / fitness[i];
total += fitness[i];
}
for (int i = 0; i < geneticData.length; i++) {
fitness[i] /= total;
}
if (best < currentRCSE) {
stallGenerations = 0;
currentRCSE = best;
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
curveEstimate[j][k] = geneticData[bestindex][j][k];
}
}
}
/*
System.out.println("RCSE: " + currentRCSE);
for (int j = 0; j < components; j++) {
System.out.println("a: " + curveEstimate[j][0] + " b: " +
curveEstimate[j][1] + " c: " + curveEstimate[j][2]);
}
*/
}
/**
* Sets the data to be used to generate curve estimates.
* The array is expected to be of size datapoints
**/
public void setData(int[] data) {
curveData = data;
firstindex = 0;
lastindex = data.length - 1;
}
/**
* Returns a reference to the data array.
* Does not create a copy.
*/
public int[] getData() {
return curveData;
}
/**
* Sets how many exponentials are expected to be fitted.
* Currently, more than 2 is not supported.
**/
public void setComponentCount(int numExp) {
components = numExp;
curveEstimate = new double[numExp][3];
}
// Returns the number of exponentials to be fitted.
public int getComponentCount() {
return components;
}
// Initializes the curve fitter with a starting curve estimate.
public void estimate() {
/*
System.out.println("****** DATA ******");
for (int i = 0; i < curveData.length; i++) {
System.out.println("i: " + i + " data: " + curveData[i]);
}
*/
//try { Thread.sleep(1000); } catch(Exception e) {}
if (components >= 1) {
// TODO: Estimate c, factor it in below.
double guessC = Double.MAX_VALUE;
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
//double guessC = 0.0d;
// First, get a guess for the exponent.
// The exponent should be "constant", but we'd also like to weight
// the area at the beginning of the curve more heavily.
double num = 0.0;
double den = 0.0;
//for (int i = 1; i < curveData.length; i++) {
for (int i = firstindex + 1; i < curveData.length && i < lastindex; i++) {
if (curveData[i] > guessC && curveData[i-1] > guessC) {
//double time = curveData[i][0] - curveData[i-1][0];
double time = 1.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-1] - guessC);
double guess = 1.0 * -Math.log(factor);
if (DEBUG) {
System.out.println("Guess: " + guess + " Factor: " + factor);
}
num += (guess * (curveData[i] - guessC));
den += curveData[i] - guessC;
}
}
double exp = num/den;
if (DEBUG) System.out.println("Final exp guess: " + exp);
num = 0.0;
den = 0.0;
// Hacky... we would like to do this over the entire curve length,
// but the actual data is far too noisy to do this. Instead, we'll just
// do it for the first 5, which have the most data.
//for (int i = 0; i < curveData.length; i++)
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * exp);
// estimate a
double guessA = (curveData[i] - guessC) / value;
num += guessA * (curveData[i] - guessC);
den += curveData[i] - guessC;
if (DEBUG) {
System.out.println("Data: " + curveData[i] +
" Value: " + value + " guessA: " + guessA);
}
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
if (components == 2) {
double guessC = Double.MAX_VALUE;
//for (int i = 0; i < curveData.length; i++) {
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
curveEstimate[0][2] = guessC;
curveEstimate[1][2] = 0;
// First, get a guess for the exponents.
// To stabilize for error, do guesses over spans of 3 timepoints.
double high = 0.0d;
double low = Double.MAX_VALUE;
for (int i = firstindex + 3; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > guessC && curveData[i-3] > guessC + 10) {
//double time = curveData[i][0] - curveData[i-3][0];
double time = 3.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-3] - guessC);
double guess = (1.0 / 3.0) * -Math.log(factor);
if (guess > high) high = guess;
if (guess < low) low = guess;
}
}
curveEstimate[0][1] = high;
curveEstimate[1][1] = low;
double highA = 0.0d;
double lowA = Double.MAX_VALUE;
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC + 10) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * low);
// estimate a
double guessA = curveData[i] / value;
if (guessA > highA) highA = guessA;
if (guessA < lowA) lowA = guessA;
}
}
/*
if (10.0 > lowA) lowA = 10.0;
if (20.0 > highA) highA = 20.0;
*/
curveEstimate[0][0] = highA - lowA;
curveEstimate[1][0] = lowA;
// It seems like the low estimates are pretty good, usually.
// It may be possible to get a better high estimate by subtracting out
// the low estimate, and then recalculating as if it were single
// exponential.
double[][] lowEst = new double[1][3];
lowEst[0][0] = curveEstimate[1][0];
lowEst[0][1] = curveEstimate[1][1];
lowEst[0][2] = curveEstimate[1][2];
int[] cdata = new int[lastindex - firstindex + 1];
System.arraycopy(curveData, firstindex, cdata, 0, cdata.length);
double[] lowData = getEstimates(cdata, lowEst);
double[][] lowValues = new double[cdata.length][2];
for (int i = 0; i < lowValues.length; i++) {
lowValues[i][0] = i;
lowValues[i][1] = cdata[i] - lowData[i];
}
// now, treat lowValues as a single exponent.
double num = 0.0;
double den = 0.0;
for (int i = 1; i < lowValues.length; i++) {
if (lowValues[i][1] > guessC && lowValues[i-1][1] > guessC) {
double time = lowValues[i][0] - lowValues[i-1][0];
double factor =
(lowValues[i][1] - guessC) / (lowValues[i-1][1] - guessC);
double guess = (1.0 / time) * -Math.log(factor);
num += (guess * (lowValues[i][1] - guessC));
den += lowValues[i][1] - guessC;
}
}
double exp = num/den;
num = 0.0;
den = 0.0;
//for (int i = 0; i < lowValues.length; i++)
for (int i = 0; i < 5; i++) {
if (lowValues[i][1] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -lowValues[i][0] * exp);
// estimate a
double guessA = lowValues[i][1] / value;
num += guessA * (lowValues[i][1] - guessC);
den += lowValues[i][1] - guessC;
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
// Sometimes, if the curve looks strange, we'll get a negative estimate
// This will really have to be fixed in iteration, but until then we want
// to get a "reasonable" positive estimate.
// We'll take the high point of the curve, and then the farthest away
// low point of the curve, and naively fit a single exponential to those
// two points. In the case of a multiple exponential curve, we'll split the
// a factor unevenly among the two, and then sort it out in iteration.
// This is all very "last ditch effort" estimation.
boolean doNegativeEstimation = false;
for (int i = 0; i < curveEstimate.length; i++) {
if (curveEstimate[i][1] < 0) {
doNegativeEstimation = true;
//System.out.println("Negative factor " +
// curveEstimate[i][1] + " found.");
}
}
if (doNegativeEstimation) {
// Find highest point in the curve
int maxIndex = -1;
int maxData = -1;
for (int i = firstindex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > maxData) {
maxIndex = i;
maxData = curveData[i];
}
}
int minIndex = -1;
int minData = Integer.MAX_VALUE;
for (int i = maxIndex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] <= minData) {
minIndex = i;
minData = curveData[i];
}
}
//System.out.println("maxIndex: " + maxIndex + " minIndex: " + minIndex);
// If we have valid min and max data, perform the "estimate"
double expguess = -1;
// ae^-b(t0)+c = x
// ae^-b(t1)+c = y.
// if t0 = 0, and c is minData, then a = x - minData. (e^0 = 1)
// Then, (x-min)e^-b(t1) = y
// e^-b(t1) = y / (x-min)
// ln e^-b(t1) = ln (y / (x - min))
// -b(t1) = ln (y / (x - min))
// -b = (ln (y / (x - min)) / t1)
// b = -(ln (y / (x - min)) / t1)
// and c = minData
if (maxData != -1 && minData != -1) {
double a = maxData - minData;
// min value for many trouble cases is 0, which is problematic.
// As an estimate, if minData is 0, we'll scan back to see how far it
// until data, and use that distance as an estimate.
double y = 0;
int newmin = minIndex;
while (curveData[newmin] == minData) newmin--;
y = 1.0 / (minIndex - newmin);
expguess = -(Math.log(y / (maxData - minData)) / (minIndex - maxIndex));
}
if (expguess < 0) {
// If the guess is still somehow negative
// (example, ascending curve), punt;
expguess = 1;
}
//System.out.println("Estimating: " + expguess);
//System.out.println("maxData: " + maxData + " firstindex: " +
// firstindex + " data: " + curveData[firstindex]);
if (components == 1) {
curveEstimate[0][0] = maxData - minData;
curveEstimate[0][1] = expguess;
curveEstimate[0][2] = minData;
} else {
// 2 components
curveEstimate[0][0] = maxData * .8;
curveEstimate[0][1] = expguess;
curveEstimate[1][0] = maxData * .2;
curveEstimate[1][1] = expguess;
curveEstimate[0][2] = minData;
}
}
// To update currentRCSE.
currentRCSE = getReducedChiSquaredError();
}
/**
* Returns the current curve estimate.
* Return size is expected to be [components][3]
* For each exponential of the form ae^-bt+c,
* [][0] is a, [1] is b, [2] is c.
**/
public double[][] getCurve() {
if (components == 1) return curveEstimate;
// Otherwise, it's 2 exponential, and we want it in ascending order
if (components == 2) {
if (curveEstimate[0][1] > curveEstimate[1][1]) {
double[][] toreturn = new double[components][3];
toreturn[0] = curveEstimate[1];
toreturn[1] = curveEstimate[0];
return toreturn;
} else {
return curveEstimate;
}
}
return null;
}
/**
* Sets the current curve estimate, useful if information about the
* curve is already known.
* See getCurve for information about the array to pass.
**/
public void setCurve(double[][] curve) {
if (curve.length != components) {
throw new IllegalArgumentException("Incorrect number of components.");
}
if (curve[0].length != 3) {
throw new IllegalArgumentException(
"Incorrect number of elements per degree.");
}
curveEstimate = curve;
currentRCSE = getReducedChiSquaredError();
}
public void setFirst(int index) {
firstindex = index;
}
public void setLast(int index) {
lastindex = index;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
0fa39e924fed799acdc04323957d96bc359b90dd | 1a4770c215544028bad90c8f673ba3d9e24f03ad | /second/quark/src/main/java/com/ucpro/services/e/g.java | 0b308d584fee34ddad8eb43b0fbf231fd6a41766 | [] | no_license | zhang1998/browser | e480fbd6a43e0a4886fc83ea402f8fbe5f7c7fce | 4eee43a9d36ebb4573537eddb27061c67d84c7ba | refs/heads/master | 2021-05-03T06:32:24.361277 | 2018-02-10T10:35:36 | 2018-02-10T10:35:36 | 120,590,649 | 8 | 10 | null | null | null | null | UTF-8 | Java | false | false | 233 | java | package com.ucpro.services.e;
/* compiled from: ProGuard */
final class g implements Runnable {
final /* synthetic */ a a;
g(a aVar) {
this.a = aVar;
}
public final void run() {
this.a.b();
}
}
| [
"2764207312@qq.com"
] | 2764207312@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.