blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3351063a0cc0bf41936f63812548284418d41a4 | 34,067,680,595,502 | 8d348a7836fe550cf56f669e1836c58de47d2d4d | /app/src/main/java/com/example/gaston/myapplication/BaseDatos.java | c07cf2ac99bf202480e3bc6a00b5263921f4be02 | []
| no_license | ezecastiglione18/Programacion-Fragments-ListView-SQLite | https://github.com/ezecastiglione18/Programacion-Fragments-ListView-SQLite | 17d7a68dcddac70c2ce37e8f49f4033423749d53 | a3dbfa781576dde844693ba3a5aae15f2a4a9682 | refs/heads/master | 2019-03-08T23:06:48.694000 | 2017-08-21T17:02:51 | 2017-08-21T17:02:51 | 100,902,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.gaston.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Gaston on 20/8/2017.
*/
public class BaseDatos extends SQLiteOpenHelper {
public BaseDatos(Context Contexto, String Nombre, SQLiteDatabase.CursorFactory fabrica, int Version)
{
super (Contexto, Nombre, fabrica, Version);
}
@Override
public void onCreate(SQLiteDatabase BaseDatos)
{
Log.d("BaseDatos","Declaro e inicializo la varuable para crear la tabla de nombres");
String sqlCrearTablaNombre = "create table Nombres (nombre text)";
BaseDatos.execSQL(sqlCrearTablaNombre);
}
@Override
public void onUpgrade(SQLiteDatabase baseDatos, int versionant, int versionnueva)
{
}
}
| UTF-8 | Java | 872 | java | BaseDatos.java | Java | [
{
"context": "elper;\nimport android.util.Log;\n\n/**\n * Created by Gaston on 20/8/2017.\n */\n\npublic class BaseDatos extends",
"end": 221,
"score": 0.9990292191505432,
"start": 215,
"tag": "NAME",
"value": "Gaston"
}
]
| null | []
| package com.example.gaston.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Gaston on 20/8/2017.
*/
public class BaseDatos extends SQLiteOpenHelper {
public BaseDatos(Context Contexto, String Nombre, SQLiteDatabase.CursorFactory fabrica, int Version)
{
super (Contexto, Nombre, fabrica, Version);
}
@Override
public void onCreate(SQLiteDatabase BaseDatos)
{
Log.d("BaseDatos","Declaro e inicializo la varuable para crear la tabla de nombres");
String sqlCrearTablaNombre = "create table Nombres (nombre text)";
BaseDatos.execSQL(sqlCrearTablaNombre);
}
@Override
public void onUpgrade(SQLiteDatabase baseDatos, int versionant, int versionnueva)
{
}
}
| 872 | 0.727064 | 0.719037 | 32 | 26.25 | 30.170349 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 2 |
3c45e597be65f08d5c010df3134e4e402a3ff180 | 34,557,306,881,164 | 75df5750190c732492bdb7aaab96c90688e71c0a | /src/main/java/com/raven/dynamic/datasource/common/annotation/EnableSharding.java | 62af36d92e9c1aa9693f6eefd745024d9440b647 | []
| no_license | RavenHuo/sharding-jdbc-dynamic-datasource | https://github.com/RavenHuo/sharding-jdbc-dynamic-datasource | 7e58380967f4c5cf71314dfb54928e2afd5dd071 | 9e05936c1d01f4604e0019873d08cb55f45a2db0 | refs/heads/master | 2023-02-18T18:13:12.600000 | 2021-01-12T08:49:49 | 2021-01-12T08:49:49 | 289,028,241 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.raven.dynamic.datasource.common.annotation;
import com.raven.dynamic.datasource.sharding.ShardingTablePackageRegister;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
/**
* @author raven
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(ShardingTablePackageRegister.class)
public @interface EnableSharding {
/**
* 实体类扫描包
* @return
*/
String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
}
| UTF-8 | Java | 559 | java | EnableSharding.java | Java | [
{
"context": "t;\n\nimport java.lang.annotation.*;\n\n/**\n * @author raven\n */\n@Target(ElementType.TYPE)\n@Retention(Retentio",
"end": 240,
"score": 0.9992584586143494,
"start": 235,
"tag": "USERNAME",
"value": "raven"
}
]
| null | []
| package com.raven.dynamic.datasource.common.annotation;
import com.raven.dynamic.datasource.sharding.ShardingTablePackageRegister;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
/**
* @author raven
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(ShardingTablePackageRegister.class)
public @interface EnableSharding {
/**
* 实体类扫描包
* @return
*/
String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
}
| 559 | 0.736746 | 0.736746 | 27 | 19.25926 | 20.85149 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 2 |
302a16e8b1a43f8dce1dfd2993677b1dbddb8894 | 34,437,047,795,689 | 83593598f21cba234f08eca4dec44d2f73a6052d | /prj/otc/web-exchange/src/main/java/gnnt/MEBS/common/security/util/Configuration.java | 8604f850e475ea11a6cf2bf27379e90facb0971a | [
"Apache-2.0"
]
| permissive | bigstar18/prjs | https://github.com/bigstar18/prjs | 23a04309a51b0372ddf6c391ee42270e640ec13c | c29da4d0892ce43e074d9e9831f1eedf828cd9d8 | refs/heads/master | 2021-05-31T19:55:16.217000 | 2016-06-24T02:35:31 | 2016-06-24T02:35:31 | 42,025,473 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gnnt.MEBS.common.security.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Configuration
{
private static boolean initFlag;
private static Hashtable<String, Properties> configInfo = new Hashtable();
private Properties propertyInfo;
private String cPath;
private boolean ConfigFlag;
private String CompName;
private static Object xmlConfigA = new Object();
private static Object xmlConfigB = new Object();
public Configuration()
{
this(getDefaultPath());
}
public Configuration(String path)
{
synchronized (xmlConfigA)
{
this.cPath = path;
if (!initFlag) {
if (resetConfigInfo() == 0) {
initFlag = true;
}
}
}
}
public Hashtable getConfigInfo()
{
return configInfo;
}
public Properties getSection(String sectionPath)
{
this.propertyInfo = ((Properties)configInfo.get(sectionPath));
return this.propertyInfo;
}
public int resetConfigInfo()
{
synchronized (xmlConfigB)
{
int IsParseT = 10;
IsParseT = parseXML();
if (IsParseT != 0) {
return 1;
}
return 0;
}
}
protected int parseXML()
{
Document doc = null;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
if ((this.cPath == null) || (this.cPath.equals("")))
{
System.out.println("ERROR:File .xml is null or not equals any value");
return 1;
}
File f = new File(this.cPath);
doc = db.parse(f);
NodeList comp = null;
if (!this.ConfigFlag)
{
NodeList conf = doc.getChildNodes();
for (int i = 0; i < conf.getLength(); i++) {
if (!conf.item(0).getNodeName().toUpperCase().equals("CONFIG"))
{
System.out.println("ERROR:Some tags are in wrong location with CONFIG in " + this.cPath);
return 1;
}
}
this.ConfigFlag = true;
comp = conf.item(0).getChildNodes();
}
else
{
comp = doc.getChildNodes();
}
for (int j = 0; j < comp.getLength(); j++) {
if (comp.item(j).getNodeName().toUpperCase().equals("COMPONENT"))
{
NodeList children = comp.item(j).getChildNodes();
String name = null;
String type = null;
boolean IsNamed = false;
boolean IsTyped = false;
for (int k = 0; k < children.getLength(); k++)
{
String tagName = children.item(k).getNodeName();
if (tagName.toUpperCase().equals("NAME"))
{
if (IsNamed)
{
System.out.println("ERROR:The name appeared twice in " + this.cPath);
return 1;
}
name = children.item(k).getFirstChild().getNodeValue();
if (this.CompName != null) {
name = this.CompName + "." + name;
}
IsNamed = true;
}
else if (tagName.toUpperCase().equals("TYPE"))
{
if (IsTyped)
{
System.out.println("ERROR:The type appeared twice in " + this.cPath);
return 1;
}
type = children.item(k).getFirstChild().getNodeValue();
if (type.toLowerCase().equals("link"))
{
if (name == null)
{
System.out.println("ERROR:The link filename is not assigned");
return 1;
}
this.cPath = (vPathToFPath() + "\\" + name);
if (parseXML() != 0)
{
System.out.println("ERROR:The link " + name + " in " + this.cPath + " is found wrong");
return 1;
}
}
IsTyped = true;
}
else if (tagName.toUpperCase().equals("SECTION"))
{
if ((name == null) || (type == null))
{
System.out.println("ERROR:The component's name is not known in " + this.cPath);
return 1;
}
NodeList sec = children.item(k).getChildNodes();
String sname = null;
Properties pr = new Properties();
for (int n = 0; n < sec.getLength(); n++)
{
String secName = sec.item(n).getNodeName();
if (secName.toUpperCase().equals("NAME"))
{
sname = name + "." + sec.item(n).getFirstChild().getNodeValue();
}
else if (secName.toUpperCase().equals("PROPERTYS"))
{
NodeList prop = sec.item(n).getChildNodes();
for (int m = 0; m < prop.getLength(); m++)
{
String pname = prop.item(m).getNodeName();
if (pname.toUpperCase().equals("PROPERTY"))
{
NodeList kv = prop.item(m).getChildNodes();
String key = null;
String value = null;
for (int l = 0; l < kv.getLength(); l++)
{
String kname = kv.item(l).getNodeName();
if (kname.toUpperCase().equals("KEY")) {
key = kv.item(l).getFirstChild().getNodeValue();
} else if (kname.toUpperCase().equals("VALUE")) {
value = kv.item(l).getFirstChild().getNodeValue();
}
}
if ((key == null) || (value == null))
{
System.out.println("ERROR:Section " + sname + " has null key or null value in " + this.cPath);
return 1;
}
try
{
pr.setProperty(key, value);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the property " + key + " in section " + sname + " in " + this.cPath);
}
}
}
}
}
try
{
configInfo.put(sname, pr);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the section " + sname + " into the hashtable in " + this.cPath);
}
}
else if (tagName.toUpperCase().equals("COMPONENT"))
{
int pc = parseComponent(name, children.item(k).getChildNodes());
if (pc != 0)
{
System.out.println("ERROR:False is in the inner component in " + this.cPath);
return pc;
}
}
}
}
}
}
catch (FileNotFoundException e)
{
System.out.println("ERROR:File " + this.cPath + " not found");
return 1;
}
catch (IOException e)
{
System.out.println("ERROR:There is something wrong with inputStream");
return 1;
}
catch (ParserConfigurationException e)
{
System.out.println("ERROR:There is something wrong with Parsing xml");
return 1;
}
catch (SAXException e)
{
System.out.println("ERROR:There is something wrong with Parsing xml");
return 1;
}
return 0;
}
protected int parseComponent(String cname, NodeList children)
{
String name = null;
String type = null;
String linkName = null;
boolean IsNamed = false;
boolean IsTyped = false;
for (int k = 0; k < children.getLength(); k++)
{
String tagName = children.item(k).getNodeName();
if (tagName.toUpperCase().equals("NAME"))
{
if (IsNamed)
{
System.out.println("ERROR:The name appeared twice in " + this.cPath);
return 1;
}
name = cname + "." + children.item(k).getFirstChild().getNodeValue();
linkName = children.item(k).getFirstChild().getNodeValue();
IsNamed = true;
}
else if (tagName.toUpperCase().equals("TYPE"))
{
if (IsTyped)
{
System.out.println("ERROR:The type appeared twice in " + this.cPath);
return 1;
}
type = children.item(k).getFirstChild().getNodeValue();
if (type.toLowerCase().equals("link"))
{
if (linkName == null)
{
System.out.println("ERROR:The link filename is not assigned in " + this.cPath);
return 1;
}
this.cPath = (vPathToFPath() + "\\" + linkName);
name = cname;
this.CompName = name;
if (parseXML() != 0)
{
System.out.println("ERROR:The link " + name + " in " + this.cPath + " is found wrong");
return 1;
}
}
IsTyped = true;
}
else if (tagName.toUpperCase().equals("SECTION"))
{
if ((name == null) || (type == null))
{
System.out.println("ERROR:The component's name is not known in " + this.cPath);
return 1;
}
NodeList sec = children.item(k).getChildNodes();
String sname = null;
Properties pr = new Properties();
for (int n = 0; n < sec.getLength(); n++)
{
String secName = sec.item(n).getNodeName();
if (secName.toUpperCase().equals("NAME"))
{
sname = name + "." + sec.item(n).getFirstChild().getNodeValue();
}
else if (secName.toUpperCase().equals("PROPERTYS"))
{
NodeList prop = sec.item(n).getChildNodes();
for (int m = 0; m < prop.getLength(); m++)
{
String pname = prop.item(m).getNodeName();
if (pname.toUpperCase().equals("PROPERTY"))
{
NodeList kv = prop.item(m).getChildNodes();
String key = null;
String value = null;
for (int l = 0; l < kv.getLength(); l++)
{
String kname = kv.item(l).getNodeName();
if (kname.toUpperCase().equals("KEY")) {
key = kv.item(l).getFirstChild().getNodeValue();
} else if (kname.toUpperCase().equals("VALUE")) {
value = kv.item(l).getFirstChild().getNodeValue();
}
}
if ((key == null) || (value == null))
{
System.out.println("ERROR:Section " + sname + " has null key or null value in " + this.cPath);
return 1;
}
try
{
pr.setProperty(key, value);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the property " + key + " in section " + sname + " in " + this.cPath);
return 1;
}
}
}
}
}
try
{
configInfo.put(sname, pr);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the section " + sname + " into the hashtable" + " in " + this.cPath);
return 1;
}
}
else if (tagName.toUpperCase().equals("COMPONENT"))
{
int pc = parseComponent(name, children.item(k).getChildNodes());
if (pc != 0)
{
System.out.println("ERROR:False is in the inner component in " + this.cPath);
return pc;
}
}
}
return 0;
}
private String vPathToFPath()
{
int a = this.cPath.lastIndexOf("\\");
this.cPath = this.cPath.substring(0, a);
return this.cPath;
}
private static String getDefaultPath()
{
String configPath = "";
try
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url1 = loader.getResource("mgr.xml");
if (url1 == null) {
throw new Exception("没有找到xml文件");
}
configPath = url1.getPath();
configPath = URLDecoder.decode(configPath, "UTF-8");
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("ERROR:When you get default path");
}
return configPath;
}
}
| UTF-8 | Java | 13,594 | java | Configuration.java | Java | []
| null | []
| package gnnt.MEBS.common.security.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Configuration
{
private static boolean initFlag;
private static Hashtable<String, Properties> configInfo = new Hashtable();
private Properties propertyInfo;
private String cPath;
private boolean ConfigFlag;
private String CompName;
private static Object xmlConfigA = new Object();
private static Object xmlConfigB = new Object();
public Configuration()
{
this(getDefaultPath());
}
public Configuration(String path)
{
synchronized (xmlConfigA)
{
this.cPath = path;
if (!initFlag) {
if (resetConfigInfo() == 0) {
initFlag = true;
}
}
}
}
public Hashtable getConfigInfo()
{
return configInfo;
}
public Properties getSection(String sectionPath)
{
this.propertyInfo = ((Properties)configInfo.get(sectionPath));
return this.propertyInfo;
}
public int resetConfigInfo()
{
synchronized (xmlConfigB)
{
int IsParseT = 10;
IsParseT = parseXML();
if (IsParseT != 0) {
return 1;
}
return 0;
}
}
protected int parseXML()
{
Document doc = null;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
if ((this.cPath == null) || (this.cPath.equals("")))
{
System.out.println("ERROR:File .xml is null or not equals any value");
return 1;
}
File f = new File(this.cPath);
doc = db.parse(f);
NodeList comp = null;
if (!this.ConfigFlag)
{
NodeList conf = doc.getChildNodes();
for (int i = 0; i < conf.getLength(); i++) {
if (!conf.item(0).getNodeName().toUpperCase().equals("CONFIG"))
{
System.out.println("ERROR:Some tags are in wrong location with CONFIG in " + this.cPath);
return 1;
}
}
this.ConfigFlag = true;
comp = conf.item(0).getChildNodes();
}
else
{
comp = doc.getChildNodes();
}
for (int j = 0; j < comp.getLength(); j++) {
if (comp.item(j).getNodeName().toUpperCase().equals("COMPONENT"))
{
NodeList children = comp.item(j).getChildNodes();
String name = null;
String type = null;
boolean IsNamed = false;
boolean IsTyped = false;
for (int k = 0; k < children.getLength(); k++)
{
String tagName = children.item(k).getNodeName();
if (tagName.toUpperCase().equals("NAME"))
{
if (IsNamed)
{
System.out.println("ERROR:The name appeared twice in " + this.cPath);
return 1;
}
name = children.item(k).getFirstChild().getNodeValue();
if (this.CompName != null) {
name = this.CompName + "." + name;
}
IsNamed = true;
}
else if (tagName.toUpperCase().equals("TYPE"))
{
if (IsTyped)
{
System.out.println("ERROR:The type appeared twice in " + this.cPath);
return 1;
}
type = children.item(k).getFirstChild().getNodeValue();
if (type.toLowerCase().equals("link"))
{
if (name == null)
{
System.out.println("ERROR:The link filename is not assigned");
return 1;
}
this.cPath = (vPathToFPath() + "\\" + name);
if (parseXML() != 0)
{
System.out.println("ERROR:The link " + name + " in " + this.cPath + " is found wrong");
return 1;
}
}
IsTyped = true;
}
else if (tagName.toUpperCase().equals("SECTION"))
{
if ((name == null) || (type == null))
{
System.out.println("ERROR:The component's name is not known in " + this.cPath);
return 1;
}
NodeList sec = children.item(k).getChildNodes();
String sname = null;
Properties pr = new Properties();
for (int n = 0; n < sec.getLength(); n++)
{
String secName = sec.item(n).getNodeName();
if (secName.toUpperCase().equals("NAME"))
{
sname = name + "." + sec.item(n).getFirstChild().getNodeValue();
}
else if (secName.toUpperCase().equals("PROPERTYS"))
{
NodeList prop = sec.item(n).getChildNodes();
for (int m = 0; m < prop.getLength(); m++)
{
String pname = prop.item(m).getNodeName();
if (pname.toUpperCase().equals("PROPERTY"))
{
NodeList kv = prop.item(m).getChildNodes();
String key = null;
String value = null;
for (int l = 0; l < kv.getLength(); l++)
{
String kname = kv.item(l).getNodeName();
if (kname.toUpperCase().equals("KEY")) {
key = kv.item(l).getFirstChild().getNodeValue();
} else if (kname.toUpperCase().equals("VALUE")) {
value = kv.item(l).getFirstChild().getNodeValue();
}
}
if ((key == null) || (value == null))
{
System.out.println("ERROR:Section " + sname + " has null key or null value in " + this.cPath);
return 1;
}
try
{
pr.setProperty(key, value);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the property " + key + " in section " + sname + " in " + this.cPath);
}
}
}
}
}
try
{
configInfo.put(sname, pr);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the section " + sname + " into the hashtable in " + this.cPath);
}
}
else if (tagName.toUpperCase().equals("COMPONENT"))
{
int pc = parseComponent(name, children.item(k).getChildNodes());
if (pc != 0)
{
System.out.println("ERROR:False is in the inner component in " + this.cPath);
return pc;
}
}
}
}
}
}
catch (FileNotFoundException e)
{
System.out.println("ERROR:File " + this.cPath + " not found");
return 1;
}
catch (IOException e)
{
System.out.println("ERROR:There is something wrong with inputStream");
return 1;
}
catch (ParserConfigurationException e)
{
System.out.println("ERROR:There is something wrong with Parsing xml");
return 1;
}
catch (SAXException e)
{
System.out.println("ERROR:There is something wrong with Parsing xml");
return 1;
}
return 0;
}
protected int parseComponent(String cname, NodeList children)
{
String name = null;
String type = null;
String linkName = null;
boolean IsNamed = false;
boolean IsTyped = false;
for (int k = 0; k < children.getLength(); k++)
{
String tagName = children.item(k).getNodeName();
if (tagName.toUpperCase().equals("NAME"))
{
if (IsNamed)
{
System.out.println("ERROR:The name appeared twice in " + this.cPath);
return 1;
}
name = cname + "." + children.item(k).getFirstChild().getNodeValue();
linkName = children.item(k).getFirstChild().getNodeValue();
IsNamed = true;
}
else if (tagName.toUpperCase().equals("TYPE"))
{
if (IsTyped)
{
System.out.println("ERROR:The type appeared twice in " + this.cPath);
return 1;
}
type = children.item(k).getFirstChild().getNodeValue();
if (type.toLowerCase().equals("link"))
{
if (linkName == null)
{
System.out.println("ERROR:The link filename is not assigned in " + this.cPath);
return 1;
}
this.cPath = (vPathToFPath() + "\\" + linkName);
name = cname;
this.CompName = name;
if (parseXML() != 0)
{
System.out.println("ERROR:The link " + name + " in " + this.cPath + " is found wrong");
return 1;
}
}
IsTyped = true;
}
else if (tagName.toUpperCase().equals("SECTION"))
{
if ((name == null) || (type == null))
{
System.out.println("ERROR:The component's name is not known in " + this.cPath);
return 1;
}
NodeList sec = children.item(k).getChildNodes();
String sname = null;
Properties pr = new Properties();
for (int n = 0; n < sec.getLength(); n++)
{
String secName = sec.item(n).getNodeName();
if (secName.toUpperCase().equals("NAME"))
{
sname = name + "." + sec.item(n).getFirstChild().getNodeValue();
}
else if (secName.toUpperCase().equals("PROPERTYS"))
{
NodeList prop = sec.item(n).getChildNodes();
for (int m = 0; m < prop.getLength(); m++)
{
String pname = prop.item(m).getNodeName();
if (pname.toUpperCase().equals("PROPERTY"))
{
NodeList kv = prop.item(m).getChildNodes();
String key = null;
String value = null;
for (int l = 0; l < kv.getLength(); l++)
{
String kname = kv.item(l).getNodeName();
if (kname.toUpperCase().equals("KEY")) {
key = kv.item(l).getFirstChild().getNodeValue();
} else if (kname.toUpperCase().equals("VALUE")) {
value = kv.item(l).getFirstChild().getNodeValue();
}
}
if ((key == null) || (value == null))
{
System.out.println("ERROR:Section " + sname + " has null key or null value in " + this.cPath);
return 1;
}
try
{
pr.setProperty(key, value);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the property " + key + " in section " + sname + " in " + this.cPath);
return 1;
}
}
}
}
}
try
{
configInfo.put(sname, pr);
}
catch (NullPointerException e)
{
System.out.println("ERROR:When you set the section " + sname + " into the hashtable" + " in " + this.cPath);
return 1;
}
}
else if (tagName.toUpperCase().equals("COMPONENT"))
{
int pc = parseComponent(name, children.item(k).getChildNodes());
if (pc != 0)
{
System.out.println("ERROR:False is in the inner component in " + this.cPath);
return pc;
}
}
}
return 0;
}
private String vPathToFPath()
{
int a = this.cPath.lastIndexOf("\\");
this.cPath = this.cPath.substring(0, a);
return this.cPath;
}
private static String getDefaultPath()
{
String configPath = "";
try
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url1 = loader.getResource("mgr.xml");
if (url1 == null) {
throw new Exception("没有找到xml文件");
}
configPath = url1.getPath();
configPath = URLDecoder.decode(configPath, "UTF-8");
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("ERROR:When you get default path");
}
return configPath;
}
}
| 13,594 | 0.472611 | 0.468782 | 414 | 30.806763 | 25.713985 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.487923 | false | false | 2 |
2adf1ddce123175e00c04a2ca6846104c5ee90f8 | 14,310,831,088,439 | 668584d63f6ed8f48c8609c3a142f8bdf1ba1a40 | /prj/coherence-core/src/main/java/com/tangosol/dev/compiler/java/ExitStatement.java | 3898df0ba3811f19fa0d6d24477990429f5fda9a | [
"EPL-1.0",
"Classpath-exception-2.0",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-protobuf",
"CDDL-1.1",
"W3C",
"APSL-1.0",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"SAX-PD",
"MPL-2.0",
"MPL-1.1",
"CC-PDDC",
"BSD-2-Clause",
"Plexus",
"EPL-2.0",
"CDDL-1.0",
"LicenseRef-scancode-proprietary-license",
"MIT",
"CC0-1.0",
"APSL-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-only",
"LGPL-2.1-or-later",
"UPL-1.0"
]
| permissive | oracle/coherence | https://github.com/oracle/coherence | 34c48d36674e69974a693925c18f097175052c5f | b1a009a406e37fdc5479366035d8c459165324e1 | refs/heads/main | 2023-08-31T14:53:40.437000 | 2023-08-31T02:04:15 | 2023-08-31T02:04:15 | 242,776,849 | 416 | 96 | UPL-1.0 | false | 2023-08-07T04:27:39 | 2020-02-24T15:51:04 | 2023-07-07T09:20:15 | 2023-08-07T04:10:10 | 8,736,774 | 396 | 73 | 7 | Java | false | false | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
package com.tangosol.dev.compiler.java;
import com.tangosol.dev.assembler.CodeAttribute;
import com.tangosol.dev.compiler.CompilerException;
import com.tangosol.dev.compiler.Context;
import com.tangosol.util.ErrorList;
/**
* This class represents the statements which can exit a method: throw and
* return.
*
* @version 1.00, 09/21/98
* @author Cameron Purdy
*/
public abstract class ExitStatement extends Statement
{
// ----- construction ---------------------------------------------------
/**
* Construct an exit statement.
*
* @param stmt the statement within which this element exists
* @param token the first token of the statement
*/
protected ExitStatement(Statement stmt, Token token)
{
super(stmt, token);
}
// ----- Element methods ------------------------------------------------
/**
* Print the element information.
*
* @param sIndent
*/
public void print(String sIndent)
{
out(sIndent + toString());
if (expr != null)
{
out(sIndent + " Value:");
expr.print(sIndent + " ");
}
}
// ----- accessors ------------------------------------------------------
/**
* Get the exit value.
*
* @return the value expression of the exit statement
*/
public Expression getExpression()
{
return expr;
}
/**
* Set the exit value.
*
* @param expr the value expression of the exit statement
*/
protected void setExpression(Expression expr)
{
this.expr = expr;
}
// ----- data members ---------------------------------------------------
/**
* The class name.
*/
private static final String CLASS = "ExitStatement";
/**
* The return or exception value.
*/
private Expression expr;
}
| UTF-8 | Java | 2,092 | java | ExitStatement.java | Java | [
{
"context": "d\n* return.\n*\n* @version 1.00, 09/21/98\n* @author Cameron Purdy\n*/\npublic abstract class ExitStatement extends St",
"end": 545,
"score": 0.9998318552970886,
"start": 532,
"tag": "NAME",
"value": "Cameron Purdy"
}
]
| null | []
| /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
package com.tangosol.dev.compiler.java;
import com.tangosol.dev.assembler.CodeAttribute;
import com.tangosol.dev.compiler.CompilerException;
import com.tangosol.dev.compiler.Context;
import com.tangosol.util.ErrorList;
/**
* This class represents the statements which can exit a method: throw and
* return.
*
* @version 1.00, 09/21/98
* @author <NAME>
*/
public abstract class ExitStatement extends Statement
{
// ----- construction ---------------------------------------------------
/**
* Construct an exit statement.
*
* @param stmt the statement within which this element exists
* @param token the first token of the statement
*/
protected ExitStatement(Statement stmt, Token token)
{
super(stmt, token);
}
// ----- Element methods ------------------------------------------------
/**
* Print the element information.
*
* @param sIndent
*/
public void print(String sIndent)
{
out(sIndent + toString());
if (expr != null)
{
out(sIndent + " Value:");
expr.print(sIndent + " ");
}
}
// ----- accessors ------------------------------------------------------
/**
* Get the exit value.
*
* @return the value expression of the exit statement
*/
public Expression getExpression()
{
return expr;
}
/**
* Set the exit value.
*
* @param expr the value expression of the exit statement
*/
protected void setExpression(Expression expr)
{
this.expr = expr;
}
// ----- data members ---------------------------------------------------
/**
* The class name.
*/
private static final String CLASS = "ExitStatement";
/**
* The return or exception value.
*/
private Expression expr;
}
| 2,085 | 0.527247 | 0.518164 | 96 | 20.791666 | 23.037069 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 2 |
9b740a6987a996813dad63ec269605d4a7500946 | 11,381,663,368,965 | b175489e2d4ab646b9ed2b272fa581ff56f25ece | /BouncyCastle/util/src/main/java/com/distrimind/bouncycastle/asn1/its/ToBeSignedData.java | 4a0f7cf21b75e5cac6d4f10e18511b462e2f0d57 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
]
| permissive | JazZ51/BouncyCastle | https://github.com/JazZ51/BouncyCastle | 9af0e80e40c30375bc20febe47f1991ac0610851 | 729df0a976f40c1d8457e5ad4d131b7623abc565 | refs/heads/main | 2021-11-13T20:06:59.815000 | 2021-11-01T16:22:23 | 2021-11-01T16:23:03 | 99,471,871 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.distrimind.bouncycastle.asn1.its;
import com.distrimind.bouncycastle.asn1.ASN1EncodableVector;
import com.distrimind.bouncycastle.asn1.ASN1Object;
import com.distrimind.bouncycastle.asn1.ASN1Primitive;
import com.distrimind.bouncycastle.asn1.DERSequence;
/**
* <pre>
* ToBeSignedData ::= SEQUENCE {
* payload SignedDataPayload,
* headerInfo HeaderInfo
* }
* </pre>
*/
public class ToBeSignedData
extends ASN1Object
{
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector v = new ASN1EncodableVector();
return new DERSequence(v);
}
}
| UTF-8 | Java | 618 | java | ToBeSignedData.java | Java | []
| null | []
| package com.distrimind.bouncycastle.asn1.its;
import com.distrimind.bouncycastle.asn1.ASN1EncodableVector;
import com.distrimind.bouncycastle.asn1.ASN1Object;
import com.distrimind.bouncycastle.asn1.ASN1Primitive;
import com.distrimind.bouncycastle.asn1.DERSequence;
/**
* <pre>
* ToBeSignedData ::= SEQUENCE {
* payload SignedDataPayload,
* headerInfo HeaderInfo
* }
* </pre>
*/
public class ToBeSignedData
extends ASN1Object
{
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector v = new ASN1EncodableVector();
return new DERSequence(v);
}
}
| 618 | 0.716828 | 0.695793 | 25 | 23.719999 | 21.208527 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 2 |
6ad56b6e43041b1e0f32e1c3d0eeb50f32c31359 | 23,905,788,009,219 | 6c88fe9c106b33d6214d9b9ae9250b8cba9092b3 | /rdgame_mock/src/test/java/com/jd/rd/game/mock/HttpClientUtilTest.java | 054b92111a22f822d153fd2a9b4ce1e7d62a82a7 | []
| no_license | SiHeZi/game_mock | https://github.com/SiHeZi/game_mock | 0d16790315fbe238dae6bc181563788c3d72f879 | 2fea4ff49b08598d2d063e5098871b57294cd4c3 | refs/heads/master | 2021-01-02T09:24:26.970000 | 2017-08-03T08:20:29 | 2017-08-03T08:20:29 | 99,208,686 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jd.rd.game.mock;
import com.alibaba.fastjson.JSON;
import com.jd.rd.game.mock.dto.request.GameLogicReq;
import com.jd.rd.game.mock.util.HttpClientUtil;
import org.junit.Test;
public class HttpClientUtilTest {
@Test
public void testSendHttpPost2() {
GameLogicReq logicReq = new GameLogicReq();
logicReq.setTranType(0);
logicReq.setFeeType(4);
logicReq.setExt("xxx");
logicReq.setGameID(1001L);
logicReq.setGameRequest("游戏侧自定义");
String param1 = JSON.toJSONString(logicReq);
System.out.println(param1.replaceAll("\"","'"));
String responseContent = HttpClientUtil.getInstance()
.sendHttpPost("http://localhost:8080/gameLogic",param1);
System.out.println("reponse content:" + responseContent);
}
//@Test
public void testSendHttpsGet() {
String responseContent = HttpClientUtil.getInstance()
.sendHttpsGet("http://localhost:8080/login");
System.out.println("reponse content:" + responseContent);
}
}
| UTF-8 | Java | 1,084 | java | HttpClientUtilTest.java | Java | []
| null | []
| package com.jd.rd.game.mock;
import com.alibaba.fastjson.JSON;
import com.jd.rd.game.mock.dto.request.GameLogicReq;
import com.jd.rd.game.mock.util.HttpClientUtil;
import org.junit.Test;
public class HttpClientUtilTest {
@Test
public void testSendHttpPost2() {
GameLogicReq logicReq = new GameLogicReq();
logicReq.setTranType(0);
logicReq.setFeeType(4);
logicReq.setExt("xxx");
logicReq.setGameID(1001L);
logicReq.setGameRequest("游戏侧自定义");
String param1 = JSON.toJSONString(logicReq);
System.out.println(param1.replaceAll("\"","'"));
String responseContent = HttpClientUtil.getInstance()
.sendHttpPost("http://localhost:8080/gameLogic",param1);
System.out.println("reponse content:" + responseContent);
}
//@Test
public void testSendHttpsGet() {
String responseContent = HttpClientUtil.getInstance()
.sendHttpsGet("http://localhost:8080/login");
System.out.println("reponse content:" + responseContent);
}
}
| 1,084 | 0.661381 | 0.64459 | 38 | 27.18421 | 24.224667 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
23dfc8ec4cf15ef55b1bbf0c5d665b11420168b9 | 23,905,788,007,887 | 22083c3ee6a244c5edebda3ef9e90618bb3ec3a3 | /src/Buyer.java | 6c6c0388238aa52d73ab7eb5e428583d625c7d47 | []
| no_license | martenkrings/ConcurrencyOpdracht3 | https://github.com/martenkrings/ConcurrencyOpdracht3 | ede967281e8b0244a207ef54f35e45be46a6ccaa | 58c52c82ce530890d6da52e656010e542de9e625 | refs/heads/master | 2020-05-23T08:09:35.471000 | 2016-10-30T18:56:11 | 2016-10-30T18:56:11 | 69,347,552 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Random;
/**
* A thread that tries to enter the Hiswa to buy a boat
*/
public class Buyer extends Thread {
private Hiswa hiswa;
public Buyer(Hiswa hiswa) {
this.hiswa = hiswa;
}
public void run() {
//life never ends
while (true) {
try {
//go to the Hiswa at a random time
this.sleep(new Random().nextInt(12000));
hiswa.buyerEnterHiswa();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 575 | java | Buyer.java | Java | []
| null | []
| import java.util.Random;
/**
* A thread that tries to enter the Hiswa to buy a boat
*/
public class Buyer extends Thread {
private Hiswa hiswa;
public Buyer(Hiswa hiswa) {
this.hiswa = hiswa;
}
public void run() {
//life never ends
while (true) {
try {
//go to the Hiswa at a random time
this.sleep(new Random().nextInt(12000));
hiswa.buyerEnterHiswa();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 575 | 0.516522 | 0.507826 | 25 | 22 | 17.760632 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.24 | false | false | 2 |
f25e033d857728e590d82e52e42cef4b69f8b77e | 38,714,835,235,743 | d63b36464fe21b95c7705f9699319a88ece48ded | /Java_HCL/day3/DemoProject/src/com/hcl/day4/Quiz.java | 18ed21f1fe4493a3481f996225b18914b54271d0 | []
| no_license | sandeshAraveti/Java-training | https://github.com/sandeshAraveti/Java-training | 8d2046081f33c7b1463eb75c05897fbc483e2ab0 | 288ea295391053c79be24ca57863dc2281d5d53e | refs/heads/master | 2022-12-24T18:41:43.087000 | 2020-01-07T12:36:19 | 2020-01-07T12:36:19 | 223,157,169 | 0 | 0 | null | false | 2022-12-16T03:48:15 | 2019-11-21T11:19:13 | 2020-01-07T12:36:22 | 2022-12-16T03:48:13 | 70,155 | 0 | 0 | 16 | JavaScript | false | false | package com.hcl.day4;
public class Quiz {
static int score;
public void incr(){
score++;
}
@Override
public String toString() {
return "Quiz [score=" + score + "]";
}
public static void main(String[] args) {
Quiz obj1=new Quiz();
obj1.incr();
System.out.println(obj1);
Quiz obj2=new Quiz();
obj2.incr();
System.out.println(obj2);
Quiz obj3=new Quiz();
obj3.incr();
System.out.println(obj3);
}
}
| UTF-8 | Java | 430 | java | Quiz.java | Java | []
| null | []
| package com.hcl.day4;
public class Quiz {
static int score;
public void incr(){
score++;
}
@Override
public String toString() {
return "Quiz [score=" + score + "]";
}
public static void main(String[] args) {
Quiz obj1=new Quiz();
obj1.incr();
System.out.println(obj1);
Quiz obj2=new Quiz();
obj2.incr();
System.out.println(obj2);
Quiz obj3=new Quiz();
obj3.incr();
System.out.println(obj3);
}
}
| 430 | 0.632558 | 0.609302 | 25 | 16.200001 | 11.661903 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 2 |
b3557eadb395058df718b33c477d98dd1c21d25b | 7,937,099,629,751 | dce3f05765ddf75284f70e1a26fcb2e330a4c7da | /src/main/java/com/takshine/wxcrm/domain/Sign.java | d492976cb45c9208edc6fbabc50d91bc858d87ff | []
| no_license | bellmit/ZJWK4SHYY | https://github.com/bellmit/ZJWK4SHYY | 302cf6a4c23ecada30ad802313d62a98489a2a1b | fdaec363d29e82f8d59ad6fc32d3b8454fe3b2fc | refs/heads/master | 2023-03-20T21:12:20.221000 | 2016-06-24T02:35:33 | 2016-06-24T02:35:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.takshine.wxcrm.domain;
import java.util.List;
import com.takshine.wxcrm.model.SignModel;
/**
* 考勤签到
*
*
*/
public class Sign extends SignModel {
private String signTime = null;
private String signType = null;
private String signAddr = null;
private String signLongitude = null;
private String signLatitude = null;
private String remark = null;
private String viewtype = null;//
private int currpages = 0;
private int pagecounts = 10;
private String name = null;
private String startdate = null;
private String enddate = null;
private List<String> crm_id_in = null;
private String wximgids;//微信上传图片
public String getSignTime() {
return signTime;
}
public void setSignTime(String signTime) {
this.signTime = signTime;
}
public String getSignType() {
return signType;
}
public void setSignType(String signType) {
this.signType = signType;
}
public String getSignAddr() {
return signAddr;
}
public void setSignAddr(String signAddr) {
this.signAddr = signAddr;
}
public String getSignLongitude() {
return signLongitude;
}
public void setSignLongitude(String signLongitude) {
this.signLongitude = signLongitude;
}
public String getSignLatitude() {
return signLatitude;
}
public void setSignLatitude(String signLatitude) {
this.signLatitude = signLatitude;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getViewtype() {
return viewtype;
}
public void setViewtype(String viewtype) {
this.viewtype = viewtype;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
public List<String> getCrm_id_in() {
return crm_id_in;
}
public void setCrm_id_in(List<String> crm_id_in) {
this.crm_id_in = crm_id_in;
}
public String getWximgids() {
return wximgids;
}
public void setWximgids(String wximgids) {
this.wximgids = wximgids;
}
}
| UTF-8 | Java | 2,230 | java | Sign.java | Java | []
| null | []
| package com.takshine.wxcrm.domain;
import java.util.List;
import com.takshine.wxcrm.model.SignModel;
/**
* 考勤签到
*
*
*/
public class Sign extends SignModel {
private String signTime = null;
private String signType = null;
private String signAddr = null;
private String signLongitude = null;
private String signLatitude = null;
private String remark = null;
private String viewtype = null;//
private int currpages = 0;
private int pagecounts = 10;
private String name = null;
private String startdate = null;
private String enddate = null;
private List<String> crm_id_in = null;
private String wximgids;//微信上传图片
public String getSignTime() {
return signTime;
}
public void setSignTime(String signTime) {
this.signTime = signTime;
}
public String getSignType() {
return signType;
}
public void setSignType(String signType) {
this.signType = signType;
}
public String getSignAddr() {
return signAddr;
}
public void setSignAddr(String signAddr) {
this.signAddr = signAddr;
}
public String getSignLongitude() {
return signLongitude;
}
public void setSignLongitude(String signLongitude) {
this.signLongitude = signLongitude;
}
public String getSignLatitude() {
return signLatitude;
}
public void setSignLatitude(String signLatitude) {
this.signLatitude = signLatitude;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getViewtype() {
return viewtype;
}
public void setViewtype(String viewtype) {
this.viewtype = viewtype;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
public List<String> getCrm_id_in() {
return crm_id_in;
}
public void setCrm_id_in(List<String> crm_id_in) {
this.crm_id_in = crm_id_in;
}
public String getWximgids() {
return wximgids;
}
public void setWximgids(String wximgids) {
this.wximgids = wximgids;
}
}
| 2,230 | 0.720362 | 0.719005 | 102 | 20.666666 | 15.638272 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.490196 | false | false | 2 |
356c5e06dddba653e04e83be293be170965d1bd6 | 7,937,099,627,362 | c70b41de06db789dbf768ad4969030dd7494dad2 | /app/src/main/java/com/example/studenttrackerapp/admin_view_student.java | e66efb9a390e2e18854846490d5dbe0461c56530 | []
| no_license | HemantPatil0219/StudentTrackerApp3 | https://github.com/HemantPatil0219/StudentTrackerApp3 | 984e4cec53848152119bc7cf4754c76f8533441c | d950bd1e1a774a8b66ffd3162a0d9f148f8af40f | refs/heads/master | 2020-08-04T23:02:27.269000 | 2019-10-16T17:58:10 | 2019-10-16T17:58:10 | 212,306,877 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.studenttrackerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class admin_view_student extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_view_student);
}
public void btn_admin_view_student(View view) {
}
public void btn_admin_update_student(View view) {
}
}
| UTF-8 | Java | 508 | java | admin_view_student.java | Java | []
| null | []
| package com.example.studenttrackerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class admin_view_student extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_view_student);
}
public void btn_admin_view_student(View view) {
}
public void btn_admin_update_student(View view) {
}
}
| 508 | 0.738189 | 0.738189 | 20 | 24.4 | 23.380333 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 2 |
2bfdd770a7d4bd7cd013ac8683d97d1b6b9ddce8 | 36,421,322,684,283 | 05bdf0c0e70988539537a947445a30b7c9a3c28d | /AndroidLibrary/src/com/android/library/utils/PreferenceUtils.java | 863bde4352c5fdbdfa9a523a490a80506302206c | []
| no_license | byoooy/android_dev_lib | https://github.com/byoooy/android_dev_lib | 4c0e7e537ee698546422f321a38918e1f75fdb37 | 58c2aa4fea9ac7556ef056cba5804d4cfbe858fa | refs/heads/master | 2020-05-19T10:58:58.376000 | 2015-09-09T09:44:41 | 2015-09-09T09:44:41 | 42,112,821 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.library.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* SharedPreferences配置保存工具
*/
public class PreferenceUtils {
private final String CONFIG = "config";
private SharedPreferences mShared;
/**
* 构建配置工具
*
* @param context
* 设备上下文环境
*/
public PreferenceUtils(Context context) {
new PreferenceUtils(context, CONFIG);
}
/**
* 构建配置工具
*
* @param context
* 设备上下文环境
* @param name
* 配置文件名
*/
public PreferenceUtils(Context context, String name) {
mShared = context.getSharedPreferences(name, 0);
}
/**
* 保存boolean值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, boolean value) {
Editor editor = mShared.edit();
editor.putBoolean(key, value);
editor.commit();
}
/**
* 获取boolean值
*
* @param key
* 键
* @return 查找不到值,默认返回false
*/
public boolean getBoolean(String key) {
return getBoolean(key, false);
}
/**
* 获取boolean值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public boolean getBoolean(String key, boolean defValue) {
return mShared.getBoolean(key, defValue);
}
/**
* 保存float值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, float value) {
Editor editor = mShared.edit();
editor.putFloat(key, value);
editor.commit();
}
/**
* 获取float值
*
* @param key
* 键
* @return 查找不到值,默认返回0
*/
public float getFloat(String key) {
return getFloat(key, 0);
}
/**
* 获取float值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public float getFloat(String key, float defValue) {
return mShared.getFloat(key, defValue);
}
/**
* 保存int值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, int value) {
Editor editor = mShared.edit();
editor.putInt(key, value);
editor.commit();
}
/**
* 获取int值
*
* @param key
* 键
* @return 查找不到值,默认返回0
*/
public int getInt(String key) {
return getInt(key, 0);
}
/**
* 获取int值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public int getInt(String key, int defValue) {
return mShared.getInt(key, defValue);
}
/**
* 保存long值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, long value) {
Editor editor = mShared.edit();
editor.putLong(key, value);
editor.commit();
}
/**
* 获取long值
*
* @param key
* 键
* @return 查找不到值,默认返回0
*/
public long getLong(String key) {
return getLong(key, 0);
}
/**
* 获取long值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public long getLong(String key, long defValue) {
return mShared.getLong(key, defValue);
}
/**
* 保存String值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, String value) {
Editor editor = mShared.edit();
editor.putString(key, value);
editor.commit();
}
/**
* 获取String值
*
* @param key
* 键
* @return 查找不到值,默认返回null
*/
public String getString(String key) {
return getString(key, null);
}
/**
* 获取String值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public String getString(String key, String defValue) {
return mShared.getString(key, defValue);
}
/**
* 保存序列化对象
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, Serializable value) {
try {
ByteArrayOutputStream toByte = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(toByte);
oos.writeObject(value);
String str = new String(Base64EncryptUtil.getInstance().encode(
toByte.toByteArray()));
Editor editor = mShared.edit();
editor.putString(key, str);
editor.commit();
} catch (IOException e) {
}
}
/**
* 获取序列化对象
*
* @param key
* 键
* @return 查找不到值,默认返回null
*/
public Object get(String key) {
return get(key, null);
}
/**
* 获取序列化对象
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public Object get(String key, Serializable defValue) {
String str = mShared.getString(key, null);
if (str == null) {
return defValue;
}
try {
byte[] baseBytes = Base64EncryptUtil.getInstance().decode(str)
.getBytes();
ByteArrayInputStream fromeByte = new ByteArrayInputStream(baseBytes);
ObjectInputStream ois = new ObjectInputStream(fromeByte);
return ois.readObject();
} catch (Exception e) {
}
return defValue;
}
/**
* 清空保存的数据
*/
public void clear() {
Editor editor = mShared.edit();
editor.clear();
editor.commit();
}
}
| UTF-8 | Java | 5,968 | java | PreferenceUtils.java | Java | []
| null | []
| package com.android.library.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* SharedPreferences配置保存工具
*/
public class PreferenceUtils {
private final String CONFIG = "config";
private SharedPreferences mShared;
/**
* 构建配置工具
*
* @param context
* 设备上下文环境
*/
public PreferenceUtils(Context context) {
new PreferenceUtils(context, CONFIG);
}
/**
* 构建配置工具
*
* @param context
* 设备上下文环境
* @param name
* 配置文件名
*/
public PreferenceUtils(Context context, String name) {
mShared = context.getSharedPreferences(name, 0);
}
/**
* 保存boolean值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, boolean value) {
Editor editor = mShared.edit();
editor.putBoolean(key, value);
editor.commit();
}
/**
* 获取boolean值
*
* @param key
* 键
* @return 查找不到值,默认返回false
*/
public boolean getBoolean(String key) {
return getBoolean(key, false);
}
/**
* 获取boolean值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public boolean getBoolean(String key, boolean defValue) {
return mShared.getBoolean(key, defValue);
}
/**
* 保存float值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, float value) {
Editor editor = mShared.edit();
editor.putFloat(key, value);
editor.commit();
}
/**
* 获取float值
*
* @param key
* 键
* @return 查找不到值,默认返回0
*/
public float getFloat(String key) {
return getFloat(key, 0);
}
/**
* 获取float值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public float getFloat(String key, float defValue) {
return mShared.getFloat(key, defValue);
}
/**
* 保存int值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, int value) {
Editor editor = mShared.edit();
editor.putInt(key, value);
editor.commit();
}
/**
* 获取int值
*
* @param key
* 键
* @return 查找不到值,默认返回0
*/
public int getInt(String key) {
return getInt(key, 0);
}
/**
* 获取int值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public int getInt(String key, int defValue) {
return mShared.getInt(key, defValue);
}
/**
* 保存long值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, long value) {
Editor editor = mShared.edit();
editor.putLong(key, value);
editor.commit();
}
/**
* 获取long值
*
* @param key
* 键
* @return 查找不到值,默认返回0
*/
public long getLong(String key) {
return getLong(key, 0);
}
/**
* 获取long值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public long getLong(String key, long defValue) {
return mShared.getLong(key, defValue);
}
/**
* 保存String值
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, String value) {
Editor editor = mShared.edit();
editor.putString(key, value);
editor.commit();
}
/**
* 获取String值
*
* @param key
* 键
* @return 查找不到值,默认返回null
*/
public String getString(String key) {
return getString(key, null);
}
/**
* 获取String值
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public String getString(String key, String defValue) {
return mShared.getString(key, defValue);
}
/**
* 保存序列化对象
*
* @param key
* 键
* @param value
* 值
*/
public void put(String key, Serializable value) {
try {
ByteArrayOutputStream toByte = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(toByte);
oos.writeObject(value);
String str = new String(Base64EncryptUtil.getInstance().encode(
toByte.toByteArray()));
Editor editor = mShared.edit();
editor.putString(key, str);
editor.commit();
} catch (IOException e) {
}
}
/**
* 获取序列化对象
*
* @param key
* 键
* @return 查找不到值,默认返回null
*/
public Object get(String key) {
return get(key, null);
}
/**
* 获取序列化对象
*
* @param key
* 键
* @param defValue
* 默认返回值
* @return 值
*/
public Object get(String key, Serializable defValue) {
String str = mShared.getString(key, null);
if (str == null) {
return defValue;
}
try {
byte[] baseBytes = Base64EncryptUtil.getInstance().decode(str)
.getBytes();
ByteArrayInputStream fromeByte = new ByteArrayInputStream(baseBytes);
ObjectInputStream ois = new ObjectInputStream(fromeByte);
return ois.readObject();
} catch (Exception e) {
}
return defValue;
}
/**
* 清空保存的数据
*/
public void clear() {
Editor editor = mShared.edit();
editor.clear();
editor.commit();
}
}
| 5,968 | 0.55029 | 0.548293 | 300 | 16.360001 | 15.130446 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.41 | false | false | 2 |
c8e62e4a20781e86265ea60171d33ed5899a10e4 | 28,999,619,235,005 | 38fe757bf571c1244878062184f744f957f196cd | /src/algorithm/leetcode/WeekTest166subtractProductAndSum.java | 2bacb44521b92ca6b3899d8d0d81d50896798405 | []
| no_license | NiuHaihang/algorithm | https://github.com/NiuHaihang/algorithm | 4bff93546e068f905cc95e87a12328f30b7c157a | ce33d41614410ed7522f31bf90b0001336568be6 | refs/heads/master | 2021-07-14T11:19:52.799000 | 2020-09-23T02:26:59 | 2020-09-23T02:26:59 | 205,844,890 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package algorithm.leetcode;
public class WeekTest166subtractProductAndSum {
public int subtractProductAndSum(int n) {
int product=1;
int sum=0;
while(n!=0){
product*=(n%10);
System.out.println("product="+product);
sum+=(n%10);
System.out.println("sum="+sum);
n/=10;
}
return product-sum;
}
public static void main(String[] args) {
WeekTest166subtractProductAndSum res=new WeekTest166subtractProductAndSum();
int ans=res.subtractProductAndSum(234);
System.out.println(ans);
}
}
| UTF-8 | Java | 591 | java | WeekTest166subtractProductAndSum.java | Java | []
| null | []
| package algorithm.leetcode;
public class WeekTest166subtractProductAndSum {
public int subtractProductAndSum(int n) {
int product=1;
int sum=0;
while(n!=0){
product*=(n%10);
System.out.println("product="+product);
sum+=(n%10);
System.out.println("sum="+sum);
n/=10;
}
return product-sum;
}
public static void main(String[] args) {
WeekTest166subtractProductAndSum res=new WeekTest166subtractProductAndSum();
int ans=res.subtractProductAndSum(234);
System.out.println(ans);
}
}
| 591 | 0.617597 | 0.582064 | 21 | 27.142857 | 18.941729 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
b79c4847daaac026400d96459461e3c7cd440056 | 7,026,566,535,557 | be39997010d1e6f1c9c77d20b9bf671307b64472 | /src/test/java/com/example/demo/DemoApplicationTests.java | ff82fff03e21d669fdd6a478a8699ad7223fb34e | []
| no_license | vedha004/spring-boot-demo | https://github.com/vedha004/spring-boot-demo | 6847ec067c49896bcd118f5738001368fb962284 | a6bfbbc57aa99784a01e5a44d7a81d87b8e88bb9 | refs/heads/master | 2021-09-04T05:05:08.313000 | 2018-01-16T05:52:44 | 2018-01-16T05:52:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private static final Log log = LogFactory.getLog(DemoApplicationTests.class);
@Autowired
private JavaMailSender mailSender;
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("490441342@qq.com");//发送者.
message.setTo("jiazhijie@navinfo.com");//接收者.
message.setSubject("测试邮件(邮件主题)");//邮件主题.
message.setText("这是邮件内容sssjjd");//邮件内容.
mailSender.send(message);//发送邮件
}
@Test
public void sendAttachmentsMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("490441342@qq.com");//发送者.
helper.setTo("jiazhijie@navinfo.com");//接收者.
helper.setSubject("主题:有附件");
helper.setText("有附件的邮件");
FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
helper.addAttachment("附件-1.jpg", file);
helper.addAttachment("附件-2.jpg", file);
mailSender.send(mimeMessage);
}
@Test
public void sendInlineMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("490441342@qq.com");//发送者.
helper.setTo("jiazhijie@navinfo.com");//接收者.
helper.setSubject("主题:嵌入静态资源");
helper.setText("<html><body><img src=\"cid:weixin\" ></body></html>", true);
FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
helper.addInline("weixin", file);
mailSender.send(mimeMessage);
}
}
| UTF-8 | Java | 2,457 | java | DemoApplicationTests.java | Java | [
{
"context": "ge = new SimpleMailMessage();\n\n\t\tmessage.setFrom(\"490441342@qq.com\");//发送者.\n\t\tmessage.setTo(\"jiazhijie@navinfo.com\")",
"end": 1043,
"score": 0.999616265296936,
"start": 1027,
"tag": "EMAIL",
"value": "490441342@qq.com"
},
{
"context": "tFrom(\"490441342@qq.com\");//发送者.\n\t\tmessage.setTo(\"jiazhijie@navinfo.com\");//接收者.\n\t\tmessage.setSubject(\"测试邮件(邮件主题)\");//邮件主",
"end": 1091,
"score": 0.9998754262924194,
"start": 1070,
"tag": "EMAIL",
"value": "jiazhijie@navinfo.com"
},
{
"context": "ssageHelper(mimeMessage, true);\n\t\thelper.setFrom(\"490441342@qq.com\");//发送者.\n\t\thelper.setTo(\"jiazhijie@navinfo.com\");",
"end": 1453,
"score": 0.9997416138648987,
"start": 1437,
"tag": "EMAIL",
"value": "490441342@qq.com"
},
{
"context": "etFrom(\"490441342@qq.com\");//发送者.\n\t\thelper.setTo(\"jiazhijie@navinfo.com\");//接收者.\n\t\thelper.setSubject(\"主题:有附件\");\n\t\thelper.",
"end": 1500,
"score": 0.9998757243156433,
"start": 1479,
"tag": "EMAIL",
"value": "jiazhijie@navinfo.com"
},
{
"context": "ssageHelper(mimeMessage, true);\n\t\thelper.setFrom(\"490441342@qq.com\");//发送者.\n\t\thelper.setTo(\"jiazhijie@navinfo.com\");",
"end": 1990,
"score": 0.9993472695350647,
"start": 1974,
"tag": "EMAIL",
"value": "490441342@qq.com"
},
{
"context": "etFrom(\"490441342@qq.com\");//发送者.\n\t\thelper.setTo(\"jiazhijie@navinfo.com\");//接收者.\n\t\thelper.setSubject(\"主题:嵌入静态资源\");\n\t\thelp",
"end": 2037,
"score": 0.9998680949211121,
"start": 2016,
"tag": "EMAIL",
"value": "jiazhijie@navinfo.com"
}
]
| null | []
| package com.example.demo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private static final Log log = LogFactory.getLog(DemoApplicationTests.class);
@Autowired
private JavaMailSender mailSender;
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("<EMAIL>");//发送者.
message.setTo("<EMAIL>");//接收者.
message.setSubject("测试邮件(邮件主题)");//邮件主题.
message.setText("这是邮件内容sssjjd");//邮件内容.
mailSender.send(message);//发送邮件
}
@Test
public void sendAttachmentsMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("<EMAIL>");//发送者.
helper.setTo("<EMAIL>");//接收者.
helper.setSubject("主题:有附件");
helper.setText("有附件的邮件");
FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
helper.addAttachment("附件-1.jpg", file);
helper.addAttachment("附件-2.jpg", file);
mailSender.send(mimeMessage);
}
@Test
public void sendInlineMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("<EMAIL>");//发送者.
helper.setTo("<EMAIL>");//接收者.
helper.setSubject("主题:嵌入静态资源");
helper.setText("<html><body><img src=\"cid:weixin\" ></body></html>", true);
FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
helper.addInline("weixin", file);
mailSender.send(mimeMessage);
}
}
| 2,388 | 0.772354 | 0.759395 | 75 | 29.84 | 24.761282 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.466667 | false | false | 2 |
8e1289b6b048b0053ccacfe1963121a49dd686a5 | 14,869,176,815,217 | 3fb0497ef703093bfb1b4bb6f44daef0596c2c31 | /ManagerStudent/app/src/main/java/com/example/managerstudent/MyDataBaseHelper.java | c3dce29dbb9ea8c8fd3d3984d813a9676d1886b6 | []
| no_license | kien2929/FileAndStudentManger | https://github.com/kien2929/FileAndStudentManger | 77bea4b6726fd107d148468c17357c4404fc2d0c | 4911c0625edac2f7b2cc518896d2d0271e3be882 | refs/heads/master | 2022-11-09T16:23:33.664000 | 2020-06-25T15:47:54 | 2020-06-25T15:47:54 | 274,955,548 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.managerstudent;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class MyDataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "SQLite";
// Database version
private static final int DATABASE_VERSION = 1;
// Database name
private static final String DATABASE_NAME = "Student_Manager.db";
// Table name : Student
private static final String TABLE_STUDENT = "Student";
private static final String STUDENT_ID = "Student_Id";
private static final String STUDENT_NAME = "Student_Name";
private static final String STUDENT_MSSV = "Student_Mssv";
private static final String STUDENT_DATE = "Student_Date";
private static final String STUDENT_EMAIL = "Student_Email";
private static final String STUDENT_ADDRESS = "Student_Address";
public MyDataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String script = "CREATE TABLE " + TABLE_STUDENT + " ("
+ STUDENT_ID + " INTEGER PRIMARY KEY,"
+ STUDENT_NAME + " TEXT,"
+ STUDENT_MSSV + " TEXT,"
+ STUDENT_DATE + " TEXT,"
+ STUDENT_EMAIL + " TEXT,"
+ STUDENT_ADDRESS + " TEXT)";
db.execSQL(script);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENT);
// Create tables again
onCreate(db);
}
public void addStudent(Student student){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STUDENT_NAME, student.getName());
values.put(STUDENT_MSSV, student.getMSSV());
values.put(STUDENT_DATE, student.getDateOfBirth());
values.put(STUDENT_EMAIL, student.getEmail());
values.put(STUDENT_ADDRESS, student.getAddress());
db.insert(TABLE_STUDENT, null, values);
db.close();
}
public List<Student> getAllNote(){
List<Student> studentList = new ArrayList<Student>();
// Select query
String selectQuery = "SELECT * FROM " + TABLE_STUDENT;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.setName(cursor.getString(1));
student.setMSSV(cursor.getString(2));
student.setDateOfBirth(cursor.getString(3));
student.setEmail(cursor.getString(4));
student.setAddress(cursor.getString(5));
studentList.add(student);
} while (cursor.moveToNext());
}
// return note list
return studentList;
}
public void createDefault(){
Student student1 = new Student("20160723", "Pham Ngoc Du", "29/11/1998",
"ngocdu12a1@gmail.com", "Thai Binh");
Student student2 = new Student("20161234", "Pham Ngoc Duong", "08/02/2008",
"ngocduong12a1@gmail.com", "Ha Noi");
this.addStudent(student1);
this.addStudent(student2);
}
public List<Student> search(String data){
String script = String.format("SELECT * FROM %s WHERE (%s LIKE '%%%s%%') OR (%s LIKE '%%%s%%')",
TABLE_STUDENT, STUDENT_NAME, data, STUDENT_MSSV, data);
Log.d(TAG, "search: " + script);
List<Student> studentList = new ArrayList<Student>();
// Select query
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(script, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.setName(cursor.getString(1));
student.setMSSV(cursor.getString(2));
student.setDateOfBirth(cursor.getString(3));
student.setEmail(cursor.getString(4));
student.setAddress(cursor.getString(5));
studentList.add(student);
} while (cursor.moveToNext());
}
// return note list
return studentList;
}
public void delete(String mssv){
String script = String.format("DELETE FROM %s WHERE %s LIKE %s", TABLE_STUDENT, STUDENT_MSSV, mssv);
Log.d(TAG, "search: " + script);
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(script);
}
}
| UTF-8 | Java | 5,030 | java | MyDataBaseHelper.java | Java | [
{
"context": " Student student1 = new Student(\"20160723\", \"Pham Ngoc Du\", \"29/11/1998\",\n \"ngocdu12a1@gmail",
"end": 3405,
"score": 0.9998184442520142,
"start": 3393,
"tag": "NAME",
"value": "Pham Ngoc Du"
},
{
"context": "\", \"Pham Ngoc Du\", \"29/11/1998\",\n \"ngocdu12a1@gmail.com\", \"Thai Binh\");\n Student student2 = new St",
"end": 3459,
"score": 0.9999282360076904,
"start": 3439,
"tag": "EMAIL",
"value": "ngocdu12a1@gmail.com"
},
{
"context": "1/1998\",\n \"ngocdu12a1@gmail.com\", \"Thai Binh\");\n Student student2 = new Student(\"201612",
"end": 3472,
"score": 0.8381929993629456,
"start": 3463,
"tag": "NAME",
"value": "Thai Binh"
},
{
"context": " Student student2 = new Student(\"20161234\", \"Pham Ngoc Duong\", \"08/02/2008\",\n \"ngocduong12a1@gm",
"end": 3543,
"score": 0.9998314380645752,
"start": 3528,
"tag": "NAME",
"value": "Pham Ngoc Duong"
},
{
"context": "\"Pham Ngoc Duong\", \"08/02/2008\",\n \"ngocduong12a1@gmail.com\", \"Ha Noi\");\n\n this.addStudent(student1);\n",
"end": 3600,
"score": 0.9999290108680725,
"start": 3577,
"tag": "EMAIL",
"value": "ngocduong12a1@gmail.com"
}
]
| null | []
| package com.example.managerstudent;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class MyDataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "SQLite";
// Database version
private static final int DATABASE_VERSION = 1;
// Database name
private static final String DATABASE_NAME = "Student_Manager.db";
// Table name : Student
private static final String TABLE_STUDENT = "Student";
private static final String STUDENT_ID = "Student_Id";
private static final String STUDENT_NAME = "Student_Name";
private static final String STUDENT_MSSV = "Student_Mssv";
private static final String STUDENT_DATE = "Student_Date";
private static final String STUDENT_EMAIL = "Student_Email";
private static final String STUDENT_ADDRESS = "Student_Address";
public MyDataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String script = "CREATE TABLE " + TABLE_STUDENT + " ("
+ STUDENT_ID + " INTEGER PRIMARY KEY,"
+ STUDENT_NAME + " TEXT,"
+ STUDENT_MSSV + " TEXT,"
+ STUDENT_DATE + " TEXT,"
+ STUDENT_EMAIL + " TEXT,"
+ STUDENT_ADDRESS + " TEXT)";
db.execSQL(script);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENT);
// Create tables again
onCreate(db);
}
public void addStudent(Student student){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STUDENT_NAME, student.getName());
values.put(STUDENT_MSSV, student.getMSSV());
values.put(STUDENT_DATE, student.getDateOfBirth());
values.put(STUDENT_EMAIL, student.getEmail());
values.put(STUDENT_ADDRESS, student.getAddress());
db.insert(TABLE_STUDENT, null, values);
db.close();
}
public List<Student> getAllNote(){
List<Student> studentList = new ArrayList<Student>();
// Select query
String selectQuery = "SELECT * FROM " + TABLE_STUDENT;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.setName(cursor.getString(1));
student.setMSSV(cursor.getString(2));
student.setDateOfBirth(cursor.getString(3));
student.setEmail(cursor.getString(4));
student.setAddress(cursor.getString(5));
studentList.add(student);
} while (cursor.moveToNext());
}
// return note list
return studentList;
}
public void createDefault(){
Student student1 = new Student("20160723", "<NAME>", "29/11/1998",
"<EMAIL>", "<NAME>");
Student student2 = new Student("20161234", "<NAME>", "08/02/2008",
"<EMAIL>", "Ha Noi");
this.addStudent(student1);
this.addStudent(student2);
}
public List<Student> search(String data){
String script = String.format("SELECT * FROM %s WHERE (%s LIKE '%%%s%%') OR (%s LIKE '%%%s%%')",
TABLE_STUDENT, STUDENT_NAME, data, STUDENT_MSSV, data);
Log.d(TAG, "search: " + script);
List<Student> studentList = new ArrayList<Student>();
// Select query
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(script, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.setName(cursor.getString(1));
student.setMSSV(cursor.getString(2));
student.setDateOfBirth(cursor.getString(3));
student.setEmail(cursor.getString(4));
student.setAddress(cursor.getString(5));
studentList.add(student);
} while (cursor.moveToNext());
}
// return note list
return studentList;
}
public void delete(String mssv){
String script = String.format("DELETE FROM %s WHERE %s LIKE %s", TABLE_STUDENT, STUDENT_MSSV, mssv);
Log.d(TAG, "search: " + script);
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(script);
}
}
| 4,983 | 0.613718 | 0.603181 | 148 | 32.986488 | 25.222252 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716216 | false | false | 2 |
c1a1c15b818c5a2a329a04caee2dd475d056d3c8 | 16,810,502,032,816 | d616568430917165aae86708e30172c516a78094 | /dailyProblem/lt518coinChangeII.java | f012bf839ff7e32e0dbcf0fe07d530ca7b31f92c | []
| no_license | sjxswgjhf/roadToSDE | https://github.com/sjxswgjhf/roadToSDE | 7d8ca853cddfd1ffe55205f3577f4656d7e13b84 | e6a262fb0536767c2bc115a0bd557b68f639ff9c | refs/heads/master | 2023-02-22T12:18:50.274000 | 2021-01-23T02:50:02 | 2021-01-23T02:50:02 | 294,164,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dailyProblem;
import java.util.Arrays;
public class lt518coinChangeII {
class Solution {
/*
dp[5]
1 2 5
1: 1 == 1 dp[1] = 1, dp[2] += dp[1] = 1, dp[3] = 1, dp[4] = 1, dp[5] = 1
2: 2
dp[2]:
*/
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
// dp[0] = 1;
Arrays.sort(coins);
outer: for(int i = 0; i < coins.length; i++){
for(int j = 1; j <= amount; j++){
if(coins[i] > j){
break outer;
}
else if(coins[i] == j){
dp[i]++;
}else{
if(dp[i - coins[j]] != 0){
dp[i] += dp[i - coins[j]];
}
}
}
}
return dp[amount];
}
}
}
| UTF-8 | Java | 964 | java | lt518coinChangeII.java | Java | []
| null | []
| package dailyProblem;
import java.util.Arrays;
public class lt518coinChangeII {
class Solution {
/*
dp[5]
1 2 5
1: 1 == 1 dp[1] = 1, dp[2] += dp[1] = 1, dp[3] = 1, dp[4] = 1, dp[5] = 1
2: 2
dp[2]:
*/
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
// dp[0] = 1;
Arrays.sort(coins);
outer: for(int i = 0; i < coins.length; i++){
for(int j = 1; j <= amount; j++){
if(coins[i] > j){
break outer;
}
else if(coins[i] == j){
dp[i]++;
}else{
if(dp[i - coins[j]] != 0){
dp[i] += dp[i - coins[j]];
}
}
}
}
return dp[amount];
}
}
}
| 964 | 0.31639 | 0.28527 | 38 | 24.368422 | 18.879704 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 2 |
a6bb53eee10ebf9fab1b6fd047310628a30dbaf8 | 8,959,301,828,354 | eddc20191c3182cde53db1f02b091b54dbee61ec | /src/main/java/com/db/tables/Followupevent.java | 3d894cb51a06a7fda6cbe6b7aef13a582ac3b687 | []
| no_license | pigflying/spring-boot | https://github.com/pigflying/spring-boot | 32fb8120d016671b56d87418397de3c84a0e091c | 3e18b625ae4b2cdd8098c0b9904f9c2adc3d8d13 | refs/heads/master | 2016-08-09T13:36:36.125000 | 2016-03-06T13:42:41 | 2016-03-06T13:42:41 | 53,232,904 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This class is generated by jOOQ
*/
package com.db.tables;
import com.db.Keys;
import com.db.Privdoc;
import com.db.tables.records.FollowupeventRecord;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Identity;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.7.3"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Followupevent extends TableImpl<FollowupeventRecord> {
private static final long serialVersionUID = -1845101771;
/**
* The reference instance of <code>privdoc.FollowUpEvent</code>
*/
public static final Followupevent FOLLOWUPEVENT = new Followupevent();
/**
* The class holding records for this type
*/
@Override
public Class<FollowupeventRecord> getRecordType() {
return FollowupeventRecord.class;
}
/**
* The column <code>privdoc.FollowUpEvent.id</code>.
*/
public final TableField<FollowupeventRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>privdoc.FollowUpEvent.planId</code>.
*/
public final TableField<FollowupeventRecord, Integer> PLANID = createField("planId", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>privdoc.FollowUpEvent.eventId</code>.
*/
public final TableField<FollowupeventRecord, Integer> EVENTID = createField("eventId", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* Create a <code>privdoc.FollowUpEvent</code> table reference
*/
public Followupevent() {
this("FollowUpEvent", null);
}
/**
* Create an aliased <code>privdoc.FollowUpEvent</code> table reference
*/
public Followupevent(String alias) {
this(alias, FOLLOWUPEVENT);
}
private Followupevent(String alias, Table<FollowupeventRecord> aliased) {
this(alias, aliased, null);
}
private Followupevent(String alias, Table<FollowupeventRecord> aliased, Field<?>[] parameters) {
super(alias, Privdoc.PRIVDOC, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Identity<FollowupeventRecord, Integer> getIdentity() {
return Keys.IDENTITY_FOLLOWUPEVENT;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<FollowupeventRecord> getPrimaryKey() {
return Keys.KEY_FOLLOWUPEVENT_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<FollowupeventRecord>> getKeys() {
return Arrays.<UniqueKey<FollowupeventRecord>>asList(Keys.KEY_FOLLOWUPEVENT_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public Followupevent as(String alias) {
return new Followupevent(alias, this);
}
/**
* Rename this table
*/
public Followupevent rename(String name) {
return new Followupevent(name, null);
}
}
| UTF-8 | Java | 2,984 | java | Followupevent.java | Java | []
| null | []
| /**
* This class is generated by jOOQ
*/
package com.db.tables;
import com.db.Keys;
import com.db.Privdoc;
import com.db.tables.records.FollowupeventRecord;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Identity;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.7.3"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Followupevent extends TableImpl<FollowupeventRecord> {
private static final long serialVersionUID = -1845101771;
/**
* The reference instance of <code>privdoc.FollowUpEvent</code>
*/
public static final Followupevent FOLLOWUPEVENT = new Followupevent();
/**
* The class holding records for this type
*/
@Override
public Class<FollowupeventRecord> getRecordType() {
return FollowupeventRecord.class;
}
/**
* The column <code>privdoc.FollowUpEvent.id</code>.
*/
public final TableField<FollowupeventRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>privdoc.FollowUpEvent.planId</code>.
*/
public final TableField<FollowupeventRecord, Integer> PLANID = createField("planId", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>privdoc.FollowUpEvent.eventId</code>.
*/
public final TableField<FollowupeventRecord, Integer> EVENTID = createField("eventId", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* Create a <code>privdoc.FollowUpEvent</code> table reference
*/
public Followupevent() {
this("FollowUpEvent", null);
}
/**
* Create an aliased <code>privdoc.FollowUpEvent</code> table reference
*/
public Followupevent(String alias) {
this(alias, FOLLOWUPEVENT);
}
private Followupevent(String alias, Table<FollowupeventRecord> aliased) {
this(alias, aliased, null);
}
private Followupevent(String alias, Table<FollowupeventRecord> aliased, Field<?>[] parameters) {
super(alias, Privdoc.PRIVDOC, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Identity<FollowupeventRecord, Integer> getIdentity() {
return Keys.IDENTITY_FOLLOWUPEVENT;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<FollowupeventRecord> getPrimaryKey() {
return Keys.KEY_FOLLOWUPEVENT_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<FollowupeventRecord>> getKeys() {
return Arrays.<UniqueKey<FollowupeventRecord>>asList(Keys.KEY_FOLLOWUPEVENT_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public Followupevent as(String alias) {
return new Followupevent(alias, this);
}
/**
* Rename this table
*/
public Followupevent rename(String name) {
return new Followupevent(name, null);
}
}
| 2,984 | 0.718834 | 0.714477 | 127 | 22.496063 | 29.577837 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.188976 | false | false | 2 |
b5f309adb2850d296fd1e8a78a851e52af6a218d | 35,734,127,917,290 | 4463b1a830082060959443b8da085910fe3e62fa | /app/src/main/java/com/ym/traegergill/db/bean/UserData.java | a35b7a74ac53e4f2ad7153334029ec10eaa8744a | []
| no_license | cmFodWx5YWRhdjEyMTA5/rectec | https://github.com/cmFodWx5YWRhdjEyMTA5/rectec | 6c6b2fe68f697d47c6b602091bb9f718ba2d952c | ed97d369f3e56907093b3a9feb771021786d5971 | refs/heads/master | 2020-05-02T03:31:11.969000 | 2017-12-13T03:10:00 | 2017-12-13T03:10:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ym.traegergill.db.bean;
/**
* Created by Administrator on 2017/10/26.
*/
public class UserData {
private int id;
private String user;
private int gill_range = 10;
private boolean flag = false;
private int probe_a_temp = 200;
private boolean a_temp_open = false;
private int probe_b_temp = 200;
private boolean b_temp_open = false;
private String dev_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getGill_range() {
return gill_range;
}
public void setGill_range(int gill_range) {
this.gill_range = gill_range;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getProbe_a_temp() {
return probe_a_temp;
}
public void setProbe_a_temp(int probe_a_temp) {
this.probe_a_temp = probe_a_temp;
}
public boolean isA_temp_open() {
return a_temp_open;
}
public void setA_temp_open(boolean a_temp_open) {
this.a_temp_open = a_temp_open;
}
public int getProbe_b_temp() {
return probe_b_temp;
}
public void setProbe_b_temp(int probe_b_temp) {
this.probe_b_temp = probe_b_temp;
}
public boolean isB_temp_open() {
return b_temp_open;
}
public void setB_temp_open(boolean b_temp_open) {
this.b_temp_open = b_temp_open;
}
public String getDev_id() {
return dev_id;
}
public void setDev_id(String dev_id) {
this.dev_id = dev_id;
}
}
| UTF-8 | Java | 1,773 | java | UserData.java | Java | [
{
"context": "age com.ym.traegergill.db.bean;\n\n/**\n * Created by Administrator on 2017/10/26.\n */\n\npublic class UserData {\n p",
"end": 68,
"score": 0.6337347030639648,
"start": 55,
"tag": "NAME",
"value": "Administrator"
}
]
| null | []
| package com.ym.traegergill.db.bean;
/**
* Created by Administrator on 2017/10/26.
*/
public class UserData {
private int id;
private String user;
private int gill_range = 10;
private boolean flag = false;
private int probe_a_temp = 200;
private boolean a_temp_open = false;
private int probe_b_temp = 200;
private boolean b_temp_open = false;
private String dev_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getGill_range() {
return gill_range;
}
public void setGill_range(int gill_range) {
this.gill_range = gill_range;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getProbe_a_temp() {
return probe_a_temp;
}
public void setProbe_a_temp(int probe_a_temp) {
this.probe_a_temp = probe_a_temp;
}
public boolean isA_temp_open() {
return a_temp_open;
}
public void setA_temp_open(boolean a_temp_open) {
this.a_temp_open = a_temp_open;
}
public int getProbe_b_temp() {
return probe_b_temp;
}
public void setProbe_b_temp(int probe_b_temp) {
this.probe_b_temp = probe_b_temp;
}
public boolean isB_temp_open() {
return b_temp_open;
}
public void setB_temp_open(boolean b_temp_open) {
this.b_temp_open = b_temp_open;
}
public String getDev_id() {
return dev_id;
}
public void setDev_id(String dev_id) {
this.dev_id = dev_id;
}
}
| 1,773 | 0.575296 | 0.566272 | 89 | 18.921349 | 16.753483 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314607 | false | false | 2 |
abf85c6a0e4ce4df3c253faf37299d72754810c3 | 35,588,099,042,064 | c6a700608bd105b10a4300b9c72ed5fddd871c01 | /CommonInfra-ejb/src/java/Common/session/CompanyManagementSessionBean.java | b9a8a6d8438921f2903757ce9158dc0f7919ddcd | []
| no_license | sunchongyang1/CommonInfra | https://github.com/sunchongyang1/CommonInfra | 47d66970248111a140eb2a4e86a518f582a6e19c | 8c5385027a1d63d12b270cbcd7ca945e206eae9d | refs/heads/master | 2021-01-15T22:29:26.462000 | 2014-09-17T07:33:26 | 2014-09-17T07:33:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 Common.session;
import Common.entity.Company;
import Common.entity.CustomerCompany;
import Common.entity.Department;
import Common.entity.PartnerCompany;
import Common.entity.Title;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import util.exception.CompanyExistException;
import util.exception.CompanyNotExistException;
import util.exception.DepartmentExistException;
import util.exception.DepartmentNotExistException;
/**
*
* @author chongyangsun
*/
@Stateless
public class CompanyManagementSessionBean implements CompanyManagementSessionBeanLocal {
@PersistenceContext
private EntityManager em;
@Override
public Company retrieveCompany(String companyName) throws CompanyNotExistException{
CustomerCompany ownerCompany = null;
Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1 and c.lockedOrNot=FALSE and c.deleteOrNot=FALSE");
query.setParameter(1, companyName);
ArrayList<CustomerCompany> ownerCompanyList = new ArrayList(query.getResultList());
if(ownerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyName+" does not exist!");
}
ownerCompany = ownerCompanyList.get(0);
return ownerCompany;
}
@Override
public Company retrieveCompany(Long companyId) throws CompanyNotExistException {
// CustomerCompany ownerCompany = null;
// Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1 and c.lockedOrnot=FALSE");
// query.setParameter(1, companyName);
// ArrayList<CustomerCompany> ownerCompanyList = new ArrayList(query.getResultList());
// if(ownerCompanyList.isEmpty()){
// throw new CompanyNotExistException("Company "+companyName+" does not exist!");
// }
// ownerCompany = ownerCompanyList.get(0);
// return ownerCompany;
Company company = em.find(Company.class, companyId);
System.out.println("The retrieved Company is " + company.getCompanyName());
if(company == null) {
throw new CompanyNotExistException("Company id: " + companyId + " does not exist!");
}
return company;
}
@Override
public CustomerCompany createCustomerCompany(String companyName, String companyType, String contactNo) throws CompanyExistException {
CustomerCompany customerCompany = null;
Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1");
query.setParameter(1, companyName);
ArrayList<CustomerCompany> customerCompanyList = new ArrayList(query.getResultList());
if(!customerCompanyList.isEmpty()){
customerCompany = customerCompanyList.get(0);
if(customerCompany.getDeleteOrNot()) {
throw new CompanyExistException("Company "+companyName+" is already exist and customer company is DELETED!");
}
throw new CompanyExistException("Company "+companyName+" is already exist!");
}
customerCompany = new CustomerCompany(companyName, companyType, contactNo);
em.persist(customerCompany);
em.flush();
System.out.println("In creating customer company - " + customerCompany.getCompanyName() + ", account ID: " + customerCompany.getId());
return customerCompany;
}
@Override
public CustomerCompany updateCustomerCompany(Long companyId, String companyName, String companyType, String contactNo) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1 and c.lockedOrNot=FALSE and c.deleteOrNot=FALSE");
query.setParameter(1, companyId);
ArrayList<CustomerCompany> customerCompanyList = new ArrayList(query.getResultList());
if(customerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyName+" does not exist!");
}
CustomerCompany customerCompany = customerCompanyList.get(0);
if (!customerCompany.getCompanyName().equals(companyName)) {
customerCompany.setCompanyName(companyName);
}
if (!customerCompany.getCompanyType().equals(companyType)) {
customerCompany.setCompanyType(companyType);
}
if (!customerCompany.getContactNo().equals(contactNo)) {
customerCompany.setContactNo(contactNo);
}
em.merge(customerCompany);
em.flush();
System.out.println("In updating customer company - " + customerCompany.getCompanyName() + ", account ID: " + customerCompany.getId());
return customerCompany;
}
@Override
public Boolean deleteCustomerCompany(Long companyId) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1");
query.setParameter(1, companyId);
ArrayList<CustomerCompany> customerCompanyList = new ArrayList(query.getResultList());
if(customerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyId+" does not exist!");
}
CustomerCompany customerCompany = customerCompanyList.get(0);
try {
customerCompany.setDeleteOrNot(Boolean.TRUE);
em.merge(customerCompany);
em.flush();
System.out.println("In deleting customer company - " + customerCompany.getCompanyName() + ", account ID: " + customerCompany.getId());
return Boolean.TRUE;
} catch(Exception e) {
return Boolean.FALSE;
}
}
@Override
public PartnerCompany createPartnerCompany(String companyName, String companyType, String contactNo) throws CompanyExistException {
PartnerCompany partnerCompany = null;
Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1");
query.setParameter(1, companyName);
ArrayList<PartnerCompany> partnerCompanyList = new ArrayList(query.getResultList());
if(!partnerCompanyList.isEmpty()){
partnerCompany = partnerCompanyList.get(0);
if(partnerCompany.getDeleteOrNot()) {
throw new CompanyExistException("Company "+companyName+" is already exist and partner company is DELETED!");
}
throw new CompanyExistException("Company "+companyName+" is already exist!");
}
partnerCompany = new PartnerCompany(companyName, companyType, contactNo);
em.persist(partnerCompany);
em.flush();
System.out.println("In creating partner company - " + partnerCompany.getCompanyName() + ", account ID: " + partnerCompany.getId());
return partnerCompany;
}
@Override
public PartnerCompany updatePartnerCompany(Long companyId, String companyName, String companyType, String contactNo) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1 and c.lockedOrNot=FALSE and c.deleteOrNot=FALSE");
query.setParameter(1, companyId);
ArrayList<PartnerCompany> partnerCompanyList = new ArrayList(query.getResultList());
if(partnerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyName+" does not exist!");
}
PartnerCompany partnerCompany = partnerCompanyList.get(0);
if (!partnerCompany.getCompanyName().equals(companyName)) {
partnerCompany.setCompanyName(companyName);
}
if (!partnerCompany.getCompanyType().equals(companyType)) {
partnerCompany.setCompanyType(companyType);
}
if (!partnerCompany.getContactNo().equals(contactNo)) {
partnerCompany.setContactNo(contactNo);
}
em.merge(partnerCompany);
em.flush();
System.out.println("In updating partner company - " + partnerCompany.getCompanyName() + ", account ID: " + partnerCompany.getId());
return partnerCompany;
}
@Override
public Boolean deletePartnerCompany(Long companyId) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1");
query.setParameter(1, companyId);
ArrayList<PartnerCompany> partnerCompanyList = new ArrayList(query.getResultList());
if(partnerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyId+" does not exist!");
}
PartnerCompany partnerCompany = partnerCompanyList.get(0);
try {
partnerCompany.setDeleteOrNot(Boolean.TRUE);
em.merge(partnerCompany);
em.flush();
System.out.println("In deleting customer company - " + partnerCompany.getCompanyName() + ", account ID: " + partnerCompany.getId());
return Boolean.TRUE;
} catch(Exception e) {
return Boolean.FALSE;
}
}
@Override
public Department createDepartment(String departmentName, Company company) throws DepartmentExistException {
Query query = em.createQuery("select d from Department d where d.departmentName=?1 and d.company=?2");
query.setParameter(1, departmentName);
query.setParameter(2, company);
ArrayList<Department> departmentList = new ArrayList(query.getResultList());
if(departmentList.isEmpty()) {
System.out.println("List is empty");
}
if(!departmentList.isEmpty()){
System.out.println("List is not empty");
throw new DepartmentExistException("Department " + departmentName + " for company " + company.getCompanyName() + " is already exist");
}
Department department = new Department(departmentName, company);
em.persist(department);
System.out.println("In creating department - " + department.getDepartmentName() + " for company " + company.getCompanyName());
return department;
}
@Override
public Boolean deleteDepartment(String departmentName, Company company) throws DepartmentNotExistException, CompanyNotExistException {
if(em.find(Company.class, company.getId()) == null)
throw new CompanyNotExistException("Company " + company.getCompanyName() + " does not exist!");
Query query = em.createQuery("select d from Department d where d.departmentName=?1 and d.company=?2");
query.setParameter(1, departmentName);
query.setParameter(2, company.getId());
ArrayList<Department> departmentList = new ArrayList(query.getResultList());
if(!departmentList.isEmpty()){
throw new DepartmentNotExistException("Department " + departmentName + " for company " + company.getCompanyName() + " does not already exist");
}
Department department = em.find(Department.class, departmentList.get(0).getId());
try {
em.remove(department);
em.flush();
System.out.println("In deleting department - " + department.getDepartmentName() + " for company " + company.getCompanyName());
return Boolean.TRUE;
} catch(Exception e) {
return Boolean.FALSE;
}
}
@Override
public void approveRequest(Long companyId, String companyType) {
if(companyType.equals("1PL")) {
CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
customerCompany.setApprovedOrNot(true);
List<Department> departmentList = customerCompany.getDepartment();
for(Department d: departmentList) {
d.setApprovedOrNot(true);
List<Title> titleList = d.getTitles();
for(Title t: titleList) {
t.setApprovedOrNot(true);
if(!t.getUser().isEmpty()) {
t.getUser().get(0).setApprovedOrNot(true);
}
}
}
}
}
}
| UTF-8 | Java | 12,728 | java | CompanyManagementSessionBean.java | Java | [
{
"context": "on.DepartmentNotExistException;\n\n/**\n *\n * @author chongyangsun\n */\n@Stateless\npublic class CompanyManagementSess",
"end": 796,
"score": 0.9995930194854736,
"start": 784,
"tag": "USERNAME",
"value": "chongyangsun"
}
]
| null | []
| /*
* 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 Common.session;
import Common.entity.Company;
import Common.entity.CustomerCompany;
import Common.entity.Department;
import Common.entity.PartnerCompany;
import Common.entity.Title;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import util.exception.CompanyExistException;
import util.exception.CompanyNotExistException;
import util.exception.DepartmentExistException;
import util.exception.DepartmentNotExistException;
/**
*
* @author chongyangsun
*/
@Stateless
public class CompanyManagementSessionBean implements CompanyManagementSessionBeanLocal {
@PersistenceContext
private EntityManager em;
@Override
public Company retrieveCompany(String companyName) throws CompanyNotExistException{
CustomerCompany ownerCompany = null;
Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1 and c.lockedOrNot=FALSE and c.deleteOrNot=FALSE");
query.setParameter(1, companyName);
ArrayList<CustomerCompany> ownerCompanyList = new ArrayList(query.getResultList());
if(ownerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyName+" does not exist!");
}
ownerCompany = ownerCompanyList.get(0);
return ownerCompany;
}
@Override
public Company retrieveCompany(Long companyId) throws CompanyNotExistException {
// CustomerCompany ownerCompany = null;
// Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1 and c.lockedOrnot=FALSE");
// query.setParameter(1, companyName);
// ArrayList<CustomerCompany> ownerCompanyList = new ArrayList(query.getResultList());
// if(ownerCompanyList.isEmpty()){
// throw new CompanyNotExistException("Company "+companyName+" does not exist!");
// }
// ownerCompany = ownerCompanyList.get(0);
// return ownerCompany;
Company company = em.find(Company.class, companyId);
System.out.println("The retrieved Company is " + company.getCompanyName());
if(company == null) {
throw new CompanyNotExistException("Company id: " + companyId + " does not exist!");
}
return company;
}
@Override
public CustomerCompany createCustomerCompany(String companyName, String companyType, String contactNo) throws CompanyExistException {
CustomerCompany customerCompany = null;
Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1");
query.setParameter(1, companyName);
ArrayList<CustomerCompany> customerCompanyList = new ArrayList(query.getResultList());
if(!customerCompanyList.isEmpty()){
customerCompany = customerCompanyList.get(0);
if(customerCompany.getDeleteOrNot()) {
throw new CompanyExistException("Company "+companyName+" is already exist and customer company is DELETED!");
}
throw new CompanyExistException("Company "+companyName+" is already exist!");
}
customerCompany = new CustomerCompany(companyName, companyType, contactNo);
em.persist(customerCompany);
em.flush();
System.out.println("In creating customer company - " + customerCompany.getCompanyName() + ", account ID: " + customerCompany.getId());
return customerCompany;
}
@Override
public CustomerCompany updateCustomerCompany(Long companyId, String companyName, String companyType, String contactNo) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1 and c.lockedOrNot=FALSE and c.deleteOrNot=FALSE");
query.setParameter(1, companyId);
ArrayList<CustomerCompany> customerCompanyList = new ArrayList(query.getResultList());
if(customerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyName+" does not exist!");
}
CustomerCompany customerCompany = customerCompanyList.get(0);
if (!customerCompany.getCompanyName().equals(companyName)) {
customerCompany.setCompanyName(companyName);
}
if (!customerCompany.getCompanyType().equals(companyType)) {
customerCompany.setCompanyType(companyType);
}
if (!customerCompany.getContactNo().equals(contactNo)) {
customerCompany.setContactNo(contactNo);
}
em.merge(customerCompany);
em.flush();
System.out.println("In updating customer company - " + customerCompany.getCompanyName() + ", account ID: " + customerCompany.getId());
return customerCompany;
}
@Override
public Boolean deleteCustomerCompany(Long companyId) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1");
query.setParameter(1, companyId);
ArrayList<CustomerCompany> customerCompanyList = new ArrayList(query.getResultList());
if(customerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyId+" does not exist!");
}
CustomerCompany customerCompany = customerCompanyList.get(0);
try {
customerCompany.setDeleteOrNot(Boolean.TRUE);
em.merge(customerCompany);
em.flush();
System.out.println("In deleting customer company - " + customerCompany.getCompanyName() + ", account ID: " + customerCompany.getId());
return Boolean.TRUE;
} catch(Exception e) {
return Boolean.FALSE;
}
}
@Override
public PartnerCompany createPartnerCompany(String companyName, String companyType, String contactNo) throws CompanyExistException {
PartnerCompany partnerCompany = null;
Query query = em.createQuery("select c from CustomerCompany c where c.companyName=?1");
query.setParameter(1, companyName);
ArrayList<PartnerCompany> partnerCompanyList = new ArrayList(query.getResultList());
if(!partnerCompanyList.isEmpty()){
partnerCompany = partnerCompanyList.get(0);
if(partnerCompany.getDeleteOrNot()) {
throw new CompanyExistException("Company "+companyName+" is already exist and partner company is DELETED!");
}
throw new CompanyExistException("Company "+companyName+" is already exist!");
}
partnerCompany = new PartnerCompany(companyName, companyType, contactNo);
em.persist(partnerCompany);
em.flush();
System.out.println("In creating partner company - " + partnerCompany.getCompanyName() + ", account ID: " + partnerCompany.getId());
return partnerCompany;
}
@Override
public PartnerCompany updatePartnerCompany(Long companyId, String companyName, String companyType, String contactNo) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1 and c.lockedOrNot=FALSE and c.deleteOrNot=FALSE");
query.setParameter(1, companyId);
ArrayList<PartnerCompany> partnerCompanyList = new ArrayList(query.getResultList());
if(partnerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyName+" does not exist!");
}
PartnerCompany partnerCompany = partnerCompanyList.get(0);
if (!partnerCompany.getCompanyName().equals(companyName)) {
partnerCompany.setCompanyName(companyName);
}
if (!partnerCompany.getCompanyType().equals(companyType)) {
partnerCompany.setCompanyType(companyType);
}
if (!partnerCompany.getContactNo().equals(contactNo)) {
partnerCompany.setContactNo(contactNo);
}
em.merge(partnerCompany);
em.flush();
System.out.println("In updating partner company - " + partnerCompany.getCompanyName() + ", account ID: " + partnerCompany.getId());
return partnerCompany;
}
@Override
public Boolean deletePartnerCompany(Long companyId) throws CompanyNotExistException {
// CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
Query query = em.createQuery("select c from CustomerCompany c where c.id=?1");
query.setParameter(1, companyId);
ArrayList<PartnerCompany> partnerCompanyList = new ArrayList(query.getResultList());
if(partnerCompanyList.isEmpty()){
throw new CompanyNotExistException("Company "+companyId+" does not exist!");
}
PartnerCompany partnerCompany = partnerCompanyList.get(0);
try {
partnerCompany.setDeleteOrNot(Boolean.TRUE);
em.merge(partnerCompany);
em.flush();
System.out.println("In deleting customer company - " + partnerCompany.getCompanyName() + ", account ID: " + partnerCompany.getId());
return Boolean.TRUE;
} catch(Exception e) {
return Boolean.FALSE;
}
}
@Override
public Department createDepartment(String departmentName, Company company) throws DepartmentExistException {
Query query = em.createQuery("select d from Department d where d.departmentName=?1 and d.company=?2");
query.setParameter(1, departmentName);
query.setParameter(2, company);
ArrayList<Department> departmentList = new ArrayList(query.getResultList());
if(departmentList.isEmpty()) {
System.out.println("List is empty");
}
if(!departmentList.isEmpty()){
System.out.println("List is not empty");
throw new DepartmentExistException("Department " + departmentName + " for company " + company.getCompanyName() + " is already exist");
}
Department department = new Department(departmentName, company);
em.persist(department);
System.out.println("In creating department - " + department.getDepartmentName() + " for company " + company.getCompanyName());
return department;
}
@Override
public Boolean deleteDepartment(String departmentName, Company company) throws DepartmentNotExistException, CompanyNotExistException {
if(em.find(Company.class, company.getId()) == null)
throw new CompanyNotExistException("Company " + company.getCompanyName() + " does not exist!");
Query query = em.createQuery("select d from Department d where d.departmentName=?1 and d.company=?2");
query.setParameter(1, departmentName);
query.setParameter(2, company.getId());
ArrayList<Department> departmentList = new ArrayList(query.getResultList());
if(!departmentList.isEmpty()){
throw new DepartmentNotExistException("Department " + departmentName + " for company " + company.getCompanyName() + " does not already exist");
}
Department department = em.find(Department.class, departmentList.get(0).getId());
try {
em.remove(department);
em.flush();
System.out.println("In deleting department - " + department.getDepartmentName() + " for company " + company.getCompanyName());
return Boolean.TRUE;
} catch(Exception e) {
return Boolean.FALSE;
}
}
@Override
public void approveRequest(Long companyId, String companyType) {
if(companyType.equals("1PL")) {
CustomerCompany customerCompany = em.find(CustomerCompany.class, companyId);
customerCompany.setApprovedOrNot(true);
List<Department> departmentList = customerCompany.getDepartment();
for(Department d: departmentList) {
d.setApprovedOrNot(true);
List<Title> titleList = d.getTitles();
for(Title t: titleList) {
t.setApprovedOrNot(true);
if(!t.getUser().isEmpty()) {
t.getUser().get(0).setApprovedOrNot(true);
}
}
}
}
}
}
| 12,728 | 0.671669 | 0.668919 | 260 | 47.953846 | 39.403313 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719231 | false | false | 2 |
e1036286da741283c02411ef105e0fec19f2fd9e | 35,330,401,007,144 | 30d5a4e2fc16ee3ad2b5314783610168002f5e05 | /exemplehibernate/src/main/java/fr/treeptik/Maison.java | 7d8cd136f57e2e24e79483cd7d5a5bac1f14cf86 | []
| no_license | aymen2255/tp-hibernate | https://github.com/aymen2255/tp-hibernate | 4714288a8b6ce4562cebec07d3b95d0d0714d550 | 0a8c8400badb3d8f107c677ad7aba1f2cbf1f19a | refs/heads/master | 2016-09-06T12:11:49.849000 | 2014-11-20T12:46:12 | 2014-11-20T12:46:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.treeptik;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class Maison {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer Id;
private long superficie;
public Maison(){
}
/**
* @param id
* @param superficie
*/
public Maison(Integer id, long superficie) {
super();
Id = id;
this.setSuperficie(superficie);
}
public long getSuperficie() {
return superficie;
}
public void setSuperficie(long superficie) {
this.superficie = superficie;
}
}
| UTF-8 | Java | 614 | java | Maison.java | Java | []
| null | []
| package fr.treeptik;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class Maison {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer Id;
private long superficie;
public Maison(){
}
/**
* @param id
* @param superficie
*/
public Maison(Integer id, long superficie) {
super();
Id = id;
this.setSuperficie(superficie);
}
public long getSuperficie() {
return superficie;
}
public void setSuperficie(long superficie) {
this.superficie = superficie;
}
}
| 614 | 0.716612 | 0.716612 | 40 | 14.35 | 15.204522 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 2 |
97a2e597ec46d7bb035b03f57e5c3cd50a780710 | 36,120,674,976,408 | 4f7901f085ca968a6fd01fc5c7501692adfe17e0 | /src/com/practice/programming/KTHSMALLESTELEMENT.java | cacd6a9c577de4f905ec4a0cd6c1c3128b6116f0 | []
| no_license | asifazamali/programming_practice | https://github.com/asifazamali/programming_practice | ca61626edf479c27edb0b6ba7f93b7a7345ef67e | 8255302eabd57ada5d46339c9cd22f7b00abaa5a | refs/heads/master | 2020-05-30T15:27:52.256000 | 2019-06-02T12:35:45 | 2019-06-02T12:35:45 | 189,819,847 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.practice.programming;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Heap{
ArrayList<Integer> arrayList;
int heapSize;
Heap(ArrayList<Integer> arrayList) {
this.arrayList = arrayList;
this.heapSize = arrayList.size();
System.out.println(arrayList);
}
public int getParent(int i) {
return ((i - 1) / 2);
}
public int getLeft(int i) {
return (i * 2 + 1);
}
public int getRight(int i) {
return (i * 2 + 2);
}
public void heapify(int i) {
// System.out.println(i);
int smallest = i;
int left = getLeft(i);
int right = getRight(i);
if (left < heapSize && arrayList.get(left) < arrayList.get(smallest))
smallest = left;
if(right < heapSize && arrayList.get(right) < arrayList.get(smallest))
smallest = right;
if(smallest != i) {
swap(i, smallest);
heapify(smallest);
}
}
public void swap(int i, int j) {
int temp = arrayList.get(i);
arrayList.set(i, arrayList.get(j));
arrayList.set(j, temp);
}
public int getMin() {
int temp = arrayList.get(0);
swap(0, heapSize -1 );
heapSize--;
heapify(0);
return temp;
}
public void minHeap() {
int i = (heapSize /2) -1;
while( i >= 0) {
heapify(i);
i--;
}
}
}
public class KTHSMALLESTELEMENT {
public static void main(String[] args) throws IOException {
// ArrayList<Integer> list = new ArrayList<>(Arrays.asList(8, 10, 4, 3, 20, 15));
// int k = 3;
// System.out.println(kthSmallestElt(list,k));
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// int T = Integer.parseInt(reader.readLine());
// while(T-- > 0) {
// int n = Integer.parseInt(reader.readLine());
// ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(reader.readLine().split(" ")));
// arrayList.forEach(x -> list.add(Integer.parseInt(x)));
// int k = Integer.parseInt(reader.readLine());
// System.out.println(kthSmallestElt(list,k));
// }
}
private static int kthSmallestElt(ArrayList<Integer> arrayList, int k) {
Heap heap = new Heap(arrayList);
heap.minHeap();
int kminn = -1;
for(int i = 0; i <k; i++) {
kminn = heap.getMin();
System.out.println(kminn);
}
return kminn;
}
}
| UTF-8 | Java | 2,635 | java | KTHSMALLESTELEMENT.java | Java | []
| null | []
| package com.practice.programming;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Heap{
ArrayList<Integer> arrayList;
int heapSize;
Heap(ArrayList<Integer> arrayList) {
this.arrayList = arrayList;
this.heapSize = arrayList.size();
System.out.println(arrayList);
}
public int getParent(int i) {
return ((i - 1) / 2);
}
public int getLeft(int i) {
return (i * 2 + 1);
}
public int getRight(int i) {
return (i * 2 + 2);
}
public void heapify(int i) {
// System.out.println(i);
int smallest = i;
int left = getLeft(i);
int right = getRight(i);
if (left < heapSize && arrayList.get(left) < arrayList.get(smallest))
smallest = left;
if(right < heapSize && arrayList.get(right) < arrayList.get(smallest))
smallest = right;
if(smallest != i) {
swap(i, smallest);
heapify(smallest);
}
}
public void swap(int i, int j) {
int temp = arrayList.get(i);
arrayList.set(i, arrayList.get(j));
arrayList.set(j, temp);
}
public int getMin() {
int temp = arrayList.get(0);
swap(0, heapSize -1 );
heapSize--;
heapify(0);
return temp;
}
public void minHeap() {
int i = (heapSize /2) -1;
while( i >= 0) {
heapify(i);
i--;
}
}
}
public class KTHSMALLESTELEMENT {
public static void main(String[] args) throws IOException {
// ArrayList<Integer> list = new ArrayList<>(Arrays.asList(8, 10, 4, 3, 20, 15));
// int k = 3;
// System.out.println(kthSmallestElt(list,k));
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// int T = Integer.parseInt(reader.readLine());
// while(T-- > 0) {
// int n = Integer.parseInt(reader.readLine());
// ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(reader.readLine().split(" ")));
// arrayList.forEach(x -> list.add(Integer.parseInt(x)));
// int k = Integer.parseInt(reader.readLine());
// System.out.println(kthSmallestElt(list,k));
// }
}
private static int kthSmallestElt(ArrayList<Integer> arrayList, int k) {
Heap heap = new Heap(arrayList);
heap.minHeap();
int kminn = -1;
for(int i = 0; i <k; i++) {
kminn = heap.getMin();
System.out.println(kminn);
}
return kminn;
}
}
| 2,635 | 0.552182 | 0.542315 | 98 | 25.887754 | 22.523403 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 2 |
6abe807324b90fde53c2cdbb98bd1c8984a0ab52 | 19,069,654,861,283 | ec755585a66c1781e9260a0b158e0414e763ff93 | /src/main/java/com/fengyaodong/bloan/model/domain/UserMsgDomain.java | 9f6a009a7a7fb75226d1b5d035ec5927d21dec8e | []
| no_license | yangyining/Springboot-vue | https://github.com/yangyining/Springboot-vue | 60c2b688d07d5c03f09ac5e416bacee7f415750b | 70657b1007ca96dc07075d1a8b213f3fbd68c2ec | refs/heads/master | 2020-07-24T12:53:25.953000 | 2019-07-05T07:16:45 | 2019-07-05T07:16:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fengyaodong.bloan.model.domain;
import com.fengyaodong.bloan.common.codehandler.MsgTypeHandler;
import com.fengyaodong.bloan.common.codehandler.ReadHandler;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* 用户消息Domain
*
* @author: feng_yd[740195680@qq.com]
* @date: 2019/3/10 16:59
* @version: V1.0
* @review: feng_yd[740195680@qq.com]/2019/3/10 16:59
*/
@ApiModel
@Data
@Accessors(chain = true)
public class UserMsgDomain implements Serializable, ReadHandler, MsgTypeHandler {
private static final long serialVersionUID = 1L;
@ApiModelProperty("消息ID")
private String msgId;
@ApiModelProperty("用户ID")
private String userId;
@ApiModelProperty("账单号")
private String billNo;
@ApiModelProperty("消息类型 0:还款提醒 1:扣款提醒 2:逾期提醒")
private String msgType;
@ApiModelProperty("消息内容")
private String msgContent;
@ApiModelProperty("是否阅读 0:否 1:是")
private String isRead;
@ApiModelProperty("创建时间")
private Date createDate;
@Override
public String getReadHandlerCode() {
return this.getIsRead();
}
@Override
public void setReadHandlerText(String text) {
this.setIsRead(text);
}
@Override
public String getMsgTypeHandlerCode() {
return this.getMsgType();
}
@Override
public void setMsgTypeHandlerText(String text) {
this.setMsgType(text);
}
}
| UTF-8 | Java | 1,642 | java | UserMsgDomain.java | Java | [
{
"context": " java.util.Date;\n\n/**\n * 用户消息Domain\n *\n * @author: feng_yd[740195680@qq.com]\n * @date: 2019/3/10 16:59\n * @v",
"end": 410,
"score": 0.9991503953933716,
"start": 403,
"tag": "USERNAME",
"value": "feng_yd"
},
{
"context": "l.Date;\n\n/**\n * 用户消息Domain\n *\n * @author: feng_yd[740195680@qq.com]\n * @date: 2019/3/10 16:59\n * @version: V1.0\n * @",
"end": 427,
"score": 0.9999062418937683,
"start": 411,
"tag": "EMAIL",
"value": "740195680@qq.com"
},
{
"context": "/3/10 16:59\n * @version: V1.0\n * @review: feng_yd[740195680@qq.com]/2019/3/10 16:59\n */\n@ApiModel\n@Data\n@Accessors(c",
"end": 509,
"score": 0.9998733997344971,
"start": 493,
"tag": "EMAIL",
"value": "740195680@qq.com"
}
]
| null | []
| package com.fengyaodong.bloan.model.domain;
import com.fengyaodong.bloan.common.codehandler.MsgTypeHandler;
import com.fengyaodong.bloan.common.codehandler.ReadHandler;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* 用户消息Domain
*
* @author: feng_yd[<EMAIL>]
* @date: 2019/3/10 16:59
* @version: V1.0
* @review: feng_yd[<EMAIL>]/2019/3/10 16:59
*/
@ApiModel
@Data
@Accessors(chain = true)
public class UserMsgDomain implements Serializable, ReadHandler, MsgTypeHandler {
private static final long serialVersionUID = 1L;
@ApiModelProperty("消息ID")
private String msgId;
@ApiModelProperty("用户ID")
private String userId;
@ApiModelProperty("账单号")
private String billNo;
@ApiModelProperty("消息类型 0:还款提醒 1:扣款提醒 2:逾期提醒")
private String msgType;
@ApiModelProperty("消息内容")
private String msgContent;
@ApiModelProperty("是否阅读 0:否 1:是")
private String isRead;
@ApiModelProperty("创建时间")
private Date createDate;
@Override
public String getReadHandlerCode() {
return this.getIsRead();
}
@Override
public void setReadHandlerText(String text) {
this.setIsRead(text);
}
@Override
public String getMsgTypeHandlerCode() {
return this.getMsgType();
}
@Override
public void setMsgTypeHandlerText(String text) {
this.setMsgType(text);
}
}
| 1,624 | 0.707742 | 0.676774 | 68 | 21.794117 | 19.306017 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.338235 | false | false | 2 |
f82ae65082a5fd31da0e336cd039ce769997e8e2 | 15,831,249,516,366 | d30d45556e8523ea94cc0300485a87fa13337523 | /Solution1/app/src/main/java/com/clean/sharednode/solution1/presenters/HomePresenter.java | b4e88495184697ee57c970455e45b08a26c52acb | [
"MIT"
]
| permissive | fmendes6/Mono2Clean-V1 | https://github.com/fmendes6/Mono2Clean-V1 | 209440ba84a6cbefbeb66fe1ed9d5f9390cba283 | 79f5d1e0eead3eb0d9820bf098f0efaf85162c1e | refs/heads/master | 2021-01-10T11:42:35.803000 | 2016-03-21T09:41:22 | 2016-03-21T09:41:22 | 54,345,896 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.clean.sharednode.solution1.presenters;
import com.clean.sharednode.solution1.model.Comment;
import com.clean.sharednode.solution1.model.Post;
import com.clean.sharednode.solution1.presenters.rest.ApiProvider;
import com.clean.sharednode.solution1.presenters.rest.PostApi;
import com.clean.sharednode.solution1.view.IHomeView;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class HomePresenter {
private PostApi mApi;
private IHomeView mView;
public HomePresenter(IHomeView view) {
mApi = ApiProvider.getApi().create(PostApi.class);
mView = view;
}
public void loadPost(final int postId){
mApi.getPostById(postId, new Callback<Post>() {
public void success(Post post, Response response) {
mView.onPostLoaded(post);
}
@Override
public void failure(RetrofitError error) {
mView.onError(error.getMessage());
}
});
}
public void loadComments(int postId){
mApi.getPostComments(postId, new Callback<List<Comment>>() {
@Override
public void success(List<Comment> commentList, Response response) {
mView.onCommentsLoaded(commentList);
}
@Override
public void failure(RetrofitError error) {
mView.onError(error.getMessage());
}
});
}
}
| UTF-8 | Java | 1,499 | java | HomePresenter.java | Java | []
| null | []
| package com.clean.sharednode.solution1.presenters;
import com.clean.sharednode.solution1.model.Comment;
import com.clean.sharednode.solution1.model.Post;
import com.clean.sharednode.solution1.presenters.rest.ApiProvider;
import com.clean.sharednode.solution1.presenters.rest.PostApi;
import com.clean.sharednode.solution1.view.IHomeView;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class HomePresenter {
private PostApi mApi;
private IHomeView mView;
public HomePresenter(IHomeView view) {
mApi = ApiProvider.getApi().create(PostApi.class);
mView = view;
}
public void loadPost(final int postId){
mApi.getPostById(postId, new Callback<Post>() {
public void success(Post post, Response response) {
mView.onPostLoaded(post);
}
@Override
public void failure(RetrofitError error) {
mView.onError(error.getMessage());
}
});
}
public void loadComments(int postId){
mApi.getPostComments(postId, new Callback<List<Comment>>() {
@Override
public void success(List<Comment> commentList, Response response) {
mView.onCommentsLoaded(commentList);
}
@Override
public void failure(RetrofitError error) {
mView.onError(error.getMessage());
}
});
}
}
| 1,499 | 0.647098 | 0.643095 | 53 | 27.283018 | 23.343519 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45283 | false | false | 2 |
d756569a73636f09a1e2c34322a86d61ff700c25 | 34,144,990,042,276 | 01ea7445bac78a067787264340654a036b147b26 | /Cypda/src/main/java/com/xs/fastcy/cypda/fragment/ggxx/GgxxSelectDataConverter.java | 17604d864076c8db2f8e99fa7f2e4c3625c5f425 | []
| no_license | blind20/FastCy | https://github.com/blind20/FastCy | 451c1cc931e50eeaba2b430acee210c2adf3fedf | a017c9bc1b349a76927b9fb1592861196d1fc582 | refs/heads/master | 2020-04-16T07:56:09.313000 | 2019-02-20T03:07:42 | 2019-02-20T03:07:42 | 165,404,610 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xs.fastcy.cypda.fragment.ggxx;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flj.latte.ui.recycler.DataConverter;
import com.flj.latte.ui.recycler.MultipleFields;
import com.flj.latte.ui.recycler.MultipleItemEntity;
import com.xs.fastcy.cypda.fragment.VehItemType;
import com.xs.fastcy.cypda.util.ToolUtil;
import java.util.ArrayList;
public class GgxxSelectDataConverter extends DataConverter {
@Override
public ArrayList<MultipleItemEntity> convert() {
final JSONArray array = JSON.parseArray(getJsonData());
final int size = array.size();
for (int i = 0; i < size; i++) {
final JSONObject jo = array.getJSONObject(i);
if (jo != null && !jo.isEmpty()) {
String bh = jo.getString("BH");
String clxh = jo.getString("CLXH");
String ggrq = jo.getString("GGRQ");
if (ToolUtil.isEmpty(bh)|| ToolUtil.isEmpty(clxh)|| ToolUtil.isEmpty(ggrq)) {
break;
}
final MultipleItemEntity entity = MultipleItemEntity.builder()
.setField(MultipleFields.ITEM_TYPE, VehItemType.ITEM_GGXX_SELECT)
.setField(MultipleFields.ID, i + 1)
.setField(GgxxSelectItemFields.ITEM_GGBH, bh)
.setField(GgxxSelectItemFields.ITEM_CLXH, clxh)
.setField(GgxxSelectItemFields.ITEM_GGRQ, ggrq)
.setField(GgxxSelectItemFields.ITEM_GGXX_JSON,jo)
.build();
ENTITIES.add(entity);
}
}
return ENTITIES;
}
}
| UTF-8 | Java | 1,742 | java | GgxxSelectDataConverter.java | Java | []
| null | []
| package com.xs.fastcy.cypda.fragment.ggxx;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flj.latte.ui.recycler.DataConverter;
import com.flj.latte.ui.recycler.MultipleFields;
import com.flj.latte.ui.recycler.MultipleItemEntity;
import com.xs.fastcy.cypda.fragment.VehItemType;
import com.xs.fastcy.cypda.util.ToolUtil;
import java.util.ArrayList;
public class GgxxSelectDataConverter extends DataConverter {
@Override
public ArrayList<MultipleItemEntity> convert() {
final JSONArray array = JSON.parseArray(getJsonData());
final int size = array.size();
for (int i = 0; i < size; i++) {
final JSONObject jo = array.getJSONObject(i);
if (jo != null && !jo.isEmpty()) {
String bh = jo.getString("BH");
String clxh = jo.getString("CLXH");
String ggrq = jo.getString("GGRQ");
if (ToolUtil.isEmpty(bh)|| ToolUtil.isEmpty(clxh)|| ToolUtil.isEmpty(ggrq)) {
break;
}
final MultipleItemEntity entity = MultipleItemEntity.builder()
.setField(MultipleFields.ITEM_TYPE, VehItemType.ITEM_GGXX_SELECT)
.setField(MultipleFields.ID, i + 1)
.setField(GgxxSelectItemFields.ITEM_GGBH, bh)
.setField(GgxxSelectItemFields.ITEM_CLXH, clxh)
.setField(GgxxSelectItemFields.ITEM_GGRQ, ggrq)
.setField(GgxxSelectItemFields.ITEM_GGXX_JSON,jo)
.build();
ENTITIES.add(entity);
}
}
return ENTITIES;
}
}
| 1,742 | 0.603904 | 0.602755 | 41 | 41.487804 | 24.205545 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.780488 | false | false | 2 |
6ee278fdb23a96c9d12872be6633c02ad29aa4c1 | 34,144,990,040,346 | 53d677a55e4ece8883526738f1c9d00fa6560ff7 | /com/tencent/mm/plugin/recharge/model/a.java | 65c490c39a3059aaaeb322a0bdc4314cdc9e3672 | []
| no_license | 0jinxing/wechat-apk-source | https://github.com/0jinxing/wechat-apk-source | 544c2d79bfc10261eb36389c1edfdf553d8f312a | f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d | refs/heads/master | 2020-06-07T20:06:03.580000 | 2019-06-21T09:17:26 | 2019-06-21T09:17:26 | 193,069,132 | 9 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.mm.plugin.recharge.model;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.sdk.platformtools.ab;
import com.tencent.mm.sdk.platformtools.bo;
import org.json.JSONException;
import org.json.JSONObject;
public final class a
{
public static final int[] pFK = { -1, -1 };
public static final int[] pFL = { -2, -2 };
public int cvp;
public String name;
public String pFM;
public String pFN;
public int[] pFO = pFK;
public a(String paramString1, String paramString2, int paramInt)
{
this(paramString1, paramString2, "", paramInt);
}
public a(String paramString1, String paramString2, String paramString3, int paramInt)
{
this.pFM = paramString1;
this.name = paramString2;
this.pFN = paramString3;
this.cvp = paramInt;
}
public static a aj(JSONObject paramJSONObject)
{
AppMethodBeat.i(44182);
String str1 = paramJSONObject.optString("name");
String str2 = paramJSONObject.optString("record");
paramJSONObject = paramJSONObject.optString("location");
if (!bo.isNullOrNil(str2))
{
paramJSONObject = new a(str2, str1, paramJSONObject, 2);
AppMethodBeat.o(44182);
}
while (true)
{
return paramJSONObject;
paramJSONObject = null;
AppMethodBeat.o(44182);
}
}
public final JSONObject toJson()
{
AppMethodBeat.i(44181);
JSONObject localJSONObject = new JSONObject();
try
{
localJSONObject.put("record", bo.bc(this.pFM, ""));
localJSONObject.put("name", bo.bc(this.name, ""));
localJSONObject.put("location", bo.bc(this.pFN, ""));
AppMethodBeat.o(44181);
return localJSONObject;
}
catch (JSONException localJSONException)
{
while (true)
{
ab.printErrStackTrace("MicroMsg.MallInputRecord", localJSONException, "", new Object[0]);
Object localObject = null;
AppMethodBeat.o(44181);
}
}
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes7-dex2jar.jar
* Qualified Name: com.tencent.mm.plugin.recharge.model.a
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 2,240 | java | a.java | Java | []
| null | []
| package com.tencent.mm.plugin.recharge.model;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.sdk.platformtools.ab;
import com.tencent.mm.sdk.platformtools.bo;
import org.json.JSONException;
import org.json.JSONObject;
public final class a
{
public static final int[] pFK = { -1, -1 };
public static final int[] pFL = { -2, -2 };
public int cvp;
public String name;
public String pFM;
public String pFN;
public int[] pFO = pFK;
public a(String paramString1, String paramString2, int paramInt)
{
this(paramString1, paramString2, "", paramInt);
}
public a(String paramString1, String paramString2, String paramString3, int paramInt)
{
this.pFM = paramString1;
this.name = paramString2;
this.pFN = paramString3;
this.cvp = paramInt;
}
public static a aj(JSONObject paramJSONObject)
{
AppMethodBeat.i(44182);
String str1 = paramJSONObject.optString("name");
String str2 = paramJSONObject.optString("record");
paramJSONObject = paramJSONObject.optString("location");
if (!bo.isNullOrNil(str2))
{
paramJSONObject = new a(str2, str1, paramJSONObject, 2);
AppMethodBeat.o(44182);
}
while (true)
{
return paramJSONObject;
paramJSONObject = null;
AppMethodBeat.o(44182);
}
}
public final JSONObject toJson()
{
AppMethodBeat.i(44181);
JSONObject localJSONObject = new JSONObject();
try
{
localJSONObject.put("record", bo.bc(this.pFM, ""));
localJSONObject.put("name", bo.bc(this.name, ""));
localJSONObject.put("location", bo.bc(this.pFN, ""));
AppMethodBeat.o(44181);
return localJSONObject;
}
catch (JSONException localJSONException)
{
while (true)
{
ab.printErrStackTrace("MicroMsg.MallInputRecord", localJSONException, "", new Object[0]);
Object localObject = null;
AppMethodBeat.o(44181);
}
}
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes7-dex2jar.jar
* Qualified Name: com.tencent.mm.plugin.recharge.model.a
* JD-Core Version: 0.6.2
*/ | 2,240 | 0.643304 | 0.616518 | 78 | 26.743589 | 24.310194 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75641 | false | false | 2 |
8c2d843dd007f377e908d378988b05ec0690c389 | 17,154,099,411,200 | 0a0fc22d5b6fe0901a048fd136a73d9345da5102 | /smeEnterprise-ear-web/src/main/java/za/co/smeEnterprise/tool/ToolController.java | 7f844d8eb5cc5252f87e0018a09cf96c202a632c | []
| no_license | inboxtrevorjohnson/smeEnterprise-ear | https://github.com/inboxtrevorjohnson/smeEnterprise-ear | ec0f98a7678ce1306d4f3eab9b4b52de89b44431 | 726c1e23c607ca7ea2c6570c246739ff4f2aeaad | refs/heads/master | 2018-09-12T18:23:54.302000 | 2018-08-01T11:25:12 | 2018-08-01T11:25:12 | 84,197,560 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package za.co.smeEnterprise.tool;
import org.primefaces.model.StreamedContent;
import za.co.smeEnterprise.exception.CreationException;
import za.co.smeEnterprise.exception.ModificationException;
import za.co.smeEnterprise.exception.RemovalException;
import za.co.smeEnterprise.exception.RetrievalException;
import za.co.smeEnterprise.organisation.ToolFilter;
import za.co.smeEnterprise.print.PrintController;
import za.co.smeEnterprise.safety.EmployeePPEItem;
import za.co.smeEnterprise.session.tool.ToolMaintenanceLocalBusiness;
import za.co.smeEnterprise.utility.DateOperations;
import za.co.smeEnterprise.utility.TabViewController;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
/**
* The <code>ToolController</code> is used as a 'controller' to
* manage creation, modification and removal of <code>Tool</code>s
* using the respective session bean.
*
* @author <a href="mailto:trljohnson@mweb.co.za">ALR</a>
*/
@ManagedBean(eager=true)
@SessionScoped
public class ToolController extends TabViewController implements Serializable{
private static final Logger logger = Logger.getLogger("@@@ Tool Controller");
private Tool tool;
private ToolState toolState;
@ManagedProperty(value="#{printController}")
PrintController printController;
private ToolManufacturer toolManufacturer;
@ManagedProperty(value="#{toolFilter}")
ToolFilter toolFilter;
@EJB
private ToolMaintenanceLocalBusiness toolMaintenanceLocalBusiness;
public ToolController(){
logger.info("Creating a new tool controller");
}
public String insertTool(){
setCurrentAction(ACTION_ADDING);
setTool(new Tool());
return "addChangeTool";
}
public String addTool() throws Exception{
try{
toolMaintenanceLocalBusiness.addTool(tool);
toolFilter.filterList();
}
catch(CreationException m){
logger.info("Exception adding tool!");
throw m;
}
return "tools";
}
public String editTool(Tool tool){
setCurrentAction(ACTION_MODIFYING);
setTool(tool);
return "addChangeTool";
}
public String changeTool() throws Exception{
try{
toolMaintenanceLocalBusiness.changeTool(tool);
toolFilter.filterList();
}
catch(ModificationException m){
logger.info("Exception modifying tool!");
throw m;
}
return "tools";
}
public String removeTool() throws Exception{
try{
toolMaintenanceLocalBusiness.removeTool(tool);
toolFilter.filterList();
}
catch(RemovalException r){
logger.info("Exception removing tool!");
throw r;
}
return "tools";
}
public String viewTool(Tool tool){
setTool(tool);
return "viewTool";
}
public void setTool(Tool tool){
this.tool = tool;
}
public Tool getTool(){
return this.tool;
}
public void setToolFilter(ToolFilter toolFilter){
this.toolFilter = toolFilter;
}
public ToolFilter getToolFilter(){
return this.toolFilter;
}
public void setPrintController(PrintController printController){
this.printController = printController;
}
public PrintController getPrintController(){
return this.printController;
}
public StreamedContent print() throws Exception{
return printController.printToolStateReport();
}
/* Utility methods */
@Override
public String save() throws Exception {
if(getCurrentAction().equalsIgnoreCase(ACTION_ADDING)){
return addTool();
}
else {
return changeTool();
}
}
@Override
public String getTitle() {
if(getCurrentAction().equalsIgnoreCase(ACTION_ADDING)){
return "Add Tool";
}
else {
return "Edit Tool";
}
}
public Date getCommissionDate(){
if(tool.getCommissionDate() == null){
tool.setCommissionDate(new Date().getTime());
}
return new Date(tool.getCommissionDate());
}
public void setCommissionDate(Date commissionDate){
if(commissionDate == null){
tool.setCommissionDate(new Date().getTime());
}
tool.setCommissionDate(commissionDate.getTime());
}
public String getDecommissionDate(){
if(tool.getDecommissionDate() == null){
return "";
}
return DateOperations.formatGivenDate(new Date(tool.getDecommissionDate()), DateOperations.DISPLAY_DATE_FORMAT);
}
public void setDecommissionDate(String decommissionDate){
if(decommissionDate == null || decommissionDate.equalsIgnoreCase("")){
tool.setDecommissionDate(null);
return;
}
try {
tool.setDecommissionDate(new SimpleDateFormat(DateOperations.TEXT_DATE_FORMAT).parse(decommissionDate).getTime());
}
catch(ParseException p){
tool.setDecommissionDate(null);
}
}
public List<ToolState> getToolStates() throws Exception{
try{
return new ArrayList<>(toolMaintenanceLocalBusiness.listToolStates());
}
catch(RetrievalException r){
throw r;
}
}
public ToolState getToolState(){
toolState = tool.getToolState();
return toolState;
}
public void setToolState(ToolState toolState){
this.toolState = toolState;
tool.setToolState(this.toolState);
}
public List<ToolManufacturer> getToolManufacturers() throws Exception{
try{
return new ArrayList<>(toolMaintenanceLocalBusiness.listToolManufacturers());
}
catch(RetrievalException r){
throw r;
}
}
public ToolManufacturer getToolManufacturer(){
toolManufacturer = tool.getToolManufacturer();
return toolManufacturer;
}
public void setToolManufacturer(ToolManufacturer toolManufacturer){
this.toolManufacturer = toolManufacturer;
tool.setToolManufacturer(this.toolManufacturer);
}
}
| UTF-8 | Java | 6,530 | java | ToolController.java | Java | [
{
"context": "ctive session bean.\n *\n * @author <a href=\"mailto:trljohnson@mweb.co.za\">ALR</a>\n */\n\n@ManagedBean(eager=true)\n@SessionSc",
"end": 1205,
"score": 0.9999240040779114,
"start": 1184,
"tag": "EMAIL",
"value": "trljohnson@mweb.co.za"
},
{
"context": " * @author <a href=\"mailto:trljohnson@mweb.co.za\">ALR</a>\n */\n\n@ManagedBean(eager=true)\n@SessionScoped\n",
"end": 1210,
"score": 0.785021185874939,
"start": 1207,
"tag": "NAME",
"value": "ALR"
}
]
| null | []
| package za.co.smeEnterprise.tool;
import org.primefaces.model.StreamedContent;
import za.co.smeEnterprise.exception.CreationException;
import za.co.smeEnterprise.exception.ModificationException;
import za.co.smeEnterprise.exception.RemovalException;
import za.co.smeEnterprise.exception.RetrievalException;
import za.co.smeEnterprise.organisation.ToolFilter;
import za.co.smeEnterprise.print.PrintController;
import za.co.smeEnterprise.safety.EmployeePPEItem;
import za.co.smeEnterprise.session.tool.ToolMaintenanceLocalBusiness;
import za.co.smeEnterprise.utility.DateOperations;
import za.co.smeEnterprise.utility.TabViewController;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
/**
* The <code>ToolController</code> is used as a 'controller' to
* manage creation, modification and removal of <code>Tool</code>s
* using the respective session bean.
*
* @author <a href="mailto:<EMAIL>">ALR</a>
*/
@ManagedBean(eager=true)
@SessionScoped
public class ToolController extends TabViewController implements Serializable{
private static final Logger logger = Logger.getLogger("@@@ Tool Controller");
private Tool tool;
private ToolState toolState;
@ManagedProperty(value="#{printController}")
PrintController printController;
private ToolManufacturer toolManufacturer;
@ManagedProperty(value="#{toolFilter}")
ToolFilter toolFilter;
@EJB
private ToolMaintenanceLocalBusiness toolMaintenanceLocalBusiness;
public ToolController(){
logger.info("Creating a new tool controller");
}
public String insertTool(){
setCurrentAction(ACTION_ADDING);
setTool(new Tool());
return "addChangeTool";
}
public String addTool() throws Exception{
try{
toolMaintenanceLocalBusiness.addTool(tool);
toolFilter.filterList();
}
catch(CreationException m){
logger.info("Exception adding tool!");
throw m;
}
return "tools";
}
public String editTool(Tool tool){
setCurrentAction(ACTION_MODIFYING);
setTool(tool);
return "addChangeTool";
}
public String changeTool() throws Exception{
try{
toolMaintenanceLocalBusiness.changeTool(tool);
toolFilter.filterList();
}
catch(ModificationException m){
logger.info("Exception modifying tool!");
throw m;
}
return "tools";
}
public String removeTool() throws Exception{
try{
toolMaintenanceLocalBusiness.removeTool(tool);
toolFilter.filterList();
}
catch(RemovalException r){
logger.info("Exception removing tool!");
throw r;
}
return "tools";
}
public String viewTool(Tool tool){
setTool(tool);
return "viewTool";
}
public void setTool(Tool tool){
this.tool = tool;
}
public Tool getTool(){
return this.tool;
}
public void setToolFilter(ToolFilter toolFilter){
this.toolFilter = toolFilter;
}
public ToolFilter getToolFilter(){
return this.toolFilter;
}
public void setPrintController(PrintController printController){
this.printController = printController;
}
public PrintController getPrintController(){
return this.printController;
}
public StreamedContent print() throws Exception{
return printController.printToolStateReport();
}
/* Utility methods */
@Override
public String save() throws Exception {
if(getCurrentAction().equalsIgnoreCase(ACTION_ADDING)){
return addTool();
}
else {
return changeTool();
}
}
@Override
public String getTitle() {
if(getCurrentAction().equalsIgnoreCase(ACTION_ADDING)){
return "Add Tool";
}
else {
return "Edit Tool";
}
}
public Date getCommissionDate(){
if(tool.getCommissionDate() == null){
tool.setCommissionDate(new Date().getTime());
}
return new Date(tool.getCommissionDate());
}
public void setCommissionDate(Date commissionDate){
if(commissionDate == null){
tool.setCommissionDate(new Date().getTime());
}
tool.setCommissionDate(commissionDate.getTime());
}
public String getDecommissionDate(){
if(tool.getDecommissionDate() == null){
return "";
}
return DateOperations.formatGivenDate(new Date(tool.getDecommissionDate()), DateOperations.DISPLAY_DATE_FORMAT);
}
public void setDecommissionDate(String decommissionDate){
if(decommissionDate == null || decommissionDate.equalsIgnoreCase("")){
tool.setDecommissionDate(null);
return;
}
try {
tool.setDecommissionDate(new SimpleDateFormat(DateOperations.TEXT_DATE_FORMAT).parse(decommissionDate).getTime());
}
catch(ParseException p){
tool.setDecommissionDate(null);
}
}
public List<ToolState> getToolStates() throws Exception{
try{
return new ArrayList<>(toolMaintenanceLocalBusiness.listToolStates());
}
catch(RetrievalException r){
throw r;
}
}
public ToolState getToolState(){
toolState = tool.getToolState();
return toolState;
}
public void setToolState(ToolState toolState){
this.toolState = toolState;
tool.setToolState(this.toolState);
}
public List<ToolManufacturer> getToolManufacturers() throws Exception{
try{
return new ArrayList<>(toolMaintenanceLocalBusiness.listToolManufacturers());
}
catch(RetrievalException r){
throw r;
}
}
public ToolManufacturer getToolManufacturer(){
toolManufacturer = tool.getToolManufacturer();
return toolManufacturer;
}
public void setToolManufacturer(ToolManufacturer toolManufacturer){
this.toolManufacturer = toolManufacturer;
tool.setToolManufacturer(this.toolManufacturer);
}
}
| 6,516 | 0.657427 | 0.657427 | 232 | 27.142241 | 23.785709 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392241 | false | false | 2 |
66462351a788405acdce84a8cb414928db57623c | 34,866,544,545,453 | 8d1c7fba7cd15f8a1e33fd27d11eefd1c67d579f | /src/main/java/com/google/devtools/build/lib/bazel/repository/RepositoryResolvedEvent.java | b428ed6993d85b160efac9ac484591bf6842f0f6 | [
"Apache-2.0"
]
| permissive | bazelbuild/bazel | https://github.com/bazelbuild/bazel | 5896162455f032efc899b8de60aa39b9d2cad4a6 | 171aae3f9c57b41089e25ec61fc84c35baa3079d | refs/heads/master | 2023-08-22T22:52:48.714000 | 2023-08-22T18:01:53 | 2023-08-22T18:01:53 | 20,773,773 | 20,294 | 4,383 | Apache-2.0 | false | 2023-09-14T18:38:44 | 2014-06-12T16:00:38 | 2023-09-14T16:49:53 | 2023-09-14T18:38:43 | 834,634 | 21,350 | 3,861 | 1,797 | Java | false | false | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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.google.devtools.build.lib.bazel.repository;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.ATTRIBUTES;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.DEFINITION_INFORMATION;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.ORIGINAL_ATTRIBUTES;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.ORIGINAL_RULE_CLASS;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.OUTPUT_TREE_HASH;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.REPOSITORIES;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.RULE_CLASS;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.bazel.ResolvedEvent;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.StructImpl;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.XattrProvider;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkThread;
/**
* Event indicating that a repository rule was executed, together with the return value of the rule.
*/
public class RepositoryResolvedEvent implements ResolvedEvent {
/**
* The entry for WORSPACE.resolved corresponding to that rule invocation.
*
* <p>It will always be a dict with three entries
*
* <ul>
* <li>the original rule class (as String, e.g., "@bazel_tools//:git.bzl%git_repository")
* <li>the original attributes (as dict, e.g., mapping "name" to "build_bazel" and "remote" to
* "https://github.com/bazelbuild/bazel.git"), and
* <li>a "repositories" entry; this is a list, often a single entry, of fully resolved
* repositories the rule call expanded to (in the above example, the attributes entry would
* have an additional "commit" and "shallow-since" entry).
* </ul>
*/
private Object resolvedInformation;
/**
* The builders for the resolved information.
*
* <p>As the resolved information contains a value, the hash of the output directory, that is
* expensive to compute, we delay computing it till its first use. In this way, we avoid the
* expensive operation if it is not needed, e.g., if no resolved file is generated.
*/
private ImmutableMap.Builder<String, Object> resolvedInformationBuilder = ImmutableMap.builder();
private ImmutableMap.Builder<String, Object> repositoryBuilder = ImmutableMap.builder();
private String directoryDigest;
private final Path outputDirectory;
private final String name;
private final boolean informationReturned;
private final String message;
public RepositoryResolvedEvent(Rule rule, StructImpl attrs, Path outputDirectory, Object result) {
this.outputDirectory = outputDirectory;
String originalClass =
rule.getRuleClassObject().getRuleDefinitionEnvironmentLabel() + "%" + rule.getRuleClass();
resolvedInformationBuilder.put(ORIGINAL_RULE_CLASS, originalClass);
resolvedInformationBuilder.put(DEFINITION_INFORMATION, getRuleDefinitionInformation(rule));
ImmutableMap.Builder<String, Object> origAttrBuilder = ImmutableMap.builder();
ImmutableMap.Builder<String, Object> defaults = ImmutableMap.builder();
for (Attribute attr : rule.getAttributes()) {
String name = attr.getPublicName();
try {
Object value = attrs.getValue(name, Object.class);
if (value != null) {
if (rule.isAttributeValueExplicitlySpecified(attr)) {
origAttrBuilder.put(name, value);
} else {
defaults.put(name, value);
}
}
} catch (EvalException e) {
// Do nothing, just ignore the value.
}
}
ImmutableMap<String, Object> origAttr = origAttrBuilder.buildOrThrow();
resolvedInformationBuilder.put(ORIGINAL_ATTRIBUTES, origAttr);
repositoryBuilder.put(RULE_CLASS, originalClass);
if (result == Starlark.NONE) {
// Rule claims to be already reproducible, so wants to be called as is.
repositoryBuilder.put(ATTRIBUTES, origAttr);
this.informationReturned = false;
this.message = "Repository rule '" + rule.getName() + "' finished.";
} else if (result instanceof Map) {
// Rule claims that the returned (probably changed) arguments are a reproducible
// version of itself.
repositoryBuilder.put(ATTRIBUTES, result);
Pair<Map<String, Object>, List<String>> diff =
compare(origAttr, defaults.buildOrThrow(), (Map<?, ?>) result);
if (diff.getFirst().isEmpty() && diff.getSecond().isEmpty()) {
this.informationReturned = false;
this.message = "Repository rule '" + rule.getName() + "' finished.";
} else {
this.informationReturned = true;
if (diff.getFirst().isEmpty()) {
this.message =
"Rule '"
+ rule.getName()
+ "' indicated that a canonical reproducible form can be obtained by"
+ " dropping arguments "
+ Starlark.repr(diff.getSecond());
} else if (diff.getSecond().isEmpty()) {
this.message =
"Rule '"
+ rule.getName()
+ "' indicated that a canonical reproducible form can be obtained by"
+ " modifying arguments "
+ representModifications(diff.getFirst());
} else {
this.message =
"Rule '"
+ rule.getName()
+ "' indicated that a canonical reproducible form can be obtained by"
+ " modifying arguments "
+ representModifications(diff.getFirst())
+ " and dropping "
+ Starlark.repr(diff.getSecond());
}
}
} else {
// TODO(aehlig): handle strings specially to allow encodings of the former
// values to be accepted as well.
resolvedInformationBuilder.put(REPOSITORIES, result);
repositoryBuilder = null; // We already added the REPOSITORIES entry
this.informationReturned = true;
this.message = "Repository rule '" + rule.getName() + "' returned: " + result;
}
this.name = rule.getName();
}
/**
* Ensure that the {@code resolvedInformation} and the {@code directoryDigest} fields are
* initialized properly. Does nothing, if the values are computed already.
*/
private synchronized void finalizeResolvedInformation(XattrProvider xattrProvider) {
if (resolvedInformation != null) {
return;
}
String digest = "[unavailable]";
try {
digest = outputDirectory.getDirectoryDigest(xattrProvider);
repositoryBuilder.put(OUTPUT_TREE_HASH, digest);
} catch (IOException e) {
// Digest not available, but we still have to report that a repository rule
// was invoked. So we can do nothing, but ignore the event.
}
this.directoryDigest = digest;
if (repositoryBuilder != null) {
resolvedInformationBuilder.put(
REPOSITORIES, ImmutableList.<Object>of(repositoryBuilder.buildOrThrow()));
}
this.resolvedInformation = resolvedInformationBuilder.buildOrThrow();
this.resolvedInformationBuilder = null;
this.repositoryBuilder = null;
}
/**
* Returns the entry for the given rule invocation in a format suitable for WORKSPACE.resolved.
*/
@Override
public Object getResolvedInformation(XattrProvider xattrProvider) {
finalizeResolvedInformation(xattrProvider);
return resolvedInformation;
}
/** Return the name of the rule that produced the resolvedInformation */
@Override
public String getName() {
return name;
}
public String getDirectoryDigest(XattrProvider xattrProvider) {
finalizeResolvedInformation(xattrProvider);
return directoryDigest;
}
/**
* True, if the return value of the repository rule contained new information with respect to the
* way it was called.
*/
public boolean isNewInformationReturned() {
return informationReturned;
}
/** Message describing the event */
public String getMessage() {
return message;
}
/** Returns an unstructured message explaining the origin of this rule. */
public static String getRuleDefinitionInformation(Rule rule) {
StringBuilder buf = new StringBuilder();
// Emit stack of rule instantiation.
buf.append("Repository ").append(rule.getName()).append(" instantiated at:\n");
ImmutableList<StarlarkThread.CallStackEntry> stack = rule.reconstructCallStack();
// TODO: Callstack should always be available for bazel.
if (stack.isEmpty()) {
buf.append(" callstack not available\n");
} else {
for (StarlarkThread.CallStackEntry frame : stack) {
buf.append(" ").append(frame.location).append(": in ").append(frame.name).append('\n');
}
}
// Emit stack of rule class declaration.
stack = rule.getRuleClassObject().getCallStack();
if (stack.isEmpty()) {
buf.append("Repository rule ").append(rule.getRuleClass()).append(" is built-in.\n");
} else {
buf.append("Repository rule ").append(rule.getRuleClass()).append(" defined at:\n");
for (StarlarkThread.CallStackEntry frame : stack) {
buf.append(" ").append(frame.location).append(": in ").append(frame.name).append('\n');
}
}
return buf.toString();
}
/**
* Attributes that may be defined on a repository rule without affecting its canonical
* representation. These may be created implicitly by Bazel.
*/
private static final ImmutableSet<String> IGNORED_ATTRIBUTE_NAMES =
ImmutableSet.of("generator_name", "generator_function", "generator_location");
/**
* Compare two maps from Strings to objects, returning a pair of the map with all entries not in
* the original map or in the original map, but with a different value, and the keys dropped from
* the original map. However, ignore changes where a value is explicitly set to its default.
*
* <p>Ignores attributes listed in {@code IGNORED_ATTRIBUTE_NAMES}.
*/
static Pair<Map<String, Object>, List<String>> compare(
Map<String, Object> orig, Map<String, Object> defaults, Map<?, ?> modified) {
ImmutableMap.Builder<String, Object> valuesChanged = ImmutableMap.builder();
for (Map.Entry<?, ?> entry : modified.entrySet()) {
if (entry.getKey() instanceof String) {
String key = (String) entry.getKey();
if (IGNORED_ATTRIBUTE_NAMES.contains(key)) {
// The dict returned by the repo rule really shouldn't know about these anyway, but
// for symmetry we'll ignore them if they happen to be present.
continue;
}
Object value = entry.getValue();
Object old = orig.get(key);
if (old == null) {
Object defaultValue = defaults.get(key);
if (defaultValue == null || !defaultValue.equals(value)) {
valuesChanged.put(key, value);
}
} else {
if (!old.equals(entry.getValue())) {
valuesChanged.put(key, value);
}
}
}
}
ImmutableList.Builder<String> keysDropped = ImmutableList.builder();
for (String key : orig.keySet()) {
if (IGNORED_ATTRIBUTE_NAMES.contains(key)) {
continue;
}
if (!modified.containsKey(key)) {
keysDropped.add(key);
}
}
return Pair.of(valuesChanged.buildOrThrow(), keysDropped.build());
}
static String representModifications(Map<String, Object> changes) {
StringBuilder representation = new StringBuilder();
boolean isFirst = true;
for (Map.Entry<String, Object> entry : changes.entrySet()) {
if (!isFirst) {
representation.append(", ");
}
representation.append(entry.getKey()).append(" = ").append(Starlark.repr(entry.getValue()));
isFirst = false;
}
return representation.toString();
}
}
| UTF-8 | Java | 13,021 | java | RepositoryResolvedEvent.java | Java | [
{
"context": "l\" and \"remote\" to\n * \"https://github.com/bazelbuild/bazel.git\"), and\n * <li>a \"repositories\" entr",
"end": 2668,
"score": 0.9992111921310425,
"start": 2658,
"tag": "USERNAME",
"value": "bazelbuild"
},
{
"context": "());\n }\n }\n } else {\n // TODO(aehlig): handle strings specially to allow encodings of ",
"end": 6910,
"score": 0.9841437339782715,
"start": 6904,
"tag": "USERNAME",
"value": "aehlig"
}
]
| null | []
| // Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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.google.devtools.build.lib.bazel.repository;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.ATTRIBUTES;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.DEFINITION_INFORMATION;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.ORIGINAL_ATTRIBUTES;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.ORIGINAL_RULE_CLASS;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.OUTPUT_TREE_HASH;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.REPOSITORIES;
import static com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction.RULE_CLASS;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.bazel.ResolvedEvent;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.StructImpl;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.XattrProvider;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkThread;
/**
* Event indicating that a repository rule was executed, together with the return value of the rule.
*/
public class RepositoryResolvedEvent implements ResolvedEvent {
/**
* The entry for WORSPACE.resolved corresponding to that rule invocation.
*
* <p>It will always be a dict with three entries
*
* <ul>
* <li>the original rule class (as String, e.g., "@bazel_tools//:git.bzl%git_repository")
* <li>the original attributes (as dict, e.g., mapping "name" to "build_bazel" and "remote" to
* "https://github.com/bazelbuild/bazel.git"), and
* <li>a "repositories" entry; this is a list, often a single entry, of fully resolved
* repositories the rule call expanded to (in the above example, the attributes entry would
* have an additional "commit" and "shallow-since" entry).
* </ul>
*/
private Object resolvedInformation;
/**
* The builders for the resolved information.
*
* <p>As the resolved information contains a value, the hash of the output directory, that is
* expensive to compute, we delay computing it till its first use. In this way, we avoid the
* expensive operation if it is not needed, e.g., if no resolved file is generated.
*/
private ImmutableMap.Builder<String, Object> resolvedInformationBuilder = ImmutableMap.builder();
private ImmutableMap.Builder<String, Object> repositoryBuilder = ImmutableMap.builder();
private String directoryDigest;
private final Path outputDirectory;
private final String name;
private final boolean informationReturned;
private final String message;
public RepositoryResolvedEvent(Rule rule, StructImpl attrs, Path outputDirectory, Object result) {
this.outputDirectory = outputDirectory;
String originalClass =
rule.getRuleClassObject().getRuleDefinitionEnvironmentLabel() + "%" + rule.getRuleClass();
resolvedInformationBuilder.put(ORIGINAL_RULE_CLASS, originalClass);
resolvedInformationBuilder.put(DEFINITION_INFORMATION, getRuleDefinitionInformation(rule));
ImmutableMap.Builder<String, Object> origAttrBuilder = ImmutableMap.builder();
ImmutableMap.Builder<String, Object> defaults = ImmutableMap.builder();
for (Attribute attr : rule.getAttributes()) {
String name = attr.getPublicName();
try {
Object value = attrs.getValue(name, Object.class);
if (value != null) {
if (rule.isAttributeValueExplicitlySpecified(attr)) {
origAttrBuilder.put(name, value);
} else {
defaults.put(name, value);
}
}
} catch (EvalException e) {
// Do nothing, just ignore the value.
}
}
ImmutableMap<String, Object> origAttr = origAttrBuilder.buildOrThrow();
resolvedInformationBuilder.put(ORIGINAL_ATTRIBUTES, origAttr);
repositoryBuilder.put(RULE_CLASS, originalClass);
if (result == Starlark.NONE) {
// Rule claims to be already reproducible, so wants to be called as is.
repositoryBuilder.put(ATTRIBUTES, origAttr);
this.informationReturned = false;
this.message = "Repository rule '" + rule.getName() + "' finished.";
} else if (result instanceof Map) {
// Rule claims that the returned (probably changed) arguments are a reproducible
// version of itself.
repositoryBuilder.put(ATTRIBUTES, result);
Pair<Map<String, Object>, List<String>> diff =
compare(origAttr, defaults.buildOrThrow(), (Map<?, ?>) result);
if (diff.getFirst().isEmpty() && diff.getSecond().isEmpty()) {
this.informationReturned = false;
this.message = "Repository rule '" + rule.getName() + "' finished.";
} else {
this.informationReturned = true;
if (diff.getFirst().isEmpty()) {
this.message =
"Rule '"
+ rule.getName()
+ "' indicated that a canonical reproducible form can be obtained by"
+ " dropping arguments "
+ Starlark.repr(diff.getSecond());
} else if (diff.getSecond().isEmpty()) {
this.message =
"Rule '"
+ rule.getName()
+ "' indicated that a canonical reproducible form can be obtained by"
+ " modifying arguments "
+ representModifications(diff.getFirst());
} else {
this.message =
"Rule '"
+ rule.getName()
+ "' indicated that a canonical reproducible form can be obtained by"
+ " modifying arguments "
+ representModifications(diff.getFirst())
+ " and dropping "
+ Starlark.repr(diff.getSecond());
}
}
} else {
// TODO(aehlig): handle strings specially to allow encodings of the former
// values to be accepted as well.
resolvedInformationBuilder.put(REPOSITORIES, result);
repositoryBuilder = null; // We already added the REPOSITORIES entry
this.informationReturned = true;
this.message = "Repository rule '" + rule.getName() + "' returned: " + result;
}
this.name = rule.getName();
}
/**
* Ensure that the {@code resolvedInformation} and the {@code directoryDigest} fields are
* initialized properly. Does nothing, if the values are computed already.
*/
private synchronized void finalizeResolvedInformation(XattrProvider xattrProvider) {
if (resolvedInformation != null) {
return;
}
String digest = "[unavailable]";
try {
digest = outputDirectory.getDirectoryDigest(xattrProvider);
repositoryBuilder.put(OUTPUT_TREE_HASH, digest);
} catch (IOException e) {
// Digest not available, but we still have to report that a repository rule
// was invoked. So we can do nothing, but ignore the event.
}
this.directoryDigest = digest;
if (repositoryBuilder != null) {
resolvedInformationBuilder.put(
REPOSITORIES, ImmutableList.<Object>of(repositoryBuilder.buildOrThrow()));
}
this.resolvedInformation = resolvedInformationBuilder.buildOrThrow();
this.resolvedInformationBuilder = null;
this.repositoryBuilder = null;
}
/**
* Returns the entry for the given rule invocation in a format suitable for WORKSPACE.resolved.
*/
@Override
public Object getResolvedInformation(XattrProvider xattrProvider) {
finalizeResolvedInformation(xattrProvider);
return resolvedInformation;
}
/** Return the name of the rule that produced the resolvedInformation */
@Override
public String getName() {
return name;
}
public String getDirectoryDigest(XattrProvider xattrProvider) {
finalizeResolvedInformation(xattrProvider);
return directoryDigest;
}
/**
* True, if the return value of the repository rule contained new information with respect to the
* way it was called.
*/
public boolean isNewInformationReturned() {
return informationReturned;
}
/** Message describing the event */
public String getMessage() {
return message;
}
/** Returns an unstructured message explaining the origin of this rule. */
public static String getRuleDefinitionInformation(Rule rule) {
StringBuilder buf = new StringBuilder();
// Emit stack of rule instantiation.
buf.append("Repository ").append(rule.getName()).append(" instantiated at:\n");
ImmutableList<StarlarkThread.CallStackEntry> stack = rule.reconstructCallStack();
// TODO: Callstack should always be available for bazel.
if (stack.isEmpty()) {
buf.append(" callstack not available\n");
} else {
for (StarlarkThread.CallStackEntry frame : stack) {
buf.append(" ").append(frame.location).append(": in ").append(frame.name).append('\n');
}
}
// Emit stack of rule class declaration.
stack = rule.getRuleClassObject().getCallStack();
if (stack.isEmpty()) {
buf.append("Repository rule ").append(rule.getRuleClass()).append(" is built-in.\n");
} else {
buf.append("Repository rule ").append(rule.getRuleClass()).append(" defined at:\n");
for (StarlarkThread.CallStackEntry frame : stack) {
buf.append(" ").append(frame.location).append(": in ").append(frame.name).append('\n');
}
}
return buf.toString();
}
/**
* Attributes that may be defined on a repository rule without affecting its canonical
* representation. These may be created implicitly by Bazel.
*/
private static final ImmutableSet<String> IGNORED_ATTRIBUTE_NAMES =
ImmutableSet.of("generator_name", "generator_function", "generator_location");
/**
* Compare two maps from Strings to objects, returning a pair of the map with all entries not in
* the original map or in the original map, but with a different value, and the keys dropped from
* the original map. However, ignore changes where a value is explicitly set to its default.
*
* <p>Ignores attributes listed in {@code IGNORED_ATTRIBUTE_NAMES}.
*/
static Pair<Map<String, Object>, List<String>> compare(
Map<String, Object> orig, Map<String, Object> defaults, Map<?, ?> modified) {
ImmutableMap.Builder<String, Object> valuesChanged = ImmutableMap.builder();
for (Map.Entry<?, ?> entry : modified.entrySet()) {
if (entry.getKey() instanceof String) {
String key = (String) entry.getKey();
if (IGNORED_ATTRIBUTE_NAMES.contains(key)) {
// The dict returned by the repo rule really shouldn't know about these anyway, but
// for symmetry we'll ignore them if they happen to be present.
continue;
}
Object value = entry.getValue();
Object old = orig.get(key);
if (old == null) {
Object defaultValue = defaults.get(key);
if (defaultValue == null || !defaultValue.equals(value)) {
valuesChanged.put(key, value);
}
} else {
if (!old.equals(entry.getValue())) {
valuesChanged.put(key, value);
}
}
}
}
ImmutableList.Builder<String> keysDropped = ImmutableList.builder();
for (String key : orig.keySet()) {
if (IGNORED_ATTRIBUTE_NAMES.contains(key)) {
continue;
}
if (!modified.containsKey(key)) {
keysDropped.add(key);
}
}
return Pair.of(valuesChanged.buildOrThrow(), keysDropped.build());
}
static String representModifications(Map<String, Object> changes) {
StringBuilder representation = new StringBuilder();
boolean isFirst = true;
for (Map.Entry<String, Object> entry : changes.entrySet()) {
if (!isFirst) {
representation.append(", ");
}
representation.append(entry.getKey()).append(" = ").append(Starlark.repr(entry.getValue()));
isFirst = false;
}
return representation.toString();
}
}
| 13,021 | 0.68113 | 0.680516 | 315 | 40.33651 | 31.382046 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577778 | false | false | 2 |
48eac3ba5c9e54dbbc7046fdc07eb081ac752b80 | 36,721,970,395,576 | 46853e4da7adf48b7fc877be7e177503361c1cd4 | /src/main/java/nasa/mars/MarsPhotosApplication.java | dbd0fc04bcdb2178cf2aa5399fa1cc0eb34d3728 | []
| no_license | sreenij/MarsPhotos | https://github.com/sreenij/MarsPhotos | 43bd97a47ba6b313b753ff3622fc44d41ccf6b68 | 41af799984828fcd495295b8a052547d465d2556 | refs/heads/master | 2020-03-08T18:03:50.006000 | 2018-04-06T02:09:11 | 2018-04-06T02:09:11 | 128,285,538 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nasa.mars;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.format.datetime.DateFormatter;
import com.fasterxml.jackson.databind.ObjectMapper;
@SpringBootApplication
public class MarsPhotosApplication {
private static final Logger log = LoggerFactory.getLogger(MarsPhotosApplication.class);
private DateFormatter dateFormatter = new DateFormatter();
public static void main(String[] args) {
MarsPhotosApplication app = new MarsPhotosApplication();
app.run();
}
public void run() {
String[] datesArray = {"15-Dec-17",
"1-Mar-16",
"22-Feb-15",
"3-Jul-17",
"5-May-19"};
Date date;
try {
for(String dateStr : datesArray) {
dateFormatter.setPattern("dd-MMM-yy");
date = dateFormatter.parse(dateStr, Locale.US);
dateFormatter.setPattern("yyyy-MM-dd");
log.info(dateStr + "-->" + dateFormatter.print(date, Locale.US));
getMarsImages(dateFormatter.print(date, Locale.US));
}
} catch(IOException ioe) {
log.error(ioe.getMessage());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getMarsImages(String dateStr) throws IOException {
StringBuilder urlString = new StringBuilder();
urlString.append("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?api_key=DEMO_KEY&earth_date=").append(dateStr);
ObjectMapper objectMapper = new ObjectMapper();
MarsPhotos photos = objectMapper.readValue(new URL(urlString.toString()), MarsPhotos.class);
//log.info(photos.toString());
if(photos.getImages().size()>0) {
log.info("Reading image-->"+photos.getImages().get(0).getImg_src());
int last_slash_loc = photos.getImages().get(0).getImg_src().lastIndexOf("/");
String imgName = photos.getImages().get(0).getImg_src().substring(last_slash_loc+1);
URL url = new URL(photos.getImages().get(0).getImg_src());
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
File imgDir = new File("C://temp//mars images");
if(!imgDir.exists()) {
imgDir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(imgDir.getAbsolutePath() + "//" + dateStr + "_" + imgName);
fos.write(response);
fos.close();
}
}
}
| UTF-8 | Java | 3,194 | java | MarsPhotosApplication.java | Java | []
| null | []
| package nasa.mars;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.format.datetime.DateFormatter;
import com.fasterxml.jackson.databind.ObjectMapper;
@SpringBootApplication
public class MarsPhotosApplication {
private static final Logger log = LoggerFactory.getLogger(MarsPhotosApplication.class);
private DateFormatter dateFormatter = new DateFormatter();
public static void main(String[] args) {
MarsPhotosApplication app = new MarsPhotosApplication();
app.run();
}
public void run() {
String[] datesArray = {"15-Dec-17",
"1-Mar-16",
"22-Feb-15",
"3-Jul-17",
"5-May-19"};
Date date;
try {
for(String dateStr : datesArray) {
dateFormatter.setPattern("dd-MMM-yy");
date = dateFormatter.parse(dateStr, Locale.US);
dateFormatter.setPattern("yyyy-MM-dd");
log.info(dateStr + "-->" + dateFormatter.print(date, Locale.US));
getMarsImages(dateFormatter.print(date, Locale.US));
}
} catch(IOException ioe) {
log.error(ioe.getMessage());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getMarsImages(String dateStr) throws IOException {
StringBuilder urlString = new StringBuilder();
urlString.append("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?api_key=DEMO_KEY&earth_date=").append(dateStr);
ObjectMapper objectMapper = new ObjectMapper();
MarsPhotos photos = objectMapper.readValue(new URL(urlString.toString()), MarsPhotos.class);
//log.info(photos.toString());
if(photos.getImages().size()>0) {
log.info("Reading image-->"+photos.getImages().get(0).getImg_src());
int last_slash_loc = photos.getImages().get(0).getImg_src().lastIndexOf("/");
String imgName = photos.getImages().get(0).getImg_src().substring(last_slash_loc+1);
URL url = new URL(photos.getImages().get(0).getImg_src());
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
File imgDir = new File("C://temp//mars images");
if(!imgDir.exists()) {
imgDir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(imgDir.getAbsolutePath() + "//" + dateStr + "_" + imgName);
fos.write(response);
fos.close();
}
}
}
| 3,194 | 0.626174 | 0.615842 | 98 | 31.591837 | 27.555449 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.489796 | false | false | 2 |
6ab19b8fcaaf704c6cae111828a2b23f38e2c84a | 36,721,970,396,162 | 4ead80ec478a9ae03c73c7408436bd507be7b6a9 | /business/pay/pay-biz/src/main/java/study/daydayup/wolf/business/pay/biz/service/china/alipay/AlipayService.java | 76b7e7c08323c7e2c40ca12230758b058121d718 | [
"MIT"
]
| permissive | timxim/wolf | https://github.com/timxim/wolf | cfea87e0efcd5c6e6ff76c85b3882ffce60dde07 | 207c61cd473d1433bf3e4fc5a591aaf3a5964418 | refs/heads/master | 2022-11-12T15:13:33.096000 | 2020-07-04T14:03:53 | 2020-07-04T14:03:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package study.daydayup.wolf.business.pay.biz.service.china.alipay;
/**
* study.daydayup.wolf.business.pay.biz.api.china
*
* @author Wingle
* @since 2020/2/28 10:39 上午
**/
public interface AlipayService {
}
| UTF-8 | Java | 216 | java | AlipayService.java | Java | [
{
"context": "ayup.wolf.business.pay.biz.api.china\n *\n * @author Wingle\n * @since 2020/2/28 10:39 上午\n **/\npublic interfac",
"end": 142,
"score": 0.9903919696807861,
"start": 136,
"tag": "USERNAME",
"value": "Wingle"
}
]
| null | []
| package study.daydayup.wolf.business.pay.biz.service.china.alipay;
/**
* study.daydayup.wolf.business.pay.biz.api.china
*
* @author Wingle
* @since 2020/2/28 10:39 上午
**/
public interface AlipayService {
}
| 216 | 0.721698 | 0.669811 | 10 | 20.200001 | 21.917116 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 2 |
cd58280e55b3d59ddd196278521f02a9fa2e37a9 | 18,700,287,663,838 | 558516df49b1f598d17994b6d994b15a935d83c8 | /app/src/main/java/com/kaizen/models/Childcat.java | d33d1396418e2c0e79956600a071c998e77e48bf | []
| no_license | Dummyurl/Kaizen | https://github.com/Dummyurl/Kaizen | dfaa28701dfa618d2356f0677f8135b92242f25e | ab747de0514e2651fb80b7076b093fc7c441292e | refs/heads/master | 2020-04-10T08:52:04.314000 | 2018-09-03T05:25:02 | 2018-09-03T05:25:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kaizen.models;
public class Childcat {
private String created_date;
private String mainCategoryId;
private String categoryTitle;
private String status;
private String categoryAlias;
private String brand_id;
private String brandName;
private String mainImage;
private String id;
private String subCategoryId;
private String aliasName;
private String enquiry;
private String description;
private String CatId;
private String CreatedDate;
private String mainCatId;
private String subCatId;
private String bannerImg;
private String createDate;
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getMainCategoryId() {
return mainCategoryId;
}
public void setMainCategoryId(String mainCategoryId) {
this.mainCategoryId = mainCategoryId;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCategoryAlias() {
return categoryAlias;
}
public void setCategoryAlias(String categoryAlias) {
this.categoryAlias = categoryAlias;
}
public String getBrand_id() {
return brand_id;
}
public void setBrand_id(String brand_id) {
this.brand_id = brand_id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getMainImage() {
return mainImage;
}
public void setMainImage(String mainImage) {
this.mainImage = mainImage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSubCategoryId() {
return subCategoryId;
}
public void setSubCategoryId(String subCategoryId) {
this.subCategoryId = subCategoryId;
}
public String getAliasName() {
return aliasName;
}
public void setAliasName(String aliasName) {
this.aliasName = aliasName;
}
public String getEnquiry() {
return enquiry;
}
public void setEnquiry(String enquiry) {
this.enquiry = enquiry;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCatId() {
return CatId;
}
public void setCatId(String catId) {
CatId = catId;
}
public String getCreatedDate() {
return CreatedDate;
}
public void setCreatedDate(String createdDate) {
CreatedDate = createdDate;
}
public String getMainCatId() {
return mainCatId;
}
public void setMainCatId(String mainCatId) {
this.mainCatId = mainCatId;
}
public String getSubCatId() {
return subCatId;
}
public void setSubCatId(String subCatId) {
this.subCatId = subCatId;
}
public String getBannerImg() {
return bannerImg;
}
public void setBannerImg(String bannerImg) {
this.bannerImg = bannerImg;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
}
| UTF-8 | Java | 3,721 | java | Childcat.java | Java | []
| null | []
| package com.kaizen.models;
public class Childcat {
private String created_date;
private String mainCategoryId;
private String categoryTitle;
private String status;
private String categoryAlias;
private String brand_id;
private String brandName;
private String mainImage;
private String id;
private String subCategoryId;
private String aliasName;
private String enquiry;
private String description;
private String CatId;
private String CreatedDate;
private String mainCatId;
private String subCatId;
private String bannerImg;
private String createDate;
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getMainCategoryId() {
return mainCategoryId;
}
public void setMainCategoryId(String mainCategoryId) {
this.mainCategoryId = mainCategoryId;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCategoryAlias() {
return categoryAlias;
}
public void setCategoryAlias(String categoryAlias) {
this.categoryAlias = categoryAlias;
}
public String getBrand_id() {
return brand_id;
}
public void setBrand_id(String brand_id) {
this.brand_id = brand_id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getMainImage() {
return mainImage;
}
public void setMainImage(String mainImage) {
this.mainImage = mainImage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSubCategoryId() {
return subCategoryId;
}
public void setSubCategoryId(String subCategoryId) {
this.subCategoryId = subCategoryId;
}
public String getAliasName() {
return aliasName;
}
public void setAliasName(String aliasName) {
this.aliasName = aliasName;
}
public String getEnquiry() {
return enquiry;
}
public void setEnquiry(String enquiry) {
this.enquiry = enquiry;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCatId() {
return CatId;
}
public void setCatId(String catId) {
CatId = catId;
}
public String getCreatedDate() {
return CreatedDate;
}
public void setCreatedDate(String createdDate) {
CreatedDate = createdDate;
}
public String getMainCatId() {
return mainCatId;
}
public void setMainCatId(String mainCatId) {
this.mainCatId = mainCatId;
}
public String getSubCatId() {
return subCatId;
}
public void setSubCatId(String subCatId) {
this.subCatId = subCatId;
}
public String getBannerImg() {
return bannerImg;
}
public void setBannerImg(String bannerImg) {
this.bannerImg = bannerImg;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
}
| 3,721 | 0.631013 | 0.631013 | 193 | 18.279793 | 17.537657 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.300518 | false | false | 2 |
c0e91ee56e6f8bc953b899196c422ab520330ad0 | 34,394,098,136,453 | 5657758df5829bfb50b8be87c7214947ec02a795 | /NewsAggregator/src/newsagg/view/Main.java | 8972418e026a053b590204b93d6ee12419ebb11f | []
| no_license | kiru1283/NewsAgg | https://github.com/kiru1283/NewsAgg | 19ac89dcad75cb3cd4233c9dc8254c967c4d68a0 | 0749607ea639f2ac6d2edd2af0ccfc0c8ea9736b | refs/heads/master | 2021-08-24T17:55:48.490000 | 2017-11-21T09:57:44 | 2017-11-21T09:57:44 | 108,413,836 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package newsagg.view;
import java.util.Scanner;
/**
* Main Class acting as View and called other View classes
* @author Kiruthiga
*
*
*/
public class Main {
private Scanner scanner;
private UserLogin userObj;
private FeedView feedObj;
private ArticleView artObj;
private String inputUser;
/**
* constructor to initialize the scanner and controller classes
*/
public Main() {
scanner = new Scanner(System.in);
userObj = new UserLogin();
feedObj = new FeedView();
artObj = new ArticleView();
}
/**
* Main method for program start point
*
* @param args
*/
public static void main(String[] args) {
Main main = new Main();
main.mainLoop();
}
/**
* Method to call controller class methods based on user input
*/
public void mainLoop() {
System.out.println("***********************************");
System.out.println("* Welcome To FeedBook Application *");
System.out.println("***********************************");
System.out.println("");
while (true) {
boolean validUser = false;
while (!validUser) {
System.out.println("To Enter Please Select One Option : ");
System.out.println("C -> Create New User Account");
System.out.println("L -> Login With Existing User Account");
String inputOption = scanner.nextLine();
if (inputOption.toUpperCase().trim().equals("C")) {
validUser = userObj.createNewUser();
} else if (inputOption.toUpperCase().trim().equals("L")) {
validUser = userObj.loginUser();
} else {
System.out.println("Invalid Option Entered!!");
}
}
// for Valid users choose operation
if (validUser) {
inputUser = userObj.getinputUser();
userOperations();
}
}
}
// Method used for processing user input after login
private void userOperations() {
String loop = "GO";
while (!loop.equals("LOGOUT")) {
System.out.println("--------------");
System.out.println("| MAIN MENU |");
System.out.println("--------------");
System.out.println("Please Enter An Option: ");
System.out.println("S -> Subscribe a feed");
System.out.println("R -> Read a feed");
System.out.println("V -> View Favourite Articles");
System.out.println("U -> UnSubscribe a feed");
System.out.println("X -> Exit the application");
String inputVal = scanner.nextLine();
if (inputVal.toUpperCase().trim().equals("S")) {
feedObj.subscribeFeed(inputUser);
} else if (inputVal.toUpperCase().trim().equals("R")) {
feedObj.readFeed(inputUser);
} else if (inputVal.toUpperCase().trim().equals("U")) {
feedObj.unsubscribeFeed(inputUser);
} else if (inputVal.toUpperCase().trim().equals("V")) {
artObj.viewFavourites(inputUser);
} else if (inputVal.toUpperCase().trim().equals("X")) {
loop = "LOGOUT";
} else {
System.out.println("Invalid Option Entered!!");
}
}
System.out.println("**************************************");
System.out.println("*Logged Out Of FeedBook Application!!*");
System.out.println("**************************************");
System.out.println("");
}
}
| UTF-8 | Java | 3,107 | java | Main.java | Java | [
{
"context": "g as View and called other View classes\n * @author Kiruthiga\n * \n * \n */\npublic class Main {\n\tprivate Scanner ",
"end": 135,
"score": 0.9926216006278992,
"start": 126,
"tag": "NAME",
"value": "Kiruthiga"
}
]
| null | []
| package newsagg.view;
import java.util.Scanner;
/**
* Main Class acting as View and called other View classes
* @author Kiruthiga
*
*
*/
public class Main {
private Scanner scanner;
private UserLogin userObj;
private FeedView feedObj;
private ArticleView artObj;
private String inputUser;
/**
* constructor to initialize the scanner and controller classes
*/
public Main() {
scanner = new Scanner(System.in);
userObj = new UserLogin();
feedObj = new FeedView();
artObj = new ArticleView();
}
/**
* Main method for program start point
*
* @param args
*/
public static void main(String[] args) {
Main main = new Main();
main.mainLoop();
}
/**
* Method to call controller class methods based on user input
*/
public void mainLoop() {
System.out.println("***********************************");
System.out.println("* Welcome To FeedBook Application *");
System.out.println("***********************************");
System.out.println("");
while (true) {
boolean validUser = false;
while (!validUser) {
System.out.println("To Enter Please Select One Option : ");
System.out.println("C -> Create New User Account");
System.out.println("L -> Login With Existing User Account");
String inputOption = scanner.nextLine();
if (inputOption.toUpperCase().trim().equals("C")) {
validUser = userObj.createNewUser();
} else if (inputOption.toUpperCase().trim().equals("L")) {
validUser = userObj.loginUser();
} else {
System.out.println("Invalid Option Entered!!");
}
}
// for Valid users choose operation
if (validUser) {
inputUser = userObj.getinputUser();
userOperations();
}
}
}
// Method used for processing user input after login
private void userOperations() {
String loop = "GO";
while (!loop.equals("LOGOUT")) {
System.out.println("--------------");
System.out.println("| MAIN MENU |");
System.out.println("--------------");
System.out.println("Please Enter An Option: ");
System.out.println("S -> Subscribe a feed");
System.out.println("R -> Read a feed");
System.out.println("V -> View Favourite Articles");
System.out.println("U -> UnSubscribe a feed");
System.out.println("X -> Exit the application");
String inputVal = scanner.nextLine();
if (inputVal.toUpperCase().trim().equals("S")) {
feedObj.subscribeFeed(inputUser);
} else if (inputVal.toUpperCase().trim().equals("R")) {
feedObj.readFeed(inputUser);
} else if (inputVal.toUpperCase().trim().equals("U")) {
feedObj.unsubscribeFeed(inputUser);
} else if (inputVal.toUpperCase().trim().equals("V")) {
artObj.viewFavourites(inputUser);
} else if (inputVal.toUpperCase().trim().equals("X")) {
loop = "LOGOUT";
} else {
System.out.println("Invalid Option Entered!!");
}
}
System.out.println("**************************************");
System.out.println("*Logged Out Of FeedBook Application!!*");
System.out.println("**************************************");
System.out.println("");
}
}
| 3,107 | 0.609913 | 0.609913 | 139 | 21.352518 | 22.153442 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.913669 | false | false | 2 |
ae9a11696efa783cca2a840e15a736cacf69e34b | 34,291,018,920,200 | dd53cb7dbc7c340987f1982551c4927dfa5f0efe | /main/plugins/org.talend.core.runtime/src/main/java/org/talend/core/model/metadata/MetadataTalendTypeFilter.java | 5dbeb957522b0410d0b51d96952403d0e554abac | [
"Apache-2.0"
]
| permissive | Talend/tcommon-studio-se | https://github.com/Talend/tcommon-studio-se | e6fcaeddb561aea62af747c164c0be9d4c490ca3 | 3c68f3f13cdab9457392473d10e27891094bd4b8 | refs/heads/master | 2023-08-18T03:46:54.705000 | 2023-08-11T02:58:04 | 2023-08-11T02:58:04 | 21,085,139 | 86 | 275 | null | false | 2023-09-14T08:15:34 | 2014-06-22T04:07:18 | 2023-09-13T07:51:37 | 2023-09-14T08:15:33 | 864,742 | 80 | 103 | 122 | Java | false | false | // ============================================================================
//
// Copyright (C) 2006-2021 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.core.model.metadata;
import java.util.ArrayList;
import java.util.List;
import org.talend.core.model.metadata.types.JavaType;
public abstract class MetadataTalendTypeFilter {
/**
* This method returns a List of String, representing the data types that must not be shown in the Talend schema.
*
* @return
*/
protected abstract List<String> getUnsupportedTypes();
/**
* This method has the responsibility to remove the unsupported type from the Talend schema. DOC rdubois Comment
* method "filter".
*
* @param arrayTalendTypes
* @return
*/
public String[] filter(String[] arrayTalendTypes) {
List<String> unsupportedTypes = getUnsupportedTypes();
List<String> arrayTalendTypesNew = new ArrayList<>();
for (int i = 0; i < arrayTalendTypes.length; i++) {
if (!unsupportedTypes.contains(arrayTalendTypes[i])) {
arrayTalendTypesNew.add(arrayTalendTypes[i]);
}
}
return arrayTalendTypesNew.toArray(new String[arrayTalendTypesNew.size()]);
}
public JavaType[] filter(JavaType[] arrayTalendTypes) {
List<String> unsupportedTypes = getUnsupportedTypes();
List<JavaType> arrayTalendTypesNew = new ArrayList<>();
for (int i = 0; i < arrayTalendTypes.length; i++) {
if (!unsupportedTypes.contains(arrayTalendTypes[i].getLabel())) {
arrayTalendTypesNew.add(arrayTalendTypes[i]);
}
}
return arrayTalendTypesNew.toArray(new JavaType[arrayTalendTypesNew.size()]);
}
}
| UTF-8 | Java | 2,137 | java | MetadataTalendTypeFilter.java | Java | [
{
"context": "e the unsupported type from the Talend schema. DOC rdubois Comment\n * method \"filter\".\n *\n * @pa",
"end": 1053,
"score": 0.7840245962142944,
"start": 1046,
"tag": "USERNAME",
"value": "rdubois"
}
]
| null | []
| // ============================================================================
//
// Copyright (C) 2006-2021 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.core.model.metadata;
import java.util.ArrayList;
import java.util.List;
import org.talend.core.model.metadata.types.JavaType;
public abstract class MetadataTalendTypeFilter {
/**
* This method returns a List of String, representing the data types that must not be shown in the Talend schema.
*
* @return
*/
protected abstract List<String> getUnsupportedTypes();
/**
* This method has the responsibility to remove the unsupported type from the Talend schema. DOC rdubois Comment
* method "filter".
*
* @param arrayTalendTypes
* @return
*/
public String[] filter(String[] arrayTalendTypes) {
List<String> unsupportedTypes = getUnsupportedTypes();
List<String> arrayTalendTypesNew = new ArrayList<>();
for (int i = 0; i < arrayTalendTypes.length; i++) {
if (!unsupportedTypes.contains(arrayTalendTypes[i])) {
arrayTalendTypesNew.add(arrayTalendTypes[i]);
}
}
return arrayTalendTypesNew.toArray(new String[arrayTalendTypesNew.size()]);
}
public JavaType[] filter(JavaType[] arrayTalendTypes) {
List<String> unsupportedTypes = getUnsupportedTypes();
List<JavaType> arrayTalendTypesNew = new ArrayList<>();
for (int i = 0; i < arrayTalendTypes.length; i++) {
if (!unsupportedTypes.contains(arrayTalendTypes[i].getLabel())) {
arrayTalendTypesNew.add(arrayTalendTypes[i]);
}
}
return arrayTalendTypesNew.toArray(new JavaType[arrayTalendTypesNew.size()]);
}
}
| 2,137 | 0.620028 | 0.612541 | 57 | 36.491226 | 32.303452 | 117 | false | false | 0 | 0 | 0 | 0 | 84 | 0.077679 | 0.368421 | false | false | 2 |
0a6283806bb0c3f129f9bedadc925ea753642072 | 37,314,675,875,127 | 4d32200b1d30cdb996e0d1b941b92a72fd1a06c6 | /oval-xml/src/main/java/org/mitre/oval/xmlschema/oval_definitions_5_windows/CmdletObject.java | 6b7320c848c31839e1540c249f958c017fd54dd2 | []
| no_license | 72nomada/CyberPonk | https://github.com/72nomada/CyberPonk | 3da0c651a2483bc276fbf8317c47c6ec8309b55f | 3c01f61fe19209945fb47b5892e120cb32fb632a | refs/heads/master | 2016-09-09T12:51:59.232000 | 2013-05-25T09:47:17 | 2013-05-25T09:47:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.05.21 at 10:11:54 AM CEST
//
package org.mitre.oval.xmlschema.oval_definitions_5_windows;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.mitre.oval.xmlschema.oval_definitions_5.EntityObjectRecordType;
import org.mitre.oval.xmlschema.oval_definitions_5.EntityObjectStringType;
import org.mitre.oval.xmlschema.oval_definitions_5.EntityObjectVersionType;
import org.mitre.oval.xmlschema.oval_definitions_5.Filter;
import org.mitre.oval.xmlschema.oval_definitions_5.ObjectType;
import org.mitre.oval.xmlschema.oval_definitions_5.Set;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://oval.mitre.org/XMLSchema/oval-definitions-5}ObjectType">
* <sequence>
* <choice>
* <element ref="{http://oval.mitre.org/XMLSchema/oval-definitions-5}set"/>
* <sequence>
* <element name="module_name" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectStringType"/>
* <element name="module_id" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5#windows}EntityObjectGUIDType"/>
* <element name="module_version" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectVersionType"/>
* <element name="verb" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5#windows}EntityObjectCmdletVerbType"/>
* <element name="noun" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectStringType"/>
* <element name="parameters" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectRecordType"/>
* <element name="select" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectRecordType"/>
* <element ref="{http://oval.mitre.org/XMLSchema/oval-definitions-5}filter" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </choice>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"set",
"moduleName",
"moduleId",
"moduleVersion",
"verb",
"noun",
"parameters",
"select",
"filter"
})
public class CmdletObject
extends ObjectType
{
@XmlElement(namespace = "http://oval.mitre.org/XMLSchema/oval-definitions-5")
protected Set set;
@XmlElement(name = "module_name", nillable = true)
protected EntityObjectStringType moduleName;
@XmlElement(name = "module_id", nillable = true)
protected EntityObjectGUIDType moduleId;
@XmlElement(name = "module_version", nillable = true)
protected EntityObjectVersionType moduleVersion;
protected EntityObjectCmdletVerbType verb;
protected EntityObjectStringType noun;
@XmlElement(nillable = true)
protected EntityObjectRecordType parameters;
@XmlElement(nillable = true)
protected EntityObjectRecordType select;
@XmlElement(namespace = "http://oval.mitre.org/XMLSchema/oval-definitions-5")
protected List<Filter> filter;
/**
* Gets the value of the set property.
*
* @return
* possible object is
* {@link Set }
*
*/
public Set getSet() {
return set;
}
/**
* Sets the value of the set property.
*
* @param value
* allowed object is
* {@link Set }
*
*/
public void setSet(Set value) {
this.set = value;
}
/**
* Gets the value of the moduleName property.
*
* @return
* possible object is
* {@link EntityObjectStringType }
*
*/
public EntityObjectStringType getModuleName() {
return moduleName;
}
/**
* Sets the value of the moduleName property.
*
* @param value
* allowed object is
* {@link EntityObjectStringType }
*
*/
public void setModuleName(EntityObjectStringType value) {
this.moduleName = value;
}
/**
* Gets the value of the moduleId property.
*
* @return
* possible object is
* {@link EntityObjectGUIDType }
*
*/
public EntityObjectGUIDType getModuleId() {
return moduleId;
}
/**
* Sets the value of the moduleId property.
*
* @param value
* allowed object is
* {@link EntityObjectGUIDType }
*
*/
public void setModuleId(EntityObjectGUIDType value) {
this.moduleId = value;
}
/**
* Gets the value of the moduleVersion property.
*
* @return
* possible object is
* {@link EntityObjectVersionType }
*
*/
public EntityObjectVersionType getModuleVersion() {
return moduleVersion;
}
/**
* Sets the value of the moduleVersion property.
*
* @param value
* allowed object is
* {@link EntityObjectVersionType }
*
*/
public void setModuleVersion(EntityObjectVersionType value) {
this.moduleVersion = value;
}
/**
* Gets the value of the verb property.
*
* @return
* possible object is
* {@link EntityObjectCmdletVerbType }
*
*/
public EntityObjectCmdletVerbType getVerb() {
return verb;
}
/**
* Sets the value of the verb property.
*
* @param value
* allowed object is
* {@link EntityObjectCmdletVerbType }
*
*/
public void setVerb(EntityObjectCmdletVerbType value) {
this.verb = value;
}
/**
* Gets the value of the noun property.
*
* @return
* possible object is
* {@link EntityObjectStringType }
*
*/
public EntityObjectStringType getNoun() {
return noun;
}
/**
* Sets the value of the noun property.
*
* @param value
* allowed object is
* {@link EntityObjectStringType }
*
*/
public void setNoun(EntityObjectStringType value) {
this.noun = value;
}
/**
* Gets the value of the parameters property.
*
* @return
* possible object is
* {@link EntityObjectRecordType }
*
*/
public EntityObjectRecordType getParameters() {
return parameters;
}
/**
* Sets the value of the parameters property.
*
* @param value
* allowed object is
* {@link EntityObjectRecordType }
*
*/
public void setParameters(EntityObjectRecordType value) {
this.parameters = value;
}
/**
* Gets the value of the select property.
*
* @return
* possible object is
* {@link EntityObjectRecordType }
*
*/
public EntityObjectRecordType getSelect() {
return select;
}
/**
* Sets the value of the select property.
*
* @param value
* allowed object is
* {@link EntityObjectRecordType }
*
*/
public void setSelect(EntityObjectRecordType value) {
this.select = value;
}
/**
* Gets the value of the filter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the filter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFilter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Filter }
*
*
*/
public List<Filter> getFilter() {
if (filter == null) {
filter = new ArrayList<Filter>();
}
return this.filter;
}
}
| UTF-8 | Java | 8,990 | java | CmdletObject.java | Java | []
| null | []
| //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.05.21 at 10:11:54 AM CEST
//
package org.mitre.oval.xmlschema.oval_definitions_5_windows;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.mitre.oval.xmlschema.oval_definitions_5.EntityObjectRecordType;
import org.mitre.oval.xmlschema.oval_definitions_5.EntityObjectStringType;
import org.mitre.oval.xmlschema.oval_definitions_5.EntityObjectVersionType;
import org.mitre.oval.xmlschema.oval_definitions_5.Filter;
import org.mitre.oval.xmlschema.oval_definitions_5.ObjectType;
import org.mitre.oval.xmlschema.oval_definitions_5.Set;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://oval.mitre.org/XMLSchema/oval-definitions-5}ObjectType">
* <sequence>
* <choice>
* <element ref="{http://oval.mitre.org/XMLSchema/oval-definitions-5}set"/>
* <sequence>
* <element name="module_name" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectStringType"/>
* <element name="module_id" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5#windows}EntityObjectGUIDType"/>
* <element name="module_version" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectVersionType"/>
* <element name="verb" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5#windows}EntityObjectCmdletVerbType"/>
* <element name="noun" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectStringType"/>
* <element name="parameters" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectRecordType"/>
* <element name="select" type="{http://oval.mitre.org/XMLSchema/oval-definitions-5}EntityObjectRecordType"/>
* <element ref="{http://oval.mitre.org/XMLSchema/oval-definitions-5}filter" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </choice>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"set",
"moduleName",
"moduleId",
"moduleVersion",
"verb",
"noun",
"parameters",
"select",
"filter"
})
public class CmdletObject
extends ObjectType
{
@XmlElement(namespace = "http://oval.mitre.org/XMLSchema/oval-definitions-5")
protected Set set;
@XmlElement(name = "module_name", nillable = true)
protected EntityObjectStringType moduleName;
@XmlElement(name = "module_id", nillable = true)
protected EntityObjectGUIDType moduleId;
@XmlElement(name = "module_version", nillable = true)
protected EntityObjectVersionType moduleVersion;
protected EntityObjectCmdletVerbType verb;
protected EntityObjectStringType noun;
@XmlElement(nillable = true)
protected EntityObjectRecordType parameters;
@XmlElement(nillable = true)
protected EntityObjectRecordType select;
@XmlElement(namespace = "http://oval.mitre.org/XMLSchema/oval-definitions-5")
protected List<Filter> filter;
/**
* Gets the value of the set property.
*
* @return
* possible object is
* {@link Set }
*
*/
public Set getSet() {
return set;
}
/**
* Sets the value of the set property.
*
* @param value
* allowed object is
* {@link Set }
*
*/
public void setSet(Set value) {
this.set = value;
}
/**
* Gets the value of the moduleName property.
*
* @return
* possible object is
* {@link EntityObjectStringType }
*
*/
public EntityObjectStringType getModuleName() {
return moduleName;
}
/**
* Sets the value of the moduleName property.
*
* @param value
* allowed object is
* {@link EntityObjectStringType }
*
*/
public void setModuleName(EntityObjectStringType value) {
this.moduleName = value;
}
/**
* Gets the value of the moduleId property.
*
* @return
* possible object is
* {@link EntityObjectGUIDType }
*
*/
public EntityObjectGUIDType getModuleId() {
return moduleId;
}
/**
* Sets the value of the moduleId property.
*
* @param value
* allowed object is
* {@link EntityObjectGUIDType }
*
*/
public void setModuleId(EntityObjectGUIDType value) {
this.moduleId = value;
}
/**
* Gets the value of the moduleVersion property.
*
* @return
* possible object is
* {@link EntityObjectVersionType }
*
*/
public EntityObjectVersionType getModuleVersion() {
return moduleVersion;
}
/**
* Sets the value of the moduleVersion property.
*
* @param value
* allowed object is
* {@link EntityObjectVersionType }
*
*/
public void setModuleVersion(EntityObjectVersionType value) {
this.moduleVersion = value;
}
/**
* Gets the value of the verb property.
*
* @return
* possible object is
* {@link EntityObjectCmdletVerbType }
*
*/
public EntityObjectCmdletVerbType getVerb() {
return verb;
}
/**
* Sets the value of the verb property.
*
* @param value
* allowed object is
* {@link EntityObjectCmdletVerbType }
*
*/
public void setVerb(EntityObjectCmdletVerbType value) {
this.verb = value;
}
/**
* Gets the value of the noun property.
*
* @return
* possible object is
* {@link EntityObjectStringType }
*
*/
public EntityObjectStringType getNoun() {
return noun;
}
/**
* Sets the value of the noun property.
*
* @param value
* allowed object is
* {@link EntityObjectStringType }
*
*/
public void setNoun(EntityObjectStringType value) {
this.noun = value;
}
/**
* Gets the value of the parameters property.
*
* @return
* possible object is
* {@link EntityObjectRecordType }
*
*/
public EntityObjectRecordType getParameters() {
return parameters;
}
/**
* Sets the value of the parameters property.
*
* @param value
* allowed object is
* {@link EntityObjectRecordType }
*
*/
public void setParameters(EntityObjectRecordType value) {
this.parameters = value;
}
/**
* Gets the value of the select property.
*
* @return
* possible object is
* {@link EntityObjectRecordType }
*
*/
public EntityObjectRecordType getSelect() {
return select;
}
/**
* Sets the value of the select property.
*
* @param value
* allowed object is
* {@link EntityObjectRecordType }
*
*/
public void setSelect(EntityObjectRecordType value) {
this.select = value;
}
/**
* Gets the value of the filter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the filter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFilter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Filter }
*
*
*/
public List<Filter> getFilter() {
if (filter == null) {
filter = new ArrayList<Filter>();
}
return this.filter;
}
}
| 8,990 | 0.584983 | 0.580645 | 310 | 27 | 27.308157 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.251613 | false | false | 2 |
ad0d19269f8190a0616fa8b155032e88dbea35f4 | 23,768,349,076,776 | c45e646360590ba02030c779c04c6703fe54d9b3 | /src/main/java/persistencia/ConexionBD.java | 390160a22e014f62e4820a53a233588a66c8a62c | []
| no_license | CatatumboGirl/AppexRepository | https://github.com/CatatumboGirl/AppexRepository | 3824263d1e9b00ed819cf1dd30d2031eba819ec3 | bcee6106a8b6cd5bd3d3e4abf4e6802c6517203d | refs/heads/master | 2023-08-15T08:04:30.994000 | 2021-09-30T15:18:04 | 2021-09-30T15:18:04 | 411,508,414 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package persistencia;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/*
Clase para realizar conexión a base de datos dbappex2
*/
public class ConexionBD {
private String conectorInstalado = "jdbc:mysql:";
private String host = "localhost:3306";
private String baseDatos = "dbappex2"; //nombre de la base de datos dbappex2
private String username = "root"; //usuario de mysql
private String password = "mysql"; //password de mysql
private Connection conexion;
private Statement ejecutor;
public ConexionBD() {
conectar();
}
/*
Método para determinar si la conexión se encuentra activa o no.
@return true = conexión activa ; false = conexión inactiva
*/
public boolean isConectado() {
return (this.conexion != null);
}
/*
Método para realizar conexion a la base de datos
*/
public void conectar() {
try
{
String cadenaConexion = conectorInstalado + "//" + host + "/" + baseDatos;
Class.forName("com.mysql.jdbc.Driver"); //registra el driver de conexion para la base de datos
conexion = DriverManager.getConnection(cadenaConexion, username, password);//crea la conexion
ejecutor = conexion.createStatement(); //crea un ejecutor
ejecutor.setQueryTimeout(30); // set timeout to 30 sec. Establece el tiempo de ejecución máximo en 30s
}
//si no se establece la conexión se muestra la excepcion generada
catch(Exception e)
{
e.printStackTrace();
}
}
/*
Método que ejecuta sentencias sql select.
@param sql = contiene la consulta sql que se va a ejecutar.
@return rs = resultset que contiene todos los registros que retorna la consulta.
*/
public ResultSet ejecutarQuery(String sql)
{
ResultSet rs = null;
try
{
rs = ejecutor.executeQuery(sql);
}
catch (Exception e)
{
e.printStackTrace();
}
return rs;
}
/*
Método que ejecuta sentencias sql de update y delete.
@param sql = contiene la consulta sql que se va a ejecutar.
@return cant = entero que indica el numero de registros afectados por la operación.
*/
public int ejecutarUpdate(String sql) {
int cant = 0;
try
{
cant = ejecutor.executeUpdate(sql);
}
catch (Exception e)
{
e.printStackTrace();
}
return cant;
}
/*
Método que ejecuta sentencias sql de inserción
@param sql = contiene la consulta sql que se va a ejecutar.
@return rs = resultset que contiene el id (llaves generadas) del registro insertado.
*/
public ResultSet ejecutarInsert(String sql) {
ResultSet rs = null;
try
{
int cant = ejecutor.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if (cant > 0) {
rs = ejecutor.getGeneratedKeys();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return rs;
}
/*
Método para realizar desconexión de la base de datos
*/
public void desconectar()
{
try {
conexion.close();
conexion = null;
}
catch(Exception e) {
System.out.println(e);
}
}
}
| UTF-8 | Java | 3,554 | java | ConexionBD.java | Java | [
{
"context": "//usuario de mysql\n private String password = \"mysql\"; //password de mysql\n private Connection cone",
"end": 495,
"score": 0.9989756345748901,
"start": 490,
"tag": "PASSWORD",
"value": "mysql"
}
]
| null | []
| package persistencia;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/*
Clase para realizar conexión a base de datos dbappex2
*/
public class ConexionBD {
private String conectorInstalado = "jdbc:mysql:";
private String host = "localhost:3306";
private String baseDatos = "dbappex2"; //nombre de la base de datos dbappex2
private String username = "root"; //usuario de mysql
private String password = "<PASSWORD>"; //password de mysql
private Connection conexion;
private Statement ejecutor;
public ConexionBD() {
conectar();
}
/*
Método para determinar si la conexión se encuentra activa o no.
@return true = conexión activa ; false = conexión inactiva
*/
public boolean isConectado() {
return (this.conexion != null);
}
/*
Método para realizar conexion a la base de datos
*/
public void conectar() {
try
{
String cadenaConexion = conectorInstalado + "//" + host + "/" + baseDatos;
Class.forName("com.mysql.jdbc.Driver"); //registra el driver de conexion para la base de datos
conexion = DriverManager.getConnection(cadenaConexion, username, password);//crea la conexion
ejecutor = conexion.createStatement(); //crea un ejecutor
ejecutor.setQueryTimeout(30); // set timeout to 30 sec. Establece el tiempo de ejecución máximo en 30s
}
//si no se establece la conexión se muestra la excepcion generada
catch(Exception e)
{
e.printStackTrace();
}
}
/*
Método que ejecuta sentencias sql select.
@param sql = contiene la consulta sql que se va a ejecutar.
@return rs = resultset que contiene todos los registros que retorna la consulta.
*/
public ResultSet ejecutarQuery(String sql)
{
ResultSet rs = null;
try
{
rs = ejecutor.executeQuery(sql);
}
catch (Exception e)
{
e.printStackTrace();
}
return rs;
}
/*
Método que ejecuta sentencias sql de update y delete.
@param sql = contiene la consulta sql que se va a ejecutar.
@return cant = entero que indica el numero de registros afectados por la operación.
*/
public int ejecutarUpdate(String sql) {
int cant = 0;
try
{
cant = ejecutor.executeUpdate(sql);
}
catch (Exception e)
{
e.printStackTrace();
}
return cant;
}
/*
Método que ejecuta sentencias sql de inserción
@param sql = contiene la consulta sql que se va a ejecutar.
@return rs = resultset que contiene el id (llaves generadas) del registro insertado.
*/
public ResultSet ejecutarInsert(String sql) {
ResultSet rs = null;
try
{
int cant = ejecutor.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if (cant > 0) {
rs = ejecutor.getGeneratedKeys();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return rs;
}
/*
Método para realizar desconexión de la base de datos
*/
public void desconectar()
{
try {
conexion.close();
conexion = null;
}
catch(Exception e) {
System.out.println(e);
}
}
}
| 3,559 | 0.585076 | 0.580837 | 124 | 27.443548 | 26.218161 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.322581 | false | false | 2 |
cea41f82867b97957233980f47dbbc81276b7612 | 12,438,225,357,843 | dbae9f51af763bf6be7c4ffcf04bcba6f9efa908 | /backend/src/main/java/com/intexsoft/web/controllers/ReviewController.java | 95f444a478261bb676f3c38e625487096fcbc257 | []
| no_license | VitaliyPerelayko/newbookstore | https://github.com/VitaliyPerelayko/newbookstore | 5b75df0aabeafbf109794c7f78dad2aa50625732 | 5f96f72cda0a29f20fe3ad36bac1ac271c21d40c | refs/heads/develop | 2022-06-27T19:24:37.788000 | 2019-07-17T13:48:29 | 2019-07-17T13:48:29 | 193,864,932 | 0 | 0 | null | false | 2022-06-21T01:21:13 | 2019-06-26T08:39:45 | 2019-07-17T13:48:45 | 2022-06-21T01:21:13 | 542 | 0 | 0 | 31 | Java | false | false | package com.intexsoft.web.controllers;
import com.intexsoft.dao.model.Review;
import com.intexsoft.service.entityservice.ReviewService;
import com.intexsoft.web.dto.mapping.ReviewDTOMapper;
import com.intexsoft.web.dto.request.ReviewRequestDTO;
import com.intexsoft.web.dto.response.ReviewResponseDTO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/reviews")
public class ReviewController {
private final ReviewDTOMapper reviewDTOMapper;
private final ReviewService reviewService;
public ReviewController(ReviewDTOMapper reviewDTOMapper, ReviewService reviewService) {
this.reviewDTOMapper = reviewDTOMapper;
this.reviewService = reviewService;
}
@GetMapping("/book_and_user")
public ResponseEntity<List<ReviewResponseDTO>> getByBookAndUser(@RequestParam Long bookId, @RequestParam Long userId) {
List<Review> reviews = reviewService.findByBookAndUser(bookId, userId);
return ResponseEntity.ok(reviews.stream()
.map(reviewDTOMapper::mapReviewToReviewResponseDTO).collect(Collectors.toList()));
}
@GetMapping("/book")
public ResponseEntity<List<ReviewResponseDTO>> getAllByUser(@RequestParam Long id) {
List<Review> reviews = reviewService.findAllByBook(id);
return ResponseEntity.ok(reviews.stream()
.map(reviewDTOMapper::mapReviewToReviewResponseDTO).collect(Collectors.toList()));
}
@GetMapping("/user")
public ResponseEntity<List<ReviewResponseDTO>> getAllByBook(@RequestParam Long id) {
List<Review> reviews = reviewService.findAllByUser(id);
return ResponseEntity.ok(reviews.stream()
.map(reviewDTOMapper::mapReviewToReviewResponseDTO).collect(Collectors.toList()));
}
@GetMapping("/{id}")
public ResponseEntity<ReviewResponseDTO> getById(@PathVariable Long id) {
Review review = reviewService.findById(id).orElseThrow(() ->
new RuntimeException("Review with the given id wasn't found in database"));
return ResponseEntity.ok(reviewDTOMapper.mapReviewToReviewResponseDTO(review));
}
@PostMapping
public ResponseEntity<ReviewResponseDTO> save(@Valid @RequestBody ReviewRequestDTO requestDTO) {
Review review = reviewDTOMapper.mapReviewRequestDTOtoReview(requestDTO);
review.setTime(LocalDateTime.now());
return ResponseEntity.ok(reviewDTOMapper.mapReviewToReviewResponseDTO(
reviewService.save(review)
));
}
@PutMapping("/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN') or #id == authentication.principal.id")
public ResponseEntity<ReviewResponseDTO> update(@PathVariable Long id,
@Valid @RequestBody ReviewRequestDTO requestDTO) {
if (!id.equals(requestDTO.getId())) {
throw new IllegalStateException("Id in URL path and id in request body must be the same");
}
Review review = reviewDTOMapper.mapReviewRequestDTOtoReview(requestDTO);
return ResponseEntity.ok(reviewDTOMapper.mapReviewToReviewResponseDTO(
reviewService.update(review)
));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("hasRole('ROLE_ADMIN') or #id == authentication.principal.id")
public void delete(@PathVariable Long id) {
reviewService.delete(id);
}
}
| UTF-8 | Java | 3,709 | java | ReviewController.java | Java | []
| null | []
| package com.intexsoft.web.controllers;
import com.intexsoft.dao.model.Review;
import com.intexsoft.service.entityservice.ReviewService;
import com.intexsoft.web.dto.mapping.ReviewDTOMapper;
import com.intexsoft.web.dto.request.ReviewRequestDTO;
import com.intexsoft.web.dto.response.ReviewResponseDTO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/reviews")
public class ReviewController {
private final ReviewDTOMapper reviewDTOMapper;
private final ReviewService reviewService;
public ReviewController(ReviewDTOMapper reviewDTOMapper, ReviewService reviewService) {
this.reviewDTOMapper = reviewDTOMapper;
this.reviewService = reviewService;
}
@GetMapping("/book_and_user")
public ResponseEntity<List<ReviewResponseDTO>> getByBookAndUser(@RequestParam Long bookId, @RequestParam Long userId) {
List<Review> reviews = reviewService.findByBookAndUser(bookId, userId);
return ResponseEntity.ok(reviews.stream()
.map(reviewDTOMapper::mapReviewToReviewResponseDTO).collect(Collectors.toList()));
}
@GetMapping("/book")
public ResponseEntity<List<ReviewResponseDTO>> getAllByUser(@RequestParam Long id) {
List<Review> reviews = reviewService.findAllByBook(id);
return ResponseEntity.ok(reviews.stream()
.map(reviewDTOMapper::mapReviewToReviewResponseDTO).collect(Collectors.toList()));
}
@GetMapping("/user")
public ResponseEntity<List<ReviewResponseDTO>> getAllByBook(@RequestParam Long id) {
List<Review> reviews = reviewService.findAllByUser(id);
return ResponseEntity.ok(reviews.stream()
.map(reviewDTOMapper::mapReviewToReviewResponseDTO).collect(Collectors.toList()));
}
@GetMapping("/{id}")
public ResponseEntity<ReviewResponseDTO> getById(@PathVariable Long id) {
Review review = reviewService.findById(id).orElseThrow(() ->
new RuntimeException("Review with the given id wasn't found in database"));
return ResponseEntity.ok(reviewDTOMapper.mapReviewToReviewResponseDTO(review));
}
@PostMapping
public ResponseEntity<ReviewResponseDTO> save(@Valid @RequestBody ReviewRequestDTO requestDTO) {
Review review = reviewDTOMapper.mapReviewRequestDTOtoReview(requestDTO);
review.setTime(LocalDateTime.now());
return ResponseEntity.ok(reviewDTOMapper.mapReviewToReviewResponseDTO(
reviewService.save(review)
));
}
@PutMapping("/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN') or #id == authentication.principal.id")
public ResponseEntity<ReviewResponseDTO> update(@PathVariable Long id,
@Valid @RequestBody ReviewRequestDTO requestDTO) {
if (!id.equals(requestDTO.getId())) {
throw new IllegalStateException("Id in URL path and id in request body must be the same");
}
Review review = reviewDTOMapper.mapReviewRequestDTOtoReview(requestDTO);
return ResponseEntity.ok(reviewDTOMapper.mapReviewToReviewResponseDTO(
reviewService.update(review)
));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("hasRole('ROLE_ADMIN') or #id == authentication.principal.id")
public void delete(@PathVariable Long id) {
reviewService.delete(id);
}
}
| 3,709 | 0.720949 | 0.720949 | 87 | 41.632183 | 33.114609 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.425287 | false | false | 2 |
5fcca217c806a6313cc164ac1bb324a27ea4a25d | 38,998,303,049,885 | b8932a0a51d34f32cca3d9e607ee90fd68b6f2a3 | /app/src/main/java/FontRatio/Ratio_Message.java | da437ddd58679442769c260e82aa5d1c5c21a016 | []
| no_license | kenait1224/STUST-Student-Assistant | https://github.com/kenait1224/STUST-Student-Assistant | 4aee1f2329bfa759a142eaa983d06ab1bba96bb9 | f94fdc3dfc2152b4150335908038fde135af23db | refs/heads/main | 2023-04-02T01:06:54.008000 | 2021-03-27T12:30:35 | 2021-03-27T12:30:35 | 345,284,561 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package FontRatio;
public class Ratio_Message extends Ratio {
private float MessageContentHeight_Weight = (float) 0.12;
public Ratio_Message(int width, int height) {
super(width, height);
}
public int getMessageContentHeight() {
return (int) (MessageContentHeight_Weight * this.DisplayHeight);
}
}
| UTF-8 | Java | 339 | java | Ratio_Message.java | Java | []
| null | []
| package FontRatio;
public class Ratio_Message extends Ratio {
private float MessageContentHeight_Weight = (float) 0.12;
public Ratio_Message(int width, int height) {
super(width, height);
}
public int getMessageContentHeight() {
return (int) (MessageContentHeight_Weight * this.DisplayHeight);
}
}
| 339 | 0.684366 | 0.675516 | 14 | 23.214285 | 24.770889 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 2 |
e2ad951e7493b16848f9044ecfd2ede03e3e0a21 | 38,998,303,052,306 | 24d8cf871b092b2d60fc85d5320e1bc761a7cbe2 | /iText/rev2818-3306/base-trunk-2818/com/lowagie/text/pdf/interfaces/PdfRunDirection.java | ab01e64e9a6291146f66943f5fe92ca1903a3ee5 | []
| no_license | joliebig/featurehouse_fstmerge_examples | https://github.com/joliebig/featurehouse_fstmerge_examples | af1b963537839d13e834f829cf51f8ad5e6ffe76 | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | refs/heads/master | 2016-09-05T10:24:50.974000 | 2013-03-28T16:28:47 | 2013-03-28T16:28:47 | 9,080,611 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lowagie.text.pdf.interfaces;
public interface PdfRunDirection {
public void setRunDirection(int runDirection);
public int getRunDirection();
}
| UTF-8 | Java | 194 | java | PdfRunDirection.java | Java | []
| null | []
|
package com.lowagie.text.pdf.interfaces;
public interface PdfRunDirection {
public void setRunDirection(int runDirection);
public int getRunDirection();
}
| 194 | 0.659794 | 0.659794 | 10 | 18.200001 | 17.870646 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 2 |
6e25526e441dbb205a968edceeb29f18763d96b8 | 35,081,292,913,302 | bce31e3c7517825fdfa3151322e5d60d6ee59538 | /navisu-widgets/src/main/java/bzh/terrevirtuelle/navisu/widgets/radialmenu/menu/RadialMenuSeparator.java | 832953263e2b8432da74c1da988fce5a959e0562 | []
| no_license | terre-virtuelle/navisu | https://github.com/terre-virtuelle/navisu | b0355461b9c77035834f79646036a9dc002f203d | 97bc2baaed37f83c9b773f1973a2a65683dc9e79 | refs/heads/master | 2021-08-04T03:41:09.226000 | 2021-06-17T11:27:22 | 2021-06-17T11:27:22 | 14,243,882 | 31 | 16 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bzh.terrevirtuelle.navisu.widgets.radialmenu.menu;
/**
* NaVisu
*
* @author Jordan Mens
*/
public class RadialMenuSeparator extends RadialMenuItem {
public RadialMenuSeparator() {
}
protected void update() {
//TODO Must be review
double delta = 2;
double center = (getOuterRadius() + getInnerRadius()) / 2;
System.out.println("update "+ getLength());
//Arc lenght angle
double arcAngleLengthInRadians = Math.toRadians(getLength());
//Angle rotation of the item
double itemAngleInRadians = Math.toRadians(getStartAngle() + ANGLE_TO_START_AT_ZERO_DEGREE);
moveTo.setX((center - delta) * Math.cos(itemAngleInRadians));
moveTo.setY((center - delta) * Math.sin(itemAngleInRadians));
lineTo.setX((center + delta ) * Math.cos(itemAngleInRadians));
lineTo.setY((center + delta ) * Math.sin(itemAngleInRadians));
arcTo.setX((center + delta) * Math.cos(itemAngleInRadians + arcAngleLengthInRadians));
arcTo.setY((center + delta) * Math.sin(itemAngleInRadians + arcAngleLengthInRadians));
arcTo.setRadiusX(center);
arcTo.setRadiusY(center) ;
arcTo.setSweepFlag(true);
lineTo2.setX((center - delta) * Math.cos(itemAngleInRadians + arcAngleLengthInRadians));
lineTo2.setY((center - delta) * Math.sin(itemAngleInRadians + arcAngleLengthInRadians));
arcToInner.setX((center - delta) * Math.cos(itemAngleInRadians));
arcToInner.setY((center - delta) * Math.sin(itemAngleInRadians));
arcToInner.setRadiusX(center);
arcToInner.setRadiusY(center);
}
}
| UTF-8 | Java | 1,668 | java | RadialMenuSeparator.java | Java | [
{
"context": "ets.radialmenu.menu;\n\n\n/**\n * NaVisu\n *\n * @author Jordan Mens\n */\npublic class RadialMenuSeparator extends Radi",
"end": 100,
"score": 0.9998085498809814,
"start": 89,
"tag": "NAME",
"value": "Jordan Mens"
}
]
| null | []
| package bzh.terrevirtuelle.navisu.widgets.radialmenu.menu;
/**
* NaVisu
*
* @author <NAME>
*/
public class RadialMenuSeparator extends RadialMenuItem {
public RadialMenuSeparator() {
}
protected void update() {
//TODO Must be review
double delta = 2;
double center = (getOuterRadius() + getInnerRadius()) / 2;
System.out.println("update "+ getLength());
//Arc lenght angle
double arcAngleLengthInRadians = Math.toRadians(getLength());
//Angle rotation of the item
double itemAngleInRadians = Math.toRadians(getStartAngle() + ANGLE_TO_START_AT_ZERO_DEGREE);
moveTo.setX((center - delta) * Math.cos(itemAngleInRadians));
moveTo.setY((center - delta) * Math.sin(itemAngleInRadians));
lineTo.setX((center + delta ) * Math.cos(itemAngleInRadians));
lineTo.setY((center + delta ) * Math.sin(itemAngleInRadians));
arcTo.setX((center + delta) * Math.cos(itemAngleInRadians + arcAngleLengthInRadians));
arcTo.setY((center + delta) * Math.sin(itemAngleInRadians + arcAngleLengthInRadians));
arcTo.setRadiusX(center);
arcTo.setRadiusY(center) ;
arcTo.setSweepFlag(true);
lineTo2.setX((center - delta) * Math.cos(itemAngleInRadians + arcAngleLengthInRadians));
lineTo2.setY((center - delta) * Math.sin(itemAngleInRadians + arcAngleLengthInRadians));
arcToInner.setX((center - delta) * Math.cos(itemAngleInRadians));
arcToInner.setY((center - delta) * Math.sin(itemAngleInRadians));
arcToInner.setRadiusX(center);
arcToInner.setRadiusY(center);
}
}
| 1,663 | 0.66187 | 0.659472 | 47 | 34.489361 | 32.82505 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489362 | false | false | 2 |
edb54f0ce768ec4e0e03cecec8dedd6f330165bf | 39,376,260,189,419 | e919de92705a30267ac12f4346a974b68d630a68 | /jmetal/jmetal/metaheuristics/splot/ProductSolution.java | a2d591d2b948ebb5111aa2c9f13e081b1d485747 | []
| no_license | peterb0yd/SPLOT | https://github.com/peterb0yd/SPLOT | 41332e6039a5bab1451210d0d23af1eec3cabc5c | 32566f3c983e39f188cd9123ca17e66200ff9fe3 | refs/heads/master | 2021-01-01T06:17:20.447000 | 2014-12-08T04:09:17 | 2014-12-08T04:09:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jmetal.metaheuristics.splot;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import jmetal.core.Solution;
import jmetal.core.SolutionSet;
import jmetal.util.Configuration;
import jmetal.util.JMException;
public class ProductSolution {
private static int[][] products;
private static int numberOfFeatures;
public static void print(List<Solution> solutionsList, String algorithmType, int amount, int featureNum) {
products = new int[amount][numberOfFeatures];
numberOfFeatures = featureNum;
readSolutionsFromFile();
printSolutionsToFile(solutionsList, algorithmType);
}
private static void readSolutionsFromFile() {
try {
// Read "solutions" file to obtain products
BufferedReader br = new BufferedReader(new FileReader("productsCreated"));
String line;
String[] line_string = new String[numberOfFeatures];
int line_count = 0;
// Set each line of file to int array - represents each product
while ((line = br.readLine()) != null) {
int[] product = new int[numberOfFeatures];
line_string = line.toString().replace(",", "").split(" ");
for (int i = 0; i < product.length; i++) {
product[i] = Integer.parseInt(line_string[i]);
}
products[line_count] = product; // add product to product array
line_count++;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printSolutionsToFile(List<Solution> solutionsList, String algorithmType) {
try {
FileOutputStream fos = new FileOutputStream("blank");
switch (algorithmType) {
case "IBEA": fos = new FileOutputStream("IBEA_Solutions"); break;
case "NSGAII": fos = new FileOutputStream("NSGAII_Solutions"); break;
case "RANDOM": fos = new FileOutputStream("RANDOM_Solutions"); break;
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
int productIndex = 0;
int numberOfVariables = solutionsList.get(0).getDecisionVariables().length;
for (Solution solution : solutionsList) {
bw.write("Product Line Solution " + (solutionsList.indexOf(solution)+1));
bw.write("\t\t Objectives: " + solution.toString());
bw.newLine();
for (int i = 0; i < numberOfVariables; i++) {
productIndex = (int) solution.getDecisionVariables()[i].getValue();
if (productIndex < 1000){
bw.write("Product " + productIndex + ": " + Arrays.toString(products[productIndex]));
bw.newLine();
}
}
bw.newLine();
}
bw.close();
} catch (IOException | JMException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 2,794 | java | ProductSolution.java | Java | []
| null | []
| package jmetal.metaheuristics.splot;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import jmetal.core.Solution;
import jmetal.core.SolutionSet;
import jmetal.util.Configuration;
import jmetal.util.JMException;
public class ProductSolution {
private static int[][] products;
private static int numberOfFeatures;
public static void print(List<Solution> solutionsList, String algorithmType, int amount, int featureNum) {
products = new int[amount][numberOfFeatures];
numberOfFeatures = featureNum;
readSolutionsFromFile();
printSolutionsToFile(solutionsList, algorithmType);
}
private static void readSolutionsFromFile() {
try {
// Read "solutions" file to obtain products
BufferedReader br = new BufferedReader(new FileReader("productsCreated"));
String line;
String[] line_string = new String[numberOfFeatures];
int line_count = 0;
// Set each line of file to int array - represents each product
while ((line = br.readLine()) != null) {
int[] product = new int[numberOfFeatures];
line_string = line.toString().replace(",", "").split(" ");
for (int i = 0; i < product.length; i++) {
product[i] = Integer.parseInt(line_string[i]);
}
products[line_count] = product; // add product to product array
line_count++;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printSolutionsToFile(List<Solution> solutionsList, String algorithmType) {
try {
FileOutputStream fos = new FileOutputStream("blank");
switch (algorithmType) {
case "IBEA": fos = new FileOutputStream("IBEA_Solutions"); break;
case "NSGAII": fos = new FileOutputStream("NSGAII_Solutions"); break;
case "RANDOM": fos = new FileOutputStream("RANDOM_Solutions"); break;
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
int productIndex = 0;
int numberOfVariables = solutionsList.get(0).getDecisionVariables().length;
for (Solution solution : solutionsList) {
bw.write("Product Line Solution " + (solutionsList.indexOf(solution)+1));
bw.write("\t\t Objectives: " + solution.toString());
bw.newLine();
for (int i = 0; i < numberOfVariables; i++) {
productIndex = (int) solution.getDecisionVariables()[i].getValue();
if (productIndex < 1000){
bw.write("Product " + productIndex + ": " + Arrays.toString(products[productIndex]));
bw.newLine();
}
}
bw.newLine();
}
bw.close();
} catch (IOException | JMException e) {
e.printStackTrace();
}
}
}
| 2,794 | 0.701145 | 0.697566 | 87 | 31.114943 | 25.89609 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.873563 | false | false | 2 |
14d488d652282bded4e10f501571a1072128ff21 | 37,684,043,078,700 | ea1470cd0aa3c8d0a47268a0714393db81c66ed9 | /GledalisceCheckIn/app/src/main/java/com/example/amadej/gledaliscecheckin/NovaPredstava.java | 812e38121b5a1dceb5bd8903a539a3e77cd7a598 | []
| no_license | skornsek/UVGledalisce | https://github.com/skornsek/UVGledalisce | 6a0a0043d8f760bebf1b8ba040c81a6b00c974ca | 8cf207d0ad1cd915feb9d37406f7cc555582e197 | refs/heads/master | 2022-12-13T05:00:20.886000 | 2020-03-07T18:41:25 | 2020-03-07T18:41:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.amadej.gledaliscecheckin;
import android.app.ProgressDialog;
import android.content.Intent;
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.EditText;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class NovaPredstava extends Fragment {
private EditText input_ime_predstave;
private Button btn_dodaj_predstavo;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_nova_predstava, container, false);
getActivity().setTitle("Dodaj predstavo");
input_ime_predstave = v.findViewById(R.id.input_predstava_naslov_predstave);
btn_dodaj_predstavo = v.findViewById(R.id.btn_predstava_dodaj_predstavo);
btn_dodaj_predstavo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ime_predstave = input_ime_predstave.getText().toString().trim();
if (ime_predstave.length() > 0) {
//pošlje v main activiti in doda v bazo
//listener.onInputNovaPredstavaSend(new Predstava(ime_predstave));
addItemToSheet();
//input_ime_predstave.setText("");
/*
//nafili podakte
ArrayList<Predstava> list = new ArrayList<>();
adapter = new PredstaveAdapterListView(v.getContext(), R.layout.predstava, list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
*/
} else {
Toast.makeText(getActivity(), "Vpišite ime predstave", Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
private void addItemToSheet() {
final ProgressDialog loading = ProgressDialog.show(getContext(),"Dodajanje predstave","Prosimo počakajte");
final String naslov = input_ime_predstave.getText().toString().trim();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://script.google.com/macros/s/AKfycbxr4Dv-AfWK-n927DhLpLoqVIZQvpGBPWi8QXihkR0E2PmBpXpv/exec",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
loading.dismiss();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Predstave()).commit();
//Toast.makeText(getContext(),"Gledalec dodan ID:"+gledalecID,Toast.LENGTH_LONG).show();
/*
input_ime.setText("");
input_priimek.setText("");
input_sedez.setText("");
input_vrsta.setText("");
input_telefon.setText("");
input_email.setText("");
Intent intent = new Intent(getContext(), WriteNFCActivity.class);
intent.putExtra("ID_GLEDALCA", gledalecID);
intent.putExtra("ID_IME", ime);
intent.putExtra("ID_PRIIMEK", priimek);
intent.putExtra("ID_SEDEZ", sedez);
intent.putExtra("ID_VRSTA", vrsta);
intent.putExtra("ID_OBISKI", "6");
*/
//startActivity(intent);
//Intent intent = new Intent(getContext(),MainActivity.class);
//startActivity(intent);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),"Pri vstavljanju je prišlo do napake",Toast.LENGTH_LONG).show();
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> parmas = new HashMap<>();
//here we pass params
parmas.put("action","addPredstavaSheet");
parmas.put("naslov",naslov);
return parmas;
}
};
int socketTimeOut = 50000;// u can change this .. here it is 50 seconds
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
RequestQueue queue = Volley.newRequestQueue(this.getContext());
queue.add(stringRequest);
}
}
| UTF-8 | Java | 5,404 | java | NovaPredstava.java | Java | [
{
"context": "package com.example.amadej.gledaliscecheckin;\n\nimport android.app.ProgressDi",
"end": 26,
"score": 0.9992578029632568,
"start": 20,
"tag": "USERNAME",
"value": "amadej"
}
]
| null | []
| package com.example.amadej.gledaliscecheckin;
import android.app.ProgressDialog;
import android.content.Intent;
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.EditText;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class NovaPredstava extends Fragment {
private EditText input_ime_predstave;
private Button btn_dodaj_predstavo;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_nova_predstava, container, false);
getActivity().setTitle("Dodaj predstavo");
input_ime_predstave = v.findViewById(R.id.input_predstava_naslov_predstave);
btn_dodaj_predstavo = v.findViewById(R.id.btn_predstava_dodaj_predstavo);
btn_dodaj_predstavo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ime_predstave = input_ime_predstave.getText().toString().trim();
if (ime_predstave.length() > 0) {
//pošlje v main activiti in doda v bazo
//listener.onInputNovaPredstavaSend(new Predstava(ime_predstave));
addItemToSheet();
//input_ime_predstave.setText("");
/*
//nafili podakte
ArrayList<Predstava> list = new ArrayList<>();
adapter = new PredstaveAdapterListView(v.getContext(), R.layout.predstava, list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
*/
} else {
Toast.makeText(getActivity(), "Vpišite ime predstave", Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
private void addItemToSheet() {
final ProgressDialog loading = ProgressDialog.show(getContext(),"Dodajanje predstave","Prosimo počakajte");
final String naslov = input_ime_predstave.getText().toString().trim();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://script.google.com/macros/s/AKfycbxr4Dv-AfWK-n927DhLpLoqVIZQvpGBPWi8QXihkR0E2PmBpXpv/exec",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
loading.dismiss();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Predstave()).commit();
//Toast.makeText(getContext(),"Gledalec dodan ID:"+gledalecID,Toast.LENGTH_LONG).show();
/*
input_ime.setText("");
input_priimek.setText("");
input_sedez.setText("");
input_vrsta.setText("");
input_telefon.setText("");
input_email.setText("");
Intent intent = new Intent(getContext(), WriteNFCActivity.class);
intent.putExtra("ID_GLEDALCA", gledalecID);
intent.putExtra("ID_IME", ime);
intent.putExtra("ID_PRIIMEK", priimek);
intent.putExtra("ID_SEDEZ", sedez);
intent.putExtra("ID_VRSTA", vrsta);
intent.putExtra("ID_OBISKI", "6");
*/
//startActivity(intent);
//Intent intent = new Intent(getContext(),MainActivity.class);
//startActivity(intent);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),"Pri vstavljanju je prišlo do napake",Toast.LENGTH_LONG).show();
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> parmas = new HashMap<>();
//here we pass params
parmas.put("action","addPredstavaSheet");
parmas.put("naslov",naslov);
return parmas;
}
};
int socketTimeOut = 50000;// u can change this .. here it is 50 seconds
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
RequestQueue queue = Volley.newRequestQueue(this.getContext());
queue.add(stringRequest);
}
}
| 5,404 | 0.592407 | 0.589074 | 139 | 37.848923 | 34.056641 | 182 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.755396 | false | false | 2 |
04d2fa84cafafc95955e1468faae76df585fc5c8 | 32,057,635,897,421 | b0454d3e034af6d00635dd74fdd181fd44a3ddde | /src/main/java/camt/se234/lab11/exception/NoDataException.java | b43952df2397b8a9d105fdecc2c0ff6ea3b3318e | []
| no_license | bas512/lab234-lab11-backend | https://github.com/bas512/lab234-lab11-backend | d8aa0107ef838d170e640f6d4f18fd15e3e71246 | ea1104f99a8f5ec1dd5d45a520a829799d913bb8 | refs/heads/master | 2020-03-13T12:37:05.215000 | 2018-04-27T07:30:12 | 2018-04-27T07:30:12 | 131,122,980 | 0 | 0 | null | true | 2018-04-26T08:16:57 | 2018-04-26T08:16:56 | 2018-04-26T02:34:55 | 2018-04-18T07:06:57 | 59 | 0 | 0 | 0 | null | false | null | package camt.se234.lab11.exception;
public class NoDataException extends RuntimeException {
}
| UTF-8 | Java | 95 | java | NoDataException.java | Java | []
| null | []
| package camt.se234.lab11.exception;
public class NoDataException extends RuntimeException {
}
| 95 | 0.831579 | 0.778947 | 4 | 22.75 | 23.349251 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 2 |
cf88a112832f3d4315bc0253c5490201d3e8f192 | 25,692,494,414,666 | 81b172d96735cc1238d8747c3cff6d5c5884bcb8 | /src/organizationalunits/CommiteeType.java | 4820be9cbe31384dd77ec37f2f8c4b14954d7386 | []
| no_license | fylmz/BP18 | https://github.com/fylmz/BP18 | 3f3abd640b7e4081a6123a314f6dd53f9405afad | 3368f4db868bdfe3ff417b711ddc6fa4958eedc6 | refs/heads/master | 2018-11-07T00:00:20.759000 | 2018-09-28T18:49:45 | 2018-09-28T18:49:45 | 139,082,291 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package organizationalunits;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
@Entity
@Access(AccessType.PROPERTY)
public class CommiteeType extends UnitOfWorkType {
private BooleanProperty internal;
private StringProperty corporateRelevance;
private IntegerProperty meetingsPerYear;
// private StringProperty mission;
private final String orgType = "Committee";
@Override
public void unbindProperties() {
nameProperty().unbind();
descriptionProperty().unbind();
missionProperty().unbind();
internal.unbind();
corporateRelevance.unbind();
meetingsPerYear.unbind();
}
/////////////// Getter/Setter ////////////////
public final BooleanProperty internalProperty() {
if (internal == null) {
internal = new SimpleBooleanProperty();
}
return this.internal;
}
public final StringProperty corporateRelevanceProperty() {
if (corporateRelevance == null) {
corporateRelevance = new SimpleStringProperty();
}
return this.corporateRelevance;
}
public final String getCorporateRelevance() {
return this.corporateRelevanceProperty().get();
}
public final void setCorporateRelevance(final String corporateRelevance) {
this.corporateRelevanceProperty().set(corporateRelevance);
}
public final boolean isInternal() {
return this.internalProperty().get();
}
public final void setInternal(final boolean internal) {
this.internalProperty().set(internal);
}
public final IntegerProperty meetingsPerYearProperty() {
if(meetingsPerYear == null){
meetingsPerYear = new SimpleIntegerProperty();
}
return this.meetingsPerYear;
}
public final int getMeetingsPerYear() {
return this.meetingsPerYearProperty().get();
}
public final void setMeetingsPerYear(final int meetingsPerYear) {
this.meetingsPerYearProperty().set(meetingsPerYear);
}
// public final StringProperty missionProperty() {
//
// if (mission == null) {
//
// mission = new SimpleStringProperty();
// }
// return this.mission;
// }
//
// public final String getMission() {
//
// return this.missionProperty().get();
// }
//
// public final void setMission(final String mission) {
//
// this.missionProperty().set(mission);
// }
public String getOrgType() {
return orgType;
}
}
| UTF-8 | Java | 2,803 | java | CommiteeType.java | Java | []
| null | []
| package organizationalunits;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
@Entity
@Access(AccessType.PROPERTY)
public class CommiteeType extends UnitOfWorkType {
private BooleanProperty internal;
private StringProperty corporateRelevance;
private IntegerProperty meetingsPerYear;
// private StringProperty mission;
private final String orgType = "Committee";
@Override
public void unbindProperties() {
nameProperty().unbind();
descriptionProperty().unbind();
missionProperty().unbind();
internal.unbind();
corporateRelevance.unbind();
meetingsPerYear.unbind();
}
/////////////// Getter/Setter ////////////////
public final BooleanProperty internalProperty() {
if (internal == null) {
internal = new SimpleBooleanProperty();
}
return this.internal;
}
public final StringProperty corporateRelevanceProperty() {
if (corporateRelevance == null) {
corporateRelevance = new SimpleStringProperty();
}
return this.corporateRelevance;
}
public final String getCorporateRelevance() {
return this.corporateRelevanceProperty().get();
}
public final void setCorporateRelevance(final String corporateRelevance) {
this.corporateRelevanceProperty().set(corporateRelevance);
}
public final boolean isInternal() {
return this.internalProperty().get();
}
public final void setInternal(final boolean internal) {
this.internalProperty().set(internal);
}
public final IntegerProperty meetingsPerYearProperty() {
if(meetingsPerYear == null){
meetingsPerYear = new SimpleIntegerProperty();
}
return this.meetingsPerYear;
}
public final int getMeetingsPerYear() {
return this.meetingsPerYearProperty().get();
}
public final void setMeetingsPerYear(final int meetingsPerYear) {
this.meetingsPerYearProperty().set(meetingsPerYear);
}
// public final StringProperty missionProperty() {
//
// if (mission == null) {
//
// mission = new SimpleStringProperty();
// }
// return this.mission;
// }
//
// public final String getMission() {
//
// return this.missionProperty().get();
// }
//
// public final void setMission(final String mission) {
//
// this.missionProperty().set(mission);
// }
public String getOrgType() {
return orgType;
}
}
| 2,803 | 0.711737 | 0.711737 | 121 | 21.165289 | 20.964491 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.297521 | false | false | 2 |
4b9fd2cfd3c4afe959217e61e23d1c6240266019 | 35,579,509,120,480 | c60137d893a06902bc7743ef013471a59727b4f1 | /src/main/java/com/lingwei/um/web/UserTokenController.java | 1112eebff2f90614c6dc0d2a7796cd73b75a93b7 | []
| no_license | zgw1469039806/BusinessErp | https://github.com/zgw1469039806/BusinessErp | 7884f756277ef68f50355120d152b1a19df932d4 | 35706f5efbcfa42ae41271052da0d5ba5c03b60e | refs/heads/master | 2020-04-13T07:16:34.321000 | 2018-12-25T11:33:07 | 2018-12-25T11:33:07 | 163,046,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lingwei.um.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import com.lingwei.framework.core.BaseController;
/**
* <p>
* 登陆token验证 前端控制器
* </p>
*
* @author 马浩然
* @since 2018-12-14
*/
@Controller
@RequestMapping("/um/userToken")
public class UserTokenController extends BaseController {
}
| UTF-8 | Java | 407 | java | UserTokenController.java | Java | [
{
"context": "*\n * <p>\n * 登陆token验证 前端控制器\n * </p>\n *\n * @author 马浩然\n * @since 2018-12-14\n */\n@Controller\n@RequestMapp",
"end": 250,
"score": 0.9990018606185913,
"start": 247,
"tag": "NAME",
"value": "马浩然"
}
]
| null | []
| package com.lingwei.um.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import com.lingwei.framework.core.BaseController;
/**
* <p>
* 登陆token验证 前端控制器
* </p>
*
* @author 马浩然
* @since 2018-12-14
*/
@Controller
@RequestMapping("/um/userToken")
public class UserTokenController extends BaseController {
}
| 407 | 0.751958 | 0.731071 | 21 | 17.190475 | 20.226383 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | false | false | 2 |
722e165d2141ac4663d594558db8608e036b0e4e | 39,298,950,797,272 | 0085acce00bbd20658f312f30575632b6272090d | /src/algorithm/Search2DMatrix.java | aa0f6979b67830d55494b96836071b99ea5fd41c | []
| no_license | garderobin/Leetcode | https://github.com/garderobin/Leetcode | 52fce8279e4963bc7824a19aae903ca6aad83867 | ea10ce7fe465431399e444c6ecb0b7560b17e1e4 | refs/heads/master | 2021-01-17T14:43:49.423000 | 2018-11-12T00:55:47 | 2018-11-12T00:55:47 | 51,183,667 | 0 | 1 | null | false | 2018-11-12T00:55:48 | 2016-02-06T01:00:36 | 2018-09-21T04:50:26 | 2018-11-12T00:55:48 | 904 | 0 | 1 | 0 | Java | false | null | package algorithm;
public class Search2DMatrix {
/**
* Don't treat it as a 2D-Matrix. Treat it as a sorted list.
* 一个典型例子:利用除余的办法来降维。这里降二维为一维。
* @param matrix
* @param target
* @return
*/
public boolean searchMatrixDiscussion(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) {
return false;
}
int start = 0, rows = matrix.length, cols = matrix[0].length;
int end = rows * cols - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (matrix[mid / cols][mid % cols] == target) {
return true;
}
if (matrix[mid / cols][mid % cols] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return false;
}
public static boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) {
return false;
}
int rnum = matrix.length;
int cnum = matrix[0].length;
if (target > matrix[rnum - 1][cnum - 1] || target < matrix[0][0]) {
return false;
}
return searchRow(matrix, target, 0, rnum - 1, cnum);
}
private static boolean searchRow(int[][] matrix, int target, int startRow, int endRow, int cnum) {
if (target > matrix[endRow][cnum - 1]) {
//return 2;
return false;
}
if (target < matrix[startRow][0]) {
//return -1;
return false;
}
if (startRow == endRow) {
// search in one row
return searchCol(matrix, target, startRow, 0, cnum - 1);
}
int k = (endRow - startRow) / 2 + startRow;
if (target < matrix[k][cnum - 1]) {
return searchRow(matrix, target, startRow, k, cnum);
}
if (target > matrix[k][cnum - 1]) {
return searchRow(matrix, target, k + 1, endRow, cnum);
}
return true;
}
private static boolean searchCol(int[][] matrix, int target, int row, int startCol, int endCol) {
if (target > matrix[row][endCol] || target < matrix[row][startCol]) {
return false;
}
if (startCol == endCol) {
return target == matrix[row][startCol];
}
int k = startCol + (endCol - startCol) / 2;
if (target < matrix[row][k]) {
return searchCol(matrix, target, row, startCol, k);
}
if (target > matrix[row][k]) {
return searchCol(matrix, target, row, k+1, endCol);
}
return true;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 50}
};
int target = 3;
System.out.println(searchMatrix(matrix, target));
}
}
| UTF-8 | Java | 2,723 | java | Search2DMatrix.java | Java | []
| null | []
| package algorithm;
public class Search2DMatrix {
/**
* Don't treat it as a 2D-Matrix. Treat it as a sorted list.
* 一个典型例子:利用除余的办法来降维。这里降二维为一维。
* @param matrix
* @param target
* @return
*/
public boolean searchMatrixDiscussion(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) {
return false;
}
int start = 0, rows = matrix.length, cols = matrix[0].length;
int end = rows * cols - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (matrix[mid / cols][mid % cols] == target) {
return true;
}
if (matrix[mid / cols][mid % cols] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return false;
}
public static boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) {
return false;
}
int rnum = matrix.length;
int cnum = matrix[0].length;
if (target > matrix[rnum - 1][cnum - 1] || target < matrix[0][0]) {
return false;
}
return searchRow(matrix, target, 0, rnum - 1, cnum);
}
private static boolean searchRow(int[][] matrix, int target, int startRow, int endRow, int cnum) {
if (target > matrix[endRow][cnum - 1]) {
//return 2;
return false;
}
if (target < matrix[startRow][0]) {
//return -1;
return false;
}
if (startRow == endRow) {
// search in one row
return searchCol(matrix, target, startRow, 0, cnum - 1);
}
int k = (endRow - startRow) / 2 + startRow;
if (target < matrix[k][cnum - 1]) {
return searchRow(matrix, target, startRow, k, cnum);
}
if (target > matrix[k][cnum - 1]) {
return searchRow(matrix, target, k + 1, endRow, cnum);
}
return true;
}
private static boolean searchCol(int[][] matrix, int target, int row, int startCol, int endCol) {
if (target > matrix[row][endCol] || target < matrix[row][startCol]) {
return false;
}
if (startCol == endCol) {
return target == matrix[row][startCol];
}
int k = startCol + (endCol - startCol) / 2;
if (target < matrix[row][k]) {
return searchCol(matrix, target, row, startCol, k);
}
if (target > matrix[row][k]) {
return searchCol(matrix, target, row, k+1, endCol);
}
return true;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 50}
};
int target = 3;
System.out.println(searchMatrix(matrix, target));
}
}
| 2,723 | 0.537655 | 0.518921 | 96 | 26.802084 | 23.003904 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.270833 | false | false | 2 |
6503fe21e31b9d979e29a9f2809cb025f2bb7ece | 37,366,215,507,805 | b4eef59111930d41d9d9de75274cac5c6cbf7f11 | /src/Estado.java | 11113433f72a9aeaf36630ee26258670bd6ba66a | []
| no_license | irahel/TCP-Protocol | https://github.com/irahel/TCP-Protocol | fe63b8edf250dc810c59540d19e5f24efa0ac219 | 7ed13d6dad820dee0e08339269810b8987e4e10e | refs/heads/master | 2021-08-29T10:29:22.438000 | 2017-12-13T17:55:05 | 2017-12-13T17:55:05 | 114,152,033 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings("SameParameterValue")
public class Estado {
/*** Atributos ***/
/***
* estado - Controla se o pacote foi enviado e confirmado com ack.
* timer - Timer para estouro.
* estouro - Controla se o pacote foi estourado.
* numero_sequencia - Numero de sequencia atribuido à aquele pacote.
* ***/
private boolean estado;
private Timer timer = null;
private boolean estouro;
private int numero_sequencia;
/*** Construtor ***/
Estado()
{
this.estado = false;
this.estouro = false;
}
void ativa_timer()
{
this.timer = new Timer();
this.timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
estouro = true;
}
}, 1500, 1500);
}
void desativa_timer()
{
if(this.timer != null) this.timer.cancel();
}
/*** Getters e Setters ***/
int getNumero_sequencia()
{
return numero_sequencia;
}
void setNumero_sequencia(int numero_sequencia)
{
this.numero_sequencia = numero_sequencia;
}
boolean isEstado()
{
return estado;
}
void setEstado(boolean estado)
{
this.estado = estado;
}
boolean isEstouro()
{
return !this.estado && estouro;
}
void setEstouro(boolean estouro)
{
this.estouro = estouro;
}
public String toString()
{
return "Estado: "+this.estado + " Estouro: " +this.estouro + " Seq:" +numero_sequencia +" ";
}
}
| UTF-8 | Java | 1,652 | java | Estado.java | Java | []
| null | []
| import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings("SameParameterValue")
public class Estado {
/*** Atributos ***/
/***
* estado - Controla se o pacote foi enviado e confirmado com ack.
* timer - Timer para estouro.
* estouro - Controla se o pacote foi estourado.
* numero_sequencia - Numero de sequencia atribuido à aquele pacote.
* ***/
private boolean estado;
private Timer timer = null;
private boolean estouro;
private int numero_sequencia;
/*** Construtor ***/
Estado()
{
this.estado = false;
this.estouro = false;
}
void ativa_timer()
{
this.timer = new Timer();
this.timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
estouro = true;
}
}, 1500, 1500);
}
void desativa_timer()
{
if(this.timer != null) this.timer.cancel();
}
/*** Getters e Setters ***/
int getNumero_sequencia()
{
return numero_sequencia;
}
void setNumero_sequencia(int numero_sequencia)
{
this.numero_sequencia = numero_sequencia;
}
boolean isEstado()
{
return estado;
}
void setEstado(boolean estado)
{
this.estado = estado;
}
boolean isEstouro()
{
return !this.estado && estouro;
}
void setEstouro(boolean estouro)
{
this.estouro = estouro;
}
public String toString()
{
return "Estado: "+this.estado + " Estouro: " +this.estouro + " Seq:" +numero_sequencia +" ";
}
}
| 1,652 | 0.551181 | 0.546336 | 69 | 22.927536 | 20.034983 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 2 |
1cf6c223fac9f9b1b7b91d840965e60fd82027cc | 38,568,806,339,842 | 7876ab6828d9fae0ac1b7ee57f707e278a7aa021 | /app/src/main/java/mr_auspicious/shivam_kr_shiv/com/menus3/MainActivity.java | 27cae6568f0943d7e2d8b10d385dc274f9ea6dbc | []
| no_license | Shivamkshiv/Acadgild_Assignment_5.3 | https://github.com/Shivamkshiv/Acadgild_Assignment_5.3 | 6c6ab25f341fe54e3ddae2e20dab714441dd4ade | 4cc03d112a89fc2fd6d755ffb44b8c10c44a05c4 | refs/heads/master | 2021-01-21T10:08:54.556000 | 2017-02-28T03:38:30 | 2017-02-28T03:38:30 | 83,385,910 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mr_auspicious.shivam_kr_shiv.com.menus3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Adding the values in our Array List...
ArrayList<Info> information = new ArrayList<>();
information.add(new Info("Ish","11111111"));
information.add(new Info("Kumar","2222222222"));
information.add(new Info("Shyam","4455756767"));
information.add(new Info("Ram", "34642653"));
information.add(new Info("Rakesh","76756645"));
information.add(new Info("Ram"," 967564764"));
information.add(new Info("Rajesh","6756464"));
ListView listView = (ListView) findViewById(R.id.list); // Defining the listview
InfoAdapter infoAdapter = new InfoAdapter(getBaseContext(),information);
listView.setAdapter(infoAdapter); //Setting the adapter to our listview ...
registerForContextMenu(listView); //Registering the listview for Context Menu...
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select The Action"); //sets the title to "Select The Action"..
//Adding the menu options...
menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
menu.add(0, v.getId(), 0, "SMS");
}
@Override
public boolean onContextItemSelected(MenuItem item){
if(item.getTitle()=="Call"){
Toast.makeText(getApplicationContext(),"Calling...",Toast.LENGTH_LONG).show(); //prints this toast when u click on this option
}
else if(item.getTitle()=="SMS"){
Toast.makeText(getApplicationContext(),"Sending...",Toast.LENGTH_LONG).show(); //prints this toast when u click on this option
}else{
return false;
}
return true;
}
}
| UTF-8 | Java | 2,315 | java | MainActivity.java | Java | [
{
"context": " ArrayList<>();\n information.add(new Info(\"Ish\",\"11111111\"));\n information.add(new Info(\"",
"end": 667,
"score": 0.7677921056747437,
"start": 664,
"tag": "NAME",
"value": "Ish"
},
{
"context": "\",\"11111111\"));\n information.add(new Info(\"Kumar\",\"2222222222\"));\n information.add(new Info",
"end": 722,
"score": 0.9604654908180237,
"start": 717,
"tag": "NAME",
"value": "Kumar"
},
{
"context": "\"2222222222\"));\n information.add(new Info(\"Shyam\",\"4455756767\"));\n information.add(new Info",
"end": 779,
"score": 0.8532614707946777,
"start": 774,
"tag": "NAME",
"value": "Shyam"
},
{
"context": ", \"34642653\"));\n information.add(new Info(\"Rakesh\",\"76756645\"));\n information.add(new Info(\"",
"end": 891,
"score": 0.874754011631012,
"start": 885,
"tag": "NAME",
"value": "Rakesh"
},
{
"context": "\" 967564764\"));\n information.add(new Info(\"Rajesh\",\"6756464\"));\n\n ListView listView = (ListV",
"end": 1002,
"score": 0.9346117377281189,
"start": 996,
"tag": "NAME",
"value": "Rajesh"
}
]
| null | []
| package mr_auspicious.shivam_kr_shiv.com.menus3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Adding the values in our Array List...
ArrayList<Info> information = new ArrayList<>();
information.add(new Info("Ish","11111111"));
information.add(new Info("Kumar","2222222222"));
information.add(new Info("Shyam","4455756767"));
information.add(new Info("Ram", "34642653"));
information.add(new Info("Rakesh","76756645"));
information.add(new Info("Ram"," 967564764"));
information.add(new Info("Rajesh","6756464"));
ListView listView = (ListView) findViewById(R.id.list); // Defining the listview
InfoAdapter infoAdapter = new InfoAdapter(getBaseContext(),information);
listView.setAdapter(infoAdapter); //Setting the adapter to our listview ...
registerForContextMenu(listView); //Registering the listview for Context Menu...
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select The Action"); //sets the title to "Select The Action"..
//Adding the menu options...
menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
menu.add(0, v.getId(), 0, "SMS");
}
@Override
public boolean onContextItemSelected(MenuItem item){
if(item.getTitle()=="Call"){
Toast.makeText(getApplicationContext(),"Calling...",Toast.LENGTH_LONG).show(); //prints this toast when u click on this option
}
else if(item.getTitle()=="SMS"){
Toast.makeText(getApplicationContext(),"Sending...",Toast.LENGTH_LONG).show(); //prints this toast when u click on this option
}else{
return false;
}
return true;
}
}
| 2,315 | 0.668683 | 0.640173 | 62 | 36.338711 | 33.238117 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.903226 | false | false | 2 |
459e350dd40b5a09ad8489b0334455fabedfc66c | 38,886,633,934,558 | 49f69430705c5beb638f332c4ba97214eb91e8b0 | /src/com/skilldistillery/jets/entity/Airfield.java | 3cbcd0b27cd4908a9e78172b6cf85c432b7f3273 | []
| no_license | KNett07/Jets | https://github.com/KNett07/Jets | 1e7399718f3bfcdbad7f4a87a01d8994827917ca | 024c0bd7abc23ee7b642a0174dac4ca4e668fb20 | refs/heads/main | 2023-05-08T17:34:42.539000 | 2021-06-01T01:54:10 | 2021-06-01T01:54:10 | 371,820,732 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.skilldistillery.jets.entity;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Airfield {
List<Jet> jets1;
public Airfield() {
jets1 = new ArrayList<>();
}
public void addJet(Jet j) {
jets1.add(j);
}
public void removeJet(Jet j) {
jets1.remove(j);
}
public void listFleet() {
System.out.println("Entire Current Fleet: ");
for (int i = 0; i < jets1.size(); i++) {
System.out.println(this.jets1.get(i).toString());
System.out.println();
}
}
public void flyAllJets() {
for (int i = 0; i < jets1.size(); i++) {
jets1.get(i).fly();
}
}
public void fastestJet() {
Jet fastest = jets1.get(0);
for (int i = 1; i < jets1.size(); i++) {
if (fastest.getSpeed() < jets1.get(i).getSpeed()) {
fastest = jets1.get(i);
}
}
System.out.println(fastest.toString());
}
public void longestRange() {
Jet longest = jets1.get(0);
for (int i = 1; i < jets1.size(); i++) {
if (longest.getRange() < jets1.get(i).getRange()) {
longest = jets1.get(i);
}
}
System.out.println(longest.toString());
}
public void allCargoJets() {
for (int i = 0; i < jets1.size(); i++) {
if (jets1.get(i) instanceof CargoCarrier) {
((CargoCarrier) jets1.get(i)).loadCargo();
}
}
}
public void allFloatAway() {
for (int i = 0; i < jets1.size(); i++) {
if (jets1.get(i) instanceof FloatAway) {
((FloatAway) jets1.get(i)).allFloat();
}
}
}
public Jet addJetToFleet(Scanner input) {
int range, speed;
double price;
String model;
System.out.println("Please enter a model: ");
model = input.nextLine();
System.out.println("Please enter a speed: ");
speed = input.nextInt();
System.out.println("Please enter a range: ");
range = input.nextInt();
System.out.println("Please enter a price: ");
price = input.nextDouble();
input.nextLine();
Jet jet = new JetImpl(model, speed, range, price);
return jet;
}
public Jet removeJetFromFleet(Scanner input) {
System.out.println("Enter the model of jet you would like to remove: ");
String model = input.nextLine();
Jet jetToRemove = null;
for (Jet jet : jets1) {
if (model.equalsIgnoreCase(jet.getModel())) {
jetToRemove = jet;
}
}
System.out.println("");
return jetToRemove;
}
}
| UTF-8 | Java | 2,308 | java | Airfield.java | Java | []
| null | []
| package com.skilldistillery.jets.entity;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Airfield {
List<Jet> jets1;
public Airfield() {
jets1 = new ArrayList<>();
}
public void addJet(Jet j) {
jets1.add(j);
}
public void removeJet(Jet j) {
jets1.remove(j);
}
public void listFleet() {
System.out.println("Entire Current Fleet: ");
for (int i = 0; i < jets1.size(); i++) {
System.out.println(this.jets1.get(i).toString());
System.out.println();
}
}
public void flyAllJets() {
for (int i = 0; i < jets1.size(); i++) {
jets1.get(i).fly();
}
}
public void fastestJet() {
Jet fastest = jets1.get(0);
for (int i = 1; i < jets1.size(); i++) {
if (fastest.getSpeed() < jets1.get(i).getSpeed()) {
fastest = jets1.get(i);
}
}
System.out.println(fastest.toString());
}
public void longestRange() {
Jet longest = jets1.get(0);
for (int i = 1; i < jets1.size(); i++) {
if (longest.getRange() < jets1.get(i).getRange()) {
longest = jets1.get(i);
}
}
System.out.println(longest.toString());
}
public void allCargoJets() {
for (int i = 0; i < jets1.size(); i++) {
if (jets1.get(i) instanceof CargoCarrier) {
((CargoCarrier) jets1.get(i)).loadCargo();
}
}
}
public void allFloatAway() {
for (int i = 0; i < jets1.size(); i++) {
if (jets1.get(i) instanceof FloatAway) {
((FloatAway) jets1.get(i)).allFloat();
}
}
}
public Jet addJetToFleet(Scanner input) {
int range, speed;
double price;
String model;
System.out.println("Please enter a model: ");
model = input.nextLine();
System.out.println("Please enter a speed: ");
speed = input.nextInt();
System.out.println("Please enter a range: ");
range = input.nextInt();
System.out.println("Please enter a price: ");
price = input.nextDouble();
input.nextLine();
Jet jet = new JetImpl(model, speed, range, price);
return jet;
}
public Jet removeJetFromFleet(Scanner input) {
System.out.println("Enter the model of jet you would like to remove: ");
String model = input.nextLine();
Jet jetToRemove = null;
for (Jet jet : jets1) {
if (model.equalsIgnoreCase(jet.getModel())) {
jetToRemove = jet;
}
}
System.out.println("");
return jetToRemove;
}
}
| 2,308 | 0.62435 | 0.610919 | 115 | 19.069565 | 18.417252 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.913043 | false | false | 2 |
1a023d4b060f119e580a059409cec00efe240def | 38,886,633,933,717 | 72ac5480d6380128dfe320d32f7d66a9593f871e | /src/controller/MainPage.java | fbecd7e8a6532555837791bfcd417a15a646c4f2 | []
| no_license | Edviuxas/Buhalterija_desktop | https://github.com/Edviuxas/Buhalterija_desktop | 557e006a674184c588bf872e696bb996addbc4f6 | 90828293c10978594af2ff2ae3148b52bd952c2f | refs/heads/master | 2023-08-23T14:49:53.912000 | 2021-11-06T17:37:46 | 2021-11-06T17:37:46 | 425,307,556 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import ds.CompanyUser;
import ds.FinanceManagementIS;
import ds.IndividualPersonUser;
import ds.User;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class MainPage implements Initializable {
private User currentUser = null;
private FinanceManagementIS fmis = null;
@FXML
public Button btnManageUsers;
@FXML
public Button btnManageCategories;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
if (!(currentUser.getUserName().equals("admin") && currentUser.getPassword().equals("admin"))) {
// btnManageUsers.setDisable(true);
btnManageUsers.setText("Change personal information");
}
}
public void setFmis(FinanceManagementIS fmis) {
this.fmis = fmis;
}
public void manageCategories(ActionEvent actionEvent) throws IOException {
loadManageCategories();
}
public void manageUsersClick(ActionEvent actionEvent) throws IOException {
if (btnManageUsers.getText().equals("Change personal information")) {
FXMLLoader loader = new FXMLLoader();
Parent root = null;
if (currentUser instanceof CompanyUser) {
loader = new FXMLLoader(getClass().getResource("RegisterCompanyPage.fxml"));
root = loader.load();
CompanyUser companyUser = (CompanyUser) currentUser;
RegisterCompanyPage registerCompanyPage = loader.getController();
registerCompanyPage.setFmis(fmis);
registerCompanyPage.textContactPerson.setText(companyUser.getContactPerson());
registerCompanyPage.textPassword.setText(companyUser.getPassword());
registerCompanyPage.textCompanyName.setText(companyUser.getName());
registerCompanyPage.textLogin.setText(companyUser.getUserName());
registerCompanyPage.btnSave.setText("Save updates");
registerCompanyPage.setCurrentUser(currentUser);
registerCompanyPage.setEditingUser(companyUser);
registerCompanyPage.setCameFromMainPage(true);
Stage stage = (Stage) btnManageUsers.getScene().getWindow();
stage.setTitle("Update user");
stage.setScene(new Scene(root));
stage.show();
} else {
loader = new FXMLLoader(getClass().getResource("RegisterIndividualPage.fxml"));
root = loader.load();
IndividualPersonUser individualPersonUser = (IndividualPersonUser) currentUser;
RegisterIndividualPage registerIndividualPage = loader.getController();
registerIndividualPage.setFmis(fmis);
registerIndividualPage.textSurname.setText(individualPersonUser.getSurname());
registerIndividualPage.textName.setText(individualPersonUser.getName());
registerIndividualPage.textEmail.setText(individualPersonUser.getEmailAddress());
registerIndividualPage.textLogin.setText(individualPersonUser.getUserName());
registerIndividualPage.textPassword.setText(individualPersonUser.getPassword());
registerIndividualPage.btnSave.setText("Save updates");
registerIndividualPage.setCurrentUser(currentUser);
registerIndividualPage.setEditingUser(individualPersonUser);
registerIndividualPage.setCameFromMainPage(true);
Stage stage = (Stage) btnManageUsers.getScene().getWindow();
stage.setTitle("Update user");
stage.setScene(new Scene(root));
stage.show();
}
} else {
loadManageUsers();
}
}
private void loadManageCategories() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ManageCategoriesPage.fxml"));
Parent root = loader.load();
ManageCategoriesPage manageCategoriesPage = loader.getController();
manageCategoriesPage.setFmis(fmis);
manageCategoriesPage.setCurrentUser(currentUser);
Stage stage = (Stage) btnManageCategories.getScene().getWindow();
stage.setTitle("Manage Categories Page");
stage.setScene(new Scene(root));
stage.show();
}
private void loadManageUsers() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ManageUsersPage.fxml"));
Parent root = loader.load();
ManageUsersPage manageUsersPage = loader.getController();
manageUsersPage.setFmis(fmis);
manageUsersPage.setCurrentUser(currentUser);
Stage stage = (Stage) btnManageCategories.getScene().getWindow();
stage.setTitle("Manage Users");
stage.setScene(new Scene(root));
stage.show();
}
public void logOff(ActionEvent actionEvent) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("LoginPage.fxml"));
Parent root = loader.load();
LoginPage manageUsersPage = loader.getController();
manageUsersPage.setFmis(fmis);
Stage stage = (Stage) btnManageCategories.getScene().getWindow();
stage.setTitle("Login");
stage.setScene(new Scene(root));
stage.show();
}
}
| UTF-8 | Java | 5,734 | java | MainPage.java | Java | [
{
"context": ";\n if (!(currentUser.getUserName().equals(\"admin\") && currentUser.getPassword().equals(\"admin\"))) ",
"end": 909,
"score": 0.9640691876411438,
"start": 904,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "als(\"admin\") && currentUser.getPassword().equals(\"admin\"))) {\n// btnManageUsers.setDisable(tru",
"end": 954,
"score": 0.9906090497970581,
"start": 949,
"tag": "PASSWORD",
"value": "admin"
},
{
"context": " registerIndividualPage.textPassword.setText(individualPersonUser.getPassword());\n registerIndividualPage.btnSav",
"end": 3594,
"score": 0.9671088457107544,
"start": 3562,
"tag": "PASSWORD",
"value": "individualPersonUser.getPassword"
}
]
| null | []
| package controller;
import ds.CompanyUser;
import ds.FinanceManagementIS;
import ds.IndividualPersonUser;
import ds.User;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class MainPage implements Initializable {
private User currentUser = null;
private FinanceManagementIS fmis = null;
@FXML
public Button btnManageUsers;
@FXML
public Button btnManageCategories;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
if (!(currentUser.getUserName().equals("admin") && currentUser.getPassword().equals("<PASSWORD>"))) {
// btnManageUsers.setDisable(true);
btnManageUsers.setText("Change personal information");
}
}
public void setFmis(FinanceManagementIS fmis) {
this.fmis = fmis;
}
public void manageCategories(ActionEvent actionEvent) throws IOException {
loadManageCategories();
}
public void manageUsersClick(ActionEvent actionEvent) throws IOException {
if (btnManageUsers.getText().equals("Change personal information")) {
FXMLLoader loader = new FXMLLoader();
Parent root = null;
if (currentUser instanceof CompanyUser) {
loader = new FXMLLoader(getClass().getResource("RegisterCompanyPage.fxml"));
root = loader.load();
CompanyUser companyUser = (CompanyUser) currentUser;
RegisterCompanyPage registerCompanyPage = loader.getController();
registerCompanyPage.setFmis(fmis);
registerCompanyPage.textContactPerson.setText(companyUser.getContactPerson());
registerCompanyPage.textPassword.setText(companyUser.getPassword());
registerCompanyPage.textCompanyName.setText(companyUser.getName());
registerCompanyPage.textLogin.setText(companyUser.getUserName());
registerCompanyPage.btnSave.setText("Save updates");
registerCompanyPage.setCurrentUser(currentUser);
registerCompanyPage.setEditingUser(companyUser);
registerCompanyPage.setCameFromMainPage(true);
Stage stage = (Stage) btnManageUsers.getScene().getWindow();
stage.setTitle("Update user");
stage.setScene(new Scene(root));
stage.show();
} else {
loader = new FXMLLoader(getClass().getResource("RegisterIndividualPage.fxml"));
root = loader.load();
IndividualPersonUser individualPersonUser = (IndividualPersonUser) currentUser;
RegisterIndividualPage registerIndividualPage = loader.getController();
registerIndividualPage.setFmis(fmis);
registerIndividualPage.textSurname.setText(individualPersonUser.getSurname());
registerIndividualPage.textName.setText(individualPersonUser.getName());
registerIndividualPage.textEmail.setText(individualPersonUser.getEmailAddress());
registerIndividualPage.textLogin.setText(individualPersonUser.getUserName());
registerIndividualPage.textPassword.setText(<PASSWORD>());
registerIndividualPage.btnSave.setText("Save updates");
registerIndividualPage.setCurrentUser(currentUser);
registerIndividualPage.setEditingUser(individualPersonUser);
registerIndividualPage.setCameFromMainPage(true);
Stage stage = (Stage) btnManageUsers.getScene().getWindow();
stage.setTitle("Update user");
stage.setScene(new Scene(root));
stage.show();
}
} else {
loadManageUsers();
}
}
private void loadManageCategories() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ManageCategoriesPage.fxml"));
Parent root = loader.load();
ManageCategoriesPage manageCategoriesPage = loader.getController();
manageCategoriesPage.setFmis(fmis);
manageCategoriesPage.setCurrentUser(currentUser);
Stage stage = (Stage) btnManageCategories.getScene().getWindow();
stage.setTitle("Manage Categories Page");
stage.setScene(new Scene(root));
stage.show();
}
private void loadManageUsers() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ManageUsersPage.fxml"));
Parent root = loader.load();
ManageUsersPage manageUsersPage = loader.getController();
manageUsersPage.setFmis(fmis);
manageUsersPage.setCurrentUser(currentUser);
Stage stage = (Stage) btnManageCategories.getScene().getWindow();
stage.setTitle("Manage Users");
stage.setScene(new Scene(root));
stage.show();
}
public void logOff(ActionEvent actionEvent) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("LoginPage.fxml"));
Parent root = loader.load();
LoginPage manageUsersPage = loader.getController();
manageUsersPage.setFmis(fmis);
Stage stage = (Stage) btnManageCategories.getScene().getWindow();
stage.setTitle("Login");
stage.setScene(new Scene(root));
stage.show();
}
}
| 5,717 | 0.669166 | 0.669166 | 139 | 40.251797 | 30.269554 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647482 | false | false | 2 |
063cf2fdd09df4c4f287979f91ceb80d2c345028 | 38,448,547,255,025 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/12/12_5bb44f52c1f154e9dcc93baf5cbe986dc1835ade/CompareUtil/12_5bb44f52c1f154e9dcc93baf5cbe986dc1835ade_CompareUtil_s.java | a4d961be7cadb5c8f265fbbd5d6fc32b96d39de1 | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | /*******************************************************************************
* Copyright (c) 2009 Atlassian and others.
* 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
*
* Contributors:
* Atlassian - initial API and implementation
* Tasktop Technologies - improvements
******************************************************************************/
package org.eclipse.mylyn.internal.reviews.ui.compare;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.contentmergeviewer.ContentMergeViewer;
import org.eclipse.compare.contentmergeviewer.IMergeViewerContentProvider;
import org.eclipse.compare.contentmergeviewer.TextMergeViewer;
import org.eclipse.compare.internal.MergeSourceViewer;
import org.eclipse.compare.structuremergeviewer.DiffNode;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.reviews.ui.ReviewsUiPlugin;
import org.eclipse.mylyn.reviews.core.model.IFileItem;
import org.eclipse.mylyn.reviews.core.model.IFileRevision;
/**
* @author Steffen Pingel
*/
public class CompareUtil {
public static DiffNode createDiffNode(IFileItem file) {
byte[] targetContent = getContent(file.getTarget());
byte[] baseContent = getContent(file.getBase());
String targetPath = file.getTarget().getPath();
if (targetPath == null) {
targetPath = file.getBase().getPath();
}
String basePath = file.getBase().getPath();
if (basePath == null) {
basePath = targetPath;
}
return new DiffNode(new ByteArrayInput(targetContent, targetPath), new ByteArrayInput(baseContent, basePath));
}
static byte[] getContent(IFileRevision revision) {
String content = revision.getContent();
return (content != null) ? content.getBytes() : new byte[0];
}
static SourceViewer getSourceViewer(MergeSourceViewer sourceViewer) {
if (SourceViewer.class.isInstance(sourceViewer)) {
return SourceViewer.class.cast(sourceViewer);
} else {
Object returnValue;
try {
Method getSourceViewerRefl = MergeSourceViewer.class.getDeclaredMethod("getSourceViewer");
getSourceViewerRefl.setAccessible(true);
returnValue = getSourceViewerRefl.invoke(sourceViewer);
if (returnValue instanceof SourceViewer) {
return (SourceViewer) returnValue;
}
} catch (Exception e) {
// ignore
}
}
return null;
}
static void setActiveViewer(TextMergeViewer mergeViewer, MergeSourceViewer focusViewer) {
try {
Method setActiveViewer = TextMergeViewer.class.getDeclaredMethod("setActiveViewer",
MergeSourceViewer.class, boolean.class);
setActiveViewer.setAccessible(true);
setActiveViewer.invoke(mergeViewer, focusViewer, true);
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.WARNING, ReviewsUiPlugin.PLUGIN_ID, "Failed to activate viewer", e));
}
}
static void configureSourceViewers(Viewer contentViewer, TextMergeViewer textMergeViewer,
final MergeSourceViewer fLeft, final MergeSourceViewer fRight) {
// FIXME: hack for e3.5
try {
Method getCompareConfiguration = ContentMergeViewer.class.getDeclaredMethod("getCompareConfiguration");
getCompareConfiguration.setAccessible(true);
CompareConfiguration cc = (CompareConfiguration) getCompareConfiguration.invoke(textMergeViewer);
Method getMergeContentProvider = ContentMergeViewer.class.getDeclaredMethod("getMergeContentProvider");
getMergeContentProvider.setAccessible(true);
IMergeViewerContentProvider cp = (IMergeViewerContentProvider) getMergeContentProvider.invoke(textMergeViewer);
Method getSourceViewer = MergeSourceViewer.class.getDeclaredMethod("getSourceViewer");
Method configureSourceViewer = TextMergeViewer.class.getDeclaredMethod("configureSourceViewer",
SourceViewer.class, boolean.class);
configureSourceViewer.setAccessible(true);
configureSourceViewer.invoke(contentViewer, getSourceViewer.invoke(fLeft),
cc.isLeftEditable() && cp.isLeftEditable(textMergeViewer.getInput()));
configureSourceViewer.invoke(contentViewer, getSourceViewer.invoke(fRight),
cc.isRightEditable() && cp.isRightEditable(textMergeViewer.getInput()));
Field isConfiguredField = TextMergeViewer.class.getDeclaredField("isConfigured");
isConfiguredField.setAccessible(true);
isConfiguredField.set(contentViewer, true);
} catch (Throwable t) {
t.printStackTrace();
// ignore as it may not exist in other versions
}
}
}
| UTF-8 | Java | 4,951 | java | 12_5bb44f52c1f154e9dcc93baf5cbe986dc1835ade_CompareUtil_s.java | Java | [
{
"context": "views.core.model.IFileRevision;\n \n /**\n * @author Steffen Pingel\n */\n public class CompareUtil {\n \n \tpublic stati",
"end": 1520,
"score": 0.9998215436935425,
"start": 1506,
"tag": "NAME",
"value": "Steffen Pingel"
}
]
| null | []
| /*******************************************************************************
* Copyright (c) 2009 Atlassian and others.
* 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
*
* Contributors:
* Atlassian - initial API and implementation
* Tasktop Technologies - improvements
******************************************************************************/
package org.eclipse.mylyn.internal.reviews.ui.compare;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.contentmergeviewer.ContentMergeViewer;
import org.eclipse.compare.contentmergeviewer.IMergeViewerContentProvider;
import org.eclipse.compare.contentmergeviewer.TextMergeViewer;
import org.eclipse.compare.internal.MergeSourceViewer;
import org.eclipse.compare.structuremergeviewer.DiffNode;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.reviews.ui.ReviewsUiPlugin;
import org.eclipse.mylyn.reviews.core.model.IFileItem;
import org.eclipse.mylyn.reviews.core.model.IFileRevision;
/**
* @author <NAME>
*/
public class CompareUtil {
public static DiffNode createDiffNode(IFileItem file) {
byte[] targetContent = getContent(file.getTarget());
byte[] baseContent = getContent(file.getBase());
String targetPath = file.getTarget().getPath();
if (targetPath == null) {
targetPath = file.getBase().getPath();
}
String basePath = file.getBase().getPath();
if (basePath == null) {
basePath = targetPath;
}
return new DiffNode(new ByteArrayInput(targetContent, targetPath), new ByteArrayInput(baseContent, basePath));
}
static byte[] getContent(IFileRevision revision) {
String content = revision.getContent();
return (content != null) ? content.getBytes() : new byte[0];
}
static SourceViewer getSourceViewer(MergeSourceViewer sourceViewer) {
if (SourceViewer.class.isInstance(sourceViewer)) {
return SourceViewer.class.cast(sourceViewer);
} else {
Object returnValue;
try {
Method getSourceViewerRefl = MergeSourceViewer.class.getDeclaredMethod("getSourceViewer");
getSourceViewerRefl.setAccessible(true);
returnValue = getSourceViewerRefl.invoke(sourceViewer);
if (returnValue instanceof SourceViewer) {
return (SourceViewer) returnValue;
}
} catch (Exception e) {
// ignore
}
}
return null;
}
static void setActiveViewer(TextMergeViewer mergeViewer, MergeSourceViewer focusViewer) {
try {
Method setActiveViewer = TextMergeViewer.class.getDeclaredMethod("setActiveViewer",
MergeSourceViewer.class, boolean.class);
setActiveViewer.setAccessible(true);
setActiveViewer.invoke(mergeViewer, focusViewer, true);
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.WARNING, ReviewsUiPlugin.PLUGIN_ID, "Failed to activate viewer", e));
}
}
static void configureSourceViewers(Viewer contentViewer, TextMergeViewer textMergeViewer,
final MergeSourceViewer fLeft, final MergeSourceViewer fRight) {
// FIXME: hack for e3.5
try {
Method getCompareConfiguration = ContentMergeViewer.class.getDeclaredMethod("getCompareConfiguration");
getCompareConfiguration.setAccessible(true);
CompareConfiguration cc = (CompareConfiguration) getCompareConfiguration.invoke(textMergeViewer);
Method getMergeContentProvider = ContentMergeViewer.class.getDeclaredMethod("getMergeContentProvider");
getMergeContentProvider.setAccessible(true);
IMergeViewerContentProvider cp = (IMergeViewerContentProvider) getMergeContentProvider.invoke(textMergeViewer);
Method getSourceViewer = MergeSourceViewer.class.getDeclaredMethod("getSourceViewer");
Method configureSourceViewer = TextMergeViewer.class.getDeclaredMethod("configureSourceViewer",
SourceViewer.class, boolean.class);
configureSourceViewer.setAccessible(true);
configureSourceViewer.invoke(contentViewer, getSourceViewer.invoke(fLeft),
cc.isLeftEditable() && cp.isLeftEditable(textMergeViewer.getInput()));
configureSourceViewer.invoke(contentViewer, getSourceViewer.invoke(fRight),
cc.isRightEditable() && cp.isRightEditable(textMergeViewer.getInput()));
Field isConfiguredField = TextMergeViewer.class.getDeclaredField("isConfigured");
isConfiguredField.setAccessible(true);
isConfiguredField.set(contentViewer, true);
} catch (Throwable t) {
t.printStackTrace();
// ignore as it may not exist in other versions
}
}
}
| 4,943 | 0.738033 | 0.735811 | 118 | 40.949154 | 31.627024 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.211864 | false | false | 2 |
1e4452b3ccb9823f00006927b022342b5c420976 | 38,336,878,113,159 | a0bec87e88991c9aa81cb87b8bcfa05f4a9da3a0 | /grimsby/src/main/java/grimsby/networking/server/ServerThread.java | 127e19272f9aec3445bb6916567576c92a7af640 | []
| no_license | Pwittiboy/grimsby | https://github.com/Pwittiboy/grimsby | 80b6c36fb08214a6b2c722a814d2fe455b5ff58c | d12ec16006844134b698c15346bcddeee05b0950 | refs/heads/master | 2020-03-15T20:00:14.003000 | 2018-05-19T08:49:20 | 2018-05-19T08:49:20 | 132,322,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package grimsby.networking.server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import grimsby.libraries.dataaccess.dao.factory.DAOFactory;
import grimsby.libraries.dataaccess.dao.impl.AccountDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.ConversationDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.GroupDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.GroupMemberDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.MessageDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.ParticipantDAOImpl;
import grimsby.libraries.entities.AccountEntity;
import grimsby.libraries.entities.ConversationEntity;
import grimsby.libraries.entities.GroupEntity;
import grimsby.libraries.entities.GroupMemberEntity;
import grimsby.libraries.entities.MessageEntity;
import grimsby.libraries.entities.ParticipantEntity;
import grimsby.networking.util.Constants;
import grimsby.networking.util.MessageUS;
import grimsby.networking.util.User;
/**
* The Class ServerThread. Created for communication between a client and the
* server. Each client has one thread and sends commands to the server.
*/
public class ServerThread extends Thread {
/** The Constant EMAIL address of the server. */
private static final String EMAIL = "your1chatroom@gmail.com";
/** The Constant password of the server's email address. */
private static final String PASS = "softwareworkshop";
/** The client. */
private Socket client;
/** The online people. */
private ConcurrentHashMap<String, ObjectOutputStream> onlinePeople;
/** The connections. */
private ConcurrentHashMap<String, HashSet<String>> connections;
/** The connection information. */
private ConcurrentHashMap<String, HashSet<String>> connectionInformation;
/** The to client. */
private ObjectOutputStream toClient;
/** The from client. */
private ObjectInputStream fromClient;
/** The this login. */
private String thisLogin;
/** The list of connections. */
private List<ServerThread> listOfConnections;
/** The dao factory. */
private DAOFactory daoFactory;
/** The adao. */
private AccountDAOImpl adao;
/** The cdao. */
private ConversationDAOImpl cdao;
/** The gdao. */
private GroupDAOImpl gdao;
/** The gmdao. */
private GroupMemberDAOImpl gmdao;
/** The mdao. */
private MessageDAOImpl mdao;
/** The pdao. */
private ParticipantDAOImpl pdao;
/** The account. */
private AccountEntity account;
/**
* Instantiates a new server thread.
*
* @param client the client
* @param onlinePeople the online people
* @param connections the connections
* @param connectionInformation the connection information
* @param listOfConnections the list of connections
*/
public ServerThread(Socket client, ConcurrentHashMap<String, ObjectOutputStream> onlinePeople,
ConcurrentHashMap<String, HashSet<String>> connections,
ConcurrentHashMap<String, HashSet<String>> connectionInformation, List<ServerThread> listOfConnections) {
super("ServerThread");
try {
fromClient = new ObjectInputStream(client.getInputStream());
toClient = new ObjectOutputStream(client.getOutputStream());
} catch (IOException e) {
System.err.println("connection with client was not created...");
this.interrupt();
}
this.connections = connections;
this.client = client;
this.onlinePeople = onlinePeople;
this.listOfConnections = listOfConnections;
this.connectionInformation = connectionInformation;
this.thisLogin = null;
setUpDatabase();
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
public void run() {
while (true) {
try {
MessageUS message = (MessageUS) fromClient.readObject();
String comand = message.getInstruction();
System.out.println("I got new command: " + comand);
if (comand.equals(Constants.LOGIN)) {
login(message);
} else if (comand.equals(Constants.FORGOT_PASSWORD)) {
forgotPassword(message);
} else if (comand.equals(Constants.CREATE_ACCOUNT)) {
createAccount(message);
} else if (thisLogin != null && onlinePeople.containsKey(thisLogin)) {
if (comand.equals(Constants.CONNECT)) {
connect(message);
} else if (comand.equals(Constants.CREATE_GROUP)) {
createGroup(message);
} else if (comand.equals(Constants.ADD_PERSON)) {
addPersonToGroup(message);
} else if (comand.equals(Constants.ACCEPTED_CONNECT)) {
acceptConnect(message);
} else if (comand.equals(Constants.DECLINED_CONNECT)) {
declineConnect(message);
} else if (comand.equals(Constants.SEND_MESSAGE)) {
sendMessage(message);
} else if (comand.equals(Constants.PUBLIC_MESSAGE)) {
publicMessage(message);
} else if (comand.equals(Constants.SEND_PHOTO)) {
sendPhoto(message);
} else if (comand.equals(Constants.SEND_PUBLIC_PHOTO)) {
sendPublicPhoto(message);
} else if (comand.equals(Constants.END_CHAT)) {
endChat(message);
} else if (comand.equals(Constants.LOAD_ALL_HISTORY)) {
loadAllHistory(message);
} else if (comand.equals(Constants.LOAD_PARTICULAR_HISTORY)) {
loadParticularHistory(message);
} else if (comand.equals(Constants.GET_MY_TOP)) {
getTop();
} else if (comand.equals(Constants.UPLOAD_PHOTO)) {
uploadPhoto(message);
} else if (comand.equals(Constants.VIEW_PROFILE)) {
viewProfile(message);
} else if (comand.equals(Constants.CHANGE_PASSWORD)) {
changePassword(message);
} else if (comand.equals(Constants.CHANGE_NAME)) {
changeName(message);
} else if (comand.equals(Constants.CHANGE_SURENAME)) {
changeSurname(message);
} else if (comand.equals(Constants.CHANGE_EMAIL)) {
changeEmail(message);
} else if (comand.equals(Constants.CHANGE_BIO)) {
changeBio(message);
} else if (comand.equals(Constants.PLAY_TIC_TAC_REQUEST)) {
play2TicTac(message);
} else if (comand.equals(Constants.PLAY_TIC_TAC_ACCEPTED)) {
accept2TicTac(message);
} else if (comand.equals(Constants.PLAY_TIC_TAC_DECLINED)) {
decline2TicTac(message);
} else if (comand.equals(Constants.MOVE_TIC_TAC)) {
move2TicTac(message);
} else if (comand.equals(Constants.END_TIC_TAC)) {
endTicTac(message);
} else if (comand.equals(Constants.END_OF_GAME)) {
endOfGame(message);
} else if (comand.equals(Constants.SET_THEME)) {
setTheme(message);
} else if (comand.equals(Constants.END)) {
end();
break;
} else if (comand.equals(Constants.DELETE_ACCOUNT)) {
deleteAccount();
} else {
System.err.println("unknown command " + comand);
}
} else {
MessageUS m = new MessageUS(Constants.SOMETHING_WENT_WRONG);
m.setReason("You are logged off! You need to log in first");
synchronized (toClient) {
toClient.writeObject(m);
}
}
} catch (SocketException e) {
// System.err.println("Socket exception.");
end();
break;
} catch (Exception e) {
System.err.println("Other exception.");
e.printStackTrace();
end();
break;
}
}
System.out.println("bye bye " + thisLogin);
}
private void deleteAccount() throws IOException {
boolean deleted = true;
try {
deleted = adao.delete(adao.findByUsername(thisLogin));
} catch (Exception e) {
deleted = false;
}
MessageUS informationMessage = new MessageUS(Constants.DELETE_ACCOUNT_SUCCESSFUL);
if (!deleted)
informationMessage = new MessageUS(Constants.DELETE_ACCOUNT_UNSUCCESSFUL);
synchronized (toClient) {
toClient.writeObject(informationMessage);
}
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
}
end();
}
/**
* Sets the theme. in the database. If operation is unsuccessful, sends
* answer something went wrong.
*
* @param message the new theme
* @throws IOException Signals that an I/O exception has occurred.
*/
private void setTheme(MessageUS message) throws IOException {
try {
adao.setDarkTheme(adao.findByUsername(thisLogin), message.getStyle() == 1);
} catch (SQLException e) {
MessageUS mess = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mess.setReason("Server error! the theme you chosen was not saved");
synchronized (toClient) {
toClient.writeObject(mess);
}
}
}
/**
* End of game. Sends to both of the players the message informing that the
* game has ended.
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void endOfGame(MessageUS message) throws IOException {
MessageUS messageWinner = new MessageUS(message.getInstruction(), message.getLogin(), message.getLogin());
messageWinner.setReason(message.getReason());
messageWinner.setX(message.getX());
messageWinner.setPlayer(message.isPlayer1());
MessageUS messageLooser = new MessageUS(message.getInstruction(), thisLogin, thisLogin);
messageLooser.setReason(message.getReason());
messageLooser.setX(message.getX());
messageLooser.setPlayer(message.isPlayer1());
try {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin()).writeObject(messageLooser);
}
} catch (Exception e) {
}
synchronized (toClient) {
toClient.writeObject(messageWinner);
}
}
private void endTicTac(MessageUS message) throws IOException {
MessageUS messageWinner = new MessageUS(message.getInstruction(), thisLogin, thisLogin);
messageWinner.setReason(message.getReason());
messageWinner.setX(message.getX());
try {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin()).writeObject(messageWinner);
}
} catch (Exception e) {
}
}
/**
* Play 2 tic tac toe. Sends request to play tick tack toe to the other
* person
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void play2TicTac(MessageUS message) throws IOException {
try {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(message.getLogin())
&& !thisLogin.equals(message.getLogin())) {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin())
.writeObject(new MessageUS(Constants.PLAY_TIC_TAC_REQUEST, thisLogin, ""));
}
} else {
MessageUS mess = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mess.setReason("The person you are trying to play game with is offline");
synchronized (toClient) {
toClient.writeObject(mess);
}
}
} catch (Exception e) {
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.SOMETHING_WENT_WRONG));
}
}
}
/**
* Accept 2 tic tac toe play
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void accept2TicTac(MessageUS message) throws IOException {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(message.getLogin())) {
try {
// Game id will be our partner's login
MessageUS messPlayer1 = new MessageUS(Constants.PLAY_TIC_TAC_ACCEPTED, thisLogin, true);
try {
messPlayer1.addPhoto(adao.findByUsername(thisLogin).getImage());
} catch (Exception e) {
}
MessageUS messPlayer2 = new MessageUS(Constants.PLAY_TIC_TAC_ACCEPTED, message.getLogin(), false);
try {
messPlayer2.addPhoto(adao.findByUsername(message.getLogin()).getImage());
} catch (Exception e) {
}
synchronized (toClient) {
toClient.writeObject(messPlayer2);
}
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin()).writeObject(messPlayer1);
}
} catch (Exception e) {
try {
MessageUS mes = new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, message.getLogin(), "");
synchronized (toClient) {
toClient.writeObject(mes);
}
mes = new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, thisLogin, "");
synchronized (onlinePeople.get(mes.getLogin())) {
try {
onlinePeople.get(mes.getLogin()).writeObject(mes);
} catch (Exception e1) {
System.err.println("Could not send a message");
}
}
} catch (Exception ex) {
}
}
} else
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, message.getLogin(), ""));
}
}
/**
* Decline 2 tic tac toegame.
*
* @param message the message
*/
private void decline2TicTac(MessageUS message) {
MessageUS messPlayer1 = new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, thisLogin, "");
try {
onlinePeople.get(message.getLogin()).writeObject(messPlayer1);
} catch (IOException e) {
}
}
/**
* Move 2 tic tac.
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void move2TicTac(MessageUS message) throws IOException {
MessageUS mess = new MessageUS(Constants.MOVE_TIC_TAC, thisLogin, message.getX());
System.out.println("login of the partner: " + message.getLogin());
synchronized (onlinePeople.get(message.getLogin())) {
try {
onlinePeople.get(message.getLogin()).writeObject(mess);
} catch (IOException e) {
toClient.writeObject(new MessageUS(Constants.END_TIC_TAC, mess.getLogin(), ""));
try {
if (onlinePeople.contains(message.getLogin())) {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin())
.writeObject(new MessageUS(Constants.END_TIC_TAC, thisLogin, ""));
}
}
} catch (Exception ex) {
}
}
}
}
/**
* Change bio information. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and updated bio.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeBio(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.updateBio(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
e.printStackTrace();
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_BIO_ACCEPTED, new String[] { userInfo });
information.setReason("Your bio was successfully updated!");
} else {
information = new MessageUS(Constants.CHANGE_BIO_DECLINED);
information.setReason("Error! Your bio was not updated. Try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Changes user's email address containing instruction and new email
* address. The new email address is set only if it is unique in the
* database. Sends message to the user informing whether the action was
* successful.
*
* @param message the message containing instruction and new email adress
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeEmail(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.updateEmail(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_EMAIL_ACCEPTED, new String[] { userInfo });
information.setReason("Your email address was successfully updated!");
} else {
information = new MessageUS(Constants.CHANGE_EMAIL_DECLINED);
try {
if (null != adao.findByEmail(message.getUserInformation()[0]))
information.setReason("The email address: " + userInfo + " is already registered. Try another one");
else
information.setReason("Server error. Email address could not be updated");
} catch (SQLException e1) {
System.err.println("SQL exception");
information.setReason("Error! Email address could not be updated");
}
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Changes client's surname. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and new surname.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeSurname(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.setSurname(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
System.err.println("SQL exception");
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_SURENAME_ACCEPTED, new String[] { userInfo });
information.setReason("Your surname was successfully changed!");
} else {
information = new MessageUS(Constants.CHANGE_SURENAME_DECLINED);
information.setReason("Error! your surname was not changed. Try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Changes client's name. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and new name
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeName(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.setName(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
System.err.println("SQL exception");
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_NAME_ACCEPTED, new String[] { userInfo });
information.setReason("Your name was successfully updated!");
} else {
information = new MessageUS(Constants.CHANGE_NAME_DECLINED);
information.setReason("Error! your name was not updated. Try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* View profile. Sends the message to the client containing the profile
* information of the requested user.
*
* @param message the message containing instruction and login of the user
* whose profile information is requested
* @throws IOException Signals that an I/O exception has occurred.
*/
private void viewProfile(MessageUS message) throws IOException {
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
String username = message.getLogin();
AccountEntity theUsersAccount = adao.findByUsername(username);
String[] info = { username, theUsersAccount.getName(), theUsersAccount.getSurname(),
theUsersAccount.getEmail(), theUsersAccount.getBio() };
information = new MessageUS(Constants.VIEW_PROFILE, info);
byte[] photo = adao.findByUsername(message.getLogin()).getImage();
information.addPhoto(photo);
} catch (Exception e) {
e.printStackTrace();
information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
information.setReason("The users " + message.getLogin() + " information could not be loaded. try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Uploads a new photo. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and byte[]
* @throws IOException Signals that an I/O exception has occurred.
*/
private void uploadPhoto(MessageUS message) throws IOException {
MessageUS uploaded = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
byte[] photo = message.getImage();
adao.updateImage(adao.findByUsername(thisLogin), thisLogin + System.currentTimeMillis(), photo);
uploaded = new MessageUS(Constants.PHOTO_UPLOADED);
uploaded.addPhoto(photo);
} catch (Exception e) {
uploaded = new MessageUS(Constants.PHOTO_DECLINED);
}
toClient.writeObject(uploaded);
}
/**
* Gets the favourite users and sends the message containing these users to
* the client.
*
* @return the top
* @throws IOException Signals that an I/O exception has occurred.
*/
private void getTop() throws IOException {
MessageUS messageOfTop = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
List<AccountEntity> accounts = adao.getTopContacts(adao.findByUsername(thisLogin), 4);
Set<User> myTopContacts = new HashSet<>();
accounts.forEach(ac -> myTopContacts.add(new User(ac.getImage(), ac.getUsername())));
messageOfTop = new MessageUS(Constants.GET_MY_TOP, myTopContacts, thisLogin, "");
} catch (SQLException e) {
e.printStackTrace();
messageOfTop = new MessageUS(Constants.SOMETHING_WENT_WRONG);
messageOfTop.setReason("Something went wrong. Could not give top contacts list");
}
synchronized (toClient) {
toClient.writeObject(messageOfTop);
}
}
/**
* Load all history. Gets and sends the whole history of the client
*
* @param message the message containing instruction
* @throws IOException Signals that an I/O exception has occurred.
*/
private void loadAllHistory(MessageUS message) throws IOException {
MessageUS sendingHistory = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
List<String> historyList = adao.getAllHistory(adao.findByUsername(thisLogin));
String[][] temp = new String[historyList.size()][1];
for (int i = 0; i < historyList.size(); i++)
temp[i][0] = historyList.get(i);
sendingHistory = new MessageUS(Constants.LOAD_ALL_HISTORY, temp, new HashMap<>());
} catch (Exception e) {
sendingHistory = new MessageUS(Constants.SOMETHING_WENT_WRONG);
sendingHistory.setReason("The history could not be loaded. Try again");
}
synchronized (sendingHistory) {
toClient.writeObject(sendingHistory);
}
}
/**
* Load particular history. Gets and sends particular history to the user
*
* @param message the message containing instruction and the information
* about which chat should be loaded
* @throws IOException Signals that an I/O exception has occurred.
*/
private void loadParticularHistory(MessageUS message) throws IOException {
MessageUS messageUS = new MessageUS(Constants.SOMETHING_WENT_WRONG);
String[] info = message.getUserInformation()[0].split("---");
try {
if (info[0].contains("-")) {
String groupId = info[0].split("-")[1] + "---" + info[1];
String[][] history = adao.getParticularGroupHistory(groupId);
HashMap<String, String> creationT = new HashMap<>();
for (String[] arr : history)
creationT.put(arr[0], adao.findByUsername(arr[0]).getTimestamp() + "");
messageUS = new MessageUS(Constants.LOAD_PARTICULAR_HISTORY, history, creationT);
} else {
String[][] history = adao.getParticularHistory(adao.findByUsername(thisLogin),
adao.findByUsername(info[0]));
HashMap<String, String> creationT = new HashMap<>();
for (String[] arr : history)
creationT.put(arr[0], adao.findByUsername(arr[0]).getTimestamp() + "");
messageUS = new MessageUS(Constants.LOAD_PARTICULAR_HISTORY, history, creationT);
}
synchronized (toClient) {
toClient.writeObject(messageUS);
}
} catch (Exception e) {
MessageUS mess = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mess.setReason("Unable to load the history with: " + info[0]);
synchronized (toClient) {
toClient.writeObject(mess);
}
}
}
/**
* Changes password.Sends message to the user informing whether the action
* was successful.
*
* @param message the message containing instruction, old and new passwords
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changePassword(MessageUS message) throws IOException {
MessageUS answer = new MessageUS(Constants.DECLINE_PASSWORD);
String[] accoutnInfo = message.getUserInformation();
String oldPass = accoutnInfo[0];
String newPass = accoutnInfo[1];
try {
if (oldPass.equals((account = adao.findByUsername(thisLogin)).getPassword())) {
adao.updatePassword(account, newPass);
answer = new MessageUS(Constants.ACCEPT_PASSWORD);
} else
answer.setReason("Your old password is incorrect!");
} catch (Exception e) {
answer.setReason("Something went wrong... Your password was not changed");
System.err.println("Password was not changed");
}
synchronized (toClient) {
toClient.writeObject(answer);
}
}
/**
* Login. Logins the user or declines the logging in. Sends the outcome to
* the user. If logging in was successful, additional information is added
* to the message: username, registration time, flags for temporary password
* and first time logging in as well as photo as byte[]. otherwise declined
* login instruction is sent
*
* @param message the message containing instruction and relevant
* information
* @throws Exception the exception
*/
private void login(MessageUS message) throws Exception {
MessageUS answer = new MessageUS(Constants.SOMETHING_WENT_WRONG);
String[] details = message.getUserInformation();
String username = details[0];
String password = details[1];
account = adao.findByUsername(username);
answer = new MessageUS(Constants.DECLINED_LOGIN);
if (adao.findByUsername(username) == null)
answer.setReason("The username " + username + " does not exist!");
else {
boolean verified = adao.verifyUser(username, password);
if (verified) {
this.thisLogin = username;
if (!onlinePeople.containsKey(thisLogin)) {
getTop();
String[] userInformation = new String[] { thisLogin,
adao.findByUsername(thisLogin).getTimestamp() + "" };
answer = new MessageUS(Constants.ACCEPTED_LOGIN, userInformation);
answer.setTempData(adao.findByUsername(thisLogin).getEmail());
if (account.isReminder())
answer.setTemporaty();
if (account.isFirstLogin())
answer.setIsFirstTime();
byte[] photo = adao.findByUsername(username).getImage();
answer.addPhoto(photo);
int style = adao.findByUsername(thisLogin).isDarkTheme() ? 1 : 0;
answer.setStyle(style);
onlinePeople.put(thisLogin, toClient);
connections.put(thisLogin, new HashSet<>());
listOfConnections.add(this);
System.out.println(thisLogin + " is logged!");
adao.setFirstLogin(account, false);
} else
answer.setReason("You cannot login whilst being online...");
} else
answer.setReason("The password is incorrect. Try again or send reminder to the email.");
}
synchronized (toClient) {
toClient.writeObject(answer);
}
listIsChanged();
}
/**
* Forgot password. Sends reminder to the clients email adress which is
* stored in database. Information message about the success or failure is
* sent to the client.
*
* Reference:
* https://crunchify.com/java-mailapi-example-send-an-email-via-gmail-smtp/
*
* @param m the message containing instruction and clients login.
* @throws Exception the exception
*/
private void forgotPassword(MessageUS m) throws Exception {
MessageUS messageUS = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
System.out.println("forgot password");
String userEmailAdress = null;
if (adao.findByUsername(m.getLogin()) == null) {
System.out.println("account does not exist");
messageUS = new MessageUS(Constants.EMAIL_NOT_SENT);
messageUS.setReason("The account with username: " + m.getLogin() + " does not exist!");
} else {
String password = adao.generateTempPassword(adao.findByUsername(m.getLogin()));
userEmailAdress = adao.findByUsername(m.getLogin()).getEmail();
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session getMailSession = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(getMailSession);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(userEmailAdress));
message.setSubject("Password reminder");
String emailBody = "Dear " + m.getLogin() + ","
+ "<br><br>Thank you for using our Chatroom. <br>Your temporary password is: " + password
+ " . Use this password when logging in.<br><br> Regards, <br>Chatroom team";
message.setContent(emailBody, "text/html");
Transport transport = getMailSession.getTransport("smtp");
transport.connect("smtp.gmail.com", EMAIL, PASS);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
messageUS = (new MessageUS(Constants.EMAIL_SENT));
}
} catch (Exception e) {
System.out.println("The letter was not sent");
e.printStackTrace();
messageUS = (new MessageUS(Constants.EMAIL_NOT_SENT));
messageUS.setReason("Error in server...");
} finally {
synchronized (toClient) {
toClient.writeObject(messageUS);
}
}
}
/**
* Creates the account. Sends confirmation or failure message to the client.
*
* @param messageUS the message containing instructions and potential
* client's information: username, password, email address
* @throws IOException Signals that an I/O exception has occurred.
*/
private void createAccount(MessageUS messageUS) throws IOException {
try {
String[] userDetails = messageUS.getUserInformation();
String username = userDetails[0];
String password = userDetails[1];
String email = userDetails[2];
String name = "Unknown";
String surname = "Unknown";
boolean usernameNotTaken = false;
if ((usernameNotTaken = ((account = adao.findByUsername(username)) == null))
&& adao.findByEmail(email) == null) {
account = new AccountEntity(username, password, name, surname, email, false, true,
"You have no bio :) ");
adao.create(account);
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.ACCEPTED_CREATE_ACCOUNT));
}
} else {
MessageUS m = new MessageUS(Constants.DECLINED_CREATE_ACCOUNT);
if (!usernameNotTaken) {
m.setReason("The username " + username + " is taken. Try another one");
System.out.println("username taken");
} else
m.setReason("The email adress " + email + " is taken. Try another one");
synchronized (toClient) {
toClient.writeObject(m);
}
}
} catch (SQLException e) {
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.SOMETHING_WENT_WRONG));
}
}
}
/**
* Connect. Sends a connection request to the chosen client.
*
* @param messageUS the message containing instruction and the potential
* partner's username
* @throws IOException Signals that an I/O exception has occurred.
*/
private void connect(MessageUS messageUS) throws IOException {
try {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(messageUS.getLogin())
&& !thisLogin.equals(messageUS.getLogin())) {
synchronized (onlinePeople.get(messageUS.getLogin())) {
onlinePeople.get(messageUS.getLogin())
.writeObject(new MessageUS(Constants.CONNECTION_REQUEST, thisLogin, ""));
}
System.out.println("Asking for the permission to connect...");
} else
synchronized (toClient) {
MessageUS message = new MessageUS(Constants.DECLINED_CONNECT, messageUS.getLogin(), "");
message.setReason("The person you are trying to connect with is offline");
toClient.writeObject(message);
}
} catch (Exception e) {
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.SOMETHING_WENT_WRONG));
}
}
}
/**
* Creates the group. Sends information message to all the members of the
* group containing accepted connect group instruction, group name and group
* id.
*
* @param message the message containing instruction and group name
* @throws IOException Signals that an I/O exception has occurred.
*/
private void createGroup(MessageUS message) throws IOException {
System.out.println("creating group");
// people online is list of people in this group chat
ArrayList<String> peopleInGroup = message.getPeopleOnline();
peopleInGroup.add(thisLogin);
for (String person : peopleInGroup)
if (!onlinePeople.containsKey(person))
peopleInGroup.remove(person);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
String groupID = message.getName() + "---" + currentTime;
System.out.println("Potential group id: " + groupID);
try {
account = adao.findByUsername(thisLogin);
GroupEntity groupEntity = new GroupEntity(groupID, account, message.getName(), currentTime);
gdao.create(groupEntity);
MessageUS messageConnection = new MessageUS(Constants.ACCEPTED_CONNECT_GROUP, message.getName(), groupID);
Set<User> potentialParticipants = new HashSet<>();
peopleInGroup.forEach(name -> {
try {
User newUser = new User(adao.findByUsername(name).getImage(), name);
potentialParticipants.add(newUser);
} catch (SQLException e1) {
System.err.println("Could not add image of " + name + " to the array");
e1.printStackTrace();
}
});
// even some of them might not be successful, but it is better to
// have them all and do not use uneccessary data in user
messageConnection.setPeople(potentialParticipants);
peopleInGroup.forEach(e -> {
if (onlinePeople.containsKey(e))
synchronized (onlinePeople.get(e)) {
try {
GroupMemberEntity groupMember = new GroupMemberEntity(groupEntity, adao.findByUsername(e));
gmdao.create(groupMember);
onlinePeople.get(e).writeObject(messageConnection);
synchronized (connections.get(e)) {
connections.get(e).add(groupID);
}
} catch (Exception e1) {
peopleInGroup.remove(e);
e1.printStackTrace();
}
}
else
peopleInGroup.remove(e);
});
connectionInformation.put(groupID, new HashSet<>(peopleInGroup));
ConversationEntity conversation = new ConversationEntity(adao.findByUsername(thisLogin),
gdao.findById(groupID));
cdao.create(conversation);
} catch (SQLException e2) {
MessageUS messageConnection = new MessageUS(Constants.SOMETHING_WENT_WRONG);
messageConnection.setReason("The group " + message.getName() + " could not be created");
synchronized (messageConnection) {
toClient.writeObject(messageConnection);
}
}
}
/**
* Adds the person to group. Sends the notification to all members of the
* group.
*
* @param message the message containing instruction, login of the person to
* be added and the chat id.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void addPersonToGroup(MessageUS message) throws IOException {
String personToAdd = message.getLogin();
String chatID = message.getID();
String chatName = message.getName();
if (onlinePeople.containsKey(personToAdd)) {
if (connectionInformation.containsKey(personToAdd)) {
try {
MessageUS mess = new MessageUS(Constants.DECLINED_ADD, personToAdd, chatID);
mess.setName(chatName);
mess.setReason(personToAdd + " is already in the group chat \"" + chatName + "\"");
try {
mess.addPhoto(adao.findByUsername(personToAdd).getImage());
} catch (SQLException e) {
mess.addPhoto(null);
}
synchronized (toClient) {
toClient.writeObject(mess);
}
} catch (IOException e) {
}
} else {
HashSet<String> peopleInTheChat = connectionInformation.get(chatID);
peopleInTheChat.add(personToAdd);
HashSet<User> setOfPeople = new HashSet<>();
peopleInTheChat.forEach(name -> {
try {
User thisUser = new User(adao.findByUsername(name).getImage(), name);
setOfPeople.add(thisUser);
} catch (SQLException e) {
e.printStackTrace();
}
});
try {
gmdao.create(new GroupMemberEntity(gdao.findById(chatID), adao.findByUsername(personToAdd)));
} catch (SQLException e1) {
MessageUS mess = new MessageUS(Constants.DECLINED_ADD, personToAdd, chatID);
mess.setReason("Server error ");
synchronized (toClient) {
toClient.writeObject(mess);
}
e1.printStackTrace();
}
MessageUS messageConnection = new MessageUS(Constants.ACCEPTED_CONNECT_GROUP, chatName, chatID);
messageConnection.setPeople(setOfPeople);
synchronized (onlinePeople.get(personToAdd)) {
try {
onlinePeople.get(personToAdd).writeObject(messageConnection);
} catch (IOException e) {
return;
}
}
MessageUS mess = new MessageUS(Constants.ACCEPTED_ADD, personToAdd, chatID);
mess.setName(chatName);
try {
mess.addPhoto(adao.findByUsername(personToAdd).getImage());
} catch (SQLException e1) {
}
peopleInTheChat.forEach(x -> {
if (!x.equals(personToAdd))
synchronized (onlinePeople.get(x)) {
try {
onlinePeople.get(x).writeObject(mess);
} catch (IOException e) {
System.out.println("Could not send the message to " + x);
}
}
});
}
synchronized (connections.get(personToAdd)) {
connections.get(personToAdd).add(message.getID());
}
synchronized (connectionInformation.get(message.getID())) {
connectionInformation.get(message.getID()).add(personToAdd);
}
}
}
/**
* Accept connect. Sends confirmation message to the person who sent the
* connection request. Creates new private chat
*
* @param messageUS the message containing instruction and login of the
* partner
* @throws IOException Signals that an I/O exception has occurred.
*/
private void acceptConnect(MessageUS messageUS) throws IOException {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(messageUS.getLogin())) {
grimsby.libraries.entities.ConversationEntity conversation = null;
List<grimsby.libraries.entities.ConversationEntity> conversations = null;
int conversationID = -1;
try {
conversation = new grimsby.libraries.entities.ConversationEntity(
adao.findByUsername(messageUS.getLogin()), null);
cdao.create(conversation);
conversations = cdao.findByOwner(adao.findByUsername(messageUS.getLogin()));
conversation = conversations.get(conversations.size() - 1);
ParticipantEntity sender = new ParticipantEntity(adao.findByUsername(messageUS.getLogin()),
conversation);
ParticipantEntity receiver = new ParticipantEntity(adao.findByUsername(thisLogin), conversation);
pdao.create(sender);
pdao.create(receiver);
conversationID = conversation.getId();
synchronized (connections.get(thisLogin)) {
connections.get(thisLogin).add(conversationID + "");
}
synchronized (connections.get(messageUS.getLogin())) {
connections.get(messageUS.getLogin()).add(conversationID + "");
}
HashSet<String> peopleInChat = new HashSet<>();
peopleInChat.add(thisLogin);
peopleInChat.add(messageUS.getLogin());
connectionInformation.put(conversationID + "", peopleInChat);
MessageUS mess = new MessageUS(Constants.ACCEPTED_CONNECT, messageUS.getLogin(), conversationID + "");
mess.addPhoto(adao.findByUsername(messageUS.getLogin()).getImage());
synchronized (toClient) {
toClient.writeObject(mess);
}
try {
MessageUS mess2 = new MessageUS(Constants.ACCEPTED_CONNECT, thisLogin, conversationID + "");
mess2.addPhoto(adao.findByUsername(thisLogin).getImage());
synchronized (onlinePeople.get(messageUS.getLogin())) {
onlinePeople.get(messageUS.getLogin()).writeObject(mess2);
}
} catch (IOException e) {
}
} catch (SQLException e) {
synchronized (connections.get(thisLogin)) {
connections.get(thisLogin).remove(conversationID + "");
}
synchronized (connections.get(messageUS.getLogin())) {
connections.get(messageUS.getLogin()).remove(conversationID + "");
}
connectionInformation.remove(conversation + "");
MessageUS mes = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mes.setReason("Your connection with " + messageUS.getLogin()
+ " was not established due to server problems. Try again");
synchronized (toClient) {
toClient.writeObject(mes);
}
mes.setReason(
"Your connection with " + thisLogin + " was not established due to server problems. Try again");
synchronized (onlinePeople.get(mes.getLogin())) {
try {
onlinePeople.get(mes.getLogin()).writeObject(mes);
} catch (Exception e1) {
System.err.println("Could not send the message");
}
}
e.printStackTrace();
}
} else
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.DECLINED_CONNECT, messageUS.getLogin(), ""));
}
}
/**
* Decline connect. Sends message to the client who asked to connect
* connection declined answer.
*
* @param messageUS the message containing instruction, and the login of the
* person that sent a connection request
* @throws IOException Signals that an I/O exception has occurred.
*/
private void declineConnect(MessageUS messageUS) throws IOException {
try {
synchronized (onlinePeople.get(messageUS.getLogin())) {
onlinePeople.get(messageUS.getLogin())
.writeObject(new MessageUS(Constants.DECLINED_CONNECT, thisLogin, ""));
}
} catch (Exception e) {
}
}
/**
* Sends a message to the particular chat. Used for both private and group
* chats
*
* @param messageUS the message containing instruction and required
* information: author of the message, message text and conversation id
* @throws IOException
*/
private void sendMessage(MessageUS messageUS) throws IOException {
try {
if (onlinePeople.containsKey(thisLogin) && connectionInformation.containsKey(messageUS.getID())) {
System.out.println("got message " + messageUS.getMessage() + " from " + thisLogin);
HashSet<String> peopleInConversation = connectionInformation.get(messageUS.getID());
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
MessageUS newMessage = new MessageUS(Constants.RECEIVE_MESSAGE, messageUS.getMessage(),
messageUS.getLogin(), messageUS.getID());
newMessage.setTimeStamp(timeStamp);
newMessage.setAccountCreationTime(adao.findByUsername(thisLogin).getTimestamp() + "");
peopleInConversation.forEach(e -> {
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(newMessage);
} catch (IOException e1) {
System.err.println("The message was not sent to " + e);
}
}
});
AccountEntity sender = adao.findByUsername(thisLogin);
ConversationEntity conversation;
GroupEntity group;
try {
// if exception is thrown, means that we are dealing with
// group chat
conversation = cdao.findById(Integer.parseInt(messageUS.getID()));
List<ParticipantEntity> participants = pdao.findByConversation(conversation);
for (ParticipantEntity participant : participants)
if (participant.getAccount().getId() != sender.getId()) {
MessageEntity messageEntity = new MessageEntity(sender, participant.getAccount(),
conversation, messageUS.getMessage());
mdao.create(messageEntity);
}
} catch (Exception e) {
group = gdao.findById(messageUS.getID());
List<GroupMemberEntity> members = gmdao.findByGroup(group);
for (GroupMemberEntity groupMember : members)
if (groupMember.getAccount().getId() != sender.getId()) {
MessageEntity messageEntity = new MessageEntity(sender, groupMember.getAccount(),
cdao.findByGroup(group), messageUS.getMessage());
mdao.create(messageEntity);
}
}
} else {
MessageUS message = new MessageUS(Constants.DECLINED_SEND_MESSAGE, messageUS.getMessage(),
messageUS.getLogin(), messageUS.getID());
message.setAccountCreationTime(adao.findByUsername(thisLogin).getTimestamp() + "");
synchronized (toClient) {
toClient.writeObject(message);
}
}
} catch (Exception e) {
MessageUS message = new MessageUS(Constants.SOMETHING_WENT_WRONG);
message.setReason("The message was not sent");
synchronized (toClient) {
toClient.writeObject(message);
}
}
}
/**
* Send photo to the particular chat.
*
* @param messageUS the message containing instruction and information
* required to send a photo: author, conversation id, and the byte[]
* (representing photo)
*/
private void sendPhoto(MessageUS messageUS) {
try {
if (onlinePeople.containsKey(thisLogin) && connectionInformation.containsKey(messageUS.getID())) {
System.out.println("got photo " + messageUS.getMessage() + " from " + thisLogin);
HashSet<String> peopleInConversation = connectionInformation.get(messageUS.getID());
peopleInConversation.forEach(e -> {
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
MessageUS newMessage = new MessageUS(Constants.RECEIVE_PHOTO, messageUS.getImage(),
messageUS.getLogin(), messageUS.getID());
newMessage.setTimeStamp(timeStamp);
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(newMessage);
} catch (IOException e1) {
}
}
});
} else {
synchronized (toClient) {
MessageUS message = new MessageUS(Constants.PHOTO_DECLINED);
message.setReason("Error! The photo was not sent");
toClient.writeObject(message);
}
}
} catch (Exception e) {
System.err.println("Something went wrong");
}
}
/**
* Sends public message to all online users.
*
* @param message the message containing instruction and required
* information to send a public message: author, message text
*/
private void publicMessage(MessageUS message) {
MessageUS publicMessage = new MessageUS(Constants.RECEIVE_PUBLIC_MESSAGE, message.getMessage(),
message.getLogin(), message.getID());
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
publicMessage.setTimeStamp(timeStamp);
onlinePeople.keySet().forEach(e -> {
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(publicMessage);
} catch (IOException e1) {
System.out.println("The message was not sent");
}
}
});
}
/**
* Send public photo.
*
* @param message the message
*/
private void sendPublicPhoto(MessageUS message) {
MessageUS publicPhoto = new MessageUS(Constants.RECEIVE_PUBLIC_PHOTO, message.getImage(), message.getLogin(),
message.getID());
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
publicPhoto.setTimeStamp(timeStamp);
onlinePeople.keySet().forEach(e -> {
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(publicPhoto);
} catch (IOException e1) {
System.out.println("The message was not sent");
e1.printStackTrace();
}
}
});
}
/**
* Ends the particular chat by sending message containing chat end
* instruction, chat name and chat id.
*
* @param message the message containing instructions and required
* information to end the chat: chat/partner's name and conversation id.
*/
private void endChat(MessageUS message) {
HashSet<String> peopleInChat = connectionInformation.get(message.getID());
connectionInformation.remove(message.getID());
MessageUS newMessage = new MessageUS(Constants.CHAT_ENDED, message.getLogin(), message.getID());
try {
peopleInChat.forEach(e -> {
synchronized (connections.get(e)) {
connections.get(e).remove(message.getID());
}
synchronized (onlinePeople.get(e)) {
if (onlinePeople.containsKey(e) && !e.equals(thisLogin))
try {
onlinePeople.get(e).writeObject(newMessage);
} catch (IOException e1) {
System.err.println("The message was not sent...");
}
}
});
} catch (Exception e) {
System.err.println("Something went wrong...");
}
}
/**
* Ending connection.
*/
public synchronized void end() {
if (thisLogin != null)
try {
HashSet<String> myConnections = connections.get(thisLogin);
if (myConnections == null)
myConnections = new HashSet<>();
myConnections.forEach(e -> {
MessageUS sendBye = new MessageUS(Constants.CHAT_ENDED, thisLogin, e);
connectionInformation.get(e).forEach(q -> {
try {
onlinePeople.get(q).writeObject(sendBye);
connections.get(q).remove(e);
} catch (Exception e1) {
System.err.println("Could not send bye to " + q);
}
});
connectionInformation.remove(e);
});
connections.remove(thisLogin);
onlinePeople.remove(thisLogin);
listOfConnections.remove(this);
listIsChanged();
fromClient.close();
client.close();
} catch (Exception e) {
connections.remove(thisLogin);
onlinePeople.remove(thisLogin);
listOfConnections.remove(this);
listIsChanged();
try {
fromClient.close();
client.close();
} catch (IOException e1) {
}
System.out.println("catching..");
}
}
/**
* List is changed. Called when list of online users changes(due to logging
* in or logging out)
*/
private void listIsChanged() {
Set<String> idPeopleOnline = onlinePeople.keySet();
ArrayList<String> peopleOnline = new ArrayList<>(idPeopleOnline);
MessageUS messageToEverybody = new MessageUS(Constants.LIST_CHANGED, peopleOnline);
listOfConnections.forEach(x -> x.notifyAboutChanges(messageToEverybody));
}
/**
* Notifies users about changed list of online users by sending a message.
*
* @param toSend the message to send to the users, containing the list of
* online people
*/
private void notifyAboutChanges(MessageUS toSend) {
synchronized (toClient) {
try {
toClient.writeObject(toSend);
} catch (IOException e) {
System.err.println("Unable to send message to " + thisLogin);
}
}
}
/**
* Sets the up database.
*/
private void setUpDatabase() {
daoFactory = DAOFactory.getInstance();
this.adao = (AccountDAOImpl) daoFactory.getAccountDAO();
this.cdao = (ConversationDAOImpl) daoFactory.getConversationDAO();
this.gdao = daoFactory.getGroupDAOImpl();
this.gmdao = daoFactory.getGroupMemberDAOImpl();
this.mdao = (MessageDAOImpl) daoFactory.getMessageDAO();
this.pdao = daoFactory.getParticipantDAO();
}
} | UTF-8 | Java | 51,048 | java | ServerThread.java | Java | [
{
"context": "ver. */\n\tprivate static final String EMAIL = \"your1chatroom@gmail.com\";\n\n\t/** The Constant password o",
"end": 1776,
"score": 0.8245377540588379,
"start": 1775,
"tag": "EMAIL",
"value": "1"
},
{
"context": "er. */\n\tprivate static final String EMAIL = \"your1chatroom@gmail.com\";\n\n\t/** The Constant password of the server's ema",
"end": 1794,
"score": 0.9998813271522522,
"start": 1776,
"tag": "EMAIL",
"value": "chatroom@gmail.com"
},
{
"context": " address. */\n\tprivate static final String PASS = \"softwareworkshop\";\n\n\t/** The client. */\n\tprivate Socket client;\n\n\t",
"end": 1912,
"score": 0.9991218447685242,
"start": 1896,
"tag": "PASSWORD",
"value": "softwareworkshop"
},
{
"context": "y = adao.getParticularHistory(adao.findByUsername(thisLogin),\n\t\t\t\t\t\tadao.findByUsername(info[0]));\n\t\t\t\tHashMa",
"end": 23480,
"score": 0.6942059397697449,
"start": 23471,
"tag": "USERNAME",
"value": "thisLogin"
},
{
"context": "es not exist!\");\n\t\t\t} else {\n\t\t\t\tString password = adao.generateTempPassword(adao.findByUsername(m.getLogin()));\n\t\t\t\tuserEmail",
"end": 28165,
"score": 0.8798286318778992,
"start": 28140,
"tag": "PASSWORD",
"value": "adao.generateTempPassword"
},
{
"context": "\t\t\tAccountEntity sender = adao.findByUsername(thisLogin);\n\t\t\t\tConversationEntity conversation;\n\t\t\t\tGroupE",
"end": 43347,
"score": 0.5453516840934753,
"start": 43342,
"tag": "USERNAME",
"value": "Login"
}
]
| null | []
| package grimsby.networking.server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import grimsby.libraries.dataaccess.dao.factory.DAOFactory;
import grimsby.libraries.dataaccess.dao.impl.AccountDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.ConversationDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.GroupDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.GroupMemberDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.MessageDAOImpl;
import grimsby.libraries.dataaccess.dao.impl.ParticipantDAOImpl;
import grimsby.libraries.entities.AccountEntity;
import grimsby.libraries.entities.ConversationEntity;
import grimsby.libraries.entities.GroupEntity;
import grimsby.libraries.entities.GroupMemberEntity;
import grimsby.libraries.entities.MessageEntity;
import grimsby.libraries.entities.ParticipantEntity;
import grimsby.networking.util.Constants;
import grimsby.networking.util.MessageUS;
import grimsby.networking.util.User;
/**
* The Class ServerThread. Created for communication between a client and the
* server. Each client has one thread and sends commands to the server.
*/
public class ServerThread extends Thread {
/** The Constant EMAIL address of the server. */
private static final String EMAIL = "your1<EMAIL>";
/** The Constant password of the server's email address. */
private static final String PASS = "<PASSWORD>";
/** The client. */
private Socket client;
/** The online people. */
private ConcurrentHashMap<String, ObjectOutputStream> onlinePeople;
/** The connections. */
private ConcurrentHashMap<String, HashSet<String>> connections;
/** The connection information. */
private ConcurrentHashMap<String, HashSet<String>> connectionInformation;
/** The to client. */
private ObjectOutputStream toClient;
/** The from client. */
private ObjectInputStream fromClient;
/** The this login. */
private String thisLogin;
/** The list of connections. */
private List<ServerThread> listOfConnections;
/** The dao factory. */
private DAOFactory daoFactory;
/** The adao. */
private AccountDAOImpl adao;
/** The cdao. */
private ConversationDAOImpl cdao;
/** The gdao. */
private GroupDAOImpl gdao;
/** The gmdao. */
private GroupMemberDAOImpl gmdao;
/** The mdao. */
private MessageDAOImpl mdao;
/** The pdao. */
private ParticipantDAOImpl pdao;
/** The account. */
private AccountEntity account;
/**
* Instantiates a new server thread.
*
* @param client the client
* @param onlinePeople the online people
* @param connections the connections
* @param connectionInformation the connection information
* @param listOfConnections the list of connections
*/
public ServerThread(Socket client, ConcurrentHashMap<String, ObjectOutputStream> onlinePeople,
ConcurrentHashMap<String, HashSet<String>> connections,
ConcurrentHashMap<String, HashSet<String>> connectionInformation, List<ServerThread> listOfConnections) {
super("ServerThread");
try {
fromClient = new ObjectInputStream(client.getInputStream());
toClient = new ObjectOutputStream(client.getOutputStream());
} catch (IOException e) {
System.err.println("connection with client was not created...");
this.interrupt();
}
this.connections = connections;
this.client = client;
this.onlinePeople = onlinePeople;
this.listOfConnections = listOfConnections;
this.connectionInformation = connectionInformation;
this.thisLogin = null;
setUpDatabase();
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
public void run() {
while (true) {
try {
MessageUS message = (MessageUS) fromClient.readObject();
String comand = message.getInstruction();
System.out.println("I got new command: " + comand);
if (comand.equals(Constants.LOGIN)) {
login(message);
} else if (comand.equals(Constants.FORGOT_PASSWORD)) {
forgotPassword(message);
} else if (comand.equals(Constants.CREATE_ACCOUNT)) {
createAccount(message);
} else if (thisLogin != null && onlinePeople.containsKey(thisLogin)) {
if (comand.equals(Constants.CONNECT)) {
connect(message);
} else if (comand.equals(Constants.CREATE_GROUP)) {
createGroup(message);
} else if (comand.equals(Constants.ADD_PERSON)) {
addPersonToGroup(message);
} else if (comand.equals(Constants.ACCEPTED_CONNECT)) {
acceptConnect(message);
} else if (comand.equals(Constants.DECLINED_CONNECT)) {
declineConnect(message);
} else if (comand.equals(Constants.SEND_MESSAGE)) {
sendMessage(message);
} else if (comand.equals(Constants.PUBLIC_MESSAGE)) {
publicMessage(message);
} else if (comand.equals(Constants.SEND_PHOTO)) {
sendPhoto(message);
} else if (comand.equals(Constants.SEND_PUBLIC_PHOTO)) {
sendPublicPhoto(message);
} else if (comand.equals(Constants.END_CHAT)) {
endChat(message);
} else if (comand.equals(Constants.LOAD_ALL_HISTORY)) {
loadAllHistory(message);
} else if (comand.equals(Constants.LOAD_PARTICULAR_HISTORY)) {
loadParticularHistory(message);
} else if (comand.equals(Constants.GET_MY_TOP)) {
getTop();
} else if (comand.equals(Constants.UPLOAD_PHOTO)) {
uploadPhoto(message);
} else if (comand.equals(Constants.VIEW_PROFILE)) {
viewProfile(message);
} else if (comand.equals(Constants.CHANGE_PASSWORD)) {
changePassword(message);
} else if (comand.equals(Constants.CHANGE_NAME)) {
changeName(message);
} else if (comand.equals(Constants.CHANGE_SURENAME)) {
changeSurname(message);
} else if (comand.equals(Constants.CHANGE_EMAIL)) {
changeEmail(message);
} else if (comand.equals(Constants.CHANGE_BIO)) {
changeBio(message);
} else if (comand.equals(Constants.PLAY_TIC_TAC_REQUEST)) {
play2TicTac(message);
} else if (comand.equals(Constants.PLAY_TIC_TAC_ACCEPTED)) {
accept2TicTac(message);
} else if (comand.equals(Constants.PLAY_TIC_TAC_DECLINED)) {
decline2TicTac(message);
} else if (comand.equals(Constants.MOVE_TIC_TAC)) {
move2TicTac(message);
} else if (comand.equals(Constants.END_TIC_TAC)) {
endTicTac(message);
} else if (comand.equals(Constants.END_OF_GAME)) {
endOfGame(message);
} else if (comand.equals(Constants.SET_THEME)) {
setTheme(message);
} else if (comand.equals(Constants.END)) {
end();
break;
} else if (comand.equals(Constants.DELETE_ACCOUNT)) {
deleteAccount();
} else {
System.err.println("unknown command " + comand);
}
} else {
MessageUS m = new MessageUS(Constants.SOMETHING_WENT_WRONG);
m.setReason("You are logged off! You need to log in first");
synchronized (toClient) {
toClient.writeObject(m);
}
}
} catch (SocketException e) {
// System.err.println("Socket exception.");
end();
break;
} catch (Exception e) {
System.err.println("Other exception.");
e.printStackTrace();
end();
break;
}
}
System.out.println("bye bye " + thisLogin);
}
private void deleteAccount() throws IOException {
boolean deleted = true;
try {
deleted = adao.delete(adao.findByUsername(thisLogin));
} catch (Exception e) {
deleted = false;
}
MessageUS informationMessage = new MessageUS(Constants.DELETE_ACCOUNT_SUCCESSFUL);
if (!deleted)
informationMessage = new MessageUS(Constants.DELETE_ACCOUNT_UNSUCCESSFUL);
synchronized (toClient) {
toClient.writeObject(informationMessage);
}
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
}
end();
}
/**
* Sets the theme. in the database. If operation is unsuccessful, sends
* answer something went wrong.
*
* @param message the new theme
* @throws IOException Signals that an I/O exception has occurred.
*/
private void setTheme(MessageUS message) throws IOException {
try {
adao.setDarkTheme(adao.findByUsername(thisLogin), message.getStyle() == 1);
} catch (SQLException e) {
MessageUS mess = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mess.setReason("Server error! the theme you chosen was not saved");
synchronized (toClient) {
toClient.writeObject(mess);
}
}
}
/**
* End of game. Sends to both of the players the message informing that the
* game has ended.
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void endOfGame(MessageUS message) throws IOException {
MessageUS messageWinner = new MessageUS(message.getInstruction(), message.getLogin(), message.getLogin());
messageWinner.setReason(message.getReason());
messageWinner.setX(message.getX());
messageWinner.setPlayer(message.isPlayer1());
MessageUS messageLooser = new MessageUS(message.getInstruction(), thisLogin, thisLogin);
messageLooser.setReason(message.getReason());
messageLooser.setX(message.getX());
messageLooser.setPlayer(message.isPlayer1());
try {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin()).writeObject(messageLooser);
}
} catch (Exception e) {
}
synchronized (toClient) {
toClient.writeObject(messageWinner);
}
}
private void endTicTac(MessageUS message) throws IOException {
MessageUS messageWinner = new MessageUS(message.getInstruction(), thisLogin, thisLogin);
messageWinner.setReason(message.getReason());
messageWinner.setX(message.getX());
try {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin()).writeObject(messageWinner);
}
} catch (Exception e) {
}
}
/**
* Play 2 tic tac toe. Sends request to play tick tack toe to the other
* person
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void play2TicTac(MessageUS message) throws IOException {
try {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(message.getLogin())
&& !thisLogin.equals(message.getLogin())) {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin())
.writeObject(new MessageUS(Constants.PLAY_TIC_TAC_REQUEST, thisLogin, ""));
}
} else {
MessageUS mess = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mess.setReason("The person you are trying to play game with is offline");
synchronized (toClient) {
toClient.writeObject(mess);
}
}
} catch (Exception e) {
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.SOMETHING_WENT_WRONG));
}
}
}
/**
* Accept 2 tic tac toe play
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void accept2TicTac(MessageUS message) throws IOException {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(message.getLogin())) {
try {
// Game id will be our partner's login
MessageUS messPlayer1 = new MessageUS(Constants.PLAY_TIC_TAC_ACCEPTED, thisLogin, true);
try {
messPlayer1.addPhoto(adao.findByUsername(thisLogin).getImage());
} catch (Exception e) {
}
MessageUS messPlayer2 = new MessageUS(Constants.PLAY_TIC_TAC_ACCEPTED, message.getLogin(), false);
try {
messPlayer2.addPhoto(adao.findByUsername(message.getLogin()).getImage());
} catch (Exception e) {
}
synchronized (toClient) {
toClient.writeObject(messPlayer2);
}
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin()).writeObject(messPlayer1);
}
} catch (Exception e) {
try {
MessageUS mes = new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, message.getLogin(), "");
synchronized (toClient) {
toClient.writeObject(mes);
}
mes = new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, thisLogin, "");
synchronized (onlinePeople.get(mes.getLogin())) {
try {
onlinePeople.get(mes.getLogin()).writeObject(mes);
} catch (Exception e1) {
System.err.println("Could not send a message");
}
}
} catch (Exception ex) {
}
}
} else
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, message.getLogin(), ""));
}
}
/**
* Decline 2 tic tac toegame.
*
* @param message the message
*/
private void decline2TicTac(MessageUS message) {
MessageUS messPlayer1 = new MessageUS(Constants.PLAY_TIC_TAC_DECLINED, thisLogin, "");
try {
onlinePeople.get(message.getLogin()).writeObject(messPlayer1);
} catch (IOException e) {
}
}
/**
* Move 2 tic tac.
*
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
private void move2TicTac(MessageUS message) throws IOException {
MessageUS mess = new MessageUS(Constants.MOVE_TIC_TAC, thisLogin, message.getX());
System.out.println("login of the partner: " + message.getLogin());
synchronized (onlinePeople.get(message.getLogin())) {
try {
onlinePeople.get(message.getLogin()).writeObject(mess);
} catch (IOException e) {
toClient.writeObject(new MessageUS(Constants.END_TIC_TAC, mess.getLogin(), ""));
try {
if (onlinePeople.contains(message.getLogin())) {
synchronized (onlinePeople.get(message.getLogin())) {
onlinePeople.get(message.getLogin())
.writeObject(new MessageUS(Constants.END_TIC_TAC, thisLogin, ""));
}
}
} catch (Exception ex) {
}
}
}
}
/**
* Change bio information. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and updated bio.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeBio(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.updateBio(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
e.printStackTrace();
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_BIO_ACCEPTED, new String[] { userInfo });
information.setReason("Your bio was successfully updated!");
} else {
information = new MessageUS(Constants.CHANGE_BIO_DECLINED);
information.setReason("Error! Your bio was not updated. Try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Changes user's email address containing instruction and new email
* address. The new email address is set only if it is unique in the
* database. Sends message to the user informing whether the action was
* successful.
*
* @param message the message containing instruction and new email adress
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeEmail(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.updateEmail(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_EMAIL_ACCEPTED, new String[] { userInfo });
information.setReason("Your email address was successfully updated!");
} else {
information = new MessageUS(Constants.CHANGE_EMAIL_DECLINED);
try {
if (null != adao.findByEmail(message.getUserInformation()[0]))
information.setReason("The email address: " + userInfo + " is already registered. Try another one");
else
information.setReason("Server error. Email address could not be updated");
} catch (SQLException e1) {
System.err.println("SQL exception");
information.setReason("Error! Email address could not be updated");
}
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Changes client's surname. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and new surname.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeSurname(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.setSurname(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
System.err.println("SQL exception");
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_SURENAME_ACCEPTED, new String[] { userInfo });
information.setReason("Your surname was successfully changed!");
} else {
information = new MessageUS(Constants.CHANGE_SURENAME_DECLINED);
information.setReason("Error! your surname was not changed. Try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Changes client's name. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and new name
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changeName(MessageUS message) throws IOException {
boolean wasSuccessful = false;
String userInfo = message.getUserInformation()[0];
try {
wasSuccessful = adao.setName(adao.findByUsername(thisLogin), userInfo);
} catch (SQLException e) {
System.err.println("SQL exception");
}
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
if (wasSuccessful) {
information = new MessageUS(Constants.CHANGE_NAME_ACCEPTED, new String[] { userInfo });
information.setReason("Your name was successfully updated!");
} else {
information = new MessageUS(Constants.CHANGE_NAME_DECLINED);
information.setReason("Error! your name was not updated. Try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* View profile. Sends the message to the client containing the profile
* information of the requested user.
*
* @param message the message containing instruction and login of the user
* whose profile information is requested
* @throws IOException Signals that an I/O exception has occurred.
*/
private void viewProfile(MessageUS message) throws IOException {
MessageUS information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
String username = message.getLogin();
AccountEntity theUsersAccount = adao.findByUsername(username);
String[] info = { username, theUsersAccount.getName(), theUsersAccount.getSurname(),
theUsersAccount.getEmail(), theUsersAccount.getBio() };
information = new MessageUS(Constants.VIEW_PROFILE, info);
byte[] photo = adao.findByUsername(message.getLogin()).getImage();
information.addPhoto(photo);
} catch (Exception e) {
e.printStackTrace();
information = new MessageUS(Constants.SOMETHING_WENT_WRONG);
information.setReason("The users " + message.getLogin() + " information could not be loaded. try again");
}
synchronized (toClient) {
toClient.writeObject(information);
}
}
/**
* Uploads a new photo. Sends message to the user informing whether the
* action was successful.
*
* @param message the message containing instruction and byte[]
* @throws IOException Signals that an I/O exception has occurred.
*/
private void uploadPhoto(MessageUS message) throws IOException {
MessageUS uploaded = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
byte[] photo = message.getImage();
adao.updateImage(adao.findByUsername(thisLogin), thisLogin + System.currentTimeMillis(), photo);
uploaded = new MessageUS(Constants.PHOTO_UPLOADED);
uploaded.addPhoto(photo);
} catch (Exception e) {
uploaded = new MessageUS(Constants.PHOTO_DECLINED);
}
toClient.writeObject(uploaded);
}
/**
* Gets the favourite users and sends the message containing these users to
* the client.
*
* @return the top
* @throws IOException Signals that an I/O exception has occurred.
*/
private void getTop() throws IOException {
MessageUS messageOfTop = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
List<AccountEntity> accounts = adao.getTopContacts(adao.findByUsername(thisLogin), 4);
Set<User> myTopContacts = new HashSet<>();
accounts.forEach(ac -> myTopContacts.add(new User(ac.getImage(), ac.getUsername())));
messageOfTop = new MessageUS(Constants.GET_MY_TOP, myTopContacts, thisLogin, "");
} catch (SQLException e) {
e.printStackTrace();
messageOfTop = new MessageUS(Constants.SOMETHING_WENT_WRONG);
messageOfTop.setReason("Something went wrong. Could not give top contacts list");
}
synchronized (toClient) {
toClient.writeObject(messageOfTop);
}
}
/**
* Load all history. Gets and sends the whole history of the client
*
* @param message the message containing instruction
* @throws IOException Signals that an I/O exception has occurred.
*/
private void loadAllHistory(MessageUS message) throws IOException {
MessageUS sendingHistory = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
List<String> historyList = adao.getAllHistory(adao.findByUsername(thisLogin));
String[][] temp = new String[historyList.size()][1];
for (int i = 0; i < historyList.size(); i++)
temp[i][0] = historyList.get(i);
sendingHistory = new MessageUS(Constants.LOAD_ALL_HISTORY, temp, new HashMap<>());
} catch (Exception e) {
sendingHistory = new MessageUS(Constants.SOMETHING_WENT_WRONG);
sendingHistory.setReason("The history could not be loaded. Try again");
}
synchronized (sendingHistory) {
toClient.writeObject(sendingHistory);
}
}
/**
* Load particular history. Gets and sends particular history to the user
*
* @param message the message containing instruction and the information
* about which chat should be loaded
* @throws IOException Signals that an I/O exception has occurred.
*/
private void loadParticularHistory(MessageUS message) throws IOException {
MessageUS messageUS = new MessageUS(Constants.SOMETHING_WENT_WRONG);
String[] info = message.getUserInformation()[0].split("---");
try {
if (info[0].contains("-")) {
String groupId = info[0].split("-")[1] + "---" + info[1];
String[][] history = adao.getParticularGroupHistory(groupId);
HashMap<String, String> creationT = new HashMap<>();
for (String[] arr : history)
creationT.put(arr[0], adao.findByUsername(arr[0]).getTimestamp() + "");
messageUS = new MessageUS(Constants.LOAD_PARTICULAR_HISTORY, history, creationT);
} else {
String[][] history = adao.getParticularHistory(adao.findByUsername(thisLogin),
adao.findByUsername(info[0]));
HashMap<String, String> creationT = new HashMap<>();
for (String[] arr : history)
creationT.put(arr[0], adao.findByUsername(arr[0]).getTimestamp() + "");
messageUS = new MessageUS(Constants.LOAD_PARTICULAR_HISTORY, history, creationT);
}
synchronized (toClient) {
toClient.writeObject(messageUS);
}
} catch (Exception e) {
MessageUS mess = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mess.setReason("Unable to load the history with: " + info[0]);
synchronized (toClient) {
toClient.writeObject(mess);
}
}
}
/**
* Changes password.Sends message to the user informing whether the action
* was successful.
*
* @param message the message containing instruction, old and new passwords
* @throws IOException Signals that an I/O exception has occurred.
*/
private void changePassword(MessageUS message) throws IOException {
MessageUS answer = new MessageUS(Constants.DECLINE_PASSWORD);
String[] accoutnInfo = message.getUserInformation();
String oldPass = accoutnInfo[0];
String newPass = accoutnInfo[1];
try {
if (oldPass.equals((account = adao.findByUsername(thisLogin)).getPassword())) {
adao.updatePassword(account, newPass);
answer = new MessageUS(Constants.ACCEPT_PASSWORD);
} else
answer.setReason("Your old password is incorrect!");
} catch (Exception e) {
answer.setReason("Something went wrong... Your password was not changed");
System.err.println("Password was not changed");
}
synchronized (toClient) {
toClient.writeObject(answer);
}
}
/**
* Login. Logins the user or declines the logging in. Sends the outcome to
* the user. If logging in was successful, additional information is added
* to the message: username, registration time, flags for temporary password
* and first time logging in as well as photo as byte[]. otherwise declined
* login instruction is sent
*
* @param message the message containing instruction and relevant
* information
* @throws Exception the exception
*/
private void login(MessageUS message) throws Exception {
MessageUS answer = new MessageUS(Constants.SOMETHING_WENT_WRONG);
String[] details = message.getUserInformation();
String username = details[0];
String password = details[1];
account = adao.findByUsername(username);
answer = new MessageUS(Constants.DECLINED_LOGIN);
if (adao.findByUsername(username) == null)
answer.setReason("The username " + username + " does not exist!");
else {
boolean verified = adao.verifyUser(username, password);
if (verified) {
this.thisLogin = username;
if (!onlinePeople.containsKey(thisLogin)) {
getTop();
String[] userInformation = new String[] { thisLogin,
adao.findByUsername(thisLogin).getTimestamp() + "" };
answer = new MessageUS(Constants.ACCEPTED_LOGIN, userInformation);
answer.setTempData(adao.findByUsername(thisLogin).getEmail());
if (account.isReminder())
answer.setTemporaty();
if (account.isFirstLogin())
answer.setIsFirstTime();
byte[] photo = adao.findByUsername(username).getImage();
answer.addPhoto(photo);
int style = adao.findByUsername(thisLogin).isDarkTheme() ? 1 : 0;
answer.setStyle(style);
onlinePeople.put(thisLogin, toClient);
connections.put(thisLogin, new HashSet<>());
listOfConnections.add(this);
System.out.println(thisLogin + " is logged!");
adao.setFirstLogin(account, false);
} else
answer.setReason("You cannot login whilst being online...");
} else
answer.setReason("The password is incorrect. Try again or send reminder to the email.");
}
synchronized (toClient) {
toClient.writeObject(answer);
}
listIsChanged();
}
/**
* Forgot password. Sends reminder to the clients email adress which is
* stored in database. Information message about the success or failure is
* sent to the client.
*
* Reference:
* https://crunchify.com/java-mailapi-example-send-an-email-via-gmail-smtp/
*
* @param m the message containing instruction and clients login.
* @throws Exception the exception
*/
private void forgotPassword(MessageUS m) throws Exception {
MessageUS messageUS = new MessageUS(Constants.SOMETHING_WENT_WRONG);
try {
System.out.println("forgot password");
String userEmailAdress = null;
if (adao.findByUsername(m.getLogin()) == null) {
System.out.println("account does not exist");
messageUS = new MessageUS(Constants.EMAIL_NOT_SENT);
messageUS.setReason("The account with username: " + m.getLogin() + " does not exist!");
} else {
String password = <PASSWORD>(adao.findByUsername(m.getLogin()));
userEmailAdress = adao.findByUsername(m.getLogin()).getEmail();
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session getMailSession = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(getMailSession);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(userEmailAdress));
message.setSubject("Password reminder");
String emailBody = "Dear " + m.getLogin() + ","
+ "<br><br>Thank you for using our Chatroom. <br>Your temporary password is: " + password
+ " . Use this password when logging in.<br><br> Regards, <br>Chatroom team";
message.setContent(emailBody, "text/html");
Transport transport = getMailSession.getTransport("smtp");
transport.connect("smtp.gmail.com", EMAIL, PASS);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
messageUS = (new MessageUS(Constants.EMAIL_SENT));
}
} catch (Exception e) {
System.out.println("The letter was not sent");
e.printStackTrace();
messageUS = (new MessageUS(Constants.EMAIL_NOT_SENT));
messageUS.setReason("Error in server...");
} finally {
synchronized (toClient) {
toClient.writeObject(messageUS);
}
}
}
/**
* Creates the account. Sends confirmation or failure message to the client.
*
* @param messageUS the message containing instructions and potential
* client's information: username, password, email address
* @throws IOException Signals that an I/O exception has occurred.
*/
private void createAccount(MessageUS messageUS) throws IOException {
try {
String[] userDetails = messageUS.getUserInformation();
String username = userDetails[0];
String password = userDetails[1];
String email = userDetails[2];
String name = "Unknown";
String surname = "Unknown";
boolean usernameNotTaken = false;
if ((usernameNotTaken = ((account = adao.findByUsername(username)) == null))
&& adao.findByEmail(email) == null) {
account = new AccountEntity(username, password, name, surname, email, false, true,
"You have no bio :) ");
adao.create(account);
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.ACCEPTED_CREATE_ACCOUNT));
}
} else {
MessageUS m = new MessageUS(Constants.DECLINED_CREATE_ACCOUNT);
if (!usernameNotTaken) {
m.setReason("The username " + username + " is taken. Try another one");
System.out.println("username taken");
} else
m.setReason("The email adress " + email + " is taken. Try another one");
synchronized (toClient) {
toClient.writeObject(m);
}
}
} catch (SQLException e) {
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.SOMETHING_WENT_WRONG));
}
}
}
/**
* Connect. Sends a connection request to the chosen client.
*
* @param messageUS the message containing instruction and the potential
* partner's username
* @throws IOException Signals that an I/O exception has occurred.
*/
private void connect(MessageUS messageUS) throws IOException {
try {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(messageUS.getLogin())
&& !thisLogin.equals(messageUS.getLogin())) {
synchronized (onlinePeople.get(messageUS.getLogin())) {
onlinePeople.get(messageUS.getLogin())
.writeObject(new MessageUS(Constants.CONNECTION_REQUEST, thisLogin, ""));
}
System.out.println("Asking for the permission to connect...");
} else
synchronized (toClient) {
MessageUS message = new MessageUS(Constants.DECLINED_CONNECT, messageUS.getLogin(), "");
message.setReason("The person you are trying to connect with is offline");
toClient.writeObject(message);
}
} catch (Exception e) {
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.SOMETHING_WENT_WRONG));
}
}
}
/**
* Creates the group. Sends information message to all the members of the
* group containing accepted connect group instruction, group name and group
* id.
*
* @param message the message containing instruction and group name
* @throws IOException Signals that an I/O exception has occurred.
*/
private void createGroup(MessageUS message) throws IOException {
System.out.println("creating group");
// people online is list of people in this group chat
ArrayList<String> peopleInGroup = message.getPeopleOnline();
peopleInGroup.add(thisLogin);
for (String person : peopleInGroup)
if (!onlinePeople.containsKey(person))
peopleInGroup.remove(person);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
String groupID = message.getName() + "---" + currentTime;
System.out.println("Potential group id: " + groupID);
try {
account = adao.findByUsername(thisLogin);
GroupEntity groupEntity = new GroupEntity(groupID, account, message.getName(), currentTime);
gdao.create(groupEntity);
MessageUS messageConnection = new MessageUS(Constants.ACCEPTED_CONNECT_GROUP, message.getName(), groupID);
Set<User> potentialParticipants = new HashSet<>();
peopleInGroup.forEach(name -> {
try {
User newUser = new User(adao.findByUsername(name).getImage(), name);
potentialParticipants.add(newUser);
} catch (SQLException e1) {
System.err.println("Could not add image of " + name + " to the array");
e1.printStackTrace();
}
});
// even some of them might not be successful, but it is better to
// have them all and do not use uneccessary data in user
messageConnection.setPeople(potentialParticipants);
peopleInGroup.forEach(e -> {
if (onlinePeople.containsKey(e))
synchronized (onlinePeople.get(e)) {
try {
GroupMemberEntity groupMember = new GroupMemberEntity(groupEntity, adao.findByUsername(e));
gmdao.create(groupMember);
onlinePeople.get(e).writeObject(messageConnection);
synchronized (connections.get(e)) {
connections.get(e).add(groupID);
}
} catch (Exception e1) {
peopleInGroup.remove(e);
e1.printStackTrace();
}
}
else
peopleInGroup.remove(e);
});
connectionInformation.put(groupID, new HashSet<>(peopleInGroup));
ConversationEntity conversation = new ConversationEntity(adao.findByUsername(thisLogin),
gdao.findById(groupID));
cdao.create(conversation);
} catch (SQLException e2) {
MessageUS messageConnection = new MessageUS(Constants.SOMETHING_WENT_WRONG);
messageConnection.setReason("The group " + message.getName() + " could not be created");
synchronized (messageConnection) {
toClient.writeObject(messageConnection);
}
}
}
/**
* Adds the person to group. Sends the notification to all members of the
* group.
*
* @param message the message containing instruction, login of the person to
* be added and the chat id.
* @throws IOException Signals that an I/O exception has occurred.
*/
private void addPersonToGroup(MessageUS message) throws IOException {
String personToAdd = message.getLogin();
String chatID = message.getID();
String chatName = message.getName();
if (onlinePeople.containsKey(personToAdd)) {
if (connectionInformation.containsKey(personToAdd)) {
try {
MessageUS mess = new MessageUS(Constants.DECLINED_ADD, personToAdd, chatID);
mess.setName(chatName);
mess.setReason(personToAdd + " is already in the group chat \"" + chatName + "\"");
try {
mess.addPhoto(adao.findByUsername(personToAdd).getImage());
} catch (SQLException e) {
mess.addPhoto(null);
}
synchronized (toClient) {
toClient.writeObject(mess);
}
} catch (IOException e) {
}
} else {
HashSet<String> peopleInTheChat = connectionInformation.get(chatID);
peopleInTheChat.add(personToAdd);
HashSet<User> setOfPeople = new HashSet<>();
peopleInTheChat.forEach(name -> {
try {
User thisUser = new User(adao.findByUsername(name).getImage(), name);
setOfPeople.add(thisUser);
} catch (SQLException e) {
e.printStackTrace();
}
});
try {
gmdao.create(new GroupMemberEntity(gdao.findById(chatID), adao.findByUsername(personToAdd)));
} catch (SQLException e1) {
MessageUS mess = new MessageUS(Constants.DECLINED_ADD, personToAdd, chatID);
mess.setReason("Server error ");
synchronized (toClient) {
toClient.writeObject(mess);
}
e1.printStackTrace();
}
MessageUS messageConnection = new MessageUS(Constants.ACCEPTED_CONNECT_GROUP, chatName, chatID);
messageConnection.setPeople(setOfPeople);
synchronized (onlinePeople.get(personToAdd)) {
try {
onlinePeople.get(personToAdd).writeObject(messageConnection);
} catch (IOException e) {
return;
}
}
MessageUS mess = new MessageUS(Constants.ACCEPTED_ADD, personToAdd, chatID);
mess.setName(chatName);
try {
mess.addPhoto(adao.findByUsername(personToAdd).getImage());
} catch (SQLException e1) {
}
peopleInTheChat.forEach(x -> {
if (!x.equals(personToAdd))
synchronized (onlinePeople.get(x)) {
try {
onlinePeople.get(x).writeObject(mess);
} catch (IOException e) {
System.out.println("Could not send the message to " + x);
}
}
});
}
synchronized (connections.get(personToAdd)) {
connections.get(personToAdd).add(message.getID());
}
synchronized (connectionInformation.get(message.getID())) {
connectionInformation.get(message.getID()).add(personToAdd);
}
}
}
/**
* Accept connect. Sends confirmation message to the person who sent the
* connection request. Creates new private chat
*
* @param messageUS the message containing instruction and login of the
* partner
* @throws IOException Signals that an I/O exception has occurred.
*/
private void acceptConnect(MessageUS messageUS) throws IOException {
if (onlinePeople.containsKey(thisLogin) && onlinePeople.containsKey(messageUS.getLogin())) {
grimsby.libraries.entities.ConversationEntity conversation = null;
List<grimsby.libraries.entities.ConversationEntity> conversations = null;
int conversationID = -1;
try {
conversation = new grimsby.libraries.entities.ConversationEntity(
adao.findByUsername(messageUS.getLogin()), null);
cdao.create(conversation);
conversations = cdao.findByOwner(adao.findByUsername(messageUS.getLogin()));
conversation = conversations.get(conversations.size() - 1);
ParticipantEntity sender = new ParticipantEntity(adao.findByUsername(messageUS.getLogin()),
conversation);
ParticipantEntity receiver = new ParticipantEntity(adao.findByUsername(thisLogin), conversation);
pdao.create(sender);
pdao.create(receiver);
conversationID = conversation.getId();
synchronized (connections.get(thisLogin)) {
connections.get(thisLogin).add(conversationID + "");
}
synchronized (connections.get(messageUS.getLogin())) {
connections.get(messageUS.getLogin()).add(conversationID + "");
}
HashSet<String> peopleInChat = new HashSet<>();
peopleInChat.add(thisLogin);
peopleInChat.add(messageUS.getLogin());
connectionInformation.put(conversationID + "", peopleInChat);
MessageUS mess = new MessageUS(Constants.ACCEPTED_CONNECT, messageUS.getLogin(), conversationID + "");
mess.addPhoto(adao.findByUsername(messageUS.getLogin()).getImage());
synchronized (toClient) {
toClient.writeObject(mess);
}
try {
MessageUS mess2 = new MessageUS(Constants.ACCEPTED_CONNECT, thisLogin, conversationID + "");
mess2.addPhoto(adao.findByUsername(thisLogin).getImage());
synchronized (onlinePeople.get(messageUS.getLogin())) {
onlinePeople.get(messageUS.getLogin()).writeObject(mess2);
}
} catch (IOException e) {
}
} catch (SQLException e) {
synchronized (connections.get(thisLogin)) {
connections.get(thisLogin).remove(conversationID + "");
}
synchronized (connections.get(messageUS.getLogin())) {
connections.get(messageUS.getLogin()).remove(conversationID + "");
}
connectionInformation.remove(conversation + "");
MessageUS mes = new MessageUS(Constants.SOMETHING_WENT_WRONG);
mes.setReason("Your connection with " + messageUS.getLogin()
+ " was not established due to server problems. Try again");
synchronized (toClient) {
toClient.writeObject(mes);
}
mes.setReason(
"Your connection with " + thisLogin + " was not established due to server problems. Try again");
synchronized (onlinePeople.get(mes.getLogin())) {
try {
onlinePeople.get(mes.getLogin()).writeObject(mes);
} catch (Exception e1) {
System.err.println("Could not send the message");
}
}
e.printStackTrace();
}
} else
synchronized (toClient) {
toClient.writeObject(new MessageUS(Constants.DECLINED_CONNECT, messageUS.getLogin(), ""));
}
}
/**
* Decline connect. Sends message to the client who asked to connect
* connection declined answer.
*
* @param messageUS the message containing instruction, and the login of the
* person that sent a connection request
* @throws IOException Signals that an I/O exception has occurred.
*/
private void declineConnect(MessageUS messageUS) throws IOException {
try {
synchronized (onlinePeople.get(messageUS.getLogin())) {
onlinePeople.get(messageUS.getLogin())
.writeObject(new MessageUS(Constants.DECLINED_CONNECT, thisLogin, ""));
}
} catch (Exception e) {
}
}
/**
* Sends a message to the particular chat. Used for both private and group
* chats
*
* @param messageUS the message containing instruction and required
* information: author of the message, message text and conversation id
* @throws IOException
*/
private void sendMessage(MessageUS messageUS) throws IOException {
try {
if (onlinePeople.containsKey(thisLogin) && connectionInformation.containsKey(messageUS.getID())) {
System.out.println("got message " + messageUS.getMessage() + " from " + thisLogin);
HashSet<String> peopleInConversation = connectionInformation.get(messageUS.getID());
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
MessageUS newMessage = new MessageUS(Constants.RECEIVE_MESSAGE, messageUS.getMessage(),
messageUS.getLogin(), messageUS.getID());
newMessage.setTimeStamp(timeStamp);
newMessage.setAccountCreationTime(adao.findByUsername(thisLogin).getTimestamp() + "");
peopleInConversation.forEach(e -> {
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(newMessage);
} catch (IOException e1) {
System.err.println("The message was not sent to " + e);
}
}
});
AccountEntity sender = adao.findByUsername(thisLogin);
ConversationEntity conversation;
GroupEntity group;
try {
// if exception is thrown, means that we are dealing with
// group chat
conversation = cdao.findById(Integer.parseInt(messageUS.getID()));
List<ParticipantEntity> participants = pdao.findByConversation(conversation);
for (ParticipantEntity participant : participants)
if (participant.getAccount().getId() != sender.getId()) {
MessageEntity messageEntity = new MessageEntity(sender, participant.getAccount(),
conversation, messageUS.getMessage());
mdao.create(messageEntity);
}
} catch (Exception e) {
group = gdao.findById(messageUS.getID());
List<GroupMemberEntity> members = gmdao.findByGroup(group);
for (GroupMemberEntity groupMember : members)
if (groupMember.getAccount().getId() != sender.getId()) {
MessageEntity messageEntity = new MessageEntity(sender, groupMember.getAccount(),
cdao.findByGroup(group), messageUS.getMessage());
mdao.create(messageEntity);
}
}
} else {
MessageUS message = new MessageUS(Constants.DECLINED_SEND_MESSAGE, messageUS.getMessage(),
messageUS.getLogin(), messageUS.getID());
message.setAccountCreationTime(adao.findByUsername(thisLogin).getTimestamp() + "");
synchronized (toClient) {
toClient.writeObject(message);
}
}
} catch (Exception e) {
MessageUS message = new MessageUS(Constants.SOMETHING_WENT_WRONG);
message.setReason("The message was not sent");
synchronized (toClient) {
toClient.writeObject(message);
}
}
}
/**
* Send photo to the particular chat.
*
* @param messageUS the message containing instruction and information
* required to send a photo: author, conversation id, and the byte[]
* (representing photo)
*/
private void sendPhoto(MessageUS messageUS) {
try {
if (onlinePeople.containsKey(thisLogin) && connectionInformation.containsKey(messageUS.getID())) {
System.out.println("got photo " + messageUS.getMessage() + " from " + thisLogin);
HashSet<String> peopleInConversation = connectionInformation.get(messageUS.getID());
peopleInConversation.forEach(e -> {
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
MessageUS newMessage = new MessageUS(Constants.RECEIVE_PHOTO, messageUS.getImage(),
messageUS.getLogin(), messageUS.getID());
newMessage.setTimeStamp(timeStamp);
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(newMessage);
} catch (IOException e1) {
}
}
});
} else {
synchronized (toClient) {
MessageUS message = new MessageUS(Constants.PHOTO_DECLINED);
message.setReason("Error! The photo was not sent");
toClient.writeObject(message);
}
}
} catch (Exception e) {
System.err.println("Something went wrong");
}
}
/**
* Sends public message to all online users.
*
* @param message the message containing instruction and required
* information to send a public message: author, message text
*/
private void publicMessage(MessageUS message) {
MessageUS publicMessage = new MessageUS(Constants.RECEIVE_PUBLIC_MESSAGE, message.getMessage(),
message.getLogin(), message.getID());
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
publicMessage.setTimeStamp(timeStamp);
onlinePeople.keySet().forEach(e -> {
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(publicMessage);
} catch (IOException e1) {
System.out.println("The message was not sent");
}
}
});
}
/**
* Send public photo.
*
* @param message the message
*/
private void sendPublicPhoto(MessageUS message) {
MessageUS publicPhoto = new MessageUS(Constants.RECEIVE_PUBLIC_PHOTO, message.getImage(), message.getLogin(),
message.getID());
Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
publicPhoto.setTimeStamp(timeStamp);
onlinePeople.keySet().forEach(e -> {
synchronized (onlinePeople.get(e)) {
try {
onlinePeople.get(e).writeObject(publicPhoto);
} catch (IOException e1) {
System.out.println("The message was not sent");
e1.printStackTrace();
}
}
});
}
/**
* Ends the particular chat by sending message containing chat end
* instruction, chat name and chat id.
*
* @param message the message containing instructions and required
* information to end the chat: chat/partner's name and conversation id.
*/
private void endChat(MessageUS message) {
HashSet<String> peopleInChat = connectionInformation.get(message.getID());
connectionInformation.remove(message.getID());
MessageUS newMessage = new MessageUS(Constants.CHAT_ENDED, message.getLogin(), message.getID());
try {
peopleInChat.forEach(e -> {
synchronized (connections.get(e)) {
connections.get(e).remove(message.getID());
}
synchronized (onlinePeople.get(e)) {
if (onlinePeople.containsKey(e) && !e.equals(thisLogin))
try {
onlinePeople.get(e).writeObject(newMessage);
} catch (IOException e1) {
System.err.println("The message was not sent...");
}
}
});
} catch (Exception e) {
System.err.println("Something went wrong...");
}
}
/**
* Ending connection.
*/
public synchronized void end() {
if (thisLogin != null)
try {
HashSet<String> myConnections = connections.get(thisLogin);
if (myConnections == null)
myConnections = new HashSet<>();
myConnections.forEach(e -> {
MessageUS sendBye = new MessageUS(Constants.CHAT_ENDED, thisLogin, e);
connectionInformation.get(e).forEach(q -> {
try {
onlinePeople.get(q).writeObject(sendBye);
connections.get(q).remove(e);
} catch (Exception e1) {
System.err.println("Could not send bye to " + q);
}
});
connectionInformation.remove(e);
});
connections.remove(thisLogin);
onlinePeople.remove(thisLogin);
listOfConnections.remove(this);
listIsChanged();
fromClient.close();
client.close();
} catch (Exception e) {
connections.remove(thisLogin);
onlinePeople.remove(thisLogin);
listOfConnections.remove(this);
listIsChanged();
try {
fromClient.close();
client.close();
} catch (IOException e1) {
}
System.out.println("catching..");
}
}
/**
* List is changed. Called when list of online users changes(due to logging
* in or logging out)
*/
private void listIsChanged() {
Set<String> idPeopleOnline = onlinePeople.keySet();
ArrayList<String> peopleOnline = new ArrayList<>(idPeopleOnline);
MessageUS messageToEverybody = new MessageUS(Constants.LIST_CHANGED, peopleOnline);
listOfConnections.forEach(x -> x.notifyAboutChanges(messageToEverybody));
}
/**
* Notifies users about changed list of online users by sending a message.
*
* @param toSend the message to send to the users, containing the list of
* online people
*/
private void notifyAboutChanges(MessageUS toSend) {
synchronized (toClient) {
try {
toClient.writeObject(toSend);
} catch (IOException e) {
System.err.println("Unable to send message to " + thisLogin);
}
}
}
/**
* Sets the up database.
*/
private void setUpDatabase() {
daoFactory = DAOFactory.getInstance();
this.adao = (AccountDAOImpl) daoFactory.getAccountDAO();
this.cdao = (ConversationDAOImpl) daoFactory.getConversationDAO();
this.gdao = daoFactory.getGroupDAOImpl();
this.gmdao = daoFactory.getGroupMemberDAOImpl();
this.mdao = (MessageDAOImpl) daoFactory.getMessageDAO();
this.pdao = daoFactory.getParticipantDAO();
}
} | 51,016 | 0.703632 | 0.701928 | 1,459 | 33.989033 | 28.047642 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.178204 | false | false | 2 |
1b12777ff404b20adc68ec162069e47514f996fd | 37,228,776,555,887 | 40cd4da5514eb920e6a6889e82590e48720c3d38 | /desktop/applis/apps/sys_apps/sys_apps_core/compos_core/src/main/java/code/vi/prot/impl/gui/events/WrMouseListenerPresRel.java | 197a7d301fa195692b79b54e1816ff074052a93a | []
| no_license | Cardman/projects | https://github.com/Cardman/projects | 02704237e81868f8cb614abb37468cebb4ef4b31 | 23a9477dd736795c3af10bccccb3cdfa10c8123c | refs/heads/master | 2023-08-17T11:27:41.999000 | 2023-08-15T07:09:28 | 2023-08-15T07:09:28 | 34,724,613 | 4 | 0 | null | false | 2020-10-13T08:08:38 | 2015-04-28T10:39:03 | 2020-10-12T21:02:20 | 2020-10-13T08:08:37 | 44,842 | 1 | 0 | 0 | Java | false | false | package code.vi.prot.impl.gui.events;
import code.gui.events.AbsMouseListenerPresRel;
import code.vi.prot.impl.gui.DefCtrlKeyState;
import code.vi.prot.impl.gui.DefMouseButtons;
import code.vi.prot.impl.gui.DefMouseLocation;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public final class WrMouseListenerPresRel extends MouseAdapter {
private final AbsMouseListenerPresRel mouseListener;
public WrMouseListenerPresRel(AbsMouseListenerPresRel _mouseListener) {
this.mouseListener = _mouseListener;
}
@Override
public void mousePressed(MouseEvent _e) {
mouseListener.mousePressed(new DefMouseLocation(_e),new DefCtrlKeyState(_e),new DefMouseButtons(_e));
}
@Override
public void mouseReleased(MouseEvent _e) {
mouseListener.mouseReleased(new DefMouseLocation(_e),new DefCtrlKeyState(_e),new DefMouseButtons(_e));
}
}
| UTF-8 | Java | 907 | java | WrMouseListenerPresRel.java | Java | []
| null | []
| package code.vi.prot.impl.gui.events;
import code.gui.events.AbsMouseListenerPresRel;
import code.vi.prot.impl.gui.DefCtrlKeyState;
import code.vi.prot.impl.gui.DefMouseButtons;
import code.vi.prot.impl.gui.DefMouseLocation;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public final class WrMouseListenerPresRel extends MouseAdapter {
private final AbsMouseListenerPresRel mouseListener;
public WrMouseListenerPresRel(AbsMouseListenerPresRel _mouseListener) {
this.mouseListener = _mouseListener;
}
@Override
public void mousePressed(MouseEvent _e) {
mouseListener.mousePressed(new DefMouseLocation(_e),new DefCtrlKeyState(_e),new DefMouseButtons(_e));
}
@Override
public void mouseReleased(MouseEvent _e) {
mouseListener.mouseReleased(new DefMouseLocation(_e),new DefCtrlKeyState(_e),new DefMouseButtons(_e));
}
}
| 907 | 0.76516 | 0.76516 | 28 | 31.392857 | 31.505486 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false | 2 |
47eedae772f9225edc5a6e7a1326ea4013eb979a | 28,449,863,429,223 | e179a1380fbd1933fea5513580d4ead84bf37f95 | /src/main/java/com/employee/service/EmployeeService.java | 936ca569c4222dffe3c4b7830fd9ba1cb58276df | []
| no_license | edwardKa/java-21-validator-exception-handler | https://github.com/edwardKa/java-21-validator-exception-handler | 29757081ac50c879d0757043d78150970ccfee97 | 547faeafe0fc5b34b21a0ee162f0e88f3f0fa0a6 | refs/heads/master | 2021-05-05T03:29:22.575000 | 2018-02-01T07:42:17 | 2018-02-01T07:42:17 | 119,799,434 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.employee.service;
import com.employee.model.Employee;
import java.util.List;
public interface EmployeeService {
List<Employee> getAll();
Employee getOne(Integer employeeId);
Employee save();
}
| UTF-8 | Java | 221 | java | EmployeeService.java | Java | []
| null | []
| package com.employee.service;
import com.employee.model.Employee;
import java.util.List;
public interface EmployeeService {
List<Employee> getAll();
Employee getOne(Integer employeeId);
Employee save();
}
| 221 | 0.742081 | 0.742081 | 12 | 17.416666 | 15.413513 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
20ed958153b90523d5e4a57e1d00e0d3900086b0 | 39,359,080,310,787 | 5bed7088e04c938d6a9f2e79a6ecec70284c124a | /src/main/java/com/lohika/kdibrov/core/web/pages/IndexLogin.java | 7c9c5a0a4f1d82f1ff57fd8fd8049f2443e14988 | []
| no_license | kdibrov/testing | https://github.com/kdibrov/testing | 5a6cfafbf71eb3ce3267e812f1d4d744ebf841b4 | 01756ede692b6986ecef6454f249a6b77cf347fb | refs/heads/master | 2016-08-06T15:05:10.293000 | 2015-04-21T22:29:28 | 2015-04-21T22:29:28 | 34,340,797 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lohika.kdibrov.core.web.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import com.lohika.kdibrov.core.web.WebPage;
import com.lohika.kdibrov.core.web.elements.Button;
import com.lohika.kdibrov.core.web.elements.Link;
import com.lohika.kdibrov.core.web.elements.TextInput;
public class IndexLogin extends WebPage<IndexLogin> {
private static final String PAGE_URL="http://localhost/phpbb/ucp.php?mode=login";
public IndexLogin(WebDriver driver) {
super(driver);
}
@Override
public IndexLogin load() {
driver.get(PAGE_URL);
return this; //test
}
@Override
public boolean isAvailable() {
return getUserNameInput().isAvailable() ||
getPasswordInput().isAvailable() ||
//getLoginButton().isAvailable() || // works, but I'm not sure how to handle it correctly
getAdminControlPanelLink().isAvailable();
}
public IndexLogin loginAsAdmin(String username, String password) {
load();
//getLoginModeLink().click();
getUserNameInput().inputText(username);
getPasswordInput().inputText(password);
getLoginButton().click();
return new IndexLogin(driver).waitUntillAvailable();
}
private TextInput getUserNameInput() {
return new TextInput(driver, By.id("username"));
}
private TextInput getPasswordInput() {
return new TextInput(driver, By.id("password"));
}
private Button getLoginButton() {
return new Button(driver, By.name("login"));
}
private Link getAdminControlPanelLink() {
return new Link(driver, By.xpath("//a[contains(@href,'./adm/')]"));
}
//private Link getLoginModeLink() {
// return new Link(driver, By.xpath("//a[contains(@href,'mode=login')]"));
//}
}
| UTF-8 | Java | 1,680 | java | IndexLogin.java | Java | []
| null | []
| package com.lohika.kdibrov.core.web.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import com.lohika.kdibrov.core.web.WebPage;
import com.lohika.kdibrov.core.web.elements.Button;
import com.lohika.kdibrov.core.web.elements.Link;
import com.lohika.kdibrov.core.web.elements.TextInput;
public class IndexLogin extends WebPage<IndexLogin> {
private static final String PAGE_URL="http://localhost/phpbb/ucp.php?mode=login";
public IndexLogin(WebDriver driver) {
super(driver);
}
@Override
public IndexLogin load() {
driver.get(PAGE_URL);
return this; //test
}
@Override
public boolean isAvailable() {
return getUserNameInput().isAvailable() ||
getPasswordInput().isAvailable() ||
//getLoginButton().isAvailable() || // works, but I'm not sure how to handle it correctly
getAdminControlPanelLink().isAvailable();
}
public IndexLogin loginAsAdmin(String username, String password) {
load();
//getLoginModeLink().click();
getUserNameInput().inputText(username);
getPasswordInput().inputText(password);
getLoginButton().click();
return new IndexLogin(driver).waitUntillAvailable();
}
private TextInput getUserNameInput() {
return new TextInput(driver, By.id("username"));
}
private TextInput getPasswordInput() {
return new TextInput(driver, By.id("password"));
}
private Button getLoginButton() {
return new Button(driver, By.name("login"));
}
private Link getAdminControlPanelLink() {
return new Link(driver, By.xpath("//a[contains(@href,'./adm/')]"));
}
//private Link getLoginModeLink() {
// return new Link(driver, By.xpath("//a[contains(@href,'mode=login')]"));
//}
}
| 1,680 | 0.723214 | 0.723214 | 61 | 26.52459 | 24.777439 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.655738 | false | false | 2 |
a12f7cd7dbd52bab15d0fb007b2f6a75234201d7 | 38,749,194,970,496 | d9c9055887ad4f3508fbcfedfec577f721fdab0e | /opentsp-user-service/src/main/java/com/navinfo/opentsp/user/service/sms/SmsSenderImpl.java | 98ff8e0e8b80d0b4ee9f5d9d40e41c5d9ef457ce | []
| no_license | wujiangbo45/user_center | https://github.com/wujiangbo45/user_center | 35d5fdc39bbd4bffbb2cc4edfed2706cd4f7f4d9 | 1ef795771bbacc893759f5c40d9149e64da59e64 | refs/heads/master | 2021-08-15T20:05:56.861000 | 2017-11-18T07:01:10 | 2017-11-18T07:01:10 | 111,183,343 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.navinfo.opentsp.user.service.sms;
import com.navinfo.opentsp.user.common.util.json.JsonUtil;
import com.navinfo.opentsp.user.dal.dao.SendSmsLogDao;
import com.navinfo.opentsp.user.dal.entity.SendSmsLogEntity;
import com.navinfo.opentsp.user.service.security.EncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
* @author wupeng
* @version 1.0
* @date 2015-10-10
* @modify
* @copyright Navi Tsp
*/
@Service
@Profile("!dev")
public class SmsSenderImpl implements SmsSender {
private static final Logger logger = LoggerFactory.getLogger(SmsSenderImpl.class);
@Value("${opentsp.sms.url}")
private String sendSmsUrl;
@Value("${opentsp.sms.product.id}")
private String productId;
@Value("${opentsp.sms.product.key}")
private String key;
@Autowired
private SendSmsLogDao smsLogDao;
/**
* 签名的参数名
*/
private static final String SIGN_PARAM = "user_sign";
/**
* 渠道的参数名
*/
private static final String CHANNEL_PARAM = "sendposition";
@Autowired
private RestTemplate restTemplate;
@Override
public void sendSms(SendSmsLogEntity entity) {
this.sendSms(new String[]{String.valueOf(entity.getMobile())}, entity);
}
@Override
public void sendSms(String[] phones, SendSmsLogEntity entity) {
if(phones == null || phones.length == 0)
return;
if (StringUtils.isEmpty(entity.getClientIp())) {
throw new RuntimeException("IP can not be null !");
}
StringBuilder ph = new StringBuilder();
for(String phone : phones) {
ph.append(",").append(phone);
}
ph.deleteCharAt(0);
try {
Map<String, Object> map = new HashMap<>();
map.put("method","sendIntegralWall");//to specify execute which method in action
map.put(CHANNEL_PARAM, productId);
map.put("phone", ph.toString());
map.put("title", encodeChinese("短信发送"));
map.put("content", encodeChinese(entity.getContent()));
map.put("ip",entity.getClientIp());
map.put("timestamp", System.currentTimeMillis());
map.put(SIGN_PARAM, this.sign(map));
StringBuilder sb = new StringBuilder(sendSmsUrl).append("?");
for(Map.Entry<String, Object> entry : map.entrySet()){
sb.append(entry.getKey()).append("=")
.append(entry.getValue() == null ? "" : String.valueOf(entry.getValue()))
.append("&");
}
sb.deleteCharAt(sb.length() - 1);// delete last char '&'
String url = sb.toString();
logger.debug("send message url : " + url);
String response = restTemplate.getForObject(url, String.class);
logger.info("send message, response : " + response);
entity.setResponse(response);
smsLogDao.save(entity);
Map<String, String> result = JsonUtil.fromJson(response, Map.class);
if(!"200".equals(result.get("code"))){
throw new RuntimeException("send sms error ! response : " + response);
}
} finally {
}
}
private String encodeChinese(String message){
try {
return URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
return message;
}
/**
* generate sign info, need 3 steps
* 1, sort all param names by nature order (exclude SIGN_PARAM)
* 2, spell params and values with &. eg. name=admin&password=mhy
* 3, hmac-sha1 encrypt with specified key
*
*
* @param params
* @return
*/
public String sign(Map<String, Object> params){
if(params == null || params.size() == 0){
return null;
}
Object channel = String.valueOf(params.get(CHANNEL_PARAM));
if(channel == null)
return null;
params.remove(SIGN_PARAM);
List<String> paramNames = new ArrayList<>(params.keySet());
Collections.sort(paramNames);//step 1,sort param names by nature order
StringBuilder sb = new StringBuilder();
for(String paramName : paramNames){//step 2
Object obj = params.get(paramName);
sb.append(paramName).append("=").append(obj == null ? "" : String.valueOf(obj)).append("&");
}
if(sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return EncryptUtil.HMAC_SHA1(sb.toString(), key);//step 3
}
public static void main(String[] args) {
SmsSenderImpl smsSender = new SmsSenderImpl();
smsSender.sendSmsUrl = "https://wedrive.mapbar.com/sms/send.do";
smsSender.productId = "opentsp_user";
smsSender.key = "f67919a6edf94945a3845ce73bc9b12a";
smsSender.restTemplate = new RestTemplate();
SendSmsLogEntity entity = new SendSmsLogEntity();
entity.setMobile(15311612804L);
entity.setResponse("");
entity.setClientIp("10.10.24.31");
entity.setContent("1231sdfdsf中文测试rret");
smsSender.sendSms(entity);
}
}
| UTF-8 | Java | 5,693 | java | SmsSenderImpl.java | Java | [
{
"context": "et.URLEncoder;\nimport java.util.*;\n\n/**\n * @author wupeng\n * @version 1.0\n * @date 2015-10-10\n * @modify\n *",
"end": 778,
"score": 0.9990721344947815,
"start": 772,
"tag": "USERNAME",
"value": "wupeng"
},
{
"context": "n 1.0\n * @date 2015-10-10\n * @modify\n * @copyright Navi Tsp\n */\n@Service\n@Profile(\"!dev\")\npublic class SmsSen",
"end": 848,
"score": 0.9938206672668457,
"start": 840,
"tag": "NAME",
"value": "Navi Tsp"
},
{
"context": "params and values with &. eg. name=admin&password=mhy\n * 3, hmac-sha1 encrypt with specified key\n ",
"end": 4093,
"score": 0.9992015361785889,
"start": 4090,
"tag": "PASSWORD",
"value": "mhy"
},
{
"context": "ductId = \"opentsp_user\";\n smsSender.key = \"f67919a6edf94945a3845ce73bc9b12a\";\n smsSender.restTemplate = new RestTempla",
"end": 5330,
"score": 0.9997411370277405,
"start": 5298,
"tag": "KEY",
"value": "f67919a6edf94945a3845ce73bc9b12a"
}
]
| null | []
| package com.navinfo.opentsp.user.service.sms;
import com.navinfo.opentsp.user.common.util.json.JsonUtil;
import com.navinfo.opentsp.user.dal.dao.SendSmsLogDao;
import com.navinfo.opentsp.user.dal.entity.SendSmsLogEntity;
import com.navinfo.opentsp.user.service.security.EncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
* @author wupeng
* @version 1.0
* @date 2015-10-10
* @modify
* @copyright <NAME>
*/
@Service
@Profile("!dev")
public class SmsSenderImpl implements SmsSender {
private static final Logger logger = LoggerFactory.getLogger(SmsSenderImpl.class);
@Value("${opentsp.sms.url}")
private String sendSmsUrl;
@Value("${opentsp.sms.product.id}")
private String productId;
@Value("${opentsp.sms.product.key}")
private String key;
@Autowired
private SendSmsLogDao smsLogDao;
/**
* 签名的参数名
*/
private static final String SIGN_PARAM = "user_sign";
/**
* 渠道的参数名
*/
private static final String CHANNEL_PARAM = "sendposition";
@Autowired
private RestTemplate restTemplate;
@Override
public void sendSms(SendSmsLogEntity entity) {
this.sendSms(new String[]{String.valueOf(entity.getMobile())}, entity);
}
@Override
public void sendSms(String[] phones, SendSmsLogEntity entity) {
if(phones == null || phones.length == 0)
return;
if (StringUtils.isEmpty(entity.getClientIp())) {
throw new RuntimeException("IP can not be null !");
}
StringBuilder ph = new StringBuilder();
for(String phone : phones) {
ph.append(",").append(phone);
}
ph.deleteCharAt(0);
try {
Map<String, Object> map = new HashMap<>();
map.put("method","sendIntegralWall");//to specify execute which method in action
map.put(CHANNEL_PARAM, productId);
map.put("phone", ph.toString());
map.put("title", encodeChinese("短信发送"));
map.put("content", encodeChinese(entity.getContent()));
map.put("ip",entity.getClientIp());
map.put("timestamp", System.currentTimeMillis());
map.put(SIGN_PARAM, this.sign(map));
StringBuilder sb = new StringBuilder(sendSmsUrl).append("?");
for(Map.Entry<String, Object> entry : map.entrySet()){
sb.append(entry.getKey()).append("=")
.append(entry.getValue() == null ? "" : String.valueOf(entry.getValue()))
.append("&");
}
sb.deleteCharAt(sb.length() - 1);// delete last char '&'
String url = sb.toString();
logger.debug("send message url : " + url);
String response = restTemplate.getForObject(url, String.class);
logger.info("send message, response : " + response);
entity.setResponse(response);
smsLogDao.save(entity);
Map<String, String> result = JsonUtil.fromJson(response, Map.class);
if(!"200".equals(result.get("code"))){
throw new RuntimeException("send sms error ! response : " + response);
}
} finally {
}
}
private String encodeChinese(String message){
try {
return URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
return message;
}
/**
* generate sign info, need 3 steps
* 1, sort all param names by nature order (exclude SIGN_PARAM)
* 2, spell params and values with &. eg. name=admin&password=mhy
* 3, hmac-sha1 encrypt with specified key
*
*
* @param params
* @return
*/
public String sign(Map<String, Object> params){
if(params == null || params.size() == 0){
return null;
}
Object channel = String.valueOf(params.get(CHANNEL_PARAM));
if(channel == null)
return null;
params.remove(SIGN_PARAM);
List<String> paramNames = new ArrayList<>(params.keySet());
Collections.sort(paramNames);//step 1,sort param names by nature order
StringBuilder sb = new StringBuilder();
for(String paramName : paramNames){//step 2
Object obj = params.get(paramName);
sb.append(paramName).append("=").append(obj == null ? "" : String.valueOf(obj)).append("&");
}
if(sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
return EncryptUtil.HMAC_SHA1(sb.toString(), key);//step 3
}
public static void main(String[] args) {
SmsSenderImpl smsSender = new SmsSenderImpl();
smsSender.sendSmsUrl = "https://wedrive.mapbar.com/sms/send.do";
smsSender.productId = "opentsp_user";
smsSender.key = "f67919a6edf94945a3845ce73bc9b12a";
smsSender.restTemplate = new RestTemplate();
SendSmsLogEntity entity = new SendSmsLogEntity();
entity.setMobile(15311612804L);
entity.setResponse("");
entity.setClientIp("10.10.24.31");
entity.setContent("1231sdfdsf中文测试rret");
smsSender.sendSms(entity);
}
}
| 5,691 | 0.618787 | 0.605696 | 173 | 31.6763 | 25.944569 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606936 | false | false | 2 |
116ccd81662cc8a7812193efc9edf3bc0909ce33 | 1,932,735,353,859 | 2fca12b8b04eb848b23caf2d909137a67ebecaf1 | /project/AndroidLearn/app/src/main/java/com/example/yjq/androidlearn/servicce/MyRemoveService.java | a14cd92fe2e240ba917ecca08ce7c814755ad4bb | []
| no_license | yangjg/mycode | https://github.com/yangjg/mycode | 75b676d580444b42671ad3e41069a1de1c51e1fe | c432622f71a93483adeb880aa3a3651438c54f3e | refs/heads/master | 2020-05-28T05:00:58.327000 | 2018-06-06T06:30:30 | 2018-06-06T06:30:30 | 41,576,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.yjq.androidlearn.servicce;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Random;
/**
* Created by yjq on 2016/4/20.
*/
public class MyRemoveService extends Service {
private static final String TAG = "MyRemoveService";
final Random generator = new Random();
final Messenger messenger = new Messenger(new MsgHandle());
public MyRemoveService(){
// super("MyService");
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
super.onCreate();
}
/*
@Override
protected void onHandleIntent(Intent intent) {
Bundle data = intent.getExtras();
if(null!=data){
int count = data.getInt("count");
Log.e(TAG,String.valueOf(count));
}
Log.e(TAG, "onHandleIntent finish");
// intent.getExtras();
}*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle data = intent.getExtras();
if(null!=data){
int count = data.getInt("count");
Log.e(TAG,String.valueOf(count));
}
// Log.e(TAG, "onHandleIntent finish");
Log.e(TAG, "onStartCommand:" + startId);
Log.e(TAG, String.valueOf( android.os.Process.myPid()));
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, "onStart");
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind");
Log.e(TAG, "Pid:"+String.valueOf( android.os.Process.myPid()));
return messenger.getBinder();
}
public int getRandomNumber(){
return generator.nextInt(100);
}
public final static int HELLO_WORLD=1;
class MsgHandle extends Handler{
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case HELLO_WORLD:
try {
Thread.currentThread().sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e(TAG,"handleMessage time=="+ System.currentTimeMillis());
Log.e(TAG,"hello world");
Log.e(TAG, "Pid:"+String.valueOf(android.os.Process.myPid()));
Messenger messenger = msg.replyTo;
Message newMsg =Message.obtain(null,2,0,0);
try {
messenger.send(newMsg);
} catch (RemoteException e) {
e.printStackTrace();
Log.e(TAG,e.getMessage());
}
break;
default:super.handleMessage(msg);
}
}
}
}
| UTF-8 | Java | 3,296 | java | MyRemoveService.java | Java | [
{
"context": "l.Log;\n\nimport java.util.Random;\n/**\n * Created by yjq on 2016/4/20.\n */\npublic class MyRemoveService ex",
"end": 420,
"score": 0.9995818734169006,
"start": 417,
"tag": "USERNAME",
"value": "yjq"
}
]
| null | []
| package com.example.yjq.androidlearn.servicce;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Random;
/**
* Created by yjq on 2016/4/20.
*/
public class MyRemoveService extends Service {
private static final String TAG = "MyRemoveService";
final Random generator = new Random();
final Messenger messenger = new Messenger(new MsgHandle());
public MyRemoveService(){
// super("MyService");
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
super.onCreate();
}
/*
@Override
protected void onHandleIntent(Intent intent) {
Bundle data = intent.getExtras();
if(null!=data){
int count = data.getInt("count");
Log.e(TAG,String.valueOf(count));
}
Log.e(TAG, "onHandleIntent finish");
// intent.getExtras();
}*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle data = intent.getExtras();
if(null!=data){
int count = data.getInt("count");
Log.e(TAG,String.valueOf(count));
}
// Log.e(TAG, "onHandleIntent finish");
Log.e(TAG, "onStartCommand:" + startId);
Log.e(TAG, String.valueOf( android.os.Process.myPid()));
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, "onStart");
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind");
Log.e(TAG, "Pid:"+String.valueOf( android.os.Process.myPid()));
return messenger.getBinder();
}
public int getRandomNumber(){
return generator.nextInt(100);
}
public final static int HELLO_WORLD=1;
class MsgHandle extends Handler{
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case HELLO_WORLD:
try {
Thread.currentThread().sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e(TAG,"handleMessage time=="+ System.currentTimeMillis());
Log.e(TAG,"hello world");
Log.e(TAG, "Pid:"+String.valueOf(android.os.Process.myPid()));
Messenger messenger = msg.replyTo;
Message newMsg =Message.obtain(null,2,0,0);
try {
messenger.send(newMsg);
} catch (RemoteException e) {
e.printStackTrace();
Log.e(TAG,e.getMessage());
}
break;
default:super.handleMessage(msg);
}
}
}
}
| 3,296 | 0.561286 | 0.556129 | 116 | 27.413794 | 20.709013 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 2 |
3746dc414a4f63f78785749f5eccb3f25694bfea | 39,350,490,393,815 | 773879c32acc043e882f156b5ced3a9020d5fabf | /app/src/main/java/com/ids/madesubmission3/ui/main/MainNavigator.java | d8e39155730d98689684895e5500c3e97a657993 | []
| no_license | muhajirshiddiqaf/madesubmission3 | https://github.com/muhajirshiddiqaf/madesubmission3 | 9f54824d42ddba52cd5c6b32ff805db73adef66a | e8db682d27a2af832f64172533335cb61f6c04ed | refs/heads/master | 2020-11-28T22:26:14.697000 | 2019-12-24T12:18:26 | 2019-12-24T12:18:26 | 229,936,417 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ids.madesubmission3.ui.main;
import com.ids.madesubmission3.base.BaseNavigator;
public interface MainNavigator extends BaseNavigator {
}
| UTF-8 | Java | 152 | java | MainNavigator.java | Java | []
| null | []
| package com.ids.madesubmission3.ui.main;
import com.ids.madesubmission3.base.BaseNavigator;
public interface MainNavigator extends BaseNavigator {
}
| 152 | 0.828947 | 0.815789 | 7 | 20.714285 | 23.944664 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 2 |
04780e3ec373afe35fd4050b81eb77a4c2b7029f | 36,361,193,170,607 | cfa68c493f7be3b5391482729f25fe1176de0974 | /flink-be-god/flink-operator/src/main/java/window/watermark/CustomPunctuatedWatermarkAssignerDemo.java | b683c08c97e70f3ff199d4576d745ab822d4010d | []
| no_license | Ljc-xiaohu/flink-demo | https://github.com/Ljc-xiaohu/flink-demo | 4636d5bd221f94b05a8f2ab360a733ac57fd0b9b | 1784440dd80d89b8016ca53f87be809983f5de04 | refs/heads/main | 2023-01-05T00:51:10.486000 | 2020-11-05T14:21:29 | 2020-11-05T14:21:29 | 305,075,466 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package window.watermark;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.tuple.Tuple3;
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.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.runtime.operators.util.AssignerWithPunctuatedWatermarksAdapter;
import window.datasource.SourceGenerator;
import window.function.ApplyWindowFunction;
import javax.annotation.Nullable;
/**
* 根据元素生成水印,
*/
public class CustomPunctuatedWatermarkAssignerDemo {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
DataStream<Tuple3<String, Integer, Long>> src =
env.addSource(new SourceGenerator()).setParallelism(1)
.assignTimestampsAndWatermarks(WatermarkStrategy.forGenerator(
new AssignerWithPunctuatedWatermarksAdapter.Strategy<>(
new AssignerWithPunctuatedWatermarks<Tuple3<String, Integer, Long>>() {
@Nullable
@Override
public Watermark checkAndGetNextWatermark(Tuple3<String, Integer, Long> lastElement, long extractedTimestamp) {
return new Watermark(lastElement.f2>extractedTimestamp?lastElement.f2:extractedTimestamp);
}
@Override
public long extractTimestamp(Tuple3<String, Integer, Long> element, long previousElementTimestamp) {
return element.f2;
}
})))
/*.assignTimestampsAndWatermarks(new AssignerWithPunctuatedWatermarks<Tuple3<String, Integer, Long>>() {
@Nullable
@Override
public Watermark checkAndGetNextWatermark(Tuple3<String, Integer, Long> lastElement, long extractedTimestamp) {
return new Watermark(lastElement.f2>extractedTimestamp?lastElement.f2:extractedTimestamp);
}
@Override
public long extractTimestamp(Tuple3<String, Integer, Long> element, long previousElementTimestamp) {
return element.f2;
}
})*/
;
src.keyBy(t->t.f0).timeWindow(Time.seconds(5)).apply(new ApplyWindowFunction()).print();
env.execute();
}
}
| UTF-8 | Java | 3,058 | java | CustomPunctuatedWatermarkAssignerDemo.java | Java | []
| null | []
| package window.watermark;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.tuple.Tuple3;
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.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.runtime.operators.util.AssignerWithPunctuatedWatermarksAdapter;
import window.datasource.SourceGenerator;
import window.function.ApplyWindowFunction;
import javax.annotation.Nullable;
/**
* 根据元素生成水印,
*/
public class CustomPunctuatedWatermarkAssignerDemo {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
DataStream<Tuple3<String, Integer, Long>> src =
env.addSource(new SourceGenerator()).setParallelism(1)
.assignTimestampsAndWatermarks(WatermarkStrategy.forGenerator(
new AssignerWithPunctuatedWatermarksAdapter.Strategy<>(
new AssignerWithPunctuatedWatermarks<Tuple3<String, Integer, Long>>() {
@Nullable
@Override
public Watermark checkAndGetNextWatermark(Tuple3<String, Integer, Long> lastElement, long extractedTimestamp) {
return new Watermark(lastElement.f2>extractedTimestamp?lastElement.f2:extractedTimestamp);
}
@Override
public long extractTimestamp(Tuple3<String, Integer, Long> element, long previousElementTimestamp) {
return element.f2;
}
})))
/*.assignTimestampsAndWatermarks(new AssignerWithPunctuatedWatermarks<Tuple3<String, Integer, Long>>() {
@Nullable
@Override
public Watermark checkAndGetNextWatermark(Tuple3<String, Integer, Long> lastElement, long extractedTimestamp) {
return new Watermark(lastElement.f2>extractedTimestamp?lastElement.f2:extractedTimestamp);
}
@Override
public long extractTimestamp(Tuple3<String, Integer, Long> element, long previousElementTimestamp) {
return element.f2;
}
})*/
;
src.keyBy(t->t.f0).timeWindow(Time.seconds(5)).apply(new ApplyWindowFunction()).print();
env.execute();
}
}
| 3,058 | 0.646053 | 0.640461 | 57 | 52.333332 | 39.438309 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719298 | false | false | 2 |
85a75e88efd03e02c6f6fb96aef3d18f637f1d01 | 35,802,847,426,216 | 97965409f182f319da44ee599800dcb0a8778266 | /Lista2/src/Questao_10/AppQuadrado.java | 798dafde6bf7acc8ce6620caca6f513064ceb080 | []
| no_license | FabricioLinhares/exercicios-java-poo | https://github.com/FabricioLinhares/exercicios-java-poo | 4a67b716ec0af8957dca2d48fd68e079a6a6954f | 29937bd309833928940ce86e5407a0c9e715b1ce | refs/heads/main | 2023-01-21T04:16:34.555000 | 2020-12-04T17:17:01 | 2020-12-04T17:17:01 | 314,323,526 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Questao_10;
public class AppQuadrado {
public static void main(String[] args) {
Quadrado[] quadrado = new Quadrado[3];
quadrado[0] = new Quadrado();
quadrado[1] = new Quadrado();
quadrado[2] = new Quadrado();
quadrado[0].setLado(3.5);
quadrado[1].setLado(4.6);
quadrado[2].setLado(2.4);
byte maiorAreaId=0, menorPerimetroId=0;
for(byte i=0; i < 3; i++) {
System.out.println("Lado do Quadrado " + i + ": " + quadrado[i].getLado());
if (quadrado[i].calcularArea() > quadrado[maiorAreaId].calcularArea())
maiorAreaId = i;
if (quadrado[i].calcularPerimetro() < quadrado[menorPerimetroId].calcularPerimetro())
menorPerimetroId = i;
}
System.out.println("\nQuadro com maior área: " + maiorAreaId);
System.out.println("Quadro com menor perímetro: " + menorPerimetroId);
}
}
| UTF-8 | Java | 955 | java | AppQuadrado.java | Java | []
| null | []
| package Questao_10;
public class AppQuadrado {
public static void main(String[] args) {
Quadrado[] quadrado = new Quadrado[3];
quadrado[0] = new Quadrado();
quadrado[1] = new Quadrado();
quadrado[2] = new Quadrado();
quadrado[0].setLado(3.5);
quadrado[1].setLado(4.6);
quadrado[2].setLado(2.4);
byte maiorAreaId=0, menorPerimetroId=0;
for(byte i=0; i < 3; i++) {
System.out.println("Lado do Quadrado " + i + ": " + quadrado[i].getLado());
if (quadrado[i].calcularArea() > quadrado[maiorAreaId].calcularArea())
maiorAreaId = i;
if (quadrado[i].calcularPerimetro() < quadrado[menorPerimetroId].calcularPerimetro())
menorPerimetroId = i;
}
System.out.println("\nQuadro com maior área: " + maiorAreaId);
System.out.println("Quadro com menor perímetro: " + menorPerimetroId);
}
}
| 955 | 0.582371 | 0.562434 | 28 | 33.035713 | 28.363058 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607143 | false | false | 2 |
eef8f659985f657dfb4484cc467bfb6cac7cf47d | 38,938,173,526,934 | c4f24e5b099e729d85c7189638d0c8c80184f55b | /WebTourfirm/src/main/java/com/softserve/dao/impl/BaseDaoImpl.java | 8e220f6d7fd8bde04e300c712efe44af7b128ce4 | []
| no_license | luckyvch/tourfirm | https://github.com/luckyvch/tourfirm | d8603163e1d5be59768ba909cdc2a7ebffb1ee2c | f82ed07f2dd98226a368b0472d9fc20420dd1197 | refs/heads/master | 2020-06-02T20:05:15.199000 | 2015-09-03T17:16:29 | 2015-09-03T17:16:29 | 40,672,522 | 0 | 0 | null | false | 2015-08-17T11:19:13 | 2015-08-13T17:31:16 | 2015-08-14T15:21:15 | 2015-08-17T11:19:13 | 0 | 0 | 0 | 0 | Java | null | null | package com.softserve.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.softserve.dao.BaseDao;
@Repository
public class BaseDaoImpl<E> implements BaseDao<E> {
@PersistenceContext(unitName = "primary")
private EntityManager em;
private Class<E> entityClass;
private BaseDaoImpl() {
}
public BaseDaoImpl(Class<E> entityClass) {
this.entityClass = entityClass;
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public void insert(E e) {
em.persist(e);
}
public <T> E find(T id) {
return em.find(entityClass, id);
}
public void update(E e) {
em.merge(e);
}
@SuppressWarnings("unchecked")
public List<E> getAll() {
return em.createQuery("from " + entityClass.getSimpleName())
.getResultList();
}
public void deleteEntity(E e) {
em.remove(em.contains(e)? e : em.merge(e));
}
}
| UTF-8 | Java | 1,075 | java | BaseDaoImpl.java | Java | []
| null | []
| package com.softserve.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.softserve.dao.BaseDao;
@Repository
public class BaseDaoImpl<E> implements BaseDao<E> {
@PersistenceContext(unitName = "primary")
private EntityManager em;
private Class<E> entityClass;
private BaseDaoImpl() {
}
public BaseDaoImpl(Class<E> entityClass) {
this.entityClass = entityClass;
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public void insert(E e) {
em.persist(e);
}
public <T> E find(T id) {
return em.find(entityClass, id);
}
public void update(E e) {
em.merge(e);
}
@SuppressWarnings("unchecked")
public List<E> getAll() {
return em.createQuery("from " + entityClass.getSimpleName())
.getResultList();
}
public void deleteEntity(E e) {
em.remove(em.contains(e)? e : em.merge(e));
}
}
| 1,075 | 0.72093 | 0.72093 | 59 | 17.220339 | 18.405109 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.016949 | false | false | 2 |
fff4ee3376b924f46932d8b485fcb880506ba38f | 38,869,454,053,032 | 16ecaf5a34d5f5e632ac9cdea4ac8c2be1ec24dc | /MovyparkCordoba_v5.13_apkpure.com_source_from_JADX/sources/com/google/android/gms/internal/zzyl.java | f69243238719e28d8fecb0c8fd779aa3041b7fa5 | []
| no_license | turbo-funicular/com.movypark.cordoba | https://github.com/turbo-funicular/com.movypark.cordoba | 3eca439eb0a14339c7f74e7ce8b3b3b50e08f7b5 | 320eee3a676969880c1a280419f2a26f87d23ce4 | refs/heads/master | 2020-08-09T23:57:23.309000 | 2019-10-10T20:06:48 | 2019-10-10T20:06:48 | 214,202,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.internal;
public final class zzyl {
/* access modifiers changed from: private */
public boolean zzclr;
/* access modifiers changed from: private */
public boolean zzcls;
/* access modifiers changed from: private */
public boolean zzclt;
/* access modifiers changed from: private */
public boolean zzclu;
/* access modifiers changed from: private */
public boolean zzclv;
public final zzyl zzn(boolean z) {
this.zzclr = z;
return this;
}
public final zzyl zzo(boolean z) {
this.zzcls = z;
return this;
}
public final zzyl zzp(boolean z) {
this.zzclt = z;
return this;
}
public final zzyl zzq(boolean z) {
this.zzclu = z;
return this;
}
public final zzyl zzr(boolean z) {
this.zzclv = true;
return this;
}
}
| UTF-8 | Java | 903 | java | zzyl.java | Java | []
| null | []
| package com.google.android.gms.internal;
public final class zzyl {
/* access modifiers changed from: private */
public boolean zzclr;
/* access modifiers changed from: private */
public boolean zzcls;
/* access modifiers changed from: private */
public boolean zzclt;
/* access modifiers changed from: private */
public boolean zzclu;
/* access modifiers changed from: private */
public boolean zzclv;
public final zzyl zzn(boolean z) {
this.zzclr = z;
return this;
}
public final zzyl zzo(boolean z) {
this.zzcls = z;
return this;
}
public final zzyl zzp(boolean z) {
this.zzclt = z;
return this;
}
public final zzyl zzq(boolean z) {
this.zzclu = z;
return this;
}
public final zzyl zzr(boolean z) {
this.zzclv = true;
return this;
}
}
| 903 | 0.600221 | 0.600221 | 39 | 22.153847 | 15.906035 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410256 | false | false | 2 |
92471b194d2b8cbbed25e00013cb290cedbfd1ef | 38,869,454,051,032 | aa6ecf8c87c5bdca623cf62ea85ef030de2d6a42 | /Prototype Design Pattern/SapientConsultant/src/main/java/Company/SapientConsultant/CompanyFactory.java | 134a36cc6a2cfa7a36411ee0ec0259020aa9c16f | []
| no_license | aporwal2801/DesignPattern_PPt | https://github.com/aporwal2801/DesignPattern_PPt | f443670f9343c377fa35ffc0b591311d58829b39 | 01c65ec9670834967fc8b5acb282b973563161bb | refs/heads/master | 2021-01-12T07:26:31.673000 | 2016-12-21T12:24:44 | 2016-12-21T12:24:44 | 76,960,680 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Company.SapientConsultant;
public class CompanyFactory extends Prototype {
private static java.util.Map<String , Prototype> employeePrototype = new java.util.HashMap<String , Prototype>();
static {
employeePrototype.put("Employee", new Employee());
employeePrototype.put("Department", new Department(1001, "Sapient"));
}
public static Prototype getPrototype(String type){
Prototype prototype = employeePrototype.get(type);
if(prototype != null){
try {
return (Prototype)prototype.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public static String registerEmployee(int id, String name, String jobType){
Employee employeeType = (Employee)getPrototype("Employee");
Department deptType = (Department)getPrototype("Department");
if(employeeType !=null){
employeeType.setEmpId(id);
employeeType.setEmpName(name);
employeeType.setType(jobType);
employeeType.setDept(deptType);
return employeeType.toString();
}
return null;
}
}
| UTF-8 | Java | 1,156 | java | CompanyFactory.java | Java | []
| null | []
| package Company.SapientConsultant;
public class CompanyFactory extends Prototype {
private static java.util.Map<String , Prototype> employeePrototype = new java.util.HashMap<String , Prototype>();
static {
employeePrototype.put("Employee", new Employee());
employeePrototype.put("Department", new Department(1001, "Sapient"));
}
public static Prototype getPrototype(String type){
Prototype prototype = employeePrototype.get(type);
if(prototype != null){
try {
return (Prototype)prototype.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public static String registerEmployee(int id, String name, String jobType){
Employee employeeType = (Employee)getPrototype("Employee");
Department deptType = (Department)getPrototype("Department");
if(employeeType !=null){
employeeType.setEmpId(id);
employeeType.setEmpName(name);
employeeType.setType(jobType);
employeeType.setDept(deptType);
return employeeType.toString();
}
return null;
}
}
| 1,156 | 0.685121 | 0.681661 | 45 | 23.688889 | 26.114128 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.511111 | false | false | 2 |
a469a6e04726852d94dda9b7309d8bacd4dfc92b | 15,590,731,323,101 | 197dbb2d251500ecd8ba57715ce70f9489b6ec62 | /src/voogasalad_GucciGames/gameEngine/groovyEngine/GroovyCustomEvent.java | b73d0ad4a8f5c233f0362196b02c78372502ddbe | [
"MIT"
]
| permissive | TedYav/GucciGames | https://github.com/TedYav/GucciGames | a93dfd66a748541f16d63d299d906127d824bb15 | e3595750ef6a7ac5e2d3a3cf66adc4275348185b | refs/heads/master | 2020-07-21T02:03:31.302000 | 2017-01-04T18:13:33 | 2017-01-04T18:13:33 | 73,740,195 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package voogasalad_GucciGames.gameEngine.groovyEngine;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class GroovyCustomEvent extends AGroovyCustomObject {
private static String BUNDLE_STRING = "resources.groovy.groovyStringsEvents";
private static String IMPORT_FILE = "./resources/groovy/events.txt";
private String myGroovyString;
public GroovyCustomEvent(String name, String request, String action) {
super(name);
// TODO Auto-generated constructor stub
String imports = getImports();
StringBuilder groovy = new StringBuilder();
groovy.append(imports);
this.myGroovyString = String.format(groovy.toString(), name, name, name, request, action);
}
@Override
public String getGroovyString() {
// TODO Auto-generated method stub
return myGroovyString;
}
private String getImports() {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(this.getClass().getClassLoader().getResource(IMPORT_FILE).getFile()));
br.lines().forEach(line -> {
sb.append(line + "\n");
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
/*
* public static void main(String[] a){ new
* GroovyCustomEvent("","request","action"); }
*/
}
| UTF-8 | Java | 1,372 | java | GroovyCustomEvent.java | Java | []
| null | []
| package voogasalad_GucciGames.gameEngine.groovyEngine;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class GroovyCustomEvent extends AGroovyCustomObject {
private static String BUNDLE_STRING = "resources.groovy.groovyStringsEvents";
private static String IMPORT_FILE = "./resources/groovy/events.txt";
private String myGroovyString;
public GroovyCustomEvent(String name, String request, String action) {
super(name);
// TODO Auto-generated constructor stub
String imports = getImports();
StringBuilder groovy = new StringBuilder();
groovy.append(imports);
this.myGroovyString = String.format(groovy.toString(), name, name, name, request, action);
}
@Override
public String getGroovyString() {
// TODO Auto-generated method stub
return myGroovyString;
}
private String getImports() {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(this.getClass().getClassLoader().getResource(IMPORT_FILE).getFile()));
br.lines().forEach(line -> {
sb.append(line + "\n");
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
/*
* public static void main(String[] a){ new
* GroovyCustomEvent("","request","action"); }
*/
}
| 1,372 | 0.725947 | 0.725947 | 49 | 27 | 24.591354 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.959184 | false | false | 13 |
53206547968da6784449421db3ca4618a54b6d35 | 23,330,262,358,013 | de348906cc560bef96ff97f1e7268a7b18b37fb7 | /src/main/java/gkfire/hibernate/CustomHibernateException.java | 3e0fa6f2d2609b6edbfdc4144d69b6696b4d6454 | []
| no_license | DarkusNightstalker/projects_core | https://github.com/DarkusNightstalker/projects_core | 2d4b56157de6232bd659553df0b8b1a8d278f5e9 | 4e25b4a7eae1f79af6520335b7693a5705d27683 | refs/heads/master | 2020-07-14T01:35:05.486000 | 2017-08-28T15:31:32 | 2017-08-28T15:31:32 | 94,295,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 gkfire.hibernate;
import org.hibernate.HibernateException;
/**
*
* @author Darkus Nightmare
*/
public class CustomHibernateException extends HibernateException {
public CustomHibernateException(String message) {
super(message);
}
}
| UTF-8 | Java | 468 | java | CustomHibernateException.java | Java | [
{
"context": "bernate.HibernateException;\r\n\r\n/**\r\n *\r\n * @author Darkus Nightmare\r\n */\r\npublic class CustomHibernateException exten",
"end": 299,
"score": 0.9998828768730164,
"start": 283,
"tag": "NAME",
"value": "Darkus Nightmare"
}
]
| null | []
| /*
* 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 gkfire.hibernate;
import org.hibernate.HibernateException;
/**
*
* @author <NAME>
*/
public class CustomHibernateException extends HibernateException {
public CustomHibernateException(String message) {
super(message);
}
}
| 458 | 0.707265 | 0.707265 | 18 | 24 | 25.174944 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 13 |
75995c7b115bd189f1eb979d33842e3a00f19235 | 23,691,039,610,444 | eac6a685dfa8bcc5cdb758df1618e4731f6492d4 | /JuegoSoftware/src/decorador/Decorator.java | 34e4aa5ba33e38262957a1d7651095a846d7b66e | []
| no_license | AlviVilla/JuegoSoftware | https://github.com/AlviVilla/JuegoSoftware | 139bbab6c1a4490731aa12036095c44b8578b85a | 8a4f7d678b5961343fdf6049e8c385607df43512 | refs/heads/master | 2021-04-28T23:29:55.675000 | 2017-07-14T19:07:51 | 2017-07-14T19:07:51 | 77,452,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package decorador;
import fighter.Fighter;
public abstract class Decorator extends Fighter{
public abstract String getDecorador();
}
| UTF-8 | Java | 141 | java | Decorator.java | Java | []
| null | []
| package decorador;
import fighter.Fighter;
public abstract class Decorator extends Fighter{
public abstract String getDecorador();
}
| 141 | 0.780142 | 0.780142 | 10 | 13.1 | 17.218885 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 13 |
ac7d0fa97d8d55aa07b0f7a27b03c977def0a2fb | 30,829,275,281,669 | 7a7f01707bbe8ff623dc518aff0496f86943272b | /app/config/MailgunService.java | 4d3788904a8fde87b913c081ce3114fb86d91b51 | [
"MIT"
]
| permissive | ahmedulger/oauthly | https://github.com/ahmedulger/oauthly | 4276c0a6cd3868debd918db0c5c32eab1e750f9d | 75758237ccf331e371eb8910fd5310cd1914549d | refs/heads/master | 2020-05-14T16:01:46.218000 | 2019-01-14T15:34:53 | 2019-01-14T15:34:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package config;
import akka.stream.javadsl.Source;
import com.typesafe.config.Config;
import play.libs.ws.WSAuthScheme;
import play.libs.ws.WSClient;
import play.mvc.Http.MultipartFormData.DataPart;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
/**
* Created by Selim Eren Bekçe on 6.09.2017.
*
* TODO Use circuit breaker or akka for retries https://github.com/jhalterman/failsafe#circuit-breakers
*
*/
@Singleton
public class MailgunService implements MailService {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MailgunService.class);
private final String mailgunKey;
private final String mailgunFrom;
private final String mailgunDomain;
private final WSClient ws;
@Inject
public MailgunService(Config config, WSClient ws) {
this.mailgunKey = config.getString("mail.mailgun.key");
this.mailgunFrom = config.getString("mail.mailgun.from");
this.mailgunDomain = config.getString("mail.mailgun.domain");
this.ws = ws;
}
@Override
public CompletableFuture<String> sendEmail(String to, String subject, String content) {
return ws.url(String.format("https://api.mailgun.net/v3/%s/messages", mailgunDomain))
.setAuth("api", mailgunKey, WSAuthScheme.BASIC)
.post(Source.from(Arrays.asList(
new DataPart("from", mailgunFrom),
new DataPart("to", to),
new DataPart("subject", subject),
new DataPart("html", content))))
.handleAsync((response, throwable) -> {
if(throwable != null) {
log.error("sendEmail: Exception", throwable);
} else if(response.getStatus() != 200) {
log.error("sendEmail: Non-200 response, status={}, body={}", response.getStatus(), response.getBody());
} else {
log.error("sendEmail: OK, status={}, body={}", response.getStatus(), response.getBody());
return response.asJson().get("id").textValue();
}
return null;
}).toCompletableFuture();
}
}
| UTF-8 | Java | 2,326 | java | MailgunService.java | Java | [
{
"context": "l.concurrent.CompletableFuture;\n\n/**\n * Created by Selim Eren Bekçe on 6.09.2017.\n *\n * TODO Use circuit breaker or a",
"end": 367,
"score": 0.999845564365387,
"start": 351,
"tag": "NAME",
"value": "Selim Eren Bekçe"
},
{
"context": "it breaker or akka for retries https://github.com/jhalterman/failsafe#circuit-breakers\n *\n */\n@Singleton\npubli",
"end": 462,
"score": 0.9979303479194641,
"start": 452,
"tag": "USERNAME",
"value": "jhalterman"
}
]
| null | []
| package config;
import akka.stream.javadsl.Source;
import com.typesafe.config.Config;
import play.libs.ws.WSAuthScheme;
import play.libs.ws.WSClient;
import play.mvc.Http.MultipartFormData.DataPart;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
/**
* Created by <NAME> on 6.09.2017.
*
* TODO Use circuit breaker or akka for retries https://github.com/jhalterman/failsafe#circuit-breakers
*
*/
@Singleton
public class MailgunService implements MailService {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MailgunService.class);
private final String mailgunKey;
private final String mailgunFrom;
private final String mailgunDomain;
private final WSClient ws;
@Inject
public MailgunService(Config config, WSClient ws) {
this.mailgunKey = config.getString("mail.mailgun.key");
this.mailgunFrom = config.getString("mail.mailgun.from");
this.mailgunDomain = config.getString("mail.mailgun.domain");
this.ws = ws;
}
@Override
public CompletableFuture<String> sendEmail(String to, String subject, String content) {
return ws.url(String.format("https://api.mailgun.net/v3/%s/messages", mailgunDomain))
.setAuth("api", mailgunKey, WSAuthScheme.BASIC)
.post(Source.from(Arrays.asList(
new DataPart("from", mailgunFrom),
new DataPart("to", to),
new DataPart("subject", subject),
new DataPart("html", content))))
.handleAsync((response, throwable) -> {
if(throwable != null) {
log.error("sendEmail: Exception", throwable);
} else if(response.getStatus() != 200) {
log.error("sendEmail: Non-200 response, status={}, body={}", response.getStatus(), response.getBody());
} else {
log.error("sendEmail: OK, status={}, body={}", response.getStatus(), response.getBody());
return response.asJson().get("id").textValue();
}
return null;
}).toCompletableFuture();
}
}
| 2,315 | 0.616774 | 0.609892 | 59 | 38.40678 | 31.452477 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813559 | false | false | 13 |
3c2acbb7ee9adcb7e38bf9f0113bbbde2cea2cc5 | 22,187,801,076,638 | 90cd137fed2603707d40f243359e99edcfdc8843 | /src/main/java/base/BaseApplication.java | 0831f01ea17449c96660588ea53796186fb5e604 | []
| no_license | sanata00/Test_Framework | https://github.com/sanata00/Test_Framework | 2e2efe784cbdfa90fad72764f2da4d1717481813 | b05d6daf60e057389c5211503e4c2275f972efd6 | refs/heads/master | 2020-05-23T15:43:15.654000 | 2019-04-12T11:35:33 | 2019-04-12T11:35:33 | 186,832,066 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package base;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;
public class BaseApplication {
protected WebDriver driver;
protected BaseApplication() {
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public void quit() {
driver.quit();
driver = null;
}
public WebDriver getDriver() {
return driver;
}
}
| UTF-8 | Java | 615 | java | BaseApplication.java | Java | []
| null | []
| package base;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;
public class BaseApplication {
protected WebDriver driver;
protected BaseApplication() {
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public void quit() {
driver.quit();
driver = null;
}
public WebDriver getDriver() {
return driver;
}
}
| 615 | 0.730081 | 0.728455 | 27 | 21.777779 | 19.316723 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518519 | false | false | 13 |
d6634e2a974a24317f6a2142afea43f5896e5049 | 22,187,801,079,435 | 8f398cddabae2e94b08b4953a68bce72c800233a | /javatot/src/chap4/Student.java | 6f44928745366e8e8d4f84e1c7655de5817e502f | []
| no_license | mawaddah2009/moh-java | https://github.com/mawaddah2009/moh-java | 5c8c95c9f6620542e624af221913c48a48dea376 | d7466d5080752b74e04a10c143fafde0c7ec1840 | refs/heads/master | 2020-04-26T15:39:53.661000 | 2019-03-08T14:58:00 | 2019-03-08T14:58:00 | 173,653,702 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //method set nama
//x return apa2 so kena letak void
package chap4;
//primitive + string = passing value
//object always passing by reference
public class Student {
void setName(String name){
System.out.println(name);
name = name + " binti mat zan";
}
void changeBookTitle(Book b){
b.title = "Java for Advaned";
}
public static void main(String[] args){
//create obj student dr class student
Student s1 = new Student();
//ini passing by value
String nama = "hasnita";
s1.setName(nama);
System.out.println(nama);
//passing var by reference
Book b1 = new Book();
b1.title = "Java for Beginner";
System.out.println(b1.title);
s1.changeBookTitle(b1);
System.out.println(b1.title);
}
}
//run:hasnita | UTF-8 | Java | 790 | java | Student.java | Java | [
{
"context": "\n System.out.println(name);\n name = name + \" binti mat zan\";\n }\n void changeBookTitle(Book b){\n ",
"end": 259,
"score": 0.9984888434410095,
"start": 246,
"tag": "NAME",
"value": "binti mat zan"
},
{
"context": "();\n //ini passing by value\n String nama = \"hasnita\";\n s1.setName(nama);\n System.out.println(na",
"end": 517,
"score": 0.8410539031028748,
"start": 510,
"tag": "USERNAME",
"value": "hasnita"
}
]
| null | []
| //method set nama
//x return apa2 so kena letak void
package chap4;
//primitive + string = passing value
//object always passing by reference
public class Student {
void setName(String name){
System.out.println(name);
name = name + " <NAME>";
}
void changeBookTitle(Book b){
b.title = "Java for Advaned";
}
public static void main(String[] args){
//create obj student dr class student
Student s1 = new Student();
//ini passing by value
String nama = "hasnita";
s1.setName(nama);
System.out.println(nama);
//passing var by reference
Book b1 = new Book();
b1.title = "Java for Beginner";
System.out.println(b1.title);
s1.changeBookTitle(b1);
System.out.println(b1.title);
}
}
//run:hasnita | 783 | 0.641772 | 0.629114 | 31 | 24.516129 | 12.088039 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 13 |
13eb63cf88e6c6ca9a097e075823e17ff8a925f2 | 31,851,477,492,805 | 022980735384919a0e9084f57ea2f495b10c0d12 | /src/ext-cttdt-lltnxp/ext-service/src/com/sgs/portlet/recievergroup/service/persistence/RecieverFinder.java | 06a72907eba49016fd44ae7ba5fc91d79fc32cd8 | []
| no_license | thaond/nsscttdt | https://github.com/thaond/nsscttdt | 474d8e359f899d4ea6f48dd46ccd19bbcf34b73a | ae7dacc924efe578ce655ddfc455d10c953abbac | refs/heads/master | 2021-01-10T03:00:24.086000 | 2011-02-19T09:18:34 | 2011-02-19T09:18:34 | 50,081,202 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sgs.portlet.recievergroup.service.persistence;
public interface RecieverFinder {
public java.util.List<com.liferay.portal.model.User> findUserByFullName(
long companyId, java.lang.String name)
throws com.liferay.portal.SystemException;
}
| UTF-8 | Java | 271 | java | RecieverFinder.java | Java | []
| null | []
| package com.sgs.portlet.recievergroup.service.persistence;
public interface RecieverFinder {
public java.util.List<com.liferay.portal.model.User> findUserByFullName(
long companyId, java.lang.String name)
throws com.liferay.portal.SystemException;
}
| 271 | 0.771218 | 0.771218 | 7 | 37.714287 | 26.428957 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
81c129105416617a377f023cc67a0b13cdbf726d | 24,644,522,414,011 | 345c86d3092cb33f77f14681602f2c2bb6c1c090 | /Entrega-3/Proyecto/Acme-HandyWorker/src/test/java/services/SystemRequirementsServiceTest.java | d2754ab68ce1b98677087e6426a13d684ba6aa79 | []
| no_license | juanmiguelruiz/DP1 | https://github.com/juanmiguelruiz/DP1 | 03bac7b98f9c1363165887b0c163b0eeee6356d2 | acc84371af6f43bbc1e3688ba62eef3f8fc730b0 | refs/heads/master | 2020-08-29T15:31:19.198000 | 2020-06-03T15:14:58 | 2020-06-03T15:14:58 | 218,074,049 | 0 | 0 | null | false | 2020-10-13T17:03:18 | 2019-10-28T15:05:24 | 2020-06-03T15:15:08 | 2020-10-13T17:03:18 | 84,606 | 0 | 0 | 30 | Java | false | false |
package services;
import java.util.Arrays;
import java.util.Collection;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import domain.SystemRequirements;
import utilities.AbstractTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:spring/datasource.xml", "classpath:spring/config/packages.xml"
})
@Transactional
public class SystemRequirementsServiceTest extends AbstractTest {
//Service Under Test -----------------------------------------
@Autowired
private SystemRequirementsService systemRequirementsService;
//Tests ------------------------------------------------------
@Test
public void testCreate() {
final SystemRequirements systemRequirements = this.systemRequirementsService.create();
Assert.notNull(systemRequirements);
}
@Test
public void testDelete() {
final SystemRequirements systemRequirements = this.systemRequirementsService.create();
final Collection<String> palabras = Arrays.asList("palabra", "palabra");
systemRequirements.setSystemName("Nombre");
systemRequirements.setBanner("http://google.es");
systemRequirements.setWelcomeMessageSpanish("Hola");
systemRequirements.setWelcomeMessageEnglish("Hello");
systemRequirements.setCountryCode("+34");
systemRequirements.setPositiveWords(palabras);
systemRequirements.setNegativeWords(palabras);
systemRequirements.setSpamWords(palabras);
systemRequirements.setVAT(21);
systemRequirements.setTimeCacheFinder(20);
systemRequirements.setMaxSearch(20);
final SystemRequirements deleteSystemRequirements = this.systemRequirementsService.save(systemRequirements);
this.systemRequirementsService.delete(deleteSystemRequirements);
}
@Test
public void testSave() {
final SystemRequirements systemRequirements = this.systemRequirementsService.create();
final Collection<String> palabras = Arrays.asList("palabra", "palabra");
systemRequirements.setSystemName("Nombre");
systemRequirements.setBanner("http://google.es");
systemRequirements.setWelcomeMessageSpanish("Hola");
systemRequirements.setWelcomeMessageEnglish("Hello");
systemRequirements.setCountryCode("+34");
systemRequirements.setPositiveWords(palabras);
systemRequirements.setNegativeWords(palabras);
systemRequirements.setSpamWords(palabras);
systemRequirements.setVAT(21);
systemRequirements.setTimeCacheFinder(20);
systemRequirements.setMaxSearch(20);
final SystemRequirements saveSystemRequirements = this.systemRequirementsService.save(systemRequirements);
Assert.notNull(saveSystemRequirements);
Assert.isTrue(this.systemRequirementsService.findAll().contains(saveSystemRequirements));
}
@Test
public void testFindAll() {
final Collection<SystemRequirements> systemRequirements = this.systemRequirementsService.findAll();
Assert.notNull(systemRequirements);
}
@Test
public void testFindOne() {
final SystemRequirements systemRequirements = this.systemRequirementsService.findOne(super.getEntityId("SystemRequirements1"));
Assert.notNull(systemRequirements);
}
}
| UTF-8 | Java | 3,337 | java | SystemRequirementsServiceTest.java | Java | []
| null | []
|
package services;
import java.util.Arrays;
import java.util.Collection;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import domain.SystemRequirements;
import utilities.AbstractTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:spring/datasource.xml", "classpath:spring/config/packages.xml"
})
@Transactional
public class SystemRequirementsServiceTest extends AbstractTest {
//Service Under Test -----------------------------------------
@Autowired
private SystemRequirementsService systemRequirementsService;
//Tests ------------------------------------------------------
@Test
public void testCreate() {
final SystemRequirements systemRequirements = this.systemRequirementsService.create();
Assert.notNull(systemRequirements);
}
@Test
public void testDelete() {
final SystemRequirements systemRequirements = this.systemRequirementsService.create();
final Collection<String> palabras = Arrays.asList("palabra", "palabra");
systemRequirements.setSystemName("Nombre");
systemRequirements.setBanner("http://google.es");
systemRequirements.setWelcomeMessageSpanish("Hola");
systemRequirements.setWelcomeMessageEnglish("Hello");
systemRequirements.setCountryCode("+34");
systemRequirements.setPositiveWords(palabras);
systemRequirements.setNegativeWords(palabras);
systemRequirements.setSpamWords(palabras);
systemRequirements.setVAT(21);
systemRequirements.setTimeCacheFinder(20);
systemRequirements.setMaxSearch(20);
final SystemRequirements deleteSystemRequirements = this.systemRequirementsService.save(systemRequirements);
this.systemRequirementsService.delete(deleteSystemRequirements);
}
@Test
public void testSave() {
final SystemRequirements systemRequirements = this.systemRequirementsService.create();
final Collection<String> palabras = Arrays.asList("palabra", "palabra");
systemRequirements.setSystemName("Nombre");
systemRequirements.setBanner("http://google.es");
systemRequirements.setWelcomeMessageSpanish("Hola");
systemRequirements.setWelcomeMessageEnglish("Hello");
systemRequirements.setCountryCode("+34");
systemRequirements.setPositiveWords(palabras);
systemRequirements.setNegativeWords(palabras);
systemRequirements.setSpamWords(palabras);
systemRequirements.setVAT(21);
systemRequirements.setTimeCacheFinder(20);
systemRequirements.setMaxSearch(20);
final SystemRequirements saveSystemRequirements = this.systemRequirementsService.save(systemRequirements);
Assert.notNull(saveSystemRequirements);
Assert.isTrue(this.systemRequirementsService.findAll().contains(saveSystemRequirements));
}
@Test
public void testFindAll() {
final Collection<SystemRequirements> systemRequirements = this.systemRequirementsService.findAll();
Assert.notNull(systemRequirements);
}
@Test
public void testFindOne() {
final SystemRequirements systemRequirements = this.systemRequirementsService.findOne(super.getEntityId("SystemRequirements1"));
Assert.notNull(systemRequirements);
}
}
| 3,337 | 0.792628 | 0.786635 | 102 | 31.705883 | 30.75507 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.441176 | false | false | 13 |
0c7260de31e349efcf51918822bc7c8111a21f26 | 24,713,241,873,986 | 8e52172b0320cf56e7e0078328116b7d6528328d | /src/main/java/morph/avaritia/entity/EntityHeavenArrow.java | 61e977a114446efea496bbefbbdcb8fef88ccdab | [
"MIT"
]
| permissive | Morpheus1101/Avaritia | https://github.com/Morpheus1101/Avaritia | ea9940d8fe2213481a58bc89f81e9b11b94a3ba3 | eac76456071d5cc0da3da7876a601b4a1470cad9 | refs/heads/master | 2023-02-21T08:32:03.160000 | 2022-01-29T07:10:03 | 2022-01-29T07:10:03 | 82,286,093 | 53 | 65 | null | true | 2023-02-19T10:59:33 | 2017-02-17T10:30:19 | 2023-01-23T10:24:39 | 2023-02-13T15:08:01 | 70,941 | 33 | 28 | 32 | Java | false | false | package morph.avaritia.entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import java.util.Random;
public class EntityHeavenArrow extends EntityArrow {
public boolean impacted = false;
public EntityHeavenArrow(World world, double x, double y, double z) {
super(world, x, y, z);
}
public EntityHeavenArrow(World world, EntityLivingBase entity) {
super(world, entity);
}
public EntityHeavenArrow(World world) {
super(world);
}
@Override
public void onUpdate() {
rotationPitch = 0;
rotationYaw = 0;
super.onUpdate();
if (!impacted) {
try {
if (inGround) {
impacted = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if (impacted) {
if (!world.isRemote) {
barrage();
}
}
}
if (inGround && timeInGround >= 100) {
setDead();
}
}
@Override
public void writeEntityToNBT(NBTTagCompound tag) {
super.writeEntityToNBT(tag);
tag.setBoolean("impacted", impacted);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound tag) {
super.readEntityFromNBT(tag);
impacted = tag.getBoolean("impacted");
}
public void barrage() {//TODO, this logic may be borked.
Random randy = getEntityWorld().rand;
for (int i = 0; i < 10; i++) {
double angle = randy.nextDouble() * 2 * Math.PI;
double dist = randy.nextGaussian() * 0.5;
double x = Math.sin(angle) * dist + posX;
double z = Math.cos(angle) * dist + posZ;
double y = posY + 25.0;
double dangle = randy.nextDouble() * 2 * Math.PI;
double ddist = randy.nextDouble() * 0.35;
double dx = Math.sin(dangle) * ddist;
double dz = Math.cos(dangle) * ddist;
EntityArrow arrow = new EntityHeavenSubArrow(world, x, y, z);
arrow.shootingEntity = shootingEntity;
arrow.addVelocity(dx, -(randy.nextDouble() * 1.85 + 0.15), dz);
arrow.setDamage(getDamage());
arrow.setIsCritical(true);
arrow.pickupStatus = pickupStatus;
world.spawnEntity(arrow);
}
}
@Override
protected ItemStack getArrowStack() {
return new ItemStack(Items.ARROW);//TODO This needs to be null but can't be, Because vanulla.
}
}
| UTF-8 | Java | 2,832 | java | EntityHeavenArrow.java | Java | []
| null | []
| package morph.avaritia.entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import java.util.Random;
public class EntityHeavenArrow extends EntityArrow {
public boolean impacted = false;
public EntityHeavenArrow(World world, double x, double y, double z) {
super(world, x, y, z);
}
public EntityHeavenArrow(World world, EntityLivingBase entity) {
super(world, entity);
}
public EntityHeavenArrow(World world) {
super(world);
}
@Override
public void onUpdate() {
rotationPitch = 0;
rotationYaw = 0;
super.onUpdate();
if (!impacted) {
try {
if (inGround) {
impacted = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if (impacted) {
if (!world.isRemote) {
barrage();
}
}
}
if (inGround && timeInGround >= 100) {
setDead();
}
}
@Override
public void writeEntityToNBT(NBTTagCompound tag) {
super.writeEntityToNBT(tag);
tag.setBoolean("impacted", impacted);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound tag) {
super.readEntityFromNBT(tag);
impacted = tag.getBoolean("impacted");
}
public void barrage() {//TODO, this logic may be borked.
Random randy = getEntityWorld().rand;
for (int i = 0; i < 10; i++) {
double angle = randy.nextDouble() * 2 * Math.PI;
double dist = randy.nextGaussian() * 0.5;
double x = Math.sin(angle) * dist + posX;
double z = Math.cos(angle) * dist + posZ;
double y = posY + 25.0;
double dangle = randy.nextDouble() * 2 * Math.PI;
double ddist = randy.nextDouble() * 0.35;
double dx = Math.sin(dangle) * ddist;
double dz = Math.cos(dangle) * ddist;
EntityArrow arrow = new EntityHeavenSubArrow(world, x, y, z);
arrow.shootingEntity = shootingEntity;
arrow.addVelocity(dx, -(randy.nextDouble() * 1.85 + 0.15), dz);
arrow.setDamage(getDamage());
arrow.setIsCritical(true);
arrow.pickupStatus = pickupStatus;
world.spawnEntity(arrow);
}
}
@Override
protected ItemStack getArrowStack() {
return new ItemStack(Items.ARROW);//TODO This needs to be null but can't be, Because vanulla.
}
}
| 2,832 | 0.570621 | 0.562147 | 99 | 27.60606 | 22.992233 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.59596 | false | false | 13 |
e579e30666e0f18efe51314689708f3eb00c4fd4 | 25,443,386,320,548 | cb74b9573e4eb6fa75f9ae7a3768258cdcea5a15 | /filmus/src/main/java/com/filmus/myapp/mapper/HeartMapper.java | c123d0b77732d35019f42636cac4d7058367ee0c | []
| no_license | jhyeona/myfilmee | https://github.com/jhyeona/myfilmee | 6101cf6c9e3311ae9dc35a996134e84f4f24d8ed | faa9ec1ba48a7fbcbf45c1975a8c7459419135fa | refs/heads/master | 2023-08-13T16:36:57.024000 | 2023-04-22T11:55:18 | 2023-04-22T11:55:18 | 399,667,998 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.filmus.myapp.mapper;
import org.apache.ibatis.annotations.Param;
import com.filmus.myapp.domain.HeartVO;
public interface HeartMapper {
public abstract int heartInsert(HeartVO vo); //처음이라면 insert
public abstract int heartCheck(@Param("bno")Integer bno, @Param("userid")Integer userid); //좋아요를 눌렀을 때
public abstract int heartUncheck(@Param("bno")Integer bno, @Param("userid")Integer userid); //좋아요를 취소할 때
public abstract HeartVO check(@Param("bno")Integer bno, @Param("userid")Integer userid); //좋아요 되어 있는지 확인
public abstract int heartCnt(Integer bno); //좋아요 개수
}//end interface
| UTF-8 | Java | 684 | java | HeartMapper.java | Java | []
| null | []
| package com.filmus.myapp.mapper;
import org.apache.ibatis.annotations.Param;
import com.filmus.myapp.domain.HeartVO;
public interface HeartMapper {
public abstract int heartInsert(HeartVO vo); //처음이라면 insert
public abstract int heartCheck(@Param("bno")Integer bno, @Param("userid")Integer userid); //좋아요를 눌렀을 때
public abstract int heartUncheck(@Param("bno")Integer bno, @Param("userid")Integer userid); //좋아요를 취소할 때
public abstract HeartVO check(@Param("bno")Integer bno, @Param("userid")Integer userid); //좋아요 되어 있는지 확인
public abstract int heartCnt(Integer bno); //좋아요 개수
}//end interface
| 684 | 0.746732 | 0.746732 | 20 | 29.6 | 36.74017 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.35 | false | false | 13 |
579fbb4e96dd7f4cb266301aea54df625f4d1064 | 17,952,963,324,306 | 5b2e51c08d91ca6f9b68427bf0a2320293604d71 | /app/src/main/java/com/binbasket/binbasket/ExecuteUrl.java | 5a183579fb1dc8edb2fcce56252bf0e4f73cb27b | []
| no_license | iqubalashraf/BinBasket2 | https://github.com/iqubalashraf/BinBasket2 | 6c3a68cec3ca737f548c890dfc9872d129af1c89 | 2fb098d89d500ce12d73119aeeb5c7dd1e781961 | refs/heads/master | 2021-01-17T08:25:27.870000 | 2017-03-04T17:12:16 | 2017-03-04T17:12:16 | 83,910,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.binbasket.binbasket;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by ashrafiqubal on 29/06/16.
*/
public class ExecuteUrl extends AsyncTask<String, Void, Boolean> {
String serverResponse;
private ProgressDialog pDialog;
Context context1;
SharedPreferences sharedpreferences;
public ExecuteUrl(Context context){
context1 = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
pDialog = new ProgressDialog(context1);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
String str;
HttpClient myClient = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
HttpResponse myResponse = myClient.execute(get);
BufferedReader br = new BufferedReader(new InputStreamReader(myResponse.getEntity().getContent()));
while ((str = br.readLine()) != null) {
serverResponse = str;
Log.d("SingUp: ", str);
}
} catch (IOException e) {
e.printStackTrace();
}
prepared = true;
return prepared;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
Object obj = JSONValue.parse(serverResponse);
JSONObject jsonObject = (JSONObject)obj;
String status = (String)jsonObject.get("STATUS");
if(status.equals("0")){
Log.d("SingUp:// ", "onPostExecution ");
if(CustomAdapter.check==1){
Toast.makeText(context1,"PickUp Cancelled",Toast.LENGTH_SHORT).show();
}
if(CustomAdapter.check==2){
Toast.makeText(context1,"Order Placed Successfully",Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(context1,MainActivity.class);
context1.startActivity(intent);
((MainActivity)context1).finish();
}
if(status.equals("1")){
Toast.makeText(context1,"Phone no already exists",Toast.LENGTH_SHORT).show();
}
if(status.equals("2")){
Log.d("SingUp:","Registration Successful");
Toast.makeText(context1,"Invalid details",Toast.LENGTH_SHORT).show();
}
if(status.equals("3")){
Log.d("SingUp:","Registration Successful");
Toast.makeText(context1,"You already have a Active Order !",Toast.LENGTH_SHORT).show();
}
}
} | UTF-8 | Java | 3,383 | java | ExecuteUrl.java | Java | [
{
"context": "port java.io.InputStreamReader;\n\n/**\n * Created by ashrafiqubal on 29/06/16.\n */\npublic class ExecuteUrl extends ",
"end": 632,
"score": 0.9992302060127258,
"start": 620,
"tag": "USERNAME",
"value": "ashrafiqubal"
}
]
| null | []
| package com.binbasket.binbasket;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by ashrafiqubal on 29/06/16.
*/
public class ExecuteUrl extends AsyncTask<String, Void, Boolean> {
String serverResponse;
private ProgressDialog pDialog;
Context context1;
SharedPreferences sharedpreferences;
public ExecuteUrl(Context context){
context1 = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
pDialog = new ProgressDialog(context1);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
String str;
HttpClient myClient = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
HttpResponse myResponse = myClient.execute(get);
BufferedReader br = new BufferedReader(new InputStreamReader(myResponse.getEntity().getContent()));
while ((str = br.readLine()) != null) {
serverResponse = str;
Log.d("SingUp: ", str);
}
} catch (IOException e) {
e.printStackTrace();
}
prepared = true;
return prepared;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
Object obj = JSONValue.parse(serverResponse);
JSONObject jsonObject = (JSONObject)obj;
String status = (String)jsonObject.get("STATUS");
if(status.equals("0")){
Log.d("SingUp:// ", "onPostExecution ");
if(CustomAdapter.check==1){
Toast.makeText(context1,"PickUp Cancelled",Toast.LENGTH_SHORT).show();
}
if(CustomAdapter.check==2){
Toast.makeText(context1,"Order Placed Successfully",Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(context1,MainActivity.class);
context1.startActivity(intent);
((MainActivity)context1).finish();
}
if(status.equals("1")){
Toast.makeText(context1,"Phone no already exists",Toast.LENGTH_SHORT).show();
}
if(status.equals("2")){
Log.d("SingUp:","Registration Successful");
Toast.makeText(context1,"Invalid details",Toast.LENGTH_SHORT).show();
}
if(status.equals("3")){
Log.d("SingUp:","Registration Successful");
Toast.makeText(context1,"You already have a Active Order !",Toast.LENGTH_SHORT).show();
}
}
} | 3,383 | 0.634348 | 0.627254 | 96 | 34.25 | 22.826794 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.760417 | false | false | 13 |
3f4fee6d7e3d20b99d58c88e8bc162f84dd7efa9 | 24,885,040,522,429 | 73e12d6a3d43120aa85da7bff112cad38c15a1ab | /app/src/main/java/com/payghost/dazzleondivas/MainTabActivity.java | daa1ef252f24c166bb96ea8b22d03a42d3179332 | []
| no_license | Mbukutshe/DazzleonDivas | https://github.com/Mbukutshe/DazzleonDivas | 6034cb9ba9e6fad389bf64c05d5060202fc938cd | 3e3a2b2b81f3060501542196c58fe48f5a19d256 | refs/heads/master | 2021-04-29T14:58:02.060000 | 2018-02-17T06:44:02 | 2018-02-17T06:44:02 | 121,787,064 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.payghost.dazzleondivas;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.TabHost;
public class MainTabActivity extends TabActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tab);
toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
toolbar.setTitle("Dashboard");
TabHost tabHost = getTabHost();
TabHost.TabSpec Gallery = tabHost.newTabSpec("Gallery");
Gallery.setIndicator("Gallery");
Intent GroupIntent = new Intent(this,ImageUpload.class);
Gallery.setContent(GroupIntent);
TabHost.TabSpec Event = tabHost.newTabSpec("Message");
Event.setIndicator("Message");
Intent ShowIntent = new Intent(this,Message.class);
Event.setContent(ShowIntent);
TabHost.TabSpec specials = tabHost.newTabSpec("Specials");
specials.setIndicator("Specials");
Intent AccountIntent = new Intent(this,AddPost.class);
specials.setContent(AccountIntent);
TabHost.TabSpec chats = tabHost.newTabSpec("Contacts");
chats.setIndicator("Contacts");
Intent ChatsIntent = new Intent(this,Users.class);
chats.setContent(ChatsIntent);
TabHost.TabSpec Accounts = tabHost.newTabSpec("Accounts");
Accounts.setIndicator("Accounts");
Intent AccountsIntent = new Intent(this,Register.class);
chats.setContent(AccountsIntent);
tabHost.addTab(specials);
tabHost.addTab(Gallery);
tabHost.addTab(Event);
tabHost.addTab(chats);
tabHost.addTab(Accounts);
}
}
| UTF-8 | Java | 1,883 | java | MainTabActivity.java | Java | [
{
"context": "package com.payghost.dazzleondivas;\n\nimport android.app.TabActivity;\ni",
"end": 20,
"score": 0.5829469561576843,
"start": 15,
"tag": "USERNAME",
"value": "ghost"
}
]
| null | []
| package com.payghost.dazzleondivas;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.TabHost;
public class MainTabActivity extends TabActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tab);
toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
toolbar.setTitle("Dashboard");
TabHost tabHost = getTabHost();
TabHost.TabSpec Gallery = tabHost.newTabSpec("Gallery");
Gallery.setIndicator("Gallery");
Intent GroupIntent = new Intent(this,ImageUpload.class);
Gallery.setContent(GroupIntent);
TabHost.TabSpec Event = tabHost.newTabSpec("Message");
Event.setIndicator("Message");
Intent ShowIntent = new Intent(this,Message.class);
Event.setContent(ShowIntent);
TabHost.TabSpec specials = tabHost.newTabSpec("Specials");
specials.setIndicator("Specials");
Intent AccountIntent = new Intent(this,AddPost.class);
specials.setContent(AccountIntent);
TabHost.TabSpec chats = tabHost.newTabSpec("Contacts");
chats.setIndicator("Contacts");
Intent ChatsIntent = new Intent(this,Users.class);
chats.setContent(ChatsIntent);
TabHost.TabSpec Accounts = tabHost.newTabSpec("Accounts");
Accounts.setIndicator("Accounts");
Intent AccountsIntent = new Intent(this,Register.class);
chats.setContent(AccountsIntent);
tabHost.addTab(specials);
tabHost.addTab(Gallery);
tabHost.addTab(Event);
tabHost.addTab(chats);
tabHost.addTab(Accounts);
}
}
| 1,883 | 0.690919 | 0.690388 | 53 | 34.528301 | 22.177334 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.811321 | false | false | 13 |
afbe2333b7e0769fe6cbd2654e1f7199c35f045c | 13,520,557,099,716 | e399d7d49b433959ffd2d67d34b25fb5f2153b75 | /post/src/main/java/com/example/post/dto/PostRequestDto.java | fff354ab8e388874c943680fe43ddc99fd6d6c31 | []
| no_license | jinseonghee/spring-boot-crud | https://github.com/jinseonghee/spring-boot-crud | 59813b9d1fb056e5e9b976af6d865f2dd1da714e | fb8579d2bf6e9d579f98807940ad5ca0787d23bd | refs/heads/main | 2023-07-09T16:49:46.420000 | 2021-08-05T10:11:45 | 2021-08-05T10:11:45 | 392,340,113 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.post.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PostRequestDto {
private String account; //요청하는 json의 key에 해당되기 때문에 json의 key와 매칭이 되어야 함
private String email;
private String address;
private String password;
@JsonProperty("phone_number") //변수에 다 달아줘야 하는 단점이 있지만 이 어노테이션을 쓰고 이름을 달아주면 특정 이름에 매칭 가능
private String phoneNumber; //camelcase, phone_number(snakecase)
//object mapper를 library를 통해서 text data가 결국엔 Object로 바뀌게 되는데, 따로 변수 이름을 바꿔주지 않으면
//json형식에서 보낸 snakecase를 찾아가기 떄문에 camelcase로 변수 선언이 되어있는걸 못 찾음
@JsonProperty("OTP")//camelcase, snakecase도 아닌 특정한 값이나 약어를 사용할 때, @JsonProperty를 사용하여, 실제로 json으로 들어오는 이름 값을 매칭
private String OTP;
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "PostRequestDto{" +
"account='" + account + '\'' +
", email='" + email + '\'' +
", address='" + address + '\'' +
", password='" + password + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", OTP='" + OTP + '\'' +
'}';
}
}
| UTF-8 | Java | 2,260 | java | PostRequestDto.java | Java | [
{
"context": " address + '\\'' +\n \", password='\" + password + '\\'' +\n \", phoneNumber='\" + phon",
"end": 1809,
"score": 0.9919547438621521,
"start": 1801,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.example.post.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PostRequestDto {
private String account; //요청하는 json의 key에 해당되기 때문에 json의 key와 매칭이 되어야 함
private String email;
private String address;
private String password;
@JsonProperty("phone_number") //변수에 다 달아줘야 하는 단점이 있지만 이 어노테이션을 쓰고 이름을 달아주면 특정 이름에 매칭 가능
private String phoneNumber; //camelcase, phone_number(snakecase)
//object mapper를 library를 통해서 text data가 결국엔 Object로 바뀌게 되는데, 따로 변수 이름을 바꿔주지 않으면
//json형식에서 보낸 snakecase를 찾아가기 떄문에 camelcase로 변수 선언이 되어있는걸 못 찾음
@JsonProperty("OTP")//camelcase, snakecase도 아닌 특정한 값이나 약어를 사용할 때, @JsonProperty를 사용하여, 실제로 json으로 들어오는 이름 값을 매칭
private String OTP;
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "PostRequestDto{" +
"account='" + account + '\'' +
", email='" + email + '\'' +
", address='" + address + '\'' +
", password='" + <PASSWORD> + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", OTP='" + OTP + '\'' +
'}';
}
}
| 2,262 | 0.57554 | 0.57554 | 71 | 26.408451 | 26.803183 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.408451 | false | false | 13 |
f757fc3a7329194e1657b04be58ecb823cb27854 | 10,436,770,585,109 | 8889ac28f020ba70f1ec5bd7891a67ea6eff82cc | /src/UnderlineFile.java | 67442ef23750b6e8908503873b8017fef6554b0e | []
| no_license | austinvoice/buildingjava | https://github.com/austinvoice/buildingjava | b12072d6f95d045882775b465262679509e5af68 | de15ae09421097206af70a1c8134e0b7e552d348 | refs/heads/master | 2020-09-01T21:39:00.527000 | 2019-11-03T14:59:17 | 2019-11-03T14:59:17 | 219,065,006 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // import file and create formatted output
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class UnderlineFile {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("out/production/Builidng Graphics/paper.txt"));
expandFile(input);
}
public static void expandFile(Scanner input) {
while (input.hasNextLine()) {
String text = input.nextLine();
if (text.length() > 0 && text.startsWith(".")) {
System.out.println(text.substring(1));
for (int i = 1; i <= text.length() - 1; i++) {
System.out.print("-"); // underline
}
System.out.println();
} else {
System.out.println(text);
}
}
}
}
| UTF-8 | Java | 879 | java | UnderlineFile.java | Java | []
| null | []
| // import file and create formatted output
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class UnderlineFile {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("out/production/Builidng Graphics/paper.txt"));
expandFile(input);
}
public static void expandFile(Scanner input) {
while (input.hasNextLine()) {
String text = input.nextLine();
if (text.length() > 0 && text.startsWith(".")) {
System.out.println(text.substring(1));
for (int i = 1; i <= text.length() - 1; i++) {
System.out.print("-"); // underline
}
System.out.println();
} else {
System.out.println(text);
}
}
}
}
| 879 | 0.556314 | 0.551763 | 27 | 31.555555 | 24.089853 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 13 |
f15c3961a9feb1d252bfbacf7c9b62a5b4a46c97 | 27,419,071,220,045 | 1109bc9fe89a2f4ba75392e3fa6540a4b555321d | /att28-04JOptPane/src/view/Execucao.java | 66eb04d8100f7ca257ce26eff9235f297b2819e5 | []
| no_license | gustavosouzaveiga/Aula-28-04_com_JOptionPane | https://github.com/gustavosouzaveiga/Aula-28-04_com_JOptionPane | 414f732a302dace3cefb17c8b4f0a02fd31e776d | 0c00d38e29caa6efffac0008a0463d7d8b78a577 | refs/heads/master | 2020-05-16T20:58:31.517000 | 2019-04-24T19:26:45 | 2019-04-24T19:26:45 | 183,293,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package view;
import javax.swing.JOptionPane;
import model.Pessoa;
public class Execucao {
public static void main(String[] args) {
Pessoa ps = new Pessoa();
ps.setNome("Gustavo de Souza Veiga Alves");
ps.setEnd("Rua Palmeira das Bermudas, 849");
ps.setBairro("Jardim dos Ipês");
ps.setCep("08161-160");
ps.setCid("São Paulo");
ps.setEst("São Paulo");
JOptionPane.showMessageDialog(null, ps.getNome() + "\n" +
ps.getEnd() + "\n" +
ps.getBairro() + "\n" +
ps.getCep() + "\n" +
ps.getCid() + "\n" +
ps.getEst());
}
}
| ISO-8859-1 | Java | 578 | java | Execucao.java | Java | [
{
"context": "gs) {\r\n\t\tPessoa ps = new Pessoa();\r\n\t\tps.setNome(\"Gustavo de Souza Veiga Alves\");\r\n\t\tps.setEnd(\"Rua Palmeira das Bermudas, 849\")",
"end": 215,
"score": 0.9998669028282166,
"start": 187,
"tag": "NAME",
"value": "Gustavo de Souza Veiga Alves"
},
{
"context": "ua Palmeira das Bermudas, 849\");\r\n\t\tps.setBairro(\"Jardim dos Ipês\");\r\n\t\tps.setCep(\"08161-160\");\r\n\t\tps.setCid(\"São P",
"end": 299,
"score": 0.9928078651428223,
"start": 284,
"tag": "NAME",
"value": "Jardim dos Ipês"
}
]
| null | []
| package view;
import javax.swing.JOptionPane;
import model.Pessoa;
public class Execucao {
public static void main(String[] args) {
Pessoa ps = new Pessoa();
ps.setNome("<NAME>");
ps.setEnd("Rua Palmeira das Bermudas, 849");
ps.setBairro("<NAME>");
ps.setCep("08161-160");
ps.setCid("São Paulo");
ps.setEst("São Paulo");
JOptionPane.showMessageDialog(null, ps.getNome() + "\n" +
ps.getEnd() + "\n" +
ps.getBairro() + "\n" +
ps.getCep() + "\n" +
ps.getCid() + "\n" +
ps.getEst());
}
}
| 546 | 0.605217 | 0.586087 | 24 | 21.958334 | 15.844239 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.833333 | false | false | 13 |
6928930b8faebcf94189b30d88a0d2ae7f47552e | 30,683,246,378,367 | c355551605628b4b3c8358847c007ad1e6181461 | /backend-user/src/main/java/com/mooc/meeting/film/user/entity/MoocBackendUserT.java | 8c8c524a2a4b34c3881b7c04352d602b47691a8d | []
| no_license | satan12345/backend-parent | https://github.com/satan12345/backend-parent | 8e4cb8994e419e426a2b37eca3a65cb987b0df39 | 366ca55788e11fe0ae282cf1d13651af9fee3ffd | refs/heads/master | 2022-07-04T02:18:10.870000 | 2020-03-10T11:35:20 | 2020-03-10T11:35:20 | 243,731,037 | 0 | 1 | null | false | 2022-06-21T02:53:07 | 2020-02-28T09:59:36 | 2020-03-10T11:35:32 | 2022-06-21T02:53:04 | 172 | 0 | 1 | 4 | Java | false | false | package com.mooc.meeting.film.user.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import java.io.Serializable;
/**
* 后台用户表(MoocBackendUserT)实体类
*
* @author makejava
* @since 2020-02-29 15:30:52
*/
@Data
@Table(name = "mooc_backend_user_t")
public class MoocBackendUserT implements Serializable {
private static final long serialVersionUID = 673775299725912780L;
/**
* 主键编号
*/
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "UUID")
private Integer uuid;
/**
* 用户账号
*/
@Column(name = "user_name")
private String userName;
/**
* 用户密码
*/
@Column(name = "user_pwd")
private String userPwd;
/**
* 用户手机号
*/
@Column(name = "user_phone")
private String userPhone;
} | UTF-8 | Java | 979 | java | MoocBackendUserT.java | Java | [
{
"context": ";\n\n/**\n * 后台用户表(MoocBackendUserT)实体类\n *\n * @author makejava\n * @since 2020-02-29 15:30:52\n */\n@Data\n@Table(na",
"end": 298,
"score": 0.9995846748352051,
"start": 290,
"tag": "USERNAME",
"value": "makejava"
}
]
| null | []
| package com.mooc.meeting.film.user.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import java.io.Serializable;
/**
* 后台用户表(MoocBackendUserT)实体类
*
* @author makejava
* @since 2020-02-29 15:30:52
*/
@Data
@Table(name = "mooc_backend_user_t")
public class MoocBackendUserT implements Serializable {
private static final long serialVersionUID = 673775299725912780L;
/**
* 主键编号
*/
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "UUID")
private Integer uuid;
/**
* 用户账号
*/
@Column(name = "user_name")
private String userName;
/**
* 用户密码
*/
@Column(name = "user_pwd")
private String userPwd;
/**
* 用户手机号
*/
@Column(name = "user_phone")
private String userPhone;
} | 979 | 0.669537 | 0.635091 | 46 | 19.217392 | 16.958918 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26087 | false | false | 13 |
b6e1f433585b897ae8cfee378b16b9ffcc8b3d51 | 30,683,246,379,827 | 4f56678940fcbcce4a402bddb0f9fd2b3df2d620 | /HolaSpring/src/java/service/HolaService.java | b151877de5bf42e5b906ca6368402c8b0838c107 | []
| no_license | yueofdark/IngTarea5 | https://github.com/yueofdark/IngTarea5 | ea62484c719dfa71cfbd6cf2fd18be47bcad9fe4 | af4bfbf3b22fdc65e21cc2af8b3877911a7e7604 | refs/heads/master | 2020-12-30T09:26:19.556000 | 2013-10-18T05:19:15 | 2013-10-18T05:19:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package service;
/**
*
* @author nilver
*/
import java.sql.*;
import controller.Usuario;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class HolaService {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Usuario diHola(String nombreUsuario,String claveUsuario){
//abrir la Base de datos
//Aqui ya deberia conectarse bien, ya configure el dispacher-Servlet
//SOlo que no se como mostrarlo con el .query
// jdbcTemplate.query("select nombre,clave,tipo from usuario");
String sql = "SELECT * FROM USUARIO"
+ " WHERE (NOMBRE = nombreUsuario) AND (CLAVE = claveUsuario)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, nombreUsuario);
Usuario usuario = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
usuario = new Usuario(
rs.getString("NOMBRE"),
rs.getString("CLAVE"),
rs.getString("TIPO")
);
}
rs.close();
ps.close();
return usuario;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}
| UTF-8 | Java | 1,856 | java | HolaService.java | Java | [
{
"context": "he editor.\n */\npackage service;\n\n/**\n *\n * @author nilver\n */\nimport java.sql.*;\nimport controller.Usuario;",
"end": 142,
"score": 0.9986271262168884,
"start": 136,
"tag": "USERNAME",
"value": "nilver"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package service;
/**
*
* @author nilver
*/
import java.sql.*;
import controller.Usuario;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class HolaService {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Usuario diHola(String nombreUsuario,String claveUsuario){
//abrir la Base de datos
//Aqui ya deberia conectarse bien, ya configure el dispacher-Servlet
//SOlo que no se como mostrarlo con el .query
// jdbcTemplate.query("select nombre,clave,tipo from usuario");
String sql = "SELECT * FROM USUARIO"
+ " WHERE (NOMBRE = nombreUsuario) AND (CLAVE = claveUsuario)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, nombreUsuario);
Usuario usuario = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
usuario = new Usuario(
rs.getString("NOMBRE"),
rs.getString("CLAVE"),
rs.getString("TIPO")
);
}
rs.close();
ps.close();
return usuario;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}
| 1,856 | 0.617457 | 0.616918 | 77 | 23.103895 | 20.118212 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.51948 | false | false | 13 |
addf5e437fb4b041008a185f5b0fdd68796740f0 | 2,929,167,746,242 | aad22755d19873889cd7ed3801d97ed10e891920 | /demo/demo/GameDemo.java | ce3d513f0fbb7208cd44b559ac01d54ec6083d8a | [
"Apache-2.0"
]
| permissive | blernermhc/Bridge4Blind | https://github.com/blernermhc/Bridge4Blind | 40e92a396cdd9cf4e57fec6e623228898e7e292c | decc31913b98cb6b62fa8508292714acd9a3eb7c | refs/heads/master | 2020-05-17T15:19:03.869000 | 2018-03-07T02:06:56 | 2018-03-07T02:06:56 | 30,430,982 | 1 | 1 | Apache-2.0 | false | 2018-07-01T19:34:56 | 2015-02-06T20:12:54 | 2017-07-10T12:33:31 | 2018-07-01T19:34:56 | 60,816 | 1 | 0 | 0 | Java | false | null | package demo;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import controller.AntennaHandler;
import model.Card;
import model.CardDatabase;
import model.Direction;
import model.Game;
import model.Player;
import model.Suit;
import audio.AudioPlayer;
public class GameDemo extends JFrame{
//the game for the demo
private Game game;
//the hands in the demo game
private Player[] players;
//the deck of cards
private Deck deck;
//the position of the next sound to be played
private int nextSound = 0;
//the vector of sounds to play
private Vector<String> toPlay;
private AudioPlayer ap;
private Thread thread;
public GameDemo() throws UnknownHostException, IOException{
ap = new AudioPlayer();
//set the JFrame to exit the program on close
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
//create a JPanel to place inside the frame
JPanel demoPanel = new JPanel();
//create a JLabel to show that the demo is running
JLabel demoLabel = new JLabel("Demo running...");
//add the label to the panel
demoPanel.add(demoLabel);
//add the panel to the JFrame
this.add(demoPanel);
this.pack();
this.setVisible(true);
setFocusTraversalKeysEnabled(false);
//initialize the game
game = new Game(new AntennaHandler(new CardDatabase()), false);
//get the hands from the game
players = game.getPlayers();
//initialize the deck
deck = new Deck();
//set the declarer to be East
game.initPlayingPhase(Direction.EAST);
//deal cards to both the visually impaired player's hand and the dummy
//hand until both are full
while(!players[0].hasFullHand() && !players[game.getDummyPosition().ordinal()].hasFullHand()){
players[0].addCard(deck.draw());
players[game.getDummyPosition().ordinal()].addCard(deck.draw());
}
//add a KeyListener to this JFrame
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
//get the code from the key
int keyCode = e.getKeyCode();
System.out.println(keyCode);
//if the backspace key was pressed
if (keyCode == 8){
//read the visually impaired player's spades
System.out.println("Own spades:");
printCards(Suit.SPADES, players[0]);
readCards(Suit.SPADES, players[0], false);
//if the asterisk was pressed
} else if (keyCode == 106){
//read the visually impaired player's hearts
System.out.println("Own hearts:");
printCards(Suit.HEARTS, players[0]);
readCards(Suit.HEARTS, players[0], false);
//if the backslash was pressed
} else if (keyCode == 111){
//read the visually impaired player's diamonds
System.out.println("Own diamonds:");
printCards(Suit.DIAMONDS, players[0]);
readCards(Suit.DIAMONDS, players[0], false);
//if the tab key was pressed
} else if (keyCode == 9){
//read the visually impaired player's clubs
System.out.println("Own clubs:");
printCards(Suit.CLUBS, players[0]);
readCards(Suit.CLUBS, players[0], false);
//if the dash was pressed
} else if (keyCode == 109){
//read the dummy's spades
System.out.println("Dummy spades:");
printCards(Suit.SPADES, players[game.getDummyPosition().ordinal()]);
readCards(Suit.SPADES, players[game.getDummyPosition().ordinal()], true);
//if the 9 was pressed
} else if (keyCode == 105){
//read the dummy's hearts
System.out.println("Dummy hearts:");
printCards(Suit.HEARTS, players[game.getDummyPosition().ordinal()]);
readCards(Suit.HEARTS, players[game.getDummyPosition().ordinal()], true);
//if the 8 was pressed
} else if (keyCode == 104){
//read the dummy's diamonds
System.out.println("Dummy diamonds:");
printCards(Suit.DIAMONDS, players[game.getDummyPosition().ordinal()]);
readCards(Suit.DIAMONDS, players[game.getDummyPosition().ordinal()], true);
//if the 7 was pressed
} else if (keyCode == 103){
//read the dummy's clubs
System.out.println("Dummy clubs:");
printCards(Suit.CLUBS, players[game.getDummyPosition().ordinal()]);
readCards(Suit.CLUBS, players[game.getDummyPosition().ordinal()], true);
}
}
});
}
//Prints out a list of cards in the suit and hand specified.
private void printCards(Suit s, Player players2){
Iterator<Card> cardIter = players2.cards();
while (cardIter.hasNext()) {
//if this card is of the correct suit
Card c = cardIter.next();
if (c.getSuit() == s) {
//print its suit and rank
System.out.println(c.getRank() + " of " + c.getSuit());
}
}
}
//Audibly reads out the cards in the suit and hand specified.
private void readCards(Suit s, Player players2, boolean dummy){
//initialize the new toPlay vector
toPlay = new Vector<String>();
//add the appropriate ownership sound
if (dummy){
toPlay.add("/sounds/ownership/dummy2.WAV");
} else {
toPlay.add("/sounds/ownership/you2.WAV");
}
//add the appropriate number
int num = players2.getNumOfSuit(s);
if (num == 0){
toPlay.add("/sounds/cards/none.WAV");
} else {
toPlay.add("/sounds/bidding/" + num + ".WAV");
toPlay.add(s.getSound());
//walk over every card in the hand
Iterator<Card> cardIter = players2.cards();
while (cardIter.hasNext()) {
//if the card is of the correct suit
Card c = cardIter.next();
if (c.getSuit() == s){
//add its sound string to the vector
toPlay.add(c.getRank().getSound());
}
}
}
thread = new Thread(){
public void run(){
playNextSound();
}
};
// Barb commented out
// thread.start();
//
// try {
// Thread.sleep(100);
// }
// catch (InterruptedException e) {
// e.printStackTrace();
// }
while (true){
playNextSound();
do {
//System.out.println("playing");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (ap.isPlaying());
//if the next sound is outside the bounds of the vector
if (toPlay.size() == nextSound){
//reset the next sound
nextSound = 0;
break;
}
}
}
//Plays the next sound in line in the toPlay vector.
private void playNextSound(){
//initialize the audio player with the correct sound
ap.init (toPlay.get(nextSound));
//play the sound
ap.play();
//increment the next sound
nextSound++;
}
public static void main(String[] args){
try {
new GameDemo();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 7,087 | java | GameDemo.java | Java | [
{
"context": " run(){\n\t\t\t\tplayNextSound();\n\t\t\t}\n\t\t\t\n\t\t};\n\t\t\n\t\t// Barb commented out\n//\t\tthread.start();\n//\t\t\n//\t\ttry {\n",
"end": 5955,
"score": 0.6545077562332153,
"start": 5951,
"tag": "NAME",
"value": "Barb"
}
]
| null | []
| package demo;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import controller.AntennaHandler;
import model.Card;
import model.CardDatabase;
import model.Direction;
import model.Game;
import model.Player;
import model.Suit;
import audio.AudioPlayer;
public class GameDemo extends JFrame{
//the game for the demo
private Game game;
//the hands in the demo game
private Player[] players;
//the deck of cards
private Deck deck;
//the position of the next sound to be played
private int nextSound = 0;
//the vector of sounds to play
private Vector<String> toPlay;
private AudioPlayer ap;
private Thread thread;
public GameDemo() throws UnknownHostException, IOException{
ap = new AudioPlayer();
//set the JFrame to exit the program on close
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
//create a JPanel to place inside the frame
JPanel demoPanel = new JPanel();
//create a JLabel to show that the demo is running
JLabel demoLabel = new JLabel("Demo running...");
//add the label to the panel
demoPanel.add(demoLabel);
//add the panel to the JFrame
this.add(demoPanel);
this.pack();
this.setVisible(true);
setFocusTraversalKeysEnabled(false);
//initialize the game
game = new Game(new AntennaHandler(new CardDatabase()), false);
//get the hands from the game
players = game.getPlayers();
//initialize the deck
deck = new Deck();
//set the declarer to be East
game.initPlayingPhase(Direction.EAST);
//deal cards to both the visually impaired player's hand and the dummy
//hand until both are full
while(!players[0].hasFullHand() && !players[game.getDummyPosition().ordinal()].hasFullHand()){
players[0].addCard(deck.draw());
players[game.getDummyPosition().ordinal()].addCard(deck.draw());
}
//add a KeyListener to this JFrame
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
//get the code from the key
int keyCode = e.getKeyCode();
System.out.println(keyCode);
//if the backspace key was pressed
if (keyCode == 8){
//read the visually impaired player's spades
System.out.println("Own spades:");
printCards(Suit.SPADES, players[0]);
readCards(Suit.SPADES, players[0], false);
//if the asterisk was pressed
} else if (keyCode == 106){
//read the visually impaired player's hearts
System.out.println("Own hearts:");
printCards(Suit.HEARTS, players[0]);
readCards(Suit.HEARTS, players[0], false);
//if the backslash was pressed
} else if (keyCode == 111){
//read the visually impaired player's diamonds
System.out.println("Own diamonds:");
printCards(Suit.DIAMONDS, players[0]);
readCards(Suit.DIAMONDS, players[0], false);
//if the tab key was pressed
} else if (keyCode == 9){
//read the visually impaired player's clubs
System.out.println("Own clubs:");
printCards(Suit.CLUBS, players[0]);
readCards(Suit.CLUBS, players[0], false);
//if the dash was pressed
} else if (keyCode == 109){
//read the dummy's spades
System.out.println("Dummy spades:");
printCards(Suit.SPADES, players[game.getDummyPosition().ordinal()]);
readCards(Suit.SPADES, players[game.getDummyPosition().ordinal()], true);
//if the 9 was pressed
} else if (keyCode == 105){
//read the dummy's hearts
System.out.println("Dummy hearts:");
printCards(Suit.HEARTS, players[game.getDummyPosition().ordinal()]);
readCards(Suit.HEARTS, players[game.getDummyPosition().ordinal()], true);
//if the 8 was pressed
} else if (keyCode == 104){
//read the dummy's diamonds
System.out.println("Dummy diamonds:");
printCards(Suit.DIAMONDS, players[game.getDummyPosition().ordinal()]);
readCards(Suit.DIAMONDS, players[game.getDummyPosition().ordinal()], true);
//if the 7 was pressed
} else if (keyCode == 103){
//read the dummy's clubs
System.out.println("Dummy clubs:");
printCards(Suit.CLUBS, players[game.getDummyPosition().ordinal()]);
readCards(Suit.CLUBS, players[game.getDummyPosition().ordinal()], true);
}
}
});
}
//Prints out a list of cards in the suit and hand specified.
private void printCards(Suit s, Player players2){
Iterator<Card> cardIter = players2.cards();
while (cardIter.hasNext()) {
//if this card is of the correct suit
Card c = cardIter.next();
if (c.getSuit() == s) {
//print its suit and rank
System.out.println(c.getRank() + " of " + c.getSuit());
}
}
}
//Audibly reads out the cards in the suit and hand specified.
private void readCards(Suit s, Player players2, boolean dummy){
//initialize the new toPlay vector
toPlay = new Vector<String>();
//add the appropriate ownership sound
if (dummy){
toPlay.add("/sounds/ownership/dummy2.WAV");
} else {
toPlay.add("/sounds/ownership/you2.WAV");
}
//add the appropriate number
int num = players2.getNumOfSuit(s);
if (num == 0){
toPlay.add("/sounds/cards/none.WAV");
} else {
toPlay.add("/sounds/bidding/" + num + ".WAV");
toPlay.add(s.getSound());
//walk over every card in the hand
Iterator<Card> cardIter = players2.cards();
while (cardIter.hasNext()) {
//if the card is of the correct suit
Card c = cardIter.next();
if (c.getSuit() == s){
//add its sound string to the vector
toPlay.add(c.getRank().getSound());
}
}
}
thread = new Thread(){
public void run(){
playNextSound();
}
};
// Barb commented out
// thread.start();
//
// try {
// Thread.sleep(100);
// }
// catch (InterruptedException e) {
// e.printStackTrace();
// }
while (true){
playNextSound();
do {
//System.out.println("playing");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (ap.isPlaying());
//if the next sound is outside the bounds of the vector
if (toPlay.size() == nextSound){
//reset the next sound
nextSound = 0;
break;
}
}
}
//Plays the next sound in line in the toPlay vector.
private void playNextSound(){
//initialize the audio player with the correct sound
ap.init (toPlay.get(nextSound));
//play the sound
ap.play();
//increment the next sound
nextSound++;
}
public static void main(String[] args){
try {
new GameDemo();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 7,087 | 0.647241 | 0.640327 | 287 | 23.69338 | 19.751682 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.160279 | false | false | 13 |
2e814add6c30eb96e5c286f3061dbf07b1803dd9 | 1,219,770,764,535 | 1d5ea0a2c6e16ee4f2ea4debedd9867bb65d2464 | /MiniTalk/src/com/reyhoo/minitalk/P.java | 5506b05884b6a2dd65bdb7ac12c1fa109bea4350 | []
| no_license | reyhoo/socketDemo | https://github.com/reyhoo/socketDemo | 31ced6e161c5989a7ee2bea521422625eca9f12f | c681553798a6292ca336751d98f666c823a19050 | refs/heads/master | 2021-01-11T18:22:08.506000 | 2016-10-11T02:37:19 | 2016-10-11T02:37:19 | 69,629,513 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.reyhoo.minitalk;
abstract public class P {
public void hello(){
System.out.println(this+"::P Hello");
}
}
| UTF-8 | Java | 126 | java | P.java | Java | []
| null | []
| package com.reyhoo.minitalk;
abstract public class P {
public void hello(){
System.out.println(this+"::P Hello");
}
}
| 126 | 0.674603 | 0.674603 | 9 | 13 | 14.360439 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 13 |
2efd5eb200f3a5fafd6a30154613be0a487837b2 | 16,621,523,493,322 | adf226bdc1e7b6ec42f7bb292b2fb19f269227a3 | /Client/CommandIntepreter.java | 3b3219994550c4f5b3800f6302169be9e57ca5a5 | [
"MIT"
]
| permissive | Algy-Jr12/FTP-Protocol | https://github.com/Algy-Jr12/FTP-Protocol | 2312bab3853dcf92a030d89859a72bc5b2cc0d65 | 31a7bfdf129f6b71e5db70fa9e5d60bf9f717d9b | refs/heads/main | 2023-04-23T20:36:19.308000 | 2021-05-10T09:52:29 | 2021-05-10T09:52:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Client;
import Shared.Commands;
import Shared.Constants;
import Shared.InterfaceCounter;
import Shared.PathResolver;
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.rmi.RemoteException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CommandIntepreter {
private String fs;
private Path cwd;
private ArrayList<String> pathNames;
public boolean isOnServer;
private String ROOT_CLIENT = System.getProperty("user.dir") + "/FileSystem/ClientRoot";
private PrintWriter pw;
private Scanner sc;
private Socket socket;
private InterfaceCounter counter;
private String username;
private String hostForFileShare;
public CommandIntepreter(Socket socket, Scanner sc, PrintWriter pw, InterfaceCounter counter) {
this.socket = socket;
this.sc = sc;
this.pw = pw;
this.fs = "[" + Constants.CLIENT_SIDE.name() + "]~@localhost:/";
this.pathNames = new ArrayList<>();
this.cwd = Path.of(System.getProperty("user.dir") + "/FileSystem/ClientRoot");
this.isOnServer = true;
this.counter = counter;
this.hostForFileShare = "197.249.10.243"; // TODO this is the server IP
//197.249.10.243
}
public String intepretCommand(String command) throws FileNotFoundException {
String [] commandNdOptions = command.split(" ");
String option = "";
String action = commandNdOptions[0];
action = action.toUpperCase();
if(commandNdOptions.length > 1)
option = commandNdOptions[1];
switch (action) {
case Commands.CD: changeDirectory(option); return "";
case Commands.LS: return listDirectory(option);
case Commands.PWD: return getCurrentWorkingDirectory();
case Commands.MKDIR: return makeDirectory(option);
case Commands.GET: return downloadFile(command);
case Commands.PUT: return uploadFile(command);
case Commands.MVS: {this.isOnServer = true; return "";}
case Commands.MVC: {this.isOnServer = false; return "";}
case Commands.STAT: return printStat(command);
case Commands.EXIT: return this.exit(command);
default:
return "Client: Command Not Found";
}
}
//::>> COMMANDS
private String listDirectory(String path) {
ArrayList<String> pathNames = PathResolver.resolvePath(Path.of(ROOT_CLIENT), path, this.pathNames);
if (pathNames == null) {
return ":::> Error: Invalid Path For Operation";
}
Path pathToWalk = PathResolver.generatePath(Path.of(ROOT_CLIENT).toString(), pathNames);
String dirTree = "";
try(Stream<Path> walk = Files.walk(pathToWalk, PathResolver.DEFAULT_PATH_WALK_DEPTH)) {
List<String> result = walk.map(file -> {
Path rPath = file.relativize(Path.of(System.getProperty("user.dir")));
String fPath = "|-";
if (Files.isDirectory(file))
fPath += "-";
else
fPath += "---";
// //for(int i = 0; i < rPath.getNameCount(); i++) {
// if(Files.isDirectory(file))
// fPath += "-";
// else
// fPath += "--";
// //}
fPath += file.getFileName().toString();
return fPath;
}).collect(Collectors.toList());
for (String res: result) {
dirTree += res + "0-0";
}
} catch (NoSuchFileException ex) {
return ".";
} catch (IOException ex) {
ex.printStackTrace();
}
return dirTree;
}
private void changeDirectory(String path) {
ArrayList<String> newPathNames = PathResolver.resolvePath(Path.of(ROOT_CLIENT), path, this.pathNames);
if(newPathNames == null) {
System.out.println(":::> Error: Invalid Path For Operation");
return;
}
this.pathNames = new ArrayList<>(newPathNames);
this.cwd = PathResolver.generatePath(Path.of(ROOT_CLIENT).toString(), newPathNames);
}
private String makeDirectory(String folderName) {
if(folderName.isEmpty()) return ":::Error: No Folder Name Specified";
String folderPath = this.cwd.toString() + "/" + folderName;
ArrayList<String> newPathNames = PathResolver.resolvePath(this.cwd, folderPath, this.pathNames);
if(newPathNames != null) return "Folder Already Exists!" ;
File folder = new File(folderPath);
boolean hasCreated = folder.mkdir();
if(hasCreated) {
return "Folder Created Successfully!";
}
return "Could not create Folder!";
}
private String downloadFile(String command) {
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
String fileName;
int chunkSize, portForFileSharing;
this.pw.println(command);
this.pw.flush();
//::>> Receive chunkSize, portForFileSharing, FileName e FileSize
fileName = this.sc.nextLine();
if(fileName.equals(Constants.FILE_NOT_FOUND.name()))
return "::>> Error: File Not Found";
// Check if file Exists
char response = ' ';
File file = new File(cwd.toString() + "/" + fileName);
//System.out.println(file.exists());
if (file.exists()) {
System.out.println("A duplicate file was found \n Would you like to overwrite [y/n]");
Scanner scn = new Scanner(System.in);
response = scn.nextLine().charAt(0);
}
if (response == 'y' || response == ' ') {
long fileSize = Long.parseLong(this.sc.nextLine());
//::>> Receive Port Number to Send The File
portForFileSharing = Integer.parseInt(this.sc.nextLine());
chunkSize = Integer.parseInt(this.sc.nextLine());
Thread toWait = new Thread(new Runnable() {
@Override
public void run() {
try {
Socket socket = new Socket(hostForFileShare, portForFileSharing);
DataInputStream is = new DataInputStream(socket.getInputStream());
FileOutputStream fo = new FileOutputStream(cwd.toString() + "/" + fileName);
double readChunk = 0;
double percentage;
byte[] bytes;
while (!((bytes = is.readNBytes(chunkSize)).length == 0)) {
readChunk += bytes.length;
percentage = (readChunk / fileSize) * 100;
System.out.print("\r" + df.format(percentage) + "%");
fo.write(bytes);
}
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
try {
toWait.start();
toWait.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return "\nFile Download Complete!";
}
else{
// Ignore incoming info
sc.nextLine();
sc.nextLine();
sc.nextLine();
return "\nFile NOT downloaded";
}
}
private String uploadFile(String command) throws FileNotFoundException {
this.pw.println(command);
this.pw.flush();
int portForFileShare, chnkSize;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
ArrayList<String> pathNames = PathResolver.resolvePath(this.cwd, command.split(" ")[1], this.pathNames);
if (pathNames == null) {
this.pw.println(Constants.FILE_NOT_FOUND.name());
this.pw.flush();
return Constants.FILE_NOT_FOUND.name();
}
String filePath = PathResolver.generatePath(this.cwd.toString(), pathNames).toString();
File fileObj = new File(filePath);
FileInputStream fi = new FileInputStream(fileObj);
long fileSize = fileObj.length();
//::>> Send FileName and FileSize
this.pw.println(fileObj.getName());
this.pw.flush();
//::>> Receive Port Number to Send The File
portForFileShare = Integer.parseInt(this.sc.nextLine());
chnkSize = Integer.parseInt(this.sc.nextLine());
Thread toWait = new Thread(() -> {
try {
Socket socket = new Socket(hostForFileShare,portForFileShare);
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
double readChunk = 0;
double percentage;
int bytes;;
byte[] byteArray = new byte[chnkSize];
while ((bytes = fi.read(byteArray, 0, chnkSize)) != -1) {
//::>> Print Progress
readChunk += byteArray.length;
percentage = (readChunk / fileSize) * 100;
System.out.print("\r" + df.format(percentage) + "%");
os.write(byteArray);
os.flush();
}
System.out.println();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
});
try {
toWait.start();
toWait.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return "File Uploaded!";
}
private String exit(String command) {
this.pw.println(command);
this.pw.flush();
return "";
}
private String getCurrentWorkingDirectory() {
return this.cwd.toString();
}
private String printStat(String command) {
try {
return this.counter.statisticResume();
} catch (RemoteException e) {
return "::: Could not print statistics!";
}
}
//::>> Getter and Setters
public String getFs() {
return fs;
}
public ArrayList<String> getPathNames() {
return pathNames;
}
public void setMainPath() {
ArrayList<String> newPathNames = PathResolver.resolvePath(this.cwd, this.username, this.pathNames);
if(newPathNames == null)
makeDirectory(this.username);
this.cwd = Path.of(this.cwd.toString() + "/" + this.username);
ROOT_CLIENT = ROOT_CLIENT.toString() + "/" + this.username;
}
public void setUsername(String username) {
this.username = username;
}
}
| UTF-8 | Java | 11,460 | java | CommandIntepreter.java | Java | [
{
"context": "unter = counter;\n this.hostForFileShare = \"197.249.10.243\"; // TODO this is the server IP\n //197.249",
"end": 1393,
"score": 0.9997462034225464,
"start": 1379,
"tag": "IP_ADDRESS",
"value": "197.249.10.243"
},
{
"context": ".10.243\"; // TODO this is the server IP\n //197.249.10.243\n }\n\n public String intepretCommand(String c",
"end": 1450,
"score": 0.9997445344924927,
"start": 1436,
"tag": "IP_ADDRESS",
"value": "197.249.10.243"
},
{
"context": "sername(String username) {\n this.username = username;\n }\n}\n",
"end": 11450,
"score": 0.9221922159194946,
"start": 11442,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package Client;
import Shared.Commands;
import Shared.Constants;
import Shared.InterfaceCounter;
import Shared.PathResolver;
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.rmi.RemoteException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CommandIntepreter {
private String fs;
private Path cwd;
private ArrayList<String> pathNames;
public boolean isOnServer;
private String ROOT_CLIENT = System.getProperty("user.dir") + "/FileSystem/ClientRoot";
private PrintWriter pw;
private Scanner sc;
private Socket socket;
private InterfaceCounter counter;
private String username;
private String hostForFileShare;
public CommandIntepreter(Socket socket, Scanner sc, PrintWriter pw, InterfaceCounter counter) {
this.socket = socket;
this.sc = sc;
this.pw = pw;
this.fs = "[" + Constants.CLIENT_SIDE.name() + "]~@localhost:/";
this.pathNames = new ArrayList<>();
this.cwd = Path.of(System.getProperty("user.dir") + "/FileSystem/ClientRoot");
this.isOnServer = true;
this.counter = counter;
this.hostForFileShare = "192.168.3.11"; // TODO this is the server IP
//192.168.3.11
}
public String intepretCommand(String command) throws FileNotFoundException {
String [] commandNdOptions = command.split(" ");
String option = "";
String action = commandNdOptions[0];
action = action.toUpperCase();
if(commandNdOptions.length > 1)
option = commandNdOptions[1];
switch (action) {
case Commands.CD: changeDirectory(option); return "";
case Commands.LS: return listDirectory(option);
case Commands.PWD: return getCurrentWorkingDirectory();
case Commands.MKDIR: return makeDirectory(option);
case Commands.GET: return downloadFile(command);
case Commands.PUT: return uploadFile(command);
case Commands.MVS: {this.isOnServer = true; return "";}
case Commands.MVC: {this.isOnServer = false; return "";}
case Commands.STAT: return printStat(command);
case Commands.EXIT: return this.exit(command);
default:
return "Client: Command Not Found";
}
}
//::>> COMMANDS
private String listDirectory(String path) {
ArrayList<String> pathNames = PathResolver.resolvePath(Path.of(ROOT_CLIENT), path, this.pathNames);
if (pathNames == null) {
return ":::> Error: Invalid Path For Operation";
}
Path pathToWalk = PathResolver.generatePath(Path.of(ROOT_CLIENT).toString(), pathNames);
String dirTree = "";
try(Stream<Path> walk = Files.walk(pathToWalk, PathResolver.DEFAULT_PATH_WALK_DEPTH)) {
List<String> result = walk.map(file -> {
Path rPath = file.relativize(Path.of(System.getProperty("user.dir")));
String fPath = "|-";
if (Files.isDirectory(file))
fPath += "-";
else
fPath += "---";
// //for(int i = 0; i < rPath.getNameCount(); i++) {
// if(Files.isDirectory(file))
// fPath += "-";
// else
// fPath += "--";
// //}
fPath += file.getFileName().toString();
return fPath;
}).collect(Collectors.toList());
for (String res: result) {
dirTree += res + "0-0";
}
} catch (NoSuchFileException ex) {
return ".";
} catch (IOException ex) {
ex.printStackTrace();
}
return dirTree;
}
private void changeDirectory(String path) {
ArrayList<String> newPathNames = PathResolver.resolvePath(Path.of(ROOT_CLIENT), path, this.pathNames);
if(newPathNames == null) {
System.out.println(":::> Error: Invalid Path For Operation");
return;
}
this.pathNames = new ArrayList<>(newPathNames);
this.cwd = PathResolver.generatePath(Path.of(ROOT_CLIENT).toString(), newPathNames);
}
private String makeDirectory(String folderName) {
if(folderName.isEmpty()) return ":::Error: No Folder Name Specified";
String folderPath = this.cwd.toString() + "/" + folderName;
ArrayList<String> newPathNames = PathResolver.resolvePath(this.cwd, folderPath, this.pathNames);
if(newPathNames != null) return "Folder Already Exists!" ;
File folder = new File(folderPath);
boolean hasCreated = folder.mkdir();
if(hasCreated) {
return "Folder Created Successfully!";
}
return "Could not create Folder!";
}
private String downloadFile(String command) {
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
String fileName;
int chunkSize, portForFileSharing;
this.pw.println(command);
this.pw.flush();
//::>> Receive chunkSize, portForFileSharing, FileName e FileSize
fileName = this.sc.nextLine();
if(fileName.equals(Constants.FILE_NOT_FOUND.name()))
return "::>> Error: File Not Found";
// Check if file Exists
char response = ' ';
File file = new File(cwd.toString() + "/" + fileName);
//System.out.println(file.exists());
if (file.exists()) {
System.out.println("A duplicate file was found \n Would you like to overwrite [y/n]");
Scanner scn = new Scanner(System.in);
response = scn.nextLine().charAt(0);
}
if (response == 'y' || response == ' ') {
long fileSize = Long.parseLong(this.sc.nextLine());
//::>> Receive Port Number to Send The File
portForFileSharing = Integer.parseInt(this.sc.nextLine());
chunkSize = Integer.parseInt(this.sc.nextLine());
Thread toWait = new Thread(new Runnable() {
@Override
public void run() {
try {
Socket socket = new Socket(hostForFileShare, portForFileSharing);
DataInputStream is = new DataInputStream(socket.getInputStream());
FileOutputStream fo = new FileOutputStream(cwd.toString() + "/" + fileName);
double readChunk = 0;
double percentage;
byte[] bytes;
while (!((bytes = is.readNBytes(chunkSize)).length == 0)) {
readChunk += bytes.length;
percentage = (readChunk / fileSize) * 100;
System.out.print("\r" + df.format(percentage) + "%");
fo.write(bytes);
}
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
try {
toWait.start();
toWait.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return "\nFile Download Complete!";
}
else{
// Ignore incoming info
sc.nextLine();
sc.nextLine();
sc.nextLine();
return "\nFile NOT downloaded";
}
}
private String uploadFile(String command) throws FileNotFoundException {
this.pw.println(command);
this.pw.flush();
int portForFileShare, chnkSize;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
ArrayList<String> pathNames = PathResolver.resolvePath(this.cwd, command.split(" ")[1], this.pathNames);
if (pathNames == null) {
this.pw.println(Constants.FILE_NOT_FOUND.name());
this.pw.flush();
return Constants.FILE_NOT_FOUND.name();
}
String filePath = PathResolver.generatePath(this.cwd.toString(), pathNames).toString();
File fileObj = new File(filePath);
FileInputStream fi = new FileInputStream(fileObj);
long fileSize = fileObj.length();
//::>> Send FileName and FileSize
this.pw.println(fileObj.getName());
this.pw.flush();
//::>> Receive Port Number to Send The File
portForFileShare = Integer.parseInt(this.sc.nextLine());
chnkSize = Integer.parseInt(this.sc.nextLine());
Thread toWait = new Thread(() -> {
try {
Socket socket = new Socket(hostForFileShare,portForFileShare);
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
double readChunk = 0;
double percentage;
int bytes;;
byte[] byteArray = new byte[chnkSize];
while ((bytes = fi.read(byteArray, 0, chnkSize)) != -1) {
//::>> Print Progress
readChunk += byteArray.length;
percentage = (readChunk / fileSize) * 100;
System.out.print("\r" + df.format(percentage) + "%");
os.write(byteArray);
os.flush();
}
System.out.println();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
});
try {
toWait.start();
toWait.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return "File Uploaded!";
}
private String exit(String command) {
this.pw.println(command);
this.pw.flush();
return "";
}
private String getCurrentWorkingDirectory() {
return this.cwd.toString();
}
private String printStat(String command) {
try {
return this.counter.statisticResume();
} catch (RemoteException e) {
return "::: Could not print statistics!";
}
}
//::>> Getter and Setters
public String getFs() {
return fs;
}
public ArrayList<String> getPathNames() {
return pathNames;
}
public void setMainPath() {
ArrayList<String> newPathNames = PathResolver.resolvePath(this.cwd, this.username, this.pathNames);
if(newPathNames == null)
makeDirectory(this.username);
this.cwd = Path.of(this.cwd.toString() + "/" + this.username);
ROOT_CLIENT = ROOT_CLIENT.toString() + "/" + this.username;
}
public void setUsername(String username) {
this.username = username;
}
}
| 11,456 | 0.54171 | 0.537958 | 333 | 33.414413 | 26.80229 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615616 | false | false | 13 |
d81941ce4f7c59a82f587a7f116589620b8773d4 | 19,868,518,767,323 | 8d3d8c63fe88ee06e067d05653f3a6de57c6c703 | /src/com/zrgk/test/TestProcedure.java | dc488b134145d95b9462864f191a4da1d60bfb5e | []
| no_license | lsx1014426766/hi1112 | https://github.com/lsx1014426766/hi1112 | 69ca1d1810d68aa27867eb7a02830caa617a4a77 | ab33e3ec429ca20c05df06e8a4ee3b9e05216ad6 | refs/heads/master | 2020-12-30T14:20:00.150000 | 2017-05-22T05:37:08 | 2017-05-22T05:37:08 | 91,310,044 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zrgk.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import oracle.jdbc.OracleTypes;
import org.hibernate.Query;
import org.hibernate.Session;
import com.zrgk.entity.Emp;
import com.zrgk.util.HibernateUtil1;
//命名sql调用存储过程
public class TestProcedure {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
Session session = HibernateUtil1.getSession();
Query query = session.getNamedQuery("getListProc");
// 给问号设置值
query.setInteger(0, 10);
//query.setParameter(i, list.get(i));
//query.executeUpdate(); //增删改
// 通过CallableStatement调用存储过程
// Connection conn = session.connection();
// String sql ="{call xxxx(?,?)}";
// CallableStatement call = conn.prepareCall(sql);
// call.setObject(1,xxxx);
// call.registerOutParameter(1, Types.INTEGER);
// call.registerOutParameter(2, OracleTypes.CURSOR);
List<Emp> list = query.list();
for(Emp e:list){
System.out.println(e.getEname());
}
session.close();
}
}
| GB18030 | Java | 1,144 | java | TestProcedure.java | Java | []
| null | []
| package com.zrgk.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import oracle.jdbc.OracleTypes;
import org.hibernate.Query;
import org.hibernate.Session;
import com.zrgk.entity.Emp;
import com.zrgk.util.HibernateUtil1;
//命名sql调用存储过程
public class TestProcedure {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
Session session = HibernateUtil1.getSession();
Query query = session.getNamedQuery("getListProc");
// 给问号设置值
query.setInteger(0, 10);
//query.setParameter(i, list.get(i));
//query.executeUpdate(); //增删改
// 通过CallableStatement调用存储过程
// Connection conn = session.connection();
// String sql ="{call xxxx(?,?)}";
// CallableStatement call = conn.prepareCall(sql);
// call.setObject(1,xxxx);
// call.registerOutParameter(1, Types.INTEGER);
// call.registerOutParameter(2, OracleTypes.CURSOR);
List<Emp> list = query.list();
for(Emp e:list){
System.out.println(e.getEname());
}
session.close();
}
}
| 1,144 | 0.725777 | 0.718464 | 45 | 23.311111 | 17.321564 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 13 |
22940ecabc01978b6448505a789d8cd54b3f6297 | 3,126,736,234,658 | 82c48189a55a835ec62c34c8feb667c7b7f30c3b | /src/main/java/com/company/model/BowlingRoll.java | 9590759b778e6e9757f5754eab382e8a1a27cf26 | []
| no_license | hedgehog1833/it-bowling-game | https://github.com/hedgehog1833/it-bowling-game | 95a4387781087c5d6d97e7c65a2074e00ec0090e | f7680e42cd5841c093f8b7b358c3895b17d9c807 | refs/heads/master | 2020-06-29T09:22:24.145000 | 2019-12-12T22:00:11 | 2019-12-12T22:00:11 | 200,497,659 | 0 | 0 | null | false | 2020-01-06T22:17:54 | 2019-08-04T13:42:28 | 2019-12-12T22:00:15 | 2019-12-13T06:46:51 | 70 | 0 | 0 | 0 | Java | false | false | package com.company.model;
public class BowlingRoll {
private final int pinsStandingAfterRoll;
private final int pinsHit;
public BowlingRoll(int pinsStandingBeforeRoll, int pinsHit) {
this.pinsHit = pinsHit;
pinsStandingAfterRoll = pinsStandingBeforeRoll - pinsHit;
}
public int getPinsStandingAfterRoll() {
return pinsStandingAfterRoll;
}
public int getPinsHit() {
return pinsHit;
}
@Override
public String toString() {
return "Roll: Pins standing before roll = " + (pinsStandingAfterRoll + pinsHit) + "; Pins hit = " + pinsHit + "; Pins standing after roll = " + pinsStandingAfterRoll;
}
}
| UTF-8 | Java | 639 | java | BowlingRoll.java | Java | []
| null | []
| package com.company.model;
public class BowlingRoll {
private final int pinsStandingAfterRoll;
private final int pinsHit;
public BowlingRoll(int pinsStandingBeforeRoll, int pinsHit) {
this.pinsHit = pinsHit;
pinsStandingAfterRoll = pinsStandingBeforeRoll - pinsHit;
}
public int getPinsStandingAfterRoll() {
return pinsStandingAfterRoll;
}
public int getPinsHit() {
return pinsHit;
}
@Override
public String toString() {
return "Roll: Pins standing before roll = " + (pinsStandingAfterRoll + pinsHit) + "; Pins hit = " + pinsHit + "; Pins standing after roll = " + pinsStandingAfterRoll;
}
}
| 639 | 0.716745 | 0.716745 | 24 | 25.625 | 35.509167 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 13 |
7d593eadb7ee1919bbd7f5e60f2f53c3a84e567e | 26,998,164,467,062 | d7de2533d599373236f9de9cb47dce02ef2de8c5 | /src/main/java/com/zeng/typeliteral/Service.java | 0fad35f4432278ef598c131e156365fc4d7c3343 | []
| no_license | zuifengke/hr-guice | https://github.com/zuifengke/hr-guice | 3fa634befbd153a54b0182608d5310f0a2d23fe5 | aafde41af188406fe97fc212ac824a8aeb56c263 | refs/heads/master | 2021-01-10T01:51:40.538000 | 2016-04-08T10:12:53 | 2016-04-08T10:12:53 | 55,769,971 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zeng.typeliteral;
public interface Service {
public void test();
}
| UTF-8 | Java | 84 | java | Service.java | Java | []
| null | []
| package com.zeng.typeliteral;
public interface Service {
public void test();
}
| 84 | 0.72619 | 0.72619 | 5 | 15.8 | 12.63962 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
12e97f71263741ceb8fb0bbae414a0a4d9c4f9ef | 32,392,643,412,980 | a5c406e0a26f76192b0d37f94dd480d1d8c79981 | /jsslnyxxh/src/main/java/com/jsslnyxxh/app/web/biz/HpwlmUploadController.java | 121ee8148d50399b49f8456d5b6a74f4461b775c | []
| no_license | lejch/jsslnyxxh | https://github.com/lejch/jsslnyxxh | 078a1fa9fa2879509a92390f451f77f48b553644 | 84f8f59c0062291cca32acb4f42e9140404c0fba | refs/heads/master | 2023-04-20T15:54:36.918000 | 2021-05-07T10:46:35 | 2021-05-07T10:46:35 | 365,201,191 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jsslnyxxh.app.web.biz;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jsslnyxxh.common.util.EnDecodeUtil;
import com.jsslnyxxh.common.util.PropertiesUtil;
import com.jsslnyxxh.common.util.UUIDGenerator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("/HpwlmUp")
public class HpwlmUploadController {
@RequestMapping(value="/uploadImg", method = RequestMethod.POST)
@ResponseBody
public Object uploadImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String picPath = "";
String newPath = "";
JSONObject result = null;
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("upfile");
String fileType = ".gif,.png,.jpg,.jpeg,.bmp";
if (!file.isEmpty()) {
String rls = "SUCCESS";
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String newFileName = null;
if(fileType.indexOf(suffix.toLowerCase())>0){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Random ran = new Random();
newFileName = formatter.format(new Date())
+ String.valueOf(ran.nextInt(100000)) + suffix;
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/")+"upload/";
newPath = newFileName;
File dtoryFile = new File(filePath);
if(!dtoryFile.exists() && !dtoryFile.isDirectory())
{
dtoryFile.mkdirs();
}
// 转存文件
file.transferTo(new File(filePath+newFileName));
} catch (Exception e) {
e.printStackTrace();
rls = "图片上传异常";
}
}else{
rls = "不允许的文件格式";
}
result = new JSONObject();
result.put("name", newFileName);
result.put("originalName", fileName);
result.put("size", file.getSize());
result.put("state", rls);
result.put("type", suffix);
result.put("url", newPath);
System.out.println(result);
}
return EnDecodeUtil.enCodeReturns2UTF8(result.toString());
}
@RequestMapping(value="/img_save_to_file", method = RequestMethod.POST)
@ResponseBody
public Object img_save_to_file(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String picPath = "";
String newPath = "";
String filePath = null;
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("img");
String fileType = ".gif,.png,.jpg,.jpeg,.bmp";
JSONObject result = null;
if (!file.isEmpty()) {
String rls = "success";
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String newFileName = null;
if(fileType.indexOf(suffix.toLowerCase())>0){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Random ran = new Random();
newFileName = formatter.format(new Date())
+ String.valueOf(ran.nextInt(100000)) + suffix;
try {
// 文件保存路径
filePath = request.getSession().getServletContext().getRealPath("/")+"upload/";
newPath = newFileName;
File dtoryFile = new File(filePath);
if(!dtoryFile.exists() && !dtoryFile.isDirectory())
{
dtoryFile.mkdirs();
}
// 转存文件
file.transferTo(new File(filePath+newFileName));
} catch (Exception e) {
e.printStackTrace();
result = new JSONObject();
result.put("status", "error");
result.put("message", "图片上传异常");
}
}else{
result = new JSONObject();
result.put("status", "error");
result.put("message", "不允许的文件格式");
}
if(result==null){
File picture = new File(filePath+newFileName);
BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture));
result = new JSONObject();
result.put("status", "success");
result.put("url", request.getContextPath()+"/upload/"+newFileName);
result.put("width", sourceImg.getWidth());
result.put("height", sourceImg.getHeight());
}
System.out.println(result);
}
return result;
}
@RequestMapping(value="/img_crop_to_file", method = RequestMethod.POST)
@ResponseBody
public Object img_crop_to_file(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
JSONObject result = new JSONObject();
String imgUrl = request.getParameter("imgUrl");
String imgInitW = request.getParameter("imgInitW");
String imgInitH = request.getParameter("imgInitH");
String imgW = request.getParameter("imgW");
String imgH = request.getParameter("imgH");
Double imgWd = Double.valueOf(imgW);
Double imgHd = Double.valueOf(imgH);
int imgWi = imgWd.intValue();
int imgHi = imgHd.intValue();
int imgX1 = Integer.parseInt(request.getParameter("imgX1"));
int imgY1 = Integer.parseInt(request.getParameter("imgY1"));
int cropW = Integer.parseInt(request.getParameter("cropW"));
int cropH = Integer.parseInt(request.getParameter("cropH"));
String urlFix = imgUrl.substring(0,imgUrl.lastIndexOf("/"));
String fileName = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
String houzhui = imgUrl.substring(imgUrl.lastIndexOf("."));
String houzhuixx = imgUrl.substring(imgUrl.lastIndexOf(".")+1).toLowerCase();
String filePath = request.getSession().getServletContext().getRealPath("/")+"upload/";
String newFileName = fileName.replaceAll(houzhui, "_scale"+houzhui);
String newCropFileName = fileName.replaceAll(houzhui, "_crop"+houzhui);
try{
ImgUtils.scale(filePath+fileName, filePath+newFileName, imgHi,imgWi, false);
BufferedImage bufferedimage = ImageIO.read(new File(filePath+newFileName));
bufferedimage = ImgUtils.cropImage(bufferedimage, imgX1, imgY1, imgX1+cropW, imgY1+cropH);
ImageIO.write(bufferedimage, houzhuixx, new File(filePath+newCropFileName));
result.put("status", "success");
result.put("url", urlFix+"/"+newCropFileName);
}catch(Exception e){
e.printStackTrace();
result.put("status", "error");
result.put("message","裁剪图片错误,请稍后重试!");
}
System.out.println(result);
return result;
}
} | UTF-8 | Java | 8,627 | java | HpwlmUploadController.java | Java | []
| null | []
| package com.jsslnyxxh.app.web.biz;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jsslnyxxh.common.util.EnDecodeUtil;
import com.jsslnyxxh.common.util.PropertiesUtil;
import com.jsslnyxxh.common.util.UUIDGenerator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("/HpwlmUp")
public class HpwlmUploadController {
@RequestMapping(value="/uploadImg", method = RequestMethod.POST)
@ResponseBody
public Object uploadImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String picPath = "";
String newPath = "";
JSONObject result = null;
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("upfile");
String fileType = ".gif,.png,.jpg,.jpeg,.bmp";
if (!file.isEmpty()) {
String rls = "SUCCESS";
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String newFileName = null;
if(fileType.indexOf(suffix.toLowerCase())>0){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Random ran = new Random();
newFileName = formatter.format(new Date())
+ String.valueOf(ran.nextInt(100000)) + suffix;
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/")+"upload/";
newPath = newFileName;
File dtoryFile = new File(filePath);
if(!dtoryFile.exists() && !dtoryFile.isDirectory())
{
dtoryFile.mkdirs();
}
// 转存文件
file.transferTo(new File(filePath+newFileName));
} catch (Exception e) {
e.printStackTrace();
rls = "图片上传异常";
}
}else{
rls = "不允许的文件格式";
}
result = new JSONObject();
result.put("name", newFileName);
result.put("originalName", fileName);
result.put("size", file.getSize());
result.put("state", rls);
result.put("type", suffix);
result.put("url", newPath);
System.out.println(result);
}
return EnDecodeUtil.enCodeReturns2UTF8(result.toString());
}
@RequestMapping(value="/img_save_to_file", method = RequestMethod.POST)
@ResponseBody
public Object img_save_to_file(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String picPath = "";
String newPath = "";
String filePath = null;
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("img");
String fileType = ".gif,.png,.jpg,.jpeg,.bmp";
JSONObject result = null;
if (!file.isEmpty()) {
String rls = "success";
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String newFileName = null;
if(fileType.indexOf(suffix.toLowerCase())>0){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Random ran = new Random();
newFileName = formatter.format(new Date())
+ String.valueOf(ran.nextInt(100000)) + suffix;
try {
// 文件保存路径
filePath = request.getSession().getServletContext().getRealPath("/")+"upload/";
newPath = newFileName;
File dtoryFile = new File(filePath);
if(!dtoryFile.exists() && !dtoryFile.isDirectory())
{
dtoryFile.mkdirs();
}
// 转存文件
file.transferTo(new File(filePath+newFileName));
} catch (Exception e) {
e.printStackTrace();
result = new JSONObject();
result.put("status", "error");
result.put("message", "图片上传异常");
}
}else{
result = new JSONObject();
result.put("status", "error");
result.put("message", "不允许的文件格式");
}
if(result==null){
File picture = new File(filePath+newFileName);
BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture));
result = new JSONObject();
result.put("status", "success");
result.put("url", request.getContextPath()+"/upload/"+newFileName);
result.put("width", sourceImg.getWidth());
result.put("height", sourceImg.getHeight());
}
System.out.println(result);
}
return result;
}
@RequestMapping(value="/img_crop_to_file", method = RequestMethod.POST)
@ResponseBody
public Object img_crop_to_file(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
JSONObject result = new JSONObject();
String imgUrl = request.getParameter("imgUrl");
String imgInitW = request.getParameter("imgInitW");
String imgInitH = request.getParameter("imgInitH");
String imgW = request.getParameter("imgW");
String imgH = request.getParameter("imgH");
Double imgWd = Double.valueOf(imgW);
Double imgHd = Double.valueOf(imgH);
int imgWi = imgWd.intValue();
int imgHi = imgHd.intValue();
int imgX1 = Integer.parseInt(request.getParameter("imgX1"));
int imgY1 = Integer.parseInt(request.getParameter("imgY1"));
int cropW = Integer.parseInt(request.getParameter("cropW"));
int cropH = Integer.parseInt(request.getParameter("cropH"));
String urlFix = imgUrl.substring(0,imgUrl.lastIndexOf("/"));
String fileName = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
String houzhui = imgUrl.substring(imgUrl.lastIndexOf("."));
String houzhuixx = imgUrl.substring(imgUrl.lastIndexOf(".")+1).toLowerCase();
String filePath = request.getSession().getServletContext().getRealPath("/")+"upload/";
String newFileName = fileName.replaceAll(houzhui, "_scale"+houzhui);
String newCropFileName = fileName.replaceAll(houzhui, "_crop"+houzhui);
try{
ImgUtils.scale(filePath+fileName, filePath+newFileName, imgHi,imgWi, false);
BufferedImage bufferedimage = ImageIO.read(new File(filePath+newFileName));
bufferedimage = ImgUtils.cropImage(bufferedimage, imgX1, imgY1, imgX1+cropW, imgY1+cropH);
ImageIO.write(bufferedimage, houzhuixx, new File(filePath+newCropFileName));
result.put("status", "success");
result.put("url", urlFix+"/"+newCropFileName);
}catch(Exception e){
e.printStackTrace();
result.put("status", "error");
result.put("message","裁剪图片错误,请稍后重试!");
}
System.out.println(result);
return result;
}
} | 8,627 | 0.614462 | 0.610582 | 228 | 35.311405 | 26.17107 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.008772 | false | false | 13 |
5eb4eb817cf8e13347a5e87cb7cf50849629ae79 | 32,392,643,414,396 | 5837685f9f27a871fa51c1134df6d0030b48dbf0 | /android-viewfinder-test/src/se/birkler/opencvcalibrate/opencvutil/PreviewView.java | 3dd3c8174f5c6380a100f33f89ff05479bcabf69 | []
| no_license | solomonnsumba/android-camera-tests | https://github.com/solomonnsumba/android-camera-tests | 755030b8223a63c97f309860bdeca0eae351f802 | e3147d0da5011792dc907de80926587089ca89cd | refs/heads/master | 2021-01-18T06:57:13.544000 | 2014-01-15T22:39:22 | 2014-01-15T22:39:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package se.birkler.opencvcalibrate.opencvutil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import se.birkler.opencvcalibrate.util.XLog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
/**
* A simple wrapper around a Camera and a SurfaceView that renders a centered preview of the Camera
* to the surface. We need to center the SurfaceView because not all devices have cameras that
* support preview sizes at the same aspect ratio as the device's display.
*
* Startup states:
* onLayout (with vga size)
*
*
*/
public class PreviewView extends RelativeLayout implements Runnable, Camera.PictureCallback, Camera.ShutterCallback, SurfaceTextureListener
{
private static final int CAMERA_INIT_DELAY = 500;
private Rect mSurfaceViewVisibleRect = new Rect();
public interface OpenCVProcessor {
void processFrame(Canvas canvas, int width, int height, Mat yuvData, Mat grayData);
}
public interface PictureCallback {
public void onShutter();
public void onPictureTaken(byte[] data);
}
static final int PREFERRED_HEIGHT = 480;
static final int PREFERRED_WIDTH = 640;
private static final int INIT_MESSAGE_ID = 0;
TextureView mSurfaceView;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
private OpenCVProcessor mProcessor;
private float mFieldOfView = -1;
private FrameLayout mResultSurfaceViewOwner;
private TextureView mResultSurfaceView;
private ArrayBlockingQueue<PreviewBuffer> mPreviewFrames = new ArrayBlockingQueue<PreviewBuffer>(3);
private boolean mThreadRun;
private int frameCount;
private long prevTime;
private Thread mThread;
class PreviewBuffer {
public ByteBuffer mPreviewCallbackBuffer;
public Mat mYuv;
public Mat mGraySubmat;
public PreviewBuffer(int width, int height, int format) {
int bytesneeded = height * width * ImageFormat.getBitsPerPixel(format) / 8;
mPreviewCallbackBuffer = ByteBuffer.allocateDirect(bytesneeded);
mYuv = new MatByteBufferWrapper(mPreviewCallbackBuffer,height + height / 2, width, CvType.CV_8UC1);
mGraySubmat = mYuv.submat(0, height, 0, width);
}
}
PreviewBuffer mPreviewBuffer1;
Handler mInitHandler;
PictureCallback mPictureCallback = null;
private AudioManager mAudioManager;
private Paint mPreviewFramePaint;
private PreviewBuffer mPreviewBuffer2;
public PreviewView(Context context, AttributeSet attr) {
super(context,attr);
mSurfaceView = new TextureView(context);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mSurfaceView.setLayoutParams(lp);
mSurfaceView.setOpaque(true);
mSurfaceView.setSurfaceTextureListener(this);
addView(mSurfaceView);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
//mCameraHolder = mSurfaceView.getHolder();
//mCameraHolder.addCallback(this);
//mCameraHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mResultSurfaceView = new TextureView(context);
mResultSurfaceView.setOpaque(false);
lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mResultSurfaceView.setLayoutParams(lp);
mResultSurfaceView.setSurfaceTextureListener(this);
mResultSurfaceViewOwner = new FrameLayout(context);
lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mResultSurfaceViewOwner.setLayoutParams(lp);
mResultSurfaceViewOwner.addView(mResultSurfaceView);
addView(mResultSurfaceViewOwner);
//mResultSurfaceView.setZOrderOnTop(true);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
//mResultHolder = mResultSurfaceView.getHolder();
//mResultHolder.setFormat(PixelFormat.TRANSPARENT);
//mResultHolder.addCallback(this);
setWillNotDraw(false);
mInitHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
initCameraAndStartPreview();
}
};
mThread = new Thread(this);
mThread.setPriority(Thread.MIN_PRIORITY+1);
mThread.setName("Processing thread");
//mMediaPlayer = MediaPlayer.create(context,R.raw.shutter_sound);
//mMediaPlayer.prepare();
mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
mPreviewFramePaint = new Paint();
mPreviewFramePaint.setColor(Color.CYAN);
mPreviewFramePaint.setAlpha(128);
mPreviewFramePaint.setStrokeWidth((float) 3.0);
}
@Override
public void onFinishInflate () {
super.onFinishInflate();
}
//@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = Integer.MAX_VALUE;
int height = Integer.MAX_VALUE;
int mostWidth = Integer.MAX_VALUE;
int mostHeight = Integer.MAX_VALUE;
final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
//if (widthSpecMode == MeasureSpec.UNSPECIFIED) width = Integer.MAX_VALUE;
//if (heightSpecMode == MeasureSpec.UNSPECIFIED) height = Integer.MAX_VALUE;
if (widthSpecMode == MeasureSpec.EXACTLY && heightMeasureSpec == MeasureSpec.EXACTLY) {
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
} else if (widthSpecMode == MeasureSpec.UNSPECIFIED && heightMeasureSpec == MeasureSpec.UNSPECIFIED) {
}
else {
double aspect = 640.0 / 480.0;
if (widthSpecMode == MeasureSpec.EXACTLY || widthSpecMode == MeasureSpec.AT_MOST) {
mostWidth = MeasureSpec.getSize(widthMeasureSpec);
}
if (heightSpecMode == MeasureSpec.EXACTLY || heightSpecMode == MeasureSpec.AT_MOST) {
mostHeight = MeasureSpec.getSize(heightMeasureSpec);
}
if ((double)mostWidth > (double)mostHeight * aspect) {
width = (int) ((double)mostHeight * aspect);
height = mostHeight;
} else {
width = mostWidth;
height = (int) ((double)mostWidth / aspect);
}
}
/*
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
if (mPreviewSize != null) {
setMeasuredDimension(mPreviewSize.width, mPreviewSize.height);
}
else {
setMeasuredDimension(PREFERRED_WIDTH,PREFERRED_HEIGHT);
}*/
setMeasuredDimension(width,height);
mResultSurfaceView.measure(MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY));
mResultSurfaceViewOwner.measure(MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY));
//final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
//final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
//setMeasuredDimension(width, height);
//tMeasuredDimension(mPreviewSize.width, mPreviewSize.height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed) {
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
l = (width - scaledChildWidth) / 2;
t = 0;
r = (width + scaledChildWidth) / 2;
b = height;
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
l = 0;
t = (height - scaledChildHeight) / 2;
r = width;
b = (height + scaledChildHeight) / 2;
}
super.onLayout(changed,l,t,r,b);
mSurfaceView.layout(l, t,r, b);
mResultSurfaceViewOwner.layout(l, t,r, b);
//mResultSurfaceView.layout(l, t,r, b);
float scale;
int w = 640;
int h = 480;
if (mPreviewSize != null) {
scale = (float)(b-t) / (float)mPreviewSize.height;
w = mPreviewSize.width;
h = mPreviewSize.height;
} else {
scale = (float)(b-t) / 480;
}
//In the middle
mResultSurfaceView.layout((l+r-w) / 2, (t+b-h) / 2, (l+r+w) / 2, (t+b+h) / 2);
//Matrix transform = new Matrix();
//transform.preScale(scale, scale);
//mResultSurfaceView.setTransform(transform);
mResultSurfaceViewOwner.setScaleX(scale);
mResultSurfaceViewOwner.setScaleY(scale);
mSurfaceView.getLocalVisibleRect(mSurfaceViewVisibleRect);
XLog.d("surfaceView:" + mSurfaceView.toString() + mSurfaceViewVisibleRect.toString());
}
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
// The Surface has been created, acquire the camera and tell it where to draw.
if (surface == mSurfaceView.getSurfaceTexture()) {
//Debug.startMethodTracing("opencvtrace_viewfinder");
mThreadRun = true;
mThread.start();
mInitHandler.removeMessages(INIT_MESSAGE_ID);
mInitHandler.sendMessageDelayed(Message.obtain(mInitHandler, INIT_MESSAGE_ID), CAMERA_INIT_DELAY);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
// Surface will be destroyed when we return, so stop the preview.
if (surface == mSurfaceView.getSurfaceTexture()) {
mInitHandler.removeMessages(INIT_MESSAGE_ID);
//Debug.stopMethodTracing();
if (mCamera != null) {
mThread.interrupt();
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
try {
mThread.join(500);
} catch (InterruptedException e) {
XLog.e("Cannot interrupt processing thread",e);
}
}
}
return false;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
if (surface == mSurfaceView.getSurfaceTexture()) {
mInitHandler.removeMessages(INIT_MESSAGE_ID);
mInitHandler.sendMessageDelayed(Message.obtain(mInitHandler, INIT_MESSAGE_ID), CAMERA_INIT_DELAY);
}
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
public void setProcessor(OpenCVProcessor processor) {
mProcessor = processor;
}
private void initCameraAndStartPreview() {
if (mCamera == null && mSurfaceView.getSurfaceTexture() != null) {
try {
mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
///Set preview and picture size
mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, PREFERRED_WIDTH, PREFERRED_HEIGHT);
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
parameters.setPictureSize(mPreviewSize.width, mPreviewSize.height);
parameters.setJpegQuality(97);
mFieldOfView = parameters.getHorizontalViewAngle();
mFieldOfView = 65.0f;
mFieldOfView /= mPreviewSize.width;
mCamera.setParameters(parameters);
///Callbacks and butffers
mCamera.setPreviewCallbackWithBuffer (new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
if (data.equals(mPreviewBuffer1.mPreviewCallbackBuffer.array())) {
try {
PreviewView.this.mPreviewFrames.put(mPreviewBuffer1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (data.equals(mPreviewBuffer2.mPreviewCallbackBuffer.array())) {
try {
PreviewView.this.mPreviewFrames.put(mPreviewBuffer2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
mPreviewBuffer1 = new PreviewBuffer(mPreviewSize.width,mPreviewSize.height, parameters.getPreviewFormat());
mPreviewBuffer2 = new PreviewBuffer(mPreviewSize.width,mPreviewSize.height, parameters.getPreviewFormat());
mCamera.addCallbackBuffer(mPreviewBuffer1.mPreviewCallbackBuffer.array());
mCamera.addCallbackBuffer(mPreviewBuffer2.mPreviewCallbackBuffer.array());
///Start it up
mCamera.setPreviewTexture(mSurfaceView.getSurfaceTexture());
mCamera.startPreview();
requestLayout();
} catch (RuntimeException e) {
XLog.e("Failed to connect to camera",e);
} catch (IOException e) {
XLog.e("Cannot init camera",e);
}
} else {
mInitHandler.removeMessages(INIT_MESSAGE_ID);
mInitHandler.sendMessageDelayed(Message.obtain(mInitHandler, INIT_MESSAGE_ID), CAMERA_INIT_DELAY);
}
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0,getWidth(),getHeight(), mPreviewFramePaint);
}
public float getFOVPerPixel() {
return mFieldOfView;
}
public void takePicture(PictureCallback piccallback) {
if (mCamera != null) {
if (mPictureCallback == null) {
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
mPictureCallback = piccallback;
mCamera.takePicture(this, null, this);
}
}
}
public void run() {
mThreadRun = true;
XLog.i("Starting processing thread");
while (mThreadRun) {
Mat grayMat = null;
Mat yuvMat = null;
PreviewBuffer frame;
try {
frame = mPreviewFrames.take();
frameCount++;
long now = System.currentTimeMillis();
if (prevTime > 0) {
long diff = now - prevTime;
if (diff > 2000) {
Log.d("OpenCVDemo:",String.format("frames/s:%.2f data.size=%d",frameCount * 1000.0f / diff,frame == null ? 0 : frame.mPreviewCallbackBuffer.capacity()));
frameCount = 0;
prevTime = now;
}
}
else {
prevTime = now;
}
grayMat = frame.mGraySubmat;
yuvMat = frame.mYuv;
if (mProcessor != null) {
Canvas canvas = mResultSurfaceView.lockCanvas();
if (canvas != null) {
mProcessor.processFrame(canvas, mPreviewSize.width,mPreviewSize.height, yuvMat,grayMat);
mResultSurfaceView.unlockCanvasAndPost(canvas);
}
}
//Need to add back the callback buffer
byte[] framedata = frame.mPreviewCallbackBuffer.array();
if (mCamera != null) {
mCamera.addCallbackBuffer(framedata);
}
} catch (InterruptedException e) {
mThreadRun = false;
}
}
}
static private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find vga
for (Size size : sizes) {
if (size.height == 480 && size.width == 640) {
return size;
}
}
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
@Override
public void onShutter() {
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
if (mPictureCallback != null) {
mPictureCallback.onShutter();
}
//mMediaPlayer.seekTo(0);
//mMediaPlayer.start();
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
if (mPictureCallback != null) {
mPictureCallback.onPictureTaken(data);
mPictureCallback = null;
}
camera.startPreview();
}
}
| UTF-8 | Java | 18,519 | java | PreviewView.java | Java | []
| null | []
| package se.birkler.opencvcalibrate.opencvutil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import se.birkler.opencvcalibrate.util.XLog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
/**
* A simple wrapper around a Camera and a SurfaceView that renders a centered preview of the Camera
* to the surface. We need to center the SurfaceView because not all devices have cameras that
* support preview sizes at the same aspect ratio as the device's display.
*
* Startup states:
* onLayout (with vga size)
*
*
*/
public class PreviewView extends RelativeLayout implements Runnable, Camera.PictureCallback, Camera.ShutterCallback, SurfaceTextureListener
{
private static final int CAMERA_INIT_DELAY = 500;
private Rect mSurfaceViewVisibleRect = new Rect();
public interface OpenCVProcessor {
void processFrame(Canvas canvas, int width, int height, Mat yuvData, Mat grayData);
}
public interface PictureCallback {
public void onShutter();
public void onPictureTaken(byte[] data);
}
static final int PREFERRED_HEIGHT = 480;
static final int PREFERRED_WIDTH = 640;
private static final int INIT_MESSAGE_ID = 0;
TextureView mSurfaceView;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
private OpenCVProcessor mProcessor;
private float mFieldOfView = -1;
private FrameLayout mResultSurfaceViewOwner;
private TextureView mResultSurfaceView;
private ArrayBlockingQueue<PreviewBuffer> mPreviewFrames = new ArrayBlockingQueue<PreviewBuffer>(3);
private boolean mThreadRun;
private int frameCount;
private long prevTime;
private Thread mThread;
class PreviewBuffer {
public ByteBuffer mPreviewCallbackBuffer;
public Mat mYuv;
public Mat mGraySubmat;
public PreviewBuffer(int width, int height, int format) {
int bytesneeded = height * width * ImageFormat.getBitsPerPixel(format) / 8;
mPreviewCallbackBuffer = ByteBuffer.allocateDirect(bytesneeded);
mYuv = new MatByteBufferWrapper(mPreviewCallbackBuffer,height + height / 2, width, CvType.CV_8UC1);
mGraySubmat = mYuv.submat(0, height, 0, width);
}
}
PreviewBuffer mPreviewBuffer1;
Handler mInitHandler;
PictureCallback mPictureCallback = null;
private AudioManager mAudioManager;
private Paint mPreviewFramePaint;
private PreviewBuffer mPreviewBuffer2;
public PreviewView(Context context, AttributeSet attr) {
super(context,attr);
mSurfaceView = new TextureView(context);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mSurfaceView.setLayoutParams(lp);
mSurfaceView.setOpaque(true);
mSurfaceView.setSurfaceTextureListener(this);
addView(mSurfaceView);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
//mCameraHolder = mSurfaceView.getHolder();
//mCameraHolder.addCallback(this);
//mCameraHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mResultSurfaceView = new TextureView(context);
mResultSurfaceView.setOpaque(false);
lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mResultSurfaceView.setLayoutParams(lp);
mResultSurfaceView.setSurfaceTextureListener(this);
mResultSurfaceViewOwner = new FrameLayout(context);
lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mResultSurfaceViewOwner.setLayoutParams(lp);
mResultSurfaceViewOwner.addView(mResultSurfaceView);
addView(mResultSurfaceViewOwner);
//mResultSurfaceView.setZOrderOnTop(true);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
//mResultHolder = mResultSurfaceView.getHolder();
//mResultHolder.setFormat(PixelFormat.TRANSPARENT);
//mResultHolder.addCallback(this);
setWillNotDraw(false);
mInitHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
initCameraAndStartPreview();
}
};
mThread = new Thread(this);
mThread.setPriority(Thread.MIN_PRIORITY+1);
mThread.setName("Processing thread");
//mMediaPlayer = MediaPlayer.create(context,R.raw.shutter_sound);
//mMediaPlayer.prepare();
mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
mPreviewFramePaint = new Paint();
mPreviewFramePaint.setColor(Color.CYAN);
mPreviewFramePaint.setAlpha(128);
mPreviewFramePaint.setStrokeWidth((float) 3.0);
}
@Override
public void onFinishInflate () {
super.onFinishInflate();
}
//@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = Integer.MAX_VALUE;
int height = Integer.MAX_VALUE;
int mostWidth = Integer.MAX_VALUE;
int mostHeight = Integer.MAX_VALUE;
final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
//if (widthSpecMode == MeasureSpec.UNSPECIFIED) width = Integer.MAX_VALUE;
//if (heightSpecMode == MeasureSpec.UNSPECIFIED) height = Integer.MAX_VALUE;
if (widthSpecMode == MeasureSpec.EXACTLY && heightMeasureSpec == MeasureSpec.EXACTLY) {
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
} else if (widthSpecMode == MeasureSpec.UNSPECIFIED && heightMeasureSpec == MeasureSpec.UNSPECIFIED) {
}
else {
double aspect = 640.0 / 480.0;
if (widthSpecMode == MeasureSpec.EXACTLY || widthSpecMode == MeasureSpec.AT_MOST) {
mostWidth = MeasureSpec.getSize(widthMeasureSpec);
}
if (heightSpecMode == MeasureSpec.EXACTLY || heightSpecMode == MeasureSpec.AT_MOST) {
mostHeight = MeasureSpec.getSize(heightMeasureSpec);
}
if ((double)mostWidth > (double)mostHeight * aspect) {
width = (int) ((double)mostHeight * aspect);
height = mostHeight;
} else {
width = mostWidth;
height = (int) ((double)mostWidth / aspect);
}
}
/*
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
if (mPreviewSize != null) {
setMeasuredDimension(mPreviewSize.width, mPreviewSize.height);
}
else {
setMeasuredDimension(PREFERRED_WIDTH,PREFERRED_HEIGHT);
}*/
setMeasuredDimension(width,height);
mResultSurfaceView.measure(MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY));
mResultSurfaceViewOwner.measure(MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY));
//final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
//final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
//setMeasuredDimension(width, height);
//tMeasuredDimension(mPreviewSize.width, mPreviewSize.height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed) {
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
l = (width - scaledChildWidth) / 2;
t = 0;
r = (width + scaledChildWidth) / 2;
b = height;
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
l = 0;
t = (height - scaledChildHeight) / 2;
r = width;
b = (height + scaledChildHeight) / 2;
}
super.onLayout(changed,l,t,r,b);
mSurfaceView.layout(l, t,r, b);
mResultSurfaceViewOwner.layout(l, t,r, b);
//mResultSurfaceView.layout(l, t,r, b);
float scale;
int w = 640;
int h = 480;
if (mPreviewSize != null) {
scale = (float)(b-t) / (float)mPreviewSize.height;
w = mPreviewSize.width;
h = mPreviewSize.height;
} else {
scale = (float)(b-t) / 480;
}
//In the middle
mResultSurfaceView.layout((l+r-w) / 2, (t+b-h) / 2, (l+r+w) / 2, (t+b+h) / 2);
//Matrix transform = new Matrix();
//transform.preScale(scale, scale);
//mResultSurfaceView.setTransform(transform);
mResultSurfaceViewOwner.setScaleX(scale);
mResultSurfaceViewOwner.setScaleY(scale);
mSurfaceView.getLocalVisibleRect(mSurfaceViewVisibleRect);
XLog.d("surfaceView:" + mSurfaceView.toString() + mSurfaceViewVisibleRect.toString());
}
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
// The Surface has been created, acquire the camera and tell it where to draw.
if (surface == mSurfaceView.getSurfaceTexture()) {
//Debug.startMethodTracing("opencvtrace_viewfinder");
mThreadRun = true;
mThread.start();
mInitHandler.removeMessages(INIT_MESSAGE_ID);
mInitHandler.sendMessageDelayed(Message.obtain(mInitHandler, INIT_MESSAGE_ID), CAMERA_INIT_DELAY);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
// Surface will be destroyed when we return, so stop the preview.
if (surface == mSurfaceView.getSurfaceTexture()) {
mInitHandler.removeMessages(INIT_MESSAGE_ID);
//Debug.stopMethodTracing();
if (mCamera != null) {
mThread.interrupt();
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
try {
mThread.join(500);
} catch (InterruptedException e) {
XLog.e("Cannot interrupt processing thread",e);
}
}
}
return false;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
if (surface == mSurfaceView.getSurfaceTexture()) {
mInitHandler.removeMessages(INIT_MESSAGE_ID);
mInitHandler.sendMessageDelayed(Message.obtain(mInitHandler, INIT_MESSAGE_ID), CAMERA_INIT_DELAY);
}
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
public void setProcessor(OpenCVProcessor processor) {
mProcessor = processor;
}
private void initCameraAndStartPreview() {
if (mCamera == null && mSurfaceView.getSurfaceTexture() != null) {
try {
mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
///Set preview and picture size
mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, PREFERRED_WIDTH, PREFERRED_HEIGHT);
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
parameters.setPictureSize(mPreviewSize.width, mPreviewSize.height);
parameters.setJpegQuality(97);
mFieldOfView = parameters.getHorizontalViewAngle();
mFieldOfView = 65.0f;
mFieldOfView /= mPreviewSize.width;
mCamera.setParameters(parameters);
///Callbacks and butffers
mCamera.setPreviewCallbackWithBuffer (new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
if (data.equals(mPreviewBuffer1.mPreviewCallbackBuffer.array())) {
try {
PreviewView.this.mPreviewFrames.put(mPreviewBuffer1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (data.equals(mPreviewBuffer2.mPreviewCallbackBuffer.array())) {
try {
PreviewView.this.mPreviewFrames.put(mPreviewBuffer2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
mPreviewBuffer1 = new PreviewBuffer(mPreviewSize.width,mPreviewSize.height, parameters.getPreviewFormat());
mPreviewBuffer2 = new PreviewBuffer(mPreviewSize.width,mPreviewSize.height, parameters.getPreviewFormat());
mCamera.addCallbackBuffer(mPreviewBuffer1.mPreviewCallbackBuffer.array());
mCamera.addCallbackBuffer(mPreviewBuffer2.mPreviewCallbackBuffer.array());
///Start it up
mCamera.setPreviewTexture(mSurfaceView.getSurfaceTexture());
mCamera.startPreview();
requestLayout();
} catch (RuntimeException e) {
XLog.e("Failed to connect to camera",e);
} catch (IOException e) {
XLog.e("Cannot init camera",e);
}
} else {
mInitHandler.removeMessages(INIT_MESSAGE_ID);
mInitHandler.sendMessageDelayed(Message.obtain(mInitHandler, INIT_MESSAGE_ID), CAMERA_INIT_DELAY);
}
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0,getWidth(),getHeight(), mPreviewFramePaint);
}
public float getFOVPerPixel() {
return mFieldOfView;
}
public void takePicture(PictureCallback piccallback) {
if (mCamera != null) {
if (mPictureCallback == null) {
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
mPictureCallback = piccallback;
mCamera.takePicture(this, null, this);
}
}
}
public void run() {
mThreadRun = true;
XLog.i("Starting processing thread");
while (mThreadRun) {
Mat grayMat = null;
Mat yuvMat = null;
PreviewBuffer frame;
try {
frame = mPreviewFrames.take();
frameCount++;
long now = System.currentTimeMillis();
if (prevTime > 0) {
long diff = now - prevTime;
if (diff > 2000) {
Log.d("OpenCVDemo:",String.format("frames/s:%.2f data.size=%d",frameCount * 1000.0f / diff,frame == null ? 0 : frame.mPreviewCallbackBuffer.capacity()));
frameCount = 0;
prevTime = now;
}
}
else {
prevTime = now;
}
grayMat = frame.mGraySubmat;
yuvMat = frame.mYuv;
if (mProcessor != null) {
Canvas canvas = mResultSurfaceView.lockCanvas();
if (canvas != null) {
mProcessor.processFrame(canvas, mPreviewSize.width,mPreviewSize.height, yuvMat,grayMat);
mResultSurfaceView.unlockCanvasAndPost(canvas);
}
}
//Need to add back the callback buffer
byte[] framedata = frame.mPreviewCallbackBuffer.array();
if (mCamera != null) {
mCamera.addCallbackBuffer(framedata);
}
} catch (InterruptedException e) {
mThreadRun = false;
}
}
}
static private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find vga
for (Size size : sizes) {
if (size.height == 480 && size.width == 640) {
return size;
}
}
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
@Override
public void onShutter() {
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
if (mPictureCallback != null) {
mPictureCallback.onShutter();
}
//mMediaPlayer.seekTo(0);
//mMediaPlayer.start();
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
if (mPictureCallback != null) {
mPictureCallback.onPictureTaken(data);
mPictureCallback = null;
}
camera.startPreview();
}
}
| 18,519 | 0.661753 | 0.656731 | 515 | 34.959225 | 28.677454 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.916505 | false | false | 13 |
33fc76d3831c20480125ed7de86c0dcc77b89097 | 21,036,749,864,013 | 874d8fa9d0b122ab04bf585ebb93c0c8d058528b | /src/main/java/com/xiaour/spring/boot/service/ZookeeperService.java | 312f8e817ca4dcfd8a6421714a0d117841713e83 | []
| no_license | aioprxu/exam | https://github.com/aioprxu/exam | ac65bb0a3078f60153d6b75f04856d2c4d7eab27 | d50259dfad242f7c3e6d8ca66ae8447662c4c24d | refs/heads/master | 2022-07-02T16:05:47.158000 | 2019-05-31T22:55:11 | 2019-05-31T22:55:11 | 180,793,089 | 0 | 0 | null | false | 2022-06-29T17:19:21 | 2019-04-11T13:01:26 | 2019-05-31T22:55:23 | 2022-06-29T17:19:19 | 73 | 0 | 0 | 5 | Java | false | false | package com.xiaour.spring.boot.service;
public interface ZookeeperService {
String getConfig() throws Exception;
String setConfig();
}
| UTF-8 | Java | 147 | java | ZookeeperService.java | Java | []
| null | []
| package com.xiaour.spring.boot.service;
public interface ZookeeperService {
String getConfig() throws Exception;
String setConfig();
}
| 147 | 0.741497 | 0.741497 | 9 | 15.333333 | 17.5119 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 13 |
1895d54e5b98a8587bc4919fceba2d608c133069 | 5,695,126,692,134 | c225a27d4d5efb188460b23d808ce68a5581cd17 | /siqian/siqian-webapp/src/main/java/com/sdstc/sys/service/impl/RoleServiceImpl.java | d130039b21b1a9425cce0bf0afa61a4c60799898 | []
| no_license | dzchengang/siqian | https://github.com/dzchengang/siqian | 4367bbbea736624b161f014d25b3492c3b0bfb96 | 5763270295edfd4289dc0a2eb93956b82aea67db | refs/heads/master | 2019-06-15T18:56:31.027000 | 2017-07-26T07:59:57 | 2017-07-26T07:59:57 | 98,396,223 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sdstc.sys.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sdstc.core.dto.jqgrid.PageDto;
import com.sdstc.core.utils.IDGenerator;
import com.sdstc.sys.dao.RoleMapper;
import com.sdstc.sys.model.Role;
import com.sdstc.sys.service.RoleService;
@Service("roleServiceImpl")
@SuppressWarnings("all")
public class RoleServiceImpl implements RoleService {
@Resource
private RoleMapper roleMapper;
@Autowired
private IDGenerator idGenerator;
public int deleteByPrimaryKey(String id) {
// TODO Auto-generated method stub
return roleMapper.deleteByPrimaryKey(id);
}
public int insert(Role record) {
// TODO Auto-generated method stub
String roleID =idGenerator.getUUID();
record.setId(roleID);
Integer result = roleMapper.insert(record);
return result;
}
public int insertSelective(Role record) {
// TODO Auto-generated method stub
return roleMapper.insertSelective(record);
}
public Role selectByPrimaryKey(String id) {
// TODO Auto-generated method stub
return roleMapper.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(Role record) {
// TODO Auto-generated method stub
return roleMapper.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(Role record) {
// TODO Auto-generated method stub
return roleMapper.updateByPrimaryKey(record);
}
@Override
public int selectCount(Role role) {
// TODO Auto-generated method stub
return roleMapper.selectCount(role);
}
@Override
public PageDto getGridData(Role role) {
// TODO Auto-generated method stub
Integer count = this.selectCount(role);
List<Role> roles = this.selectByPage(role);
PageDto page = new PageDto();
page.setPage(role.getPage());
page.setRecords(count);
page.setRows(roles);
page.setRowsCount(role.getRows());
return page;
}
@Override
public int deleteBatchs(List<String> ids) {
// TODO Auto-generated method stub
// 删除 角色_菜单 角色_权限关系表
roleMapper.deleteRoleMenuByRoleIdBatchs(ids);
roleMapper.deleteRolePermissionByRoleIdBatchs(ids);
int userC = roleMapper.deleteBatchs(ids);
return userC;
}
@Override
public List<Role> selectByPage(Role role) {
// TODO Auto-generated method stub
return roleMapper.selectByPage(role);
}
@Override
public int saveRole_Menus(String roleId, String[] menuIds) {
// TODO Auto-generated method stub
roleMapper.deleteRoleMenuByRoleId(roleId);
List<Map> roleMenus = new ArrayList<Map>();
int result=0;
if(menuIds!=null){
for (String menuId : menuIds) {
Map roleMenu = new HashMap<String, String>();
roleMenu.put("roleId", roleId);
roleMenu.put("menuId", menuId);
roleMenus.add(roleMenu);
}
result=roleMapper.insertRole_Menus(roleMenus);
}
return result;
}
@Override
public List<String> selectRole_MenuByRoleId(String roleId) {
// TODO Auto-generated method stub
return roleMapper.selectRole_MenuByRoleId(roleId);
}
@Override
public int saveRole_Permissions(String roleId, String[] permissionIds) {
// TODO Auto-generated method stub
roleMapper.deleteRolePermissionByRoleId(roleId);
List<Map> rolePermissions = new ArrayList<Map>();
int result=0;
if(permissionIds!=null){
for (String permissionId : permissionIds) {
Map rolePermission = new HashMap<String, String>();
rolePermission.put("roleId", roleId);
rolePermission.put("permissionId", permissionId);
rolePermissions.add(rolePermission);
}
result=roleMapper.insertRole_Permissions(rolePermissions);
}
return result;
}
@Override
public List<String> selectRole_PermissionByRoleId(String roleId) {
// TODO Auto-generated method stub
return roleMapper.selectRole_PermissionByRoleId(roleId);
}
@Override
public List<Role> selectAll() {
// TODO Auto-generated method stub
return roleMapper.selectAll();
}
}
| UTF-8 | Java | 4,202 | java | RoleServiceImpl.java | Java | []
| null | []
| package com.sdstc.sys.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sdstc.core.dto.jqgrid.PageDto;
import com.sdstc.core.utils.IDGenerator;
import com.sdstc.sys.dao.RoleMapper;
import com.sdstc.sys.model.Role;
import com.sdstc.sys.service.RoleService;
@Service("roleServiceImpl")
@SuppressWarnings("all")
public class RoleServiceImpl implements RoleService {
@Resource
private RoleMapper roleMapper;
@Autowired
private IDGenerator idGenerator;
public int deleteByPrimaryKey(String id) {
// TODO Auto-generated method stub
return roleMapper.deleteByPrimaryKey(id);
}
public int insert(Role record) {
// TODO Auto-generated method stub
String roleID =idGenerator.getUUID();
record.setId(roleID);
Integer result = roleMapper.insert(record);
return result;
}
public int insertSelective(Role record) {
// TODO Auto-generated method stub
return roleMapper.insertSelective(record);
}
public Role selectByPrimaryKey(String id) {
// TODO Auto-generated method stub
return roleMapper.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(Role record) {
// TODO Auto-generated method stub
return roleMapper.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(Role record) {
// TODO Auto-generated method stub
return roleMapper.updateByPrimaryKey(record);
}
@Override
public int selectCount(Role role) {
// TODO Auto-generated method stub
return roleMapper.selectCount(role);
}
@Override
public PageDto getGridData(Role role) {
// TODO Auto-generated method stub
Integer count = this.selectCount(role);
List<Role> roles = this.selectByPage(role);
PageDto page = new PageDto();
page.setPage(role.getPage());
page.setRecords(count);
page.setRows(roles);
page.setRowsCount(role.getRows());
return page;
}
@Override
public int deleteBatchs(List<String> ids) {
// TODO Auto-generated method stub
// 删除 角色_菜单 角色_权限关系表
roleMapper.deleteRoleMenuByRoleIdBatchs(ids);
roleMapper.deleteRolePermissionByRoleIdBatchs(ids);
int userC = roleMapper.deleteBatchs(ids);
return userC;
}
@Override
public List<Role> selectByPage(Role role) {
// TODO Auto-generated method stub
return roleMapper.selectByPage(role);
}
@Override
public int saveRole_Menus(String roleId, String[] menuIds) {
// TODO Auto-generated method stub
roleMapper.deleteRoleMenuByRoleId(roleId);
List<Map> roleMenus = new ArrayList<Map>();
int result=0;
if(menuIds!=null){
for (String menuId : menuIds) {
Map roleMenu = new HashMap<String, String>();
roleMenu.put("roleId", roleId);
roleMenu.put("menuId", menuId);
roleMenus.add(roleMenu);
}
result=roleMapper.insertRole_Menus(roleMenus);
}
return result;
}
@Override
public List<String> selectRole_MenuByRoleId(String roleId) {
// TODO Auto-generated method stub
return roleMapper.selectRole_MenuByRoleId(roleId);
}
@Override
public int saveRole_Permissions(String roleId, String[] permissionIds) {
// TODO Auto-generated method stub
roleMapper.deleteRolePermissionByRoleId(roleId);
List<Map> rolePermissions = new ArrayList<Map>();
int result=0;
if(permissionIds!=null){
for (String permissionId : permissionIds) {
Map rolePermission = new HashMap<String, String>();
rolePermission.put("roleId", roleId);
rolePermission.put("permissionId", permissionId);
rolePermissions.add(rolePermission);
}
result=roleMapper.insertRole_Permissions(rolePermissions);
}
return result;
}
@Override
public List<String> selectRole_PermissionByRoleId(String roleId) {
// TODO Auto-generated method stub
return roleMapper.selectRole_PermissionByRoleId(roleId);
}
@Override
public List<Role> selectAll() {
// TODO Auto-generated method stub
return roleMapper.selectAll();
}
}
| 4,202 | 0.722701 | 0.722222 | 152 | 25.473684 | 19.71706 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.789474 | false | false | 13 |
1e4f6004174d693a67c6b1f1e867f6dd93a29928 | 11,038,065,956,628 | 532540517c77a038b7b13b73c704491025507978 | /src/com/lsj/learningroute/servlet/LearningRouteServlet.java | a8ca89e55ade9c09025ae4c85722bebfb650def4 | []
| no_license | lsj113602/Stadyweb | https://github.com/lsj113602/Stadyweb | 2491f2c57cf2bc553ca66e02d19fa8e36b8fec77 | 1eecc634faa0c8b508277c2f3fd7c911a672036f | refs/heads/master | 2021-01-21T16:00:28.869000 | 2017-05-26T01:54:29 | 2017-05-26T01:54:29 | 91,869,414 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lsj.learningroute.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lsj.knowlege.main.Knowledge;
import com.lsj.knowlege.service.KnowledgeService;
import com.lsj.learningroute.main.LearningRoute;
import com.lsj.learningroute.service.LearningRouteService;
import com.lsj.user.main.user;
import com.lsj.user.service.userservice;
import com.lsj.video.main.Video;
import com.lsj.video.service.VideoService;
import cn.itcast.servlet.BaseServlet;
public class LearningRouteServlet extends BaseServlet {
private LearningRouteService lrs=new LearningRouteService();
private userservice us =new userservice();
private KnowledgeService ks=new KnowledgeService();
private VideoService vs=new VideoService();
public String AddLearningRoute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SQLException{
LearningRoute lr=new LearningRoute();
String id=req.getParameter("knowid");
req.setAttribute("knowid", id);
int knowid=Integer.valueOf(id).intValue();
String us_name=(String) req.getSession().getAttribute("user_name");
//获取用户
user u=us.findbyname(us_name);
int userid=u.getUser_id();
//获取知识点
Knowledge k=ks.FindByknowId(knowid);
//查看该用户之前是否学过该知识点
LearningRoute mark=lrs.FindByUAndK(userid,knowid);
if(mark!=null){
mark.setNumber(mark.getNumber()+1);
lrs.UpLearnRouteNum(mark);
}else{
//获取开始学习的时间
Date date1= new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str1 = sdf.format(date1);
lr.setKnowledge(k);
lr.setUs(u);
lr.setLr_state(0);
lr.setNumber(1);
lr.setStart_time(str1);
lrs.AddLearningRoute(lr);
}
return "f:/user/KnowledgeView.jsp";
}
public String FindFriendByKnowid(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SQLException{
String id=req.getParameter("knowid");
int knowid=Integer.valueOf(id).intValue();
List<LearningRoute>list=lrs.FindFindFriendByKnowid(knowid);
req.setAttribute("list", list);
return "f:/user/FriendView.jsp";
}
public String FindFriendLearn(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SQLException{
String id=req.getParameter("uid");
int uid=Integer.valueOf(id).intValue();
List<LearningRoute>list=lrs.FindFriendLearn(uid);
req.setAttribute("list", list);
user uu=us.FindById(uid);
String uu_name=uu.getUser_name();
List<Video> listvid=vs.FindByWriter(uu_name);
req.setAttribute("listvid", listvid);
return "f:/user/FriendLearn.jsp";
}
}
| GB18030 | Java | 2,922 | java | LearningRouteServlet.java | Java | []
| null | []
| package com.lsj.learningroute.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lsj.knowlege.main.Knowledge;
import com.lsj.knowlege.service.KnowledgeService;
import com.lsj.learningroute.main.LearningRoute;
import com.lsj.learningroute.service.LearningRouteService;
import com.lsj.user.main.user;
import com.lsj.user.service.userservice;
import com.lsj.video.main.Video;
import com.lsj.video.service.VideoService;
import cn.itcast.servlet.BaseServlet;
public class LearningRouteServlet extends BaseServlet {
private LearningRouteService lrs=new LearningRouteService();
private userservice us =new userservice();
private KnowledgeService ks=new KnowledgeService();
private VideoService vs=new VideoService();
public String AddLearningRoute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SQLException{
LearningRoute lr=new LearningRoute();
String id=req.getParameter("knowid");
req.setAttribute("knowid", id);
int knowid=Integer.valueOf(id).intValue();
String us_name=(String) req.getSession().getAttribute("user_name");
//获取用户
user u=us.findbyname(us_name);
int userid=u.getUser_id();
//获取知识点
Knowledge k=ks.FindByknowId(knowid);
//查看该用户之前是否学过该知识点
LearningRoute mark=lrs.FindByUAndK(userid,knowid);
if(mark!=null){
mark.setNumber(mark.getNumber()+1);
lrs.UpLearnRouteNum(mark);
}else{
//获取开始学习的时间
Date date1= new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str1 = sdf.format(date1);
lr.setKnowledge(k);
lr.setUs(u);
lr.setLr_state(0);
lr.setNumber(1);
lr.setStart_time(str1);
lrs.AddLearningRoute(lr);
}
return "f:/user/KnowledgeView.jsp";
}
public String FindFriendByKnowid(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SQLException{
String id=req.getParameter("knowid");
int knowid=Integer.valueOf(id).intValue();
List<LearningRoute>list=lrs.FindFindFriendByKnowid(knowid);
req.setAttribute("list", list);
return "f:/user/FriendView.jsp";
}
public String FindFriendLearn(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SQLException{
String id=req.getParameter("uid");
int uid=Integer.valueOf(id).intValue();
List<LearningRoute>list=lrs.FindFriendLearn(uid);
req.setAttribute("list", list);
user uu=us.FindById(uid);
String uu_name=uu.getUser_name();
List<Video> listvid=vs.FindByWriter(uu_name);
req.setAttribute("listvid", listvid);
return "f:/user/FriendLearn.jsp";
}
}
| 2,922 | 0.761555 | 0.759104 | 101 | 27.277227 | 21.919348 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.960396 | false | false | 13 |
89a4393553cc11657f5ba088f7a565e9c4681059 | 21,672,405,003,238 | 1ab0ff5c53591c50f9c73805abc8bc04aa13c37a | /src/main/java/candidatetest/main/controller/AccountRestController.java | 217b0efc2402f862177948b7cb2fa1b14f98ff06 | []
| no_license | PMSI-AlignAlytics/candidate-test-seed | https://github.com/PMSI-AlignAlytics/candidate-test-seed | f2370e63571b44bf9b0da8c58130e7ca260cf451 | a5a369c584fda3fd1faf7e9469be101f2724c6d2 | refs/heads/master | 2021-04-29T21:20:30.363000 | 2018-02-15T14:41:59 | 2018-02-15T14:41:59 | 121,612,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package candidatetest.main.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import candidatetest.main.model.data.User;
/**
* User end-point for all API operations relating to the API user
*/
@RequestMapping("/api/account")
@RestController
public class AccountRestController {
/**
* GET /api/account - Get the authenticated user. It returns one of the following:<br><br>
* 200 - User returned successfully<br>
* 500 - Unknown error occurred
* @return The currently authenticated user
*/
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<User> get() {
return new ResponseEntity<User>(User.principal(), HttpStatus.OK);
}
}
| UTF-8 | Java | 933 | java | AccountRestController.java | Java | []
| null | []
| package candidatetest.main.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import candidatetest.main.model.data.User;
/**
* User end-point for all API operations relating to the API user
*/
@RequestMapping("/api/account")
@RestController
public class AccountRestController {
/**
* GET /api/account - Get the authenticated user. It returns one of the following:<br><br>
* 200 - User returned successfully<br>
* 500 - Unknown error occurred
* @return The currently authenticated user
*/
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<User> get() {
return new ResponseEntity<User>(User.principal(), HttpStatus.OK);
}
}
| 933 | 0.753483 | 0.747052 | 28 | 32.32143 | 26.276081 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 13 |
14a2834ab0075f97a2ca1ac48880651fd3e7f852 | 24,232,205,484,330 | eac0ec8bbf29fb32e8b4464685828ba79b47bd11 | /src/bomberman/Gameobjects/movableobjects/enemys/Enemy.java | 57e0a291c09e0285d8ed7ae5a885264e4c3c0eb1 | []
| no_license | cesarcota/Bomberman | https://github.com/cesarcota/Bomberman | 66ff489aff5f0b6b19d281f62aeb03010bbccd2c | 961d513f8d56c5dd1f9c38fff858035cd9fdfb45 | refs/heads/master | 2021-09-13T13:17:45.572000 | 2018-02-06T17:41:32 | 2018-02-06T17:41:32 | 112,108,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bomberman.Gameobjects.movableobjects.enemys;
import bomberman.Gameobjects.movableobjects.MovableObjects;
import bomberman.grid.GridDirection;
import bomberman.grid.position.GridPosition;
abstract public class Enemy extends MovableObjects {
private GridDirection currentDirection;
public Enemy(GridPosition pos) {
super(pos);
chooseDirection();
}
public void move() {
if (isDestroyed()) {
return;
}
chooseDirection();
switch (currentDirection) {
case LEFT:
if (!collisionDetector.isUnSafe(getPos().getCol() - 1, getPos().getRow())) {
getPos().moveInDirection(GridDirection.LEFT, 1);
break;
}
break;
case RIGHT:
if (!collisionDetector.isUnSafe(getPos().getCol() + 1, getPos().getRow())) {
getPos().moveInDirection(GridDirection.RIGHT, 1);
break;
}
break;
case UP:
if (!collisionDetector.isUnSafe(getPos().getCol(), getPos().getRow() - 1)) {
getPos().moveInDirection(GridDirection.UP, 1);
break;
}
break;
case DOWN:
if (!collisionDetector.isUnSafe(getPos().getCol(), getPos().getRow() + 1)) {
getPos().moveInDirection(GridDirection.DOWN, 1);
break;
}
break;
default:
}
}
@Override
public void setDestroyed() {
super.setDestroyed();
}
public void chooseDirection() {
if (currentDirection == null){
currentDirection = GridDirection.DOWN;
}
int randomNumber = (int) (Math.random() * 100);
if (randomNumber >= 30) {
currentDirection = GridDirection.values()[(int) (Math.random() * GridDirection.values().length)];
}
}
}
| UTF-8 | Java | 2,029 | java | Enemy.java | Java | []
| null | []
| package bomberman.Gameobjects.movableobjects.enemys;
import bomberman.Gameobjects.movableobjects.MovableObjects;
import bomberman.grid.GridDirection;
import bomberman.grid.position.GridPosition;
abstract public class Enemy extends MovableObjects {
private GridDirection currentDirection;
public Enemy(GridPosition pos) {
super(pos);
chooseDirection();
}
public void move() {
if (isDestroyed()) {
return;
}
chooseDirection();
switch (currentDirection) {
case LEFT:
if (!collisionDetector.isUnSafe(getPos().getCol() - 1, getPos().getRow())) {
getPos().moveInDirection(GridDirection.LEFT, 1);
break;
}
break;
case RIGHT:
if (!collisionDetector.isUnSafe(getPos().getCol() + 1, getPos().getRow())) {
getPos().moveInDirection(GridDirection.RIGHT, 1);
break;
}
break;
case UP:
if (!collisionDetector.isUnSafe(getPos().getCol(), getPos().getRow() - 1)) {
getPos().moveInDirection(GridDirection.UP, 1);
break;
}
break;
case DOWN:
if (!collisionDetector.isUnSafe(getPos().getCol(), getPos().getRow() + 1)) {
getPos().moveInDirection(GridDirection.DOWN, 1);
break;
}
break;
default:
}
}
@Override
public void setDestroyed() {
super.setDestroyed();
}
public void chooseDirection() {
if (currentDirection == null){
currentDirection = GridDirection.DOWN;
}
int randomNumber = (int) (Math.random() * 100);
if (randomNumber >= 30) {
currentDirection = GridDirection.values()[(int) (Math.random() * GridDirection.values().length)];
}
}
}
| 2,029 | 0.522425 | 0.516018 | 72 | 27.180555 | 26.546776 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 13 |
7ae378f23b3050af052357ded10293a2aeb6f9dd | 25,872,882,993,368 | 4c4d204fa6f8642d907b70927b64381ae4c65e27 | /src/main/java/org/aplikator/client/shared/descriptor/ActionTypes.java | 93744c47cc7e4ab86f360b972ab474bb11edbf01 | [
"Apache-2.0"
]
| permissive | incad/aplikator | https://github.com/incad/aplikator | 25415e6186d0abf602b15e1e191a1e025811bb27 | 7c7060e23fdd6958b185f96f819e4bfa716babe8 | refs/heads/master | 2019-07-09T10:38:19.529000 | 2019-02-20T11:49:17 | 2019-02-20T11:49:17 | 90,353,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.aplikator.client.shared.descriptor;
public interface ActionTypes {
static final String LIST = "list";
static final String FORM = "form";
static final String WIZZARD = "wizzard";
}
| UTF-8 | Java | 205 | java | ActionTypes.java | Java | []
| null | []
| package org.aplikator.client.shared.descriptor;
public interface ActionTypes {
static final String LIST = "list";
static final String FORM = "form";
static final String WIZZARD = "wizzard";
}
| 205 | 0.721951 | 0.721951 | 7 | 28.285715 | 18.257792 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
9d0549ea387772c0c6bb747be4e5c7faa7a9a571 | 31,327,491,515,616 | 0339f4c4f429bbe99b3e131a695e10c165d21bfd | /lj-mes-base-server/src/main/java/com/bpm/lj/mes/base/server/utils/DictTreeUtil.java | 8b637b85bcc2e4c2309a8f29794da91b5fc677af | []
| no_license | 528031951/lj-mes-base | https://github.com/528031951/lj-mes-base | 7ae32ce02d81e4aa7b645705f7f08fb0ef882a8e | 1d21452791e7806764f7508a82b754bf7452c3b8 | refs/heads/master | 2023-01-21T02:17:40.168000 | 2020-11-27T10:41:47 | 2020-11-27T10:41:47 | 316,087,734 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bpm.lj.mes.base.server.utils;
import com.bpm.lj.mes.base.server.dto.DictTreeNode;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@ApiModel(description = "Tree树结构封装类")
public class DictTreeUtil {
/**
* 使用递归方法建树
* @param treeNodes
* @param parentId
* @return
*/
public static List<DictTreeNode> build(List<DictTreeNode> treeNodes, Long parentId) {
List<DictTreeNode> trees = new ArrayList<DictTreeNode>();
for (DictTreeNode treeNode : treeNodes) {
if (treeNode.getParentId() == parentId) {
//一级节点
if (parentId==null) {
treeNode.setType("1");
}
trees.add(findChildren(treeNode,treeNodes));
}
}
return trees;
}
/**
* 递归查找子节点
* @param treeNodes
* @return
*/
public static DictTreeNode findChildren(DictTreeNode treeNode, List<DictTreeNode> treeNodes) {
/*for (DictTreeNode it : treeNodes) {
if(treeNode.getId().equals(it.getParentId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<DictTreeNode>());
}
treeNode.getChildren().add(findChildren(it,treeNodes));
}
}*/
for (int i = 0; i < treeNodes.size(); i++) {
DictTreeNode it = treeNodes.get(i);
if (treeNode.getId().equals(it.getParentId())){
//it为子节点
it.setType((Integer.parseInt(treeNode.getType())+1)+"");
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<DictTreeNode>());
}
treeNode.getChildren().add(findChildren(it,treeNodes));
}
}
return treeNode;
}
}
| UTF-8 | Java | 1,985 | java | DictTreeUtil.java | Java | []
| null | []
| package com.bpm.lj.mes.base.server.utils;
import com.bpm.lj.mes.base.server.dto.DictTreeNode;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@ApiModel(description = "Tree树结构封装类")
public class DictTreeUtil {
/**
* 使用递归方法建树
* @param treeNodes
* @param parentId
* @return
*/
public static List<DictTreeNode> build(List<DictTreeNode> treeNodes, Long parentId) {
List<DictTreeNode> trees = new ArrayList<DictTreeNode>();
for (DictTreeNode treeNode : treeNodes) {
if (treeNode.getParentId() == parentId) {
//一级节点
if (parentId==null) {
treeNode.setType("1");
}
trees.add(findChildren(treeNode,treeNodes));
}
}
return trees;
}
/**
* 递归查找子节点
* @param treeNodes
* @return
*/
public static DictTreeNode findChildren(DictTreeNode treeNode, List<DictTreeNode> treeNodes) {
/*for (DictTreeNode it : treeNodes) {
if(treeNode.getId().equals(it.getParentId())) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<DictTreeNode>());
}
treeNode.getChildren().add(findChildren(it,treeNodes));
}
}*/
for (int i = 0; i < treeNodes.size(); i++) {
DictTreeNode it = treeNodes.get(i);
if (treeNode.getId().equals(it.getParentId())){
//it为子节点
it.setType((Integer.parseInt(treeNode.getType())+1)+"");
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<DictTreeNode>());
}
treeNode.getChildren().add(findChildren(it,treeNodes));
}
}
return treeNode;
}
}
| 1,985 | 0.549559 | 0.548002 | 62 | 30.016129 | 25.022888 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387097 | false | false | 13 |
84d2c30ceeb578f43e96881c09c69433c988723c | 6,451,040,891,475 | 190a7c2894862dfbf01ea751c95bfe608d788703 | /splash/src/com/kainotomia/start/TrackPad.java | 710e913768448bb140d977ed83d838cb4f58e1bf | []
| no_license | IamAKX/Old-projects | https://github.com/IamAKX/Old-projects | 38cfab8254a985f254ab28bd7a8161a648d2345f | d7f6113a17fdf17a141ca69c038214826256fef6 | refs/heads/master | 2021-01-10T17:50:05.028000 | 2016-03-16T12:10:19 | 2016-03-16T12:10:19 | 53,965,078 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kainotomia.start;
import org.apache.http.conn.ClientConnectionManager;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class TrackPad extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.trackpad);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
/*if(event.equals(MotionEvent.ACTION_MOVE))
{
}*/
float x=event.getX();
float y=event.getY();
//String data="Motion x="+x+"ex y="+y+"ey";
String data="#x"+x+"y"+y;
client.launching(data);
//System.out.println("x = "+x+" y = "+y);
return super.onTouchEvent(event);
}
public void right(View view)
{
client.launching("rightclick");
}
public void left(View view)
{
client.launching("leftclick");
}
}
| UTF-8 | Java | 1,114 | java | TrackPad.java | Java | []
| null | []
| package com.kainotomia.start;
import org.apache.http.conn.ClientConnectionManager;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class TrackPad extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.trackpad);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
/*if(event.equals(MotionEvent.ACTION_MOVE))
{
}*/
float x=event.getX();
float y=event.getY();
//String data="Motion x="+x+"ex y="+y+"ey";
String data="#x"+x+"y"+y;
client.launching(data);
//System.out.println("x = "+x+" y = "+y);
return super.onTouchEvent(event);
}
public void right(View view)
{
client.launching("rightclick");
}
public void left(View view)
{
client.launching("leftclick");
}
}
| 1,114 | 0.7307 | 0.7307 | 44 | 24.318182 | 22.700394 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.545455 | false | false | 13 |
d7e3b6f9f2a554f9f4dbfadec7fc19440ab7ba74 | 16,398,185,173,585 | 647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4 | /com.tencent.mm/classes.jar/com/tencent/mm/plugin/scanner/l$h.java | 95fbe82c8b0b8dbfb6fb631b43cf1d33d6b4d641 | []
| no_license | tsuzcx/qq_apk | https://github.com/tsuzcx/qq_apk | 0d5e792c3c7351ab781957bac465c55c505caf61 | afe46ef5640d0ba6850cdefd3c11badbd725a3f6 | refs/heads/main | 2022-07-02T10:32:11.651000 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | false | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | 2022-01-31T06:56:43 | 2022-01-31T09:46:26 | 167,304 | 0 | 1 | 1 | Java | false | false | package com.tencent.mm.plugin.scanner;
public final class l$h
{
public static final int icons_outlined_more = 2131691045;
public static final int scan_no_network_error = 2131691713;
public static final int scan_no_result_error = 2131691714;
public static final int scan_success_mark_dot = 2131691717;
public static final int scan_success_mark_dot_with_arrow = 2131691718;
public static final int scan_translation = 2131691719;
public static final int scan_translation_hl = 2131691720;
public static final int scan_without_commodity_icon = 2131691721;
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes6.jar
* Qualified Name: com.tencent.mm.plugin.scanner.l.h
* JD-Core Version: 0.7.0.1
*/ | UTF-8 | Java | 766 | java | l$h.java | Java | []
| null | []
| package com.tencent.mm.plugin.scanner;
public final class l$h
{
public static final int icons_outlined_more = 2131691045;
public static final int scan_no_network_error = 2131691713;
public static final int scan_no_result_error = 2131691714;
public static final int scan_success_mark_dot = 2131691717;
public static final int scan_success_mark_dot_with_arrow = 2131691718;
public static final int scan_translation = 2131691719;
public static final int scan_translation_hl = 2131691720;
public static final int scan_without_commodity_icon = 2131691721;
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes6.jar
* Qualified Name: com.tencent.mm.plugin.scanner.l.h
* JD-Core Version: 0.7.0.1
*/ | 766 | 0.723238 | 0.612272 | 23 | 31.565218 | 29.687981 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 13 |
85d5f4a328596e71ef356eb6e468abdf22563433 | 2,482,491,160,447 | e02ec2f605a02d91de8e550e7b4dc6577be218a0 | /server/src/main/java/com/example/server/src/main/java/edu/byu/cs/tweeter/server/dao/FollowDAOM3.java | 1d3e726250e04939bfc78083bc2a8ed283bad8da | []
| no_license | Jobo97/CS340_Course_Project | https://github.com/Jobo97/CS340_Course_Project | 55dda06f9e7210defcea3dd53863a0278784cf5b | 23a2f67a3059a7497d6a1aeba0b690c410c91343 | refs/heads/master | 2023-04-07T23:22:41.736000 | 2021-04-14T18:39:50 | 2021-04-14T18:39:50 | 335,785,970 | 0 | 0 | null | false | 2021-04-14T18:39:51 | 2021-02-03T23:44:57 | 2021-04-14T18:37:32 | 2021-04-14T18:39:50 | 57,597 | 0 | 0 | 0 | Java | false | false | package com.example.server.src.main.java.edu.byu.cs.tweeter.server.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.domain.User;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.request.FollowCountRequest;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.request.FollowRequest;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.request.UserFollowRequest;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.response.FollowCountResponse;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.response.FollowResponse;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.response.UserFollowResponse;
/**
* A DAO for accessing 'following' data from the database.
*/
public class FollowDAOM3 {
private final User ben = new User("Ben", "Millett", "@benmillett", MALE_IMAGE_URL);
private final User michael = new User("Michael", "Skonnard", "@michaelskonnard", MALE_IMAGE_URL);
private final User carter = new User("Carter", "Wonnacott", "@carterwonnacott", MALE_IMAGE_URL);
private static final String MALE_IMAGE_URL = "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/donald_duck.png";
private static final String FEMALE_IMAGE_URL = "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png";
private final User user1 = new User("Allen", "Anderson", MALE_IMAGE_URL);
private final User user2 = new User("Amy", "Ames", FEMALE_IMAGE_URL);
private final User user3 = new User("Bob", "Bobson", MALE_IMAGE_URL);
private final User user4 = new User("Bonnie", "Beatty", FEMALE_IMAGE_URL);
private final User user5 = new User("Chris", "Colston", MALE_IMAGE_URL);
private final User user6 = new User("Cindy", "Coats", FEMALE_IMAGE_URL);
private final User user7 = new User("Dan", "Donaldson", MALE_IMAGE_URL);
private final User user8 = new User("Dee", "Dempsey", FEMALE_IMAGE_URL);
private final User user9 = new User("Elliott", "Enderson", MALE_IMAGE_URL);
private final User user10 = new User("Elizabeth", "Engle", FEMALE_IMAGE_URL);
private final User user11 = new User("Frank", "Frandson", MALE_IMAGE_URL);
private final User user12 = new User("Fran", "Franklin", FEMALE_IMAGE_URL);
private final User user13 = new User("Gary", "Gilbert", MALE_IMAGE_URL);
private final User user14 = new User("Giovanna", "Giles", FEMALE_IMAGE_URL);
private final User user15 = new User("Henry", "Henderson", MALE_IMAGE_URL);
private final User user16 = new User("Helen", "Hopwell", FEMALE_IMAGE_URL);
private final User user17 = new User("Igor", "Isaacson", MALE_IMAGE_URL);
private final User user18 = new User("Isabel", "Isaacson", FEMALE_IMAGE_URL);
private final User user19 = new User("Justin", "Jones", MALE_IMAGE_URL);
private final User user20 = new User("Jill", "Johnson", FEMALE_IMAGE_URL);
/**
* Gets the count of users from the database that the user specified is following. The
* current implementation uses generated data and doesn't actually access a database.
*
* @param follower the User whose count of how many following is desired.
* @return said count.
*/
public Integer getFolloweeCount(User follower) {
// TODO: uses the dummy data. Replace with a real implementation.
assert follower != null;
return getDummyFollowees().size();
}
/**
* Gets the users from the database that the user specified in the request is following. Uses
* information in the request object to limit the number of followees returned and to return the
* next set of followees after any that were returned in a previous request. The current
* implementation returns generated data and doesn't actually access a database.
*
* @param request contains information about the user whose followees are to be returned and any
* other information required to satisfy the request.
* @return the followees.
*/
public FollowResponse getFollows(FollowRequest request) {
// Used in place of assert statements because Android does not support them
// if(BuildConfig.DEBUG) {
// if(request.getLimit() < 0) {
// throw new AssertionError();
// }
//
// if(request.getFollowerAlias() == null) {
// throw new AssertionError();
// }
// }
List<User> allFollows;
if(request.getFollowerAlias() == null){
return new FollowResponse(null, false);
}
if (request.getFollower()) {
allFollows = getDummyFollowers();
}
else {
allFollows = getDummyFollowees();
}
List<User> responseFollows = new ArrayList<>(request.getLimit());
boolean hasMorePages = false;
if(request.getLimit() > 0) {
int followIndex = getStartingIndex(request.getLastFolloweeAlias(), allFollows);
for(int limitCounter = 0; followIndex < allFollows.size() && limitCounter < request.getLimit(); followIndex++, limitCounter++) {
responseFollows.add(allFollows.get(followIndex));
}
hasMorePages = followIndex < allFollows.size();
}
return new FollowResponse(responseFollows, hasMorePages);
}
/**
* Determines the index for the first followee in the specified 'allFollowees' list that should
* be returned in the current request. This will be the index of the next followee after the
* specified 'lastFollowee'.
*
* @param lastFolloweeAlias the alias of the last followee that was returned in the previous
* request or null if there was no previous request.
* @param allFollowees the generated list of followees from which we are returning paged results.
* @return the index of the first followee to be returned.
*/
private int getStartingIndex(String lastFolloweeAlias, List<User> allFollowees) {
int followeesIndex = 0;
if(lastFolloweeAlias != null) {
// This is a paged request for something after the first page. Find the first item
// we should return
for (int i = 0; i < allFollowees.size(); i++) {
if(lastFolloweeAlias.equals(allFollowees.get(i).getAlias())) {
// We found the index of the last item returned last time. Increment to get
// to the first one we should return
followeesIndex = i + 1;
break;
}
}
}
return followeesIndex;
}
public UserFollowResponse checkFollows(UserFollowRequest request) {
//Deal with error throwing for invalid data
Random random = new Random();
if (request.getUserAlias() == null){
return new UserFollowResponse(false, random.nextBoolean());
}
return new UserFollowResponse(true, random.nextBoolean());
}
public FollowCountResponse getFollowCount(FollowCountRequest request) {
//Ignore the request for dummy data only
if(request.getUserAlias() == null){
return new FollowCountResponse(false, 0, 0);
}
return new FollowCountResponse(true, getDummyFollowers().size(), getDummyFollowees().size());
}
public UserFollowResponse followStatus(UserFollowRequest request) {
if(request.getUserAlias() == null || request.getViewedAlias() == null){
return new UserFollowResponse(false, false);
}
Random random = new Random();
return new UserFollowResponse(true, random.nextBoolean());
}
/**
* Returns the list of dummy followee data. This is written as a separate method to allow
* mocking of the followees.
*
* @return the followees.
*/
public List<User> getDummyFollowees() {
return Arrays.asList(user1, user2, user3, user4, user5, user6, user7,
user8, user9, user10, user11, user12, user13, user14, user15, user16, user17, user18,
user19, user20);
}
List<User> getDummyFollowers() {
return Arrays.asList(michael, user2, user4, user6, user8, user10, user12, user14, user16, user18, user20);
}
}
| UTF-8 | Java | 8,495 | java | FollowDAOM3.java | Java | [
{
"context": "lowDAOM3 {\n private final User ben = new User(\"Ben\", \"Millett\", \"@benmillett\", MALE_IMAGE_URL);\n ",
"end": 990,
"score": 0.999747097492218,
"start": 987,
"tag": "NAME",
"value": "Ben"
},
{
"context": "3 {\n private final User ben = new User(\"Ben\", \"Millett\", \"@benmillett\", MALE_IMAGE_URL);\n private fin",
"end": 1001,
"score": 0.9998107552528381,
"start": 994,
"tag": "NAME",
"value": "Millett"
},
{
"context": "rivate final User ben = new User(\"Ben\", \"Millett\", \"@benmillett\", MALE_IMAGE_URL);\n private final User michael",
"end": 1016,
"score": 0.9166086912155151,
"start": 1004,
"tag": "USERNAME",
"value": "\"@benmillett"
},
{
"context": "_URL);\n private final User michael = new User(\"Michael\", \"Skonnard\", \"@michaelskonnard\", MALE_IMAGE_URL)",
"end": 1086,
"score": 0.999665379524231,
"start": 1079,
"tag": "NAME",
"value": "Michael"
},
{
"context": "private final User michael = new User(\"Michael\", \"Skonnard\", \"@michaelskonnard\", MALE_IMAGE_URL);\n privat",
"end": 1098,
"score": 0.9998151063919067,
"start": 1090,
"tag": "NAME",
"value": "Skonnard"
},
{
"context": "nal User michael = new User(\"Michael\", \"Skonnard\", \"@michaelskonnard\", MALE_IMAGE_URL);\n private final User carter ",
"end": 1118,
"score": 0.9843378663063049,
"start": 1101,
"tag": "USERNAME",
"value": "\"@michaelskonnard"
},
{
"context": "E_URL);\n private final User carter = new User(\"Carter\", \"Wonnacott\", \"@carterwonnacott\", MALE_IMAGE_URL",
"end": 1186,
"score": 0.9998160600662231,
"start": 1180,
"tag": "NAME",
"value": "Carter"
},
{
"context": " private final User carter = new User(\"Carter\", \"Wonnacott\", \"@carterwonnacott\", MALE_IMAGE_URL);\n\n priva",
"end": 1199,
"score": 0.9998039603233337,
"start": 1190,
"tag": "NAME",
"value": "Wonnacott"
},
{
"context": "inal User carter = new User(\"Carter\", \"Wonnacott\", \"@carterwonnacott\", MALE_IMAGE_URL);\n\n private static final Stri",
"end": 1219,
"score": 0.9561267495155334,
"start": 1202,
"tag": "USERNAME",
"value": "\"@carterwonnacott"
},
{
"context": "k.png\";\n\n private final User user1 = new User(\"Allen\", \"Anderson\", MALE_IMAGE_URL);\n private final ",
"end": 1544,
"score": 0.9997836351394653,
"start": 1539,
"tag": "NAME",
"value": "Allen"
},
{
"context": " private final User user1 = new User(\"Allen\", \"Anderson\", MALE_IMAGE_URL);\n private final User user2 =",
"end": 1556,
"score": 0.9997554421424866,
"start": 1548,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "GE_URL);\n private final User user2 = new User(\"Amy\", \"Ames\", FEMALE_IMAGE_URL);\n private final Us",
"end": 1620,
"score": 0.999755322933197,
"start": 1617,
"tag": "NAME",
"value": "Amy"
},
{
"context": ";\n private final User user2 = new User(\"Amy\", \"Ames\", FEMALE_IMAGE_URL);\n private final User user3",
"end": 1628,
"score": 0.9997477531433105,
"start": 1624,
"tag": "NAME",
"value": "Ames"
},
{
"context": "GE_URL);\n private final User user3 = new User(\"Bob\", \"Bobson\", MALE_IMAGE_URL);\n private final Us",
"end": 1694,
"score": 0.9998775124549866,
"start": 1691,
"tag": "NAME",
"value": "Bob"
},
{
"context": ";\n private final User user3 = new User(\"Bob\", \"Bobson\", MALE_IMAGE_URL);\n private final User user4 =",
"end": 1704,
"score": 0.9997090101242065,
"start": 1698,
"tag": "NAME",
"value": "Bobson"
},
{
"context": "GE_URL);\n private final User user4 = new User(\"Bonnie\", \"Beatty\", FEMALE_IMAGE_URL);\n private final ",
"end": 1771,
"score": 0.999808669090271,
"start": 1765,
"tag": "NAME",
"value": "Bonnie"
},
{
"context": " private final User user4 = new User(\"Bonnie\", \"Beatty\", FEMALE_IMAGE_URL);\n private final User user5",
"end": 1781,
"score": 0.9998010396957397,
"start": 1775,
"tag": "NAME",
"value": "Beatty"
},
{
"context": "GE_URL);\n private final User user5 = new User(\"Chris\", \"Colston\", MALE_IMAGE_URL);\n private final U",
"end": 1849,
"score": 0.999812126159668,
"start": 1844,
"tag": "NAME",
"value": "Chris"
},
{
"context": " private final User user5 = new User(\"Chris\", \"Colston\", MALE_IMAGE_URL);\n private final User user6 =",
"end": 1860,
"score": 0.9997968673706055,
"start": 1853,
"tag": "NAME",
"value": "Colston"
},
{
"context": "GE_URL);\n private final User user6 = new User(\"Cindy\", \"Coats\", FEMALE_IMAGE_URL);\n private final U",
"end": 1926,
"score": 0.9998123049736023,
"start": 1921,
"tag": "NAME",
"value": "Cindy"
},
{
"context": " private final User user6 = new User(\"Cindy\", \"Coats\", FEMALE_IMAGE_URL);\n private final User user7",
"end": 1935,
"score": 0.9998149275779724,
"start": 1930,
"tag": "NAME",
"value": "Coats"
},
{
"context": "GE_URL);\n private final User user7 = new User(\"Dan\", \"Donaldson\", MALE_IMAGE_URL);\n private final",
"end": 2001,
"score": 0.9998729228973389,
"start": 1998,
"tag": "NAME",
"value": "Dan"
},
{
"context": ";\n private final User user7 = new User(\"Dan\", \"Donaldson\", MALE_IMAGE_URL);\n private final User user8 =",
"end": 2014,
"score": 0.9997190237045288,
"start": 2005,
"tag": "NAME",
"value": "Donaldson"
},
{
"context": "GE_URL);\n private final User user8 = new User(\"Dee\", \"Dempsey\", FEMALE_IMAGE_URL);\n private final",
"end": 2078,
"score": 0.9998648762702942,
"start": 2075,
"tag": "NAME",
"value": "Dee"
},
{
"context": ";\n private final User user8 = new User(\"Dee\", \"Dempsey\", FEMALE_IMAGE_URL);\n private final User user9",
"end": 2089,
"score": 0.9997037053108215,
"start": 2082,
"tag": "NAME",
"value": "Dempsey"
},
{
"context": "GE_URL);\n private final User user9 = new User(\"Elliott\", \"Enderson\", MALE_IMAGE_URL);\n private final ",
"end": 2159,
"score": 0.9997816681861877,
"start": 2152,
"tag": "NAME",
"value": "Elliott"
},
{
"context": " private final User user9 = new User(\"Elliott\", \"Enderson\", MALE_IMAGE_URL);\n private final User user10 ",
"end": 2171,
"score": 0.9997272491455078,
"start": 2163,
"tag": "NAME",
"value": "Enderson"
},
{
"context": "E_URL);\n private final User user10 = new User(\"Elizabeth\", \"Engle\", FEMALE_IMAGE_URL);\n private final U",
"end": 2242,
"score": 0.9997481107711792,
"start": 2233,
"tag": "NAME",
"value": "Elizabeth"
},
{
"context": "rivate final User user10 = new User(\"Elizabeth\", \"Engle\", FEMALE_IMAGE_URL);\n private final User user1",
"end": 2251,
"score": 0.9997034072875977,
"start": 2246,
"tag": "NAME",
"value": "Engle"
},
{
"context": "E_URL);\n private final User user11 = new User(\"Frank\", \"Frandson\", MALE_IMAGE_URL);\n private final ",
"end": 2320,
"score": 0.999790370464325,
"start": 2315,
"tag": "NAME",
"value": "Frank"
},
{
"context": " private final User user11 = new User(\"Frank\", \"Frandson\", MALE_IMAGE_URL);\n private final User user12 ",
"end": 2332,
"score": 0.9997057914733887,
"start": 2324,
"tag": "NAME",
"value": "Frandson"
},
{
"context": "E_URL);\n private final User user12 = new User(\"Fran\", \"Franklin\", FEMALE_IMAGE_URL);\n private fina",
"end": 2398,
"score": 0.9997875690460205,
"start": 2394,
"tag": "NAME",
"value": "Fran"
},
{
"context": " private final User user12 = new User(\"Fran\", \"Franklin\", FEMALE_IMAGE_URL);\n private final User user1",
"end": 2410,
"score": 0.9997236132621765,
"start": 2402,
"tag": "NAME",
"value": "Franklin"
},
{
"context": "E_URL);\n private final User user13 = new User(\"Gary\", \"Gilbert\", MALE_IMAGE_URL);\n private final U",
"end": 2478,
"score": 0.9997856020927429,
"start": 2474,
"tag": "NAME",
"value": "Gary"
},
{
"context": " private final User user13 = new User(\"Gary\", \"Gilbert\", MALE_IMAGE_URL);\n private final User user14 ",
"end": 2489,
"score": 0.9997034072875977,
"start": 2482,
"tag": "NAME",
"value": "Gilbert"
},
{
"context": "E_URL);\n private final User user14 = new User(\"Giovanna\", \"Giles\", FEMALE_IMAGE_URL);\n private final U",
"end": 2559,
"score": 0.9997660517692566,
"start": 2551,
"tag": "NAME",
"value": "Giovanna"
},
{
"context": "private final User user14 = new User(\"Giovanna\", \"Giles\", FEMALE_IMAGE_URL);\n private final User user1",
"end": 2568,
"score": 0.999763011932373,
"start": 2563,
"tag": "NAME",
"value": "Giles"
},
{
"context": "E_URL);\n private final User user15 = new User(\"Henry\", \"Henderson\", MALE_IMAGE_URL);\n private final",
"end": 2637,
"score": 0.9997496604919434,
"start": 2632,
"tag": "NAME",
"value": "Henry"
},
{
"context": " private final User user15 = new User(\"Henry\", \"Henderson\", MALE_IMAGE_URL);\n private final User user16 ",
"end": 2650,
"score": 0.9997835755348206,
"start": 2641,
"tag": "NAME",
"value": "Henderson"
},
{
"context": "E_URL);\n private final User user16 = new User(\"Helen\", \"Hopwell\", FEMALE_IMAGE_URL);\n private final",
"end": 2717,
"score": 0.9997791647911072,
"start": 2712,
"tag": "NAME",
"value": "Helen"
},
{
"context": " private final User user16 = new User(\"Helen\", \"Hopwell\", FEMALE_IMAGE_URL);\n private final User user1",
"end": 2728,
"score": 0.9997690916061401,
"start": 2721,
"tag": "NAME",
"value": "Hopwell"
},
{
"context": "E_URL);\n private final User user17 = new User(\"Igor\", \"Isaacson\", MALE_IMAGE_URL);\n private final ",
"end": 2796,
"score": 0.9997747540473938,
"start": 2792,
"tag": "NAME",
"value": "Igor"
},
{
"context": " private final User user17 = new User(\"Igor\", \"Isaacson\", MALE_IMAGE_URL);\n private final User user18 ",
"end": 2808,
"score": 0.9997401237487793,
"start": 2800,
"tag": "NAME",
"value": "Isaacson"
},
{
"context": "E_URL);\n private final User user18 = new User(\"Isabel\", \"Isaacson\", FEMALE_IMAGE_URL);\n private fina",
"end": 2876,
"score": 0.9997711777687073,
"start": 2870,
"tag": "NAME",
"value": "Isabel"
},
{
"context": " private final User user18 = new User(\"Isabel\", \"Isaacson\", FEMALE_IMAGE_URL);\n private final User user1",
"end": 2888,
"score": 0.9997076988220215,
"start": 2880,
"tag": "NAME",
"value": "Isaacson"
},
{
"context": "E_URL);\n private final User user19 = new User(\"Justin\", \"Jones\", MALE_IMAGE_URL);\n private final Use",
"end": 2958,
"score": 0.9997578859329224,
"start": 2952,
"tag": "NAME",
"value": "Justin"
},
{
"context": " private final User user19 = new User(\"Justin\", \"Jones\", MALE_IMAGE_URL);\n private final User user20 ",
"end": 2967,
"score": 0.9996004700660706,
"start": 2962,
"tag": "NAME",
"value": "Jones"
},
{
"context": "E_URL);\n private final User user20 = new User(\"Jill\", \"Johnson\", FEMALE_IMAGE_URL);\n\n /**\n * G",
"end": 3033,
"score": 0.9997653961181641,
"start": 3029,
"tag": "NAME",
"value": "Jill"
},
{
"context": " private final User user20 = new User(\"Jill\", \"Johnson\", FEMALE_IMAGE_URL);\n\n /**\n * Gets the cou",
"end": 3044,
"score": 0.9997385740280151,
"start": 3037,
"tag": "NAME",
"value": "Johnson"
},
{
"context": "etDummyFollowers() {\n return Arrays.asList(michael, user2, user4, user6, user8, user10, user12",
"end": 8402,
"score": 0.9719514846801758,
"start": 8401,
"tag": "NAME",
"value": "m"
},
{
"context": "tDummyFollowers() {\n return Arrays.asList(michael, user2, user4, user6, user8, user10, user12, user",
"end": 8408,
"score": 0.6360602974891663,
"start": 8402,
"tag": "NAME",
"value": "ichael"
}
]
| null | []
| package com.example.server.src.main.java.edu.byu.cs.tweeter.server.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.domain.User;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.request.FollowCountRequest;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.request.FollowRequest;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.request.UserFollowRequest;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.response.FollowCountResponse;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.response.FollowResponse;
import com.example.shared.src.main.java.edu.byu.cs.tweeter.model.service.response.UserFollowResponse;
/**
* A DAO for accessing 'following' data from the database.
*/
public class FollowDAOM3 {
private final User ben = new User("Ben", "Millett", "@benmillett", MALE_IMAGE_URL);
private final User michael = new User("Michael", "Skonnard", "@michaelskonnard", MALE_IMAGE_URL);
private final User carter = new User("Carter", "Wonnacott", "@carterwonnacott", MALE_IMAGE_URL);
private static final String MALE_IMAGE_URL = "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/donald_duck.png";
private static final String FEMALE_IMAGE_URL = "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png";
private final User user1 = new User("Allen", "Anderson", MALE_IMAGE_URL);
private final User user2 = new User("Amy", "Ames", FEMALE_IMAGE_URL);
private final User user3 = new User("Bob", "Bobson", MALE_IMAGE_URL);
private final User user4 = new User("Bonnie", "Beatty", FEMALE_IMAGE_URL);
private final User user5 = new User("Chris", "Colston", MALE_IMAGE_URL);
private final User user6 = new User("Cindy", "Coats", FEMALE_IMAGE_URL);
private final User user7 = new User("Dan", "Donaldson", MALE_IMAGE_URL);
private final User user8 = new User("Dee", "Dempsey", FEMALE_IMAGE_URL);
private final User user9 = new User("Elliott", "Enderson", MALE_IMAGE_URL);
private final User user10 = new User("Elizabeth", "Engle", FEMALE_IMAGE_URL);
private final User user11 = new User("Frank", "Frandson", MALE_IMAGE_URL);
private final User user12 = new User("Fran", "Franklin", FEMALE_IMAGE_URL);
private final User user13 = new User("Gary", "Gilbert", MALE_IMAGE_URL);
private final User user14 = new User("Giovanna", "Giles", FEMALE_IMAGE_URL);
private final User user15 = new User("Henry", "Henderson", MALE_IMAGE_URL);
private final User user16 = new User("Helen", "Hopwell", FEMALE_IMAGE_URL);
private final User user17 = new User("Igor", "Isaacson", MALE_IMAGE_URL);
private final User user18 = new User("Isabel", "Isaacson", FEMALE_IMAGE_URL);
private final User user19 = new User("Justin", "Jones", MALE_IMAGE_URL);
private final User user20 = new User("Jill", "Johnson", FEMALE_IMAGE_URL);
/**
* Gets the count of users from the database that the user specified is following. The
* current implementation uses generated data and doesn't actually access a database.
*
* @param follower the User whose count of how many following is desired.
* @return said count.
*/
public Integer getFolloweeCount(User follower) {
// TODO: uses the dummy data. Replace with a real implementation.
assert follower != null;
return getDummyFollowees().size();
}
/**
* Gets the users from the database that the user specified in the request is following. Uses
* information in the request object to limit the number of followees returned and to return the
* next set of followees after any that were returned in a previous request. The current
* implementation returns generated data and doesn't actually access a database.
*
* @param request contains information about the user whose followees are to be returned and any
* other information required to satisfy the request.
* @return the followees.
*/
public FollowResponse getFollows(FollowRequest request) {
// Used in place of assert statements because Android does not support them
// if(BuildConfig.DEBUG) {
// if(request.getLimit() < 0) {
// throw new AssertionError();
// }
//
// if(request.getFollowerAlias() == null) {
// throw new AssertionError();
// }
// }
List<User> allFollows;
if(request.getFollowerAlias() == null){
return new FollowResponse(null, false);
}
if (request.getFollower()) {
allFollows = getDummyFollowers();
}
else {
allFollows = getDummyFollowees();
}
List<User> responseFollows = new ArrayList<>(request.getLimit());
boolean hasMorePages = false;
if(request.getLimit() > 0) {
int followIndex = getStartingIndex(request.getLastFolloweeAlias(), allFollows);
for(int limitCounter = 0; followIndex < allFollows.size() && limitCounter < request.getLimit(); followIndex++, limitCounter++) {
responseFollows.add(allFollows.get(followIndex));
}
hasMorePages = followIndex < allFollows.size();
}
return new FollowResponse(responseFollows, hasMorePages);
}
/**
* Determines the index for the first followee in the specified 'allFollowees' list that should
* be returned in the current request. This will be the index of the next followee after the
* specified 'lastFollowee'.
*
* @param lastFolloweeAlias the alias of the last followee that was returned in the previous
* request or null if there was no previous request.
* @param allFollowees the generated list of followees from which we are returning paged results.
* @return the index of the first followee to be returned.
*/
private int getStartingIndex(String lastFolloweeAlias, List<User> allFollowees) {
int followeesIndex = 0;
if(lastFolloweeAlias != null) {
// This is a paged request for something after the first page. Find the first item
// we should return
for (int i = 0; i < allFollowees.size(); i++) {
if(lastFolloweeAlias.equals(allFollowees.get(i).getAlias())) {
// We found the index of the last item returned last time. Increment to get
// to the first one we should return
followeesIndex = i + 1;
break;
}
}
}
return followeesIndex;
}
public UserFollowResponse checkFollows(UserFollowRequest request) {
//Deal with error throwing for invalid data
Random random = new Random();
if (request.getUserAlias() == null){
return new UserFollowResponse(false, random.nextBoolean());
}
return new UserFollowResponse(true, random.nextBoolean());
}
public FollowCountResponse getFollowCount(FollowCountRequest request) {
//Ignore the request for dummy data only
if(request.getUserAlias() == null){
return new FollowCountResponse(false, 0, 0);
}
return new FollowCountResponse(true, getDummyFollowers().size(), getDummyFollowees().size());
}
public UserFollowResponse followStatus(UserFollowRequest request) {
if(request.getUserAlias() == null || request.getViewedAlias() == null){
return new UserFollowResponse(false, false);
}
Random random = new Random();
return new UserFollowResponse(true, random.nextBoolean());
}
/**
* Returns the list of dummy followee data. This is written as a separate method to allow
* mocking of the followees.
*
* @return the followees.
*/
public List<User> getDummyFollowees() {
return Arrays.asList(user1, user2, user3, user4, user5, user6, user7,
user8, user9, user10, user11, user12, user13, user14, user15, user16, user17, user18,
user19, user20);
}
List<User> getDummyFollowers() {
return Arrays.asList(michael, user2, user4, user6, user8, user10, user12, user14, user16, user18, user20);
}
}
| 8,495 | 0.662036 | 0.651089 | 180 | 46.194443 | 36.580975 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 13 |
f8195d0ef4b537aaba7625a0e81687964c3510f5 | 5,171,140,667,217 | b7ae47c4ae4e9b5123ed4f2be44a36d934b89f77 | /EjercicioVeintidos.java | 19407fed31d0288237d4685438496c8ace96cddd | []
| no_license | fernandorvarela/EJERCICIOSJAVA | https://github.com/fernandorvarela/EJERCICIOSJAVA | fac2c3ea137feb7a27fa51225006d5b1df5f0c24 | 52f4bda391787b67cd240aef6493bc612042a14d | refs/heads/master | 2021-05-16T06:21:44.747000 | 2018-04-11T18:00:08 | 2018-04-11T18:00:08 | 103,433,883 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 ejercicioveintidos;
import java.util.Scanner;
/**
*
* @author wetsuit-skr
*/
public class EjercicioVeintidos {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/*se ingresa una nota, si es 10 mostrar excelente, si esta entre 9 y 4 mostrar
aprobó , de lo contrario mostrar “ la próxima será” .*/
Scanner sc= new Scanner(System.in);
Integer Nota;
System.out.println("Ingrese Nota");
Nota= sc.nextInt();
if (Nota >9) {
System.out.println("Excelente");
}else if (Nota >3) {
System.out.println("Aprobo");
}else{
System.out.println("La proxima será");
}
}
}
| UTF-8 | Java | 1,075 | java | EjercicioVeintidos.java | Java | [
{
"context": "\r\nimport java.util.Scanner;\r\n\r\n/**\r\n *\r\n * @author wetsuit-skr\r\n */\r\npublic class EjercicioVeintidos {\r\n\r\n /**\r",
"end": 281,
"score": 0.9525490403175354,
"start": 270,
"tag": "USERNAME",
"value": "wetsuit-skr"
}
]
| null | []
| /*
* 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 ejercicioveintidos;
import java.util.Scanner;
/**
*
* @author wetsuit-skr
*/
public class EjercicioVeintidos {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/*se ingresa una nota, si es 10 mostrar excelente, si esta entre 9 y 4 mostrar
aprobó , de lo contrario mostrar “ la próxima será” .*/
Scanner sc= new Scanner(System.in);
Integer Nota;
System.out.println("Ingrese Nota");
Nota= sc.nextInt();
if (Nota >9) {
System.out.println("Excelente");
}else if (Nota >3) {
System.out.println("Aprobo");
}else{
System.out.println("La proxima será");
}
}
}
| 1,075 | 0.528585 | 0.522962 | 44 | 22.25 | 21.726738 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.340909 | false | false | 13 |
6dbb67e32c8c9eb13d8193f2822dd42e4d97814d | 6,957,847,021,984 | da0c7138f80906e0af4be9da71b6a010f8007b84 | /family_order/src/web/com/asiainfo/veris/crm/order/web/person/sundryquery/voicemagzine12590/CancelCaptcha.java | 0bb739cce66c5a7546bfcc8591162bfb4a1cd5e6 | []
| no_license | bellmit/origin | https://github.com/bellmit/origin | 9d0e392cefc0f0c975ee042f2a7a93e3415ba7e6 | 9309074f033a53ba58144085cd044a660911ddb5 | refs/heads/master | 2022-12-02T16:08:42.301000 | 2020-08-21T05:34:24 | 2020-08-21T05:34:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asiainfo.veris.crm.order.web.person.sundryquery.voicemagzine12590;
import org.apache.log4j.Logger;
import com.ailk.common.data.IData;
import com.asiainfo.veris.crm.order.web.person.sundryquery.ibossutil.CommonSubmit;
public abstract class CancelCaptcha extends CommonSubmit {
static transient final Logger logger = Logger.getLogger(CancelCaptcha.class);
//删除灰名单
@Override
public String operateConditions() throws Exception{
IData pageData= getData("cond");
StringBuilder operateConditions = new StringBuilder();
operateConditions.append(pageData.getString("SUBMIT_MODE1", "")); //号码
operateConditions.append("|");
operateConditions.append(pageData.getString("SUBMIT_MODE2", "")); //省份
operateConditions.append("|");
operateConditions.append(pageData.getString("SUBMIT_MODE3", "")); //操作人员
return operateConditions.toString();
}
@Override
public String operateTypeId() throws Exception{
// TODO Auto-generated method stub
return "02004";
}
@Override
public String serviceTypeId() throws Exception{
// TODO Auto-generated method stub
return "121";
}
@Override
public String svctypeId() throws Exception{
// TODO Auto-generated method stub
return null;
}
@Override
public String kindId() throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 1,365 | java | CancelCaptcha.java | Java | []
| null | []
| package com.asiainfo.veris.crm.order.web.person.sundryquery.voicemagzine12590;
import org.apache.log4j.Logger;
import com.ailk.common.data.IData;
import com.asiainfo.veris.crm.order.web.person.sundryquery.ibossutil.CommonSubmit;
public abstract class CancelCaptcha extends CommonSubmit {
static transient final Logger logger = Logger.getLogger(CancelCaptcha.class);
//删除灰名单
@Override
public String operateConditions() throws Exception{
IData pageData= getData("cond");
StringBuilder operateConditions = new StringBuilder();
operateConditions.append(pageData.getString("SUBMIT_MODE1", "")); //号码
operateConditions.append("|");
operateConditions.append(pageData.getString("SUBMIT_MODE2", "")); //省份
operateConditions.append("|");
operateConditions.append(pageData.getString("SUBMIT_MODE3", "")); //操作人员
return operateConditions.toString();
}
@Override
public String operateTypeId() throws Exception{
// TODO Auto-generated method stub
return "02004";
}
@Override
public String serviceTypeId() throws Exception{
// TODO Auto-generated method stub
return "121";
}
@Override
public String svctypeId() throws Exception{
// TODO Auto-generated method stub
return null;
}
@Override
public String kindId() throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| 1,365 | 0.749066 | 0.73637 | 53 | 24.264151 | 25.569107 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.471698 | false | false | 13 |
ae460967672b2fb5f87f47495c41764333013d2e | 26,328,149,542,625 | 9222dccf5fe932b6e4d3bdb950af186ae02f71ee | /src/j2eetutorial14/examples/cb/saaj/src/com/sun/cb/OrderRequest.java | da2c0f8c5827c70c4c1a4aa3f2f87d44ee65b328 | []
| no_license | connaryscott/dukesbank | https://github.com/connaryscott/dukesbank | 7e9f7f9ab337522a435eb0a4863772ea16c83ef1 | 549585e51652054ab667dc2d4e65d6f385553ac6 | refs/heads/master | 2021-01-24T03:29:58.132000 | 2013-01-10T22:27:23 | 2013-01-10T22:27:23 | 1,304,055 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2006 Sun Microsystems, Inc. All rights reserved. U.S.
* Government Rights - Commercial software. Government users are subject
* to the Sun Microsystems, Inc. standard license agreement and
* applicable provisions of the FAR and its supplements. Use is subject
* to license terms.
*
* This distribution may include materials developed by third parties.
* Sun, Sun Microsystems, the Sun logo, Java and J2EE are trademarks
* or registered trademarks of Sun Microsystems, Inc. in the U.S. and
* other countries.
*
* Copyright (c) 2006 Sun Microsystems, Inc. Tous droits reserves.
*
* Droits du gouvernement americain, utilisateurs gouvernementaux - logiciel
* commercial. Les utilisateurs gouvernementaux sont soumis au contrat de
* licence standard de Sun Microsystems, Inc., ainsi qu'aux dispositions
* en vigueur de la FAR (Federal Acquisition Regulations) et des
* supplements a celles-ci. Distribue par des licences qui en
* restreignent l'utilisation.
*
* Cette distribution peut comprendre des composants developpes par des
* tierces parties. Sun, Sun Microsystems, le logo Sun, Java et J2EE
* sont des marques de fabrique ou des marques deposees de Sun
* Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
*/
package com.sun.cb;
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import javax.xml.soap.*;
public class OrderRequest {
String url;
public OrderRequest(String url) {
this.url = url;
}
public ConfirmationBean placeOrder(OrderBean orderBean) {
ConfirmationBean cb = null;
try {
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection con = scf.createConnection();
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
// Access the SOAPBody object
SOAPBody body = msg.getSOAPBody();
// Create the appropriate elements and add them
Name bodyName =
soapFactory.createName("coffee-order", "PO",
"http://sonata.coffeebreak.com");
SOAPBodyElement order = body.addBodyElement(bodyName);
// orderID
Name orderIDName = soapFactory.createName("orderID");
SOAPElement orderID = order.addChildElement(orderIDName);
orderID.addTextNode(orderBean.getId());
// customer
Name childName = soapFactory.createName("customer");
SOAPElement customer = order.addChildElement(childName);
childName = soapFactory.createName("last-name");
SOAPElement lastName = customer.addChildElement(childName);
lastName.addTextNode(orderBean.getCustomer().getLastName());
childName = soapFactory.createName("first-name");
SOAPElement firstName = customer.addChildElement(childName);
firstName.addTextNode(orderBean.getCustomer().getFirstName());
childName = soapFactory.createName("phone-number");
SOAPElement phoneNumber = customer.addChildElement(childName);
phoneNumber.addTextNode(orderBean.getCustomer().getPhoneNumber());
childName = soapFactory.createName("email-address");
SOAPElement emailAddress = customer.addChildElement(childName);
emailAddress.addTextNode(orderBean.getCustomer().getEmailAddress());
// address
childName = soapFactory.createName("address");
SOAPElement address = order.addChildElement(childName);
childName = soapFactory.createName("street");
SOAPElement street = address.addChildElement(childName);
street.addTextNode(orderBean.getAddress().getStreet());
childName = soapFactory.createName("city");
SOAPElement city = address.addChildElement(childName);
city.addTextNode(orderBean.getAddress().getCity());
childName = soapFactory.createName("state");
SOAPElement state = address.addChildElement(childName);
state.addTextNode(orderBean.getAddress().getState());
childName = soapFactory.createName("zip");
SOAPElement zip = address.addChildElement(childName);
zip.addTextNode(orderBean.getAddress().getZip());
LineItemBean[] lineItems = orderBean.getLineItems();
for (int i = 0; i < lineItems.length; i++) {
LineItemBean lib = lineItems[i];
childName = soapFactory.createName("line-item");
SOAPElement lineItem = order.addChildElement(childName);
childName = soapFactory.createName("coffeeName");
SOAPElement coffeeName = lineItem.addChildElement(childName);
coffeeName.addTextNode(lib.getCoffeeName());
childName = soapFactory.createName("pounds");
SOAPElement pounds = lineItem.addChildElement(childName);
pounds.addTextNode(lib.getPounds().toString());
childName = soapFactory.createName("price");
SOAPElement price = lineItem.addChildElement(childName);
price.addTextNode(lib.getPrice().toString());
}
// total
childName = soapFactory.createName("total");
SOAPElement total = order.addChildElement(childName);
total.addTextNode(orderBean.getTotal().toString());
URL endpoint = new URL(url);
SOAPMessage reply = con.call(msg, endpoint);
con.close();
// Extract content of reply
// Extract order ID and ship date
SOAPBody sBody = reply.getSOAPBody();
Iterator bodyIt = sBody.getChildElements();
SOAPBodyElement sbEl = (SOAPBodyElement) bodyIt.next();
Iterator bodyIt2 = sbEl.getChildElements();
// Get orderID
SOAPElement ID = (SOAPElement) bodyIt2.next();
String id = ID.getValue();
// Get ship date
SOAPElement sDate = (SOAPElement) bodyIt2.next();
String shippingDate = sDate.getValue();
SimpleDateFormat df =
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = df.parse(shippingDate);
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cb = new ConfirmationBean(id, cal);
} catch (Exception e) {
e.printStackTrace();
}
return cb;
}
}
| UTF-8 | Java | 6,729 | java | OrderRequest.java | Java | []
| null | []
| /*
* Copyright (c) 2006 Sun Microsystems, Inc. All rights reserved. U.S.
* Government Rights - Commercial software. Government users are subject
* to the Sun Microsystems, Inc. standard license agreement and
* applicable provisions of the FAR and its supplements. Use is subject
* to license terms.
*
* This distribution may include materials developed by third parties.
* Sun, Sun Microsystems, the Sun logo, Java and J2EE are trademarks
* or registered trademarks of Sun Microsystems, Inc. in the U.S. and
* other countries.
*
* Copyright (c) 2006 Sun Microsystems, Inc. Tous droits reserves.
*
* Droits du gouvernement americain, utilisateurs gouvernementaux - logiciel
* commercial. Les utilisateurs gouvernementaux sont soumis au contrat de
* licence standard de Sun Microsystems, Inc., ainsi qu'aux dispositions
* en vigueur de la FAR (Federal Acquisition Regulations) et des
* supplements a celles-ci. Distribue par des licences qui en
* restreignent l'utilisation.
*
* Cette distribution peut comprendre des composants developpes par des
* tierces parties. Sun, Sun Microsystems, le logo Sun, Java et J2EE
* sont des marques de fabrique ou des marques deposees de Sun
* Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
*/
package com.sun.cb;
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import javax.xml.soap.*;
public class OrderRequest {
String url;
public OrderRequest(String url) {
this.url = url;
}
public ConfirmationBean placeOrder(OrderBean orderBean) {
ConfirmationBean cb = null;
try {
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection con = scf.createConnection();
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
// Access the SOAPBody object
SOAPBody body = msg.getSOAPBody();
// Create the appropriate elements and add them
Name bodyName =
soapFactory.createName("coffee-order", "PO",
"http://sonata.coffeebreak.com");
SOAPBodyElement order = body.addBodyElement(bodyName);
// orderID
Name orderIDName = soapFactory.createName("orderID");
SOAPElement orderID = order.addChildElement(orderIDName);
orderID.addTextNode(orderBean.getId());
// customer
Name childName = soapFactory.createName("customer");
SOAPElement customer = order.addChildElement(childName);
childName = soapFactory.createName("last-name");
SOAPElement lastName = customer.addChildElement(childName);
lastName.addTextNode(orderBean.getCustomer().getLastName());
childName = soapFactory.createName("first-name");
SOAPElement firstName = customer.addChildElement(childName);
firstName.addTextNode(orderBean.getCustomer().getFirstName());
childName = soapFactory.createName("phone-number");
SOAPElement phoneNumber = customer.addChildElement(childName);
phoneNumber.addTextNode(orderBean.getCustomer().getPhoneNumber());
childName = soapFactory.createName("email-address");
SOAPElement emailAddress = customer.addChildElement(childName);
emailAddress.addTextNode(orderBean.getCustomer().getEmailAddress());
// address
childName = soapFactory.createName("address");
SOAPElement address = order.addChildElement(childName);
childName = soapFactory.createName("street");
SOAPElement street = address.addChildElement(childName);
street.addTextNode(orderBean.getAddress().getStreet());
childName = soapFactory.createName("city");
SOAPElement city = address.addChildElement(childName);
city.addTextNode(orderBean.getAddress().getCity());
childName = soapFactory.createName("state");
SOAPElement state = address.addChildElement(childName);
state.addTextNode(orderBean.getAddress().getState());
childName = soapFactory.createName("zip");
SOAPElement zip = address.addChildElement(childName);
zip.addTextNode(orderBean.getAddress().getZip());
LineItemBean[] lineItems = orderBean.getLineItems();
for (int i = 0; i < lineItems.length; i++) {
LineItemBean lib = lineItems[i];
childName = soapFactory.createName("line-item");
SOAPElement lineItem = order.addChildElement(childName);
childName = soapFactory.createName("coffeeName");
SOAPElement coffeeName = lineItem.addChildElement(childName);
coffeeName.addTextNode(lib.getCoffeeName());
childName = soapFactory.createName("pounds");
SOAPElement pounds = lineItem.addChildElement(childName);
pounds.addTextNode(lib.getPounds().toString());
childName = soapFactory.createName("price");
SOAPElement price = lineItem.addChildElement(childName);
price.addTextNode(lib.getPrice().toString());
}
// total
childName = soapFactory.createName("total");
SOAPElement total = order.addChildElement(childName);
total.addTextNode(orderBean.getTotal().toString());
URL endpoint = new URL(url);
SOAPMessage reply = con.call(msg, endpoint);
con.close();
// Extract content of reply
// Extract order ID and ship date
SOAPBody sBody = reply.getSOAPBody();
Iterator bodyIt = sBody.getChildElements();
SOAPBodyElement sbEl = (SOAPBodyElement) bodyIt.next();
Iterator bodyIt2 = sbEl.getChildElements();
// Get orderID
SOAPElement ID = (SOAPElement) bodyIt2.next();
String id = ID.getValue();
// Get ship date
SOAPElement sDate = (SOAPElement) bodyIt2.next();
String shippingDate = sDate.getValue();
SimpleDateFormat df =
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = df.parse(shippingDate);
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cb = new ConfirmationBean(id, cal);
} catch (Exception e) {
e.printStackTrace();
}
return cb;
}
}
| 6,729 | 0.639768 | 0.637688 | 181 | 36.176796 | 28.817039 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569061 | false | false | 13 |
003aed9b5d7abed46cf18ec157ca1681b6c1bd95 | 18,245,021,132,818 | f04222ce2306388d04e4aaa02847a053a1de4dee | /SampleJava/src/Demos/Sess10_Program2.java | 44bfbe8431f6df806260d7491e521ef2928c327c | []
| no_license | BhavaniPericherla/test | https://github.com/BhavaniPericherla/test | 5dea412270810c5538e690a413095e7779cc7855 | 3f62fbad4f124ddcda225304e85792a2deb665f2 | refs/heads/master | 2020-07-27T21:28:48.611000 | 2019-09-18T05:44:34 | 2019-09-18T05:44:34 | 209,220,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sample;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/*2.Write a program to Add 7 entries of type String into HashMap and then print all the values in 3 possible ways.*/
public class Sess10_Program2
{
public static void main(String[] args)
{
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("S","Kumari");
hm.put("P", "Bhavani");
hm.put("J", "Ramu");
hm.put("T", "Raju");
hm.put("R", "Raju");
hm.put("V", "Vidhya");
hm.put("K", "Krishna");
// Type 1:
System.out.println("Type1: To get all the values in Java 8");
hm.values().stream().forEach((value)->System.out.println(value));
// Type 2:
System.out.println("Type2: To get all the values using Collection and for each loop");
Collection<String> c1=hm.values();
for(String str:c1)
System.out.println(str);
//Type 3:
System.out.println("Type3:To print all the keys by using Iterator Cursor");
Collection<String> set= hm.values();
Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
String ent= itr.next();
System.out.println(ent);
}
/*System.out.println("To get all the values and keys using Collection and for each loop");
Set<Entry<String,String>> entries=hm.entrySet();
for(Entry<String,String> entry:entries)
System.out.println(entry);*/
}
}
| UTF-8 | Java | 1,500 | java | Sess10_Program2.java | Java | [
{
"context": "= new HashMap<String,String>();\r\n\t hm.put(\"S\",\"Kumari\");\r\n\t hm.put(\"P\", \"Bhavani\");\r\n\t hm.put(",
"end": 460,
"score": 0.715742826461792,
"start": 457,
"tag": "NAME",
"value": "Kum"
},
{
"context": ");\r\n\t hm.put(\"S\",\"Kumari\");\r\n\t hm.put(\"P\", \"Bhavani\");\r\n\t hm.put(\"J\", \"Ramu\");\r\n\t hm.put(\"T\", \"",
"end": 493,
"score": 0.9839678406715393,
"start": 486,
"tag": "NAME",
"value": "Bhavani"
},
{
"context": "\r\n\t hm.put(\"P\", \"Bhavani\");\r\n\t hm.put(\"J\", \"Ramu\");\r\n\t hm.put(\"T\", \"Raju\");\r\n\t hm.put(\"R\", \"",
"end": 520,
"score": 0.9817163944244385,
"start": 516,
"tag": "NAME",
"value": "Ramu"
},
{
"context": "\");\r\n\t hm.put(\"J\", \"Ramu\");\r\n\t hm.put(\"T\", \"Raju\");\r\n\t hm.put(\"R\", \"Raju\");\r\n\t hm.put(\"V\", \"",
"end": 547,
"score": 0.8888006210327148,
"start": 543,
"tag": "NAME",
"value": "Raju"
},
{
"context": "\");\r\n\t hm.put(\"T\", \"Raju\");\r\n\t hm.put(\"R\", \"Raju\");\r\n\t hm.put(\"V\", \"Vidhya\");\r\n\t hm.put(\"K\",",
"end": 574,
"score": 0.9294142723083496,
"start": 570,
"tag": "NAME",
"value": "Raju"
},
{
"context": "\");\r\n\t hm.put(\"R\", \"Raju\");\r\n\t hm.put(\"V\", \"Vidhya\");\r\n\t hm.put(\"K\", \"Krishna\");\r\n\r\n\t\t// Type 1:\r",
"end": 603,
"score": 0.9541568756103516,
"start": 597,
"tag": "NAME",
"value": "Vidhya"
},
{
"context": ";\r\n\t hm.put(\"V\", \"Vidhya\");\r\n\t hm.put(\"K\", \"Krishna\");\r\n\r\n\t\t// Type 1:\r\n\t\tSystem.out.println(\"Type1: ",
"end": 633,
"score": 0.9948144555091858,
"start": 626,
"tag": "NAME",
"value": "Krishna"
}
]
| null | []
| package sample;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/*2.Write a program to Add 7 entries of type String into HashMap and then print all the values in 3 possible ways.*/
public class Sess10_Program2
{
public static void main(String[] args)
{
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("S","Kumari");
hm.put("P", "Bhavani");
hm.put("J", "Ramu");
hm.put("T", "Raju");
hm.put("R", "Raju");
hm.put("V", "Vidhya");
hm.put("K", "Krishna");
// Type 1:
System.out.println("Type1: To get all the values in Java 8");
hm.values().stream().forEach((value)->System.out.println(value));
// Type 2:
System.out.println("Type2: To get all the values using Collection and for each loop");
Collection<String> c1=hm.values();
for(String str:c1)
System.out.println(str);
//Type 3:
System.out.println("Type3:To print all the keys by using Iterator Cursor");
Collection<String> set= hm.values();
Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
String ent= itr.next();
System.out.println(ent);
}
/*System.out.println("To get all the values and keys using Collection and for each loop");
Set<Entry<String,String>> entries=hm.entrySet();
for(Entry<String,String> entry:entries)
System.out.println(entry);*/
}
}
| 1,500 | 0.639333 | 0.629333 | 53 | 26.301888 | 25.992441 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.90566 | false | false | 13 |
3ed460e954a026b4bcace1dfc58459a054ff93f5 | 11,716,670,816,673 | 57db4e05a3a825b0de45772c93c767300a0dd672 | /Semicolon/src/A.java | 4eb10b1a37ac405ca99071bd347f6abe9ae598dc | []
| no_license | Soundariya0104/Java-Sample-Programs | https://github.com/Soundariya0104/Java-Sample-Programs | fc8089858fcd49cde83755d683f60ada3535951d | 897e4fc8453a600afc5961500a48018121da29d4 | refs/heads/master | 2021-01-13T03:01:22.528000 | 2017-03-25T16:52:19 | 2017-03-25T16:52:19 | 77,056,866 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class A {
int a,b;
public static void add(int a,int b){
System.out.println(a+b);
}
public static void main(String args[]){
add(4,5);
}
}
| UTF-8 | Java | 157 | java | A.java | Java | []
| null | []
|
public class A {
int a,b;
public static void add(int a,int b){
System.out.println(a+b);
}
public static void main(String args[]){
add(4,5);
}
}
| 157 | 0.617834 | 0.605096 | 9 | 15.222222 | 14.061593 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.