blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
18b8d39c1d46590f8abae6fbbf77673732783c85
|
Java
|
yb3502660/Mock4J
|
/src/main/java/com/bingo/MockMain.java
|
UTF-8
| 346 | 1.515625 | 2 |
[] |
no_license
|
package com.bingo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author:yaobin
* @date:2021/4/26,11:55
*/
@SpringBootApplication
public class MockMain {
public static void main(String[] args) {
SpringApplication.run(MockMain.class, args);
}
}
| true |
3ebf8dc23be839d86cfba39f24b253c82c58a978
|
Java
|
jdesjean/InterviewPrep
|
/InterviewPrep/src/org/ip/bst/ConvertBSTToSortedToSortedCircularDoublyLinkedList.java
|
UTF-8
| 4,274 | 3.140625 | 3 |
[] |
no_license
|
package org.ip.bst;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import org.ip.Test;
/**
* <a href="https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/">LC: 426</a>
*/
public class ConvertBSTToSortedToSortedCircularDoublyLinkedList {
public static void main(String[] s) {
Object[] tc1 = new Object[] {new Integer[] {}, new Integer[] { null }};
Object[] tc2 = new Object[] {new Integer[] {1,2}, new Integer[] { 2,1 } };
Object[] tc3 = new Object[] {new Integer[] {1,2}, new Integer[] { 1,null,2 }};
Object[] tc4 = new Object[] {new Integer[] {1,2,3}, new Integer[] {2,1,3}};
Object[] tc5 = new Object[] {new Integer[] {1,2,3,4,5,6,7}, new Integer[] {4,2,6,1,3,5,7}};
Object[] tc6 = new Object[] {new Integer[] {1,2,3,4,5}, new Integer[] {4,2,5,1,3}};
Object[][] tcs = new Object[][] { tc1, tc2, tc3, tc4, tc5, tc6};
for (Object[] tc : tcs) {
tc[1] = Node.fromBfs((Integer[]) tc[1]);
}
Problem[] solvers = new Problem[] { new Solver() };
Test.apply(solvers, tcs);
}
static class Solver implements Problem {
@Override
public Node apply(Node t) {
AtomicReference<Node> tail = new AtomicReference<>();
AtomicReference<Node> head = new AtomicReference<>();
new InOrderConsumer(new LList(head, tail)).inOrder(t);
if (tail.get() != null) { // circular
tail.get().right = head.get();
}
return head.get();
}
static class LList implements Consumer<Node> {
private AtomicReference<Node> head;
private AtomicReference<Node> tail;
public LList(AtomicReference<Node> head, AtomicReference<Node> tail) {
this.head = head;
this.tail = tail;
}
@Override
public void accept(Node node) {
Node prev = tail.get();
node.left = prev;
if (prev != null) {
prev.right = node;
}
tail.set(node);
head.compareAndSet(null, node);
head.get().left = node;
}
}
static class InOrderConsumer {
private Consumer<Node> consumer;
public InOrderConsumer(Consumer<Node> consumer) {
this.consumer = consumer;
}
public void inOrder(Node current) {
if (current == null) return;
inOrder(current.left);
consumer.accept(current);
inOrder(current.right);
}
}
}
interface Problem extends Function<Node, Node> {
}
public static class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int val) { this.val = val; }
public Node(int val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
public static int len(Node node) {
if (node == null) return 0;
int len = 1;
for (Node current = node.right; current != node; len++, current = current.right) {}
return len;
}
public static Node find(Node node, int k) {
if (node == null) return null;
if (node.val == k) return node;
Node left = find(node.left, k);
if (left != null) return left;
return find(node.right, k);
}
public static Node fromBfs(Integer[] values) {
if (values == null || values.length == 0 || values[0] == null) return null;
List<Node> parents = new ArrayList<>();
Node root = new Node(values[0]);
parents.add(root);
for (int i = 1; i < values.length;) {
List<Node> childs = new ArrayList<Node>(parents.size() * 2);
for (Node parent : parents) {
Integer left = i < values.length ? values[i++] : null;
Integer right = i < values.length ? values[i++] : null;
if (left != null) {
parent.left = new Node(left);
childs.add(parent.left);
}
if (right != null) {
parent.right = new Node(right);
childs.add(parent.right);
}
}
parents = childs;
}
return root;
}
@Override
public String toString() {
Node node = this;
Integer[] values = new Integer[Node.len(this)];
for (int i = 0; i < values.length; i++) {
values[i] = node.val;
node = node.right;
}
return Arrays.toString(values);
}
}
}
| true |
ea9e5ea62c170f22b1c72c628fa9d7edda54934e
|
Java
|
guanggege521/MyChina
|
/app/src/main/java/com/example/my_china/homepage/home_activity/Utils.java
|
UTF-8
| 2,475 | 2.140625 | 2 |
[] |
no_license
|
package com.example.my_china.homepage.home_activity;
import android.os.Handler;
import com.example.my_china.homepage.home_activity.bean.ZhengHe_DongTai;
import com.example.my_china.homepage.home_activity.bean.ZhongHe_BoKe;
import com.example.my_china.homepage.home_activity.bean.ZhongHe_ZiXun;
import com.thoughtworks.xstream.XStream;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by 吴肖光 on 2017/11/1.
*/
public class Utils {
public void getOkHttp(final String url, final Handler handler){
OkHttpClient okHttpClient=new OkHttpClient();
Request build = new Request.Builder().url("http://www.oschina.net/" + url).build();
okHttpClient.newCall(build).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
XStream xStream=new XStream();
if(url.indexOf("action/api/news_list")!=-1){
xStream.alias("oschina", ZhongHe_ZiXun.class);
xStream.alias("news", ZhongHe_ZiXun.NewsBean.class);
xStream.alias("newstype", ZhongHe_ZiXun.NewsBean.NewstypeBean.class);
ZhongHe_ZiXun zhongHe_ziXun = (ZhongHe_ZiXun) xStream.fromXML(string);
handler.obtainMessage(100,zhongHe_ziXun).sendToTarget();
return;
}else if(url.indexOf("action/api/blog_list")!=-1){
xStream.alias("oschina", ZhongHe_BoKe.class);
xStream.alias("blog", ZhongHe_BoKe.BlogBean.class);
ZhongHe_BoKe zhongHe_boKe = (ZhongHe_BoKe) xStream.fromXML(string);
handler.obtainMessage(101,zhongHe_boKe).sendToTarget();
return;
}else if(url.indexOf("action/api/tweet_list")!=-1){
xStream.alias("oschina", ZhengHe_DongTai.class);
xStream.alias("tweet",ZhengHe_DongTai.TweetBean.class);
ZhengHe_DongTai zhongHe_dongtai = (ZhengHe_DongTai) xStream.fromXML(string);
handler.obtainMessage(102,zhongHe_dongtai).sendToTarget();
}
}
});
}
}
| true |
151b2b6d9dab80aa5d35a31a630d897fb37572bf
|
Java
|
FWdarling/DesignPattern
|
/src/main/java/extensionobjects/concreteextensions/Injury.java
|
UTF-8
| 585 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
package extensionobjects.concreteextensions;
import extensionobjects.Race;
import extensionobjects.abstractextensions.InjuryOvertime;
/**
* 继承并实现 InjuryOvertime 类。实现其扩展功能。
*/
public class Injury extends InjuryOvertime {
public Injury(Race race) {
super(race);
}
/**
* 设置加时赛
* @param overtime int
*/
@Override
public void SetOvertime(int overtime) {
race.Overtime(overtime);
System.out.println("Set an injury overtime for " + overtime + " minutes");
race.GetTime();
}
}
| true |
5a7727f01348fe3e53c53f66c38517404aea51ca
|
Java
|
alipay/alipay-sdk-java-all
|
/v2/src/main/java/com/alipay/api/domain/SettleConfirmExtendParams.java
|
UTF-8
| 697 | 1.789063 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 确认结算接口扩展字段模型
*
* @author auto create
* @since 1.0, 2021-11-26 17:20:00
*/
public class SettleConfirmExtendParams extends AlipayObject {
private static final long serialVersionUID = 6288298151614646731L;
/**
* 是否进行资金冻结,用于后续分账,true表示冻结,false或不传表示不冻结
*/
@ApiField("royalty_freeze")
private String royaltyFreeze;
public String getRoyaltyFreeze() {
return this.royaltyFreeze;
}
public void setRoyaltyFreeze(String royaltyFreeze) {
this.royaltyFreeze = royaltyFreeze;
}
}
| true |
ec974640d230db81b8dc9e417b2eac33bf6b823e
|
Java
|
alireza-ebrahimi/telegram-talaeii
|
/5.3.5/sources/com/google/android/gms/internal/zzcii.java
|
UTF-8
| 2,723 | 1.75 | 2 |
[] |
no_license
|
package com.google.android.gms.internal;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.zzbq;
public final class zzcii extends zzbgl {
public static final Creator<zzcii> CREATOR = new zzcij();
public String packageName;
private int versionCode;
public String zzjgm;
public zzcnl zzjgn;
public long zzjgo;
public boolean zzjgp;
public String zzjgq;
public zzcix zzjgr;
public long zzjgs;
public zzcix zzjgt;
public long zzjgu;
public zzcix zzjgv;
zzcii(int i, String str, String str2, zzcnl zzcnl, long j, boolean z, String str3, zzcix zzcix, long j2, zzcix zzcix2, long j3, zzcix zzcix3) {
this.versionCode = i;
this.packageName = str;
this.zzjgm = str2;
this.zzjgn = zzcnl;
this.zzjgo = j;
this.zzjgp = z;
this.zzjgq = str3;
this.zzjgr = zzcix;
this.zzjgs = j2;
this.zzjgt = zzcix2;
this.zzjgu = j3;
this.zzjgv = zzcix3;
}
zzcii(zzcii zzcii) {
this.versionCode = 1;
zzbq.checkNotNull(zzcii);
this.packageName = zzcii.packageName;
this.zzjgm = zzcii.zzjgm;
this.zzjgn = zzcii.zzjgn;
this.zzjgo = zzcii.zzjgo;
this.zzjgp = zzcii.zzjgp;
this.zzjgq = zzcii.zzjgq;
this.zzjgr = zzcii.zzjgr;
this.zzjgs = zzcii.zzjgs;
this.zzjgt = zzcii.zzjgt;
this.zzjgu = zzcii.zzjgu;
this.zzjgv = zzcii.zzjgv;
}
zzcii(String str, String str2, zzcnl zzcnl, long j, boolean z, String str3, zzcix zzcix, long j2, zzcix zzcix2, long j3, zzcix zzcix3) {
this.versionCode = 1;
this.packageName = str;
this.zzjgm = str2;
this.zzjgn = zzcnl;
this.zzjgo = j;
this.zzjgp = z;
this.zzjgq = str3;
this.zzjgr = zzcix;
this.zzjgs = j2;
this.zzjgt = zzcix2;
this.zzjgu = j3;
this.zzjgv = zzcix3;
}
public final void writeToParcel(Parcel parcel, int i) {
int zze = zzbgo.zze(parcel);
zzbgo.zzc(parcel, 1, this.versionCode);
zzbgo.zza(parcel, 2, this.packageName, false);
zzbgo.zza(parcel, 3, this.zzjgm, false);
zzbgo.zza(parcel, 4, this.zzjgn, i, false);
zzbgo.zza(parcel, 5, this.zzjgo);
zzbgo.zza(parcel, 6, this.zzjgp);
zzbgo.zza(parcel, 7, this.zzjgq, false);
zzbgo.zza(parcel, 8, this.zzjgr, i, false);
zzbgo.zza(parcel, 9, this.zzjgs);
zzbgo.zza(parcel, 10, this.zzjgt, i, false);
zzbgo.zza(parcel, 11, this.zzjgu);
zzbgo.zza(parcel, 12, this.zzjgv, i, false);
zzbgo.zzai(parcel, zze);
}
}
| true |
8179611d05d95d73b22b086fc6cc79f5cb31011f
|
Java
|
cping/LGame
|
/Java/Loon-Lite(PureJava)/LoonLiteCore/src/loon/component/skin/ClickButtonSkin.java
|
UTF-8
| 2,518 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2008 - 2015 The Loon Game Engine Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loon
* @author cping
* @email:[email protected]
* @version 0.5
*/
package loon.component.skin;
import loon.LSystem;
import loon.LTexture;
import loon.canvas.LColor;
import loon.component.DefUI;
import loon.font.FontSet;
import loon.font.IFont;
public class ClickButtonSkin implements FontSet<ClickButtonSkin>{
private LTexture idleClickTexture;
private LTexture hoverClickTexture;
private LTexture disableTexture;
private IFont font;
private LColor fontColor;
public final static ClickButtonSkin def() {
return new ClickButtonSkin();
}
public ClickButtonSkin() {
this(LSystem.getSystemGameFont(), LColor.white.cpy(), DefUI.self().getDefaultTextures(7),
DefUI.self().getDefaultTextures(8), DefUI.self().getDefaultTextures(9));
}
public ClickButtonSkin(IFont font, LColor fontColor, LTexture idle,
LTexture hover, LTexture disable) {
this.font = font;
this.fontColor = fontColor;
this.idleClickTexture = idle;
this.hoverClickTexture = hover;
this.disableTexture = disable;
}
public LTexture getIdleClickTexture() {
return idleClickTexture;
}
public void setIdleClickTexture(LTexture idleClickTexture) {
this.idleClickTexture = idleClickTexture;
}
public LTexture getHoverClickTexture() {
return hoverClickTexture;
}
public void setHoverClickTexture(LTexture hoverClickTexture) {
this.hoverClickTexture = hoverClickTexture;
}
public LTexture getDisableTexture() {
return disableTexture;
}
public void setDisableTexture(LTexture disableTexture) {
this.disableTexture = disableTexture;
}
@Override
public IFont getFont() {
return font;
}
@Override
public ClickButtonSkin setFont(IFont font) {
this.font = font;
return this;
}
@Override
public LColor getFontColor() {
return fontColor.cpy();
}
@Override
public ClickButtonSkin setFontColor(LColor fontColor) {
this.fontColor = fontColor;
return this;
}
}
| true |
41d99e2178276b0e02223920f90b185cdc31cccf
|
Java
|
Aureliu/Jet
|
/jet/src/Jet/Pat/PatternView.java
|
UTF-8
| 11,144 | 2.390625 | 2 |
[
"Apache-2.0"
] |
permissive
|
// -*- tab-width: 4 -*-
//Title: JET
//Version: 1.00
//Copyright: Copyright (c) 2000
//Author: Ralph Grishman
//Description: A Java-based Information Extraction Tool
package Jet.Pat;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/**
* A view of the pattern as a tree.
*/
public class PatternView extends JFrame implements ActionListener {
PatternCollection pc;
DefaultMutableTreeNode patternsNode;
DefaultMutableTreeNode patternSetsNode;
JTree patternTree;
JScrollPane jScrollPane = new JScrollPane();
JFileChooser fc = new JFileChooser(".");
File currentFile;
Vector matchedPatterns = new Vector(); // Vector of String
Vector appliedPatterns = new Vector(); // Vector of String
public PatternView(File file) {
currentFile = file;
readPatterns();
buildTree();
jbInit();
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Open ...")) {
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
readPatterns();
buildTree();
patternTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
jScrollPane.getViewport().add(patternTree, null);
this.setTitle("Pattern View - " + currentFile.getPath());
}
}
else if (e.getActionCommand().equals("Expand")) {
TreePath path = patternTree.getSelectionPath();
if (path != null) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) path.getLastPathComponent();
expand(root);
}
}
else if (e.getActionCommand().equals("Collapse")) {
TreePath path = patternTree.getSelectionPath();
if (path != null) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) path.getLastPathComponent();
collapse(root);
}
}
else if (e.getActionCommand().equals("Expand All")) {
expand(patternsNode);
expand(patternSetsNode);
}
else if (e.getActionCommand().equals("Collapse All")) {
collapse(patternsNode);
collapse(patternSetsNode);
}
else if (e.getActionCommand().equals("Clear Marks")) {
clearMatchedPatterns();
clearAppliedPatterns();
refresh();
}
else { // e.getActionCommand().equals("Exit")
this.dispose();
}
}
public void addMatchedPattern(String pattern) {
matchedPatterns.add(pattern);
}
public void clearMatchedPatterns() {
matchedPatterns = new Vector();
}
public void addAppliedPattern(String pattern) {
appliedPatterns.add(pattern);
}
public void clearAppliedPatterns() {
appliedPatterns = new Vector();
}
public void refresh() {
/*System.out.println("matchedPatterns:");
for (int i = 0; i < matchedPatterns.size(); i++) {
System.out.println(matchedPatterns.get(i));
}*/
patternTree.updateUI();
}
private void buildTree() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
patternTree = new JTree(root);
patternTree.setRootVisible(false);
patternTree.setShowsRootHandles(true);
patternTree.setEditable(false);
patternTree.putClientProperty("JTree.lineStyle", "Angled");
patternTree.setCellRenderer(new PatternRenderer());
patternsNode = new DefaultMutableTreeNode("Patterns");
patternSetsNode = new DefaultMutableTreeNode("Pattern Sets");
root.add(patternsNode);
root.add(patternSetsNode);
DefaultMutableTreeNode parent;
DefaultMutableTreeNode child;
String name;
PatternElement pe;
PatternAlternation pa;
PatternSet ps;
PatternRule pr;
Action action;
for (int i = 0; i < pc.patternNames.size(); i++) {
name = (String) pc.patternNames.get(i);
child = new DefaultMutableTreeNode(name);
patternsNode.add(child);
parent = child;
pe = (PatternElement) pc.patterns.get(name);
if (pe instanceof PatternAlternation) {
pa = (PatternAlternation) pe;
for (int j = 0; j < pa.options.length; j++) {
child = new DefaultMutableTreeNode(pa.options[j].toString());
parent.add(child);
}
}
else {
child = new DefaultMutableTreeNode(pe.toString());
parent.add(child);
}
}
for (int i = 0; i < pc.patternSetNames.size(); i++) {
name = (String) pc.patternSetNames.get(i);
child = new DefaultMutableTreeNode("Pattern Set: " + name);
patternSetsNode.add(child);
parent = child;
ps = (PatternSet) pc.patternSets.get(name);
for (int j = 0; j < ps.rules.size(); j++) {
pr = (PatternRule) ps.rules.get(j);
child = new DefaultMutableTreeNode(pr.patternName);
parent.add(child);
for (int k = 0; k < pr.actions().size(); k++) {
action = (Action) pr.actions().get(k);
child.add(new DefaultMutableTreeNode(action));
}
}
}
patternTree.updateUI();
}
private void readPatterns() {
pc = new PatternCollection();
try {
pc.readPatternCollection(new BufferedReader(new FileReader(currentFile)));
}
catch (IOException e) {
System.err.println("Error: reading pattern file " +
currentFile.getName() + ", " + e.getMessage());
}
pc.makePatternGraph();
}
private void expand(DefaultMutableTreeNode root) {
patternTree.expandPath(new TreePath(root.getPath()));
for (int i = 0; i < root.getChildCount(); i++) {
expand((DefaultMutableTreeNode) root.getChildAt(i));
}
}
private void collapse(DefaultMutableTreeNode root) {
for (int i = 0; i < root.getChildCount(); i++) {
collapse((DefaultMutableTreeNode) root.getChildAt(i));
}
patternTree.collapsePath(new TreePath(root.getPath()));
}
private void jbInit() {
// Menu Bar
JMenuBar jmb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem item;
item = new JMenuItem("Open ...");
item.setMnemonic(KeyEvent.VK_O);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
fileMenu.add(item);
item.addActionListener(this);
fileMenu.addSeparator();
item = new JMenuItem("Exit");
item.setMnemonic(KeyEvent.VK_X);
fileMenu.add(item);
item.addActionListener(this);
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);
item = new JMenuItem("Expand");
item.setMnemonic(KeyEvent.VK_E);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
viewMenu.add(item);
item.addActionListener(this);
item = new JMenuItem("Collapse");
item.setMnemonic(KeyEvent.VK_C);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
viewMenu.add(item);
item.addActionListener(this);
item = new JMenuItem("Expand All");
item.setMnemonic(KeyEvent.VK_E);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK + ActionEvent.ALT_MASK));
viewMenu.add(item);
item.addActionListener(this);
item = new JMenuItem("Collapse All");
item.setMnemonic(KeyEvent.VK_C);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK + ActionEvent.ALT_MASK));
viewMenu.add(item);
item.addActionListener(this);
viewMenu.addSeparator();
item = new JMenuItem("Clear Marks");
item.setMnemonic(KeyEvent.VK_M);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK));
viewMenu.add(item);
item.addActionListener(this);
jmb.add(fileMenu);
jmb.add(viewMenu);
setJMenuBar(jmb);
// file chooser
Jet.Concepts.ConcreteFileFilter filter =
new Jet.Concepts.ConcreteFileFilter("pat", "Pattern Files (*.pat)");
fc.setFileFilter(filter);
fc.setDialogTitle("Open Pattern File");
fc.setApproveButtonText("Open");
fc.setApproveButtonMnemonic(KeyEvent.VK_O);
fc.setApproveButtonToolTipText("Open Pattern File");
// content pane
patternTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
jScrollPane.getViewport().add(patternTree, null);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(jScrollPane, BorderLayout.CENTER);
this.setSize(600, 600);
this.setTitle("Pattern View - " + currentFile.getPath());
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
PatternView.this.dispose();
}
});
}
class PatternRenderer extends DefaultTreeCellRenderer {
ImageIcon actionIcon;
ImageIcon matchIcon;
ImageIcon applyIcon;
PatternRenderer() {
actionIcon = new ImageIcon("images/fish.gif");
matchIcon = new ImageIcon("images/octopus.gif");
applyIcon = new ImageIcon("images/crab.gif");
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (leaf && isAction(value))
setIcon(actionIcon);
else if (!leaf && isMatched(value))
setIcon(matchIcon);
else if (!leaf && isApplied(value))
setIcon(applyIcon);
return this;
}
boolean isAction(Object value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
TreeNode[] path = node.getPath();
for (int i = 0; i < path.length; i++) {
if (((DefaultMutableTreeNode) path[i]).equals(patternSetsNode))
return true;
}
return false;
}
boolean isMatched(Object value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
String info = node.getUserObject().toString();
if (!matchedPatterns.contains(info))
return false;
TreeNode[] path = node.getPath();
for (int i = 0; i < path.length; i++) {
if (((DefaultMutableTreeNode) path[i]).equals(patternsNode))
return true;
}
return false;
}
boolean isApplied(Object value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
String info = node.getUserObject().toString();
if (!appliedPatterns.contains(info))
return false;
TreeNode[] path = node.getPath();
for (int i = 0; i < path.length; i++) {
if (((DefaultMutableTreeNode) path[i]).equals(patternSetsNode))
return true;
}
return false;
}
}
}
| true |
f019aef25cc70cda67c95dc1812828be5181e1c1
|
Java
|
mrlzy/reactjs
|
/src/main/java/com/mrlzy/shiro/dao/local/mapper/OrgMapper.java
|
UTF-8
| 1,524 | 1.773438 | 2 |
[] |
no_license
|
package com.mrlzy.shiro.dao.local.mapper;
import com.mrlzy.shiro.plugin.dto.CaseIgnoreDto;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface OrgMapper {
@Select("select org_id id,org_name text, (case when is_leaf=1 then 'item' else 'folder' end) type from sys_org where parent_id = #{parent_id} order by sortno asc ")
public List<Map<String,String>> treeComponentOrg(@Param("parent_id") String parent_id);
@Select("select org_id id,org_name text, (case when is_leaf=1 then 'item' else 'folder' end) type from sys_org where parent_id is null order by sortno asc ")
public List<Map<String,String>> treeComponentRootOrg();
@Select("select org_id,is_leaf leaf ,org_name,sortno,statu,parent_id,(select org_name from sys_org where t.parent_id=org_id) parent_name " +
" from sys_org t where org_id=#{parent_id} or weights like '%${parent_id}%' ${wherebuff} order by ${orderby} ")
public List<CaseIgnoreDto> listOrgByWeights(@Param("parent_id") String parent_id, @Param("wherebuff") String wherebuff, @Param("orderby") String orderby);
@Select("select weights||org_id from sys_org where org_name like '%${name}%'")
public List<String> listOrgPathByName(@Param("name")String name);
@Select("select replace(WMSYS.WM_CONCAT(org_name),',','=>') from sys_org where org_id in (${ids})")
public String listOrgNamesByIds(@Param("ids")String ids);
}
| true |
0bcc215bb08eebd0ceaaa862c4195e661e3369eb
|
Java
|
Shahrukh734/Selenium-Projects-
|
/src/com/pack/common/tests/Dream/myTools_AllTeamsTest.java
|
UTF-8
| 2,945 | 1.773438 | 2 |
[] |
no_license
|
package com.pack.common.tests.Dream;
import org.openqa.selenium.By;
import org.testng.Reporter;
import org.testng.annotations.Test;
import com.pack.base.TestBaseSetup;
import com.pack.common.pageobjects.Dream.contextsearch;
import com.pack.common.pageobjects.Dream.fetchingReports;
import com.pack.common.pageobjects.Dream.homePage;
import com.pack.common.pageobjects.Dream.myTools_AllTeams;
public class myTools_AllTeamsTest extends TestBaseSetup {
public myTools_AllTeams allteams ;
public fetchingReports fetchingreports;
@Test(enabled=true)
public void TC_MyTools_AllTeams() throws Throwable{
Reporter.log("Move The Cursor On My Tools");
fetchingreports=new fetchingReports(driver);
allteams= new myTools_AllTeams(driver);
Reporter.log("Click on All Teams From My Tools");
allteams.myToolsAllTeams(allteams.getlinkMyToolsAllTeams());
Reporter.log("Click On Request New Team Button");
allteams.getbtnRequestNewTeam().click();
fetchingreports.switchWindows();
Reporter.log("Enter the Details in New Request Team and Close the Window");
allteams.gettxtTeamName().sendKeys("abc");
allteams.drpdownTeamOwner(allteams.getTeamOwnerDrpdown(),"Md Mudassir Imam");
allteams.gettxtPurpose().sendKeys("Testing");
allteams.getbtnSubmit().click();
fetchingreports.getAlert();
allteams.switchToParentWindow();
}
//Donot Run this testcase there is a bug.
@Test(enabled=false)
public void TC_MyTools_AllTeams_AddRemoveFavourites() throws Throwable {
Reporter.log("Move The Cursor On My Tools");
fetchingreports=new fetchingReports(driver);
allteams= new myTools_AllTeams(driver);
Reporter.log("Click on All Teams From My Tools");
allteams.myToolsAllTeamsWithoutFrame(allteams.getlinkMyToolsAllTeams());
allteams.switchToFrame("ctl00_ctl00_BodyContent_radPaneRight");
Thread.sleep(4000);
allteams.SelectRecords(3);
allteams.getbtnAddToFavorites().click();
Thread.sleep(4000);
allteams.getradiobtnFavourites().click();
Thread.sleep(4000);
allteams.SelectRecords(3);
allteams.getbtnAddToFavorites().click();
}
@Test(enabled=true)
public void TC_myTools_AllTeams_TeamFilter() throws Throwable {
Reporter.log("Move The Cursor On My Tools");
fetchingreports=new fetchingReports(driver);
allteams= new myTools_AllTeams(driver);
Reporter.log("Click on All Teams From My Tools");
allteams.myToolsAllTeamsWithoutFrame(allteams.getlinkMyToolsAllTeams());
allteams.switchToFrame("ctl00_ctl00_BodyContent_radPaneRight");
Thread.sleep(4000);
allteams.getimgExpandTeamFilter().click();
allteams.drpdownTeamOwner(allteams.getlstTeamOwner(),"Babula Parida");
allteams.getbtnApplyFilter().click();
Thread.sleep(4000);
String teamname=allteams.getText(allteams.getlnkTeamName());
Thread.sleep(2000);
allteams.getimgExpandTeamFilter().click();
allteams.drpdownTeamOwner(allteams.getlstTeamName(),teamname);
allteams.getbtnApplyFilter().click();
Thread.sleep(2000);
}
}
| true |
2a7787240a782c50a1b6e8c008727cd19b80a4a4
|
Java
|
adorsys/secure-token-service
|
/sts-keymanagement/sts-keymanagement-api/src/main/java/de/adorsys/sts/keymanagement/service/KeyRotationService.java
|
UTF-8
| 260 | 1.671875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package de.adorsys.sts.keymanagement.service;
import de.adorsys.sts.keymanagement.model.KeyRotationResult;
import de.adorsys.sts.keymanagement.model.StsKeyStore;
public interface KeyRotationService {
KeyRotationResult rotate(StsKeyStore stsKeyStore);
}
| true |
40e699db7ca20033e7ca08dbeeef7428280e2f45
|
Java
|
sashokbg/docker-exercise
|
/src/main/java/com/devoteam/dockerexercise/VisitRepository.java
|
UTF-8
| 237 | 1.539063 | 2 |
[] |
no_license
|
package com.devoteam.dockerexercise;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VisitRepository extends CrudRepository<Visit, Integer> {
}
| true |
8697baac3cf20dc2068d917148208df8079f84dd
|
Java
|
lunar-logan/assemblage
|
/src/main/java/com/anurag/aggregator/common/type/TransportType.java
|
UTF-8
| 657 | 2.765625 | 3 |
[] |
no_license
|
package com.anurag.aggregator.common.type;
public enum TransportType {
HTTP("http"),
HTTPS("https"),
MQTT("mqtt"),
TCP("tcp");
private final String scheme;
TransportType(String scheme) {
this.scheme = scheme;
}
public String getScheme() {
return scheme;
}
public static TransportType fromScheme(String scheme) {
// TODO: Can be optimized (for eg. by maintaining a scheme => Type map)
for (TransportType transportType : TransportType.values()) {
if (transportType.getScheme().equals(scheme))
return transportType;
}
return null;
}
}
| true |
e1991bfc71a3a4b2ff8a106d0166d8260df4ade2
|
Java
|
gaoyuan117/MD
|
/app/src/main/java/com/gaoyuan/materialdesign/SnackBarActivity.java
|
UTF-8
| 2,417 | 2.3125 | 2 |
[] |
no_license
|
package com.gaoyuan.materialdesign;
import android.content.Context;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.gaoyuan.materialdesign.R;
public class SnackBarActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snack_bar);
}
/**
* 自定义Toast
* @param v
*/
public void showCustomToast(View v){
Toast toast = new Toast(this);
LayoutInflater inflate = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.custom_toast, null);
TextView tv = (TextView)view.findViewById(R.id.textView1);
tv.setText("自定义吐司在此!");
// toast.setGravity(gravity, xOffset, yOffset)
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
public void showSnackbar(View v){
//LENGTH_INDEFINITE:无穷
Snackbar snackbar = Snackbar.make(v, "是否开启加速模式?", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("确定", new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomToast(null);
}
});
//不能设置多个action,会被覆盖
snackbar.setAction("取消", new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomToast(null);
}
});
snackbar.setCallback(new Snackbar.Callback() {
@Override
public void onDismissed(Snackbar snackbar, int event) {//消失
Log.e("gy","onDismissed");
showCustomToast(null);
super.onDismissed(snackbar, event);
}
@Override
public void onShown(Snackbar snackbar) {//显示中
Log.e("gy","onShown");
super.onShown(snackbar);
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.show();
}
}
| true |
42d047104437f42c5a8630de72743d0b1d719c90
|
Java
|
iivaishnavii/Stack-1
|
/NextGreaterElement.java
|
UTF-8
| 613 | 3.109375 | 3 |
[] |
no_license
|
//TC : o(n) , length of nums array
//SC : O(n) , stack space
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> st = new Stack<>();
int[] result = new int[nums.length];
Arrays.fill(result,-1);
int n = nums.length;
for(int i=0;i<2*n;i++){
while(!st.isEmpty() && nums[st.peek()] < nums[i%n]){
int idx = st.pop();
result[idx] = nums[i%n];
}
if(i<n)
st.push(i%n);
}
return result;
}
}
| true |
3567155eccbeb62567026cbdc98e23624644cf43
|
Java
|
KimSeongGyu1/atdd-subway-favorite
|
/src/main/java/wooteco/subway/web/LineController.java
|
UTF-8
| 2,348 | 2.4375 | 2 |
[] |
no_license
|
package wooteco.subway.web;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import wooteco.subway.domain.line.Line;
import wooteco.subway.service.line.LineService;
import wooteco.subway.service.line.dto.*;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/lines")
public class LineController {
private LineService lineService;
public LineController(LineService lineService) {
this.lineService = lineService;
}
@PostMapping
public ResponseEntity<LineResponse> createLine(@RequestBody LineRequest view) {
Line persistLine = lineService.save(view.toLine());
return ResponseEntity
.created(URI.create("/lines/" + persistLine.getId()))
.body(LineResponse.of(persistLine));
}
@GetMapping
public ResponseEntity<List<LineResponse>> showLine() {
return ResponseEntity.ok().body(LineResponse.listOf(lineService.findLines()));
}
@GetMapping("/{id}")
public ResponseEntity<LineDetailResponse> retrieveLine(@PathVariable Long id) {
return ResponseEntity.ok().body(lineService.retrieveLine(id));
}
@PutMapping("/{id}")
public ResponseEntity<Void> updateLine(@PathVariable Long id, @RequestBody LineRequest view) {
lineService.updateLine(id, view);
return ResponseEntity.ok().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteLine(@PathVariable Long id) {
lineService.deleteLineById(id);
return ResponseEntity.noContent().build();
}
@PostMapping("/{id}/stations")
public ResponseEntity<Void> addLineStation(@PathVariable Long id, @RequestBody LineStationCreateRequest view) {
lineService.addLineStation(id, view);
return ResponseEntity.ok().build();
}
@DeleteMapping("/{lineId}/stations/{stationId}")
public ResponseEntity<Void> removeLineStation(@PathVariable Long lineId, @PathVariable Long stationId) {
lineService.removeLineStation(lineId, stationId);
return ResponseEntity.noContent().build();
}
@GetMapping("/detail")
public ResponseEntity<WholeSubwayResponse> wholeLines() {
WholeSubwayResponse result = lineService.findLinesWithStations();
return ResponseEntity.ok().body(result);
}
}
| true |
48f8b93d1e4a09d5024907bb8599f112b13cc609
|
Java
|
happylamp99/photo_album
|
/src/main/java/ict/methodologies/Photos/controllers/MenuController.java
|
UTF-8
| 2,378 | 2.6875 | 3 |
[] |
no_license
|
package ict.methodologies.Photos.controllers;
import ict.methodologies.Photos.PhotosApplication;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import java.io.IOException;
public class MenuController {
@FXML
private Button addPhotosBtn;
@FXML
private Button viewPhotosBtn;
public void onMouseClick(MouseEvent mouseEvent) throws IOException {
Button button = (Button) mouseEvent.getSource();
String buttonText = button.getText();
switch (buttonText) {
case ("Add Photos"):
try{
FXMLLoader loader=new FXMLLoader(getClass().getResource("/AddImages.fxml"));
Parent root = loader.load();
Stage stage = (Stage) addPhotosBtn.getScene().getWindow();
stage.hide();
PhotosApplication.getShowImagesStage().setScene(new Scene(root));
PhotosApplication.getShowImagesStage().show();
}catch(IOException ex){
System.out.println(ex);
}
break;
case ("View Photos"):
try{
FXMLLoader loader=new FXMLLoader(getClass().getResource("/ShowImages.fxml"));
Parent root = loader.load();
Stage stage = (Stage) addPhotosBtn.getScene().getWindow();
stage.hide();
PhotosApplication.getShowImagesStage().setScene(new Scene(root));
PhotosApplication.getShowImagesStage().show();
}catch(IOException ex){
System.out.println(ex);
}
break;
case ("View Albums"):
FXMLLoader loader=new FXMLLoader(getClass().getResource("/AlbumViewer.fxml"));
Parent root = loader.load();
Stage stage = (Stage) addPhotosBtn.getScene().getWindow();
stage.hide();
PhotosApplication.getShowImagesStage().setScene(new Scene(root));
PhotosApplication.getShowImagesStage().show();
case("Exit"):
System.exit(0);
break;
}
}
}
| true |
525e396ebfb8260091553df2ac08a1642ad22d23
|
Java
|
Baikhojun/SWExpertAcademy
|
/Hc_Office/src/com/excel/model/dao/InfoFunction.java
|
UTF-8
| 3,123 | 2.84375 | 3 |
[] |
no_license
|
package com.excel.model.dao;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
public class InfoFunction extends JFrame{
// 도움말 띄우는 클래스
public InfoFunction(){
// frame 이름
super("Help");
// 프레임 크기
setBounds(1250, 100, 500, 825);
JTextArea jta = new JTextArea();
JPanel panHelp1 = new JPanel();
JPanel panHelp2 = new JPanel();
JButton btnOk;
setVisible(true);
// 종료버튼 눌렀을때 New frame 창만 종료
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// frame 사이즈 고정
setResizable(false);
JLabel lbl = new JLabel("Hc Office 도움말");
jta.setText("함수 좌표 형식 : (행 주소,열 주소)\n\n"
+ "함수 사용 형식 : =함수(행 주소,열주소)\n"
+ "범위를 지정 가능한 함수는 =함수(행 주소:열 주소)\n"
+ "모든 실수의 표현범위는 소숫점 아래 3자리까지 표현 가능\n\n"
+ "함수 종류\n\n"
+ "=SUM(A,B) : 두 셀 혹은 범위 내 값의 합을 구한다\n"
+ "=SUM(A:B)\n\n"
+ "=SUB(A,B) : 두 셀 혹은 범위 내 값의 차를 구한다\n"
+ "=SUB(A:B)\n\n"
+ "=MUT(A,B) : 두 셀 혹은 범위 내 값의 곱을 구한다\n"
+ "=MUT(A:B)\n\n"
+ "=DIV(A,B) : 두 셀 혹은 범위 내 값을 나눈 몫을 구한다\n"
+ "=DIV(A:B)\n\n"
+ "=AVE(A:B) : 선택한 범위 내 값의 평균을 구한다\n\n"
+ "=COUNT(A:B) : 선택한 범위 내의 숫자만이 포함된 셀의 갯수를 구한다\n\n"
+ "=COUNTA(A:B) : 선택한 범위 내의 값이 들어있는 모든 셀의 갯수를 구한다 \n\n"
+ "=TODAY() : 오늘 날짜를 구한다\n\n"
+ "=DATE(year,month,date) : 입력한 날짜를 출력한다\n\n"
+ "=IF(A>B) : 두 셀을 비교해 참과 거짓을 출력한다\n"
+ "=IF(A<B)\n\n"
+ "=MAX(A:B) : 범위 내에서 가장 높은 값을 구한다\n\n"
+ "=MIN(A:B) : 범위 내에서 가장 낮은 값을 구한다\n\n"
+ "=UPPER(a) : 소문자 문자열 a를 대문자로 바꾼다\n\n"
+ "=LOWER(A) : 대문자 문자열 A를 소문자로 바꾼다");
jta.setEditable(false);
// 글씨 설정
jta.setFont(jta.getFont().deriveFont(Font.BOLD,13f));
// 경계선을 만드는 컴포넌트
EtchedBorder eborder = new EtchedBorder();
lbl.setBorder(eborder);
jta.setBorder(eborder);
btnOk = new JButton("확인");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panHelp1.add(lbl);
panHelp2.add(jta);
panHelp2.add(btnOk,"Center");
// 색 지정
panHelp1.setBackground(Color.white);
panHelp2.setBackground(Color.WHITE);
btnOk.setBackground(Color.WHITE);
getContentPane().add(panHelp1, "North");
getContentPane().add(panHelp2, "Center");
}
}
| true |
cb61c05e887520635ba1d64ba7c57a41a23239e4
|
Java
|
jeanlks/scratches
|
/problem-solving/SuffixTrie.java
|
UTF-8
| 1,226 | 3.34375 | 3 |
[] |
no_license
|
import java.util.*;
public class SuffixTrie {
static class TrieNode {
Map<Character, TrieNode> children = new HashMap<Character, TrieNode>();
}
TrieNode root = new TrieNode();
char endSymbol = '*';
public SuffixTrie() {
}
public void insertIntoTrie(String str) {
str = str.toLowerCase();
TrieNode curr = root;
for(int i = 0; i< str.length(); i++) {
char letter = str.charAt(i);
if(!curr.children.containsKey(letter))
curr.children.put(letter, new TrieNode());
curr = curr.children.get(letter);
}
curr.children.put(endSymbol, null);
}
public boolean contains(String str) {
str = str.toLowerCase();
TrieNode curr = root;
for(int i = 0; i< str.length(); i++) {
char letter = str.charAt(i);
if(!curr.children.containsKey(letter))
return false;
curr = curr.children.get(letter);
}
return curr.children.containsKey(endSymbol) ? true: false ;
}
}
| true |
74b976010fec4629f02eaf6368749a09155889f3
|
Java
|
lirenhao/demo
|
/manager/src/main/java/com/like/manager/model/Action.java
|
UTF-8
| 1,363 | 2.09375 | 2 |
[] |
no_license
|
package com.like.manager.model;
import javax.persistence.*;
@Entity
public class Action {
/**
* 动作ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Long id;
/**
* 名称
*/
@Column
private String name;
/**
* 值
*/
@Column
private String value;
/**
* 显示顺序
*/
@Column
private Long orderNo;
/**
* 描述
*/
@Column
private String remark;
@ManyToOne
private ResType resType;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public ResType getResType() {
return resType;
}
public void setResType(ResType resType) {
this.resType = resType;
}
}
| true |
e8d6fbbab00cc517688ade067d55e5a2867c2c15
|
Java
|
simple4098/toms
|
/src/main/java/com/fanqielaile/toms/service/impl/CtripHomeStayConnServiceImpl.java
|
UTF-8
| 22,467 | 1.679688 | 2 |
[] |
no_license
|
package com.fanqielaile.toms.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fanqie.core.dto.TBParam;
import com.fanqie.util.DcUtil;
import com.fanqielaile.toms.bo.ctrip.homestay.ChildOrder;
import com.fanqielaile.toms.bo.ctrip.homestay.OmsOrder;
import com.fanqielaile.toms.bo.ctrip.homestay.OrderPerson;
import com.fanqielaile.toms.common.CommonApi;
import com.fanqielaile.toms.dao.*;
import com.fanqielaile.toms.dto.*;
import com.fanqielaile.toms.enums.*;
import com.fanqielaile.toms.exception.CtripHomeStayConnException;
import com.fanqielaile.toms.helper.InnRoomHelper;
import com.fanqielaile.toms.helper.OrderMethodHelper;
import com.fanqielaile.toms.model.*;
import com.fanqielaile.toms.model.Dictionary;
import com.fanqielaile.toms.service.ICtripHomeStayConnService;
import com.fanqielaile.toms.service.ITPService;
import com.fanqielaile.toms.support.holder.TPHolder;
import com.fanqielaile.toms.support.util.Constants;
import com.fanqielaile.toms.support.util.HttpClientUtil;
import com.fanqielaile.toms.support.util.JodaTimeUtil;
import com.fanqielaile.toms.support.util.JsonModel;
import com.fanqielaile.toms.util.CommonUtil;
import com.fanqielaile.toms.util.PassWordUtil;
import com.fanqielaile.toms.vo.ctrip.homestay.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
/**
* Create by jame
* Date: 2016/9/6 10:27
* Version: 1.0
* Description: 阐述
*/
@Service
public class CtripHomeStayConnServiceImpl implements ICtripHomeStayConnService, ITPService {
@Resource
private TPHolder tpHolder;
@Resource
private CompanyDao companyDao;
@Autowired
private ICtripHomeStayRoomRefDao ctripHomeStayRoomRefDao;
@Autowired
private OrderDao orderDao;
@Autowired
private OrderService orderService;
@Autowired
DictionaryDao dictionaryDao;
private static final String HOMESTAY_COMPANY_CODE = "45470283";
private static final String USERCODE = "XCMS";
private static final String PASSWORD = "XCMS654";
private static final Logger logger = LoggerFactory.getLogger(CtripHomeStayConnServiceImpl.class);
@Override
public SubmitOrderReturnVo submitOrder(SubmitOrderRequestVo submitOrderParamVo) {
logger.info("携程民宿,提交订单请求,参数:" + JSON.toJSONString(submitOrderParamVo));
SubmitOrderReturnVo submitOrderReturnVo = new SubmitOrderReturnVo();
Order tomsOrder = new Order();
try {
Integer accountId, innId;
String roomTypeName;
try {
CtripHomeStayRoomRef ctripHomeStayRoomRef = new CtripHomeStayRoomRef();
ctripHomeStayRoomRef.setOtaRoomTypeId(Integer.parseInt(String.valueOf(submitOrderParamVo.getRoomId())));
List<CtripHomeStayRoomRef> list = ctripHomeStayRoomRefDao.query(ctripHomeStayRoomRef);//通过otaRoomTypeId查找accounId
accountId = list.get(0).getAccountId();
innId = list.get(0).getInnId();
roomTypeName = list.get(0).getRoomTypeName();
} catch (Exception e) {
throw new CtripHomeStayConnException("该房型对应的客栈没有设置携程民宿渠道,请联系管理员");
}
tomsOrder = getTomsOrder(submitOrderParamVo, accountId, innId, roomTypeName);
OmsOrder omsOrder = convertOrderModel(submitOrderParamVo, accountId);
Map param = new HashMap();
param.put("order", JSON.toJSONString(omsOrder));
param.put("timestamp", submitOrderParamVo.getTimestamp());
param.put("otaId", submitOrderParamVo.getOtaId());
param.put("signature", submitOrderParamVo.getSignature());
// 查询调用的url
Dictionary dictionary = dictionaryDao.selectDictionaryByType(DictionaryType.CREATE_ORDER.name());
logger.debug("请求oms下单URL:" + dictionary.getUrl());
logger.debug("请求oms下单参数:" + JSON.toJSONString(param));
String result = HttpClientUtil.httpKvPost(dictionary.getUrl(), param);
logger.debug("请求oms下单返回值:" + result);
com.fanqielaile.toms.vo.oms.SubmitOrderReturnVo omsVo = JSON.parseObject(result, com.fanqielaile.toms.vo.oms.SubmitOrderReturnVo.class);
if (omsVo.getStatus().equals(Integer.parseInt(Constants.SUCCESS200))) {
submitOrderReturnVo.setStatusId(1);
submitOrderReturnVo.setOrderId(Long.parseLong(omsVo.getOrderNo()));
submitOrderReturnVo.setResultCode(CtripHomeStayResultCodeEnum.SUCCESS.getValue());
tomsOrder.setOmsOrderCode(String.valueOf(submitOrderReturnVo.getOrderId()));
tomsOrder.setOrderStatus(OrderStatus.CONFIM_AND_ORDER);
} else {
submitOrderReturnVo.setResultCode(CtripHomeStayResultCodeEnum.SYSTEM_ERROR.getValue());
submitOrderReturnVo.setResultMessage(omsVo.getMessage());
tomsOrder.setOrderStatus(OrderStatus.REFUSE);
tomsOrder.setReason(omsVo.getMessage());
}
} catch (Exception e) {
submitOrderReturnVo.setResultCode(CtripHomeStayResultCodeEnum.SYSTEM_ERROR.getValue());
submitOrderReturnVo.setResultMessage("提交订单异常," + e.getMessage());
tomsOrder.setReason(submitOrderReturnVo.getResultMessage());
tomsOrder.setOrderStatus(OrderStatus.REFUSE);
logger.error(submitOrderReturnVo.getResultMessage(), e);
}
tomsOrder.setId(tomsOrder.getUuid());
orderDao.insertOrder(tomsOrder);
return submitOrderReturnVo;
}
private Order getTomsOrder(SubmitOrderRequestVo submitOrderParamVo, Integer accountId, Integer innId, String roomTypeName) {
Order tomsOrder = new Order();
try {
tomsOrder.setVersion(0);
tomsOrder.setCreatedDate(new Date());
tomsOrder.setDeleted(0);
tomsOrder.setChannelSource(ChannelSource.CTRIP_HOMESTAY);
tomsOrder.setChannelOrderCode(String.valueOf(submitOrderParamVo.getCtripOrderId()));
tomsOrder.setAccountId(accountId);
tomsOrder.setInnId(innId);
tomsOrder.setRoomTypeId(String.valueOf(submitOrderParamVo.getRoomId()));
tomsOrder.setHomeAmount(submitOrderParamVo.getQuantity());
tomsOrder.setLiveTime(JodaTimeUtil.parse(submitOrderParamVo.getCheckIn()));
tomsOrder.setLeaveTime(JodaTimeUtil.parse(submitOrderParamVo.getCheckOut()));
tomsOrder.setTotalPrice(BigDecimal.valueOf(submitOrderParamVo.getTotalAmount()).divide(new BigDecimal(100)));
tomsOrder.setOrderTime(new Date());
tomsOrder.setOTARoomTypeId(String.valueOf(submitOrderParamVo.getRoomId()));
tomsOrder.setCurrency(CurrencyCode.CNY);
tomsOrder.setFeeStatus(FeeStatus.PAID);
if (submitOrderParamVo.getDeposit() != null) {
tomsOrder.setPaymentType(submitOrderParamVo.getDeposit().getType() == 1 ? PaymentType.PREPAY : PaymentType.NOW_PAY);
}
if (CommonUtil.isListNotEmpty(submitOrderParamVo.getGuests())) {
List<SubmitOrderGuestsVo> guests = submitOrderParamVo.getGuests();
String guestName = "";
for (SubmitOrderGuestsVo guest : guests) {
guestName += guest.getName() + ",";
}
guestName = CommonUtil.substrLastPatten(guestName);
tomsOrder.setGuestName(guestName);
tomsOrder.setPerson(submitOrderParamVo.getGuests().size());
}
tomsOrder.setPayment(BigDecimal.valueOf(submitOrderParamVo.getTotalAmount()).divide(new BigDecimal(100)));
Company company = new Company();
company.setUserAccount(USERCODE);
company.setUserPassword(PASSWORD);
company = companyDao.selectByUser(company);
tomsOrder.setCompanyId(company.getId());
tomsOrder.setOrderCode(OrderMethodHelper.getOrderCode());
tomsOrder.setUsedPriceModel(UsedPriceModel.MAI);
tomsOrder.setBasicTotalPrice(BigDecimal.valueOf(submitOrderParamVo.getTotalAmount()).divide(new BigDecimal(100)));
// tomsOrder.setOrderInnName //
tomsOrder.setRoomTypeName(roomTypeName);
tomsOrder.setJsonData(JSON.toJSONString(submitOrderParamVo));
tomsOrder.setOrderSource(OrderSource.SYSTEM);
} catch (Exception e) {
logger.error("提交订单toms对象转换异常,method=getTomsOrder", e);
throw new CtripHomeStayConnException("提交订单toms对象转换异常,请检查参数是否正确", e);
}
return tomsOrder;
}
private OmsOrder convertOrderModel(SubmitOrderRequestVo submitOrderParamVo, Integer accountId) throws CtripHomeStayConnException {
OmsOrder omsOrder = new OmsOrder();
try {
omsOrder.setAccountId(accountId);
omsOrder.setOtaOrderNo(String.valueOf(submitOrderParamVo.getCtripOrderId()));
omsOrder.setRoomTypeNum(submitOrderParamVo.getQuantity());
omsOrder.setTotalPrice((BigDecimal.valueOf(submitOrderParamVo.getTotalAmount()).divide(new BigDecimal(100))).doubleValue());
omsOrder.setPaidAmount(BigDecimal.valueOf(submitOrderParamVo.getOnlineAmount()).divide(new BigDecimal(100)).doubleValue());
omsOrder.setContact(submitOrderParamVo.getContacts().getMobile());
omsOrder.setUserName(submitOrderParamVo.getContacts().getName());
omsOrder.setOtaId(EnumOta.ctrip_homestay.getValue());
List<ChildOrder> childOrders = new ArrayList<>();
ChildOrder childOrder = new ChildOrder();
childOrder.setRoomTypeId(Integer.parseInt(String.valueOf(submitOrderParamVo.getRoomId())));
childOrder.setCheckInAt(submitOrderParamVo.getCheckIn());
childOrder.setCheckOutAt(submitOrderParamVo.getCheckOut());
childOrder.setBookRoomPrice(0d);
childOrders.add(childOrder);
omsOrder.setChildOrders(childOrders);
List<OrderPerson> orderPersons = new ArrayList<>();
List<SubmitOrderGuestsVo> guestsVoList = submitOrderParamVo.getGuests();
for (SubmitOrderGuestsVo submitOrderGuestsVo : guestsVoList) {
OrderPerson orderPerson = new OrderPerson();
orderPerson.setName(submitOrderGuestsVo.getName());
orderPerson.setCardNo(submitOrderGuestsVo.getIdCode());
if (submitOrderGuestsVo.getIdType() != 0) {
//(1=身份证 2=军官证 3=通行证 4=护 照 5=其他) 番茄idType
//1.身份证;2.军人证;3.护照; 携程idType
int idType = submitOrderGuestsVo.getIdType() == 3 ? 4 : submitOrderGuestsVo.getIdType();
orderPerson.setCardType(idType);
}
orderPersons.add(orderPerson);
}
omsOrder.setPersons(orderPersons);
return omsOrder;
} catch (Exception e) {
logger.error("提交订单对象转换异常,method=convertOrderModel", e);
throw new CtripHomeStayConnException("提交订单对象转换异常,请检查参数是否正确", e);
}
}
@Override
public GetOrderReturnVo getOrder(Map map) {
logger.info("携程民宿,查询订单请求,参数:" + JSON.toJSONString(map));
GetOrderReturnVo getOrderReturnVo = new GetOrderReturnVo();
try {
List<Object> orderIDs;
if (map == null || map.get("orderIDs") == null) {
logger.error("查询订单,参数错误,method=getOrder");
throw new CtripHomeStayConnException("查询订单,参数错误");
} else {
orderIDs = (List) map.get("orderIDs");
List<GetOrderDetailVo> orderDetailVos = new ArrayList<>();
for (Object orderID : orderIDs) {
GetOrderDetailVo getOrderDetailVo = new GetOrderDetailVo();
Order order = orderDao.selectOrderByOmsOrderCodeAndSource(ChannelSource.CTRIP_HOMESTAY.name(), String.valueOf(orderID));
getOrderDetailVo.setCreateTime(JodaTimeUtil.format(order.getOrderTime(), "yyyy-MM-dd HH:mm:ss"));
SubmitOrderRequestVo submitOrderParamVo = JSON.parseObject(order.getJsonData(), new TypeReference<SubmitOrderRequestVo>() {
});
getOrderDetailVo.setOfflinePayment(submitOrderParamVo.getOfflineAmount());
getOrderDetailVo.setOnlinePayment(submitOrderParamVo.getOnlineAmount());
getOrderDetailVo.setOrderId(Long.valueOf(orderID.toString()));
getOrderDetailVo.setTotalAmount(submitOrderParamVo.getTotalAmount());
if (order.getOrderStatus().name().equals(OrderStatus.CONFIM_AND_ORDER.name())) {
getOrderDetailVo.setStatusId(22);//预定已确认
} else if (order.getOrderStatus().name().equals(OrderStatus.CANCEL_ORDER.name())) {
getOrderDetailVo.setStatusId(31);//预定已取消
} else {//已拒绝
getOrderDetailVo.setStatusId(23);
}
orderDetailVos.add(getOrderDetailVo);
}
getOrderReturnVo.setOrders(orderDetailVos);
getOrderReturnVo.setResultCode(CtripHomeStayResultCodeEnum.SUCCESS.getValue());
}
} catch (Exception e) {
logger.error("查询订单异常,method=getOrder", e);
getOrderReturnVo.setResultCode(CtripHomeStayResultCodeEnum.SYSTEM_ERROR.getValue());
getOrderReturnVo.setResultMessage("查询订单异常," + e.getMessage());
}
return getOrderReturnVo;
}
@Override
public CancelOrderReturnVo cancelOrder(CancelOrderRequestVo cancelOrderRequestVo) {
logger.info("携程民宿,取消订单请求,参数:" + JSON.toJSONString(cancelOrderRequestVo));
CancelOrderReturnVo cancelOrderReturnVo = new CancelOrderReturnVo();
try {
Order order = orderDao.selectOrderByOmsOrderCodeAndSource(ChannelSource.CTRIP_HOMESTAY.name(), String.valueOf(cancelOrderRequestVo.getOrderId()));
if (order == null) {
throw new CtripHomeStayConnException("不存在此渠道订单id:" + cancelOrderRequestVo.getOrderId());
}
CancelOrderRefundVo cancelOrderRefundVo = new CancelOrderRefundVo();
cancelOrderRefundVo.setAmount(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
if (cancelOrderRequestVo.getCancelType() == 1) { //1.检查是否可以取消
if (order.getOrderStatus().name().equals(OrderStatus.CONFIM_AND_ORDER.name())) {
cancelOrderReturnVo.setStatusId(2); //可取消
cancelOrderRefundVo.setDesc("此订单可退线上支付的金额。");
cancelOrderReturnVo.setRefund(cancelOrderRefundVo);
} else {
cancelOrderReturnVo.setStatusId(1); //不可取消
}
} else if (cancelOrderRequestVo.getCancelType() == 2) { //2.取消订单
if (order.getOrderStatus().name().equals(OrderStatus.CONFIM_AND_ORDER.name())) {
OrderParamDto orderParamDto = orderService.findOrderById(order.getId());
JsonModel jsonModel = this.orderService.cancelHandOrder(orderParamDto);
logger.debug("处理取消订单,返回值:" + JSON.toJSONString(jsonModel));
if (jsonModel.isSuccess()) {
cancelOrderReturnVo.setStatusId(2);
cancelOrderRefundVo.setDesc("订单退款结果:" + jsonModel.getMessage());
cancelOrderReturnVo.setRefund(cancelOrderRefundVo);
} else {
cancelOrderReturnVo.setStatusId(1);
cancelOrderReturnVo.setResultMessage(jsonModel.getMessage());
}
} else {
cancelOrderReturnVo.setStatusId(1); //不可取消
}
}
cancelOrderReturnVo.setResultCode(CtripHomeStayResultCodeEnum.SUCCESS.getValue());
} catch (Exception e) {
logger.error("取消订单异常,method=getOrder", e);
cancelOrderReturnVo.setResultCode(CtripHomeStayResultCodeEnum.SYSTEM_ERROR.getValue());
cancelOrderReturnVo.setResultMessage("取消订单异常," + e.getMessage());
}
return cancelOrderReturnVo;
}
@Override
public void updateOrAddHotel(TBParam tbParam, OtaInfoRefDto otaInfo) throws Exception {
String innId = tbParam.getInnId();
Company company = companyDao.selectCompanyByCompanyCode(tbParam.getCompanyCode());
tpHolder.validate(company, innId, otaInfo.getOtaInfoId());
if (tbParam.isSj()) {//上架,新增数据
tbParam.setOtaId(String.valueOf(company.getOtaId()));
logger.debug("请求oms查询房型URL:" + CommonApi.getRoomType());
Map param = new HashMap();
param.put("accountId", tbParam.getAccountId());
param.put("otaId", tbParam.getOtaId());
Long time = System.currentTimeMillis();
param.put("timestamp", time);
String signature = tbParam.getOtaId() + time + USERCODE + PASSWORD;
signature = PassWordUtil.getMd5Pwd(signature);
param.put("signature", signature);
logger.debug("请求oms查询房型参数:" + JSON.toJSONString(param));
String result = HttpClientUtil.httpKvPost(CommonApi.getRoomType(), param);
Map resultMap = JSON.parseObject(result, Map.class);
List<Map> listRooms = (List<Map>) resultMap.get("list");
List<CtripHomeStayRoomRef> inserList = new ArrayList<>();
for (Map room : listRooms) {
CtripHomeStayRoomRef ctripHomeStayRoomRef = new CtripHomeStayRoomRef();
ctripHomeStayRoomRef.setAccountId(Integer.parseInt(tbParam.getAccountId()));
ctripHomeStayRoomRef.setOtaId(Integer.parseInt(tbParam.getOtaId()));
ctripHomeStayRoomRef.setDeleted(0);
ctripHomeStayRoomRef.setInnId(Integer.parseInt(tbParam.getInnId()));
ctripHomeStayRoomRef.setOtaRoomTypeId(Integer.parseInt(room.get("roomTypeId").toString()));
ctripHomeStayRoomRef.setRoomTypeName(room.get("roomTypeName").toString());
inserList.add(ctripHomeStayRoomRef);
}
ctripHomeStayRoomRefDao.insertAll(inserList);
} else {//下架,删除数据
CtripHomeStayRoomRef ctripHomeStayRoomRef = new CtripHomeStayRoomRef();
ctripHomeStayRoomRef.setAccountId(Integer.parseInt(tbParam.getAccountId()));
ctripHomeStayRoomRefDao.deleteByAccountId(ctripHomeStayRoomRef);
}
//
// BangInn bangInn = bangInnDao.selectBangInnByCompanyIdAndInnId(company.getId(), Integer.parseInt(innId));
// tpHolder.validate(company, tbParam.getInnId(), otaInfo.getOtaInfoId());
// tbParam.setOtaId(String.valueOf(company.getOtaId()));
// String inn_info = DcUtil.omsUrl(company.getOtaId(), company.getUserAccount(), company.getUserPassword(), tbParam.getAccountId() != null ? tbParam.getAccountId() : tbParam.getAccountIdDi(), CommonApi.INN_INFO);
// logger.info("inn url:" + inn_info);
// OtaInnOtaDto otaInnOta = otaInnOtaDao.selectOtaInnOtaByInnIdAndCompanyIdAndOtaInfoId(Integer.parseInt(tbParam.getInnId()), company.getId(), otaInfo.getOtaInfoId());
// InnDto omsInnDto = InnRoomHelper.getInnInfo(inn_info);
// //未绑定
// BangInnDto bangInnDto = null;
// if (bangInn == null) {
// bangInnDto = BangInnDto.toDto(company.getId(), tbParam, omsInnDto);
// bangInnDao.createBangInn(bangInnDto);
// } else {
// BangInnDto.toUpdateDto(bangInn, tbParam, omsInnDto);
// bangInnDao.updateBangInnTp(bangInn);
// }
// if (otaInnOta != null) {
// otaInnOta.setSj(tbParam.isSj() ? 1 : 0);
// otaInnOtaDao.updateOtaInnOta(otaInnOta);
// } else {
// String hid = tbParam.getOtaId().toString() + tbParam.getInnId().toString();
// otaInnOta = OtaInnOtaDto.toDto(hid, omsInnDto.getInnName(), company.getId(), tbParam, bangInn == null ? bangInnDto.getId() : bangInn.getId(), otaInfo.getOtaInfoId());
// otaInnOtaDao.saveOtaInnOta(otaInnOta);
// }
}
@Override
public void deleteHotel(TBParam tbParam, OtaInfoRefDto otaInfo) throws Exception {
}
@Override
public void updateHotel(OtaInfoRefDto infoRefDto, TBParam tbParam) throws Exception {
}
@Override
public void updateHotelRoom(OtaInfoRefDto infoRefDto, List<PushRoom> pushRoomList) throws Exception {
}
@Override
public void updateHotelFailTimer(OtaInfoRefDto infoRefDto) {
}
@Override
public void updateRoomTypePrice(OtaInfoRefDto infoRefDto, String innId, String companyId, String userId, String json) throws Exception {
}
@Override
public Result validatedOTAAccuracy(OtaInfoRefDto infoRefDto) {
return null;
}
@Override
public void sellingRoomType(String from, String to, OtaInfoRefDto otaInfoRefDto) {
}
}
| true |
d26caa707c91f45487386ddf22f9ef027180a6b1
|
Java
|
alvaroPereiraVargas980/AssureSoftPatterTes
|
/src/test/java/com/alvaro/Test/AbstractFactoryPatter/RectangleTest.java
|
UTF-8
| 384 | 2.421875 | 2 |
[] |
no_license
|
package com.alvaro.Test.AbstractFactoryPatter;
import com.alvaro.AbstractFactoryPatter.Rectangle;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class RectangleTest {
@Test
public void draw() {
Rectangle spy=spy(new Rectangle());
doCallRealMethod().when(spy).draw();
spy.draw();
verify(spy,atLeastOnce()).draw();
}
}
| true |
67fac332be927ded5831dc7b034f62af7cacc1c2
|
Java
|
popovicmarija20/chef_web_ontology
|
/src/main/java/com/chefSearch/service/RatingsService.java
|
UTF-8
| 266 | 1.65625 | 2 |
[] |
no_license
|
package com.chefSearch.service;
import com.chefSearch.model.Chef;
import org.apache.jena.rdf.model.StmtIterator;
import java.util.List;
public interface RatingsService {
void createRatings(Chef chefModel, StmtIterator ratingsIterator, List<String> ratings);
}
| true |
d7d42ca195484dd248dbe96b033c967aba7b378f
|
Java
|
jiechu/jiechu-
|
/src/com/zafu/shop/servlet/InsertGood.java
|
UTF-8
| 3,526 | 2.25 | 2 |
[] |
no_license
|
package com.zafu.shop.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.zafu.shop.bean.Good;
import com.zafu.shop.dao.GoodDao;
import com.zafu.shop.dao.SellerDao;
import com.zafu.shop.db.DBHelper;
/**
* Servlet implementation class InsertGood
*/
@WebServlet("/InsertGood")
public class InsertGood extends HttpServlet {
private static final long serialVersionUID = 1L;
public void utf8(HttpServletResponse response,HttpServletRequest request)
{
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
if (request != null) {
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
/**
* @see HttpServlet#HttpServlet()
*/
public InsertGood() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// gid,gname,gtuan,gmen,gsold,"
// + "gscore,gcombo,gnotice,gphoto,sid
utf8(response,request);
Good good=new Good();
int sid=Integer.parseInt(request.getParameter("sid"));
int gid=GoodDao.SelectLastGood()+1;
good.setGid(gid);
good.setSeller(SellerDao.getSellerByid(sid));
if(request.getParameter("gtuan")!=null&&request.getParameter("gtuan")!="")
{
int gtuan=Integer.parseInt(request.getParameter("gtuan"));
good.setGtuan(gtuan);
}
if(request.getParameter("gsold")!=null&&request.getParameter("gsold")!="")
{
int gsold=Integer.parseInt(request.getParameter("gsold"));
good.setGsold(gsold);
}
if(request.getParameter("gmen")!=null&&request.getParameter("gmen")!="")
{
int gmen=Integer.parseInt(request.getParameter("gmen"));
good.setGmen(gmen);
}
if(request.getParameter("gname") != null&&request.getParameter("gname")!="")
{
String gname=request.getParameter("gname");
good.setGname(gname);
}
if(request.getParameter("gcombo") != null&&request.getParameter("gcombo")!="")
{
String gcombo=request.getParameter("gcombo");
good.setGcombo(gcombo);
}
if(request.getParameter("gnotice") != null&&request.getParameter("gnotice")!="")
{
String gnotice=request.getParameter("gnotice");
good.setGnotice(gnotice);
}
if(request.getParameter("gphoto") != null&&request.getParameter("gphoto")!="")
{
String gphoto=request.getParameter("gphoto");
good.setGphoto(gphoto);
}
good.setGscore(0);
GoodDao.insertGood(good);
PrintWriter writer=response.getWriter();
writer.write(JSON.toJSONString(good));
}
}
| true |
4ff9f32fc8b0677774cdc7f0148862af884606f7
|
Java
|
HongZe1090/coordinateUtil
|
/src/main/java/com/coordinate/Util/coordtrans.java
|
UTF-8
| 1,450 | 2.21875 | 2 |
[] |
no_license
|
package com.coordinate.Util;
import org.osgeo.proj4j.CRSFactory;
import org.osgeo.proj4j.CoordinateReferenceSystem;
import org.osgeo.proj4j.CoordinateTransform;
import org.osgeo.proj4j.CoordinateTransformFactory;
public class coordtrans {
public CoordinateTransform coordtrans() {
CRSFactory targetFactory = new CRSFactory();
CRSFactory crsFactory = new CRSFactory();
//目标坐标系统
String target_param = "+proj=longlat +datum=WGS84 +no_defs ";
CoordinateReferenceSystem target = targetFactory.createFromParameters("wgs84", target_param);
//源坐标系统
// String xian80_param = "+proj=longlat +a=6378140 +b=6356755.288157528 +towgs84=94.462,70.149,-1.511,-0.423814,-0.091708,0.133866,-1.732 +no_de
// 偏移量也要加上带号
// 参数说明:投影坐标系-》墨脱
// 椭球体-》IAU76
// 偏移量-》未加代号
// 单位-》米
String xian80_param = "+proj=tmerc +ellps=IAU76 +lat_0=0 +lon_0=117e +x_0=500000 +y_0=0 +units=m +k=1.0 +towgs84=94.462,70.149,-1.511,-0.423814,-0.091708,0.133866,-1.732 +no_defs";
CoordinateReferenceSystem xian80 = crsFactory.createFromParameters("xian80", xian80_param);
CoordinateTransformFactory ctf = new CoordinateTransformFactory();
CoordinateTransform transform = ctf.createTransform(xian80, target);
return transform;
}
}
| true |
2ae88ed8f7ae66b095fbd307507f6982bce84fce
|
Java
|
andelai/Codewars
|
/src/Kata/SimpleNumSeq2.java
|
UTF-8
| 1,317 | 2.984375 | 3 |
[] |
no_license
|
//package Kata;
//
//import static org.junit.Assert.assertEquals;
//
//import java.util.ArrayList;
//import java.util.List;
//
//public class SimpleNumSeq2 {
//// public static int missing(String s){
//// List<Integer> al = new ArrayList<Integer>();
//// al = findSeq(s);
//// }
////
//// private static List<Integer> findSeq(String s) {
////
////
////
//// }
////
//// private static boolean numOfdigitsChange(int x, int k) {
//// return String.valueOf(x+1).length()>k;
//// }
////
//// private static int findInteger(String s, int k, int prethodni) {
//// if(prethodni != 0 && String.valueOf(prethodni+1).length()>k) k=k+1;
//// if(k<s.length()) return Integer.valueOf(s.substring(0, k));
//// return -1;
//// }
//// public static void main(String[] a) {
//// assertEquals(4,missing("123567"));
////// assertEquals(92,missing("899091939495"));
////// assertEquals(100,missing("9899101102"));
////// assertEquals(-1,missing("599600601602"));
////// assertEquals(-1,missing("8990919395"));
////// assertEquals(1002,missing("998999100010011003"));
//// assertEquals(10000,missing("99991000110002"));
//// assertEquals(-1,missing("979899100101102"));
////// assertEquals(900003,missing("900001900002900004900005900006"));
////
//// }
////}
| true |
0cce20b21d1b9a2522cf1e12668decb8c6698176
|
Java
|
louzj82/YoTa
|
/src/org/ike/yota/model/EActivitiesType.java
|
UTF-8
| 413 | 1.9375 | 2 |
[] |
no_license
|
package org.ike.yota.model;
public class EActivitiesType {
private Integer typeId; //活动类型Id
private String typeName; //活动类型名
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
| true |
649f020954142822808cdff559872cd09c5dabfc
|
Java
|
flywind2/joeis
|
/src/irvine/oeis/a052/A052953.java
|
UTF-8
| 328 | 2.484375 | 2 |
[] |
no_license
|
package irvine.oeis.a052;
import irvine.oeis.LinearRecurrence;
/**
* A052953 Expansion of <code>2*(1-x-x^2)/((1-x)*(1+x)*(1-2*x))</code>.
* @author Sean A. Irvine
*/
public class A052953 extends LinearRecurrence {
/** Construct the sequence. */
public A052953() {
super(new long[] {-2, 1, 2}, new long[] {2, 2, 4});
}
}
| true |
7f4d01ac27f3e0cca40d4f1c9cfeff4083666323
|
Java
|
sindongboy/id_mapper
|
/src/main/java/com/skplanet/nlp/data/HoppinDramaMeta.java
|
UTF-8
| 5,899 | 2.515625 | 3 |
[] |
no_license
|
package com.skplanet.nlp.data;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.log4j.Logger;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Hoppin Drama/Animation meta
* @author Donghun Shin / [email protected]
* @date 2/27/15
*/
public class HoppinDramaMeta {
private static final Logger LOGGER = Logger.getLogger(HoppinDramaMeta.class.getName());
private Config myConfig = null;
// json field definition for value overriding
private static final String ID = "id";
private static final String TITLE = "title";
private static final String B_DATE = "begin";
private static final String E_DATE = "end";
private static final String SYNOPSIS = "synopsis";
private static final String DIRECTORS = "directors";
private static final String ACTORS_1 = "actors1";
private static final String ACTORS_2 = "actors2";
private static final String SCORE = "score";
private static final String SCORE_COUNT = "score-count";
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
private static DecimalFormat scoreFormat = new DecimalFormat("0.00");
// members
private String id = null;
private String title = null;
private Calendar bDate = null;
private boolean ends = false;
private String synopsis = null;
private List<String> directors = null;
private List<String> actors1 = null;
private List<String> actors2 = null;
private double score = 0.00;
private int scoreCount = 0;
public HoppinDramaMeta() {
}
/**
* Constructor for value overriding
* @param config {@link com.typesafe.config.Config}
*/
public HoppinDramaMeta(final Config config) {
this.myConfig = config;
this.id = config.getString(ID);
this.title = config.getString(TITLE);
String bDateStr = config.getString(B_DATE);
this.bDate = new GregorianCalendar();
int year, month, day;
if ("null".equals(bDateStr)) {
year = 9999;
month = 01;
day = 01;
} else {
year = Integer.parseInt(bDateStr.substring(0, 4));
month = Integer.parseInt(bDateStr.substring(4, 6)) - 1;
day = Integer.parseInt(bDateStr.substring(6));
}
this.bDate.set(Calendar.YEAR, year);
this.bDate.set(Calendar.MONTH, month);
this.bDate.set(Calendar.DAY_OF_MONTH, day);
this.ends = config.getBoolean(E_DATE);
this.synopsis = config.getString(SYNOPSIS);
this.directors = config.getStringList(DIRECTORS);
this.actors1 = config.getStringList(ACTORS_1);
this.actors2 = config.getStringList(ACTORS_2);
this.score = config.getDouble(SCORE);
this.scoreCount = config.getInt(SCORE_COUNT);
}
/**
* Get ID
* @return id
*/
public String getId() {
return id;
}
/**
* Set ID
* @param id id to be set
*/
public void setId(String id) {
this.id = id;
}
/**
* Get Title
* @return title
*/
public String getTitle() {
return title;
}
/**
* Set Title
* @param title title to be set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get Start Date*
* @return start date
*/
public Calendar getStartDate() {
return bDate;
}
/**
* Set Start date
* @param date start date
*/
public void setStartDate(Calendar date) {
this.bDate = date;
}
/**
* Set End Status
* @param end end?
*/
public void setEnds(boolean end) {
this.ends = end;
}
/**
* check if the contents is currently playing on tv or not
* @return true for currently playing, false otherwise
*/
public boolean isEnds() {
return this.ends;
}
/**
* Get Synopsis
* @return synopsis
*/
public String getSynopsis() {
return synopsis;
}
/**
* Set Synopsis
* @param synopsis synopsis
*/
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
/**
* Get Director list
* @return director list
*/
public List<String> getDirectors() {
return directors;
}
/**
* Set Director list
* @param directors director list
*/
public void setDirectors(List<String> directors) {
this.directors = directors;
}
/**
* Get Main Actor list
* @return main actor list
*/
public List<String> getActors1() {
return actors1;
}
/**
* Set Main Actor List
* @param actors actor list
*/
public void setActors1(List<String> actors) {
this.actors1 = actors;
}
/**
* Get General Actor list
* @return actor list
*/
public List<String> getActors2() {
return actors2;
}
/**
* Set General Actor list
* @param actors actor list
*/
public void setActors2(List<String> actors) {
this.actors2 = actors;
}
/**
* Get Score
* @return score
*/
public double getScore() {
return score;
}
/**
* Set Score
* @param score score
*/
public void setScore(double score) {
this.score = score;
}
/**
* Get Score Count
* @return score count
*/
public double getScoreCount() {
return scoreCount;
}
/**
* Set Score Count
* @param scoreCount score count
*/
public void setScoreCount(int scoreCount) {
this.scoreCount = scoreCount;
}
@Override
public String toString() {
return "HoppinDramaMeta{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", bDate=" + bDate +
", ends=" + ends +
", synopsis='" + synopsis + '\'' +
", directors=" + directors +
", actors1=" + actors1 +
", actors2=" + actors2 +
", score=" + score +
", scoreCount=" + scoreCount +
'}';
}
/*
public static void main(String[] args) {
Config mainConfig = ConfigFactory.load("daum-meta");
long btime, etime;
Collection<HoppinDramaMeta> metaCollection = new ArrayList<HoppinDramaMeta>();
btime = System.currentTimeMillis();
for (Config singleItem : mainConfig.getConfigList("daum.meta")) {
HoppinDramaMeta singleMeta = new HoppinDramaMeta(singleItem);
metaCollection.add(singleMeta);
}
etime = System.currentTimeMillis();
System.out.println("meta loaded in " + (etime - btime) + " msec.");
}
*/
}
| true |
45df992b154d01685134236bac100e81676f273e
|
Java
|
Seokheelee-11/hee
|
/eventservice/src/main/java/com/chatbot/eventservice/controller/EventController.java
|
UTF-8
| 910 | 2.09375 | 2 |
[] |
no_license
|
package com.chatbot.eventservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.chatbot.eventservice.dto.EventInputDto;
import com.chatbot.eventservice.dto.EventOutputDto;
import com.chatbot.eventservice.service.EventService;
@RestController
public class EventController {
@Autowired
private EventService eventService;
@ResponseBody
@RequestMapping(value="/applyEvent", method=RequestMethod.POST)
public EventOutputDto eventApply(@RequestBody EventInputDto eventInputDto) {
return eventService.applyEvent(eventInputDto);
}
}
| true |
32f14bc0a5a98605cd2be0b0d9d1c3dd5ef76c29
|
Java
|
alopezcastillo/dgt-android
|
/app/src/main/java/com/tutorial/albertopc/dgt_circulacion/bbdd/BdCitas.java
|
UTF-8
| 3,033 | 2.359375 | 2 |
[] |
no_license
|
package com.tutorial.albertopc.dgt_circulacion.bbdd;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.tutorial.albertopc.dgt_circulacion.entity.Cita;
import java.util.ArrayList;
/**
* Created by Alberto PC on 15/04/2017.
*/
public class BdCitas extends SQLiteOpenHelper {
public BdCitas(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table citas(id integer key, doi text,fechaCitacion text,autoescuela text,vehiculo text,examinador text, estado text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean alta(Cita cita) {
// AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,
// "administracion", null, 1);
boolean retorno =true;
try{
SQLiteDatabase bd = this.getWritableDatabase();
ContentValues registro = new ContentValues();
registro.put("id", cita.getId());
registro.put("doi", cita.getDoi());
registro.put("fechaCitacion", cita.getFecha());
registro.put("autoescuela", cita.getAutoescuela());
registro.put("vehiculo", cita.getVehiculo());
registro.put("examinador", cita.getExaminador());
registro.put("estado", cita.getEstado());
bd.insert("citas", null, registro);
bd.close();}
catch(Exception ex){retorno=false;}
return retorno;
}
public void modificacionEstado(String doi, String estado) {
SQLiteDatabase bd = this.getWritableDatabase();
ContentValues registro = new ContentValues();
registro.put("estado", estado);
int cant = bd.update("citas", registro, "doi= '"+ doi+"'", null);
bd.close();
}
public ArrayList<Cita> consultaPorExaminador(String examinador) {
SQLiteDatabase bd = this.getWritableDatabase();
Cursor cursor = bd.rawQuery(
"select id,doi,fechaCitacion,autoescuela,vehiculo,estado from citas where examinador= '"+examinador+"'", null);
ArrayList<Cita> mArrayList = new ArrayList<Cita>();
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
Cita cit = new Cita();
// The Cursor is now set to the right position
cit.setId(Integer.valueOf(cursor.getInt(0)));
cit.setDoi(cursor.getString(1));
cit.setFecha(cursor.getString(2));
cit.setAutoescuela(cursor.getString(3));
cit.setVehiculo(cursor.getString(4));
cit.setExaminador(examinador);
cit.setEstado(cursor.getString(5));
mArrayList.add(cit);
}
bd.close();
return mArrayList;
}
//añadir métodos
}
| true |
38484dd2b725a06de99eb32fe05fa2890c5dc25b
|
Java
|
Justin01Wu/JavaFrame
|
/myBatis/src/main/java/com/justa/mybatis/Address.java
|
UTF-8
| 659 | 2.546875 | 3 |
[] |
no_license
|
package com.justa.mybatis;
public class Address {
private int addressId;
private String streetAddress;
private int personId;
public int getAddressId() {
return addressId;
}
public void setAddressId(int addressId) {
this.addressId = addressId;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
@Override
public String toString() {
return "id=" +addressId
+", streetAddress:" + streetAddress;
}
}
| true |
e6734cebca01ac41a61102ed13cf4f115cb54940
|
Java
|
Jorgeoliv/Overlay-P2PandMobility
|
/P2P/src/main/java/mensagens/FCIDStruct.java
|
UTF-8
| 316 | 2.3125 | 2 |
[] |
no_license
|
package mensagens;
public class FCIDStruct{
public int referenceID;
public byte[] toAdd;
public byte[] inc;
public FCIDStruct(){}
public FCIDStruct(int referenceID , byte[] toAdd, byte[] inc){
this.referenceID = referenceID ;
this.toAdd = toAdd;
this.inc = inc;
}
}
| true |
bd991f12ddabf797eab949743df39a9491715a79
|
Java
|
dsikdar/consolidated_work
|
/practice/src/StringWork/Str.java
|
UTF-8
| 644 | 3.203125 | 3 |
[] |
no_license
|
package StringWork;
public class Str {
public static void main(String[] args) {
String cv= "My name is Debajyoti Sikdar ,"
+ " I live in kolkata 700050 in WB , I eat meat"
+ "Again I m Debajyoti Sikdar";
String[] splitStr=cv.split(",");
for(String item : splitStr) {
System.out.println(item);
}
System.out.println("CV printing done");
String about=cv.substring(cv.indexOf('I'));//should return from the second line
System.out.println(about);
System.out.println(cv.charAt(0));
StringBuilder mystrbuilder=new StringBuilder(cv);
mystrbuilder.setCharAt(cv.indexOf('I'), 'i');
System.out.println(mystrbuilder);
}
}
| true |
2405d047468b9e4490f217983d9f0ab32d0b00db
|
Java
|
THE-ORONCO/ObjectCalastenics
|
/src/GameOfLife/CellState.java
|
UTF-8
| 301 | 3.21875 | 3 |
[] |
no_license
|
package GameOfLife;
public enum CellState {
ALIVE("X"),
DEAD(" ");
private String representationSymbol;
CellState(String x) {
representationSymbol = x;
}
@Override
public String toString() {
return "Cellstate = \"" + representationSymbol + "\"";
}
}
| true |
611efa8ee3864221ce0c63a15f14ecd5e3079b61
|
Java
|
caseyj1229/EquiLeader
|
/EquiLeaderTest.java
|
UTF-8
| 658 | 2.5625 | 3 |
[] |
no_license
|
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class EquiLeaderTest {
@Test
void solution() {
int[] A = {4,3,4,4,4,2};
assertEquals(2,EquiLeader.solution(A));
int[] B = {1,2,3,4};
assertEquals(0,EquiLeader.solution(B));
int[] C = {-4,3,-4,-4,-4,2};
assertEquals(2,EquiLeader.solution(C));
int[] D = {6,6,6,6,6,6,6,6,6,6,6};
assertEquals(10,EquiLeader.solution(D));
int[] E = {1,1};
assertEquals(1,EquiLeader.solution(E));
int[] F = {1};
assertEquals(0,EquiLeader.solution(F));
}
}
| true |
9d5e0b041cbacbd817fd22a9cae35857141e081f
|
Java
|
DataBiosphere/consent
|
/src/main/java/org/broadinstitute/consent/http/enumeration/MatchAlgorithm.java
|
UTF-8
| 340 | 2.234375 | 2 |
[
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
package org.broadinstitute.consent.http.enumeration;
public enum MatchAlgorithm {
V1("v1"),
V2("v2"),
V3("v3");
String version;
MatchAlgorithm(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
| true |
55272d54b38e38784f77c1e7580b27726b4dcf00
|
Java
|
dobro3000/jday
|
/app/src/main/java/com/bignerdranch/dobro/myjday/Activity/SettingActivity.java
|
UTF-8
| 2,007 | 2.046875 | 2 |
[] |
no_license
|
package com.bignerdranch.dobro.myjday.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import com.bignerdranch.dobro.myjday.R;
/**
* Created by Dobro on 14.02.2018.
*/
public class SettingActivity extends AppCompatActivity {
SeekBar seekAge, seekSphere;
TextView exitTxt, communicationTxt;
RelativeLayout superlike, mentorNotify, messageNotify;
Switch superLikeSwith, mentorRequestSwith, messageNotifitySwith, swithAll, swithSphere;
TextView ageTxt, stageTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_activity);
ActionBar bar = this.getSupportActionBar();
bar.setHomeButtonEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
ageTxt = (TextView) findViewById(R.id.age_value);
stageTxt = (TextView) findViewById(R.id.age_stage);
swithAll = (Switch) findViewById(R.id.switch_all);
swithSphere = (Switch) findViewById(R.id.switch_sphere);
seekAge = (SeekBar) findViewById(R.id.seek_age);
seekSphere = (SeekBar) findViewById(R.id.stage);
messageNotifitySwith = (Switch) findViewById(R.id.message_notify);
mentorRequestSwith = (Switch) findViewById(R.id.mentor_request);
superLikeSwith = (Switch) findViewById(R.id.switch_superlike);
communicationTxt = (TextView) findViewById(R.id.communication);
exitTxt = (TextView) findViewById(R.id.exit_btn);
messageNotify = (RelativeLayout) findViewById(R.id.notification_message);
superlike = (RelativeLayout) findViewById(R.id.notification_superlike);
mentorNotify = (RelativeLayout) findViewById(R.id.notification_mentorequest);
}
}
| true |
2c691a34ac62707e50401f25f2259f7a0797d385
|
Java
|
185368123/StreetLamp
|
/src/main/java/com/shuorigf/streetlampapp/data/LampControlDetailsData.java
|
UTF-8
| 7,749 | 2.03125 | 2 |
[] |
no_license
|
package com.shuorigf.streetlampapp.data;
import java.io.Serializable;
public class LampControlDetailsData extends ResultCodeData {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data implements Serializable{
private static final long serialVersionUID = 1L;
private String updatetime;
private int status;
private int isfaulted;
private String lamp_no;
private String network_no;
private String network_id;
private String project_id;
private String project_name;
private String address;
private double longitude;
private double latitude;
private String section;
private String location;
private float boardpower;
private int temper;
private float sysvoltage;
private float syscurrent;
private int lampstatus;
private int lighteness;
private float lamppower;
private int nightlength;
private int lighttime;
private float lampvoltage;
private float lampcurrent;
private float solarvoltage;
private float solarpower;
private float solarcurrent;
private int solartime;
private int chargetime;
private float totalchargeah;
private float battvoltage;
private float batttemper;
private float electricleft;
private float voltagedaymin;
private float voltagedaymax;
private int battstatus;
private int chargestage;
private int overtimes;
private int rundays;
private int fulltimes;
private float totalgeneration;
private float totalconsumption;
private int electricSOC;
public String getUpdatetime() {
return updatetime;
}
public void setUpdatetime(String updatetime) {
this.updatetime = updatetime;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getIsfaulted() {
return isfaulted;
}
public void setIsfaulted(int isfaulted) {
this.isfaulted = isfaulted;
}
public String getLamp_no() {
return lamp_no;
}
public void setLamp_no(String lamp_no) {
this.lamp_no = lamp_no;
}
public String getNetwork_no() {
return network_no;
}
public void setNetwork_no(String network_no) {
this.network_no = network_no;
}
public String getProject_id() {
return project_id;
}
public void setProject_id(String project_id) {
this.project_id = project_id;
}
public String getProject_name() {
return project_name;
}
public void setProject_name(String project_name) {
this.project_name = project_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public float getBoardpower() {
return boardpower;
}
public void setBoardpower(float boardpower) {
this.boardpower = boardpower;
}
public int getTemper() {
return temper;
}
public void setTemper(int temper) {
this.temper = temper;
}
public float getSysvoltage() {
return sysvoltage;
}
public void setSysvoltage(float sysvoltage) {
this.sysvoltage = sysvoltage;
}
public float getSyscurrent() {
return syscurrent;
}
public void setSyscurrent(float syscurrent) {
this.syscurrent = syscurrent;
}
public int getLampstatus() {
return lampstatus;
}
public void setLampstatus(int lampstatus) {
this.lampstatus = lampstatus;
}
public int getLighteness() {
return lighteness;
}
public void setLighteness(int lighteness) {
this.lighteness = lighteness;
}
public float getLamppower() {
return lamppower;
}
public void setLamppower(float lamppower) {
this.lamppower = lamppower;
}
public float getLampvoltage() {
return lampvoltage;
}
public void setLampvoltage(float lampvoltage) {
this.lampvoltage = lampvoltage;
}
public float getLampcurrent() {
return lampcurrent;
}
public void setLampcurrent(float lampcurrent) {
this.lampcurrent = lampcurrent;
}
public float getSolarvoltage() {
return solarvoltage;
}
public void setSolarvoltage(float solarvoltage) {
this.solarvoltage = solarvoltage;
}
public float getSolarpower() {
return solarpower;
}
public void setSolarpower(float solarpower) {
this.solarpower = solarpower;
}
public float getSolarcurrent() {
return solarcurrent;
}
public void setSolarcurrent(float solarcurrent) {
this.solarcurrent = solarcurrent;
}
public float getTotalchargeah() {
return totalchargeah;
}
public void setTotalchargeah(float totalchargeah) {
this.totalchargeah = totalchargeah;
}
public float getBattvoltage() {
return battvoltage;
}
public void setBattvoltage(float battvoltage) {
this.battvoltage = battvoltage;
}
public float getBatttemper() {
return batttemper;
}
public void setBatttemper(float batttemper) {
this.batttemper = batttemper;
}
public float getElectricleft() {
return electricleft;
}
public void setElectricleft(float electricleft) {
this.electricleft = electricleft;
}
public float getVoltagedaymin() {
return voltagedaymin;
}
public void setVoltagedaymin(float voltagedaymin) {
this.voltagedaymin = voltagedaymin;
}
public float getVoltagedaymax() {
return voltagedaymax;
}
public void setVoltagedaymax(float voltagedaymax) {
this.voltagedaymax = voltagedaymax;
}
public int getBattstatus() {
return battstatus;
}
public void setBattstatus(int battstatus) {
this.battstatus = battstatus;
}
public int getChargestage() {
return chargestage;
}
public void setChargestage(int chargestage) {
this.chargestage = chargestage;
}
public int getOvertimes() {
return overtimes;
}
public void setOvertimes(int overtimes) {
this.overtimes = overtimes;
}
public int getRundays() {
return rundays;
}
public void setRundays(int rundays) {
this.rundays = rundays;
}
public int getFulltimes() {
return fulltimes;
}
public void setFulltimes(int fulltimes) {
this.fulltimes = fulltimes;
}
public float getTotalgeneration() {
return totalgeneration;
}
public void setTotalgeneration(float totalgeneration) {
this.totalgeneration = totalgeneration;
}
public float getTotalconsumption() {
return totalconsumption;
}
public void setTotalconsumption(float totalconsumption) {
this.totalconsumption = totalconsumption;
}
public int getNightlength() {
return nightlength;
}
public void setNightlength(int nightlength) {
this.nightlength = nightlength;
}
public int getLighttime() {
return lighttime;
}
public void setLighttime(int lighttime) {
this.lighttime = lighttime;
}
public int getSolartime() {
return solartime;
}
public void setSolartime(int solartime) {
this.solartime = solartime;
}
public int getChargetime() {
return chargetime;
}
public void setChargetime(int chargetime) {
this.chargetime = chargetime;
}
public int getElectricSOC() {
return electricSOC;
}
public void setElectricSOC(int electricSOC) {
this.electricSOC = electricSOC;
}
public String getNetwork_id() {
return network_id;
}
public void setNetwork_id(String network_id) {
this.network_id = network_id;
}
}
}
| true |
74dd0f44128979489cc3d17955cd6b6ae4254cd1
|
Java
|
AlejandroNieto-DAM/Android_Exercises
|
/TheMovieDB/app/src/main/java/com/example/practicaandroid/ui/retrofit/MovieService.java
|
UTF-8
| 3,553 | 2.234375 | 2 |
[] |
no_license
|
package com.example.practicaandroid.ui.retrofit;
import com.example.practicaandroid.ui.CastClassesToMovie.CastMovieCredits;
import com.example.practicaandroid.ui.Videos.Videos;
import com.example.practicaandroid.ui.models.CreditsDetail;
import com.example.practicaandroid.ui.models.CreditsFeed;
import com.example.practicaandroid.ui.models.MovieDetail;
import com.example.practicaandroid.ui.models.MovieFeed;
import com.example.practicaandroid.ui.models.TVShowDetail;
import com.example.practicaandroid.ui.models.TVShowFeed;
import com.example.practicaandroid.ui.models.TVShowListed;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface MovieService {
//Movie calls
@GET("movie/top_rated")
Call<MovieFeed> getTopRated(@Query("api_key") String apiKey, @Query("language") String language);
@GET("/movie/{movie_id}/credits")
Call<CreditsFeed> getCast(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("movie/popular")
Call<MovieFeed> getMovies(@Query("api_key") String apiKey, @Query("language") String language);
@GET("movie/{id}")
Call<MovieDetail> getMovieByID(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("movie/{id}/credits")
Call<CreditsFeed> getMovieCast(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("/3/search/movie/")
Call<MovieFeed> getMovieByName(@Query("api_key") String apiKey, @Query("language") String language, @Query("query") String query);
@GET("/3/movie/{id}/videos")
Call<Videos> getMovieTrailer(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("/3/movie/{id}/similar")
Call<MovieFeed> getSimilarMovies(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
//Tv calls
@GET("tv/popular")
Call<TVShowFeed> getSeriesPopular(@Query("api_key") String apiKey, @Query("language") String language);
@GET("tv/{id}")
Call<TVShowDetail> getSerieByID(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("tv/top_rated")
Call<TVShowFeed> getSeriesTopRated(@Query("api_key") String apiKey, @Query("language") String language);
@GET("tv/{id}/credits")
Call<CreditsFeed> getSeriesCast(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("/3/search/tv/")
Call<TVShowFeed> getSerieByName(@Query("api_key") String apiKey, @Query("language") String language, @Query("query") String query);
@GET("/3/tv/{id}/videos")
Call<Videos> getSerieTrailer(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("/3/tv/{id}/similar")
Call<TVShowFeed> getSimilarSeries(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
//Cast calls
@GET("/3/person/{id}")
Call<CreditsDetail> getActorByID(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("/3/person/{id}/movie_credits")
Call<CastMovieCredits> getActorCredits(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
@GET("/3/person/{id}/tv_credits")
Call<CastMovieCredits> getActorSeriesCredits(@Path("id") int id, @Query("api_key") String apiKey, @Query("language") String language);
}
| true |
4c8a6c17749b1536a9b8f7a81459cef8e81b78cd
|
Java
|
QuickBlox/quickblox-blackberry5-6-7-sdk
|
/sample-chat/src/com/injoit/examplechat/jmc/screens/ContactEditScreen.java
|
UTF-8
| 4,456 | 2.109375 | 2 |
[] |
no_license
|
package com.injoit.examplechat.jmc.screens;
import com.injoit.examplechat.jmc.*;
import com.injoit.examplechat.jmc.connection.*;
import com.injoit.examplechat.jmc.controls.*;
import com.injoit.examplechat.jmc.media.*;
import com.injoit.examplechat.util.*;
import com.injoit.examplechat.threads.*;
import com.injoit.examplechat.jabber.conversation.*;
import com.injoit.examplechat.jabber.roster.*;
import com.injoit.examplechat.jabber.presence.*;
import com.injoit.examplechat.jabber.subscription.*;
import com.injoit.examplechat.me.regexp.RE;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.database.*;
import net.rim.device.api.io.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import net.rim.device.api.ui.decor.*;
public class ContactEditScreen extends MainScreen implements FieldChangeListener
{
private ContactEditScreen me;
private ChatManager chat_manager;
private EditField nick;
private EditField group;
private EditField jid;
private ButtonField bOk;
private ButtonField bCancel;
String name = "Edit Contact";
public ContactEditScreen(ChatManager _chat_manager)
{
super(NO_VERTICAL_SCROLL);
me = this;
this.getMainManager().setBackground(
BackgroundFactory.createLinearGradientBackground(0x0099CCFF,
0x0099CCFF,0x00336699,0x00336699)
);
chat_manager = _chat_manager;
VerticalFieldManager vman = new VerticalFieldManager();
String group_Jid = "";
String jnick = "";
String jname = "";
if (chat_manager.currentjid != null)
{
name = chat_manager.currentjid.getUsername();
jname = chat_manager.currentjid.getFullJid();
group_Jid = chat_manager.currentjid.group;
jnick = chat_manager.currentjid.getNick();
}
jid =new EditField("JID: ", jname, 64, 0);
jid.setEditable(false);
if(jnick.length()>0)
{
nick = new EditField("Nick: ", jnick, 64, 0);
}
else
{
nick = new EditField("Nick: ", name, 64, 0);
}
group = new EditField("Group: ", group_Jid, 32, 0);
bOk = new ButtonField("Accept", Field.FIELD_HCENTER|DrawStyle.HCENTER);
bOk.setChangeListener(this);
bOk.setEditable(true);
bCancel = new ButtonField("Cancel", Field.FIELD_HCENTER|DrawStyle.HCENTER);
bCancel.setChangeListener(this);
bCancel.setEditable(true);
vman.add(jid);
vman.add(nick);
vman.add(group);
vman.add(bOk);
vman.add(bCancel);
add(vman);
bOk.setFocus();
}
protected void makeMenu(Menu menu, int instance)
{
if (instance == Menu.INSTANCE_DEFAULT)
{
menu.add(_acceptItem);
menu.add(_closeItem);
}
}
private MenuItem _acceptItem = new MenuItem("Accept", 250, 250)
{
public void run()
{
accept();
onClose();
}
};
private MenuItem _closeItem = new MenuItem("Close", 260, 260)
{
public void run()
{
onClose();
}
};
public boolean onSavePrompt()
{
return true;
}
public boolean onClose()
{
close();
return true;
}
public void fieldChanged(Field field, int context)
{
if(field == bOk)
{
accept();
}
else if(field == bCancel)
{
onClose();
}
}
private void accept()
{
if(nick.getText().length()>0)
{
chat_manager.currentjid.setNick(nick.getText());
}
else
{
chat_manager.currentjid.setNick(chat_manager.currentjid.getNickName());
}
chat_manager.internal_state = chat_manager.ONLINE;
Subscribe.renameRosterItem(chat_manager.currentjid);
chat_manager.getGuiOnlineMenu();
onClose();
}
}
| true |
2897055ce661307e6a6bd63159dcc920af8fda34
|
Java
|
DanielTempleUK/StackCode
|
/src/main/java/animals/Edible.java
|
UTF-8
| 95 | 2 | 2 |
[] |
no_license
|
package animals;
public interface Edible {
void isEaten(final int hitPointsToDeduct);
}
| true |
5edace2e21060f1c009ebe6f0523e6be568a3cee
|
Java
|
canghailan/commons-vfs2-kit
|
/src/main/java/cc/whohow/fs/util/EmptyFileSystemAttributes.java
|
UTF-8
| 568 | 2.28125 | 2 |
[] |
no_license
|
package cc.whohow.fs.util;
import cc.whohow.fs.Attribute;
import cc.whohow.fs.FileSystemAttributes;
import java.util.Collections;
import java.util.Iterator;
class EmptyFileSystemAttributes implements FileSystemAttributes {
private static final EmptyFileSystemAttributes INSTANCE = new EmptyFileSystemAttributes();
private EmptyFileSystemAttributes() {
}
public static EmptyFileSystemAttributes get() {
return INSTANCE;
}
@Override
public Iterator<Attribute<?>> iterator() {
return Collections.emptyIterator();
}
}
| true |
e942b5116fac1a369024c58c4aae760af4c69b98
|
Java
|
joelkoz/mavlink
|
/mavlink-protocol/src/main/java/io/dronefleet/mavlink/protocol/MavlinkFrameReader.java
|
UTF-8
| 1,169 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
package io.dronefleet.mavlink.protocol;
import java.io.IOException;
import java.io.InputStream;
public class MavlinkFrameReader {
private final TransactionalInputStream in;
public MavlinkFrameReader(InputStream in) {
this.in = new TransactionalInputStream(in, 1024);
}
public boolean next() throws IOException {
int versionMarker;
int payloadLength;
in.commit();
while ((versionMarker = in.read()) != -1) {
if ((payloadLength = in.read()) == -1) {
return false;
}
switch (versionMarker) {
case MavlinkPacket.MAGIC_V1:
return in.advance(6 + payloadLength);
case MavlinkPacket.MAGIC_V2:
return in.advance(25 + payloadLength);
default:
in.rollback();
in.skip(1);
in.commit();
}
}
return false;
}
public byte[] frame() {
return in.getBuffer();
}
public void drop() throws IOException {
in.rollback();
in.skip(1);
in.commit();
}
}
| true |
38e2fa7400c079c4f3b801364d6a45c47a564bef
|
Java
|
elyasaad/Bank_Demo
|
/src/main/java/bank/transactions/Type.java
|
UTF-8
| 66 | 1.789063 | 2 |
[] |
no_license
|
package bank.transactions;
public enum Type {
WITHDRAW,DEPOSIT
}
| true |
5bc0fcd906934eea14f897f0234a171ca07a7534
|
Java
|
russelldb/InMemoryAppender
|
/src/main/java/com/basho/riak/client/http/util/logging/LogNoHttpResponseRetryHandler.java
|
UTF-8
| 3,451 | 2.421875 | 2 |
[] |
no_license
|
/*
* This file is provided to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.basho.riak.client.http.util.logging;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
/**
* An {@link HttpMethodRetryHandler} that delegates directly to the
* {@link DefaultHttpMethodRetryHandler}, after first checking the
* {@link IOException} type and flushing the {@link InMemoryAppender} if
* required.
*
* <p>
* Works in concert with {@link InMemoryAppender}. To use you must configure
* your log4j correctly. See the log4j.properties example with this project.
* Basically, the "httpclient.wire" logger must have an {@link InMemoryAppender}
* configured for it. And the name of the appender must be made available to
* this class, either via the constructor or by using
* {@link InMemoryAppender#DEFAULT_NAME}
* </p>
*
* @author russell
*
*/
public class LogNoHttpResponseRetryHandler implements HttpMethodRetryHandler {
private static final Logger logger = Logger.getLogger("httpclient.wire");
private static final String INMEM_APPENDER_NAME = InMemoryAppender.DEFAULT_NAME;
private final DefaultHttpMethodRetryHandler delegate = new DefaultHttpMethodRetryHandler();
private final InMemoryAppender inMemoryAppender;
/**
* Create a handler which calls dump on an appender with the name
* {@link InMemoryAppender#DEFAULT_NAME}
*/
public LogNoHttpResponseRetryHandler() {
this(INMEM_APPENDER_NAME);
}
/**
* Create a hndler which called dump on an appender with the name
* <code>inMemAppenderName</code>
*
* @param inMemAppenderName
* the name of the "httpclient.wire" appender to call
* <code>dump</code> on when a {@link NoHttpResponseException} is
* received.
*/
public LogNoHttpResponseRetryHandler(String inMemAppenderName) {
Appender a = logger.getAppender(inMemAppenderName);
if (a == null || !(a instanceof InMemoryAppender)) {
throw new IllegalStateException("No " + INMEM_APPENDER_NAME + " appender found");
}
inMemoryAppender = (InMemoryAppender) a;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.commons.httpclient.HttpMethodRetryHandler#retryMethod(org.
* apache.commons.httpclient.HttpMethod, java.io.IOException, int)
*/
@Override public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
if (exception instanceof NoHttpResponseException) {
inMemoryAppender.dump();
}
return delegate.retryMethod(method, exception, executionCount);
}
}
| true |
7293d48b784538dfe9a43409235f09fecd6f7e49
|
Java
|
whulucy/NewsArticleGrouping
|
/SCUCourses/SCU2016Spring/coen268JunSun/PA for Mobile Programming/PA4/li.xiaoyu.pa4/app/src/main/java/edu/scu/xli2/photonotesplus/AddPhoto.java
|
UTF-8
| 12,812 | 1.664063 | 2 |
[] |
no_license
|
package edu.scu.xli2.photonotesplus;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Xiaoyu on 5/10/16.
*/
public class AddPhoto extends AppCompatActivity implements SensorEventListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private EditText caption_edit;
private Button take_photoBtn;
private Button save_photoBtn;
private Uri imageUri;
private static final int TAKE_PICTURE = 1;
private int maxId;
private static final String fileExt = ".jpg";
private PhotoDbHelper dbHelper;
Cursor cursor;
String fileName; //original fileName
String thumbFile; //thumbFile generated
MyPhoto myPhoto;
//section for the shake sensor part
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
//section for adding audio recording
private static final String LOG_TAG = "AudioRecordTest";
private static String voiceFile = null;
private Button mRecordButton = null;
private MediaRecorder mRecorder = null;
private Button mPlayButton = null;
private MediaPlayer mPlayer = null;
//section for adding geoLocation
String mLastLocation = "";
String revisedPath = "";
//section for photo preview
TouchDrawView preview;
//get the location
GoogleApiClient mGoogleApiClient = null;
// String mLatitudeText;
// String mLongitudeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_photo);
caption_edit = (EditText) findViewById(R.id.captionEdit);
take_photoBtn = (Button) findViewById(R.id.button_take);
save_photoBtn = (Button) findViewById(R.id.button_save);
dbHelper = new PhotoDbHelper(getApplicationContext());
verifyStoragePermissions(this);
verifyMapPermissions(this);
preview = (TouchDrawView)findViewById(R.id.photo_preview);
maxId = dbHelper.getMaxRecID() + 1;
//audio part
voiceFile = Environment.getExternalStorageDirectory().getAbsolutePath();
voiceFile += "/audiorecordtest" + maxId + ".3gp";
mRecordButton = (Button)findViewById(R.id.button_record);
mRecordButton.setText("Start recording");
mRecordButton.setOnClickListener(new View.OnClickListener() {
boolean mStartRecording = true;
@Override
public void onClick(View v) {
if (mStartRecording) {
mRecordButton.setText("Stop recording");
mRecordButton.setBackgroundColor(Color.RED);
startRecording();
} else {
mRecordButton.setText("Start recording");
mRecordButton.setBackgroundColor(Color.WHITE);
stopRecording();
}
mStartRecording = !mStartRecording;
}
});
mPlayButton = (Button)findViewById(R.id.button_play);
mPlayButton.setText("Start playing");
mPlayButton.setOnClickListener(new View.OnClickListener(){
boolean mStartPlaying = true;
public void onClick(View v){
if (mStartPlaying) {
mPlayButton.setText("Stop playing");
mPlayButton.setBackgroundColor(Color.BLUE);
startPlaying();
} else {
mPlayButton.setText("Start playing");
mPlayButton.setBackgroundColor(Color.WHITE);
stopPlaying();
}
mStartPlaying = !mStartPlaying;
}
});
//initialization for the sensor part
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
//section for the map
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
//section for the voice recording begin
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(voiceFile);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
mRecorder = null;
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(voiceFile);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
@Override
// public void onPause() {
// super.onPause();
// if (mRecorder != null) {
// mRecorder.release();
// mRecorder = null;
// }
//
// if (mPlayer != null) {
// mPlayer.release();
// mPlayer = null;
// }
// }
//Section for the recording ends
//section for the sensor
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta * 0.1f; // perform low-cut filter
displayAcceleration();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
private void displayAcceleration() {
float accel = Math.abs( mAccel);
if (accel > 0.2f) {
preview.clear();
}
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
// Storage Permissions
private static final int REQUEST_MAP = 2;
private static String[] PERMISSIONS_MAP = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
public static void verifyMapPermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_MAP,
REQUEST_MAP
);
}
}
public void takePhotoFunc(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), maxId + fileExt);
String caption = caption_edit.getText().toString();
revisedPath = photo.getPath();
myPhoto = new MyPhoto(caption, photo.getPath(),revisedPath, voiceFile, mLastLocation);
dbHelper.add(myPhoto);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
fileName=photo.getPath();
thumbFile=photo.getPath();
startActivityForResult(intent, TAKE_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != TAKE_PICTURE || resultCode != RESULT_OK) return;
try {
Bitmap picture = BitmapFactory.decodeFile(fileName);
Drawable drawable = new BitmapDrawable(getResources(), picture);
preview.setBackground(drawable);
Bitmap resized = ThumbnailUtils.extractThumbnail(picture, 120, 120);
FileOutputStream fos = new FileOutputStream(thumbFile);
resized.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush(); fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void savePhotoFunc(View view){
preview.setDrawingCacheEnabled(true);
Bitmap b = preview.getDrawingCache();
Bitmap resized = ThumbnailUtils.extractThumbnail(b, 120, 120);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(revisedPath);
resized.compress(Bitmap.CompressFormat.JPEG, 120, fos);
fos.flush();
fos.close();
myPhoto.setPath(revisedPath);
} catch(Exception e){
e.printStackTrace();
}
startActivity(new Intent(this, MainActivity.class));
finish();
}
public void onConnectionSuspended(int var1){
}
@Override
public void onConnected(Bundle connectionHint) {
try {
Location location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
mLastLocation = Location.convert(location.getLatitude(), Location.FORMAT_DEGREES) + " " + Location.convert(location.getLongitude(), Location.FORMAT_DEGREES);
Log.i(mLastLocation,"location");
}catch (SecurityException exception){
exception.printStackTrace();
}
}
public void onLocationChanged(Location location)
{
}
public void onConnectionFailed(ConnectionResult var1){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
public void onProviderEnabled(String provider){
}
public void onProviderDisabled(String provider){
}
}
| true |
95d8d923cc04f992b00bdee0a66c328f936359e9
|
Java
|
mvvianaf/Inventory
|
/app/src/main/java/net/viniciusviana/inventory/YoungActivity.java
|
UTF-8
| 4,281 | 2.578125 | 3 |
[] |
no_license
|
package net.viniciusviana.inventory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import net.viniciusviana.inventory.adapter.ItemAdapter;
import net.viniciusviana.inventory.dao.CountDao;
import net.viniciusviana.inventory.model.Count;
import net.viniciusviana.inventory.model.Item;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class YoungActivity extends AppCompatActivity implements View.OnClickListener{
private EditText txtCompany;
private EditText txtBarCode;
private Button btnStart;
private Button btnInsert;
private Button btnEnd;
private ListView lvItens;
private Count c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_young);
//START COUNT AND LIST OF ITENS
this.c = new Count();
//JOIN
this.txtCompany = (EditText)findViewById(R.id.txtCompany);
this.txtBarCode = (EditText)findViewById(R.id.txtBarCode);
this.lvItens = (ListView)findViewById(R.id.lvItens);
this.btnStart = (Button)findViewById(R.id.btnStart);
this.btnInsert = (Button)findViewById(R.id.btnInsert);
this.btnEnd = (Button)findViewById(R.id.btnEnd);
//SET ONCLICK
this.btnStart.setOnClickListener(this);
this.btnInsert.setOnClickListener(this);
this.btnEnd.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:
start();
break;
case R.id.btnInsert:
insertCodeBar();
break;
case R.id.btnEnd:
save();
break;
}
}
private void start(){
//GET THE NAME OF COMPANY AND DATE TIME THE BEGIN
this.c.setCompany(this.txtCompany.getText().toString());
this.c.setDateTimeStart(Calendar.getInstance());
//DISABLE INFORMATION ABOUT COMPANY
this.txtCompany.setEnabled(false);
this.btnStart.setEnabled(false);
//ENABLE INOUT CODE BARS
this.btnInsert.setEnabled(true);
this.txtBarCode.setEnabled(true);
//SET FOCUS
this.txtBarCode.requestFocus();
}
private void insertCodeBar(){
//CHECK IF THE INPUT THERE ISN'T EMPTY
if(!this.txtBarCode.getText().toString().equals("")) {
Item i = new Item();
i.setBarCode(this.txtBarCode.getText().toString());
i.setQuantity(1);
groupCodeBar(i);
this.lvItens.setAdapter(new ItemAdapter(this, this.c.getItens()));
//MENSAGE OF THE SUCESS
Toast.makeText(this,"CODIGO DE BARRA ADICIONADO COM SUCESSO!",Toast.LENGTH_SHORT).show();
//CLEAN INPUT
this.txtBarCode.setText("");
//ENABLE THE END BUTTON
if(this.c.getItens().size()==1)
this.btnEnd.setEnabled(true);
}
else{
Toast.makeText(this,"CODIGO DE BARRA INVALIDO!",Toast.LENGTH_SHORT).show();
}
}
private void groupCodeBar(Item i){
boolean exist = false;
for(Item item:this.c.getItens())
if(item.getBarCode().equals(i.getBarCode())) {
item.setQuantity(item.getQuantity() + 1);
exist = true;
break;
}
if(!exist)
this.c.setItem(i);
}
private void save(){
this.c.setDateTimeEnd(Calendar.getInstance());
new CountDao(this).save(this.c);
//CLEANING UP INPUTS FOR A NEW COUNT
this.txtBarCode.setText("");
this.txtBarCode.setEnabled(false);
this.txtCompany.setText("");
this.txtCompany.setEnabled(true);
this.txtCompany.requestFocus();
this.btnStart.setEnabled(true);
this.btnInsert.setEnabled(false);
this.btnEnd.setEnabled(false);
this.c = new Count();
this.lvItens.setAdapter(new ItemAdapter(this, this.c.getItens()));
}
}
| true |
f2d366fa920682b09bc7d92db437568b77c54de1
|
Java
|
TianLuhua/LJPlayerHD
|
/app/src/main/java/com/example/lj/ljplayerhd/main/offline/dlna/center/IMediaScanListener.java
|
UTF-8
| 179 | 1.671875 | 2 |
[] |
no_license
|
package com.example.lj.ljplayerhd.main.offline.dlna.center;
public interface IMediaScanListener {
public void mediaScan(int mediaType, String mediaPath, String mediaName);
}
| true |
3e1c00f3613a4cadcc519e88ffc63f4f9f1222af
|
Java
|
diembate/TTS
|
/src/test/java/com/ncc/java/domain/OrderInfoTest.java
|
UTF-8
| 715 | 2.234375 | 2 |
[] |
no_license
|
package com.ncc.java.domain;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.ncc.java.web.rest.TestUtil;
public class OrderInfoTest {
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(OrderInfo.class);
OrderInfo orderInfo1 = new OrderInfo();
orderInfo1.setId(1L);
OrderInfo orderInfo2 = new OrderInfo();
orderInfo2.setId(orderInfo1.getId());
assertThat(orderInfo1).isEqualTo(orderInfo2);
orderInfo2.setId(2L);
assertThat(orderInfo1).isNotEqualTo(orderInfo2);
orderInfo1.setId(null);
assertThat(orderInfo1).isNotEqualTo(orderInfo2);
}
}
| true |
6ae946561651558dade0186babf97f117f8b1f9e
|
Java
|
assecopl/fh
|
/fhCoreLite/basicControls/src/main/java/pl/fhframework/model/forms/converters/LabelPositionAttrConverter.java
|
UTF-8
| 534 | 2.09375 | 2 |
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
package pl.fhframework.model.forms.converters;
import pl.fhframework.annotations.XMLPropertyGlobalConverter;
import pl.fhframework.model.forms.attribute.ToLowerCaseEnumAttrConverter;
import pl.fhframework.model.forms.model.LabelPosition;
/**
* Label position input element XML attribute converter
*/
@XMLPropertyGlobalConverter(LabelPosition.class)
public class LabelPositionAttrConverter extends ToLowerCaseEnumAttrConverter<LabelPosition> {
public LabelPositionAttrConverter() {
super(LabelPosition.class);
}
}
| true |
2d9fa8fb90811939ff8915444fd2bc923b70103e
|
Java
|
YeChenLiu/javaTools
|
/src/main/java/test2.java
|
UTF-8
| 728 | 3.6875 | 4 |
[] |
no_license
|
public class test2 {
public static void main(String[] args) {
//反例,浮点数采用“尾数+阶码”的编码方式,类似于科学计数法的“有效数字+指数”的表示方式。二制无法精确表示大部分的十进制小数
double a = 1.0;
double b = 0.9;
double c = 0.8;
if (a - b == b - c) {
System.out.println(true);
} else {
System.out.println(false);
}
//正例,指定一个误差范围,两个浮点数的差值在此范围之内,则认为是相等的
double d = 1.0;
double diff = 1e-6;
if (Math.abs(a - d) < diff) {
System.out.println(true);
}
}
}
| true |
67861f0311772e30caf346c62790cddc263b0f10
|
Java
|
schatterjee4/kafka-event-sourcing
|
/src/main/java/com/github/patrickbcullen/profile/ProfileEventProcessor.java
|
UTF-8
| 2,609 | 2.390625 | 2 |
[
"MIT"
] |
permissive
|
package com.github.patrickbcullen.profile;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.processor.Processor;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
/**
* Created by cullenp on 5/3/17.
*/
public class ProfileEventProcessor implements Processor<String, ProfileEvent> {
private ProcessorContext context;
private KeyValueStore<String, ProfileBean> profileStore;
private KeyValueStore<String, ProfileBean> searchStore;
@Override
public void init(ProcessorContext context) {
this.context = context;
this.context.schedule(10);
profileStore = (KeyValueStore) context.getStateStore(ProfileApp.PROFILE_STORE_NAME);
searchStore = (KeyValueStore) context.getStateStore(ProfileApp.SEARCH_STORE_NAME);
}
@Override
public void process(String uid, ProfileEvent profileEvent) {
if (profileEvent.eventType == null) {
System.out.println(profileEvent.uid);
return;
}
ProfileBean profileBean = profileStore.get(uid);
String email = null;
switch (profileEvent.eventType) {
case "delete":
if (profileBean != null && profileBean.email != null) {
email = profileBean.email;
}
profileBean = null;
break;
case "create":
profileBean = new ProfileBean(profileEvent.uid, profileEvent.username, profileEvent.email);
email = profileBean.email;
break;
case "update":
if (profileEvent.email != null) {
//remove the old email by tombstoning the previous record
searchStore.put(profileBean.email, null);
profileBean.email = profileEvent.email;
}
if (profileEvent.username != null) {
profileBean.username = profileEvent.username;
}
if (profileBean != null && profileBean.email != null) {
email = profileBean.email;
}
break;
}
profileStore.put(uid, profileBean);
if (email != null) {
searchStore.put(email, profileBean);
}
}
@Override
public void punctuate(long timestamp) {
context.commit();
}
@Override
public void close() {
profileStore.close();
searchStore.close();
}
}
| true |
5b969937f89d2c0ff58c082d4c56687dd1558e6e
|
Java
|
ethan-hsiao/officium
|
/HackAThon/app/src/main/java/com/screen/pre/prescreen/Person.java
|
UTF-8
| 2,224 | 2.734375 | 3 |
[] |
no_license
|
package com.screen.pre.prescreen;
/**
* Created by devin on 1/14/2018.
*/
public class Person {
String name, age, education, email, hobbies;
Long phoneNumber;
Double gpa;
public Person(String name, String age, String education, String email, String hobbies, Long phoneNumber, Double gpa) {
this.name = name;
this.age = age;
this.education = education;
this.email = email;
this.hobbies = hobbies;
this.phoneNumber = phoneNumber;
this.gpa = gpa;
}
public int compareTo(Person x) {
int w = 0;
if (gpa - x.getGpa() > 1 || gpa - x.getGpa() < -1) {
w = (int) (gpa - x.getGpa());
} else if (gpa - x.getGpa() > 0) {
w = 1;
} else if (gpa - x.getGpa() < 0) {
w = - 1;
}
return w;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHobbies() {
return hobbies;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Double getGpa() {
return gpa;
}
public void setGpa(Double gpa) {
this.gpa = gpa;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", education='" + education + '\'' +
", email='" + email + '\'' +
", hobbies='" + hobbies + '\'' +
", phoneNumber=" + phoneNumber +
", gpa=" + gpa +
'}';
}
}
| true |
0112fb7a20feeb3e8633e9c9914cb1622be47e6c
|
Java
|
maiorovi/quick-poll
|
/src/main/java/org/home/quickpoll/service/PollService.java
|
UTF-8
| 1,945 | 2.34375 | 2 |
[] |
no_license
|
package org.home.quickpoll.service;
import lombok.extern.slf4j.Slf4j;
import org.home.quickpoll.domain.Poll;
import org.home.quickpoll.domain.mapper.PollMapper;
import org.home.quickpoll.dto.PollDto;
import org.home.quickpoll.repository.PollRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Service
@Slf4j
@Transactional
public class PollService {
private PollRepository pollRepository;
private PollMapper pollMapper;
public PollService(@Autowired PollRepository pollRepository,@Autowired PollMapper pollMapper) {
this.pollRepository = pollRepository;
this.pollMapper = pollMapper;
}
public Poll createPoll(PollDto pollDto) {
Poll poll = pollMapper.toPoll(pollDto);
return pollRepository.save(poll);
}
public List<Poll> getAllPolls() {
List<Poll> polls = pollRepository.findAll();
return polls;
}
public Page<PollDto> getAllPolls(Pageable pageable) {
Page<Poll> page = pollRepository.findAll(pageable);
return page.map(poll -> pollMapper.toPollDto(poll));
}
public Optional<Poll> getPoll(Long pollId) {
return Optional.ofNullable(pollRepository.findOne(pollId));
}
public void deletePoll(Long pollId) {
pollRepository.delete(pollId);
}
public Optional<Poll> updatePoll(Long pollId, PollDto pollDto) {
return getPoll(pollId).map( poll -> {
final Poll updatedPoll = pollMapper.toPoll(pollDto);
poll.setQuestion(updatedPoll.getQuestion());
poll.removeAllOptions();
poll.addAllOptions(updatedPoll.getOptions());
return pollRepository.save(poll);
});
}
}
| true |
e0b38dccb503cd7cdcca436d2fd5945be13c1dbc
|
Java
|
389091912/renren-fast
|
/src/main/java/io/renren/modules/product/service/ProductBoxService.java
|
UTF-8
| 603 | 1.710938 | 2 |
[
"Apache-2.0"
] |
permissive
|
package io.renren.modules.product.service;
import com.baomidou.mybatisplus.service.IService;
import io.renren.common.utils.Dict;
import io.renren.common.utils.PageUtils;
import io.renren.modules.product.entity.ProductBoxEntity;
import java.util.List;
import java.util.Map;
/**
*
*
* @author wsy
* @email [email protected]
* @date 2019-01-25 23:35:04
*/
public interface ProductBoxService extends IService<ProductBoxEntity> {
/**
* 获取 纸箱分页
* @param params
* @return
*/
PageUtils queryPage(Map<String, Object> params);
List<Dict> getAllProductBoxList();
}
| true |
1ce1511a1608f0b7c132fb74e7b3f0c2b19f7c39
|
Java
|
ezScrum/ezScrum_TaskBoardPlugin
|
/src/plugin/taskBoard/webservice/EzScrumWebServiceController.java
|
UTF-8
| 3,004 | 2.25 | 2 |
[] |
no_license
|
package plugin.taskBoard.webservice;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.ws.rs.core.MediaType;
import org.codehaus.jettison.json.JSONObject;
import ch.ethz.ssh2.crypto.Base64;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
public class EzScrumWebServiceController {
private String mEzScrumURL;
public EzScrumWebServiceController(String ezScrumURL) {
mEzScrumURL = ezScrumURL;
}
public String getSprintInfoListString(String projectID, String account, String encodePassword) {
// user information 加密
String encodeProjectID = encodeUrl(projectID);
String encodeUserName = new String(Base64.encode(account.getBytes()));
String getSprintInfoWebServiceUrl = "http://" + mEzScrumURL +
"/web-service/" + encodeProjectID +
"/sprint-backlog/sprintlist?userName=" + encodeUserName +
"&password=" + encodePassword;
System.out.println(getSprintInfoWebServiceUrl);
Client client = Client.create();
WebResource webResource = client.resource(getSprintInfoWebServiceUrl);
Builder result = webResource.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
return result.get(String.class);
}
public String getSprintBacklog(String projectID, String account, String encodePassword, String sprintID, String handlerID) {
// user information 加密
// user information 加密
String encodeProjectID = encodeUrl(projectID);
String encodeUserName = new String(Base64.encode(account.getBytes()));
try {
System.out.println(encodeUserName.toCharArray());
Base64.decode(encodeUserName.toCharArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//http://IP:8080/ezScrum/web-service/{projectID}/sprint-backlog/{sprintID}/sprintbacklog?userName={userName}&password={password}
String getTaskBoardStoryTaskWebServiceUrl = "http://" + mEzScrumURL +
"/web-service/" + encodeProjectID +
"/sprint-backlog/" + sprintID + "/" + handlerID +
"/sprintbacklog?userName=" + encodeUserName +
"&password=" + encodePassword;
System.out.println(getTaskBoardStoryTaskWebServiceUrl);
Client client = Client.create();
WebResource webResource = client.resource(getTaskBoardStoryTaskWebServiceUrl);
Builder result = webResource.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
System.out.println("result.get(String.class);: " + result.get(String.class));
return result.get(String.class);
}
private String encodeUrl(String url) {
String result = "";
try {
result = URLEncoder.encode(url, "UTF-8");
result = result.replace("+", "%20");// % 為特殊字元, encoder讀到會有問題, 所以等encoder完再把+轉成%20
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}
| true |
f5690365e88023f9f1c9f3339796db5a9180e7a6
|
Java
|
s-k-github/Data-Structure
|
/graph/graphArray/GraphMain.java
|
UTF-8
| 1,289 | 3.421875 | 3 |
[] |
no_license
|
package graph.graphArray;
import java.util.Scanner;
public class GraphMain {
//5 0 1 0 4 1 2 1 4 2 3 3 4 -1
public static void main(String[] args) {
int source,target;
System.out.println("Please enter number of vertices : ");
Scanner sc=new Scanner(System.in);
int vertices=sc.nextInt();
GraphOperations graph=new GraphOperations(vertices);
System.out.print("Enter source and target to connect two vertices : ");
System.out.print("\nsource target ->");
source=sc.nextInt();
target=sc.nextInt();
try {
do {
graph.add(source,target);
System.out.print("source target ->");
source=sc.nextInt();
target=sc.nextInt();
}while(source!=-1 || target!=-1);
graph.display();
System.out.println("How many vertex you wish to delete ? ");
int n=sc.nextInt();
do {
System.out.print("source target ->");
source=sc.nextInt();
target=sc.nextInt();
graph.delete(source,target);
n--;
}while(n!=0);
sc.close();
graph.display();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("\nThe souce or destination you have provided is invalid");
System.out.println("source and destination must be between 0 and "+(vertices-1));
}
}
}
| true |
52d9422570fe4d4ce9968c9b87ef8363872cc8db
|
Java
|
sistonnay/ZKTeco
|
/app/src/main/java/com/zkteco/autk/components/EnrollActivity.java
|
UTF-8
| 10,966 | 1.757813 | 2 |
[] |
no_license
|
package com.zkteco.autk.components;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zkteco.autk.R;
import com.zkteco.autk.presenters.EnrollPresenter;
import com.zkteco.autk.utils.Utils;
import com.zkteco.autk.views.OverlayView;
/**
* author: Created by Ho Dao on 2019/7/29 0029 00:27
* email: [email protected] (github: sistonnay)
*/
public class EnrollActivity extends BaseActivity<EnrollPresenter> implements View.OnClickListener {
private static final String TAG = Utils.TAG + "#" + EnrollActivity.class.getSimpleName();
private static final String ADMIN_PASS = "123456";
public static final int MODE_NULL = -1;
public static final int MODE_IDENTIFY = 0;
public static final int MODE_CHECK_IN = 1;
public static final int MODE_ENTERING = 2;
public static final int MODE_ENROLL = 3;
private TextureView mPreVRect;
private OverlayView mOverlayRect;
private OverlayView.OverlayTheme mEnrollTheme;
private OverlayView.OverlayTheme mIdentifyTheme;
private LinearLayout mAlert;
private LinearLayout mInputInfo;
private LinearLayout mRegisterInfo;
private ImageView mBackButton;
private ImageView mNextButton;
private ImageView mEnrollButton;
private TextView mAlertText;
private TextView mPassText;
private TextView mNameText;
private TextView mJobNumberText;
private TextView mPhoneText;
private int mode = MODE_IDENTIFY;
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
mPresenter.init();
refreshUI();
}
@Override
protected void onResume() {
super.onResume();
mPresenter.setSurfaceTextureListener(mPreVRect);
mPresenter.resume();
}
@Override
protected void onPause() {
super.onPause();
mPresenter.pause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.destroy();
}
@Override
public int getLayoutId() {
return R.layout.activity_enroll;
}
@Override
public void initViews() {
mPreVRect = (TextureView) findViewById(R.id.preview);
mOverlayRect = (OverlayView) findViewById(R.id.overlay_view);
/*
WindowManager wm =getWindowManager();
ViewGroup.LayoutParams params = mPreVRect.getLayoutParams();
params.width = wm.getDefaultDisplay().getWidth();
params.height = (int) (params.width * (640.0f / 360.0f));
Logger.d(TAG, "surface view width = " + params.width + ", height = " + params.height);
mPreVRect.setLayoutParams(params);
*/
mAlert = (LinearLayout) findViewById(R.id.ly_alert);
mAlertText = (TextView) mAlert.findViewById(R.id.tv_alert);
mInputInfo = (LinearLayout) findViewById(R.id.ly_input_info);
mBackButton = (ImageView) mInputInfo.findViewById(R.id.back);
mBackButton.setOnClickListener(this);
mNextButton = (ImageView) mInputInfo.findViewById(R.id.next);
mNextButton.setOnClickListener(this);
mPassText = (TextView) mInputInfo.findViewById(R.id.tv_password);
mPassText.setOnClickListener(this);
mRegisterInfo = (LinearLayout) mInputInfo.findViewById(R.id.ly_register_info);
mNameText = (TextView) mRegisterInfo.findViewById(R.id.tv_name);
mNameText.setOnClickListener(this);
mJobNumberText = (TextView) mRegisterInfo.findViewById(R.id.tv_job_number);
mJobNumberText.setOnClickListener(this);
mPhoneText = (TextView) mRegisterInfo.findViewById(R.id.tv_phone);
mPhoneText.setOnClickListener(this);
mEnrollButton = (ImageView) findViewById(R.id.enroll);
mEnrollButton.setOnClickListener(this);
mEnrollTheme = mOverlayRect.getThemeFromTypedArray(
obtainStyledAttributes(R.style.OverlayView_Enroll, R.styleable.OverlayView));
mIdentifyTheme = mOverlayRect.getThemeFromTypedArray(
obtainStyledAttributes(R.style.OverlayView_Identify, R.styleable.OverlayView));
}
public void setMode(int mode) {
this.mode = mode;
}
public int getMode() {
return mode;
}
public void updateAlert(String text) {
mAlertText.setText(text);
}
public void refreshUI() {
switch (mode) {
case MODE_IDENTIFY: {
mAlert.setVisibility(View.VISIBLE);
mAlertText.setText(R.string.setup_enrollment_message);
mInputInfo.setVisibility(View.GONE);
mEnrollButton.setVisibility(View.VISIBLE);
mOverlayRect.setTheme(mIdentifyTheme);
}
break;
case MODE_CHECK_IN: {
mAlert.setVisibility(View.GONE);
mInputInfo.setVisibility(View.VISIBLE);
mPassText.setVisibility(View.VISIBLE);
mRegisterInfo.setVisibility(View.GONE);
mEnrollButton.setVisibility(View.GONE);
mOverlayRect.setTheme(mIdentifyTheme);
}
break;
case MODE_ENTERING: {
mAlert.setVisibility(View.GONE);
mInputInfo.setVisibility(View.VISIBLE);
mRegisterInfo.setVisibility(View.VISIBLE);
mPassText.setVisibility(View.GONE);
mEnrollButton.setVisibility(View.VISIBLE);
mOverlayRect.setTheme(mEnrollTheme);
}
break;
case MODE_ENROLL: {
mAlert.setVisibility(View.GONE);
mInputInfo.setVisibility(View.VISIBLE);
mEnrollButton.setVisibility(View.GONE);
mOverlayRect.setTheme(mEnrollTheme);
}
break;
}
mNameText.setText(mPresenter.getName());
mJobNumberText.setText(mPresenter.getJobNumber());
mPhoneText.setText(mPresenter.getPhone());
mPassText.setText(mPresenter.getAdminPass());
}
@Override
public void initPresenter() {
mPresenter = new EnrollPresenter();
}
@Override
public void onBackPressed() {
switch (mode) {
case MODE_ENROLL:
case MODE_ENTERING:
case MODE_CHECK_IN: {
mode = MODE_IDENTIFY;
mPresenter.resetInfo();
refreshUI();
}
break;
case MODE_IDENTIFY: {
super.onBackPressed();
}
break;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back: {
onBackPressed();
}
break;
case R.id.next: {
if (mode == MODE_CHECK_IN) {
if (TextUtils.equals(mPresenter.getAdminPass(), ADMIN_PASS)) {
mode = MODE_ENTERING;
} else {
toast("Password Error!");
return;
}
} else if (mode == MODE_ENTERING) {
if (mPresenter.isLegalEnrollInfo()) {
mode = MODE_ENROLL;
} else {
toast("Name or ID or Phone Error!");
return;
}
} else if (mode == MODE_ENROLL) {
mode = MODE_ENTERING;
}
refreshUI();
}
break;
case R.id.enroll: {
if (mode == MODE_IDENTIFY) {
mode = MODE_CHECK_IN;
mPresenter.resetInfo();
refreshUI();
} else if (mode == MODE_ENTERING) {
toast("当前网址:" + mPresenter.getUploadUrl());
new IPEditDialog(this, R.string.dialog_title_url, InputType.TYPE_CLASS_TEXT) {
@Override
public void onDialogOK(String ip, String port) {
if (!TextUtils.isEmpty(ip) && !TextUtils.isEmpty(port)) {
String url = "http://" + ip.trim() + ":" + port.trim() + "/wms/StorageFinger/001";
mPresenter.setUploadUrl(url);
//Logger.v(TAG, "url=" + url);
toast("更新网址:" + url);
}
}
}.show();
}
}
break;
case R.id.tv_password: {
EditDialog dialog = new EditDialog(this, R.string.dialog_title_pass, InputType.TYPE_CLASS_NUMBER) {
@Override
public void onDialogOK(String text) {
mPassText.setText(text);
mPresenter.setAdminPass(text);
mInputInfo.setVisibility(View.VISIBLE);
}
};
dialog.passWordStyle(true);
dialog.show();
}
break;
case R.id.tv_name: {
new EditDialog(this, R.string.dialog_title_name, InputType.TYPE_CLASS_TEXT) {
@Override
public void onDialogOK(String text) {
mNameText.setText(text);
mPresenter.setName(text);
}
}.show();
}
break;
case R.id.tv_job_number: {
new EditDialog(this, R.string.dialog_title_job_number, InputType.TYPE_CLASS_NUMBER) {
@Override
public void onDialogOK(String text) {
mJobNumberText.setText(text);
mPresenter.setJobNumber(text);
}
}.show();
}
break;
case R.id.tv_phone: {
new EditDialog(this, R.string.dialog_title_phone, InputType.TYPE_CLASS_PHONE) {
@Override
public void onDialogOK(String text) {
mPhoneText.setText(text);
mPresenter.setPhone(text);
}
}.show();
}
break;
}
}
public void setBrightness(int brightness) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
getWindow().setAttributes(lp);
}
}
| true |
4ac537ab4f4558d8606633b90b9d81dc0a93dbfb
|
Java
|
cngzltrk/java
|
/odev4/src/odev4/Odev4.java
|
UTF-8
| 1,995 | 2.96875 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package odev4;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
*
* @author Cengiz Altürk G140910048 [email protected]
* Elmar Dadaşov G151210564
* @since 29.04.2017
*/
public class Odev4 {
public static void main(String[] args) {
Scanner veriAl=new Scanner(System.in);
System.out.print("Sayi giriniz...:");
Sayi sy=new Sayi(veriAl.nextLong());
Sayi snc=new Sayi();
havuz h=new havuz(sy,snc);
Dosyalama d=new Dosyalama();
ExecutorService hvz=Executors.newFixedThreadPool(1);
sy.sureBas();
hvz.execute(h);
hvz.shutdown();
while(!hvz.isTerminated())
{}
sy.sureBit();
System.out.println("Seri Hesaplanma Süresi " + String.format("%.2f", sy.sure()) + " milisaniye.");
h.HavuzSayisi(sy.getSayi());
hvz=Executors.newFixedThreadPool(h.HavuzSayisi());
snc.setSifirla();
sy.sureBas();
long aralik=sy.getSayi()/h.HavuzSayisi();
long bas=0,bit=0;
for(int i=1;i<=h.HavuzSayisi();i++)
{
if(i==1)
{
bas=sy.getSayi();
bit=bas-aralik;
}
else
{
bas=bit-1;
bit=bas-aralik;
if(bit<1)
{
bit=1;
}
}
hvz.execute(new havuz(sy,snc,bas,bit));
}
hvz.shutdown();
while(!hvz.isTerminated())
{}
sy.sureBit();
System.out.println("Paralel Hesaplanma Süresi " + String.format("%.2f", sy.sure()) + " milisaniye.");
d.writer(String.valueOf(snc.getSnc())+" \n");
System.out.println("Sonuc Dosyaya Yazıldı.");
}
}
| true |
e9a6c65e23fe2cc9b78c6e810fcbac3246bf0b86
|
Java
|
bellmit/cms-1
|
/JavaSource/com/yuanluesoft/im/model/IMDatagramConnection.java
|
UTF-8
| 843 | 2.328125 | 2 |
[] |
no_license
|
package com.yuanluesoft.im.model;
import java.io.Serializable;
/**
*
* @author linchuan
*
*/
public class IMDatagramConnection implements Serializable {
private byte channelIndex; //使用的通道号
private String ip; //IP
private char port; //端口
/**
* @return the channelIndex
*/
public byte getChannelIndex() {
return channelIndex;
}
/**
* @param channelIndex the channelIndex to set
*/
public void setChannelIndex(byte channelIndex) {
this.channelIndex = channelIndex;
}
/**
* @return the ip
*/
public String getIp() {
return ip;
}
/**
* @param ip the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}
/**
* @return the port
*/
public char getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(char port) {
this.port = port;
}
}
| true |
727571cdf557192bd9eebb06a57334b96999af81
|
Java
|
ArchkWay/brewmapp
|
/app/src/main/java/com/brewmapp/presentation/view/impl/widget/ItemEvaluationView.java
|
UTF-8
| 8,371 | 1.570313 | 2 |
[] |
no_license
|
package com.brewmapp.presentation.view.impl.widget;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.brewmapp.R;
import com.brewmapp.app.di.module.PresenterModule;
import com.brewmapp.app.environment.BeerMap;
import com.brewmapp.app.environment.Starter;
import com.brewmapp.data.entity.BaseEvaluation;
import com.brewmapp.data.entity.Beer;
import com.brewmapp.data.entity.EvaluationBeer;
import com.brewmapp.data.entity.EvaluationResto;
import com.brewmapp.data.entity.Resto;
import com.brewmapp.data.entity.RestoDetail;
import com.brewmapp.data.entity.wrapper.BeerInfo;
import com.brewmapp.data.entity.wrapper.EvaluationData;
import com.brewmapp.data.pojo.LoadProductPackage;
import com.brewmapp.data.pojo.LoadRestoDetailPackage;
import com.brewmapp.execution.exchange.request.base.Keys;
import com.brewmapp.execution.task.LoadProductTask;
import com.brewmapp.execution.task.LoadRestoDetailTask;
import com.brewmapp.presentation.view.impl.activity.BaseActivity;
import com.squareup.picasso.Picasso;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.davidea.flexibleadapter.items.IFlexible;
import ru.frosteye.ovsa.execution.task.SimpleSubscriber;
import ru.frosteye.ovsa.presentation.view.InteractiveModelView;
import ru.frosteye.ovsa.presentation.view.widget.BaseLinearLayout;
/**
* Created by Kras on 20.01.2018.
*/
public class ItemEvaluationView extends BaseLinearLayout implements InteractiveModelView<EvaluationData> {
@BindView(R.id.view_evaluation_avatar) ImageView avatar;
@BindView(R.id.view_evaluation_title) TextView title;
@BindView(R.id.view_evaluation_interior) TextView interior;
@BindView(R.id.view_evaluation_service) TextView service;
@BindView(R.id.view_evaluation_beer) TextView beer;
@BindView(R.id.view_evaluation_effect) TextView effect;
@BindView(R.id.view_evaluation_aftertaste) TextView aftertaste;
@BindView(R.id.view_evaluation_color) TextView color;
@BindView(R.id.view_evaluation_taste) TextView taste;
@BindView(R.id.view_evaluation_flavor) TextView flavor;
@BindView(R.id.view_evaluation_container_resto) View container_resto;
@BindView(R.id.view_evaluation_container_beer) View container_beer;
private EvaluationData evaluationData;
private Listener listener;
@Inject
public LoadRestoDetailTask loadRestoDetailTask;
@Inject
public LoadProductTask loadProductTask;
public ItemEvaluationView(Context context) {
super(context);
}
public ItemEvaluationView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ItemEvaluationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ItemEvaluationView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void setListener(Listener listener) {
this.listener=listener;
}
@Override
protected void prepareView() {
if(isInEditMode()) return;
ButterKnife.bind(this);
BeerMap.getAppComponent().plus(new PresenterModule(this)).inject(this);
}
@Override
public void setModel(EvaluationData model) {
this.evaluationData=model;
}
@Override
public EvaluationData getModel() {
return null;
}
//**********************************
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
evaluationData=null;
loadRestoDetailTask.cancel();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if(isInEditMode()) return;
if(evaluationData!=null) {
switch (evaluationData.getType_of_object_evaluation()) {
case Keys.CAP_RESTO:
container_beer.setVisibility(GONE);
handleResto();
break;
case Keys.CAP_BEER:
container_resto.setVisibility(GONE);
handleBeer();
break;
}
}
}
//***********************************
private void handleBeer() {
setOnClickListener(v -> Starter.BeerDetailActivity(getContext(), evaluationData.getId_of_object_evaluation()));
Iterator<BaseEvaluation> iterator = evaluationData.iterator();
while (iterator.hasNext()) {
EvaluationBeer evaluationBeer = (EvaluationBeer) iterator.next();
switch (evaluationBeer.getEvaluation_type()) {
case "1":
flavor.setText(evaluationBeer.getEvaluation_value());
break;
case "2":
taste.setText(evaluationBeer.getEvaluation_value());
break;
case "3":
color.setText(evaluationBeer.getEvaluation_value());
break;
case "4":
aftertaste.setText(evaluationBeer.getEvaluation_value());
break;
}
}
LoadProductPackage loadProductPackage=new LoadProductPackage();
loadProductPackage.setId(evaluationData.getId_of_object_evaluation());
avatar.setImageResource(R.drawable.ic_default_beer);
loadProductTask.execute(loadProductPackage,new SimpleSubscriber<List<IFlexible>>(){
@Override
public void onNext(List<IFlexible> iFlexibles) {
super.onNext(iFlexibles);
try {
Beer beer=((BeerInfo)iFlexibles.get(0)).getModel();
Picasso.with(getContext()).load(beer.getGetThumb()).fit().centerInside().error(R.drawable.ic_default_resto).into(avatar);
title.setText(beer.getFormatedTitle());
}catch (Exception e){}
}
@Override
public void onError(Throwable e) {
super.onError(e);
}
});
}
private void handleResto() {
setOnClickListener(v -> Starter.RestoDetailActivity((BaseActivity) getContext(), evaluationData.getId_of_object_evaluation()));
Iterator<BaseEvaluation> iterator = evaluationData.iterator();
while (iterator.hasNext()) {
EvaluationResto evaluationResto = (EvaluationResto) iterator.next();
switch (evaluationResto.getEvaluation_type()) {
case "1":
interior.setText(evaluationResto.getEvaluation_value());
break;
case "2":
service.setText(evaluationResto.getEvaluation_value());
break;
case "3":
beer.setText(evaluationResto.getEvaluation_value());
break;
case "4":
effect.setText(evaluationResto.getEvaluation_value());
break;
}
}
LoadRestoDetailPackage loadRestoDetailPackage=new LoadRestoDetailPackage();
loadRestoDetailPackage.setId(evaluationData.getId_of_object_evaluation());
avatar.setImageResource(R.drawable.ic_default_resto);
loadRestoDetailTask.execute(loadRestoDetailPackage,new SimpleSubscriber<RestoDetail>(){
@Override
public void onNext(RestoDetail restoDetail) {
super.onNext(restoDetail);
Resto resto=restoDetail.getResto();
if(!TextUtils.isEmpty(resto.getThumb())) {
try {
Picasso.with(getContext()).load(resto.getThumb()).fit().centerCrop().error(R.drawable.ic_default_resto).into(avatar);
} catch (Exception e) {
}
}
try {
title.setText(resto.getName());
}catch (Exception e){}
}
});
}
}
| true |
cc0813c7364b800742aa78f85bb2496a8f730000
|
Java
|
VirgilSecurity/demo-e2ee-android
|
/app/src/main/java/com/android/virgilsecurity/jwtworkexample/data/local/UserManager.java
|
UTF-8
| 3,670 | 1.867188 | 2 |
[
"Unlicense"
] |
permissive
|
/*
* Copyright (c) 2015-2018, Virgil Security, Inc.
*
* Lead Maintainer: Virgil Security Inc. <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* (3) Neither the name of virgil nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.virgilsecurity.jwtworkexample.data.local;
import android.content.Context;
import com.android.virgilsecurity.jwtworkexample.data.model.Token;
import com.android.virgilsecurity.jwtworkexample.data.model.User;
import com.google.gson.Gson;
import com.virgilsecurity.sdk.cards.Card;
/**
* Created by Danylo Oliinyk on 3/23/18 at Virgil Security.
* -__o
*/
public class UserManager extends PropertyManager {
private static final String CURRENT_USER = "CURRENT_USER";
private static final String USER_CARD = "USER_CARD";
private static final String GOOGLE_TOKEN = "GOOGLE_TOKEN";
public UserManager(Context context) {
super(context);
}
public void setCurrentUser(User user) {
setValue(CURRENT_USER, new Gson().toJson(user));
}
public User getCurrentUser() {
return new Gson().fromJson(
(String) getValue(CURRENT_USER,
PropertyManager.SupportedTypes.STRING,
null),
User.class);
}
public void clearCurrentUser() {
clearValue(CURRENT_USER);
}
public void setUserCard(Card card) {
setValue(USER_CARD, new Gson().toJson(card));
}
public Card getUserCard() {
return new Gson().fromJson(
(String) getValue(USER_CARD,
SupportedTypes.STRING,
null),
Card.class);
}
public void clearUserCard() {
clearValue(USER_CARD);
}
public void setGoogleToken(Token token) {
setValue(GOOGLE_TOKEN, new Gson().toJson(token));
}
public Token getGoogleToken() {
return new Gson().fromJson(
(String) getValue(GOOGLE_TOKEN,
SupportedTypes.STRING,
null),
Token.class
);
}
public void clearGoogleToken() {
clearValue(GOOGLE_TOKEN);
}
}
| true |
e5b3503916db457504d146f61e8fb0cb12991573
|
Java
|
achilles1985/LeetCodeProblems
|
/dynamic/medium/LongestIncreasingSubsequence_300.java
|
UTF-8
| 3,797 | 3.5 | 4 |
[] |
no_license
|
package dynamic.medium;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/** M [marked]
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
*/
/*
Strategy: max(take, notake)
*/
public class LongestIncreasingSubsequence_300 {
public static void main(String[] args) {
LongestIncreasingSubsequence_300 s = new LongestIncreasingSubsequence_300();
System.out.println(s.lengthOfLISDynamicBottomUp(new int[]{1,2,3,4})); // 4
System.out.println(s.lengthOfLIS(new int[]{10,9,2,5,3,7,101,18})); // 4
System.out.println(s.lengthOfLISDynamicTopDown(new int[]{10,9,2,5,3,7,101,18})); // 4
System.out.println(s.lengthOfLISDynamicBottomUp(new int[]{10,9,2,5,3,7,101,18})); // 4
System.out.println(s.lengthOfLIS(new int[]{10, 9, 2, 5, 3, 4})); // 3
System.out.println(s.lengthOfLISDynamicBottomUp(new int[]{-1, 3, 4, 5, 2, 2,2,2})); // 5
}
// Brute Force, O(2^n), O(n) - space, recursion stack. Generate all 2^n subsets and take the longest one
public int lengthOfLIS(int[] nums) {
return lengthOfLIS(nums, Integer.MIN_VALUE, 0);
}
// O(n^2) - time, O(n^2) - space (memo[prevIdx][curIdx])
public int lengthOfLISDynamicTopDown(int[] nums) {
Map<String, Integer> cache = new HashMap<>();
return lengthOfLISDynamicTopDownUtils(nums, Integer.MIN_VALUE, 0, cache);
}
// O(n^2) - time, O(n) - space
public int lengthOfLISDynamicBottomUp(int[] nums) {
int max = 1;
int[] cache = new int[nums.length];
Arrays.fill(cache, 1);
for (int j = 1; j < nums.length; j++) {
for (int i = 0; i < j; i++) {
if (nums[j] > nums[i]) {
cache[j] = Math.max(cache[j], cache[i] + 1);
}
max = Math.max(cache[j], max);
}
}
return max;
}
// O(n*log(n)) - time, O(n) - space
public int lengthOfLIS2(int[] nums) {
int[] dp = new int[nums.length];
int len = 0;
for (int num : nums) {
int i = Arrays.binarySearch(dp, 0, len, num);
if (i < 0) {
i = -(i + 1);
}
dp[i] = num;
if (i == len) {
len++;
}
}
return len;
}
private int lengthOfLIS(int[] nums, int prevValue, int currIdx) {
if (currIdx == nums.length) {
return 0;
}
int taken = 0;
if (prevValue < nums[currIdx]) {
taken = 1 + lengthOfLIS(nums, nums[currIdx], currIdx + 1);
}
int nottaken = lengthOfLIS(nums, prevValue, currIdx + 1);
return Math.max(taken, nottaken);
}
private int lengthOfLISDynamicTopDownUtils(int[] nums, int prevValue, int currIdx, Map<String, Integer> map) {
String key = prevValue + ":" + currIdx;
if (map.containsKey(key)) {
return map.get(key);
}
if (currIdx == nums.length) {
return 0;
}
int taken = 0;
if (prevValue < nums[currIdx]) {
taken = 1 + lengthOfLISDynamicTopDownUtils(nums, nums[currIdx], currIdx+1, map);
}
int notaken = lengthOfLISDynamicTopDownUtils(nums, prevValue, currIdx+1, map);
int res = Math.max(taken, notaken);
map.put(key, res);
return map.get(key);
}
}
| true |
5265deb1a700843767c3565fd36cf99cd6f7e5da
|
Java
|
misterNoah/spring-boot-demo
|
/src/main/java/com/zs/config/DataSourceInit.java
|
UTF-8
| 8,538 | 1.710938 | 2 |
[] |
no_license
|
package com.zs.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.zs.handler.ListStrHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Created with IntelliJ IDEA.
* Description:
* User: zsq-1186
* Date: 2017-08-04
* Time: 17:44
*/
@Configuration
@EnableCaching
@MapperScan(basePackages = "com.zs.repository")
public class DataSourceInit {
static Logger logger= LoggerFactory.getLogger(DataSourceInit.class.getName());
@Value("${app.version}")
String appVersion;
@Value("${spring.datasource.type}")
private Class<? extends DataSource> dataSourceType;
/** 要加载的 mybatis 的配置文件目录 */
private static final String[] RESOURCE_PATH = new String[] { "mapper/*.xml" };
private static final Resource[] RESOURCE_ARRAY;
/** 要加载的 mybatis 类型处理器的目录 随便选择一个用来获取包名*/
private static final String PACKAGE = ListStrHandler.class.getPackage().getName();
private static final TypeHandler[] HANDLE_ARRAY;
static {
RESOURCE_ARRAY = getResourceArray();
HANDLE_ARRAY = getHandleArray();
}
@Bean
@ConfigurationProperties(prefix = "durid") // 加载以 durid 开头的配置
public DataSource setupDruid() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
/** 非线上则将 druid 的 servlet 开启 */
@Bean
@ConditionalOnProperty(name = {"online"}, havingValue = "false")
public ServletRegistrationBean druidServlet() {
return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
logger.info(dataSourceType.toString());
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(setupDruid());
// sessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
// 下面的代码等同 mybatis-config.xml 配置, mybatis 的 mappers 不支持通配符且标签有先后顺序限制! 因此不使用 my...fig.xml
// 配置文件
logger.info("mybatis load xml:({})", toStr(RESOURCE_ARRAY));
sessionFactory.setMapperLocations(RESOURCE_ARRAY);
// 分页插件
//sessionFactory.setPlugins(new Interceptor[]{ mybatisPage() });
logger.info("mybatis load type handle:({})", toStr(HANDLE_ARRAY));
// 为什么使用这种复杂的方式, 而不采用下面只定义一个包名让 mybatis 自己扫描
// 是因为当项目被打成 jar 的形式发布(war 包放进 tomcat 没有这个问题)时, 使用包名扫描的方式无法被加载到
sessionFactory.setTypeHandlers(HANDLE_ARRAY);
// 下面的方式只需要设置一个包名就可以了, 但是当打成 jar 包(war 包放入 tomcat 会解压, 没有这个问题)底下的 jar 发布时会无法装载到类
/** {@link org.apache.ibatis.type.TypeHandlerRegistry#register(String) } */
/** {@link org.apache.ibatis.io.ResolverUtil#find(org.apache.ibatis.io.ResolverUtil.Test, String) } */
/** 类装载这里会无法获取到: {@link org.apache.ibatis.io.VFS#getResources(String) } */
// sessionFactory.setTypeHandlersPackage(MoneyHandler.class.getPackage().getName());
return sessionFactory.getObject();
}
/** 获取 mybatis 要加载的 xml 文件 */
private static Resource[] getResourceArray() {
List<Resource> resourceList = new ArrayList<>();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
for (String path : RESOURCE_PATH) {
try {
Resource[] resources = resolver.getResources(path);
if (resources!=null && resources.length!=0) {
Collections.addAll(resourceList, resources);
}
} catch (IOException e) {
logger.error(String.format("load file(%s) exception", path), e);
}
}
return resourceList.toArray(new Resource[resourceList.size()]);
}
/** 获取 mybatis 装载的类型处理 */
private static TypeHandler[] getHandleArray() {
List<TypeHandler> handlerList = new ArrayList<>();
String packageName = PACKAGE.replace(".", "/");
URL url = com.zs.config.DataSourceInit.class.getClassLoader().getResource(packageName);
if (url != null) {
logger.debug("current mybatis load TypeHandler protocol: " + url.getProtocol());
if ("file".equals(url.getProtocol())) {
File parent = new File(url.getPath());
if (parent.isDirectory()) {
File[] files = parent.listFiles();
if (files!=null && files.length!=0) {
for (File file : files) {
TypeHandler handler = getTypeHandler(file.getName());
if (handler != null) {
handlerList.add(handler);
}
}
}
}
} else if ("jar".equals(url.getProtocol())) {
// java 7 之后的新的 try-with-resources 自动关闭资源地语法糖, 只要实现了 lang.AutoCloseable 或 io.Closeable 就行
try (JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile()) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith(packageName) && name.endsWith(".class")) {
TypeHandler handler = getTypeHandler(name.substring(name.lastIndexOf("/") + 1));
if (handler != null) {
handlerList.add(handler);
}
}
}
} catch (IOException e) {
logger.error("can't load jar file", e);
}
}
}
return handlerList.toArray(new TypeHandler[handlerList.size()]);
}
private static TypeHandler getTypeHandler(String name) {
if (!StringUtils.isEmpty(name)) {
String className = PACKAGE + "." + name.replace(".class", "");
try {
Class<?> clazz = Class.forName(className);
if (clazz != null && TypeHandler.class.isAssignableFrom(clazz)) {
return (TypeHandler) clazz.newInstance();
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
logger.error(String.format("TypeHandler clazz (%s) exception", className), e);
}
}
return null;
}
/** 以,拼接数组值**/
public String toStr(Object[] array){
StringBuilder sb=new StringBuilder();
for (Object obj:array){
sb.append(obj);
sb.append(",");
}
return sb.toString();
}
}
| true |
09b721eeeb8c44b92c7a08235bfd8e7ee0a34397
|
Java
|
liujianhui1204/gmall0105
|
/gmall-api/src/main/java/com/liujianhui/gmall/bean/PmsSkuAttrValue.java
|
UTF-8
| 1,481 | 2.296875 | 2 |
[] |
no_license
|
package com.liujianhui.gmall.bean;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "pms_sku_attr_value", schema = "gmall")
public class PmsSkuAttrValue {
private long id;
private Long attrId;
private Long valueId;
private Long skuId;
@Id
@Column(name = "id")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Basic
@Column(name = "attr_id")
public Long getAttrId() {
return attrId;
}
public void setAttrId(Long attrId) {
this.attrId = attrId;
}
@Basic
@Column(name = "value_id")
public Long getValueId() {
return valueId;
}
public void setValueId(Long valueId) {
this.valueId = valueId;
}
@Basic
@Column(name = "sku_id")
public Long getSkuId() {
return skuId;
}
public void setSkuId(Long skuId) {
this.skuId = skuId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PmsSkuAttrValue that = (PmsSkuAttrValue) o;
return id == that.id &&
Objects.equals(attrId, that.attrId) &&
Objects.equals(valueId, that.valueId) &&
Objects.equals(skuId, that.skuId);
}
@Override
public int hashCode() {
return Objects.hash(id, attrId, valueId, skuId);
}
}
| true |
ac0361ebd30181321f3c060c1e2a507964de7e98
|
Java
|
spbooth/SAFE-WEBAPP
|
/src/test/java/uk/ac/ed/epcc/webapp/servlet/RemoteAuthServletTest.java
|
UTF-8
| 7,381 | 1.710938 | 2 |
[
"Apache-2.0"
] |
permissive
|
//| Copyright - The University of Edinburgh 2016 |
//| |
//| 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 uk.ac.ed.epcc.webapp.servlet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import uk.ac.ed.epcc.webapp.email.MockTansport;
import uk.ac.ed.epcc.webapp.exceptions.ConsistencyError;
import uk.ac.ed.epcc.webapp.junit4.ConfigFixtures;
import uk.ac.ed.epcc.webapp.junit4.DataBaseFixtures;
import uk.ac.ed.epcc.webapp.mock.MockServletConfig;
import uk.ac.ed.epcc.webapp.session.AppUser;
import uk.ac.ed.epcc.webapp.session.AppUserFactory;
import uk.ac.ed.epcc.webapp.session.PasswordAuthComposite;
import uk.ac.ed.epcc.webapp.session.SessionService;
import uk.ac.ed.epcc.webapp.session.WebNameFinder;
/**
* @author spb
* @param <A>
*
*/
public class RemoteAuthServletTest<A extends AppUser> extends ServletTest {
/**
*
*/
public RemoteAuthServletTest() {
}
@Override
public void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
servlet=new RemoteAuthServlet();
MockServletConfig config = new MockServletConfig(serv_ctx, "RemoteServlet");
servlet.init(config);
req.servlet_path="RemoteServlet";
}
@Test
public void testRegister() throws ConsistencyError, Exception{
MockTansport.clear();
takeBaseline();
AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory();
A user = fac.makeBDO();
PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class);
user.setEmail("[email protected]");
composite.setPassword(user,"FredIsDead");
user.commit();
ctx.getService(SessionService.class).setCurrentPerson(user);
req.remote_user="fred";
doPost();
checkMessage("remote_auth_set");
checkDiff("/cleanup.xsl", "remote_set.xml");
}
@Test
@ConfigFixtures("multi_remote.properties")
public void testRegisterMulti() throws ConsistencyError, Exception{
MockTansport.clear();
takeBaseline();
AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory();
A user = fac.makeBDO();
PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class);
user.setEmail("[email protected]");
composite.setPassword(user,"FredIsDead");
user.commit();
ctx.getService(SessionService.class).setCurrentPerson(user);
req.remote_user="fred";
doPost();
checkMessage("remote_auth_set");
checkDiff("/cleanup.xsl", "remote_set2.xml");
}
@Test
public void testSignupRegister() throws ConsistencyError, Exception{
MockTansport.clear();
takeBaseline();
SessionService sess = ctx.getService(SessionService.class);
AppUserFactory<A> fac = sess.getLoginFactory();
A user = fac.makeBDO();
PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class);
user.setEmail("[email protected]");
composite.setPassword(user,"FredIsDead");
user.commit();
// Calling registerNewuser should allow a user to bind
// an existing is and login
AppUserFactory.registerNewUser(ctx, user);
assertFalse(sess.haveCurrentUser());
req.remote_user="fred";
doPost();
checkMessage("remote_auth_set");
assertTrue(sess.isCurrentPerson(user));
checkDiff("/cleanup.xsl", "remote_set.xml");
}
@Test
@ConfigFixtures("multi_remote.properties")
public void testSignupRegisterMulti() throws ConsistencyError, Exception{
MockTansport.clear();
takeBaseline();
SessionService sess = ctx.getService(SessionService.class);
AppUserFactory<A> fac = sess.getLoginFactory();
A user = fac.makeBDO();
PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class);
user.setEmail("[email protected]");
composite.setPassword(user,"FredIsDead");
user.commit();
// Calling registerNewuser should allow a user to bind
// an existing is and login
AppUserFactory.registerNewUser(ctx, user);
assertFalse(sess.haveCurrentUser());
req.remote_user="fred";
doPost();
checkMessage("remote_auth_set");
assertTrue(sess.isCurrentPerson(user));
checkDiff("/cleanup.xsl", "remote_set2.xml");
}
@Test
@DataBaseFixtures("remote_set.xml")
public void testReRegister() throws ConsistencyError, Exception{
MockTansport.clear();
takeBaseline();
AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory();
A user = fac.makeBDO();
PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class);
user.setEmail("[email protected]");
composite.setPassword(user,"FredIsDead");
user.commit();
ctx.getService(SessionService.class).setCurrentPerson(user);
req.remote_user="fred";
doPost();
checkMessage("remote_auth_set");
checkDiff("/cleanup.xsl", "remote_reset.xml");
A old_user = fac.findByEmail("[email protected]");
assertNull(old_user.getRealmName(WebNameFinder.WEB_NAME));
}
@Test
@DataBaseFixtures("remote_set2.xml")
@ConfigFixtures("multi_remote.properties")
public void testReRegisterMulti() throws ConsistencyError, Exception{
MockTansport.clear();
takeBaseline();
AppUserFactory<A> fac = ctx.getService(SessionService.class).getLoginFactory();
A user = fac.makeBDO();
PasswordAuthComposite<A> composite = fac.getComposite(PasswordAuthComposite.class);
user.setEmail("[email protected]");
composite.setPassword(user,"FredIsDead");
user.commit();
ctx.getService(SessionService.class).setCurrentPerson(user);
req.remote_user="fred";
doPost();
checkMessage("remote_auth_set");
checkDiff("/cleanup.xsl", "remote_reset2.xml");
A old_user = fac.findByEmail("[email protected]");
assertNull(old_user.getRealmName(WebNameFinder.WEB_NAME));
}
@Test
@DataBaseFixtures("remote_set.xml")
public void testLogin() throws ConsistencyError, Exception{
req.remote_user="fred";
doPost();
checkRedirect("/main.jsp");
assertEquals("[email protected]",ctx.getService(SessionService.class).getCurrentPerson().getEmail());
}
@Test
@DataBaseFixtures("remote_set2.xml")
@ConfigFixtures("multi_remote.properties")
public void testLoginMulti() throws ConsistencyError, Exception{
req.remote_user="fred";
doPost();
checkRedirect("/main.jsp");
assertEquals("[email protected]",ctx.getService(SessionService.class).getCurrentPerson().getEmail());
}
}
| true |
db50c49ee8572c625555575e2f03138f189da9a1
|
Java
|
GiottoVongoal/HuaBiao
|
/app/src/main/java/com/huabiao/aoiin/ui/view/RegisterCardBaseView.java
|
UTF-8
| 414 | 1.890625 | 2 |
[] |
no_license
|
package com.huabiao.aoiin.ui.view;
import android.content.Context;
import android.support.v7.widget.CardView;
/**
* @author 杨丽亚.
* @PackageName com.huabiao.aoiin.ui.view
* @date 2017-08-03 18:57
* @description 注册卡片基类
*/
public class RegisterCardBaseView extends CardView {
public RegisterCardBaseView(Context context) {
super(context);
}
public void save() {
}
}
| true |
788a5ea0ffae816816a04a4bcee9144af210acbb
|
Java
|
nguyenngoclinhbkhn/CPRAdmod
|
/app/src/main/java/com/cpr/demoadmod/retrofit/API.java
|
UTF-8
| 253 | 1.921875 | 2 |
[] |
no_license
|
package com.cpr.demoadmod.retrofit;
import com.cpr.demoadmod.model.Application;
import com.google.gson.JsonElement;
import retrofit2.Call;
import retrofit2.http.GET;
public interface API {
@GET("list_apps.php")
Call<JsonElement> listApp();
}
| true |
f55f287de7e87c20a61d45ebe1df272a23ce441d
|
Java
|
ctchentao/sort-algorithm
|
/algorithm/QuickSort.java
|
UTF-8
| 1,342 | 3.703125 | 4 |
[] |
no_license
|
package algorithm;
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
public static int partition(int[] data, int start, int end) {
Random random = new Random();
int index = random.nextInt(end - start + 1) + start;
swap(data, index, end);
int small = start - 1;
for (index = start; index < end; ++index) {
if (data[index] < data[end]) {
++ small;
if (small != index) {
swap(data, small, index);
}
}
}
++ small;
swap(data, small, end);
return small;
}
private static void swap(int[] data, int a, int b) {
int temp = data[a];
data[a] = data[b];
data[b] = temp;
}
public static void quickSort(int[] data, int start, int end) {
if (start == end) return;
int index = partition(data, start , end);
if (index > start) {
quickSort(data, start, index - 1);
}
if (index < end) {
quickSort(data, index + 1, end);
}
}
public static void main(String args[]) {
int a[] = { 51, 46, 20, 18, 65, 97, 82, 30, 77, 50 };
quickSort(a, 0, a.length - 1);
System.out.println("排序结果:" + Arrays.toString(a));
}
}
| true |
49dcac91eac6f402fc9c21b41b73aa4b1560a665
|
Java
|
rachciachose/ccItemDumperMV-1.0-SNAPSHOT
|
/com/mongodb/event/ConnectionPoolListener.java
|
UTF-8
| 725 | 1.65625 | 2 |
[] |
no_license
|
//
// Decompiled by Procyon v0.5.30
//
package com.mongodb.event;
import com.mongodb.annotations.Beta;
import java.util.EventListener;
@Beta
public interface ConnectionPoolListener extends EventListener
{
void connectionPoolOpened(final ConnectionPoolOpenedEvent p0);
void connectionPoolClosed(final ConnectionPoolEvent p0);
void connectionCheckedOut(final ConnectionEvent p0);
void connectionCheckedIn(final ConnectionEvent p0);
void waitQueueEntered(final ConnectionPoolWaitQueueEvent p0);
void waitQueueExited(final ConnectionPoolWaitQueueEvent p0);
void connectionAdded(final ConnectionEvent p0);
void connectionRemoved(final ConnectionEvent p0);
}
| true |
1bd7afe27043bf8a8ad8678b5e7a0d29261f8c60
|
Java
|
amit2014/LeetCode-5
|
/LeetCode/781_Rabbits_In_Forest.java
|
UTF-8
| 801 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
public int numRabbits(int[] answers) {
if (answers == null || answers.length == 0) {
return 0;
}
Map<Integer, Integer> map = new HashMap<>();
int min = 0;
for (int i = 0; i < answers.length; i++) {
int cur = answers[i];
if (!map.containsKey(cur)) {
map.put(cur, 1);
} else {
int num = map.get(cur);
map.put(cur, num + 1);
}
}
for (int key : map.keySet()) {
int num = map.get(key);
int set = key + 1;
if (num % set != 0) {
min += num / set * set + set;
} else {
min += num;
}
}
return min;
}
}
| true |
4b5b59da91254d82017524225d59b54b47e4daea
|
Java
|
Sushma-M/testshared1
|
/services/TestDB_26may/src/com/testshared1/testdb_26may/Asset.java
|
UTF-8
| 9,224 | 1.796875 | 2 |
[] |
no_license
|
/*Copyright (c) 2016-2017 testing.com All Rights Reserved.
This software is the confidential and proprietary information of testing.com You shall not disclose such Confidential Information and shall use it only in accordance
with the terms of the source code license agreement you entered into with testing.com*/
package com.testshared1.testdb_26may;
/*This is a Studio Managed File. DO NOT EDIT THIS FILE. Your changes may be reverted by Studio.*/
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Asset generated by WaveMaker Studio.
*/
@Entity
@Table(name = "`asset`")
public class Asset implements Serializable {
private Integer idAsset;
private String inventoryNumber;
private String name;
private String description_;
private Boolean currentlyLoaded;
private Boolean rejection;
private String brand;
private String model;
private String seriesNumber;
private String billNumber;
private Date purchaseDate;
private String supplierName;
private Double purchasedValue;
private String observation;
private Integer userLocation;
private Integer userMode;
private Date userFecha;
private Employee employee;
private TypeAsset typeAsset;
private List<ListAssetDiscarded> listAssetDiscardeds = new ArrayList<>();
private List<AssetFile> assetFiles = new ArrayList<>();
private List<ListAssetLoaded> listAssetLoadeds = new ArrayList<>();
private List<ListAssetReintegrated> listAssetReintegrateds = new ArrayList<>();
private List<AssetPhotoFile> assetPhotoFiles = new ArrayList<>();
private List<ListAssetUnloaded> listAssetUnloadeds = new ArrayList<>();
@Id
@Column(name = "`id_asset`", nullable = false, scale = 0, precision = 10)
public Integer getIdAsset() {
return this.idAsset;
}
public void setIdAsset(Integer idAsset) {
this.idAsset = idAsset;
}
@Column(name = "`inventory_number`", nullable = false, length = 16)
public String getInventoryNumber() {
return this.inventoryNumber;
}
public void setInventoryNumber(String inventoryNumber) {
this.inventoryNumber = inventoryNumber;
}
@Column(name = "`name`", nullable = false, length = 32)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "`description?`", nullable = true, length = 64)
public String getDescription_() {
return this.description_;
}
public void setDescription_(String description_) {
this.description_ = description_;
}
@Column(name = "`currently_loaded`", nullable = false)
public Boolean isCurrentlyLoaded() {
return this.currentlyLoaded;
}
public void setCurrentlyLoaded(Boolean currentlyLoaded) {
this.currentlyLoaded = currentlyLoaded;
}
@Column(name = "`rejection`", nullable = false)
public Boolean isRejection() {
return this.rejection;
}
public void setRejection(Boolean rejection) {
this.rejection = rejection;
}
@Column(name = "`brand`", nullable = true, length = 16)
public String getBrand() {
return this.brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
@Column(name = "`model`", nullable = true, length = 16)
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
@Column(name = "`series_number`", nullable = true, length = 16)
public String getSeriesNumber() {
return this.seriesNumber;
}
public void setSeriesNumber(String seriesNumber) {
this.seriesNumber = seriesNumber;
}
@Column(name = "`bill_number`", nullable = true, length = 16)
public String getBillNumber() {
return this.billNumber;
}
public void setBillNumber(String billNumber) {
this.billNumber = billNumber;
}
@Temporal(TemporalType.DATE)
@Column(name = "`purchase_date`", nullable = true)
public Date getPurchaseDate() {
return this.purchaseDate;
}
public void setPurchaseDate(Date purchaseDate) {
this.purchaseDate = purchaseDate;
}
@Column(name = "`supplier_name`", nullable = true, length = 64)
public String getSupplierName() {
return this.supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
@Column(name = "`purchased_value`", nullable = true, scale = 2, precision = 11)
public Double getPurchasedValue() {
return this.purchasedValue;
}
public void setPurchasedValue(Double purchasedValue) {
this.purchasedValue = purchasedValue;
}
@Column(name = "`observation`", nullable = true, length = 128)
public String getObservation() {
return this.observation;
}
public void setObservation(String observation) {
this.observation = observation;
}
@Column(name = "`user_location`", nullable = false, scale = 0, precision = 10)
public Integer getUserLocation() {
return this.userLocation;
}
public void setUserLocation(Integer userLocation) {
this.userLocation = userLocation;
}
@Column(name = "`user_mode`", nullable = false, scale = 0, precision = 10)
public Integer getUserMode() {
return this.userMode;
}
public void setUserMode(Integer userMode) {
this.userMode = userMode;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "`user_fecha`", nullable = false)
public Date getUserFecha() {
return this.userFecha;
}
public void setUserFecha(Date userFecha) {
this.userFecha = userFecha;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "`fk_employee`", referencedColumnName = "`id_employee`", insertable = true, updatable = true)
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "`fk_type_asset`", referencedColumnName = "`id_type_asset`", insertable = true, updatable = true)
public TypeAsset getTypeAsset() {
return this.typeAsset;
}
public void setTypeAsset(TypeAsset typeAsset) {
this.typeAsset = typeAsset;
}
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "asset")
public List<ListAssetDiscarded> getListAssetDiscardeds() {
return this.listAssetDiscardeds;
}
public void setListAssetDiscardeds(List<ListAssetDiscarded> listAssetDiscardeds) {
this.listAssetDiscardeds = listAssetDiscardeds;
}
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "asset")
public List<AssetFile> getAssetFiles() {
return this.assetFiles;
}
public void setAssetFiles(List<AssetFile> assetFiles) {
this.assetFiles = assetFiles;
}
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "asset")
public List<ListAssetLoaded> getListAssetLoadeds() {
return this.listAssetLoadeds;
}
public void setListAssetLoadeds(List<ListAssetLoaded> listAssetLoadeds) {
this.listAssetLoadeds = listAssetLoadeds;
}
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "asset")
public List<ListAssetReintegrated> getListAssetReintegrateds() {
return this.listAssetReintegrateds;
}
public void setListAssetReintegrateds(List<ListAssetReintegrated> listAssetReintegrateds) {
this.listAssetReintegrateds = listAssetReintegrateds;
}
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "asset")
public List<AssetPhotoFile> getAssetPhotoFiles() {
return this.assetPhotoFiles;
}
public void setAssetPhotoFiles(List<AssetPhotoFile> assetPhotoFiles) {
this.assetPhotoFiles = assetPhotoFiles;
}
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "asset")
public List<ListAssetUnloaded> getListAssetUnloadeds() {
return this.listAssetUnloadeds;
}
public void setListAssetUnloadeds(List<ListAssetUnloaded> listAssetUnloadeds) {
this.listAssetUnloadeds = listAssetUnloadeds;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Asset)) return false;
final Asset asset = (Asset) o;
return Objects.equals(getIdAsset(), asset.getIdAsset());
}
@Override
public int hashCode() {
return Objects.hash(getIdAsset());
}
}
| true |
344b01e27d020372afa08fe39b653daf16e44893
|
Java
|
crisan-catalin/ITec-local-goods
|
/src/main/java/com/brotech/localgoods/controller/CartController.java
|
UTF-8
| 1,438 | 2.125 | 2 |
[] |
no_license
|
package com.brotech.localgoods.controller;
import com.brotech.localgoods.constants.Session;
import com.brotech.localgoods.constants.Views;
import com.brotech.localgoods.dto.SessionUserDto;
import com.brotech.localgoods.form.AddToCartForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/cart")
public class CartController {
@PostMapping("/remove/{cartEntryProductId}")
public String removeCartEntry(@PathVariable("cartEntryProductId") Long cartEntryProductId, HttpSession session) {
SessionUserDto sessionUserDto = (SessionUserDto) session.getAttribute(Session.USER);
if (sessionUserDto != null) {
List<AddToCartForm> sessionOrderEntries = (ArrayList<AddToCartForm>) session.getAttribute(Session.ORDER_ENTRIES);
if (sessionOrderEntries != null && !sessionOrderEntries.isEmpty()) {
sessionOrderEntries.removeIf(cartEntry -> cartEntry.getProductId() == cartEntryProductId);
session.setAttribute(Session.ORDER_ENTRIES, sessionOrderEntries);
return Views.REDIRECT + "cart";
}
}
return Views.REDIRECT;
}
}
| true |
2da13617bf8c34db6b06ed827814605417b5502e
|
Java
|
joshrizzo/ReadabilityJava
|
/step5_SeaparateAbstractions/tests/EmployeeDocumentParserTestWrapper.java
|
UTF-8
| 836 | 2.40625 | 2 |
[] |
no_license
|
package step5_SeaparateAbstractions.tests;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import common.Employee;
import common.ParseEmployeeXmlException;
import step4_RefactoredCode.EmployeeDocumentParser;
public class EmployeeDocumentParserTestWrapper extends EmployeeDocumentParser {
public int calledParseDocumentForEmployees = 0;
public int calledGetEmployeeFromXmlNode = 0;
public List<Employee> parseDocumentForEmployees(Document xmlDocument)
throws ParseEmployeeXmlException {
this.calledParseDocumentForEmployees += 1;
return super.parseDocumentForEmployees(xmlDocument);
}
public Employee buildEmployeeFromXmlNode(Node employeeNode)
throws ParseEmployeeXmlException {
this.calledGetEmployeeFromXmlNode += 1;
return super.buildEmployeeFromXmlNode(employeeNode);
}
}
| true |
32c28ca594233188ac7797fa0a8ad7979f560113
|
Java
|
rahulvdev/UniBuddy
|
/UniBuddy/app/src/main/java/com/unibuddy/finalproject/unibuddy/AlcoholPrefFrag.java
|
UTF-8
| 4,026 | 2.1875 | 2 |
[] |
no_license
|
package com.unibuddy.finalproject.unibuddy;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class AlcoholPrefFrag extends Fragment {
String[] arraySpinnerAlc;
String[] arraySpinnerOkAlc;
SharedPreferences.Editor editor;
Spinner alcoholSpinner;
Spinner alcoholOkSpinner;
public AlcoholPrefFrag() {
// Required empty public constructor
}
public static Fragment newInstance(String prefName){
AlcoholPrefFrag alcFrag=new AlcoholPrefFrag();
Bundle args=new Bundle();
args.putString("prefName",prefName);
alcFrag.setArguments(args);
return alcFrag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.arraySpinnerAlc = new String[] {
"Yes","No"
};
this.arraySpinnerOkAlc=new String[]{
"Yes","No"
};
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.fragment_alcohol_pref, container, false);
String prefName=getArguments().getString("prefName").toString();
editor = getActivity().getSharedPreferences(prefName, Context.MODE_PRIVATE).edit();
try {
alcoholSpinner = (Spinner) rootView.findViewById(R.id.spinnerAlcoholPref);
ArrayAdapter<String> adapter_a = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, arraySpinnerAlc);
adapter_a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
alcoholSpinner.setAdapter(adapter_a);
alcoholSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter, View view,
int position, long id) {
String alcPref = alcoholSpinner.getSelectedItem().toString();
editor.putString("alcPref",alcPref);
editor.commit();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
alcoholOkSpinner = (Spinner) rootView.findViewById(R.id.spinnerOkWithAlcohol);
ArrayAdapter<String> adapter_b = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, arraySpinnerOkAlc);
adapter_b.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
alcoholOkSpinner.setAdapter(adapter_b);
alcoholOkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter, View view,
int position, long id) {
String alcOkPref = alcoholOkSpinner.getSelectedItem().toString();
editor.putString("alcOkPref",alcOkPref);
editor.commit();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
TextView alcQues = (TextView) rootView.findViewById(R.id.drinkQues);
TextView alcOkQues = (TextView) rootView.findViewById(R.id.drinkOkQues);
Button nxBtn = (Button) rootView.findViewById(R.id.nxAl);
}
catch(Exception e){
e.printStackTrace();
}
return rootView;
}
}
| true |
e966d39974f8c64b6d9a19842a6dd5e5828f6069
|
Java
|
rarques/GildedRoseKata
|
/src/test/java/com/gildedrose/GildedRoseNoRegressionsTest.java
|
UTF-8
| 1,413 | 2.484375 | 2 |
[] |
no_license
|
package com.gildedrose;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class GildedRoseNoRegressionsTest {
@Test
public void noRegressions() {
Item[] items = new Item[]{
new Item("+5 Dexterity Vest", 10, 20), //
new Item("Aged Brie", 2, 0), //
new Item("Elixir of the Mongoose", 5, 7), //
new Item("Sulfuras, Hand of Ragnaros", 0, 80), //
new Item("Sulfuras, Hand of Ragnaros", -1, 80),
new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20),
new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49),
new Item("Backstage passes to a TAFKAL80ETC concert", 5, 49),
// this conjured item does not work properly yet
new Item("Conjured Mana Cake", 3, 6)};
GildedRoseBaseLine appBaseLine = new GildedRoseBaseLine(items);
GildedRose app = new GildedRose(items);
appBaseLine.updateQuality();
app.updateQuality();
for (int i = 0; i < items.length; i++) {
assertThat(app.items[i].name, is(appBaseLine.items[i].name));
assertThat(app.items[i].quality, is(appBaseLine.items[i].quality));
assertThat(app.items[i].sellIn, is(appBaseLine.items[i].sellIn));
}
}
}
| true |
c38c5612b2d5cd28a734df0728129523cd49a7ef
|
Java
|
P79N6A/zlqb
|
/nyd-cash-user/nyd-cash-user-service/src/main/java/com/nyd/user/service/BindCardService.java
|
UTF-8
| 643 | 1.515625 | 2 |
[] |
no_license
|
package com.nyd.user.service;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.nyd.user.model.UserBindCardConfirm;
import com.nyd.user.model.UserBindCardReq;
import com.tasfe.framework.support.model.ResponseData;
/**
*
* @author zhangdk
*
*/
public interface BindCardService {
ResponseData bindCard(UserBindCardReq req);
ResponseData bindCardConfirm(UserBindCardConfirm req);
ResponseData bindCardReset(List<UserBindCardConfirm> req);
JSONObject queryBindCardChannelCode(String userId);
//void userBindUpdate(UserBindCardConfirm req, ResponseData resp);
}
| true |
e1671c94d5680382d3f1295b0873623cc037cf4b
|
Java
|
ianmichaelterry/CussCalc
|
/CussCalc.java
|
UTF-8
| 12,364 | 3.34375 | 3 |
[] |
no_license
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// CussCalc.Java
///
/// Author: Ian Michael Terry
///
/// Date: 10-4-2013
///
/// Description: This program requires two inputs: an artist and a song name. Both must be in lowercase with no spaces. Given those two inputs, the program will read in song
/// lyrics from a website, azlyrics. It will seperate the strings of lyrics into words, and take count of them. If the word is a curse word, it will additionally take count
/// to a seperate counter. It then calculates the percentage of curse words in the song by dividing the two counters. The program has built in counters for each individual
/// curse word so that if the user wanted to, they could retrieve more specific and customized information about the words in the song by adding very few lines of code towards
/// the end of the program.
///
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.io.*; //imports the input/output package
import java.net.*; //imports the net package
public class CussCalc{
public static void main(String args[]){
if(args.length != 2){ //checks for any error in user input and
System.out.println("\n"+"\n"+"\n"+"This program requires two inputs: an artist name and a song name. Both must be entered in lowercase with no spaces."+"\n"+"\n");
return;
}
try{ //starts a try catch
int lineCount=0;
int wordCount=-5; //counter for the number of words, this one is set to -5
int cussCount=0; //counter for the number of curses
int assCount=0; //counters for all of the individual curse words
int assholeCount=0;
int bastardCount=0;
int bitchCount=0;
int clitCount=0;
int cockCount=0;
int cocksuckerCount=0;
int crapCount=0;
int cumCount=0;
int cuntCount=0;
int damnCount=0;
int dickCount=0;
int doucheCount=0;
int fagCount=0;
int fuckCount=0;
int fuckerCount=0;
int hellCount=0;
int hoCount=0;
int homoCount=0;
int jackassCount=0;
int motherfuckerCount=0;
int niggaCount=0;
int niggerCount=0;
int pissCount=0;
int pussyCount=0;
int retardCount=0;
int shitCount=0;
int slutCount=0;
int titCount=0;
int twatCount=0;
int whoreCount=0;
boolean inSong=false; //boolean to determine whether or not the reader is in the lyrics when it is reading the html page
String artist = args[0]; //gets input from the user, the first being the artist and the second being the song name. Both need to be lowercase with no spaces
String song = args[1];
String computerPoop="<br />"; //Strings to get unnecessary parts of the lyrics removed
String computerComma=",";
String computerPeriod=".";
String computerQuestion="?";
String computerExclamation="!";
String computerColon=":";
String computerSemicolon=";";
String nothing="";
String[] slice; //string for the words of the song once they get seperated by spaces
URL lyrics = new URL("http://www.azlyrics.com/lyrics/"+artist+"/"+song+".html"); //defines the url that the program will connect to
URLConnection uz = lyrics.openConnection(); //connects to the website
BufferedReader br = new BufferedReader(new InputStreamReader(uz.getInputStream())); //buffered reader reads the html code from the URLconnection
String line = br.readLine(); //String that is read in from the buffered reader
while (line!=null){ //while loop to trim off the unnecessary characters from the lyrics
line=line.replace(computerPoop,nothing);
line=line.replace(computerComma,nothing);
line=line.replace(computerPeriod,nothing);
line=line.replace(computerQuestion,nothing);
line=line.replace(computerExclamation,nothing);
line=line.replace(computerColon,nothing);
line=line.replace(computerSemicolon,nothing);
if(lineCount<154){
inSong=true;
}
if(line.equals("<!-- MxM banner -->")){ //turns off a boolean when the reader finishes the lyrics
inSong=false;
break;
}
if(inSong==true){ //when the reader is in the lyrics
slice=line.split(" "); //seperates the strings based around spaces
for(int i=0;i<slice.length; i++){ //for loop to move through the words
wordCount++; //adds to the word counter whenever a word is encountered
//the fallowing if statements test to see if a word is equal to a curse or any of its variations
if(slice[i].equals("ass")||slice[i].equals("asses")||slice[i].equals("Ass")||slice[i].equals("Asses")){
cussCount++;
assCount++;
}
if(slice[i].equals("asshole")||slice[i].equals("asseholes")||slice[i].equals("Asshole")||slice[i].equals("Assholes")){
cussCount++;
assholeCount++;
}
if(slice[i].equals("bastard")||slice[i].equals("bastards")||slice[i].equals("Bastard")||slice[i].equals("Bastards")){
cussCount++;
bastardCount++;
}
if(slice[i].equals("bitch")||slice[i].equals("bitches")||slice[i].equals("Bitch")||slice[i].equals("Bitches")||slice[i].equals("bitching")||slice[i].equals("Bitching")||slice[i].equals("bitched")||slice[i].equals("Bitched")){
cussCount++;
assholeCount++;
}
if(slice[i].equals("clit")||slice[i].equals("clits")||slice[i].equals("Clit")||slice[i].equals("Clits")){
cussCount++;
clitCount++;
}
if(slice[i].equals("cock")||slice[i].equals("cocks")||slice[i].equals("Cock")||slice[i].equals("Cocks")){
cussCount++;
cockCount++;
}
if(slice[i].equals("cocksucker")||slice[i].equals("cocksuckers")||slice[i].equals("Cocksucker")||slice[i].equals("Cocksuckers")||slice[i].equals("cocksucking")||slice[i].equals("Cocksucking")){
cussCount++;
cocksuckerCount++;
}
if(slice[i].equals("crap")||slice[i].equals("craps")||slice[i].equals("Crap")||slice[i].equals("Craps")||slice[i].equals("crapping")||slice[i].equals("Crapping")||slice[i].equals("crapped")||slice[i].equals("Crapped")){
cussCount++;
crapCount++;
}
if(slice[i].equals("cunt")||slice[i].equals("cunts")||slice[i].equals("Cunt")||slice[i].equals("Cunts")){
cussCount++;
cuntCount++;
}
if(slice[i].equals("cum")||slice[i].equals("cums")||slice[i].equals("Cum")||slice[i].equals("Cums")||slice[i].equals("cumming")||slice[i].equals("Cumming")){
cussCount++;
cumCount++;
}
if(slice[i].equals("damn")||slice[i].equals("damns")||slice[i].equals("Damn")||slice[i].equals("Damns")||slice[i].equals("dammit")||slice[i].equals("Dammit")){
cussCount++;
damnCount++;
}
if(slice[i].equals("dick")||slice[i].equals("dicks")||slice[i].equals("Dick")||slice[i].equals("Dicks")||slice[i].equals("dicking")||slice[i].equals("Dicking")){
cussCount++;
dickCount++;
}
if(slice[i].equals("douche")||slice[i].equals("douches")||slice[i].equals("Douche")||slice[i].equals("Douches")||slice[i].equals("douchebag")||slice[i].equals("douchebags")||slice[i].equals("Douchebag")||slice[i].equals("Douchebags")){
cussCount++;
doucheCount++;
}
if(slice[i].equals("fag")||slice[i].equals("fags")||slice[i].equals("Fag")||slice[i].equals("Fags")||slice[i].equals("faggot")||slice[i].equals("faggots")||slice[i].equals("Faggot")||slice[i].equals("Faggots")){
cussCount++;
fagCount++;
}
if(slice[i].equals("fuck")||slice[i].equals("fucks")||slice[i].equals("Fuck")||slice[i].equals("Fucks")||slice[i].equals("fucking")||slice[i].equals("Fucking")||slice[i].equals("fucked")||slice[i].equals("Fucked")){
cussCount++;
fuckCount++;
}
if(slice[i].equals("fucker")||slice[i].equals("fuckers")||slice[i].equals("Fucker")||slice[i].equals("Fuckers")){
cussCount++;
fuckerCount++;
}
if(slice[i].equals("hell")||slice[i].equals("hells")||slice[i].equals("Hell")||slice[i].equals("Hells")){
cussCount++;
hellCount++;
}
if(slice[i].equals("ho")||slice[i].equals("hos")||slice[i].equals("Ho")||slice[i].equals("Hos")||slice[i].equals("hoes")||slice[i].equals("Hoes")){
cussCount++;
hoCount++;
}
if(slice[i].equals("homo")||slice[i].equals("homos")||slice[i].equals("Homo")||slice[i].equals("Homos")){
cussCount++;
homoCount++;
}
if(slice[i].equals("jackass")||slice[i].equals("jackasses")||slice[i].equals("Jackass")||slice[i].equals("Jackasses")){
cussCount++;
jackassCount++;
}
if(slice[i].equals("piss")||slice[i].equals("pisses")||slice[i].equals("Piss")||slice[i].equals("Pisses")||slice[i].equals("pissed")||slice[i].equals("Pissed")||slice[i].equals("pissing")||slice[i].equals("Pissing")){
cussCount++;
pissCount++;
}
if(slice[i].equals("pussy")||slice[i].equals("pussies")||slice[i].equals("Pussy")||slice[i].equals("Pussies")){
cussCount++;
pussyCount++;
}
if(slice[i].equals("motherfucker")||slice[i].equals("motherfuckers")||slice[i].equals("Motherfucker")||slice[i].equals("Motherfuckers")||slice[i].equals("mothafucka")||slice[i].equals("muthafukas")|
slice[i].equals("Mothafuka")||slice[i].equals("mothafucka")||slice[i].equals("Mothafucka")||slice[i].equals("Mothafuckas")||slice[i].equals("Mothafucka")){
cussCount++;
motherfuckerCount++;
}
if(slice[i].equals("nigga")||slice[i].equals("niggas")||slice[i].equals("Nigga")||slice[i].equals("Niggas")||slice[i].equals("Niggaz")||slice[i].equals("niggaz")){
cussCount++;
niggaCount++;
}
if(slice[i].equals("nigger")||slice[i].equals("niggers")||slice[i].equals("Nigger")||slice[i].equals("Niggers")){
cussCount++;
niggerCount++;
}
if(slice[i].equals("retard")||slice[i].equals("retards")||slice[i].equals("Retards")||slice[i].equals("Retard")||slice[i].equals("Retarded")||slice[i].equals("retarded")){
cussCount++;
retardCount++;
}
if(slice[i].equals("shit")||slice[i].equals("shits")||slice[i].equals("Shit")||slice[i].equals("Shits")||slice[i].equals("shitting")||slice[i].equals("Shitting")||slice[i].equals("shitted")||slice[i].equals("Shitted")||slice[i].equals("Shitter")||slice[i].equals("shitter")){
cussCount++;
shitCount++;
}
if(slice[i].equals("slut")||slice[i].equals("sluts")||slice[i].equals("Slut")||slice[i].equals("Sluts")){
cussCount++;
slutCount++;
}
if(slice[i].equals("tit")||slice[i].equals("tits")||slice[i].equals("Tit")||slice[i].equals("Tits")||slice[i].equals("titties")||slice[i].equals("Titties")||slice[i].equals("titty")||slice[i].equals("Titty")){
cussCount++;
titCount++;
}
if(slice[i].equals("twat")||slice[i].equals("twats")||slice[i].equals("Twat")||slice[i].equals("Twats")){
cussCount++;
twatCount++;
}
if(slice[i].equals("whore")||slice[i].equals("whores")||slice[i].equals("Whore")||slice[i].equals("Whores")||slice[i].equals("whored")||slice[i].equals("Whored")||slice[i].equals("whoring")){
cussCount++;
whoreCount++;
}
}
}
lineCount++;
line = br.readLine(); //moves the buffered reader to the next line
}
double cursePercent=((double)cussCount / (double)wordCount) ; //calculates the number of curse words
System.out.println("\n"+"\n"+"\n"+"This song has "+wordCount +" words"); //Prints out the word count, curse count, and percentage of curses
System.out.println("\n"+"This song has "+cussCount +" curses");
System.out.println("\n"+"This song is "+ cursePercent*100 +"% curses."+"\n"+"\n");
br.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
| true |
bdec64afdf23af32f1971078b7e6f9be226c4f4c
|
Java
|
miguellysanchez/Chase
|
/app/src/main/java/com/voyager/chase/game/skill/SkillsPool.java
|
UTF-8
| 8,737 | 2.015625 | 2 |
[] |
no_license
|
package com.voyager.chase.game.skill;
import android.content.Context;
import com.voyager.chase.R;
import com.voyager.chase.game.entity.player.Player;
import com.voyager.chase.game.skill.common.EndTurnSkill;
import com.voyager.chase.game.skill.common.MoveSkill;
import com.voyager.chase.game.skill.common.SprintSkill;
import com.voyager.chase.game.skill.sentry.SecurityCameraSkill;
import com.voyager.chase.game.skill.sentry.AttackSkill;
import com.voyager.chase.game.skill.sentry.FragGrenadeSkill;
import com.voyager.chase.game.skill.sentry.MotionSensorSkill;
import com.voyager.chase.game.skill.sentry.RecoverSkill;
import com.voyager.chase.game.skill.sentry.LuxGeneratorSkill;
import com.voyager.chase.game.skill.sentry.SearchDroneSkill;
import com.voyager.chase.game.skill.sentry.ShockRocketSkill;
import com.voyager.chase.game.skill.sentry.StunTrapSkill;
import com.voyager.chase.game.skill.sentry.SurveillanceBugSkill;
import com.voyager.chase.game.skill.spy.BaitSkill;
import com.voyager.chase.game.skill.spy.DeployBarrierSkill;
import com.voyager.chase.game.skill.spy.DropMineSkill;
import com.voyager.chase.game.skill.spy.EMPBlastSkill;
import com.voyager.chase.game.skill.spy.EmergencyHealSkill;
import com.voyager.chase.game.skill.spy.IlluminationBeaconSkill;
import com.voyager.chase.game.skill.spy.PlantDecoySkill;
import com.voyager.chase.game.skill.spy.SabotageSkill;
import com.voyager.chase.game.skill.spy.ShrapnelBlastSkill;
import com.voyager.chase.game.skill.spy.SmokeScreenSkill;
import com.voyager.chase.game.skill.spy.SnipeSkill;
import com.voyager.chase.game.skill.spy.ToxicCloudSkill;
/**
* Created by miguellysanchez on 7/14/16.
*/
public class SkillsPool {
public static final String YOUR_SKILLS_SELECTED = "key_string_arraylist_your_skills_selected";
public static final String MOVE_SKILL_NAME = "Move";
public static final String SABOTAGE_SKILL_NAME = "Sabotage";
public static final String ATTACK_SKILL_NAME = "Attack";
public static final String END_TURN_SKILL_NAME = "End Turn";
public static Skill getSkillForName(Context context, String skillName, Player player) {
String[] spyRoleSkillNames = context.getResources().getStringArray(R.array.chase_array_skill_select_name_spy);
String[] sentryRoleSkillNames = context.getResources().getStringArray(R.array.chase_array_skill_select_name_sentry);
Skill returnedSkill = null;
int skillCooldown = 0;
String description = "";
if (MOVE_SKILL_NAME.equals(skillName)) {
returnedSkill = new MoveSkill();
description = "Move from current position to a tile to the left, right, above, or below";
} else if (END_TURN_SKILL_NAME.equals(skillName)) {
returnedSkill = new EndTurnSkill();
description = "Reduces AP to 0. Ends the current turn.";
} else if (SABOTAGE_SKILL_NAME.equals(skillName)) {
returnedSkill = new SabotageSkill();
description = "Destroys all constructs/objective in any adjacent tile. Destroy all objectives to win!";
} else if (ATTACK_SKILL_NAME.equals(skillName)) {
returnedSkill = new AttackSkill();
description = "Damage other player and destroy all constructs (including yours) in any tile to the left, right, above or below the current position";
} else if (Player.SPY_ROLE.equals(player.getRole())) {
int[] spyCooldownArray = context.getResources().getIntArray(R.array.chase_array_skill_select_cooldown_spy);
String[] spyDescriptionArray = context.getResources().getStringArray(R.array.chase_array_skill_select_description_spy);
int skillIndex = -1;
if (spyRoleSkillNames[0].equals(skillName)) {
returnedSkill = new EMPBlastSkill();
skillIndex = 0;
} else if (spyRoleSkillNames[1].equals(skillName)) {
returnedSkill = new DropMineSkill();
skillIndex = 1;
} else if (spyRoleSkillNames[2].equals(skillName)) {
returnedSkill = new DropMineSkill();
skillIndex = 2;
} else if (spyRoleSkillNames[3].equals(skillName)) {
returnedSkill = new DropMineSkill();
skillIndex = 3;
} else if (spyRoleSkillNames[4].equals(skillName)) {
returnedSkill = new PlantDecoySkill();
skillIndex = 4;
} else if (spyRoleSkillNames[5].equals(skillName)) {
returnedSkill = new EmergencyHealSkill();
skillIndex = 5;
} else if (spyRoleSkillNames[6].equals(skillName)) {
returnedSkill = new DeployBarrierSkill();
skillIndex = 6;
} else if (spyRoleSkillNames[7].equals(skillName)) {
returnedSkill = new IlluminationBeaconSkill();
skillIndex = 7;
} else if (spyRoleSkillNames[8].equals(skillName)) {
returnedSkill = new SnipeSkill();
skillIndex = 8;
} else if (spyRoleSkillNames[9].equals(skillName)) {
returnedSkill = new ShrapnelBlastSkill();
skillIndex = 9;
} else if (spyRoleSkillNames[10].equals(skillName)) {
returnedSkill = new ToxicCloudSkill();
skillIndex = 10;
} else if (spyRoleSkillNames[11].equals(skillName)) {
returnedSkill = new BaitSkill();
skillIndex = 11;
} else if (spyRoleSkillNames[12].equals(skillName)) {
returnedSkill = new SprintSkill();
skillIndex = 12;
} else if (spyRoleSkillNames[13].equals(skillName)) {
returnedSkill = new SurveillanceBugSkill();
skillIndex = 13;
} else if (spyRoleSkillNames[14].equals(skillName)) {
returnedSkill = new SmokeScreenSkill();
skillIndex = 14;
}
if (skillIndex >= 0) {
skillCooldown = spyCooldownArray[skillIndex];
description = spyDescriptionArray[skillIndex];
}
} else if (Player.SENTRY_ROLE.equals(player.getRole())) {
int[] sentryCooldownArray = context.getResources().getIntArray(R.array.chase_array_skill_select_cooldown_sentry);
String[] sentryDescriptionArray = context.getResources().getStringArray(R.array.chase_array_skill_select_description_sentry);
int skillIndex = -1;
if (sentryRoleSkillNames[0].equals(skillName)) {
returnedSkill = new SecurityCameraSkill();
skillIndex = 0;
} else if (sentryRoleSkillNames[1].equals(skillName)) {
returnedSkill = new RecoverSkill();
skillIndex = 1;
} else if (sentryRoleSkillNames[2].equals(skillName)) {
returnedSkill = new StunTrapSkill();
skillIndex = 2;
} else if (sentryRoleSkillNames[3].equals(skillName)) {
returnedSkill = new MotionSensorSkill();
skillIndex = 3;
} else if (sentryRoleSkillNames[4].equals(skillName)) {
returnedSkill = new LuxGeneratorSkill();
skillIndex = 4;
} else if (sentryRoleSkillNames[5].equals(skillName)) {
returnedSkill = new FragGrenadeSkill();
skillIndex = 5;
} else if (sentryRoleSkillNames[6].equals(skillName)) {
returnedSkill = new SurveillanceBugSkill();
skillIndex = 6;
} else if (sentryRoleSkillNames[7].equals(skillName)) {
returnedSkill = new ShockRocketSkill();
skillIndex = 7;
} else if (sentryRoleSkillNames[8].equals(skillName)) {
returnedSkill = new SearchDroneSkill();
skillIndex = 8;
} else if (sentryRoleSkillNames[9].equals(skillName)) {
returnedSkill = new SprintSkill();
skillIndex = 9;
}
if (skillIndex >= 0) {
skillCooldown = sentryCooldownArray[skillIndex];
description = sentryDescriptionArray[skillIndex];
}
} else {
throw new IllegalStateException("Cannot have player with no role");
}
if (returnedSkill != null) { // assign skill name and the corresponding owner of that skill
returnedSkill.setOwner(player);
returnedSkill.setSkillName(skillName);
returnedSkill.setSkillCooldown(skillCooldown);
returnedSkill.setDescription(description);
}
return returnedSkill;
}
}
| true |
200ff50418790766e956f527f049936764e4c154
|
Java
|
celioeduardo/appcc-neo4j
|
/src/main/java/appcc/domain/Etapa.java
|
UTF-8
| 1,818 | 2.125 | 2 |
[] |
no_license
|
package appcc.domain;
import java.util.List;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
@JsonIdentityInfo(generator=JSOGGenerator.class)
@NodeEntity
public class Etapa {
@GraphId Long id;
private String nome;
private String etapaId;
private String fluxoId;
private String fluxoNome;
private Integer origens;
@Relationship(type = "PROXIMA", direction = Relationship.OUTGOING)
Etapa proxima;
@Relationship(type = "PROXIMA", direction = Relationship.INCOMING)
Etapa anterior;
@Relationship(type = "RECEBE", direction = Relationship.OUTGOING)
List<Subproduto> subprodutosEntrada;
@Relationship(type = "RECEBE", direction = Relationship.OUTGOING)
List<Material> materiais;
@Relationship(type = "PRODUZ", direction = Relationship.OUTGOING)
List<Subproduto> subprodutosSaida;
@Relationship(type = "PRODUZ", direction = Relationship.OUTGOING)
List<ProdutoFinal> produtosFinais;
public Long getId() {
return id;
}
public String getNome() {
return nome;
}
public String getEtapaId() {
return etapaId;
}
public String getFluxoId() {
return fluxoId;
}
public String getFluxoNome() {
return fluxoNome;
}
public Integer getOrigens() {
return origens;
}
public Etapa getProxima() {
return proxima;
}
public List<Subproduto> getSubprodutosEntrada() {
return subprodutosEntrada;
}
public List<Material> getMateriais() {
return materiais;
}
public List<Subproduto> getSubprodutosSaida() {
return subprodutosSaida;
}
public List<ProdutoFinal> getProdutosFinais() {
return produtosFinais;
}
public Etapa getAnterior() {
return anterior;
}
}
| true |
8afe1530a7ec9f7132a6abe799dada8deab42816
|
Java
|
tohnaman/tohnaman-java-sample
|
/spring-batch-sample/src/main/java/jp/tokyo/higashimurayama/tohnaman/batch/jobs/csv2db/MasterDeleteTasklet.java
|
UTF-8
| 797 | 2.046875 | 2 |
[
"MIT"
] |
permissive
|
package jp.tokyo.higashimurayama.tohnaman.batch.jobs.csv2db;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import jp.tokyo.higashimurayama.tohnaman.batch.mybatis.mapper.MstAddressMapper;
/**
* マスタ削除用Tasklet<br>
*/
public class MasterDeleteTasklet implements Tasklet {
@Autowired
private MstAddressMapper mstAddressMapper;
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
this.mstAddressMapper.deleteByExample(null);
return RepeatStatus.FINISHED;
}
}
| true |
62c33500e1ca86aca280d329c7cdd9b10526ebe4
|
Java
|
santhoshraj2960/Evite-Android-application
|
/src/com/vulcan/invite/ActorsAdapter.java
|
UTF-8
| 2,120 | 2.578125 | 3 |
[] |
no_license
|
package com.vulcan.invite;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ActorsAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> ArrayListActors;
int Resource;
Context context;
LayoutInflater vi;
public ActorsAdapter(Context context, int resource,
ArrayList<Actors> objects) {
super(context, resource, objects);
ArrayListActors = objects;
Resource = resource;
this.context = context;
vi=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null)
{
convertView = vi.inflate(Resource, null);
holder = new ViewHolder();
holder.month = (TextView) convertView.findViewById(R.id.textView1);
holder.year = (TextView) convertView.findViewById(R.id.textView2);
holder.date = (TextView) convertView.findViewById(R.id.textView3);
holder.event = (TextView) convertView.findViewById(R.id.textView4);
holder.time = (TextView) convertView.findViewById(R.id.textView5);
holder.organiser = (TextView) convertView.findViewById(R.id.textView6);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.month.setText(ArrayListActors.get(position).getMonth());
holder.year.setText(ArrayListActors.get(position).getYear());
holder.date.setText(ArrayListActors.get(position).getDate());
holder.event.setText(ArrayListActors.get(position).getEvent());
holder.time.setText(ArrayListActors.get(position).getTime());
holder.organiser.setText( ArrayListActors.get(position).getOrganiser());
return convertView;
}
static class ViewHolder {
public TextView month;
public TextView year;
public TextView date;
public TextView event;
public TextView time;
public TextView organiser;
}
}
| true |
d47bb38d625f758230474f1f6e6f7398793daf25
|
Java
|
chris-james-git/sfg-recipes
|
/src/test/java/guru/springframework/recipes/repositories/UnitOfMeasureRepositoryTestIT.java
|
UTF-8
| 1,194 | 2.109375 | 2 |
[] |
no_license
|
package guru.springframework.recipes.repositories;
import guru.springframework.recipes.domain.UnitOfMeasure;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.junit.Assert.*;
// Run in the Spring context...
@RunWith(SpringRunner.class)
// ... configured only for JPA
@DataJpaTest
public class UnitOfMeasureRepositoryTestIT {
@Autowired
UnitOfMeasureRepository unitOfMeasureRepository;
@Before
public void setUp() throws Exception {
}
@Test
public void findByDescriptionTeaspoon() {
UnitOfMeasure unitOfMeasure = unitOfMeasureRepository.findByDescription("teaspoon").orElseThrow();
assertEquals("teaspoon", unitOfMeasure.getDescription());
}
@Test
public void findByDescriptionCup() {
UnitOfMeasure unitOfMeasure = unitOfMeasureRepository.findByDescription("cup").orElseThrow();
assertEquals("cup", unitOfMeasure.getDescription());
}
}
| true |
32dc9ce958f9bfb230355dd26cb1e0f4e34153d7
|
Java
|
Patricia008/MyIoCContainer
|
/src/iocContainer/impl/HomemadeContextFromFile.java
|
UTF-8
| 2,371 | 2.484375 | 2 |
[] |
no_license
|
package iocContainer.impl;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import iocContainer.api.IocContainer;
public class HomemadeContextFromFile {
private IocContainer homemadeContainer;
public HomemadeContextFromFile(String fileName) {
this.homemadeContainer = new HomemadeContainer();
try {
readFromXml(fileName);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
return;
}
}
private void readFromXml(String fileName) throws ParserConfigurationException, SAXException, IOException {
File inputFile = new File(fileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList beanList = doc.getElementsByTagName("bean");
for (int i = 0; i < beanList.getLength(); i++) {
Node bean = beanList.item(i);
if (bean.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) bean;
Class clazz;
try {
clazz = Class.forName(eElement.getAttribute("class"));
NodeList propertyList = eElement.getElementsByTagName("property");
Element property = (Element) propertyList.item(0);
Class argClass = Class.forName(property.getAttribute("value"));
Object instance;
try {
instance = clazz.getConstructor(Object.class).newInstance(argClass.newInstance());
this.homemadeContainer.register(clazz, instance);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
public IocContainer getIocContainer() {
return this.homemadeContainer;
}
}
| true |
2cbed3ed4c40139931792f1922aae39e4f2dc9ea
|
Java
|
cckmit/epbpim
|
/epbpim_budget/src/com/ryxx/util/io/FileUtil.java
|
UTF-8
| 3,207 | 3 | 3 |
[] |
no_license
|
/**
* Copyright (c) coship 2007
* @author: ives
* @date: 2007-8-28 ����02:51:13
* @version: 1.0
*/
package com.ryxx.util.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* @author ives
*
*/
public class FileUtil
{
private static final int BUFFER_SIZE = 16 * 1024;
/**
* 文件复制/剪切
* <功能详细描述>
*
* @param src 源文件
* @param dst 目标文件
* @param delSrc 是否将源文件删除 false 相当于文件复制,true 相当于文件剪切
* @author zhangxiaohui
* @throws Exception 异常
*/
public static void copy(File src, File dst, boolean delSrc)
throws Exception
{
BufferedInputStream in = null;
BufferedOutputStream out = null;
try
{
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int c;
while (0 < (c = in.read(buffer)))
{
out.write(buffer, 0, c);
}
}
finally
{
try
{
out.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (delSrc)
{
delete(src);
}
}
// public static void copy(File src, File dst) {
// try {
// InputStream in = null;
// OutputStream out = null;
// try {
// in = new BufferedInputStream(new FileInputStream(src),
// BUFFER_SIZE);
// out = new BufferedOutputStream(new FileOutputStream(dst),
// BUFFER_SIZE);
// byte[] buffer = new byte[BUFFER_SIZE];
// while (in.read(buffer) > 0) {
// out.write(buffer);
// }
// } finally {
// if (null != in) {
// in.close();
// }
// if (null != out) {
// out.close();
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
public static void delete(File file)
{
try
{
if (file.exists())
{
System.out.println(file.getAbsolutePath());
file.delete();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void delete(String filename)
{
File file = new File(filename);
delete(file);
}
}
| true |
01b8cfadc7920c7353a0688abfbcd3a1a2462ca3
|
Java
|
zxf799076293/firstTest
|
/app/src/main/java/com/linhuiba/business/activity/GroupBookingPaidSuccessActivity.java
|
UTF-8
| 8,801 | 1.585938 | 2 |
[] |
no_license
|
package com.linhuiba.business.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baselib.app.activity.BaseActivity;
import com.baselib.app.util.MessageUtils;
import com.linhuiba.business.R;
import com.linhuiba.business.adapter.FieldinfoOtherResourcesAdapter;
import com.linhuiba.business.adapter.FieldinfoRecommendResourcesAdapter;
import com.linhuiba.business.basemvp.BaseMvpActivity;
import com.linhuiba.business.connector.FieldApi;
import com.linhuiba.business.connector.MyAsyncHttpClient;
import com.linhuiba.business.fragment.HomeFragment;
import com.linhuiba.business.model.GroupBookingListModel;
import com.linhuiba.business.model.ResourceSearchItemModel;
import com.linhuiba.business.network.LinhuiAsyncHttpResponseHandler;
import com.linhuiba.business.network.Response;
import com.linhuiba.business.util.TitleBarUtils;
import com.linhuiba.business.view.MyGridview;
import com.linhuiba.linhuipublic.config.LoginManager;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* Created by Administrator on 2017/9/29.
*/
public class GroupBookingPaidSuccessActivity extends BaseMvpActivity {
@InjectView(R.id.groupbooking_success_gridview)
MyGridview mGroupBookingSuccessGV;
@InjectView(R.id.other_group_list_ll)
LinearLayout mOtherGroupListLL;
private ArrayList<ResourceSearchItemModel> mFieldInfoOtherDataList = new ArrayList<>();
private FieldinfoOtherResourcesAdapter fieldinfoRecommendResources_adapter;
private String mGroupId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groupbooking_paid_success);
ButterKnife.inject(this);
TitleBarUtils.showBackImg(this,true);
TitleBarUtils.shownextButton(this,getResources().getString(R.string.confirmorder_back_homepage),
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent maintabintent = new Intent(GroupBookingPaidSuccessActivity.this, MainTabActivity.class);
maintabintent.putExtra("new_tmpintent", "goto_homepage");
startActivity(maintabintent);
}
});
initData();
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onPageStart(getResources().getString(R.string.group_paid_success_activity_name_str));
MobclickAgent.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPageEnd(getResources().getString(R.string.group_paid_success_activity_name_str));
MobclickAgent.onPause(this);
}
@OnClick ({
R.id.group_paid_success_orderlist_btn,
R.id.group_paid_success_invite_btn
})
public void OnClick(View view) {
switch (view.getId()) {
case R.id.group_paid_success_orderlist_btn:
Intent orderpayintent = new Intent(GroupBookingPaidSuccessActivity.this, GroupBookingMainActivity.class);
Bundle bundle_ordertype1 = new Bundle();
bundle_ordertype1.putInt("order_type", 2);
orderpayintent.putExtras(bundle_ordertype1);
startActivity(orderpayintent);
break;
case R.id.group_paid_success_invite_btn:
Intent inviteintent = new Intent(GroupBookingPaidSuccessActivity.this,InviteActivity.class);
startActivity(inviteintent);
finish();
break;
default:
break;
}
}
private void initData() {
Intent intent = getIntent();
if (intent.getExtras() != null &&
intent.getExtras().get("group_id") != null) {
mGroupId = intent.getExtras().get("group_id").toString();
}
if (LoginManager.isLogin()) {
//其他火爆拼团
if (mGroupId != null && mGroupId.length() > 0) {
FieldApi.getGroupBookingList(MyAsyncHttpClient.MyAsyncHttpClient(), mOtherResHandler, 1, LoginManager.getInstance().getTrackcityid(),6,Integer.parseInt(mGroupId));
}
}
}
private LinhuiAsyncHttpResponseHandler mOtherResHandler = new LinhuiAsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, okhttp3.internal.http2.Header[] headers, Response response, Object data) {
hideProgressDialog();
if (data != null) {
JSONObject jsonObject = JSONObject.parseObject(data.toString());
if (jsonObject != null && jsonObject.get("data") != null) {
ArrayList<GroupBookingListModel> mHomeRecentActivityList = (ArrayList<GroupBookingListModel>) JSONArray.parseArray(jsonObject.get("data").toString(),GroupBookingListModel.class);
if( mHomeRecentActivityList == null || mHomeRecentActivityList.isEmpty()) {
return;
}
mOtherGroupListLL.setVisibility(View.VISIBLE);
for (int i = 0; i < mHomeRecentActivityList.size(); i++) {
ResourceSearchItemModel resourceSearchItemModel = new ResourceSearchItemModel();
resourceSearchItemModel.setName(mHomeRecentActivityList.get(i).getSelling_resource().getPhysical_resource().getName());
resourceSearchItemModel.setActivity_start_date(mHomeRecentActivityList.get(i).getActivity_start());
resourceSearchItemModel.setDeadline(mHomeRecentActivityList.get(i).getActivity_end());
if (mHomeRecentActivityList.get(i).getSelling_resource().getPhysical_resource().getPhysical_resource_first_img() != null &&
mHomeRecentActivityList.get(i).getSelling_resource().getPhysical_resource().getPhysical_resource_first_img().get("pic_url") != null) {
resourceSearchItemModel.setPic_url(mHomeRecentActivityList.get(i).getSelling_resource().getPhysical_resource().getPhysical_resource_first_img().get("pic_url").toString());
}
if (mHomeRecentActivityList.get(i).getSelling_resource().getFirst_selling_resource_price() != null &&
mHomeRecentActivityList.get(i).getSelling_resource().getFirst_selling_resource_price().get("price") != null &&
mHomeRecentActivityList.get(i).getSelling_resource().getFirst_selling_resource_price().get("price").toString().length() > 0) {
resourceSearchItemModel.setPrice(mHomeRecentActivityList.get(i).getSelling_resource().getFirst_selling_resource_price().get("price").toString());
}
resourceSearchItemModel.setNumber_of_group_purchase_now(mHomeRecentActivityList.get(i).getNumber_of_group_purchase_now());
resourceSearchItemModel.setResource_id(mHomeRecentActivityList.get(i).getId());
mFieldInfoOtherDataList.add(resourceSearchItemModel);
}
fieldinfoRecommendResources_adapter = new FieldinfoOtherResourcesAdapter(GroupBookingPaidSuccessActivity.this,GroupBookingPaidSuccessActivity.this,mFieldInfoOtherDataList,1);
mGroupBookingSuccessGV.setAdapter(fieldinfoRecommendResources_adapter);
mGroupBookingSuccessGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent fieldinfo = new Intent(GroupBookingPaidSuccessActivity.this, GroupBookingInfoActivity.class);
fieldinfo.putExtra("ResId", String.valueOf(mFieldInfoOtherDataList.get(position).getResource_id()));
startActivity(fieldinfo);
finish();
}
});
}
}
}
@Override
public void onFailure(boolean superresult, int statusCode, okhttp3.internal.http2.Header[] headers, byte[] responseBody, Throwable error) {
}
};
}
| true |
1d02f98304134235729825ba55c7e47c69320569
|
Java
|
primary10/bullCard
|
/clientAndServer/circle/webcommon/java/g/web/common/shiro/local/filter/LocalRegistFilter.java
|
UTF-8
| 917 | 2.203125 | 2 |
[] |
no_license
|
package g.web.common.shiro.local.filter;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class LocalRegistFilter extends PathMatchingFilter{
private String registUrl;
public String getRegistUrl() {
return registUrl;
}
public void setRegistUrl(String registUrl) {
this.registUrl = registUrl;
}
@Override
protected boolean pathsMatch(String path, ServletRequest request) {
String requestURI = this.getPathWithinApplication(request);
return this.pathsMatch("/share*",requestURI);
}
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
WebUtils.issueRedirect(request, response, getRegistUrl());
return false;
}
}
| true |
3013b30893a5572a4d782f97d0d046cb94bbd396
|
Java
|
Voqus/comas
|
/src/comas/database/Database.java
|
UTF-8
| 1,853 | 2.984375 | 3 |
[] |
no_license
|
package comas.database;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
* Database class.
*/
public class Database
{
private static final String dbPath = "jdbc:ucanaccess://" + new File("src/comas/res/Database.accdb").getAbsolutePath();
protected Connection dbConnection;
protected ResultSet dataResults;
protected PreparedStatement dbStatement;
/**
* Connects with the database, returns true/false for success/fail.
*
* @return
*/
protected boolean connect()
{
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
dbConnection = DriverManager.getConnection(dbPath);
return true;
} // try
catch (ClassNotFoundException | SQLException e)
{
// Terminate program if database not found.
JOptionPane.showMessageDialog(null, e.getMessage(), "DATABASE ERROR", JOptionPane.ERROR_MESSAGE);
System.exit(0);
} // catch
return false;
} // connect
/**
* Closes the database
*/
protected void close()
{
try
{
if (dbConnection != null)
{
dbConnection.close();
} // if
if (dbStatement != null)
{
dbStatement.close();
} // if
if (dataResults != null)
{
dataResults.close();
} // if
} // try
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e.getMessage(), "DATABASE ERROR", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
} // catch
} // close
}
| true |
925bdaca075d41908f95348f6a4f58cae6168dbb
|
Java
|
cauvray/odeva_petit_projet
|
/test/JeuTest.java
|
UTF-8
| 3,647 | 2.65625 | 3 |
[] |
no_license
|
package test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import exception.DebitImpossibleException;
import exception.JeuFermeException;
import jeu.Banque;
import jeu.De;
import jeu.Jeu;
import jeu.Joueur;
public class JeuTest {
//test joueur qui gagne
@Test
public void testJouerLeJoueurFait7() throws JeuFermeException, DebitImpossibleException {
Banque b = mock(Banque.class);
Joueur j = mock(Joueur.class);
De d1 = mock(De.class);
De d2 = mock(De.class);
Jeu jeu = new Jeu(b);
when(b.est_solvable()).thenReturn(true);
when(d1.lancer()).thenReturn(4);
when(d2.lancer()).thenReturn(3);
when(j.mise()).thenReturn(100);
jeu.jouer(j, d1, d2);
verify(b).crediter(100);
verify(j).debiter(100);
verify(b).debiter(200);
verify(j).crediter(200);
}
//test joueur qui perd
@Test
public void testJouerLeJoueurNeFaitPas7() throws JeuFermeException, DebitImpossibleException {
Banque b = mock(Banque.class);
Joueur j = mock(Joueur.class);
De d1 = mock(De.class);
De d2 = mock(De.class);
Jeu jeu = new Jeu(b);
when(b.est_solvable()).thenReturn(true);
when(d1.lancer()).thenReturn(3);
when(d2.lancer()).thenReturn(3);
when(j.mise()).thenReturn(100);
jeu.jouer(j, d1, d2);
verify(b).crediter(100);
verify(j).debiter(100);
}
// test jeu ferme
@Test(expected = JeuFermeException.class)
public void testBanqueNonSolvable() throws JeuFermeException, DebitImpossibleException {
Banque b = mock(Banque.class);
Joueur j = mock(Joueur.class);
De d1 = mock(De.class);
De d2 = mock(De.class);
Jeu jeu = new Jeu(b);
when(b.est_solvable()).thenReturn(false);
jeu.jouer(j, d1, d2);
}
//test joueur non solvable
@Test
public void testJoueurDebitImpossible() throws JeuFermeException, DebitImpossibleException {
Banque b = mock(Banque.class);
Joueur j = mock(Joueur.class);
De d1 = mock(De.class);
De d2 = mock(De.class);
Jeu jeu = new Jeu(b);
when(b.est_solvable()).thenReturn(true);
doThrow(new DebitImpossibleException()).when(j).debiter(anyInt());
jeu.jouer(j, d1, d2);
}
//test joueur qui gagne avec banque
@Test
public void testBanqueIntegrationJouerLeJoueurFait7() throws JeuFermeException, DebitImpossibleException{
Joueur j = mock(Joueur.class);
De d1 = mock(De.class);
De d2 = mock(De.class);
Banque b = new Banque(1000, 100);
Jeu jeu = new Jeu(b);
when(d1.lancer()).thenReturn(4);
when(d2.lancer()).thenReturn(3);
when(j.mise()).thenReturn(100);
jeu.jouer(j, d1, d2);
verify(j).debiter(100);
verify(j).crediter(200);
assertEquals(b.getFond(),900);
}
//test joueur qui perd avec banque
@Test
public void testBanqueIntegrationJouerLeJoueurNeFaitPas7() throws JeuFermeException, DebitImpossibleException{
Joueur j = mock(Joueur.class);
De d1 = mock(De.class);
De d2 = mock(De.class);
Banque b = new Banque(1000, 100);
Jeu jeu = new Jeu(b);
when(d1.lancer()).thenReturn(3);
when(d2.lancer()).thenReturn(3);
when(j.mise()).thenReturn(100);
jeu.jouer(j, d1, d2);
verify(j).debiter(100);
assertEquals(b.getFond(),1100);
}
//test jeu ferme avec banque
@Test(expected = JeuFermeException.class)
public void testBanqueIntegrationBanqueNonSolvable() throws JeuFermeException, DebitImpossibleException{
Joueur j = mock(Joueur.class);
De d1 = mock(De.class);
De d2 = mock(De.class);
Banque b = new Banque(0, 100);
Jeu jeu = new Jeu(b);
when(d1.lancer()).thenReturn(4);
when(d2.lancer()).thenReturn(3);
when(j.mise()).thenReturn(100);
jeu.jouer(j, d1, d2);
}
}
| true |
e45785cf96cfda17ed3a4e7b286c89f48d412c27
|
Java
|
dnd2/CQZTDMS
|
/src/com/infodms/dms/bean/ActivityDealerBean.java
|
UTF-8
| 912 | 1.875 | 2 |
[] |
no_license
|
package com.infodms.dms.bean;
import com.infodms.dms.po.TtAsActivityPO;
public class ActivityDealerBean extends TtAsActivityPO {
private Integer dealerSum;
private Integer areaSum;
private Long orgId;
private String orgCode;
private String orgName;
public Long getOrgId() {
return orgId;
}
public void setOrgId(Long orgId) {
this.orgId = orgId;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public Integer getDealerSum() {
return dealerSum;
}
public void setDealerSum(Integer dealerSum) {
this.dealerSum = dealerSum;
}
public Integer getAreaSum() {
return areaSum;
}
public void setAreaSum(Integer areaSum) {
this.areaSum = areaSum;
}
}
| true |
796b63125a62ad5e4dd7fc41fc7d2326dc5936e1
|
Java
|
fuhongliang/Android-Supplier
|
/app/src/main/java/cn/ifhu/supplier/adapter/DiscountPackageAdapter.java
|
UTF-8
| 3,629 | 2.078125 | 2 |
[] |
no_license
|
package cn.ifhu.supplier.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ifhu.supplier.R;
import cn.ifhu.supplier.model.bean.DiscountPackageBean;
/**
* @author fuhongliang
*/
public class DiscountPackageAdapter extends BaseAdapter {
List<DiscountPackageBean> discountPackageBeans;
Context mContext;
OnClickItem onClickItem;
public DiscountPackageAdapter(List<DiscountPackageBean> discountPackageBeans, Context mContext) {
this.discountPackageBeans = discountPackageBeans;
this.mContext = mContext;
}
public void setBeanList(List<DiscountPackageBean> discountPackageBeans) {
this.discountPackageBeans = discountPackageBeans;
notifyDataSetChanged();
}
public void setOnClickItem(OnClickItem onClickItem) {
this.onClickItem = onClickItem;
}
@Override
public int getCount() {
return discountPackageBeans == null ? 0 : discountPackageBeans.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
ViewHolder viewHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.item_package, null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvName.setText(discountPackageBeans.get(position).getBl_name());
viewHolder.tvPrice.setText("总优惠价格:¥" + discountPackageBeans.get(position).getPrice());
if (discountPackageBeans.get(position).getBl_state() == 1) {
viewHolder.ivState.setBackgroundResource(R.drawable.yhq_bnt_xszk_tc);
viewHolder.ivStateRight.setVisibility(View.GONE);
viewHolder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.colorPrimary));
} else {
viewHolder.ivState.setBackgroundResource(R.drawable.yhq_bnt_xszk_tc01);
viewHolder.ivStateRight.setVisibility(View.VISIBLE);
viewHolder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.second_grey));
}
if (onClickItem != null) {
viewHolder.llDelete.setOnClickListener(v -> onClickItem.deleteDiscountPackage(position));
viewHolder.llEdit.setOnClickListener(v -> onClickItem.editDiscountPackage(position));
}
return convertView;
}
static class ViewHolder {
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.tv_price)
TextView tvPrice;
@BindView(R.id.ll_edit)
LinearLayout llEdit;
@BindView(R.id.ll_delete)
LinearLayout llDelete;
@BindView(R.id.iv_state)
ImageView ivState;
@BindView(R.id.iv_state_right)
ImageView ivStateRight;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
public interface OnClickItem {
void editDiscountPackage(int position);
void deleteDiscountPackage(int position);
}
}
| true |
b7a9360f20cfa8e635fa2b914c0eb66554e81d12
|
Java
|
TPFinal2018project/TheatreTicketBookingSystem
|
/src/main/java/TheatreTicketBookingSystem/repositories/AdminRepository.java
|
UTF-8
| 274 | 1.539063 | 2 |
[] |
no_license
|
package TheatreTicketBookingSystem.repositories;
import TheatreTicketBookingSystem.domain.Admin;
import org.springframework.data.repository.CrudRepository;
/**
* Created by Emma on 10/12/2018.
*/
public interface AdminRepository extends CrudRepository<Admin, Long> {
}
| true |
0a53b5d023056e22e73b23e03d4441afe0278848
|
Java
|
JiriFurda/IJA-proj
|
/src/ija/proj/block/BlockXor.java
|
UTF-8
| 784 | 2.96875 | 3 |
[] |
no_license
|
/**
* Backend representation of "Xor" block.
* @brief Package for Block type "Xor" from group "Logic"
* @file BlockXor.java
* @author Jiri Furda (xfurda00)
*/
package ija.proj.block;
/**
* @brief The BlockXor class is Block realising exclusive logical disjuction of two bool values.
*/
public class BlockXor extends BlockLogic
{
@Override
void executeSpecific() /// @brief executeSpecific realises exclusive logical disjuction of two bool values from input Ports and saves it to output Port
{
boolean resultB = BlockLogic.double2bool(getInputPort(0).getValue("bool")) ^ double2bool(getInputPort(1).getValue("bool"));
double resultD = BlockLogic.bool2double(resultB);
this.getOutputPort(0).setValue("bool", resultD);
}
}
| true |
eea8e875c9b2aa085bb868af63fb20fbbf2b4c53
|
Java
|
daydayfive/path-optimization-plat
|
/transfer-master/transfer-api/src/main/java/com/cqu/pojo/Feature.java
|
UTF-8
| 279 | 1.601563 | 2 |
[] |
no_license
|
package com.cqu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Feature {
private Long milvusId;
private ArrayList<Float> features;
}
| true |
bf2fd45df49666a7adc6a235ca86bb88bfc05bce
|
Java
|
mathysaru/realestate
|
/com/google/android/gms/common/data/DataBuffer.java
|
UTF-8
| 854 | 2.21875 | 2 |
[] |
no_license
|
package com.google.android.gms.common.data;
import java.util.Iterator;
public abstract class DataBuffer<T>
implements Iterable<T>
{
protected final d jf;
protected DataBuffer(d paramd)
{
this.jf = paramd;
if (this.jf != null) {
this.jf.b(this);
}
}
public void close()
{
this.jf.close();
}
public int describeContents()
{
return 0;
}
public abstract T get(int paramInt);
public int getCount()
{
return this.jf.getCount();
}
public boolean isClosed()
{
return this.jf.isClosed();
}
public Iterator<T> iterator()
{
return new a(this);
}
}
/* Location: C:\Users\shivane\Decompilation\dex2jar-2.0\classes-dex2jar.jar!\com\google\android\gms\common\data\DataBuffer.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true |
a934dbd85d62a9d3a85525c0abacc13b7ec189b2
|
Java
|
CarlosHFRibeiro/Project-Rectify
|
/src/dev/senzalla/rectify/frame/AnalyzeTruckTableFrame.java
|
UTF-8
| 8,101 | 2.078125 | 2 |
[] |
no_license
|
package dev.senzalla.rectify.frame;
import dev.senzalla.rectify.enuns.Lab;
import dev.senzalla.rectify.frame.filter.AnalyzeFilterFrame;
import dev.senzalla.rectify.treatments.Access;
import dev.senzalla.rectify.treatments.AnalyzeTruckTreatment;
import dev.senzalla.rectify.treatments.ItemTreatment;
import dev.senzalla.theme.TreatmentTheme;
/**
* @author Bomsalvez Freitas
* @e-mail [email protected]
* @github github.com/Bomsalvez
*/
public class AnalyzeTruckTableFrame extends javax.swing.JInternalFrame {
/**
* Creates new form FrmLabCarTbl
*/
public AnalyzeTruckTableFrame() {
initComponents();
initPanel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
pnlanalyzeTruck = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
btnAdd = new javax.swing.JButton();
btnFilter = new javax.swing.JButton();
roll = new javax.swing.JScrollPane();
tbl = new javax.swing.JTable();
setClosable(true);
setMaximumSize(new java.awt.Dimension(1000, 680));
setMinimumSize(new java.awt.Dimension(1000, 680));
setPreferredSize(new java.awt.Dimension(1000, 680));
pnlanalyzeTruck.setMaximumSize(new java.awt.Dimension(998, 658));
pnlanalyzeTruck.setMinimumSize(new java.awt.Dimension(998, 658));
pnlanalyzeTruck.setPreferredSize(new java.awt.Dimension(998, 658));
lblTitle.setFont(new java.awt.Font("Dialog", 1, 30)); // NOI18N
lblTitle.setText("Analise Caminhão");
btnAdd.setFont(new java.awt.Font("Dialog", 1, 10)); // NOI18N
btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/static/img/add.png"))); // NOI18N
btnAdd.setPreferredSize(new java.awt.Dimension(46, 40));
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
btnFilter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/static/img/filter.png"))); // NOI18N
btnFilter.setPreferredSize(new java.awt.Dimension(46, 40));
btnFilter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFilterActionPerformed(evt);
}
});
roll.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
roll.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
rollMouseWheelMoved(evt);
}
});
tbl.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
tbl.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Cod.", "Produto", "Acidez", "Saponidade", "Impureza %", "Densidade", "Data", "Hora"
}
) {
boolean[] canEdit = new boolean [] {
false, true, false, false, false, false, true, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tbl.setRowHeight(20);
tbl.setShowGrid(true);
roll.setViewportView(tbl);
if (tbl.getColumnModel().getColumnCount() > 0) {
tbl.getColumnModel().getColumn(1).setPreferredWidth(200);
}
javax.swing.GroupLayout pnlanalyzeTruckLayout = new javax.swing.GroupLayout(pnlanalyzeTruck);
pnlanalyzeTruck.setLayout(pnlanalyzeTruckLayout);
pnlanalyzeTruckLayout.setHorizontalGroup(
pnlanalyzeTruckLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlanalyzeTruckLayout.createSequentialGroup()
.addContainerGap(370, Short.MAX_VALUE)
.addComponent(lblTitle)
.addGap(260, 260, 260)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12))
.addGroup(pnlanalyzeTruckLayout.createSequentialGroup()
.addComponent(roll)
.addContainerGap())
);
pnlanalyzeTruckLayout.setVerticalGroup(
pnlanalyzeTruckLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlanalyzeTruckLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlanalyzeTruckLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblTitle))
.addGap(18, 18, 18)
.addComponent(roll, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlanalyzeTruck, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlanalyzeTruck, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
Access.goToInternalFrame(this, new AnalyzeTruckFrame());
}//GEN-LAST:event_btnAddActionPerformed
private void btnFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFilterActionPerformed
Access.goToFrame(new AnalyzeFilterFrame(tbl, Lab.ANALYZETRUCK));
}//GEN-LAST:event_btnFilterActionPerformed
private void rollMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_rollMouseWheelMoved
ItemTreatment.speedRoll(roll);
}//GEN-LAST:event_rollMouseWheelMoved
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnFilter;
private javax.swing.JLabel lblTitle;
private javax.swing.JPanel pnlanalyzeTruck;
private javax.swing.JScrollPane roll;
private javax.swing.JTable tbl;
// End of variables declaration//GEN-END:variables
private void initPanel() {
TreatmentTheme.initTheme(pnlanalyzeTruck);
TreatmentTheme.initTableTheme(tbl);
AnalyzeTruckTreatment.initTable(tbl);
TreatmentTheme.iconDefine(btnAdd, "/static/img/add_white.png");
TreatmentTheme.iconDefine(btnFilter, "/static/img/filter_white.png");
}
}
| true |
484062b848a66eb48998fbbfab50b3144e3b17d2
|
Java
|
shezan7/SPL-1
|
/packageOfTeenGuti/Stage3_1.java
|
UTF-8
| 12,789 | 2.671875 | 3 |
[] |
no_license
|
package packageOfTeenGuti;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Line;
public class Stage3_1 extends Pane {
double[][] board = new double[9][3];
Ellipse[] guti = new Ellipse[6];
public int selectedGuti, selectedPosition, previousPosiotion;
public int selectedGuti2, selectedPosition2, previousPosiotion2;
public int secondClick;
public boolean firstTeamClick1=false, firstTeamClick2=false,
secondTeamClick1=true, secondTeamClick2=false, second=false;
public int[][] path = new int[9][8];
public boolean play=true;
public int initial=2;
double ballX;
double ballY;
public Stage3_1() {
// TODO Auto-generated method stub
makeGraph();
Circle[] circle = new Circle[9];
Line[][] line = new Line[8][2];
int x=100;
int index=0;
int y=100;
for(int j=0; j<3; j++)
{
board[index][0]=x;
board[index][1]=y;
x=100;
for(int k=0; k<3; k++)
{
circle[index] = new Circle();
circle[index].setCenterX(x);
circle[index].setCenterY(y);
circle[index].setRadius(30);
//circle[index].setStrokeWidth(10);
circle[index].setFill(Color.TRANSPARENT);
getChildren().addAll(circle[index]);
board[index][0]=x;
board[index][1]=y;
if(index<=2) board[index][2]=1;
if(index>=6) board[index][2]=2;
x = x + 350;
index++;
}
y = y + 250;
}
line[0][0] = new Line();
line[0][0].setStartX(100);
line[0][0].setStartY(100);
line[0][0].setEndX(450);
line[0][0].setEndY(100);
line[0][0].setStrokeWidth(15);
line[0][1] = new Line();
line[0][1].setStartX(450);
line[0][1].setStartY(100);
line[0][1].setEndX(800);
line[0][1].setEndY(100);
line[0][1].setStrokeWidth(15);
line[1][0] = new Line();
line[1][0].setStartX(100);
line[1][0].setStartY(350);
line[1][0].setEndX(450);
line[1][0].setEndY(350);
line[1][0].setStrokeWidth(15);
line[1][1] = new Line();
line[1][1].setStartX(450);
line[1][1].setStartY(350);
line[1][1].setEndX(800);
line[1][1].setEndY(350);
line[1][1].setStrokeWidth(15);
line[2][0] = new Line();
line[2][0].setStartX(100);
line[2][0].setStartY(600);
line[2][0].setEndX(450);
line[2][0].setEndY(600);
line[2][0].setStrokeWidth(15);
line[2][1] = new Line();
line[2][1].setStartX(450);
line[2][1].setStartY(600);
line[2][1].setEndX(800);
line[2][1].setEndY(600);
line[2][1].setStrokeWidth(15);
line[3][0] = new Line();
line[3][0].setStartX(100);
line[3][0].setStartY(100);
line[3][0].setEndX(100);
line[3][0].setEndY(350);
line[3][0].setStrokeWidth(15);
line[3][1] = new Line();
line[3][1].setStartX(100);
line[3][1].setStartY(350);
line[3][1].setEndX(100);
line[3][1].setEndY(600);
line[3][1].setStrokeWidth(15);
line[4][0] = new Line();
line[4][0].setStartX(450);
line[4][0].setStartY(100);
line[4][0].setEndX(450);
line[4][0].setEndY(350);
line[4][0].setStrokeWidth(15);
line[4][1] = new Line();
line[4][1].setStartX(450);
line[4][1].setStartY(350);
line[4][1].setEndX(450);
line[4][1].setEndY(600);
line[4][1].setStrokeWidth(15);
line[5][0] = new Line();
line[5][0].setStartX(800);
line[5][0].setStartY(100);
line[5][0].setEndX(800);
line[5][0].setEndY(350);
line[5][0].setStrokeWidth(15);
line[5][1] = new Line();
line[5][1].setStartX(800);
line[5][1].setStartY(350);
line[5][1].setEndX(800);
line[5][1].setEndY(600);
line[5][1].setStrokeWidth(15);
line[6][0] = new Line();
line[6][0].setStartX(100);
line[6][0].setStartY(100);
line[6][0].setEndX(450);
line[6][0].setEndY(350);
line[6][0].setStrokeWidth(15);
line[6][1] = new Line();
line[6][1].setStartX(450);
line[6][1].setStartY(350);
line[6][1].setEndX(800);
line[6][1].setEndY(600);
line[6][1].setStrokeWidth(15);
line[7][0] = new Line();
line[7][0].setStartX(800);
line[7][0].setStartY(100);
line[7][0].setEndX(450);
line[7][0].setEndY(350);
line[7][0].setStrokeWidth(15);
line[7][1] = new Line();
line[7][1].setStartX(450);
line[7][1].setStartY(350);
line[7][1].setEndX(100);
line[7][1].setEndY(600);
line[7][1].setStrokeWidth(15);
addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
if(play) {
for(int c=0;c<9;c++)
{
if(c<=2&&guti[c].contains(e.getX(), e.getY())&&firstTeamClick1)
{
if(firstTeamClick2)
{
guti[selectedGuti].setStroke(Color.BLACK);
}
for(int i=0;i<9;i++)
{
if(guti[c].getCenterX()==circle[i].getCenterX()
&&guti[c].getCenterY()==circle[i].getCenterY())
{
previousPosiotion=i;
break;
}
}
selectedGuti=c;
guti[c].setStroke(Color.RED);
firstTeamClick2=true;
System.out.println("1: selectedGuti "+selectedGuti+
" previousPosiotion "+previousPosiotion);
break;
}
if(circle[c].contains(e.getX(), e.getY())&&firstTeamClick2)
{
selectedPosition=c;
//second=true;
System.out.println("1st player selectedPosition "+selectedPosition);
for(int i=0;i<8;i++)
{
if(path[previousPosiotion][i]>=0
&&path[previousPosiotion][i]==selectedPosition
&&board[path[previousPosiotion][i]][2]==0)
{
guti[selectedGuti].getFill();
guti[selectedGuti].setCenterX(board[path[previousPosiotion][i]][0]);
guti[selectedGuti].setCenterY(board[path[previousPosiotion][i]][1]);
board[selectedPosition][2]=1;
board[previousPosiotion][2]=0;
guti[selectedGuti].setStroke(Color.BLACK);
firstTeamClick2=false;
firstTeamClick1=false;
secondTeamClick1=true;
winCheckGreenGuti();
break;
}
}
break;
}
if(c<6 &&c>=3&&guti[c].contains(e.getX(), e.getY())&&secondTeamClick1)
{
if(secondTeamClick2)
{
guti[selectedGuti2].setStroke(Color.BLACK);
}
for(int i=0;i<9;i++)
{
if(guti[c].getCenterX()==circle[i].getCenterX()
&&guti[c].getCenterY()==circle[i].getCenterY())
{
previousPosiotion2=i;
break;
}
}
selectedGuti2=c;
guti[c].setStroke(Color.RED);
secondTeamClick2=true;
System.out.println("2: selectedGuti2 "+selectedGuti2+
" previousPosiotion2 "+previousPosiotion2);
break;
}
if(circle[c].contains(e.getX(), e.getY())&&secondTeamClick2)
{
selectedPosition2=c;
//second=true;
System.out.println("2nd player selectedPosition2 "+selectedPosition2);
for(int i=0;i<8;i++)
{
if(path[previousPosiotion2][i]>=0
&&path[previousPosiotion2][i]==selectedPosition2
&&board[path[previousPosiotion2][i]][2]==0)
{
guti[selectedGuti2].getFill();
guti[selectedGuti2].setCenterX(board[path[previousPosiotion2][i]][0]);
guti[selectedGuti2].setCenterY(board[path[previousPosiotion2][i]][1]);
board[selectedPosition2][2]=2;
board[previousPosiotion2][2]=0;
guti[selectedGuti2].setStroke(Color.BLACK);
secondTeamClick1=false;
secondTeamClick2=false;
firstTeamClick1=true;
winCheckBlueGuti();
break;
}
}
break;
}
}
}
});
getChildren().addAll(line[0][0], line[0][1], line[1][0], line[1][1], line[2][0], line[2][1], line[3][0], line[3][1], line[4][0], line[4][1], line[5][0], line[5][1], line[6][0], line[6][1], line[7][0], line[7][1]);
drawGuti();
}
public void winCheckGreenGuti()
{
int flag=0;
if(board[6][2]==1 && board[7][2]==1 && board[8][2]==1)
{
flag=1;
}
else if(board[3][2]==1 && board[4][2]==1 && board[5][2]==1)
{
flag=1;
}
else if(board[0][2]==1 && board[3][2]==1 && board[6][2]==1)
{
flag=1;
}
else if(board[1][2]==1 && board[4][2]==1 && board[7][2]==1)
{
flag=1;
}
else if(board[2][2]==1 && board[5][2]==1 && board[8][2]==1)
{
flag=1;
}
else if(board[0][2]==1 && board[4][2]==1 && board[8][2]==1)
{
flag=1;
}
else if(board[2][2]==1 && board[4][2]==1 && board[6][2]==1)
{
flag=1;
}
else flag=0;
if(flag==1)
{
System.out.println("Green Win!!");
play=false;
Stage3_1_W_2 pane = new Stage3_1_W_2();
Scene scene = new Scene(pane);
MainStage.getStage().setScene(scene);
MainStage.getStage().setTitle("game");
}
else ;
}
public void winCheckBlueGuti()
{
int flag=0;
if(board[0][2]==2 && board[1][2]==2 && board[2][2]==2)
{
flag=1;
}
else if(board[3][2]==2 && board[4][2]==2 && board[5][2]==2)
{
flag=1;
}
else if(board[0][2]==2 && board[3][2]==2 && board[6][2]==2)
{
flag=1;
}
else if(board[1][2]==2 && board[4][2]==2 && board[7][2]==2)
{
flag=1;
}
else if(board[2][2]==2 && board[5][2]==2 && board[8][2]==2)
{
flag=1;
}
else if(board[0][2]==2 && board[4][2]==2 && board[8][2]==2)
{
flag=1;
}
else if(board[2][2]==2 && board[4][2]==2 && board[6][2]==2)
{
flag=1;
}
else flag=0;
if(flag==1)
{
System.out.println("Blue Win!!");
play=false;
Stage3_1_W_1 pane = new Stage3_1_W_1();
Scene scene = new Scene(pane);
MainStage.getStage().setScene(scene);
MainStage.getStage().setTitle("game");
}
else ;
}
public void drawGuti()
{
int count=0;
for(int k=0;k<9;k++)
{
if(board[k][2]!=0)
{
guti[count]=new Ellipse();
guti[count].setCenterX(board[k][0]);
guti[count].setCenterY(board[k][1]);
guti[count].setRadiusX(30);
guti[count].setRadiusY(30);
guti[count].setStrokeWidth(3);
guti[count].setStroke(Color.BLACK);
if(board[k][2]==1)
{
guti[count].setFill(Color.GREEN);
}
else
guti[count].setFill(Color.BLUE);
getChildren().addAll(guti[count]);
count++;
}
}
}
public void makeGraph()
{
path[0][0]=-1;
path[0][1]=-1;
path[0][2]=-1;
path[0][3]=-1;
path[0][4]=1;
path[0][5]=4;
path[0][6]=3;
path[0][7]=-1;
path[1][0]=0;
path[1][1]=-1;
path[1][2]=-1;
path[1][3]=-1;
path[1][4]=2;
path[1][5]=-1;
path[1][6]=4;
path[1][7]=-1;
path[2][0]=1;
path[2][1]=-1;
path[2][2]=-1;
path[2][3]=-1;
path[2][4]=-1;
path[2][5]=-1;
path[2][6]=5;
path[2][7]=4;
path[3][0]=-1;
path[3][1]=-1;
path[3][2]=0;
path[3][3]=-1;
path[3][4]=4;
path[3][5]=-1;
path[3][6]=6;
path[3][7]=-1;
path[4][0]=3;
path[4][1]=0;
path[4][2]=1;
path[4][3]=2;
path[4][4]=5;
path[4][5]=8;
path[4][6]=7;
path[4][7]=6;
path[5][0]=4;
path[5][1]=-1;
path[5][2]=2;
path[5][3]=-1;
path[5][4]=-1;
path[5][5]=-1;
path[5][6]=8;
path[5][7]=-1;
path[6][0]=-1;
path[6][1]=-1;
path[6][2]=3;
path[6][3]=4;
path[6][4]=7;
path[6][5]=-1;
path[6][6]=-1;
path[6][7]=-1;
path[7][0]=6;
path[7][1]=-1;
path[7][2]=4;
path[7][3]=-1;
path[7][4]=8;
path[7][5]=-1;
path[7][6]=-1;
path[7][7]=-1;
path[8][0]=7;
path[8][1]=4;
path[8][2]=5;
path[8][3]=-1;
path[8][4]=-1;
path[8][5]=-1;
path[8][6]=-1;
path[8][7]=-1;
}
}
| true |
677b18f9244b69078343562f9f731b16472362ce
|
Java
|
vaishalikhandekar/timesheet
|
/components/project/source/com/company/timesheet/project/pojo/ProjectDetail.java
|
UTF-8
| 3,103 | 1.914063 | 2 |
[] |
no_license
|
/**
*
*/
package com.company.timesheet.project.pojo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.company.timesheet.profile.person.pojo.PersonDetail;
import com.company.timesheet.project.projectpersonlink.pojo.ProjectPersonLinkDetail;
/**
* @author vaish
*
*/
public class ProjectDetail {
private String projectName;
private Long projectID;
private Long personID;
private String description;
private String recordStatus;
private int versionNo;
private Date startDate;
private Date endDate;
private String comments;
private String acronym;
List<String> errorMessageList = new ArrayList<String>();
private String updateAction = "update";
private ProjectPersonLinkDetail projectPersonLinkDetail;
private PersonDetail personDetail;
public String getUpdateAction() {
return updateAction;
}
public void setUpdateAction(String updateAction) {
this.updateAction = updateAction;
}
public ProjectPersonLinkDetail getProjectPersonLinkDetail() {
return projectPersonLinkDetail;
}
public void setProjectPersonLinkDetail(
ProjectPersonLinkDetail projectPersonLinkDetail) {
this.projectPersonLinkDetail = projectPersonLinkDetail;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public Long getProjectID() {
return projectID;
}
public void setProjectID(Long projectID) {
this.projectID = projectID;
}
public Long getPersonID() {
return personID;
}
public void setPersonID(Long personID) {
this.personID = personID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(String recordStatus) {
this.recordStatus = recordStatus;
}
public int getVersionNo() {
return versionNo;
}
public void setVersionNo(int versionNo) {
this.versionNo = versionNo;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getAcronym() {
return acronym;
}
public void setAcronym(String acronym) {
this.acronym = acronym;
}
public List<String> getErrorMessageList() {
return errorMessageList;
}
public void setErrorMessageList(List<String> errorMessageList) {
this.errorMessageList = errorMessageList;
}
public PersonDetail getPersonDetail() {
return personDetail;
}
public void setPersonDetail(PersonDetail personDetail) {
this.personDetail = personDetail;
}
}
| true |
5b35fddd0618d0666a5d2b7707bfbb48631d6911
|
Java
|
franciscovillegas/1982-COMMONLIBS
|
/1982-COMMONLIB-FRONTCONTR/src/portal/com/eje/portal/organica/Organica.java
|
ISO-8859-1
| 27,324 | 1.9375 | 2 |
[] |
no_license
|
package portal.com.eje.portal.organica;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.StringEscapeUtils;
import cl.ejedigital.consultor.ConsultaData;
import cl.ejedigital.consultor.ConsultaDataMode;
import cl.ejedigital.tool.strings.ArrayFactory;
import cl.ejedigital.tool.strings.SqlBuilder;
import cl.ejedigital.tool.validar.Validar;
import cl.ejedigital.web.datos.ConsultaTool;
import portal.com.eje.portal.factory.Util;
import portal.com.eje.portal.organica.ctr.CtrGOrganica;
import portal.com.eje.portal.organica.ifaces.ICtrGOrganica;
import portal.com.eje.portal.trabajador.enums.EjeGesTrabajadorField;
import portal.com.eje.portal.vo.ClaseConversor;
public class Organica implements IOrganica {
protected EOrganicaTipo tipo;
public Organica() {
this.tipo = EOrganicaTipo.porUnidades;
}
public Organica getInstance() {
return Util.getInstance(Organica.class);
}
public ConsultaData getUnidadesDescendientes(String unidad) {
return getUnidadesDescendientes(null, unidad, false);
}
/**
* revisado por Pancho 31-10-2018
* */
public ConsultaData getUnidadesDescendientes(Connection connPortal, String unidad, boolean incluyeNoVigentes) {
if(unidad == null) {
throw new NullPointerException();
}
ConsultaData data = null;
try {
SqlBuilder sql = new SqlBuilder();
sql.appendLine(" SELECT distinct u.unid_id, u.unid_desc,d.unidad ");
sql.appendLine(" FROM dbo.GetDescendientes('"+StringEscapeUtils.escapeSql(Validar.getInstance().validarDato(unidad,"A900"))+"') as d");
sql.appendLine(" inner join eje_ges_unidades u on d.unidad = u.unid_id ");
if(!incluyeNoVigentes) {
sql.appendLine(" where u.vigente = 'S' ");
}
if(connPortal != null) {
data = ConsultaTool.getInstance().getData(connPortal, sql);
}
else {
data = ConsultaTool.getInstance().getData("portal", sql);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
return data;
}
public ConsultaData getUnidadesAscendientes(String unidad) {
return getUnidadesAscendientes(null, unidad, false);
}
public ConsultaData getUnidadesAscendientes(Connection connPortal, String unidad, boolean incluyeNoVigentes) {
if(unidad == null) {
throw new NullPointerException();
}
ConsultaData data = null;
try {
SqlBuilder sql = new SqlBuilder();
sql.appendLine(" SELECT distinct u.*,j.nodo_nivel");
sql.appendLine(" FROM dbo.GetAscendentes('"+StringEscapeUtils.escapeSql(Validar.getInstance().validarDato(unidad,"A900"))+"') as d");
sql.appendLine(" inner join eje_ges_unidades u on d.unidad = u.unid_id ");
sql.appendLine(" inner join eje_ges_jerarquia j on j.nodo_id = u.unid_id ");
if(!incluyeNoVigentes) {
sql.appendLine(" where u.vigente = 'S' ");
}
sql.appendLine(" ORDER BY j.nodo_nivel ");
if(connPortal != null) {
data = ConsultaTool.getInstance().getData(connPortal, sql);
}
else {
data = ConsultaTool.getInstance().getData("portal", sql);
}
//List<String> ascendientes = ConsultaTool.getInstance().getList(data, ArrayList.class, "unidad");
//data = getUnidad(connPortal, ascendientes);
} catch (SQLException e1) {
e1.printStackTrace();
}
/*INVIERTE SELECCIN, COSA DE TENER PRIMERO LAS UNIDADES SUPERIORES Y AL FINAL LA UNIDAD EN SI.*/
//
//
// for(int i = (listaInvertida.size()) -1 ; i>= 0; i--) {
// dataRetorno.add(listaInvertida.get(i));
// }
return data;
}
public ConsultaData getTrabajadoresInUnidad(String unidad) {
return getTrabajadores(null, unidad, null, false);
}
public ConsultaData getTrabajadoresInUnidad(String unidad, boolean omiteJefe) {
return getTrabajadores(null, unidad, null, omiteJefe);
}
public ConsultaData getTrabajadoresInUnidad(String strUnidad, List<EjeGesTrabajadorField> fields) {
ConsultaData data = null;
StringBuilder strSQL = new StringBuilder();
strSQL.append("select distinct dummy=null");
if(fields.contains(EjeGesTrabajadorField.rut)) {
strSQL.append(", id_persona=t.rut, t.rut");
}
if(fields.contains(EjeGesTrabajadorField.digito_ver)) {
strSQL.append(", t.digito_ver");
}
if(fields.contains(EjeGesTrabajadorField.rut) && fields.contains(EjeGesTrabajadorField.digito_ver)) {
strSQL.append(", nif=cast(rut as varchar) + '-' + digito_ver");
}
if(fields.contains(EjeGesTrabajadorField.nombre)) {
strSQL.append(", nombre=rtrim(ltrim(t.nombre))");
}
if(fields.contains(EjeGesTrabajadorField.nombres)) {
strSQL.append(", nombres=rtrim(ltrim(t.nombres))");
}
if(fields.contains(EjeGesTrabajadorField.ape_paterno)) {
strSQL.append(", ape_paterno=rtrim(ltrim(t.ape_paterno))");
}
if(fields.contains(EjeGesTrabajadorField.ape_materno)) {
strSQL.append(", ape_materno=rtrim(ltrim(t.ape_materno))");
}
if(fields.contains(EjeGesTrabajadorField.cargo)) {
strSQL.append(", id_cargo=t.cargo, cargo=rtrim(ltrim(c.descrip))");
}
if(fields.contains(EjeGesTrabajadorField.fecha_ingreso)) {
strSQL.append(", t.fecha_ingreso");
}
if(fields.contains(EjeGesTrabajadorField.unidad) || fields.contains(EjeGesTrabajadorField.unid_id)) {
strSQL.append(", id_unidad=u.unid_id, unidad=u.unid_desc, es_encargado=convert(smallint,isnull(ue.estado,0))");
}
if(fields.contains(EjeGesTrabajadorField.wp_cod_empresa) || fields.contains(EjeGesTrabajadorField.empresa)) {
strSQL.append(", id_empresa=t.empresa, empresa=e.descrip");
}
if(fields.contains(EjeGesTrabajadorField.ccosto) ) {
strSQL.append(", id_centrocosto=t.ccosto, centrocosto=cc.descrip");
}
if(fields.contains(EjeGesTrabajadorField.forma_pago) ) {
strSQL.append(", t.forma_pago, t.banco, t.cta_cte");
}
for(EjeGesTrabajadorField c: fields) {
if(strSQL.toString().indexOf(c.name()) == -1) {
strSQL.append(", t."+c.name());
}
}
strSQL.append(" \n");
strSQL.append("from eje_ges_trabajador t \n");
if(fields.contains(EjeGesTrabajadorField.unidad) || fields.contains(EjeGesTrabajadorField.unid_id)) {
strSQL.append("left join eje_ges_jerarquia j on t.unidad=j.nodo_id \n");
strSQL.append("left join eje_ges_unidades u on t.unidad=u.unid_id \n");
strSQL.append("left join eje_ges_unidad_encargado ue on ue.unid_id = t.unidad and ue.rut_encargado = t.rut and ue.estado = 1 \n");
}
if(fields.contains(EjeGesTrabajadorField.cargo)) {
strSQL.append("left join eje_ges_cargos c on t.cargo=c.cargo and t.wp_cod_empresa=c.empresa \n");
}
if(fields.contains(EjeGesTrabajadorField.wp_cod_empresa) || fields.contains(EjeGesTrabajadorField.empresa)) {
strSQL.append("left join eje_ges_empresa e on t.empresa = e.empresa \n");
}
if(fields.contains(EjeGesTrabajadorField.ccosto) ) {
strSQL.append("left join eje_ges_centro_costo cc on t.ccosto = cc.centro_costo and cc.vigente = 's' and cc.wp_cod_empresa = t.wp_cod_empresa and cc.wp_cod_planta = t.wp_cod_planta \n");
}
strSQL.append("where t.unidad='").append(strUnidad).append("' \n");
strSQL.append("order by rtrim(ltrim(t.nombre))");
try {
data = ConsultaTool.getInstance().getData("portal", strSQL.toString());
}
catch (SQLException e) {
e.printStackTrace();
}
return data;
}
public ConsultaData getTrabajadoresDependientes(String unidad, boolean omiteEstaUnidad) {
ConsultaData data = null;
try {
if(!omiteEstaUnidad) {
String sql ="select t.rut,unid_id=t.unidad from eje_ges_trabajador t inner join dbo.getdescendientes(?) u on t.unidad = u.unidad ";
Object[] params = {unidad};
data = ConsultaTool.getInstance().getData("portal", sql, params);
}
else {
String sql ="select t.rut,unid_id=t.unidad from eje_ges_trabajador t inner join dbo.getdescendientes(?) u on t.unidad = u.unidad and u.unidad <> ? ";
Object[] params = {unidad, unidad};
data = ConsultaTool.getInstance().getData("portal", sql, params);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Integer> ruts = ConsultaTool.getInstance().getList(data, ArrayList.class, "rut", Integer.class);
ConsultaData dataTrabajadores = getTrabajadores(ruts, null, null, false);
return dataTrabajadores;
}
@Override
public ConsultaData getTrabajadoresDependientes(int rut) {
ConsultaData dataUnidad = getUnidadFromRut(rut);
boolean esJefe = isJefe(rut);
String unidad =ConsultaTool.getInstance().getFirstValue(dataUnidad, "unid_id", String.class);
ConsultaData data = null;
if(esJefe) {
data = getTrabajadoresDependientes(unidad, false);
}
return data;
}
@Override
public ConsultaData getTrabajadoresDependientes(String unidad) {
return getTrabajadoresDependientes(unidad, false);
}
public ConsultaData getJefesDependientes(String unidad, boolean omiteEstaUnidad) {
ConsultaData dataTrabajadores = null;
if( unidad != null ) {
ConsultaData dataUnidad = getUnidad(unidad);
if(dataUnidad != null && dataUnidad.next()) {
ConsultaData data = getUnidadesDescendientes(unidad);
while( data != null && data.next()) {
boolean clausulaMismaUnidad = true;
if( unidad.equals( data.getString("unidad") ) && omiteEstaUnidad ) {
clausulaMismaUnidad = false;
}
if( clausulaMismaUnidad ) {
if(dataTrabajadores==null) {
dataTrabajadores = getJefeUnidad(data.getString("unidad") );
}
else {
dataTrabajadores.addAll( getJefeUnidad( data.getString("unidad") ) );
}
}
}
}
else {
throw new UnidadNotFoundException("El cdigo de unidad no es vlido:"+unidad);
}
}
return dataTrabajadores;
}
/*
*
* */
public ConsultaData getTrabajadoresReporteadores(String unidad) {
List<String> columnas = new ArrayList<String>();
columnas.add("rut");
columnas.add("nombre");
columnas.add("nombres");
columnas.add("cargo");
columnas.add("fecha_ingreso");
columnas.add("empresa");
ConsultaData reportes = new ConsultaData(columnas);
reportes.addAll(getTrabajadoresInUnidad( unidad , true ));
ConsultaData data = getUnidadesHijas(unidad);
while(data != null && data.next()) {
ConsultaData dataJefe = getJefeUnidad(data.getString("unidad"));
if(dataJefe == null || dataJefe.size() == 0) {
reportes.addAll(getTrabajadoresReporteadores(data.getString("unidad")));
}
else {
reportes.addAll(dataJefe);
}
}
return reportes;
}
public ConsultaData getTrabajadoresReporteadores(int rut) {
ConsultaData data = getUnidadFromRut(rut);
while(data != null && data.next()) {
String unidad = data.getString("unid_id");
ConsultaData dataJefatura = getJefeUnidad(unidad);
if( dataJefatura != null && dataJefatura.next() ) {
if(rut == dataJefatura.getInt("rut")) {
return getTrabajadoresReporteadores(unidad);
}
}
}
return null;
}
public ConsultaData getUnidadesHijas(String unidad) {
return getUnidadesHijas(unidad, false);
}
@Override
public ConsultaData getUnidadesHijas(String unidad, boolean incluyeNoVigentes) {
StringBuilder strSQL = new StringBuilder();
strSQL.append("select unidad=j.nodo_id, u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto, \n")
.append("dotacion_real=t.cantidad, \n")
.append("tiene_encargado=(case when coalesce(e.unid_id,'')<>'' then 1 else 0 end) \n")
.append("from eje_ges_unidades u \n")
.append("inner join eje_ges_jerarquia j on u.unid_id = j.nodo_id \n")
.append("left join (select unidad, cantidad=count(rut) from eje_ges_trabajador group by unidad) t on t.unidad=u.unid_id \n")
.append("left join (select e.unid_id \n")
.append(" from eje_ges_unidad_encargado e \n")
.append(" inner join eje_ges_trabajador t on t.rut=e.rut_encargado \n")
.append(" where e.estado=1) e on e.unid_id=u.unid_id \n")
.append("where j.nodo_padre = ? ");
if(!incluyeNoVigentes) {
strSQL.append(" and u.vigente = 'S' \n");
}
strSQL.append("group by j.nodo_id,u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto, t.cantidad, e.unid_id \n");
ConsultaData data = null;
Object[] params = {unidad};
try {
data = ConsultaTool.getInstance().getData("portal", strSQL.toString(), params );
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
public ConsultaData getJefeUnidad(String unidad) {
List<String> unidades = new ArrayList<String>();
unidades.add(unidad);
return getJefeUnidad(unidades);
}
@Override
public ConsultaData getJefeUnidad(List<String> unidades) {
ArrayFactory af = new ArrayFactory();
af.addAll(unidades);
StringBuilder strSQL = new StringBuilder();
strSQL.append(" select t.rut ");
strSQL.append(" from eje_ges_unidad_encargado ue ");
strSQL.append(" left outer join eje_ges_trabajador t on ue.unid_id=t.unidad and ue.rut_encargado=t.rut and ue.estado=1 \n");
strSQL.append(" left outer join eje_ges_unidades u on u.unid_id=t.unidad \n");
strSQL.append(" WHERE ue.unid_id in ").append(af.getArrayString());
strSQL.append(" and ue.estado = ? and t.rut is not null");
ConsultaData dataFinal = null;
try {
Object[] params = {EstadoJefaUnidad.vigente.getValue()};
ConsultaData data = ConsultaTool.getInstance().getData("portal", strSQL.toString(), params );
int rut = -1;
if(data!= null && data.next()) {
rut = data.getInt("rut");
}
dataFinal = getTrabajadores( rut );
} catch (SQLException e) {
e.printStackTrace();
}
return dataFinal;
}
public ConsultaData getJefeResponsableDeLaUnidad(String unidad) {
ConsultaData dataJefatura = getJefeUnidad(unidad);
if(dataJefatura != null && dataJefatura.next()) {
dataJefatura.toStart();
return dataJefatura;
}
else {
ConsultaData dataPadre = getUnidadesPadres(unidad);
while(dataPadre != null && dataPadre.next()) {
dataJefatura = getJefeUnidad(dataPadre.getString("unid_id"));
if(dataJefatura != null && dataJefatura.next()) {
dataJefatura.getActualData().put("pertenece_a_esta_unidad", 0);
break;
}
dataPadre = getUnidadesPadres(dataPadre.getString("unid_id"));
}
}
if(dataJefatura != null) {
dataJefatura.toStart();
}
return dataJefatura;
}
public ConsultaData getJefeDelTrabajador(int rut) {
ConsultaData data = getUnidadFromRut(rut);
ConsultaData dataJefatura = null;
if(data != null && data.next()) {
dataJefatura = getJefeResponsableDeLaUnidad(data.getString("unid_id"));
if(dataJefatura != null && dataJefatura.next()) {
if(dataJefatura.getInt("rut") == rut) {
ConsultaData dataPadre = getUnidadesPadres(data.getString("unid_id"));
if(dataPadre != null && dataPadre.next()) {
dataJefatura = getJefeResponsableDeLaUnidad(dataPadre.getString("unid_id"));
}
else {
//throw new JefaturaNotFoundException("No fue encontrado el jefe del rut >>"+rut);
}
}
}
if(dataJefatura != null){
dataJefatura.toStart();
}
return dataJefatura;
}
return null;
}
@Override
public ConsultaData getJefeDelTrabajador(String rut) {
return getJefeDelTrabajador((Integer) ClaseConversor.getInstance().getObject(rut, Integer.class));
}
public ConsultaData getUnidadesPadres(String unidad) {
StringBuilder sql = new StringBuilder();
sql.append(" select u2.* \n");
sql.append(" from eje_ges_unidades u inner join eje_ges_jerarquia j on u.unid_id = j.nodo_id \n");
sql.append(" left outer join eje_ges_unidades u2 on u2.unid_id = j.nodo_padre \n");
sql.append(" where j.nodo_id = ? \n");
ConsultaData data = null;
Object[] params = { unidad };
try {
data = ConsultaTool.getInstance().getData("portal", sql.toString(), params );
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
public ConsultaData getUnidadRaiz() {
StringBuilder sql = new StringBuilder();
sql.append(" select u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto, dotacion_real=count(distinct rut) \n");
sql.append(" from eje_ges_unidades u \n");
sql.append(" inner join eje_ges_jerarquia j on u.unid_id = j.nodo_id \n");
sql.append(" left join eje_ges_trabajador t on t.unidad = u.unid_id \n");
sql.append(" where (j.nodo_padre is null) or (j.nodo_padre = '0') \n");
sql.append(" group by u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto \n");
ConsultaData data = null;
Object[] params = { };
try {
data = ConsultaTool.getInstance().getData("portal", sql.toString(), params );
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
public ConsultaData getUnidad(String unidad) {
if(unidad == null ) {
throw new NullPointerException();
}
List<String> lUnidades = new ArrayList<String>();
lUnidades.add(unidad);
return getUnidad(null, lUnidades);
}
@Override
public ConsultaData getUnidad(Connection connPortal, List<String> listaDeUnidId) {
if(listaDeUnidId == null ) {
throw new NullPointerException();
}
if(listaDeUnidId.size() == 0) {
throw new IndexOutOfBoundsException("No puede contener 0 valores ");
}
ArrayFactory af = new ArrayFactory();
af.addAll(listaDeUnidId);
StringBuilder sql = new StringBuilder();
sql.append(" select u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto, dotacion_real=count(distinct rut), \n");
sql.append(" tiene_encargado= case when not ue.rut_encargado is null then 1 else 0 end \n");
sql.append(" from eje_ges_unidades u ");
sql.append(" inner join eje_ges_jerarquia j on u.unid_id = j.nodo_id \n");
sql.append(" left outer join eje_ges_trabajador t on t.unidad = u.unid_id \n");
sql.append(" left join eje_ges_unidad_encargado ue on ue.unid_id=t.unidad and ue.rut_encargado=t.rut and ue.estado=1 \n");
sql.append(" where u.unid_id in ").append(af.getArrayString());
sql.append(" group by u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto, ue.rut_encargado ");
ConsultaData data = null;
try {
if(connPortal == null) {
data = ConsultaTool.getInstance().getData("portal", sql.toString() );
}
else {
data = ConsultaTool.getInstance().getData(connPortal, sql.toString() );
}
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
public ConsultaData getUnidadFromRut(int rut) {
StringBuilder sql = new StringBuilder();
sql.append(" select u.* \n");
sql.append(" from eje_ges_unidades u inner join eje_ges_jerarquia j on u.unid_id = j.nodo_id \n");
sql.append(" inner join eje_ges_trabajador t on t.unidad = u.unid_id \n");
sql.append(" where t.rut = ? \n");
ConsultaData data = null;
Object[] params = { rut };
try {
data = ConsultaTool.getInstance().getData("portal", sql.toString(), params );
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
public List<String> getUnidadesRaices() {
String sql = "select j.nodo_id from eje_ges_jerarquia j inner join eje_ges_unidades u on u.unid_id = j.nodo_id where j.nodo_padre = '0' or j.nodo_padre is null";
List<String> lista = new ArrayList<String>();
try {
ConsultaData data = ConsultaTool.getInstance().getData("portal", sql);
while(data != null && data.next()) {
lista.add(data.getForcedString("nodo_id"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return lista;
}
@Override
public ConsultaData getUnidades() {
return getUnidades(null);
}
@Override
public ConsultaData getUnidades(String strFiltro) {
StringBuilder strSQL = new StringBuilder();
strSQL.append("select u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto, dotacion_real=count(distinct rut) \n")
.append("from eje_ges_unidades u \n")
.append("inner join eje_ges_jerarquia j on u.unid_id = j.nodo_id \n")
.append("left outer join eje_ges_trabajador t on t.unidad = u.unid_id \n")
.append(" WHERE u.vigente = 'S' ");
if (strFiltro!=null) {
if (strFiltro.replaceAll(" ", "")!=""){
strSQL.append("and u.unid_id+' '+u.unid_desc like '%").append(strFiltro.replaceAll(" ", "%")).append("%' ");
}
}
strSQL.append("group by u.unid_empresa, u.unid_id, u.unid_desc, u.area, u.vigente, u.id_tipo, u.texto ");
ConsultaData data = null;
Object[] params = {};
try {
data = ConsultaTool.getInstance().getData("portal", strSQL.toString(), params );
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
@Override
public boolean isJefe(int rut) {
ConsultaData dataMiUnidad = getUnidadFromRut(rut);
if(dataMiUnidad != null && dataMiUnidad.next()) {
ConsultaData dataJefe = getJefeUnidad(dataMiUnidad.getString("unid_id"));
if( dataJefe != null && dataJefe.next() ) {
return dataJefe.getInt("rut") == rut;
}
}
return false;
}
@Override
public ConsultaData getTrabajadores() {
return getTrabajadores(null, null, null, false);
}
@Override
public ConsultaData getTrabajadores(int intIdPersona) {
List<Integer> ruts = null;
if(intIdPersona != 0) {
ruts = new ArrayList<Integer>();
ruts.add(intIdPersona);
}
return getTrabajadores(ruts, null, null, false);
}
@Override
public ConsultaData getTrabajadores(String strFiltro) {
return getTrabajadores(null, null, strFiltro, false);
}
private ConsultaData getTrabajadores(List<Integer> personas, String strUnidad, String strFiltro, boolean omiteJefe) {
StringBuilder strSQL = new StringBuilder();
String strInicFiltro = "and";
strSQL.append("select distinct id_persona=t.rut,\n");
strSQL.append("t.rut,\n");
strSQL.append("nif=cast(t.rut as varchar)+'-'+t.digito_ver,\n");
strSQL.append("nombre=ltrim(rtrim(t.nombre)),\n");
strSQL.append("persona=ltrim(rtrim(t.nombre)), \n") ;
strSQL.append("ape_paterno=ltrim(rtrim(t.ape_paterno)),\n");
strSQL.append("ape_materno=ltrim(rtrim(t.ape_materno)),\n");
strSQL.append("nombres=ltrim(rtrim(t.nombres)),\n");
strSQL.append("sexo=ltrim(rtrim(t.sexo)),\n");
strSQL.append("email=ltrim(rtrim(t.e_mail)), \n");
strSQL.append("id_empresa=t.empresa, \n");
strSQL.append("empresa=ltrim(rtrim(e.descrip)), \n");
strSQL.append("u.unid_id,\n");
strSQL.append("id_unidad=t.unidad,\n");
strSQL.append("unidad=ltrim(rtrim(u.unid_desc)), \n");
strSQL.append("unid_desc=ltrim(rtrim(u.unid_desc)), \n");
strSQL.append("id_cargo=t.cargo,\n");
strSQL.append("cargo=ltrim(rtrim(c.descrip)), \n");
strSQL.append("t.ccosto , \n");
strSQL.append("ccosto_desc=cc.descrip, \n");
strSQL.append("nacionalidad=pais.nacionalidad, \n");
strSQL.append("t.fecha_nacim, \n");
strSQL.append("fecha_ingreso=convert(varchar(10),t.fecha_ingreso,120),");
strSQL.append("fecha_ingreso_date = t.fecha_ingreso, \n");
strSQL.append("t.wp_cod_planta,\n");
strSQL.append("e.compania, \n");
strSQL.append("t.mail,\n");
strSQL.append("t.e_mail, \n");
strSQL.append("t.telefono, \n");
strSQL.append("t.fec_ter_cont,\n");
strSQL.append("id_encargado=ue.rut_encargado, \n");
strSQL.append("encargado=ltrim(rtrim(te.nombre)), \n");
strSQL.append("es_encargado=(case t.rut when ue.rut_encargado then 1 else 0 end), \n");
strSQL.append("pertenece_a_esta_unidad=1 \n");
strSQL.append("from eje_ges_trabajador t \n");
strSQL.append("left join eje_ges_empresa e on e.empresa=t.empresa \n");
strSQL.append("left join eje_ges_unidades u on u.unid_id=t.unidad and u.vigente ='s' \n");
strSQL.append("left join eje_ges_cargos c on c.cargo=t.cargo and c.empresa=t.empresa \n");
strSQL.append("left join eje_ges_unidad_encargado ue on ue.unid_id=t.unidad and ue.rut_encargado=t.rut and ue.estado=1 \n");
strSQL.append("left join eje_ges_trabajador te on te.rut=ue.rut_encargado \n");
strSQL.append("left join eje_ges_centro_costo cc on cc.vigente = 's' and cc.centro_costo = t.ccosto and cc.wp_cod_empresa = t.wp_cod_empresa \n");
strSQL.append("left join eje_ges_paises pais on pais.pais = t.pais \n");
if (personas!=null) {
ArrayFactory af =new ArrayFactory();
af.addAll(personas);
strSQL.append("where t.rut in ").append(af.getArrayInteger());
}else if (strUnidad!=null) {
strSQL.append("where t.unidad=? ");
if (omiteJefe) {
strSQL.append("and ue.rut_encargado is null\n");
}
}else {
strSQL.append("where t.rut<>0 ");
}
if (strFiltro!=null) {
if (strFiltro.replaceAll(" ", "")!=""){
strSQL.append("and cast(t.rut as varchar)+' '+t.nombre+' '+c.descrip+' '+u.unid_desc like '%").append(strFiltro.replaceAll(" ", "%")).append("%' ");
}
}
strSQL.append("order by (case t.rut when ue.rut_encargado then 1 else 0 end) desc, ltrim(rtrim(t.nombre)) ");
ConsultaData data = null;
ArrayList<Object> params = new ArrayList<Object>();
if (strUnidad!=null) {
params.add(strUnidad);
}
try {
data = ConsultaTool.getInstance().getData("portal", strSQL.toString(), params.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return data;
}
@Override
public ConsultaData getUnidadesEncargadas(int intPersona) {
return getUnidadesEncargadas(intPersona, null);
}
@Override
public ConsultaData getUnidadesEncargadas(int intPersona, Integer intVigente) {
StringBuilder strSQL = new StringBuilder();
Object[] objParam = new Object[] {};
ArrayList<Object> params = new ArrayList<Object>(Arrays.asList(objParam));
params.add(intPersona);
strSQL.append("select unid_id, estado \n")
.append("from eje_ges_unidad_encargado \n")
.append("where rut_encargado=? \n");
if (intVigente!=null) {
strSQL.append("and estado=? \n");
params.add(intVigente);
}
strSQL.append("order by unid_id \n");
ConsultaData data = null;
try {
data = ConsultaTool.getInstance().getData("portal", strSQL.toString(), params.toArray());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
@Override
public ICtrGOrganica getCtrG() {
return new CtrGOrganica(this);
}
}
| true |