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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
41b2e239dbcb1099cd4cdc22b14c9545b52ba645
|
Java
|
ailyanlu1/Competitive-Programming-Solutions
|
/Not Enough Personnel!.java
|
UTF-8
| 1,781
| 3.34375
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class NotEnoughPersonnel {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
public static void main (String[] args) throws IOException {
int n = readInt();
TreeSet<Employee> ts = new TreeSet<Employee>();
for (int x = 0; x < n; x++)
ts.add(new Employee(next(), readInt(), x));
int q = readInt();
for (int x = 0; x < q; x++) {
int skill = readInt();
int d = readInt();
Employee next = ts.ceiling(new Employee("", skill, 0));
if (next == null || next.skill - skill > d) {
System.out.println("No suitable teacher!");
} else {
System.out.println(next.name);
}
}
}
static class Employee implements Comparable<Employee> {
String name;
int skill, index;
Employee (String name, int skill, int index) {
this.name = name;
this.skill = skill;
this.index = index;
}
@Override
public int compareTo (Employee o) {
if (skill == o.skill)
return index - o.index;
return skill - o.skill;
}
}
static String next () throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong () throws IOException {
return Long.parseLong(next());
}
static int readInt () throws IOException {
return Integer.parseInt(next());
}
static double readDouble () throws IOException {
return Double.parseDouble(next());
}
static char readCharacter () throws IOException {
return next().charAt(0);
}
static String readLine () throws IOException {
return br.readLine().trim();
}
}
| true
|
921707fa650b33ccc6c7c55da4ea1902d90048dc
|
Java
|
takemy/LeetCode
|
/src/main/java/highFrequencyLeetcode/leetcode_104/MaximumDepthOfBinaryTree.java
|
UTF-8
| 1,414
| 3.953125
| 4
|
[] |
no_license
|
package highFrequencyLeetcode.leetcode_104;
/**
* <p>
*
* 给定一个二叉树,找出其最大深度。
*
* 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
*
* 说明: 叶子节点是指没有子节点的节点。
*
* 示例:
* 给定二叉树 [3,9,20,null,null,15,7],
*
* 3
* / \
* 9 20
* / \
* 15 7
*
* 返回它的最大深度 3 。
*
* </p>
*
* @author Seina
* @version 2019-06-19 14:40:54
*/
public class MaximumDepthOfBinaryTree {
/**
* 解法1 递归
*
* 递归循环做的事情:先求左子树深度,再求右子树深度,然后取两者最大,再加上自身一层的深度
*
* 时间复杂度: O(n)
* 空间复杂度: 最坏时树完全不平衡 O(n),最好时树完全平衡 O(logn)
* @param root:根节点
* @return 树的最大深度
*/
public int maxDepth(TreeNode root) {
//递归终止条件:叶子节点无左右子节点
if (root == null)
return 0;
else {
//左子树深度
int leftHeight = maxDepth(root.left);
//右子树深度
int rightHeight = maxDepth(root.right);
// + 1 表示每次递归结束,求深度的时候,要把自身所在一层深度加上
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
| true
|
928c2c6ebe4d717b7ce984a3b541b3a3236ff52f
|
Java
|
ppayaoxing/hummer-framework
|
/hummer-grpc/hummer-grpc-client/src/main/java/com/hummer/simple/grpc/client/channelfactory/InProcessOrAlternativeChannelFactory.java
|
UTF-8
| 4,793
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) 2019-2021 LiGuo <bingyang136@163.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.hummer.simple.grpc.client.channelfactory;
import com.google.common.collect.ImmutableMap;
import com.hummer.simple.grpc.client.config.GrpcChannelsProperties;
import io.grpc.Channel;
import io.grpc.ClientInterceptor;
import io.grpc.ConnectivityState;
import java.net.URI;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
/**
* This channel factory is a switch between the {@link InProcessChannelFactory} and an alternative implementation. All
* channels that are configured with the {@code in-process} scheme will be handled by the in-process-channel-factory,
* the other channels will be handled by the alternative implementation.
*
* <p>
* <b>The following examples show how the configured address will be mapped to an actual channel:</b>
* </p>
*
* <ul>
* <li><code>in-process:foobar</code> -> will use the <code>foobar</code> in-process-channel.</li>
* <li><code>in-process:foo/bar</code> -> will use the <code>foo/bar</code> in-process-channel.</li>
* <li><code>static://127.0.0.1</code> -> will be handled by the alternative grpc channel factory.</li>
* </ul>
*
* <p>
* Using this class does not incur any additional performance or resource costs, as the actual channels (in-process or
* other) are only created on demand.
* </p>
*/
public class InProcessOrAlternativeChannelFactory implements GrpcChannelFactory {
private static final String IN_PROCESS_SCHEME = "in-process";
private final GrpcChannelsProperties properties;
private final InProcessChannelFactory inProcessChannelFactory;
private final GrpcChannelFactory alternativeChannelFactory;
/**
* Creates a new InProcessOrAlternativeChannelFactory with the given properties and channel factories.
*
* @param properties The properties used to resolved the target scheme
* @param inProcessChannelFactory The in process channel factory implementation to use.
* @param alternativeChannelFactory The alternative channel factory implementation to use.
*/
public InProcessOrAlternativeChannelFactory(final GrpcChannelsProperties properties,
final InProcessChannelFactory inProcessChannelFactory, final GrpcChannelFactory alternativeChannelFactory) {
this.properties = requireNonNull(properties, "properties");
this.inProcessChannelFactory = requireNonNull(inProcessChannelFactory, "inProcessChannelFactory");
this.alternativeChannelFactory = requireNonNull(alternativeChannelFactory, "alternativeChannelFactory");
}
@Override
public Channel createChannel(final String name, final List<ClientInterceptor> interceptors,
boolean sortInterceptors) {
final URI address = this.properties.getChannel(name).getAddress();
if (address != null && IN_PROCESS_SCHEME.equals(address.getScheme())) {
return this.inProcessChannelFactory.createChannel(address.getSchemeSpecificPart(), interceptors,
sortInterceptors);
}
return this.alternativeChannelFactory.createChannel(name, interceptors, sortInterceptors);
}
@Override
public Map<String, ConnectivityState> getConnectivityState() {
return ImmutableMap.<String, ConnectivityState>builder()
.putAll(inProcessChannelFactory.getConnectivityState())
.putAll(alternativeChannelFactory.getConnectivityState())
.build();
}
@Override
public void close() {
try {
this.inProcessChannelFactory.close();
} finally {
this.alternativeChannelFactory.close();
}
}
}
| true
|
d1b7471faae0973a50a99244c976e5b5b2ed524b
|
Java
|
XiaoFanMie/leetCode
|
/Linked/MyLinked.java
|
UTF-8
| 3,987
| 3.84375
| 4
|
[] |
no_license
|
package Linked;
import java.util.Random;
public class MyLinked<T> {
//链表中数据的数据结构
private class Node {
T ele;
Node next;//指向下一个节点
public Node(T ele) {
this.ele = ele;
this.next = null;
}
public Node() {
this(null);
}
}
//链表中实际存放元素的个数
private int size;
//链表的头
private Node dummyHead;//虚拟头结点
public MyLinked() {
size = 0;
dummyHead = new Node(null);
}
//获取元素个数
public int getSize() {
return size;
}
//链表是否为空
public boolean isEmpyt() {
return size == 0;
}
//在链表的头部增加节点
public void addHead(T ele) {
//第一步创建节点
Node node = new Node(ele);
//node.next = head;
//head = node;
node.next = dummyHead.next;
dummyHead.next = node;
size++;
}
//在任意位置添加节点
public void add(int index, T ele) {
Node node = new Node(ele);
//找到上一个节点
Node pre = dummyHead;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
node.next = pre.next;
pre.next = node;
size++;
}
//在链表尾部添加节点
public void addTail(T ele) {
add(size - 1, ele);
}
//获取头结点元素
public T getHead(){
return get(0);
}
//获取指定位置的元素
public T get(int index){
Node pre = new Node();
pre = dummyHead.next;
for (int i = 0; i < index; i++) {
pre= pre.next;
}
return pre.ele;
}
//获取尾结点元素
public T getTail(){
return get(size-1);
}
//查找链表中是否包含某元素
public boolean contain(T ele){
boolean flag = false;
Node cur = dummyHead.next;
while(cur.next != null){
cur = cur.next;
if (cur.ele.equals(ele)){
flag = true;
break;
}
}
return flag;
}
//更新指定位置的元素
public void upEle(int index , T ele){
Node cur = new Node();
cur = dummyHead.next;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
cur.ele = ele;
}
//删除指定位置元素
public T delete(int index){
Node pre = new Node();
Node del = new Node();
pre= dummyHead.next;
for (int i = 0; i < index-1; i++) {
pre = pre.next;
del = pre.next;
}
T result = pre.next.ele;
pre.next = del.next;
del.next = null;
return result;
}
//链表的遍历
@Override
public String toString() {
StringBuilder result = new StringBuilder();
Node cur = dummyHead.next;
while (cur != null){
result.append(cur.ele + "-->");
if (cur.next ==null) {
result.append("NULL");
}
cur = cur.next;
}
return result.toString();
}
public static void main(String[] args) {
MyLinked<Integer> myLinked = new MyLinked();
Random random = new Random();
int num = 5;
for (int i = 0; i < num; i++) {
myLinked.addHead(random.nextInt(100));
}
System.out.println(myLinked.toString());
System.out.println(myLinked.getHead());
System.out.println(myLinked.getTail());
System.out.println(myLinked.get(2));
System.out.println(myLinked.contain(87));
System.out.println(myLinked.delete(2));
System.out.println(myLinked.toString());
}
}
| true
|
ad237ddc78d6ff4de9368631fac981be4948aada
|
Java
|
meiniepan/mei-hh
|
/database-transfer/src/main/java/com/wuyou/databasetransfer/DataEndPoint.java
|
UTF-8
| 1,739
| 2.21875
| 2
|
[] |
no_license
|
package com.wuyou.databasetransfer;
import com.wuyou.base.BaseResponse;
import com.wuyou.base.util.UUIDUtils;
import com.wuyou.databasetransfer.entities.Customer;
import com.wuyou.databasetransfer.entities.User;
import com.wuyou.databasetransfer.repository.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* @author hjn
* @created 2019-01-22
**/
@RestController
@RequestMapping(path = "/database")
public class DataEndPoint {
@Autowired
OrderRepository orderRepository;
@Autowired
MongoOrderRepository mongoOrderRepository;
@Autowired
UserRepository userRepository;
@Autowired
MongoUserRepository mongoUserRepository;
@Autowired
ShopRepository shopRepository;
@Autowired
ServiceRepository serviceRepository;
@RequestMapping(method = RequestMethod.GET)
public BaseResponse<String> getEnv() {
doTransfer();
return new BaseResponse<>("ok");
}
private void doTransfer() {
List<User> all = userRepository.findAll();
List<Customer> mongoUsers = new ArrayList<>();
Customer mongoUser;
for (User user : all) {
mongoUser = new Customer(UUIDUtils.generateObjectId());
BeanUtils.copyProperties(user, mongoUser);
System.out.println(user.user_id + "............" + mongoUser.user_id);
mongoUsers.add(mongoUser);
}
mongoUserRepository.save(mongoUsers);
}
}
| true
|
05ae0aa87d8c88e4ffd991ac80cfbec3e09c9209
|
Java
|
jamz903/snatch
|
/app/src/main/java/sg/edu/np/mad/snatch/vacancyRVAdapter.java
|
UTF-8
| 4,249
| 2.390625
| 2
|
[] |
no_license
|
package sg.edu.np.mad.snatch;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class vacancyRVAdapter extends RecyclerView.Adapter<vacancyViewHolder> {
Context context;
ArrayList<FoodCourt> foodCourtList;
vacancyRVAdapterCallback listener;
public vacancyRVAdapter(Context context, ArrayList<FoodCourt> aFoodCourtList, vacancyRVAdapterCallback aListener) {
this.context = context;
this.foodCourtList = aFoodCourtList;
this.listener = aListener;
}
@NonNull
@Override
public vacancyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.vacancy_food_court_listitem, parent, false);
return new vacancyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull vacancyViewHolder holder, final int position) {
final FoodCourt foodCourt = foodCourtList.get(position);
holder.bind(foodCourt);
ArrayList<FoodItem> top3Dishes = foodCourt.popularDishes;
Collections.sort(top3Dishes);
if (foodCourt.getName().equals("FoodClub")) {
holder.listitem_foodCourtNameTextView.setText("Food Club");
}
else if (foodCourt.getName().equals("Makan Place")) {
holder.listitem_foodCourtNameTextView.setText("Makan Place");
}
else if (foodCourt.getName().equals("Poolside")) {
holder.listitem_foodCourtNameTextView.setText("Poolside");
}
else {
holder.listitem_foodCourtNameTextView.setText("Munch");
}
// Display the Food Court seating capacity
holder.capacityTextView.setText("Seating Capacity: " + String.valueOf(foodCourt.capacity));
// Retrieving the top 3 dishes and displaying in the Food Court list item
final FoodItem dish1 = top3Dishes.get(0);
String visitText = "Visit Store";
holder.foodNameTextView1.setText(dish1.foodName);
holder.visitTextView1.setText(visitText);
holder.dishImageView1.setImageResource(dish1.imageID);
final FoodItem dish2 = top3Dishes.get(1);
holder.foodNameTextView2.setText(dish2.foodName);
holder.visitTextView2.setText(visitText);
holder.dishImageView2.setImageResource(dish2.imageID);
final FoodItem dish3 = top3Dishes.get(2);
holder.foodNameTextView3.setText(dish3.foodName);
holder.visitTextView3.setText(visitText);
holder.dishImageView3.setImageResource(dish3.imageID);
// To expand/un-expand the row in Recycler View when it is clicked
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean expanded = foodCourt.isExpanded();
foodCourt.setExpanded(!expanded);
notifyItemChanged(position);
}
});
// Brings user to the food stall's menu when user selects "Visit Food Store" option
holder.visitTextView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.visitFoodStall(dish1.foodCourt, dish1.stallName);
}
});
holder.visitTextView2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.visitFoodStall(dish2.foodCourt, dish2.stallName);
}
});
holder.visitTextView3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.visitFoodStall(dish3.foodCourt, dish3.stallName);
}
});
}
@Override
public int getItemCount() {
return foodCourtList.size();
}
}
| true
|
532696b1fe224609859bdd09730a7d914bc38295
|
Java
|
AdamsTHDev/batchSalesData
|
/src/main/java/com/adms/batch/sales/dao/impl/ReconfirmStatusDaoImpl.java
|
UTF-8
| 500
| 1.984375
| 2
|
[] |
no_license
|
package com.adms.batch.sales.dao.impl;
import org.springframework.stereotype.Repository;
import com.adms.batch.sales.dao.ReconfirmStatusDao;
import com.adms.batch.sales.domain.ReconfirmStatus;
import com.adms.common.dao.generic.impl.GenericDaoHibernate;
@Repository("reconfirmStatusDao")
public class ReconfirmStatusDaoImpl extends GenericDaoHibernate<ReconfirmStatus, Long> implements ReconfirmStatusDao {
public ReconfirmStatusDaoImpl() {
super(ReconfirmStatus.class);
}
}
| true
|
7b6d4d12910a843b55e85f49c32f8888dc85c0d1
|
Java
|
gczhang-minhong/spring-boot-samples
|
/spring-security-oauth2/spring-security-oauth2-server/src/main/java/com/funtl/oauth2/server/service/impl/TbRoleServiceImpl.java
|
UTF-8
| 357
| 1.679688
| 2
|
[] |
permissive
|
package com.funtl.oauth2.server.service.impl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.funtl.oauth2.server.mapper.TbRoleMapper;
import com.funtl.oauth2.server.service.TbRoleService;
@Service
public class TbRoleServiceImpl implements TbRoleService{
@Resource
private TbRoleMapper tbRoleMapper;
}
| true
|
c7adbfff6ede730c77b502ac1c66b81f7dfe6d6f
|
Java
|
Carol-Annie/Agencia-de-Rodoviaria
|
/TRABALHO_POO/agenciaonibus/Passagem.java
|
UTF-8
| 154
| 1.75
| 2
|
[] |
no_license
|
package agenciaonibus;
public abstract class Passagem {
public abstract void InfoPassagem(String local, double preco, StatusPassagem status);
}
| true
|
a0a017a572bf6dd098dd001bea8f9baf79c534db
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/8/8_bc99bfb1f92b7e917f17f5858ee4a2695f6d212c/SwingMenuTestUtil/8_bc99bfb1f92b7e917f17f5858ee4a2695f6d212c_SwingMenuTestUtil_t.java
|
UTF-8
| 3,894
| 2.578125
| 3
|
[] |
no_license
|
package de.frosner.datagenerator.gui.main;
import static org.fest.assertions.Fail.fail;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import org.fest.swing.edt.GuiActionRunner;
import org.fest.swing.edt.GuiTask;
public final class SwingMenuTestUtil {
private static final int DIALOG_OPEN_DELAY = 500;
private static final int ROBOT_DELAY = 75;
private SwingMenu _menu;
private Robot _robot;
SwingMenuTestUtil(SwingMenu swingMenu) {
_menu = swingMenu;
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu.setVisible(true);
_menu.toFront();
}
});
try {
_robot = new Robot();
} catch (AWTException e) {
fail(e.getMessage());
}
}
void clickButton(final JButton button) {
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu.actionPerformed(new ActionEvent(button, 1, ""));
}
});
}
void tryToAddEnteredFeatureAndGiveUp() {
new Thread(new Runnable() {
@Override
public void run() {
delay(DIALOG_OPEN_DELAY);
pressAndReleaseKey(KeyEvent.VK_ENTER);
delay(ROBOT_DELAY);
pressAndReleaseKey(KeyEvent.VK_ESCAPE);
}
}).start();
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu.actionPerformed(new ActionEvent(_menu._addFeatureButton, 1, ""));
}
});
}
void addEnteredFeature() {
new Thread(new Runnable() {
@Override
public void run() {
delay(DIALOG_OPEN_DELAY);
pressAndReleaseKey(KeyEvent.VK_ENTER);
}
}).start();
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu.actionPerformed(new ActionEvent(_menu._addFeatureButton, 1, ""));
}
});
}
void selectFeature(final int i) {
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu._featureList.setSelectedIndex(i);
}
});
}
void selectFile(final File file) {
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu._exportFileDialog.setSelectedFile(file);
}
});
}
void enterText(final JTextField textField, final String text) {
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
textField.setText(text);
}
});
}
void setExportFileFilter(final FileFilter filter) {
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu._exportFileDialog.setFileFilter(filter);
}
});
}
void selectFileUsingFileChooserDialog(final File file) {
new Thread(new Runnable() {
@Override
public void run() {
_robot.delay(DIALOG_OPEN_DELAY);
GuiActionRunner.execute(new GuiTask() {
@Override
protected void executeInEDT() {
_menu._exportFileDialog.setSelectedFile(file);
_menu._exportFileDialog.approveSelection();
}
});
}
}).start();
clickButton(_menu._exportFileButton);
}
void pressAndReleaseKey(int key) {
try {
_robot = new Robot();
_robot.delay(ROBOT_DELAY);
_robot.keyPress(key);
_robot.delay(ROBOT_DELAY);
_robot.keyRelease(key);
_robot.delay(ROBOT_DELAY);
} catch (AWTException e) {
fail();
e.printStackTrace();
}
}
void delay(int ms) {
_robot.delay(ms);
}
void delay() {
delay(ROBOT_DELAY);
}
public static void delayOnce(int ms) {
try {
new Robot().delay(ms);
} catch (AWTException e) {
fail(e.getMessage());
}
}
public static void delayOnce() {
delayOnce(ROBOT_DELAY);
}
}
| true
|
4f7da54ee890c7e34dfae97faf3b28cb514341bc
|
Java
|
SHsuperCM/GamepadBoat
|
/src/main/java/shcm/shsupercm/mods/gamepadboat/GamepadBoat.java
|
UTF-8
| 4,364
| 2.046875
| 2
|
[
"BSD-2-Clause"
] |
permissive
|
package shcm.shsupercm.mods.gamepadboat;
import io.github.prospector.modmenu.api.ConfigScreenFactory;
import io.github.prospector.modmenu.api.ModMenuApi;
import me.sargunvohra.mcmods.autoconfig1u.AutoConfig;
import me.sargunvohra.mcmods.autoconfig1u.serializer.GsonConfigSerializer;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.java.games.input.*;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.entity.vehicle.BoatEntity;
import net.minecraft.text.LiteralText;
import org.lwjgl.glfw.GLFWGamepadState;
import static org.lwjgl.glfw.GLFW.*;
public class GamepadBoat implements ModInitializer, ModMenuApi {
public GamepadBoatConfig config;
private GLFWGamepadState controller = null;
private float acceleration = 0f, breaks = 0f, direction = 0f;
private long t = 0;
@Override
public void onInitialize() {
AutoConfig.register(GamepadBoatConfig.class, GsonConfigSerializer::new);
config = AutoConfig.getConfigHolder(GamepadBoatConfig.class).getConfig();
ClientTickEvents.START_CLIENT_TICK.register(minecraft -> {
if (controller == null) {
if (glfwJoystickPresent(config.controllerID) && glfwJoystickIsGamepad(config.controllerID)) {
controller = GLFWGamepadState.create();
if (MinecraftClient.getInstance().player != null)
MinecraftClient.getInstance().getToastManager().add(new SystemToast(SystemToast.Type.NARRATOR_TOGGLE, new LiteralText("Connected Boat Gamepad"), new LiteralText(glfwGetJoystickName(config.controllerID))));
}
} else {
if (!glfwJoystickPresent(config.controllerID) || !glfwJoystickIsGamepad(config.controllerID)) {
controller = null;
if (MinecraftClient.getInstance().player != null)
MinecraftClient.getInstance().getToastManager().add(new SystemToast(SystemToast.Type.NARRATOR_TOGGLE, new LiteralText("Disconnected Boat Gamepad"), null));
}
}
});
new Thread(() -> {
try {
while (!Thread.interrupted()) {
if (controller != null) {
try {
glfwGetGamepadState(config.controllerID, controller);
onTick();
} catch (Exception ignored) {}
Thread.sleep(1000 / config.pollRate);
}
}
} catch (InterruptedException ignored) {}
}).start();
}
private void onTick() {
if (MinecraftClient.getInstance().player == null || !(MinecraftClient.getInstance().player.getVehicle() instanceof BoatEntity)) return;
float leftX = controller.axes().get(GLFW_GAMEPAD_AXIS_LEFT_X);
float rightTrigger = (controller.axes().get(GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER) + 1f) / 2f;
float leftTrigger = (controller.axes().get(GLFW_GAMEPAD_AXIS_LEFT_TRIGGER) + 1f) / 2f;
if (leftX > -config.deadzone && leftX < config.deadzone)
direction = 0f;
else
direction = leftX * config.pwmCycle;
if (rightTrigger < config.deadzone)
acceleration = 0f;
else
acceleration = rightTrigger * config.pwmCycle;
if (leftTrigger < config.deadzone)
breaks = 0f;
else
breaks = leftTrigger * config.pwmCycle;
t++;
MinecraftClient.getInstance().options.keyLeft.setPressed(direction < 0f && (t % config.pwmCycle) < -direction);
MinecraftClient.getInstance().options.keyRight.setPressed(direction > 0f && (t % config.pwmCycle) < direction);
MinecraftClient.getInstance().options.keyForward.setPressed(acceleration > 0f && (t % config.pwmCycle) < acceleration);
MinecraftClient.getInstance().options.keyBack.setPressed(breaks > 0f && (t % config.pwmCycle) < breaks);
}
@Override
public ConfigScreenFactory<?> getModConfigScreenFactory() {
return (ConfigScreenFactory<Screen>) screen -> AutoConfig.getConfigScreen(GamepadBoatConfig.class, screen).get();
}
}
| true
|
990a02f480cb19951862818b99264482f613b4b1
|
Java
|
vintreth/skogmark-website
|
/skogmark-telegram-bot/src/main/java/ru/skogmark/telegram/bot/core/update/UpdateConfiguration.java
|
UTF-8
| 2,406
| 2.21875
| 2
|
[] |
no_license
|
package ru.skogmark.telegram.bot.core.update;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.skogmark.common.http.HttpRequest;
import ru.skogmark.telegram.bot.api.ApiUrlProvider;
import ru.skogmark.telegram.bot.api.dto.Update;
import ru.skogmark.telegram.bot.core.config.TelegramBotSettings;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@Configuration
public class UpdateConfiguration {
/**
* Client for updates
*/
@Bean
UpdateClient updateClient(HttpRequest httpRequest, ApiUrlProvider urlProvider) {
return new UpdateClient(httpRequest, urlProvider);
}
/**
* Executor holder for {@link UpdateEventProducer}
*/
@Bean
ScheduledExecutorService updateEventProducerExecutor() {
return Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "updateEventProducer"));
}
/**
* Topic with updates
*/
@Bean
UniqueBlockingQueueTopic<Update> updateTopic() {
return new UniqueBlockingQueueTopic<>();
}
/**
* UpdateEventProducer bean
*/
@Bean(initMethod = "start", destroyMethod = "stop")
UpdateEventProducer updateEventProducer(UpdateClient updateClient, TelegramBotSettings settings,
@Qualifier("updateEventProducerExecutor") ScheduledExecutorService executor,
UniqueBlockingQueueTopic<Update> topic) {
if (settings.isLocalMode()) {
return new LocalStubUpdateEventProducer();
}
return new DefaultUpdateEventProducer(updateClient, executor, topic);
}
/**
* Executor holder for {@link UpdateEventConsumer}
*/
@Bean
ScheduledExecutorService updateEventConsumerExecutor() {
return Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "updateEventConsumer"));
}
@Bean(initMethod = "start", destroyMethod = "stop")
UpdateEventConsumer updateEventConsumer(@Qualifier("updateEventConsumerExecutor") ScheduledExecutorService executor,
UniqueBlockingQueueTopic<Update> topic) {
return new DefaultUpdateEventConsumer(executor, topic);
}
}
| true
|
bcbf89b38071c8901651a68eacdeefa62d12df01
|
Java
|
winggynOnly/esdk_uc_neadp_interface
|
/source/esdk_uc_neadp_interface/src/main/java/com/huawei/esdk/uc/device/obg/client/IClientMsgCapability.java
|
UTF-8
| 632
| 1.8125
| 2
|
[] |
no_license
|
package com.huawei.esdk.uc.device.obg.client;
import com.huawei.esdk.platform.common.SDKErrorCode;
import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.uc.domain.model.InstanceMessage;
import com.huawei.esdk.uc.domain.model.bean.GroupInfoBase;
import com.huawei.esdk.uc.domain.model.bean.PagedList;
/** * @author w00208247 * * */
public interface IClientMsgCapability
{
SDKErrorCode sendMessage(String ucAccount,InstanceMessage instanceMessage);
SDKErrorCode withdrawMessage(InstanceMessage im);
//C03接口新增方法
SDKResult<PagedList<GroupInfoBase>> getMessage();
}
| true
|
cc624e79de83fcb46756585c7b725b0a3d59a7d9
|
Java
|
deepsoft-haolifa/haolifa
|
/src/main/java/com/deepsoft/haolifa/dao/repository/PayAssessmentScoreRecordMapper.java
|
UTF-8
| 1,156
| 1.96875
| 2
|
[] |
no_license
|
package com.deepsoft.haolifa.dao.repository;
import com.deepsoft.haolifa.model.domain.PayAssessmentScoreRecord;
import com.deepsoft.haolifa.model.domain.PayAssessmentScoreRecordExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface PayAssessmentScoreRecordMapper {
int countByExample(PayAssessmentScoreRecordExample example);
int deleteByExample(PayAssessmentScoreRecordExample example);
int deleteByPrimaryKey(Integer id);
int insert(PayAssessmentScoreRecord record);
int insertSelective(PayAssessmentScoreRecord record);
List<PayAssessmentScoreRecord> selectByExample(PayAssessmentScoreRecordExample example);
PayAssessmentScoreRecord selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") PayAssessmentScoreRecord record, @Param("example") PayAssessmentScoreRecordExample example);
int updateByExample(@Param("record") PayAssessmentScoreRecord record, @Param("example") PayAssessmentScoreRecordExample example);
int updateByPrimaryKeySelective(PayAssessmentScoreRecord record);
int updateByPrimaryKey(PayAssessmentScoreRecord record);
}
| true
|
f57e4047241dead44cfd461b8d8aea9b46e65209
|
Java
|
javaobjects/ipm_boot
|
/src/main/java/com/protocolsoft/sendemail/server/MailSenderInfoServer.java
|
UTF-8
| 6,849
| 2.296875
| 2
|
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/**
*<p>Copyright © 北京协软科技有限公司版权所有。</p>
*类名: Test001.java
*创建人: wangjianmin 创建时间: 2018年7月25日
*/
package com.protocolsoft.sendemail.server;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import com.protocolsoft.sendemail.bean.MailSenderInfoBean;
import com.protocolsoft.sendemail.bean.MyEmailBean;
/**
* @ClassName: Test001
* @Description: 邮件发送实现
* @author wangjianmin
*
*/
public class MailSenderInfoServer {
/**
*
* @Title: init
* @Description: 开始发送(初始化参数)
* @param mailSenderInfoBean 接收邮件信息
* @param bean void 接收发件人的邮箱账号
* @author wangjianmin
* @throws MessagingException
*/
public void init(MyEmailBean bean, MailSenderInfoBean mailSenderInfoBean) throws MessagingException{
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", bean.getMyEmailSMTPHost()); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
if(!bean.getSmtpPort().equals("25")){
// System.out.println("llllllllllllllllll: " + bean.getSmtpPort());
props.setProperty("mail.smtp.port", bean.getSmtpPort());
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", bean.getSmtpPort());
}
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getInstance(props);
//session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
// 3. 创建一封邮件
MimeMessage message = createMimeMessage(session, mailSenderInfoBean);
Transport transport = null;
try {
// 4. 根据 Session 获取邮件传输对象
transport = session.getTransport();
// 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
transport.connect(bean.getMyEmailAccount(),
bean.getMyEmailPassword());
// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null != transport){
try {
transport.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
*
* @Title: createMimeMessage
* @Description: 创建发送邮件
* @param session 和服务器交互的会话
* @param bean 接收发送邮件参数
* @return MimeMessage
* @author wangjianmin
*/
public MimeMessage createMimeMessage(Session session, MailSenderInfoBean bean) {
// 1. 创建一封邮件
MimeMessage message = null;
try {
message = new MimeMessage(session);
// 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称)
message.setFrom(new InternetAddress(bean.getSendMail(), bean.getSendName(), "UTF-8"));
// 3. To: 收件人(可以增加多个收件人、抄送、密送)
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(bean.getReceiveMail(), bean.getReceiveName(), "UTF-8"));
// 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题)
message.setSubject(bean.getSubject(), "UTF-8");
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(bean.getContent(), "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 添加附件的内容
if(bean.getAttachment() != null){
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(bean.getAttachment());
attachmentBodyPart.setDataHandler(new DataHandler(source));
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(bean.getEmailName(), "gb2312", "B"));
multipart.addBodyPart(attachmentBodyPart);
}
// 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
message.setContent(multipart, "text/html;charset=UTF-8");
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
}
| true
|
7c1c11da0b39f4f06dfb8d4c81fe33cca1d9927b
|
Java
|
softicar/platform
|
/platform-common/src/main/java/com/softicar/platform/common/io/stream/string/StringInputStreamFactory.java
|
UTF-8
| 280
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
package com.softicar.platform.common.io.stream.string;
public class StringInputStreamFactory {
private final String text;
public StringInputStreamFactory(String text) {
this.text = text;
}
public StringInputStream create() {
return new StringInputStream(text);
}
}
| true
|
19c87b65a647ac1b2881e8ab34d75a59e93aab17
|
Java
|
slava77/emulibSVN
|
/EMU/cscdw/ExsysGui/src/java/org/cern/cms/csc/exsys/re/gui/jsf/editor/basic/DatePropertyEditor.java
|
UTF-8
| 1,591
| 2.375
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.cern.cms.csc.exsys.re.gui.jsf.editor.basic;
import java.util.Date;
import javax.faces.convert.Converter;
import javax.faces.convert.DateTimeConverter;
import org.cern.cms.csc.dw.model.base.EntityBase;
import org.cern.cms.csc.dw.metadata.PropertyMd;
import org.cern.cms.csc.exsys.exception.InvalidEntityBeanPropertyException;
import org.cern.cms.csc.exsys.re.gui.jsf.editor.base.BasicEditor;
import org.cern.cms.csc.exsys.re.gui.jsf.editor.base.Editor;
import org.cern.cms.csc.exsys.re.gui.jsf.editor.base.Editor.InputType;
/**
* Editor used to edit Date properties
* @author Evka
*/
public class DatePropertyEditor extends BasicEditor {
/**
* Constructor
* @param entity entity that the property to be edited belongs to.
* @param metadata metadata of the property to be edited.
* @param parentEditor parent editor that this editor belongs to.
* @throws InvalidEntityBeanPropertyException thrown if property is incompatible with this kind of editor
*/
public DatePropertyEditor(EntityBase entity, PropertyMd metadata, Editor parentEditor) throws InvalidEntityBeanPropertyException {
super(entity, metadata, parentEditor);
}
@Override
public Class getValidValueClass() {
return Date.class;
}
@Override
protected Converter createConverter() {
return new DateTimeConverter();
}
@Override
protected InputType createInputType() {
return InputType.DATE_PICKER;
}
}
| true
|
bf1ee1d1d9395316d0ec166aef79c80b4bd3a529
|
Java
|
zuohuai/coreJava
|
/src/main/java/com/edu/game/jct/fight/service/alter/RateAlter.java
|
UTF-8
| 465
| 2.421875
| 2
|
[] |
no_license
|
package com.edu.game.jct.fight.service.alter;
import com.edu.game.jct.fight.model.UnitRate;
import com.edu.game.jct.fight.service.core.Unit;
/**
* 比率属性(累加关系)
* @author Administrator
*
*/
public class RateAlter extends DoubleTemplate {
private UnitRate rate;
public RateAlter(UnitRate rate) {
this.rate = rate;
}
@Override
public void execute(Unit unit, Double value) {
unit.increaseRate(rate, value);
}
}
| true
|
fac33788c54f4ccc0ccf6d9fce58909ca1ab77fe
|
Java
|
quoccuong15111997/1EMSERP
|
/app/build/generated/data_binding_base_class_source_out/debug/out/com/firstems/erp/databinding/ChartViewFragmentBinding.java
|
UTF-8
| 3,423
| 1.890625
| 2
|
[] |
no_license
|
// Generated by data binding compiler. Do not edit!
package com.firstems.erp.databinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import com.firstems.erp.R;
import com.github.mikephil.charting.charts.BarChart;
import java.lang.Deprecated;
import java.lang.Object;
public abstract class ChartViewFragmentBinding extends ViewDataBinding {
@NonNull
public final ImageView imgBack;
@NonNull
public final BarChart topBarChart;
protected ChartViewFragmentBinding(Object _bindingComponent, View _root, int _localFieldCount,
ImageView imgBack, BarChart topBarChart) {
super(_bindingComponent, _root, _localFieldCount);
this.imgBack = imgBack;
this.topBarChart = topBarChart;
}
@NonNull
public static ChartViewFragmentBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot) {
return inflate(inflater, root, attachToRoot, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.chart_view_fragment, root, attachToRoot, component)
*/
@NonNull
@Deprecated
public static ChartViewFragmentBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot, @Nullable Object component) {
return ViewDataBinding.<ChartViewFragmentBinding>inflateInternal(inflater, R.layout.chart_view_fragment, root, attachToRoot, component);
}
@NonNull
public static ChartViewFragmentBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.chart_view_fragment, null, false, component)
*/
@NonNull
@Deprecated
public static ChartViewFragmentBinding inflate(@NonNull LayoutInflater inflater,
@Nullable Object component) {
return ViewDataBinding.<ChartViewFragmentBinding>inflateInternal(inflater, R.layout.chart_view_fragment, null, false, component);
}
public static ChartViewFragmentBinding bind(@NonNull View view) {
return bind(view, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.bind(view, component)
*/
@Deprecated
public static ChartViewFragmentBinding bind(@NonNull View view, @Nullable Object component) {
return (ChartViewFragmentBinding)bind(component, view, R.layout.chart_view_fragment);
}
}
| true
|
346b67aa57c3f1e8d02f64ffd026e1ff7fee5a5e
|
Java
|
anisar667/Fragment_Activity2
|
/APP2_Login/app/src/main/java/com/example/nisarahmed/app2_login/MainActivity.java
|
UTF-8
| 4,537
| 1.976563
| 2
|
[] |
no_license
|
package com.example.nisarahmed.app2_login;
import android.app.SearchManager;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
public class MainActivity extends AppCompatActivity {
CircleMenu circleMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
circleMenu= findViewById(R.id.circle_menu);
circleMenu.setMainMenu(Color.parseColor("#CDCDCD"), R.mipmap.delete, R.mipmap.plus);
circleMenu.addSubMenu(Color.parseColor("#258CFF"), R.mipmap.facebook)
.addSubMenu(Color.parseColor("#30A400"), R.mipmap.twitter)
.addSubMenu(Color.parseColor("#FF4B32"), R.mipmap.whatsapp)
.addSubMenu(Color.parseColor("#8A39FF"), R.mipmap.google);
circleMenu.setOnMenuSelectedListener(new OnMenuSelectedListener() {
@Override
public void onMenuSelected(int index) {
switch (index) {
case 0:
Toast.makeText(MainActivity.this, "Facbook Button Clicked", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
break;
case 1:
Toast.makeText(MainActivity.this, "Twitter button Clicked", Toast.LENGTH_SHORT).show();
Intent i=new Intent(MainActivity.this,Main3Activity.class);
startActivity(i);
break;
case 2:
Toast.makeText(MainActivity.this, "Whatsapp button Clciked", Toast.LENGTH_SHORT).show();
Intent in=new Intent(MainActivity.this,Main4Activity.class);
startActivity(in);
break;
case 3:
Toast.makeText(MainActivity.this, "Google button Clcked", Toast.LENGTH_SHORT).show();
String google="google.com";
Intent intent1=new Intent(Intent.ACTION_WEB_SEARCH);
intent1.putExtra(SearchManager.QUERY,google);
startActivity(intent1);
// startActivity(new Intent(MainActivity.this, ThankYouActivity.class));
break;
}
}
}
);
circleMenu.setOnMenuStatusChangeListener(new OnMenuStatusChangeListener() {
@Override
public void onMenuOpened() {
}
@Override
public void onMenuClosed() {
}
}
);
}
@Override
public void onBackPressed() {
if (circleMenu.isOpened())
circleMenu.closeMenu();
else
finish();
}
}
| true
|
a619af5d701111af1f33366edaa4fff88e172ba2
|
Java
|
rohitjain01/project_questionBank
|
/QuestionBankProject/src/main/test/com/metacube/RoleServiceTest.java
|
UTF-8
| 1,333
| 2
| 2
|
[] |
no_license
|
package com.metacube;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.metacube.exception.QuestionBankException;
import com.metacube.exception.QuestionBankSystemException;
import com.metacube.model.Role;
import com.metacube.service.RoleService;
import com.metacube.service.impl.RoleServiceImpl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"spring-servlet.xml"})
public class RoleServiceTest {
@Autowired
RoleService roleService = new RoleServiceImpl();
@Transactional
@Test
public void testGetRole() throws QuestionBankSystemException, QuestionBankException{
Role role=roleService.getRole(1);
assertThat(role, instanceOf(Role.class));
}
@Transactional
@Test
public void testGetRoleFromRollType() throws QuestionBankSystemException, QuestionBankException{
String roleName ="Normal User";
Role role=roleService.getRoleFromRollType(roleName);
assertThat(role, instanceOf(Role.class));
}
}
| true
|
c3873b4eebbb8b7fa891a6d229bd5a757b5c3231
|
Java
|
CodecoolGlobal/filepartreader-testing-with-junit-Csaba0411
|
/src/main/java/com/codecool/FilePartReader.java
|
UTF-8
| 1,530
| 3.203125
| 3
|
[] |
no_license
|
package com.codecool;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FilePartReader {
private String filePath;
private int fromLine;
private int toLine;
public FilePartReader() {
this.filePath = "";
this.fromLine = -1;
this.toLine = 0;
}
public void setup(String filePath, int fromLine, int toLine) {
if (fromLine > toLine) throw new IllegalArgumentException("fromLine can't be bigger than toLine");
if (fromLine < 1) throw new IllegalArgumentException("fromLine have to be 1 or more!");
this.filePath = filePath;
this.fromLine = fromLine;
this.toLine = toLine;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
Stream<String> stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8);
stream.forEach(s -> sb.append(s).append("\n"));
return sb.toString();
}
public String readLines() throws IOException {
int counter = 1;
StringBuilder sb = new StringBuilder();
String[] strParts = read().split("\\n");
for (String lines : strParts) {
if (counter >= fromLine && counter <= toLine) {
sb.append(lines).append("\n");
}
counter++;
}
return sb.toString();
}
}
| true
|
a4b835cc5f029e2a437d656458adf8c9e2645fa1
|
Java
|
jgregorio0/handleticket-api
|
/src/main/java/dev/jgregorio/handleticket/api/ticket/model/grid/Grid.java
|
UTF-8
| 2,409
| 2.515625
| 3
|
[] |
no_license
|
package dev.jgregorio.handleticket.api.ticket.model.grid;
import com.google.cloud.vision.v1.EntityAnnotation;
import dev.jgregorio.handleticket.api.ticket.model.NormalizedText;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Grid {
int yErrorMax;
String rowSeparator, colSeparator;
List<Row> rows;
public Grid(int yErrorMax, String rowSeparator, String colSeparator) {
this.yErrorMax = yErrorMax;
this.rowSeparator = rowSeparator;
this.colSeparator = colSeparator;
this.rows = new ArrayList<>();
}
public void addAnnotations(List<EntityAnnotation> annotations) {
annotations.stream()
.filter(annotation -> !annotation.getDescription().contains("\n"))
.map(entityAnnotation -> new NormalizedText(entityAnnotation))
.collect(Collectors.toList())
.forEach(normalizedText -> add2Row(normalizedText));
rows.stream().forEach(row -> Collections.sort(row.getTexts(), new RowComparator()));
}
public String getTextFormatted() {
StringBuffer sb = new StringBuffer();
for (Row row : rows) {
sb.append(rowSeparator);
for (int i = 0; i < row.getTexts().size(); i++) {
NormalizedText normalizedText = row.getTexts().get(i);
String text = normalizedText.getText();
String toAppend = i == 0 ? text : colSeparator + text;
sb.append(toAppend);
}
}
return sb.toString();
}
private void add2Row(NormalizedText normalizedText) {
Row assignedRow = assignRow(normalizedText.getY());
assignedRow.getTexts().add(normalizedText);
}
private Row assignRow(int y) {
Row assignedRow = null;
Optional<Row> assignedRowOption = rows.stream()
.filter(row -> row.isInRange(y))
.findFirst();
if (assignedRowOption.isPresent()) {
assignedRow = assignedRowOption.get();
} else {
assignedRow = new Row(y, getyErrorMax());
getRows().add(assignedRow);
}
return assignedRow;
}
public List<Row> getRows() {
return rows;
}
public int getyErrorMax() {
return yErrorMax;
}
}
| true
|
2e30ca13df16d9421e67544f2529467b605cfbe9
|
Java
|
ratulmukh/zhimera
|
/src/main/java/ratul/experiments/cluster/VideoContentStorageNode.java
|
UTF-8
| 1,989
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ratul.experiments.cluster;
import ratul.experiments.cluster.ClusterMsgs.*;
import akka.actor.*;
import akka.cluster.Cluster;
import akka.cluster.ClusterEvent.CurrentClusterState;
import akka.cluster.ClusterEvent.MemberUp;
import akka.cluster.Member;
import akka.cluster.MemberStatus;
import akka.cluster.singleton.ClusterSingletonManager;
import akka.cluster.singleton.ClusterSingletonManagerSettings;
import akka.cluster.singleton.ClusterSingletonProxy;
import akka.cluster.singleton.ClusterSingletonProxySettings;
import akka.actor.Props;
import akka.actor.PoisonPill;
public class VideoContentStorageNode extends UntypedActor {
Cluster cluster = Cluster.get(getContext().system());
final ClusterSingletonManagerSettings settings =
ClusterSingletonManagerSettings.create(getContext().system()).withRole("video-content-storage-node");
ClusterSingletonProxySettings proxySettings =
ClusterSingletonProxySettings.create(getContext().system()).withRole("video-content-storage-node");
ActorRef videoStorageCoordinator;
//subscribe to cluster changes, MemberUp
@Override
public void preStart() {
cluster.subscribe(getSelf(), MemberUp.class);
context().system().actorOf(ClusterSingletonManager.props(
Props.create(VideoStorageCoordinator.class), new End(), settings), "video-storage-coordinator");
videoStorageCoordinator = context().system().actorOf(ClusterSingletonProxy.props("/user/video-storage-coordinator", proxySettings), "video-storage-coordinator-proxy");
}
public static class End {
}
//re-subscribe when restart
@Override
public void postStop() {
cluster.unsubscribe(getSelf());
}
@Override
public void onReceive(Object message) {
if(message instanceof VideoStorageRequest) {
System.out.println("VideoStorageRequest received and forwarded to coordinator");
videoStorageCoordinator.forward(message, getContext());
}else {
unhandled(message);
}
}
}
| true
|
55268c994edd8a3609d0af5d127f56deaf85daf7
|
Java
|
Amewarashi-desu/MoneyTransfer
|
/src/main/java/foo/bar/payment/PaymentServiceImpl.java
|
UTF-8
| 4,456
| 2.46875
| 2
|
[] |
no_license
|
package foo.bar.payment;
import foo.bar.DBCManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.Optional;
@Singleton
public class PaymentServiceImpl implements PaymentService {
private static final Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImpl.class);
private DBCManager dbcManager;
private static final String SELECT_PAYMENT_BY_ID =
"select payment_id, create_time, amount, left_account_id, right_account_id from payment where payment_id=?";
private static final String WITHDRAW_UPDATE = "update account set balance = (balance-?) where account_id=?";
private static final String TOP_UP_UPDATE = "update account set balance = (balance+?) where account_id=?";
private static final String INSERT_PAYMENT = "insert into payment(amount, left_account_id, right_account_id) " +
"values(?, ?, ?)";
@Inject
public PaymentServiceImpl(DBCManager dbcManager) {
this.dbcManager = dbcManager;
}
@Override
public Optional<Payment> findPayment(Long paymentId) {
try (Connection connection = dbcManager.getConnection()) {
connection.setReadOnly(true);
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_PAYMENT_BY_ID);
preparedStatement.setLong(1, paymentId);
preparedStatement.execute();
ResultSet resultSet = preparedStatement.getResultSet();
if (resultSet.next()) {
long payment_id = resultSet.getLong("payment_id");
LocalDateTime date = resultSet.getTimestamp("create_time").toLocalDateTime();
BigDecimal amount = resultSet.getBigDecimal("amount");
long left_account_id = resultSet.getLong("left_account_id");
long right_account_id = resultSet.getLong("right_account_id");
return Optional.of(new Payment(payment_id, left_account_id, right_account_id, amount, date));
} else {
return Optional.empty();
}
} catch (SQLException e) {
LOGGER.error("Error", e);
throw new RuntimeException(e);
}
}
@Override
public Long processPayment(PaymentDTO paymentDTO) {
try (Connection connection = dbcManager.getConnection()) {
connection.setReadOnly(false);
connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
try {
PreparedStatement psWithdraw = connection.prepareStatement(WITHDRAW_UPDATE);
psWithdraw.setBigDecimal(1, paymentDTO.getAmount());
psWithdraw.setLong(2, paymentDTO.getLeftAccountId());
PreparedStatement psTopUp = connection.prepareStatement(TOP_UP_UPDATE);
psTopUp.setBigDecimal(1, paymentDTO.getAmount());
psTopUp.setLong(2, paymentDTO.getRightAccountId());
PreparedStatement savePayment = connection.prepareStatement(INSERT_PAYMENT, Statement.RETURN_GENERATED_KEYS);
savePayment.setBigDecimal(1, paymentDTO.getAmount());
savePayment.setLong(2, paymentDTO.getLeftAccountId());
savePayment.setLong(3, paymentDTO.getRightAccountId());
final int updatedRows = psWithdraw.executeUpdate() + psTopUp.executeUpdate();
if (updatedRows != 2) {
throw new Exception("There must be 2 updated records, but was " + updatedRows);
}
savePayment.execute();
ResultSet generatedKeys = savePayment.getGeneratedKeys();
if (generatedKeys.next()) {
long new_payment_id = generatedKeys.getLong("payment_id");
connection.commit();
return new_payment_id;
} else {
throw new RuntimeException("There were no generated keys in result set, something went wrong");
}
} catch (Exception e) {
LOGGER.error("Error during account creation. Trying to rollback", e);
connection.rollback();
throw e;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| true
|
4dd56de7843d4bd9b94159c3aa0ac34101aa1479
|
Java
|
alaeri/BifacialView
|
/app/src/main/java/com/ebr163/bifacialview/SimpleActivity.java
|
UTF-8
| 3,123
| 2.078125
| 2
|
[
"MIT"
] |
permissive
|
package com.ebr163.bifacialview;
import android.animation.FloatEvaluator;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ebr163.bifacialview.view.BifacialView;
public class SimpleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
final BifacialView bifacialView = (BifacialView) findViewById(R.id.view);
Glide.with(this)
.load("https://files4.adme.ru/files/news/part_149/1494765/29530665-262592-3-0-1491487588-1491487592-650-bf845cd25e-1491558012.jpg")
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
bifacialView.setDrawableRight(resource);
return false;
}
}).preload();
Glide.with(this)
.load("https://files3.adme.ru/files/news/part_149/1494765/29530265-262592-33-0-1491489159-1491489163-650-8edb1df01d-1491558012.jpg")
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
bifacialView.setDrawableLeft(resource);
return false;
}
}).preload();
}
@Override
protected void onResume() {
super.onResume();
final BifacialView bifacialView = (BifacialView) findViewById(R.id.view);
final ObjectAnimator objectAnimator = ObjectAnimator.ofObject(bifacialView, "delimiterRatio", new FloatEvaluator(), 0.5f, 0.8f, 0.5f);
objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
objectAnimator.setDuration(1000);
bifacialView.postDelayed(new Runnable() {
@Override
public void run() {
objectAnimator.start();
}
},100);
}
}
| true
|
c15e3fe8bc4174c2dbe5b62c96df73a38a128c6d
|
Java
|
ngochuan1998/traffic-android
|
/app/src/main/java/ngochuan/damh/thongtingiaothong/model/User.java
|
UTF-8
| 351
| 2.1875
| 2
|
[] |
no_license
|
package ngochuan.damh.thongtingiaothong.model;
public class User {
public String id;
public String name;
public String type; // BTV, CTV
public User(String id) {
this.id = id;
}
public User(String id, String name, String type) {
this.id = id;
this.name = name;
this.type = type;
}
}
| true
|
bea33eb60339a0d125c91564b259fc1f91947491
|
Java
|
sleepyeePanda/2017opensource-01
|
/papao/papao-server-master/papao-openapi/src/main/java/com/papaolabs/openapi/domain/service/OperationServiceImpl.java
|
UTF-8
| 10,022
| 1.984375
| 2
|
[
"MIT"
] |
permissive
|
package com.papaolabs.openapi.domain.service;
import com.papaolabs.client.govdata.dto.AnimalResponse;
import com.papaolabs.client.govdata.dto.RegionResponse.Body.Items.RegionItem;
import com.papaolabs.openapi.domain.model.Animal;
import com.papaolabs.openapi.domain.model.Breed;
import com.papaolabs.openapi.domain.model.Breed.Species;
import com.papaolabs.openapi.domain.model.Region;
import com.papaolabs.openapi.domain.model.Shelter;
import org.springframework.stereotype.Service;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.papaolabs.openapi.domain.model.Breed.Species.CAT;
import static com.papaolabs.openapi.domain.model.Breed.Species.DOG;
import static com.papaolabs.openapi.domain.model.Breed.Species.ETC;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.apache.commons.lang3.StringUtils.isAllBlank;
import static org.apache.commons.lang3.StringUtils.isEmpty;
@Service
public class OperationServiceImpl implements OperationService {
public final static List<Species> BREED_SPECIES_LIST = Arrays.asList(DOG, CAT, ETC);
@NotNull
private final GovDataService govDataService;
public OperationServiceImpl(GovDataService govDataService) {
this.govDataService = govDataService;
}
@Override
public List<Animal> getAnimalList(String beginDate,
String endDate,
String speciesCode,
String kindCode,
String sidoCode,
String gunguCode,
String shelterCode,
String state,
String index,
String size) {
List<AnimalResponse.Body.Items.AnimalItem> animalItems = this.govDataService.readAnimalItems(beginDate,
endDate,
speciesCode,
kindCode,
sidoCode,
gunguCode,
shelterCode,
state,
index,
size);
if (animalItems == null) {
return Arrays.asList();
}
return animalItems.stream()
.map(x -> {
Animal animal = new Animal();
animal.setNoticeId(x.getNoticeNo());
animal.setNoticeBeginDate(x.getNoticeSdt());
animal.setNoticeEndDate(x.getNoticeEdt());
animal.setDesertionId(Long.valueOf(x.getDesertionNo()));
animal.setStateType(x.getProcessState());
animal.setImageUrl(x.getPopfile());
animal.setThumbImageUrl(x.getFilename());
animal.setBreedName(x.getKindCd());
animal.setColorName(x.getColorCd());
animal.setAge(convertAge(x.getAge()));
animal.setWeight(Float.valueOf(convertWeight(x.getWeight())));
animal.setGenderCode(x.getSexCd());
animal.setNeuterCode(x.getNeuterYn());
animal.setJurisdiction(x.getOrgNm());
animal.setShelterName(x.getCareNm());
animal.setShelterContact(x.getCareTel());
animal.setShelterAddress(x.getCareAddr());
animal.setUserName(x.getChargeNm());
animal.setUserContact(x.getOfficetel());
animal.setFeature(x.getSpecialMark());
animal.setNote(x.getNoticeComment());
/*
animal.setPageSize(Integer.valueOf(x.getNumOfRows()));
animal.setPageIndex(Integer.valueOf(x.getPageNo()));
animal.setPageTotalCount(Integer.valueOf(x.getTotalCount()));
animal.setResultCode(Integer.valueOf(x.getResultCode()));
animal.setResultMessage(x.getResultMsg());
*/
animal.setHappenDate(x.getHappenDt());
animal.setHappenPlace(x.getHappenPlace());
return animal;
})
.collect(Collectors.toList());
}
@Override
public List<Breed> getBreedList() {
return this.BREED_SPECIES_LIST.stream()
.map(this::transform)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
@Override
public List<Region> getRegionList() {
return this.govDataService.readSidoItems()
.stream()
.map(this::transform)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
@Override
public List<Shelter> getShelterList() {
return this.govDataService.readGunguItems(EMPTY)
.stream()
.map(this::shelterTransform)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
private List<Breed> transform(Species species) {
return this.govDataService.readKindItems(species.getCode())
.stream()
.map(x -> {
Breed breed = new Breed();
breed.setSpecies(species);
breed.setCode(Integer.valueOf(x.getKindCd()));
breed.setName(x.getKNm());
return breed;
})
.collect(Collectors.toList());
}
private List<Region> transform(RegionItem regionItem) {
return Optional.ofNullable(this.govDataService.readGunguItems(regionItem.getOrgCd()))
.orElse(Arrays.asList(regionItem))
.stream()
.map(x -> {
Region region = new Region();
region.setSidoCode(Integer.valueOf(regionItem.getOrgCd()));
region.setSidoName(regionItem.getOrgdownNm());
region.setGunguCode(Integer.valueOf(x.getOrgCd()));
region.setGunguName(x.getOrgdownNm());
return region;
})
.collect(Collectors.toList());
}
private List<Shelter> shelterTransform(RegionItem regionItem) {
List<RegionItem> regionItems = this.govDataService.readSidoItems();
String sidoName = regionItems.stream()
.filter(x -> x.getOrgCd()
.equals(regionItem.getUprCd()))
.map(RegionItem::getOrgdownNm)
.findFirst()
.get();
return this.govDataService.readShelterItems(regionItem.getUprCd(), regionItem.getOrgCd())
.stream()
.map(x -> {
Region region = new Region();
region.setSidoCode(Integer.valueOf(regionItem.getUprCd()));
region.setSidoName(sidoName);
region.setGunguCode(Integer.valueOf(regionItem.getOrgCd()));
region.setGunguName(regionItem.getOrgdownNm());
Shelter shelter = new Shelter();
shelter.setRegion(region);
shelter.setCode(x.getCareRegNo());
shelter.setName(x.getCareNm());
return shelter;
})
.collect(Collectors.toList());
}
private String convertWeight(String weight) {
if (isEmpty(weight)) {
return "-1";
}
if (weight.contains("(Kg)")) {
weight = weight.replace("(Kg)", "");
try {
Float.valueOf(weight);
} catch (NumberFormatException nfe) {
weight = "-1";
}
}
return weight;
}
private String convertAge(String age) {
String result = age.replace(" ", "");
if (isEmpty(result) || isAllBlank(result)) {
return "-1";
}
if (result.contains("(년생)")) {
return result.replace("(년생)", "");
}
return result;
}
}
| true
|
c37c6aeeade5664359d1ddbcd16f08dee4b98c61
|
Java
|
liushengmz/scpc
|
/SjDataSplit/src/com/system/model/BaseRequestModel.java
|
UTF-8
| 2,048
| 1.992188
| 2
|
[] |
no_license
|
package com.system.model;
public class BaseRequestModel
{
private int cpId;
private int spTroneId;
private String cpParams;
private int price;
private String imei;
private String imsi;
private String phoneNum;
private String packageName;
private String androidVersion;
private String netType;
private String ip;
private String clientIp;
private int lac;
private int cid;
public int getLac()
{
return lac;
}
public void setLac(int lac)
{
this.lac = lac;
}
public int getCid()
{
return cid;
}
public void setCid(int cid)
{
this.cid = cid;
}
public int getCpId()
{
return cpId;
}
public void setCpId(int cpId)
{
this.cpId = cpId;
}
public int getSpTroneId()
{
return spTroneId;
}
public void setSpTroneId(int spTroneId)
{
this.spTroneId = spTroneId;
}
public String getCpParams()
{
return cpParams;
}
public void setCpParams(String cpParams)
{
this.cpParams = cpParams;
}
public int getPrice()
{
return price;
}
public void setPrice(int price)
{
this.price = price;
}
public String getImei()
{
return imei;
}
public void setImei(String imei)
{
this.imei = imei;
}
public String getImsi()
{
return imsi;
}
public void setImsi(String imsi)
{
this.imsi = imsi;
}
public String getPhoneNum()
{
return phoneNum;
}
public void setPhoneNum(String phoneNum)
{
this.phoneNum = phoneNum;
}
public String getPackageName()
{
return packageName;
}
public void setPackageName(String packageName)
{
this.packageName = packageName;
}
public String getNetType()
{
return netType;
}
public void setNetType(String netType)
{
this.netType = netType;
}
public String getIp()
{
return ip;
}
public void setIp(String ip)
{
this.ip = ip;
}
public String getClientIp()
{
return clientIp;
}
public void setClientIp(String clientIp)
{
this.clientIp = clientIp;
}
public String getAndroidVersion()
{
return androidVersion;
}
public void setAndroidVersion(String androidVersion)
{
this.androidVersion = androidVersion;
}
}
| true
|
a7e1316dde470c4034df98a7604f32e832ba153e
|
Java
|
amilevich/0715JavaUSF
|
/PetsFrontController/src/main/java/com/example/controller/LoginController.java
|
UTF-8
| 846
| 2.8125
| 3
|
[] |
no_license
|
package com.example.controller;
import javax.servlet.http.HttpServletRequest;
import com.example.dao.PetDaoImpl;
import com.example.model.Pet;
public class LoginController {
public static String Login(HttpServletRequest request) {
String name = request.getParameter("name");
String type = request.getParameter("type");
PetDaoImpl petDaoImpl = new PetDaoImpl();
Pet pet = new Pet();
pet = petDaoImpl.selectPetByName(name);
//we are retrieving an existing record by the pet's name
//that the user provided on the login page and storing it into
//a pet object
if(name.equals(pet.getName()) && type.equals(pet.getType())) {
//we are setting the session to the current logged in pet
request.getSession().setAttribute("Pet", pet);
return "/html/Home.html";
}
return "/html/Login.html";
}
}
| true
|
c9df60aed2a6408a9f0570be8ed828ed46160c16
|
Java
|
lboullo0/graviteeio-access-management
|
/gravitee-am-service/src/test/java/io/gravitee/am/service/model/PatchClientTest.java
|
UTF-8
| 2,351
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.am.service.model;
import io.gravitee.am.model.oidc.Client;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.Optional;
import static org.junit.Assert.*;
/**
* @author Alexandre FARIA (contact at alexandrefaria.net)
* @author GraviteeSource Team
*/
@RunWith(JUnit4.class)
public class PatchClientTest {
@Test
public void testPatch() {
//Build Object to patch
Client toPatch = new Client();
toPatch.setClientName("oldName");
toPatch.setClientSecret("expectedSecret");
toPatch.setCertificate("shouldDisappear");
toPatch.setAccessTokenValiditySeconds(7200);
toPatch.setRefreshTokenValiditySeconds(3600);
//Build patcher
PatchClient patcher = new PatchClient();
patcher.setClientName(Optional.of("expectedClientName"));
patcher.setCertificate(Optional.empty());
patcher.setAccessTokenValiditySeconds(Optional.of(14400));
patcher.setRefreshTokenValiditySeconds(Optional.empty());
//Apply patch
Client result = patcher.patch(toPatch, false);
//Checks
assertNotNull(result);
assertEquals("Client name should have been replaced","expectedClientName",result.getClientName());
assertEquals("Client secret should have been kept","expectedSecret", result.getClientSecret());
assertNull("Certificate should have been erased",result.getCertificate());
assertEquals("Access token validity should have been replaced",14400,result.getAccessTokenValiditySeconds());
assertEquals("Refresh token validity should have been removed",0, result.getRefreshTokenValiditySeconds());
}
}
| true
|
a7fa59271b86ac9683839f355675dd49fbeb2d54
|
Java
|
lvliangxiong/gof23-examples
|
/src/main/java/com/joey/learning/gof23/creational/builder/JoeyAirshipBuilder.java
|
UTF-8
| 617
| 2.609375
| 3
|
[] |
no_license
|
package com.joey.learning.gof23.creational.builder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JoeyAirshipBuilder implements AirshipBuilder {
@Override
public Engine buildEngine() {
log.info("构建发动机");
return new Engine("Joey 牌发动机!");
}
@Override
public EscapeTower buildEscapeTower() {
log.info("构建逃逸塔");
return new EscapeTower("Joey 牌逃逸塔");
}
@Override
public OrbitalModule BuildOrbitalModule() {
log.info("构建轨道舱");
return new OrbitalModule("Joey 牌轨道舱");
}
}
| true
|
368916b5d255f2953244f4aa8a2c1dd4c12eef6a
|
Java
|
ifplusor/infoweb
|
/src/main/java/psn/ifplusor/infoweb/security/Service/UserService.java
|
UTF-8
| 1,030
| 2.265625
| 2
|
[] |
no_license
|
package psn.ifplusor.infoweb.security.Service;
import javax.annotation.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import psn.ifplusor.infoweb.security.persistence.User;
import psn.ifplusor.infoweb.security.persistence.UserDao;
@Service
public class UserService {
@Resource(name = "UserDao")
private UserDao userDao;
public User getUserByName(String username) {
return userDao.getUserByName(username);
}
public User getCurrentUser() {
return getUserByName(getCurrentUserDetails().getUsername());
}
private UserDetails getCurrentUserDetails() {
return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
public boolean existUser(String username) {
return getUserByName(username) != null;
}
public boolean registerUser(String username, String password) {
return userDao.addUser(username, password);
}
}
| true
|
4ea51d7e9210a310a79d16fde7d6a1af70db0ecc
|
Java
|
ecologylab/simplJava
|
/SimplTutorial/src/ecologylab/tutorials/rss/MonomorphicJavaTutorial.java
|
UTF-8
| 2,227
| 2.796875
| 3
|
[] |
no_license
|
package ecologylab.tutorials.rss;
import ecologylab.tutorials.rss.*;
import java.io.IOException;
import ecologylab.serialization.*;
import ecologylab.serialization.formatenums.StringFormat;
import java.net.URL;
import ecologylab.net.*;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.net.MalformedURLException;
public class MonomorphicJavaTutorial {
public static void main(String[] args) throws Exception
{
SimplTypesScope rssTranslations = RssTranslations.get();
URL url = new URL("http://www.xkcd.com/rss.xml");
String rssContent = readURL(url);
System.out.println("Raw RSS Feed:");
System.out.println(rssContent);
Rss feed = (Rss) rssTranslations.deserialize(rssContent, StringFormat.XML);
System.out.println("\nFeed translated back to xml by s.im.pl serialization:");
System.out.println(SimplTypesScope.serialize(feed, StringFormat.XML));
Item ecologylabItem = new Item();
ecologylabItem.setTitle("The Interface Ecology Lab");
ecologylabItem.setDescription("Highlights the cool research going on at the lab.");
ecologylabItem.setAuthor("Dr. Andruid Kerne");
ecologylabItem.setLink(new ParsedURL(new URL("http://www.ecologylab.net")));
// feed.getChannel().getItems().add(0, ecologylabItem);
// System.out.println("\nFeed translated to xml with our added item:");
// System.out.println(feed.serialize());
}
public static String readURL(URL earl) throws MalformedURLException, IOException{
InputStream is = null;
DataInputStream dis;
String line;
StringBuilder sb = new StringBuilder();
try {
is = earl.openStream(); // throws an IOException
dis = new DataInputStream(new BufferedInputStream(is));
while ((line = dis.readLine()) != null) {
sb.append(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
return sb.toString();
}
}
| true
|
c023b5bd6a1854b5a33232f030bb4c8d847e0796
|
Java
|
johanneskoester/proteinhypernetworks
|
/ProteinHypernetwork/src/proteinhypernetwork/tasks/perturbation/PerturbationView.java
|
UTF-8
| 12,184
| 1.851563
| 2
|
[] |
no_license
|
/* Copyright (c) 2010, Johannes Köster <johannes.koester@tu-dortmund.de>
* All rights reserved.
*
* This software is open-source under the BSD license; see "license.txt"
* for a description.
*/
/*
* PerturbationView.java
*
* Created on 30.03.2010, 13:17:07
*/
package proteinhypernetwork.tasks.perturbation;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import proteinHypernetwork.NetworkEntity;
import proteinhypernetwork.Controller;
/**
*
* @author Johannes Köster <johannes.koester@tu-dortmund.de>
*/
public class PerturbationView extends javax.swing.JPanel {
/** Creates new form PerturbationView */
public PerturbationView() {
initComponents();
perturbationButton.setPreferredSize(undoPerturbationButton.getPreferredSize());
Controller.getInstance().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
entityListModel.setEntities(Controller.getInstance().getEntities());
perturbationListModel.setEntities(Controller.getInstance().getPerturbedEntities());
}
});
}
/** 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() {
java.awt.GridBagConstraints gridBagConstraints;
entityListModel = new proteinhypernetwork.tasks.perturbation.PerturbationListModel();
perturbationListModel = new proteinhypernetwork.tasks.perturbation.PerturbationListModel();
jScrollPane1 = new javax.swing.JScrollPane();
entityList = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
perturbationList = new javax.swing.JList();
perturbationButton = new javax.swing.JButton();
undoPerturbationButton = new javax.swing.JButton();
filterEntities = new javax.swing.JTextField();
filterPerturbations = new javax.swing.JTextField();
setName("Form"); // NOI18N
setLayout(new java.awt.GridBagLayout());
jScrollPane1.setName("jScrollPane1"); // NOI18N
entityList.setModel(entityListModel);
entityList.setName("entityList"); // NOI18N
jScrollPane1.setViewportView(entityList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
add(jScrollPane1, gridBagConstraints);
jScrollPane2.setName("jScrollPane2"); // NOI18N
perturbationList.setModel(perturbationListModel);
perturbationList.setName("perturbationList"); // NOI18N
jScrollPane2.setViewportView(perturbationList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
add(jScrollPane2, gridBagConstraints);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
perturbationButton.setText(resourceMap.getString("perturbationButton.text")); // NOI18N
perturbationButton.setName("perturbationButton"); // NOI18N
perturbationButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
perturbationButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
add(perturbationButton, gridBagConstraints);
undoPerturbationButton.setText(resourceMap.getString("undoPerturbationButton.text")); // NOI18N
undoPerturbationButton.setName("undoPerturbationButton"); // NOI18N
undoPerturbationButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
undoPerturbationButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
add(undoPerturbationButton, gridBagConstraints);
filterEntities.setText(resourceMap.getString("filterEntities.text")); // NOI18N
filterEntities.setName("filterEntities"); // NOI18N
filterEntities.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
filterEntitiesActionPerformed(evt);
}
});
filterEntities.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
filterEntitiesFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
filterEntitiesFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.5;
add(filterEntities, gridBagConstraints);
filterPerturbations.setText(resourceMap.getString("filterPerturbations.text")); // NOI18N
filterPerturbations.setName("filterPerturbations"); // NOI18N
filterPerturbations.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
filterPerturbationsActionPerformed(evt);
}
});
filterPerturbations.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
filterPerturbationsFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
filterPerturbationsFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.25;
add(filterPerturbations, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void perturbationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_perturbationButtonActionPerformed
for (int i : entityList.getSelectedIndices()) {
NetworkEntity e = (NetworkEntity) entityListModel.getElementAt(i);
Controller.getInstance().perturbation(e);
}
entityListModel.setEntities(Controller.getInstance().getEntities());
perturbationListModel.setEntities(Controller.getInstance().getPerturbedEntities());
}//GEN-LAST:event_perturbationButtonActionPerformed
private void undoPerturbationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_undoPerturbationButtonActionPerformed
for (int i : perturbationList.getSelectedIndices()) {
NetworkEntity e = (NetworkEntity) perturbationListModel.getElementAt(i);
Controller.getInstance().undoPerturbation(e);
}
entityListModel.setEntities(Controller.getInstance().getEntities());
perturbationListModel.setEntities(Controller.getInstance().getPerturbedEntities());
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
filterEntities.setText(resourceMap.getString("filterEntities.text"));
filterPerturbations.setText(resourceMap.getString("filterPerturbations.text"));
}//GEN-LAST:event_undoPerturbationButtonActionPerformed
private void filterEntitiesFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_filterEntitiesFocusLost
if (!entityListModel.isFiltered()) {
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
filterEntities.setText(resourceMap.getString("filterEntities.text"));
}
}//GEN-LAST:event_filterEntitiesFocusLost
private void filterEntitiesFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_filterEntitiesFocusGained
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
if (filterEntities.getText().equals(resourceMap.getString("filterEntities.text"))) {
filterEntities.setText("");
}
}//GEN-LAST:event_filterEntitiesFocusGained
private void filterPerturbationsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_filterPerturbationsFocusGained
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
if (filterPerturbations.getText().equals(resourceMap.getString("filterPerturbations.text"))) {
filterPerturbations.setText("");
}
}//GEN-LAST:event_filterPerturbationsFocusGained
private void filterPerturbationsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_filterPerturbationsFocusLost
if (!perturbationListModel.isFiltered()) {
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
filterPerturbations.setText(resourceMap.getString("filterPerturbations.text"));
}
}//GEN-LAST:event_filterPerturbationsFocusLost
private void filterEntitiesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterEntitiesActionPerformed
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
if(!filterEntities.getText().equals(resourceMap.getString("filterEntities.text")))
entityListModel.filter(filterEntities.getText());
}//GEN-LAST:event_filterEntitiesActionPerformed
private void filterPerturbationsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterPerturbationsActionPerformed
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proteinhypernetwork.ProteinHypernetworkApp.class).getContext().getResourceMap(PerturbationView.class);
if(!filterPerturbations.getText().equals(resourceMap.getString("filterPerturbations.text")))
perturbationListModel.filter(filterPerturbations.getText());
}//GEN-LAST:event_filterPerturbationsActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JList entityList;
private proteinhypernetwork.tasks.perturbation.PerturbationListModel entityListModel;
private javax.swing.JTextField filterEntities;
private javax.swing.JTextField filterPerturbations;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton perturbationButton;
private javax.swing.JList perturbationList;
private proteinhypernetwork.tasks.perturbation.PerturbationListModel perturbationListModel;
private javax.swing.JButton undoPerturbationButton;
// End of variables declaration//GEN-END:variables
}
| true
|
0db2ee0d3ff5738b0125f493d817d65d5d64b744
|
Java
|
nassimus26/FooBarQix_Kata
|
/src/sg/code/converter/KataConverter.java
|
UTF-8
| 1,456
| 3.28125
| 3
|
[] |
no_license
|
package sg.code.converter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by Nassim MOUALEK on 18/03/2016.
* Default implementation for IntConverter (Kata)
*/
public class KataConverter implements IntConverter{
public enum KataValues {Foo, Bar, Qix}
public static Map<Integer, KataValues> intToStrMap = new LinkedHashMap<Integer, KataValues>();
public static Map<Character, KataValues> charToStrMap = new LinkedHashMap<Character, KataValues>();
static{
intToStrMap.put( 3, KataValues.Foo );
intToStrMap.put( 5, KataValues.Bar );
intToStrMap.put( 7, KataValues.Qix );
charToStrMap.put( '3', KataValues.Foo );
charToStrMap.put( '5', KataValues.Bar );
charToStrMap.put( '7', KataValues.Qix );
}
@Override
public String convert(Integer i) {
StringBuilder sb = new StringBuilder();
String i_asString = i.toString();
List<Character> i_asListOfChars = i_asString.chars().mapToObj(e->(char)e).collect(Collectors.toList());
intToStrMap.forEach( (k, v)-> {
if (i%k==0)
sb.append(v);} );
i_asListOfChars.stream().forEach( (c)-> {
KataValues kv = charToStrMap.get(c);
if (kv!=null)
sb.append(kv);
});
if (sb.length()==0)
return i_asString;
return sb.toString();
}
}
| true
|
30f69a73e36606394d861795e62927f9796d2eb2
|
Java
|
slvrookie/sea-of-ql
|
/ckonig/QLJava/src/org/uva/sea/ql/test/TestFields.java
|
UTF-8
| 2,518
| 2.671875
| 3
|
[] |
no_license
|
package org.uva.sea.ql.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.uva.sea.ql.ast.elements.Ident;
import org.uva.sea.ql.ast.expressions.Expr;
import org.uva.sea.ql.ast.literals.IntLiteral;
import org.uva.sea.ql.ast.literals.StringLiteral;
import org.uva.sea.ql.parser.ParseError;
public class TestFields extends TestExpressions {
public TestFields(){
super();
}
@Test
public final void testIds() throws ParseError {
final Class<?> c = Ident.class;
testId("a", c);
testId("aBC", c);
testId("bBCdEF", c);
testId("abc2303", c);
testId("u32bcj2a", c);
}
private void testId(String id, Class<?> c) throws ParseError {
final Expr e = parser.parse(id);
assertNotNull("result was null", e);
assertEquals(c, e.getClass());
}
@Test
public final void testNums() throws ParseError {
assertEquals(IntLiteral.class, parser.parse("0").getClass());
assertEquals(IntLiteral.class, parser.parse("1223").getClass());
assertEquals(IntLiteral.class, parser.parse("234234234").getClass());
}
@Test
public final void testString() throws ParseError {
for (String s : getTestStrings()) {
this.testString(s, false);
}
}
@Test
public final void testStringValues() throws ParseError {
for (String s : getTestStrings()) {
this.testString(s, true);
}
}
private static final String[] getTestStrings() {
final String[] ret = { "\"a\"", "\"1223\"", "\"2342 34234\"",
"\"aBc\"", "\"abc 2323\"", "\"a2bc232aa\"", };
return ret;
}
private void testString(String in, boolean testValue) throws ParseError {
final Expr e = parser.parse(in);
assertEquals(StringLiteral.class, e.getClass());
if (testValue) {
final StringLiteral s = (StringLiteral) e;
assertEquals(in.replace("\"", ""), s.getValue());
}
}
@Test
public final void testInlineComment() throws ParseError {
final Expr e = parser.parse("//this is a comment\n");
assertEquals(null, e);
}
@Test
public final void testComment() throws ParseError {
final Expr e = parser.parse("/* this is a comment /*");
assertEquals(null, e);
}
}
| true
|
6ffaaef78c527c8bfb1995186573a470ff3b308c
|
Java
|
carin-alliance/cpcds-server-ri
|
/src/main/java/ca/uhn/fhir/jpa/starter/PatientAuthorizationInterceptor.java
|
UTF-8
| 5,593
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ca.uhn.fhir.jpa.starter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.IdType;
import ca.uhn.fhir.jpa.starter.authorization.OauthEndpointController;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.server.exceptions.AuthenticationException;
import ca.uhn.fhir.rest.server.interceptor.auth.AuthorizationInterceptor;
import ca.uhn.fhir.rest.server.interceptor.auth.IAuthRule;
import ca.uhn.fhir.rest.server.interceptor.auth.RuleBuilder;
@SuppressWarnings("ConstantConditions")
public class PatientAuthorizationInterceptor extends AuthorizationInterceptor {
private static final Logger logger = ServerLogger.getLogger();
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {
String authHeader = theRequestDetails.getHeader("Authorization");
if (authHeader != null) {
// Get the JWT token from the Authorization header
String regex = "Bearer (.*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(authHeader);
String token = "";
if (matcher.find() && matcher.groupCount() == 1) {
token = matcher.group(1);
String adminToken = System.getenv("ADMIN_TOKEN");
if (adminToken != null && token.equals(adminToken)) {
return adminAuthorizedRule();
} else {
try {
IIdType patientId = verify(token, theRequestDetails.getFhirServerBase());
if (patientId == null) return unauthorizedRule();
else if (patientId.getIdPart().equals("admin")) return adminAuthorizedRule();
else return authorizedRule(patientId);
} catch (SignatureVerificationException e) {
String message = "Authorization failed: invalid signature";
logger.log(Level.SEVERE, message, e);
throw new AuthenticationException(message, e);
} catch (TokenExpiredException e) {
String message = "Authorization failed: access token expired";
logger.log(Level.SEVERE, message, e);
throw new AuthenticationException(message, e);
} catch (Exception e) {
String message = "Authorization failed";
logger.log(Level.SEVERE, message, e);
throw new AuthenticationException(message, e);
}
}
} else {
throw new AuthenticationException(
"Authorization header is not in the form \"Bearer <token>\"");
}
}
return unauthorizedRule();
}
private List<IAuthRule> adminAuthorizedRule() {
return new RuleBuilder().allowAll().build();
}
private List<IAuthRule> authorizedRule(IIdType userIdPatientId) {
return new RuleBuilder().allow().read().resourcesOfType("Coverage").inCompartment("Patient", userIdPatientId)
.andThen().allow().read().resourcesOfType("ExplanationOfBenefit").inCompartment("Patient", userIdPatientId)
.andThen().allow().read().resourcesOfType("Patient").inCompartment("Patient", userIdPatientId)
.andThen().allow().read().resourcesOfType("Practitioner").withAnyId()
.andThen().allow().read().resourcesOfType("PractitionerRole").withAnyId()
.andThen().allow().read().resourcesOfType("Organization").withAnyId()
.andThen().allow().read().resourcesOfType("OrganizationAffiliation").withAnyId()
.andThen().allow().read().resourcesOfType("MedicationKnowledge").withAnyId()
.andThen().allow().read().resourcesOfType("List").withAnyId()
.andThen().allow().read().resourcesOfType("Location").withAnyId()
.andThen().allow().read().resourcesOfType("HealthcareService").withAnyId()
.andThen().allow().metadata().andThen().denyAll()
.build();
}
private List<IAuthRule> unauthorizedRule() {
// By default, deny everything except the metadata. This is for
// unathorized users
return new RuleBuilder().allow().metadata().andThen().denyAll().build();
}
private IIdType verify(String token, String fhirBase) throws SignatureVerificationException, TokenExpiredException, JWTVerificationException {
Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
logger.fine("Verifying JWT token ISS and AUD is " + fhirBase);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(fhirBase)
.withAudience(fhirBase).build();
DecodedJWT jwt = verifier.verify(token);
String patientId = jwt.getClaim("patient_id").asString();
if (patientId != null) return new IdType("Patient", patientId);
else return null;
}
}
| true
|
91ab817dcc0a86b242875fab47ecce08e3c94447
|
Java
|
syntelos/sim-pic
|
/mach/src/lib/mach/Bit.java
|
UTF-8
| 355
| 2.515625
| 3
|
[] |
no_license
|
package lib.mach;
public class Bit
extends Object
{
public final AbstractMachine machine;
public final Register register;
public final String name;
public final int number;
public Bit(AbstractMachine m, Register r, String n, int b){
super();
this.machine = m;
this.register = r;
this.name = n;
this.number = b;
}
}
| true
|
3992ccd2dd03e67ea60a0c5e853377b24a194456
|
Java
|
Claude91/Wms-base
|
/version_b/src/main/java/com/shqtn/b/enter/AbstractBTakeBoxChild.java
|
UTF-8
| 928
| 1.765625
| 2
|
[] |
no_license
|
package com.shqtn.b.enter;
import android.support.annotation.NonNull;
import com.shqtn.b.enter.result.BTakeBoxManifest;
import com.shqtn.base.bean.enter.TakeBoxGoods;
import com.shqtn.base.bean.enter.TakeBoxPlan;
import com.shqtn.base.bean.params.TakeBoxSubmitParams;
import com.shqtn.enter.presenter.AbstractTakeBoxChild;
/**
* 创建时间:2018/1/19
* 描述:
*
* @author ql
*/
public abstract class AbstractBTakeBoxChild<T, P extends TakeBoxSubmitParams> extends AbstractTakeBoxChild<T, P> {
BTakeBoxManifest mOpearetManifest;
public AbstractBTakeBoxChild(@NonNull TakeBoxPlan takeBoxGoodsPlan, @NonNull TakeBoxGoods takeBoxGoods) {
super(takeBoxGoodsPlan, takeBoxGoods);
}
public BTakeBoxManifest getOpearetManifest() {
return mOpearetManifest;
}
public void setOpearetManifest(BTakeBoxManifest opearetManifest) {
this.mOpearetManifest = opearetManifest;
}
}
| true
|
722525e3f51338e99ba289029c810ba34b8a9f67
|
Java
|
404-bug-not-found/100_percent_capstone
|
/src/main/java/com/hundred/percent/capstone/Invoicify/company/entity/CompanyEntity.java
|
UTF-8
| 1,194
| 2.25
| 2
|
[] |
no_license
|
package com.hundred.percent.capstone.Invoicify.company.entity;
import com.hundred.percent.capstone.Invoicify.address.entity.AddressEntity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
@Entity
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode
public class CompanyEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
@NotNull
String invoiceNumber;
@NotNull
String name;
@NotNull
String contactName;
@NotNull
String contactTitle;
@NotNull
String contactPhoneNumber;
@OneToMany(mappedBy = "companyEntity", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
List<AddressEntity> addresses;
public CompanyEntity(String invoiceNumber, String name, String contactName, String contactTitle, String contactPhoneNumber) {
super();
this.invoiceNumber = invoiceNumber;
this.name = name;
this.contactName = contactName;
this.contactTitle = contactTitle;
this.contactPhoneNumber = contactPhoneNumber;
}
}
| true
|
3fc4c1b687c9a91f5683e7cac5a68714db112adc
|
Java
|
sgros/activity_flow_plugin
|
/TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/Procyon/src/main/java/com/google/android/exoplayer2/extractor/ts/H264Reader.java
|
UTF-8
| 24,484
| 1.59375
| 2
|
[] |
no_license
|
//
// Decompiled by Procyon v0.5.34
//
package com.google.android.exoplayer2.extractor.ts;
import android.util.SparseArray;
import com.google.android.exoplayer2.util.ParsableNalUnitBitArray;
import com.google.android.exoplayer2.extractor.ExtractorOutput;
import com.google.android.exoplayer2.drm.DrmInitData;
import java.util.List;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.util.CodecSpecificDataUtil;
import com.google.android.exoplayer2.util.NalUnitUtil;
import java.util.Arrays;
import java.util.ArrayList;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.extractor.TrackOutput;
public final class H264Reader implements ElementaryStreamReader
{
private final boolean allowNonIdrKeyframes;
private final boolean detectAccessUnits;
private String formatId;
private boolean hasOutputFormat;
private TrackOutput output;
private long pesTimeUs;
private final NalUnitTargetBuffer pps;
private final boolean[] prefixFlags;
private boolean randomAccessIndicator;
private SampleReader sampleReader;
private final NalUnitTargetBuffer sei;
private final SeiReader seiReader;
private final ParsableByteArray seiWrapper;
private final NalUnitTargetBuffer sps;
private long totalBytesWritten;
public H264Reader(final SeiReader seiReader, final boolean allowNonIdrKeyframes, final boolean detectAccessUnits) {
this.seiReader = seiReader;
this.allowNonIdrKeyframes = allowNonIdrKeyframes;
this.detectAccessUnits = detectAccessUnits;
this.prefixFlags = new boolean[3];
this.sps = new NalUnitTargetBuffer(7, 128);
this.pps = new NalUnitTargetBuffer(8, 128);
this.sei = new NalUnitTargetBuffer(6, 128);
this.seiWrapper = new ParsableByteArray();
}
private void endNalUnit(final long n, final int n2, int unescapeStream, final long n3) {
if (!this.hasOutputFormat || this.sampleReader.needsSpsPps()) {
this.sps.endNalUnit(unescapeStream);
this.pps.endNalUnit(unescapeStream);
if (!this.hasOutputFormat) {
if (this.sps.isCompleted() && this.pps.isCompleted()) {
final ArrayList<byte[]> list = new ArrayList<byte[]>();
final NalUnitTargetBuffer sps = this.sps;
list.add(Arrays.copyOf(sps.nalData, sps.nalLength));
final NalUnitTargetBuffer pps = this.pps;
list.add(Arrays.copyOf(pps.nalData, pps.nalLength));
final NalUnitTargetBuffer sps2 = this.sps;
final NalUnitUtil.SpsData spsNalUnit = NalUnitUtil.parseSpsNalUnit(sps2.nalData, 3, sps2.nalLength);
final NalUnitTargetBuffer pps2 = this.pps;
final NalUnitUtil.PpsData ppsNalUnit = NalUnitUtil.parsePpsNalUnit(pps2.nalData, 3, pps2.nalLength);
this.output.format(Format.createVideoSampleFormat(this.formatId, "video/avc", CodecSpecificDataUtil.buildAvcCodecString(spsNalUnit.profileIdc, spsNalUnit.constraintsFlagsAndReservedZero2Bits, spsNalUnit.levelIdc), -1, -1, spsNalUnit.width, spsNalUnit.height, -1.0f, list, -1, spsNalUnit.pixelWidthAspectRatio, null));
this.hasOutputFormat = true;
this.sampleReader.putSps(spsNalUnit);
this.sampleReader.putPps(ppsNalUnit);
this.sps.reset();
this.pps.reset();
}
}
else if (this.sps.isCompleted()) {
final NalUnitTargetBuffer sps3 = this.sps;
this.sampleReader.putSps(NalUnitUtil.parseSpsNalUnit(sps3.nalData, 3, sps3.nalLength));
this.sps.reset();
}
else if (this.pps.isCompleted()) {
final NalUnitTargetBuffer pps3 = this.pps;
this.sampleReader.putPps(NalUnitUtil.parsePpsNalUnit(pps3.nalData, 3, pps3.nalLength));
this.pps.reset();
}
}
if (this.sei.endNalUnit(unescapeStream)) {
final NalUnitTargetBuffer sei = this.sei;
unescapeStream = NalUnitUtil.unescapeStream(sei.nalData, sei.nalLength);
this.seiWrapper.reset(this.sei.nalData, unescapeStream);
this.seiWrapper.setPosition(4);
this.seiReader.consume(n3, this.seiWrapper);
}
if (this.sampleReader.endNalUnit(n, n2, this.hasOutputFormat, this.randomAccessIndicator)) {
this.randomAccessIndicator = false;
}
}
private void nalUnitData(final byte[] array, final int n, final int n2) {
if (!this.hasOutputFormat || this.sampleReader.needsSpsPps()) {
this.sps.appendToNalUnit(array, n, n2);
this.pps.appendToNalUnit(array, n, n2);
}
this.sei.appendToNalUnit(array, n, n2);
this.sampleReader.appendToNalUnit(array, n, n2);
}
private void startNalUnit(final long n, final int n2, final long n3) {
if (!this.hasOutputFormat || this.sampleReader.needsSpsPps()) {
this.sps.startNalUnit(n2);
this.pps.startNalUnit(n2);
}
this.sei.startNalUnit(n2);
this.sampleReader.startNalUnit(n, n2, n3);
}
@Override
public void consume(final ParsableByteArray parsableByteArray) {
int position = parsableByteArray.getPosition();
final int limit = parsableByteArray.limit();
final byte[] data = parsableByteArray.data;
this.totalBytesWritten += parsableByteArray.bytesLeft();
this.output.sampleData(parsableByteArray, parsableByteArray.bytesLeft());
while (true) {
final int nalUnit = NalUnitUtil.findNalUnit(data, position, limit, this.prefixFlags);
if (nalUnit == limit) {
break;
}
final int nalUnitType = NalUnitUtil.getNalUnitType(data, nalUnit);
final int n = nalUnit - position;
if (n > 0) {
this.nalUnitData(data, position, nalUnit);
}
final int n2 = limit - nalUnit;
final long n3 = this.totalBytesWritten - n2;
int n4;
if (n < 0) {
n4 = -n;
}
else {
n4 = 0;
}
this.endNalUnit(n3, n2, n4, this.pesTimeUs);
this.startNalUnit(n3, nalUnitType, this.pesTimeUs);
position = nalUnit + 3;
}
this.nalUnitData(data, position, limit);
}
@Override
public void createTracks(final ExtractorOutput extractorOutput, final TsPayloadReader.TrackIdGenerator trackIdGenerator) {
trackIdGenerator.generateNewId();
this.formatId = trackIdGenerator.getFormatId();
this.output = extractorOutput.track(trackIdGenerator.getTrackId(), 2);
this.sampleReader = new SampleReader(this.output, this.allowNonIdrKeyframes, this.detectAccessUnits);
this.seiReader.createTracks(extractorOutput, trackIdGenerator);
}
@Override
public void packetFinished() {
}
@Override
public void packetStarted(final long pesTimeUs, int n) {
this.pesTimeUs = pesTimeUs;
final boolean randomAccessIndicator = this.randomAccessIndicator;
if ((n & 0x2) != 0x0) {
n = 1;
}
else {
n = 0;
}
this.randomAccessIndicator = (((randomAccessIndicator ? 1 : 0) | n) != 0x0);
}
@Override
public void seek() {
NalUnitUtil.clearPrefixFlags(this.prefixFlags);
this.sps.reset();
this.pps.reset();
this.sei.reset();
this.sampleReader.reset();
this.totalBytesWritten = 0L;
this.randomAccessIndicator = false;
}
private static final class SampleReader
{
private final boolean allowNonIdrKeyframes;
private final ParsableNalUnitBitArray bitArray;
private byte[] buffer;
private int bufferLength;
private final boolean detectAccessUnits;
private boolean isFilling;
private long nalUnitStartPosition;
private long nalUnitTimeUs;
private int nalUnitType;
private final TrackOutput output;
private final SparseArray<NalUnitUtil.PpsData> pps;
private SliceHeaderData previousSliceHeader;
private boolean readingSample;
private boolean sampleIsKeyframe;
private long samplePosition;
private long sampleTimeUs;
private SliceHeaderData sliceHeader;
private final SparseArray<NalUnitUtil.SpsData> sps;
public SampleReader(final TrackOutput output, final boolean allowNonIdrKeyframes, final boolean detectAccessUnits) {
this.output = output;
this.allowNonIdrKeyframes = allowNonIdrKeyframes;
this.detectAccessUnits = detectAccessUnits;
this.sps = (SparseArray<NalUnitUtil.SpsData>)new SparseArray();
this.pps = (SparseArray<NalUnitUtil.PpsData>)new SparseArray();
this.previousSliceHeader = new SliceHeaderData();
this.sliceHeader = new SliceHeaderData();
this.buffer = new byte[128];
this.bitArray = new ParsableNalUnitBitArray(this.buffer, 0, 0);
this.reset();
}
private void outputSample(final int n) {
this.output.sampleMetadata(this.sampleTimeUs, this.sampleIsKeyframe ? 1 : 0, (int)(this.nalUnitStartPosition - this.samplePosition), n, null);
}
public void appendToNalUnit(final byte[] array, int n, int n2) {
if (!this.isFilling) {
return;
}
final int n3 = n2 - n;
final byte[] buffer = this.buffer;
final int length = buffer.length;
n2 = this.bufferLength;
if (length < n2 + n3) {
this.buffer = Arrays.copyOf(buffer, (n2 + n3) * 2);
}
System.arraycopy(array, n, this.buffer, this.bufferLength, n3);
this.bufferLength += n3;
this.bitArray.reset(this.buffer, 0, this.bufferLength);
if (!this.bitArray.canReadBits(8)) {
return;
}
this.bitArray.skipBit();
final int bits = this.bitArray.readBits(2);
this.bitArray.skipBits(5);
if (!this.bitArray.canReadExpGolombCodedNum()) {
return;
}
this.bitArray.readUnsignedExpGolombCodedInt();
if (!this.bitArray.canReadExpGolombCodedNum()) {
return;
}
final int unsignedExpGolombCodedInt = this.bitArray.readUnsignedExpGolombCodedInt();
if (!this.detectAccessUnits) {
this.isFilling = false;
this.sliceHeader.setSliceType(unsignedExpGolombCodedInt);
return;
}
if (!this.bitArray.canReadExpGolombCodedNum()) {
return;
}
final int unsignedExpGolombCodedInt2 = this.bitArray.readUnsignedExpGolombCodedInt();
if (this.pps.indexOfKey(unsignedExpGolombCodedInt2) < 0) {
this.isFilling = false;
return;
}
final NalUnitUtil.PpsData ppsData = (NalUnitUtil.PpsData)this.pps.get(unsignedExpGolombCodedInt2);
final NalUnitUtil.SpsData spsData = (NalUnitUtil.SpsData)this.sps.get(ppsData.seqParameterSetId);
if (spsData.separateColorPlaneFlag) {
if (!this.bitArray.canReadBits(2)) {
return;
}
this.bitArray.skipBits(2);
}
if (!this.bitArray.canReadBits(spsData.frameNumLength)) {
return;
}
final int bits2 = this.bitArray.readBits(spsData.frameNumLength);
boolean bit = false;
boolean bit2 = false;
boolean b = false;
Label_0389: {
if (!spsData.frameMbsOnlyFlag) {
if (!this.bitArray.canReadBits(1)) {
return;
}
bit = this.bitArray.readBit();
if (bit) {
if (!this.bitArray.canReadBits(1)) {
return;
}
bit2 = this.bitArray.readBit();
b = true;
break Label_0389;
}
}
else {
bit = false;
}
b = false;
bit2 = false;
}
final boolean b2 = this.nalUnitType == 5;
int unsignedExpGolombCodedInt3;
if (b2) {
if (!this.bitArray.canReadExpGolombCodedNum()) {
return;
}
unsignedExpGolombCodedInt3 = this.bitArray.readUnsignedExpGolombCodedInt();
}
else {
unsignedExpGolombCodedInt3 = 0;
}
n = spsData.picOrderCountType;
int signedExpGolombCodedInt = 0;
int signedExpGolombCodedInt2 = 0;
Label_0600: {
Label_0597: {
Label_0594: {
if (n == 0) {
if (!this.bitArray.canReadBits(spsData.picOrderCntLsbLength)) {
return;
}
n = this.bitArray.readBits(spsData.picOrderCntLsbLength);
if (ppsData.bottomFieldPicOrderInFramePresentFlag && !bit) {
if (!this.bitArray.canReadExpGolombCodedNum()) {
return;
}
n2 = this.bitArray.readSignedExpGolombCodedInt();
break Label_0594;
}
}
else if (n == 1 && !spsData.deltaPicOrderAlwaysZeroFlag) {
if (!this.bitArray.canReadExpGolombCodedNum()) {
return;
}
signedExpGolombCodedInt = this.bitArray.readSignedExpGolombCodedInt();
if (!ppsData.bottomFieldPicOrderInFramePresentFlag || bit) {
n = 0;
n2 = 0;
break Label_0597;
}
if (!this.bitArray.canReadExpGolombCodedNum()) {
return;
}
signedExpGolombCodedInt2 = this.bitArray.readSignedExpGolombCodedInt();
n = 0;
n2 = 0;
break Label_0600;
}
else {
n = 0;
}
n2 = 0;
}
signedExpGolombCodedInt = 0;
}
signedExpGolombCodedInt2 = 0;
}
this.sliceHeader.setAll(spsData, bits, unsignedExpGolombCodedInt, bits2, unsignedExpGolombCodedInt2, bit, b, bit2, b2, unsignedExpGolombCodedInt3, n, n2, signedExpGolombCodedInt, signedExpGolombCodedInt2);
this.isFilling = false;
}
public boolean endNalUnit(final long n, int n2, final boolean b, boolean iSlice) {
final int nalUnitType = this.nalUnitType;
final int n3 = 0;
if (nalUnitType == 9 || (this.detectAccessUnits && this.sliceHeader.isFirstVclNalUnitOfPicture(this.previousSliceHeader))) {
if (b && this.readingSample) {
this.outputSample(n2 + (int)(n - this.nalUnitStartPosition));
}
this.samplePosition = this.nalUnitStartPosition;
this.sampleTimeUs = this.nalUnitTimeUs;
this.sampleIsKeyframe = false;
this.readingSample = true;
}
if (this.allowNonIdrKeyframes) {
iSlice = this.sliceHeader.isISlice();
}
final boolean sampleIsKeyframe = this.sampleIsKeyframe;
final int nalUnitType2 = this.nalUnitType;
if (nalUnitType2 != 5) {
n2 = n3;
if (!iSlice) {
return this.sampleIsKeyframe = (((sampleIsKeyframe ? 1 : 0) | n2) != 0x0);
}
n2 = n3;
if (nalUnitType2 != 1) {
return this.sampleIsKeyframe = (((sampleIsKeyframe ? 1 : 0) | n2) != 0x0);
}
}
n2 = 1;
return this.sampleIsKeyframe = (((sampleIsKeyframe ? 1 : 0) | n2) != 0x0);
}
public boolean needsSpsPps() {
return this.detectAccessUnits;
}
public void putPps(final NalUnitUtil.PpsData ppsData) {
this.pps.append(ppsData.picParameterSetId, (Object)ppsData);
}
public void putSps(final NalUnitUtil.SpsData spsData) {
this.sps.append(spsData.seqParameterSetId, (Object)spsData);
}
public void reset() {
this.isFilling = false;
this.readingSample = false;
this.sliceHeader.clear();
}
public void startNalUnit(final long nalUnitStartPosition, int nalUnitType, final long nalUnitTimeUs) {
this.nalUnitType = nalUnitType;
this.nalUnitTimeUs = nalUnitTimeUs;
this.nalUnitStartPosition = nalUnitStartPosition;
if (!this.allowNonIdrKeyframes || this.nalUnitType != 1) {
if (!this.detectAccessUnits) {
return;
}
nalUnitType = this.nalUnitType;
if (nalUnitType != 5 && nalUnitType != 1 && nalUnitType != 2) {
return;
}
}
final SliceHeaderData previousSliceHeader = this.previousSliceHeader;
this.previousSliceHeader = this.sliceHeader;
(this.sliceHeader = previousSliceHeader).clear();
this.bufferLength = 0;
this.isFilling = true;
}
private static final class SliceHeaderData
{
private boolean bottomFieldFlag;
private boolean bottomFieldFlagPresent;
private int deltaPicOrderCnt0;
private int deltaPicOrderCnt1;
private int deltaPicOrderCntBottom;
private boolean fieldPicFlag;
private int frameNum;
private boolean hasSliceType;
private boolean idrPicFlag;
private int idrPicId;
private boolean isComplete;
private int nalRefIdc;
private int picOrderCntLsb;
private int picParameterSetId;
private int sliceType;
private NalUnitUtil.SpsData spsData;
private boolean isFirstVclNalUnitOfPicture(final SliceHeaderData sliceHeaderData) {
final boolean isComplete = this.isComplete;
final boolean b = true;
if (isComplete) {
boolean b2 = b;
if (!sliceHeaderData.isComplete) {
return b2;
}
b2 = b;
if (this.frameNum != sliceHeaderData.frameNum) {
return b2;
}
b2 = b;
if (this.picParameterSetId != sliceHeaderData.picParameterSetId) {
return b2;
}
b2 = b;
if (this.fieldPicFlag != sliceHeaderData.fieldPicFlag) {
return b2;
}
if (this.bottomFieldFlagPresent && sliceHeaderData.bottomFieldFlagPresent) {
b2 = b;
if (this.bottomFieldFlag != sliceHeaderData.bottomFieldFlag) {
return b2;
}
}
final int nalRefIdc = this.nalRefIdc;
final int nalRefIdc2 = sliceHeaderData.nalRefIdc;
if (nalRefIdc != nalRefIdc2) {
b2 = b;
if (nalRefIdc == 0) {
return b2;
}
b2 = b;
if (nalRefIdc2 == 0) {
return b2;
}
}
if (this.spsData.picOrderCountType == 0 && sliceHeaderData.spsData.picOrderCountType == 0) {
b2 = b;
if (this.picOrderCntLsb != sliceHeaderData.picOrderCntLsb) {
return b2;
}
b2 = b;
if (this.deltaPicOrderCntBottom != sliceHeaderData.deltaPicOrderCntBottom) {
return b2;
}
}
if (this.spsData.picOrderCountType == 1 && sliceHeaderData.spsData.picOrderCountType == 1) {
b2 = b;
if (this.deltaPicOrderCnt0 != sliceHeaderData.deltaPicOrderCnt0) {
return b2;
}
b2 = b;
if (this.deltaPicOrderCnt1 != sliceHeaderData.deltaPicOrderCnt1) {
return b2;
}
}
final boolean idrPicFlag = this.idrPicFlag;
final boolean idrPicFlag2 = sliceHeaderData.idrPicFlag;
b2 = b;
if (idrPicFlag != idrPicFlag2) {
return b2;
}
if (idrPicFlag && idrPicFlag2 && this.idrPicId != sliceHeaderData.idrPicId) {
b2 = b;
return b2;
}
}
return false;
}
public void clear() {
this.hasSliceType = false;
this.isComplete = false;
}
public boolean isISlice() {
if (this.hasSliceType) {
final int sliceType = this.sliceType;
if (sliceType == 7 || sliceType == 2) {
return true;
}
}
return false;
}
public void setAll(final NalUnitUtil.SpsData spsData, final int nalRefIdc, final int sliceType, final int frameNum, final int picParameterSetId, final boolean fieldPicFlag, final boolean bottomFieldFlagPresent, final boolean bottomFieldFlag, final boolean idrPicFlag, final int idrPicId, final int picOrderCntLsb, final int deltaPicOrderCntBottom, final int deltaPicOrderCnt0, final int deltaPicOrderCnt2) {
this.spsData = spsData;
this.nalRefIdc = nalRefIdc;
this.sliceType = sliceType;
this.frameNum = frameNum;
this.picParameterSetId = picParameterSetId;
this.fieldPicFlag = fieldPicFlag;
this.bottomFieldFlagPresent = bottomFieldFlagPresent;
this.bottomFieldFlag = bottomFieldFlag;
this.idrPicFlag = idrPicFlag;
this.idrPicId = idrPicId;
this.picOrderCntLsb = picOrderCntLsb;
this.deltaPicOrderCntBottom = deltaPicOrderCntBottom;
this.deltaPicOrderCnt0 = deltaPicOrderCnt0;
this.deltaPicOrderCnt1 = deltaPicOrderCnt2;
this.isComplete = true;
this.hasSliceType = true;
}
public void setSliceType(final int sliceType) {
this.sliceType = sliceType;
this.hasSliceType = true;
}
}
}
}
| true
|
097043e49081be18510560dd124941bd7b4e04c7
|
Java
|
sengeiou/ISportTracker
|
/app/src/main/java/com/isport/tracker/bluetooth/BootstrapService.java
|
UTF-8
| 4,673
| 1.875
| 2
|
[] |
no_license
|
package com.isport.tracker.bluetooth;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import com.isport.tracker.R;
import com.isport.tracker.main.MainActivityGroup;
/**
* Created by feige on 2017/5/26.
*/
public class BootstrapService extends Service {
@Override
public void onCreate() {
super.onCreate();
startForeground(this);
stopSelf();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
public static void startForeground(Service context) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE) != PackageManager
.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder builder = new Notification.Builder(context.getApplicationContext()); //获取一个Notification构造器
Intent nfIntent = new Intent(context, MainActivityGroup.class);
builder.setContentIntent(PendingIntent.getActivity(context, 0, nfIntent, 0)) // 设置 PendingIntent
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo_isport)) // 设置下拉列表中的图标(大图标)
.setContentTitle(context.getString(R.string.app_name)) // 设置下拉列表里的标题
.setSmallIcon(R.drawable.logo_isport) // 设置状态栏内的小图标
.setContentText("") // 设置上下文内容
.setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//修改安卓8.1以上系统报错
NotificationChannel notificationChannel = new NotificationChannel("notification_id", "bonlala", NotificationManager.IMPORTANCE_MIN);
notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯
notificationChannel.setShowBadge(false);//是否显示角标
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
builder.setChannelId("notification_id");
}
Notification notification = builder.build(); // 获取构建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
// 参数一:唯一的通知标识;参数二:通知消息。
context.startForeground(112, notification);// 开始前台服务
}
} else {
}
} catch (Exception e) {
}
/* NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notif = builder
.setContentText(context.getString(R.string.application_keep_running))
.setContentTitle(context.getString(R.string.app_name))
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.logo_isport)
.build();
//notif.contentIntent = pendingIntent;
notif.flags |= Notification.FLAG_NO_CLEAR; // 点击清除按钮时就会清除消息通知,但是点击通知栏的通知时不会消失
//notif.flags |= Notification.FLAG_ONGOING_EVENT;
notif.flags |= Notification.FLAG_FOREGROUND_SERVICE;
notif.flags |= Notification.FLAG_AUTO_CANCEL;
//notif.contentIntent =
context.startForeground(112, notif);*/
}
}
| true
|
dac010cc471008367f12d688e562accaf13fe977
|
Java
|
gitter-badger/reminders-android
|
/app/src/main/java/com/vinkas/reminders/MainActivity.java
|
UTF-8
| 4,218
| 2.203125
| 2
|
[] |
no_license
|
package com.vinkas.reminders;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TimePicker;
import vinkas.app.NavigationDrawerActivity;
import vinkas.io.reminders.ListItem;
import vinkas.io.reminders.open.Database;
import vinkas.io.reminders.open.List;
/**
* Created by Vinoth on 6-5-16.
*/
public class MainActivity extends NavigationDrawerActivity {
public List getReminders() {
return getDatabase().getReminders();
}
@Override
public Application getApp() {
return (Application) super.getApp();
}
@Override
public Database getDatabase() {
return (Database) super.getDatabase();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLayout(R.layout.activity_main);
setMenu(R.menu.activity_main);
setNavigationMenu(R.menu.activity_main_drawer);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
return super.onNavigationItemSelected(item);
}
private ListItem reminder;
DatePickerDialog dpDialog;
TimePickerDialog tpDialog;
EditText etTitle, etDate, etTime;
@Override
public void setContent(View content) {
super.setContent(content);
popHolder = (RelativeLayout) getContent().findViewById(R.id.popHolder);
etTitle = (EditText) getContent().findViewById(R.id.etTitle);
etDate = (EditText) getContent().findViewById(R.id.etDate);
etTime = (EditText) getContent().findViewById(R.id.etTime);
etDate.setInputType(InputType.TYPE_NULL);
etTime.setInputType(InputType.TYPE_NULL);
dpDialog = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
MainActivity.this.year = year;
month = monthOfYear;
day = dayOfMonth;
etDate.setText(dayOfMonth + " / " + monthOfYear + " / " + year);
tpDialog.show();
}
}, 2016, 10, 10);
tpDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
min = minute;
etTime.setText(hourOfDay + " : " + minute);
}
}, 1, 1, false);
etDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
dpDialog.show();
}
}
});
etTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
tpDialog.show();
}
});
}
@Override
public void onClick(View v) {
super.onClick(v);
if (v.getId() == R.id.add) {
addReminder(v);
}
}
public void newReminder() {
etTitle.setText("");
etDate.setText("");
etTime.setText("");
year = month = day = hour = min = 0;
}
private int year, month, day, hour, min;
public void addReminder(View v) {
reminder = getReminders().create(etTitle.getText().toString(), day, month, year, hour, min);
popHolder.setVisibility(View.GONE);
getFab().setVisibility(View.VISIBLE);
}
RelativeLayout popHolder;
@Override
public void onFabClick(View v) {
newReminder();
popHolder.setVisibility(View.VISIBLE);
v.setVisibility(View.GONE);
}
}
| true
|
4e513bfe696bd8bad0db5b246d22eecefe885bc1
|
Java
|
KANG-SEONGHYEON/bitcamp
|
/java-prepare/src/main/java/bitcamp/java100/Pre17_17/step06/Rect.java
|
UTF-8
| 324
| 3.125
| 3
|
[] |
no_license
|
package bitcamp.java100.Pre17_17.step06;
public class Rect {
int width;
int height;
// 평방미터를 구하는 메서드
/*static*/ float area() {
return (this.width * this.height) / 10000f;
}
// 평을 구하는 메서드
/*static*/ float pyeong() {
return (this.width * this.height) / 10000f / 3.3f;
}
}
| true
|
457ed85ab4870158e717ba250832640b7d9640af
|
Java
|
michbarsinai/BP-javascript-search
|
/BP-javascript/src/bp/eventsets/HashEventSet.java
|
UTF-8
| 1,101
| 2.875
| 3
|
[] |
no_license
|
package bp.eventsets;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
@SuppressWarnings("serial")
public class HashEventSet extends HashSet<EventSet> implements
EventSet, Serializable {
private String name = null;
public HashEventSet(EventSet... eSetInterfaces) {
super();
for (EventSet eSetInterface : eSetInterfaces) {
add(eSetInterface);
}
}
public HashEventSet(String name, EventSet... eSetInterfaces) {
this(eSetInterfaces);
this.setName(name);
}
public boolean contains(Object o) {
Iterator<EventSet> itr = this.iterator();
while (itr.hasNext()) {
EventSet eSetInterface = itr.next();
if (eSetInterface.contains(o)) {
return true;
}
}
return false;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
if (name != null) {
return name;
} else {
return super.toString();
}
}
}
| true
|
c55c78216c7923e9b9b1a91e1bb3c9d603fafa7d
|
Java
|
yubinbai/javatemplates
|
/DynamicProgramming/maxSubArray/MaxSubArrayTest.java
|
UTF-8
| 1,234
| 3.28125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package algorithms.dp.maxSubArray;
import java.util.Random;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class MaxSubArrayTest extends TestCase {
Float data[];
int length = 1000;
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public MaxSubArrayTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(MaxSubArrayTest.class);
}
/**
* Rigourous Test :-)
*/
public void testMSA() {
this.data = new Float[this.length];
// generate a series of random numbers, 0..length, totally length+1
Random rand = new Random();
for (int i = 0; i < this.length; i++) {
data[i] = rand.nextFloat();
}
MaxSubArray<Float> msa = new MaxSubArray<Float>(data, length);
assertEquals(msa.bruteForce(), msa.kadane());
}
public void testMSAzero() {
this.data = new Float[this.length];
for (int i = 0; i < this.length; i++) {
data[i] = (float) -1.0;
}
MaxSubArray<Float> msa = new MaxSubArray<Float>(data, length);
assertEquals(msa.bruteForce(), msa.kadane());
}
}
| true
|
9eda5a14b6ca162e3395b58d83dd9ab404876601
|
Java
|
qwertynerd97/bball-collector
|
/app/src/main/java/com/example/app/baseballmessenger/Message.java
|
UTF-8
| 3,897
| 3.25
| 3
|
[] |
no_license
|
package com.example.app.baseballmessenger;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
/**
* Created by elli on 3/15/18.
*/
public class Message {
/**
* The universally unique identifier for a message
*/
public String uuid;
/**
* The chat that the message is in
*/
public String chat;
/**
* The user that sent the message
*/
public String sender;
/**
* The user that received the message
*/
public String reciever;
/**
* The text of the message
*/
public String text;
/**
* Creates an empty message
* This is just a dummy method for DataSnapshot.getValue(Message.class)
* After creation, Firebase fills out the attributes with the values from the database
*/
public Message(){
uuid = "---";
chat = "---";
sender = "---";
reciever = "---";
text = "NO TEXT";
}
/**
* Creates a new card with the given data. This is used when a user sends a new message
* @param u The uuid for the message
* @param cha The chat uuid that the message is in
* @param send The uuid of the sending user
* @param recieve The uuid of the receiving user
* @param data The text of the message
*/
public Message(String u, String cha, String send, String recieve, String data){
uuid = u;
chat = cha;
sender = send;
reciever = recieve;
text = data;
}
/**
* Get message from database from uuid
* @param chat The uuid of the chat that holds the message
* @param uuid The uuid of the message to retrieve
*/
public Message(String chat, String uuid){
DatabaseReference reference = Message.databaseReference(chat).child(uuid);
ValueEventListener userListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Message.this.values(dataSnapshot.getValue(Message.class));
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
reference.addListenerForSingleValueEvent(userListener);
}
/**
* Sets message values based on another message
* @param other Values to use for this message
*/
private void values(Message other){
this.uuid = other.uuid;
this.chat = other.chat;
this.sender = other.sender;
this.reciever = other.reciever;
this.text = other.text;
}
/**
* Updates the Firebase database with the values for this message
*/
public void updateFirebase(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("messages").child(chat).child(uuid).setValue(this);
}
/**
* Returns a String representation of this message
* @return The uuid + text of the message
*/
@Override
public String toString(){
return uuid + ":" + text;
}
/**
* Gets the database location for a particular message
* @return The Firebase location for the particular message
*/
public DatabaseReference dbReference(){
return FirebaseDatabase.getInstance().getReference("messages").child(chat).child(uuid);
}
/**
* Gets the database location for a group of messages
* @param chat The uuid of the chat that the messages are in
* @return The Firebase location for a group of messages
*/
public static DatabaseReference databaseReference(String chat){
return FirebaseDatabase.getInstance().getReference("messages").child(chat);
}
}
| true
|
5761f514cc8ed55eb6f5587c37c46df398ede655
|
Java
|
Solomon-Herron/Froggy
|
/src/com/froggy/dao/MySQLAccessor.java
|
UTF-8
| 867
| 2.28125
| 2
|
[] |
no_license
|
package com.froggy.dao;
import com.froggy.Bug;
import com.froggy.User;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLAccessor {
private DataSource dataSource;
public MySQLAccessor(DataSource dataSource){this.dataSource = dataSource;}
protected void close(Connection conn, Statement stmnt, ResultSet rs) {
try{
if(rs != null){
rs.close();
}
if(conn != null){
conn.close(); //Does not actually close connection, it just adds connection back to pool.
}
if(stmnt != null){
stmnt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//connectors for remote apis here
}
| true
|
ca4f5362ec766788070074268e7d2035a5329dcd
|
Java
|
lq751026/mall
|
/mall-commons/src/main/java/com/shoping/mallgn/entity/UrCmEntity.java
|
UTF-8
| 564
| 1.84375
| 2
|
[] |
no_license
|
package com.shoping.mallgn.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
*
*
* @author lq
* @email
* @date 2020-11-26 14:42:28
*/
@Data
@TableName("ur_cm")
public class UrCmEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用户id
*/
@TableId
private Integer urId;
/**
* 商品id
*/
private Integer cmId;
/**
* 此用户已购买数量
*/
private Integer urBuyNumber;
}
| true
|
bb7427627c48a4fd9afba93dd2a03883a7ee058a
|
Java
|
KisLupin/spring-graphql
|
/src/main/java/com/example/springgraphql/service/impl/UserServiceImpl.java
|
UTF-8
| 766
| 2.171875
| 2
|
[] |
no_license
|
package com.example.springgraphql.service.impl;
import com.example.springgraphql.model.user.User;
import com.example.springgraphql.repository.UserRepository;
import com.example.springgraphql.service.UserService;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public User findOneById(ObjectId id) {
return userRepository.findById(id).orElse(null);
}
@Override
public List<User> findAllUsers() {
return userRepository.findAll();
}
}
| true
|
e16651c0dbf6382eacb49dd29f8883fd5ad99765
|
Java
|
Mohitha23/javaproject1
|
/One29.java
|
UTF-8
| 276
| 2.71875
| 3
|
[] |
no_license
|
package test;
public class One29 {
public void display()
{
System.out.println("SoftwareTestingHelp!!");
}
}
class Main
{
public static void main(String args[])
{
One29 obj = new One29();
obj.display();
}
}
| true
|
98f5b798f325f1c62112adfc15d6b57756894f5a
|
Java
|
Sebcot9/Zolda
|
/src/data/Data.java
|
UTF-8
| 2,772
| 2.609375
| 3
|
[] |
no_license
|
package data;
import java.util.ArrayList;
import java.util.Random;
import classes.*;
import specifications.DataService;
import tools.HardCodedParameters;
public class Data implements DataService {
private Heroes lonk;
private ArrayList <Enemies> enemies;
private ArrayList <Allies> allies;
private ArrayList <Pets> pets;
private Map maps;
private int minX, maxX, minY, maxY;
public void setStepNumber(int stepNumber) {
this.stepNumber = stepNumber;
}
private int stepNumber;
public Data(){}
/*@Override
public void init(){
}*/
@Override
public void init(){
lonk = new Heroes(new Position(30,30), "Lonk", 5);
lonk.setWeapon(new Weapon(new Position(512,450)));
maps = new Map(1024,876);
enemies = new ArrayList<Enemies>();
Random gen= new Random();
int x = (int)(gen.nextInt((int)(getMap().getWidth()*.6))+getMap().getWidth()*.1);
int y = (int)(gen.nextInt((int)(getMap().getHeight()*.6))+getMap().getHeight()*.1);
Enemies enemy = new Enemies(new Position(x,y),"Bakemono", 2);
enemies.add(enemy);
allies = new ArrayList<Allies>();
pets = new ArrayList<Pets>();
minX = HardCodedParameters.minX;
maxX = HardCodedParameters.maxX;
minY = HardCodedParameters.minY;
maxY = HardCodedParameters.maxY;
stepNumber = 0;
}
@Override
public Heroes getLonk() {
return lonk;
}
@Override
public void setLonk(Heroes lonk) {
this.lonk = lonk;
}
@Override
public ArrayList<Enemies> getEnemies() {
return enemies;
}
@Override
public void setEnemies(ArrayList<Enemies> enemies) {
this.enemies = enemies;
}
@Override
public ArrayList<Allies> getAllies() {
return allies;
}
@Override
public void setAllies(ArrayList<Allies> allies) {
this.allies = allies;
}
@Override
public ArrayList<Pets> getPets() {
return pets;
}
@Override
public void setPets(ArrayList<Pets> pets) {
this.pets = pets;
}
@Override
public Map getMap() {
return maps;
}
@Override
public void setMaps(Map maps) {
this.maps = maps;
}
@Override
public int getMinX() {
return minX;
}
@Override
public int getMaxX() {
return maxX;
}
@Override
public int getMinY() {
return minY;
}
@Override
public int getMaxY() {
return maxY;
}
@Override
public int getLinkHeight() {
return this.lonk.getHeight();
}
@Override
public int getLinkWidth() {
return this.lonk.getWidth();
}
@Override
public int getStepNumber() {
return stepNumber;
}
@Override
public Position getWeaponPosition() {
return this.lonk.getWeapon().getPosition();
}
@Override
public void setWeaponPosition(Position pos) {
this.lonk.getWeapon().setPosition(pos);
}
}
| true
|
1bf2e9d3efd35521752dd0d6238c13d78f608dd3
|
Java
|
dennysrocha/ces28_2017_dennys.rocha
|
/exame/utm_v0/src/presenter/EstacoesGCS.java
|
ISO-8859-1
| 1,346
| 2.59375
| 3
|
[] |
no_license
|
package presenter;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import view.IDroneARP;
import model.ISistemaControleUTM_CTR;
import model.Mapa;
public class EstacoesGCS extends Observable {
private static EstacoesGCS instancia;
private List<IDroneARP> observers = new ArrayList<IDroneARP>(); //eu sei que tem apenas um observer no problema, mas isso serve p/ extenses
private Mapa mapa;
private ISistemaControleUTM_CTR sistemaControle;
public EstacoesGCS(IDroneARP drone) {//implementar
this.observers.add(drone);
}
public static EstacoesGCS getInstancia(IDroneARP drone) {// padro Singleton!
if (instancia==null) {
instancia = new EstacoesGCS(drone);
}
return instancia;
}
public void comandarDrone() {//implementar
enviarInfo();
System.out.println("A estao est enviando um comando ao drone!");
}
public void receberInfo() {//implementar
System.out.println("A estao est recebendo ou enviando informaes ao drone!");
}
public void enviarInfo() {//notifyObservers()
for (IDroneARP observer:this.observers) {
observer.update();
}
}
public void atualizarMapa(Mapa mapa) {
this.mapa = mapa;
System.out.println("Mapa atualizado");
}
}
| true
|
cff7a7714079446eac4f84ab1196bb0d63447c68
|
Java
|
codimiracle/content-middleware
|
/src/main/java/com/codimiracle/web/middleware/content/pojo/eo/SocialUser.java
|
UTF-8
| 113
| 1.570313
| 2
|
[] |
no_license
|
package com.codimiracle.web.middleware.content.pojo.eo;
public interface SocialUser {
String getUserId();
}
| true
|
93abedfe694ae45a2d6564144ab79bddcf4cf91c
|
Java
|
aravindkumarguggilla5813/Selenium3plusSession
|
/Selecnium3plus/src/com/test/ApachePOIreadandwrite.java
|
UTF-8
| 1,373
| 2.625
| 3
|
[] |
no_license
|
package Selenium1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
public class ApachePOIreadandwrite {
@Test
public void test() throws Exception {
File src =new File("C:\\Users\\aravind.g.kumar\\Desktop\\testdata.xlsx");
FileInputStream fis =new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh=wb.getSheetAt(0);
int rowCount1 = sh.getLastRowNum() - sh.getFirstRowNum();
System.out.println("RowCount From Excel "+rowCount1);
for(int i=1;i<=rowCount1;i++){
String data0= sh.getRow(i).getCell(1).getStringCellValue();
String data1=sh.getRow(i).getCell(1).getStringCellValue();
System.out.println("data from excel is "+data0);
//System.out.println(data1);
Row header = sh.getRow(0);
Cell Header1 = header.createCell(2);
Header1.setCellValue("Status");
sh.getRow(1).createCell(2).setCellValue("Pass");
sh.getRow(2).createCell(2).setCellValue("fail");
FileOutputStream fos=new FileOutputStream(src);
wb.write(fos);
}
}
}
| true
|
8af5a8e7c3f1ab6cad7859d847d28c2a30f8c49d
|
Java
|
JL-shungen/CloudNote
|
/src/main/java/dao/UserDao.java
|
UTF-8
| 334
| 2.234375
| 2
|
[] |
no_license
|
package dao;
import entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public interface UserDao {
User findUserByName(String name);
int addUser(User user);
User findUserById(String userId);
int updateUser(@Param("user") User user);
}
| true
|
3b48df5cd03f3efa0184effc4dee4c4c08238864
|
Java
|
ducnguyen46/spring_coffeeshop
|
/src/main/java/com/coffee/dto/FeedbackDto.java
|
UTF-8
| 485
| 2.046875
| 2
|
[] |
no_license
|
package com.coffee.dto;
public class FeedbackDto {
private String title;
private String content;
private Long orderId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
}
| true
|
4abc82dd4669f507c9c95abafa902e540950f2ef
|
Java
|
yusijia95/javaSE
|
/ch09/src/practise/p10/Test.java
|
UTF-8
| 404
| 2.890625
| 3
|
[] |
no_license
|
package practise.p10;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student("俞思笳1","大一",100));
list.add(new Student("俞思笳2","大二",100));
list.add(new Student("俞思笳3","大三",100));
System.out.println(list);
}
}
| true
|
bb7bf7d0e8c5b38b03a790b867f7858d16b615c2
|
Java
|
olso4051/Math-UnLock
|
/src/com/olyware/mathlock/utils/Coins.java
|
UTF-8
| 1,019
| 3.078125
| 3
|
[] |
no_license
|
package com.olyware.mathlock.utils;
public class Coins {
private int money;
private int moneyPaid;
public Coins(int money, int moneyPaid) {
this.money = money;
this.moneyPaid = moneyPaid;
}
public int getMoney() {
return money;
}
public int getMoneyPaid() {
return moneyPaid;
}
public int getTotalMoney() {
return money + moneyPaid;
}
public void setMoney(int money) {
this.money = money;
}
public void setMoneyPaid(int moneyPaid) {
this.moneyPaid = moneyPaid;
}
public int increaseMoney(int amount) {
this.money += amount;
return amount;
}
public int increaseMoneyPaid(int amount) {
this.moneyPaid += amount;
return amount;
}
public int decreaseMoneyNoDebt(int amount) {
int initMoney = this.money;
this.money -= amount;
if (this.money < 0)
this.money = 0;
return initMoney - this.money;
}
public void decreaseMoneyAndPaidWithDebt(int amount) {
this.money -= amount;
if (this.money < 0) {
this.moneyPaid += this.money;
this.money = 0;
}
}
}
| true
|
82c28727774bdb0c44fe7670ea8623eecdda1398
|
Java
|
lyskevin/duke
|
/src/main/java/duke/data/tasks/Todo.java
|
UTF-8
| 857
| 3.234375
| 3
|
[] |
no_license
|
package duke.data.tasks;
/**
* Implements a todo task.
* @author Lim Yong Shen, Kevin
*/
public class Todo extends Task {
/**
* Constructs a todo task with the specified description.
* @param description The specified description.
*/
public Todo(String description) {
super(description);
}
/**
* Returns the command String (user input) used to create this todo task.
* @return The command String (user input) used to create this todo task.
*/
@Override
public String getCommandString() {
return String.format("todo %s", description);
}
/**
* Returns the string representation of this todo task.
* @return The string representation of this todo task.
*/
@Override
public String toString() {
return String.format("[T]%s", super.toString());
}
}
| true
|
fceac6fce096de21c805382450bdae119a30cf04
|
Java
|
MackHsu/FoodCare
|
/app/src/main/java/com/example/foodcare/Retrofit/DietPackage/Diet/AnyDayDiet/AnyDayDietInterface.java
|
UTF-8
| 690
| 1.945313
| 2
|
[] |
no_license
|
package com.example.foodcare.Retrofit.DietPackage.Diet.AnyDayDiet;
/********************曾志昊 2017302580214************************/
import com.example.foodcare.Retrofit.A_entity.Diet;
import java.util.Date;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Query;
public interface AnyDayDietInterface {
@GET("acc/diet/find")
Call<List<Diet>> getAnyDayDietString(@Query("account_id") int account_id,
@Query("date") String date);
}
| true
|
53107a669631e5ab81de45ba2bbf7d7ddc4123a5
|
Java
|
hamedCA/sprintjavaee
|
/PIJEE-ejb/src/main/java/com/edu/PiJEE/CommentId.java
|
UTF-8
| 1,992
| 2.625
| 3
|
[] |
no_license
|
package com.edu.PiJEE;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.*;
/**
* Entity implementation class for Entity: CommentId
*
*/
@Embeddable
public class CommentId implements Serializable {
private String userId;
private int discutionId;
private Date dateCreation;
private static final long serialVersionUID = 1L;
public CommentId() {
super();
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getDiscutionId() {
return this.discutionId;
}
public void setDiscutionId(int discutionId) {
this.discutionId = discutionId;
}
public Date getDateCreation() {
return this.dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dateCreation == null) ? 0 : dateCreation.hashCode());
result = prime * result + discutionId;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CommentId other = (CommentId) obj;
if (dateCreation == null) {
if (other.dateCreation != null)
return false;
} else if (!dateCreation.equals(other.dateCreation))
return false;
if (discutionId != other.discutionId)
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
public CommentId(String userId, int discutionId, Date dateCreation) {
super();
this.userId = userId;
this.discutionId = discutionId;
this.dateCreation = dateCreation;
}
}
| true
|
17a1ae15570e0f14dac4c386e1ab3b3263d9b6be
|
Java
|
POOPE/acme-handy-worker
|
/src/main/java/services/RefereeService.java
|
UTF-8
| 1,756
| 2.375
| 2
|
[] |
no_license
|
package services;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import repositories.RefereeRepository;
import security.Authority;
import domain.Referee;
@Service
@Transactional
public class RefereeService {
// Managed repository -----------------------------------------------------
@Autowired
private RefereeRepository refereeRepository;
// Supporting services ----------------------------------------------------
@Autowired
private ActorService actorService;
@Autowired
private UserAccountService userAccountService;
// Constructors -----------------------------------------------------------
public RefereeService() {
super();
}
// Simple CRUD methods ----------------------------------------------------
public Referee createReferee() {
Referee referee = new Referee();
referee = (Referee) this.actorService.initialize(referee);
referee = this.initializeReferee(referee);
return referee;
}
public Referee save(Referee referee) {
return this.refereeRepository.save(referee);
}
public Referee findOne(int refereeId) {
Assert.isTrue(refereeId > 0);
return this.refereeRepository.findOne(refereeId);
}
// Other business methods -------------------------------------------------
public Referee findPrincipal() {
Assert.isTrue(this.actorService.getPrincipalAuthority().contains(Authority.REFEREE), "The user logged is not a referee.");
return (Referee) this.actorService.findPrincipal();
}
public Referee initializeReferee(Referee referee) {
referee.setUser(this.userAccountService.addAuthority(referee.getUser(), "REFEREE"));
return referee;
}
}
| true
|
da76661583e2438fe6eced2c9fc752f5f199b9a0
|
Java
|
ravikumarsagar/Java_Practical
|
/src/VehicleEco/Car.java
|
UTF-8
| 1,063
| 3.359375
| 3
|
[] |
no_license
|
package VehicleEco;
abstract class Car
{
int tyre;
int window;
String color;
int model;
}
class ListOfCars extends Car{
String name;
ListOfCars(String name,int tyre,String color,int model,int window){
this.name=name;
this.tyre=tyre;
this.window=window;
this.color=color;
this.model=model;
}
public void printDetail()
{
System.out.println(this.name+" "+this.model+" "+this.color+" "+this.window+ " "+this.tyre);
}
public static void main(String[] args) {
Car car=new ListOfCars("BMW",4,"Red",2017,6);
Car car1=new ListOfCars("Audi",4,"Grey",2019,2);
Car car2=new ListOfCars("Suzuki",4,"Green",2018,8);
Car car3=new ListOfCars("Maruti",4,"Blue",2010,8);
Car car4=new ListOfCars("Celerio",4,"Black",2011,4);
((ListOfCars) car).printDetail();
((ListOfCars) car1).printDetail();
((ListOfCars) car2).printDetail();
((ListOfCars) car3).printDetail();
((ListOfCars) car4).printDetail();
}
}
| true
|
fb79e188d256c9e939f9805a4e2376537dbcfbad
|
Java
|
ShuzhongChen/ECResume
|
/app/src/main/java/com/shuzhongchen/ecresume/ProjectEditActivity.java
|
UTF-8
| 6,073
| 2.359375
| 2
|
[] |
no_license
|
package com.shuzhongchen.ecresume;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import com.shuzhongchen.ecresume.model.Project;
import com.shuzhongchen.ecresume.util.DateUtils;
import java.util.Arrays;
import java.util.Calendar;
/**
* Created by shuzhongchen on 7/17/17.
*/
public class ProjectEditActivity extends EditBaseActivity<Project> {
public static final String KEY_PROJECT = "project";
public static final String KEY_PROJECT_ID = "project_id";
private ImageButton btnChangeStartDate;
private ImageButton btnChangeEndDate;
private int year;
private int month;
private int day;
static final int START_DATE_DIALOG_ID = 999;
static final int END_DATE_DIALOG_ID = 998;
@Override
protected int getLayoutId() {
return R.layout.activity_project_edit;
}
@Override
protected void setupUIForCreate() {
setTitle("Edit Project");
setupDatePicker();
findViewById(R.id.project_edit_delete).setVisibility(View.GONE);
}
@Override
protected void setupUIForEdit(@NonNull final Project data) {
setTitle("New Project");
setupDatePicker();
((EditText) findViewById(R.id.project_edit_name))
.setText(data.name);
((EditText) findViewById(R.id.project_edit_start_date))
.setText(data.startDate);
((EditText) findViewById(R.id.project_edit_end_date))
.setText(data.endDate);
((EditText) findViewById(R.id.project_edit_details))
.setText(TextUtils.join("\n", data.details));
findViewById(R.id.project_edit_delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
resultIntent.putExtra(KEY_PROJECT_ID, data.id);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});
}
@Override
protected void saveAndExit(@Nullable Project data) {
if (data == null) {
data = new Project();
}
data.name = ((EditText) findViewById(R.id.project_edit_name)).getText().toString();
data.startDate = ((EditText) findViewById(R.id.project_edit_start_date)).getText().toString();
data.endDate = ((EditText) findViewById(R.id.project_edit_end_date)).getText().toString();
data.details = Arrays.asList(TextUtils.split(((EditText) findViewById(R.id.project_edit_details)).getText().toString(), "\n"));
Intent resultIntent = new Intent();
resultIntent.putExtra(KEY_PROJECT, data);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
@Override
protected Project initializeData() {
return getIntent().getParcelableExtra(KEY_PROJECT);
}
// date picker
public void setupDatePicker() {
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
btnChangeStartDate = (ImageButton) findViewById(R.id.btnChangeStartDate);
btnChangeEndDate = (ImageButton) findViewById(R.id.btnChangeEndDate);
btnChangeStartDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(START_DATE_DIALOG_ID);
}
});
btnChangeEndDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(END_DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case START_DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, startDatePickerListener,
year, month, day);
case END_DATE_DIALOG_ID:
return new DatePickerDialog(this, endDatePickerListener,
year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener startDatePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into EditText
((EditText) findViewById(R.id.project_edit_start_date))
.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("/").append(day).append("/")
.append(year));
}
};
private DatePickerDialog.OnDateSetListener endDatePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into EditText
((EditText) findViewById(R.id.project_edit_end_date))
.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("/").append(day).append("/")
.append(year));
}
};
}
| true
|
ce0ef5d301eba8588ebddac9aa52288fa6ac840c
|
Java
|
B0berman/festevent-android
|
/FestEvent/app/src/main/java/com/festevent/beans/Group.java
|
UTF-8
| 1,142
| 2.4375
| 2
|
[] |
no_license
|
package com.festevent.beans;
import com.beust.jcommander.internal.Lists;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class Group implements Serializable {
protected String name;
protected Event event;
protected User creator;
protected Date created = new Date();
protected List<User> members = Lists.newArrayList();
public List<User> getMembers() {
return members;
}
public void addMember(User p) {
members.add(p);
}
public void removeMember(User p) {
members.remove(p);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
| true
|
f6f4e07e36b85b2ccd2c1fcf85baeb13af65dcd9
|
Java
|
damla-unal/Assignments-with-JAVA
|
/2.Assignment/src/Items/smartphone.java
|
UTF-8
| 1,053
| 3.15625
| 3
|
[] |
no_license
|
package Items;
import Items.electronic;
/**
* smartphone is a electronic.
* This class is containing smartphone's property.
*
* @author Damla Unal
*/
public class smartphone extends electronic {
/**
* screenType is a smartphone's property.
*/
private String screenType;
/**
* The constructor has 6 parameter.
* It is creating new smartphone object.
* @param cost item's price.
* @param manufacturer Manufacturer.
* @param brand item's brand.
* @param maxVolt Max Volt.
* @param maxWatt Max Watt.
* @param screenType Screen Type.
*/
public smartphone(String cost, String manufacturer,String brand,String maxVolt,String maxWatt,String screenType) {
super(cost,manufacturer,brand,maxVolt,maxWatt);
setScreenType(screenType);
}
/**
* Returns screenType.
* @return screenType
*/
public String getScreenType() {
return this.screenType;
}
/**
* Sets a value to attribute screenType.
* @param newScreenType
*/
public void setScreenType(String newScreenType) {
this.screenType = newScreenType;
}
}
| true
|
0f385a69b40236fd97fe0c61c0cf3a9c1efbdd04
|
Java
|
denisgridin/presitor-backend
|
/src/main/java/ru/sfedu/course_project/bean/Shape.java
|
UTF-8
| 1,757
| 2.6875
| 3
|
[] |
no_license
|
package ru.sfedu.course_project.bean;
import com.opencsv.bean.CsvBindByName;
import java.io.Serializable;
import java.util.Objects;
public class Shape extends Element implements Serializable {
public Shape(long id, String name, ElementType elementType, Layout layout, Style style, Content content, Figure figure) {
super(id, name, elementType, layout);
this.style = style;
this.content = content;
this.figure = figure;
}
@CsvBindByName
private Style style;
@CsvBindByName
private Content content;
@CsvBindByName
private Figure figure;
public Style getStyle() {
return style;
}
public void setStyle(Style style) {
this.style = style;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
public Figure getFigure() {
return figure;
}
public void setFigure(Figure figure) {
this.figure = figure;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Shape shape = (Shape) o;
return Objects.equals(style, shape.style) &&
Objects.equals(content, shape.content) &&
figure == shape.figure;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), style, content, figure);
}
@Override
public String toString() {
return "Shape{" +
"style=" + style +
", content=" + content +
", figure=" + figure +
'}';
}
}
| true
|
40c4648463cb5b7e215034bacb3437e50f485ac7
|
Java
|
DMRodrigues/Advanced-Programming
|
/p1/src/ist/meic/pa/BoxingProfilerManager.java
|
UTF-8
| 4,965
| 2.5625
| 3
|
[] |
no_license
|
package ist.meic.pa;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtPrimitiveType;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
public class BoxingProfilerManager {
private CtClass ctClass;
private String[] args;
private Class<? extends String[]> argsClass;
private static final String BOXED = "boxed";
private static final String UNBOXED = "unboxed";
private static final String BOX_TEMPLATE = "{ "
+ "ist.meic.pa.BoxingProfilerManager.inc(\"%s\", \"%s\", \"%s\");"
+ "$_ = $proceed($$); " + "}";
private static final String UNBOX_TEMPLATE = ""
+ "{ "
+ "ist.meic.pa.BoxingProfilerManager.inc(\"%s\", \"%s\", \"%s\");"
+ "$_ = $proceed(); "
+ "}";
//TreeMap para garantir ordem natural das chaves
private static Map<String, Map<String, Map<String, Integer>>> resultMap = new TreeMap<String, Map<String, Map<String, Integer>>>();
public BoxingProfilerManager(String[] args) throws NotFoundException {
this.ctClass = ClassPool.getDefault().get(args[0]);
String[] restArgs = new String[args.length - 1];
System.arraycopy(args, 1, restArgs, 0, restArgs.length);
this.args = restArgs;
this.argsClass = args.getClass();
}
public void profile() {
for (CtBehavior ctBehavior : ctClass.getDeclaredBehaviors()) {
// adicionar ao mapa um novo método
if (!resultMap.containsKey(ctBehavior.getLongName())) {
resultMap.put(ctBehavior.getLongName(), new TreeMap<String, Map<String, Integer>>());
}
try {
ctBehavior.instrument(new ExprEditor() {
@Override
public void edit(MethodCall mc) throws CannotCompileException {
String methodName = mc.where().getLongName();
String className = mc.getClassName();
Map<String, Map<String, Integer>> m = resultMap.get(methodName);
// Operações box chamam sempre o método "valueOf" independentemente da classe
if (mc.getMethodName().equals("valueOf")) {
if (!m.containsKey(className)) {
m.put(className, new TreeMap<String, Integer>());
}
m.get(className).put(BOXED, 0);
//adiciona comportamento(incrementar o contador) antes da invocação do respetivo método
mc.replace(String.format(BOX_TEMPLATE, methodName, className, BOXED));
}
//Operações unbox chamam sempre o método "<tipo>Value"
else if (mc.getMethodName().equals("intValue") || mc.getMethodName().equals("longValue")
|| mc.getMethodName().equals("doubleValue") || mc.getMethodName().equals("floatValue")
|| mc.getMethodName().equals("booleanValue") || mc.getMethodName().equals("byteValue")
|| mc.getMethodName().equals("charValue") || mc.getMethodName().equals("shortValue")) {
try {
String wrapperType = ((CtPrimitiveType) mc.getMethod().getReturnType()).getWrapperName();
//verifica se o wrapper type do método chamado é igual ao type da classe
if (wrapperType.equals(className)) {
if (!m.containsKey(className)) {
m.put(className, new TreeMap<String, Integer>());
}
m.get(className).put(UNBOXED, 0);
//adiciona comportamento(incrementar o contador) antes da invocação do respetivo método
mc.replace(String.format(UNBOX_TEMPLATE, methodName, className, UNBOXED));
}
}
catch (NotFoundException e) {
throw new RuntimeException(e);
}
}
}
});
}
catch (CannotCompileException e) {
throw new RuntimeException(e);
}
}
}
public void run() {
try {
// converte a compile-time class (ctClass) num objeto java.lang.Class
Class<?> rtClass = ctClass.toClass();
Method main = rtClass.getMethod("main", argsClass);
main.invoke(null, new Object[] { args });
} catch (CannotCompileException | NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public static void inc(String methodName, String className, String operation) {
Map<String, Integer> map = resultMap.get(methodName).get(className);
Integer counter = new Integer(map.get(operation) + 1);
map.put(operation, counter);
}
public void printResults() {
for (String methodName : resultMap.keySet()) {
for (String className : resultMap.get(methodName).keySet()) {
for (String operation : resultMap.get(methodName).get(className).keySet()) {
Integer counter = resultMap.get(methodName).get(className).get(operation);
if(counter > 0)
System.err.println(methodName + " " + operation + " " + counter + " " + className);
}
}
}
}
}
| true
|
d6dc2a86837381c132b251309c776b595986e689
|
Java
|
KakuNoGemu/Game
|
/src/me/game/data/tiles/tiles/WallTile.java
|
UTF-8
| 228
| 2.109375
| 2
|
[] |
no_license
|
package me.game.data.tiles.tiles;
import me.game.data.tiles.Tile;
/**
* Created by michtros17 on 12.07.2017.
*/
public class WallTile extends Tile {
@Override
public String getName() {
return "wall";
}
}
| true
|
3357e4ad5d5f8504562ac1a8b5183bada8225f0f
|
Java
|
efeito-joule/AM
|
/Efeito Joule/src/br/com/joule/daoimpl/HistoricoDAOImpl.java
|
UTF-8
| 1,407
| 2.515625
| 3
|
[] |
no_license
|
package br.com.joule.daoimpl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import br.com.joule.dao.HistoricoDAO;
import br.com.joule.entity.Historico;
public class HistoricoDAOImpl extends DAOImpl<Historico, Long> implements HistoricoDAO{
public HistoricoDAOImpl(EntityManager em) {
super(em);
// TODO Auto-generated constructor stub
}
@Override
public Historico buscarPorAulaAluno(long aula, long aluno) {
TypedQuery<Historico> query = em.createQuery(
"from Historico h where h.aula.id like :aula "
+ "and h.aluno.id like :aluno",Historico.class);
query.setParameter("aula", aula);
query.setParameter("aluno", aluno);
try {
return query.getSingleResult();
} catch (NoResultException nre) {
return null;
}
}
@Override
public List<Historico> ListarTodosAula(long aula) {
TypedQuery<Historico> query=
em.createQuery("from Historico h where h.posicaoAula < 11 "
+ "and h.aula.id like :aula order by h.posicaoAula",Historico.class);
query.setParameter("aula", aula);
return query.getResultList();
}
@Override
public List<Historico> ListarTodosGeral() {
TypedQuery<Historico> curso=
em.createQuery("from Historico h where h.posicaoTotal < 11 order by h.posicaoTotal",Historico.class);
return curso.getResultList();
}
}
| true
|
98c243518419b209bfed2743d195009bf98896b9
|
Java
|
muttaqee/Data-Structures
|
/src/data_structure_implementations/CharLinkImpl.java
|
UTF-8
| 324
| 3.21875
| 3
|
[] |
no_license
|
package data_structure_implementations;
public class CharLinkImpl implements CharLink {
private char c;
private CharLink next;
public CharLinkImpl(char c, CharLink next) {
this.c = c;
this.next = next;
}
@Override
public char get() {
return c;
}
@Override
public CharLink next() {
return next;
}
}
| true
|
be94ebf07ab41660026b2367604a10a1d304a23e
|
Java
|
prajwalthakare/Assesment_project
|
/Myproject_backend/src/main/java/com/extc/servise.java
|
UTF-8
| 1,365
| 1.921875
| 2
|
[] |
no_license
|
package com.extc;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.extc.dao.dao;
import com.extc.entity.Empolyeesdetails;
import com.extc.entity.Managerdetails;
@Service
public class servise {
SessionFactory sessionfactory;
@Autowired
dao mvcd;
//all servises
public boolean checklogin(Managerdetails manager) {
// TODO Auto-generated method stub
System.out.println("8888");
boolean result = mvcd.checklogin(manager);
return result;
}
public List<Empolyeesdetails> getempolyee(Empolyeesdetails emp) {
List<Empolyeesdetails> listempolyee = mvcd.empolyees(emp);
return listempolyee;
}
public boolean deleteempolyee(int empNo) {
// TODO Auto-generated method stub
return mvcd.deleteempolyee(empNo);
}
public ArrayList<Empolyeesdetails> getempl(int empNo) {
return (ArrayList<Empolyeesdetails>)mvcd.getempolyees(empNo);
}
public boolean addempolyee(Empolyeesdetails empolyee) {
// TODO Auto-generated method stub
return mvcd.addempolyee(empolyee);
}
public boolean updateempolyee(Empolyeesdetails empolyee) {
// TODO Auto-generated method stub
return mvcd.updateuser(empolyee);
}
}
| true
|
e991c144f9984e6d6a3b8d76a9358cb5d76fb87a
|
Java
|
otavio-raposo/exerc-cios-e-tarefas-de-LP1
|
/ExerciciosAdriana/src/tarefas/lp1/Pessoa.java
|
UTF-8
| 719
| 3.015625
| 3
|
[] |
no_license
|
package tarefas.lp1;
public class Pessoa {
private String nome;
private int idade;
private String cordosolhos;
public void piscar() {
System.out.println("A pessoa piscou!");
}
public void sorrir() {
System.out.println("A pessoa sorriu!");
}
public void ficouemcasa() {
System.out.println("A pessoa se protegeu ficando em casa");
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getCordosolhos() {
return cordosolhos;
}
public void setCordosolhos(String cordosolhos) {
this.cordosolhos = cordosolhos;
}
}
| true
|
d2a5cda04e32cfa85bdde1fed68a793441622746
|
Java
|
ishengchiu/NewsList
|
/app/src/androidTest/java/news/agoda/com/sample/newsdetail/NewsDetailScreenTest.java
|
UTF-8
| 2,981
| 2.1875
| 2
|
[] |
no_license
|
package news.agoda.com.sample.newsdetail;
import android.content.Intent;
import android.os.Bundle;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import news.agoda.com.sample.R;
import news.agoda.com.sample.news.MainActivity;
import news.agoda.com.sample.newsdetail.DetailViewActivity;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
/**
* Created by chiu_mac on 2016/11/21.
*/
public class NewsDetailScreenTest {
private static final String TITLE = "Title1";
private static final String SUMMARY = "Summary1";
private static final String STORY_URL = "http://www.test.com";
private static final String IMG_URL = "http://www.test.com";
@Rule
public ActivityTestRule<DetailViewActivity> mNewsDetailActivityTestRule =
new ActivityTestRule<DetailViewActivity>(DetailViewActivity.class);
@Before
public void intentWithStubbedNoteId() {
// Lazily start the Activity from the ActivityTestRule this time to inject the start Intent
Intent startIntent = new Intent();
startIntent.putExtra(DetailViewActivity.EXTRA_TITLE, TITLE);
startIntent.putExtra(DetailViewActivity.EXTRA_SUMMARY, SUMMARY);
startIntent.putExtra(DetailViewActivity.EXTRA_IMAGE_URL, IMG_URL);
startIntent.putExtra(DetailViewActivity.EXTRA_STORY_URL, STORY_URL);
mNewsDetailActivityTestRule.launchActivity(startIntent);
registerIdlingResource();
}
@Test
public void newsDetails_DisplayedInUi() throws Exception {
// Check that the note title, description and image are displayed
onView(withId(R.id.title)).check(matches(withText(TITLE)));
onView(withId(R.id.summary_content)).check(matches(withText(SUMMARY)));
}
/**
* Unregister your Idling Resource so it can be garbage collected and does not leak any memory.
*/
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(
mNewsDetailActivityTestRule.getActivity().getCountingIdlingResource());
}
/**
* Convenience method to register an IdlingResources with Espresso. IdlingResource resource is
* a great way to tell Espresso when your app is in an idle state. This helps Espresso to
* synchronize your test actions, which makes tests significantly more reliable.
*/
private void registerIdlingResource() {
Espresso.registerIdlingResources(
mNewsDetailActivityTestRule.getActivity().getCountingIdlingResource());
}
}
| true
|
eb6d4ebf41148781c3cffda2c1f5ca70c467c847
|
Java
|
damianwenne/damian-wenne-kodilla-java
|
/kodilla-spring/src/main/java/com/kodilla/spring/SpringRunner.java
|
UTF-8
| 545
| 2.078125
| 2
|
[] |
no_license
|
package com.kodilla.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.stream.Stream;
@SpringBootApplication
public class SpringRunner {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SpringRunner.class, args);
Stream.of(context.getBeanDefinitionNames()).sorted().forEach(System.out::println);
}
}
| true
|
d3f3c7cd13fe2622af0f126dfdf7dba92dc32607
|
Java
|
hum789/mini-weather-hum
|
/app/src/main/java/com/pku/hum/miniweather/SelectCity.java
|
UTF-8
| 4,873
| 2.203125
| 2
|
[] |
no_license
|
package com.pku.hum.miniweather;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import cn.edu.pku.hum.app.MyApplication;
import cn.edu.pku.hum.bean.City;
/**
* Created by hum on 2016/10/18.
*/
public class SelectCity extends Activity implements View.OnClickListener{
private ImageView mBackBtn;
private ListView mListView;
private TextView mCityInfo;
private EditText eSearch;
private String state;
MyApplication app;
List<City> data = new ArrayList<City>();
ArrayList<String> city = new ArrayList<>();
ArrayList<String> cityId = new ArrayList<>();
private int position;
public void search(String string) {
city.clear();
cityId.clear();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).getCity().contains(string)) {
city.add(data.get(i).getCity());
cityId.add(data.get(i).getNumber());
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_city);
mCityInfo = (TextView)findViewById(R.id.title_city_name);
mBackBtn = (ImageView) findViewById(R.id.title_back);
mBackBtn.setOnClickListener(this);
app = (MyApplication)getApplication();
data = app.getCityList();
for(int i=0; i<data.size(); i++) {
if(cityId.isEmpty()) {
city.add(data.get(i).getCity());
cityId.add(data.get(i).getNumber());
}
String id1 = data.get(i).getNumber().substring(0,5);
String id2 = cityId.get(cityId.size()-1).substring(0,5);
if(!id1.equals(id2)) {
city.add(data.get(i).getCity());
cityId.add(data.get(i).getNumber());
}
}
mListView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
SelectCity.this, android.R.layout.simple_list_item_1, city);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(SelectCity.this,city.get(position),
Toast.LENGTH_SHORT).show();
SelectCity.this.position = position;
mCityInfo.setText("当前城市:"+city.get(position));
}
});
eSearch = (EditText) findViewById(R.id.search_edit);
eSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
//这个应该是在改变的时候会做的动作吧,具体还没用到过。
if (eSearch.getText().toString() != null) {
state = eSearch.getText().toString();
search(state);
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
//这是文本框改变之前会执行的动作
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("curCityId",cityId.get(position));
editor.commit();
switch (v.getId()) {
case R.id.title_back:
Intent i = new Intent();
i.putExtra("cityCode", cityId.get(position));
setResult(RESULT_OK, i);
finish();
break;
default:
break;
}
}
}
| true
|
0baa0c92f787d375a263d4ccda5edc2be9ed5d36
|
Java
|
dilapitan/xml-parsing
|
/Inputs.java
|
UTF-8
| 74
| 1.53125
| 2
|
[] |
no_license
|
public class Inputs {
String name;
String expectedValue;
String type;
}
| true
|
89732d1ad0099b92afa54ba5c8e307b8cb40573e
|
Java
|
li-jiangshan/hctxsys
|
/src/main/java/com/hctxsys/controller/adminmall/YskGoodController.java
|
UTF-8
| 17,203
| 2.046875
| 2
|
[] |
no_license
|
package com.hctxsys.controller.adminmall;
import com.hctxsys.entity.YskConfigEntity;
import com.hctxsys.entity.YskGoodEntity;
import com.hctxsys.entity.YskGoodImgEntity;
import com.hctxsys.entity.YskGoodPriceEntity;
import com.hctxsys.repository.ConfigRepository;
import com.hctxsys.repository.YskGoodImgRepository;
import com.hctxsys.repository.YskGoodPriceRepository;
import com.hctxsys.service.YskGoodSerivceImpl;
import com.hctxsys.util.DateUtils;
import com.hctxsys.util.Result;
import com.hctxsys.util.TableResult;
import com.hctxsys.vo.GoodPriceVo;
import com.hctxsys.vo.GoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("Adminmall/Good")
public class YskGoodController {
@Autowired
private YskGoodSerivceImpl yskGoodSerivceImpl;
@Autowired
private ConfigRepository configRepository;
@Autowired
private YskGoodPriceRepository yskGoodPriceRepository;
@Autowired
private YskGoodImgRepository yskGoodImgRepository;
/**
* 查询商品列表 (自营,有分类名)
* @return
*/
@GetMapping(path = "/index")
public ModelAndView getAllGoods(TableResult result) {
TableResult tableResult = yskGoodSerivceImpl.findList(result);
YskConfigEntity yskConfigEntity = configRepository.findById(27).get();
ModelAndView modelAndView = new ModelAndView("adminmall/good/index");
modelAndView.addObject("tableResult", tableResult);
modelAndView.addObject("configValue", Integer.valueOf(yskConfigEntity.getValue()));
return modelAndView;
}
/**
* 商品上架 商品下架
* @param id
* @return
*/
@GetMapping(path = "/putOnSale/{id}")
@ResponseBody
public Result putOnSale(@PathVariable String id,TableResult result) {
YskGoodEntity entity = yskGoodSerivceImpl.putOnSale(Integer.valueOf(id));
if(1==entity.getStatus()) {
return new Result(1, "操作成功", "/Adminmall/Good/index", "");
}else {
return new Result(1, "操作成功", "/Adminmall/Good/index", "");
}
}
/**
* 跳转添加页面
* @return
*/
@RequestMapping("/add")
public String page() {
return "adminmall/good/add"; //返回页面
}
/**
*
* 插入
* @param name
* @param email
* @return
*/
@RequestMapping(path = "/addgood",method=RequestMethod.POST)
@ResponseBody
public Result addNewGood(@RequestBody GoodVo testEntity){
YskGoodEntity entity = new YskGoodEntity();
String goodId = testEntity.getGoodId();
goodId = String.valueOf(yskGoodSerivceImpl.findMaxId().getGoodId()+1);
entity.setGoodId(Integer.valueOf(goodId));
String goodName = testEntity.getGoodName();
if(goodName==null||"".equals(goodName)) {
return new Result(0, "商品名称不能为空");
}
entity.setGoodName(goodName);
String goodNo = testEntity.getGoodNo();
if(goodNo==null||"".equals(goodNo)) {
goodNo = " ";
}
if(goodNo!=" ") {
String no = yskGoodSerivceImpl.getGood(goodId).getGoodNo();
if(goodNo!=no) {
List<YskGoodEntity> list = yskGoodSerivceImpl.findByGoodNo(goodNo);
if(list.size()!=0) {
return new Result(0, "商品编号已存在");
}
}
}
entity.setGoodNo(goodNo);
String categoryId = testEntity.getCategoryId();
if(categoryId==null||"".equals(categoryId)) {
return new Result(0, "请选择商品分类");
}
entity.setCategoryId(Integer.valueOf(categoryId));
String brandId = testEntity.getBrandId();
if(brandId==null||"".equals(brandId)) {
brandId = "0";
}
entity.setBrandId(Integer.valueOf(brandId));
String goodSupplier = testEntity.getGoodSupplier();
entity.setGoodSupplier(goodSupplier);
String keywords = testEntity.getKeywords();
if(keywords==null||"".equals(keywords)) {
keywords = " ";
}
entity.setKeywords(keywords);
String goodPrice = testEntity.getGoodPrice();
if(goodPrice==null||"".equals(goodPrice)) {
return new Result(0, "价格不能为空");
}
entity.setGoodPrice(BigDecimal.valueOf(Double.valueOf(goodPrice)));
String marketPrice = testEntity.getMarketPrice();
if(marketPrice==null||"".equals(marketPrice)) {
marketPrice = "0";
}
entity.setMarketPrice(BigDecimal.valueOf(Double.valueOf(marketPrice)));
String costPrice = testEntity.getCostPrice();
if(costPrice==null||"".equals(costPrice)) {
costPrice = "0";
}
entity.setCostPrice(BigDecimal.valueOf(Double.valueOf(costPrice)));
String goodCommission = testEntity.getGoodCommission();
if(goodCommission==null||"".equals(goodCommission)) {
goodCommission = "0";
}
entity.setGoodCommission(goodCommission);
String goodWeight = testEntity.getGoodWeight();
if(goodWeight==null||"".equals(goodWeight)) {
goodWeight = "0";
}
entity.setGoodWeight(Integer.valueOf(goodWeight));
String shipFee = testEntity.getShipFee();
if(shipFee==null||"".equals(shipFee)) {
shipFee = "0";
}
entity.setShipFee(Integer.valueOf(shipFee));
String goodStore = testEntity.getGoodStore();
if(goodStore==null||"".equals(goodStore)) {
return new Result(0, "商品库存不能为空");
}
entity.setGoodStore(Integer.valueOf(goodStore));
String goodIntegral = testEntity.getGoodIntegral();
if(goodIntegral==null||"".equals(goodIntegral)) {
goodIntegral = "0";
}
entity.setGoodIntegral(Integer.valueOf(goodIntegral));
String goodSort = testEntity.getGoodSort();
if(goodSort==null||"".equals(goodSort)) {
goodSort = "50";
}
if(Integer.valueOf(goodSort)>65535) {
return new Result(0, "商品排序超过最大值");
}
entity.setGoodSort(Integer.valueOf(goodSort));
String goodContent = testEntity.getGoodContent();
entity.setGoodContent(goodContent);
String modelId = testEntity.getModelId();
if(modelId==null||"".equals(modelId)) {
modelId = "0";
}
entity.setModelId(Integer.valueOf(modelId));
String goodCoverImg = testEntity.getGoodCoverImg();
if(goodCoverImg==null||"".equals(goodCoverImg)) {
return new Result(0, "商品封面图不能为空");
}
entity.setGoodCoverImg(goodCoverImg);
entity.setSellerId(0);
entity.setGoodType(0);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String time = DateUtils.getTime(dateFormat.format(date), dateFormat);
entity.setCreateTime(Integer.valueOf(time));
//good表
entity.setIsHot(Integer.valueOf(testEntity.getIsHot()));
entity.setIsRecommend(Integer.valueOf(testEntity.getIsRecommend()));
entity.setIsNew(Integer.valueOf(testEntity.getIsNew()));
yskGoodSerivceImpl.insertGood(entity);
//price
List<GoodPriceVo> tests = testEntity.getTests();
if(tests!=null&&tests.size()!=0) {
List<YskGoodPriceEntity> findByPriceId = yskGoodPriceRepository.findByPriceId(Integer.valueOf(goodId));
if(findByPriceId!=null) {
yskGoodPriceRepository.deleteByGoodId(Integer.valueOf(goodId));
}
for (GoodPriceVo test : tests) {
YskGoodPriceEntity priceEntity = new YskGoodPriceEntity();
List<YskGoodPriceEntity> list = yskGoodPriceRepository.findMaxId();
int id = 0;
if(list==null||list.size()==0) {
id = 1;
}else {
id = list.get(0).getId()+1;
}
priceEntity.setId(id);
priceEntity.setGoodId(Integer.valueOf(goodId));
priceEntity.setGoodAttrName(" ");
priceEntity.setGoodAttrValue(test.getAttrvalue());
priceEntity.setGoodArrOrder(0);
if(test.getPrice()==0) {
return new Result(0, "请填写商品规格对应的价格");
}else {
priceEntity.setPrice(BigDecimal.valueOf(test.getPrice()));
}
if(test.getStore()==0) {
return new Result(0, "请填写商品规格对应的价格");
}else {
priceEntity.setStore(test.getStore());
}
priceEntity.setGoodAttrText(test.getAttrtext());
yskGoodPriceRepository.save(priceEntity);
}
}
List<String> imgUrl = testEntity.getImgUrl();
for (String string : imgUrl) {
List<YskGoodImgEntity> list = yskGoodImgRepository.findMaxId();
int id = 0;
if(list==null||list.size()==0) {
id = 1;
}else {
id = list.get(0).getId()+1;
}
YskGoodImgEntity imgEntity = new YskGoodImgEntity();
imgEntity.setId(id);
imgEntity.setGoodId(Integer.valueOf(goodId));
if(string==null||"".equals(string)) {
return new Result(0, "请上传新添加的图片");
}
imgEntity.setImgUrl(string);
yskGoodImgRepository.saveAndFlush(imgEntity);
}
return new Result(1, "保存成功","/Adminmall/Good/findById/"+goodId);
}
@RequestMapping(path = "/editgood",method=RequestMethod.POST)
@ResponseBody
public Result editGood(@RequestBody GoodVo testEntity){
YskGoodEntity entity = new YskGoodEntity();
String goodId = testEntity.getGoodId();
entity.setGoodId(Integer.valueOf(goodId));
String goodName = testEntity.getGoodName();
if(goodName==null||"".equals(goodName)) {
return new Result(0, "商品名称不能为空");
}
entity.setGoodName(goodName);
String goodNo = testEntity.getGoodNo();
String no = yskGoodSerivceImpl.getGood(goodId).getGoodNo();
if(!goodNo.equals(no)) {
List<YskGoodEntity> list = yskGoodSerivceImpl.findByGoodNo(goodNo);
if(list.size()!=0) {
return new Result(0, "商品编号已存在");
}
}
entity.setGoodNo(goodNo);
String categoryId = testEntity.getCategoryId();
if(categoryId==null||"".equals(categoryId)) {
return new Result(0, "请选择商品分类");
}
entity.setCategoryId(Integer.valueOf(categoryId));
String brandId = testEntity.getBrandId();
if(brandId==null||"".equals(brandId)) {
brandId = "0";
}
entity.setBrandId(Integer.valueOf(brandId));
String goodSupplier = testEntity.getGoodSupplier();
entity.setGoodSupplier(goodSupplier);
String keywords = testEntity.getKeywords();
if(keywords==null||"".equals(keywords)) {
keywords = " ";
}
entity.setKeywords(keywords);
String goodPrice = testEntity.getGoodPrice();
if(goodPrice==null||"".equals(goodPrice)) {
return new Result(0, "价格不能为空");
}
entity.setGoodPrice(BigDecimal.valueOf(Double.valueOf(goodPrice)));
String marketPrice = testEntity.getMarketPrice();
if(marketPrice==null||"".equals(marketPrice)) {
marketPrice = "0";
}
entity.setMarketPrice(BigDecimal.valueOf(Double.valueOf(marketPrice)));
String costPrice = testEntity.getCostPrice();
if(costPrice==null||"".equals(costPrice)) {
costPrice = "0";
}
entity.setCostPrice(BigDecimal.valueOf(Double.valueOf(costPrice)));
String goodCommission = testEntity.getGoodCommission();
if(goodCommission==null||"".equals(goodCommission)) {
goodCommission = "0";
}
entity.setGoodCommission(goodCommission);
String goodWeight = testEntity.getGoodWeight();
if(goodWeight==null||"".equals(goodWeight)) {
goodWeight = "0";
}
entity.setGoodWeight(Integer.valueOf(goodWeight));
String shipFee = testEntity.getShipFee();
if(shipFee==null||"".equals(shipFee)) {
shipFee = "0";
}
entity.setShipFee(Integer.valueOf(shipFee));
String goodStore = testEntity.getGoodStore();
if(goodStore==null||"".equals(goodStore)) {
return new Result(0, "商品库存不能为空");
}
entity.setGoodStore(Integer.valueOf(goodStore));
String goodIntegral = testEntity.getGoodIntegral();
if(goodIntegral==null||"".equals(goodIntegral)) {
goodIntegral = "0";
}
entity.setGoodIntegral(Integer.valueOf(goodIntegral));
String goodSort = testEntity.getGoodSort();
if(goodSort==null||"".equals(goodSort)) {
goodSort = "50";
}
if(Integer.valueOf(goodSort)>65535) {
return new Result(0, "商品排序超过最大值");
}
entity.setGoodSort(Integer.valueOf(goodSort));
String goodContent = testEntity.getGoodContent();
entity.setGoodContent(goodContent);
String modelId = testEntity.getModelId();
if(modelId==null||"".equals(modelId)) {
modelId = "0";
}
entity.setModelId(Integer.valueOf(modelId));
String goodCoverImg = testEntity.getGoodCoverImg();
if(goodCoverImg==null||"".equals(goodCoverImg)) {
return new Result(0, "商品封面图不能为空");
}
entity.setGoodCoverImg(goodCoverImg);
entity.setSellerId(0);
entity.setGoodType(0);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String time = DateUtils.getTime(dateFormat.format(date), dateFormat);
entity.setCreateTime(Integer.valueOf(time));
entity.setIsHot(Integer.valueOf(testEntity.getIsHot()));
entity.setIsRecommend(Integer.valueOf(testEntity.getIsRecommend()));
entity.setIsNew(Integer.valueOf(testEntity.getIsNew()));
//good表
yskGoodSerivceImpl.updateGood(entity);
//TODO:暂时操作
// yskGoodSerivceImpl.update(entity);
//price
List<GoodPriceVo> tests = testEntity.getTests();
List<YskGoodPriceEntity> findByPriceId = yskGoodPriceRepository.findByPriceId(Integer.valueOf(goodId));
if(findByPriceId!=null) {
yskGoodPriceRepository.deleteByGoodId(Integer.valueOf(goodId));
}
if(tests!=null&&tests.size()!=0) {
for (GoodPriceVo test : tests) {
YskGoodPriceEntity priceEntity = new YskGoodPriceEntity();
List<YskGoodPriceEntity> list = yskGoodPriceRepository.findMaxId();
int id = 0;
if(list==null||list.size()==0) {
id = 1;
}else {
id = list.get(0).getId()+1;
}
priceEntity.setId(id);
priceEntity.setGoodId(Integer.valueOf(goodId));
priceEntity.setGoodAttrName(" ");
priceEntity.setGoodAttrValue(test.getAttrvalue());
priceEntity.setGoodArrOrder(0);
if(test.getPrice()==0) {
return new Result(0, "请填写商品规格对应的价格");
}else {
priceEntity.setPrice(BigDecimal.valueOf(test.getPrice()));
}
if(test.getStore()==0) {
return new Result(0, "请填写商品规格对应的价格");
}else {
priceEntity.setStore(test.getStore());
}
priceEntity.setGoodAttrText(test.getAttrtext());
yskGoodPriceRepository.save(priceEntity);
}
}
List<String> imgUrl = testEntity.getImgUrl();
for (String string : imgUrl) {
List<YskGoodImgEntity> list = yskGoodImgRepository.findMaxId();
int id = 0;
if(list==null||list.size()==0) {
id = 1;
}else {
id = list.get(0).getId()+1;
}
YskGoodImgEntity imgEntity = new YskGoodImgEntity();
imgEntity.setId(id);
imgEntity.setGoodId(Integer.valueOf(goodId));
if(string==null||"".equals(string)) {
return new Result(0, "请上传新添加的图片");
}
imgEntity.setImgUrl(string);
yskGoodImgRepository.saveAndFlush(imgEntity);
}
return new Result(1, "保存成功","/Adminmall/Good/findById/"+goodId);
}
/**
* 单查商品
* @return
*/
@GetMapping(path = "/findById/{id}")
public @ResponseBody ModelAndView getGood(@PathVariable String id) {
YskGoodEntity good = yskGoodSerivceImpl.getGood(id);
//List<YskGoodImgEntity> imgs = yskGoodImgSerivceImpl.getImgByGoodId(Integer.valueOf(id));
ModelAndView modelAndView = new ModelAndView("adminmall/good/edit");
modelAndView.addObject("good", good);
//modelAndView.addObject("imgs", imgs);
return modelAndView;
}
/**
* 删除商品
* @param id
* @return
*/
@GetMapping(path = "/deleteGood/{id}")
@ResponseBody
public Result deleteGood(@PathVariable String id,TableResult result) {
int i = yskGoodSerivceImpl.deleteGood(Integer.valueOf(id));
if (i==1) {
return new Result(1, "删除成功", "/Adminmall/Good/index", "");
}
return new Result(0, "删除失败", "/Adminmall/Good/index", "");
}
/**
* 修改排序
* @param id
* @param sort
* @return
*/
@PostMapping(path = "/updateSort")
@ResponseBody
public Result updateSort(@RequestParam String id,@RequestParam String sort) {
try {
YskGoodEntity s = yskGoodSerivceImpl.updateSort(Integer.valueOf(id), Short.valueOf(sort));
if (s==null) {
return new Result(0, "修改失败!", "/Adminmall/Good/index", "");
}
return new Result(1, "修改成功!", "/Adminmall/Good/index", "");
} catch (Exception e) {
return new Result(0, "修改失败!", "/Adminmall/Good/index", "");
}
}
/**
* 设置推荐 取消推荐
* isRecommend 1-推荐 0-不推荐
* @param id
* @return
*/
@GetMapping(path = "/turnRecommend/{id}")
@ResponseBody
public Result turnRecommend(@PathVariable String id,TableResult tableResult) {
Result result = yskGoodSerivceImpl.turnRecommend(Integer.valueOf(id));
return result;
}
/**
* 设置新品 取消新品
* isNew 1-新品 0-不是新品
* @param id
* @return
*/
@GetMapping(path = "/turnNew/{id}")
@ResponseBody
public Result turnNew(@PathVariable String id) {
Result result = yskGoodSerivceImpl.turnNew(Integer.valueOf(id));
return result;
}
/**
* 设置热卖 取消热卖
* isHot 1-热卖 0-不热卖
* @param id
* @return
*/
@GetMapping(path = "/turnHot/{id}")
@ResponseBody
public Result turnHot(@PathVariable String id) {
Result result = yskGoodSerivceImpl.turnHot(Integer.valueOf(id));
return result;
}
}
| true
|
243cd6eb0ac6395be18ab24b98d51f7ac94e8977
|
Java
|
LeonardoBonacci/oogway
|
/gateway/src/test/java/guru/bonacci/oogway/gateway/GatewayTestApp.java
|
UTF-8
| 677
| 1.773438
| 2
|
[] |
no_license
|
package guru.bonacci.oogway.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import guru.bonacci.oogway.gateway.GatewayApp;
import org.springframework.context.annotation.FilterType;
@SpringBootApplication
@ComponentScan(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE,
value = { GatewayApp.class }))
public class GatewayTestApp {
public static void main(String[] args) {
SpringApplication.run(GatewayTestApp.class, args);
}
}
| true
|
fe4926daa50dd1eed5d100a7c2910f4381a6c281
|
Java
|
p-dim-popov/NVNA-Java
|
/ExamPrep01/src/eu/nvna/Main.java
|
UTF-8
| 499
| 2.84375
| 3
|
[] |
no_license
|
package eu.nvna;
public class Main {
public static void main(String[] args) {
var sales = new Sales(new TV[] {
new TV("Sony",24),
new TV("Yamaha",345)
});
var path = sales.writeTo("sales.txt");
sales.edit(path.toString(), 0, new TV("North American Audio, Inc.", 123));
// new to check if readAll works
new Sales()
.readAll(path.toString())
.forEach(System.out::println);
}
}
| true
|
305b5c7fed06aa3ebe1d31b26685df73a1911231
|
Java
|
maximdumont/torrent4j
|
/src/main/java/com/torrent4j/net/peerwire/codec/PeerWireMessageEncoder.java
|
UTF-8
| 759
| 2.3125
| 2
|
[] |
no_license
|
package com.torrent4j.net.peerwire.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import com.torrent4j.net.peerwire.PeerWireMessage;
import com.torrent4j.net.peerwire.messages.KeepAliveMessage;
public class PeerWireMessageEncoder extends MessageToByteEncoder<PeerWireMessage> {
private boolean handshaked = false;
@Override
protected void encode(ChannelHandlerContext ctx, PeerWireMessage message,
ByteBuf buffer) throws Exception {
if (handshaked && !(message instanceof KeepAliveMessage))
buffer.writeInt(0x00);
message.write(buffer);
}
public void setHandshaked(boolean handshaked) {
this.handshaked = handshaked;
}
}
| true
|
a7f1a0e3a4e66ed70657ec7cab2538425b63b8cf
|
Java
|
MayurSTechnoCredit/JAVATechnoJuly2021
|
/src/purshottamJoshi/Assignment17.java
|
UTF-8
| 396
| 2.84375
| 3
|
[] |
no_license
|
package purshottamJoshi;
class Assignment17{
String getReverse(String str) {
String rev="";
for(int i=str.length(); i> 0; --i) {
rev=rev+(str.charAt(i-1));
}
return rev;
}
public static void main(String[] args){
Assignment17 assignment17 = new Assignment17();
System.out.println("Reverse of given String : "+assignment17.getReverse("TechnoCredits"));
}
}
| true
|
c3312a2c5d458e851cd4762627c9fffad6dde258
|
Java
|
pikaja/tierpflegeverwaltung
|
/test/Tierbetreuung/HundTest.java
|
UTF-8
| 1,152
| 2.59375
| 3
|
[] |
no_license
|
package Tierbetreuung;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author pp
*/
public class HundTest {
public HundTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getMagKinder method, of class Hund.
*/
@Test
public void testGetMagKinder() {
System.out.println("getMagKinder");
Hund instance = null;
boolean expResult = true;
boolean result = instance.getMagKinder();
assertEquals(expResult, result);
}
/**
* Test of getMagLeine method, of class Hund.
*/
@Test
public void testGetMagLeine() {
System.out.println("getMagLeine");
Hund instance = null;
boolean expResult = false;
boolean result = instance.getMagLeine();
assertEquals(expResult, result);
}
}
| true
|
66555cf5bf87904a5151aa48203b76356340a543
|
Java
|
labsai/EDDI
|
/src/main/java/ai/labs/eddi/testing/internal/impl/TestCaseRuntime.java
|
UTF-8
| 7,959
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ai.labs.eddi.testing.internal.impl;
import ai.labs.eddi.engine.IRestBotAdministration;
import ai.labs.eddi.engine.IRestBotEngine;
import ai.labs.eddi.engine.memory.IConversationMemoryStore;
import ai.labs.eddi.engine.memory.model.ConversationMemorySnapshot;
import ai.labs.eddi.engine.runtime.IRuntime;
import ai.labs.eddi.engine.runtime.ThreadContext;
import ai.labs.eddi.engine.runtime.client.factory.IRestInterfaceFactory;
import ai.labs.eddi.models.ConversationState;
import ai.labs.eddi.models.Deployment;
import ai.labs.eddi.testing.ITestCaseStore;
import ai.labs.eddi.testing.model.TestCase;
import ai.labs.eddi.testing.model.TestCaseState;
import ai.labs.eddi.utils.RuntimeUtilities;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.AsyncResponse;
import jakarta.ws.rs.container.TimeoutHandler;
import jakarta.ws.rs.core.Response;
import java.net.URI;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* @author ginccc
*/
@ApplicationScoped
public class TestCaseRuntime {
private final IRuntime runtime;
private final ITestCaseStore testCaseStore;
private final IConversationMemoryStore conversationMemoryStore;
private final IRestInterfaceFactory restInterfaceFactory;
@Inject
public TestCaseRuntime(IRestInterfaceFactory restInterfaceFactory, IRuntime runtime,
ITestCaseStore testCaseStore, IConversationMemoryStore conversationMemoryStore) {
this.restInterfaceFactory = restInterfaceFactory;
this.runtime = runtime;
this.testCaseStore = testCaseStore;
this.conversationMemoryStore = conversationMemoryStore;
}
public void executeTestCase(final String id, final TestCase testCase) {
runtime.submitCallable((Callable<Void>) () -> {
try {
testCaseStore.setTestCaseState(id, TestCaseState.IN_PROGRESS);
if (!isBotDeployed(testCase.getBotId(), testCase.getBotVersion())) {
deployBot(testCase.getBotId(), testCase.getBotVersion());
}
ConversationMemorySnapshot actual = runTestCase(testCase.getBotId(), testCase);
testCase.setActual(actual);
testCase.setLastRun(new Date(System.currentTimeMillis()));
testCase.setTestCaseState(testCase.getExpected().equals(testCase.getActual()) ? TestCaseState.SUCCESS : TestCaseState.FAILED);
testCaseStore.storeTestCase(id, testCase);
} catch (Exception e) {
testCaseStore.setTestCaseState(id, TestCaseState.ERROR);
throw e;
}
return null;
}, ThreadContext.getResources());
}
private boolean isBotDeployed(String botId, Integer botVersion) throws Exception {
IRestBotAdministration restBotAdministration = restInterfaceFactory.get(IRestBotAdministration.class);
String deploymentStatus;
do {
deploymentStatus = restBotAdministration.getDeploymentStatus(Deployment.Environment.test, botId, botVersion);
if (Objects.equals(deploymentStatus, Deployment.Status.IN_PROGRESS.toString())) {
Thread.sleep(1000);
} else {
break;
}
} while (true);
return !Objects.equals(deploymentStatus, Deployment.Status.NOT_FOUND.toString());
}
private void deployBot(String botId, Integer botVersion) throws Exception {
IRestBotAdministration restBotAdministration = restInterfaceFactory.get(IRestBotAdministration.class);
restBotAdministration.deployBot(Deployment.Environment.test, botId, botVersion, false);
while (true) {
//wait until deployment has finished
if (!Objects.equals(restBotAdministration.getDeploymentStatus(Deployment.Environment.test, botId, botVersion), Deployment.Status.IN_PROGRESS.toString())) {
break;
} else {
Thread.sleep(1000);
}
}
}
private ConversationMemorySnapshot runTestCase(String botId, TestCase testCase) throws Exception {
IRestBotEngine botEngine = restInterfaceFactory.get(IRestBotEngine.class);
Response ConversationResponse = botEngine.startConversation(Deployment.Environment.test, botId, "testCaseRunner");
URI conversationURI = ConversationResponse.getLocation();
String conversationURIPath = conversationURI.getPath();
String conversationId = conversationURIPath.substring(conversationURIPath.lastIndexOf("/") + 1);
ConversationMemorySnapshot expected = testCase.getExpected();
List<ConversationMemorySnapshot.ConversationStepSnapshot> expectedConversationSteps = expected.getConversationSteps();
//we skip the first one, since the initial run has already been done at this point (at startConversation)
for (int i = 1; i < expectedConversationSteps.size(); i++) {
ConversationMemorySnapshot.ConversationStepSnapshot expectedConversationStep = expectedConversationSteps.get(i);
String input = getFirstInput(expectedConversationStep);
if (RuntimeUtilities.isNullOrEmpty(input)) {
input = " ";
}
botEngine.say(Deployment.Environment.test, botId, conversationId,
true, false,
Collections.emptyList(), input, new MockAsyncResponse());
while (botEngine.getConversationState(Deployment.Environment.test, conversationId) == ConversationState.IN_PROGRESS) {
Thread.sleep(1000);
}
}
return conversationMemoryStore.loadConversationMemorySnapshot(conversationId);
}
private String getFirstInput(ConversationMemorySnapshot.ConversationStepSnapshot conversationStep) {
for (ConversationMemorySnapshot.PackageRunSnapshot packageRunSnapshot : conversationStep.getPackages()) {
for (ConversationMemorySnapshot.ResultSnapshot resultSnapshot : packageRunSnapshot.getLifecycleTasks()) {
if (resultSnapshot.getKey().startsWith("input")) {
return resultSnapshot.getResult().toString();
}
}
}
return null;
}
private static class MockAsyncResponse implements AsyncResponse {
@Override
public boolean resume(Object response) {
return false;
}
@Override
public boolean resume(Throwable response) {
return false;
}
@Override
public boolean cancel() {
return false;
}
@Override
public boolean cancel(int retryAfter) {
return false;
}
@Override
public boolean cancel(Date retryAfter) {
return false;
}
@Override
public boolean isSuspended() {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean setTimeout(long time, TimeUnit unit) {
return false;
}
@Override
public void setTimeoutHandler(TimeoutHandler handler) {
}
@Override
public Collection<Class<?>> register(Class<?> callback) {
return null;
}
@Override
public Map<Class<?>, Collection<Class<?>>> register(Class<?> callback, Class<?>[] callbacks) {
return null;
}
@Override
public Collection<Class<?>> register(Object callback) {
return null;
}
@Override
public Map<Class<?>, Collection<Class<?>>> register(Object callback, Object... callbacks) {
return null;
}
}
}
| true
|
fcf759a3b28cf97ca28c95190b1b47416b7be1b7
|
Java
|
faizzuns/MagangBDV
|
/app/src/main/java/com/example/user/magangbdv/NewsEventAdapter.java
|
UTF-8
| 5,287
| 2.546875
| 3
|
[] |
no_license
|
package com.example.user.magangbdv;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.user.magangbdv.data.DummyEvent;
import java.util.ArrayList;
/**
* Created by User on 13/09/2017.
*/
public class NewsEventAdapter extends RecyclerView.Adapter<NewsEventAdapter.ViewHolder> {
ArrayList<DummyEvent> listEvent;
NewsEventListener listener;
public NewsEventAdapter(ArrayList<DummyEvent> listEvent, NewsEventListener listener) {
this.listEvent = listEvent;
this.listener = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
ImageView imgCard;
TextView txtJudul,txtDetailWaktu,txtContent;
CardView card;
public ViewHolder(View v){
super(v);
imgCard = (ImageView)v.findViewById(R.id.card_foto);
txtJudul =(TextView)v.findViewById(R.id.card_judul);
txtDetailWaktu = (TextView)v.findViewById(R.id.card_detail_waktu);
txtContent = (TextView)v.findViewById(R.id.card_content);
card = (CardView)v.findViewById(R.id.card_news_event);
}
}
@Override
public NewsEventAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_news_event,parent,false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(NewsEventAdapter.ViewHolder holder, int position) {
final DummyEvent event = listEvent.get(position);
holder.imgCard.setImageResource(event.getFoto());
holder.txtJudul.setText(event.getJudul());
if (event.getStatus()==1){
//set detail waktu
holder.txtDetailWaktu.setVisibility(View.VISIBLE);
String detail = setDetailWaktu(event);
holder.txtDetailWaktu.setText(detail);
}else{
holder.txtDetailWaktu.setVisibility(View.GONE);
}
//set content
String content = setContent(event.getContent());
holder.txtContent.setText(content);
holder.card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onCardClicked(event);
}
});
}
private String setContent(String content) {
String edtItem = content;
if (edtItem.length()>100){
edtItem = edtItem.substring(0,98)+"...";
}
return edtItem;
}
private String setDetailWaktu(DummyEvent event) {
String edtItem;
if ((event.getStartDay()==event.getFinishDay()) && (event.getStartMonth()==event.getFinishMonth()) && (event.getStartYear()==event.getFinishYear())){
String thisMonth = getMonth(event.getStartMonth());
edtItem = thisMonth + " " + event.getStartDay() + " @ "+setHour(event.getHourMulai())+" - "+setHour(event.getHourSelesai());
}else{
String start = getMonth(event.getStartMonth());
String finish = getMonth(event.getFinishMonth());
edtItem = start + " "+event.getStartDay()+" - "+finish+" "+event.getFinishDay()+" @ "+setHour(event.getHourMulai())+" - "+setHour(event.getHourSelesai());
}
return edtItem;
}
private String setHour(int hourSelesai) {
String edtItem;
if (hourSelesai<10){
edtItem = "0"+hourSelesai+":00";
}else{
edtItem = hourSelesai+":00";
}
return edtItem;
}
private String getMonth(int startMonth) {
String month;
switch (startMonth){
case 0:
month = "Januari";
break;
case 1:
month = "Februari";
break;
case 2:
month = "Maret";
break;
case 3:
month = "April";
break;
case 4:
month = "Mei";
break;
case 5:
month = "Juni";
break;
case 6:
month = "Juli";
break;
case 7:
month = "Agustus";
break;
case 8:
month = "September";
break;
case 9:
month = "Oktober";
break;
case 10:
month ="November";
break;
case 11:
month ="Desember";
break;
default:
month = "";
break;
}
return month;
}
@Override
public int getItemCount() {
return listEvent.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void refreshData(ArrayList<DummyEvent> listEvent){
this.listEvent = listEvent;
notifyDataSetChanged();
}
}
| true
|
6b0a99223faaad07ca688ba980d67360d3ac1000
|
Java
|
Elisabitao/exo-training
|
/showcase-pom/src/main/java/com/smartgwt/sample/showcase/client/grid/appearance/GridComponentsSample.java
|
UTF-8
| 5,203
| 2.265625
| 2
|
[] |
no_license
|
package com.smartgwt.sample.showcase.client.grid.appearance;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.data.ResultSet;
import com.smartgwt.client.data.events.DataChangedEvent;
import com.smartgwt.client.data.events.DataChangedHandler;
import com.smartgwt.client.types.ListGridComponent;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;
import com.smartgwt.sample.showcase.client.PanelFactory;
import com.smartgwt.sample.showcase.client.ShowcasePanel;
import com.smartgwt.sample.showcase.client.data.CountryXmlDS;
public class GridComponentsSample extends ShowcasePanel {
private static final String DESCRIPTION = "ListGrids can be customized by changing the order of " +
"standard components, and adding entirely custom components. In this example the filter " +
"row is showing below the ListGrid header bar, and a custom set of controls has been " +
"added underneath the body. ";
public static class Factory implements PanelFactory {
private String id;
public Canvas create() {
GridComponentsSample panel = new GridComponentsSample();
id = panel.getID();
return panel;
}
public String getID() {
return id;
}
public String getDescription() {
return DESCRIPTION;
}
}
private ListGrid countryGrid;
private Label totalsLabel;
public Canvas getViewPanel() {
ToolStrip gridEditControls = new ToolStrip();
gridEditControls.setWidth100();
gridEditControls.setHeight(24);
totalsLabel = new Label();
totalsLabel.setPadding(5);
LayoutSpacer spacer = new LayoutSpacer();
spacer.setWidth("*");
ToolStripButton editButton = new ToolStripButton();
editButton.setIcon("[SKIN]/actions/edit.png");
editButton.setPrompt("Edit selected record");
editButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
ListGridRecord record = countryGrid.getSelectedRecord();
if (record == null) return;
countryGrid.startEditing(countryGrid.getDataAsRecordList().indexOf(record), 0, false);
}
});
ToolStripButton removeButton = new ToolStripButton();
removeButton.setIcon("[SKIN]/actions/remove.png");
removeButton.setPrompt("Remove selected record");
removeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
countryGrid.removeSelectedData();
}
});
gridEditControls.setMembers(totalsLabel, spacer, editButton, removeButton);
ListGridField countryName = new ListGridField("countryName");
ListGridField capital = new ListGridField("capital");
ListGridField continent = new ListGridField("continent");
ListGridField independence = new ListGridField("independence");
countryGrid = new ListGrid();
countryGrid.setFields(new ListGridField[] { countryName, capital, continent, independence });
countryGrid.setWidth(500);
countryGrid.setHeight100();
countryGrid.setDataSource(CountryXmlDS.getInstance());
countryGrid.setAutoFetchData(true);
countryGrid.setShowFilterEditor(true);
countryGrid.setCanEdit(true);
countryGrid.setEditEvent(ListGridEditEvent.NONE);
ResultSet dataProperties = new ResultSet();
dataProperties.addDataChangedHandler(new DataChangedHandler() {
@Override
public void onDataChanged(DataChangedEvent event) {
RecordList data = countryGrid.getDataAsRecordList();
if (data != null && data instanceof ResultSet && ((ResultSet)data).lengthIsKnown() && data.getLength() > 0) {
totalsLabel.setContents(data.getLength() + " Records");
} else {
totalsLabel.setContents(" ");
}
}
});
countryGrid.setDataProperties(dataProperties);
countryGrid.setGridComponents(new Object[] {
ListGridComponent.HEADER,
ListGridComponent.FILTER_EDITOR,
ListGridComponent.BODY,
gridEditControls
});
return countryGrid;
}
public String getIntro() {
return DESCRIPTION;
}
}
| true
|
32ab29552680dff61377353b8275fc3cdea6a79e
|
Java
|
davepj007/SpaceInvaders
|
/src/SpaceInvaders/EnemyRowD.java
|
UTF-8
| 3,208
| 3.03125
| 3
|
[] |
no_license
|
package SpaceInvaders;
import LinkedLists.CircularLinkedList;
import LinkedLists.Node;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
/**
* EnemyRowD : Hilera enemiga clase D
*
* @author david
*/
public class EnemyRowD extends EnemyRow {
/**
* Constructor
* EnemyRowD
*/
public EnemyRowD(){
this.enemyRow = new CircularLinkedList();
this.boss = null;
this.enemyXSpeed = 2;
this.enemyYSpeed = 0.7;
}
@Override
public void createEnemyRow(GraphicsContext gc){
if(enemyRow.getFlag() == null){
this.setEnemyRow();
this.setEnemyYSpeed(this.getEnemyYSpeed() + 0.05);
enemyRow = this.getEnemyRow();
bool = true;
}
if(bool == true){
this.setBoss(this.chooseBoss(this.enemyRow));
Node current = enemyRow.getFlag();
for (int i = 1; i <= enemyRow.getSize(); i++) {
current.getData().setShootsRequired();
current = current.getNext();
}
}
bubbleSort();
Node current = enemyRow.getFlag().getNext();
while(current != enemyRow.getFlag()){
EnemyShip enemy = current.getData();
enemy.render(gc);
if(bool == true){
this.animateEnemyRow(enemy, gc);
}
current = current.getNext();
}
EnemyShip enemy = current.getData();
enemy.render(gc);
if(bool == true){
this.animateEnemyRow(enemy, gc);
}
this.bool = false;
}
/**
* Método encargado de realizar el ordenamiento de las naves según su nivel
* de resistencia, el cual en este caso corresponde a la cantidad de disparos
* que puede recibir
*/
public void bubbleSort(){
int temp;
for (int i = 1; i <= enemyRow.getSize(); i++) {
for (int j = 2; j < enemyRow.getSize(); j++) {
EnemyShip dataA = enemyRow.getData(j-1);
EnemyShip dataB = enemyRow.getData(j);
if(dataA.getShootsRequired() < dataB.getShootsRequired()){
temp = dataA.getShootsRequired();
dataA.setShootsRequired(dataB.getShootsRequired());
dataB.setShootsRequired(temp);
}
}
}
}
@Override
public void executeBossDestroy(){
if(enemyRow.getSize() > 1){
EnemyShip oldBoss = this.boss;
Image logoBoss = this.boss.getLogo();
Node newBoss = enemyRow.chooseRandomNode();
oldBoss.setLogo(null);
enemyRow.deleteNode(oldBoss);
this.setBoss(newBoss.getData());
newBoss.getData().setShootsRequired();
newBoss.getData().setIsBoss(true);
newBoss.getData().setLogo(logoBoss);
bubbleSort();
}else{
this.boss.setLogo(null);
enemyRow.deleteNode(this.boss);
}
}
}
| true
|
d580bffaabfc3ac0a9804d4b0ec3dc7106b7c89a
|
Java
|
guptasr/InterviewPrograms
|
/src/Facebook/RotationalChiper.java
|
UTF-8
| 3,413
| 3.828125
| 4
|
[] |
no_license
|
package Facebook;
import java.util.*;
//Add any extra import statements you may need here
/*
* One simple way to encrypt a string is to "rotate" every alphanumeric character by a certain amount. Rotating a character means replacing it with another character that is a certain number of steps away in normal alphabetic or numerical order.
For example, if the string "Zebra-493?" is rotated 3 places, the resulting string is "Cheud-726?". Every alphabetic character is replaced with the character 3 letters higher (wrapping around from Z to A), and every numeric character replaced with the character 3 digits higher (wrapping around from 9 to 0). Note that the non-alphanumeric characters remain unchanged.
Given a string and a rotation factor, return an encrypted string.
Signature
string rotationalCipher(string input, int rotationFactor)
Input
1 <= |input| <= 1,000,000
0 <= rotationFactor <= 1,000,000
Output
Return the result of rotating input a number of times equal to rotationFactor.
Example 1
input = Zebra-493?
rotationFactor = 3
output = Cheud-726?
Example 2
input = abcdefghijklmNOPQRSTUVWXYZ0123456789
rotationFactor = 39
output = nopqrstuvwxyzABCDEFGHIJKLM9012345678
*
*
*/
public class RotationalChiper {
// Add any helper functions you may need here
String rotationalCipher(String input, int rotationFactor) {
// Write your code here
String s="";
int temp=0;
for(char i: input.toCharArray()){
// System.out.println(i);
if(Character.isAlphabetic(i)){
//System.out.println("in character");
if((i + rotationFactor) > 122 && i >= 97 && i <=122){
temp = rotationFactor;
temp -= 122 - i;
temp = temp%26;
s += (char)(96+temp);
}else if((i + rotationFactor) > 90 && i <= 90 && i >= 65){
temp = rotationFactor;
temp -= 65 - i;
temp = temp % 26;
s += (char)(65 + temp);
}else{
s=s+(char)(i + rotationFactor);
}
}else if(Character.isDigit(i)){
s = s + Integer.toString((Character.getNumericValue(i) + rotationFactor) % 10);
}else{
//System.out.println("other");
s = s + i;
}
//System.out.println(s);
}
return s;
}
// These are the tests we use to determine if the solution is correct.
// You can add your own at the bottom.
int test_case_number = 1;
void check(String expected, String output) {
boolean result = (expected.equals(output));
char rightTick = '\u2713';
char wrongTick = '\u2717';
if (result) {
System.out.println(rightTick + " Test #" + test_case_number);
}
else {
System.out.print(wrongTick + " Test #" + test_case_number + ": Expected ");
printString(expected);
System.out.print(" Your output: ");
printString(output);
System.out.println();
}
test_case_number++;
}
void printString(String str) {
System.out.print("[\"" + str + "\"]");
}
public void run() {
String input_1 = "All-convoYs-9-be:Alert1.";
int rotationFactor_1 = 4;
String expected_1 = "Epp-gsrzsCw-3-fi:Epivx5.";
String output_1 = rotationalCipher(input_1, rotationFactor_1);
check(expected_1, output_1);
String input_2 = "abcdZXYzxy-999.@";
int rotationFactor_2 = 200;
String expected_2 = "stuvRPQrpq-999.@";
String output_2 = rotationalCipher(input_2, rotationFactor_2);
check(expected_2, output_2);
// Add your own test cases here
}
public static void main(String[] args) {
new RotationalChiper().run();
}
}
| true
|
07978e0a79943fc71ba30869aa00f8b84c3e15de
|
Java
|
agusbiancho/pruebaSooft
|
/src/main/java/ar/edu/teclab/prueba/dto/MateriaDAO.java
|
UTF-8
| 434
| 2
| 2
|
[] |
no_license
|
package ar.edu.teclab.prueba.dto;
import ar.edu.teclab.prueba.entity.Materia;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface MateriaDAO extends CrudRepository<Materia, Long> {
public Materia findById(Long id);
public void deleteById(Long id);
@Query("select m from Materia m where m.id=?1")
public Materia findByIdSQL(Long id);
}
| true
|
69b90fdc2f63bf7f9cb6d6010c7011e5d5667266
|
Java
|
signner/lost-and-found-of-school
|
/main/src/main/java/com/shiro/service/LostFoundService.java
|
UTF-8
| 7,745
| 2.203125
| 2
|
[] |
no_license
|
package com.shiro.service;
import com.shiro.mapper.ClaimMapper;
import com.shiro.mapper.LostFoundMapper;
import com.shiro.pojo.Claim;
import com.shiro.pojo.LostFound;
import com.shiro.utils.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@SuppressWarnings("ALL")
@Service
@Transactional
public class LostFoundService{
@Autowired
LostFoundMapper lostFoundMapper;
@Autowired
ClaimMapper claimMapper;
/*每页显示记录数目*/
@Value("${rows}")
private int rows ;;
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
/*保存查询后总的页数*/
private int totalPage;
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalPage() {
return totalPage;
}
/*保存查询到的总记录数*/
private int recordNumber;
public void setRecordNumber(int recordNumber) {
this.recordNumber = recordNumber;
}
public int getRecordNumber() {
return recordNumber;
}
/*添加失物招领记录*/
public void addLostFound(LostFound lostFound) throws Exception {
lostFoundMapper.addLostFound(lostFound);
}
/*按照查询条件分页查询失物招领记录*/
@SuppressWarnings("Duplicates")
public ArrayList<LostFound> queryLostFound(Integer sid,String title, String goodsName,
Date pickUpTime, String pickUpPlace, Integer connectPerson,
String phone,Integer state, int currentPage) throws Exception {
String where = "where 1=1";
if(sid!=0) where = where + " and userinfo.sid = '"+sid+"'";
if(!title.equals("")) where = where + " and t_lostfound.title like '%" + title + "%'";
if(!goodsName.equals("")) where = where + " and t_lostfound.goodsName like '%" + goodsName + "%'";
if(!(pickUpTime==null)) where = where + " and t_lostfound.pickUpTime like '%" + StringUtil.dateTimeToString(pickUpTime) + "%'";
if(!pickUpPlace.equals("")) where = where + " and t_lostfound.pickUpPlace like '%" + pickUpPlace + "%'";
if(connectPerson!=0) where = where + " and t_lostfound.connectPerson = '"+connectPerson+"'";
if(!phone.equals("")) where = where + " and t_lostfound.phone like '%" + phone + "%'";
where = where + " and t_lostfound.state = '" + state + "'";
int startIndex = (currentPage-1) * rows;
return lostFoundMapper.queryLostFound(where, startIndex, rows);
}
/*按照查询条件查询所有记录*/
@SuppressWarnings("Duplicates")
public ArrayList<LostFound> queryLostFound(Integer sid, String title, String goodsName, Date pickUpTime,
String pickUpPlace, Integer connectPerson,
String phone,Integer state) throws Exception {
String where = "where 1=1";
if(sid!=0) where = where + " and userinfo.sid = '"+sid+"'";
if(!title.equals("")) where = where + " and t_lostfound.title like '%" + title + "%'";
if(!goodsName.equals("")) where = where + " and t_lostfound.goodsName like '%" + goodsName + "%'";
if(!(pickUpTime==null))where = where + " and t_lostfound.pickUpTime like '%" + StringUtil.dateTimeToString(pickUpTime) + "%'";
if(!pickUpPlace.equals("")) where = where + " and t_lostfound.pickUpPlace like '%" + pickUpPlace + "%'";
if(connectPerson!=0) where = where + " and t_lostfound.connectPerson = '"+connectPerson+"'";
if(!phone.equals("")) where = where + " and t_lostfound.phone like '%" + phone + "%'";
where = where + " and t_lostfound.state = '" + state + "'";
return lostFoundMapper.queryLostFoundList(where);
}
/*查询所有失物招领记录*/
public ArrayList<LostFound> queryAllLostFound() throws Exception {
return lostFoundMapper.queryLostFoundList("where 1=1");
}
/*当前查询条件下计算总的页数和记录数*/
@SuppressWarnings("Duplicates")
public void queryTotalPageAndRecordNumber(Integer sid,String title, String goodsName,
Date pickUpTime, String pickUpPlace,
Integer connectPerson, String phone,Integer state) throws Exception {
String where = "where 1=1";
if(sid!=0) where = where + " and userinfo.sid = '"+sid+"'";
if(!title.equals("")) where = where + " and t_lostfound.title like '%" + title + "%'";
if(!goodsName.equals("")) where = where + " and t_lostfound.goodsName like '%" + goodsName + "%'";
if(!(pickUpTime==null)) where = where + " and t_lostfound.pickUpTime like '%" + StringUtil.dateTimeToString(pickUpTime) + "%'";
if(!pickUpPlace.equals("")) where = where + " and t_lostfound.pickUpPlace like '%" + pickUpPlace + "%'";
if(connectPerson!=0) where = where + " and t_lostfound.connectPerson = '"+connectPerson+"'";
if(!phone.equals("")) where = where + " and t_lostfound.phone like '%" + phone + "%'";
if(!state.equals("")) where = where + " and t_lostfound.phone like '%" + phone + "%'";
where = where + " and t_lostfound.state = '" + state + "'";
recordNumber = lostFoundMapper.queryLostFoundCount(where);
int mod = recordNumber % rows;
totalPage = recordNumber / rows;
if(mod != 0) totalPage++;
}
/*根据主键获取失物招领记录*/
public LostFound getLostFound(int lostFoundId) throws Exception {
LostFound lostFound = lostFoundMapper.getLostFound(lostFoundId);
return lostFound;
}
/*更新失物招领记录*/
public void updateLostFound(LostFound lostFound) throws Exception {
lostFoundMapper.updateLostFound(lostFound);
}
/*删除多条失物招领信息*/
@Transactional(rollbackFor=Exception.class)
public void deleteLostFounds (String lostFoundIds) throws Exception {
List<String> lostFoundId = Arrays.asList(lostFoundIds.split(","));
List<String> claimIds = new ArrayList<>();
// 过滤要删除的id所对应的lostFoundIds
List<Claim> list = claimMapper.queryClaimList(" where 1=1").stream().filter(claim -> {
// System.err.println(claim.getLostFoundObj().getLostFoundId());
// System.err.println(lostFoundId.contains(claim.getLostFoundObj().getLostFoundId()));
return lostFoundId.contains(String.valueOf(claim.getLostFoundObj().getLostFoundId()));
}).collect(Collectors.toList());
if (list==null || list.size()==0)
System.out.println("要删除的消息还没有认领消息");
else {
list.forEach(claim1 -> claimIds.add(String.valueOf(claim1.getClaimId())));
claimMapper.deleteClaim(StringUtils.join(claimIds.toArray(),","));
System.err.println(claimIds);
}
lostFoundMapper.deleteLostFound(lostFoundIds);
}
/*查询超过俩个月的数据*/
public List<Integer> overTwoMonth() throws Exception{
return lostFoundMapper.overTwoMonth();
// return null;
}
// public static void main(String[] args){
// System.out.println(Arrays.asList("1".split(",")).contains(1));
// System.out.println(Arrays.asList("1".split(",")).contains("1"));
// }
}
| true
|
5be78f719d90c93d75bb854bc025bb1459a07981
|
Java
|
stosik/coding-challenges
|
/java-solutions/src/main/java/goldman/ReverseString.java
|
UTF-8
| 747
| 3.421875
| 3
|
[] |
no_license
|
package goldman;
public class ReverseString {
static String withoutLibrary(String message) {
char[] input = message.toCharArray();
int begin = 0;
int end = input.length - 1;
while (end > begin) {
char temp = input[begin];
input[begin] = input[end];
input[end] = temp;
begin++;
end--;
}
return new String(input);
}
static String withLibrary(String message) {
return new StringBuilder(message).reverse().toString();
}
public static void main(String[] args) {
String message = "reversed";
System.out.println(withLibrary(message));
System.out.println(withoutLibrary(message));
}
}
| true
|
d462faebf9d754269d997852e7718d5a2bb580e7
|
Java
|
bineshsah/Volunteer-Project
|
/mum_volunteer_website/src/main/java/com/mum/domain/Volunteer.java
|
UTF-8
| 2,458
| 2.15625
| 2
|
[] |
no_license
|
package com.mum.domain;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Volunteer {
@Id
@GeneratedValue
private int userId;
@Column
private String firstName;
@Column
private String middleName;
@Column
private String LastName;
@Column
private int telNumber;
@Temporal(TemporalType.DATE)
@Column
private Date DOB;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn
private User user;
@Embedded
private Address address;
@Column
private String email;
@OneToMany(mappedBy = "volunteer")
private List<Task> volunteerTask;
@Column
private String discription;
public List<Task> getVolunteerTask() {
return volunteerTask;
}
public void setVolunteerTask(List<Task> volunteerTask) {
this.volunteerTask = volunteerTask;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public Volunteer() {
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public int getTelNumber() {
return telNumber;
}
public void setTelNumber(int telNumber) {
this.telNumber = telNumber;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| true
|
c47c9174cc81b259fd2e3433934dfaeabb4d995b
|
Java
|
stephenAlan/springbootsimple
|
/src/main/java/com/stephen/simple/common/ResponseCode.java
|
UTF-8
| 372
| 2.25
| 2
|
[] |
no_license
|
package com.stephen.simple.common;
import lombok.Getter;
/**
* Created by ssc on 2021-01-12 17:33 .
* Description:
*/
@Getter
public enum ResponseCode {
SUCCESS(200,"success"),
ERROR(500,"error"),
;
private int value;
private String desc;
ResponseCode(int value, String desc) {
this.value = value;
this.desc = desc;
}
}
| true
|
557fe10bd152ca7c6fe842f0127569f80bd1a812
|
Java
|
AleksandarDimitrov/XML-Manager
|
/XML Manager/src/edu/pragmatic/xml/homework/students/StudentXmlParser.java
|
UTF-8
| 4,973
| 2.453125
| 2
|
[] |
no_license
|
package edu.pragmatic.xml.homework.students;
import static edu.pragmatic.xml.homework.students.StudentXMlContentHandler.NAME_ATTRIBUTE;
import static edu.pragmatic.xml.homework.students.StudentXMlContentHandler.SCHOOL_TAG;
import static edu.pragmatic.xml.homework.students.StudentXMlContentHandler.STUDENT_TAG;
import static edu.pragmatic.xml.homework.students.StudentXMlContentHandler.TEACHER_TAG;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import edu.pragmatic.xml.homework.students.model.School;
import edu.pragmatic.xml.homework.students.model.School.Exams.Exam;
public class StudentXmlParser {
public List<String> getStudentNamesWithSax(File studentsXml) throws SAXException, IOException {
StudentXMlContentHandler contentHandler = new StudentXMlContentHandler();
parseFileWithSax(studentsXml, contentHandler);
return contentHandler.getStudentNames();
}
private void parseFileWithSax(File studentsXml, StudentXMlContentHandler contentHandler) throws SAXException, FileNotFoundException, IOException {
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setContentHandler(contentHandler);
InputSource xml = new InputSource();
xml.setCharacterStream(new FileReader(studentsXml));
xmlReader.parse(xml);
}
public List<String> getStudentNamesWithDom(File studentsXml) throws ParserConfigurationException, SAXException, IOException {
Document studentXmlDocument = buildStundentXmlDocument(studentsXml);
NodeList studentTags = getStudentTags(studentXmlDocument);
return readNamesFromTags(studentTags);
}
private List<String> readNamesFromTags(NodeList tagList) {
List<String> studentNames = new ArrayList<>();
for (int i = 0; i < tagList.getLength(); i++){
Node studentTag = tagList.item(i);
String name = readNameFromTag(studentTag);
if (name != null){
studentNames.add(name);
}
}
return studentNames;
}
private String readNameFromTag(Node tag) {
NamedNodeMap studentTagAttributes = tag.getAttributes();
Node nameNode = studentTagAttributes.getNamedItem(NAME_ATTRIBUTE);
if (nameNode != null){
return nameNode.getNodeValue();
}
return null;
}
private NodeList getStudentTags(Document studentXmlDocument) {
return studentXmlDocument.getElementsByTagName(STUDENT_TAG);
}
private Document buildStundentXmlDocument(File studentsXml) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document studentXmlDocument = documentBuilder.parse(studentsXml);
return studentXmlDocument;
}
public List<String> getTeacheNamesWithSax(File studentsXml) throws FileNotFoundException, SAXException, IOException {
StudentXMlContentHandler contentHandler = new StudentXMlContentHandler();
parseFileWithSax(studentsXml, contentHandler);
return contentHandler.getTeacherNames();
}
public List<String> getTeacheNamesWithDom(File studentsXml) throws ParserConfigurationException, SAXException, IOException {
Document studentXmlDocument = buildStundentXmlDocument(studentsXml);
NodeList teacherTags = studentXmlDocument.getElementsByTagName(TEACHER_TAG);
return readNamesFromTags(teacherTags);
}
public String getSchoolNameWithSax(File studentsXml) throws FileNotFoundException, SAXException, IOException {
StudentXMlContentHandler contentHandler = new StudentXMlContentHandler();
parseFileWithSax(studentsXml, contentHandler);
return contentHandler.getSchoolName();
}
public String getSchoolNameWithDOM(File studentsXml) throws ParserConfigurationException, SAXException, IOException {
Document studentXmlDocument = buildStundentXmlDocument(studentsXml);
NodeList schoolTags = studentXmlDocument.getElementsByTagName(SCHOOL_TAG);
return readNameFromTag(schoolTags.item(0));
}
public void addNewExamWithSax(File studentsXml) {
throw new UnsupportedOperationException("You can't change xml files with a sax parse");
}
public void addNewExamWithDOM(File studentsXml) {
throw new UnsupportedOperationException("You can't create a new xml file with a DOM parser");
}
public void addNewExamWithJAXB(File studentsXml, File destinationFile, Exam newExam) {
School school = JAXB.unmarshal(studentsXml, School.class);
school.getExams().getExam().add(newExam);
JAXB.marshal(school, destinationFile);
}
}
| true
|
58f13d6ac3a653aab96bf498a86c9e65695fddd0
|
Java
|
Gitesh-Shastri/CareerAnnaApk
|
/app/src/main/java/com/careeranna/careeranna/adapter/ViewPagerAdapter.java
|
UTF-8
| 1,932
| 2.21875
| 2
|
[] |
no_license
|
package com.careeranna.careeranna.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.careeranna.careeranna.R;
import com.careeranna.careeranna.data.Banner;
import java.util.ArrayList;
public class ViewPagerAdapter extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private ArrayList<Banner> mBanners;
public ViewPagerAdapter(Context mContext, ArrayList<Banner> mBanners) {
this.mContext = mContext;
this.mBanners = mBanners;
}
@Override
public int getCount() {
return mBanners.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view == o;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.banner_layout, null);
ImageView imageView = (ImageView) view.findViewById(R.id.bannerImage);
Glide.with(view)
.load(mBanners.get(position).getmLink())
.into(imageView);
ViewPager vp = (ViewPager) container;
vp.addView(view,0);
return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
| true
|
e9f879761c824c03873333d1bca0dd2be03d85e3
|
Java
|
lilmarr/TopicosApp
|
/app/src/main/java/com/example/aluno/topicosapp/Tela2Activity.java
|
UTF-8
| 2,022
| 2.234375
| 2
|
[] |
no_license
|
package com.example.aluno.topicosapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Tela2Activity extends AppCompatActivity {
private EditText editTextVa;
private EditText editTextCot;
private Button buttonCal;
private TextView textViewResultado;
private String finalizado;
private Double valor;
private Double cotação;
private Double resultado;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela2);
editTextVa = (EditText) findViewById(R.id.editTextVa);
editTextCot = (EditText) findViewById(R.id.editTextCot);
textViewResultado = (TextView) findViewById(R.id.textViewResultado);
buttonCal = (Button) findViewById(R.id.buttonCal);
buttonCal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
valor = Double.parseDouble(editTextVa.getText().toString());
cotação = Double.parseDouble(editTextCot.getText().toString());
textViewResultado = (TextView) findViewById(R.id.textViewResultado);
buttonCal = (Button) findViewById(R.id.buttonCal);
buttonCal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
valor = Double.parseDouble(editTextVa.getText().toString());
cotação = Double.parseDouble(editTextCot.getText().toString());
resultado = (valor * cotação);
finalizado = Double.toString(resultado);
textViewResultado.setText(finalizado);
}
});
}
});
}
}
| true
|
292047ca994f9aca72ec1b0844e4bc8b81547d73
|
Java
|
alebagnato/FITTEST
|
/ITE Release/eu.fittest.softeam/eu.fittest.eclipse/eu.fittest.eclipse.testproject.edit/src/eu/fittest/test/project/provider/OracleTypeItemProvider.java
|
UTF-8
| 10,191
| 1.625
| 2
|
[] |
no_license
|
/**
*/
package eu.fittest.test.project.provider;
import eu.fittest.test.project.OracleType;
import eu.fittest.test.project.ProjectPackage;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link eu.fittest.test.project.OracleType} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class OracleTypeItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OracleTypeItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public List getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addGHCRToptsPropertyDescriptor(object);
addOracleFilePropertyDescriptor(object);
addReportFilePropertyDescriptor(object);
addEventsToIncludePropertyDescriptor(object);
addFieldsToIncludePropertyDescriptor(object);
addFunctionsToIncludePropertyDescriptor(object);
addLloOptionPropertyDescriptor(object);
addViolationFilePropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the GHCR Topts feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addGHCRToptsPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_gHCRTopts_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_gHCRTopts_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__GHCR_TOPTS,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Oracle File feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOracleFilePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_oracleFile_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_oracleFile_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__ORACLE_FILE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Report File feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addReportFilePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_reportFile_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_reportFile_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__REPORT_FILE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Events To Include feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addEventsToIncludePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_eventsToInclude_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_eventsToInclude_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__EVENTS_TO_INCLUDE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Fields To Include feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFieldsToIncludePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_fieldsToInclude_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_fieldsToInclude_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__FIELDS_TO_INCLUDE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Functions To Include feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFunctionsToIncludePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_functionsToInclude_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_functionsToInclude_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__FUNCTIONS_TO_INCLUDE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Llo Option feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addLloOptionPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_lloOption_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_lloOption_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__LLO_OPTION,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Violation File feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addViolationFilePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_OracleType_violationFile_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_OracleType_violationFile_feature", "_UI_OracleType_type"),
ProjectPackage.Literals.ORACLE_TYPE__VIOLATION_FILE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This returns OracleType.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/OracleType"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getText(Object object) {
String label = ((OracleType)object).getGHCRTopts();
return label == null || label.length() == 0 ?
getString("_UI_OracleType_type") :
getString("_UI_OracleType_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(OracleType.class)) {
case ProjectPackage.ORACLE_TYPE__GHCR_TOPTS:
case ProjectPackage.ORACLE_TYPE__ORACLE_FILE:
case ProjectPackage.ORACLE_TYPE__REPORT_FILE:
case ProjectPackage.ORACLE_TYPE__EVENTS_TO_INCLUDE:
case ProjectPackage.ORACLE_TYPE__FIELDS_TO_INCLUDE:
case ProjectPackage.ORACLE_TYPE__FUNCTIONS_TO_INCLUDE:
case ProjectPackage.ORACLE_TYPE__LLO_OPTION:
case ProjectPackage.ORACLE_TYPE__VIOLATION_FILE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void collectNewChildDescriptors(Collection newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResourceLocator getResourceLocator() {
return ProjectEditPlugin.INSTANCE;
}
}
| true
|
4fae813f972340075982824febed26d0d9876987
|
Java
|
MsFaxe/REST-API-Kodilla
|
/src/main/java/com/crud/tasks/controller/TrelloController.java
|
UTF-8
| 2,000
| 2.421875
| 2
|
[] |
no_license
|
package com.crud.tasks.controller;
import com.crud.tasks.domain.CreatedTrelloCardDto;
import com.crud.tasks.domain.TrelloBoardDto;
import com.crud.tasks.domain.TrelloCardDto;
import com.crud.tasks.service.TrelloService;
import com.crud.tasks.trello.client.TrelloClient;
import com.crud.tasks.trello.facade.TrelloFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin("*")
@RestController
@RequestMapping("/v1/trello")
public class TrelloController {
@Autowired
// private TrelloService trelloService;
private TrelloFacade trelloFacade;
@Autowired
private TrelloClient trelloClient;
@RequestMapping(method = RequestMethod.GET, value = "getTrelloBoards")
public List<TrelloBoardDto> getTrelloBoards() {
// GET request
return trelloFacade.fetchTrelloBoards(); //trelloService ->trelloFacade
// trelloBoards.stream()
// .filter(e -> e.getId() != null && e.getName().contains("Kodilla") )
// .forEach(trelloBoardDto -> System.out.println(trelloBoardDto.getId() + " " + trelloBoardDto.getName()));
}
@RequestMapping(method = RequestMethod.POST, value = "createTrelloCard")
public CreatedTrelloCardDto createdTrelloCard(@RequestBody TrelloCardDto trelloCardDto) {
return trelloFacade.createCard(trelloCardDto); //trelloService.createTrelloCard(trelloCardDto) ->trelloFacade
}
@RequestMapping(method = RequestMethod.GET, value = "getTrelloCard")
public void GetTrelloCards() {
CreatedTrelloCardDto trelloCards = trelloClient.getTrelloCards();
System.out.println(trelloCards.getId() + " - "/* + trelloCardDto.getBadges()*/);
// trelloBoardDto.getLists().forEach(trelloList ->
// System.out.println(trelloList.getName() + " - " + trelloList.getId() + " - " + trelloList.isClosed()));
}
}
| true
|